mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e60f82b45 | ||
|
|
3cef89dcda | ||
|
|
cabec91055 | ||
|
|
769d58ea45 | ||
|
|
41072f2929 | ||
|
|
07dec1218c | ||
|
|
48c353519a | ||
|
|
d39bfa9c6d | ||
|
|
5e2bb7719f | ||
|
|
e4951c107a | ||
|
|
f0dd5cb7ca | ||
|
|
44dac3237c | ||
|
|
3d8244b372 | ||
|
|
8a9f33a33f | ||
|
|
523f971088 | ||
|
|
bf541ca5d4 | ||
|
|
d47cb75475 |
No files matched your search
@@ -559,7 +559,7 @@ Validation guidance:
|
||||
- For host-boundary changes, run the fork's focused adapter tests without Obsidian, then validate plugin registration and teardown through cold startup, plugin reload, the main window, a new and restored popout, and window removal. Confirm adapter methods observe settings changed after registration.
|
||||
- After React/package-loading changes, validate cold startup, plugin reload, the main window, new and restored popouts, and moving a leaf between windows. Confirm that no `window.React` or `window.ReactDOM` global was introduced.
|
||||
- After Radix/portal changes, validate visibility, positioning, stacking, click-outside, and Escape handling in both the main window and a popout; include mobile when viewport collision behavior can differ.
|
||||
- Record `dist/main.js` byte size after packaging changes and report remaining headroom under the release limit.
|
||||
- Record `dist/main.js` byte size after packaging changes and report remaining headroom under the 5 MB release target: 5 × 1024 × 1024 = 5,242,880 bytes.
|
||||
- Prefer targeted diagnostics for the files you touched when repo-wide lint noise obscures signal.
|
||||
- Prefer `npm run build` plus targeted file diagnostics over raw `tsc --noEmit` as the primary gate. Standalone `tsc` can surface large volumes of dependency-typing noise unrelated to touched files.
|
||||
- Do not treat `dist/` output edits as source fixes.
|
||||
|
||||
+25
-1
@@ -18,6 +18,26 @@ Before spending your valuable time writing code for a new feature or significant
|
||||
|
||||
## 🛠️ Build and Lint Commands
|
||||
|
||||
### Dependency scanner warnings
|
||||
|
||||
The published `@zsviczian/excalidraw` 0.18.140 package lists the build-only Sass
|
||||
compiler as a runtime dependency. Until a component release moves Sass to
|
||||
`devDependencies`, this repository overrides that transitive dependency to
|
||||
Sass 1.98.0, which uses Chokidar 4 without `braces`. Remove the Sass override
|
||||
after installing a component release with the corrected manifest. The plugin
|
||||
consumes prebuilt component JavaScript and CSS; it does not run Sass.
|
||||
|
||||
`source-map-js` is overridden to patched version 1.2.2 for both runtime-classified
|
||||
and development paths ([advisory](https://github.com/advisories/GHSA-68fv-2mgg-jv7q)).
|
||||
The build copies its manifest and top-level declaration files with Node's native
|
||||
file APIs instead of `rollup-plugin-copy`, eliminating the other `braces` path.
|
||||
The [braces advisory](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm) has no
|
||||
patched release as of October 11, 2026; these changes remove it from this plugin's
|
||||
dependency graph rather than suppressing the warning. Check with
|
||||
`npm ls braces source-map-js sass --all` after `npm install`.
|
||||
|
||||
### Commands
|
||||
|
||||
- **Build the project:** Run `npm run build`
|
||||
*(Note: Our Rollup build is non-trivial as it merges CSS, handles MathjaxToSVG dependencies, and embeds runtime payloads. Run this command frequently to validate your changes).*
|
||||
- **Build readable development payloads:** Run `npm run dev`
|
||||
@@ -25,7 +45,7 @@ Before spending your valuable time writing code for a new feature or significant
|
||||
- **Run ESLint:** Run `npm run code`
|
||||
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
|
||||
|
||||
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the release size limit and report its byte size after dependency or packaging changes.
|
||||
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the **5 MB release target (5 × 1024 × 1024 = 5,242,880 bytes)** and report its byte size and remaining headroom after dependency or packaging changes.
|
||||
|
||||
## Updating the EA script template
|
||||
|
||||
@@ -53,6 +73,10 @@ four Obsidian artifacts first. Both native commands require explicit test-vault
|
||||
paths and a running Obsidian with CLI access enabled. See the [setup, platform
|
||||
commands, reports, and cleanup contract](docs/OBSIDIAN_RUNTIME_TESTING.md).
|
||||
|
||||
For Markdown embed changes, also run `npm run test:markdown-embeds` and
|
||||
`npm run verify:obsidian:plugin -- --embed-recovery`. See the runtime guide for
|
||||
fixture ownership, deferred rendering, popout coverage, and remaining manual checks.
|
||||
|
||||
Because Obsidian runs across a variety of environments, please manually test your changes on as many of the following platforms as possible to avoid breaking the plugin for other users:
|
||||
- Desktop: Mac, Windows, Linux
|
||||
- Mobile: Android, iOS (Test on both Phones and Tablets)
|
||||
|
||||
@@ -18,6 +18,10 @@ Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can f
|
||||
|
||||
If you are curious about the Visual PKM philosophy behind the plugin, consider my book [Sketch Your Mind](https://community.sketch-your-mind.com/sym) and the [Visual Thinking Workshops](https://community.sketch-your-mind.com/vtw). To learn about all the different options available and how they fit together, check out the [Welcome to the Sketch Your Mind Ecosystem](https://community.sketch-your-mind.com/t/welcome-to-the-sketch-your-mind-ecosystem/375) introduction page. Finally, keep the [Excalidraw Plugin Wiki](https://community.sketch-your-mind.com/Wiki) and the [NotebookLM workbook](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0) at hand, those are essential companions.
|
||||
|
||||
## Native CLI for coding agents
|
||||
|
||||
With Obsidian 1.12.2+ and CLI enabled, local agents can discover, create, inspect, edit, save, render, and run explicitly trusted local scripts through Excalidraw. Older Obsidian versions remain supported. Select **Excalidraw: Show CLI and agent instructions** in the command palette, or start with `obsidian vault="My vault" obsidian-excalidraw-plugin:help`. See the [CLI reference](docs/CLI.md) and [portable agent skill](docs/AITrainingData/excalidraw-cli/SKILL.md).
|
||||
|
||||
## Disclaimer / Disclosure: Plugin Access and Privileges
|
||||
|
||||
I treat privacy as a top priority. Apart from the few technical limitations outlined below, Excalidraw is 100% local and runs without network access. Most of the findings published on sites such as [obsidianpluginaudit.com](https://obsidianpluginaudit.com/), [plugin.observer](https://plugin.observer/), and [community.obsidian.md/plugins](https://community.obsidian.md/plugins) can be misleading without proper context.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: obsidian-excalidraw-cli
|
||||
description: Create, inspect, edit and render Obsidian Excalidraw drawings through the running app's native CLI.
|
||||
---
|
||||
|
||||
Use a local terminal with Obsidian running and CLI enabled (API 1.12.2+).
|
||||
Always put vault="<name or ID>" before the command. Native root: obsidian-excalidraw-plugin.
|
||||
Start with obsidian vault="<vault>" obsidian-excalidraw-plugin:help, then :schema action=create.
|
||||
All results use apiVersion 1. Check ok, mutation and persistence; process exit zero alone does not prove success.
|
||||
Put large requests in a visible vault-relative JSON file and pass input="<file>". Inline json is for small requests.
|
||||
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
|
||||
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
|
||||
Loop: :read source=live detail=elements → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
|
||||
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY only after read-back.
|
||||
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
|
||||
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
|
||||
:result requestId=<id> recovers a receipt after lost stdout. Receipts expire after 15 minutes/reload; unknown outcome requires read-back before another write.
|
||||
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
|
||||
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
|
||||
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
|
||||
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Remote assets follow existing permissions.
|
||||
Use :schema for exact fields, operation limits, and runnable examples. Do not edit compressed drawing Markdown directly or install another Excalidraw CLI.
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
# Excalidraw CLI
|
||||
|
||||
Use a terminal on the computer running Obsidian, with Obsidian's CLI enabled.
|
||||
Native registration requires Obsidian API **1.12.2 or newer** and the registration
|
||||
method to be present. Excalidraw still supports Obsidian 1.8.7; older installations
|
||||
simply omit native handlers. The same JSON dispatcher is available to scripts as
|
||||
`await ea.executeCLI(request)` on every supported version.
|
||||
|
||||
Select **Excalidraw: Show CLI and agent instructions** in the command palette to
|
||||
read or copy the offline instructions. The portable [agent skill](AITrainingData/excalidraw-cli/SKILL.md)
|
||||
can be installed in your agent's normal skill directory manually. Excalidraw
|
||||
does not install agent configuration or require a particular model provider.
|
||||
|
||||
```sh
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:help
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:status
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:schema action=create
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:skill format=markdown
|
||||
```
|
||||
|
||||
Put `vault` before the command. On Windows use Obsidian's console launcher,
|
||||
`Obsidian.com`, when capturing output. A remote/container/WSL terminal needs
|
||||
access to the local executable and running app. Agent integrations such as
|
||||
Claudian, Agent Client, and Copilot need a terminal-capable backend and permission
|
||||
to invoke that executable. A missing command means you should check the host API,
|
||||
enabled plugin, CLI setting, launcher, and selected vault before retrying.
|
||||
|
||||
All ordinary responses are JSON with `apiVersion: 1`, `session`, `command`,
|
||||
`status`, `ok`, `mutation`, `persistence`, `warnings`, and optional `data`,
|
||||
`target`, `revision`, or `error`. `skill format=markdown` returns Markdown on
|
||||
native stdout. Check `ok` and the persistence receipt: process exit zero alone
|
||||
does not prove success. Errors include a stable code and recovery instruction.
|
||||
|
||||
## Author a drawing
|
||||
|
||||
Save this UTF-8 JSON request as a visible vault file, for example `CLI/create.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"command": "create",
|
||||
"requestId": "flow-create-1",
|
||||
"path": "Drawings/Flow.excalidraw.md",
|
||||
"elements": [
|
||||
{"id":"start","type":"rectangle","x":0,"y":0,"width":180,"height":80,"label":{"text":"Start"}},
|
||||
{"id":"end","type":"rectangle","x":280,"y":0,"width":180,"height":80,"label":{"text":"Finish"}},
|
||||
{"id":"connection","type":"arrow","x":180,"y":40,"start":{"id":"start"},"end":{"id":"end"}}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:create input="CLI/create.json"
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:open path="Drawings/Flow.excalidraw.md"
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:read path="Drawings/Flow.excalidraw.md" source=live detail=elements
|
||||
```
|
||||
|
||||
`create` uses the existing EA serializer, keeps template prose/metadata, and
|
||||
never overwrites or appends a filename suffix. Paths are exact and include an
|
||||
extension; root paths remain at the vault root. `.excalidraw.md` creates modern
|
||||
Markdown; `.excalidraw` explicitly creates legacy JSON. `template` is an exact
|
||||
existing drawing path, with no template picker. `open` explicitly creates/reveals
|
||||
a normal tab if needed; configured drawing scripts may run as part of opening.
|
||||
Use a modern destination for templates with linked asset metadata that legacy
|
||||
JSON cannot retain; this conversion is rejected rather than dropping the assets.
|
||||
|
||||
Skeleton IDs are request-local labels. The response `data.idMap` maps them to
|
||||
actual IDs; generated labels also appear in `createdIds`. Omitted IDs use `@0`,
|
||||
`@1`, etc. Prefer explicit local IDs when using several add operations. Every
|
||||
new element, including bound text, receives an eight-character ID. Supported
|
||||
types are rectangle, ellipse, diamond, text, arrow, line, frame, and stickynote.
|
||||
Arrow `start`/`end` bindings and frame `children` reference IDs in their batch.
|
||||
Frames require children and cannot nest. Use `connect` for existing endpoints.
|
||||
|
||||
To edit, copy the current live `data.revision` and actual IDs into a new request:
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"command": "apply",
|
||||
"requestId": "flow-edit-1",
|
||||
"path": "Drawings/Flow.excalidraw.md",
|
||||
"expectedRevision": "copy-from-live-read",
|
||||
"operations": [
|
||||
{"op":"update","id":"actual-shape-id","set":{"backgroundColor":"#e7f5ff"}},
|
||||
{"op":"update","id":"actual-bound-text-id","set":{"text":"Ready"}}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`apply` stages one coherent edit, checks its file/view/API identity and scene,
|
||||
document/asset metadata, and settings again before publication, then uses the
|
||||
existing save queue. A stale preparation publishes nothing. If publication
|
||||
succeeds but saving fails, the response reports `mutation: applied` and
|
||||
`persistence: unsaved` or `unknown`; keep the recoverable drawing open and save
|
||||
or inspect it before continuing. A save receipt acknowledges the accepted edit,
|
||||
not every later human edit. A handoff is not reported as durable.
|
||||
|
||||
| Operation | Fields after `op` |
|
||||
| --- | --- |
|
||||
| `add` | `elements`: new skeleton batch |
|
||||
| `update` | `id`, `set`: finite style/geometry/text fields |
|
||||
| `delete` | `ids`; nonempty frames require `children: "delete"` or `"detach"` |
|
||||
| `connect` | `from`, `to`; optional local `id`, `fromSide`, `toSide` (top/bottom/left/right) |
|
||||
| `group` | `ids`; returns a new group ID |
|
||||
| `ungroup` | `ids`, `groupId`; preserves other groups |
|
||||
| `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG; optional `id`, `x`, `y`, `scale` (boolean) |
|
||||
| `latex` | `text`; optional `id`, `x`, `y`, `scaleX`, `scaleY`; requires compatible enabled Extras MathJax |
|
||||
|
||||
`update` accepts x/y/width/height/angle, strokeColor/backgroundColor/fillStyle,
|
||||
strokeWidth/strokeStyle/roughness/opacity, locked/link, and text/fontSize/fontFamily/
|
||||
textAlign/verticalAlign. Text fields require a text element; edit the bound label
|
||||
ID to change its text. Linear resizing and identity, version, binding, frame,
|
||||
binary, or Markdown-image metadata edits require a trusted script. Unknown
|
||||
requested fields are rejected; existing custom data is preserved. Delete uses
|
||||
tombstones and binding cleanup and does not delete attachment files.
|
||||
|
||||
## Read, render, and recover
|
||||
|
||||
`list` returns exact paths. `read` defaults to a summary without asset bodies;
|
||||
`detail=elements` returns at most 50 elements per page (maximum 200). Use
|
||||
`nextOffset` and the same `revision` for later pages. A changed snapshot returns
|
||||
`STALE_REVISION`. `ids` filters explicit IDs and `selectedOnly` needs a live view.
|
||||
|
||||
`source=auto` uses an unambiguous live view, otherwise disk; `source=live` requires
|
||||
a ready open drawing; `source=disk` reads saved content without opening/saving it.
|
||||
If several views show the same drawing, specify `view` using its returned ID.
|
||||
Disk reads/exports reject a view ID. No command silently selects the active drawing.
|
||||
|
||||
```sh
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:export path="Drawings/Flow.excalidraw.md" source=live out="Drawings/Flow.png" requestId=preview-1
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:result requestId=flow-edit-1
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:api surface=ea name=addText
|
||||
obsidian vault="My vault" obsidian-excalidraw-plugin:api surface=lib name=mutateElement
|
||||
```
|
||||
|
||||
Export writes only the explicit `.svg`/`.png` artifact. Existing files require
|
||||
`overwrite=true`; output cannot replace the request, drawing, or a referenced
|
||||
asset. Source/revision, theme, byte count, and dimensions are returned. Live export
|
||||
does not save the drawing. Optional `theme` is light/dark, `padding` is 0–200
|
||||
(default 10), `scale` is 0.1–4 for PNG (default 1), and `area` is an exact
|
||||
`{x,y,width,height}` scene rectangle. Inspect the image before another revision.
|
||||
Missing/undecoded assets fail explicitly. Existing remote assets use normal
|
||||
plugin permissions and may require network access. Core shape/text and SVG/PNG
|
||||
rendering work without Extras; optional features are never activated automatically.
|
||||
|
||||
Every write requires a unique 1–80 character `requestId` (letters, digits, `_`,
|
||||
`.`, `-`). Repeating the identical effective request returns its receipt; different
|
||||
content with the same ID is rejected. Script source is part of that identity.
|
||||
`result` can recover lost stdout or report `status: pending, ok: null`. Completed
|
||||
receipts expire after 15 minutes; there are at most 128 in one plugin session.
|
||||
Reload/expiry/unknown outcomes require read-back before issuing another write.
|
||||
Competing CLI operations on the same target return `BUSY`; human editing remains
|
||||
possible, so always refresh after `STALE_REVISION`.
|
||||
|
||||
Input is limited to 2 MiB and nesting to 30 levels; output to 512 KiB. Use either
|
||||
`input=<visible vault JSON file>` or small inline `json`, never both. Supplied
|
||||
flags must agree with JSON. Construction is limited to 500 skeletons per batch,
|
||||
100 operations, 5000 scene elements for edits/exports, 16 MiB drawings/assets,
|
||||
and 16 million raster pixels / 16384 pixels per side / 32 MiB artifacts. The
|
||||
machine schema describes structure; runtime geometry, relationship, and lifecycle
|
||||
guards also apply. Hidden, absolute, traversal, and ambiguous paths are rejected.
|
||||
|
||||
## Trusted advanced scripts
|
||||
|
||||
Choose an explicit existing `.md` script, or an enabled `.js` script, and
|
||||
acknowledge `trusted=true`. `path` is optional for view-free construction; a
|
||||
targeted script requires an explicit ready drawing. For example:
|
||||
|
||||
```js
|
||||
const input = utils.input; // JSON arguments, never interpolated into source
|
||||
const bounds = utils.excalidrawLib.getCommonBounds(ea.getViewElements());
|
||||
return { label: input.label, bounds, source: utils.executionSource }; // "cli"
|
||||
```
|
||||
|
||||
The existing ScriptEngine compiles/caches the file and runs it with a fresh EA.
|
||||
`utils.excalidrawLib` is the installed shared runtime; `api surface=lib` documents
|
||||
an intentional supported subset, while scripts can use other installed exports.
|
||||
The CLI-owned EA and its registered cleanups/hooks/sidepanel are destroyed on
|
||||
completion or failure. Manual and persistent sidepanel scripts retain their
|
||||
existing lifetimes. Utility prompts/suggesters fail with `INTERACTION_REQUIRED`.
|
||||
|
||||
Trusted code is not sandboxed or transactional and can call other interactive
|
||||
APIs. Await all writes/saves and do not retain timers, hooks, or unawaited work.
|
||||
Script completion reports unknown mutation/persistence; it does not implicitly
|
||||
save everything touched. Undefined returns become null; non-JSON or oversized
|
||||
results fail without claiming rollback. A terminal timeout cannot preempt
|
||||
arbitrary synchronous code or undo side effects. PDF, Mermaid, SVG import, and
|
||||
advanced Markdown-image workflows remain available through existing EA/Extras
|
||||
APIs with their normal dependency and interaction requirements.
|
||||
@@ -149,6 +149,57 @@ so a pending close/save cannot recreate it. Inspect both `status` and
|
||||
|
||||
## Troubleshooting and further coverage
|
||||
|
||||
For Markdown embed changes, run the focused tests and the native regression for
|
||||
issue #2953:
|
||||
|
||||
```bash
|
||||
npm run test:markdown-embeds
|
||||
npm run verify:obsidian:plugin -- --embed-recovery
|
||||
```
|
||||
|
||||
Use `npm.cmd` in PowerShell. `--embed-recovery` also works with `verify:obsidian`
|
||||
and can be combined with `--text-undo` or `--grouped-link-click`. The offline tests exercise the real
|
||||
postprocessor with deferred image generation, including failed renders, temporary
|
||||
detachment, overlapping attribute updates, repeated callbacks, loader cancellation,
|
||||
and permanent context unload. They require no Obsidian process or extra DOM package.
|
||||
|
||||
The native scenario creates four UUID-named Markdown files (including a hybrid
|
||||
drawing), one tiny PNG, and adds text to the parent runner's disposable drawing.
|
||||
A long embedded note uses a collapsed callout
|
||||
so three repeated drawing embeds stay in the viewport. It temporarily defers the
|
||||
test plugin's `awaitInit()`, detaches the owned note's content for longer than the
|
||||
loader's cancellation interval, and verifies rendering and decoding after
|
||||
reattachment. SVG image, PNG, and inline SVG are checked in Live Preview, Reading
|
||||
mode, warm reopen, and width updates; an additional popout checks detachment and
|
||||
width updates in its own document. Closing a context with a pending render must
|
||||
stop insertion. The hybrid fixture uses `excalidraw-open-md: true`, a relative
|
||||
`![[#^as-image]]`, a nested drawing, and a native PNG. Live Preview and Reading mode
|
||||
must show all three, both directly and inside another note's Markdown transclusion;
|
||||
a filename-qualified `#^as-image` must still force the drawing side. These checks
|
||||
run in the popout and require a Markdown drawing for the parent smoke fixture.
|
||||
The scenario restores the temporary method override and preview
|
||||
setting, closes its own leaves, deletes only its recorded fixture paths, and
|
||||
removes its controller in `finally`. The parent runner still checks deployed
|
||||
hashes, JavaScript errors, and drawing cleanup.
|
||||
|
||||
This is a controlled lifecycle regression, not a reproduction of every reported
|
||||
layout race. Separately check an expanded long embedded note and scrolling,
|
||||
Hybrid Note PDF export, and cold application startup. Record live macOS and
|
||||
physical mobile coverage separately; Windows results do not establish those gates.
|
||||
|
||||
For grouped Ctrl/Cmd-click selection and link navigation, run:
|
||||
|
||||
```bash
|
||||
npm run verify:obsidian:plugin -- --grouped-link-click
|
||||
```
|
||||
|
||||
This regression dispatches synthetic pointer events through the mounted editor.
|
||||
It checks first-click selection, unlinked members, second-click navigation with
|
||||
Shift/Alt, nested groups, bound labels, and unchanged ungrouped link behavior.
|
||||
It observes the real link resolver and intercepts its final navigation hook to
|
||||
keep the test in its disposable drawing. Settings and hooks are restored afterward.
|
||||
This establishes desktop event routing, not physical mouse/touch input.
|
||||
|
||||
For text-edit/history changes, run the repeatable regression for issue #2976:
|
||||
|
||||
```bash
|
||||
@@ -171,6 +222,73 @@ and legacy/empty source handling. The matrix includes plain text, `[[link]]`,
|
||||
and JavaScript error checks. The scenario uses the toolbar's stable test IDs, so
|
||||
labels may be localized. Physical mobile and popout checks remain separate.
|
||||
|
||||
For the native Excalidraw authoring protocol, run:
|
||||
|
||||
```sh
|
||||
node --test scripts/testing/cli.test.mjs
|
||||
npm run verify:obsidian:plugin -- --native-cli
|
||||
```
|
||||
|
||||
The native scenario uses real registered commands and owned fixtures for file
|
||||
input, construction, template prose, read/apply/save/reopen, replay/stale/busy
|
||||
receipts, delayed text preparation, save failure, SVG/PNG, vault image metadata,
|
||||
and trusted script context/source changes/prompt refusal. Its temporary hooks and
|
||||
files are restored/deleted in `finally`. It records actual artifact dimensions
|
||||
and bytes. The separate text-undo scenario still requires the component fix
|
||||
described above. Run one driver at a time; UI/CDP input also needs the intended
|
||||
vault window to retain focus.
|
||||
|
||||
For LaTeX dialog input and window ownership (#2970), run:
|
||||
|
||||
```bash
|
||||
npm run verify:obsidian:plugin -- --latex-input
|
||||
```
|
||||
|
||||
Use `npm.cmd` in PowerShell. This option also works with `verify:obsidian`.
|
||||
Close any existing LaTeX dialog in the test vault first. The scenario exercises
|
||||
the real plugin prompt and CodeMirror in the main window, a direct popout, and
|
||||
a tab moved to a popout. Native CDP input checks click placement, arrows,
|
||||
Backspace, selection replacement, undo, Mod-Enter, formula save/reopen, cancel
|
||||
and editor destruction. Popout input attaches only to the single new page target
|
||||
created by the scenario. It restores its temporary gateway override, detaches
|
||||
its CDP session, closes its popouts, and removes its controller in `finally`;
|
||||
the parent runner owns the disposable drawing and final JavaScript-error check.
|
||||
|
||||
This input regression supplies a deterministic local SVG renderer through the
|
||||
MathJax gateway. It requires no Extras installation or network access and does
|
||||
not test MathJax rendering, its activation flow, or Latex Suite extensions.
|
||||
For real Extras formula rendering and Latex Suite preview positioning, install
|
||||
and enable both companions in the test vault, enable Extras MathJax-to-SVG and
|
||||
Latex Suite math previews, then run:
|
||||
|
||||
```bash
|
||||
npm run verify:obsidian:plugin -- --latex-preview
|
||||
```
|
||||
|
||||
Use `npm.cmd` in PowerShell. This gate uses the real renderer without a gateway
|
||||
override and repeats the input/save/cancel checks in all three window cases. It
|
||||
also requires a visible, successfully rendered preview in each owning window.
|
||||
The paired Extras fix registers tooltip positioning in existing and newly opened
|
||||
popouts; testing only the main plugin cannot establish that companion gate.
|
||||
|
||||
Obsidian 1.14.0's Temml renderer rejects Latex Suite's `\class` cursor and
|
||||
bracket markers with “Function \class is not trusted.” This is separate from
|
||||
CodeMirror window ownership and Extras tooltip positioning. A vault with a
|
||||
pre-existing global MathJax may render successfully despite identical plugin
|
||||
versions. [Obsidian 1.14.1 switched to MathJax 4.1.3](https://obsidian.md/changelog/2026-09-08-desktop-v1.14.1/).
|
||||
Update Obsidian to 1.14.1 or newer, or temporarily clear Latex Suite's **Cursor
|
||||
symbol** and disable **Highlight brackets in preview** when testing 1.14.0.
|
||||
Do not weaken renderer trust or install a global MathJax as a test workaround.
|
||||
|
||||
On Windows, the real-preview gate passed after upgrading the test host to
|
||||
Obsidian 1.14.4 with the original Latex Suite settings. Main-window, direct-popout
|
||||
and moved-tab input, rendered previews, save/reopen, cancel, JavaScript error
|
||||
checks and fixture cleanup all passed without disabling cursor decorations.
|
||||
|
||||
Separately validate modal
|
||||
dragging outside the editor, macOS/Linux popouts, restored windows and physical
|
||||
mobile input. Windows CDP results do not establish these platform/extension gates.
|
||||
|
||||
If CLI access is disabled, enable it in Obsidian first. If the app is running but
|
||||
the CLI cannot reach it, check host permissions: a sandbox may lack access to the
|
||||
macOS CLI socket or Windows IPC. Retry with authorized host access instead of
|
||||
|
||||
@@ -0,0 +1,732 @@
|
||||
# Obsidian Excalidraw CLI — research and implementation handoff
|
||||
|
||||
Prepared by **Zsolt's Codex Agent** on **2026-10-11**.
|
||||
|
||||
**Status:** Implemented and validated locally; the maintainer authorized committing, pushing, and merging on 2026-10-11. The original research and proposed contract remain below as the decision record. Actual behavior and validation are recorded in the implementation sections and [CLI reference](../CLI.md).
|
||||
|
||||
### Implementation baseline — 2026-10-11
|
||||
|
||||
The local implementation investigation continued on this PR branch at
|
||||
`44dac3237cdfb9e542a51cc2e83f3f24ec908e4f`, using Node `v22.22.2` and the
|
||||
installed `@zsviczian/excalidraw` `0.18.140`. The initial production build
|
||||
passed with the existing 32 circular-dependency warnings. `node --check
|
||||
dist/main.js` passed, and all 11 offline native-runner tests passed.
|
||||
The baseline `npm run code` reports 120 existing errors; no source code
|
||||
was changed during this baseline investigation.
|
||||
|
||||
The resulting `dist/main.js` is **4,995,829 bytes**, leaving **247,051 bytes**
|
||||
under the maintainer's intended **5 MiB (5,242,880-byte)** budget. Its SHA-256 is
|
||||
`44d6f37e518c4d2db2de3409a42b1cc1cd538ad336de48ad3cdb25c65263f529`.
|
||||
The initial investigation mistakenly interpreted the "5 MB" limit as decimal
|
||||
5,000,000 bytes and reported a budget conflict. The maintainer corrected that
|
||||
interpretation; implementation continues against the 5 MiB budget without a
|
||||
packaging optimization. Final bundle measurements must use the explicit byte
|
||||
threshold to avoid repeating this unit error.
|
||||
|
||||
Native transport probes used the existing, running `excalidraw-test` vault
|
||||
on macOS, Obsidian **1.14.4 (installer 1.14.0)**, launched through
|
||||
`scripts/testing/host/processTools.mjs` with explicit `vault=excalidraw-test`
|
||||
and captured subprocess stdout. Temporary native handlers on the already
|
||||
installed plugin returned valid JSON for a synchronous return, a resolved
|
||||
promise, a 30 ms timer, a Vault read, and a real library PNG render
|
||||
(1,133-byte in-memory blob). All five returned `ok: true`; each process
|
||||
exited zero. The probe removed its own handler registrations and cleanup
|
||||
callbacks afterward. It did not deploy the newly built baseline or write
|
||||
an exported image to the vault. The installed runtime's skeleton converter
|
||||
was present and used in the PNG probe.
|
||||
|
||||
These results support ordinary awaited CLI replies on this macOS/Codex
|
||||
subprocess combination. They do not establish Windows, Linux, another agent
|
||||
host, mobile startup, production command registration/unload, or the full
|
||||
authoring workflow. No receipt-mode transport workaround is currently
|
||||
justified. The exact canonical CLI declarations were also read from the
|
||||
official `obsidianmd/obsidian-api` `obsidian.d.ts`: the registration method
|
||||
and `CliData`, `CliFlag`, `CliFlags`, and `CliHandler` are tagged `1.12.2`.
|
||||
The maintainer requires both `requireApiVersion("1.12.2")` and method-presence
|
||||
validation before registration, with local structural types and no change
|
||||
to the Obsidian `1.8.7` dependency or minimum app version.
|
||||
|
||||
### Implementation and validation — 2026-10-11
|
||||
|
||||
The local implementation now covers all thirteen actions and the native root,
|
||||
with the same versioned dispatcher exposed as `ea.executeCLI`. Native
|
||||
registration is desktop-only and checks both API 1.12.2 and method presence.
|
||||
Canonical CLI types are local; Obsidian 1.8.7, manifests, lockfile, component,
|
||||
and Extras dependencies are unchanged. Session IDs use the existing mobile-safe
|
||||
`nanoid` helper, avoiding a new `crypto.randomUUID` startup requirement.
|
||||
|
||||
| Checkpoint | Implemented behavior | Recorded evidence |
|
||||
| --- | --- | --- |
|
||||
| 0 | Awaited native transport and baseline | Five captured native probes; 4,995,829-byte baseline |
|
||||
| 1 | Descriptors, JSON dispatcher, discovery/schema/API/list/read/open, EA facade | 5,019,055-byte build; native help/status/schema/read registration |
|
||||
| 2 | Converter validation, local/label IDs, strict EA creation, templates | 5,028,949-byte build; labels/arrows/frames, root path and collision round-trip |
|
||||
| 3 | Guarded request-local text metadata, finite edits, save acknowledgments | Native stale/busy, delayed text, failed-save recovery, relationship edits, replay and saved read-back |
|
||||
| 4 | Vault images, optional MathJax preflight, live/disk SVG/PNG and area bounds | Native image metadata round-trip; source-tagged exports; PNG visual inspection; 200×80 crop with zero padding |
|
||||
| 5 | Trusted existing scripts, JSON/library utilities, exact source cache check, one-shot cleanup | Native context, replay/source conflict, prompt refusal; production-method tests preserve manual lifetime |
|
||||
| 6 | Offline skill, localized help/copy command, README/reference, declarations, release notes, repeatable runner | Production and library build; 19 focused tests and 11 runner tests; full native scenario passed |
|
||||
|
||||
Final production `dist/main.js`: **5,053,346 bytes**,
|
||||
**57,517 bytes** over baseline, leaving
|
||||
**189,534 bytes** under **5,242,880 bytes**.
|
||||
SHA-256: `7705eeba5d23a0bf54c2e3ea874d7d0ae0b270186ed4b2e326e6e45f3cfd7a9b`.
|
||||
Builds have no TypeScript diagnostics. Existing circular-dependency warnings
|
||||
remain. `npm run code` still reports exactly the baseline **120 errors, zero
|
||||
warnings**; the new CLI modules, types, dialog, and save-outcome seam lint cleanly.
|
||||
`npm run lib` regenerated the ignored public declaration graph, including
|
||||
`executeCLI`, its request/result DTOs, and the strict creation parameters.
|
||||
No generated build artifacts were hand-edited or added as source changes.
|
||||
|
||||
The complete registered-command scenario passed on **macOS / Codex subprocess
|
||||
execution / Obsidian 1.14.4 (installer 1.14.0)** with the installed published
|
||||
component **0.18.140**:
|
||||
|
||||
`npm run verify:obsidian:plugin -- --native-cli`
|
||||
|
||||
Final report:
|
||||
`/var/folders/b1/2dys0jfs7bq73whkl2qnyyym0000gn/T/excalidraw-obsidian-jQHWu0/report.json`.
|
||||
The report pins built/installed artifact hashes and confirms owned fixture
|
||||
cleanup. The fixture exercises native file input, discovery, templates, invalid
|
||||
construction/collision refusal, stable text IDs, fresh revisions, duplicate
|
||||
receipts, competing writes, delayed text preparation, save failure, finite
|
||||
relationships/frame guards, core rendering, vault images, scripts, and reopening.
|
||||
Separate live/light and disk/dark exports were also checked; a PNG was visually
|
||||
inspected to confirm labels, connector and frame placement. The localized help
|
||||
dialog and its copy button mounted successfully. All seven manual checkpoint
|
||||
fixtures were removed after their inspections; repeatable scenarios clean their
|
||||
own temporary files and hooks.
|
||||
|
||||
A combined `--text-undo --native-cli` attempt timed out in the existing
|
||||
text-undo eval probe before reaching CLI scenarios; its cleanup passed. Report:
|
||||
`/var/folders/b1/2dys0jfs7bq73whkl2qnyyym0000gn/T/excalidraw-obsidian-8npk9o/report.json`.
|
||||
An independent Kplex runner was active at the time; that observation does not
|
||||
establish the timeout's cause. The declared 0.18.140 component also lacks the
|
||||
separate unchanged-text history fix, as already documented in the runtime guide.
|
||||
The focused CLI scenario runs independently and passed. Driver subprocesses now
|
||||
use SIGKILL at timeout, so an ignored SIGTERM cannot leave the runner waiting.
|
||||
|
||||
Decisions/limits: schema uses `action` to avoid the native transport's
|
||||
`command` name; JSON schemas describe request structure while runtime geometry,
|
||||
relationship, and lifecycle guards remain authoritative. Lib help is an explicit
|
||||
supported subset of the installed runtime. Save handoffs/unchanged attempts are
|
||||
conservatively unacknowledged. Scripts report unknown mutation/persistence and
|
||||
cannot promise rollback or timeout cancellation. A legacy destination is rejected
|
||||
when a template's linked assets would lose their Obsidian metadata. No agent
|
||||
configuration is installed automatically, and no new outbound service is used.
|
||||
|
||||
Remaining risk-based maintainer checks (separate environments):
|
||||
|
||||
1. Apply text/image edits in an inactive popout, then migrate/unload during
|
||||
preparation; check stale/busy refusal, undo/redo, and absence of duplicate saves.
|
||||
2. Load on real Obsidian 1.8.7 and a physical mobile device; native registration
|
||||
should be absent and ordinary editing/help should work. Older API, missing
|
||||
method, and mobile registration guards are covered by automated tests.
|
||||
3. Run the full flow from a second terminal-capable agent host and Windows/Linux
|
||||
launcher. Claudian/Agent Client/Copilot, physical devices, and those platforms
|
||||
have not been tested here; conditional compatibility is not runtime evidence.
|
||||
|
||||
### Maintainer-requested visual authoring test — 2026-10-11
|
||||
|
||||
Recreated the supplied check-in/Q&A reference in `excalidraw-test` entirely
|
||||
through native CLI commands: Obsidian `create` staged the trusted EA script,
|
||||
Excalidraw `script` constructed the drawing, `read` verified disk persistence,
|
||||
`open` opened it, finite `apply` refined capsule geometry with a fresh revision
|
||||
and returned `persistence=saved`, and `export` rendered the PNG for inspection.
|
||||
No eval transport, direct drawing-file writes, or raster imports were used.
|
||||
|
||||
The saved `CLI recreation - Check-in and QA.excalidraw.md` contains **73 editable
|
||||
elements**: 9 rectangles, 28 lines, 21 text elements, and 15 ellipses, with zero
|
||||
image assets. Its **1692×961** PNG was visually checked after refinement. Both
|
||||
outputs remain in the test vault at the maintainer's request; the three temporary
|
||||
script/request notes were moved to trash through the native CLI.
|
||||
|
||||
Two native Obsidian `create` transport details were handled in the test client:
|
||||
escaped newlines in source strings expand during note creation, and an input
|
||||
request using a `.json` path is created as a Markdown note. Reading back the
|
||||
actual generated path/content resolved both; neither failure mutated the drawing.
|
||||
|
||||
The maintainer approved merging after this test. Cross-platform and physical
|
||||
device coverage remains limited to the evidence listed above.
|
||||
|
||||
### Verification after integrating current master — 2026-10-11
|
||||
|
||||
Merged `origin/master@07dec121` into the implementation branch at `769d58ea`,
|
||||
preserving the newly added embed, grouped-link, and LaTeX runner options alongside
|
||||
`--native-cli`. Resolved additive conflicts in the runtime guide and runner only.
|
||||
The release notes also document the new EA signatures.
|
||||
|
||||
Production/library builds and `node --check dist/main.js` passed. All **50 tests**
|
||||
across CLI, runner, process launchers, and Markdown embeds passed. Targeted CLI,
|
||||
type, dialog, and save-coordinator ESLint passed. The updated production bundle is
|
||||
**5,057,617 bytes**, leaving **185,263 bytes** under the **5,242,880-byte** budget;
|
||||
SHA-256 `18a27d7455cf57f83840c5053ea28ff7a88bc6b7661516ec0141482f322b95c1`.
|
||||
|
||||
The full smoke runner verified matching installed hashes, plugin load, and the
|
||||
main-window drawing, then timed out in the feature phase. Fixture cleanup passed;
|
||||
report: `/var/folders/b1/2dys0jfs7bq73whkl2qnyyym0000gn/T/excalidraw-obsidian-3FaWmy/report.json`.
|
||||
The exact timed-out command was not captured. Native readiness returned healthy
|
||||
and the app error buffer was empty afterward.
|
||||
|
||||
Reran the complete `runNativeCLIScenario` on uniquely owned fixtures against that
|
||||
same installed artifact, with command-level timeout tracing. All assertions
|
||||
passed, including save/reopen, live/disk exports, script context, guarded edits,
|
||||
failed-save recovery, and owned fixture cleanup. Evidence:
|
||||
`/private/tmp/excalidraw-cli-premerge-result.json` and
|
||||
`/private/tmp/excalidraw-cli-premerge-trace.json`. This focused rerun does not
|
||||
relabel the full runner's timeout as a pass.
|
||||
|
||||
**Implementation workspace:** `2026-10-11-obsidian-excalidraw-cli`, initially branched from plugin `master@bf541ca5d460f5773a5547ba4511eba3ff0f2e5b`. Continue on this branch and its draft PR. Recheck its head, current instructions, and related changes before coding. The maintainer requested the detailed plan in this file: retain it through implementation, update decisions and validation here, and do not treat it as the usual disposable one-paragraph planning stub.
|
||||
|
||||
## 1. Recommended design
|
||||
|
||||
Implement a **native Obsidian CLI extension in the plugin**, backed by a small transport-neutral dispatcher. Use ExcalidrawAutomate for Obsidian-aware operations and the already-exported `ExcalidrawLib.convertToExcalidrawElements` for convenient batch construction. Reuse the current view, file, asset, export, and save paths rather than building another drawing engine.
|
||||
|
||||
The intended agent loop is:
|
||||
|
||||
`discover → inspect schema → read drawing → apply a bounded edit → verify persistence → render → inspect image`
|
||||
|
||||
| Decision | Recommendation |
|
||||
| --- | --- |
|
||||
| Transport | Public `Plugin.registerCliHandler`, not an `eval`-only protocol or a new executable. |
|
||||
| Implementation scope | Plugin only. No new fork or Extras API is indicated by the source. Verify against the installed fork package, not just its remote `master`. |
|
||||
| Normal authoring | JSON requests with readable skeletons, explicit targets, and a small set of semantic operations. |
|
||||
| Full advanced access | A documented, explicitly trusted, one-shot EA script command plus progressive EA/Lib API help. Do not generate a command for every method. |
|
||||
| Discovery | Native help/autocomplete, runtime schemas/examples, a short portable Agent Skill, and a human Command Palette entry pointing to CLI help. |
|
||||
| Existing drawings | Mutate a specifically resolved live view through existing plugin logic. Require an explicit open operation when a drawing is not open. Do not add a second closed-file persistence engine. |
|
||||
| Output | JSON results by default; save SVG/PNG to an explicit vault path and return a small artifact descriptor. |
|
||||
| Non-goals | No Excalidraw+ account integration, HTTP server, MCP server, provider SDK, browser download, global agent-config editing, or generic workflow/job framework. |
|
||||
|
||||
A broad API does not mean every operation can run unattended: modals, long-lived sidepanels, optional Extras features, and trusted code have different requirements. Expose those requirements instead of hiding them behind a misleading universal command.
|
||||
|
||||
## 2. Research findings and evidence
|
||||
|
||||
### 2.1 The announced Excalidraw CLI is a reference, not a dependency
|
||||
|
||||
The supplied [announcement URL][announcement] could not be read reliably. I located and inspected the official `excalidraw/cli` repository and the Excalidraw+ roadmap instead. This analysis does not infer the tweet's exact wording or announcement date.
|
||||
|
||||
At inspected revision `55fe7f494837078781a062c4d3faf29c159ebec5`, the official CLI combines local rendering with Excalidraw+ workspace/scene/collection operations. Local rendering does not require an account. Its command registration, content validation, and browser-side rendering code are useful references. [E1], [E2], [E3], [E4]
|
||||
|
||||
Reuse the **design patterns**: machine-readable output, command-specific help, file-based JSON input, validation before writes, bounded output, and explicit partial-failure reporting. Do not copy its cloud authentication model, server content-reconciliation assumptions, Commander/Zod dependency stack, or separate browser-rendering process into the plugin. Obsidian already hosts the rendering runtime and owns vault persistence.
|
||||
|
||||
### 2.2 Obsidian has a public custom CLI API
|
||||
|
||||
The current official `obsidian.d.ts`, inspected at `9abd9605ce081383674aae1ed111c456edde0688`, declares the following public API, tagged `@since 1.12.2`: [O1]
|
||||
|
||||
```ts
|
||||
registerCliHandler(
|
||||
command: string,
|
||||
description: string,
|
||||
flags: CliFlags | null,
|
||||
handler: CliHandler,
|
||||
): void;
|
||||
|
||||
interface CliData { [key: string]: string | 'true'; }
|
||||
interface CliFlag {
|
||||
value?: string;
|
||||
description: string;
|
||||
required?: boolean;
|
||||
}
|
||||
type CliFlags = Record<string, CliFlag>;
|
||||
type CliHandler = (params: CliData) => string | Promise<string>;
|
||||
```
|
||||
|
||||
Command IDs are global, and duplicate registration throws. Use the existing plugin ID as the namespace. Native flag descriptions feed help/autocomplete. Do not confuse these handlers with Command Palette commands exposed by `obsidian commands` and `obsidian command id=...`.
|
||||
|
||||
The documented desktop CLI requires the running app, CLI enablement/registration, and a suitable installer. Use an explicit `vault=<name-or-id>` **before the command** in agent instructions. Paths are vault-relative; native parameters use `key=value` and boolean switches are bare flags. This is not Obsidian Headless. [O2]
|
||||
|
||||
The plugin currently compiles against Obsidian types `1.8.7`. Keep its existing minimum app compatibility. Add only the canonical missing CLI declarations using the repository's established typing approach, and feature-detect the registration method at runtime. Do not assume a declaration proves runtime support or raise the minimum app version solely for this optional feature. [P1], [P2]
|
||||
|
||||
### 2.3 Async CLI delivery is a real test gate
|
||||
|
||||
An April–May 2026 firsthand report describes Obsidian 1.12.7 plugin handlers losing stdout after real asynchronous work, especially through pipes/agent tools; a second reporter reproduced it without Codex. That is historical evidence, not proof that current Obsidian still has the bug. [O3]
|
||||
|
||||
**First implementation task:** register a small test handler and check synchronous return, a resolved promise, a short timer, vault I/O, and a real PNG export through native CLI stdout. Test a terminal and an actual agent subprocess, including redirected/piped output. Record app, installer, platform, launcher, and harness versions.
|
||||
|
||||
Prefer the ordinary `Promise<string>` return contract. Do not introduce a mandatory background-job system based on an old report. If supported environments reproduce lost async output, add only an explicit asynchronous receipt mode and a synchronous `:result` lookup using the same bounded session receipt map described below. Do not block Obsidian's event loop waiting for work, scrape developer-console output, or claim an empty stdout/zero exit code means success.
|
||||
|
||||
### 2.4 Agent integrations: use their existing execution paths
|
||||
|
||||
| Integration inspected | Relevant behavior | Design implication |
|
||||
| --- | --- | --- |
|
||||
| **Claudian** | Its README describes local coding-agent execution and vault tools. Its Claude command catalog relies on native SDK discovery of commands/skills rather than independently interpreting every skill directory. | A native CLI plus a standard skill fits its existing terminal/skill model. Do not depend on Claudian-private APIs. [A1], [A2] |
|
||||
| **Agent Client** | ACP clients expose terminal requests; sessions can use a directory other than the vault, and the README documents native agent skills and permissions. | Always name the vault. Terminal access depends on the selected agent's capabilities and approval, not merely on ACP being present. [A3], [A4] |
|
||||
| **Copilot for Obsidian** | Current source includes an Obsidian CLI skill for coding-agent backends and platform-specific CLI executable discovery. | Reuse the host's CLI execution and skill support; do not characterize every Copilot mode as shell-capable or add a custom provider bridge. [A5], [A6] |
|
||||
| **MCP-only or API-only chat clients** | A chat interface does not inherently provide a local terminal. | Expose the same JSON dispatcher in-process for integrations. An external MCP adapter can forward it later; no built-in MCP server is needed for V1. |
|
||||
|
||||
Agent Skills provides the portable `SKILL.md` convention and progressive disclosure. Skill availability still depends on the harness's discovery rules and permissions. Do not promise universal automatic discovery or treat a skill's `allowed-tools` metadata as a security boundary. [A7]
|
||||
|
||||
### 2.5 Existing plugin and fork primitives
|
||||
|
||||
Source baselines inspected:
|
||||
|
||||
| Repository | Revision | Role |
|
||||
| --- | --- | --- |
|
||||
| `zsviczian/obsidian-excalidraw-plugin` | `bf541ca5d460f5773a5547ba4511eba3ff0f2e5b` | Accepted plugin baseline for this plan. |
|
||||
| `zsviczian/excalidraw` | `6ec95a327b77df2696e170cb0c9d8a84ac115121` | Inspection of exported functions and skeleton conversion. |
|
||||
| `zsviczian/obsidian-excalidraw-extras` | `18ed02765078ac8e9f78df7449ccb907cb000460` | Optional feature boundary, previously inspected 0.1.1 source. |
|
||||
| `excalidraw/cli` | `55fe7f494837078781a062c4d3faf29c159ebec5` | Official CLI reference implementation. |
|
||||
|
||||
The plugin declares `@zsviczian/excalidraw` **0.18.140**. Its installed artifact must be checked independently of the fork's current source. The CLI should not require an unpublished API or automatically bump the fork package. [P1]
|
||||
|
||||
| Source | Verified behavior / implication |
|
||||
| --- | --- |
|
||||
| `src/core/index.ts`, EA `getAPI(view)` | Existing factory creates a separate EA. Allocate one per operation; never use the mutable global EA workbench for concurrent requests. [P3], [P4] |
|
||||
| EA `elementsDict`, `imagesDict`, `clear`, `setView` | EA stages edits. `clear()` clears the workbench, not the drawing. Automatic `setView()` can select active/last/first; CLI targeting must not use that fallback. [P4] |
|
||||
| EA `help`, `SuggesterInfo.ts` | Help uses existing signature/description metadata but prints to the console. A CLI help handler must return metadata, not return `ea.help()` or scrape its logs. [P4], [P5] |
|
||||
| EA `addElementsToView`, view `addElements` | Existing route handles text parsing, image/equation metadata, runtime file publication, container/arrow refresh, and saving. Reuse it, with narrow guards/receipts where required. [P4], [P6] |
|
||||
| `ViewSaveCoordinator` | Internal save outcomes exist, but public save helpers often return `void`; a resolved call is not a durable-save receipt. [P7] |
|
||||
| EA `create`, `FileManager.createDrawing` | Existing serialization handles plugin Markdown, but defaults include global format/folder settings and collision suffixing. An exact-path CLI needs a small explicit per-call option, not temporary global setting changes. [P4], [P8] |
|
||||
| EA `getSceneFromFile` | Returns elements/appState, not a complete asset/Markdown metadata round-trip. Do not use it to overwrite a drawing. [P4] |
|
||||
| EA `createViewSVG/PNG`, `createSVG/PNG` | Existing live-view and file/template export routes exist. `elementsOverride` is a complete candidate list, not a patch. [P4] |
|
||||
| `Scripts.ts` | Script execution already returns a value and supports fresh EAs, but existing scripts intentionally retain lifetime for hooks/sidepanels. Add CLI-only one-shot cleanup rather than changing all scripts. [P9] |
|
||||
| Fork `index.tsx`, plugin constants/types | `convertToExcalidrawElements`, restoration, geometry, mutation helpers, and exports are already exposed. No new fork export is required. [F1], [P10], [P11] |
|
||||
|
||||
## 3. Command surface and discovery contract
|
||||
|
||||
Use `obsidian-excalidraw-plugin` as the native root command and `obsidian-excalidraw-plugin:<action>` for actions. Keep the long but collision-safe native name in examples; no shell alias or separate npm installation is required.
|
||||
|
||||
All action handlers call the same dispatcher. A proposed public EA method, **`ea.executeCLI(request)`**, should delegate to that dispatcher and return the same JSON-compatible result. It must not reuse the caller's staged elements or automatically target the caller's current view. This is the documented in-process route for other plugins; native CLI remains the primary agent route.
|
||||
|
||||
| Action | Purpose and principal inputs |
|
||||
| --- | --- |
|
||||
| root / `help` | Short overview, action names, next command to run, and examples. |
|
||||
| `status` | CLI API version, plugin/runtime readiness, installed dependency capabilities, current vault identity, optional-feature availability. No keys or complete settings dump. |
|
||||
| `schema` | `command=<action>`; return that command's JSON input/output schema, defaults, side effects, and runnable example. |
|
||||
| `api` | `surface=ea\|lib`, `query=<text>` or `name=<method>`; bounded method search, signatures, descriptions, relevant examples. Discovery only, not reflective invocation. |
|
||||
| `list` | Drawing paths with bounded pagination; optional `folder`. Use the plugin's drawing classification rather than extension-only guesses. |
|
||||
| `read` | Exact `path`, optional `view`, `source=auto\|live\|disk`, `detail=summary\|elements`, selection/ID filters, pagination. Return source/revision/dirty state. |
|
||||
| `open` | Resolve or explicitly open a drawing as Excalidraw and return a ready view identity. This command can change the workspace; no hidden opens in `read`. |
|
||||
| `create` | Exact new `path`, optional explicit template, and JSON construction request. Fail on an existing target by default. |
|
||||
| `apply` | One bounded edit request against an explicit live target and expected revision. Stage edits, publish through the plugin, and report persistence. |
|
||||
| `export` | SVG/PNG to an explicit vault-relative `out`; source/selection/area, theme, padding, and bounded scale options. Return artifact metadata. |
|
||||
| `script` | Explicit existing script path, target when needed, JSON arguments, and a `trusted` acknowledgment. One-shot execution for advanced EA/Lib use. |
|
||||
| `skill` | Return the portable CLI skill; `format=markdown` is useful for saving or attaching it. Default JSON can contain the Markdown string. |
|
||||
| `result` | Retrieve a recent operation receipt by caller-supplied request ID. Session-only; not a persistent job service. |
|
||||
|
||||
The root index, schema, and API help should be short and useful without a loaded drawing. An unavailable optional operation must be reported as unavailable with a reason, not silently omitted from documentation or registered as a no-op.
|
||||
|
||||
### Discovery layers
|
||||
|
||||
1. Register native descriptions and `CliFlags` so `obsidian help` and `obsidian help obsidian-excalidraw-plugin:apply` explain the actual command.
|
||||
2. Return a small machine-readable index from the root command. Include `apiVersion`, capability flags, input style, and next-step examples.
|
||||
3. Return detailed schemas only when requested. Derive help, examples, validation, and skill action names from one small command descriptor registry. Do not bundle a general JSON-schema engine solely to validate this finite command set.
|
||||
4. Reuse EA's existing documentation metadata and generated Lib references for progressive API help. Do not invent signatures from runtime function arity or expose private plugin methods/settings through reflection.
|
||||
5. Add a Command Palette entry such as **Excalidraw: Show CLI and agent instructions**, with a copy action for the skill. This also helps agents that first discover the plugin through `commands filter=obsidian-excalidraw-plugin`.
|
||||
6. Add a short README entry and a CLI reference document linked from the existing EA skill. The installed plugin is normally three artifacts; repository documentation is not automatically present in every user's vault. The runtime `skill`/`help` route must work without fetching GitHub.
|
||||
|
||||
Keep the portable skill small: when to use the CLI, explicit vault/target rules, the read/apply/export loop, structured errors, and links to deeper runtime help. Exporting/installing a skill is a user action. Never overwrite vault `AGENTS.md`, `CLAUDE.md`, `.claude`/`.agents` directories, provider configuration, or Claudian's per-device skill links automatically.
|
||||
|
||||
## 4. Requests, results, and examples
|
||||
|
||||
### 4.1 Input and target rules
|
||||
|
||||
Small operations can use native flags. For construction and edits, prefer **`input=<vault-relative UTF-8 JSON file>`**. This avoids fragile shell escaping and oversized Windows IPC arguments. A small `json=<payload>` alternative may be supported; require exactly one of them. Do not interpret JSON strings as code.
|
||||
|
||||
JSON payloads use `apiVersion: 1`. The native action supplies `command`; the in-process method includes it explicitly. If a target is supplied both in flags and the file, require the values to agree rather than silently override one. Paths are exact vault-relative paths, including the extension. A missing path is an error, not permission to edit the active drawing.
|
||||
|
||||
For existing drawings, `apply` requires a fresh `expectedRevision` from a live `read`. `view` is required when more than one eligible view shows the same file. A stale or unavailable target returns a useful error and the candidates; do not pick the first or most recently active leaf.
|
||||
|
||||
`source=auto` uses an unambiguous live view when present, otherwise disk; multiple live candidates require a view choice. `source=live` fails when no ready view exists. `source=disk` does not open or save the drawing. Selection filters require a live source. Use one snapshot for each read response, with a default summary and bounded element pages. Omit base64 asset bodies and return a revision/source marker. A changed snapshot invalidates a pagination cursor. An explicit disk read may differ from unsaved live content and must say so.
|
||||
|
||||
### 4.2 Result envelope
|
||||
|
||||
A proposed completed result shape is:
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"requestId": "diagram-pass-01",
|
||||
"status": "completed",
|
||||
"ok": true,
|
||||
"command": "apply",
|
||||
"target": {
|
||||
"vault": "Design Vault",
|
||||
"path": "Drawings/Flow.excalidraw.md",
|
||||
"viewId": "opaque-view-id"
|
||||
},
|
||||
"revision": "opaque-new-revision",
|
||||
"persistence": "saved",
|
||||
"data": {
|
||||
"createdIds": ["a1b2c3d4"],
|
||||
"updatedIds": [],
|
||||
"deletedIds": [],
|
||||
"idMap": {"nodeA": "a1b2c3d4"}
|
||||
},
|
||||
"warnings": []
|
||||
}
|
||||
```
|
||||
|
||||
`status` is `completed`, `failed`, or `pending`. A pending response is **not success**: use `ok: null` and direct the caller to `result`. `persistence` is `not-applicable`, `saved`, `unsaved`, or `unknown`; `saved` means the corresponding mutation was acknowledged durable by the existing save path, not merely queued or visible. A `result` lookup may return pending while an ordinary awaited request is still running.
|
||||
|
||||
Errors include a stable code, short explanation, relevant field, and recovery action. Initial codes should cover `INVALID_INPUT`, `UNSUPPORTED_COMMAND`, `NOT_READY`, `NOT_FOUND`, `NOT_EXCALIDRAW`, `AMBIGUOUS_TARGET`, `BUSY`, `STALE_REVISION`, `ALREADY_EXISTS`, `DEPENDENCY_UNAVAILABLE`, `INTERACTION_REQUIRED`, `RENDER_FAILED`, `SAVE_FAILED`, and `OUTCOME_UNKNOWN`. Report whether a mutation was not applied, applied, partial, or unknown when failure follows side effects. Do not expose stack traces or private payloads by default.
|
||||
|
||||
Return strings from native handlers. Do not use `console.log` as the response channel, patch global logging, or call `process.exit` inside Obsidian. The host owns process exit behavior; agents must parse the result rather than infer success from exit code alone.
|
||||
|
||||
### 4.3 End-to-end authoring example
|
||||
|
||||
These are proposed commands for the implementation agent to turn into tested examples:
|
||||
|
||||
```sh
|
||||
obsidian vault="Design Vault" help obsidian-excalidraw-plugin:create
|
||||
obsidian vault="Design Vault" obsidian-excalidraw-plugin:status
|
||||
obsidian vault="Design Vault" obsidian-excalidraw-plugin:schema command=create
|
||||
obsidian vault="Design Vault" obsidian-excalidraw-plugin:create input="Agent IO/create-flow.json"
|
||||
obsidian vault="Design Vault" obsidian-excalidraw-plugin:open path="Drawings/Flow.excalidraw.md"
|
||||
obsidian vault="Design Vault" obsidian-excalidraw-plugin:read path="Drawings/Flow.excalidraw.md" source=live detail=elements
|
||||
obsidian vault="Design Vault" obsidian-excalidraw-plugin:export path="Drawings/Flow.excalidraw.md" source=live format=png out="Agent IO/flow-preview.png" requestId=preview-flow-01
|
||||
```
|
||||
|
||||
`Agent IO/create-flow.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"requestId": "create-flow-01",
|
||||
"path": "Drawings/Flow.excalidraw.md",
|
||||
"operations": [
|
||||
{
|
||||
"op": "add",
|
||||
"elements": [
|
||||
{
|
||||
"id": "input",
|
||||
"type": "rectangle",
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 180,
|
||||
"height": 90,
|
||||
"label": {"text": "Input"}
|
||||
},
|
||||
{
|
||||
"id": "output",
|
||||
"type": "rectangle",
|
||||
"x": 320,
|
||||
"y": 0,
|
||||
"width": 180,
|
||||
"height": 90,
|
||||
"label": {"text": "Output"}
|
||||
},
|
||||
{
|
||||
"id": "flow",
|
||||
"type": "arrow",
|
||||
"x": 180,
|
||||
"y": 45,
|
||||
"width": 140,
|
||||
"height": 0,
|
||||
"start": {"id": "input"},
|
||||
"end": {"id": "output"}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Here input IDs are **request-local labels**, not instructions to overwrite elements with those IDs. The result maps them to actual IDs. Generated label elements must also be discoverable in the result/read response. An edit request uses the returned actual IDs and live revision:
|
||||
|
||||
```json
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"requestId": "edit-flow-02",
|
||||
"path": "Drawings/Flow.excalidraw.md",
|
||||
"view": "view-id-from-open",
|
||||
"expectedRevision": "revision-from-live-read",
|
||||
"operations": [
|
||||
{
|
||||
"op": "update",
|
||||
"id": "actual-output-container-id",
|
||||
"set": {"backgroundColor": "#e7f5ff"}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The agent saves that payload to a new input file, calls `:apply`, checks the receipt, exports again, and inspects the rendered image through its host's image tool. Excalidraw should not call an AI provider merely to inspect its own export.
|
||||
|
||||
### 4.4 Session receipts, not a job framework
|
||||
|
||||
Require a caller-supplied request ID for drawing writes, output-file writes, and trusted scripts. Maintain a small bounded in-memory receipt map, scoped to the plugin session, keyed by ID and a fingerprint of the effective request. Fingerprint parsed input contents, not just an input filename; include the executed script's source identity for scripts. The same ID and same request returns the existing receipt rather than applying again; the same ID with different content is an error. Include a session identifier and document expiration. Do not evict active entries; reject new work when capacity is exhausted.
|
||||
|
||||
This permits `:result requestId=...` after lost stdout or a client timeout. It does **not** provide durable exactly-once execution across reloads. After restart/expiration, report unknown outcome and require read-back before a new mutation. Do not silently retry writes. If the async transport issue is reproduced, an explicit `async` flag can return the receipt immediately and let callers poll the same map. In that mode require `requestId` in the native flags before any awaited input-file read; a matching ID inside the file is allowed. No additional queue, database, or HTTP endpoint is necessary.
|
||||
|
||||
## 5. Element construction and editing
|
||||
|
||||
### 5.1 Use the existing converter for new skeleton batches
|
||||
|
||||
The fork's `packages/element/src/transform.ts` does more than fill defaults: it generates measured text, labels, arrow bindings, frame membership, and element ordering. It operates on a temporary scene containing **only the supplied skeletons**. It does not know the current Obsidian scene. [F2]
|
||||
|
||||
Implementation sequence:
|
||||
|
||||
1. Validate the complete batch before invoking the converter: supported types, finite coordinates/dimensions, unique local IDs, valid references, valid frame children, and bounded size. Preserve intentional zero values rather than applying truthy defaults in the CLI.
|
||||
2. Allocate collision-free IDs using the plugin's conventions; map local IDs and all intra-batch references before conversion. Pass `regenerateIds: false` after this mapping so the returned ID map remains useful. Account for the plugin's short text IDs and additional IDs generated for bound labels; verify post-save IDs, not just immediate constructor output.
|
||||
3. Call the **installed** library's converter once for the batch. Verify the resulting IDs, references, and supported types before publication. The converter may log/skip duplicates and may throw on invalid references; it is not a substitute for CLI validation.
|
||||
4. Put the generated elements into a fresh EA's workbench and use the plugin's insertion or creation path as appropriate. Do not write the returned array directly into a `.excalidraw.md` file or skip text/asset metadata synchronization.
|
||||
|
||||
Do not run existing scene elements through the converter just to change their style or text: that risks rebuilding identities and bindings. A new arrow referring to an **existing** scene element cannot rely on the converter's local-ID map. Copy the required live endpoints into EA and use existing `connectObjects`/arrow helpers, then publish the coherent change.
|
||||
|
||||
Do not add newly supported fork-only element types to the CLI's advertised schema until the installed package supports them. Basic shapes/text/arrows/frames can establish the first usable slice. Special elements remain accessible through documented EA methods without duplicating every constructor.
|
||||
|
||||
### 5.2 Small semantic operation set
|
||||
|
||||
`apply` should support these operations through the same staging/publication path:
|
||||
|
||||
| Operation | Implementation direction |
|
||||
| --- | --- |
|
||||
| `add` | Skeleton batch as above; ordinary shapes, text, arrows, frames, and other installed supported types. |
|
||||
| `update` | Actual element ID plus validated `set` fields. Copy live elements to EA; preserve IDs/bindings/unknown existing custom data, and maintain version/nonce increments through existing mutation helpers. Route text changes through existing raw/parsed text and measurement behavior. |
|
||||
| `delete` | Explicit IDs; use deletion/tombstone and binding cleanup behavior, not array omission or attachment deletion. Include bound labels consistently. Require an explicit children option before removing a nonempty frame's contents. |
|
||||
| `connect` | Existing/request-created endpoint IDs, optional side/arrow styling. Reuse EA's connection helpers; no new routing engine. |
|
||||
| `group` / `ungroup` | Explicit IDs/group, using existing grouping conventions and preserving unaffected groups. |
|
||||
| `image` | Explicit vault asset and coordinates, through EA image loading and `imagesDict`. No unsupported bare `fileId` with absent binary/source data. |
|
||||
| `latex` | Explicit source and coordinates through EA; preflight the existing Extras feature and report unavailable/interaction-required rather than opening consent UI unexpectedly. |
|
||||
|
||||
The first release does not need a generic full-scene replacement, arbitrary JSON Pointer patcher, or reflective `ea[method](...args)` command. Use trusted scripts for uncommon operations, advanced layouts, Mermaid, SVG import, Markdown-image workflows, or selection/view automation until their semantics warrant a stable structured command.
|
||||
|
||||
An `update` schema must identify fields that cannot be assigned directly: IDs, type changes, version bookkeeping, raw binary data, frame/arrow relationships, and special Markdown-image metadata. Reject unsupported edits with the relevant EA method/help link. Never silently discard unknown requested properties. Do preserve unknown properties already in the drawing.
|
||||
|
||||
## 6. Persistence, targeting, and side effects
|
||||
|
||||
### 6.1 Explicit live ownership
|
||||
|
||||
Resolve the target once to a file, view, and runtime API identity. Check file identity and lifecycle again after awaited work. Return `BUSY` during closing/migration, active same-file Markdown editing, or incompatible synchronization rather than bypassing existing guards. Do not use `getEA().setView()` without an explicit view, `activeWindow`, or a last-active leaf as a hidden fallback.
|
||||
|
||||
A specifically requested `open` may reveal a normal main-window tab so the existing React lifecycle actually mounts; a hidden leaf is not guaranteed to initialize. Report the resulting view ID. Existing popout views can be targeted explicitly. Do not migrate the user's leaf or construct a headless React root solely for CLI work. Opening a drawing may run its existing user-configured scripts: document that normal workspace side effect rather than claiming an execution sandbox.
|
||||
|
||||
Serialize CLI mutations for the same drawing using a small in-flight guard; return `BUSY` for competing requests rather than creating another persistence queue. Other drawings may proceed independently. This guard does not lock out human editing, so optimistic validation is still needed.
|
||||
|
||||
### 6.2 Revisions must cover the data actually being edited
|
||||
|
||||
A live read returns an opaque revision tied to the current session, file/view/API generation, and authoritative edit state. Reuse existing save revisions and source identities where they cover the operation. The fork's legacy sum-of-element-versions is not sufficient; even its ordered element hash does not describe Markdown-image source, binary mappings, or all document metadata. [F3], [P7]
|
||||
|
||||
Before publication, confirm that the state used to prepare the edit is still current. Include relevant document/asset metadata in the check or refuse an operation while that state is changing. Do not invent a universal merge policy or overwrite newer user edits.
|
||||
|
||||
**Important source trap:** view `addElements` performs awaited text work before publication. A check only at CLI entry is insufficient. Add a narrow optional prepublication validation hook or equivalent internal seam, preserving existing callers. Trace where text/asset metadata is changed as well: a guard only immediately before `updateScene` must not leave partially changed metadata from earlier preparation. Prefer request-local preparation and existing lifecycle identities; do not use a full scene rollback that could erase concurrent user work. If a path cannot meet the prepublication contract without broader redesign, keep that path out of structured `apply` and document its trusted-script alternative until resolved. [P6]
|
||||
|
||||
### 6.3 Report durable saves, not attempted saves
|
||||
|
||||
The current coordinator has useful internal outcomes including `persisted`, `unchanged`, `skipped`, `failed`, and persistence/window handoffs. Public `save()` discards the result, and force-save can return after skipping or catching an error. `addElementsToView()` returning true is therefore not proof that the requested edit reached disk. [P7]
|
||||
|
||||
Add the smallest internal outcome-returning method and view facade needed by the CLI while retaining old signatures/behavior for existing callers. Map the result to the CLI's receipt using the acknowledged revision. Do not return the internal prepared-save object or serialized vault content. A handoff is not durable until its existing completion confirms that revision.
|
||||
|
||||
Use the existing save coordinator and file persistence rules. Do not add direct `vault.modify` writes to an open drawing. Do not call `clearDirty`, drop failed edits, reset history, or print “saved” because the view currently looks clean. A save failure after scene publication must report `mutation: applied` with unsaved/unknown persistence and preserve the user's recovery options. A late client timeout does not undo the mutation.
|
||||
|
||||
Publish a coherent edit with the existing capture/update policy so normal undo remains meaningful. Add focused regression coverage for text/rawText, containers, bindings, and asset publication. Preserve the recently merged undo fix; this CLI task does not authorize reworking it.
|
||||
|
||||
### 6.4 Strict creation without another serializer
|
||||
|
||||
Reuse EA's Markdown/template construction. However, `create()` currently derives format from global compatibility mode, treats an empty folder as the configured default, and delegates to a creator that silently picks a unique filename. Those are good interactive conveniences but poor implicit CLI behavior. [P4], [P8]
|
||||
|
||||
Add a narrow backward-compatible per-call strict creation option, shared with the existing creator: exact vault path (including root), explicit format, fail-on-existing policy, and noninteractive template choice. Existing callers keep their defaults. Let the final Vault create fail on a race instead of choosing an unexpected suffix. Return the actual created path; never delete a concurrently created file as cleanup.
|
||||
|
||||
For V1, new CLI drawings default explicitly to modern `.excalidraw.md`; existing legacy drawings retain their format. Reject a contradictory extension/format request. Do not temporarily change plugin settings, invoke a template picker, or duplicate the serializer. Prevalidate construction before creating the file. If later asset/persistence work fails, return the created path and partial outcome instead of hiding an orphan drawing.
|
||||
|
||||
Template and back-of-note content must survive. Test the serialization of request-created text/labels and asset records, not just whether a file exists. Do not pretend an elements/appState-only read is a lossless document representation.
|
||||
|
||||
## 7. Assets, export, and advanced scripts
|
||||
|
||||
### 7.1 Preserve Obsidian asset semantics
|
||||
|
||||
Use EA for vault images, PDFs, LaTeX, Markdown images, and linked content rather than manufacturing file IDs. Excalidraw binary files and the plugin's `## Embedded Files`, equation, and Markdown-image metadata are related but not interchangeable. Runtime `updateScene` is not the binary-file loading channel; reuse the existing path that also publishes files. [P4], [P6]
|
||||
|
||||
No automatic feature activation. Preflight optional Extras operations through the typed gateway and current user settings. Missing dependencies return an actionable structured result. Core shape/text creation and ordinary SVG/PNG rendering must not require Extras. Read-only inspection should not fetch external assets unnecessarily.
|
||||
|
||||
Existing remote assets can make rendering perform network work under normal plugin rules. Declare this possibility in schema/help, preserve consent and network policy, and do not claim the CLI is a sandbox. Do not add a new outbound service, credentials, remote-code loader, or filesystem privilege to make the CLI work.
|
||||
|
||||
### 7.2 Visual feedback is part of completion
|
||||
|
||||
Use `createViewSVG/PNG` for a selected live scene and the existing file/template exporter for an explicit disk source. Do not auto-save a dirty drawing merely to render it. The result states whether it depicts live or disk content, the revision, effective theme/padding, dimensions, and missing-asset warnings. If a stable requested revision changes while assets are loading, report that conflict rather than claiming the image depicts the earlier revision. [P4]
|
||||
|
||||
Await the relevant existing asset/font readiness. Bound the wait and fail clearly when required images cannot be decoded or resolved; do not label a placeholder render as complete. Ordinary read/schema commands must not wait for all image decoding. Prefer a modest preview-size default with explicit bounded scale/dimensions for larger exports.
|
||||
|
||||
Write binary PNG with Vault APIs and SVG as UTF-8 to a caller-selected output path. Reject traversal/absolute paths and accidental overwrite of the source drawing or request file. Existing output requires explicit overwrite authorization. Return a small descriptor, not megabytes of base64 in default stdout. Inline image data is unnecessary for V1 because terminal-capable agents can inspect the saved file.
|
||||
|
||||
PDF export remains documented as dependency- and interaction-sensitive through existing EA. Do not invent a silent PDF destination contract or another print implementation just for this release.
|
||||
|
||||
### 7.3 Full EA/Lib access through one-shot trusted scripts
|
||||
|
||||
The advanced command should accept an explicit existing vault script file and JSON arguments. Reuse ScriptEngine's compilation/cache and execution path. Add a CLI-specific execution mode rather than concatenating user arguments into JavaScript. Proposed script context:
|
||||
|
||||
```ts
|
||||
// Existing script body, executed only after explicit trusted acknowledgment.
|
||||
// utils.input is parsed JSON; ea is a fresh, explicitly targeted EA.
|
||||
const options = utils.input;
|
||||
const chosen = ea.getViewSelectedElements();
|
||||
return { count: chosen.length, requestedLabel: options.label };
|
||||
```
|
||||
|
||||
Provide the already-loaded Excalidraw library through a documented CLI script utility such as `utils.excalidrawLib`, referencing the same runtime as the target view (or the initialized plugin runtime for view-free construction). This is an additional utility reference, not a second import/evaluation or new fork export. The API help must describe its actual installed exports.
|
||||
|
||||
Implement a small `executeScriptFileForCLI` facade or equivalent optional execution configuration that supplies `utils.input`, `utils.executionSource = "cli"`, and the library reference; returns the script result; and destroys the CLI-owned EA in `finally`. Existing manual, startup, and sidepanel script lifetime must remain unchanged. The current engine's finally block does not generally destroy EA because persistent hooks and sidepanels depend on it. [P9]
|
||||
|
||||
CLI one-shot scripts must not retain hooks, sidepanels, unawaited writes, or timers after completion. Default `utils.inputPrompt`/`suggester` should fail with `INTERACTION_REQUIRED` rather than leave a terminal waiting for a hidden modal. Arbitrary trusted code can still call other APIs directly; this is not a security sandbox or an enforceable side-effect whitelist. A client timeout cannot safely preempt arbitrary synchronous JavaScript or undo its prior side effects.
|
||||
|
||||
Keep execution restricted to explicit local source with a `trusted` flag; no remote script URL, implicit script found in a drawing, or code execution through `read`/`schema`. Respect the current script-file format policy. Return JSON-serializable values with size limits; convert an undefined return to a documented null result. Do not serialize live views/DOM/plugin objects. If result serialization fails after edits, report that side effects may already have occurred.
|
||||
|
||||
Structured `apply` can promise its bounded validation/publication behavior; arbitrary scripts cannot promise all-or-nothing edits, universal noninteractive behavior, or automatic persistence. Script help must explain explicit `await`/save discipline and the receipt must distinguish script completion from a verified saved drawing. Do not add an implicit “save everything touched” pass.
|
||||
|
||||
## 8. Implementation organization and integration points
|
||||
|
||||
Start with a few cohesive modules, not a framework:
|
||||
|
||||
| Proposed file / existing seam | Responsibility |
|
||||
| --- | --- |
|
||||
| `src/core/managers/ExcalidrawCLI.ts` | Plugin-owned registration, dispatcher, lifecycle cleanup, small in-flight/receipt maps. |
|
||||
| `src/core/cli/cliCommands.ts` | Action descriptors, input normalization/validation, help/schema/examples, finite command handlers. Split by concern only when justified by size. |
|
||||
| `src/core/cli/cliTarget.ts` | Exact file/view resolution and readiness/revision checks; no alternative view lifecycle. |
|
||||
| `src/types/excalidrawCliTypes.ts` | Public JSON DTOs/errors; derive element-related types from published fork types instead of copying them. |
|
||||
| `src/core/main.ts` | Own the manager and register it at a deliberate lifecycle point; minimal composition only. |
|
||||
| `src/types/types.d.ts` | Canonical compatibility declarations for the optional native CLI API while using older Obsidian types. |
|
||||
| `src/shared/ExcalidrawAutomate.ts` | Small `executeCLI` delegation and backward-compatible creation options where needed; no CLI parser embedded in EA. |
|
||||
| `src/shared/Scripts.ts` | CLI-only arguments/library utility/one-shot cleanup and result handling. |
|
||||
| `ExcalidrawView.ts`, `ViewSaveCoordinator.ts` | Narrow guarded-publication and outcome-returning seams, backed by tests; no new persistence subsystem. |
|
||||
| `FileManager.ts` | Strict per-call creation behavior shared with current serializers. |
|
||||
| `SuggesterInfo.ts`, docs generators, CLI docs/skill | Keep public API, generated declarations, discovery, and usage examples aligned. |
|
||||
|
||||
Register help/status without eagerly loading optional components. Mutating handlers require initialized plugin/runtime and a valid target. Use `plugin.awaitInit()` only with a bounded readiness policy; never deadlock startup waiting for the component the handler registration itself blocks. On unload, remove handlers through the registration lifecycle, reject/cancel prepublication work, release maps and EA instances, and prevent stale continuations from mutating a replacement plugin/view.
|
||||
|
||||
The public EA addition requires its SuggesterInfo documentation and generated/public library declarations to be updated in the same change. Add concise user release notes and maintain localized UI strings in the required languages. CLI command IDs and JSON keys stay stable/nonlocalized; descriptions may use the existing localization system.
|
||||
|
||||
### Bundle and startup budget
|
||||
|
||||
The plugin is already close to its release size ceiling. PR #2987 reports a 4,995,385-byte production bundle for its validation; this is historical PR evidence, not a fresh measurement of this branch. Measure the actual baseline locally before implementation. [P12]
|
||||
|
||||
Do not add Commander, Zod, AJV, Playwright, an MCP server, or an embedded copy of the full EA training corpus to production. Use existing runtime exports, small descriptors/guards, and build-time generation. Return API documentation progressively. Track byte delta after every checkpoint and keep `main.js` under the existing 5 MB policy. If the feature cannot fit, stop and report the measured trade-off; do not silently raise the limit, move it to Extras, or start unrelated size refactors.
|
||||
|
||||
## 9. Implementation checkpoints
|
||||
|
||||
Each checkpoint should build independently and update this note with actual evidence. The PR remains draft until the complete agreed slice and available validation are done.
|
||||
|
||||
### Checkpoint 0 — native transport and baseline
|
||||
|
||||
- Read current AGENTS/CONTRIBUTING, record plugin head, installed fork/Extras versions, and bundle bytes.
|
||||
- Prove native registration/help/unload and async return delivery on the intended desktop installers, including piped agent execution.
|
||||
- Confirm the installed runtime's converter and export helpers. Verify that no dependency on unpublished fork code has slipped in.
|
||||
- Choose ordinary awaited output; add the explicit receipt-mode fallback only if a recorded reproduction requires it.
|
||||
|
||||
**Exit:** written transport evidence and a runnable small probe, not an assumed `eval` workaround.
|
||||
|
||||
### Checkpoint 1 — discovery and read-only operations
|
||||
|
||||
- Implement the dispatcher, native descriptors, result envelope, `help/status/schema/api/list/read`.
|
||||
- Add the proposed EA facade without changing its workbench.
|
||||
- Test explicit vault/path/view selection, multiple matching views, disk versus live content, pagination, unsupported host API, and plugin reload.
|
||||
|
||||
**Exit:** an agent can discover the interface and inspect a drawing without mutating it or loading unnecessary assets.
|
||||
|
||||
### Checkpoint 2 — creation and skeleton construction
|
||||
|
||||
- Implement validated converter staging and stable returned ID mappings.
|
||||
- Add strict per-call creation with explicit root path/format/collision behavior through the existing serializer.
|
||||
- Test labels, arrows, frames, text IDs after save/reopen, templates, collision races, and no partial file on validation failure.
|
||||
|
||||
**Exit:** the example flow is a normal editable Obsidian drawing, not just a valid-looking JSON object.
|
||||
|
||||
### Checkpoint 3 — guarded edits and persistence receipts
|
||||
|
||||
- Implement finite `apply` operations, current-target/revision validation, one in-flight CLI mutation per drawing, and bounded request receipts.
|
||||
- Add only the necessary prepublication and save-outcome seams.
|
||||
- Test concurrent human edits, two agent requests, delayed text/asset preparation, save failures, and unload/migration; preserve undo and unrelated metadata.
|
||||
|
||||
**Exit:** applied versus saved versus unknown outcomes are truthful, with no silent active-file fallback or second writer.
|
||||
|
||||
### Checkpoint 4 — assets and visual feedback
|
||||
|
||||
- Add vault image/LaTeX preflight and use the current metadata paths.
|
||||
- Implement live/disk SVG/PNG export, output path/overwrite checks, asset readiness, and bounded dimensions.
|
||||
- Test default core functionality without Extras, missing optional features, existing remote assets under current permissions, and dirty-live versus disk previews.
|
||||
|
||||
**Exit:** the agent can inspect an exported image of the state it actually edited.
|
||||
|
||||
### Checkpoint 5 — advanced script coverage
|
||||
|
||||
- Add explicit trusted local script execution with JSON arguments, installed Lib reference, result serialization, and CLI-only cleanup.
|
||||
- Add tests proving manual/sidepanel script lifetime remains unchanged.
|
||||
- Document which interactions cannot run unattended and avoid promising script-level transaction isolation.
|
||||
|
||||
**Exit:** advanced EA/Lib functionality is reachable without dozens of bespoke commands or new provider integrations.
|
||||
|
||||
### Checkpoint 6 — agent discovery and release readiness
|
||||
|
||||
- Add the short portable skill, human help/copy entry, README/reference links, generated declarations, and real examples.
|
||||
- Exercise the workflow through at least two different agent harnesses/Obsidian hosts with terminal access; record tested combinations separately from expected compatibility.
|
||||
- Run build, relevant tests/lint, library generation, documented runtime lane, and final size/startup checks.
|
||||
- Replace the PR's plan-only summary with implemented behavior, actual validation, remaining limits, and source/artifact identities. Keep this research/decision record until the maintainer decides its final documentation home.
|
||||
|
||||
## 10. Validation matrix and acceptance
|
||||
|
||||
### Automated checks
|
||||
|
||||
Test parsers/dispatch with plain fixtures and mock only external boundaries where possible. Reuse the repository's test conventions; do not introduce a broad test framework just for the CLI.
|
||||
|
||||
- **Protocol:** required/unknown flags; mutually exclusive JSON inputs; invalid JSON/version; `true` string handling; numeric finiteness; bounded request/output sizes; harmful object keys; stable errors; same request ID with same/different effective payload; expired/reloaded receipts.
|
||||
- **Path safety:** exact root/nested paths, spaces/Unicode, malformed/traversal/absolute paths, source/input/output collisions, output overwrite consent, drawing classification, two files with the same basename.
|
||||
- **Selection and ownership:** two views of one file, inactive popout, missing view, explicit open readiness, file switch/API replacement across an await, same-file Markdown editing, unload and reload.
|
||||
- **Authoring:** measured text, raw/parsed links, bound labels, connectors, frame children, ordering, duplicate/dangling skeleton IDs, zero coordinates, existing IDs and version/nonce behavior on updates, deletion/binding cleanup, unrelated custom data preserved.
|
||||
- **Persistence:** rejected validation causes no published edit; stale preparation does not leave mutated metadata; accepted scene plus failed save remains recoverable; repeated request does not duplicate; later human edits are not acknowledged as saved by an earlier receipt; save/reopen round-trip.
|
||||
- **Assets/export:** binary/source metadata preserved, missing/decode-failed assets explicit, optional Extras disabled, dirty-live versus disk image, area/selection bounds, effective theme, no base64 in default reads, output file bytes and dimensions.
|
||||
- **Scripts:** input not interpolated into source; existing engine return/errors propagate; one-shot cleanup on success/failure; persistent manual scripts unchanged; modal helper refusal; nonserializable result after side effects does not claim rollback.
|
||||
- **Discovery:** descriptor/help/schema/example consistency; API search not reflection execution; skill available offline; no automatic edits to agent configuration.
|
||||
|
||||
### Native Obsidian checks
|
||||
|
||||
Use the dedicated `excalidraw-test` vault and the existing documented safety/cleanup contract. `npm run test:obsidian:runner` covers the offline host harness; `npm run verify:obsidian:plugin` tests the plugin with its installed component. Add focused native CLI scenarios rather than substituting a blank-drawing smoke for feature coverage. [P13], [P14]
|
||||
|
||||
Test macOS and Windows launchers, including `Obsidian.com` on Windows; Linux native execution and a real agent-host invocation need their own evidence. The existing large Windows `eval` temporary-file bridge is test-only and is not a production implementation strategy for these new native commands. Use argument arrays when an agent host exposes process execution, and file input for large payloads. WSL/container/remote agents require access to the actual local Obsidian executable/session; list these as conditional, not universally supported.
|
||||
|
||||
Run one complete discovery → create → read → edit → save/reopen → export → image-inspection scenario through Claudian or a direct coding CLI, and a second through Agent Client or Copilot's terminal-capable backend. A single model provider is not a compatibility test of all hosts. Permission-denied and missing-CLI outcomes must be actionable.
|
||||
|
||||
Desktop CLI support does not justify breaking mobile plugin startup or increasing `minAppVersion`. Run a mobile/no-CLI loading smoke when feasible. Actual mobile native CLI support is not promised by this design.
|
||||
|
||||
### Completion criteria
|
||||
|
||||
- Native commands are discoverable and explained without prior knowledge of plugin internals.
|
||||
- A terminal-capable agent can author and revise a linked diagram without hand-writing Excalidraw bookkeeping or editing compressed Markdown.
|
||||
- Advanced scripts can use the existing EA and installed library under explicit trust, with accurate limitations.
|
||||
- No request silently chooses the active drawing, replaces newer user edits, or reports an attempted save as durable.
|
||||
- Visual exports identify their source/revision and unresolved assets rather than silently claiming complete output.
|
||||
- The implementation stays in the plugin, uses existing lifecycle/save/asset behavior, and remains within packaging limits.
|
||||
- The PR records actual test/build/device evidence, unresolved transport/platform limits, and up to three maintainer manual checks. Nothing is merged automatically.
|
||||
|
||||
## 11. Questions that require evidence, not speculative architecture
|
||||
|
||||
There is no maintainer product decision blocking this plan. Resolve the following in the local environment and record results before broadening scope:
|
||||
|
||||
1. Does native async stdout work on the currently supported installers and actual agent transports? If not, use the small explicit receipt mode, not a new server.
|
||||
2. Which installed fork exports/types exactly match the inspected source? Use only that compatible subset; no CLI-driven fork work is currently needed.
|
||||
3. Can existing prepublication/save seams provide the required revision and durability evidence without broader refactoring? If not, narrow the structured operation rather than inventing another persistence model.
|
||||
4. Does the measured production bundle leave sufficient headroom? Report a real budget conflict before changing packaging scope.
|
||||
|
||||
## Sources
|
||||
|
||||
Repository links below are pinned to inspected revisions where source behavior matters. External documentation and integration READMEs are observations as of 2026-10-11, not compatibility guarantees for future versions.
|
||||
|
||||
[announcement]: https://x.com/excalidraw/status/2108249557519970369?s=20
|
||||
[E1]: https://github.com/excalidraw/cli/blob/55fe7f494837078781a062c4d3faf29c159ebec5/README.md
|
||||
[E2]: https://github.com/excalidraw/cli/blob/55fe7f494837078781a062c4d3faf29c159ebec5/src/cli.ts
|
||||
[E3]: https://github.com/excalidraw/cli/blob/55fe7f494837078781a062c4d3faf29c159ebec5/src/scene-content.ts
|
||||
[E4]: https://github.com/excalidraw/cli/blob/55fe7f494837078781a062c4d3faf29c159ebec5/src/render-page.ts
|
||||
[O1]: https://github.com/obsidianmd/obsidian-api/blob/9abd9605ce081383674aae1ed111c456edde0688/obsidian.d.ts
|
||||
[O2]: https://obsidian.md/help/cli
|
||||
[O3]: https://forum.obsidian.md/t/codex-cannot-get-results-from-delayed-handlers-registerd-with-registerclihandler/113184
|
||||
[A1]: https://github.com/YishenTu/claudian/blob/main/README.md
|
||||
[A2]: https://github.com/YishenTu/claudian/blob/1891ce25c2d83ba92334ab1358466ccd2a4fccf3/src/providers/claude/commands/ClaudeCommandCatalog.ts
|
||||
[A3]: https://github.com/RAIT-09/obsidian-agent-client/blob/3d069c91636588be4e65d955e670403a9ea642d8/README.md
|
||||
[A4]: https://github.com/RAIT-09/obsidian-agent-client/blob/3d069c91636588be4e65d955e670403a9ea642d8/src/acp/acp-client.ts
|
||||
[A5]: https://github.com/logancyang/obsidian-copilot/blob/cd873037c357d6a4d60a90ddb9e33705b65f6865/src/builtinSkills/obsidianSkills.ts
|
||||
[A6]: https://github.com/logancyang/obsidian-copilot/blob/cd873037c357d6a4d60a90ddb9e33705b65f6865/src/agentMode/backends/shared/obsidianCliPath.ts
|
||||
[A7]: https://agentskills.io/specification
|
||||
[P1]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/package.json
|
||||
[P2]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/AGENTS.md
|
||||
[P3]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/core/index.ts
|
||||
[P4]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/shared/ExcalidrawAutomate.ts
|
||||
[P5]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/shared/Dialogs/SuggesterInfo.ts
|
||||
[P6]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/view/ExcalidrawView.ts
|
||||
[P7]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/view/managers/ViewSaveCoordinator.ts
|
||||
[P8]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/core/managers/FileManager.ts
|
||||
[P9]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/shared/Scripts.ts
|
||||
[P10]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/constants/constants.ts
|
||||
[P11]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/src/types/excalidrawLib.d.ts
|
||||
[P12]: https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2987
|
||||
[P13]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/docs/OBSIDIAN_RUNTIME_TESTING.md
|
||||
[P14]: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/bf541ca5d460f5773a5547ba4511eba3ff0f2e5b/scripts/testing/host/processTools.mjs
|
||||
[F1]: https://github.com/zsviczian/excalidraw/blob/6ec95a327b77df2696e170cb0c9d8a84ac115121/packages/excalidraw/index.tsx
|
||||
[F2]: https://github.com/zsviczian/excalidraw/blob/6ec95a327b77df2696e170cb0c9d8a84ac115121/packages/element/src/transform.ts
|
||||
[F3]: https://github.com/zsviczian/excalidraw/blob/6ec95a327b77df2696e170cb0c9d8a84ac115121/packages/element/src/index.ts
|
||||
Generated
+329
-548
File diff suppressed because it is too large.
Load diff
+6
-2
@@ -11,6 +11,7 @@
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
|
||||
"test:obsidian:runner": "node --test scripts/testing/host/runner.test.mjs scripts/testing/host/processTools.test.mjs",
|
||||
"test:markdown-embeds": "node --test scripts/testing/markdownEmbeds.test.mjs",
|
||||
"verify:obsidian": "node scripts/testing/host/verify.mjs",
|
||||
"verify:obsidian:plugin": "node scripts/testing/host/verify.mjs --plugin-only",
|
||||
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs",
|
||||
@@ -89,7 +90,6 @@
|
||||
"postcss": "^8.5.25",
|
||||
"prettier": "^3.0.1",
|
||||
"rollup": "^4.14.0",
|
||||
"rollup-plugin-copy": "^3.5.0",
|
||||
"rollup-plugin-visualizer": "^7.0.1",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "5.9.3",
|
||||
@@ -104,7 +104,11 @@
|
||||
"fast-uri": "^3.1.4",
|
||||
"immutable": "^4.3.9",
|
||||
"js-yaml": "^4.3.0",
|
||||
"svgo": "^3.3.4"
|
||||
"svgo": "^3.3.4",
|
||||
"source-map-js": "1.2.2",
|
||||
"@zsviczian/excalidraw": {
|
||||
"sass": "1.98.0"
|
||||
}
|
||||
},
|
||||
"resolutions": {
|
||||
"strip-ansi": "^7.0.1"
|
||||
|
||||
+20
-7
@@ -4,7 +4,6 @@ import visualizer from 'rollup-plugin-visualizer';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import replace from "@rollup/plugin-replace";
|
||||
import terser from "@rollup/plugin-terser";
|
||||
import copy from "rollup-plugin-copy";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
@@ -27,6 +26,20 @@ try {
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
// These copies need only explicit files, not a glob dependency and its vulnerable braces parser.
|
||||
function copyBuildFiles(files, destination) {
|
||||
return {
|
||||
name: 'copy-build-files',
|
||||
writeBundle() {
|
||||
if (!files.length) return;
|
||||
fs.mkdirSync(destination, { recursive: true });
|
||||
for (const file of files) {
|
||||
fs.copyFileSync(file, path.join(destination, path.basename(file)));
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const DIST_FOLDER = 'dist';
|
||||
const absolutePath = path.resolve(DIST_FOLDER);
|
||||
fs.mkdirSync(absolutePath, { recursive: true });
|
||||
@@ -153,7 +166,7 @@ if (!isLib) {
|
||||
// runtime.
|
||||
//
|
||||
// The runtime is DEFLATE-compressed primarily to help keep the shipped plugin
|
||||
// below the Community Plugin scanner's 5 MB bundle-size limit. Obsidian plugins
|
||||
// below the 5 MB bundle-size target (5 * 1024 * 1024 = 5,242,880 bytes). Obsidian plugins
|
||||
// currently cannot ship these runtime packages separately, so without this
|
||||
// packaging step React/ReactDOM must contribute their normal bundled size to
|
||||
// main.js.
|
||||
@@ -343,10 +356,7 @@ const BUILD_CONFIG = {
|
||||
] : [
|
||||
postprocess([[/var React = require\('react'\);/, packageString]]),
|
||||
]),
|
||||
copy({
|
||||
targets: [{ src: 'manifest.json', dest: DIST_FOLDER }],
|
||||
verbose: true,
|
||||
}),
|
||||
copyBuildFiles(['manifest.json'], DIST_FOLDER),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -361,7 +371,10 @@ const LIB_CONFIG = {
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{ tsconfig: "tsconfig-lib.json" },
|
||||
copy({ targets: [{ src: "src/*.d.ts", dest: "lib/typings" }] })
|
||||
copyBuildFiles(
|
||||
fs.readdirSync('src').filter(name => name.endsWith('.d.ts')).map(name => path.join('src', name)),
|
||||
'lib/typings',
|
||||
)
|
||||
),
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
/** Exercise the actual protocol/dispatcher with only Obsidian boundaries replaced. */
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { transpileModule, ModuleKind, createSourceFile, ScriptTarget, SyntaxKind } from 'typescript';
|
||||
|
||||
function harness({ supported = true, desktop = true, native = true } = {}) {
|
||||
const cache = new Map(), registrations = new Map(), versionChecks = []; let nextId = 0;
|
||||
class View {}
|
||||
class File { constructor(path) { this.path = path; this.extension = path.split('.').at(-1); this.stat = { size: 1 }; } }
|
||||
const files = [new File('a.excalidraw.md'), new File('Drawings/b.excalidraw.md')];
|
||||
const plugin = {
|
||||
manifest: { id: 'obsidian-excalidraw-plugin', version: 'test' }, isReady: true,
|
||||
app: { vault: { getName: () => 'Test', getFileByPath: path => files.find(file => file.path === path), getFiles: () => files,
|
||||
read: async file => file.content ?? '{}' }, workspace: { getLeavesOfType: () => [] } },
|
||||
isExcalidrawFile: file => file.path.endsWith('.excalidraw.md'), getCLIRuntime: () => ({ convertToExcalidrawElements() {} }),
|
||||
...(native ? { registerCliHandler: (name, desc, flags, fn) => { assert.ok(desc); assert.ok(flags); registrations.set(name, fn); } } : {}),
|
||||
};
|
||||
const mocks = {
|
||||
obsidian: { Platform: { isDesktop: desktop }, TFile: File, requireApiVersion: version => { versionChecks.push(version); return supported; } },
|
||||
'src/core/main': {}, 'src/view/ExcalidrawView': { default: View }, 'src/shared/ExcalidrawData': { ExcalidrawData: class {} },
|
||||
'src/shared/TextMode': { getTextMode() {} }, 'src/constants/constants': { VIEW_TYPE_EXCALIDRAW: 'excalidraw', nanoid: () => String(++nextId).padStart(8, '0') },
|
||||
'src/lang/helpers': { t: key => key }, 'src/shared/Dialogs/SuggesterInfo': { EXCALIDRAW_AUTOMATE_INFO: [{ field: 'addText', code: 'addText(x,y,text)', desc: 'Add text' }, { field: 'addRect', code: 'addRect(x,y,width,height)', desc: null }] },
|
||||
'src/shared/EmbeddedFileLoader': {}, 'src/utils/excalidrawAutomateUtils': {}, 'src/utils/fileUtils': {},
|
||||
'src/utils/utils': {}, 'src/utils/excalidrawElementUtils': {}, 'src/utils/imageExportUtils': {},
|
||||
};
|
||||
function load(name, parent = resolve('.')) {
|
||||
if (mocks[name]) return mocks[name];
|
||||
const file = resolve(name.startsWith('src/') ? '.' : parent, name) + '.ts';
|
||||
if (cache.has(file)) return cache.get(file).exports;
|
||||
const module = { exports: {} }; cache.set(file, module);
|
||||
const compiled = transpileModule(readFileSync(file, 'utf8'), { compilerOptions: { module: ModuleKind.CommonJS, target: 9 } }).outputText;
|
||||
new Function('require', 'exports', 'module', compiled)(specifier => load(specifier, resolve(file, '..')), module.exports, module);
|
||||
return module.exports;
|
||||
}
|
||||
const protocol = load('src/core/cli/cliProtocol');
|
||||
const { ExcalidrawCLI } = load('src/core/managers/ExcalidrawCLI');
|
||||
return { manager: new ExcalidrawCLI(plugin), protocol, elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), plugin, registrations, versionChecks, files, View };
|
||||
}
|
||||
const request = (command, values = {}) => ({ apiVersion: 1, command, ...values });
|
||||
|
||||
test('registration validates minimum API, optional method and desktop without bumping the baseline', () => {
|
||||
for (const options of [{ supported: false }, { native: false }, { desktop: false }]) {
|
||||
const h = harness(options); h.manager.initialize(); assert.equal(h.registrations.size, 0);
|
||||
}
|
||||
const h = harness(); h.manager.initialize(); assert.equal(h.registrations.size, 14);
|
||||
assert.deepEqual(h.versionChecks, ['1.12.2']);
|
||||
});
|
||||
|
||||
test('plain JSON guards reject executable values, prototype keys, nonfinite values and excessive depth', () => {
|
||||
const { protocol: p } = harness();
|
||||
for (const value of [() => {}, NaN, new Date(), JSON.parse('{"__proto__":{}}'), { constructor: 'x' }, { value: undefined }]) assert.throws(() => p.jsonValue(value));
|
||||
let value = {}; for (let i = 0; i < 32; i++) value = { value };
|
||||
assert.throws(() => p.jsonValue(value));
|
||||
assert.deepEqual(p.jsonValue({ x: 0, empty: '', flag: false }), { x: 0, empty: '', flag: false });
|
||||
assert.throws(() => p.jsonValue('a'.repeat(200), 100));
|
||||
});
|
||||
|
||||
test('vault paths preserve exact root, nested, spaces and Unicode while rejecting traversal and hidden config', () => {
|
||||
const { protocol: p } = harness();
|
||||
for (const path of ['Flow.excalidraw.md', 'Folder/Árvíz Flow.excalidraw.md']) assert.equal(p.vaultPath(path), path);
|
||||
for (const path of ['/a.md', '../a.md', 'a/../b.md', './a.md', 'a//b.md', 'a\\b.md', '.obsidian/a.json', 'a\u0000.md', 'C:/a.md']) assert.throws(() => p.vaultPath(path));
|
||||
});
|
||||
|
||||
test('dispatcher returns stable failures for unknown fields, commands and versions', async () => {
|
||||
const { manager } = harness();
|
||||
assert.equal((await manager.execute(request('missing'))).error.code, 'UNSUPPORTED_COMMAND');
|
||||
assert.equal((await manager.execute({ apiVersion: 2, command: 'status' })).error.field, 'apiVersion');
|
||||
assert.equal((await manager.execute(request('status', { secret: true }))).error.field, 'secret');
|
||||
assert.equal((await manager.execute(request('read', { path: 'missing.md' }))).error.code, 'NOT_FOUND');
|
||||
});
|
||||
|
||||
test('native file/inline JSON is exclusive and values must agree with flags', async () => {
|
||||
const h = harness(); h.manager.initialize(); const run = h.registrations.get('obsidian-excalidraw-plugin:read');
|
||||
assert.equal(JSON.parse(await run({ input: 'a.excalidraw.md', json: '{}' })).error.code, 'INVALID_INPUT');
|
||||
assert.equal(JSON.parse(await run({ json: JSON.stringify({ apiVersion: 1, path: 'a.excalidraw.md' }), path: 'Drawings/b.excalidraw.md' })).error.field, 'path');
|
||||
assert.equal(JSON.parse(await run({ path: 'a.excalidraw.md', selectedOnly: 'yes' })).error.field, 'selectedOnly');
|
||||
assert.equal(JSON.parse(await run({ json: '{broken' })).ok, false);
|
||||
});
|
||||
|
||||
test('discovery remains available before readiness and never opens a drawing', async () => {
|
||||
const { manager, plugin } = harness(); plugin.isReady = false;
|
||||
for (const command of ['help', 'status', 'skill', 'api']) assert.equal((await manager.execute(request(command))).ok, true);
|
||||
assert.equal((await manager.execute(request('schema', { action: 'create' }))).data.example.apiVersion, 1);
|
||||
assert.equal((await manager.execute(request('list'))).error.code, 'NOT_READY');
|
||||
});
|
||||
|
||||
test('portable skill stays aligned with native output and schema describes finite operations', async () => {
|
||||
const h = harness();
|
||||
assert.equal((await h.manager.execute(request('skill'))).data.markdown, readFileSync('docs/AITrainingData/excalidraw-cli/SKILL.md', 'utf8'));
|
||||
assert.equal((await h.manager.execute(request('api', { name: 'addRect' }))).data.entries[0].description, '');
|
||||
const schema = (await h.manager.execute(request('schema', { action: 'apply' }))).data.jsonSchema;
|
||||
assert.ok(schema.required.includes('expectedRevision'));
|
||||
assert.deepEqual(schema.$defs.operation.oneOf.map(option => option.properties.op.const), ['add', 'update', 'delete', 'connect', 'group', 'ungroup', 'image', 'latex']);
|
||||
});
|
||||
|
||||
test('multiple views require explicit identity; disk ignores ambiguity and refuses view selection', async () => {
|
||||
const h = harness(); const a = Object.assign(new h.View(), { file: h.files[0], id: 'one' }), b = Object.assign(new h.View(), { file: h.files[0], id: 'two' });
|
||||
h.plugin.app.workspace.getLeavesOfType = () => [{ view: a }, { view: b }];
|
||||
assert.equal((await h.manager.execute(request('read', { path: a.file.path }))).error.code, 'AMBIGUOUS_TARGET');
|
||||
assert.equal((await h.manager.execute(request('read', { path: a.file.path, view: 'gone' }))).error.code, 'NOT_FOUND');
|
||||
assert.equal((await h.manager.execute(request('read', { path: a.file.path, source: 'disk', view: 'one' }))).error.field, 'view');
|
||||
});
|
||||
|
||||
test('drawing list pagination rejects stale snapshots instead of mixing pages', async () => {
|
||||
const h = harness(), first = await h.manager.execute(request('list', { limit: 1 }));
|
||||
const revision = first.data.revision; assert.equal(first.data.nextOffset, 1);
|
||||
const second = await h.manager.execute(request('list', { offset: 1, limit: 1, revision })); assert.equal(second.ok, true);
|
||||
h.files.push({ path: 'c.excalidraw.md' });
|
||||
assert.equal((await h.manager.execute(request('list', { offset: 1, revision }))).error.code, 'STALE_REVISION');
|
||||
assert.equal((await h.manager.execute(request('list', { offset: 0.5 }))).error.code, 'INVALID_INPUT');
|
||||
});
|
||||
|
||||
test('write receipts require IDs, replay identical requests and reject changed effective content', async () => {
|
||||
const { manager } = harness(); assert.equal((await manager.execute(request('create'))).error.field, 'requestId');
|
||||
const original = request('create', { requestId: 'test-1', path: 'new.excalidraw.md', elements: [] });
|
||||
const receipt = await manager.execute(original); assert.deepEqual(await manager.execute(original), receipt);
|
||||
assert.equal((await manager.execute({ ...original, path: 'other.excalidraw.md' })).error.field, 'requestId');
|
||||
assert.deepEqual(await manager.execute(request('result', { requestId: 'test-1' })), receipt);
|
||||
assert.equal((await manager.execute(request('result', { requestId: 'unknown' }))).error.code, 'OUTCOME_UNKNOWN');
|
||||
});
|
||||
|
||||
test('unload rejects new requests and invalidates old session receipts', async () => {
|
||||
const { manager } = harness(); let active = 0;
|
||||
const release = manager.registerOperationCleanup(() => active++); release();
|
||||
manager.registerOperationCleanup(() => active++); manager.destroy();
|
||||
assert.equal(active, 1);
|
||||
assert.equal((await manager.execute(request('status'))).error.code, 'NOT_READY');
|
||||
});
|
||||
|
||||
test('skeleton validation refuses persisted internals, dangling bindings and malformed frames before conversion', () => {
|
||||
const { elements: { validateBatch } } = harness();
|
||||
const box = { id: 'box', type: 'rectangle', x: 0, y: 0, width: 100, height: 80, opacity: 0 };
|
||||
assert.equal(validateBatch([box])[0].x, 0);
|
||||
for (const batch of [[{ ...box, version: 7 }], [box, box], [{ ...box, opacity: 101 }],
|
||||
[{ type: 'arrow', start: { id: 'absent' } }], [{ type: 'frame', children: ['absent'] }],
|
||||
[{ type: 'text', text: 'ok', fontSize: 0 }], [{ type: 'line', points: [[0, NaN], [20, 20]] }]]) assert.throws(() => validateBatch(batch));
|
||||
assert.equal(validateBatch([box, { type: 'arrow', start: { id: 'box' } }, { type: 'frame', children: ['box'] }]).length, 3);
|
||||
});
|
||||
|
||||
test('operation validation and export allocation limits reject unsupported requests', () => {
|
||||
const { apply: { validateOperations }, exporting: { exportBounds } } = harness();
|
||||
for (const operations of [[], [{ op: 'replaceScene' }], [{ op: 'update', id: 'a', set: { version: 3 } }],
|
||||
[{ op: 'delete', ids: ['a'], children: 'surprise' }], [{ op: 'image', asset: '../image.png' }], [{ op: 'latex', text: 'x', scaleX: 0 }]]) assert.throws(() => validateOperations(operations));
|
||||
assert.equal(validateOperations([{ op: 'update', id: 'a', set: { x: 0, opacity: 0, text: '' } }]).length, 1);
|
||||
for (const dimensions of [[0, 100, 1], [10000, 10000, 1], [100, Infinity, 1], [17000, 1, 1]]) assert.throws(() => exportBounds(...dimensions));
|
||||
assert.doesNotThrow(() => exportBounds(1000, 1000, 4));
|
||||
});
|
||||
|
||||
/** Load a production method intact; only its app boundary dependencies are supplied. */
|
||||
function productionMethod(path, className, name, dependencies = {}) {
|
||||
const source = createSourceFile(path, readFileSync(path, 'utf8'), ScriptTarget.Latest, true);
|
||||
const declaration = source.statements.find(node => node.kind === SyntaxKind.ClassDeclaration && node.name.text === className);
|
||||
const method = declaration.members.find(node => node.name?.getText(source) === name);
|
||||
assert.ok(method, `${className}.${name}`);
|
||||
const compiled = transpileModule(`export class Loaded { ${method.getText(source)} }`, { compilerOptions: { module: ModuleKind.CommonJS, target: 9 } }).outputText;
|
||||
const exports = {};
|
||||
new Function('exports', ...Object.keys(dependencies), compiled)(exports, ...Object.values(dependencies));
|
||||
return exports.Loaded.prototype[name];
|
||||
}
|
||||
|
||||
test('delayed text preparation leaves concurrent metadata and the scene intact when publication is rejected', async () => {
|
||||
let resume;
|
||||
const waiting = new Promise(resolve => { resume = resolve; });
|
||||
const original = { id: 'label123', type: 'text', text: 'before', rawText: 'before' };
|
||||
const model = { textElements: new Map([['label123', { raw: 'before' }]]), parse: async () => { await waiting; return { parsed: 'prepared', link: null }; } };
|
||||
model.addTextElement = productionMethod('src/shared/ExcalidrawData.ts', 'ExcalidrawData', 'addTextElement');
|
||||
const view = { excalidrawData: model, textMode: 'raw', excalidrawAPI: { getSceneElements: () => [original] }, updateScene: () => assert.fail('stale edit published') };
|
||||
const addElements = productionMethod('src/view/ExcalidrawView.ts', 'ExcalidrawView', 'addElements', {
|
||||
CaptureUpdateAction: { IMMEDIATELY: 'capture' }, TextMode: { parsed: 'parsed' }, arrayToMap: values => new Map(values.map(value => [value.id, value])),
|
||||
});
|
||||
const pending = addElements.call(view, { newElements: [{ ...original, text: 'prepared', rawText: 'prepared' }], validateBeforePublish: () => { throw Error('STALE_REVISION'); } });
|
||||
model.textElements.set('label123', { raw: 'human edit' });
|
||||
resume(); await assert.rejects(pending, /STALE_REVISION/);
|
||||
assert.equal(model.textElements.get('label123').raw, 'human edit');
|
||||
assert.equal(original.text, 'before');
|
||||
});
|
||||
|
||||
test('existing unguarded text callers retain completion-time metadata ownership', async () => {
|
||||
let resume;
|
||||
const waiting = new Promise(resolve => { resume = resolve; });
|
||||
const original = new Map(), replacement = new Map();
|
||||
const model = { textElements: original, parse: async () => { await waiting; return { parsed: 'display', link: null }; } };
|
||||
const addText = productionMethod('src/shared/ExcalidrawData.ts', 'ExcalidrawData', 'addTextElement');
|
||||
const pending = addText.call(model, 'text1234', 'source', 'source');
|
||||
model.textElements = replacement; resume(); await pending;
|
||||
assert.equal(original.size, 0); assert.equal(replacement.get('text1234').raw, 'source');
|
||||
});
|
||||
|
||||
test('trusted script receipt identity includes source content and never interpolates args', async () => {
|
||||
const h = harness(); const file = { path: 'Scripts/test.md', extension: 'md', content: 'return utils.input;', stat: { size: 18 } }; h.files.push(file);
|
||||
h.plugin.settings = {}; let executions = 0;
|
||||
h.plugin.ea = { getAPI: () => ({ destroy() {} }) };
|
||||
h.plugin.scriptEngine = { executeScriptFileForCLI: async (f, view, ea, input, lib, source, check) => { check(); executions++; assert.equal(source, file.content); return input; } };
|
||||
const input = request('script', { requestId: 'script-1', script: file.path, trusted: true, args: { text: '${notExecuted}' } });
|
||||
const first = await h.manager.execute(input); assert.equal(first.ok, true); assert.deepEqual(first.data, input.args); assert.equal(first.persistence, 'unknown');
|
||||
assert.deepEqual(await h.manager.execute(input), first); assert.equal(executions, 1);
|
||||
file.content = 'return 2;'; assert.equal((await h.manager.execute(input)).error.field, 'requestId'); assert.equal(executions, 1);
|
||||
assert.equal((await h.manager.execute({ ...input, requestId: 'script-2', trusted: false })).error.code, 'TRUST_REQUIRED');
|
||||
});
|
||||
|
||||
test('save outcome reports only an acknowledged captured revision through the existing queue policy', async () => {
|
||||
const save = productionMethod('src/view/managers/ViewSaveCoordinator.ts', 'ViewSaveCoordinator', 'saveWithOutcome', { DIRECT_SAVE_SIDE_EFFECT_POLICY: { triggerAutoexport: true } });
|
||||
for (const status of ['persisted', 'window-migration-persisted', 'failed', 'skipped', 'unchanged', 'persistence-handed-off', 'window-migration-handed-off']) {
|
||||
const coordinator = { currentRevision: 4, enqueueSave: async request => {
|
||||
assert.equal(request.bypassSameFileEditGuard, false); assert.equal(request.forcePersistence, true);
|
||||
return { status, preparedSave: { capturedRevision: 4 } };
|
||||
} };
|
||||
const result = await save.call(coordinator);
|
||||
assert.equal(result.requestedRevision, 4);
|
||||
assert.equal(result.acknowledgedRevision, ['persisted', 'window-migration-persisted'].includes(status) ? 4 : null);
|
||||
}
|
||||
});
|
||||
|
||||
test('CLI scripts clean up their owned EA on success/failure while manual scripts retain their lifetime', async () => {
|
||||
let destroyed = 0;
|
||||
const ea = { destroy: () => destroyed++ }, engine = { eaInstances: [], viewAutostartEAs: new Set(),
|
||||
getCompiledScript: async () => async (ea, utils) => ({ input: utils.input, executionSource: utils.executionSource }) };
|
||||
engine.executeExecutable = productionMethod('src/shared/Scripts.ts', 'ScriptEngine', 'executeExecutable', { getEA: () => ea });
|
||||
const cli = productionMethod('src/shared/Scripts.ts', 'ScriptEngine', 'executeScriptFileForCLI');
|
||||
const result = await cli.call(engine, { basename: 'test' }, undefined, ea, { x: 0 }, {}, 'source', () => {});
|
||||
assert.deepEqual(result, { input: { x: 0 }, executionSource: 'cli' }); assert.equal(destroyed, 1);
|
||||
engine.getCompiledScript = async () => async (ea, utils) => { await utils.inputPrompt('fail'); };
|
||||
await assert.rejects(cli.call(engine, { basename: 'test' }, undefined, ea, null, {}, 'source', () => {}), /INTERACTION_REQUIRED/);
|
||||
assert.equal(destroyed, 2);
|
||||
await engine.executeExecutable(undefined, async () => 'manual', 'test', {}, 'manual');
|
||||
assert.equal(destroyed, 2); assert.equal(engine.eaInstances.length, 1);
|
||||
});
|
||||
|
||||
test('CLI compilation checks exact source even when file stat matches a cached manual script', async () => {
|
||||
const getCompiled = productionMethod('src/shared/Scripts.ts', 'ScriptEngine', 'getCompiledScript');
|
||||
const file = { path: 'Script.md', stat: { mtime: 1, size: 10 }, content: 'old source' };
|
||||
const engine = { compiledScripts: new Map(), app: { vault: { read: async () => file.content } }, compileScript: source => async () => source };
|
||||
assert.equal(await (await getCompiled.call(engine, file))(), 'old source');
|
||||
file.content = 'new source'; assert.equal(await (await getCompiled.call(engine, file, 'new source'))(), 'new source');
|
||||
await assert.rejects(getCompiled.call(engine, file, 'different'), /source changed/);
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
/** Issue #2953: real Markdown embeds and deliberate detachment in a disposable vault. */
|
||||
import assert from "node:assert/strict";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
const CONTROL = "__excalidrawEmbedRecovery";
|
||||
|
||||
function setup(control, drawingPath, paths) {
|
||||
if (globalThis[control]) throw Error("embed controller already exists");
|
||||
if (paths.some(path => app.vault.getFileByPath(path))) throw Error("fixture path already exists");
|
||||
const plugin = app.plugins.plugins["obsidian-excalidraw-plugin"];
|
||||
const c = { plugin, drawingPath, paths, owned: [], state: "idle", paused: 0, hold: false,
|
||||
originalAwaitInit: plugin.awaitInit, hadOwnAwaitInit: Object.hasOwn(plugin, "awaitInit"),
|
||||
previewImageType: plugin.settings.previewImageType };
|
||||
globalThis[control] = c;
|
||||
plugin.awaitInit = async function (...args) {
|
||||
await c.originalAwaitInit.apply(this, args);
|
||||
if (c.hold) { c.paused++; await c.gate; }
|
||||
};
|
||||
return { started: true };
|
||||
}
|
||||
|
||||
function snapshot(control) {
|
||||
const c = globalThis[control];
|
||||
const root = c.leaf?.view.contentEl;
|
||||
const images = root ? Array.from(root.querySelectorAll("[fileSource]"))
|
||||
.filter(el => el.getAttribute("fileSource")?.split("#")[0] === c.drawingPath) : [];
|
||||
const decoded = el => el.tagName === "IMG" ? el.complete && el.naturalWidth > 0 : !!el.querySelector("svg");
|
||||
const visible = el => el.getBoundingClientRect().height > 0 && !el.closest(".excalidraw-display-none");
|
||||
const selfImages = root ? Array.from(root.querySelectorAll("[fileSource]"))
|
||||
.filter(el => el.getAttribute("fileSource") === `${c.paths[2]}#^as-image`) : [];
|
||||
const nativeImages = root ? Array.from(root.querySelectorAll(".internal-embed"))
|
||||
.filter(el => el.getAttribute("src") === c.paths[3]).flatMap(el => Array.from(el.querySelectorAll("img"))) : [];
|
||||
return { state: c.state, error: c.error, paused: c.paused, connected: !!root?.isConnected,
|
||||
popout: !!root && root.ownerDocument !== app.workspace.containerEl.ownerDocument,
|
||||
retiredImages: c.retiredEmbeds?.reduce((count, embed) => count + embed.querySelectorAll("[fileSource]").length, 0) ?? 0,
|
||||
mode: c.leaf?.view.getMode?.(), images: images.map(el => ({
|
||||
type: el.tagName, width: el.getAttribute("w"), ready: !!el.closest("[ready]"),
|
||||
decoded: decoded(el), visible: visible(el),
|
||||
})), selfImages: selfImages.map(el => ({ decoded: decoded(el), visible: visible(el) })),
|
||||
nativeImages: nativeImages.map(el => ({ decoded: decoded(el), visible: visible(el) })), owned: c.owned };
|
||||
}
|
||||
|
||||
async function createHybridFixtures(control) {
|
||||
const c = globalThis[control];
|
||||
const source = await app.vault.read(app.vault.getFileByPath(c.drawingPath));
|
||||
if (!source.startsWith("---") || !source.includes("# Excalidraw Data")) throw Error("hybrid embed regression requires a Markdown drawing");
|
||||
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aL1sAAAAASUVORK5CYII="), ch => ch.charCodeAt(0));
|
||||
await app.vault.createBinary(c.paths[3], png.buffer); c.owned.push(c.paths[3]);
|
||||
const embeds = `![[#^as-image]]\n\n![[${c.drawingPath}|180]]\n\n![[${c.paths[3]}|80]]\n\n`;
|
||||
const hybrid = source.replace(/^---\r?\n/, "---\nexcalidraw-open-md: true\n").replace("# Excalidraw Data", `${embeds}# Excalidraw Data`);
|
||||
await app.vault.create(c.paths[2], hybrid); c.owned.push(c.paths[2]);
|
||||
await app.vault.create(c.paths[4], `![[${c.paths[2]}#^as-image]]\n\n![[${c.paths[2]}]]`); c.owned.push(c.paths[4]);
|
||||
}
|
||||
|
||||
async function openHybrid(control, mode, nested) {
|
||||
const c = globalThis[control];
|
||||
const path = nested ? c.paths[4] : c.paths[2];
|
||||
await c.leaf.setViewState({ type: "markdown", state: { file: path, mode, source: false } });
|
||||
if (mode === "source") c.leaf.view.editor.setCursor({ line: 0, ch: 0 });
|
||||
}
|
||||
|
||||
async function createFixtures(control) {
|
||||
const c = globalThis[control];
|
||||
const view = app.workspace.getLeavesOfType("excalidraw").find(leaf => leaf.view.file?.path === c.drawingPath)?.view;
|
||||
const ea = new c.plugin.ea.constructor(c.plugin, view);
|
||||
try {
|
||||
ea.addText(0, 0, "Embed recovery #2953");
|
||||
if (!await ea.addElementsToView(false, true)) throw Error("could not populate drawing fixture");
|
||||
} finally { ea.destroy(); }
|
||||
// Collapse the long note so all three drawing widgets remain in the viewport.
|
||||
const large = "> [!info]- Asynchronously rendered note\n>\n" + Array.from({ length: 30 }, (_, i) =>
|
||||
`> Paragraph ${i}: ${"Long embedded Markdown content. ".repeat(24)}\n>\n`).join("");
|
||||
await app.vault.create(c.paths[0], large); c.owned.push(c.paths[0]);
|
||||
const note = `![[${c.paths[0]}]]\n\n` + [320, 360, 400].map(width => `![[${c.drawingPath}|${width}]]`).join("\n\n");
|
||||
await app.vault.create(c.paths[1], note); c.owned.push(c.paths[1]);
|
||||
c.leaf = app.workspace.getLeaf("tab");
|
||||
}
|
||||
|
||||
async function openNote(control, mode, imageType, hold) {
|
||||
const c = globalThis[control];
|
||||
c.plugin.settings.previewImageType = imageType;
|
||||
c.paused = 0; c.hold = hold;
|
||||
c.gate = new Promise(resolve => { c.release = resolve; });
|
||||
await c.leaf.openFile(app.vault.getFileByPath(c.paths[1]), { state: { mode, source: false } });
|
||||
if (mode === "source") {
|
||||
const editor = c.leaf.view.editor;
|
||||
editor.setCursor({ line: editor.lastLine(), ch: 0 });
|
||||
editor.scrollIntoView({ from: { line: editor.lastLine(), ch: 0 }, to: { line: editor.lastLine(), ch: 0 } }, true);
|
||||
}
|
||||
}
|
||||
|
||||
function detach(control) {
|
||||
const c = globalThis[control];
|
||||
c.root = c.leaf.view.contentEl; c.parent = c.root.parentElement; c.next = c.root.nextSibling;
|
||||
c.root.remove();
|
||||
return { detached: !c.root.isConnected };
|
||||
}
|
||||
|
||||
function reattach(control) {
|
||||
const c = globalThis[control];
|
||||
c.parent.insertBefore(c.root, c.next?.parentElement === c.parent ? c.next : null);
|
||||
c.root = null; c.parent = null; c.next = null;
|
||||
return { reattached: true };
|
||||
}
|
||||
|
||||
async function closeNote(control) {
|
||||
const c = globalThis[control];
|
||||
c.retiredEmbeds = Array.from(c.leaf.view.contentEl.querySelectorAll(".internal-embed"));
|
||||
await c.leaf.setViewState({ type: "empty", state: {} });
|
||||
}
|
||||
|
||||
function openPopout(control) {
|
||||
const c = globalThis[control];
|
||||
c.leaf.detach();
|
||||
c.leaf = app.workspace.openPopoutLeaf();
|
||||
return { started: true };
|
||||
}
|
||||
|
||||
function resize(control) {
|
||||
const c = globalThis[control];
|
||||
const embed = c.leaf.view.contentEl.querySelector(".internal-embed[ready]");
|
||||
if (!embed) throw Error("ready embed missing");
|
||||
embed.setAttribute("width", "280");
|
||||
return { changed: true };
|
||||
}
|
||||
|
||||
async function cleanup(control, expectedPaths) {
|
||||
const c = globalThis[control];
|
||||
if (!c) return;
|
||||
c.hold = false; c.release?.();
|
||||
if (c.hadOwnAwaitInit) c.plugin.awaitInit = c.originalAwaitInit;
|
||||
else delete c.plugin.awaitInit;
|
||||
c.plugin.settings.previewImageType = c.previewImageType;
|
||||
if (c.root && c.parent) c.parent.insertBefore(c.root, c.next?.parentElement === c.parent ? c.next : null);
|
||||
if (c.leaf) { await c.leaf.setViewState({ type: "empty", state: {} }); c.leaf.detach(); }
|
||||
for (const path of c.owned) {
|
||||
if (!expectedPaths.includes(path)) throw Error("refusing to delete an unowned fixture");
|
||||
const file = app.vault.getFileByPath(path);
|
||||
if (file) await app.vault.delete(file);
|
||||
}
|
||||
c.state = "clean";
|
||||
}
|
||||
|
||||
export async function runEmbedRecoveryScenario({ cli, drawingPath }) {
|
||||
const paths = ["large.md", "note.md", "hybrid.excalidraw.md", "pixel.png", "nested.md"]
|
||||
.map(kind => `__excalidraw_embed_${randomUUID()}_${kind}`);
|
||||
// Test-only CLI boundary: fn is always a function defined in this module, and
|
||||
// arguments are JSON literals in JavaScript source, never HTML/script markup.
|
||||
// JSON.stringify preserves quotes/backslashes; </script> cannot end this eval.
|
||||
const evaluate = code => JSON.parse(cli("eval", `code=${code}`).trim().replace(/^=>\s*/, ""));
|
||||
const invoke = (fn, ...args) => evaluate(`JSON.stringify((${fn.toString()})(${[CONTROL, ...args].map(value => JSON.stringify(value)).join(",")}))`);
|
||||
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const read = () => invoke(snapshot);
|
||||
async function poll(predicate, label) {
|
||||
const deadline = Date.now() + 20_000;
|
||||
for (;;) {
|
||||
const value = read();
|
||||
if (value.error) throw Error(value.error);
|
||||
if (predicate(value)) return value;
|
||||
if (Date.now() >= deadline) throw Error(`${label}: ${JSON.stringify(value)}`);
|
||||
await wait(100);
|
||||
}
|
||||
}
|
||||
async function act(fn, ...args) {
|
||||
evaluate(`(()=>{const c=globalThis.${CONTROL};c.state="pending";c.error=null;Promise.resolve((${fn.toString()})(${[CONTROL, ...args].map(value => JSON.stringify(value)).join(",")})).then(()=>c.state="done").catch(e=>{c.error=String(e);c.state="failed"});return JSON.stringify({started:true})})()`);
|
||||
await poll(value => value.state === "done", fn.name);
|
||||
}
|
||||
const checks = [];
|
||||
invoke(setup, drawingPath, paths);
|
||||
try {
|
||||
await act(createFixtures);
|
||||
for (const imageType of ["SVGIMG", "PNG", "SVG"]) {
|
||||
await act(openNote, "source", imageType, true);
|
||||
await poll(value => value.paused > 0, "embed did not enter image generation");
|
||||
assert.equal(invoke(detach).detached, true);
|
||||
// Longer than the loader's cancellation interval, while the context remains live.
|
||||
await wait(650);
|
||||
evaluate(`(()=>{const c=globalThis.${CONTROL};c.hold=false;c.release();return JSON.stringify({released:true})})()`);
|
||||
await poll(value => value.images.length === 3 && value.images.every(image => image.ready), "detached live context did not complete");
|
||||
invoke(reattach);
|
||||
const ready = await poll(value => value.images.length === 3 && value.images.every(image => image.ready && image.decoded), "reattached images did not decode");
|
||||
assert.equal(ready.connected, true); checks.push(`${imageType}: detached Live Preview context completes and reattaches`);
|
||||
invoke(resize);
|
||||
await poll(value => value.images.length === 3 && value.images.some(image => image.width === "280" && image.ready && image.decoded), "attribute refresh did not finish");
|
||||
checks.push(`${imageType}: width attribute refresh preserves all three embeds`);
|
||||
await act(closeNote);
|
||||
await act(openNote, "preview", imageType, false);
|
||||
await poll(value => value.images.length === 3 && value.images.every(image => image.decoded), "Reading mode images missing");
|
||||
checks.push(`${imageType}: Reading mode after Live Preview`);
|
||||
await act(closeNote);
|
||||
await act(openNote, "source", imageType, false);
|
||||
await poll(value => value.images.length === 3 && value.images.every(image => image.decoded), "warm reopen images missing");
|
||||
checks.push(`${imageType}: warm Live Preview reopen`);
|
||||
await act(closeNote);
|
||||
}
|
||||
await act(openNote, "source", "SVGIMG", true);
|
||||
await poll(value => value.paused > 0, "unload fixture did not start");
|
||||
await act(closeNote);
|
||||
evaluate(`(()=>{const c=globalThis.${CONTROL};c.hold=false;c.release();return JSON.stringify({released:true})})()`);
|
||||
await wait(650);
|
||||
assert.equal(read().images.length, 0); assert.equal(read().retiredImages, 0);
|
||||
checks.push("permanent context unload rejects insertion into the retired embed containers");
|
||||
invoke(openPopout);
|
||||
await act(openNote, "source", "SVGIMG", true);
|
||||
await poll(value => value.paused > 0 && value.popout, "popout embeds did not start");
|
||||
invoke(detach); await wait(650);
|
||||
evaluate(`(()=>{const c=globalThis.${CONTROL};c.hold=false;c.release();return JSON.stringify({released:true})})()`);
|
||||
await poll(value => value.images.length === 3 && value.images.every(image => image.ready), "detached popout context did not complete");
|
||||
invoke(reattach);
|
||||
await poll(value => value.connected && value.popout && value.images.every(image => image.decoded), "popout images did not decode");
|
||||
invoke(resize);
|
||||
await poll(value => value.images.some(image => image.width === "280" && image.ready && image.decoded), "popout attribute refresh did not finish");
|
||||
checks.push("popout: detached context, reattachment and width refresh in the owning document");
|
||||
await act(closeNote);
|
||||
await act(createHybridFixtures);
|
||||
for (const mode of ["source", "preview"]) {
|
||||
for (const nested of [false, true]) {
|
||||
await act(openHybrid, mode, nested);
|
||||
await poll(value => value.selfImages.length === (nested ? 2 : 1) &&
|
||||
value.selfImages.every(image => image.decoded && image.visible) &&
|
||||
value.images.length === 1 && value.images.every(image => image.decoded && image.visible) &&
|
||||
value.nativeImages.filter(image => image.visible).length === 1 &&
|
||||
value.nativeImages.filter(image => image.visible).every(image => image.decoded),
|
||||
`hybrid ${mode}, nested=${nested}: self-image, nested drawing or PNG missing`);
|
||||
checks.push(`hybrid ${mode}, nested=${nested}: self-image, drawing and native PNG visible in popout`);
|
||||
await act(closeNote);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await act(cleanup, paths);
|
||||
evaluate(`(()=>{delete globalThis.${CONTROL};return JSON.stringify({clean:true})})()`);
|
||||
}
|
||||
return { id: "markdown-embed-recovery-2953", status: "passed", assertions: checks, cleanup: "passed" };
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/** Run only against the guarded runner's disposable drawing. */
|
||||
async function exerciseGroupedLinkClicks(view, link, modifier) {
|
||||
const api = view.excalidrawAPI;
|
||||
const ownerWindow = view.ownerWindow;
|
||||
const originalLinkClick = view.linkClick;
|
||||
const originalHook = view.handleLinkHookCall;
|
||||
const originalAllow = view.plugin.settings.allowCtrlClick;
|
||||
const calls = [];
|
||||
const navigation = [];
|
||||
const assertions = [];
|
||||
const next = () => new Promise(resolve => ownerWindow.setTimeout(resolve, 100));
|
||||
const check = (ok, label) => {
|
||||
if (!ok) throw Error(`${label}: ${JSON.stringify({ calls, navigation, selected: api.getAppState().selectedElementIds })}`);
|
||||
assertions.push(label);
|
||||
};
|
||||
const rectangle = (id, x, extra = {}) => ({
|
||||
type: 'rectangle', id, x, y: 100, width: 150, height: 100,
|
||||
backgroundColor: '#ffffff', fillStyle: 'solid', ...extra,
|
||||
});
|
||||
const fixture = () => [
|
||||
rectangle('linked', 100, { groupIds: ['inner', 'outer'], link }),
|
||||
rectangle('plain', 300, { groupIds: ['inner', 'outer'] }),
|
||||
rectangle('other-link', 500, { groupIds: ['inner', 'outer'], link }),
|
||||
];
|
||||
const set = async (elements, appState = {}) => {
|
||||
api.updateScene({
|
||||
elements: view.packages.excalidrawLib.restoreElements(elements, null),
|
||||
appState: {
|
||||
viewModeEnabled: false, scrollX: 0, scrollY: 0, zoom: { value: 1 },
|
||||
selectedElementIds: {}, selectedGroupIds: {}, editingGroupId: null,
|
||||
contextMenu: null, ...appState,
|
||||
},
|
||||
captureUpdate: 'NEVER', forceFlushSync: true,
|
||||
});
|
||||
api.setActiveTool({ type: 'selection' });
|
||||
await next();
|
||||
calls.length = 0;
|
||||
navigation.length = 0;
|
||||
};
|
||||
const click = async (x, extra = {}) => {
|
||||
const state = api.getAppState();
|
||||
for (const type of ['pointerdown', 'pointerup']) {
|
||||
view.containerEl.querySelector('canvas.interactive').dispatchEvent(
|
||||
new ownerWindow.PointerEvent(type, {
|
||||
bubbles: true, cancelable: true, pointerId: 1, pointerType: 'mouse',
|
||||
button: 0, buttons: type === 'pointerup' ? 0 : 1,
|
||||
clientX: (x + state.scrollX) * state.zoom.value + state.offsetLeft,
|
||||
clientY: (150 + state.scrollY) * state.zoom.value + state.offsetTop,
|
||||
...modifier, ...extra,
|
||||
}),
|
||||
);
|
||||
await next();
|
||||
}
|
||||
};
|
||||
// Observe the real resolver, then intercept its final navigation hook so the
|
||||
// test cannot leave its owned drawing or open a native/external destination.
|
||||
view.linkClick = (...args) => {
|
||||
calls.push({ text: args[1]?.id, image: args[2]?.id, link: args[3]?.id });
|
||||
return originalLinkClick.apply(view, args);
|
||||
};
|
||||
view.handleLinkHookCall = (element, linkText, event) => {
|
||||
navigation.push({ id: element?.id, linkText, shift: event?.shiftKey, alt: event?.altKey });
|
||||
return true;
|
||||
};
|
||||
view.plugin.settings.allowCtrlClick = true;
|
||||
try {
|
||||
await set(fixture());
|
||||
await click(360);
|
||||
check(calls.length === 0 && api.getAppState().selectedElementIds.plain,
|
||||
'unlinked first click selects without navigation');
|
||||
await click(360);
|
||||
check(calls.length === 0, 'unlinked second click never inherits sibling link');
|
||||
|
||||
await set(fixture(), {
|
||||
selectedElementIds: { linked: true, plain: true, 'other-link': true },
|
||||
selectedGroupIds: { outer: true },
|
||||
});
|
||||
await click(160);
|
||||
check(calls.length === 0 && Object.keys(api.getAppState().selectedElementIds).join(',') === 'linked',
|
||||
'linked first click drills into selected group');
|
||||
await click(160);
|
||||
check(navigation.length === 1 && navigation[0].id === 'linked',
|
||||
'linked second click navigates exact member');
|
||||
calls.length = 0;
|
||||
navigation.length = 0;
|
||||
await click(560);
|
||||
check(calls.length === 0 && api.getAppState().selectedElementIds['other-link'],
|
||||
'switching grouped member selects without navigation');
|
||||
await click(560, { shiftKey: true });
|
||||
check(navigation.length === 1 && navigation[0].id === 'other-link' && navigation[0].shift,
|
||||
'second click preserves Shift navigation modifier');
|
||||
|
||||
await set(fixture());
|
||||
await click(160);
|
||||
check(calls.length === 0, 'unselected linked group member gets selection first');
|
||||
await click(160, { altKey: true });
|
||||
check(navigation.length === 1 && navigation[0].id === 'linked' && navigation[0].alt,
|
||||
'selected grouped member preserves Alt navigation modifier');
|
||||
calls.length = 0;
|
||||
navigation.length = 0;
|
||||
await click(360, { altKey: true });
|
||||
check(calls.length === 0, 'Alt click on different unlinked member cannot navigate stale selection');
|
||||
|
||||
await set([rectangle('ungrouped', 100, { link })]);
|
||||
await click(160);
|
||||
check(navigation.length === 1 && navigation[0].id === 'ungrouped',
|
||||
'ungrouped link still navigates on first modifier click');
|
||||
|
||||
await set([
|
||||
rectangle('container', 100, { groupIds: ['group'], boundElements: [{ type: 'text', id: 'label' }] }),
|
||||
{ type: 'text', id: 'label', x: 130, y: 125, width: 70, height: 30,
|
||||
text: 'label', originalText: 'label', rawText: 'label', containerId: 'container',
|
||||
groupIds: ['group'], link },
|
||||
rectangle('plain', 300, { groupIds: ['group'] }),
|
||||
]);
|
||||
await click(120);
|
||||
check(calls.length === 0, 'grouped bound label gets selection first');
|
||||
await click(120);
|
||||
check(navigation.length === 1 && navigation[0].id === 'label',
|
||||
'second click follows bound label link');
|
||||
return assertions;
|
||||
} finally {
|
||||
view.linkClick = originalLinkClick;
|
||||
view.handleLinkHookCall = originalHook;
|
||||
view.plugin.settings.allowCtrlClick = originalAllow;
|
||||
}
|
||||
}
|
||||
|
||||
/** Synthetic input through the mounted editor; the parent owns deployment and cleanup. */
|
||||
export async function runGroupedLinkClickScenario({ cli, drawingPath }) {
|
||||
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
|
||||
const controller = '__excalidrawGroupedLinkClick';
|
||||
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(drawingPath)})?.view`;
|
||||
const modifier = process.platform === 'darwin' ? { metaKey: true } : { ctrlKey: true };
|
||||
evaluate(`(()=>{if(globalThis.${controller})throw Error('Controller already present');const c={state:'pending'};globalThis.${controller}=c;(${exerciseGroupedLinkClicks.toString()})(${viewCode},${JSON.stringify(`[[${drawingPath}]]`)},${JSON.stringify(modifier)}).then(assertions=>{c.assertions=assertions;c.state='passed'},error=>{c.error=String(error.stack||error);c.state='failed'});return JSON.stringify({started:true})})()`);
|
||||
try {
|
||||
for (let i = 0; i < 120; i++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
const state = evaluate(`JSON.stringify(globalThis.${controller})`);
|
||||
if (state.state === 'failed') throw Error(state.error);
|
||||
if (state.state === 'passed') return {
|
||||
id: 'grouped-link-click', status: 'passed',
|
||||
input: 'owner-window synthetic pointer events', assertions: state.assertions,
|
||||
};
|
||||
}
|
||||
throw Error('Grouped link click scenario timed out');
|
||||
} finally {
|
||||
evaluate(`(()=>{delete globalThis.${controller};return JSON.stringify({clean:true})})()`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/** #2970: real CodeMirror input in a main window and an owned Electron popout. */
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const CONTROL = "__excalidrawLatexInput";
|
||||
|
||||
async function setup(control, drawingPath, realRenderer) {
|
||||
if (globalThis[control]) throw Error("LaTeX controller already exists");
|
||||
const plugin = app.plugins.plugins["obsidian-excalidraw-plugin"];
|
||||
const leaf = app.workspace.getLeavesOfType("excalidraw").find(l => l.view.file?.path === drawingPath);
|
||||
if (!leaf?.view.excalidrawAPI) throw Error("owned drawing missing");
|
||||
if (document.querySelector(".excalidraw-LatexPrompt .cm-editor")) throw Error("close the existing LaTeX dialog first");
|
||||
const gateway = plugin.extrasGateway;
|
||||
const c = { plugin, leaf, current: leaf, previous: app.workspace.activeLeaf,
|
||||
original: gateway.getMathJax, hadOwn: Object.hasOwn(gateway, "getMathJax"), realRenderer, state: "pending" };
|
||||
globalThis[control] = c;
|
||||
if (realRenderer) {
|
||||
const extras = app.plugins.plugins["excalidraw-extras"];
|
||||
if (!extras?.settings.enableMathJaxToSVG) throw Error("Enable Extras MathJax-to-SVG in excalidraw-test before --latex-preview");
|
||||
if (!app.plugins.plugins["obsidian-latex-suite"]?.settings.mathPreviewEnabled) throw Error("Enable Latex Suite math previews in excalidraw-test before --latex-preview");
|
||||
}
|
||||
// Exercise the actual prompt and formula persistence without installing Extras,
|
||||
// requesting activation, or claiming to test MathJax's rendering engine.
|
||||
if (!realRenderer) gateway.getMathJax = async () => ({ tex2dataURL: async tex => {
|
||||
const safe = tex.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="30"><text x="0" y="20">${safe}</text></svg>`;
|
||||
const bytes = new TextEncoder().encode(tex);
|
||||
const digest = await crypto.subtle.digest("SHA-1", bytes);
|
||||
return { mimeType: "image/svg+xml", fileId: Array.from(new Uint8Array(digest), n => n.toString(16).padStart(2, "0")).join(""),
|
||||
dataURL: "data:image/svg+xml;base64," + btoa(svg), created: Date.now(), size: { width: 120, height: 30 } };
|
||||
} });
|
||||
const ea = new plugin.ea.constructor(plugin, leaf.view);
|
||||
try {
|
||||
c.elementId = await ea.addLaTex(0, 0, "abcdef");
|
||||
if (!c.elementId || !await ea.addElementsToView(false, true)) throw Error("could not create formula fixture");
|
||||
} finally { ea.destroy(); }
|
||||
}
|
||||
|
||||
function editor(control) {
|
||||
const c = globalThis[control];
|
||||
const doc = c.current.view.ownerDocument ?? c.current.view.containerEl.ownerDocument;
|
||||
const content = doc.querySelector(".excalidraw-LatexPrompt .cm-content");
|
||||
// Obsidian supplies CodeMirror externally. Its current release uses cmTile;
|
||||
// older supported releases expose cmView. This introspection is test-only.
|
||||
return { c, doc, content, view: content?.cmTile?.view ?? content?.cmView?.rootView?.view };
|
||||
}
|
||||
|
||||
function snapshot(control) {
|
||||
const { c, doc, content, view } = editor(control);
|
||||
const selection = doc.getSelection();
|
||||
const e = c.current.view.getViewElements?.().find(e => e.id === c.elementId);
|
||||
const tooltip = content?.closest(".cm-editor").querySelector(".cm-tooltip-cursor");
|
||||
const rect = tooltip?.getBoundingClientRect();
|
||||
return { state: c.state, error: c.error, modal: !!content, rootMatches: view?.root === doc,
|
||||
focused: view?.hasFocus, text: view?.state.doc.toString(), anchor: view?.state.selection.main.anchor,
|
||||
head: view?.state.selection.main.head, nativeHead: selection?.focusOffset,
|
||||
nativeInEditor: !!content && content.contains(selection?.focusNode), destroyed: c.retired?.destroyed,
|
||||
popout: doc !== app.workspace.containerEl.ownerDocument,
|
||||
formula: e && c.current.view.excalidrawData.getEquation(e.fileId)?.latex,
|
||||
dirty: c.current.view.isDirty?.(), tool: c.current.view.excalidrawAPI?.getAppState().activeTool.type,
|
||||
preview: { exists: !!tooltip, visible: !!rect && rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.bottom <= doc.defaultView.innerHeight,
|
||||
rendered: !!tooltip?.querySelector("mjx-container, math, .katex"),
|
||||
error: tooltip?.querySelector(".temml-error, .katex-error, mjx-merror, merror")?.textContent } };
|
||||
}
|
||||
|
||||
async function open(control) {
|
||||
const c = globalThis[control];
|
||||
app.workspace.setActiveLeaf(c.current, { focus: true });
|
||||
await c.current.view.openLaTeXEditor(c.elementId);
|
||||
}
|
||||
|
||||
function cancel(control) {
|
||||
const { c, content, view } = editor(control);
|
||||
c.retired = view;
|
||||
content?.closest(".excalidraw-LatexPrompt").querySelector("button:not(.mod-cta)")?.click();
|
||||
return { closed: true };
|
||||
}
|
||||
|
||||
async function popout(control, migrate) {
|
||||
const c = globalThis[control];
|
||||
if (migrate) {
|
||||
app.workspace.moveLeafToPopout(c.leaf);
|
||||
c.pop = c.leaf;
|
||||
} else {
|
||||
c.pop = app.workspace.openPopoutLeaf();
|
||||
await c.pop.setViewState({ type: "excalidraw", state: { file: c.leaf.view.file.path } });
|
||||
}
|
||||
c.current = c.pop;
|
||||
}
|
||||
|
||||
async function saveAndReopen(control) {
|
||||
const c = globalThis[control];
|
||||
const path = c.current.view.file.path;
|
||||
await c.current.view.forceSave(true, true);
|
||||
if (c.current.view.isDirty()) throw Error("formula remained dirty after save");
|
||||
await c.current.setViewState({ type: "empty", state: {} });
|
||||
await c.current.setViewState({ type: "excalidraw", state: { file: path } });
|
||||
}
|
||||
|
||||
async function cleanup(control) {
|
||||
const c = globalThis[control];
|
||||
if (!c) return;
|
||||
const gateway = c.plugin.extrasGateway;
|
||||
if (!c.realRenderer) {
|
||||
if (c.hadOwn) gateway.getMathJax = c.original;
|
||||
else delete gateway.getMathJax;
|
||||
}
|
||||
cancel(control);
|
||||
if (c.pop) { await c.pop.setViewState({ type: "empty", state: {} }); c.pop.detach(); }
|
||||
if (c.previous && c.previous !== c.pop) app.workspace.setActiveLeaf(c.previous, { focus: true });
|
||||
delete globalThis[control];
|
||||
}
|
||||
|
||||
/** The guarded runner owns deployment/drawing cleanup; this scenario owns dialogs,
|
||||
* temporary gateway replacement, popouts, CDP sessions and controller cleanup.
|
||||
* All evaluated functions are trusted local source; arguments use JSON literals.
|
||||
* CLI eval accepts raw JavaScript, not HTML, so HTML script escaping is inapplicable.
|
||||
*/
|
||||
export async function runLatexInputScenario({ cli, drawingPath, realRenderer = false }) {
|
||||
const evaluate = code => JSON.parse(cli("eval", `code=${code}`).trim().replace(/^=>\s*/, ""));
|
||||
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
// Browser functions referencing these helpers need their local definitions.
|
||||
const definitions = `${editor.toString()};${cancel.toString()};`;
|
||||
const invoke = (fn, ...args) => evaluate(`(()=>{${definitions}return JSON.stringify((${fn.toString()})(${[CONTROL, ...args].map(v => JSON.stringify(v)).join(",")}))})()`);
|
||||
const current = () => invoke(snapshot);
|
||||
async function poll(test, label) {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const value = current();
|
||||
if (value.error) throw Error(value.error);
|
||||
if (test(value)) return value;
|
||||
await wait(100);
|
||||
}
|
||||
throw Error(`${label}: ${JSON.stringify(current())}`);
|
||||
}
|
||||
async function act(fn, ...args) {
|
||||
evaluate(`(()=>{${definitions}const c=globalThis.${CONTROL};c.state="pending";c.error=null;Promise.resolve((${fn.toString()})(${[CONTROL, ...args].map(v => JSON.stringify(v)).join(",")})).then(()=>c.state="done").catch(e=>{c.error=e.stack||String(e);c.state="failed"});return JSON.stringify({started:true})})()`);
|
||||
await poll(v => v.state === "done", fn.name);
|
||||
}
|
||||
const cdp = (method, params = {}) => JSON.parse(cli("dev:cdp", `method=${method}`, `params=${JSON.stringify(params)}`));
|
||||
let session, request = 0;
|
||||
const input = (method, params) => session ? cdp("Target.sendMessageToTarget", {
|
||||
sessionId: session, message: JSON.stringify({ id: ++request, method, params }),
|
||||
}) : cdp(method, params);
|
||||
const modifier = process.platform === "darwin" ? 4 : 2;
|
||||
function key(key, code, keyCode, modifiers = 0) {
|
||||
for (const type of ["keyDown", "keyUp"]) input("Input.dispatchKeyEvent", { type, key, code, windowsVirtualKeyCode: keyCode, modifiers });
|
||||
}
|
||||
const cases = [];
|
||||
invoke(control => {
|
||||
if (globalThis[control]) throw Error("LaTeX controller already exists");
|
||||
if (document.querySelector(".excalidraw-LatexPrompt .cm-editor")) throw Error("close the existing LaTeX dialog first");
|
||||
return { ready: true };
|
||||
});
|
||||
try {
|
||||
// setup must install its controller before starting async fixture work.
|
||||
evaluate(`(()=>{Promise.resolve((${setup.toString()})(${JSON.stringify(CONTROL)},${JSON.stringify(drawingPath)},${JSON.stringify(realRenderer)})).then(()=>globalThis.${CONTROL}.state="done").catch(e=>{const c=globalThis.${CONTROL};if(c){c.error=e.stack;c.state="failed"}else throw e});return JSON.stringify({started:true})})()`);
|
||||
await poll(v => v.state === "done", "setup");
|
||||
for (const mode of ["main", "direct-popout", "moved-popout"]) {
|
||||
if (mode !== "main") {
|
||||
const before = new Set(cdp("Target.getTargets").targetInfos.map(t => t.targetId));
|
||||
await act(popout, mode === "moved-popout");
|
||||
await poll(v => v.popout && v.formula, "popout ready");
|
||||
const candidates = cdp("Target.getTargets").targetInfos.filter(t => t.type === "page" && !before.has(t.targetId));
|
||||
assert.equal(candidates.length, 1, "exactly one owned popout target");
|
||||
session = cdp("Target.attachToTarget", { targetId: candidates[0].targetId, flatten: false }).sessionId;
|
||||
}
|
||||
await act(open);
|
||||
const opened = await poll(v => v.modal, "editor opened");
|
||||
assert.ok(opened.rootMatches, `${mode}: CodeMirror root belongs to mounted document`);
|
||||
assert.equal(opened.text, "abcdef", `${mode}: source after reopen`);
|
||||
key("a", "KeyA", 65, modifier);
|
||||
input("Input.insertText", { text: "abcdef" });
|
||||
await poll(v => v.text === "abcdef" && v.head === 6, "text entry");
|
||||
key("ArrowLeft", "ArrowLeft", 37);
|
||||
await poll(v => v.head === 5 && v.nativeInEditor && v.nativeHead === 5, "arrow/native caret");
|
||||
if (realRenderer) {
|
||||
const { preview } = await poll(v => v.preview.exists, "Latex Suite preview");
|
||||
assert.ok(preview.visible, `${mode}: Latex Suite preview is inside its owning window`);
|
||||
assert.ok(!preview.error, `${mode}: Latex Suite preview renderer error: ${preview.error}. Obsidian 1.14.0 Temml rejects Latex Suite's \\class markers; update Obsidian to 1.14.1 or newer, or clear Latex Suite Cursor symbol and disable bracket highlighting.`);
|
||||
assert.ok(preview.rendered, `${mode}: preview contains rendered math`);
|
||||
}
|
||||
key("Backspace", "Backspace", 8);
|
||||
await poll(v => v.text === "abcdf" && v.head === 4, "backspace");
|
||||
key("z", "KeyZ", 90, modifier);
|
||||
await poll(v => v.text === "abcdef", "undo");
|
||||
// Place the cursor using the editor's actual layout and native mouse input.
|
||||
const point = invoke(control => {
|
||||
const { view } = editor(control);
|
||||
const rect = view.coordsAtPos(2);
|
||||
return { x: rect.left, y: (rect.top + rect.bottom) / 2 };
|
||||
});
|
||||
for (const type of ["mousePressed", "mouseReleased"]) input("Input.dispatchMouseEvent", { type, ...point, button: "left", clickCount: 1 });
|
||||
await poll(v => v.head === 2 && v.nativeHead === 2, "click placement");
|
||||
key("ArrowRight", "ArrowRight", 39, 8);
|
||||
await poll(v => v.anchor === 2 && v.head === 3, "shift selection");
|
||||
input("Input.insertText", { text: "X" });
|
||||
await poll(v => v.text === "abXdef", "selection replacement");
|
||||
assert.equal(current().tool, opened.tool, `${mode}: typing does not activate canvas tools`);
|
||||
key("Enter", "Enter", 13, modifier);
|
||||
await poll(v => !v.modal && v.formula === "abXdef", "Mod-Enter submission");
|
||||
await act(saveAndReopen);
|
||||
await poll(v => v.formula === "abXdef", "saved source");
|
||||
await act(open);
|
||||
await poll(v => v.modal && v.text === "abXdef", "reopen submitted source");
|
||||
key("a", "KeyA", 65, modifier);
|
||||
input("Input.insertText", { text: "cancelled" });
|
||||
await poll(v => v.text === "cancelled", "cancelled edit");
|
||||
invoke(cancel);
|
||||
await poll(v => !v.modal && v.destroyed && v.formula === "abXdef", "cancel and editor destruction");
|
||||
// Restore fixture text for the next independent window case.
|
||||
await act(open);
|
||||
await poll(v => v.modal, "restore editor");
|
||||
key("a", "KeyA", 65, modifier); input("Input.insertText", { text: "abcdef" });
|
||||
await poll(v => v.text === "abcdef", "restore text");
|
||||
key("Enter", "Enter", 13, modifier);
|
||||
await poll(v => !v.modal && v.formula === "abcdef", "restore source");
|
||||
await act(saveAndReopen);
|
||||
await poll(v => v.formula === "abcdef", "restore saved source");
|
||||
cases.push(mode);
|
||||
if (session) {
|
||||
cdp("Target.detachFromTarget", { sessionId: session }); session = undefined;
|
||||
await act(async control => { const c = globalThis[control]; await c.pop.setViewState({ type: "empty", state: {} }); c.pop.detach(); c.pop = null; c.current = c.leaf; });
|
||||
}
|
||||
}
|
||||
return { id: realRenderer ? "latex-preview-2970" : "latex-input-2970", status: "passed", cases,
|
||||
renderer: realRenderer ? "real Extras MathJax and Latex Suite preview" : "local SVG stub; MathJax/Extras not tested",
|
||||
assertions: ["mounted CodeMirror root", "native clicks/arrows/backspace", "selection replacement/undo", "Mod-Enter/save/reopen", "cancel/destroy",
|
||||
...(realRenderer ? ["visible Latex Suite preview", "preview contains rendered math without errors"] : [])] };
|
||||
} finally {
|
||||
let detachError;
|
||||
try { if (session) cdp("Target.detachFromTarget", { sessionId: session }); }
|
||||
catch (error) { detachError = error; }
|
||||
evaluate(`(()=>{${definitions}Promise.resolve((${cleanup.toString()})(${JSON.stringify(CONTROL)})).catch(e=>{globalThis.${CONTROL}.cleanupError=e.stack});return JSON.stringify({started:true})})()`);
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const value = evaluate(`JSON.stringify({exists:!!globalThis.${CONTROL},error:globalThis.${CONTROL}?.cleanupError})`);
|
||||
if (!value.exists) break;
|
||||
if (value.error) throw Error(value.error);
|
||||
if (i === 99) throw Error("LaTeX cleanup timed out");
|
||||
await wait(100);
|
||||
}
|
||||
if (detachError) throw detachError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/** Native authoring round-trip on fixtures owned by the guarded parent runner. */
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
export async function runNativeCLIScenario({ cli, drawingPath }) {
|
||||
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_native_cli';
|
||||
assert.ok(prefix.split('/').at(-1).startsWith('__excalidraw_cli_smoke_'));
|
||||
const idPrefix = prefix.split('/').at(-1).slice(-40);
|
||||
const paths = { drawing: `${prefix}.excalidraw.md`, request: `${prefix}.json`, png: `${prefix}.png`, svg: `${prefix}.svg`, disk: `${prefix}_disk.png`,
|
||||
script: `${prefix}_script.md`, template: `${prefix}_template.excalidraw.md`, invalid: `${prefix}_invalid.excalidraw.md` };
|
||||
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
|
||||
const action = (command, request = {}) => JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, `json=${JSON.stringify({ apiVersion: 1, ...request })}`));
|
||||
const ok = (result) => { assert.equal(result.ok, true, JSON.stringify(result)); return result; };
|
||||
const write = (path, text) => evaluate(`(async()=>{const path=${JSON.stringify(path)},file=app.vault.getFileByPath(path);if(file)await app.vault.modify(file,${JSON.stringify(text)});else await app.vault.create(path,${JSON.stringify(text)});return JSON.stringify({written:true})})()`);
|
||||
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(leaf=>leaf.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
|
||||
const control = '__excalidrawNativeCLIRegression';
|
||||
let cleanup = false;
|
||||
const artifacts = [];
|
||||
try {
|
||||
for (const command of ['help', 'status', 'skill', 'list']) ok(action(command));
|
||||
assert.equal(ok(action('schema', { action: 'apply' })).data.command, 'apply');
|
||||
assert.equal(ok(action('api', { name: 'executeCLI' })).data.entries[0].name, 'executeCLI');
|
||||
const create = { apiVersion: 1, requestId: `${idPrefix}-create`, path: paths.drawing, elements: [
|
||||
{ id: 'a', type: 'rectangle', x: 0, y: 0, width: 180, height: 80, label: { text: 'Start' } },
|
||||
{ id: 'b', type: 'rectangle', x: 280, y: 0, width: 180, height: 80, label: { text: '[[Link]]' } },
|
||||
{ id: 'arrow', type: 'arrow', x: 180, y: 40, start: { id: 'a' }, end: { id: 'b' } },
|
||||
{ id: 'frame', type: 'frame', children: ['a', 'b', 'arrow'], name: 'Native CLI' },
|
||||
] };
|
||||
write(paths.request, JSON.stringify(create));
|
||||
const created = ok(JSON.parse(cli('obsidian-excalidraw-plugin:create', `input=${paths.request}`)));
|
||||
assert.equal(created.persistence, 'saved'); assert.equal(created.data.createdIds.length, 6);
|
||||
assert.ok(created.data.createdIds.every(id => id.length === 8));
|
||||
assert.deepEqual(action('create', create), created);
|
||||
assert.equal(action('create', { ...create, requestId: `${idPrefix}-collision` }).error.code, 'ALREADY_EXISTS');
|
||||
const invalid = action('create', { requestId: `${idPrefix}-invalid`, path: paths.invalid, elements: [{ type: 'arrow', start: { id: 'missing' } }] });
|
||||
assert.equal(invalid.mutation, 'not-applied');
|
||||
assert.equal(evaluate(`JSON.stringify({exists:!!app.vault.getFileByPath(${JSON.stringify(paths.invalid)})})`).exists, false);
|
||||
const templateSource = evaluate(`(async()=>{const file=app.vault.getFileByPath(${JSON.stringify(paths.drawing)});const text=await app.vault.read(file);await app.vault.modify(file,text.replace('# Excalidraw Data',${JSON.stringify('## Hybrid note\n\nTemplate prose survives.\n\n# Excalidraw Data')}));return JSON.stringify({ready:true})})()`); assert.equal(templateSource.ready, true);
|
||||
ok(action('create', { requestId: `${idPrefix}-template`, path: paths.template, template: paths.drawing, elements: [{ id: 'new', type: 'text', text: 'Template addition', x: 0, y: 150 }] }));
|
||||
assert.equal(evaluate(`(async()=>{const text=await app.vault.read(app.vault.getFileByPath(${JSON.stringify(paths.template)}));return JSON.stringify({preserved:text.includes('Template prose survives.')&&text.includes('Template addition')})})()`).preserved, true);
|
||||
ok(action('open', { path: paths.drawing }));
|
||||
const read = () => ok(action('read', { path: paths.drawing, source: 'live', detail: 'elements' })).data;
|
||||
let live = read(); const label = live.elements.find(element => element.type === 'text' && element.text === 'Start');
|
||||
const update = { requestId: `${idPrefix}-update`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'update', id: label.id, set: { text: 'Edited via native CLI', strokeColor: '#1971c2' } }] };
|
||||
const applied = ok(action('apply', update)); assert.equal(applied.persistence, 'saved');
|
||||
assert.deepEqual(action('apply', update), applied);
|
||||
assert.equal(action('apply', { ...update, requestId: `${idPrefix}-stale` }).error.code, 'STALE_REVISION');
|
||||
assert.equal(ok(action('read', { path: paths.drawing, source: 'disk', detail: 'elements' })).data.elements.find(element => element.id === label.id).rawText, 'Edited via native CLI');
|
||||
// Actual delayed text path, competing CLI write, and a newer human scene.
|
||||
live = read();
|
||||
evaluate(`(()=>{const v=${viewCode},p=app.plugins.plugins['obsidian-excalidraw-plugin'];if(globalThis.${control})throw Error('test controller exists');const c={view:v,model:v.excalidrawData,original:v.excalidrawData.addTextElement,state:'waiting'};globalThis.${control}=c;c.gate=new Promise(resolve=>c.release=resolve);c.model.addTextElement=async function(...args){await c.gate;return c.original.apply(this,args)};p.executeCLI(${JSON.stringify({ apiVersion: 1, command: 'apply', requestId: `${idPrefix}-delayed`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'update', id: label.id, set: { text: 'Must not publish' } }] })}).then(result=>{c.result=result;c.state='finished'});return JSON.stringify({started:true})})()`);
|
||||
assert.equal(action('apply', { ...update, requestId: `${idPrefix}-competing`, expectedRevision: live.revision }).error.code, 'BUSY');
|
||||
evaluate(`(()=>{const c=globalThis.${control},v=c.view,a=v.excalidrawAPI;const elements=structuredClone(a.getSceneElements());elements.find(e=>e.type==='rectangle').x+=1;v.updateScene({elements,captureUpdate:'IMMEDIATELY'});c.model.addTextElement=c.original;c.release();return JSON.stringify({released:true})})()`);
|
||||
let delayed;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
delayed = action('result', { requestId: `${idPrefix}-delayed` }); if (delayed.status !== 'pending') break;
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
}
|
||||
assert.equal(delayed.error.code, 'STALE_REVISION'); assert.equal(delayed.mutation, 'not-applied');
|
||||
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Edited via native CLI');
|
||||
evaluate(`(()=>{delete globalThis.${control};return JSON.stringify({clean:true})})()`);
|
||||
// Published edits survive a failed save receipt; no false durability claim.
|
||||
evaluate(`(()=>{const v=${viewCode};globalThis.${control}={view:v,originalSave:v.saveWithOutcome};v.saveWithOutcome=async()=>({status:'failed',requestedRevision:1,acknowledgedRevision:null,currentRevision:1});return JSON.stringify({ready:true})})()`);
|
||||
const failed = action('apply', { ...update, requestId: `${idPrefix}-failed-save`, expectedRevision: read().revision, operations: [{ op: 'update', id: label.id, set: { text: 'Recoverable edit' } }] });
|
||||
assert.equal(failed.mutation, 'applied'); assert.equal(failed.persistence, 'unsaved');
|
||||
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Recoverable edit');
|
||||
evaluate(`(async()=>{const c=globalThis.${control};c.view.saveWithOutcome=c.originalSave;delete globalThis.${control};const saved=await c.view.saveWithOutcome();return JSON.stringify({status:saved.status})})()`);
|
||||
const relationships = ok(action('apply', { requestId: `${idPrefix}-relations`, path: paths.drawing, expectedRevision: read().revision, operations: [
|
||||
{ op: 'add', elements: [{ id: 'new-node', type: 'rectangle', x: 540, y: 0, width: 180, height: 80, label: { text: 'Temporary' } }] },
|
||||
{ op: 'connect', id: 'new-arrow', from: created.data.idMap.b, to: 'new-node', fromSide: 'right', toSide: 'left' },
|
||||
{ op: 'group', ids: [created.data.idMap.b, 'new-node'] },
|
||||
] }));
|
||||
assert.ok(relationships.data.idMap['new-node'] && relationships.data.idMap['new-arrow']);
|
||||
const cleanupRelations = ok(action('apply', { requestId: `${idPrefix}-ungroup`, path: paths.drawing, expectedRevision: read().revision, operations: [
|
||||
{ op: 'ungroup', ids: [created.data.idMap.b, relationships.data.idMap['new-node']], groupId: relationships.data.groupIds[0] },
|
||||
{ op: 'delete', ids: [relationships.data.idMap['new-node'], relationships.data.idMap['new-arrow']] },
|
||||
] })); assert.equal(cleanupRelations.persistence, 'saved');
|
||||
const refusedFrame = action('apply', { requestId: `${idPrefix}-frame-guard`, path: paths.drawing, expectedRevision: read().revision, operations: [{ op: 'delete', ids: [created.data.idMap.frame] }] });
|
||||
assert.equal(refusedFrame.error.field, 'children'); assert.equal(refusedFrame.mutation, 'not-applied');
|
||||
for (const [format, source, out] of [['svg', 'live', paths.svg], ['png', 'live', paths.png], ['png', 'disk', paths.disk]]) {
|
||||
const result = ok(action('export', { requestId: `${idPrefix}-${source}-${format}`, path: paths.drawing, source, out, theme: 'light' }));
|
||||
assert.equal(result.persistence, 'saved'); assert.ok(result.data.width > 0 && result.data.height > 0 && result.data.bytes > 100);
|
||||
artifacts.push(result.data);
|
||||
}
|
||||
assert.equal(action('export', { requestId: `${idPrefix}-no-overwrite`, path: paths.drawing, out: paths.png }).error.code, 'ALREADY_EXISTS');
|
||||
live = read();
|
||||
const image = ok(action('apply', { requestId: `${idPrefix}-image`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'image', id: 'preview', asset: paths.png, x: 0, y: 200 }] })); assert.ok(image.data.idMap.preview);
|
||||
assert.equal(ok(action('read', { path: paths.drawing, source: 'disk' })).data.types.image, 1);
|
||||
write(paths.script, 'return {input:utils.input,source:utils.executionSource,converter:typeof utils.excalidrawLib.convertToExcalidrawElements};');
|
||||
const scriptRequest = { requestId: `${idPrefix}-script`, script: paths.script, trusted: true, args: { x: 0, text: '${literal}' } };
|
||||
const script = ok(action('script', scriptRequest)); assert.equal(script.persistence, 'unknown'); assert.deepEqual(script.data.input, scriptRequest.args); assert.equal(script.data.source, 'cli');
|
||||
assert.deepEqual(action('script', scriptRequest), script);
|
||||
write(paths.script, 'await utils.inputPrompt("must fail");');
|
||||
assert.equal(action('script', scriptRequest).error.field, 'requestId');
|
||||
assert.equal(action('script', { ...scriptRequest, requestId: `${idPrefix}-prompt` }).error.code, 'INTERACTION_REQUIRED');
|
||||
const close = evaluate(`(async()=>{for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}return JSON.stringify({closed:true})})()`); assert.equal(close.closed, true);
|
||||
ok(action('open', { path: paths.drawing }));
|
||||
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Recoverable edit');
|
||||
} finally {
|
||||
const result = evaluate(`(async()=>{const c=globalThis.${control};if(c){if(c.original)c.model.addTextElement=c.original;if(c.originalSave)c.view.saveWithOutcome=c.originalSave;c.release?.();delete globalThis.${control}}const paths=${JSON.stringify(Object.values(paths))};for(const path of paths){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe fixture cleanup');for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}const file=app.vault.getFileByPath(path);if(file)await app.vault.delete(file)}return JSON.stringify({clean:true})})()`);
|
||||
cleanup = result.clean;
|
||||
}
|
||||
assert.equal(cleanup, true);
|
||||
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts };
|
||||
}
|
||||
@@ -8,12 +8,21 @@ import { mkdtempSync } from "node:fs";
|
||||
import { runObsidianSmoke } from "./runner.mjs";
|
||||
import { obsidianCliExecutable, packageManagerInvocation, spawnNativeSync } from "./processTools.mjs";
|
||||
import { runTextUndoScenario } from "./textUndo.mjs";
|
||||
import { runNativeCLIScenario } from "./nativeCLI.mjs";
|
||||
import { runEmbedRecoveryScenario } from "./embedRecovery.mjs";
|
||||
import { runGroupedLinkClickScenario } from "./groupedLinkClick.mjs";
|
||||
import { runLatexInputScenario } from "./latexInput.mjs";
|
||||
|
||||
const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const pluginOnly = process.argv.includes("--plugin-only");
|
||||
const textUndo = process.argv.includes("--text-undo");
|
||||
if (process.argv.slice(2).some(arg => !["--plugin-only", "--text-undo"].includes(arg))) {
|
||||
throw new Error("Supported options: --plugin-only, --text-undo");
|
||||
const nativeCLI = process.argv.includes("--native-cli");
|
||||
const embedRecovery = process.argv.includes("--embed-recovery");
|
||||
const groupedLinkClick = process.argv.includes("--grouped-link-click");
|
||||
const latexInput = process.argv.includes("--latex-input");
|
||||
const latexPreview = process.argv.includes("--latex-preview");
|
||||
if (process.argv.slice(2).some(arg => !["--plugin-only", "--text-undo", "--native-cli", "--embed-recovery", "--grouped-link-click", "--latex-input", "--latex-preview"].includes(arg))) {
|
||||
throw new Error("Supported options: --plugin-only, --text-undo, --native-cli, --embed-recovery, --grouped-link-click, --latex-input, --latex-preview");
|
||||
}
|
||||
const forkRoot = resolve(process.env.EXCALIDRAW_FORK_ROOT || join(pluginRoot, "../excalidraw"));
|
||||
const reportDir = process.env.EXCALIDRAW_TEST_REPORT_DIR || mkdtempSync(join(tmpdir(), "excalidraw-obsidian-"));
|
||||
@@ -21,7 +30,7 @@ const FORK_ARTIFACTS = ["excalidraw.production.min.js", "excalidraw.production.m
|
||||
"excalidraw.development.js", "excalidraw.development.css"];
|
||||
|
||||
function command(file, args, cwd, timeout = 60_000, inherit = false) {
|
||||
const result = spawnNativeSync(file, args, { cwd, encoding: "utf8", timeout, maxBuffer: 4 * 1024 * 1024,
|
||||
const result = spawnNativeSync(file, args, { cwd, encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 4 * 1024 * 1024,
|
||||
stdio: inherit ? "inherit" : "pipe" });
|
||||
if (result.error) throw new Error(`${file}: ${result.error.message}`);
|
||||
if (result.status !== 0) throw new Error(`${file} ${args.join(" ")} failed (${result.status}): ${(result.stderr || result.stdout || "").trim().slice(0, 1000)}`);
|
||||
@@ -48,7 +57,14 @@ const report = await runObsidianSmoke({
|
||||
configDir: process.env.EXCALIDRAW_TEST_CONFIG_DIR,
|
||||
reportDir,
|
||||
source,
|
||||
scenarios: textUndo ? [runTextUndoScenario] : [],
|
||||
scenarios: [
|
||||
...(textUndo ? [runTextUndoScenario] : []),
|
||||
...(nativeCLI ? [runNativeCLIScenario] : []),
|
||||
...(embedRecovery ? [runEmbedRecoveryScenario] : []),
|
||||
...(groupedLinkClick ? [runGroupedLinkClickScenario] : []),
|
||||
...(latexInput ? [runLatexInputScenario] : []),
|
||||
...(latexPreview ? [context => runLatexInputScenario({ ...context, realRenderer: true })] : []),
|
||||
],
|
||||
runCli: (vault, commandName, ...args) => command(obsidianCliExecutable(),
|
||||
[`vault=${vault}`, commandName, ...args], pluginRoot),
|
||||
runBuild: () => {
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
/** Exercise the real postprocessor with deferred image generation, without Electron. */
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import test from "node:test";
|
||||
import vm from "node:vm";
|
||||
import ts from "typescript";
|
||||
|
||||
const root = resolve(import.meta.dirname, "../..");
|
||||
const deferred = () => {
|
||||
let resolve, reject;
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
function fixture() {
|
||||
const observers = [], timers = new Map(), intervals = new Map(), jobs = [], requests = [], errors = [], released = [], loaders = [];
|
||||
let timerId = 0;
|
||||
class Observer {
|
||||
constructor(callback) { this.callback = callback; observers.push(this); }
|
||||
observe(el) { this.el = el; this.connected = true; }
|
||||
disconnect() { this.connected = false; }
|
||||
fire(...attributes) {
|
||||
if (this.connected) this.callback(attributes.map(attributeName => ({ attributeName })));
|
||||
}
|
||||
}
|
||||
const ownerWindow = {
|
||||
MutationObserver: Observer,
|
||||
setTimeout: callback => { timers.set(++timerId, callback); return timerId; },
|
||||
clearTimeout: id => timers.delete(id),
|
||||
setInterval: callback => { intervals.set(++timerId, callback); return timerId; },
|
||||
clearInterval: id => intervals.delete(id),
|
||||
};
|
||||
class Element {
|
||||
constructor(classes = "", tag = "div") {
|
||||
this.classes = new Set(classes.split(" "));
|
||||
this.tag = tag; this.attrs = new Map(); this.children = []; this.isConnected = true;
|
||||
this.ownerDocument = { defaultView: ownerWindow };
|
||||
this.ownerDocument.body = { querySelectorAll: () => [] };
|
||||
}
|
||||
hasClass(cls) { return this.classes.has(cls); }
|
||||
addClass(cls) { this.classes.add(cls); }
|
||||
removeClass(cls) { this.classes.delete(cls); }
|
||||
getAttribute(key) { return this.attrs.get(key) ?? null; }
|
||||
setAttribute(key, value) { this.attrs.set(key, value); }
|
||||
removeAttribute(key) { this.attrs.delete(key); }
|
||||
hasAttribute(key) { return this.attrs.has(key); }
|
||||
get firstElementChild() { return this.children[0] ?? null; }
|
||||
hasChildNodes() { return this.children.length > 0; }
|
||||
closest(selector) {
|
||||
let el = this;
|
||||
while (el) { if (selector.startsWith(".") && el.hasClass(selector.slice(1))) return el; el = el.parentElement; }
|
||||
return null;
|
||||
}
|
||||
empty() { for (const child of this.children) child.parentElement = null; this.children = []; }
|
||||
appendChild(child) { this.children.push(child); child.parentElement = this; return child; }
|
||||
replaceChild(child, old) {
|
||||
const index = this.children.indexOf(old); assert.notEqual(index, -1);
|
||||
this.children[index] = child; child.parentElement = this; old.parentElement = null;
|
||||
}
|
||||
querySelectorAll(selector) {
|
||||
return this.children.flatMap(child => [...(selector === child.tag || (selector.startsWith(".") && child.hasClass(selector.slice(1))) ? [child] : []), ...child.querySelectorAll(selector)]);
|
||||
}
|
||||
querySelector(selector) { return this.querySelectorAll(selector)[0] ?? null; }
|
||||
}
|
||||
class RenderChild {
|
||||
constructor(containerEl) { this.containerEl = containerEl; this.cleanups = []; this._loaded = false; }
|
||||
register(callback) { this.cleanups.push(callback); }
|
||||
load() { if (!this._loaded) { this._loaded = true; this.onload(); } }
|
||||
unload() {
|
||||
if (!this._loaded) return;
|
||||
this._loaded = false;
|
||||
for (const callback of this.cleanups.splice(0).reverse()) callback();
|
||||
this.onunload();
|
||||
}
|
||||
}
|
||||
class TFile { constructor(path) { this.path = path; this.extension = path.split(".").at(-1); } }
|
||||
const sourceFile = new TFile("source.excalidraw.md"), targetFile = new TFile("target.excalidraw.md");
|
||||
const plainFile = new TFile("image.png");
|
||||
const files = new Map([sourceFile, targetFile, plainFile].map(file => [file.path, file]));
|
||||
const frontmatters = new Map();
|
||||
const plugin = {
|
||||
_loaded: true,
|
||||
awaitInit: async () => {},
|
||||
awaitSettings: async () => {},
|
||||
settings: { width: "400", height: "", renderImageInMarkdownReadingMode: true, renderImageInMarkdownToPDF: true },
|
||||
isExcalidrawFile: file => file.path.endsWith("excalidraw.md"),
|
||||
app: {
|
||||
vault: { getAbstractFileByPath: path => files.get(path), getFileByPath: path => files.get(path) },
|
||||
metadataCache: { getFirstLinkpathDest: path => files.get(path), getFileCache: file => ({ frontmatter: frontmatters.get(file.path) }) },
|
||||
},
|
||||
};
|
||||
const queue = { addTask: task => new Promise((resolve, reject) => jobs.push(async () => { try { await task(); resolve(); } catch (e) { reject(e); } })) };
|
||||
const image = (name = "result") => {
|
||||
const div = new Element(), img = new Element("", "img"); img.src = `blob:${name}`; div.appendChild(img); return div;
|
||||
};
|
||||
const createImage = async (attr, onCanvas, embedEl, isRenderActive) => {
|
||||
const result = deferred(); requests.push({ ...result, attr, isRenderActive }); return result.promise;
|
||||
};
|
||||
const mocks = {
|
||||
obsidian: { TFile, MarkdownRenderChild: RenderChild },
|
||||
"src/shared/GlobalTaskQueue": { getGlobalTaskQueue: () => queue },
|
||||
"../../utils/debugHelper": { DEBUGGING: false },
|
||||
"../../shared/ImageCache": { getImageCache: () => ({ isReady: () => false, releaseObsidianURL: url => released.push(url) }) },
|
||||
"../../shared/EmbeddedFileLoader": { EmbeddedFilesLoader: class { constructor() { this.terminate = false; loaders.push(this); } } },
|
||||
"../../types/utilTypes": { PreviewImageType: { PNG: "PNG", SVGIMG: "SVGIMG", SVG: "SVG" } },
|
||||
"../../utils/typechecks": { isInstanceOfHTMLImageElement: el => el.tag === "img" },
|
||||
"../../utils/obsidianUtils": { getSafeFrontmatter: fm => fm ?? {}, getParentOfClass: () => null },
|
||||
"src/utils/htmlUtils": { setElementDisplay: (el, display) => { if (display === "none") el.addClass("excalidraw-display-none"); else el.removeClass("excalidraw-display-none"); } },
|
||||
"../../utils/utils": {
|
||||
hasExportTheme: () => false, getWithBackground: () => false, isMaskFile: () => false,
|
||||
getEmbeddedFilenameParts: src => ({ hasBlockref: src.includes("#^"), blockref: src.split("#^")[1] }),
|
||||
},
|
||||
};
|
||||
const context = vm.createContext({ MutationObserver: Observer, window: ownerWindow, createEl: tag => new Element("", tag),
|
||||
console: { error: (...args) => errors.push(args) }, __createImage: createImage, __createRaster: async () => null });
|
||||
const compile = (source, require) => {
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
|
||||
const exports = {};
|
||||
vm.runInContext(`(function(require,exports){${code}\n})`, context)(require, exports);
|
||||
return exports;
|
||||
};
|
||||
const child = compile(readFileSync(resolve(root, "src/core/managers/MarkdownEmbedRenderChild.ts"), "utf8"), name => mocks[name]);
|
||||
Object.assign(mocks["../../utils/utils"], compile(readFileSync(resolve(root, "src/utils/embeddedFilenameParts.ts"), "utf8"), () => ({})));
|
||||
let source = readFileSync(resolve(root, "src/core/managers/MarkdownPostProcessor.ts"), "utf8");
|
||||
// Stub only image generation. Routing, cleanup, queueing and lifecycle are production code.
|
||||
const tree = ts.createSourceFile("processor.ts", source, ts.ScriptTarget.Latest, true);
|
||||
const seams = { createImageDiv: "globalThis.__createImage", _getPNG: "globalThis.__createRaster", setImgStyle: "() => {}" };
|
||||
const statements = tree.statements.filter(s => ts.isVariableStatement(s) && s.declarationList.declarations.some(d => Object.hasOwn(seams, d.name.getText(tree))));
|
||||
assert.equal(statements.length, 3, "image generation seams exist");
|
||||
for (const statement of statements.reverse()) {
|
||||
const name = statement.declarationList.declarations[0].name.getText(tree);
|
||||
source = source.slice(0, statement.getStart(tree)) + `const ${name} = ${seams[name]};` + source.slice(statement.end);
|
||||
}
|
||||
source += "\nexport { tmpObsidianWYSIWYG, processReadingMode, getIMG };";
|
||||
const processor = compile(source, name => name === "./MarkdownEmbedRenderChild" ? child : mocks[name] ?? {});
|
||||
processor.initializeMarkdownPostProcessor(plugin);
|
||||
const container = new Element("internal-embed markdown-embed"); container.setAttribute("src", targetFile.path);
|
||||
const el = container.appendChild(new Element());
|
||||
const children = [];
|
||||
const ctx = { sourcePath: sourceFile.path, containerEl: container, remainingNestLevel: 5, addChild: c => { children.push(c); c.load(); } };
|
||||
const render = () => processor.tmpObsidianWYSIWYG(el, ctx, false, false, false);
|
||||
const flushTimers = () => { for (const [id, callback] of timers) { timers.delete(id); callback(); } };
|
||||
const start = () => { assert.ok(jobs.length); const done = jobs.shift()(); return done; };
|
||||
const settle = async (name = "result", request = requests.at(-1)) => { const result = image(name); request.resolve(result); await Promise.resolve(); return result; };
|
||||
return { processor, plugin, container, ctx, el, children, render, jobs, requests, errors, released, observers, timers, intervals, loaders, frontmatters, flushTimers, start, settle, image, Element };
|
||||
}
|
||||
|
||||
test("ready follows successful insertion; repeated callbacks preserve the image", async () => {
|
||||
const f = fixture(); const first = f.render(); const repeat = f.render();
|
||||
assert.equal(f.container.hasAttribute("ready"), false); assert.equal(f.jobs.length, 1); assert.equal(f.children.length, 1);
|
||||
const job = f.start(); const result = await f.settle(); await job; await Promise.all([first, repeat]);
|
||||
assert.equal(f.container.children[0], result); assert.equal(f.container.hasAttribute("ready"), true);
|
||||
await f.render(); assert.equal(f.container.children[0], result); assert.equal(f.jobs.length, 0);
|
||||
});
|
||||
|
||||
for (const phase of ["before queue start", "during image generation"]) {
|
||||
test(`a live, detached context recovers on reattachment (${phase})`, async () => {
|
||||
const f = fixture(); const rendered = f.render();
|
||||
if (phase === "before queue start") f.container.isConnected = false;
|
||||
const job = f.start(); f.container.isConnected = false;
|
||||
assert.equal(f.requests[0].isRenderActive(), true, "embedded-file loading survives a temporary detach");
|
||||
const result = await f.settle(); await job; await rendered;
|
||||
f.container.isConnected = true; await f.render();
|
||||
assert.equal(f.container.children[0], result); assert.equal(f.container.hasAttribute("ready"), true);
|
||||
assert.equal(f.requests.length, 1); assert.equal(f.released.includes("blob:result"), false);
|
||||
});
|
||||
}
|
||||
|
||||
for (const failure of ["null", "throw"]) {
|
||||
test(`${failure} releases pending state and allows a later callback to retry`, async () => {
|
||||
const f = fixture(); const rendered = f.render(); const job = f.start();
|
||||
if (failure === "null") f.requests[0].resolve(null); else f.requests[0].reject(Error("expected fixture failure"));
|
||||
await job; await rendered; assert.equal(f.container.hasAttribute("ready"), false);
|
||||
const retry = f.render(); const secondJob = f.start(); const result = await f.settle("retry"); await secondJob; await retry;
|
||||
assert.equal(f.container.children[0], result); assert.equal(f.errors.length, failure === "throw" ? 1 : 0);
|
||||
});
|
||||
}
|
||||
|
||||
test("an obsolete completion cannot insert or clear a newer pending attempt", async () => {
|
||||
const f = fixture(); const first = f.render(); const oldJob = f.start();
|
||||
f.observers.find(o => o.el === f.container).fire("class", "width"); f.flushTimers();
|
||||
const newJob = f.start(); assert.equal(f.requests.length, 2);
|
||||
await f.settle("obsolete", f.requests[0]); await oldJob; await first;
|
||||
const repeat = f.render(); assert.equal(f.jobs.length, 0);
|
||||
const result = await f.settle("current", f.requests[1]); await newJob; await repeat;
|
||||
assert.equal(f.container.children[0], result); assert.ok(f.released.includes("blob:obsolete"));
|
||||
assert.equal(f.container.hasAttribute("ready"), true);
|
||||
});
|
||||
|
||||
test("attribute refresh retains the current image and the actual target until replacement", async () => {
|
||||
const f = fixture(); const first = f.render(); const job = f.start(); const result = await f.settle(); await job; await first;
|
||||
f.container.setAttribute("width", "123"); f.observers.find(o => o.el === f.container).fire("width"); f.flushTimers();
|
||||
const refresh = f.start(); assert.equal(f.container.children[0], result);
|
||||
assert.equal(f.requests[1].attr.file.path, "target.excalidraw.md"); assert.equal(f.requests[1].attr.fwidth, "123");
|
||||
const replacement = await f.settle("resized"); await refresh;
|
||||
assert.equal(f.container.children[0], replacement); assert.ok(f.released.includes("blob:result"));
|
||||
});
|
||||
|
||||
test("a later callback repairs content removed by the host", async () => {
|
||||
const f = fixture(); const first = f.render(); const job = f.start(); await f.settle(); await job; await first;
|
||||
f.container.empty();
|
||||
const retry = f.render(); const next = f.start(); const result = await f.settle("restored"); await next; await retry;
|
||||
assert.equal(f.container.children[0], result); assert.equal(f.container.hasAttribute("ready"), true);
|
||||
});
|
||||
|
||||
test("an unloaded context cannot overwrite a replacement context's image", async () => {
|
||||
const f = fixture(); const first = f.render(); const oldJob = f.start(); f.children[0].unload();
|
||||
const second = f.render(); const newJob = f.start(); const result = await f.settle("new-context", f.requests[1]); await newJob; await second;
|
||||
await f.settle("old-context", f.requests[0]); await oldJob; await first;
|
||||
assert.equal(f.container.children[0], result); assert.equal(f.container.hasAttribute("ready"), true);
|
||||
assert.ok(f.released.includes("blob:old-context")); assert.equal(f.children.length, 2);
|
||||
});
|
||||
|
||||
test("plugin unload cancels an in-flight image", async () => {
|
||||
const f = fixture(); const rendered = f.render(); const job = f.start(); f.plugin._loaded = false;
|
||||
await f.settle("plugin-unloaded"); await job; await rendered;
|
||||
assert.equal(f.container.children.length, 0); assert.equal(f.container.hasAttribute("ready"), false);
|
||||
assert.ok(f.released.includes("blob:plugin-unloaded"));
|
||||
});
|
||||
|
||||
for (const phase of ["queued", "generating", "debounced"]) {
|
||||
test(`permanent unload stops ${phase} work and cleans observers/timers`, async () => {
|
||||
const f = fixture(); const rendered = f.render();
|
||||
const job = phase === "queued" ? null : f.start();
|
||||
if (phase === "debounced") f.observers.find(o => o.el === f.container).fire("height");
|
||||
f.children[0].unload(); f.container.isConnected = false;
|
||||
if (job) assert.equal(f.requests[0].isRenderActive(), false, "embedded-file loading stops on unload");
|
||||
if (job) await f.settle("cancelled");
|
||||
await (job ?? f.start()); await rendered; f.flushTimers();
|
||||
assert.equal(f.container.children.length, 0); assert.equal(f.container.hasAttribute("ready"), false);
|
||||
assert.equal(f.timers.size, 0); assert.equal(f.observers.some(o => o.connected), false);
|
||||
if (job) assert.ok(f.released.includes("blob:cancelled")); else assert.equal(f.requests.length, 0);
|
||||
});
|
||||
}
|
||||
|
||||
test("ordinary image embeds, text references and code blocks remain native", async () => {
|
||||
for (const kind of ["image.png", "target.excalidraw.md#^text", "code"]) {
|
||||
const f = fixture();
|
||||
if (kind === "code") { f.container.classes = new Set(["cm-embed-block"]); }
|
||||
else f.container.setAttribute("src", kind);
|
||||
await f.render(); assert.equal(f.container.children[0], f.el); assert.equal(f.children.length, 0); assert.equal(f.jobs.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("Reading mode skips a detached candidate without suppressing a later live drawing", async () => {
|
||||
const f = fixture(); const detached = new f.Element(); detached.isConnected = false;
|
||||
const parent = new f.Element(), live = parent.appendChild(new f.Element("internal-embed")); live.setAttribute("src", "target.excalidraw.md");
|
||||
const rendered = f.processor.processReadingMode([detached, live], f.ctx);
|
||||
assert.equal(f.jobs.length, 1); const job = f.start(); const result = await f.settle(); await job; await rendered;
|
||||
assert.equal(parent.children[0], result);
|
||||
});
|
||||
|
||||
test("image loader cancellation follows context lifetime and always clears its interval", async () => {
|
||||
for (const alive of [true, false]) {
|
||||
const f = fixture(); const init = deferred(); f.plugin.awaitInit = () => init.promise;
|
||||
f.plugin.settings.previewImageType = "PNG"; f.container.isConnected = false;
|
||||
const result = f.processor.getIMG({ file: { path: "target.excalidraw.md" }, fname: "target.excalidraw.md", imgstyle: [] }, false, f.container, () => alive);
|
||||
assert.equal(f.intervals.size, 1);
|
||||
for (const callback of f.intervals.values()) callback();
|
||||
assert.equal(f.loaders[0].terminate, !alive);
|
||||
init.resolve(); await result; assert.equal(f.intervals.size, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("explicit self-images override Markdown preferences and use the containing drawing", async () => {
|
||||
for (const property of ["excalidraw-open-md", "excalidraw-embed-md"]) {
|
||||
const f = fixture(); f.ctx.frontmatter = { [property]: true }; f.frontmatters.set(f.ctx.sourcePath, f.ctx.frontmatter);
|
||||
f.container.setAttribute("src", "#^as-image");
|
||||
const rendered = f.render(); const job = f.start();
|
||||
assert.equal(f.requests[0].attr.fname, `${f.ctx.sourcePath}#^as-image`);
|
||||
await f.settle(); await job; await rendered;
|
||||
assert.equal(f.container.hasAttribute("ready"), true);
|
||||
}
|
||||
});
|
||||
|
||||
test("Reading mode resolves explicit self-images, but ignores empty and ordinary text fragments", async () => {
|
||||
for (const src of ["#^as-image", "", "#", "#^", "#Heading", "#^real-block"]) {
|
||||
const f = fixture(); const parent = new f.Element(); const embed = parent.appendChild(new f.Element("internal-embed")); embed.setAttribute("src", src);
|
||||
const rendered = f.processor.processReadingMode([embed], f.ctx);
|
||||
if (src === "#^as-image") {
|
||||
const job = f.start(); assert.equal(f.requests[0].attr.fname, `${f.ctx.sourcePath}#^as-image`);
|
||||
const result = await f.settle(); await job; await rendered; assert.equal(parent.children[0], result);
|
||||
} else { await rendered; assert.equal(f.jobs.length, 0); assert.equal(parent.children[0], embed); }
|
||||
}
|
||||
});
|
||||
|
||||
test("Reading mode preserves a target's Markdown side unless the link explicitly requests an image", async () => {
|
||||
for (const property of ["excalidraw-open-md", "excalidraw-embed-md"]) {
|
||||
for (const suffix of ["", "#^as-image"]) {
|
||||
const f = fixture(); const parent = new f.Element(); const embed = parent.appendChild(new f.Element("internal-embed")); embed.setAttribute("src", `target.excalidraw.md${suffix}`);
|
||||
f.frontmatters.set("target.excalidraw.md", { [property]: true });
|
||||
const rendered = f.processor.processReadingMode([embed], f.ctx);
|
||||
if (suffix) { const job = f.start(); await f.settle(); await job; await rendered; assert.notEqual(parent.children[0], embed); }
|
||||
else { await rendered; assert.equal(f.jobs.length, 0); assert.equal(parent.children[0], embed); }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("nested Markdown-side drawings and PNGs remain visible; drawing metadata stays hidden", async () => {
|
||||
for (const property of ["excalidraw-open-md", "excalidraw-embed-md", null]) {
|
||||
for (const src of ["target.excalidraw.md", "image.png", "#^as-image"]) {
|
||||
const f = fixture(); f.ctx.frontmatter = { "excalidraw-plugin": "parsed", ...(property ? { [property]: true } : {}) };
|
||||
f.frontmatters.set(f.ctx.sourcePath, f.ctx.frontmatter);
|
||||
const section = new f.Element("el-p excalidraw-display-none"); const embed = section.appendChild(new f.Element("internal-embed")); embed.setAttribute("src", src);
|
||||
const rendered = f.processor.markdownPostProcessor(section, f.ctx); await new Promise(resolve => setImmediate(resolve));
|
||||
if (property && src !== "image.png") { const job = f.start(); await f.settle(); await job; }
|
||||
await rendered;
|
||||
assert.equal(section.hasClass("excalidraw-display-none"), !property);
|
||||
if (property && src === "image.png") assert.equal(section.children[0], embed);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
/** Bounded CLI mutations use existing EA, view persistence, and Vault creation. */
|
||||
import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
|
||||
import { CLIError, vaultPath } from "./cliProtocol";
|
||||
import { constructBatch } from "./cliElements";
|
||||
import { diskSnapshot, drawingFile } from "./cliTarget";
|
||||
import { applyDrawing } from "./cliApply";
|
||||
import { exportDrawing } from "./cliExport";
|
||||
import { executeScript, type PreparedCLIScript } from "./cliScripts";
|
||||
|
||||
/** Write-specific lifecycle and exclusion, without another save queue or serializer. */
|
||||
export class CLIWriteCommands {
|
||||
private activeEAs = new Set<ExcalidrawAutomate>();
|
||||
private inFlight = new Set<string>();
|
||||
public constructor(private readonly cli: ExcalidrawCLI) {}
|
||||
|
||||
/** Cancels unpublished work through the manager's session guard and disposes owned EAs. */
|
||||
public destroy(): void {
|
||||
for (const ea of this.activeEAs) ea.destroy();
|
||||
this.activeEAs.clear(); this.inFlight.clear();
|
||||
}
|
||||
|
||||
/** Dispatches finite writes; side-effect-aware failures preserve their applied outcome. */
|
||||
public async execute(command: string, request: Record<string, unknown>, preparedScript?: PreparedCLIScript): Promise<Partial<ExcalidrawCLIResult>> {
|
||||
if (!this.cli.plugin.isReady) throw new CLIError("NOT_READY", "Excalidraw is still initializing.");
|
||||
const path = command === "script" && request.path === undefined ? vaultPath(request.script, "script") : vaultPath(request.path);
|
||||
const out = command === "export" ? vaultPath(request.out, "out") : undefined;
|
||||
const locks = [...new Set([path, ...(out ? [out] : [])])];
|
||||
if (locks.some(key => this.inFlight.has(key))) throw new CLIError("BUSY", "Another CLI operation is running for this target.", "path");
|
||||
locks.forEach(key => this.inFlight.add(key));
|
||||
try {
|
||||
if (command === "create") return await this.create(path, request);
|
||||
if (command === "export") return await exportDrawing(this.cli, request, out);
|
||||
const ea = this.cli.plugin.ea.getAPI(); this.activeEAs.add(ea);
|
||||
try { return command === "script" ? await executeScript(this.cli, request, preparedScript, ea) : await applyDrawing(this.cli, request, ea); }
|
||||
finally { this.activeEAs.delete(ea); ea.destroy(); }
|
||||
}
|
||||
finally { locks.forEach(key => this.inFlight.delete(key)); }
|
||||
}
|
||||
|
||||
private async create(path: string, request: Record<string, unknown>): Promise<Partial<ExcalidrawCLIResult>> {
|
||||
const plugin = this.cli.plugin;
|
||||
if (!path.endsWith(".excalidraw.md") && !path.endsWith(".excalidraw")) throw new CLIError("INVALID_INPUT", "New drawings require .excalidraw.md or .excalidraw.", "path");
|
||||
const template = request.template === undefined ? null : drawingFile(plugin, request.template);
|
||||
const templatePath = template?.path, templateStat = template ? JSON.stringify(template.stat) : null;
|
||||
const check = () => {
|
||||
if (!this.cli.isCurrent()) throw new CLIError("NOT_READY", "Plugin session ended.");
|
||||
if (plugin.app.vault.getAbstractFileByPath(path)) throw new CLIError("ALREADY_EXISTS", "Creation never overwrites an existing target.", "path");
|
||||
if (template && (plugin.app.vault.getFileByPath(templatePath) !== template || JSON.stringify(template.stat) !== templateStat)) throw new CLIError("STALE_REVISION", "Template changed during preparation.", "template");
|
||||
};
|
||||
check();
|
||||
const templateSnapshot = template ? await diskSnapshot(plugin, template, this.cli.isCurrent) : null;
|
||||
if (path.endsWith(".excalidraw") && templateSnapshot?.scene.elements.some(element => element.type === "image" && !templateSnapshot.scene.files?.[element.fileId]?.dataURL)) throw new CLIError("INVALID_INPUT", "Use .excalidraw.md to preserve this template's linked asset metadata.", "path");
|
||||
const occupied = templateSnapshot?.scene.elements.map(element => element.id) ?? [];
|
||||
check();
|
||||
const { elements, idMap } = constructBatch(request.elements ?? [], plugin.getCLIRuntime(), occupied);
|
||||
const createdIds = elements.map(element => element.id);
|
||||
const ea = plugin.ea.getAPI(); this.activeEAs.add(ea);
|
||||
try {
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
const created = await ea.create({ exactPath: path, ...(templatePath ? { templatePath } : {}), validateBeforeCreate: check, silent: true });
|
||||
return { target: { vault: plugin.app.vault.getName(), path: created }, persistence: "saved", mutation: "applied", data: { path: created, createdIds, idMap }, warnings: this.cli.isCurrent() ? [] : ["Plugin session ended after creation; read the file back before further edits."] };
|
||||
} catch (error) {
|
||||
if (error instanceof CLIError) throw error;
|
||||
if (plugin.app.vault.getAbstractFileByPath(path)) throw new CLIError("OUTCOME_UNKNOWN", "A target exists after an interrupted create.", "path", "Read back this exact path; do not create another drawing blindly.", { target: { vault: plugin.app.vault.getName(), path }, data: { path }, mutation: "unknown", persistence: "unknown" });
|
||||
throw new CLIError("SAVE_FAILED", "Drawing could not be created.", "path", "Check folder permissions and retry only after read-back.");
|
||||
} finally { this.activeEAs.delete(ea); ea.destroy(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/** Finite request-local edits followed by one guarded view publication. */
|
||||
import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
|
||||
import type { ConnectionPoint } from "src/types/types";
|
||||
import { CLIError, boolean, number, object, string, vaultPath } from "./cliProtocol";
|
||||
import { CLI_STYLE_FIELDS, constructBatch, fields, validateBatch, validateStyle } from "./cliElements";
|
||||
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
|
||||
|
||||
export const CLI_OPERATION_FIELDS: Record<string, string[]> = {
|
||||
add: ["elements"], update: ["id", "set"], delete: ["ids", "children"],
|
||||
connect: ["id", "from", "to", "fromSide", "toSide"], group: ["ids"], ungroup: ["ids", "groupId"],
|
||||
image: ["id", "asset", "x", "y", "scale"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
|
||||
};
|
||||
|
||||
function ids(value: unknown): string[] {
|
||||
if (!Array.isArray(value) || !value.length || value.length > 500) throw new CLIError("INVALID_INPUT", "Expected 1–500 element IDs.", "ids");
|
||||
return value.map(id => string(id, "ids"));
|
||||
}
|
||||
function side(value: unknown): ConnectionPoint {
|
||||
if (value === undefined || value === null) return null;
|
||||
if (!["top", "bottom", "left", "right"].includes(string(value, "side"))) throw new CLIError("INVALID_INPUT", "Unknown connection side.");
|
||||
return value as ConnectionPoint;
|
||||
}
|
||||
|
||||
/** Validate every operation before any asset/text preparation begins. */
|
||||
export function validateOperations(input: unknown): Record<string, unknown>[] {
|
||||
if (!Array.isArray(input) || !input.length || input.length > 100) throw new CLIError("INVALID_INPUT", "Expected 1–100 operations.", "operations");
|
||||
return input.map(value => {
|
||||
const operation = object(value), op = string(operation.op, "op");
|
||||
if (!Object.hasOwn(CLI_OPERATION_FIELDS, op)) throw new CLIError("INVALID_INPUT", "Unsupported operation.", "op");
|
||||
fields(operation, ["op", ...CLI_OPERATION_FIELDS[op]]);
|
||||
if (op === "add") validateBatch(operation.elements);
|
||||
if (op === "update") { string(operation.id, "id"); const set = object(operation.set, "set"); fields(set, CLI_STYLE_FIELDS); validateStyle(set); }
|
||||
if (["delete", "group", "ungroup"].includes(op)) ids(operation.ids);
|
||||
if (op === "delete" && operation.children !== undefined && !["delete", "detach"].includes(string(operation.children, "children"))) throw new CLIError("INVALID_INPUT", "Expected delete or detach.", "children");
|
||||
if (op === "ungroup") string(operation.groupId, "groupId");
|
||||
if (op === "connect") { string(operation.from, "from"); string(operation.to, "to"); side(operation.fromSide); side(operation.toSide); }
|
||||
if (["image", "latex"].includes(op)) {
|
||||
number(operation.x, "x", 0, -1000000, 1000000); number(operation.y, "y", 0, -1000000, 1000000);
|
||||
if (op === "image") { vaultPath(operation.asset, "asset"); boolean(operation.scale, "scale", true); }
|
||||
else { string(operation.text, "text"); number(operation.scaleX, "scaleX", 1, 0.1, 4); number(operation.scaleY, "scaleY", 1, 0.1, 4); }
|
||||
}
|
||||
if (operation.id !== undefined) string(operation.id, "id");
|
||||
return operation;
|
||||
});
|
||||
}
|
||||
|
||||
/** No scene or document metadata changes until the guard inside addElements succeeds. */
|
||||
export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, unknown>, ea: ExcalidrawAutomate): Promise<Partial<ExcalidrawCLIResult>> {
|
||||
const plugin = cli.plugin, file = drawingFile(plugin, request.path), view = drawingView(plugin, file, request.view);
|
||||
if (!view) throw new CLIError("NOT_READY", "Apply requires a live drawing.", "path", "Open the drawing, then read a fresh live revision.");
|
||||
const operations = validateOperations(request.operations), api = view.excalidrawAPI, model = view.excalidrawData;
|
||||
const identity = liveIdentity(view), revision = cli.targets.revision(view, identity);
|
||||
if (string(request.expectedRevision, "expectedRevision") !== revision) throw new CLIError("STALE_REVISION", "Drawing changed since the live read.", "expectedRevision", "Read the drawing again and prepare a new request.");
|
||||
const check = () => {
|
||||
if (!cli.isCurrent() || view.file !== file || view.excalidrawAPI !== api || view.excalidrawData !== model || plugin.app.vault.getFileByPath(file.path) !== file) throw new CLIError("STALE_REVISION", "Target identity changed during preparation.");
|
||||
if (view.isSameFileEditingActive() || view.isPersistenceBusy()) throw new CLIError("BUSY", "Drawing is being edited as Markdown or synchronized.");
|
||||
if (liveIdentity(view) !== identity) throw new CLIError("STALE_REVISION", "Drawing changed during preparation.", "expectedRevision", "Read the new scene before retrying.");
|
||||
};
|
||||
check(); ea.setView(view);
|
||||
const originalElements = new Map(structuredClone(api.getSceneElements()).map(element => [element.id, element]));
|
||||
ea.copyViewElementsToEAforEditing([...originalElements.values()]);
|
||||
if (ea.getElements().length > 5000) throw new CLIError("INVALID_INPUT", "Structured edits are limited to 5000 scene elements.");
|
||||
const lib = plugin.getCLIRuntime(), elementsMap = new Map(ea.getElements().map(element => [element.id, element])), idMap: Record<string, string> = {}, groupIds: string[] = [];
|
||||
const resolve = (value: unknown) => {
|
||||
const id = string(value, "id"), actual = Object.hasOwn(idMap, id) ? idMap[id] : id;
|
||||
const element = Object.hasOwn(ea.elementsDict, actual) ? ea.elementsDict[actual] : null;
|
||||
if (!element || element.isDeleted) throw new CLIError("NOT_FOUND", "Operation references a missing or deleted element.", "id");
|
||||
return element;
|
||||
};
|
||||
const recordId = (local: unknown, actual: string) => {
|
||||
if (!actual) throw new CLIError("DEPENDENCY_UNAVAILABLE", "EA could not construct this element.");
|
||||
if (local !== undefined) {
|
||||
const key = string(local, "id");
|
||||
if (["__proto__", "constructor", "prototype"].includes(key)) throw new CLIError("INVALID_INPUT", "Reserved local ID.", "id");
|
||||
if (Object.hasOwn(idMap, key) || (Object.hasOwn(ea.elementsDict, key) && key !== actual)) throw new CLIError("INVALID_INPUT", "Local ID conflicts with another ID.", "id");
|
||||
idMap[key] = actual;
|
||||
}
|
||||
};
|
||||
for (const operation of operations) {
|
||||
check();
|
||||
const op = operation.op;
|
||||
if (op === "add") {
|
||||
const batch = constructBatch(operation.elements, lib, Object.keys(ea.elementsDict));
|
||||
for (const [local, actual] of Object.entries(batch.idMap)) recordId(local, actual);
|
||||
ea.copyViewElementsToEAforEditing(batch.elements);
|
||||
for (const element of batch.elements) elementsMap.set(element.id, element);
|
||||
} else if (op === "update") {
|
||||
const element = resolve(operation.id), set = { ...object(operation.set) };
|
||||
if (element.type !== "text" && ["text", "fontSize", "fontFamily", "textAlign", "verticalAlign"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Text fields require a text element; edit its bound label ID.", "set");
|
||||
if (["arrow", "line", "freedraw"].includes(element.type) && ["width", "height"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Linear resizing requires a trusted EA script.", "set");
|
||||
if ("text" in set) { set.rawText = set.text; set.originalText = set.text; }
|
||||
lib.mutateElement(element, elementsMap, set);
|
||||
} else if (op === "delete") {
|
||||
const removed = new Set(ids(operation.ids).map(id => resolve(id).id));
|
||||
for (const id of [...removed]) {
|
||||
const element = ea.elementsDict[id];
|
||||
for (const bound of element.boundElements ?? []) if (bound.type === "text") removed.add(bound.id);
|
||||
if (element.type === "frame") {
|
||||
const children = ea.getElements().filter(child => child.frameId === id && !child.isDeleted);
|
||||
if (children.length && operation.children === undefined) throw new CLIError("INVALID_INPUT", "Nonempty frame deletion requires children=delete or detach.", "children");
|
||||
for (const child of children) {
|
||||
if (operation.children === "delete") removed.add(child.id);
|
||||
else lib.mutateElement(child, elementsMap, { frameId: null });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const element of ea.getElements()) {
|
||||
if (removed.has(element.id)) {
|
||||
if (element.type === "image" && model.markdownImages.has(element.fileId)) throw new CLIError("INTERACTION_REQUIRED", "Markdown-image deletion requires a trusted EA script.");
|
||||
lib.mutateElement(element, elementsMap, { isDeleted: true });
|
||||
} else {
|
||||
if (element.boundElements?.some(bound => removed.has(bound.id))) lib.mutateElement(element, elementsMap, { boundElements: element.boundElements.filter(bound => !removed.has(bound.id)) });
|
||||
if (element.type === "arrow") {
|
||||
if (removed.has(element.startBinding?.elementId)) lib.mutateElement(element, elementsMap, { startBinding: null });
|
||||
if (removed.has(element.endBinding?.elementId)) lib.mutateElement(element, elementsMap, { endBinding: null });
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (op === "connect") {
|
||||
const from = resolve(operation.from), to = resolve(operation.to);
|
||||
if (![from.type, to.type].every(type => ["rectangle", "ellipse", "diamond", "text", "stickynote"].includes(type))) throw new CLIError("INVALID_INPUT", "Connect requires two bindable shapes.");
|
||||
recordId(operation.id, ea.connectObjects(from.id, side(operation.fromSide), to.id, side(operation.toSide)));
|
||||
} else if (op === "group") {
|
||||
const members = ids(operation.ids).map(id => resolve(id)), previous = members.map(element => [...element.groupIds]);
|
||||
const groupId = ea.addToGroup(members.map(element => element.id)); groupIds.push(groupId);
|
||||
members.forEach((element, index) => {
|
||||
element.groupIds = previous[index];
|
||||
lib.mutateElement(element, elementsMap, { groupIds: [...previous[index], groupId] });
|
||||
});
|
||||
}
|
||||
else if (op === "ungroup") {
|
||||
for (const id of ids(operation.ids)) {
|
||||
const element = resolve(id);
|
||||
lib.mutateElement(element, elementsMap, { groupIds: element.groupIds.filter(group => group !== operation.groupId) });
|
||||
}
|
||||
} else if (op === "image") {
|
||||
const path = vaultPath(operation.asset, "asset"), asset = plugin.app.vault.getFileByPath(path);
|
||||
if (!asset || !["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(asset.extension.toLowerCase())) throw new CLIError("INVALID_INPUT", "Image requires an existing vault raster image or SVG.", "asset");
|
||||
if (asset.stat.size > 16 * 1024 * 1024) throw new CLIError("INVALID_INPUT", "Image exceeds 16 MiB.", "asset");
|
||||
const stat = JSON.stringify(asset.stat);
|
||||
const actual = await ea.addImage(number(operation.x, "x", 0, -1000000, 1000000), number(operation.y, "y", 0, -1000000, 1000000), asset, boolean(operation.scale, "scale", true));
|
||||
if (plugin.app.vault.getFileByPath(path) !== asset || JSON.stringify(asset.stat) !== stat) throw new CLIError("STALE_REVISION", "Image changed during preparation.", "asset");
|
||||
recordId(operation.id, actual);
|
||||
} else if (op === "latex") {
|
||||
const extras = plugin.extrasGateway.getAPI();
|
||||
if (!extras?.features.isActive("mathjax") || !plugin.extrasGateway.checkVersion("mathjax", extras).valid) throw new CLIError("DEPENDENCY_UNAVAILABLE", "Enable a compatible Excalidraw Extras MathJax feature before using latex.");
|
||||
recordId(operation.id, await ea.addLaTex(number(operation.x, "x", 0, -1000000, 1000000), number(operation.y, "y", 0, -1000000, 1000000), string(operation.text, "text"), number(operation.scaleX, "scaleX", 1, 0.1, 4), number(operation.scaleY, "scaleY", 1, 0.1, 4), { throwOnError: true }));
|
||||
}
|
||||
}
|
||||
check();
|
||||
if (ea.getElements().length > 5000) throw new CLIError("INVALID_INPUT", "Result exceeds 5000 scene elements.");
|
||||
for (const element of ea.getElements()) {
|
||||
const original = originalElements.get(element.id);
|
||||
// EA grouping/connection helpers also edit relationships directly. Ensure
|
||||
// every changed existing element participates in versioned scene updates.
|
||||
if (original && element.version <= original.version && JSON.stringify(element) !== JSON.stringify(original)) lib.mutateElement(element, elementsMap, { groupIds: [...element.groupIds] });
|
||||
}
|
||||
const outcome: Partial<ExcalidrawCLIResult> = { target: { vault: plugin.app.vault.getName(), path: file.path, viewId: view.id }, mutation: "not-applied", persistence: "not-applicable" };
|
||||
try {
|
||||
if (!await view.addElements({ newElements: ea.getElements(), images: ea.imagesDict, newElementsOnTop: true, save: false, validateBeforePublish: () => { check(); outcome.mutation = "unknown"; outcome.persistence = "unknown"; } })) throw new CLIError("NOT_READY", "View could not publish the edit.");
|
||||
outcome.mutation = "applied"; outcome.persistence = "unsaved";
|
||||
const acceptedRevision = cli.targets.revision(view);
|
||||
const saved = await view.saveWithOutcome();
|
||||
const sameTarget = cli.isCurrent() && view.file === file && view.excalidrawAPI === api && !view.isClosingOrMigrating();
|
||||
const durable = sameTarget && saved.acknowledgedRevision !== null && saved.acknowledgedRevision >= saved.requestedRevision;
|
||||
outcome.persistence = durable ? "saved" : ["failed", "skipped"].includes(saved.status) ? "unsaved" : "unknown";
|
||||
if (!durable) throw new CLIError("SAVE_FAILED", "Edit was published but its save was not acknowledged.", undefined, "Keep the drawing open and save/read back before further edits.", outcome);
|
||||
return { ...outcome, revision: sameTarget ? cli.targets.revision(view) : acceptedRevision, data: { idMap, groupIds, acceptedRevision, saveStatus: saved.status }, warnings: saved.currentRevision > saved.acknowledgedRevision ? ["A later edit is still unsaved; this receipt acknowledges the applied edit only. Read a fresh revision before continuing."] : [] };
|
||||
} catch (error) {
|
||||
if (error instanceof CLIError && outcome.mutation === "not-applied") throw error;
|
||||
throw new CLIError(error instanceof CLIError ? error.code : "SAVE_FAILED", error instanceof CLIError ? error.message : "Edit may have been published before an interrupted save.", undefined, "Read back the drawing; preserve unsaved work before retrying.", outcome);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/** One descriptor registry for native flags, schemas and progressive help. */
|
||||
import type { CLICommand } from "src/types/excalidrawCliTypes";
|
||||
import type { CliFlags } from "src/types/obsidianCli";
|
||||
|
||||
interface CommandDescriptor {
|
||||
description: string;
|
||||
fields: Record<string, string>;
|
||||
writes?: boolean;
|
||||
example: Record<string, unknown>;
|
||||
}
|
||||
const target = { path: "Exact drawing path including extension", view: "View ID from open/read; required for multiple views" };
|
||||
const source = { source: "auto (default), live, or disk" };
|
||||
const page = { offset: "Integer offset, default 0", limit: "Integer page size, default 50; maximum 200", revision: "Required when offset is greater than zero" };
|
||||
const write = { requestId: "Unique caller ID; same effective request is replayed for 15 minutes in this session" };
|
||||
|
||||
export const CLI_COMMANDS: Record<CLICommand, CommandDescriptor> = {
|
||||
help: { description: "Discover commands and the authoring workflow", fields: {}, example: {} },
|
||||
status: { description: "Inspect readiness and available runtime capabilities", fields: {}, example: {} },
|
||||
schema: { description: "Inspect one command's fields and side effects", fields: { action: "Command to describe" }, example: { action: "create" } },
|
||||
api: { description: "Search EA documentation or the supported installed Lib reference", fields: { surface: "ea (default) or lib", name: "Exact method name", query: "Case-insensitive search" }, example: { surface: "ea", name: "addText" } },
|
||||
list: { description: "List drawing paths without opening them", fields: { folder: "Optional exact folder", ...page }, example: { limit: 50 } },
|
||||
read: { description: "Read an explicit live or disk drawing; no base64 asset bodies", fields: { ...target, ...source, ...page, detail: "summary (default) or elements", selectedOnly: "Live selection only", ids: "JSON array of element IDs" }, example: { path: "Drawings/Flow.excalidraw.md", source: "live", detail: "elements" } },
|
||||
open: { description: "Explicitly open a ready Excalidraw view; normal drawing scripts can run", fields: { ...target }, example: { path: "Drawings/Flow.excalidraw.md" } },
|
||||
create: { description: "Create an exact new path using EA's serializer; never overwrite", fields: { ...write, path: target.path, template: "Optional exact drawing template; no picker", elements: "Validated batch of installed Excalidraw skeletons" }, writes: true, example: { requestId: "flow-1", path: "Drawings/Flow.excalidraw.md", elements: [{ id: "a", type: "rectangle", x: 0, y: 0, width: 200, height: 80, label: { text: "Start" } }] } },
|
||||
apply: { description: "Apply one bounded edit to an explicit live revision and report its save outcome", fields: { ...write, ...target, expectedRevision: "Fresh revision from live read", operations: "Array of add, update, delete, connect, group, ungroup, image, or latex operations" }, writes: true, example: { requestId: "flow-2", path: "Drawings/Flow.excalidraw.md", expectedRevision: "from-read", operations: [{ op: "update", id: "actual-id", set: { backgroundColor: "#e7f5ff" } }] } },
|
||||
export: { description: "Render SVG/PNG to an explicit vault path; existing remote assets may use normal network permissions", fields: { ...write, ...target, ...source, out: "Exact .svg or .png output path", overwrite: "Explicit permission to replace an existing output", selectedOnly: "Live selection only", theme: "light or dark", padding: "0 to 200, default 10", scale: "PNG scale 0.1 to 4, default 1", area: "JSON object with x,y,width,height" }, writes: true, example: { requestId: "preview-1", path: "Drawings/Flow.excalidraw.md", out: "Drawings/Flow.png" } },
|
||||
script: { description: "Run an explicitly trusted local EA script once; arbitrary code is not transactional or sandboxed", fields: { ...write, ...target, script: "Exact existing .md or enabled .js script path", trusted: "Required explicit true", args: "JSON passed as utils.input; never interpolated into code" }, writes: true, example: { requestId: "script-1", script: "Scripts/Inspect.md", trusted: true, args: {} } },
|
||||
skill: { description: "Return offline portable agent instructions without installing them", fields: { format: "json (default) or markdown for native stdout" }, example: { format: "markdown" } },
|
||||
result: { description: "Look up a session-only operation receipt after a client timeout", fields: { requestId: write.requestId }, example: { requestId: "flow-2" } },
|
||||
};
|
||||
|
||||
/** Native flags describe transport fields as well as command-specific inputs. */
|
||||
export function commandFlags(command: CLICommand): CliFlags {
|
||||
return Object.fromEntries(Object.entries({ ...CLI_COMMANDS[command].fields, input: "Vault-relative UTF-8 JSON request; exclusive with json", json: "Small inline JSON request; exclusive with input" }).map(([key, description]) => [key, {
|
||||
description, ...(["trusted", "overwrite", "selectedOnly"].includes(key) ? {} : { value: `<${key}>` }),
|
||||
}]));
|
||||
}
|
||||
|
||||
/** Progressive Lib help describes an intentional supported subset, not reflection. */
|
||||
export const CLI_LIB_HELP = [
|
||||
{ name: "convertToExcalidrawElements", signature: "convertToExcalidrawElements(skeletons, {regenerateIds})", description: "Construct a batch with labels, bindings and frames. It is not an existing-scene patcher." },
|
||||
{ name: "getCommonBounds", signature: "getCommonBounds(elements)", description: "Return [minX,minY,maxX,maxY]." },
|
||||
{ name: "mutateElement", signature: "mutateElement(element, elementsMap, updates)", description: "Maintain element versions/nonces when mutating an EA workbench copy." },
|
||||
{ name: "exportToSvg", signature: "exportToSvg({elements, appState, files})", description: "Low-level SVG export; prefer the CLI export action for Obsidian assets." },
|
||||
{ name: "exportToBlob", signature: "exportToBlob({elements, appState, files, mimeType})", description: "Low-level raster export; prefer CLI export for Obsidian assets." },
|
||||
];
|
||||
|
||||
/** Portable instructions available offline; never written to agent configuration automatically. */
|
||||
export const CLI_SKILL = `---
|
||||
name: obsidian-excalidraw-cli
|
||||
description: Create, inspect, edit and render Obsidian Excalidraw drawings through the running app's native CLI.
|
||||
---
|
||||
|
||||
Use a local terminal with Obsidian running and CLI enabled (API 1.12.2+).
|
||||
Always put vault="<name or ID>" before the command. Native root: obsidian-excalidraw-plugin.
|
||||
Start with obsidian vault="<vault>" obsidian-excalidraw-plugin:help, then :schema action=create.
|
||||
All results use apiVersion 1. Check ok, mutation and persistence; process exit zero alone does not prove success.
|
||||
Put large requests in a visible vault-relative JSON file and pass input="<file>". Inline json is for small requests.
|
||||
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
|
||||
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
|
||||
Loop: :read source=live detail=elements → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
|
||||
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY only after read-back.
|
||||
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
|
||||
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
|
||||
:result requestId=<id> recovers a receipt after lost stdout. Receipts expire after 15 minutes/reload; unknown outcome requires read-back before another write.
|
||||
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
|
||||
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
|
||||
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
|
||||
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Remote assets follow existing permissions.
|
||||
Use :schema for exact fields, operation limits, and runnable examples. Do not edit compressed drawing Markdown directly or install another Excalidraw CLI.
|
||||
`;
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Validate and construct request-local skeleton batches using the installed fork. */
|
||||
import type { ExcalidrawElementSkeleton } from "@zsviczian/excalidraw/types/element/src/transform";
|
||||
import type { Packages } from "src/types/types";
|
||||
import { nanoid } from "src/constants/constants";
|
||||
import { CLIError, boolean, number, object, string } from "./cliProtocol";
|
||||
|
||||
export const CLI_SHAPES = ["rectangle", "ellipse", "diamond", "text", "arrow", "line", "frame", "stickynote"];
|
||||
export const CLI_STYLE_FIELDS = ["x", "y", "width", "height", "angle", "strokeColor", "backgroundColor", "fillStyle", "strokeWidth", "strokeStyle", "roughness", "opacity", "locked", "link", "text", "fontSize", "fontFamily", "textAlign", "verticalAlign"];
|
||||
const skeletonFields = new Set([...CLI_STYLE_FIELDS, "id", "type", "roundness", "label", "points", "start", "end", "startArrowhead", "endArrowhead", "children", "name"]);
|
||||
const arrowheads = ["arrow", "bar", "circle", "circle_outline", "triangle", "triangle_outline", "diamond", "diamond_outline"];
|
||||
|
||||
/** Rejects unsupported keys before staging any work. */
|
||||
export function fields(value: Record<string, unknown>, allowed: readonly string[]): void {
|
||||
for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new CLIError("INVALID_INPUT", "Unsupported field; use a trusted EA script for advanced relationships or metadata.", key);
|
||||
}
|
||||
|
||||
/** Validates the finite assignable style/geometry surface shared by batches and updates. */
|
||||
export function validateStyle(value: Record<string, unknown>): void {
|
||||
for (const key of ["x", "y", "angle"]) if (value[key] !== undefined) number(value[key], key, 0, -1_000_000, 1_000_000);
|
||||
for (const key of ["width", "height"]) if (value[key] !== undefined) number(value[key], key, 0, 0, 100_000);
|
||||
for (const [key, min, max] of [["opacity", 0, 100], ["strokeWidth", 0, 100], ["roughness", 0, 3], ["fontSize", 1, 1000], ["fontFamily", 1, 10]] as const) {
|
||||
if (value[key] !== undefined) number(value[key], key, min, min, max);
|
||||
}
|
||||
if (value.fontFamily !== undefined && !Number.isInteger(value.fontFamily)) throw new CLIError("INVALID_INPUT", "Font family must be an installed numeric family ID.", "fontFamily");
|
||||
for (const [key, options] of Object.entries({ fillStyle: ["hachure", "cross-hatch", "solid", "zigzag"], strokeStyle: ["solid", "dashed", "dotted"], textAlign: ["left", "center", "right"], verticalAlign: ["top", "middle", "bottom"] })) {
|
||||
if (value[key] !== undefined && !options.includes(string(value[key], key))) throw new CLIError("INVALID_INPUT", "Unknown option.", key);
|
||||
}
|
||||
for (const key of ["strokeColor", "backgroundColor"]) if (value[key] !== undefined) string(value[key], key);
|
||||
if (value.text !== undefined && (typeof value.text !== "string" || value.text.length > 10000)) throw new CLIError("INVALID_INPUT", "Text must be a string of at most 10000 characters.", "text");
|
||||
if (value.link !== undefined && value.link !== null) string(value.link, "link");
|
||||
if (value.locked !== undefined) boolean(value.locked, "locked");
|
||||
}
|
||||
|
||||
/** Complete validation precedes conversion; relationship references are batch-local. */
|
||||
export function validateBatch(input: unknown): Record<string, unknown>[] {
|
||||
if (!Array.isArray(input) || input.length > 500) throw new CLIError("INVALID_INPUT", "Expected at most 500 skeletons.", "elements");
|
||||
const batch = input.map((entry, index) => {
|
||||
const element = object(entry, `elements[${index}]`);
|
||||
fields(element, [...skeletonFields]); validateStyle(element);
|
||||
if (!CLI_SHAPES.includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "Unsupported skeleton type.", "type");
|
||||
if (element.type !== "frame") { number(element.x, "x", 0, -1_000_000, 1_000_000); number(element.y, "y", 0, -1_000_000, 1_000_000); }
|
||||
if (element.type === "text" && typeof element.text !== "string") throw new CLIError("INVALID_INPUT", "Text skeleton requires text.", "text");
|
||||
if (element.type !== "text" && ["text", "fontSize", "fontFamily", "textAlign", "verticalAlign"].some(key => key in element)) throw new CLIError("INVALID_INPUT", "Use label for container text and its font options.", "label");
|
||||
if (element.id !== undefined && ["__proto__", "constructor", "prototype"].includes(string(element.id, "id"))) throw new CLIError("INVALID_INPUT", "Reserved local ID.", "id");
|
||||
if (element.name !== undefined) {
|
||||
if (element.type !== "frame") throw new CLIError("INVALID_INPUT", "Name requires a frame.", "name");
|
||||
if (element.name !== null) string(element.name, "name");
|
||||
}
|
||||
if (element.label !== undefined) {
|
||||
if (!["rectangle", "ellipse", "diamond", "arrow", "stickynote"].includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "This element cannot have a bound label.", "label");
|
||||
const label = object(element.label, "label");
|
||||
fields(label, ["text", "fontSize", "fontFamily", "textAlign", "verticalAlign"]); validateStyle(label);
|
||||
if (typeof label.text !== "string") throw new CLIError("INVALID_INPUT", "Label requires text.", "label.text");
|
||||
}
|
||||
if (element.roundness !== undefined && element.roundness !== null) {
|
||||
const roundness = object(element.roundness, "roundness"); fields(roundness, ["type", "value"]);
|
||||
if (typeof roundness.type !== "number" || ![1, 2, 3].includes(roundness.type)) throw new CLIError("INVALID_INPUT", "Unknown roundness type.", "roundness");
|
||||
if (roundness.value !== undefined) number(roundness.value, "roundness.value", 0, 0, 1000);
|
||||
}
|
||||
if (element.points !== undefined) {
|
||||
if (!["line", "arrow"].includes(string(element.type, "type")) || !Array.isArray(element.points) || element.points.length < 2 || element.points.length > 100) throw new CLIError("INVALID_INPUT", "Expected 2–100 linear points.", "points");
|
||||
for (const point of element.points) {
|
||||
if (!Array.isArray(point) || point.length !== 2) throw new CLIError("INVALID_INPUT", "Expected [x,y] point.", "points");
|
||||
point.forEach(coordinate => number(coordinate, "points", 0, -100000, 100000));
|
||||
}
|
||||
}
|
||||
for (const key of ["startArrowhead", "endArrowhead"]) if (element[key] !== undefined) {
|
||||
if (!["arrow", "line"].includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "Arrowheads require a linear element.", key);
|
||||
if (element[key] !== null && !arrowheads.includes(string(element[key], key))) throw new CLIError("INVALID_INPUT", "Unknown arrowhead.", key);
|
||||
}
|
||||
return element;
|
||||
});
|
||||
const labels = batch.map((element, index) => element.id === undefined ? `@${index}` : string(element.id, "id"));
|
||||
if (new Set(labels).size !== labels.length) throw new CLIError("INVALID_INPUT", "Duplicate skeleton IDs.", "id");
|
||||
const parented = new Set<string>();
|
||||
for (const element of batch) {
|
||||
for (const key of ["start", "end"]) if (element[key] !== undefined) {
|
||||
if (element.type !== "arrow") throw new CLIError("INVALID_INPUT", "Bindings require an arrow.", key);
|
||||
const endpoint = object(element[key], key); fields(endpoint, ["id"]);
|
||||
const id = string(endpoint.id, `${key}.id`), target = batch[labels.indexOf(id)];
|
||||
if (!target || !["rectangle", "ellipse", "diamond", "text", "stickynote"].includes(string(target.type, "type"))) throw new CLIError("INVALID_INPUT", "Binding must reference a bindable element in this batch; use connect for existing elements.", key);
|
||||
}
|
||||
if (element.type === "frame") {
|
||||
if (!Array.isArray(element.children)) throw new CLIError("INVALID_INPUT", "Frame requires children IDs.", "children");
|
||||
for (const value of element.children) {
|
||||
const id = string(value, "children"), target = batch[labels.indexOf(id)];
|
||||
if (!target || target.type === "frame" || parented.has(id)) throw new CLIError("INVALID_INPUT", "Frame child is missing, repeated or a nested frame.", "children");
|
||||
parented.add(id);
|
||||
}
|
||||
} else if (element.children !== undefined) throw new CLIError("INVALID_INPUT", "Children require a frame.", "children");
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
/** Maps every requested/generated ID before the installed converter creates labels and bindings. */
|
||||
export function constructBatch(input: unknown, lib: NonNullable<Packages["excalidrawLib"]>, occupied: Iterable<string> = []) {
|
||||
const batch = validateBatch(input), used = new Set(occupied);
|
||||
const allocate = () => { let id: string; do { id = nanoid(); } while (used.has(id)); used.add(id); return id; };
|
||||
const idMap: Record<string, string> = {};
|
||||
const mapped: Record<string, unknown>[] = batch.map((element, index) => {
|
||||
const label = element.id === undefined ? `@${index}` : string(element.id, "id");
|
||||
const id = allocate(); idMap[label] = id;
|
||||
return { ...element, id, ...(element.type !== "frame" ? { x: element.x ?? 0, y: element.y ?? 0 } : {}) };
|
||||
});
|
||||
for (const element of mapped) {
|
||||
if (element.label) element.label = { ...object(element.label), id: allocate() };
|
||||
for (const key of ["start", "end"]) if (element[key]) element[key] = { id: idMap[string(object(element[key]).id, "id")] };
|
||||
if (element.children) element.children = (element.children as string[]).map(id => idMap[id]);
|
||||
}
|
||||
// Runtime guards above establish the canonical fork skeleton union. No persisted
|
||||
// identity/version/asset fields are accepted at this untrusted boundary.
|
||||
const elements = lib.convertToExcalidrawElements(mapped as unknown as ExcalidrawElementSkeleton[], { regenerateIds: false });
|
||||
const ids = new Set(elements.map(element => element.id));
|
||||
if (ids.size !== elements.length || Object.values(idMap).some(id => !ids.has(id)) || elements.some(element => !CLI_SHAPES.includes(element.type) || element.id.length !== 8)) throw new CLIError("INVALID_INPUT", "Converter did not preserve the requested batch identities.", "elements");
|
||||
for (const element of elements) {
|
||||
validateStyle(element);
|
||||
const references = [...(element.boundElements ?? []).map(bound => bound.id), element.frameId,
|
||||
...(element.type === "text" ? [element.containerId] : []),
|
||||
...(element.type === "arrow" ? [element.startBinding?.elementId, element.endBinding?.elementId] : [])].filter(Boolean);
|
||||
if (references.some(id => !ids.has(id))) throw new CLIError("INVALID_INPUT", "Converter returned a dangling relationship.", "elements");
|
||||
}
|
||||
return { elements, idMap };
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/** Visual feedback through the existing asset loader and rendering helpers. */
|
||||
import { TFile } from "obsidian";
|
||||
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
|
||||
import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import { EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader";
|
||||
import { getTemplate } from "src/utils/excalidrawAutomateUtils";
|
||||
import { getSVG, getPNG } from "src/utils/utils";
|
||||
import { checkAndCreateFolder } from "src/utils/fileUtils";
|
||||
import { createExportAreaAnchor, getElementsIntersectionArea } from "src/utils/excalidrawElementUtils";
|
||||
import { cropPNGBlob } from "src/utils/imageExportUtils";
|
||||
import { CLIError, boolean, number, object, string } from "./cliProtocol";
|
||||
import { diskSnapshot, drawingFile, drawingView, liveIdentity } from "./cliTarget";
|
||||
import { fields } from "./cliElements";
|
||||
|
||||
/** Bounds limit allocation before rendering, including any area intermediate. */
|
||||
export function exportBounds(width: number, height: number, scale: number): void {
|
||||
if (![width, height].every(value => Number.isFinite(value) && value > 0 && value * scale <= 16384) || width * height * scale * scale > 16000000) throw new CLIError("INVALID_INPUT", "Export exceeds 16 million pixels or 16384 pixels on either side.");
|
||||
}
|
||||
|
||||
/** Does not save the source drawing; writes only an explicitly named image artifact. */
|
||||
export async function exportDrawing(cli: ExcalidrawCLI, request: Record<string, unknown>, out: string): Promise<Partial<ExcalidrawCLIResult>> {
|
||||
const plugin = cli.plugin, vault = plugin.app.vault, file = drawingFile(plugin, request.path);
|
||||
const format = out.endsWith(".svg") ? "svg" : out.endsWith(".png") ? "png" : null;
|
||||
if (!format || out === file.path) throw new CLIError("INVALID_INPUT", "Output requires an explicit .svg or .png path distinct from the source.", "out");
|
||||
const overwrite = boolean(request.overwrite, "overwrite"), selectedOnly = boolean(request.selectedOnly, "selectedOnly");
|
||||
const source = request.source === undefined ? "auto" : string(request.source, "source");
|
||||
if (!["auto", "live", "disk"].includes(source)) throw new CLIError("INVALID_INPUT", "Expected auto, live or disk.", "source");
|
||||
if (source === "disk" && request.view !== undefined) throw new CLIError("INVALID_INPUT", "Disk export cannot select a view.", "view");
|
||||
const view = source === "disk" ? null : drawingView(plugin, file, request.view);
|
||||
if ((source === "live" || selectedOnly) && !view) throw new CLIError("NOT_READY", "Export requires a live view for this source/selection.");
|
||||
const originalOutput = vault.getAbstractFileByPath(out);
|
||||
if (originalOutput && (!(originalOutput instanceof TFile) || !overwrite)) throw new CLIError("ALREADY_EXISTS", "Output exists; replacing a file requires overwrite=true.", "out");
|
||||
const outputStat = originalOutput instanceof TFile ? JSON.stringify(originalOutput.stat) : null;
|
||||
const checkOutput = () => {
|
||||
if (!cli.isCurrent()) throw new CLIError("NOT_READY", "Plugin session ended.");
|
||||
const current = vault.getAbstractFileByPath(out);
|
||||
if (current !== originalOutput || (current instanceof TFile && JSON.stringify(current.stat) !== outputStat)) throw new CLIError("STALE_REVISION", "Output changed during rendering.", "out");
|
||||
};
|
||||
const padding = number(request.padding, "padding", 10, 0, 200), scale = number(request.scale, "scale", 1, 0.1, 4);
|
||||
const theme = request.theme === undefined ? undefined : string(request.theme, "theme");
|
||||
if (theme !== undefined && theme !== "light" && theme !== "dark") throw new CLIError("INVALID_INPUT", "Expected light or dark.", "theme");
|
||||
const area = request.area === undefined ? undefined : object(request.area, "area");
|
||||
if (area) { fields(area, ["x", "y", "width", "height"]); for (const key of ["x", "y", "width", "height"]) if (area[key] === undefined) throw new CLIError("INVALID_INPUT", "Area requires x, y, width and height.", "area"); }
|
||||
const rectangle = area ? { x: number(area.x, "area.x", 0, -1000000, 1000000), y: number(area.y, "area.y", 0, -1000000, 1000000), width: number(area.width, "area.width", 1, 0.1, 100000), height: number(area.height, "area.height", 1, 0.1, 100000) } : undefined;
|
||||
const api = view?.excalidrawAPI;
|
||||
let identity = view ? liveIdentity(view) : null;
|
||||
// Existing view asset loading can finish independently; never publish a
|
||||
// placeholder export as complete or initiate optional-feature consent UI.
|
||||
if (view) {
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const missing = view.getScene(selectedOnly).elements.some(element => !element.isDeleted && element.type === "image" && !api.getFiles()[element.fileId]?.dataURL);
|
||||
if (!missing) break;
|
||||
if (!cli.isCurrent() || view.file !== file || view.excalidrawAPI !== api || view.isClosingOrMigrating()) throw new CLIError("STALE_REVISION", "Target changed while waiting for assets.");
|
||||
await new Promise(resolve => window.setTimeout(resolve, 50));
|
||||
}
|
||||
identity = liveIdentity(view);
|
||||
}
|
||||
const snapshot = view ? null : await diskSnapshot(plugin, file, cli.isCurrent);
|
||||
const revision = view ? cli.targets.revision(view, identity) : snapshot.revision;
|
||||
const checkSource = async () => {
|
||||
checkOutput();
|
||||
if (vault.getFileByPath(file.path) !== file) throw new CLIError("STALE_REVISION", "Source file identity changed.");
|
||||
if (view) {
|
||||
if (view.file !== file || view.excalidrawAPI !== api || liveIdentity(view) !== identity) throw new CLIError("STALE_REVISION", "Live scene changed during rendering.");
|
||||
} else if ((await diskSnapshot(plugin, file, cli.isCurrent)).revision !== revision) throw new CLIError("STALE_REVISION", "Disk drawing changed during rendering.");
|
||||
checkOutput();
|
||||
};
|
||||
let scene = view ? structuredClone(view.getScene(selectedOnly)) : { ...snapshot.scene };
|
||||
const assetPaths = view ? scene.elements.filter(element => element.type === "image").map(element => view.excalidrawData.getFile(element.fileId)?.file?.path) : snapshot.assetPaths;
|
||||
if (assetPaths.includes(out)) throw new CLIError("INVALID_INPUT", "Output cannot replace a referenced source asset.", "out");
|
||||
if (!view) {
|
||||
for (const feature of snapshot.dependencies) {
|
||||
const extras = plugin.extrasGateway.getAPI();
|
||||
if (!extras?.features.isActive(feature) || !plugin.extrasGateway.checkVersion(feature, extras).valid) throw new CLIError("DEPENDENCY_UNAVAILABLE", `Enable compatible Excalidraw Extras ${feature} before rendering this drawing.`);
|
||||
}
|
||||
if (plugin.app.metadataCache.getFirstLinkpathDest(file.path, "") !== file) throw new CLIError("NOT_FOUND", "Exact source is unavailable to the asset loader.");
|
||||
const loader = new EmbeddedFilesLoader(plugin, theme === undefined ? undefined : theme === "dark");
|
||||
const releaseCleanup = cli.registerOperationCleanup(() => { loader.terminate = true; });
|
||||
try {
|
||||
const template = await getTemplate(plugin, file.path, true, loader, 0);
|
||||
if (!["idle", "completed"].includes(loader.terminalState)) throw new CLIError("ASSETS_UNAVAILABLE", "Drawing assets did not finish loading.");
|
||||
scene = { ...scene, elements: template.elements, files: template.files, appState: template.appState };
|
||||
} finally { releaseCleanup(); loader.terminate = true; }
|
||||
await checkSource();
|
||||
}
|
||||
scene.elements = scene.elements.filter(element => !element.isDeleted);
|
||||
if (scene.elements.length > 5000) throw new CLIError("INVALID_INPUT", "Exports are limited to 5000 elements.");
|
||||
if (scene.elements.some(element => element.type === "image" && (element.status === "error" || !scene.files?.[element.fileId]?.dataURL || scene.files[element.fileId].dataURL.startsWith("http")))) throw new CLIError("ASSETS_UNAVAILABLE", "An image is missing or undecoded; retry when its normal loader is ready.");
|
||||
if (rectangle) scene.elements = [...getElementsIntersectionArea(scene.elements, rectangle, { includeBoundElements: true }), createExportAreaAnchor(rectangle)];
|
||||
if (!scene.elements.length) throw new CLIError("INVALID_INPUT", "Nothing to export.");
|
||||
const [minX, minY, maxX, maxY] = plugin.getCLIRuntime().getCommonBounds(scene.elements);
|
||||
exportBounds(maxX - minX + padding * 2, maxY - minY + padding * 2, format === "png" ? scale : 1);
|
||||
if (rectangle) exportBounds(rectangle.width + padding * 2, rectangle.height + padding * 2, format === "png" ? scale : 1);
|
||||
const effectiveTheme = theme ?? (view ? view.getViewExportTheme() : scene.appState.theme ?? "light");
|
||||
scene.appState = { ...scene.appState, theme: effectiveTheme as "light" | "dark", exportEmbedScene: false };
|
||||
const settings = { withBackground: true, withTheme: true, isMask: false };
|
||||
let binary: ArrayBuffer, width: number, height: number;
|
||||
if (format === "svg") {
|
||||
const svg = await getSVG(scene, settings, padding, file);
|
||||
if (!svg) throw new CLIError("EXPORT_FAILED", "SVG rendering failed.");
|
||||
if (rectangle) {
|
||||
svg.setAttribute("viewBox", `${rectangle.x - minX} ${rectangle.y - minY} ${rectangle.width + padding * 2} ${rectangle.height + padding * 2}`);
|
||||
svg.setAttribute("width", `${rectangle.width + padding * 2}`); svg.setAttribute("height", `${rectangle.height + padding * 2}`);
|
||||
}
|
||||
width = Number(svg.getAttribute("width")); height = Number(svg.getAttribute("height"));
|
||||
binary = new TextEncoder().encode(svg.outerHTML).buffer;
|
||||
} else {
|
||||
let png = await getPNG(scene, settings, padding, scale);
|
||||
if (!png) throw new CLIError("EXPORT_FAILED", "PNG rendering failed.");
|
||||
if (rectangle) png = await cropPNGBlob(png, { x: (rectangle.x - minX) * scale, y: (rectangle.y - minY) * scale, width: (rectangle.width + padding * 2) * scale, height: (rectangle.height + padding * 2) * scale });
|
||||
binary = await png.arrayBuffer(); const header = new DataView(binary);
|
||||
width = header.getUint32(16); height = header.getUint32(20);
|
||||
}
|
||||
exportBounds(width, height, 1);
|
||||
if (binary.byteLength > 32 * 1024 * 1024) throw new CLIError("EXPORT_FAILED", "Artifact exceeds 32 MiB.");
|
||||
await checkSource();
|
||||
await checkAndCreateFolder(out.split("/").slice(0, -1).join("/"));
|
||||
await checkSource();
|
||||
try {
|
||||
if (originalOutput instanceof TFile) await vault.modifyBinary(originalOutput, binary);
|
||||
else await vault.createBinary(out, binary);
|
||||
} catch {
|
||||
throw new CLIError("OUTCOME_UNKNOWN", "Artifact write was interrupted.", "out", "Inspect this exact output before retrying.", { mutation: "unknown", persistence: "unknown" });
|
||||
}
|
||||
return { target: { vault: vault.getName(), path: file.path, ...(view ? { viewId: view.id } : {}) }, revision, mutation: "applied", persistence: "saved", data: { path: out, format, bytes: binary.byteLength, width, height, source: view ? "live" : "disk", theme: effectiveTheme, revision }, warnings: [] };
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/** Small, dependency-free guards for the finite CLI protocol. */
|
||||
import type { CLIJSON, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
|
||||
export const CLI_INPUT_LIMIT = 2 * 1024 * 1024;
|
||||
export const CLI_OUTPUT_LIMIT = 512 * 1024;
|
||||
|
||||
/** A protocol failure with actionable recovery, without a private stack trace. */
|
||||
export class CLIError extends Error {
|
||||
public constructor(public readonly code: string, message: string, public readonly field?: string,
|
||||
public readonly recovery = "Read the command schema and correct the request.",
|
||||
public readonly outcome: Partial<ExcalidrawCLIResult> = {}) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects arrays and primitives where an object is required. */
|
||||
export function object(value: unknown, field = "request"): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new CLIError("INVALID_INPUT", "Expected an object.", field);
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Validates and copies plain JSON, excluding prototypes, nonfinite values and oversized output. */
|
||||
export function jsonValue(value: unknown, limit = CLI_OUTPUT_LIMIT): CLIJSON {
|
||||
const visit = (item: unknown, depth: number): void => {
|
||||
if (depth > 30) throw new CLIError("INVALID_INPUT", "JSON nesting exceeds 30 levels.");
|
||||
if (item === null || typeof item === "string" || typeof item === "boolean") return;
|
||||
if (typeof item === "number" && Number.isFinite(item)) return;
|
||||
if (Array.isArray(item)) { item.forEach(entry => visit(entry, depth + 1)); return; }
|
||||
if (item && typeof item === "object") {
|
||||
const prototype: unknown = Object.getPrototypeOf(item);
|
||||
const constructor: unknown = prototype && Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
||||
if (prototype !== null && (typeof constructor !== "function" || constructor.name !== "Object")) throw new CLIError("INVALID_INPUT", "Expected a plain JSON object.");
|
||||
for (const [key, entry] of Object.entries(item)) {
|
||||
if (["__proto__", "prototype", "constructor"].includes(key)) throw new CLIError("INVALID_INPUT", "Unsafe JSON key.", key);
|
||||
visit(entry, depth + 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new CLIError("INVALID_INPUT", "Expected plain, finite JSON values.");
|
||||
};
|
||||
try { visit(value, 0); } catch (error) {
|
||||
if (error instanceof CLIError) throw error;
|
||||
throw new CLIError("INVALID_INPUT", "Cannot serialize the supplied value.");
|
||||
}
|
||||
const encoded = JSON.stringify(value);
|
||||
if (new TextEncoder().encode(encoded).length > limit) throw new CLIError("INVALID_INPUT", "JSON exceeds the size limit.");
|
||||
return JSON.parse(encoded) as CLIJSON;
|
||||
}
|
||||
|
||||
/** Exact vault paths; normalization must never silently reinterpret a target. */
|
||||
export function vaultPath(value: unknown, field = "path"): string {
|
||||
if (typeof value !== "string" || !value || value.length > 1024 || /[\\:#|?*<>]/.test(value) || [...value].some(char => char.charCodeAt(0) < 32) ||
|
||||
value.startsWith("/") || value.split("/").some(part => !part || part === "." || part === ".." || part.startsWith("."))) {
|
||||
throw new CLIError("INVALID_INPUT", "Expected an exact, visible vault-relative path.", field);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Requires a string without truthy/falsy coercion. */
|
||||
export function string(value: unknown, field: string): string {
|
||||
if (typeof value !== "string" || !value || value.length > 10000) throw new CLIError("INVALID_INPUT", "Expected a nonempty string.", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Bounded numeric option, preserving deliberate zero values. */
|
||||
export function number(value: unknown, field: string, fallback: number, min: number, max: number): number {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) throw new CLIError("INVALID_INPUT", "Number is outside the permitted range.", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Strict boolean option; native bare flags normalize before this guard. */
|
||||
export function boolean(value: unknown, field: string, fallback = false): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "boolean") throw new CLIError("INVALID_INPUT", "Expected a boolean.", field);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Stable key ordering for retries; compare complete values rather than a weak hash. */
|
||||
export function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
||||
if (value && typeof value === "object") return `{${Object.entries(object(value)).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(",")}}`;
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
/** Compact content revision, using two independent 32-bit streams and length. */
|
||||
export function fingerprint(text: string): string {
|
||||
let a = 2166136261, b = 5381;
|
||||
for (let i = 0; i < text.length; i++) { const c = text.charCodeAt(i); a = Math.imul(a ^ c, 16777619); b = Math.imul(b, 33) ^ c; }
|
||||
return `${text.length.toString(36)}-${(a >>> 0).toString(36)}-${(b >>> 0).toString(36)}`;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Compact machine schemas generated from the command and operation registries. */
|
||||
import type { CLICommand } from "src/types/excalidrawCliTypes";
|
||||
import { CLI_COMMANDS } from "./cliCommands";
|
||||
import { CLI_OPERATION_FIELDS } from "./cliApply";
|
||||
import { CLI_SHAPES, CLI_STYLE_FIELDS } from "./cliElements";
|
||||
|
||||
const required: Partial<Record<CLICommand, string[]>> = {
|
||||
schema: ["action"], read: ["path"], open: ["path"], create: ["requestId", "path"],
|
||||
apply: ["requestId", "path", "expectedRevision", "operations"], export: ["requestId", "path", "out"],
|
||||
script: ["requestId", "script", "trusted"], result: ["requestId"],
|
||||
};
|
||||
const operationRequired: Record<string, string[]> = {
|
||||
add: ["elements"], update: ["id", "set"], delete: ["ids"], connect: ["from", "to"],
|
||||
group: ["ids"], ungroup: ["ids", "groupId"], image: ["asset"], latex: ["text"],
|
||||
};
|
||||
function property(name: string): Record<string, unknown> {
|
||||
if (["x", "y", "width", "height", "angle", "fontSize", "fontFamily", "opacity", "strokeWidth", "roughness", "offset", "limit", "padding", "scale", "scaleX", "scaleY"].includes(name)) return { type: "number" };
|
||||
if (["overwrite", "trusted", "selectedOnly", "locked"].includes(name)) return { type: "boolean" };
|
||||
if (name === "ids" || name === "children") return { type: "array", items: { type: "string" } };
|
||||
if (name === "elements") return { type: "array", maxItems: 500, items: { $ref: "#/$defs/skeleton" } };
|
||||
if (name === "operations") return { type: "array", minItems: 1, maxItems: 100, items: { $ref: "#/$defs/operation" } };
|
||||
if (name === "set") return { type: "object", additionalProperties: false, properties: Object.fromEntries(CLI_STYLE_FIELDS.map(key => [key, property(key)])) };
|
||||
if (name === "args") return {};
|
||||
if (["area", "roundness", "label", "start", "end"].includes(name)) return { type: "object" };
|
||||
if (name === "points") return { type: "array", minItems: 2, maxItems: 100, items: { type: "array", minItems: 2, maxItems: 2, items: { type: "number" } } };
|
||||
if (name === "link") return { type: ["string", "null"] };
|
||||
return { type: "string" };
|
||||
}
|
||||
|
||||
/** Runtime guards remain authoritative for geometry, relationship and lifecycle constraints. */
|
||||
export function commandSchema(command: CLICommand): Record<string, unknown> {
|
||||
const skeletonFields = [...CLI_STYLE_FIELDS, "id", "type", "roundness", "label", "points", "start", "end", "startArrowhead", "endArrowhead", "children", "name"];
|
||||
return {
|
||||
$schema: "https://json-schema.org/draft/2020-12/schema", type: "object", additionalProperties: false,
|
||||
required: ["apiVersion", "command", ...(required[command] ?? [])],
|
||||
properties: { apiVersion: { const: 1 }, command: { const: command },
|
||||
...Object.fromEntries(Object.entries(CLI_COMMANDS[command].fields).map(([name, description]) => [name, { ...property(name), description }])),
|
||||
requestId: { type: "string", pattern: "^[A-Za-z0-9_.-]{1,80}$" },
|
||||
},
|
||||
...(command === "create" || command === "apply" ? { $defs: {
|
||||
skeleton: { type: "object", required: ["type"], additionalProperties: false, properties: { ...Object.fromEntries(skeletonFields.map(name => [name, property(name)])), type: { enum: CLI_SHAPES }, roundness: { type: ["object", "null"] }, name: { type: ["string", "null"] }, startArrowhead: { type: ["string", "null"] }, endArrowhead: { type: ["string", "null"] } } },
|
||||
operation: { oneOf: Object.entries(CLI_OPERATION_FIELDS).map(([op, fields]) => ({ type: "object", required: ["op", ...operationRequired[op]], additionalProperties: false, properties: { op: { const: op }, ...Object.fromEntries(fields.map(name => [name, name === "children" ? { enum: ["delete", "detach"] } : property(name)])) } })) },
|
||||
} } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/** Explicit trust and source identity for one-shot existing local scripts. */
|
||||
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
|
||||
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import { CLIError, boolean, jsonValue, vaultPath } from "./cliProtocol";
|
||||
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
|
||||
|
||||
/** Source content participates in the effective request identity, including cached scripts. */
|
||||
export async function prepareScript(cli: ExcalidrawCLI, request: Record<string, unknown>) {
|
||||
if (!boolean(request.trusted, "trusted")) throw new CLIError("TRUST_REQUIRED", "Local script execution requires trusted=true.", "trusted");
|
||||
const plugin = cli.plugin, path = vaultPath(request.script, "script"), file = plugin.app.vault.getFileByPath(path);
|
||||
if (!file || (file.extension !== "md" && !(file.extension === "js" && plugin.settings.allowJavaScriptFiles))) throw new CLIError("INVALID_INPUT", "Choose an existing Markdown script or enable JavaScript scripts.", "script");
|
||||
if (file.stat.size > 1024 * 1024) throw new CLIError("INVALID_INPUT", "Script source exceeds 1 MiB.", "script");
|
||||
const source = await plugin.app.vault.read(file);
|
||||
if (!cli.isCurrent()) throw new CLIError("NOT_READY", "Plugin session ended.");
|
||||
return { file, source, stat: JSON.stringify(file.stat) };
|
||||
}
|
||||
export type PreparedCLIScript = Awaited<ReturnType<typeof prepareScript>>;
|
||||
|
||||
/** Completion only acknowledges script execution; arbitrary writes require script-owned await/save discipline. */
|
||||
export async function executeScript(cli: ExcalidrawCLI, request: Record<string, unknown>, prepared: PreparedCLIScript, ea: ExcalidrawAutomate): Promise<Partial<ExcalidrawCLIResult>> {
|
||||
const plugin = cli.plugin;
|
||||
if (request.path === undefined && request.view !== undefined) throw new CLIError("INVALID_INPUT", "A view requires an explicit drawing path.", "view");
|
||||
const drawing = request.path === undefined ? null : drawingFile(plugin, request.path);
|
||||
const view = drawing ? drawingView(plugin, drawing, request.view) : null;
|
||||
if (drawing && !view) throw new CLIError("NOT_READY", "Targeted scripts require an open live drawing.");
|
||||
const api = view?.excalidrawAPI, identity = view ? liveIdentity(view) : null;
|
||||
const check = () => {
|
||||
if (!cli.isCurrent() || plugin.app.vault.getFileByPath(prepared.file.path) !== prepared.file || JSON.stringify(prepared.file.stat) !== prepared.stat) throw new CLIError("STALE_REVISION", "Script or plugin identity changed before execution.");
|
||||
if (view && (view.file !== drawing || view.excalidrawAPI !== api || liveIdentity(view) !== identity)) throw new CLIError("STALE_REVISION", "Drawing changed before script execution.");
|
||||
if (view && (view.isSameFileEditingActive() || view.isPersistenceBusy())) throw new CLIError("BUSY", "Drawing is being edited as Markdown or synchronized.");
|
||||
};
|
||||
check(); if (view) ea.setView(view);
|
||||
const outcome: Partial<ExcalidrawCLIResult> = { mutation: "unknown", persistence: "unknown", ...(view ? { target: { vault: plugin.app.vault.getName(), path: drawing.path, viewId: view.id } } : {}) };
|
||||
let started = false;
|
||||
try {
|
||||
const value = await plugin.scriptEngine.executeScriptFileForCLI(prepared.file, view ?? undefined, ea, request.args ?? null, plugin.getCLIRuntime(), prepared.source, () => { check(); started = true; });
|
||||
return { ...outcome, data: jsonValue(value === undefined ? null : value), warnings: ["Script completion does not verify drawing persistence. Trusted scripts must await their writes and saves."] };
|
||||
} catch (error) {
|
||||
if (!started && error instanceof CLIError) throw error;
|
||||
const interaction = error instanceof Error && error.message.startsWith("INTERACTION_REQUIRED:");
|
||||
throw new CLIError(interaction ? "INTERACTION_REQUIRED" : started ? "OUTCOME_UNKNOWN" : "SCRIPT_FAILED", interaction ? error.message : "Script execution or result serialization failed.", undefined, "Inspect drawing/output before retrying; script side effects cannot be rolled back.", started ? outcome : {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/** Explicit drawing/view ownership and revision snapshots for CLI operations. */
|
||||
import { TFile } from "obsidian";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { ExcalidrawData } from "src/shared/ExcalidrawData";
|
||||
import { getTextMode } from "src/shared/TextMode";
|
||||
import { VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
|
||||
import { CLIError, fingerprint, vaultPath } from "./cliProtocol";
|
||||
|
||||
/** Resolves an exact file; never uses basename/link lookup or the active drawing. */
|
||||
export function drawingFile(plugin: ExcalidrawPlugin, value: unknown): TFile {
|
||||
const path = vaultPath(value);
|
||||
const file = plugin.app.vault.getFileByPath(path);
|
||||
if (!file) throw new CLIError("NOT_FOUND", "Drawing does not exist.", "path");
|
||||
if (!plugin.isExcalidrawFile(file)) throw new CLIError("NOT_EXCALIDRAW", "Target is not an Excalidraw drawing.", "path");
|
||||
return file;
|
||||
}
|
||||
|
||||
/** Includes unavailable views so auto cannot silently read stale disk content. */
|
||||
export function drawingViews(plugin: ExcalidrawPlugin, file: TFile): ExcalidrawView[] {
|
||||
return plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).map(leaf => leaf.view)
|
||||
.filter((view): view is ExcalidrawView => view instanceof ExcalidrawView && view.file === file);
|
||||
}
|
||||
|
||||
/** Rejects ambiguous or explicitly missing identities instead of choosing the first view. */
|
||||
export function drawingView(plugin: ExcalidrawPlugin, file: TFile, id?: unknown): ExcalidrawView | null {
|
||||
const views = drawingViews(plugin, file);
|
||||
if (id !== undefined) {
|
||||
if (typeof id !== "string") throw new CLIError("INVALID_INPUT", "Expected a view ID.", "view");
|
||||
const view = views.find(view => view.id === id);
|
||||
if (!view) throw new CLIError("NOT_FOUND", "Requested view is no longer available.", "view", "Open the drawing and read its current view ID.");
|
||||
return view;
|
||||
}
|
||||
if (views.length > 1) throw new CLIError("AMBIGUOUS_TARGET", `Choose a view: ${views.map(view => view.id).join(", ")}`, "view", "Pass an explicit view ID.");
|
||||
return views[0] ?? null;
|
||||
}
|
||||
|
||||
/** Captures authoritative scene, document metadata, assets and settings for optimistic checks. */
|
||||
export function liveIdentity(view: ExcalidrawView): string {
|
||||
if (!view.excalidrawAPI || !view.isLoaded || view.isClosingOrMigrating()) throw new CLIError("BUSY", "Drawing is loading, closing or migrating.", "path");
|
||||
const model = view.excalidrawData;
|
||||
const exportData = model.exportPreparedSaveData();
|
||||
return JSON.stringify({
|
||||
elements: view.excalidrawAPI.getSceneElementsIncludingDeleted(),
|
||||
files: view.excalidrawAPI.getFiles(),
|
||||
scene: view.getScene()?.appState,
|
||||
sourceText: view.data,
|
||||
textMode: view.textMode,
|
||||
text: [...model.textElements],
|
||||
filesMetadata: exportData ? [...exportData.files] : null,
|
||||
markdown: [...model.markdownImages], equations: [...model.equations], mermaids: [...model.mermaids],
|
||||
stat: view.file.stat, settings: view.plugin.settings,
|
||||
});
|
||||
}
|
||||
|
||||
/** API identity changes invalidate old revisions even when the content is identical. */
|
||||
export class CLITargets {
|
||||
private generations = new WeakMap<object, number>();
|
||||
private nextGeneration = 1;
|
||||
public constructor(private readonly session: string) {}
|
||||
|
||||
/** Opaque session/view/runtime/content marker. */
|
||||
public revision(view: ExcalidrawView, identity = liveIdentity(view)): string {
|
||||
const api = view.excalidrawAPI;
|
||||
if (!this.generations.has(api)) this.generations.set(api, this.nextGeneration++);
|
||||
return `${this.session}:${view.id}:${this.generations.get(api)}:${fingerprint(identity)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Parses a single exact Vault read with the existing drawing model and releases it. */
|
||||
export async function diskSnapshot(plugin: ExcalidrawPlugin, file: TFile, isCurrent: () => boolean) {
|
||||
if (file.stat.size > 16 * 1024 * 1024) throw new CLIError("INVALID_INPUT", "Drawing exceeds the 16 MiB inspection limit.", "path");
|
||||
const text = await plugin.app.vault.read(file);
|
||||
if (!isCurrent()) throw new CLIError("NOT_READY", "Plugin session ended.");
|
||||
const data = new ExcalidrawData(plugin);
|
||||
try {
|
||||
if (file.extension === "excalidraw") await data.loadLegacyData(text, file);
|
||||
else if (!await data.loadData(text, file, getTextMode(text), isCurrent)) throw new CLIError("NOT_READY", "Drawing could not be loaded.");
|
||||
if (!isCurrent() || plugin.app.vault.getFileByPath(file.path) !== file || !data.scene) throw new CLIError("NOT_READY", "Drawing changed while reading.");
|
||||
return { scene: structuredClone(data.scene), revision: `disk:${fingerprint(text)}`,
|
||||
dependencies: [...(data.equations.size ? ["mathjax" as const] : []), ...(data.mermaids.size ? ["mermaid" as const] : [])],
|
||||
assetPaths: data.scene.elements.filter(element => element.type === "image").map(element => data.getFile(element.fileId)?.file?.path).filter(Boolean),
|
||||
};
|
||||
} finally { data.destroy(); }
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export type {
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
export type { Point } from "src/types/types";
|
||||
export type { MathJaxRenderOptions } from "src/types/mathJaxTypes";
|
||||
export type { ExcalidrawCLIRequest, ExcalidrawCLIResult, CLICommand, CLIJSON } from "src/types/excalidrawCliTypes";
|
||||
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
|
||||
try {
|
||||
return window.ExcalidrawAutomate.getAPI(view);
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { ExcalidrawExtrasGateway } from "../utils/ExcalidrawExtrasGateway";
|
||||
import { ExcalidrawCLI } from "./managers/ExcalidrawCLI";
|
||||
import type { ExcalidrawCLIRequest, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import type { ExactDrawingCreationOptions } from "src/types/drawingCreationTypes";
|
||||
import {
|
||||
TFile,
|
||||
Plugin,
|
||||
@@ -163,6 +166,7 @@ const EXCALIDRAW_EXTERNAL_GET_LABEL_KEY_SET = new Set<keyof typeof en>(
|
||||
);
|
||||
|
||||
export default class ExcalidrawPlugin extends Plugin {
|
||||
private cli: ExcalidrawCLI;
|
||||
public extrasGateway: ExcalidrawExtrasGateway;
|
||||
private fileManager: PluginFileManager;
|
||||
private observerManager: ObserverManager;
|
||||
@@ -298,6 +302,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
//isExcalidraw function is used already is already used by MarkdownPostProcessor in onLoad before onLayoutReady
|
||||
this.fileManager = new PluginFileManager(this);
|
||||
this.cli = new ExcalidrawCLI(this);
|
||||
this.settingsManager = new PluginSettingsManager(this);
|
||||
this.footerSafeAreaManager = new FooterSafeAreaManager(this);
|
||||
this.fontManager = new FontManager(this, () =>
|
||||
@@ -310,6 +315,16 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}*/
|
||||
}
|
||||
|
||||
/** Executes the versioned CLI protocol without selecting an active drawing. */
|
||||
public executeCLI(request: ExcalidrawCLIRequest): Promise<ExcalidrawCLIResult> {
|
||||
return this.cli.execute(request);
|
||||
}
|
||||
|
||||
/** Returns the existing shared runtime for CLI construction and trusted scripts. */
|
||||
public getCLIRuntime(): NonNullable<Packages["excalidrawLib"]> {
|
||||
return this.packageManager.getRuntimePackage().excalidrawLib;
|
||||
}
|
||||
|
||||
/** Records a startup timing event without changing lifecycle ordering. */
|
||||
public logStartupEvent(message: string): void {
|
||||
this.startupTimer.logEvent(message, this.loadTimestamp);
|
||||
@@ -454,6 +469,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
console.error("Error initializing Excalidraw Automate", e);
|
||||
}
|
||||
this.logStartupEvent("Excalidraw Automate initialized");
|
||||
this.cli.initialize();
|
||||
|
||||
try {
|
||||
//Licat: Are you registering your post processors in onLayoutReady? You should register them in onload instead
|
||||
@@ -940,6 +956,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
onunload() {
|
||||
this.cli.destroy();
|
||||
ExcalidrawSidepanelView.onPluginUnload(this);
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
excalidrawViews.forEach(({ leaf }) => {
|
||||
@@ -1121,13 +1138,17 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
filename: string,
|
||||
foldername?: string,
|
||||
initData?: string,
|
||||
exact?: ExactDrawingCreationOptions,
|
||||
): Promise<TFile> {
|
||||
const file = await this.fileManager.createDrawing(
|
||||
filename,
|
||||
foldername,
|
||||
initData,
|
||||
exact,
|
||||
);
|
||||
|
||||
if (exact) return file;
|
||||
|
||||
if (Date.now() - this.loadTimestamp > 1) {
|
||||
//2000) {
|
||||
const filecount = this.app.vault
|
||||
|
||||
@@ -93,6 +93,7 @@ import { PaneTarget } from "src/types/utilTypes";
|
||||
import { decompress } from "src/utils/sceneDataUtils";
|
||||
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
|
||||
import { isMarkdownImageElement } from "src/shared/MarkdownImage";
|
||||
import { CLIInstructions } from "src/shared/Dialogs/CLIInstructions";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
@@ -141,6 +142,11 @@ export class CommandManager {
|
||||
}
|
||||
|
||||
public initialize() {
|
||||
this.plugin.addCommand({
|
||||
id: "show-cli-instructions",
|
||||
name: t("CLI_HELP"),
|
||||
callback: () => new CLIInstructions(this.app).open(),
|
||||
});
|
||||
try {
|
||||
this.taskbone = new Taskbone(this.plugin);
|
||||
this.registerCommands();
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
/** Plugin-owned native CLI registration, JSON dispatcher and bounded session receipts. */
|
||||
import { Platform, requireApiVersion } from "obsidian";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import type { CLICommand, ExcalidrawCLIRequest, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import type { CliData, ObsidianCliRuntime } from "src/types/obsidianCli";
|
||||
import { EXCALIDRAW_AUTOMATE_INFO } from "src/shared/Dialogs/SuggesterInfo";
|
||||
import { CLI_COMMANDS, CLI_LIB_HELP, CLI_SKILL, commandFlags } from "src/core/cli/cliCommands";
|
||||
import { CLIError, CLI_INPUT_LIMIT, boolean, canonical, fingerprint, jsonValue, number, object, string, vaultPath } from "src/core/cli/cliProtocol";
|
||||
import { CLITargets, diskSnapshot, drawingFile, drawingView, drawingViews, liveIdentity } from "src/core/cli/cliTarget";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { CLIWriteCommands } from "src/core/cli/CLIWriteCommands";
|
||||
import { prepareScript } from "src/core/cli/cliScripts";
|
||||
import { commandSchema } from "src/core/cli/cliSchema";
|
||||
import { nanoid } from "src/constants/constants";
|
||||
|
||||
type Receipt = { fingerprint: string; result: ExcalidrawCLIResult; finishedAt?: number };
|
||||
|
||||
/** Optional CLI; all registrations use Plugin's own unload cleanup. */
|
||||
export class ExcalidrawCLI {
|
||||
public readonly session = `${nanoid()}${nanoid()}${nanoid()}${nanoid()}`;
|
||||
public readonly targets = new CLITargets(this.session);
|
||||
private alive = true;
|
||||
private receipts = new Map<string, Receipt>();
|
||||
private operationCleanups = new Set<() => void>();
|
||||
private writes = new CLIWriteCommands(this);
|
||||
public constructor(public readonly plugin: ExcalidrawPlugin) {}
|
||||
|
||||
/** Skips both older APIs and runtimes without the optional registration method. */
|
||||
public initialize(): void {
|
||||
const runtime = this.plugin as ExcalidrawPlugin & Partial<ObsidianCliRuntime>;
|
||||
if (!Platform.isDesktop || !requireApiVersion("1.12.2") || typeof runtime.registerCliHandler !== "function") return;
|
||||
runtime.registerCliHandler(this.plugin.manifest.id, t("CLI_DESCRIPTION"), commandFlags("help"), params => this.native("help", params));
|
||||
for (const action of Object.keys(CLI_COMMANDS) as CLICommand[]) {
|
||||
runtime.registerCliHandler(`${this.plugin.manifest.id}:${action}`, `${t("CLI_DESCRIPTION")} — ${action}`, commandFlags(action), params => this.native(action, params));
|
||||
}
|
||||
}
|
||||
|
||||
/** Invalidates awaited continuations before plugin/view teardown begins. */
|
||||
public destroy(): void {
|
||||
this.alive = false;
|
||||
for (const cleanup of this.operationCleanups) cleanup();
|
||||
this.operationCleanups.clear(); this.writes.destroy(); this.receipts.clear();
|
||||
}
|
||||
|
||||
/** Stops request-owned loaders at unload without retaining completed operations. */
|
||||
public registerOperationCleanup(cleanup: () => void): () => void {
|
||||
if (!this.alive) cleanup();
|
||||
else this.operationCleanups.add(cleanup);
|
||||
return () => this.operationCleanups.delete(cleanup);
|
||||
}
|
||||
|
||||
/** Whether a continuation still belongs to this plugin session. */
|
||||
public isCurrent = (): boolean => this.alive;
|
||||
|
||||
private async native(command: CLICommand, flags: CliData): Promise<string> {
|
||||
try {
|
||||
const params: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(flags)) {
|
||||
if (key === "vault") continue; // Native transport selects the vault before dispatch.
|
||||
if (["overwrite", "selectedOnly", "trusted"].includes(key)) {
|
||||
if (!["true", "false"].includes(value)) throw new CLIError("INVALID_INPUT", "Expected true or false.", key);
|
||||
params[key] = value === "true";
|
||||
} else if (["offset", "limit", "scale", "padding"].includes(key)) params[key] = Number(value);
|
||||
else if (["ids", "args", "area", "elements", "operations"].includes(key)) params[key] = JSON.parse(value);
|
||||
else params[key] = value;
|
||||
}
|
||||
if (params.input !== undefined && params.json !== undefined) throw new CLIError("INVALID_INPUT", "Choose input or json, not both.");
|
||||
let payload: Record<string, unknown> = {};
|
||||
if (params.input !== undefined || params.json !== undefined) {
|
||||
let content: string;
|
||||
if (params.input !== undefined) {
|
||||
const path = vaultPath(params.input, "input");
|
||||
const file = this.plugin.app.vault.getFileByPath(path);
|
||||
if (!file) throw new CLIError("NOT_FOUND", "Input file does not exist.", "input");
|
||||
if (file.stat.size > CLI_INPUT_LIMIT) throw new CLIError("INVALID_INPUT", "Input exceeds 2 MiB.", "input");
|
||||
content = await this.plugin.app.vault.read(file);
|
||||
} else content = string(params.json, "json");
|
||||
if (new TextEncoder().encode(content).length > CLI_INPUT_LIMIT) throw new CLIError("INVALID_INPUT", "Input exceeds 2 MiB.");
|
||||
payload = object(JSON.parse(content));
|
||||
if (payload.apiVersion !== 1) throw new CLIError("INVALID_INPUT", "JSON requests require apiVersion 1.", "apiVersion");
|
||||
}
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (key === "input" || key === "json") continue;
|
||||
if (key in payload && canonical(payload[key]) !== canonical(value)) throw new CLIError("INVALID_INPUT", "Flag and JSON values disagree.", key);
|
||||
payload[key] = value;
|
||||
}
|
||||
if (payload.command !== undefined && payload.command !== command) throw new CLIError("INVALID_INPUT", "JSON command disagrees with native action.", "command");
|
||||
if (params.input !== undefined && payload.out === params.input) throw new CLIError("INVALID_INPUT", "Output cannot replace the request file.", "out");
|
||||
const result = await this.execute({ ...payload, apiVersion: 1, command });
|
||||
return result.ok && command === "skill" && payload.format === "markdown" ? CLI_SKILL : JSON.stringify(result);
|
||||
} catch (error) { return JSON.stringify(this.failure(command, undefined, error)); }
|
||||
}
|
||||
|
||||
private base(command: string, requestId?: string): ExcalidrawCLIResult {
|
||||
return { apiVersion: 1, session: this.session, command, ...(requestId ? { requestId } : {}), status: "completed", ok: true, persistence: "not-applicable", mutation: "not-applied", warnings: [] };
|
||||
}
|
||||
|
||||
private failure(command: string, requestId: string | undefined, error: unknown): ExcalidrawCLIResult {
|
||||
const failure = error instanceof CLIError ? error : new CLIError("INVALID_INPUT", "Request could not be completed.");
|
||||
return { ...this.base(command, requestId), ...failure.outcome, status: "failed", ok: false,
|
||||
error: { code: failure.code, message: failure.message, ...(failure.field ? { field: failure.field } : {}), recovery: failure.recovery } };
|
||||
}
|
||||
|
||||
/** Shared native/in-process protocol; does not inspect the caller's EA workbench or target. */
|
||||
public async execute(input: ExcalidrawCLIRequest): Promise<ExcalidrawCLIResult> {
|
||||
let command = "unknown", requestId: string | undefined;
|
||||
try {
|
||||
const request = object(jsonValue(input, CLI_INPUT_LIMIT));
|
||||
command = string(request.command, "command");
|
||||
requestId = request.requestId === undefined ? undefined : string(request.requestId, "requestId");
|
||||
if (!this.alive) throw new CLIError("NOT_READY", "Plugin session ended.");
|
||||
if (request.apiVersion !== 1) throw new CLIError("INVALID_INPUT", "Expected apiVersion 1.", "apiVersion");
|
||||
if (!Object.hasOwn(CLI_COMMANDS, command)) throw new CLIError("UNSUPPORTED_COMMAND", "Unknown CLI command.", "command");
|
||||
const action = command as CLICommand;
|
||||
const descriptor = CLI_COMMANDS[action];
|
||||
for (const key of Object.keys(request)) {
|
||||
if (!["apiVersion", "command", "requestId"].includes(key) && !Object.hasOwn(descriptor.fields, key)) throw new CLIError("INVALID_INPUT", "Unknown command field.", key);
|
||||
}
|
||||
this.purgeReceipts();
|
||||
if (action === "result") {
|
||||
const receipt = this.receipts.get(string(request.requestId, "requestId"));
|
||||
if (!receipt) throw new CLIError("OUTCOME_UNKNOWN", "Receipt expired, is unknown, or belongs to an earlier session.", "requestId", "Read back drawing/output before sending a new write.");
|
||||
return structuredClone(receipt.result);
|
||||
}
|
||||
const preparedScript = action === "script" ? await prepareScript(this, request) : undefined;
|
||||
if (descriptor.writes) {
|
||||
requestId = string(request.requestId, "requestId");
|
||||
if (!/^[\w.-]{1,80}$/.test(requestId)) throw new CLIError("INVALID_INPUT", "Use 1–80 letters, digits, underscores, dots or hyphens.", "requestId");
|
||||
const signature = canonical(preparedScript ? { request, source: preparedScript.source } : request);
|
||||
const existing = this.receipts.get(requestId);
|
||||
if (existing) {
|
||||
if (existing.fingerprint !== signature) throw new CLIError("INVALID_INPUT", "requestId was already used for different content.", "requestId");
|
||||
return structuredClone(existing.result);
|
||||
}
|
||||
if (this.receipts.size >= 128) throw new CLIError("BUSY", "Session receipt capacity is exhausted.", "requestId", "Wait for completed receipts to expire; do not retry writes with a new ID blindly.");
|
||||
this.receipts.set(requestId, { fingerprint: signature, result: { ...this.base(action, requestId), status: "pending", ok: null, persistence: "unknown" } });
|
||||
}
|
||||
let result: ExcalidrawCLIResult;
|
||||
try {
|
||||
const output = descriptor.writes ? await this.writes.execute(action, request, preparedScript) : { data: await this.dispatch(action, request) };
|
||||
try { result = { ...this.base(action, requestId), ...output, data: jsonValue(output.data ?? null) }; }
|
||||
catch { throw new CLIError("OUTCOME_UNKNOWN", "Result could not be serialized after execution.", undefined, "Read back the target before another write.", { ...output, data: null }); }
|
||||
}
|
||||
catch (error) { result = this.failure(action, requestId, error); }
|
||||
if (descriptor.writes && this.alive) {
|
||||
const receipt = this.receipts.get(requestId);
|
||||
receipt.result = result; receipt.finishedAt = Date.now();
|
||||
}
|
||||
return result;
|
||||
} catch (error) { return this.failure(command, requestId, error); }
|
||||
}
|
||||
|
||||
private purgeReceipts(): void {
|
||||
for (const [id, receipt] of this.receipts) if (receipt.finishedAt && Date.now() - receipt.finishedAt > 15 * 60 * 1000) this.receipts.delete(id);
|
||||
}
|
||||
|
||||
private async dispatch(command: CLICommand, request: Record<string, unknown>): Promise<unknown> {
|
||||
const plugin = this.plugin;
|
||||
if (command === "help") return { commands: CLI_COMMANDS, input: "input=<vault-relative JSON file> or json=<small JSON>", next: `obsidian vault="${plugin.app.vault.getName()}" ${plugin.manifest.id}:schema action=create` };
|
||||
if (command === "skill") {
|
||||
if (request.format !== undefined && !["json", "markdown"].includes(string(request.format, "format"))) throw new CLIError("INVALID_INPUT", "Expected json or markdown.", "format");
|
||||
return { markdown: CLI_SKILL };
|
||||
}
|
||||
if (command === "status") return { apiVersion: 1, nativeCLI: Platform.isDesktop && requireApiVersion("1.12.2") && typeof (plugin as ExcalidrawPlugin & Partial<ObsidianCliRuntime>).registerCliHandler === "function", ready: plugin.isReady, vault: plugin.app.vault.getName(), version: plugin.manifest.version, converter: plugin.isReady && typeof plugin.getCLIRuntime().convertToExcalidrawElements === "function", receiptTTLSeconds: 900, receiptCapacity: 128 };
|
||||
if (command === "schema") {
|
||||
const action = string(request.action, "action");
|
||||
if (!Object.hasOwn(CLI_COMMANDS, action)) throw new CLIError("UNSUPPORTED_COMMAND", "Unknown action.", "action");
|
||||
return { apiVersion: 1, command: action, ...CLI_COMMANDS[action as CLICommand], jsonSchema: commandSchema(action as CLICommand), inputLimitBytes: CLI_INPUT_LIMIT, example: { apiVersion: 1, command: action, ...CLI_COMMANDS[action as CLICommand].example } };
|
||||
}
|
||||
if (command === "api") {
|
||||
const surface = request.surface === undefined ? "ea" : string(request.surface, "surface");
|
||||
if (!["ea", "lib"].includes(surface)) throw new CLIError("INVALID_INPUT", "Expected ea or lib.", "surface");
|
||||
const query = (request.name === undefined && request.query === undefined ? "" : string(request.name ?? request.query, "query")).toLowerCase();
|
||||
const entries = surface === "ea" ? EXCALIDRAW_AUTOMATE_INFO.map(entry => ({ name: entry.field, signature: entry.code ?? "", description: (entry.desc ?? "").replace(/<br\s*\/?\s*>/gi, "\n").replace(/<[^>]*>/g, "") })) : CLI_LIB_HELP;
|
||||
return { surface, subset: surface === "lib", entries: entries.filter(entry => request.name ? entry.name.toLowerCase() === query : `${entry.name} ${entry.description}`.toLowerCase().includes(query)).slice(0, 20) };
|
||||
}
|
||||
if (!plugin.isReady) throw new CLIError("NOT_READY", "Excalidraw is still initializing.", undefined, "Retry status after startup.");
|
||||
if (command === "list") {
|
||||
const folder = request.folder === undefined ? null : vaultPath(request.folder, "folder");
|
||||
const paths = plugin.app.vault.getFiles().filter(file => plugin.isExcalidrawFile(file) && (!folder || file.path.startsWith(`${folder}/`))).map(file => file.path).sort();
|
||||
return this.page(paths, request, `list:${this.session}:${fingerprint(canonical(paths))}`, "paths");
|
||||
}
|
||||
if (command !== "read" && command !== "open") throw new CLIError("DEPENDENCY_UNAVAILABLE", "This command is not implemented yet.");
|
||||
const file = drawingFile(plugin, request.path);
|
||||
const view = request.source === "disk" ? null : drawingView(plugin, file, request.view);
|
||||
if (command === "open") {
|
||||
if (view) { liveIdentity(view); return { path: file.path, viewId: view.id, revision: this.targets.revision(view) }; }
|
||||
const leaf = plugin.app.workspace.getLeaf("tab");
|
||||
await leaf.setViewState({ type: "excalidraw", state: { file: file.path }, active: true });
|
||||
await plugin.app.workspace.revealLeaf(leaf);
|
||||
for (let i = 0; i < 200; i++) {
|
||||
if (!this.alive) throw new CLIError("NOT_READY", "Plugin session ended.");
|
||||
const opened = drawingViews(plugin, file).find(candidate => candidate.leaf === leaf);
|
||||
if (opened?.isLoaded && opened.excalidrawAPI && !opened.isClosingOrMigrating()) return { path: file.path, viewId: opened.id, revision: this.targets.revision(opened) };
|
||||
await new Promise(resolve => window.setTimeout(resolve, 50));
|
||||
}
|
||||
throw new CLIError("NOT_READY", "Drawing did not become ready within 10 seconds.", "path");
|
||||
}
|
||||
const source = request.source === undefined ? "auto" : string(request.source, "source");
|
||||
if (!["auto", "live", "disk"].includes(source)) throw new CLIError("INVALID_INPUT", "Expected auto, live or disk.", "source");
|
||||
const useLive = source !== "disk" && view !== null;
|
||||
if (source === "live" && !view) throw new CLIError("NOT_READY", "Drawing has no live view.", "path", "Use open first.");
|
||||
if (source === "disk" && request.view !== undefined) throw new CLIError("INVALID_INPUT", "A disk read cannot select a view.", "view");
|
||||
if (!useLive && boolean(request.selectedOnly, "selectedOnly")) throw new CLIError("INVALID_INPUT", "Selection requires a live source.", "selectedOnly");
|
||||
const snapshot = useLive ? { scene: structuredClone(view.getScene()), revision: this.targets.revision(view) } : await diskSnapshot(plugin, file, this.isCurrent);
|
||||
let elements = snapshot.scene.elements.filter(element => !element.isDeleted);
|
||||
if (request.ids !== undefined) {
|
||||
if (!Array.isArray(request.ids) || request.ids.some(id => typeof id !== "string")) throw new CLIError("INVALID_INPUT", "Expected an ID array.", "ids");
|
||||
const ids = new Set(request.ids); elements = elements.filter(element => ids.has(element.id));
|
||||
}
|
||||
if (useLive && boolean(request.selectedOnly, "selectedOnly")) {
|
||||
const selected = view.excalidrawAPI.getAppState().selectedElementIds;
|
||||
elements = elements.filter(element => selected[element.id]);
|
||||
}
|
||||
if (request.detail !== undefined && !["summary", "elements"].includes(string(request.detail, "detail"))) throw new CLIError("INVALID_INPUT", "Expected summary or elements.", "detail");
|
||||
const data = { path: file.path, source: useLive ? "live" : "disk", ...(useLive ? { viewId: view.id, dirty: view.isDirty() } : {}), revision: snapshot.revision, total: elements.length, assetIds: Object.keys(snapshot.scene.files ?? {}), types: Object.fromEntries([...new Set(elements.map(element => element.type))].map(type => [type, elements.filter(element => element.type === type).length])) };
|
||||
return request.detail === "elements" ? { ...data, ...this.page(JSON.parse(JSON.stringify(elements)) as unknown[], request, snapshot.revision, "elements") } : data;
|
||||
}
|
||||
|
||||
private page(values: unknown[], request: Record<string, unknown>, revision: string, field: string) {
|
||||
const offset = number(request.offset, "offset", 0, 0, values.length), limit = number(request.limit, "limit", 50, 1, 200);
|
||||
if (!Number.isInteger(offset) || !Number.isInteger(limit)) throw new CLIError("INVALID_INPUT", "Pagination requires integers.");
|
||||
if ((offset > 0 || request.revision !== undefined) && request.revision !== revision) throw new CLIError("STALE_REVISION", "Pagination snapshot changed.", "revision", "Read the first page again.");
|
||||
return { [field]: values.slice(offset, offset + limit), total: values.length, revision, nextOffset: offset + limit < values.length ? offset + limit : null };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ExactDrawingCreationOptions } from "src/types/drawingCreationTypes";
|
||||
import {
|
||||
App,
|
||||
FrontMatterCache,
|
||||
@@ -141,12 +142,18 @@ export class PluginFileManager {
|
||||
filename: string,
|
||||
foldername?: string,
|
||||
initData?: string,
|
||||
exact?: ExactDrawingCreationOptions,
|
||||
): Promise<TFile> {
|
||||
if (exact && (initData === undefined || normalizePath(exact.exactPath) !== exact.exactPath || exact.exactPath.split("/").some(part => !part || part === "." || part === ".." || part.startsWith(".")))) {
|
||||
throw new Error("Exact drawing creation requires a visible vault-relative path");
|
||||
}
|
||||
const folderpath = normalizePath(
|
||||
foldername ? foldername : this.settings.folder,
|
||||
exact ? exact.exactPath.split("/").slice(0, -1).join("/") : foldername ? foldername : this.settings.folder,
|
||||
);
|
||||
exact?.validateBeforeCreate?.();
|
||||
await checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
const fname = getNewUniqueFilepath(this.app.vault, filename, folderpath);
|
||||
const fname = exact?.exactPath ?? getNewUniqueFilepath(this.app.vault, filename, folderpath);
|
||||
exact?.validateBeforeCreate?.();
|
||||
const file = await this.app.vault.create(
|
||||
fname,
|
||||
initData ?? (await this.plugin.getBlankDrawing()),
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { MarkdownPostProcessorContext, MarkdownRenderChild } from "obsidian";
|
||||
|
||||
interface EmbedRenderer {
|
||||
enqueue: (task: () => Promise<void>) => Promise<void>;
|
||||
createImage: (isCurrent: () => boolean) => Promise<HTMLDivElement>;
|
||||
discardImage: (image: Element) => void;
|
||||
isPluginLoaded: () => boolean;
|
||||
}
|
||||
|
||||
// One render owner per embed, including repeated postprocessor callbacks.
|
||||
const children = new WeakMap<HTMLElement, MarkdownEmbedRenderChild>();
|
||||
|
||||
/** DOM attachment is temporary; the Markdown render context owns our lifetime. */
|
||||
class MarkdownEmbedRenderChild extends MarkdownRenderChild {
|
||||
private active = false;
|
||||
private generation = 0;
|
||||
private pending: Promise<void> | null = null;
|
||||
private ready = false;
|
||||
private image: HTMLDivElement | null = null;
|
||||
private timer: number | null = null;
|
||||
|
||||
constructor(containerEl: HTMLElement, private renderer: EmbedRenderer) {
|
||||
super(containerEl);
|
||||
}
|
||||
|
||||
onload(): void {
|
||||
this.active = true;
|
||||
const ownerWindow = this.containerEl.ownerDocument.defaultView;
|
||||
const observer = new ownerWindow.MutationObserver((mutations) => {
|
||||
if (!mutations.some((m) => ["alt", "width", "height"].includes(m.attributeName))) {
|
||||
return;
|
||||
}
|
||||
// Invalidate immediately: an old result must not win during the debounce.
|
||||
this.generation++;
|
||||
this.pending = null;
|
||||
this.ready = false;
|
||||
this.containerEl.removeAttribute("ready");
|
||||
if (this.timer !== null) ownerWindow.clearTimeout(this.timer);
|
||||
this.timer = ownerWindow.setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.render();
|
||||
}, 500);
|
||||
});
|
||||
observer.observe(this.containerEl, {
|
||||
attributes: true,
|
||||
attributeFilter: ["alt", "width", "height"],
|
||||
});
|
||||
this.register(() => {
|
||||
observer.disconnect();
|
||||
if (this.timer !== null) ownerWindow.clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
});
|
||||
void this.render();
|
||||
}
|
||||
|
||||
onunload(): void {
|
||||
this.active = false;
|
||||
this.generation++;
|
||||
this.pending = null;
|
||||
this.ready = false;
|
||||
this.image = null;
|
||||
this.containerEl.removeAttribute("ready");
|
||||
this.renderer.discardImage(this.containerEl);
|
||||
if (children.get(this.containerEl) === this) children.delete(this.containerEl);
|
||||
}
|
||||
|
||||
render(): Promise<void> {
|
||||
if (!this.active || !this.renderer.isPluginLoaded() || this.timer !== null) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (this.ready && this.image?.parentElement === this.containerEl) return Promise.resolve();
|
||||
this.ready = false;
|
||||
this.containerEl.removeAttribute("ready");
|
||||
if (this.pending !== null) return this.pending;
|
||||
|
||||
const generation = ++this.generation;
|
||||
const isCurrent = () => this.active && this.renderer.isPluginLoaded() && generation === this.generation;
|
||||
const pending = this.renderer.enqueue(async () => {
|
||||
if (!isCurrent()) return;
|
||||
const image = await this.renderer.createImage(isCurrent);
|
||||
if (!image) return;
|
||||
if (!isCurrent()) {
|
||||
this.renderer.discardImage(image);
|
||||
return;
|
||||
}
|
||||
// A live context may be temporarily detached by Obsidian. Rendering into
|
||||
// its container lets the image appear when that same section is reattached.
|
||||
this.renderer.discardImage(this.containerEl);
|
||||
this.containerEl.empty();
|
||||
this.containerEl.appendChild(image);
|
||||
this.image = image;
|
||||
this.ready = true;
|
||||
this.containerEl.setAttribute("ready", "");
|
||||
}).catch((error: unknown) => {
|
||||
if (isCurrent()) console.error("Excalidraw Markdown embed render failed", error);
|
||||
}).finally(() => {
|
||||
if (generation === this.generation) this.pending = null;
|
||||
});
|
||||
this.pending = pending;
|
||||
return pending;
|
||||
}
|
||||
}
|
||||
|
||||
export const renderMarkdownEmbed = async (
|
||||
el: HTMLElement,
|
||||
containerEl: HTMLElement,
|
||||
ctx: MarkdownPostProcessorContext,
|
||||
renderer: EmbedRenderer,
|
||||
): Promise<void> => {
|
||||
let child = children.get(containerEl);
|
||||
if (!child) {
|
||||
el.empty();
|
||||
containerEl.empty();
|
||||
containerEl.removeAttribute("ready");
|
||||
child = new MarkdownEmbedRenderChild(containerEl, renderer);
|
||||
children.set(containerEl, child);
|
||||
ctx.addChild(child);
|
||||
}
|
||||
await child.render();
|
||||
};
|
||||
@@ -48,6 +48,7 @@ import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setElementDisplay } from "src/utils/htmlUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import { getGlobalTaskQueue } from "src/shared/GlobalTaskQueue";
|
||||
import { renderMarkdownEmbed } from "./MarkdownEmbedRenderChild";
|
||||
|
||||
interface imgElementAttributes {
|
||||
file?: TFile;
|
||||
@@ -460,6 +461,7 @@ const getIMG = async (
|
||||
imgAttributes: imgElementAttributes,
|
||||
onCanvas: boolean = false,
|
||||
embedEl?: Node,
|
||||
isRenderActive?: () => boolean,
|
||||
): Promise<HTMLImageElement | HTMLDivElement> => {
|
||||
let file = imgAttributes.file;
|
||||
if (!imgAttributes.file) {
|
||||
@@ -507,7 +509,7 @@ const getIMG = async (
|
||||
let terminationTimer: number;
|
||||
if (embedEl) {
|
||||
terminationTimer = window.setInterval(() => {
|
||||
if (!embedEl.isConnected) {
|
||||
if (!(isRenderActive ? isRenderActive() : embedEl.isConnected)) {
|
||||
loader.terminate = true;
|
||||
window.clearInterval(terminationTimer);
|
||||
}
|
||||
@@ -622,8 +624,9 @@ const createImgElement = async (
|
||||
attr: imgElementAttributes,
|
||||
onCanvas: boolean = false,
|
||||
embedEl?: Element,
|
||||
isRenderActive?: () => boolean,
|
||||
): Promise<HTMLElement> => {
|
||||
const imgOrDiv = await getIMG(attr, onCanvas, embedEl);
|
||||
const imgOrDiv = await getIMG(attr, onCanvas, embedEl, isRenderActive);
|
||||
if (!imgOrDiv) {
|
||||
return null;
|
||||
}
|
||||
@@ -803,14 +806,34 @@ const createImageDiv = async (
|
||||
attr: imgElementAttributes,
|
||||
onCanvas: boolean = false,
|
||||
embedEl?: Element,
|
||||
isRenderActive?: () => boolean,
|
||||
): Promise<HTMLDivElement> => {
|
||||
const img = await createImgElement(attr, onCanvas, embedEl);
|
||||
const img = await createImgElement(attr, onCanvas, embedEl, isRenderActive);
|
||||
if (!img) {
|
||||
return null;
|
||||
}
|
||||
return createDiv(attr.imgstyle.join(" "), (el) => el.append(img));
|
||||
};
|
||||
|
||||
const isExplicitImageEmbed = (src: string): boolean => {
|
||||
const parts = getEmbeddedFilenameParts(src);
|
||||
return isImagePartRef(parts) || (parts.hasBlockref && parts.blockref === "as-image");
|
||||
};
|
||||
|
||||
const resolveEmbedTarget = (src: string, sourcePath: string): TFile | null => {
|
||||
if (!src) return null;
|
||||
const filename = src.split("#")[0];
|
||||
if (filename) return metadataCache.getFirstLinkpathDest(filename, sourcePath);
|
||||
// Only recognized image fragments may refer to the containing drawing.
|
||||
// The active workspace file can be different in nested notes and popouts.
|
||||
return isExplicitImageEmbed(src) ? vault.getFileByPath(sourcePath) : null;
|
||||
};
|
||||
|
||||
const embedsMarkdown = (file: TFile): boolean => {
|
||||
const frontmatter = getSafeFrontmatter(metadataCache.getFileCache(file)?.frontmatter);
|
||||
return Boolean(frontmatter["excalidraw-open-md"] || frontmatter["excalidraw-embed-md"]);
|
||||
};
|
||||
|
||||
const processReadingMode = async (
|
||||
embeddedItems: NodeListOf<Element> | [HTMLElement],
|
||||
ctx: MarkdownPostProcessorContext,
|
||||
@@ -824,18 +847,14 @@ const processReadingMode = async (
|
||||
const promises: Promise<void>[] = [];
|
||||
|
||||
for (const maybeDrawing of embeddedItems) {
|
||||
// If the node is detached from the DOM, the user has closed the note or navigated away.
|
||||
// A detached candidate must not suppress later, connected embeds.
|
||||
if (!maybeDrawing.isConnected) {
|
||||
break;
|
||||
}
|
||||
|
||||
//check to see if the file in the src attribute exists
|
||||
const fname = maybeDrawing.getAttribute("src")?.split("#")[0];
|
||||
if (!fname) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file = metadataCache.getFirstLinkpathDest(fname, ctx.sourcePath);
|
||||
//check to see if the file in the src attribute exists
|
||||
const src = maybeDrawing.getAttribute("src");
|
||||
const file = resolveEmbedTarget(src, ctx.sourcePath);
|
||||
|
||||
//if the embeddedFile exits and it is an Excalidraw file
|
||||
//then lets replace the .internal-embed with the generated PNG or SVG image
|
||||
@@ -845,6 +864,7 @@ const processReadingMode = async (
|
||||
//should be embedded as legacy text
|
||||
continue;
|
||||
}
|
||||
if (embedsMarkdown(file) && !isExplicitImageEmbed(src)) continue;
|
||||
|
||||
promises.push(
|
||||
getGlobalTaskQueue(plugin).addTask(async () => {
|
||||
@@ -876,6 +896,7 @@ const processReadingMode = async (
|
||||
const processInternalEmbed = async (
|
||||
internalEmbedEl: Element,
|
||||
file: TFile,
|
||||
isRenderActive?: () => boolean,
|
||||
): Promise<HTMLDivElement> => {
|
||||
const attr: imgElementAttributes = {
|
||||
fname: "",
|
||||
@@ -911,7 +932,7 @@ const processInternalEmbed = async (
|
||||
? fnameParts.linkpartReference
|
||||
: "");
|
||||
attr.file = file;
|
||||
return await createImageDiv(attr, false, internalEmbedEl);
|
||||
return await createImageDiv(attr, false, internalEmbedEl, isRenderActive);
|
||||
};
|
||||
|
||||
function getDimensionsFromAliasString(data: string) {
|
||||
@@ -1068,10 +1089,6 @@ const tmpObsidianWYSIWYG = async (
|
||||
if (!plugin.isExcalidrawFile(file)) {
|
||||
return;
|
||||
}
|
||||
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
|
||||
if (safeFrontmatter["excalidraw-open-md"]) {
|
||||
return;
|
||||
}
|
||||
if (ctx.remainingNestLevel < 4) {
|
||||
return;
|
||||
}
|
||||
@@ -1119,6 +1136,14 @@ const tmpObsidianWYSIWYG = async (
|
||||
return; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/835
|
||||
}
|
||||
|
||||
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
|
||||
if (
|
||||
(safeFrontmatter["excalidraw-open-md"] || safeFrontmatter["excalidraw-embed-md"] || embedsMarkdown(file)) &&
|
||||
!(internalEmbedDiv.hasClass("internal-embed") && isExplicitImageEmbed(internalEmbedDiv.getAttribute("src")))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!plugin.settings.renderImageInHoverPreviewForMDNotes) {
|
||||
//const isHoverPopover = internalEmbedDiv.parentElement?.hasClass("hover-popover");
|
||||
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
|
||||
@@ -1258,10 +1283,7 @@ const tmpObsidianWYSIWYG = async (
|
||||
//over rendering when it is genuinely an Excalidraw drawing; otherwise leave the
|
||||
//embed alone so Obsidian's native renderer can display it.
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
|
||||
const embedSrc = internalEmbedDiv.getAttribute("src")?.split("#")[0];
|
||||
const embedTargetFile = embedSrc
|
||||
? metadataCache.getFirstLinkpathDest(embedSrc, ctx.sourcePath)
|
||||
: null;
|
||||
const embedTargetFile = resolveEmbedTarget(internalEmbedDiv.getAttribute("src"), ctx.sourcePath);
|
||||
if (
|
||||
!embedTargetFile ||
|
||||
!(embedTargetFile instanceof TFile) ||
|
||||
@@ -1270,73 +1292,12 @@ const tmpObsidianWYSIWYG = async (
|
||||
return;
|
||||
}
|
||||
|
||||
el.empty();
|
||||
|
||||
if (internalEmbedDiv.hasAttribute("ready")) {
|
||||
return;
|
||||
}
|
||||
internalEmbedDiv.setAttribute("ready", "");
|
||||
|
||||
internalEmbedDiv.empty();
|
||||
|
||||
await getGlobalTaskQueue(plugin).addTask(async () => {
|
||||
if (!internalEmbedDiv.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
const imgDiv = await processInternalEmbed(internalEmbedDiv, embedTargetFile);
|
||||
if (!imgDiv) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Abort insertion if the container is no longer connected
|
||||
if (!internalEmbedDiv.isConnected) {
|
||||
discardImage(imgDiv);
|
||||
return;
|
||||
}
|
||||
|
||||
internalEmbedDiv.appendChild(imgDiv);
|
||||
});
|
||||
|
||||
//timer to avoid the image flickering when the user is typing
|
||||
let timer: number = null;
|
||||
const markdownObserverFn: MutationCallback = (m) => {
|
||||
if (!["alt", "width", "height"].contains(m[0]?.attributeName)) {
|
||||
return;
|
||||
}
|
||||
if (timer) {
|
||||
window.clearTimeout(timer);
|
||||
}
|
||||
timer = window.setTimeout(() => {
|
||||
timer = null;
|
||||
internalEmbedDiv.empty();
|
||||
void getGlobalTaskQueue(plugin).addTask(async () => {
|
||||
if (!internalEmbedDiv.isConnected) {
|
||||
observer.disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
|
||||
if (!imgDiv) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (internalEmbedDiv.isConnected) {
|
||||
internalEmbedDiv.appendChild(imgDiv);
|
||||
} else {
|
||||
discardImage(imgDiv);
|
||||
}
|
||||
});
|
||||
}, 500);
|
||||
};
|
||||
const observer = DEBUGGING
|
||||
? new CustomMutationObserver(
|
||||
markdownObserverFn,
|
||||
"markdowPostProcessorObserverFn",
|
||||
)
|
||||
: new MutationObserver(markdownObserverFn);
|
||||
observer.observe(internalEmbedDiv, {
|
||||
attributes: true, //configure it to listen to attribute changes
|
||||
const currentPlugin = plugin;
|
||||
await renderMarkdownEmbed(el, internalEmbedDiv, ctx, {
|
||||
enqueue: (task) => getGlobalTaskQueue(currentPlugin).addTask(task),
|
||||
createImage: (isCurrent) => processInternalEmbed(internalEmbedDiv, embedTargetFile, isCurrent),
|
||||
discardImage,
|
||||
isPluginLoaded: () => currentPlugin._loaded,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1446,8 +1407,12 @@ export const markdownPostProcessor = async (
|
||||
//in reading mode these elements should be hidden
|
||||
const excalidrawFile = Boolean(safeFrontmatter["excalidraw-plugin"]);
|
||||
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
|
||||
setElementDisplay(el, "none");
|
||||
return;
|
||||
if (!(safeFrontmatter["excalidraw-open-md"] || safeFrontmatter["excalidraw-embed-md"])) {
|
||||
setElementDisplay(el, "none");
|
||||
return;
|
||||
}
|
||||
// Back-of-note Markdown transclusions own real embeds, not drawing metadata.
|
||||
setElementDisplay(el, "");
|
||||
}
|
||||
|
||||
await processReadingMode(embeddedItems, ctx);
|
||||
|
||||
@@ -662,7 +662,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
excalidrawMasteryPromoCollapsed: false,
|
||||
compareManifestToPluginVersion: true,
|
||||
showNewVersionNotification: true,
|
||||
latexBoilerplate: "\\color{green}e=mc^2",
|
||||
latexBoilerplate: "e=mc^2",
|
||||
latexPreambleLocation: "preamble.sty",
|
||||
taskboneEnabled: false,
|
||||
taskboneAPIkey: "",
|
||||
|
||||
@@ -16,6 +16,11 @@ declare const PLUGIN_VERSION: string;
|
||||
|
||||
// English
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "Show CLI and agent instructions",
|
||||
CLI_COPY_SKILL: "Copy agent instructions",
|
||||
CLI_DESCRIPTION: "Native Excalidraw CLI",
|
||||
|
||||
INITIALIZATION_MESSAGE:
|
||||
"Excalidraw is waiting for Obsidian to initialize all of your plugins...",
|
||||
// Sugester
|
||||
|
||||
@@ -16,6 +16,11 @@ declare const PLUGIN_VERSION: string;
|
||||
|
||||
// Español
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "Mostrar instrucciones de CLI y agentes",
|
||||
CLI_COPY_SKILL: "Copiar instrucciones para agentes",
|
||||
CLI_DESCRIPTION: "CLI nativa de Excalidraw",
|
||||
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
|
||||
// main.ts
|
||||
|
||||
@@ -14,6 +14,11 @@ import {
|
||||
|
||||
// русский
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "Показать инструкции CLI и для агентов",
|
||||
CLI_COPY_SKILL: "Копировать инструкции для агентов",
|
||||
CLI_DESCRIPTION: "Нативный CLI Excalidraw",
|
||||
|
||||
// main.ts
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw ожидает корректный файл data.json. Изменения настроек не будут сохранены, пока файл не будет восстановлен или вы не перезапустите Obsidian и не выберете сброс настроек.",
|
||||
|
||||
@@ -11,6 +11,11 @@ declare const PLUGIN_VERSION: string;
|
||||
|
||||
// 简体中文
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "显示 CLI 和智能体说明",
|
||||
CLI_COPY_SKILL: "复制智能体说明",
|
||||
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
|
||||
|
||||
INITIALIZATION_MESSAGE: "等待所有插件就绪…",
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "选择要嵌入到当前绘图中的文件",
|
||||
|
||||
@@ -11,6 +11,11 @@ declare const PLUGIN_VERSION: string;
|
||||
|
||||
// 繁體中文
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "顯示 CLI 和代理程式說明",
|
||||
CLI_COPY_SKILL: "複製代理程式說明",
|
||||
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
|
||||
|
||||
INITIALIZATION_MESSAGE: "等待所有外掛就緒…",
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "選擇要嵌入到當前繪圖中的檔案",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { App, Modal, Notice, Setting } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { CLI_SKILL } from "src/core/cli/cliCommands";
|
||||
|
||||
/** Human discovery for the same offline instructions exposed by the native CLI. */
|
||||
export class CLIInstructions extends Modal {
|
||||
public constructor(app: App) { super(app); }
|
||||
public onOpen(): void {
|
||||
this.titleEl.setText(t("CLI_HELP"));
|
||||
this.contentEl.createEl("pre").createEl("code", { text: CLI_SKILL });
|
||||
new Setting(this.contentEl).addButton(button => button.setButtonText(t("CLI_COPY_SKILL")).onClick(async () => {
|
||||
try { await this.contentEl.ownerDocument.defaultView.navigator.clipboard.writeText(CLI_SKILL); }
|
||||
catch { new Notice(t("AI_USAGE_MODAL_COPY_FAILURE")); }
|
||||
}));
|
||||
}
|
||||
public onClose(): void { this.contentEl.empty(); }
|
||||
}
|
||||
@@ -18,7 +18,19 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
"2.29.0": `
|
||||
## New
|
||||
- Native Excalidraw CLI for local coding agents: discover, create, read, edit, save, render, and run explicitly trusted local scripts. Requires Obsidian 1.12.2+ with CLI enabled; older Obsidian versions remain supported. Select **Excalidraw: Show CLI and agent instructions** in the command palette. [#2988](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2988)
|
||||
- Scripts can use the same CLI protocol through Excalidraw Automate, and create drawings at an exact new path with collision checks:
|
||||
\`\`\`ts
|
||||
executeCLI(request: ExcalidrawCLIRequest): Promise<ExcalidrawCLIResult>;
|
||||
create(params?: { exactPath?: string; /* existing creation options */ }): Promise<string>;
|
||||
\`\`\`
|
||||
|
||||
## Fixed
|
||||
- LaTeX formula editing in popout windows now keeps cursor placement and keyboard selection in the correct window. [#2970](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2970)
|
||||
- Self-referencing drawing embeds such as \`![[#^as-image]]\` work again. Nested drawings and ordinary images remain visible when embedding a drawing's Markdown side. [#2979](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2979)
|
||||
- Drawing embeds no longer stay blank when Obsidian temporarily detaches a Markdown section while rendering. [#2953](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2953)
|
||||
- Ctrl/Cmd-click on a grouped element now selects it first. A second click opens its own link without following links on other group members.
|
||||
- Editing text after undo or redo now keeps the restored text instead of bringing back the previous edit. [#2976](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2976)
|
||||
- Back-of-the-note embeds now wait for initialization so they display the linked Markdown section instead of the whole drawing. 🙏[askalf](${URLs.GITHUB_COM}/askalf) [#2931](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2931)
|
||||
`,
|
||||
|
||||
@@ -280,6 +280,9 @@ export class LaTexPrompt extends FloatingModal {
|
||||
|
||||
onOpen(): void {
|
||||
super.onOpen();
|
||||
// zsviczian #2970: Obsidian adopts the prebuilt modal into the popout document.
|
||||
// Rebind CodeMirror's selection observer and styles before focusing it.
|
||||
this.editorView.setRoot(this.contentEl.ownerDocument);
|
||||
this.editorView.focus();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,12 @@ const hyperlink = (url: string, text: string) => {
|
||||
const EMBEDDABLE_MDCUSTOMPROPS = `type EmbeddableMDCustomProps = {<br>useObsidianDefaults: boolean;<br>backgroundMatchCanvas: boolean;<br>backgroundMatchElement: boolean;<br>backgroundColor: string;<br>backgroundOpacity: number;<br>borderMatchElement: boolean;<br>borderColor: string;<br>borderOpacity: number;<br>filenameVisible: boolean;<br>};<br>`;
|
||||
|
||||
export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "executeCLI",
|
||||
code: "executeCLI(request: ExcalidrawCLIRequest): Promise<ExcalidrawCLIResult>;",
|
||||
desc: "Runs the versioned native CLI protocol in-process with explicit targets. Does not use this EA's workbench or target view. Check ok, mutation and persistence. Use schema for fields; receipts expire after 15 minutes or plugin reload.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "help",
|
||||
code: "help(target: Function | string)",
|
||||
@@ -222,9 +228,9 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "create",
|
||||
code: "async create(params?: {filename?: string, foldername?: string, templatePath?: string, onNewPane?: boolean, silent?: boolean, frontmatterKeys?: {},}): Promise<string>;",
|
||||
code: "async create(params?: {filename?: string, foldername?: string, exactPath?: string, validateBeforeCreate?: () => void, templatePath?: string, onNewPane?: boolean, silent?: boolean, frontmatterKeys?: {},}): Promise<string>;",
|
||||
desc:
|
||||
"Create a drawing and save it to filename.\nIf filename is null: default filename as defined in Excalidraw settings.\nIf folder is null: default folder as defined in Excalidraw settings\nReturns the path to the created file.\n" +
|
||||
"Create a drawing and save it to filename.\nIf filename is null: default filename as defined in Excalidraw settings.\nIf folder is null: default folder as defined in Excalidraw settings\nexactPath creates that exact new vault path/format without collision suffixes, template pickers, or opening a view. validateBeforeCreate is a synchronous lifecycle guard. Returns the path to the created file.\n" +
|
||||
"frontmatterKeys: {\n" +
|
||||
' "excalidraw-plugin"?: "raw" | "parsed";\n' +
|
||||
' "excalidraw-link-prefix"?: string;\n' +
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type React from "react";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import LZString from "lz-string";
|
||||
import type { ExcalidrawCLIRequest, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
|
||||
import {
|
||||
FillStyle,
|
||||
StrokeStyle,
|
||||
@@ -1169,6 +1170,16 @@ export class ExcalidrawAutomate {
|
||||
return ea;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the native CLI's JSON protocol in-process. Targets must be explicit;
|
||||
* this method does not use this EA's staged elements or target view. Inspect
|
||||
* `schema` for command fields and check `ok` and `persistence` in the result.
|
||||
* Receipts are session-only and expire after 15 minutes or plugin reload.
|
||||
*/
|
||||
public executeCLI(request: ExcalidrawCLIRequest): Promise<ExcalidrawCLIResult> {
|
||||
return this.plugin.executeCLI(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the fill style for new elements.
|
||||
* @param {number} val - The fill style value (0: "hachure", 1: "cross-hatch", 2: "solid").
|
||||
@@ -1459,6 +1470,10 @@ export class ExcalidrawAutomate {
|
||||
async create(params?: {
|
||||
filename?: string;
|
||||
foldername?: string;
|
||||
/** Exact new vault path/format, fail on collision, bypass interactive defaults. */
|
||||
exactPath?: string;
|
||||
/** Internal synchronous lifecycle guard for unattended creation. */
|
||||
validateBeforeCreate?: () => void;
|
||||
templatePath?: string;
|
||||
onNewPane?: boolean;
|
||||
silent?: boolean;
|
||||
@@ -1488,11 +1503,15 @@ export class ExcalidrawAutomate {
|
||||
? await getTemplate(
|
||||
this.plugin,
|
||||
params.templatePath,
|
||||
true,
|
||||
!params.exactPath,
|
||||
new EmbeddedFilesLoader(this.plugin),
|
||||
0,
|
||||
)
|
||||
: null;
|
||||
const templateEmbeddedMetadata = params?.exactPath && params.templatePath
|
||||
? (await this.plugin.app.vault.read(this.plugin.app.vault.getFileByPath(params.templatePath)))
|
||||
.replaceAll("\r\n", "\n").match(/^##? Embedded Files\s*\n([\s\S]*?)(?=^%%|^##? Drawing\b)/m)?.[1] ?? ""
|
||||
: "";
|
||||
if (template?.plaintext) {
|
||||
if (params.plaintext) {
|
||||
params.plaintext = `${params.plaintext}\n\n${template.plaintext}`;
|
||||
@@ -1502,6 +1521,7 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
let elements = template ? template.elements : [];
|
||||
elements = elements.concat(this.getElements());
|
||||
if (params?.exactPath && new Set(elements.map(element => element.id)).size !== elements.length) throw new Error("Exact drawing creation requires unique element IDs");
|
||||
let frontmatter: string;
|
||||
if (params?.frontmatterKeys) {
|
||||
const keys = Object.keys(params.frontmatterKeys);
|
||||
@@ -1594,15 +1614,16 @@ export class ExcalidrawAutomate {
|
||||
};
|
||||
|
||||
const generateMD = (): string => {
|
||||
const textElements = this.getElements().filter(
|
||||
const metadataElements = params?.exactPath ? elements : this.getElements();
|
||||
const textElements = metadataElements.filter(
|
||||
(el) => el.type === "text",
|
||||
) as ExcalidrawTextElement[];
|
||||
);
|
||||
let outString = `# Excalidraw Data\n\n## Text Elements\n`;
|
||||
textElements.forEach((te) => {
|
||||
outString += `${te.rawText ?? te.originalText ?? te.text} ^${te.id}\n\n`;
|
||||
});
|
||||
|
||||
const elementsWithLinks = this.getElements().filter(
|
||||
const elementsWithLinks = metadataElements.filter(
|
||||
(el) => el.type !== "text" && el.link,
|
||||
);
|
||||
elementsWithLinks.forEach((el) => {
|
||||
@@ -1610,9 +1631,10 @@ export class ExcalidrawAutomate {
|
||||
});
|
||||
|
||||
outString +=
|
||||
Object.keys(this.imagesDict).length > 0
|
||||
Object.keys(this.imagesDict).length > 0 || templateEmbeddedMetadata
|
||||
? `\n## Embedded Files\n`
|
||||
: "\n";
|
||||
outString += templateEmbeddedMetadata;
|
||||
|
||||
const embeddedFile = (
|
||||
key: FileId,
|
||||
@@ -1661,7 +1683,7 @@ export class ExcalidrawAutomate {
|
||||
const foldername = params?.foldername
|
||||
? params.foldername
|
||||
: this.plugin.settings.folder;
|
||||
const initData = this.plugin.settings.compatibilityMode
|
||||
const initData = (params?.exactPath ? params.exactPath.endsWith(".excalidraw") : this.plugin.settings.compatibilityMode)
|
||||
? JSON.stringify(scene, null, "\t")
|
||||
: frontmatter +
|
||||
generateMD() +
|
||||
@@ -1670,6 +1692,12 @@ export class ExcalidrawAutomate {
|
||||
this.plugin.settings.compress,
|
||||
);
|
||||
|
||||
if (params?.exactPath) {
|
||||
return (await this.plugin.createDrawing(filename, foldername, initData, {
|
||||
exactPath: params.exactPath, validateBeforeCreate: params.validateBeforeCreate,
|
||||
})).path;
|
||||
}
|
||||
|
||||
if (params.silent) {
|
||||
return (await this.plugin.createDrawing(filename, foldername, initData))
|
||||
.path;
|
||||
|
||||
@@ -2175,9 +2175,10 @@ export class ExcalidrawData {
|
||||
elementID: string,
|
||||
rawText: string,
|
||||
rawOriginalText: string,
|
||||
target?: Map<string, TextElementData>,
|
||||
): Promise<{ parseResult: string; link: string }> {
|
||||
const parseResult = await this.parse(rawOriginalText);
|
||||
this.textElements.set(elementID, {
|
||||
(target ?? this.textElements).set(elementID, {
|
||||
raw: rawOriginalText,
|
||||
parsed: parseResult.parsed,
|
||||
hasTextLink: !!parseResult.link,
|
||||
|
||||
+34
-5
@@ -34,6 +34,7 @@ export type ScriptIconMap = {
|
||||
|
||||
/** Identifies why the script engine invoked a script. */
|
||||
export type ScriptExecutionSource =
|
||||
| "cli"
|
||||
| "manual"
|
||||
| "plugin-startup"
|
||||
| "view-autostart"
|
||||
@@ -50,6 +51,7 @@ type CompiledScript = {
|
||||
path: string;
|
||||
mtime: number;
|
||||
size: number;
|
||||
source: string;
|
||||
executable: ScriptExecutable | null;
|
||||
};
|
||||
|
||||
@@ -208,6 +210,7 @@ export class ScriptEngine {
|
||||
*/
|
||||
private async getCompiledScript(
|
||||
file: TFile,
|
||||
expectedSource?: string,
|
||||
): Promise<ScriptExecutable | null> {
|
||||
while (true) {
|
||||
const path = file.path;
|
||||
@@ -224,7 +227,8 @@ export class ScriptEngine {
|
||||
if (
|
||||
file.path === cached.path &&
|
||||
file.stat.mtime === cached.mtime &&
|
||||
file.stat.size === cached.size
|
||||
file.stat.size === cached.size &&
|
||||
(expectedSource === undefined || cached.source === expectedSource)
|
||||
) {
|
||||
return cached.executable;
|
||||
}
|
||||
@@ -240,10 +244,12 @@ export class ScriptEngine {
|
||||
|
||||
const compilePromise = (async (): Promise<CompiledScript> => {
|
||||
const source = await this.app.vault.read(file);
|
||||
if (expectedSource !== undefined && source !== expectedSource) throw new Error("Script source changed before compilation");
|
||||
return {
|
||||
path,
|
||||
mtime,
|
||||
size,
|
||||
source,
|
||||
executable: this.compileScript(source),
|
||||
};
|
||||
})();
|
||||
@@ -1036,6 +1042,24 @@ export class ScriptEngine {
|
||||
);
|
||||
}
|
||||
|
||||
/** One-shot CLI context; persistent manual/sidepanel script lifetimes are unchanged. */
|
||||
public async executeScriptFileForCLI(
|
||||
file: TFile,
|
||||
view: ExcalidrawView | undefined,
|
||||
ea: ExcalidrawAutomate,
|
||||
input: unknown,
|
||||
excalidrawLib: NonNullable<import("src/types/types").Packages["excalidrawLib"]>,
|
||||
source: string,
|
||||
validateBeforeExecution: () => void,
|
||||
): Promise<unknown> {
|
||||
try {
|
||||
const executable = await this.getCompiledScript(file, source);
|
||||
validateBeforeExecution();
|
||||
if (!executable) throw new Error("Script could not be compiled");
|
||||
return await this.executeExecutable(view, executable, file.basename, file, "cli", ea, false, true, { input, excalidrawLib });
|
||||
} finally { ea.destroy(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the configured startup file using the plugin-global EA while
|
||||
* sharing ScriptEngine's loading, compilation, utilities, and error path.
|
||||
@@ -1096,6 +1120,7 @@ export class ScriptEngine {
|
||||
eaOverride?: ExcalidrawAutomate,
|
||||
trackEA: boolean = true,
|
||||
setActiveScript: boolean = true,
|
||||
cliUtilities?: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
//addresses the situation when after paste text element IDs are not updated to 8 characters
|
||||
//linked to onPaste save issue with the false parameter
|
||||
@@ -1104,7 +1129,7 @@ export class ScriptEngine {
|
||||
//execution itself must continue so view-autostart can attach to the new view.
|
||||
const scene = view?.getScene();
|
||||
if (
|
||||
scene?.elements.some(
|
||||
executionSource !== "cli" && scene?.elements.some(
|
||||
(el) => !el.isDeleted && el.type === "text" && el.id.length > 8,
|
||||
)
|
||||
) {
|
||||
@@ -1125,6 +1150,7 @@ export class ScriptEngine {
|
||||
}
|
||||
try {
|
||||
return await executable(ea, {
|
||||
...cliUtilities,
|
||||
inputPrompt: (
|
||||
header: string | InputPromptOptions,
|
||||
placeholder?: string,
|
||||
@@ -1137,6 +1163,7 @@ export class ScriptEngine {
|
||||
controlsOnTop?: boolean,
|
||||
draggable?: boolean,
|
||||
) => {
|
||||
if (executionSource === "cli") throw new Error("INTERACTION_REQUIRED: inputPrompt is unavailable in one-shot CLI scripts");
|
||||
if (typeof header === "object") {
|
||||
const options = header;
|
||||
header = options.header;
|
||||
@@ -1172,14 +1199,16 @@ export class ScriptEngine {
|
||||
items: unknown[],
|
||||
hint?: string,
|
||||
instructions?: Instruction[],
|
||||
) =>
|
||||
ScriptEngine.suggester(
|
||||
) => {
|
||||
if (executionSource === "cli") throw new Error("INTERACTION_REQUIRED: suggester is unavailable in one-shot CLI scripts");
|
||||
return ScriptEngine.suggester(
|
||||
this.app,
|
||||
displayItems,
|
||||
items,
|
||||
hint,
|
||||
instructions,
|
||||
),
|
||||
);
|
||||
},
|
||||
scriptFile: file,
|
||||
executionSource,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
/** Per-call exact-path creation without changing interactive defaults or settings. */
|
||||
export interface ExactDrawingCreationOptions {
|
||||
exactPath: string;
|
||||
/** Synchronous session/target validation immediately before each write. */
|
||||
validateBeforeCreate?: () => void;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/** Versioned JSON protocol shared by native CLI and Excalidraw Automate. */
|
||||
export type CLIJSON = null | boolean | number | string | CLIJSON[] | { [key: string]: CLIJSON };
|
||||
export type CLICommand = "help" | "status" | "schema" | "api" | "list" | "read" | "open" | "create" | "apply" | "export" | "script" | "skill" | "result";
|
||||
|
||||
/** Command-specific fields are validated against the runtime `schema` action. */
|
||||
export interface ExcalidrawCLIRequest {
|
||||
apiVersion: 1;
|
||||
command: CLICommand;
|
||||
requestId?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** A completed script is not itself proof that a drawing was durably saved. */
|
||||
export interface ExcalidrawCLIResult {
|
||||
apiVersion: 1;
|
||||
session: string;
|
||||
requestId?: string;
|
||||
command: string;
|
||||
status: "completed" | "failed" | "pending";
|
||||
ok: boolean | null;
|
||||
persistence: "not-applicable" | "saved" | "unsaved" | "unknown";
|
||||
mutation: "not-applied" | "applied" | "partial" | "unknown";
|
||||
target?: { vault: string; path: string; viewId?: string };
|
||||
revision?: string;
|
||||
data?: CLIJSON;
|
||||
warnings: string[];
|
||||
error?: { code: string; message: string; field?: string; recovery: string };
|
||||
}
|
||||
Vendored
+2
-10
@@ -27,7 +27,6 @@ import {
|
||||
LibraryItems_anyVersion,
|
||||
Zoom,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
|
||||
type JsonValue = string | number | boolean | null | JsonObject | JsonValue[];
|
||||
@@ -138,10 +137,6 @@ export declare namespace ExcalidrawLib {
|
||||
}>;
|
||||
}>;
|
||||
|
||||
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
|
||||
Partial<TElement>,
|
||||
"id" | "updated"
|
||||
>;
|
||||
|
||||
type ExportOpts = {
|
||||
elements: readonly NonDeleted<ExcalidrawElement>[];
|
||||
@@ -282,11 +277,8 @@ export declare namespace ExcalidrawLib {
|
||||
},
|
||||
): Promise<Blob>;
|
||||
|
||||
function mutateElement<TElement extends Mutable<ExcalidrawElement>>(
|
||||
element: TElement,
|
||||
updates: ElementUpdate<TElement>,
|
||||
informMutation?: boolean,
|
||||
): TElement;
|
||||
const mutateElement: typeof import("@zsviczian/excalidraw/types/element/src/mutateElement").mutateElement;
|
||||
const getCommonBounds: typeof import("@zsviczian/excalidraw/types/element/src/bounds").getCommonBounds;
|
||||
|
||||
function getEmbedLink(link: string | null | undefined): EmbeddedLink;
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Type-only Obsidian 1.12.2 CLI boundary, mirrored from obsidianmd/obsidian-api
|
||||
* obsidian.d.ts. The project deliberately compiles against 1.8.7. Replace with
|
||||
* type imports when that dependency includes the API; declarations do not
|
||||
* establish runtime availability.
|
||||
*/
|
||||
export interface CliData {
|
||||
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- Mirrors the canonical 1.12.2 API, including its documented bare-flag literal.
|
||||
[key: string]: string | "true";
|
||||
}
|
||||
|
||||
export interface CliFlag {
|
||||
value?: string;
|
||||
description: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export type CliFlags = Record<string, CliFlag>;
|
||||
export type CliHandler = (params: CliData) => string | Promise<string>;
|
||||
|
||||
export interface ObsidianCliRuntime {
|
||||
registerCliHandler(command: string, description: string, flags: CliFlags | null, handler: CliHandler): void;
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
ExcalidrawImperativeAPI,
|
||||
ExcalidrawInitialDataState,
|
||||
Gesture,
|
||||
PointerDownState,
|
||||
LibraryItems,
|
||||
UIAppState,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
@@ -1038,6 +1039,11 @@ export default class ExcalidrawView
|
||||
);
|
||||
}
|
||||
|
||||
/** Reports persistence acknowledgment without exposing a serialized save snapshot. */
|
||||
public saveWithOutcome() {
|
||||
return this.saveCoordinator.saveWithOutcome();
|
||||
}
|
||||
|
||||
private async withPersistenceWriteLease<T>(
|
||||
filePath: string,
|
||||
operation: () => T | Promise<T>,
|
||||
@@ -5108,6 +5114,7 @@ export default class ExcalidrawView
|
||||
newElementsOnTop = false,
|
||||
shouldRestoreElements = false,
|
||||
captureUpdate = CaptureUpdateAction.IMMEDIATELY,
|
||||
validateBeforePublish,
|
||||
}: {
|
||||
newElements: ExcalidrawElement[];
|
||||
repositionToCursor?: boolean;
|
||||
@@ -5116,14 +5123,18 @@ export default class ExcalidrawView
|
||||
newElementsOnTop?: boolean;
|
||||
shouldRestoreElements?: boolean;
|
||||
captureUpdate?: CaptureUpdateActionType;
|
||||
validateBeforePublish?: () => void;
|
||||
}): Promise<boolean> {
|
||||
const api = this.excalidrawAPI;
|
||||
if (!api) {
|
||||
return false;
|
||||
}
|
||||
const sceneElements = api.getSceneElements() as ExcalidrawElement[];
|
||||
// Guarded callers prepare parsed text in a request-local map. A stale
|
||||
// continuation must not leave metadata behind before publishing its scene.
|
||||
const preparedText = validateBeforePublish ? new Map(this.excalidrawData.textElements) : undefined;
|
||||
const elementsMap = arrayToMap(sceneElements) as ElementsMap;
|
||||
const textElements = newElements.filter((el) => el.type == "text");
|
||||
const textElements = newElements.filter((el) => el.type == "text" && (!validateBeforePublish || !el.isDeleted));
|
||||
let shouldRefreshArrows = false;
|
||||
for (let i = 0; i < textElements.length; i++) {
|
||||
const textElement = textElements[i] as Mutable<ExcalidrawTextElement>;
|
||||
@@ -5131,6 +5142,7 @@ export default class ExcalidrawView
|
||||
textElement.id,
|
||||
textElement.text,
|
||||
textElement.rawText, //TODO: implement originalText support in ExcalidrawAutomate
|
||||
preparedText,
|
||||
);
|
||||
if (link) {
|
||||
if (this.plugin.settings.syncElementLinkWithText) {
|
||||
@@ -5199,6 +5211,11 @@ export default class ExcalidrawView
|
||||
);
|
||||
}
|
||||
|
||||
validateBeforePublish?.();
|
||||
if (validateBeforePublish) {
|
||||
for (const element of newElements) if (element.isDeleted) preparedText.delete(element.id);
|
||||
this.excalidrawData.textElements = preparedText;
|
||||
}
|
||||
const files: BinaryFileData[] = [];
|
||||
if (images && Object.keys(images).length > 0) {
|
||||
Object.keys(images).forEach((k: FileId) => {
|
||||
@@ -5698,7 +5715,11 @@ export default class ExcalidrawView
|
||||
}
|
||||
}
|
||||
|
||||
public onPointerDown(e: PointerEvent) {
|
||||
public onPointerDown(
|
||||
e: PointerEvent,
|
||||
selectionBeforePointerDown?: AppState,
|
||||
pointerDownState?: PointerDownState,
|
||||
) {
|
||||
if (!(isWinCTRLorMacCMD(e) || isWinMETAorMacCTRL(e))) {
|
||||
return;
|
||||
}
|
||||
@@ -5712,6 +5733,56 @@ export default class ExcalidrawView
|
||||
//Timeout is required for Excalidraw to first complete the selection action before execution
|
||||
//of the link click continues
|
||||
window.setTimeout(() => {
|
||||
const hitElement = pointerDownState?.hit.element;
|
||||
if (
|
||||
!this.excalidrawAPI?.getAppState().viewModeEnabled &&
|
||||
isWinCTRLorMacCMD(e) &&
|
||||
hitElement?.groupIds.length
|
||||
) {
|
||||
// Deep selection gets the first click. Group-wide link fallbacks must
|
||||
// never turn an unlinked member into a link to one of its siblings.
|
||||
if (
|
||||
!selectionBeforePointerDown?.selectedElementIds[hitElement.id] ||
|
||||
Object.keys(selectionBeforePointerDown.selectedElementIds).length !==
|
||||
1 ||
|
||||
hitElement.groupIds.some(
|
||||
(id) => selectionBeforePointerDown.selectedGroupIds[id],
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const textElement =
|
||||
hitElement.type === "text"
|
||||
? hitElement
|
||||
: hitElement.type !== "arrow"
|
||||
? this.excalidrawAPI.getSceneElements().find(
|
||||
(el) =>
|
||||
el.type === "text" &&
|
||||
el.id === getBoundTextElementId(hitElement),
|
||||
)
|
||||
: null;
|
||||
if (
|
||||
textElement?.type !== "text" &&
|
||||
hitElement.type !== "image" &&
|
||||
!hitElement.link
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.removeLinkTooltip();
|
||||
void this.linkClick(
|
||||
e,
|
||||
textElement?.type === "text"
|
||||
? { id: textElement.id, text: textElement.text }
|
||||
: null,
|
||||
hitElement.type === "image"
|
||||
? { id: hitElement.id, fileId: hitElement.fileId }
|
||||
: null,
|
||||
!textElement && hitElement.type !== "image"
|
||||
? { id: hitElement.id, text: hitElement.link }
|
||||
: null,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.isLinkSelected()) {
|
||||
void this.handleLinkClick(e);
|
||||
return;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import {
|
||||
AppState,
|
||||
ExcalidrawInitialDataState,
|
||||
PointerDownState,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import type { PointerEvent as ReactPointerEvent } from "react";
|
||||
import { DEVICE, obsidianToExcalidrawMap } from "../../constants/constants";
|
||||
import { t } from "../../lang/helpers";
|
||||
import { isMarkdownImageElement } from "../../shared/MarkdownImage";
|
||||
@@ -56,6 +58,8 @@ export function createExcalidrawRootElement(
|
||||
const excalidrawWrapperRef = React.useRef<HTMLDivElement>(null);
|
||||
const toolsPanelRef = React.useRef<ToolsPanel>(null);
|
||||
const embeddableMenuRef = React.useRef<HTMLDivElement>(null);
|
||||
const selectionBeforePointerDown = React.useRef<AppState>(null);
|
||||
const canvasPointerDown = React.useRef<PointerDownState>(null);
|
||||
view.toolsPanelRef = toolsPanelRef;
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -153,7 +157,16 @@ export function createExcalidrawRootElement(
|
||||
tabIndex: 0,
|
||||
onKeyDown: view.excalidrawDIVonKeyDown.bind(view),
|
||||
onKeyUp: view.excalidrawDIVonKeyUp.bind(view),
|
||||
onPointerDown: view.onPointerDown.bind(view),
|
||||
onPointerDownCapture: () => {
|
||||
selectionBeforePointerDown.current = view.excalidrawAPI?.getAppState();
|
||||
canvasPointerDown.current = null;
|
||||
},
|
||||
onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) =>
|
||||
view.onPointerDown(
|
||||
event.nativeEvent,
|
||||
selectionBeforePointerDown.current,
|
||||
canvasPointerDown.current,
|
||||
),
|
||||
onMouseMove: view.onMouseMove.bind(view),
|
||||
onMouseOver: view.onMouseOver.bind(view),
|
||||
onDragOver: view.dropManager?.onDragOver.bind(view.dropManager),
|
||||
@@ -163,6 +176,9 @@ export function createExcalidrawRootElement(
|
||||
Excalidraw,
|
||||
{
|
||||
ownerDocument: view.ownerDocument,
|
||||
onPointerDown: (_, pointerDownState) => {
|
||||
canvasPointerDown.current = pointerDownState;
|
||||
},
|
||||
onExcalidrawAPI: (api) => view.setExcalidrawAPI(api),
|
||||
onInitialize: (api) => view.onExcalidrawInitialize(api),
|
||||
UIOptions: {
|
||||
|
||||
@@ -40,6 +40,14 @@ export interface SaveExecutionResult {
|
||||
preparedSave?: PreparedSave;
|
||||
}
|
||||
|
||||
/** Small durability receipt for callers that need more than an attempted save. */
|
||||
export interface SaveAcknowledgment {
|
||||
status: SaveExecutionStatus;
|
||||
requestedRevision: number;
|
||||
acknowledgedRevision: number | null;
|
||||
currentRevision: number;
|
||||
}
|
||||
|
||||
/** Clean durability baseline transferred with a migrated drawing. */
|
||||
export interface ViewSaveMigrationState {
|
||||
currentRevision: number;
|
||||
@@ -192,6 +200,25 @@ export class ViewSaveCoordinator {
|
||||
});
|
||||
}
|
||||
|
||||
/** Uses the existing queue and same-file guard; never acknowledges a handoff. */
|
||||
public async saveWithOutcome(): Promise<SaveAcknowledgment> {
|
||||
const requestedRevision = this.currentRevision;
|
||||
const result = await this.enqueueSave({
|
||||
suppressReloadFromOwnWrite: false,
|
||||
forcePersistence: true,
|
||||
bypassSameFileEditGuard: false,
|
||||
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
|
||||
revision: requestedRevision,
|
||||
});
|
||||
return {
|
||||
status: result.status,
|
||||
requestedRevision,
|
||||
currentRevision: this.currentRevision,
|
||||
acknowledgedRevision: (result.status === "persisted" || result.status === "window-migration-persisted")
|
||||
? result.preparedSave?.capturedRevision ?? null : null,
|
||||
};
|
||||
}
|
||||
|
||||
private enqueueSave(request: SaveRequest): Promise<SaveExecutionResult> {
|
||||
if (this.pendingSaveRequest) {
|
||||
this.pendingSaveRequest = this.mergeSaveRequests(
|
||||
|
||||
Reference in new issue
Block a user