Compare commits

...
Author SHA1 Message Date
zsviczian 078f48e28a Support Obsidian CLI testing on Windows and macOS 2026-10-11 13:22:07 +02:00
zsviczian f30b4c5d3d updated messages 2026-10-03 13:16:44 +02:00
zsviczian 593ad99bab Merge PR #2959 with mount lifecycle fixes and 2.29.0 release note 2026-10-03 13:10:05 +02:00
zsviczian f591b7558f Merge pull request #2964 from mnaoumov/save-pasted-images-via-saveAttachment
Save pasted and dropped images through internal `app.saveAttachment()`
2026-09-30 22:54:46 +02:00
Michael Naumov 9cf33817b7 Save pasted and dropped images through app.saveAttachment
When the drawing is the active file and no onImageFilePathHook is set, an
imported image is saved the way Obsidian saves one pasted or dropped into a
markdown note, so attachment-management plugins apply their naming and
location rules to it. A generated paste name follows Obsidian's own
"Pasted image YYYYMMDDHHmmss" in that case. Every other caller keeps the
existing path.
2026-09-29 14:31:31 -06:00
zsviczian 128a9ef47b 2.28.1 2026-09-29 20:52:23 +02:00
zsviczian 96bd2212c2 2.28.0 2026-09-29 19:30:31 +02:00
zsviczian 3d8f312add Obsidian CLI testing framework 2026-09-29 17:26:28 +02:00
zsviczian bd40308a83 2.28.0-rc.0 2026-09-28 23:20:00 +02:00
zsviczian 3e13b61c6d lint fix 2026-09-28 22:00:31 +02:00
askalf 921f679f0b keep the mount plan checks runnable against the factory on master
master now builds the factory's Canvas leaf directly and inserts it into the
detached split, instead of calling workspace.createLeafInParent(). The check
script's stand-in WorkspaceSplit gains insertChild, and the fake workspace
drops the createLeafInParent it no longer needs. All 21 mount plan checks and
the call site checks pass on the merged tree.
2026-09-28 19:47:24 +00:00
askalf c3955cad5f Merge remote-tracking branch 'upstream/master' into fix/back-of-note-embeddable-canvas-node-race
# Conflicts:
#	src/view/managers/CanvasNodeFactory.ts
2026-09-28 19:42:42 +00:00
zsviczian 5da2b452f1 Merge pull request #2962 from zsviczian/toggleViewMode
feat: add ExcalidrawAutomate toggleViewMode API
2026-09-28 19:51:31 +02:00
askalf ef9b7cd014 Drop explanatory comments from the embeddable mount change 2026-09-25 18:37:22 +00:00
askalf 0d5a809372 simplify mount check wording 2026-09-25 17:32:29 +00:00
askalf 496d451914 Simplify embeddable mount check wording 2026-09-25 16:55:21 +00:00
askalf f25a7ba08b simplify embeddable mount checks 2026-09-25 16:18:24 +00:00
askalf eb284a1c85 bound the injected poll delay so a wait that never ends fails the block 2026-09-25 05:26:48 +00:00
askalf 6e3c8d7468 fold the factory lifecycle checks into the mount plan script
Events that used to be sequenced with timers now land on a named poll of the
wait, through the injected delay, so each block asserts the poll it ended on
rather than an elapsed time. The one block whose subject is elapsed time, the
slow real factory, still runs against the clock.
2026-09-25 05:23:09 +00:00
askalf 41e578320c describe the mount host selection as it stands 2026-09-25 05:23:09 +00:00
askalf a951d371cb pin the three inputs the mount dispatch forwards to the helper 2026-09-25 03:43:27 +00:00
askalf d31ac3b62b require the mount effect to reach the factory only through the dispatch
The wiring checks pinned where the dispatch sits and how it cancels, but
not what else the effect does beside it. A readiness read in the effect's
own body (an early return onto the workspace leaf, or a ternary choosing
it) restores the whole-file leaf on a slow start while every existing
check stays green, and so does a direct createNode() or
mountWorkspaceLeaf() call next to the dispatch, which mounts a second
host. Reject both: the effect may not name canvasNodeFactory outside the
closures it hands the helper, and may not call either mount path itself.
2026-09-24 14:48:53 +00:00
askalf f96cbc53ff keep the clock in the two cap blocks whose subject is elapsed time
Counting reads made the cap blocks stop discriminating: the cap is a
wall-clock quantity, so readiness has to land after real elapsed time for
its expiry to be the thing under test. Both are green at base again without
them.
2026-09-22 12:09:04 +00:00
askalf dbc9476202 fold the mount checks into the repository's check-script idiom
The mount-plan checks had grown a case per scenario with narrated assertion
labels, so the three scripts read as a patch history rather than as a
description of the behaviour. Table the cases that share a shape, name each
block for what it pins, and run them through the same per-block runner the
lifecycle checks already use, so an arm that reintroduces one defect reports
every block it breaks instead of stopping at the first.

Sequencing by wall clock goes with it: the hosts now ready, give up or
cancel on a counted read, which is what the poll loop actually observes.
Only the two blocks whose subject is elapsed time still use timers. Drop the
helper JSDoc, the issue numbers the squashed commit will carry anyway, and
the comments arguing the implementation is correct rather than recording the
contract.
2026-09-22 12:05:10 +00:00
askalf 8e08316ba6 scope the cancellation-flag check to the mount effect's own body
The declaration check counted `let effectCancelled = false;` in the whole
file, so moving the sole declaration to module or component scope still
satisfied it while leaving a flag shared by every invocation: one
embeddable's cleanup then cancels the mount that replaced it, which is the
regression the flag exists to prevent. Parse the effect instead and require
the declaration's enclosing function to be the effect itself.

Reading the syntax tree also replaces the text heuristics for the other
wiring rows: the dispatch must be a statement of the effect's body and the
whole of its expression, which rejects an `if` gate and an `&&` operand
directly rather than by inspecting the preceding line.
2026-09-22 11:56:58 +00:00
askalf 1eb1aa9ff0 pin the canvas node factory's lifecycle settle sites
The mount wait's consumer was covered through the injected host interface, but the three sites that settle whenInitialized -- initialize() succeeding, its catch, destroy() -- were only read. Aliasing the two modules the factory imports but does not exercise lets it run under node, so the producer side and the real factory through the real dispatch are executed too.
2026-09-21 03:14:27 +00:00
askalf a18fd81133 pin the lifecycle wait and the per-dispatch cancellation latch
Seven discriminating checks and three controls for the lifecycle wait and
the superseded-mount latch, plus call-site assertions requiring the
dispatch to consult this invocation's own cancellation flag and the
cleanup to raise it before its early returns.
2026-09-21 01:48:41 +00:00
askalf d38510fad7 wait for the canvas node factory's lifecycle instead of a fixed timeout
A subpath embed fell back to a whole-file workspace leaf whenever the
factory took longer than the two second cap to initialize. Startup can
legitimately outlast it: layout ready polls up to 50 x 50 ms before
initialize() is called, and initialize() then awaits the core canvas
plugin's load, so the cap cannot tell a slow start from one that will
never finish. CanvasNodeFactory now exposes whenInitialized, settled on
every terminal path, and the wait uses it; the cap remains only for a
host that reports no lifecycle.

Cancellation also latches per dispatch, so a mount superseded by a link
change cannot mount over its replacement once the shared refs are
repopulated.
2026-09-21 01:42:31 +00:00
askalf b48112e4ca pin the mount dispatch against a readiness gate and cover zero/nullish waits
The call-site check accepted a dispatch re-gated on
view.canvasNodeFactory.isInitialized(), which skips the wait inside
mountEmbeddableHost and restores the whole-file workspace leaf while both
check scripts stayed green. Require the dispatch to be reached
unconditionally.

Also pin the boundaries the existing rows only reached by argument: a zero
timeout, an undefined subpath, a null extension, a factory that never
appears or is torn down mid-wait, the synchrony of both fast paths, a
teardown landing as the factory readies, and concurrent embeddables.
2026-09-20 13:34:16 +00:00
askalf 5c5e351258 pin the embeddable mount dispatch at its call site
The mount-plan checks exercise the helper only, so removing the dispatch
from the mount effect and keeping the helper leaves them green while the
back-of-the-note embeddable regresses to a whole-file workspace leaf.
Check the wiring against the source of the effect, which cannot be
imported here because it pulls in the types-only obsidian package.
2026-09-20 13:09:37 +00:00
askalf 9e69f245b5 move the mount-plan check to the repository's script convention
The first version of the regression test used node:test inside src/, which
the repository's own lint rejects there: src/ is runtime code that must work
on mobile and in popout windows, so node built-ins and bare timers are
banned. Follow scripts/check-*.mjs instead - jiti-imported TypeScript with
node:assert, outside the linted source tree - and inject the wait primitive
so the module can still default to Obsidian's sleep global.
2026-09-20 11:30:58 +00:00
askalf ac359575f6 fix back-of-the-note embeddable initializing as the full drawing
A subpath embeddable can mount before CanvasNodeFactory has finished its
asynchronous initialization on layout ready. The mount check treated an
uninitialized factory the same as an absent subpath and fell through to a
workspace leaf, which renders the whole file - for a hybrid drawing, the
entire drawing - and cannot be edited. Wait for the factory instead, with a
timeout so the leaf fallback still applies when it never initializes.

[#2931](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2931)
2026-09-20 11:19:18 +00:00
25 changed files with 2041 additions and 206 deletions

No files matched your search

+16 -4
View File
@@ -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.
@@ -310,11 +312,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 +507,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.
+9 -1
View File
@@ -14,7 +14,7 @@ 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
@@ -45,6 +45,14 @@ 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).
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)
+169
View File
@@ -0,0 +1,169 @@
# 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, and cleanup. Inspect both `status` and
`cleanup`; keep reports outside the checkout and review local paths before sharing.
## Troubleshooting and further coverage
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.
This 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.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.28.0-beta.4",
"version": "2.28.1",
"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
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.27.3",
"version": "2.28.1",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+4 -4
View File
@@ -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.140",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5255,9 +5255,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.140",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.140.tgz",
"integrity": "sha512-DXdxSFVkyVXYBDIlq63IfoegKRZYp71ECSPErSZASxcssKyKOcbiDjI/EjO4nnsvhampnr8mrlLPBjsQyoRTKQ==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+6 -3
View File
@@ -9,7 +9,10 @@
],
"scripts": {
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
"build": "cross-env NODE_ENV=production 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",
"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 +37,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.140",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -111,4 +114,4 @@
"node": ">=22.0.0",
"npm": ">=10.0.0"
}
}
}
+1 -57
View File
@@ -1,5 +1,4 @@
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';
@@ -33,59 +32,7 @@ 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.
@@ -354,9 +301,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 }),
@@ -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");
+730
View File
@@ -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;
+60
View File
@@ -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/);
});
+183
View File
@@ -0,0 +1,183 @@
/** 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)})){app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path)?.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);leaf?.detach();c.state="cleaning";Promise.resolve(app.vault.delete(file)).then(()=>{c.state="clean"},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() }) {
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.scenarios.push({ id: "drawing-main-window", status: "passed", assertions: ["Excalidraw API ready", "wrapper mounted", "owner document matches", "main application document"] });
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;
}
+118
View File
@@ -0,0 +1,118 @@
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")) { 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 report = await runObsidianSmoke({ ...input, runCli, runBuild: () => {}, unique: () => "1", wait: () => {} });
assert.equal(report.status, "passed", report.error);
assert.equal(report.cleanup, "passed");
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");
});
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");
});
+88
View File
@@ -0,0 +1,88 @@
/** 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";
const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
const pluginOnly = process.argv.includes("--plugin-only");
if (process.argv.slice(2).some(arg => arg !== "--plugin-only")) throw new Error("Only --plugin-only is supported");
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, 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,
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;
+14 -64
View File
@@ -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 });
@@ -92,22 +42,22 @@ const defineUrl = (url: string, purpose: string) => ({ url, purpose });
export const URL_REGISTRY = {
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(
+28 -32
View File
@@ -17,56 +17,52 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.29.0": `
## Fixed
- Back-of-the-note embeds now wait for initialization so they display the linked Markdown section instead of the whole drawing. 🙏[askalf](${URLs.GITHUB_COM}/askalf) [#2931](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2931)
`,
"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
- 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.
- 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. 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)
- 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": `
+8 -2
View File
@@ -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":
+11
View File
@@ -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;
+175
View File
@@ -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";
}
+27
View File
@@ -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) {
+1 -3
View File
@@ -6725,9 +6725,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"),
});
+27 -12
View File
@@ -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
+45 -22
View File
@@ -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;