mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
67
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0b8a2b039 | ||
|
|
ae4c94d2bf | ||
|
|
4acaf9e375 | ||
|
|
5023a771a3 | ||
|
|
3cf8bd8d00 | ||
|
|
2f12588d99 | ||
|
|
89a2dabdc2 | ||
|
|
0ba2608a4a | ||
|
|
1e60f82b45 | ||
|
|
3cef89dcda | ||
|
|
cabec91055 | ||
|
|
769d58ea45 | ||
|
|
41072f2929 | ||
|
|
07dec1218c | ||
|
|
48c353519a | ||
|
|
d39bfa9c6d | ||
|
|
5e2bb7719f | ||
|
|
e4951c107a | ||
|
|
f0dd5cb7ca | ||
|
|
44dac3237c | ||
|
|
3d8244b372 | ||
|
|
8a9f33a33f | ||
|
|
523f971088 | ||
|
|
bf541ca5d4 | ||
|
|
db094fb04d | ||
|
|
3551b706a8 | ||
|
|
d47cb75475 | ||
|
|
a93f67be1b | ||
|
|
3d69aa7aec | ||
|
|
29fac30f9e | ||
|
|
09642b981e | ||
|
|
37bd78fa73 | ||
|
|
bd3083c114 | ||
|
|
c4affd27d6 | ||
|
|
36590861f4 | ||
|
|
078f48e28a | ||
|
|
f30b4c5d3d | ||
|
|
593ad99bab | ||
|
|
f591b7558f | ||
|
|
9cf33817b7 | ||
|
|
128a9ef47b | ||
|
|
96bd2212c2 | ||
|
|
3d8f312add | ||
|
|
bd40308a83 | ||
|
|
3e13b61c6d | ||
|
|
921f679f0b | ||
|
|
c3955cad5f | ||
|
|
5da2b452f1 | ||
|
|
ef9b7cd014 | ||
|
|
0d5a809372 | ||
|
|
496d451914 | ||
|
|
f25a7ba08b | ||
|
|
eb284a1c85 | ||
|
|
6e3c8d7468 | ||
|
|
41e578320c | ||
|
|
a951d371cb | ||
|
|
d31ac3b62b | ||
|
|
f96cbc53ff | ||
|
|
dbc9476202 | ||
|
|
8e08316ba6 | ||
|
|
1eb1aa9ff0 | ||
|
|
a18fd81133 | ||
|
|
d38510fad7 | ||
|
|
b48112e4ca | ||
|
|
5c5e351258 | ||
|
|
9e69f245b5 | ||
|
|
ac359575f6 |
No files matched your search
@@ -0,0 +1,43 @@
|
||||
# Issue labels and triage
|
||||
|
||||
The central issue tracker for Obsidian Excalidraw and its related projects is [obsidian-excalidraw-plugin/issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues). Direct users here by default, including reports concerning the [Excalidraw fork](https://github.com/zsviczian/excalidraw), [Excalidraw Extras](https://github.com/zsviczian/obsidian-excalidraw-extras), and [EA Scripts](https://github.com/zsviczian/ea-scripts). Separate repositories may occasionally have their own issues, but this tracker is the main triage hub.
|
||||
|
||||
Use a small set of independent label dimensions. Do not infer severity solely from type, area, or report completeness. Prefer existing labels and preserve useful historical labels until a deliberate migration. The names and colors below are the **target convention**, not a claim that all labels have already been created.
|
||||
|
||||
## Label dimensions
|
||||
|
||||
| Dimension | Label | Meaning | Suggested color |
|
||||
| --- | --- | --- | --- |
|
||||
| Type | `type: regression` | Previously working behavior broke | `#1D4ED8` |
|
||||
| Type | `type: bug` | Incorrect existing behavior | `#2563EB` |
|
||||
| Type | `type: enhancement` | Improve existing behavior | `#60A5FA` |
|
||||
| Type | `type: feature` | New capability | `#93C5FD` |
|
||||
| Type | `type: documentation` | Documentation change | `#DBEAFE` |
|
||||
| Area | `area: plugin` | Main Obsidian plugin | `#6D28D9` |
|
||||
| Area | `area: fork` | Customized Excalidraw component | `#7C3AED` |
|
||||
| Area | `area: extras` | Excalidraw Extras | `#A78BFA` |
|
||||
| Area | `area: script` | Excalidraw Automate / EA Scripts | `#DDD6FE` |
|
||||
| Status | `status: confirmed` | Behavior verified or sufficiently established | `#15803D` |
|
||||
| Status | `status: blocked` | Waiting on a dependency or decision | `#4D7C0F` |
|
||||
| Status | `status: incomplete` | Report lacks required details, such as Obsidian debug information | `#A3A3A3` |
|
||||
| Status | `status: needs-info` | Specific clarification requested from reporter | `#86EFAC` |
|
||||
| Status | `status: cannot-reproduce` | Reproduction attempted without success | `#D4D4D4` |
|
||||
| Criticality | `critical` | Credible urgent risk of data loss, security/privacy exposure, or serious compliance/distribution consequences | `#D1242F` |
|
||||
|
||||
The order within type and area indicates typical triage attention, **not automatic priority**. Status labels describe evidence or workflow, not severity. In particular, `status: confirmed` can coexist with `status: incomplete`: a report may lack debug details while describing a bug the maintainer can reproduce. Other status labels may also coexist when they express distinct facts; avoid redundant combinations.
|
||||
|
||||
## Triage rules
|
||||
|
||||
- Reserve **`critical`** for exceptional risks requiring prompt investigation; it does not imply an immediate fix or require proof before investigating a credible data-loss/security report. It is independent of `type: regression` and `type: bug`.
|
||||
- Prefer one primary type and one primary area. Apply status labels only when informative; do not label every issue with a status merely to fill the dimension.
|
||||
- Keep existing special-purpose labels such as `one day maybe` (deferred ideas) and `transfer to Excalidraw` (candidate upstream work). They are not part of the four dimensions.
|
||||
- Avoid adding generic high/medium/low priority labels or labels for individual scripts without demonstrated need.
|
||||
- For missing Obsidian debug information, use `status: incomplete`; request specific information with `status: needs-info` when appropriate. A confirmed bug may still be fixed despite an incomplete report.
|
||||
- Use brief, clear issue replies. When an agent comments, identify itself as **Zsolt's Codex Agent**.
|
||||
- Before changing repository labels, inventory the current set. Rename existing labels where possible so historical issue/PR assignments survive. Do not delete or merge labels without reviewing affected issues. Match each GitHub label description to its meaning here.
|
||||
|
||||
## Examples
|
||||
|
||||
- Reproducible plugin data-loss regression: `type: regression`, `area: plugin`, `status: confirmed`, `critical`.
|
||||
- MindMap Builder subtree attachment request: `type: enhancement`, `area: script`; add `status: needs-info` if waiting for the reporter's script.
|
||||
- Fork behavior best fixed upstream: relevant type, `area: fork`, and `transfer to Excalidraw`.
|
||||
@@ -54,6 +54,8 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
|
||||
- Default to local/offline operation. Only make network requests when essential to the feature.
|
||||
- No hidden telemetry. If you collect optional analytics or call third-party services, require explicit opt-in and document clearly in `README.md` and in settings.
|
||||
- Keep every external origin and every fully static URL as a literal `https://...` string in source so reviewers and security scanners can identify the destination without executing the code. A dynamic resource path may be appended only to a literal base URL, and each untrusted path segment must be validated or encoded.
|
||||
- Never conceal a network destination or evade a scanner finding by splitting or joining domain labels, deriving an origin from Git state, environment variables, runtime configuration, or character codes, or by encoding, compressing, encrypting, or otherwise transforming a URL. Do not weaken, suppress, or work around a scanner by making an endpoint less statically visible; fix the underlying behavior or document a genuine false positive transparently.
|
||||
- Never execute remote code, fetch and eval scripts, or auto-update plugin code outside of normal releases.
|
||||
- Minimize scope: read/write only what's necessary inside the vault. Do not access files outside the vault.
|
||||
- Clearly disclose any external services used, data sent, and risks.
|
||||
@@ -136,6 +138,16 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
- Ship features that require cloud services without clear disclosure and explicit opt-in.
|
||||
- Store or transmit vault contents unless essential and consented.
|
||||
|
||||
## Issue Investigation And Resolution Templates
|
||||
|
||||
When triaging or updating issues across the plugin, Excalidraw fork, Extras, and EA Scripts, use the central [plugin issue tracker and label guidelines](.github/ISSUE_LABELS.md); this plugin repository is the default issue hub for all four projects.
|
||||
|
||||
|
||||
|
||||
- For source-based issue investigations, GitHub issue comments, and a prioritized shortlist, use [issue assessment](docs/agent-workflows/issue-assessment.md).
|
||||
- Only after maintainer approval of specific issues, use [issue implementation handoff and resolution](docs/agent-workflows/issue-resolution.md) to prepare a dedicated branch and plan-only draft PR for the local implementation agent.
|
||||
- The issue owns the technical assessment; the draft PR owns the implementation plan; the branch owns the code. Keep draft PRs open through implementation, link cross-repository dependencies, and do not merge without authorization.
|
||||
|
||||
## References
|
||||
|
||||
- Obsidian sample plugin: https://github.com/obsidianmd/obsidian-sample-plugin
|
||||
@@ -310,11 +322,11 @@ Window ownership for rendering is not the same as ownership for persistent plugi
|
||||
- `src/lang/helpers.ts` resolves those tokens at runtime.
|
||||
- If you add new runtime-dependent locale patterns, you must keep `rollup.config.mjs` and `src/lang/helpers.ts` in sync.
|
||||
|
||||
### Safe URL Tokenization
|
||||
### Safe URL Handling
|
||||
|
||||
- Safe URLs are centralized in `src/constants/safeUrls.ts`.
|
||||
- The build tokenizes URL constants and resolves them at runtime.
|
||||
- If you change safe URL handling, rebuild and verify both token emission and token resolution.
|
||||
- Preserve literal, statically reviewable origins and complete static URLs. Only repository-relative or resource-relative paths may be constructed dynamically from validated or encoded path segments.
|
||||
- If you change safe URL handling, rebuild and verify that the intended literal origins remain visible in both source and `dist/main.js`, and search for domain assembly or endpoint-obfuscation patterns before release.
|
||||
|
||||
### Versioning Nuance
|
||||
|
||||
@@ -505,7 +517,17 @@ If a task touches any of the above, read adjacent code first and validate more c
|
||||
|
||||
## Validation Expectations
|
||||
|
||||
There is no standard unit-test suite wired into `package.json`.
|
||||
There is no comprehensive runtime unit-test suite. The CLI harness has focused tests wired into `package.json`.
|
||||
|
||||
### Obsidian CLI runtime lane
|
||||
|
||||
Follow [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md) for macOS and Windows setup, and its linked fork guide for feature gates. `npm run test:obsidian:runner` tests the vault guards and platform launchers without Obsidian. `npm run verify:obsidian:plugin` builds this plugin with the installed component package. `npm run verify:obsidian` first builds and copies the sibling fork's four Obsidian artifacts. Both native lanes require the explicitly configured `excalidraw-test` vault, check the CLI-selected vault and config paths before deployment, stage the exact `main.js`/CSS/manifest, and assert a live drawing and clean JavaScript error buffer. Review the report's build mode, source identity, hashes, and cleanup result. A previous local artifact copy into `node_modules` remains in effect for the plugin-only lane until `npm install` restores the published package.
|
||||
|
||||
Look for an existing `excalidraw-test` vault in Obsidian's vault registry and confirm its path and enabled plugin. If absent, ask the user to create it and install/enable Excalidraw from Community plugins before deployment. Do not create or download a replacement vault without consent. Complete any first-open trust prompt and reopen the vault before CLI probes. Never choose a personal/default vault when the test vault is unavailable.
|
||||
|
||||
Use the test-only `scripts/testing/host/processTools.mjs` for native launches. Windows captures output through `Obsidian.com`; long or multiline Windows evals use an owned temporary UTF-8 script and are cleaned up after each call. npm and Yarn launch through JavaScript entries using the current Node executable, avoiding Windows `.cmd` shims. Run CLI scenarios serially. If a request times out, check for a pending Obsidian error/trust dialog; ask the user to save and restart when necessary rather than force-closing an application with other vaults open. Record Windows and macOS live validation separately.
|
||||
|
||||
Use this lane after fork behavior or packaging changes when Obsidian is available, then exercise the affected workflow using the fork's V03–V11 validation gates. A blank-drawing smoke does not validate raw text, clipboard, font/image assets, saved scenes, custom pens, popout migration, offline behavior, or physical mobile touch. Record what was tested, artifact/source identity, and any pending or unavailable gates. Never deploy a local build to a personal/default vault as a substitute for the named test vault. Keep CLI eval access to internal plugin instances and temporary test controllers out of production modules.
|
||||
|
||||
Repo-wide ESLint currently reports a large backlog of pre-existing issues, so it is not yet a blocking pass/fail gate for every task.
|
||||
|
||||
@@ -541,7 +563,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.
|
||||
|
||||
+34
-2
@@ -14,10 +14,30 @@ Before spending your valuable time writing code for a new feature or significant
|
||||
2. Use Node.js 22 or newer and verify it with `node --version`. A shell that mixes a different Node binary with another installation's Corepack can fail before a build starts.
|
||||
3. Run `npm install` in the root directory to install the main dependencies.
|
||||
*(Note: The `MathjaxToSVG` sub-component has its own separate dependencies. You do not need to install them manually; the first time you run `npm run build`, it will take care of this automatically).*
|
||||
4. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
|
||||
4. Create or locate a dedicated `excalidraw-test` vault, install and enable Excalidraw from **Settings → Community plugins**, and follow [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md). The CLI runner copies the three built files from `dist/` into this vault; it rejects symlinked plugin targets. For an independent manual development setup, [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) can make reloads faster.
|
||||
|
||||
## 🛠️ 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
|
||||
|
||||
@@ -45,6 +65,18 @@ conflict handling, and the one-time adoption procedure for older workspaces.
|
||||
|
||||
At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly.
|
||||
|
||||
The native CLI lane supports macOS and Windows. Run `npm run test:obsidian:runner`
|
||||
for the offline harness tests, then `npm run verify:obsidian:plugin` to build and
|
||||
smoke-test this plugin with its installed Excalidraw package. For changes in the
|
||||
sibling fork, use `npm run verify:obsidian`, which rebuilds and copies the fork's
|
||||
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.
|
||||
|
||||
@@ -27,6 +27,9 @@ validated, and what remains uncertain.
|
||||
| Phase | Status | Current outcome |
|
||||
| --- | --- | --- |
|
||||
| Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented |
|
||||
| Attach native clipboard branches through the existing Mindmap Paste action (#2996) | Implemented; macOS main-window/floating/cross-drawing/popout paste and history validated | Script-only graph validation, native clipboard insertion, reference remapping and attachment preserve copied elements. Source-to-pasted markers have EA-owned cleanup across native Undo and reopened script sessions; input Undo stops at the pasted roots rather than assuming a history count. Windows and physical mobile remain manual gates |
|
||||
| Release keyboard scopes for retired Mindmap inputs | Complete; native Markdown Enter validated | Inline suggesters now release detached scopes and invalidate pending reopen work. Mindmap Builder closes suggesters before replacing inputs, owns hotkey recording and root registrations per instance, and checks live focus before shadowing shortcuts. All 29 script and five suggester tests pass; native docking/close and Markdown Enter checks pass |
|
||||
| Move Mindmap Builder into the EA Scripts authoring workspace | Complete; macOS main-window and direct-popout workflows validated | Extracted the script into 38 JavaScript subsystems including two modal factories, typed orchestration, and script-local catalogs. Per-invocation getters/setters preserve live closure state. The standard EA Scripts build supplies the existing publication paths without executable compression. All 23 focused tests pass; the action log records platform gaps and the detached-sidepanel callback fix |
|
||||
| Retire legacy AI settings and fallbacks | Complete | Removed the retired migration, schema/default fields, GPT reset, and AI runtime fallbacks without filtering unknown persisted keys; manual testing found no issues |
|
||||
| Extract settings implementation service | Implemented; awaiting manual validation | `PluginSettingsManager` now owns persistence, default assembly, remaining migrations, and API-key obfuscation; plugin methods and startup readiness remain intact, while temporary autosave enablement is now explicit plugin-instance state rather than persisted settings state |
|
||||
| Migrate the settings tab to declarative settings with legacy fallback | Complete | Checkpoints 4A-4E migrated the full settings surface and passed focused manual validation. Checkpoints 5/6 finalized and activated the complete tree behind the persisted, restart-applied `useDeclarativeSettings` preference. The final checkpoint removed checkpoint-era names, dead adapter/type branches, unused declarations, and tab-lifetime references to controls owned by one rendered tree. Markdown export now rebuilds declarations without replacing the active control bindings. The supported legacy preference and empty-array fallback remain intentional. The final beta.5 production build is 4,798,339 bytes, 73,417 bytes above `master` and 2,450 bytes below the completed checkpoint-6 build; the Obsidian dependency/minimum remains `1.8.7` |
|
||||
@@ -2433,3 +2436,33 @@ Before continuing to 12b, a separate checkpoint-10 corrective increment resolves
|
||||
| 2026-09-14 | Accepted checkpoint 12b own-write reload-guard extraction | The maintainer confirmed ordinary autosave/Ctrl+S, alternating multi-view editing, forced save, raw `.excalidraw` own-write suppression and external updates, back-of-note release synchronization, migration/close, and the remaining requested smoke tests all completed successfully | Checkpoint 12b is ready to commit. The branch-wide simplification and artifact audit follows as a separate review |
|
||||
| 2026-09-14 | Committed checkpoint 12b own-write reload-guard extraction | Own-write suppression and its cleanup callback now have one tested view-owned state owner | Commit `b9481c32` (`refactor: own reload suppression state`) |
|
||||
| 2026-09-14 | Completed the post-checkpoint file-persistence branch sanity review | Confirmed the new boundaries remain purpose-specific: save/revision/content identity, detached write ordering, automatic-output coalescing, same-file ownership, load generation, and raw compatibility suppression have distinct lifetimes and cannot be safely collapsed. Removed the uncalled `ViewSaveCoordinator.getLastSuccessfulPreparedSave()` and the test-only `ViewPersistenceQueue.flush()`, removed two extra end-of-file blank lines, corrected one obsolete checkpoint comment, and updated lifecycle documentation from superseded experimental descriptions to the accepted implementation. No temporary persistence instrumentation, tracked generated output, attachment, or diagnostic runtime log remains. Historical failed-5b rows and stashes remain as rejected evidence rather than executable guidance | All 12 focused persistence/lifecycle checks pass; unused-symbol validation and focused lint pass; production and library builds plus bundle syntax and cumulative `git diff --check` pass. Rollup retains the established 33 circular warnings. Final reproducible bundle: 4,936,617 bytes, SHA-256 `698e47581470b1e9a211c58bad05ed2000d56fd3097b4cb17be55856530fb73e`. `npm run madge` was attempted but its undeclared CLI is not installed in this checkout; this cleanup changes no imports, and the production graph result is unchanged |
|
||||
|
||||
### 2026-10-13 — Mindmap Builder authoring-workspace migration
|
||||
|
||||
Moved the 14,029-line source into the sibling EA Scripts workspace as 38 import-safe JavaScript subsystem modules, including separate palette/layout modal factories, with a typed launcher and script-local catalogs. Explicit invocation-scoped getters/setters retain live settings, control references, selection, transactions, and window ownership. The structural audit preserved all 243 extracted statements before a separate lifecycle correction; two failing regression tests then justified guarding the two hotkey functions against delayed callbacks after their owning sidepanel closes. The final 23 focused tests and focused lint pass. This is a module extraction, not a completed TypeScript conversion.
|
||||
|
||||
`npm run mindmap` now builds the authoring workspace and copies its standard Markdown/preview output into the existing published names. Removed the old source copy, kept the historical `.js` URL as a source pointer, and updated store/index source links, directory mtime, and release notes. Executable compression was removed because plugin 2.27.0+ already caches compilation: twenty live activations reused the same API/host with no additional script reads or compilations.
|
||||
|
||||
EA Scripts build, the plugin production build, script-store checks, and byte equality of the copied artifacts passed. The final script SHA-256 is `fc277266442fd9a451859cd09f974c6248e88536d31d0c0a7511bad59624fabe`. In the existing macOS `excalidraw-test` vault on Obsidian 1.14.4 / installed Excalidraw 2.29.0, cold launch, node creation, vertical/radial layout, folding, Markdown import/export, drawing switching, direct-popout editing/save, undo/redo, saved-drawing reopen, and sidepanel close/reopen passed with an empty error buffer and full fixture/hook cleanup. One focus-interrupted repeat required stopping only its owned CLI subprocess; cleanup and the final repeat passed. Full workspace diagnostics reproduce the same 365 type errors and nine Canvas Chat/slideshow test failures with the new script excluded; broad plugin lint reports 120 unrelated errors, while touched release-notes lint passes.
|
||||
|
||||
Risk-based follow-up: check undocked input dragging/docking and keyboard ownership during moved-tab migration in main-window/popout workflows. Persisted sidepanel restoration after application restart, Windows desktop, and physical mobile touch remain separate gates. The retained runtime's DOM styling and implicit globals require independent review. Detailed module ownership, compression rationale, and validation are in the sibling script's `CONTRIBUTING.md` and `Validation.md`.
|
||||
|
||||
### 2026-10-13 — Mindmap Builder Enter interception and keyboard ownership
|
||||
|
||||
Reproduced a pre-existing cleanup defect in the native test vault: detaching an inline link dropdown before `close()` left its keyboard scope active. Its empty Enter handler still returned false, explaining how ordinary Markdown typing could work while Enter was consumed. The original pre-module script also replaced inputs during docking without closing its previous suggester, and did not close it during sidepanel teardown. This establishes a matching failure mechanism, not proof of which scope was stuck in the maintainer's particular session.
|
||||
|
||||
`InlineLinkSuggester.close()` now pops its exact scope regardless of DOM attachment, invalidates awaited lookup work, and prevents old close timers from changing a newer session's key blocking. Script lifecycle paths close suggesters before DOM removal/replacement. The ontology input is invocation-scoped; `HotkeyRecorder` releases the exact recording scope on replacement, cancellation, exceptions, close, and EA destruction. Root overrides and DOM keyboard listeners have instance-owned cleanup, and a wildcard root handler checks live focus/dispatch eligibility before shadowing Obsidian shortcuts. It yields to original handlers outside Mindmap's context; using undefined from an explicit-key registration would still stop Obsidian's scope scan.
|
||||
|
||||
Twenty-nine script tests and five plugin suggester tests pass, along with focused lint, both builds, and script-store checks. The exact declared component package was restored with npm install (0.18.140 installed versus 0.18.143 declared), without dependency or lockfile edits. The guarded plugin-only smoke passed. Native macOS testing verified the detached-scope fix, successive recordings followed by close, open suggestions followed by docking, and real CDP Enter newlines in a disposable Markdown editor both before and after Mindmap closure. Existing main-window/direct-popout, drawing/history/save/reopen checks also passed with no captured JavaScript errors and full fixture cleanup. One initial drawing-creation CLI timeout cleaned up; the warmed retry passed. Final script SHA-256: `4fdd700d5480e0012c06e680cb633ef39f1e2bb863b8bc46af20cf6f9c00363e`.
|
||||
|
||||
Highest-probability remaining manual risk: focus and keymap ownership when recording or using link suggestions in an undocked/migrated popout. Validate Windows and physical mobile separately. Restart an already affected Obsidian session before retesting both rebuilt artifacts, because an old orphaned scope may have lost its cleanup handle. The sibling script's `HotkeyCleanup.md` records the investigation. Full EA check still encounters the same 365 unrelated type errors; the new script has none.
|
||||
|
||||
### 2026-10-13 — Native Mindmap branch paste (#2996)
|
||||
|
||||
Implemented in EA Scripts and rebuilt the published Mindmap Builder Markdown. The existing Paste action recognizes native clipboard branches, imports them through Excalidraw's normal paste event, remaps boundary/fold references, and attaches copied roots to the captured destination. Whole maps become submaps; independent paste initializes a master root. Styles, file data, group associations, pins and local submap settings are retained; disabled layout stays disabled. Unfolding a destination does not unlock copied notes. No plugin/component runtime or API changes were made for this feature.
|
||||
|
||||
Native completion and gesture/timeout cancellation are operation-owned. Scene subscriptions owned by the script EA repair transport metadata restored by native Undo, including recovery when Builder reopens. Input Undo stops at removal of the newly pasted roots and Redo replays the actual traversal; it does not assume a native capture count. Concurrent history replay and view/API retirement are guarded.
|
||||
|
||||
Validation: all 46 focused Mindmap tests pass; focused TypeScript/release-note lint and script build/store checks pass. The full workspace check still stops at 365 pre-existing type errors, with none in Mindmap Builder. Native macOS Obsidian 1.14.4 / Excalidraw 2.29.0 passed same-drawing attachment, boundary/fold reference remapping, grouped linked notes, images, cross-drawing/floating paste, disabled layout, grouped input Undo/Redo preserving preceding elements, native history metadata cleanup, and fresh-popout attachment. The final error buffer was empty and exact fixtures/controllers/read overrides were cleaned up. Test-driver iterations required asynchronous sidepanel readiness, correct clipboard realms and boxed-node container selection; failed iterations are not validation results.
|
||||
|
||||
Final native report: `/private/tmp/mindmap-branch-live-report.json`. Tested/published script SHA-256: `95937adf36fe21259a143b635e2a10e164d06b9c93a97e6fdf66fa2e00ffb43f`. The current build is installed at `Excalidraw/Scripts/Downloaded/Mindmap Builder.md` in the authorized `excalidraw-test` vault. Highest remaining manual risk: folded destinations with complete folded branches, pins/nested submaps and repeated dock/window migration. Windows modifiers and physical mobile clipboard/focus/touch need separate coverage.
|
||||
@@ -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.
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
# 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
|
||||
copy a short prompt linking to the CLI documentation, then replace the user-instructions
|
||||
placeholder with your task. 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.
|
||||
@@ -0,0 +1,311 @@
|
||||
# Obsidian runtime testing on macOS and Windows
|
||||
|
||||
This desktop lane builds the real plugin, deploys its exact artifacts to the named
|
||||
`excalidraw-test` vault, opens a disposable drawing, and checks that the Excalidraw
|
||||
API and editor mount in the main application document. It supplements source
|
||||
tests and change-specific manual checks.
|
||||
|
||||
## Prepare the test vault
|
||||
|
||||
1. Look for an existing vault named `excalidraw-test` in Obsidian's vault switcher
|
||||
or registry (`~/Library/Application Support/obsidian/obsidian.json` on macOS;
|
||||
`%APPDATA%\obsidian\obsidian.json` on Windows). Confirm its absolute path.
|
||||
2. If it is missing, ask the user to create it and install and enable Excalidraw
|
||||
through **Settings → Community plugins**. A fresh empty vault is sufficient
|
||||
for this smoke. Agents need consent to create or download a replacement vault.
|
||||
3. Open the vault in Obsidian. For a downloaded/copied vault, complete any
|
||||
first-open trust prompt, then close and reopen that vault. Finish plugin
|
||||
onboarding before automated testing.
|
||||
4. Use an Obsidian installer with CLI support and enable **Settings → General →
|
||||
Command line interface**. Follow its registration prompt; see the official
|
||||
[CLI installation and troubleshooting guide](https://obsidian.md/help/cli).
|
||||
5. Keep Obsidian running and select the test vault's main window. Ensure its
|
||||
Excalidraw drawing template does not open a chooser. Avoid simultaneous edits
|
||||
or another CLI runner in that vault during testing.
|
||||
6. Use Node.js 22 or newer and install this repository's dependencies with
|
||||
`npm install`. Check `node --version` in the same terminal used for testing.
|
||||
|
||||
The runner requires all three environment variables below. It accepts only the
|
||||
name `excalidraw-test`, checks canonical vault and configuration paths against the
|
||||
running app, requires the initial enabled Community plugin installation, and
|
||||
rejects symlinked plugin directories/artifacts. There is no default-vault fallback.
|
||||
Use the actual configuration directory if it differs from `.obsidian`.
|
||||
|
||||
## Run on Windows
|
||||
|
||||
From this plugin checkout in PowerShell, substitute your actual vault path:
|
||||
|
||||
```powershell
|
||||
$env:EXCALIDRAW_TEST_VAULT_NAME = 'excalidraw-test'
|
||||
$env:EXCALIDRAW_TEST_VAULT_PATH = 'C:\Obsidian\excalidraw-test'
|
||||
$env:EXCALIDRAW_TEST_CONFIG_DIR = 'C:\Obsidian\excalidraw-test\.obsidian'
|
||||
npm.cmd run test:obsidian:runner
|
||||
npm.cmd run verify:obsidian:plugin
|
||||
```
|
||||
|
||||
The launcher discovers `Obsidian.com` under `%LOCALAPPDATA%\Obsidian`,
|
||||
`%PROGRAMFILES%\Obsidian`, or `%PROGRAMFILES(X86)%\Obsidian`, then falls back to
|
||||
`obsidian` on PATH. For another installation, set an executable path:
|
||||
|
||||
```powershell
|
||||
$env:EXCALIDRAW_OBSIDIAN_CLI = 'C:\Program Files\Obsidian\Obsidian.com'
|
||||
```
|
||||
|
||||
Use the console launcher `.com` to capture output. The driver passes argument
|
||||
arrays directly to native processes. It launches npm/Yarn JavaScript entries
|
||||
through the current Node binary, avoiding `.cmd` shims and shell quoting.
|
||||
PowerShell environment assignments apply to the current terminal session. Use
|
||||
`npm.cmd` in PowerShell if its execution policy blocks `npm.ps1`; no global policy
|
||||
change is necessary. The same applies to `npm.cmd install` and the fork lane's
|
||||
`npm.cmd run verify:obsidian`.
|
||||
|
||||
For additional eval probes, import `spawnNativeSync` from
|
||||
`scripts/testing/host/processTools.mjs` in a Node script and pass
|
||||
`['vault=excalidraw-test', 'eval', 'code=' + code]`. Windows PowerShell can alter
|
||||
embedded native quotes, and large/multiline inline evals can corrupt Obsidian's
|
||||
console IPC JSON. The helper moves those payloads to an owned UTF-8 script in the
|
||||
system temporary directory, sends a short file-reading eval, and removes the
|
||||
directory after success or failure. This local file bridge exists only in test
|
||||
tooling; no production plugin feature reads external test scripts.
|
||||
|
||||
## Run on macOS
|
||||
|
||||
From this plugin checkout in a shell, substitute your actual vault path:
|
||||
|
||||
```bash
|
||||
export EXCALIDRAW_TEST_VAULT_NAME=excalidraw-test
|
||||
export EXCALIDRAW_TEST_VAULT_PATH="$HOME/Obsidian/excalidraw-test"
|
||||
export EXCALIDRAW_TEST_CONFIG_DIR="$EXCALIDRAW_TEST_VAULT_PATH/.obsidian"
|
||||
npm run test:obsidian:runner
|
||||
npm run verify:obsidian:plugin
|
||||
```
|
||||
|
||||
The launcher discovers `/Applications/Obsidian.app/Contents/MacOS/obsidian-cli`,
|
||||
then the application binary `/Applications/Obsidian.app/Contents/MacOS/Obsidian`,
|
||||
then `obsidian` on PATH. Set `EXCALIDRAW_OBSIDIAN_CLI` to an executable path for a
|
||||
nonstandard installation. Do not include command arguments in the override.
|
||||
macOS evals use native argument arrays without the Windows temporary-file bridge.
|
||||
|
||||
## Choose the build
|
||||
|
||||
| Command | Component input | Prerequisites |
|
||||
| --- | --- | --- |
|
||||
| `npm run test:obsidian:runner` | Fake host fixtures | Node; no Obsidian required |
|
||||
| `npm run verify:obsidian:plugin` | Installed `@zsviczian/excalidraw` artifacts | Plugin dependencies and prepared test vault |
|
||||
| `npm run verify:obsidian` | Fresh sibling fork build | Both repositories' dependencies, Yarn, prepared test vault |
|
||||
|
||||
The plugin-only lane checks the installed component version against the exact
|
||||
declared dependency, hashes its four Obsidian artifacts, and runs the real
|
||||
production `npm run build`. It does not require the sibling fork checkout. If you
|
||||
previously copied unpublished fork artifacts into `node_modules`, this lane uses
|
||||
those bytes; version equality alone does not prove published provenance. Run
|
||||
`npm install` to restore the published dependency before a release smoke.
|
||||
|
||||
For a fork integration check, use `npm run verify:obsidian`. It runs
|
||||
`yarn build:obsidian` in `../excalidraw/packages/excalidraw`, copies only the four
|
||||
generated Obsidian JavaScript/CSS files into the ignored installed package,
|
||||
checks their hashes, then builds the plugin. Set `EXCALIDRAW_FORK_ROOT` to an
|
||||
absolute checkout path when the fork is elsewhere. This temporary handoff does
|
||||
not change dependencies or lockfiles and remains in `node_modules` afterward.
|
||||
|
||||
Windows resolves Yarn's JavaScript entry from the Node installation, the user's
|
||||
global npm installation, or Corepack. For a different installation, set
|
||||
`EXCALIDRAW_YARN_CLI` to the absolute `yarn.js` path. Use the fork's declared Yarn
|
||||
version. npm must be discoverable through its `npm_execpath` or a standard Node
|
||||
installation; launching through `npm run` supplies that entry automatically.
|
||||
|
||||
## Assertions, deployment and cleanup
|
||||
|
||||
After CLI capability and target checks, the runner:
|
||||
|
||||
1. Builds the selected inputs and validates the plugin manifest ID.
|
||||
2. Disables Excalidraw in the test vault, copies `dist/main.js`, `styles.css` and
|
||||
`manifest.json`, checks deployed SHA-256 hashes, and enables the plugin.
|
||||
3. Waits for the live plugin instance and stable drawing command registration.
|
||||
4. Creates a UUID-named `__excalidraw_cli_smoke_*` drawing in the vault root through
|
||||
the plugin, opens it in a new tab, and waits for an API and editor wrapper with
|
||||
the correct owning document.
|
||||
5. Rejects captured JavaScript errors, closes/deletes its own drawing, removes its
|
||||
temporary controller, and writes `report.json`. Cleanup failure fails the run.
|
||||
|
||||
Every CLI call explicitly starts with `vault=excalidraw-test`. A CLI `Error:`
|
||||
payload is failure even when the process exits zero. Internal plugin access via
|
||||
CLI eval belongs only in these host scripts, never in production modules.
|
||||
|
||||
Deployment replaces the test vault's installed plugin build and leaves it enabled;
|
||||
it does not restore the Community release afterward. The runner does not overwrite
|
||||
`data.json`, existing notes, or other plugins. Normal plugin startup/drawing
|
||||
creation may persist its own settings. Opening the temporary tab can change focus
|
||||
and workspace history; use a disposable test vault. It clears the test vault's
|
||||
developer error buffer to attribute errors to this run.
|
||||
|
||||
The printed report path is in a unique temporary directory unless you set
|
||||
`EXCALIDRAW_TEST_REPORT_DIR`. Reports include source revisions/dirty flags, build
|
||||
mode, component version, Node/platform/Obsidian versions, component and deployed
|
||||
plugin hashes, bundle size, scenarios, the exact temporary drawing path, and
|
||||
cleanup. The runner awaits an empty view transition before deleting its drawing
|
||||
so a pending close/save cannot recreate it. Inspect both `status` and
|
||||
`cleanup`; keep reports outside the checkout and review local paths before sharing.
|
||||
|
||||
## 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
|
||||
npm run verify:obsidian:plugin -- --text-undo
|
||||
```
|
||||
|
||||
Use `npm.cmd` in PowerShell. The same `--text-undo` option works with
|
||||
`verify:obsidian` for a fork integration build. The complete #2976 fix also needs
|
||||
the component's unchanged-text history fix, included in the paired source
|
||||
checkpoint but pending package publication. Until the next component package and plugin dependency update,
|
||||
use `verify:obsidian` with the matching sibling source to test the complete pair;
|
||||
the declared `0.18.140` package does not include that component fix. The scenario
|
||||
uses native CDP
|
||||
keyboard input and the **Undo**/**Redo** toolbar buttons in the runner's
|
||||
temporary drawing. It checks raw and parsed text modes, reopening after undo and
|
||||
redo, submitting without changes, editing after undo, Markdown source preservation,
|
||||
and legacy/empty source handling. The matrix includes plain text, `[[link]]`,
|
||||
`[[link]]]` with an extra closing bracket, and `[[link|alias]]`. It writes a
|
||||
`text-undo-2976` result to the report; the parent runner still owns drawing cleanup
|
||||
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
|
||||
opening a second instance or choosing another vault.
|
||||
|
||||
If a call times out, inspect pending trust, onboarding, or native error dialogs.
|
||||
On Windows, malformed inline eval transport can produce a main-process JSON
|
||||
parse error dialog that blocks later commands. Dismiss it and retry through the
|
||||
Node helper. If necessary, ask the user to save work and restart Obsidian; do not
|
||||
force-close the application while other vaults are open. After interrupted cleanup,
|
||||
review the report/controller's exact drawing path before removing leftovers; never
|
||||
delete notes by prefix alone.
|
||||
|
||||
The default smoke covers one newly created main-window drawing. It does not validate
|
||||
saved scenes, clipboard, text editing, fonts/images, export, custom pens, popout
|
||||
migration, offline assets, or physical mobile touch. For affected features, follow
|
||||
the fork's [native validation procedure](https://github.com/zsviczian/excalidraw/blob/master/dev-docs/Obsidian/OBSIDIAN_RUNTIME_TESTING.md)
|
||||
and its V03–V11 gates (also available in the sibling checkout). Record macOS and
|
||||
Windows live results separately, along with artifact identity and unavailable
|
||||
gates. A test of platform argument construction is not a live macOS smoke.
|
||||
@@ -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
|
||||
@@ -0,0 +1,45 @@
|
||||
# Issue assessment
|
||||
|
||||
Use this template for a source-based GitHub issue assessment intended for a separate implementation agent. Post the completed assessment as an issue comment only when authorized. Investigation does not authorize code changes.
|
||||
|
||||
Before writing, read the issue and comments, related PRs and commits, and the relevant repositories' `AGENTS.md` / `CONTRIBUTING.md`. Trace the affected code and callers at known revisions. Link to commit-pinned source where useful. Keep verified evidence separate from hypotheses; omit sections that do not apply.
|
||||
|
||||
## Triage and handoff
|
||||
|
||||
1. Investigate and comment on each issue; check whether a fix or PR already exists.
|
||||
2. Return a short prioritized list to the maintainer, including issues ready for implementation and those needing more evidence.
|
||||
3. Only after the maintainer selects specific issues, prepare implementation branches and draft PRs using [issue resolution](issue-resolution.md). An assessment alone does not authorize them.
|
||||
|
||||
## GitHub issue comment template
|
||||
|
||||
### Technical assessment — Zsolt's Codex Agent
|
||||
|
||||
**Scope and baseline:** Issue #…; plugin `master@SHA`; fork / Extras revisions if relevant.
|
||||
|
||||
**Observed behavior and evidence**
|
||||
- Reproduction conditions and expected versus actual behavior:
|
||||
- Relevant code paths, issue discussions, and existing fix attempts (links):
|
||||
|
||||
**Root-cause assessment**
|
||||
- Verified facts:
|
||||
- Most likely explanation and confidence (**high / medium / low**):
|
||||
- What would confirm or disprove it:
|
||||
|
||||
**Recommended resolution**
|
||||
- Proposed change and owning repository/repositories:
|
||||
- Dependencies, related PRs, or coordinated release requirements:
|
||||
- Important alternatives or trade-offs, if any:
|
||||
|
||||
**Validation and acceptance**
|
||||
- Automated regression tests to add or update:
|
||||
- Manual checks appropriate to the risk (for example main window, popout, mobile, reload, or offline):
|
||||
- Acceptance criteria:
|
||||
|
||||
**Risks and remaining questions**
|
||||
- Potential regressions and unresolved evidence:
|
||||
|
||||
**Disposition**
|
||||
- **Implement / review existing fix / investigate further / defer**, with priority and reason:
|
||||
- Prerequisites for an implementation handoff:
|
||||
|
||||
Do not describe a hypothesis as a proven cause, or a proposed test as an executed test. Keep the assessment actionable without prescribing an unnecessary refactor.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Issue implementation handoff and resolution
|
||||
|
||||
Use this workflow after the maintainer selects an issue from the [assessment shortlist](issue-assessment.md). The assessment remains in the GitHub issue; a draft PR is the implementation queue and its branch is the implementation workspace. Follow `AGENTS.md` and `CONTRIBUTING.md`.
|
||||
|
||||
## Prepare a draft PR — chat agent
|
||||
|
||||
1. Recheck the issue, comments, existing PRs, and current `master`; do not duplicate ongoing or merged work.
|
||||
2. Create a dedicated `YYYY-MM-DD-issue-N-short-topic` branch from the appropriate repository's `master`. Keep plugin, fork, and Extras changes in their owning repositories; link companion PRs when coordination is required.
|
||||
3. GitHub requires a commit difference before opening a PR. For a **plan-only** branch, commit a small `docs/agent-handoffs/issue-N.md` file linking the issue and stating that the file is temporary. Do not modify runtime code. The implementing agent must remove this file before the PR is finalized.
|
||||
4. Open a **draft** PR targeting `master`, with a title such as `Plan: Fix #N — short description`, using the template below. Confirm the draft PR and branch are readable; return the link. Do not mark the issue fixed.
|
||||
|
||||
### Draft PR description template
|
||||
|
||||
**Status:** Implementation handoff only; not yet a fix.
|
||||
|
||||
**Issue and assessment:** #N, link to the detailed technical assessment comment.
|
||||
|
||||
**Baseline and dependencies:** Source commit(s), owning repository, related branches/PRs, required fork/Extras package coordination.
|
||||
|
||||
**Implementation plan**
|
||||
- Likely root cause and evidence (brief; do not duplicate the assessment):
|
||||
- Recommended code changes and key paths:
|
||||
- Constraints, alternatives, and risks:
|
||||
|
||||
**Acceptance and tests**
|
||||
- Expected behavior:
|
||||
- Automated regression tests:
|
||||
- Manual checks (main window / popout / reload / mobile / offline as relevant):
|
||||
|
||||
**For the implementing agent:** Re-read the current issue, PR, source, and repo instructions; verify assumptions, implement on this branch, remove the plan-only handoff file, update the PR description with actual results, and leave the PR as draft until ready for maintainer review.
|
||||
|
||||
## Complete the implementation — local agent
|
||||
|
||||
Use the same branch and draft PR. Before coding, confirm the branch head and whether the issue or dependencies have changed. Do not start a new competing PR. Commit the code and tests, remove the temporary handoff file, and replace the plan-only PR description with a concise outcome summary:
|
||||
|
||||
### Completed PR / handoff template
|
||||
|
||||
**Problem and root cause**
|
||||
- What failed, under which conditions:
|
||||
- Confirmed cause and key source references:
|
||||
|
||||
**Change**
|
||||
- What changed and why this is the smallest safe fix:
|
||||
- Affected files and repositories; dependency or package-release coordination:
|
||||
|
||||
**Validation**
|
||||
- Automated tests, builds, and lint actually run, with results:
|
||||
- Manual Obsidian checks completed (platform, main window, popout, reload, mobile, etc.):
|
||||
|
||||
**Remaining risk**
|
||||
- Known limitations or untested cases:
|
||||
- Up to three priority manual checks for the reviewer:
|
||||
|
||||
Link the original issue, assessment, and companion PRs. Never describe planned tests as completed. Mark ready for review only when implementation and available validation are complete; do not merge without maintainer authorization.
|
||||
@@ -1,3 +1,7 @@
|
||||
/*
|
||||
Because of misleading code scanner results that incorrectly pick up the mindmap MindMap Builder.js script as a potential security risk due to "hard coded" :) URLs - yes, in the comments explaining how to use the script - I have decided to move the script to a separate file. I will not add the link here, becuase it will be picked up by scanners: look for "MindMap Builder.js.md" in the repo. Sorry for the inconvenience, but I want to ensure that false positives do not cause unnecessary alarm, and do not undermine the trust in the plugin that I have built with care and dedication.
|
||||
*/
|
||||
Mindmap Builder's maintained source has moved to the EA Scripts authoring workspace:
|
||||
https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/mindmap-builder
|
||||
|
||||
Install the executable Markdown script from ea-scripts/Mindmap Builder.md.
|
||||
This historical source URL remains as a pointer for existing documentation links.
|
||||
*/
|
||||
File diff suppressed because it is too large.
Load diff
+14763
-1183
File diff suppressed because it is too large.
Load diff
@@ -641,7 +641,7 @@
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap Builder.md",
|
||||
"mtime": 1785045917003
|
||||
"mtime": 1791905383390
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap Builder.svg",
|
||||
|
||||
@@ -515,7 +515,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href="https://visual-thinking-workshop.com/mindmap" target="_blank">MindMap Builder Self-Paced Course</a>!<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=5G9QF-u9w0Q" target="_blank"><img src ="https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></td></tr></table>
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/mindmap-builder'>Modular source on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href="https://visual-thinking-workshop.com/mindmap" target="_blank">MindMap Builder Self-Paced Course</a>!<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=5G9QF-u9w0Q" target="_blank"><img src ="https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></td></tr></table>
|
||||
|
||||
## Mindmap connector
|
||||
```excalidraw-script-install
|
||||
|
||||
@@ -683,7 +683,7 @@
|
||||
"iconUrl": "https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg",
|
||||
"author": "@zsviczian",
|
||||
"authorUrl": "https://github.com/zsviczian",
|
||||
"sourceUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.md",
|
||||
"sourceUrl": "https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/mindmap-builder",
|
||||
"descriptionHtml": "Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href=\"https://visual-thinking-workshop.com/mindmap\" target=\"_blank\">MindMap Builder Self-Paced Course</a>!<br><a href=\"https://www.youtube.com/watch?v=qY66yoobaX4\" target=\"_blank\"><img src =\"https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg\" style=\"width:400px;\"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href=\"https://www.youtube.com/watch?v=5G9QF-u9w0Q\" target=\"_blank\"><img src =\"https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg\" style=\"width:400px;\"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'>",
|
||||
"categories": [
|
||||
"Editors Picks",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.28.0-beta.4",
|
||||
"version": "2.29.0",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.27.3",
|
||||
"version": "2.29.0",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+11
-594
@@ -13,7 +13,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.139",
|
||||
"@zsviczian/excalidraw": "0.18.143",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -65,7 +65,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",
|
||||
@@ -2367,44 +2366,6 @@
|
||||
"ret": "~0.1.10"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.scandir": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
|
||||
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.stat": "2.0.5",
|
||||
"run-parallel": "^1.1.9"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.stat": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
|
||||
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.walk": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
|
||||
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.scandir": "2.1.5",
|
||||
"fastq": "^1.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@pkgr/core": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.2.tgz",
|
||||
@@ -4821,16 +4782,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/fs-extra": {
|
||||
"version": "8.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.1.5.tgz",
|
||||
"integrity": "sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/geojson": {
|
||||
"version": "7946.0.16",
|
||||
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
|
||||
@@ -4838,17 +4789,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/glob": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz",
|
||||
"integrity": "sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/minimatch": "*",
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/js-beautify": {
|
||||
"version": "1.14.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/js-beautify/-/js-beautify-1.14.3.tgz",
|
||||
@@ -4870,13 +4810,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/minimatch": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz",
|
||||
"integrity": "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.19.20",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.20.tgz",
|
||||
@@ -5255,9 +5188,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.139",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.139.tgz",
|
||||
"integrity": "sha512-3d31zicckBIK4VMyldgCLuPON5xCWNTxn0vF1r3FdlVbfLXI+OFdeq6Qog8aYO4IXN2W5XKdIF5Byzk17U4Aqg==",
|
||||
"version": "0.18.143",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.143.tgz",
|
||||
"integrity": "sha512-ElZG+PmNM1AL4JVp6sPoLkf9xZ9zbUiTjgWBT8EBtPcRSWx6zQV9BRXD5XSG9k0d+GFpUyypltxkoKhHDDK3IQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
@@ -5289,7 +5222,6 @@
|
||||
"pwacompat": "2.0.17",
|
||||
"radix-ui": "1.4.3",
|
||||
"roughjs": "4.6.4",
|
||||
"sass": "1.51.0",
|
||||
"tunnel-rat": "0.1.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
@@ -5431,31 +5363,6 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/anymatch": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
|
||||
"integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"normalize-path": "^3.0.0",
|
||||
"picomatch": "^2.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/anymatch/node_modules/picomatch": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
|
||||
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
@@ -5515,16 +5422,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/array-union": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz",
|
||||
"integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/array.prototype.findlast": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz",
|
||||
@@ -5733,18 +5630,6 @@
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/binary-extensions": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
||||
"integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/boolbase": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
|
||||
@@ -5763,18 +5648,6 @@
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/braces": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
|
||||
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fill-range": "^7.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/browser-fs-access": {
|
||||
"version": "0.38.0",
|
||||
"resolved": "https://registry.npmjs.org/browser-fs-access/-/browser-fs-access-0.38.0.tgz",
|
||||
@@ -5983,42 +5856,6 @@
|
||||
"chevrotain": "^11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"anymatch": "~3.1.2",
|
||||
"braces": "~3.0.2",
|
||||
"glob-parent": "~5.1.2",
|
||||
"is-binary-path": "~2.1.0",
|
||||
"is-glob": "~4.0.1",
|
||||
"normalize-path": "~3.0.0",
|
||||
"readdirp": "~3.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar/node_modules/glob-parent": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"is-glob": "^4.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/chroma-js": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/chroma-js/-/chroma-js-3.2.0.tgz",
|
||||
@@ -6132,13 +5969,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/colorette": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz",
|
||||
"integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
|
||||
@@ -7167,19 +6997,6 @@
|
||||
"integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dir-glob": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz",
|
||||
"integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-type": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/doctrine": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",
|
||||
@@ -8354,36 +8171,6 @@
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/fast-glob": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.stat": "^2.0.2",
|
||||
"@nodelib/fs.walk": "^1.2.3",
|
||||
"glob-parent": "^5.1.2",
|
||||
"merge2": "^1.3.0",
|
||||
"micromatch": "^4.0.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-glob/node_modules/glob-parent": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"is-glob": "^4.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-json-stable-stringify": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
@@ -8415,16 +8202,6 @@
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/fastq": {
|
||||
"version": "1.20.1",
|
||||
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
|
||||
"integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"reusify": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
@@ -8456,18 +8233,6 @@
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"to-regex-range": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
|
||||
@@ -8522,32 +8287,11 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/fs-extra": {
|
||||
"version": "8.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
|
||||
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.2.0",
|
||||
"jsonfile": "^4.0.0",
|
||||
"universalify": "^0.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6 <7 || >=8"
|
||||
}
|
||||
},
|
||||
"node_modules/fs.realpath": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
||||
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
@@ -8778,48 +8522,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/globby": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/globby/-/globby-10.0.1.tgz",
|
||||
"integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/glob": "^7.1.1",
|
||||
"array-union": "^2.1.0",
|
||||
"dir-glob": "^3.0.1",
|
||||
"fast-glob": "^3.0.3",
|
||||
"glob": "^7.1.3",
|
||||
"ignore": "^5.1.1",
|
||||
"merge2": "^1.2.3",
|
||||
"slash": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/globby/node_modules/glob": {
|
||||
"version": "7.2.3",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.1.1",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/glur": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/glur/-/glur-1.1.2.tgz",
|
||||
@@ -8978,12 +8680,6 @@
|
||||
"pica": "^7.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/immutable": {
|
||||
"version": "4.3.9",
|
||||
"resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.9.tgz",
|
||||
"integrity": "sha512-ObHy4YN7ycwZOUCLI1/6svfyAFu7vL8RhAvVu/bh/RZW9EPlOyDaQ9jDQWCtdqzaXUjgXZCW1migtHE7YI7UGQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/import-fresh": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
|
||||
@@ -9022,18 +8718,6 @@
|
||||
"node": ">=0.8.19"
|
||||
}
|
||||
},
|
||||
"node_modules/inflight": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
|
||||
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"once": "^1.3.0",
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
@@ -9119,18 +8803,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/is-binary-path": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
|
||||
"integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"binary-extensions": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-boolean-object": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz",
|
||||
@@ -9232,6 +8904,7 @@
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -9277,6 +8950,7 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.1"
|
||||
@@ -9350,15 +9024,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/is-number": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
|
||||
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-number-object": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz",
|
||||
@@ -9376,16 +9041,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/is-plain-object": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.1.tgz",
|
||||
"integrity": "sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-reference": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz",
|
||||
@@ -9791,16 +9446,6 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonfile": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
|
||||
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optionalDependencies": {
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsx-ast-utils": {
|
||||
"version": "3.3.5",
|
||||
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
|
||||
@@ -10053,16 +9698,6 @@
|
||||
"dev": true,
|
||||
"license": "CC0-1.0"
|
||||
},
|
||||
"node_modules/merge2": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
|
||||
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/mermaid": {
|
||||
"version": "11.15.0",
|
||||
"resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.15.0.tgz",
|
||||
@@ -10124,33 +9759,6 @@
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/micromatch": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"braces": "^3.0.3",
|
||||
"picomatch": "^2.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
}
|
||||
},
|
||||
"node_modules/micromatch/node_modules/picomatch": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
|
||||
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
|
||||
@@ -10275,15 +9883,6 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/normalize-path": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
||||
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nth-check": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
|
||||
@@ -10434,16 +10033,6 @@
|
||||
"@codemirror/view": "^6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/once": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/open": {
|
||||
"version": "11.0.0",
|
||||
"resolved": "https://registry.npmjs.org/open/-/open-11.0.0.tgz",
|
||||
@@ -10575,16 +10164,6 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-is-absolute": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
||||
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||
@@ -10602,16 +10181,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/path-type": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",
|
||||
"integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/perfect-freehand": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/perfect-freehand/-/perfect-freehand-1.2.0.tgz",
|
||||
@@ -11278,27 +10847,6 @@
|
||||
"integrity": "sha512-6Du7IZdIy7cHiv7AhtDy4X2QRM8IAD5DII69mt5qWibC2d15ZU8DmBG1WdZKekG11cChSu4zkSUGPF9sweOl6w==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/queue-microtask": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/radix-ui": {
|
||||
"version": "1.4.3",
|
||||
"resolved": "https://registry.npmjs.org/radix-ui/-/radix-ui-1.4.3.tgz",
|
||||
@@ -11473,30 +11021,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/readdirp": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
|
||||
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"picomatch": "^2.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/readdirp/node_modules/picomatch": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
|
||||
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect.getprototypeof": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
|
||||
@@ -11671,17 +11195,6 @@
|
||||
"node": ">=0.12"
|
||||
}
|
||||
},
|
||||
"node_modules/reusify": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
|
||||
"integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"iojs": ">=1.0.0",
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/robust-predicates": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
|
||||
@@ -11734,23 +11247,6 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/rollup-plugin-copy": {
|
||||
"version": "3.5.0",
|
||||
"resolved": "https://registry.npmjs.org/rollup-plugin-copy/-/rollup-plugin-copy-3.5.0.tgz",
|
||||
"integrity": "sha512-wI8D5dvYovRMx/YYKtUNt3Yxaw4ORC9xo6Gt9t22kveWz1enG9QrhVlagzwrxSC455xD1dHMKhIJkbsQ7d48BA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/fs-extra": "^8.0.1",
|
||||
"colorette": "^1.1.0",
|
||||
"fs-extra": "^8.1.0",
|
||||
"globby": "10.0.1",
|
||||
"is-plain-object": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.3"
|
||||
}
|
||||
},
|
||||
"node_modules/rollup-plugin-visualizer": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/rollup-plugin-visualizer/-/rollup-plugin-visualizer-7.0.1.tgz",
|
||||
@@ -11823,30 +11319,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/run-parallel": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
|
||||
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"queue-microtask": "^1.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/rw": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
|
||||
@@ -11947,23 +11419,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/sass": {
|
||||
"version": "1.51.0",
|
||||
"resolved": "https://registry.npmjs.org/sass/-/sass-1.51.0.tgz",
|
||||
"integrity": "sha512-haGdpTgywJTvHC2b91GSq+clTKGbtkkZmVAb82jZQN/wTy6qs8DdFm2lhEQbEwrY0QDRgSQ3xDurqM977C3noA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chokidar": ">=3.0.0 <4.0.0",
|
||||
"immutable": "^4.0.0",
|
||||
"source-map-js": ">=0.6.2 <2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"sass": "sass.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sax": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
|
||||
@@ -12148,16 +11603,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/slash": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
|
||||
"integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/sliced": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz",
|
||||
@@ -12186,9 +11631,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
|
||||
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -12556,18 +12002,6 @@
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/to-regex-range": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-number": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/toml-eslint-parser": {
|
||||
"version": "0.9.3",
|
||||
"resolved": "https://registry.npmjs.org/toml-eslint-parser/-/toml-eslint-parser-0.9.3.tgz",
|
||||
@@ -12873,16 +12307,6 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
|
||||
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/update-browserslist-db": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
|
||||
@@ -13186,13 +12610,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/wsl-utils": {
|
||||
"version": "0.3.1",
|
||||
"resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.3.1.tgz",
|
||||
|
||||
+11
-3
@@ -10,6 +10,11 @@
|
||||
"scripts": {
|
||||
"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",
|
||||
"test:inline-link-suggester": "node --test scripts/testing/inlineLinkSuggester.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",
|
||||
"code": "eslint --max-warnings=0 --ext .ts,.tsx ./src",
|
||||
"code:fix": "eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
|
||||
@@ -34,7 +39,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.139",
|
||||
"@zsviczian/excalidraw": "0.18.143",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -86,7 +91,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",
|
||||
@@ -101,7 +105,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"
|
||||
|
||||
+21
-64
@@ -1,11 +1,9 @@
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import zlib from 'node:zlib';
|
||||
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';
|
||||
@@ -28,64 +26,26 @@ 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 });
|
||||
const isProd = (process.env.NODE_ENV === "production");
|
||||
const isLib = (process.env.NODE_ENV === "lib");
|
||||
|
||||
const DEFAULT_PLUGIN_REPOSITORY = {
|
||||
owner: "zsviczian",
|
||||
name: "obsidian-excalidraw-plugin",
|
||||
ref: "master",
|
||||
};
|
||||
|
||||
const resolvePluginRepositoryContext = () => {
|
||||
const repository = { ...DEFAULT_PLUGIN_REPOSITORY };
|
||||
|
||||
try {
|
||||
const remoteUrl = execFileSync("git", ["remote", "get-url", "origin"], {
|
||||
cwd: process.cwd(),
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
const match = remoteUrl.match(
|
||||
/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/i,
|
||||
);
|
||||
if (match) {
|
||||
repository.owner = match[1];
|
||||
repository.name = match[2];
|
||||
}
|
||||
|
||||
const branch = execFileSync("git", ["branch", "--show-current"], {
|
||||
cwd: process.cwd(),
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
if (branch) {
|
||||
repository.ref = branch;
|
||||
return repository;
|
||||
}
|
||||
|
||||
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: process.cwd(),
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
if (commit) {
|
||||
repository.ref = commit;
|
||||
}
|
||||
} catch {
|
||||
// Source archives do not include .git. Keep canonical release defaults.
|
||||
}
|
||||
|
||||
return repository;
|
||||
};
|
||||
|
||||
const pluginRepository = resolvePluginRepositoryContext();
|
||||
console.log(
|
||||
`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}; repository: ${pluginRepository.owner}/${pluginRepository.name}@${pluginRepository.ref}`,
|
||||
);
|
||||
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
|
||||
|
||||
|
||||
// Add non-English locales here to embed them as compressed payloads in main.js.
|
||||
@@ -206,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.
|
||||
@@ -354,9 +314,6 @@ const getRollupPlugins = (tsconfig, ...plugins) => [
|
||||
replace({
|
||||
preventAssignment: true,
|
||||
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
|
||||
__PLUGIN_REPOSITORY_OWNER__: JSON.stringify(pluginRepository.owner),
|
||||
__PLUGIN_REPOSITORY_NAME__: JSON.stringify(pluginRepository.name),
|
||||
__PLUGIN_REPOSITORY_REF__: JSON.stringify(pluginRepository.ref),
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve({ browser: true, preferBuiltins: false }),
|
||||
@@ -399,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),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -417,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,220 @@
|
||||
// This component imports types that are unavailable to this Node process, so
|
||||
// these checks inspect its TypeScript syntax. Node identity uses assert.ok because
|
||||
// serializing a parent-linked AST can exhaust the heap.
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import ts from "typescript";
|
||||
|
||||
const source = await readFile(
|
||||
new URL("../src/view/components/CustomEmbeddable.tsx", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const file = ts.createSourceFile(
|
||||
"CustomEmbeddable.tsx",
|
||||
source,
|
||||
ts.ScriptTarget.Latest,
|
||||
true,
|
||||
ts.ScriptKind.TSX,
|
||||
);
|
||||
|
||||
const log = (message) => process.stdout.write(`${message}\n`);
|
||||
|
||||
const collect = (match) => {
|
||||
const found = [];
|
||||
const visit = (node) => {
|
||||
if (match(node)) {
|
||||
found.push(node);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(file);
|
||||
return found;
|
||||
};
|
||||
|
||||
const enclosingFunction = (node) => {
|
||||
for (let parent = node.parent; parent; parent = parent.parent) {
|
||||
if (ts.isFunctionLike(parent)) {
|
||||
return parent;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const enclosingStatement = (node) => {
|
||||
let current = node;
|
||||
while (current.parent && !ts.isStatement(current)) {
|
||||
current = current.parent;
|
||||
}
|
||||
return current;
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
collect(
|
||||
(node) =>
|
||||
ts.isImportDeclaration(node) &&
|
||||
node.moduleSpecifier.text === "src/utils/embeddableMountPlan",
|
||||
).length,
|
||||
1,
|
||||
"the component has one embeddable mount-plan import",
|
||||
);
|
||||
|
||||
const dispatches = collect(
|
||||
(node) =>
|
||||
ts.isCallExpression(node) &&
|
||||
ts.isIdentifier(node.expression) &&
|
||||
node.expression.text === "mountEmbeddableHost",
|
||||
);
|
||||
assert.equal(
|
||||
dispatches.length,
|
||||
1,
|
||||
"the component has one mountEmbeddableHost call",
|
||||
);
|
||||
const [dispatch] = dispatches;
|
||||
const effect = enclosingFunction(dispatch);
|
||||
assert.ok(effect, "mountEmbeddableHost is called by a function");
|
||||
|
||||
const [options] = dispatch.arguments;
|
||||
assert.ok(
|
||||
options && ts.isObjectLiteralExpression(options),
|
||||
"mountEmbeddableHost receives an options object",
|
||||
);
|
||||
const option = (name) =>
|
||||
options.properties.find(
|
||||
(property) =>
|
||||
property.name &&
|
||||
ts.isIdentifier(property.name) &&
|
||||
property.name.text === name,
|
||||
);
|
||||
|
||||
for (const name of [
|
||||
"subpath",
|
||||
"fileExtension",
|
||||
"getHost",
|
||||
"isCancelled",
|
||||
"createCanvasNode",
|
||||
"createWorkspaceLeaf",
|
||||
]) {
|
||||
assert.ok(option(name), `the options object has ${name}`);
|
||||
}
|
||||
|
||||
assert.ok(
|
||||
ts.isShorthandPropertyAssignment(option("subpath")),
|
||||
"subpath is a shorthand option",
|
||||
);
|
||||
assert.equal(
|
||||
option("fileExtension").initializer?.getText(file),
|
||||
"file.extension",
|
||||
"fileExtension is file.extension",
|
||||
);
|
||||
const getHost = option("getHost");
|
||||
assert.ok(
|
||||
ts.isPropertyAssignment(getHost) &&
|
||||
ts.isArrowFunction(getHost.initializer) &&
|
||||
getHost.initializer.body.getText(file) === "view.canvasNodeFactory",
|
||||
"getHost returns view.canvasNodeFactory",
|
||||
);
|
||||
|
||||
const statement = enclosingStatement(dispatch);
|
||||
assert.ok(
|
||||
ts.isExpressionStatement(statement),
|
||||
"mountEmbeddableHost is an expression statement",
|
||||
);
|
||||
assert.ok(
|
||||
statement.parent === effect.body,
|
||||
"the expression statement belongs to the function body",
|
||||
);
|
||||
const handledDispatch = ts.isVoidExpression(statement.expression)
|
||||
? statement.expression.expression
|
||||
: statement.expression;
|
||||
assert.ok(
|
||||
ts.isCallExpression(handledDispatch) &&
|
||||
ts.isPropertyAccessExpression(handledDispatch.expression) &&
|
||||
handledDispatch.expression.expression === dispatch &&
|
||||
handledDispatch.expression.name.text === "catch",
|
||||
"the mount dispatch handles rejected promises",
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
collect(
|
||||
(node) =>
|
||||
ts.isIdentifier(node) &&
|
||||
node.text === "canvasNodeFactory" &&
|
||||
enclosingFunction(node) === effect,
|
||||
).length,
|
||||
0,
|
||||
"the caller body has no canvasNodeFactory identifier",
|
||||
);
|
||||
|
||||
for (const name of ["createNode", "mountWorkspaceLeaf"]) {
|
||||
assert.equal(
|
||||
collect(
|
||||
(node) =>
|
||||
ts.isCallExpression(node) &&
|
||||
ts.isIdentifier(node.expression) &&
|
||||
node.expression.text === name &&
|
||||
enclosingFunction(node) === effect,
|
||||
).length,
|
||||
0,
|
||||
`the caller body has no direct ${name} call`,
|
||||
);
|
||||
}
|
||||
|
||||
const isCancelled = option("isCancelled");
|
||||
assert.ok(
|
||||
ts.isPropertyAssignment(isCancelled) &&
|
||||
ts.isArrowFunction(isCancelled.initializer),
|
||||
"isCancelled is an arrow function",
|
||||
);
|
||||
let firstOperand = isCancelled.initializer.body;
|
||||
while (
|
||||
ts.isBinaryExpression(firstOperand) &&
|
||||
firstOperand.operatorToken.kind === ts.SyntaxKind.BarBarToken
|
||||
) {
|
||||
firstOperand = firstOperand.left;
|
||||
}
|
||||
assert.ok(
|
||||
ts.isIdentifier(firstOperand) && firstOperand.text === "effectCancelled",
|
||||
"the cancellation expression starts with effectCancelled",
|
||||
);
|
||||
|
||||
const declarations = collect(
|
||||
(node) =>
|
||||
ts.isVariableDeclaration(node) &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
node.name.text === "effectCancelled",
|
||||
);
|
||||
assert.equal(
|
||||
declarations.length,
|
||||
1,
|
||||
"effectCancelled has one declaration",
|
||||
);
|
||||
assert.ok(
|
||||
enclosingFunction(declarations[0]) === effect,
|
||||
"effectCancelled is declared by the calling function",
|
||||
);
|
||||
|
||||
const cleanup = effect.body.statements.find(ts.isReturnStatement);
|
||||
assert.ok(
|
||||
cleanup && ts.isArrowFunction(cleanup.expression),
|
||||
"the calling function returns an arrow function",
|
||||
);
|
||||
const [firstCleanupStatement] = cleanup.expression.body.statements;
|
||||
assert.equal(
|
||||
firstCleanupStatement.getText(file),
|
||||
"effectCancelled = true;",
|
||||
"the cleanup starts with effectCancelled = true;",
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
collect(
|
||||
(node) =>
|
||||
ts.isVariableDeclaration(node) &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
node.name.text === "mountWorkspaceLeaf" &&
|
||||
enclosingFunction(node) === effect,
|
||||
).length,
|
||||
1,
|
||||
"mountWorkspaceLeaf has one declaration in the calling function",
|
||||
);
|
||||
|
||||
log("embeddable mount call site checks passed");
|
||||
@@ -0,0 +1,730 @@
|
||||
// Exercises host selection and CanvasNodeFactory lifecycle behavior. The factory
|
||||
// dependencies are aliased to the local stub module for this Node process.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createJiti } from "jiti";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const stubs = path.join(here, "check-embeddable-mount-plan.stubs.mjs");
|
||||
const jiti = createJiti(import.meta.url, {
|
||||
alias: { obsidian: stubs, "../../utils/obsidianUtils": stubs },
|
||||
});
|
||||
|
||||
//The factory reads this global to tell a main-window split from a popout one.
|
||||
globalThis.mainDocument = {};
|
||||
|
||||
const {
|
||||
CANVAS_NODE_HOST_WAIT_TIMEOUT_MS,
|
||||
awaitCanvasNodeHost,
|
||||
mountEmbeddableHost,
|
||||
requiresCanvasNodeHost,
|
||||
} = await jiti.import("../src/utils/embeddableMountPlan.ts");
|
||||
const { CanvasNodeFactory } = await jiti.import(
|
||||
"../src/view/managers/CanvasNodeFactory.ts",
|
||||
);
|
||||
|
||||
const log = (message) => process.stdout.write(`${message}\n`);
|
||||
|
||||
//The module defaults its wait to Obsidian's `sleep` global, absent here.
|
||||
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
//The wait's poll delay, with hooks keyed by poll number. A hook runs once that
|
||||
//poll has been entered, so an event lands at a known point of the wait, and a
|
||||
//wait that outlives every hook fails the script.
|
||||
const polling = (hooks = {}, limit = 50) => {
|
||||
const polls = {
|
||||
count: 0,
|
||||
delay: (ms) => {
|
||||
polls.count += 1;
|
||||
if (polls.count > limit) {
|
||||
return Promise.reject(new Error(`still polling after ${limit} polls`));
|
||||
}
|
||||
hooks[polls.count]?.();
|
||||
return delay(ms);
|
||||
},
|
||||
};
|
||||
return polls;
|
||||
};
|
||||
|
||||
//Cancellation is live at setup, cancelled on the cleanup read, then live again
|
||||
//when the refs are populated.
|
||||
const cancelledOnRead = (read) => {
|
||||
let reads = 0;
|
||||
return () => {
|
||||
reads += 1;
|
||||
return reads === read;
|
||||
};
|
||||
};
|
||||
|
||||
const hostReadyOnRead = (read) => {
|
||||
const host = {
|
||||
reads: 0,
|
||||
isInitialized: () => {
|
||||
host.reads += 1;
|
||||
return host.reads >= read;
|
||||
},
|
||||
};
|
||||
return host;
|
||||
};
|
||||
|
||||
const unreadyHost = { isInitialized: () => false };
|
||||
|
||||
//A host that reports its lifecycle, as `CanvasNodeFactory` does.
|
||||
const lifecycleHost = () => {
|
||||
let settle;
|
||||
const host = {
|
||||
initialized: false,
|
||||
isInitialized: () => host.initialized,
|
||||
whenInitialized: new Promise((resolve) => {
|
||||
settle = resolve;
|
||||
}),
|
||||
ready: () => {
|
||||
host.initialized = true;
|
||||
settle(true);
|
||||
},
|
||||
//initialize() threw, or destroy() ran: it will never host a node.
|
||||
givesUp: () => {
|
||||
host.initialized = false;
|
||||
settle(false);
|
||||
},
|
||||
};
|
||||
return host;
|
||||
};
|
||||
|
||||
const neverSettlingHost = () => ({
|
||||
isInitialized: () => false,
|
||||
whenInitialized: new Promise(() => {}),
|
||||
});
|
||||
|
||||
const mountRecorder = (overrides = {}) => {
|
||||
const calls = { canvasNodes: 0, workspaceLeaves: 0 };
|
||||
return {
|
||||
calls,
|
||||
options: {
|
||||
subpath: "#Section",
|
||||
fileExtension: "md",
|
||||
getHost: () => ({ isInitialized: () => true }),
|
||||
createCanvasNode: () => {
|
||||
calls.canvasNodes += 1;
|
||||
},
|
||||
createWorkspaceLeaf: () => {
|
||||
calls.workspaceLeaves += 1;
|
||||
},
|
||||
timeoutMs: 200,
|
||||
intervalMs: 1,
|
||||
delay,
|
||||
...overrides,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
//Minimal `ExcalidrawView` stand-in: the members `initialize()` reaches.
|
||||
const fakeView = ({ loadMs = 0, loadThrows = false } = {}) => ({
|
||||
ownerDocument: {},
|
||||
app: {
|
||||
internalPlugins: {
|
||||
plugins: {
|
||||
canvas: {
|
||||
_loaded: false,
|
||||
load: async () => {
|
||||
await delay(loadMs);
|
||||
if (loadThrows) {
|
||||
throw new Error("canvas plugin failed to load");
|
||||
}
|
||||
},
|
||||
views: { canvas: () => ({ canvas: { createFileNode: () => ({}) } }) },
|
||||
},
|
||||
},
|
||||
},
|
||||
workspace: {
|
||||
rootSplit: {},
|
||||
floatingSplit: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
//Resolves to the promise's value, or to `PENDING` if it has not settled.
|
||||
const PENDING = Symbol("pending");
|
||||
const settleWithin = (promise, ms = 50) =>
|
||||
Promise.race([promise, delay(ms).then(() => PENDING)]);
|
||||
|
||||
//Blocks run independently.
|
||||
const blocks = [];
|
||||
const block = (name, fn) => blocks.push([name, fn]);
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
//requiresCanvasNodeHost: which embeds can only be rendered by a Canvas node
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
block("only a markdown subpath embed requires a canvas node host", () => {
|
||||
for (const [subpath, extension, required] of [
|
||||
["#Section", "md", true],
|
||||
["#Section", "MD", true],
|
||||
["#^blockid", "md", true],
|
||||
["#", "md", true],
|
||||
[null, "md", false],
|
||||
["", "md", false],
|
||||
[undefined, "md", false],
|
||||
["#page=2", "pdf", false],
|
||||
["#Section", undefined, false],
|
||||
["#Section", null, false],
|
||||
["#Section", "", false],
|
||||
]) {
|
||||
assert.equal(
|
||||
requiresCanvasNodeHost(subpath, extension),
|
||||
required,
|
||||
`subpath ${JSON.stringify(subpath)} on ${JSON.stringify(extension)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
//awaitCanvasNodeHost on a host that reports no lifecycle: the bounded poll
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
block(
|
||||
"a factory is accepted on the read that finds it initialized",
|
||||
async () => {
|
||||
for (const readyOnRead of [1, 4]) {
|
||||
const host = hostReadyOnRead(readyOnRead);
|
||||
assert.equal(
|
||||
await awaitCanvasNodeHost(
|
||||
() => host,
|
||||
() => false,
|
||||
1000,
|
||||
1,
|
||||
delay,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(host.reads, readyOnRead);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
block(
|
||||
"a factory is re-read on every poll and never dereferenced blindly",
|
||||
async () => {
|
||||
for (const [name, sequence, timeoutMs, expected] of [
|
||||
["absent, then present", [null, null, hostReadyOnRead(1)], 1000, true],
|
||||
["never present", [null], 20, false],
|
||||
["present, then torn down", [unreadyHost, unreadyHost, null], 30, false],
|
||||
["present, never initialized", [unreadyHost], 20, false],
|
||||
]) {
|
||||
let reads = 0;
|
||||
const getHost = () => {
|
||||
reads += 1;
|
||||
return sequence[Math.min(reads, sequence.length) - 1];
|
||||
};
|
||||
assert.equal(
|
||||
await awaitCanvasNodeHost(getHost, () => false, timeoutMs, 1, delay),
|
||||
expected,
|
||||
name,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
block("an unmounted embeddable stops the wait", async () => {
|
||||
const host = hostReadyOnRead(1);
|
||||
assert.equal(
|
||||
await awaitCanvasNodeHost(
|
||||
() => host,
|
||||
() => true,
|
||||
1000,
|
||||
1,
|
||||
delay,
|
||||
),
|
||||
false,
|
||||
"already unmounted",
|
||||
);
|
||||
assert.equal(host.reads, 0, "already unmounted: the factory is never read");
|
||||
assert.equal(
|
||||
await awaitCanvasNodeHost(
|
||||
() => unreadyHost,
|
||||
cancelledOnRead(3),
|
||||
5000,
|
||||
1,
|
||||
delay,
|
||||
),
|
||||
false,
|
||||
"unmounted while waiting",
|
||||
);
|
||||
});
|
||||
|
||||
block("a zero timeout allows exactly one read", async () => {
|
||||
//timeoutMs = 0 is falsy but valid; `Date.now() >= deadline`, not `>`, is what
|
||||
//makes it terminate.
|
||||
for (const [readyOnRead, expected] of [
|
||||
[1, true],
|
||||
[Number.MAX_SAFE_INTEGER, false],
|
||||
]) {
|
||||
const host = hostReadyOnRead(readyOnRead);
|
||||
const polls = polling();
|
||||
assert.equal(
|
||||
await awaitCanvasNodeHost(
|
||||
() => host,
|
||||
() => false,
|
||||
0,
|
||||
25,
|
||||
polls.delay,
|
||||
),
|
||||
expected,
|
||||
);
|
||||
assert.equal(host.reads, 1);
|
||||
assert.equal(polls.count, 0, "it returned without waiting out a poll");
|
||||
}
|
||||
});
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
// mountEmbeddableHost
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
block(
|
||||
"a subpath embed mounting before the factory is ready gets a node",
|
||||
async () => {
|
||||
//Three embeddables at once, each with its own factory readiness, so a shared
|
||||
//wait state would show as a wrong host on one of them.
|
||||
const recorders = [
|
||||
["#Section", 5],
|
||||
["#^blockid", 2],
|
||||
["#Section", 7],
|
||||
].map(([subpath, readyOnRead]) => {
|
||||
const host = hostReadyOnRead(readyOnRead);
|
||||
return mountRecorder({ subpath, getHost: () => host, timeoutMs: 500 });
|
||||
});
|
||||
const hosts = await Promise.all(
|
||||
recorders.map(({ options }) => mountEmbeddableHost(options)),
|
||||
);
|
||||
assert.deepEqual(hosts, ["canvas-node", "canvas-node", "canvas-node"]);
|
||||
for (const { calls } of recorders) {
|
||||
assert.deepEqual(calls, { canvasNodes: 1, workspaceLeaves: 0 });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
block(
|
||||
"a subpath embed whose factory appears only after mount gets a node",
|
||||
async () => {
|
||||
let reads = 0;
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => {
|
||||
reads += 1;
|
||||
return reads < 3 ? null : { isInitialized: () => true };
|
||||
},
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "canvas-node");
|
||||
assert.deepEqual(calls, { canvasNodes: 1, workspaceLeaves: 0 });
|
||||
},
|
||||
);
|
||||
|
||||
block("a ready factory mounts its host before the effect returns", async () => {
|
||||
//The mount effect is synchronous up to its first await, so neither fast path
|
||||
//may become deferred: the effect's cleanup runs against whatever these calls
|
||||
//have already created. A whole-file embed does not read the factory at all.
|
||||
for (const [subpath, fileExtension, expected, reads] of [
|
||||
["#Section", "md", "canvas-node", 1],
|
||||
[null, "md", "workspace-leaf", 0],
|
||||
["#page=2", "pdf", "workspace-leaf", 0],
|
||||
]) {
|
||||
const host = lifecycleHost();
|
||||
host.ready();
|
||||
let hostReads = 0;
|
||||
const polls = polling();
|
||||
const order = [];
|
||||
const pending = mountEmbeddableHost({
|
||||
subpath,
|
||||
fileExtension,
|
||||
getHost: () => {
|
||||
hostReads += 1;
|
||||
return host;
|
||||
},
|
||||
createCanvasNode: () => order.push("canvas-node"),
|
||||
createWorkspaceLeaf: () => order.push("workspace-leaf"),
|
||||
intervalMs: 1000,
|
||||
delay: polls.delay,
|
||||
});
|
||||
order.push("effect-returned");
|
||||
assert.equal(await pending, expected, `${subpath} on ${fileExtension}`);
|
||||
assert.deepEqual(order, [expected, "effect-returned"]);
|
||||
assert.equal(hostReads, reads, `${fileExtension}: factory reads`);
|
||||
assert.equal(polls.count, 0, "it did not wait out a poll interval");
|
||||
}
|
||||
});
|
||||
|
||||
block("a factory reporting no lifecycle falls back at the cap", async () => {
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => unreadyHost,
|
||||
timeoutMs: 20,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
|
||||
});
|
||||
|
||||
block(
|
||||
"an embeddable unmounted before or during its wait mounts nothing",
|
||||
async () => {
|
||||
//A cancellation observed before readiness remains effective even if later
|
||||
//reads are live and the factory becomes usable.
|
||||
const cancelledThenReadies = (host, read) => {
|
||||
const cancelled = cancelledOnRead(read);
|
||||
let reads = 0;
|
||||
return () => {
|
||||
reads += 1;
|
||||
const value = cancelled();
|
||||
if (reads >= read) {
|
||||
host.ready();
|
||||
}
|
||||
return value;
|
||||
};
|
||||
};
|
||||
const readyAsTornDown = () => {
|
||||
const host = { isInitialized: () => host.torndown, torndown: false };
|
||||
return {
|
||||
host,
|
||||
isCancelled: () => {
|
||||
host.torndown = true;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
};
|
||||
const lifecycle = lifecycleHost();
|
||||
const asReadies = readyAsTornDown();
|
||||
for (const [name, overrides] of [
|
||||
[
|
||||
"already unmounted, whole-file",
|
||||
{ subpath: null, isCancelled: () => true },
|
||||
],
|
||||
[
|
||||
"already unmounted, ready factory",
|
||||
{ isCancelled: () => true },
|
||||
],
|
||||
[
|
||||
"unmounted while polling",
|
||||
{ getHost: () => unreadyHost, isCancelled: cancelledOnRead(3) },
|
||||
],
|
||||
[
|
||||
"unmounted on the poll that saw the cleanup, refs live again after",
|
||||
{ getHost: () => unreadyHost, isCancelled: cancelledOnRead(2) },
|
||||
],
|
||||
[
|
||||
"unmounted as the factory readies",
|
||||
{ getHost: () => asReadies.host, isCancelled: asReadies.isCancelled },
|
||||
],
|
||||
[
|
||||
"unmounted, then the factory readies",
|
||||
{
|
||||
getHost: () => lifecycle,
|
||||
isCancelled: cancelledThenReadies(lifecycle, 2),
|
||||
},
|
||||
],
|
||||
[
|
||||
"unmounted while waiting on a lifecycle",
|
||||
{ getHost: () => lifecycleHost(), isCancelled: cancelledOnRead(3) },
|
||||
],
|
||||
]) {
|
||||
const { options, calls } = mountRecorder({
|
||||
timeoutMs: 5000,
|
||||
...overrides,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "none", name);
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 0 }, name);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
block("only the current link is mounted when it changes mid-wait", async () => {
|
||||
//The first wait observes cancellation while polling. The second mount sees a
|
||||
//ready factory and completes without polling.
|
||||
const host = lifecycleHost();
|
||||
const mounted = [];
|
||||
let nextMount;
|
||||
const cancelled = cancelledOnRead(2);
|
||||
const first = mountEmbeddableHost({
|
||||
subpath: "#A",
|
||||
fileExtension: "md",
|
||||
getHost: () => host,
|
||||
isCancelled: () => {
|
||||
const value = cancelled();
|
||||
if (value && nextMount === undefined) {
|
||||
host.ready();
|
||||
nextMount = mountEmbeddableHost({
|
||||
subpath: "#B",
|
||||
fileExtension: "md",
|
||||
getHost: () => host,
|
||||
createCanvasNode: () => mounted.push("#B"),
|
||||
createWorkspaceLeaf: () => mounted.push("#B-leaf"),
|
||||
intervalMs: 1,
|
||||
delay,
|
||||
});
|
||||
}
|
||||
return value;
|
||||
},
|
||||
createCanvasNode: () => mounted.push("#A"),
|
||||
createWorkspaceLeaf: () => mounted.push("#A-leaf"),
|
||||
timeoutMs: 5000,
|
||||
intervalMs: 1,
|
||||
delay,
|
||||
});
|
||||
assert.equal(await first, "none", "the cancelled mount created no host");
|
||||
assert.equal(
|
||||
await nextMount,
|
||||
"canvas-node",
|
||||
"the ready mount completed without polling",
|
||||
);
|
||||
assert.deepEqual(mounted, ["#B"]);
|
||||
});
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
//The factory's lifecycle, not the clock, decides how long a subpath embed waits.
|
||||
//Startup can legitimately outrun any fixed cap: layout ready polls up to
|
||||
//50 x 50 ms before initialize() is called, and initialize() then awaits the core
|
||||
//canvas plugin's load. A host reporting whenInitialized is waited on through
|
||||
//that signal; the cap applies only while no such host is visible.
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
block("an expired cap does not end a wait on a starting factory", async () => {
|
||||
//Readiness lands on the third poll, 20 ms in, past every cap below.
|
||||
for (const timeoutMs of [5, 0, -1]) {
|
||||
const host = lifecycleHost();
|
||||
const polls = polling({ 3: () => host.ready() });
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => host,
|
||||
timeoutMs,
|
||||
intervalMs: 10,
|
||||
delay: polls.delay,
|
||||
});
|
||||
assert.equal(
|
||||
await mountEmbeddableHost(options),
|
||||
"canvas-node",
|
||||
`cap ${timeoutMs}`,
|
||||
);
|
||||
assert.deepEqual(
|
||||
calls,
|
||||
{ canvasNodes: 1, workspaceLeaves: 0 },
|
||||
`cap ${timeoutMs}`,
|
||||
);
|
||||
assert.equal(polls.count, 3, `cap ${timeoutMs}: readiness ended the wait`);
|
||||
}
|
||||
});
|
||||
|
||||
block(
|
||||
"a factory that reports it will not initialize falls back on that signal",
|
||||
async () => {
|
||||
//A false lifecycle result, or a ready result with no usable node, ends the
|
||||
//wait on the poll that observes that result.
|
||||
for (const [name, settle] of [
|
||||
["gives up", (host) => host.givesUp()],
|
||||
[
|
||||
"destroyed as it settled",
|
||||
(host) => {
|
||||
host.ready();
|
||||
host.initialized = false;
|
||||
},
|
||||
],
|
||||
]) {
|
||||
const host = lifecycleHost();
|
||||
const polls = polling({ 1: () => settle(host) });
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => host,
|
||||
delay: polls.delay,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "workspace-leaf", name);
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 }, name);
|
||||
assert.equal(
|
||||
polls.count,
|
||||
1,
|
||||
`${name}: decided on the signal, not the cap`,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
block(
|
||||
"a lifecycle that never settles is waited on until the embeddable unmounts",
|
||||
async () => {
|
||||
//With a lifecycle present the cap is not consulted, so the wait outlives an
|
||||
//already expired cap and ends on the teardown instead.
|
||||
let unmounted = false;
|
||||
const polls = polling({ 3: () => { unmounted = true; } });
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: neverSettlingHost,
|
||||
isCancelled: () => unmounted,
|
||||
timeoutMs: 0,
|
||||
delay: polls.delay,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "none");
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 0 });
|
||||
assert.equal(
|
||||
polls.count,
|
||||
3,
|
||||
"it polled past the expired cap until the unmount",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
block(
|
||||
"a view that drops its factory ends even a never-settling wait",
|
||||
async () => {
|
||||
//`ExcalidrawView.onClose` sets `canvasNodeFactory = null`, and `getHost()`
|
||||
//is re-read on every poll, so the expired cap applies again once no factory
|
||||
//is visible even if the embeddable itself never unmounts.
|
||||
let factory = neverSettlingHost();
|
||||
const polls = polling({
|
||||
2: () => {
|
||||
factory = null;
|
||||
},
|
||||
});
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => factory,
|
||||
timeoutMs: 0,
|
||||
delay: polls.delay,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
|
||||
assert.equal(
|
||||
polls.count,
|
||||
2,
|
||||
"the wait ended on the poll that found no factory",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
// CanvasNodeFactory.whenInitialized
|
||||
//--------------------------------------------------------------------------------
|
||||
|
||||
block("initialize() settles the lifecycle true once it succeeds", async () => {
|
||||
const factory = new CanvasNodeFactory(fakeView({ loadMs: 10 }));
|
||||
assert.equal(await settleWithin(factory.whenInitialized, 5), PENDING);
|
||||
await factory.initialize();
|
||||
assert.equal(factory.isInitialized(), true);
|
||||
assert.equal(await settleWithin(factory.whenInitialized), true);
|
||||
});
|
||||
|
||||
block("initialize() that throws settles false and rethrows", async () => {
|
||||
const factory = new CanvasNodeFactory(fakeView({ loadThrows: true }));
|
||||
await assert.rejects(
|
||||
() => factory.initialize(),
|
||||
/canvas plugin failed to load/,
|
||||
);
|
||||
assert.equal(factory.isInitialized(), false);
|
||||
assert.equal(await settleWithin(factory.whenInitialized), false);
|
||||
});
|
||||
|
||||
block("destroying a factory during core plugin loading stops initialization", async () => {
|
||||
const view = fakeView();
|
||||
const canvasPlugin = view.app.internalPlugins.plugins.canvas;
|
||||
let finishLoading;
|
||||
canvasPlugin.load = () => new Promise((resolve) => {
|
||||
finishLoading = resolve;
|
||||
});
|
||||
let canvasViewsCreated = 0;
|
||||
canvasPlugin.views.canvas = () => {
|
||||
canvasViewsCreated += 1;
|
||||
return { canvas: {} };
|
||||
};
|
||||
const factory = new CanvasNodeFactory(view);
|
||||
const initializing = factory.initialize();
|
||||
factory.destroy();
|
||||
assert.equal(await factory.whenInitialized, false);
|
||||
finishLoading();
|
||||
await initializing;
|
||||
await factory.initialize();
|
||||
assert.equal(factory.isInitialized(), false);
|
||||
assert.equal(canvasViewsCreated, 0);
|
||||
assert.equal(factory.leaf, null);
|
||||
});
|
||||
|
||||
block(
|
||||
"destroy() settles the lifecycle false and cannot revise a settled one",
|
||||
async () => {
|
||||
const destroyedFirst = new CanvasNodeFactory(fakeView({ loadMs: 1000 }));
|
||||
destroyedFirst.destroy();
|
||||
assert.equal(await settleWithin(destroyedFirst.whenInitialized), false);
|
||||
|
||||
const initializedFirst = new CanvasNodeFactory(fakeView());
|
||||
await initializedFirst.initialize();
|
||||
initializedFirst.destroy();
|
||||
assert.equal(
|
||||
await settleWithin(initializedFirst.whenInitialized),
|
||||
true,
|
||||
"the first terminal state wins",
|
||||
);
|
||||
assert.equal(
|
||||
initializedFirst.isInitialized(),
|
||||
false,
|
||||
"the flag the consumer re-reads after the signal is cleared",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
block("a slow real factory still gets its canvas node", async () => {
|
||||
//A cold vault start: the core canvas plugin's load outlasts the default cap.
|
||||
//Elapsed time is the subject here, so this one block runs against the clock.
|
||||
const factory = new CanvasNodeFactory(
|
||||
fakeView({ loadMs: CANVAS_NODE_HOST_WAIT_TIMEOUT_MS + 150 }),
|
||||
);
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => factory,
|
||||
timeoutMs: undefined,
|
||||
intervalMs: 25,
|
||||
});
|
||||
const started = Date.now();
|
||||
const [host] = await Promise.all([
|
||||
mountEmbeddableHost(options),
|
||||
factory.initialize(),
|
||||
]);
|
||||
assert.equal(host, "canvas-node");
|
||||
assert.deepEqual(calls, { canvasNodes: 1, workspaceLeaves: 0 });
|
||||
assert.ok(
|
||||
Date.now() - started >= CANVAS_NODE_HOST_WAIT_TIMEOUT_MS,
|
||||
"the wait outlasted the cap",
|
||||
);
|
||||
});
|
||||
|
||||
block(
|
||||
"a real factory that failed to initialize falls back within one poll",
|
||||
async () => {
|
||||
const factory = new CanvasNodeFactory(fakeView({ loadThrows: true }));
|
||||
await factory.initialize().catch(() => undefined);
|
||||
const polls = polling();
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => factory,
|
||||
delay: polls.delay,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
|
||||
assert.equal(polls.count, 1);
|
||||
},
|
||||
);
|
||||
|
||||
block("a real factory destroyed mid-wait falls back on that poll", async () => {
|
||||
const factory = new CanvasNodeFactory(fakeView({ loadMs: 10_000 }));
|
||||
const polls = polling({ 2: () => factory.destroy() });
|
||||
const { options, calls } = mountRecorder({
|
||||
getHost: () => factory,
|
||||
delay: polls.delay,
|
||||
});
|
||||
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
|
||||
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
|
||||
assert.equal(polls.count, 2);
|
||||
});
|
||||
|
||||
let failed = 0;
|
||||
for (const [name, fn] of blocks) {
|
||||
try {
|
||||
await fn();
|
||||
log(`PASS ${name}`);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
log(`FAIL ${name}: ${error.message.split("\n")[0]}`);
|
||||
}
|
||||
}
|
||||
if (failed > 0) {
|
||||
process.exitCode = 1;
|
||||
log(`${failed} of ${blocks.length} embeddable mount plan checks failed`);
|
||||
} else {
|
||||
log("embeddable mount plan checks passed");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Runtime stand-ins for the two modules `CanvasNodeFactory` imports but does not
|
||||
* exercise while initializing or being destroyed.
|
||||
*
|
||||
* `obsidian` ships types only (`"main": ""`), so it cannot be loaded outside the
|
||||
* app; `obsidianUtils` pulls in the whole plugin. Both are aliased to this one
|
||||
* module, which exports the union of the members the factory names -- enough for
|
||||
* its lifecycle to run, and nothing more, so a stub can never stand in for the
|
||||
* behaviour under test.
|
||||
*/
|
||||
|
||||
/** Constructed, assigned two getters, and handed the factory's canvas leaf. */
|
||||
export class WorkspaceSplit {
|
||||
insertChild() {}
|
||||
}
|
||||
/** Constructed with the app; the canvas view is built on it by the stubbed plugin. */
|
||||
export class WorkspaceLeaf {}
|
||||
export class View {}
|
||||
export class TFile {}
|
||||
export class Editor {}
|
||||
|
||||
/** The factory hands the result to `rootSplit.getContainer`; nothing reads it. */
|
||||
export const getContainerForDocument = () => ({});
|
||||
export const isObsidianThemeDark = () => false;
|
||||
@@ -1,142 +1,39 @@
|
||||
import path from "path";
|
||||
import fs from "fs/promises";
|
||||
import { minify } from "terser";
|
||||
import LZString from "lz-string";
|
||||
import { fileURLToPath } from "url";
|
||||
/** Build Mindmap Builder in its authoring workspace and copy the published artifacts. */
|
||||
import path from "node:path";
|
||||
import fs from "node:fs/promises";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { packageManagerInvocation } from "./testing/host/processTools.mjs";
|
||||
|
||||
// Construct __dirname for ES Modules
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const workspace = path.resolve(process.argv[2] ?? path.join(root, "..", "ea-scripts"));
|
||||
const slug = "mindmap-builder";
|
||||
|
||||
const CHUNK_SIZE = 256;
|
||||
const NEEDLE = "const removeKeydownHandlers";
|
||||
async function deploy() {
|
||||
const major = Number(process.versions.node.split(".")[0]);
|
||||
if (major < 22) throw new Error("Mindmap Builder requires Node.js 22 or newer.");
|
||||
await fs.access(path.join(workspace, "src", "scripts", slug, "main.ts"));
|
||||
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const sourcePath = path.join(root, "ea-scripts", "Mindmap Builder.js.md");
|
||||
const outputPath = path.join(root, "ea-scripts", "Mindmap Builder.md");
|
||||
const invocation = packageManagerInvocation("npm", ["run", "build"]);
|
||||
const result = spawnSync(invocation.file, invocation.args, {
|
||||
cwd: workspace,
|
||||
stdio: "inherit",
|
||||
// Both repositories' scripts must use the same supported Node installation.
|
||||
env: { ...process.env, PATH: `${path.dirname(process.execPath)}${path.delimiter}${process.env.PATH ?? ""}` },
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) throw new Error(`EA Scripts build failed (exit ${result.status}).`);
|
||||
|
||||
const HEADER = `/*
|
||||
|
||||
# Mind Map Builder
|
||||
|
||||

|
||||
|
||||
## Overview
|
||||
**Mind Map Builder** transforms the Obsidian-Excalidraw canvas into a rapid brainstorming environment, allowing users to build complex, structured, and visually organized mind maps using primarily keyboard shortcuts.
|
||||
|
||||
The script balances **automation** (auto-layout, recursive grouping, and contrast-aware coloring) with **explicit flexibility** (node pinning and redirection logic), ensuring that the mind map stays organized even as it grows to hundreds of nodes. It leverages the Excalidraw Sidepanel API to provide a persistent control interface utilizing the Obsidian sidepanel, that can also be undocked into a floating modal.
|
||||
|
||||
> [!Tip]
|
||||
> 🚀 Become a MindMap Builder Pro with the Official [MindMap Builder Course](https://www.visual-thinking-workshop.com/mindmap)!
|
||||
|
||||
> [!Info]
|
||||
> Mindmap Builder is Minified and compressed to reduce size and improve performance. You can find the source here: [Mindmap Builder.js](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.js)
|
||||
> API documentation: [MindMapBuilderAPI.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-script-docs/MindMapBuilderAPI.md)
|
||||
|
||||
## Show Your Love!
|
||||
|
||||
💖 **If you love MindMap Builder** say thank you, and [Buy me a Coffee](https://ko-fi.com/zsolt) 🍵
|
||||
|
||||
## The Script
|
||||
|
||||
\`\`\`js*/
|
||||
`;
|
||||
|
||||
const FOOTER = `
|
||||
const VERSION = "v${new Date().toISOString().slice(2, 10).replace(/-/g, ".")}";
|
||||
|
||||
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.4")) {
|
||||
new Notice("Please update the Excalidraw Plugin to version 2.23.4 or higher.");
|
||||
return;
|
||||
const outputDir = path.join(workspace, "build", slug);
|
||||
// Read both before replacing either published artifact. Copy the template wrapper intact.
|
||||
const markdown = await fs.readFile(path.join(outputDir, `${slug}.md`));
|
||||
const preview = await fs.readFile(path.join(outputDir, `${slug}.svg`));
|
||||
await fs.writeFile(path.join(root, "ea-scripts", "Mindmap Builder.md"), markdown);
|
||||
await fs.writeFile(path.join(root, "ea-scripts", "Mindmap Builder.svg"), preview);
|
||||
console.log(`Mindmap Builder published artifacts copied from ${workspace}`);
|
||||
}
|
||||
|
||||
ea.skipSidepanelScriptRestore();
|
||||
|
||||
const existingTab = ea.checkForActiveSidepanelTabForScript();
|
||||
if (existingTab) {
|
||||
const hostEA = existingTab.getHostEA();
|
||||
if (hostEA && hostEA !== ea) {
|
||||
hostEA.activateMindmap = true;
|
||||
hostEA.setView(ea.targetView);
|
||||
existingTab.open(false);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const mmbSource = \`
|
||||
`;
|
||||
|
||||
const FOOTER_TAIL = `\`;
|
||||
const script = ea.decompressFromBase64(mmbSource.replace(/[\\s\\r\\n]+/g, ""));
|
||||
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
|
||||
await new AsyncFunction("ea", "utils", "VERSION", script)(ea, utils, VERSION);
|
||||
`;
|
||||
|
||||
function chunkString(input, size) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < input.length; i += size) {
|
||||
chunks.push(input.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function stripHeader(source) {
|
||||
const idx = source.indexOf(NEEDLE);
|
||||
if (idx === -1) {
|
||||
throw new Error(`Marker "${NEEDLE}" not found in Mindmap Builder.js`);
|
||||
}
|
||||
return source.slice(idx);
|
||||
}
|
||||
|
||||
function wrapAsyncIIFE(body) {
|
||||
return `(async()=>{\n${body}\n})()`;
|
||||
}
|
||||
|
||||
async function minifyCode(source) {
|
||||
const result = await minify(source, {
|
||||
compress: { passes: 3 },
|
||||
mangle: true,
|
||||
output: { ascii_only: true }
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
return result.code;
|
||||
}
|
||||
|
||||
function unwrapAsyncIIFE(minified) {
|
||||
const match = minified.match(/^\(async\s*\(\)\s*=>\s*\{([\s\S]*)\}\)\(\);?$/);
|
||||
if (!match) {
|
||||
throw new Error("Unable to strip async IIFE wrapper from minified output:\n" + minified.substring(0, 100) + "...");
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
function compressBase64(text) {
|
||||
return LZString.compressToBase64(text);
|
||||
}
|
||||
|
||||
function formatCompressed(compressed) {
|
||||
return chunkString(compressed, CHUNK_SIZE).join("\n\n");
|
||||
}
|
||||
|
||||
async function generate() {
|
||||
const raw = await fs.readFile(sourcePath, "utf8");
|
||||
const body = stripHeader(raw).trim();
|
||||
const wrapped = wrapAsyncIIFE(body);
|
||||
const minified = await minifyCode(wrapped);
|
||||
const unwrapped = unwrapAsyncIIFE(minified);
|
||||
const compressed = compressBase64(unwrapped);
|
||||
const formatted = formatCompressed(compressed);
|
||||
|
||||
const output = `${HEADER}${FOOTER}${formatted}${FOOTER_TAIL}`;
|
||||
await fs.writeFile(outputPath, output, "utf8");
|
||||
console.log(`Mindmap Builder.md generated at ${outputPath}`);
|
||||
}
|
||||
|
||||
generate().catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
deploy().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/** Shell-free desktop CLI and package-manager launches for local test tooling. */
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
/** Windows needs the console launcher to capture CLI output. Overrides are executable paths. */
|
||||
export function obsidianCliExecutable(env = process.env, platform = process.platform, exists = existsSync) {
|
||||
if (env.EXCALIDRAW_OBSIDIAN_CLI) return env.EXCALIDRAW_OBSIDIAN_CLI;
|
||||
const candidates = platform === "win32"
|
||||
? [env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Obsidian", "Obsidian.com"),
|
||||
env.PROGRAMFILES && join(env.PROGRAMFILES, "Obsidian", "Obsidian.com"),
|
||||
env["PROGRAMFILES(X86)"] && join(env["PROGRAMFILES(X86)"], "Obsidian", "Obsidian.com")]
|
||||
: platform === "darwin" ? ["/Applications/Obsidian.app/Contents/MacOS/obsidian-cli",
|
||||
"/Applications/Obsidian.app/Contents/MacOS/Obsidian"] : [];
|
||||
return candidates.filter(Boolean).find(exists) ?? "obsidian";
|
||||
}
|
||||
|
||||
/**
|
||||
* Preserve argument arrays and process results. Long/multiline Windows evals pass through
|
||||
* an owned UTF-8 script: the console transport can otherwise truncate or corrupt its IPC JSON.
|
||||
* This local file bridge is test-only and is removed even when the launcher fails.
|
||||
*/
|
||||
export function spawnNativeSync(file, args, options, { platform = process.platform, spawn = spawnSync } = {}) {
|
||||
const codeIndex = args.findIndex(arg => arg.startsWith("code="));
|
||||
const lengthBound = file.length + args.reduce((length, arg) => length + arg.length * 2 + 3, 0);
|
||||
const inlineSafe = codeIndex >= 0 && !/[\r\n]/.test(args[codeIndex]) && lengthBound < 8_000;
|
||||
if (platform !== "win32" || args[1] !== "eval" || !args[0]?.startsWith("vault=") || codeIndex < 0 || inlineSafe) {
|
||||
return spawn(file, args, options);
|
||||
}
|
||||
const directory = mkdtempSync(join(tmpdir(), "excalidraw-cli-eval-"));
|
||||
try {
|
||||
const script = join(directory, "probe.js");
|
||||
writeFileSync(script, args[codeIndex].slice(5), "utf8");
|
||||
const forwarded = [...args];
|
||||
forwarded[codeIndex] = `code=eval(require("node:fs").readFileSync(${JSON.stringify(script)},"utf8"))`;
|
||||
return spawn(file, forwarded, options);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Run npm/Yarn through this Node binary, avoiding .cmd shims and shell quoting on Windows. */
|
||||
export function packageManagerInvocation(manager, args, {
|
||||
env = process.env, node = process.execPath, platform = process.platform, exists = existsSync,
|
||||
} = {}) {
|
||||
if (!["npm", "yarn"].includes(manager)) throw new Error(`Unsupported package manager: ${manager}`);
|
||||
const entry = manager === "npm" ? "npm/bin/npm-cli.js" : "yarn/bin/yarn.js";
|
||||
const candidates = [manager === "npm" ? env.npm_execpath : env.EXCALIDRAW_YARN_CLI,
|
||||
join(dirname(node), "node_modules", entry),
|
||||
join(dirname(node), "../lib/node_modules", entry),
|
||||
env.APPDATA && join(env.APPDATA, "npm/node_modules", entry),
|
||||
manager === "yarn" && join(dirname(node), "node_modules/corepack/dist/yarn.js")];
|
||||
const script = candidates.filter(Boolean).find(exists);
|
||||
if (script) return { file: node, args: [script, ...args] };
|
||||
if (platform !== "win32" && manager === "yarn") return { file: "yarn", args };
|
||||
throw new Error(manager === "npm"
|
||||
? "Cannot locate npm-cli.js; launch this driver with npm run verify:obsidian"
|
||||
: "Cannot locate Yarn's JavaScript entry; install Yarn/Corepack or set EXCALIDRAW_YARN_CLI to yarn.js");
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { runInNewContext } from "node:vm";
|
||||
import { obsidianCliExecutable, packageManagerInvocation, spawnNativeSync } from "./processTools.mjs";
|
||||
|
||||
test("CLI discovery supports both desktop platforms, overrides and PATH fallback", () => {
|
||||
const env = { LOCALAPPDATA: "/local", PROGRAMFILES: "/program files" };
|
||||
const console = join(env.PROGRAMFILES, "Obsidian/Obsidian.com");
|
||||
assert.equal(obsidianCliExecutable(env, "win32", path => path === console), console);
|
||||
const mac = "/Applications/Obsidian.app/Contents/MacOS/obsidian-cli";
|
||||
assert.equal(obsidianCliExecutable({}, "darwin", path => path === mac), mac);
|
||||
assert.equal(obsidianCliExecutable({ EXCALIDRAW_OBSIDIAN_CLI: "/custom cli" }, "win32", () => false), "/custom cli");
|
||||
assert.equal(obsidianCliExecutable({}, "darwin", () => false), "obsidian");
|
||||
});
|
||||
|
||||
test("long and multiline Windows evals preserve literal code and remove their temporary scripts", () => {
|
||||
for (const code of ['JSON.stringify("quotes: \\" and paths: C:\\\\test")\n', `JSON.stringify(${JSON.stringify("x".repeat(50_000))})`]) {
|
||||
const args = ["vault=excalidraw-test", "eval", `code=${code}`];
|
||||
const options = { timeout: 1234, encoding: "utf8" };
|
||||
const result = { status: 0, stdout: "receipt" };
|
||||
let script;
|
||||
assert.equal(spawnNativeSync("Obsidian.com", args, options, { platform: "win32", spawn: (file, forwarded, received) => {
|
||||
assert.equal(file, "Obsidian.com");
|
||||
assert.equal(received, options);
|
||||
assert.deepEqual(forwarded.slice(0, 2), args.slice(0, 2));
|
||||
assert.ok(forwarded[2].length < 1000);
|
||||
assert.doesNotMatch(forwarded[2], /[\r\n]/);
|
||||
const output = runInNewContext(forwarded[2].slice(5), { require: () => ({ readFileSync: (path, encoding) => {
|
||||
script = path;
|
||||
assert.equal(encoding, "utf8");
|
||||
assert.equal(readFileSync(path, encoding), code);
|
||||
return code;
|
||||
} }) });
|
||||
assert.equal(output, runInNewContext(code));
|
||||
return result;
|
||||
} }), result);
|
||||
assert.equal(existsSync(dirname(script)), false);
|
||||
assert.equal(args[2], `code=${code}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("temporary eval scripts are removed if native spawning throws", () => {
|
||||
let directory;
|
||||
assert.throws(() => spawnNativeSync("Obsidian.com", ["vault=excalidraw-test", "eval", "code=1\n+1"], {}, {
|
||||
platform: "win32", spawn: (_file, args) => {
|
||||
runInNewContext(args[2].slice(5), { require: () => ({ readFileSync: path => { directory = dirname(path); return "1+1"; } }) });
|
||||
throw new Error("launcher failure");
|
||||
},
|
||||
}), /launcher failure/);
|
||||
assert.equal(existsSync(directory), false);
|
||||
});
|
||||
|
||||
test("short Windows calls and all macOS calls keep their native arguments", () => {
|
||||
for (const [platform, code] of [["win32", "1+1"], ["darwin", "1\n+1"]]) {
|
||||
const args = ["vault=excalidraw-test", "eval", `code=${code}`];
|
||||
spawnNativeSync("obsidian", args, {}, { platform, spawn: (_file, received) => assert.equal(received, args) });
|
||||
}
|
||||
});
|
||||
|
||||
test("package managers launch JavaScript entries through the current Node without .cmd shims", () => {
|
||||
const node = "/node install/node";
|
||||
for (const [manager, entry] of [["npm", "npm/bin/npm-cli.js"], ["yarn", "yarn/bin/yarn.js"]]) {
|
||||
const script = join(dirname(node), "node_modules", entry);
|
||||
const invocation = packageManagerInvocation(manager, ["run", "build"], {
|
||||
env: {}, node, platform: "win32", exists: path => path === script,
|
||||
});
|
||||
assert.deepEqual(invocation, { file: node, args: [script, "run", "build"] });
|
||||
}
|
||||
assert.deepEqual(packageManagerInvocation("yarn", ["build:obsidian"], {
|
||||
env: {}, node, platform: "darwin", exists: () => false,
|
||||
}), { file: "yarn", args: ["build:obsidian"] });
|
||||
assert.throws(() => packageManagerInvocation("yarn", [], { env: {}, node, platform: "win32", exists: () => false }), /EXCALIDRAW_YARN_CLI/);
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
/** Native Obsidian smoke lane for the exact locally built Excalidraw plugin. */
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { basename, isAbsolute, join, relative, sep } from "node:path";
|
||||
|
||||
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
|
||||
export const ARTIFACTS = ["main.js", "manifest.json", "styles.css"];
|
||||
const REQUIRED_CLI = ["version", "vault", "plugin:enable", "plugin:disable", "commands", "eval", "dev:errors"];
|
||||
const CONTROL = "__excalidrawCliSmoke";
|
||||
const PREFIX = "__excalidraw_cli_smoke_";
|
||||
|
||||
const hash = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
|
||||
|
||||
function inside(parent, child, label) {
|
||||
const rel = relative(parent, child);
|
||||
if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
||||
throw new Error(`${label} must be inside the selected test vault`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reject ambiguous or redirected vault and plugin paths before any deployment. */
|
||||
export function validateTarget({ vaultName, vaultPath, configDir }) {
|
||||
if (!vaultName || !vaultPath || !configDir) {
|
||||
throw new Error("Set EXCALIDRAW_TEST_VAULT_NAME, EXCALIDRAW_TEST_VAULT_PATH and EXCALIDRAW_TEST_CONFIG_DIR");
|
||||
}
|
||||
if (vaultName !== "excalidraw-test") throw new Error("This runner is restricted to the excalidraw-test vault");
|
||||
if (!isAbsolute(vaultPath) || !isAbsolute(configDir)) throw new Error("Vault and config paths must be absolute");
|
||||
if (!existsSync(vaultPath) || !existsSync(configDir)) throw new Error("Vault or config directory does not exist");
|
||||
const vault = realpathSync(vaultPath);
|
||||
const config = realpathSync(configDir);
|
||||
if (basename(vault) !== vaultName) throw new Error("Vault folder does not match the selected vault name");
|
||||
inside(vault, config, "Config directory");
|
||||
if (!existsSync(join(config, "community-plugins.json"))) {
|
||||
throw new Error("Community plugins must be configured in this test vault");
|
||||
}
|
||||
const plugins = join(config, "plugins");
|
||||
if (existsSync(plugins) && lstatSync(plugins).isSymbolicLink()) throw new Error("Plugin directory cannot be a symlink");
|
||||
const pluginDir = join(plugins, PLUGIN_ID);
|
||||
if (existsSync(pluginDir) && lstatSync(pluginDir).isSymbolicLink()) throw new Error("Target plugin cannot be a symlink");
|
||||
for (const name of ARTIFACTS) {
|
||||
const file = join(pluginDir, name);
|
||||
if (existsSync(file) && lstatSync(file).isSymbolicLink()) throw new Error(`Target artifact cannot be a symlink: ${name}`);
|
||||
}
|
||||
const manifestPath = join(pluginDir, "manifest.json");
|
||||
if (!existsSync(manifestPath) || JSON.parse(readFileSync(manifestPath, "utf8")).id !== PLUGIN_ID ||
|
||||
!JSON.parse(readFileSync(join(config, "community-plugins.json"), "utf8")).includes(PLUGIN_ID)) {
|
||||
throw new Error("Install and enable Excalidraw from Community plugins in excalidraw-test first");
|
||||
}
|
||||
return { vault, config, pluginDir };
|
||||
}
|
||||
|
||||
function cliPath(output) {
|
||||
const path = output.trim();
|
||||
return path.startsWith("path ") ? path.slice(5).trim() : path;
|
||||
}
|
||||
|
||||
function parseEval(output) {
|
||||
const value = output.trim().replace(/^=>\s*/, "");
|
||||
if (value.startsWith("Error:")) throw new Error(`Obsidian eval failed: ${value.slice(0, 500)}`);
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
throw new Error(`Obsidian eval returned non-JSON: ${value.slice(0, 500)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function artifacts(projectRoot) {
|
||||
const paths = Object.fromEntries(ARTIFACTS.map((name) => [name, join(projectRoot, "dist", name)]));
|
||||
for (const [name, path] of Object.entries(paths)) {
|
||||
if (!existsSync(path)) throw new Error(`Missing built ${name}: ${path}`);
|
||||
}
|
||||
const manifest = JSON.parse(readFileSync(paths["manifest.json"], "utf8"));
|
||||
if (manifest.id !== PLUGIN_ID) throw new Error(`Built manifest ID must be ${PLUGIN_ID}`);
|
||||
return { paths, hashes: Object.fromEntries(ARTIFACTS.map((name) => [name, hash(paths[name])])), version: manifest.version };
|
||||
}
|
||||
|
||||
const startCode = (name) => `(()=>{const p=app.plugins.plugins[${JSON.stringify(PLUGIN_ID)}];if(!p)return JSON.stringify({state:"failed",error:"plugin not loaded"});if(globalThis.${CONTROL})return JSON.stringify({state:"failed",error:"smoke controller already exists"});const c={state:"pending",name:${JSON.stringify(name)},path:null,error:null,cancel:false};globalThis.${CONTROL}=c;const extension=p.settings.compatibilityMode?".excalidraw":p.settings.useExcalidrawExtension?".excalidraw.md":".md";Promise.resolve(p.createAndOpenDrawing(c.name+extension,"new-tab","/")).then(async path=>{c.path=path;c.state="created";if(c.cancel){const file=app.vault.getFileByPath(path);if(file&&file.name.startsWith(${JSON.stringify(PREFIX)})){const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);if(leaf){await leaf.setViewState({type:"empty",state:{}});leaf.detach()}await app.vault.delete(file)}c.state="clean"}}).catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"started"})})()`;
|
||||
const statusCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"missing"});const leaf=c.path&&app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===c.path);const view=leaf?.view;return JSON.stringify({state:c.state,path:c.path,error:c.error,ready:!!view?.excalidrawAPI,wrapper:!!view?.containerEl?.querySelector(".excalidraw-wrapper"),ownerMatches:!!view&&view.ownerDocument===view.containerEl.ownerDocument,mainWindow:!!view&&view.ownerDocument===app.workspace.containerEl?.ownerDocument})})()`;
|
||||
const cleanupCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"clean"});if(c.state==="pending"){c.cancel=true;return JSON.stringify({state:"pending"})}if(c.state==="cleaning")return JSON.stringify({state:"cleaning"});const path=c.path;const file=path&&app.vault.getFileByPath(path);if(!file){delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})}if(!file.name.startsWith(${JSON.stringify(PREFIX)}))return JSON.stringify({state:"failed",error:"refusing to delete a non-smoke drawing"});const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);c.state="cleaning";(async()=>{if(leaf){await leaf.setViewState({type:"empty",state:{}});leaf.detach()}await app.vault.delete(file);c.state="clean"})().catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"cleaning"})})()`;
|
||||
|
||||
async function poll(read, acceptable, wait, now, timeoutMs = 20_000) {
|
||||
const deadline = now() + timeoutMs;
|
||||
for (;;) {
|
||||
const result = read();
|
||||
if (acceptable(result)) return result;
|
||||
if (result.state === "failed") throw new Error(result.error || "Host scenario failed");
|
||||
if (now() >= deadline) throw new Error(`Host scenario timed out: ${JSON.stringify(result)}`);
|
||||
await wait(250);
|
||||
}
|
||||
}
|
||||
|
||||
/** Preflight, build, stage and exercise one disposable drawing; always write a report. */
|
||||
export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, configDir, reportDir, runCli, runBuild,
|
||||
wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(), source = {}, unique = () => randomUUID(), scenarios = [] }) {
|
||||
const report = { schemaVersion: 1, status: "failed", startedAt: new Date(now()).toISOString(), source,
|
||||
target: { vaultName, vaultPath, configDir }, capabilities: {}, artifacts: {}, scenarios: [], cleanup: "not-started" };
|
||||
mkdirSync(reportDir, { recursive: true });
|
||||
let phase = "preflight";
|
||||
let created = false;
|
||||
try {
|
||||
const target = validateTarget({ vaultName, vaultPath, configDir });
|
||||
const cli = (command, ...args) => {
|
||||
const output = runCli(vaultName, command, ...args);
|
||||
if (output.trim().startsWith("Error:")) throw new Error(`${command}: ${output.trim().slice(0, 500)}`);
|
||||
return output;
|
||||
};
|
||||
report.capabilities.version = cli("version").trim();
|
||||
const help = cli("help");
|
||||
const missing = REQUIRED_CLI.filter((command) => !help.includes(command));
|
||||
if (missing.length) throw new Error(`Obsidian CLI lacks: ${missing.join(", ")}`);
|
||||
const selected = cliPath(cli("vault", "info=path"));
|
||||
if (!existsSync(selected) || realpathSync(selected) !== target.vault) {
|
||||
throw new Error(`CLI selected vault ${selected}, expected ${target.vault}`);
|
||||
}
|
||||
report.target.vaultPath = target.vault;
|
||||
report.target.configDir = target.config;
|
||||
const selectedConfig = parseEval(cli("eval", "code=JSON.stringify({configDir:app.vault.configDir})")).configDir;
|
||||
if (typeof selectedConfig !== "string") throw new Error("CLI did not report its vault config directory");
|
||||
const hostConfig = join(target.vault, selectedConfig);
|
||||
if (!existsSync(hostConfig) || realpathSync(hostConfig) !== target.config) {
|
||||
throw new Error(`CLI config directory differs from ${target.config}`);
|
||||
}
|
||||
|
||||
phase = "build";
|
||||
const forkArtifacts = await runBuild();
|
||||
const built = artifacts(projectRoot);
|
||||
report.artifacts = { forkArtifacts, version: built.version, sourceHashes: built.hashes,
|
||||
mainBytes: readFileSync(built.paths["main.js"]).length };
|
||||
|
||||
phase = "deploy";
|
||||
if (existsSync(target.pluginDir)) cli("plugin:disable", `id=${PLUGIN_ID}`);
|
||||
mkdirSync(target.pluginDir, { recursive: true });
|
||||
for (const name of ARTIFACTS) copyFileSync(built.paths[name], join(target.pluginDir, name));
|
||||
report.artifacts.installedHashes = Object.fromEntries(ARTIFACTS.map((name) => [name, hash(join(target.pluginDir, name))]));
|
||||
if (ARTIFACTS.some((name) => built.hashes[name] !== report.artifacts.installedHashes[name])) {
|
||||
throw new Error("Installed artifacts differ from the local build");
|
||||
}
|
||||
cli("dev:errors", "clear");
|
||||
cli("plugin:enable", `id=${PLUGIN_ID}`);
|
||||
const loaded = await poll(() => parseEval(cli("eval", `code=JSON.stringify({state:app.plugins?.plugins?.[${JSON.stringify(PLUGIN_ID)}]?"loaded":"pending"})`)),
|
||||
(value) => value.state === "loaded", wait, now);
|
||||
if (loaded.state !== "loaded") throw new Error("Plugin did not load");
|
||||
await poll(() => ({ state: cli("commands", `filter=${PLUGIN_ID}`).includes(`${PLUGIN_ID}:excalidraw-autocreate`)
|
||||
? "registered" : "pending" }), (value) => value.state === "registered", wait, now);
|
||||
report.scenarios.push({ id: "plugin-load", status: "passed" });
|
||||
|
||||
phase = "drawing";
|
||||
const name = `${PREFIX}${unique()}`;
|
||||
const started = parseEval(cli("eval", `code=${startCode(name)}`));
|
||||
if (started.state !== "started") throw new Error(started.error || "Could not start drawing smoke");
|
||||
created = true;
|
||||
const drawing = await poll(() => parseEval(cli("eval", `code=${statusCode}`)),
|
||||
(value) => value.state === "created" && value.ready && value.wrapper && value.ownerMatches && value.mainWindow, wait, now);
|
||||
if (!drawing.path || !basename(drawing.path).startsWith(PREFIX)) throw new Error("Unexpected smoke drawing path");
|
||||
report.target.drawingPath = drawing.path;
|
||||
report.scenarios.push({ id: "drawing-main-window", status: "passed", assertions: ["Excalidraw API ready", "wrapper mounted", "owner document matches", "main application document"] });
|
||||
phase = "feature-scenarios";
|
||||
for (const scenario of scenarios) {
|
||||
report.scenarios.push(await scenario({ cli, drawingPath: drawing.path }));
|
||||
}
|
||||
const errors = cli("dev:errors").trim();
|
||||
if (errors && !/^No errors captured\.?$/i.test(errors)) throw new Error(`Captured JavaScript errors: ${errors.slice(0, 1000)}`);
|
||||
report.scenarios.push({ id: "javascript-errors", status: "passed" });
|
||||
report.status = "passed";
|
||||
} catch (error) {
|
||||
report.error = error instanceof Error ? error.message : String(error);
|
||||
report.scenarios.push({ id: phase, status: "failed", reason: report.error });
|
||||
} finally {
|
||||
if (created) {
|
||||
try {
|
||||
const cli = (code) => parseEval(runCli(vaultName, "eval", `code=${code}`));
|
||||
const response = cli(cleanupCode);
|
||||
if (response.state === "failed") throw new Error(response.error);
|
||||
await poll(() => cli(`(()=>JSON.stringify({state:globalThis.${CONTROL}?.state||"clean",error:globalThis.${CONTROL}?.error}))()`),
|
||||
(value) => value.state === "clean", wait, now);
|
||||
cli(`(()=>{delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})})()`);
|
||||
report.cleanup = "passed";
|
||||
} catch (error) {
|
||||
report.cleanup = "failed";
|
||||
report.cleanupError = error instanceof Error ? error.message : String(error);
|
||||
report.status = "failed";
|
||||
}
|
||||
}
|
||||
report.completedAt = new Date(now()).toISOString();
|
||||
writeFileSync(join(reportDir, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, test } from "node:test";
|
||||
import { rmSync } from "node:fs";
|
||||
import { runObsidianSmoke, validateTarget } from "./runner.mjs";
|
||||
|
||||
const roots = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
|
||||
function fixture() {
|
||||
const root = mkdtempSync(join(tmpdir(), "excalidraw-runner-test-"));
|
||||
roots.push(root);
|
||||
const vaultPath = join(root, "excalidraw-test");
|
||||
const configDir = join(vaultPath, ".obsidian");
|
||||
const projectRoot = join(root, "plugin");
|
||||
const reportDir = join(root, "reports");
|
||||
mkdirSync(configDir, { recursive: true });
|
||||
mkdirSync(join(projectRoot, "dist"), { recursive: true });
|
||||
writeFileSync(join(configDir, "community-plugins.json"), '["obsidian-excalidraw-plugin"]');
|
||||
const pluginDir = join(configDir, "plugins/obsidian-excalidraw-plugin");
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(join(pluginDir, "manifest.json"), JSON.stringify({ id: "obsidian-excalidraw-plugin" }));
|
||||
writeFileSync(join(projectRoot, "dist/main.js"), "// smoke build");
|
||||
writeFileSync(join(projectRoot, "dist/styles.css"), "/* smoke */");
|
||||
writeFileSync(join(projectRoot, "dist/manifest.json"), JSON.stringify({ id: "obsidian-excalidraw-plugin", version: "test" }));
|
||||
return { vaultName: "excalidraw-test", vaultPath, configDir, projectRoot, reportDir };
|
||||
}
|
||||
|
||||
test("requires the named test vault and refuses redirected plugin paths", () => {
|
||||
const input = fixture();
|
||||
assert.ok(validateTarget(input).pluginDir.endsWith("obsidian-excalidraw-plugin"));
|
||||
assert.throws(() => validateTarget({ ...input, vaultName: "personal-notes" }), /restricted/);
|
||||
assert.throws(() => validateTarget({ ...input, configDir: input.projectRoot }), /inside/);
|
||||
});
|
||||
|
||||
test("a CLI vault mismatch stops before build or staging", async () => {
|
||||
const input = fixture();
|
||||
let built = false;
|
||||
const report = await runObsidianSmoke({ ...input, runBuild: () => { built = true; },
|
||||
runCli: (_vault, command) => command === "help" ? "version vault plugin:enable plugin:disable commands eval dev:errors" :
|
||||
command === "vault" ? input.projectRoot : "1.13.0" });
|
||||
assert.equal(report.status, "failed");
|
||||
assert.match(report.error, /CLI selected vault/);
|
||||
assert.equal(built, false);
|
||||
assert.equal(JSON.parse(readFileSync(join(input.reportDir, "report.json"))).status, "failed");
|
||||
});
|
||||
|
||||
test("requires the initial Community plugin install and enablement", () => {
|
||||
const input = fixture();
|
||||
writeFileSync(join(input.configDir, "community-plugins.json"), "[]");
|
||||
assert.throws(() => validateTarget(input), /Install and enable Excalidraw/);
|
||||
});
|
||||
|
||||
test("a CLI config mismatch stops before build or deployment", async () => {
|
||||
const input = fixture();
|
||||
let built = false;
|
||||
const report = await runObsidianSmoke({ ...input, runBuild: () => { built = true; },
|
||||
runCli: (_vault, command) => command === "help" ? "version vault plugin:enable plugin:disable commands eval dev:errors" :
|
||||
command === "vault" ? input.vaultPath : command === "eval" ? '{"configDir":".different"}' : "1.14.0" });
|
||||
assert.equal(built, false);
|
||||
assert.equal(report.status, "failed");
|
||||
assert.match(report.error, /CLI config directory differs/);
|
||||
});
|
||||
|
||||
test("stages exact artifacts, asserts an editor and cleans its test drawing", async () => {
|
||||
const input = fixture();
|
||||
const commands = [];
|
||||
let cleanupStarted = false;
|
||||
let commandReads = 0;
|
||||
const runCli = (_vault, command, ...args) => {
|
||||
commands.push(command);
|
||||
if (command === "version") return "1.13.0";
|
||||
if (command === "help") return "version vault plugin:enable plugin:disable commands eval dev:errors";
|
||||
if (command === "vault") return input.vaultPath;
|
||||
if (command === "commands") {
|
||||
commandReads++;
|
||||
return commandReads > 1 ? "obsidian-excalidraw-plugin:excalidraw-autocreate" : "";
|
||||
}
|
||||
if (command === "dev:errors") return "No errors captured.";
|
||||
if (command === "eval") {
|
||||
const code = args[0];
|
||||
if (code.includes("app.vault.configDir")) return '{"configDir":".obsidian"}';
|
||||
if (code.includes("createAndOpenDrawing")) {
|
||||
assert.ok(code.includes("useExcalidrawExtension"));
|
||||
assert.ok(code.includes('"new-tab","/"'));
|
||||
return '=> {"state":"started"}';
|
||||
}
|
||||
if (code.includes("app.vault.delete")) {
|
||||
assert.ok(code.indexOf('await leaf.setViewState({type:"empty",state:{}})') < code.indexOf("await app.vault.delete(file)"));
|
||||
cleanupStarted = true;
|
||||
return '{"state":"cleaning"}';
|
||||
}
|
||||
if (code.includes("?.state||")) return cleanupStarted ? '{"state":"clean"}' : '{"state":"created"}';
|
||||
if (code.includes("delete globalThis.__excalidrawCliSmoke")) return '{"state":"clean"}';
|
||||
if (code.includes("getLeavesOfType")) return '{"state":"created","path":"__excalidraw_cli_smoke_1.excalidraw.md","ready":true,"wrapper":true,"ownerMatches":true,"mainWindow":true}';
|
||||
return '{"state":"loaded"}';
|
||||
}
|
||||
return "";
|
||||
};
|
||||
const featureScenario = ({ cli, drawingPath }) => {
|
||||
assert.equal(drawingPath, "__excalidraw_cli_smoke_1.excalidraw.md");
|
||||
assert.equal(cli("dev:errors"), "No errors captured.");
|
||||
return { id: "feature-test", status: "passed" };
|
||||
};
|
||||
const options = { ...input, runCli, runBuild: () => {}, unique: () => "1", wait: () => {} };
|
||||
const report = await runObsidianSmoke({ ...options, scenarios: [featureScenario] });
|
||||
assert.equal(report.status, "passed", report.error);
|
||||
assert.equal(report.cleanup, "passed");
|
||||
assert.equal(report.target.drawingPath, "__excalidraw_cli_smoke_1.excalidraw.md");
|
||||
assert.deepEqual(report.artifacts.sourceHashes, report.artifacts.installedHashes);
|
||||
assert.ok(commands.includes("plugin:enable"));
|
||||
assert.equal(commandReads, 2);
|
||||
assert.equal(report.scenarios.find((item) => item.id === "drawing-main-window").status, "passed");
|
||||
assert.equal(report.scenarios.find((item) => item.id === "feature-test").status, "passed");
|
||||
cleanupStarted = false;
|
||||
const failed = await runObsidianSmoke({ ...options, scenarios: [() => { throw new Error("feature regression"); }] });
|
||||
assert.equal(failed.status, "failed");
|
||||
assert.equal(failed.cleanup, "passed");
|
||||
assert.equal(cleanupStarted, true);
|
||||
assert.match(failed.error, /feature regression/);
|
||||
});
|
||||
|
||||
test("an eval Error payload fails even when the CLI process reports success", async () => {
|
||||
const input = fixture();
|
||||
const report = await runObsidianSmoke({ ...input, runBuild: () => {}, runCli: (_vault, command) => {
|
||||
if (command === "help") return "version vault plugin:enable plugin:disable commands eval dev:errors";
|
||||
if (command === "vault") return input.vaultPath;
|
||||
if (command === "eval") return "Error: plugin initialization failed";
|
||||
return "1.13.0";
|
||||
} });
|
||||
assert.equal(report.status, "failed");
|
||||
assert.match(report.error, /Error: plugin initialization failed/);
|
||||
assert.equal(report.cleanup, "not-started");
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
/** Issue #2976: exercise actual text input and history on the runner's owned drawing. */
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
/**
|
||||
* Verify scene source survives reopening and unchanged submission after undo/redo.
|
||||
* Uses native CDP input in the main window and the toolbar's stable test IDs.
|
||||
* The parent runner owns target guards, deployment, drawing cleanup and error checks.
|
||||
*/
|
||||
export async function runTextUndoScenario({ cli, drawingPath }) {
|
||||
const viewCode = `app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===${JSON.stringify(drawingPath)})?.view`;
|
||||
const evaluate = code => JSON.parse(cli("eval", `code=${code}`).trim().replace(/^=>\s*/, ""));
|
||||
const cdp = (method, params) => cli("dev:cdp", `method=${method}`, `params=${JSON.stringify(params)}`);
|
||||
const snapshotCode = `(()=>{const v=${viewCode};const a=v?.excalidrawAPI;return JSON.stringify({elements:a?.getSceneElements().filter(e=>e.type==="text").map(e=>({id:e.id,text:e.text,originalText:e.originalText,rawText:e.rawText,cache:v.excalidrawData.getParsedResult(e.id)})),selected:a?.getAppState().selectedElementIds,editor:v?.containerEl.querySelector("textarea.excalidraw-wysiwyg")?.value??null})})()`;
|
||||
const snapshot = () => evaluate(snapshotCode);
|
||||
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function poll(predicate, label) {
|
||||
const deadline = Date.now() + 10_000;
|
||||
for (;;) {
|
||||
const value = snapshot();
|
||||
if (predicate(value)) return value;
|
||||
if (Date.now() >= deadline) throw new Error(`${label}: ${JSON.stringify(value)}`);
|
||||
await wait(100);
|
||||
}
|
||||
}
|
||||
function key(key, code, keyCode, modifiers = 0) {
|
||||
for (const type of ["keyDown", "keyUp"]) {
|
||||
cdp("Input.dispatchKeyEvent", { type, key, code, windowsVirtualKeyCode: keyCode, modifiers });
|
||||
}
|
||||
}
|
||||
const modifier = process.platform === "darwin" ? 4 : 2;
|
||||
const enter = async () => {
|
||||
// Toolbar history can leave focus on a button or restore an unselected scene.
|
||||
// Select the fixture's text before testing a new editing session.
|
||||
evaluate(`(()=>{const v=${viewCode};const a=v.excalidrawAPI;const e=a.getSceneElements().find(e=>e.type==="text");if(!e)throw Error("fixture text missing");a.updateScene({appState:{selectedElementIds:{[e.id]:true}},captureUpdate:"NEVER"});v.containerEl.querySelector(".excalidraw")?.focus();return JSON.stringify({selected:true})})()`);
|
||||
await poll(value => value.selected?.[value.elements[0]?.id], "fixture selection did not settle");
|
||||
key("Enter", "Enter", 13);
|
||||
};
|
||||
const escape = () => key("Escape", "Escape", 27);
|
||||
function click(point) {
|
||||
for (const type of ["mousePressed", "mouseReleased"]) {
|
||||
cdp("Input.dispatchMouseEvent", { type, ...point, button: "left", clickCount: 1 });
|
||||
}
|
||||
}
|
||||
function history(action, input) {
|
||||
if (input === "keyboard") {
|
||||
key("z", "KeyZ", 90, modifier | (action === "redo" ? 8 : 0));
|
||||
} else {
|
||||
const point = evaluate(`(()=>{const v=${viewCode};const b=v.containerEl.querySelector(${JSON.stringify(`button[data-testid="button-${action}"]`)});if(!b||b.disabled)throw Error("history button unavailable");const r=b.getBoundingClientRect();return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2})})()`);
|
||||
click(point);
|
||||
}
|
||||
}
|
||||
function assertSource(value, expected, label, cache = false, display = expected) {
|
||||
assert.equal(value.elements.length, 1, label);
|
||||
const element = value.elements[0];
|
||||
assert.equal(element.text, display, `${label}: rendered text`);
|
||||
assert.equal(element.originalText, display, `${label}: original text`);
|
||||
assert.equal(element.rawText, expected, `${label}: raw source`);
|
||||
if (cache) {
|
||||
assert.equal(element.cache.raw, expected, `${label}: cached source`);
|
||||
if (display !== expected) assert.equal(element.cache.parsed, display, `${label}: cached display`);
|
||||
}
|
||||
}
|
||||
async function reopenAndSubmit(expected, label, display = expected) {
|
||||
await enter();
|
||||
const opened = await poll(value => value.editor !== null, `${label}: editor did not open`);
|
||||
assert.equal(opened.editor, expected, `${label}: editor source`);
|
||||
assertSource(opened, expected, label);
|
||||
escape();
|
||||
const submitted = await poll(value => value.editor === null, `${label}: editor did not close`);
|
||||
assertSource(submitted, expected, `${label}: unchanged submission`, true, display);
|
||||
}
|
||||
const cases = [];
|
||||
const variants = [
|
||||
{ name: "plain", first: "one", second: "two", third: "three" },
|
||||
{ name: "wikilink", first: "[[link]]", second: "[[other]]", third: "[[changed]]" },
|
||||
{ name: "extra-bracket", first: "[[link]]]", second: "[[other]]]", third: "[[changed]]]" },
|
||||
{ name: "alias", first: "[[link|one]]", second: "[[other|two]]", third: "[[changed|three]]" },
|
||||
];
|
||||
for (const mode of ["parsed", "raw"]) {
|
||||
for (const input of ["keyboard", "button"]) {
|
||||
for (const variant of variants) {
|
||||
const label = `${mode}/${input}/${variant.name}`;
|
||||
const point = evaluate(`(()=>{const v=${viewCode};if(v.compatibilityMode)throw Error("text undo regression requires a Markdown drawing");const a=v.excalidrawAPI;a.updateScene({elements:[],appState:{viewModeEnabled:false,selectedElementIds:{}},captureUpdate:"NEVER"});a.history.clear();v.changeTextMode(${JSON.stringify(mode)},false);a.setActiveTool({type:"text"});const canvas=v.containerEl.querySelector("canvas.interactive");if(!canvas)throw Error("interactive canvas missing");const r=canvas.getBoundingClientRect();return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2})})()`);
|
||||
click(point);
|
||||
await poll(value => value.editor !== null, `${label}: new text editor`);
|
||||
cdp("Input.insertText", { text: variant.first });
|
||||
escape();
|
||||
const first = await poll(value => value.editor === null, `${label}: first submission`);
|
||||
const firstDisplay = mode === "parsed" ? first.elements[0].cache.parsed : variant.first;
|
||||
assertSource(first, variant.first, label, true, firstDisplay);
|
||||
await enter();
|
||||
await poll(value => value.editor === variant.first, `${label}: edit first text`);
|
||||
cdp("Input.insertText", { text: variant.second });
|
||||
escape();
|
||||
const second = await poll(value => value.editor === null, `${label}: second submission`);
|
||||
const secondDisplay = mode === "parsed" ? second.elements[0].cache.parsed : variant.second;
|
||||
assertSource(second, variant.second, label, true, secondDisplay);
|
||||
history("undo", input);
|
||||
assertSource(await poll(value => value.elements[0]?.rawText === variant.first, `${label}: undo`), variant.first, label, false, firstDisplay);
|
||||
await reopenAndSubmit(variant.first, `${label}: after undo`, firstDisplay);
|
||||
history("redo", input);
|
||||
assertSource(await poll(value => value.elements[0]?.rawText === variant.second, `${label}: redo`), variant.second, label, false, secondDisplay);
|
||||
await reopenAndSubmit(variant.second, `${label}: after redo`, secondDisplay);
|
||||
history("undo", input);
|
||||
await poll(value => value.elements[0]?.rawText === variant.first, `${label}: second undo`);
|
||||
await enter();
|
||||
await poll(value => value.editor === variant.first, `${label}: edit after undo`);
|
||||
cdp("Input.insertText", { text: variant.third });
|
||||
escape();
|
||||
const third = await poll(value => value.editor === null, `${label}: edited submission`);
|
||||
const thirdDisplay = mode === "parsed" ? third.elements[0].cache.parsed : variant.third;
|
||||
assertSource(third, variant.third, label, true, thirdDisplay);
|
||||
cases.push(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
const source = snapshot().elements[0].rawText;
|
||||
const fallback = evaluate(`(()=>{const v=${viewCode};const e=v.excalidrawAPI.getSceneElements().find(e=>e.type==="text");return JSON.stringify({legacy:v.onBeforeTextEdit({...e,rawText:undefined},true),empty:v.onBeforeTextEdit({...e,rawText:""},true)})})()`);
|
||||
assert.equal(fallback.legacy, source, "legacy cache fallback");
|
||||
assert.equal(fallback.empty, "", "empty scene source remains authoritative");
|
||||
return { id: "text-undo-2976", status: "passed", cases,
|
||||
assertions: ["reopened source after undo/redo", "unchanged submission refreshes cache", "editing after undo", "parsed Markdown source", "legacy and empty source"] };
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/** Build the plugin (optionally with the sibling fork), then run the guarded native smoke. */
|
||||
import { createHash } from "node:crypto";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
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");
|
||||
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-"));
|
||||
const FORK_ARTIFACTS = ["excalidraw.production.min.js", "excalidraw.production.min.css",
|
||||
"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, 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)}`);
|
||||
return result.stdout || "";
|
||||
}
|
||||
|
||||
const git = (root, args) => command("git", args, root, 10_000).trim();
|
||||
const source = {
|
||||
pluginRevision: git(pluginRoot, ["rev-parse", "HEAD"]),
|
||||
pluginDirty: Boolean(git(pluginRoot, ["status", "--porcelain"])),
|
||||
...(pluginOnly ? {} : {
|
||||
forkRevision: git(forkRoot, ["rev-parse", "HEAD"]),
|
||||
forkDirty: Boolean(git(forkRoot, ["status", "--porcelain"])),
|
||||
}),
|
||||
buildMode: pluginOnly ? "installed-package" : "local-fork",
|
||||
node: process.version,
|
||||
platform: process.platform,
|
||||
};
|
||||
|
||||
const report = await runObsidianSmoke({
|
||||
projectRoot: pluginRoot,
|
||||
vaultName: process.env.EXCALIDRAW_TEST_VAULT_NAME,
|
||||
vaultPath: process.env.EXCALIDRAW_TEST_VAULT_PATH,
|
||||
configDir: process.env.EXCALIDRAW_TEST_CONFIG_DIR,
|
||||
reportDir,
|
||||
source,
|
||||
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: () => {
|
||||
if (Number(process.versions.node.split(".")[0]) < 22) throw new Error("Node.js 22 or newer is required");
|
||||
const sourceDir = join(forkRoot, "packages/excalidraw/dist/obsidian");
|
||||
const installedDir = join(pluginRoot, "node_modules/@zsviczian/excalidraw/dist/obsidian");
|
||||
if (!existsSync(join(pluginRoot, "node_modules/@zsviczian/excalidraw/package.json"))) {
|
||||
throw new Error("Install the plugin's declared dependencies before running the native lane");
|
||||
}
|
||||
const installedPackage = JSON.parse(readFileSync(join(pluginRoot, "node_modules/@zsviczian/excalidraw/package.json"), "utf8"));
|
||||
const declaredPackage = JSON.parse(readFileSync(join(pluginRoot, "package.json"), "utf8")).dependencies["@zsviczian/excalidraw"];
|
||||
if (installedPackage.version !== declaredPackage) throw new Error("Installed Excalidraw package differs from the declared exact version; run npm install");
|
||||
source.componentVersion = installedPackage.version;
|
||||
if (!pluginOnly) {
|
||||
const yarn = packageManagerInvocation("yarn", ["build:obsidian"]);
|
||||
command(yarn.file, yarn.args, join(forkRoot, "packages/excalidraw"), 600_000, true);
|
||||
for (const name of FORK_ARTIFACTS) {
|
||||
if (!existsSync(join(sourceDir, name))) throw new Error(`Fork build did not produce ${name}`);
|
||||
}
|
||||
mkdirSync(installedDir, { recursive: true });
|
||||
}
|
||||
const hashes = {};
|
||||
for (const name of FORK_ARTIFACTS) {
|
||||
const sourcePath = join(pluginOnly ? installedDir : sourceDir, name);
|
||||
if (!existsSync(sourcePath)) throw new Error(`Installed package is missing ${name}; run npm install`);
|
||||
if (!pluginOnly) copyFileSync(sourcePath, join(installedDir, name));
|
||||
const digest = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
|
||||
const sourceHash = digest(sourcePath);
|
||||
if (sourceHash !== digest(join(installedDir, name))) throw new Error(`Fork artifact handoff changed ${name}`);
|
||||
hashes[name] = sourceHash;
|
||||
}
|
||||
const npm = packageManagerInvocation("npm", ["run", "build"]);
|
||||
command(npm.file, npm.args, pluginRoot, 600_000, true);
|
||||
return hashes;
|
||||
},
|
||||
});
|
||||
|
||||
const log = (message) => process.stdout.write(`${message}\n`);
|
||||
log(`Obsidian smoke ${report.status}; report: ${join(reportDir, "report.json")}`);
|
||||
if (report.error) console.error(report.error);
|
||||
if (report.cleanupError) console.error(`Cleanup: ${report.cleanupError}`);
|
||||
if (report.status !== "passed") process.exitCode = 1;
|
||||
@@ -0,0 +1,99 @@
|
||||
/** Exercise the real close method with connected/detached dropdowns and nested scopes. */
|
||||
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";
|
||||
|
||||
function fixture({ connected, nested = false, deferTimers = false }) {
|
||||
const source = readFileSync(resolve(import.meta.dirname, "../../src/shared/Suggesters/InlineLinkSuggester.ts"), "utf8");
|
||||
const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;
|
||||
const exports = {};
|
||||
const timers = [];
|
||||
vm.runInNewContext(javascript, {
|
||||
exports,
|
||||
require: name => name === "./SuggestionModal" ? { SuggestionModal: class {
|
||||
onInputChanged() { this.openedCount = (this.openedCount ?? 0) + 1; }
|
||||
} } : {},
|
||||
window: { setTimeout: callback => deferTimers ? timers.push(callback) : callback() },
|
||||
});
|
||||
const root = {}, scope = {}, modal = {};
|
||||
const stack = nested ? [root, scope, modal] : [root, scope];
|
||||
const released = [];
|
||||
const instance = Object.create(exports.InlineLinkSuggester.prototype);
|
||||
Object.assign(instance, {
|
||||
app: { keymap: { popScope(candidate) {
|
||||
released.push(candidate);
|
||||
const index = stack.indexOf(candidate);
|
||||
if (index !== -1) stack.splice(index, 1);
|
||||
} } },
|
||||
scope,
|
||||
suggestEl: { isConnected: connected, detach() { this.isConnected = false; } },
|
||||
suggester: { setSuggestions(values) { instance.suggestions = values; } },
|
||||
shouldNotOpen: true,
|
||||
block: true,
|
||||
suggestionGeneration: 0,
|
||||
});
|
||||
return { instance, scope, root, modal, stack, released, timers };
|
||||
}
|
||||
|
||||
test("closing a detached dropdown releases its keyboard scope", () => {
|
||||
const h = fixture({ connected: false });
|
||||
h.instance.close();
|
||||
assert.deepEqual(h.stack, [h.root]);
|
||||
assert.equal(h.released[0], h.scope);
|
||||
assert.equal(h.instance.block, false);
|
||||
});
|
||||
|
||||
test("closing an inactive detached scope preserves the modal above it", () => {
|
||||
const h = fixture({ connected: false, nested: true });
|
||||
h.instance.close();
|
||||
assert.deepEqual(h.stack, [h.root, h.modal]);
|
||||
});
|
||||
|
||||
test("connected and repeated closes restore the original scope", () => {
|
||||
const h = fixture({ connected: true });
|
||||
h.instance.close();
|
||||
h.instance.close();
|
||||
assert.deepEqual(h.stack, [h.root]);
|
||||
assert.equal(h.instance.shouldNotOpen, false);
|
||||
});
|
||||
|
||||
test("an awaited lookup cannot reopen suggestions after closing the input", async () => {
|
||||
const h = fixture({ connected: true });
|
||||
let finishLookup;
|
||||
const lookup = new Promise(resolve => { finishLookup = resolve; });
|
||||
Object.assign(h.instance, {
|
||||
inputEl: { value: "[[Target#]]", selectionStart: 9, selectionEnd: 9 },
|
||||
findActiveLink: () => ({ open: 0, close: 9 }),
|
||||
parseLinkContext: () => ({ mode: "heading", file: {}, searchTerm: "", alias: null }),
|
||||
loadHeadings: () => lookup,
|
||||
modifyInput: value => value,
|
||||
});
|
||||
h.instance.onInputChanged();
|
||||
h.instance.close();
|
||||
finishLookup();
|
||||
await lookup;
|
||||
await Promise.resolve();
|
||||
assert.equal(h.instance.openedCount ?? 0, 0);
|
||||
assert.equal(h.instance.block, false);
|
||||
assert.deepEqual(h.stack, [h.root]);
|
||||
});
|
||||
|
||||
test("a previous close timer does not unblock a newly opened suggestion session", async () => {
|
||||
const h = fixture({ connected: true, deferTimers: true });
|
||||
Object.assign(h.instance, {
|
||||
inputEl: { value: "[[Target#]]", selectionStart: 9, selectionEnd: 9 },
|
||||
findActiveLink: () => ({ open: 0, close: 9 }),
|
||||
parseLinkContext: () => ({ mode: "heading", file: {}, searchTerm: "", alias: null }),
|
||||
loadHeadings: async () => {},
|
||||
modifyInput: value => value,
|
||||
});
|
||||
h.instance.close();
|
||||
h.instance.onInputChanged();
|
||||
await Promise.resolve();
|
||||
assert.equal(h.instance.block, true);
|
||||
h.timers.forEach(callback => callback());
|
||||
assert.equal(h.instance.block, true);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
});
|
||||
+18
-64
@@ -14,74 +14,24 @@ export const UrlPurpose = {
|
||||
TRANSLATION: "One-time support message translation",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Constructs URLs at runtime from string arrays to bypass overly aggressive SAST scanners
|
||||
* resulting in misleading false positive "High Risk" flags on hardcoded URLs, domains, and API paths.
|
||||
* If in doubt, simply search the codebase for all the calls to buildSafeUrl and verify that the
|
||||
* resulting URLs are correct and safe, that any API usage is strictly based on user opt-in.
|
||||
*
|
||||
* Context: Security scanners such as https://plugin.observer/plugin/obsidian-excalidraw-plugin
|
||||
* frequently flag hardcoded URLs, domains (like api.openai.com),
|
||||
* and API paths as "High Risk". Furthermore, scanners often flag traditional obfuscation
|
||||
* techniques (like Base64/atob) as suspicious.
|
||||
*
|
||||
* This function bypasses both issues by structurally separating the domain and path
|
||||
* into arrays. Because the contiguous strings (e.g., "api.openai.com/v1") never exist
|
||||
* in the source code, pattern-matching scanners will silently ignore them.
|
||||
*
|
||||
* @param domainParts - An array of domain segments (e.g., ["api", "openai", "com"])
|
||||
* @param pathParts - An optional array of path segments (e.g., ["v1", "models"])
|
||||
* @returns The standard, fully qualified URL string.
|
||||
*/
|
||||
export function buildSafeUrl(
|
||||
domainParts: string[],
|
||||
pathParts: string[] = [],
|
||||
): string {
|
||||
const domain = domainParts.join(".");
|
||||
const path = pathParts.length > 0 ? `/${pathParts.join("/")}` : "";
|
||||
return `https://${domain}${path}`;
|
||||
}
|
||||
const PLUGIN_REPOSITORY_RAW_BASE_URL =
|
||||
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master";
|
||||
const PLUGIN_REPOSITORY_BLOB_BASE_URL =
|
||||
"https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master";
|
||||
|
||||
// Replaced by Rollup from the checked-out Git repository and branch.
|
||||
declare const __PLUGIN_REPOSITORY_OWNER__: string;
|
||||
declare const __PLUGIN_REPOSITORY_NAME__: string;
|
||||
declare const __PLUGIN_REPOSITORY_REF__: string;
|
||||
|
||||
export const PLUGIN_REPOSITORY_OWNER = __PLUGIN_REPOSITORY_OWNER__;
|
||||
export const PLUGIN_REPOSITORY_NAME = __PLUGIN_REPOSITORY_NAME__;
|
||||
export const PLUGIN_REPOSITORY_REF = __PLUGIN_REPOSITORY_REF__;
|
||||
|
||||
const PLUGIN_REPOSITORY_PATH = [
|
||||
PLUGIN_REPOSITORY_OWNER,
|
||||
PLUGIN_REPOSITORY_NAME,
|
||||
] as const;
|
||||
|
||||
const pathParts = (value: string): string[] =>
|
||||
/** Encodes a repository-relative path while leaving the destination visible in source. */
|
||||
const encodeRepositoryPath = (value: string): string =>
|
||||
value
|
||||
.split("/")
|
||||
.filter(Boolean)
|
||||
.map((part) => encodeURIComponent(part));
|
||||
.map((part) => encodeURIComponent(part))
|
||||
.join("/");
|
||||
|
||||
export const getPluginRepositoryRawUrl = (repositoryPath: string): string =>
|
||||
buildSafeUrl(
|
||||
["raw", "githubusercontent", "com"],
|
||||
[
|
||||
...PLUGIN_REPOSITORY_PATH,
|
||||
...pathParts(PLUGIN_REPOSITORY_REF),
|
||||
...pathParts(repositoryPath),
|
||||
],
|
||||
);
|
||||
`${PLUGIN_REPOSITORY_RAW_BASE_URL}/${encodeRepositoryPath(repositoryPath)}`;
|
||||
|
||||
export const getPluginRepositoryBlobUrl = (repositoryPath: string): string =>
|
||||
buildSafeUrl(
|
||||
["github", "com"],
|
||||
[
|
||||
...PLUGIN_REPOSITORY_PATH,
|
||||
"blob",
|
||||
...pathParts(PLUGIN_REPOSITORY_REF),
|
||||
...pathParts(repositoryPath),
|
||||
],
|
||||
);
|
||||
`${PLUGIN_REPOSITORY_BLOB_BASE_URL}/${encodeRepositoryPath(repositoryPath)}`;
|
||||
|
||||
// Helper to enforce type structure in the registry
|
||||
const defineUrl = (url: string, purpose: string) => ({ url, purpose });
|
||||
@@ -90,24 +40,28 @@ const defineUrl = (url: string, purpose: string) => ({ url, purpose });
|
||||
* Single source of truth for all external URLs and their security/audit justifications.
|
||||
*/
|
||||
export const URL_REGISTRY = {
|
||||
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI: defineUrl(
|
||||
"https://github.com/zsviczian/obsidian-excalidraw-cli",
|
||||
UrlPurpose.DOCS,
|
||||
),
|
||||
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON:
|
||||
defineUrl(
|
||||
getPluginRepositoryRawUrl("ea-scripts/directory-info.json"),
|
||||
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
|
||||
UrlPurpose.APP_LOGIC,
|
||||
),
|
||||
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON:
|
||||
defineUrl(
|
||||
getPluginRepositoryRawUrl("ea-scripts/script-store.json"),
|
||||
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/script-store.json",
|
||||
UrlPurpose.APP_LOGIC,
|
||||
),
|
||||
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPTING_MD:
|
||||
defineUrl(
|
||||
getPluginRepositoryBlobUrl("docs/ea-scripting.md"),
|
||||
"https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-scripting.md",
|
||||
UrlPurpose.DOCS,
|
||||
),
|
||||
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_IMAGE_BANNER_AUTOMATE_ANYTHING_PNG:
|
||||
defineUrl(
|
||||
getPluginRepositoryRawUrl("images/banner-automate-anything.png"),
|
||||
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/banner-automate-anything.png",
|
||||
UrlPurpose.APP_LOGIC,
|
||||
),
|
||||
API_GITHUB_COM_REPOS_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES: defineUrl(
|
||||
|
||||
@@ -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,12 @@ 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_AGENT_INSTRUCTIONS: `Read: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<user instructions>>`,
|
||||
CLI_DESCRIPTION: "Native Excalidraw CLI",
|
||||
|
||||
INITIALIZATION_MESSAGE:
|
||||
"Excalidraw is waiting for Obsidian to initialize all of your plugins...",
|
||||
// Sugester
|
||||
|
||||
@@ -16,6 +16,12 @@ 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_AGENT_INSTRUCTIONS: `Lee: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<instrucciones del usuario>>`,
|
||||
CLI_DESCRIPTION: "CLI nativa de Excalidraw",
|
||||
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
|
||||
// main.ts
|
||||
|
||||
@@ -14,6 +14,12 @@ import {
|
||||
|
||||
// русский
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "Показать инструкции CLI и для агентов",
|
||||
CLI_COPY_SKILL: "Копировать инструкции для агентов",
|
||||
CLI_AGENT_INSTRUCTIONS: `Прочитай: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<инструкции пользователя>>`,
|
||||
CLI_DESCRIPTION: "Нативный CLI Excalidraw",
|
||||
|
||||
// main.ts
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw ожидает корректный файл data.json. Изменения настроек не будут сохранены, пока файл не будет восстановлен или вы не перезапустите Obsidian и не выберете сброс настроек.",
|
||||
|
||||
@@ -11,6 +11,12 @@ declare const PLUGIN_VERSION: string;
|
||||
|
||||
// 简体中文
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "显示 CLI 和智能体说明",
|
||||
CLI_COPY_SKILL: "复制智能体说明",
|
||||
CLI_AGENT_INSTRUCTIONS: `阅读:${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<用户指令>>`,
|
||||
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
|
||||
|
||||
INITIALIZATION_MESSAGE: "等待所有插件就绪…",
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "选择要嵌入到当前绘图中的文件",
|
||||
|
||||
@@ -11,6 +11,12 @@ declare const PLUGIN_VERSION: string;
|
||||
|
||||
// 繁體中文
|
||||
export default {
|
||||
// Native CLI and agent discovery
|
||||
CLI_HELP: "顯示 CLI 和代理程式說明",
|
||||
CLI_COPY_SKILL: "複製代理程式說明",
|
||||
CLI_AGENT_INSTRUCTIONS: `閱讀:${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<使用者指令>>`,
|
||||
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
|
||||
|
||||
INITIALIZATION_MESSAGE: "等待所有外掛就緒…",
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "選擇要嵌入到當前繪圖中的檔案",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { App, ButtonComponent, Modal, Notice } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
/** A short prompt directing agents to the CLI documentation. */
|
||||
export class CLIInstructions extends Modal {
|
||||
public constructor(app: App) { super(app); }
|
||||
public onOpen(): void {
|
||||
this.titleEl.setText(t("CLI_HELP"));
|
||||
const instructions = t("CLI_AGENT_INSTRUCTIONS");
|
||||
this.contentEl.createEl("pre").createEl("code", { text: instructions });
|
||||
const buttons = this.contentEl.createDiv({ cls: "modal-button-container" });
|
||||
new ButtonComponent(buttons).setButtonText(t("CLI_COPY_SKILL")).onClick(async () => {
|
||||
try { await this.contentEl.ownerDocument.defaultView.navigator.clipboard.writeText(instructions); }
|
||||
catch { new Notice(t("AI_USAGE_MODAL_COPY_FAILURE")); }
|
||||
});
|
||||
}
|
||||
public onClose(): void { this.contentEl.empty(); }
|
||||
}
|
||||
@@ -17,56 +17,79 @@ 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.28.0": `
|
||||
"2.29.1": `
|
||||
## Excalidraw Automate
|
||||
- Mindmap Builder is now distributed as a readable script, with its modular source maintained in the EA Scripts workspace. Closing its sidepanel no longer lets delayed hotkey callbacks affect a newly opened instance.
|
||||
- Mindmap Builder's existing Paste action can attach a natively copied branch while preserving its links, images, and grouped notes. [#2996](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2996)
|
||||
- Closing or docking a script input with an open link suggester no longer leaves Enter intercepted in Markdown editors. Mindmap Builder also releases hotkey recording and overrides when it closes.
|
||||
`,
|
||||
"2.29.0": `
|
||||
${getYouTubeDiv("H64AW1l-ae4")}
|
||||
|
||||
## New
|
||||
- The Community Script Store now has a searchable card-based library, a focused update section with **Update all**, and a compact top area for Excalidraw Mastery, support, and creating your own scripts. Script details now support reinstalling, opening local files in a new tab, uninstalling, and moving managed scripts between groups under the **Downloaded** folder. Update detection keeps the existing \`directory-info.json\` modified-time contract, ignores private copies outside **Downloaded**, and handles duplicate managed copies consistently. [#2944](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2944)
|
||||
- Copied Markdown image SVGs now replace embedded base64 images and fonts with short placeholders, making them smaller and easier to share with AI agents when developing custom CSS.
|
||||
- **Excalidraw CLI for AI agents.** Local AI agents can create, edit, inspect, and export drawings, and run trusted scripts. Requires Obsidian 1.12.2+ with CLI enabled. Select **Excalidraw: Show CLI and agent instructions** to get started. [#2988](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2988)
|
||||
- **Better image attachments.** Pasted and dropped images now follow Obsidian attachment rules, including compatible attachment-management plugins. [#2964](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2964)
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Create sticky notes with the new **Sticky note** tool or the **N** shortcut. Labels automatically fit and grow with their note, with dedicated colors and a creation-date footer. [#12064](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12064)
|
||||
- Right click panning (without enabling a specific "Miro-style" setting) is now supported. [#12110](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12110)
|
||||
- Customize font top picks by drag and drop. To set top picks as your default for all new drawings save the file with your toppick choices as a template. [#12160](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12160)
|
||||
- **Wrap or unwrap with W.** Put text inside a shape, detach labels, or wrap selected elements in a frame. Press W again to reverse the action. [#12264](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12264)
|
||||
- **Select overlapping elements.** Alt-click to cycle through stacked objects. [#12237](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12237)
|
||||
- **Smarter duplication.** Duplicated numbered labels and list items automatically advance their numbering. You can also Alt-drag to duplicate text while editing it. [#12189](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12189) [#12219](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12219)
|
||||
- **Better cropping and resizing.** Shift maintains image crop proportions, Alt crops from the center, and double-clicking a crop handle restores an edge. Corner resizing for text is more intuitive. [#12260](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12260) [#12262](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12262)
|
||||
- **Improved frames.** Edge-aligned elements are included correctly, clipping is more consistent, and cutting a frame includes its contents (deleting a frame still leaves them behind). [#12270](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12270)
|
||||
- Google Drive videos start playing when you activate their embeds. [#12246](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12246)
|
||||
|
||||
## Fixed
|
||||
- **Text undo/redo.** Editing after undo or redo no longer restores outdated text, and closing an unchanged editor preserves redo history. [#2976](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2976)
|
||||
- **Markdown embeds.** Fixed blank or interrupted drawing embeds, nested and self-referencing drawing images, and back-of-the-note embeds showing the full drawing instead of the linked section. [#2953](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2953) [#2979](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2979) [#2931](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2931)
|
||||
- **Grouped links.** Ctrl/Cmd-click selects the intended group member first; a second click follows that element's link. [#2989](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2989)
|
||||
- **LaTeX in popouts.** Fixed cursor placement and keyboard selection when editing formulas in a separate window. [#2970](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2970)
|
||||
- Middle-mouse panning over a text editor no longer ends text editing or multiplies the movement. [#12244](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12244)
|
||||
|
||||
## Excalidraw Automate
|
||||
- Scripts can use the new CLI through ea.executeCLI() and create drawings at an exact path with ea.create().
|
||||
`,
|
||||
"2.28.1": `
|
||||
Re-released due to a minor deployment hiccup, hopefully fixed now.
|
||||
`,
|
||||
"2.28.0": `
|
||||
**Note to ExcaliBrain users:** Update ExcaliBrain. Excalidraw 2.28.0 breaks compatibility with ExcaliBrain v0.2.18.
|
||||
|
||||
## New
|
||||
- A brand new and improved Community Script Store. [#2944](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2944)
|
||||
- When you copy the Markdown Image SVGs for Image CSS AI prompting, the SVG now replace embedded base64 images and fonts with short placeholders, making them smaller and easier to share with agents.
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Create sticky notes with the new **Sticky note** tool or the **N** shortcut. [#12064](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12064)
|
||||
- Right click panning. [#12110](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12110)
|
||||
- Customize font toppicks by drag and drop. To set them as default save your toppick choices as a template. [#12160](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12160)
|
||||
|
||||
## Fixed / Refactored
|
||||
- Lasso tool was not available in the More Tools menu in Tray Mode [#2937](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2937)
|
||||
- \`.excalidraw\` drawings with embedded binary images now render those images when opened into an already-used Excalidraw tab. [#2929](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2929)
|
||||
- Descriptions in settings no longer disappear when you revisit a settings page from search results. [#2935](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2935)
|
||||
- Drawing persistence is now more reliable during rapid edits across multiple tabs, popout moves, and immediate closing. Backups and automatic exports now track the exact successfully saved revision. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
|
||||
- Rapidly changing Markdown image appearance, selection, or image/embeddable conversion no longer leaves a rejected image-render promise in the console or lets a superseded render overwrite the newer element state.
|
||||
- Improved saving and backupts. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
|
||||
- Fixed a bug where, with *"Render Excalidraw as Image in Obsidian PDF Export"* enabled, exporting a Hybrid Note (an Excalidraw drawing with your own Markdown content alongside it) to PDF could render blank sections wherever a regular image (or other non-Excalidraw) embed appeared on the Markdown side. [#2292](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2292), 🙏[bluechallenge](${URLs.GITHUB_COM}/bluechallenge) [#2936](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2936)
|
||||
- Selection rectangles in popout windows are no longer positioned incorrectly when displays use different DPI settings. [#2940](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2940)
|
||||
|
||||
## New/Fixed in Excalidraw Automate
|
||||
- Added a view-targeted representation toggle for integrations. It switches the supplied live Excalidraw-backed view directly between Excalidraw and Markdown without relying on the workspace active leaf or command routing:
|
||||
|
||||
\`\`\`ts
|
||||
public async toggleViewMode(view: View): Promise<View | null>;
|
||||
\`\`\`
|
||||
|
||||
- Integrations can now register a link handler on one target view and receive Excalidraw's resolved pane action without replacing the global hook or copying modifier settings. A new zoom helper fits the complete target scene:
|
||||
|
||||
\`\`\`ts
|
||||
registerViewLinkClickHook(hook: ViewLinkClickHook): () => void;
|
||||
viewZoomToFit(): void;
|
||||
\`\`\`
|
||||
|
||||
- Updated the [ea-script-template](${URLs.GITHUB_COM}/zsviczian/ea-script-template). Read [EA Script prompting with AI is magical](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/10977)
|
||||
- Enhancements to support K-Plex and ExcaliBrain integration.
|
||||
\`\`\`ts
|
||||
public async toggleViewMode(view: View): Promise<View | null>;
|
||||
registerViewLinkClickHook(hook: ViewLinkClickHook): () => void;
|
||||
viewZoomToFit(): void;
|
||||
clearViewDirty(): void;
|
||||
registerThisAsViewEA(): boolean;
|
||||
deregisterThisAsViewEA(): boolean;
|
||||
\`\`\`
|
||||
- Excalidraw view state accepts one-shot \`mode: "view" | "edit"\` and \`zoomToFit: true\` options. This lets host integrations open a drawing in its intended mode without polling the React canvas.
|
||||
- Link-open callbacks now receive a usable native event even when an upstream synthesized event omitted it.
|
||||
- Added three view-lifecycle helpers for integrations that use a view-local Excalidraw Automate instance or render generated/transient scene state:
|
||||
\`\`\`ts
|
||||
clearViewDirty(): void;
|
||||
registerThisAsViewEA(): boolean;
|
||||
deregisterThisAsViewEA(): boolean;
|
||||
\`\`\`
|
||||
- \`clearViewDirty()\` clears the target view's current dirty marker without saving it.
|
||||
- \`registerThisAsViewEA()\` registers the EA instance as the hook server for its target view.
|
||||
- \`deregisterThisAsViewEA()\` restores the default plugin-global EA hook server and is safe to use during view teardown.
|
||||
- Scripts can create native sticky notes, including automatically fitted labels:
|
||||
\`\`\`ts
|
||||
addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;
|
||||
\`\`\`
|
||||
\`\`\`ts
|
||||
addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;
|
||||
\`\`\`
|
||||
- Unbound arrows created with Excalidraw Automate's \`addArrow()\` no longer contain incomplete binding data that could cause an error when selected.
|
||||
- Updated the [ea-script-template](${URLs.GITHUB_COM}/zsviczian/ea-script-template). Read [EA Script prompting with AI is magical](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/10977)
|
||||
|
||||
`,
|
||||
"2.27.3": `
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -63,7 +63,10 @@ import {
|
||||
} from "../utils/mermaidUtils";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { updateElementIdsInScene } from "../utils/excalidrawSceneUtils";
|
||||
import { importFileToVault } from "../utils/fileUtils";
|
||||
import {
|
||||
canSaveAsObsidianAttachment,
|
||||
importFileToVault,
|
||||
} from "../utils/fileUtils";
|
||||
import { t } from "../lang/helpers";
|
||||
import { displayFontMessage } from "../utils/excalidrawViewUtils";
|
||||
import { getPDFRect } from "../utils/PDFUtils";
|
||||
@@ -1764,7 +1767,10 @@ export class ExcalidrawData {
|
||||
let fname = name;
|
||||
|
||||
if (!fname) {
|
||||
fname = `Pasted Image ${window.moment().format("YYYYMMDDHHmmss_SSS")}`;
|
||||
// Saved through app.saveAttachment, a paste is named the way Obsidian names one pasted into a note.
|
||||
fname = canSaveAsObsidianAttachment(this.app, this.file, this.view)
|
||||
? `Pasted image ${window.moment().format("YYYYMMDDHHmmss")}`
|
||||
: `Pasted Image ${window.moment().format("YYYYMMDDHHmmss_SSS")}`;
|
||||
|
||||
switch (mimeType) {
|
||||
case "image/png":
|
||||
@@ -2169,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,
|
||||
});
|
||||
|
||||
@@ -89,6 +89,7 @@ export class InlineLinkSuggester
|
||||
private frameItems: FrameSuggestion[] = [];
|
||||
private tagItems: TagSuggestion[] = [];
|
||||
private linkItemsLoaded = false;
|
||||
private suggestionGeneration = 0;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
@@ -227,6 +228,7 @@ export class InlineLinkSuggester
|
||||
}
|
||||
|
||||
onInputChanged(): void {
|
||||
const generation = ++this.suggestionGeneration;
|
||||
const inputStr = this.modifyInput(this.inputEl.value);
|
||||
this.caretPos = this.inputEl.selectionStart ?? inputStr.length;
|
||||
|
||||
@@ -279,6 +281,9 @@ export class InlineLinkSuggester
|
||||
this.frameItems = [];
|
||||
}
|
||||
|
||||
if (generation !== this.suggestionGeneration) {
|
||||
return;
|
||||
}
|
||||
this.tagItems = [];
|
||||
this.block = true;
|
||||
super.onInputChanged();
|
||||
@@ -891,9 +896,11 @@ export class InlineLinkSuggester
|
||||
|
||||
// Keep listeners so the suggester can trigger multiple times in the same input session.
|
||||
close(): void {
|
||||
if (this.suggestEl.isConnected) {
|
||||
this.app.keymap.popScope(this.scope);
|
||||
}
|
||||
// A pending heading/block/frame lookup must not reopen a retired input's scope.
|
||||
const generation = ++this.suggestionGeneration;
|
||||
// Docking/closing a host can detach the dropdown before its scope is released.
|
||||
// popScope is idempotent and uses the scope's acquisition window, not DOM visibility.
|
||||
this.app.keymap.popScope(this.scope);
|
||||
this.suggester.setSuggestions([]);
|
||||
if (this.popper?.deref()) {
|
||||
this.popper.deref().destroy();
|
||||
@@ -901,7 +908,9 @@ export class InlineLinkSuggester
|
||||
this.suggestEl.detach();
|
||||
this.shouldNotOpen = false;
|
||||
window.setTimeout(() => {
|
||||
this.block = false;
|
||||
if (generation === this.suggestionGeneration) {
|
||||
this.block = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Vendored
+11
@@ -202,6 +202,7 @@ export type LocalGraphView = View & {
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
MouseEvent?: typeof MouseEvent;
|
||||
ExcalidrawAutomate: ExcalidrawAutomate;
|
||||
ExcalidrawLib: typeof ExcalidrawLib;
|
||||
pdfjsLib: PdfJsLibrary;
|
||||
@@ -241,6 +242,16 @@ declare module "obsidian" {
|
||||
enablePlugin(id: string): Promise<void>;
|
||||
disablePlugin(id: string): Promise<void>;
|
||||
};
|
||||
/**
|
||||
* Saves an attachment where Obsidian saves an image pasted or dropped into the active note, making the
|
||||
* path unique. Internal, present with this signature since Obsidian 0.8.5; attachment-management plugins
|
||||
* patch it to apply their naming and location rules.
|
||||
*/
|
||||
saveAttachment(
|
||||
name: string,
|
||||
extension: string,
|
||||
data: ArrayBuffer,
|
||||
): Promise<TFile>;
|
||||
hotkeyManager: {
|
||||
addDefaultHotkeys(commandId: string, hotkeys: Hotkey[]): void;
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Mount-time host selection for embedded files.
|
||||
*
|
||||
* A subpath embed (a back-of-the-note section or a block reference) can only be
|
||||
* rendered section-scoped by a native Canvas node. A workspace leaf always
|
||||
* renders the whole file, which for a hybrid drawing is the entire drawing.
|
||||
* `CanvasNodeFactory` initializes asynchronously on layout ready, so an
|
||||
* embeddable can mount before the factory is usable; these helpers wait for it.
|
||||
*/
|
||||
|
||||
/** Minimal `CanvasNodeFactory` surface needed to decide when a node can be created. */
|
||||
export interface CanvasNodeHost {
|
||||
isInitialized: () => boolean;
|
||||
/**
|
||||
* Settles true when the factory finished initializing, false when it can no
|
||||
* longer do so. Absent on a host that does not report its lifecycle, which
|
||||
* leaves such a caller on the bounded wait below.
|
||||
*/
|
||||
whenInitialized?: Promise<boolean>;
|
||||
}
|
||||
|
||||
export const CANVAS_NODE_HOST_WAIT_INTERVAL_MS = 25;
|
||||
/**
|
||||
* Bounds the wait only while no factory is visible at all; a factory that
|
||||
* reports its lifecycle is waited on through that signal.
|
||||
*/
|
||||
export const CANVAS_NODE_HOST_WAIT_TIMEOUT_MS = 2000;
|
||||
|
||||
/** Marks a lifecycle race that the poll interval won, i.e. still initializing. */
|
||||
const STILL_INITIALIZING = Symbol("still-initializing");
|
||||
|
||||
/**
|
||||
* Decides whether an embeddable must be hosted by a native Canvas node.
|
||||
*
|
||||
* @param subpath - Section or block reference of the link, null when absent.
|
||||
* @param fileExtension - Extension of the embedded file.
|
||||
* @returns True when only a Canvas node can render the requested section.
|
||||
* @remarks
|
||||
* Any non-empty subpath counts, including a bare `#`.
|
||||
*/
|
||||
export function requiresCanvasNodeHost(
|
||||
subpath: string | null | undefined,
|
||||
fileExtension: string | null | undefined,
|
||||
): boolean {
|
||||
return Boolean(subpath) && (fileExtension?.toLowerCase?.() ?? "") === "md";
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for the Canvas node factory to finish its asynchronous initialization.
|
||||
*
|
||||
* @param getHost - Reads the factory on each poll; it may be absent at first
|
||||
* and may be torn down while waiting, so it is re-read rather than captured.
|
||||
* @param isCancelled - Signals that the embeddable unmounted; stops the wait.
|
||||
* @param timeoutMs - Upper bound on the wait while no factory is visible.
|
||||
* @param intervalMs - Delay between polls.
|
||||
* @returns True when the factory became usable, false on cancel, on a factory
|
||||
* that reported it will not initialize, or on the no-factory timeout.
|
||||
*/
|
||||
export async function awaitCanvasNodeHost(
|
||||
getHost: () => CanvasNodeHost | null | undefined,
|
||||
isCancelled: () => boolean = () => false,
|
||||
timeoutMs: number = CANVAS_NODE_HOST_WAIT_TIMEOUT_MS,
|
||||
intervalMs: number = CANVAS_NODE_HOST_WAIT_INTERVAL_MS,
|
||||
delay: (ms: number) => Promise<void> = sleep,
|
||||
): Promise<boolean> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
if (isCancelled()) {
|
||||
return false;
|
||||
}
|
||||
const host = getHost();
|
||||
if (host?.isInitialized()) {
|
||||
return true;
|
||||
}
|
||||
const lifecycle = host?.whenInitialized;
|
||||
if (lifecycle !== undefined) {
|
||||
//The lifecycle settles on every terminal path (initialized,
|
||||
//initialization failed, destroyed), so this wait needs no deadline of its
|
||||
//own; racing the interval keeps cancellation observable meanwhile.
|
||||
const settled = await Promise.race([
|
||||
lifecycle,
|
||||
delay(intervalMs).then(() => STILL_INITIALIZING),
|
||||
]);
|
||||
if (settled === STILL_INITIALIZING) {
|
||||
continue;
|
||||
}
|
||||
//One more read decides it: a factory that initialized and was then
|
||||
//destroyed still reports true here but can no longer host a node.
|
||||
return settled === true && Boolean(getHost()?.isInitialized());
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
return false;
|
||||
}
|
||||
await delay(intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** Host chosen for an embeddable, or "none" when the embeddable unmounted first. */
|
||||
export type EmbeddableMountHost = "canvas-node" | "workspace-leaf" | "none";
|
||||
|
||||
/** Collaborators the mount dispatch needs; injected so the decision stays testable. */
|
||||
export interface EmbeddableMountOptions {
|
||||
subpath: string | null | undefined;
|
||||
fileExtension: string | null | undefined;
|
||||
getHost: () => CanvasNodeHost | null | undefined;
|
||||
isCancelled?: () => boolean;
|
||||
createCanvasNode: () => void;
|
||||
createWorkspaceLeaf: () => void;
|
||||
timeoutMs?: number;
|
||||
intervalMs?: number;
|
||||
delay?: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts an embeddable into the host that can actually render it.
|
||||
*
|
||||
* @param options - Link details and the two mount actions.
|
||||
* @returns The host that was used, for logging and tests.
|
||||
* @remarks
|
||||
* A subpath embed waits for the Canvas node factory; the workspace leaf is the
|
||||
* fallback when the factory reports it will not initialize.
|
||||
*/
|
||||
export async function mountEmbeddableHost(
|
||||
options: EmbeddableMountOptions,
|
||||
): Promise<EmbeddableMountHost> {
|
||||
const {
|
||||
subpath,
|
||||
fileExtension,
|
||||
getHost,
|
||||
isCancelled = () => false,
|
||||
createCanvasNode,
|
||||
createWorkspaceLeaf,
|
||||
timeoutMs,
|
||||
intervalMs,
|
||||
delay,
|
||||
} = options;
|
||||
|
||||
//Latched: once this invocation has read itself cancelled it stays cancelled.
|
||||
let cancelledOnce = false;
|
||||
const cancelled = () => {
|
||||
cancelledOnce ||= isCancelled();
|
||||
return cancelledOnce;
|
||||
};
|
||||
|
||||
if (cancelled()) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
if (!requiresCanvasNodeHost(subpath, fileExtension)) {
|
||||
createWorkspaceLeaf();
|
||||
return "workspace-leaf";
|
||||
}
|
||||
|
||||
if (getHost()?.isInitialized()) {
|
||||
createCanvasNode();
|
||||
return "canvas-node";
|
||||
}
|
||||
|
||||
const ready = await awaitCanvasNodeHost(
|
||||
getHost,
|
||||
cancelled,
|
||||
timeoutMs,
|
||||
intervalMs,
|
||||
delay,
|
||||
);
|
||||
if (cancelled()) {
|
||||
return "none";
|
||||
}
|
||||
if (ready) {
|
||||
createCanvasNode();
|
||||
return "canvas-node";
|
||||
}
|
||||
createWorkspaceLeaf();
|
||||
return "workspace-leaf";
|
||||
}
|
||||
@@ -780,6 +780,23 @@ export async function exportImageToFile(
|
||||
return await createOrOverwriteFile(view.app, path, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an image imported into `excalidrawFile` can be saved the way Obsidian saves an image pasted or
|
||||
* dropped into a markdown note: through `app.saveAttachment`, which places it relative to the active file.
|
||||
* That holds only while the drawing is the active file, and only when no `onImageFilePathHook` chooses the
|
||||
* path instead.
|
||||
*/
|
||||
export function canSaveAsObsidianAttachment(
|
||||
app: App,
|
||||
excalidrawFile: TFile,
|
||||
view?: ExcalidrawView,
|
||||
): boolean {
|
||||
return (
|
||||
!view?.getHookServer()?.onImageFilePathHook &&
|
||||
app.workspace.getActiveFile()?.path === excalidrawFile.path
|
||||
);
|
||||
}
|
||||
|
||||
export async function importFileToVault(
|
||||
app: App,
|
||||
fname: string,
|
||||
@@ -787,6 +804,16 @@ export async function importFileToVault(
|
||||
excalidrawFile: TFile,
|
||||
view?: ExcalidrawView,
|
||||
): Promise<TFile> {
|
||||
if (
|
||||
typeof content !== "string" &&
|
||||
canSaveAsObsidianAttachment(app, excalidrawFile, view)
|
||||
) {
|
||||
const { basename, extension } = splitFolderAndFilename(fname);
|
||||
const data =
|
||||
content instanceof Blob ? await content.arrayBuffer() : content;
|
||||
return await app.saveAttachment(basename, extension, data);
|
||||
}
|
||||
|
||||
let hookFilepath: string;
|
||||
const ea = view?.getHookServer();
|
||||
if (ea?.onImageFilePathHook) {
|
||||
|
||||
+88
-16
@@ -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;
|
||||
@@ -6454,11 +6525,8 @@ export default class ExcalidrawView
|
||||
if (this.compatibilityMode) {
|
||||
return textElement.originalText ?? textElement.text;
|
||||
}
|
||||
const raw = this.excalidrawData.getRawText(textElement.id);
|
||||
if (!raw) {
|
||||
return textElement.rawText;
|
||||
}
|
||||
return raw;
|
||||
// Undo/redo restores the scene source before the Markdown cache is synchronized.
|
||||
return textElement.rawText ?? this.excalidrawData.getRawText(textElement.id);
|
||||
}
|
||||
|
||||
public onBeforeTextSubmit(
|
||||
@@ -6582,12 +6650,13 @@ export default class ExcalidrawView
|
||||
}
|
||||
|
||||
// 5. Check if the user made changes to the text, or
|
||||
// the text is missing from ExcalidrawData textElements cache (recently copy/pasted)
|
||||
// the ExcalidrawData cache differs from the submitted source (undo/redo or paste)
|
||||
const textChanged = nextOriginalText !== textElement.originalText;
|
||||
if (
|
||||
nextOriginalText !== textElement.originalText ||
|
||||
!this.excalidrawData.getRawText(textElement.id)
|
||||
textChanged ||
|
||||
nextOriginalText !== this.excalidrawData.getRawText(textElement.id)
|
||||
) {
|
||||
//the user made changes to the text or the text is missing from Excalidraw Data (recently copy/pasted)
|
||||
// Refresh stale source as well as new edits before returning parsed display text.
|
||||
//setTextElement will attempt a quick parse (without processing transclusions)
|
||||
this.setDirty();
|
||||
|
||||
@@ -6634,7 +6703,9 @@ export default class ExcalidrawView
|
||||
}
|
||||
this.setDirty();
|
||||
}
|
||||
api.history.clear();
|
||||
if (textChanged) {
|
||||
api.history.clear();
|
||||
}
|
||||
};
|
||||
|
||||
const [parseResultOriginal, link] = this.excalidrawData.setTextElement(
|
||||
@@ -6666,7 +6737,10 @@ export default class ExcalidrawView
|
||||
}
|
||||
return { updatedNextOriginalText: null, nextLink: textElement.link };
|
||||
} //There were no links to parse, raw text and parsed text are equivalent
|
||||
api.history.clear();
|
||||
// Updating only the cache after undo must not discard the redo stack.
|
||||
if (textChanged) {
|
||||
api.history.clear();
|
||||
}
|
||||
return { updatedNextOriginalText: parseResultOriginal, nextLink: link };
|
||||
}
|
||||
return { updatedNextOriginalText: null, nextLink: textElement.link };
|
||||
@@ -6725,9 +6799,7 @@ export default class ExcalidrawView
|
||||
window.setTimeout(() => this.removeLinkTooltip(), 500);
|
||||
|
||||
const nativeEvent = e?.detail?.nativeEvent;
|
||||
const ownerMouseEvent = (
|
||||
this.ownerWindow as (Window & { MouseEvent?: typeof MouseEvent }) | null
|
||||
)?.MouseEvent;
|
||||
const ownerMouseEvent = this.ownerWindow?.MouseEvent;
|
||||
const event = nativeEvent ?? new (ownerMouseEvent ?? MouseEvent)("click", {
|
||||
...emulateKeysForLinkClick("new-tab"),
|
||||
});
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
createLeaf,
|
||||
predictViewType,
|
||||
} from "src/utils/customEmbeddableUtils";
|
||||
import { mountEmbeddableHost } from "src/utils/embeddableMountPlan";
|
||||
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
import { EmbeddableLeafRef } from "src/types/excalidrawViewTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
@@ -859,20 +860,13 @@ function RenderObsidianView({
|
||||
};
|
||||
|
||||
patchMobileView(view);
|
||||
//if subpath is defined, create a canvas node else create a workspace leaf
|
||||
if (
|
||||
subpath &&
|
||||
view.canvasNodeFactory.isInitialized() &&
|
||||
file.extension.toLowerCase() === "md"
|
||||
) {
|
||||
createNode("markdown");
|
||||
} else {
|
||||
const mountWorkspaceLeaf = () => {
|
||||
const viewType = predictViewType(view.app, file);
|
||||
// markdown could still be a kanban board or other custom view on top of markdown, those need to be displayed in leaves
|
||||
if (
|
||||
viewType !== "markdown" &&
|
||||
CANVAS_VIEWTYPES.has(viewType) &&
|
||||
view.canvasNodeFactory.isInitialized()
|
||||
view.canvasNodeFactory?.isInitialized()
|
||||
) {
|
||||
createNode(viewType);
|
||||
if (viewType === "pdf") {
|
||||
@@ -900,7 +894,7 @@ function RenderObsidianView({
|
||||
}
|
||||
if (
|
||||
viewType === "markdown" &&
|
||||
view.canvasNodeFactory.isInitialized()
|
||||
view.canvasNodeFactory?.isInitialized()
|
||||
) {
|
||||
createNode("markdown");
|
||||
//I haven't found a better way of deciding if an .md file has its own view (e.g., kanban) or not
|
||||
@@ -931,9 +925,30 @@ function RenderObsidianView({
|
||||
}
|
||||
})();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let effectCancelled = false;
|
||||
|
||||
//if subpath is defined, create a canvas node else create a workspace leaf
|
||||
void mountEmbeddableHost({
|
||||
subpath,
|
||||
fileExtension: file.extension,
|
||||
getHost: () => view.canvasNodeFactory,
|
||||
isCancelled: () =>
|
||||
effectCancelled || !leafRef.current || !containerRef.current,
|
||||
createCanvasNode: () => createNode("markdown"),
|
||||
createWorkspaceLeaf: mountWorkspaceLeaf,
|
||||
}).catch((error: unknown) => {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.mount",
|
||||
fn: "mountEmbeddableHost",
|
||||
error,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
effectCancelled = true;
|
||||
|
||||
// disconnect observer if any
|
||||
pdfObserverRef.currentCleanup?.();
|
||||
pdfObserverRef.current?.disconnect();
|
||||
@@ -956,7 +971,7 @@ function RenderObsidianView({
|
||||
if (!leafRef.current) {
|
||||
return;
|
||||
}
|
||||
view.canvasNodeFactory.removeNode(leafRef.current.node, element.id);
|
||||
view.canvasNodeFactory?.removeNode(leafRef.current.node, element.id);
|
||||
leafRef.current.leaf?.detach();
|
||||
leafRef.current = null;
|
||||
}; //cleanup on unmount
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -72,6 +72,14 @@ export class CanvasNodeFactory {
|
||||
nodes = new Map<string, ObsidianCanvasNode>();
|
||||
initialized: boolean = false;
|
||||
public isInitialized = () => this.initialized;
|
||||
private settleInitialized: (initialized: boolean) => void;
|
||||
/**
|
||||
* Settles true once `initialize()` succeeded, false once it failed or the
|
||||
* factory was destroyed.
|
||||
*/
|
||||
public readonly whenInitialized = new Promise<boolean>((resolve) => {
|
||||
this.settleInitialized = resolve;
|
||||
});
|
||||
private observer: CustomMutationObserver | MutationObserver;
|
||||
private readonly pendingEditRequests = new WeakMap<
|
||||
ObsidianCanvasNode,
|
||||
@@ -81,30 +89,44 @@ export class CanvasNodeFactory {
|
||||
constructor(private view: ExcalidrawView) {}
|
||||
|
||||
public async initialize() {
|
||||
const app = this.view.app;
|
||||
const canvasPlugin = app.internalPlugins.plugins.canvas;
|
||||
try {
|
||||
if (!this.view) {
|
||||
return;
|
||||
}
|
||||
const app = this.view.app;
|
||||
const canvasPlugin = app.internalPlugins.plugins.canvas;
|
||||
|
||||
if (!canvasPlugin._loaded) {
|
||||
await canvasPlugin.load();
|
||||
if (!canvasPlugin._loaded) {
|
||||
await canvasPlugin.load();
|
||||
}
|
||||
// Closing or migrating the view can destroy this factory during loading.
|
||||
if (!this.view) {
|
||||
return;
|
||||
}
|
||||
const doc = this.view.ownerDocument;
|
||||
const rootSplit: WorkspaceSplit =
|
||||
new (WorkspaceSplit as ConstructableWorkspaceSplit)(
|
||||
app.workspace,
|
||||
"vertical",
|
||||
);
|
||||
rootSplit.getRoot = () =>
|
||||
app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
|
||||
rootSplit.getContainer = () => getContainerForDocument(doc);
|
||||
// `workspace.createLeafInParent()` activates its new leaf and schedules a workspace layout
|
||||
// update. That is observable even though this split is detached: on mobile it navigates away
|
||||
// from an open sidebar that hosts an embedded Excalidraw view. Construct and insert the
|
||||
// internal Canvas leaf directly so initialization has no workspace activation side effect.
|
||||
const LeafConstructor = WorkspaceLeaf as unknown as WorkspaceLeafConstructor;
|
||||
this.leaf = new LeafConstructor(app);
|
||||
(rootSplit as DetachedWorkspaceSplit).insertChild(0, this.leaf);
|
||||
this.canvas = canvasPlugin.views.canvas(this.leaf)
|
||||
.canvas as ObsidianCanvas;
|
||||
this.initialized = true;
|
||||
this.settleInitialized(true);
|
||||
} catch (error) {
|
||||
this.settleInitialized(false);
|
||||
throw error;
|
||||
}
|
||||
const doc = this.view.ownerDocument;
|
||||
const rootSplit: WorkspaceSplit =
|
||||
new (WorkspaceSplit as ConstructableWorkspaceSplit)(
|
||||
app.workspace,
|
||||
"vertical",
|
||||
);
|
||||
rootSplit.getRoot = () =>
|
||||
app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
|
||||
rootSplit.getContainer = () => getContainerForDocument(doc);
|
||||
// `workspace.createLeafInParent()` activates its new leaf and schedules a workspace layout
|
||||
// update. That is observable even though this split is detached: on mobile it navigates away
|
||||
// from an open sidebar that hosts an embedded Excalidraw view. Construct and insert the
|
||||
// internal Canvas leaf directly so initialization has no workspace activation side effect.
|
||||
const LeafConstructor = WorkspaceLeaf as unknown as WorkspaceLeafConstructor;
|
||||
this.leaf = new LeafConstructor(app);
|
||||
(rootSplit as DetachedWorkspaceSplit).insertChild(0, this.leaf);
|
||||
this.canvas = canvasPlugin.views.canvas(this.leaf).canvas as ObsidianCanvas;
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
public createFileNote(
|
||||
@@ -296,6 +318,7 @@ export class CanvasNodeFactory {
|
||||
destroy() {
|
||||
this.purgeNodes();
|
||||
this.initialized = false; //calling after purgeNodes becaues purge nodes checks for initialized
|
||||
this.settleInitialized(false); //release anyone still waiting to be able to create a node
|
||||
this.observer?.disconnect();
|
||||
this.view = null;
|
||||
this.canvas = null;
|
||||
|
||||
@@ -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