jsmdcui 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +189 -19
  3. package/cdp-maze.js +141 -0
  4. package/demos/maze.md +149 -0
  5. package/demos/todo-zh.md +98 -0
  6. package/demos/todo.md +98 -0
  7. package/edit +9 -0
  8. package/llm-maze.txt +94 -0
  9. package/package.json +1 -1
  10. package/runmd.mjs +44 -2
  11. package/runtime/help/cdp.md +5 -0
  12. package/runtime/help/help.md +189 -19
  13. package/runtime/jsplugins/cdp/cdp-server.js +26 -2
  14. package/runtime/jsplugins/cdp/cdp.js +60 -51
  15. package/runtime/jsplugins/chapter/chapter.js +6 -3
  16. package/runtime/jsplugins/example/example.js +12 -7
  17. package/runtime/syntax/markdown.yaml +1 -0
  18. package/single-exe/README.md +223 -45
  19. package/single-exe/compiled.js +6 -3
  20. package/single-exe/entry.mjs +4 -3
  21. package/single-exe/packAssets.sh +1 -1
  22. package/src/cui/fence-events.mjs +106 -0
  23. package/src/cui/id-collision.mjs +10 -28
  24. package/src/cui/kitty-debug.mjs +1 -1
  25. package/src/cui/kitty-images.mjs +11 -1
  26. package/src/cui/rpc.mjs +6 -3
  27. package/src/cui/server.mjs +13 -2
  28. package/src/index.js +425 -72
  29. package/src/lua/engine.js +1 -4
  30. package/src/platform/terminal.js +5 -0
  31. package/src/plugins/js-bridge.js +157 -8
  32. package/tests/compiled-runtime.test.js +8 -0
  33. package/tests/demo.test.js +40 -0
  34. package/tests/fence-events.test.js +405 -0
  35. package/tests/id-collision.test.js +11 -0
  36. package/tests/js-plugin-prompts.test.js +46 -0
  37. package/tests/key-event.md +10 -0
  38. package/tests/kitty-demo.md +1 -1
  39. package/tests/kitty-images.test.js +22 -0
  40. package/tests/platform-terminal.test.js +8 -0
  41. package/tests/textarea.md +8 -0
  42. package/tests/wui.test.js +16 -1
  43. package/demo.resized.jpg +0 -0
  44. package/src/runtime/compiled.js +0 -25
@@ -1,27 +1,231 @@
1
- # This is completely optional
2
- - I still recommend using the methods in the root README.md
3
- - Bun's Android build is currently not supported
1
+ # Bun Single-File Executable Bootstrap
4
2
 
5
- # Usage
6
- - First run `bun ./packAssets.sh` to bundle the assets into `assets.tar`
7
- - Then run the build script like this
3
+ Build a Bun application and its runtime assets into one executable while
4
+ keeping the regular main module free of Bun-specific asset imports.
8
5
 
9
- ```shell
10
- bun build --compile --bytecode --minify ./entry.mjs --outfile=binname
11
- ```
6
+ You can copy and adapt this build setup for your own project by changing its
7
+ main-module path and asset list as described below.
12
8
 
13
- - You'll get a binname executable
9
+ - Bundle an asset tree alongside the application code in one executable.
10
+ - Keep the regular main module available to the Node.js ESM execution path.
11
+ - Read embedded resources first with an optional external-file fallback.
12
+ - List, extract, or bypass embedded assets with built-in CLI flags.
13
+ - Build for the current platform or pass a Bun cross-compilation target.
14
14
 
15
- # Single Executable Intro
15
+ > This workflow is optional; the standard methods in the root README remain
16
+ > available. Bun's Android build is currently not supported.
16
17
 
17
- This folder contains the Bun single-exe bootstrap used by the project.
18
+ ## Quick start for jsmdcui
19
+
20
+ From the repository root, build for the current platform:
21
+
22
+ ```shell
23
+ bun ./src/index.js --build-exe
24
+ ./mdcui --version
25
+ ```
26
+
27
+ `--build-exe` runs `packAssets.sh` automatically and writes the `mdcui`
28
+ executable to the current directory. To pass a Bun compilation target, use:
29
+
30
+ ```shell
31
+ bun ./src/index.js --build-for <target>
32
+ ```
33
+
34
+ To perform the same steps manually, run these commands from `single-exe/`:
35
+
36
+ ```shell
37
+ bun ./packAssets.sh
38
+ bun build --format=esm --compile --minify --bytecode ./entry.mjs --outfile=mdcui
39
+ ```
40
+
41
+ ## Adapting this folder to another project
42
+
43
+ This folder is a reusable starting point, not a drop-in package. The current
44
+ `entry.mjs` and `packAssets.sh` contain jsmdcui paths, so another project must
45
+ complete the following integration steps.
46
+
47
+ The adopting project needs Bun for packing and compiling, a `tar` command for
48
+ `packAssets.sh`, and an ES-module setup. Keep `"type": "module"` in
49
+ `package.json`, or rename the copied `.js` modules to `.mjs` and update their
50
+ imports. The supported uncompiled Node path requires Node.js 20.11 or newer
51
+ because `compiled.js` uses `import.meta.dirname`.
52
+
53
+ `assetsHelper.js` and `compiled.js` are Node-compatible under those conditions.
54
+ `assetsLoader.mjs` and `entry.mjs` are Bun-only and must not be imported by the
55
+ regular Node entry path.
56
+
57
+ ### 1. Copy the bootstrap directory
58
+
59
+ Copy the entire `single-exe/` directory to the root of the other project and
60
+ keep its name and relative position unless you also update the paths in
61
+ `compiled.js` and `packAssets.sh`. A typical layout is:
62
+
63
+ ```text
64
+ my-project/
65
+ ├── single-exe/
66
+ │ ├── assetsHelper.js
67
+ │ ├── assetsLoader.mjs
68
+ │ ├── compiled.js
69
+ │ ├── entry.mjs
70
+ │ └── packAssets.sh
71
+ └── src/
72
+ └── index.js
73
+ ```
74
+
75
+ `assets.tar` is generated by `packAssets.sh`; it does not need to exist before
76
+ the first packing step.
77
+
78
+ ### 2. Point `entry.mjs` at the main program
79
+
80
+ Keep the asset loader as the first import and change the path passed to the
81
+ final `await import()` so it points to the other project's real entry module:
82
+
83
+ ```js
84
+ #!/usr/bin/env bun
85
+
86
+ import "./assetsLoader.mjs";
87
+ await globalThis.assetsLoaderPromise;
88
+ await import("../src/index.js");
89
+ ```
90
+
91
+ > **Important:** Keep the final import dynamic. Do not replace it with a static
92
+ > `import "../src/index.js"`, because static dependencies are evaluated before
93
+ > the asset Promise is awaited.
94
+
95
+ Only the Bun single-file executable build should use this bootstrap entry.
96
+ Continue to run the regular main module directly when using Node:
97
+
98
+ ```shell
99
+ node ./src/index.js
100
+ ```
101
+
102
+ ### 3. Choose which files to embed
103
+
104
+ Edit the resource list in `packAssets.sh`; the script runs `tar` for you. It
105
+ changes to the project root, writes `single-exe/assets.tar`, and packs every
106
+ listed runtime resource required by the compiled program. Paths stored in the
107
+ archive become the lookup keys used by `assetsHelper.js`; use keys such as
108
+ `public/app.css`, without a leading `./`. The normal `--build-exe` and
109
+ `--build-for` flows invoke this script automatically, so you do not need to run
110
+ `tar` yourself.
111
+
112
+ For example:
113
+
114
+ ```sh
115
+ #!/bin/sh
116
+
117
+ script_dir=$(dirname "$0")
118
+ cd "$script_dir/.." || exit 1
119
+
120
+ tar -cvf single-exe/assets.tar public templates README.md
121
+ ```
122
+
123
+ Do not retain jsmdcui's `demos`, `runtime`, `src/cui`, or `testapp.md` entries
124
+ unless the adopting project actually contains and needs them.
125
+
126
+ ### 4. Read embedded assets with an external fallback
127
+
128
+ Import the Node-compatible helpers from `assetsHelper.js`. They return `null`
129
+ when the embedded store is unavailable or a path is not present:
130
+
131
+ ```js
132
+ import { readFile } from "node:fs/promises";
133
+ import { resolve } from "node:path";
134
+ import { readInternalAssetText } from "../single-exe/assetsHelper.js";
135
+ import { REPO_ROOT } from "../single-exe/compiled.js";
136
+
137
+ async function readResourceText(path) {
138
+ return readInternalAssetText(path) ??
139
+ await readFile(resolve(REPO_ROOT, path), "utf8");
140
+ }
141
+ ```
142
+
143
+ In the source tree, `REPO_ROOT` is the project root. In a compiled executable,
144
+ it is the executable's directory, which is also where `--assets-extract`
145
+ places the external resource tree. Apply the same embedded-first fallback to
146
+ every file that must work in both modes. Use `readInternalAssetBytes()` when
147
+ a resource should be returned as bytes instead of decoded text.
148
+ Use `listInternalAssetPaths()` to list embedded asset paths and
149
+ `listInternalAssetDirs()` to list embedded directories.
150
+
151
+ ### 5. Add the optional build commands to the regular CLI
152
+
153
+ Before normal argument parsing, call `buildEarlyExit` from the regular main
154
+ module:
155
+
156
+ ```js
157
+ const compiledHelper = await import("../single-exe/compiled.js").catch(() => null);
158
+ await compiledHelper?.buildEarlyExit?.(process.argv, "my-bin");
159
+ ```
160
+
161
+ The second argument is the output filename; it defaults to `single.exe` when
162
+ omitted. This enables:
163
+
164
+ ```shell
165
+ bun ./src/index.js --build-exe
166
+ bun ./src/index.js --build-for <target>
167
+ ```
168
+
169
+ Both commands run `packAssets.sh` before `bun build`. The second form passes
170
+ `<target>` through as Bun's `--target=<target>` value.
171
+
172
+ Alternatively, build manually from inside `single-exe/`:
173
+
174
+ ```shell
175
+ bun ./packAssets.sh
176
+ bun build --format=esm --compile --minify --bytecode ./entry.mjs --outfile=my-bin
177
+ ```
178
+
179
+ ### 6. Verify both execution paths
180
+
181
+ Verify the compiled asset archive and then run the program normally:
182
+
183
+ ```shell
184
+ ./my-bin --assets-list
185
+ ./my-bin
186
+ ```
187
+
188
+ Also run the uncompiled main module with Node.js 20.11 or newer to verify that
189
+ all required files have a working external fallback:
190
+
191
+ ```shell
192
+ node ./src/index.js
193
+ ```
194
+
195
+ Use `./my-bin --assets-extract` to write the packed tree beside the executable.
196
+ After extraction, `./my-bin --assets-external` skips the embedded store and is
197
+ useful for testing the external-resource path.
198
+
199
+ ### Why `assetsLoaderPromise` is used
200
+
201
+ A more tightly coupled ESM design could export the assets with top-level
202
+ `await`, then make the main module import `assetsLoader.mjs` directly. This
203
+ project deliberately does not do that because `assetsLoader.mjs` contains
204
+ Bun's compiled-file import:
205
+
206
+ ```js
207
+ import assets from "./assets.tar" with { type: "file" };
208
+ ```
209
+
210
+ If the regular main module imported `assetsLoader.mjs`, that Bun-specific
211
+ `type: "file"` dependency would enter the main module graph. Node would then be
212
+ unable to load the program before it could select an external-file fallback.
213
+
214
+ Instead, only Bun's `entry.mjs` imports the Bun-specific loader, awaits its
215
+ Promise, and then dynamically imports the regular main module. The main module
216
+ does not import the loader, inspect the Promise, or contain Bun bootstrap code.
217
+ Under the supported Node.js 20.11+ ESM path, Node runs that clean main module
218
+ directly with external files. The Promise is therefore an intentional
219
+ Node-compatibility boundary inside the Bun-only bootstrap, not a failure to use
220
+ a more modern dependency or top-level-`await` design.
18
221
 
19
222
  ## Entry Flow
20
223
 
21
224
  - `entry.mjs` imports `assetsLoader.mjs` first
22
225
  - `assetsLoader.mjs` loads `assets.tar` with `Bun.Archive` and mounts it as `globalThis.internalAssets`
23
226
  - `assetsLoaderPromise` is exposed on `globalThis`
24
- - The main program waits for `assetsLoaderPromise` if it exists
227
+ - `entry.mjs` awaits `assetsLoaderPromise`
228
+ - `entry.mjs` dynamically imports the main program after the assets are ready
25
229
 
26
230
  That keeps the main program bootable even if asset loading reports errors.
27
231
 
@@ -32,6 +236,12 @@ That keeps the main program bootable even if asset loading reports errors.
32
236
  - Asset loading never rejects the bootstrap promise
33
237
  - When loading succeeds, the archive is available through `globalThis.internalAssets`
34
238
 
239
+ This loader is not zero-copy: it materializes every bundled file in memory and
240
+ keeps the resulting bytes in `globalThis.internalAssets`. Large asset archives
241
+ can therefore increase startup and ongoing RAM usage. For workloads where that
242
+ matters, I also wrote an experimental Linux-only zero-copy hack:
243
+ [bun-assets-zerocopy](https://github.com/jjtseng93/bun-assets-zerocopy).
244
+
35
245
  ## CLI Flags
36
246
 
37
247
  - `--assets-list`
@@ -46,35 +256,3 @@ That keeps the main program bootable even if asset loading reports errors.
46
256
  - Skips loading bundled assets into `globalThis.internalAssets`
47
257
  - Forces the main program and runtime helpers to use the external file tree
48
258
  - Keeps the bootstrap alive while leaving `internalAssets` falsy
49
-
50
- ## Adapting this folder
51
-
52
- This single-exe folder is intended for reuse by other projects. Usually you
53
- only need to edit these project-specific files first:
54
-
55
- - `entry.mjs`
56
- - `packAssets.sh`
57
-
58
- Then the main program can import `buildEarlyExit` from `compiled.js` and call
59
- it before normal CLI parsing. `--build-exe` and `--build-for <target>` will run
60
- `packAssets.sh` first, so `assets.tar` is generated as part of the build flow.
61
-
62
- ```js
63
- const compiledHelper = await import("./single-exe/compiled.js").catch(() => null);
64
- await compiledHelper?.buildEarlyExit?.(process.argv, "my-bin");
65
- ```
66
-
67
- - `--build-exe` builds with no Bun target.
68
- - `--build-for <target>` passes `<target>` to `bun build --target=<target>`.
69
- - The second argument is the output filename. If omitted, it defaults to `single.exe`.
70
-
71
- The main program should also switch its repo/resource root when running as a
72
- compiled binary. Use `IS_COMPILED` and `REPO_ROOT` from
73
- `compiled.js`; when compiled, treat the executable directory as the repo root
74
- used for external fallback files such as `static/`, `README.md`, or other files
75
- packed by `packAssets.sh`.
76
-
77
- ```js
78
- const compiledHelper = await import("./single-exe/compiled.js").catch(() => null);
79
- const repoRoot = compiledHelper?.REPO_ROOT
80
- ```
@@ -12,9 +12,12 @@ const SINGLE_EXE_DIR = resolve(REPO_ROOT, "single-exe");
12
12
  const SINGLE_EXE_ENTRY = resolve(SINGLE_EXE_DIR, "entry.mjs");
13
13
 
14
14
 
15
- export function isCompiledBinary() {
16
- const argv = process.argv
17
- return Boolean(argv?.[1]?.startsWith?.("/$bunfs/"));
15
+ export function isCompiledBinary(argv = process.argv) {
16
+ const entry = argv?.[1];
17
+ return Boolean(
18
+ entry?.startsWith?.("/$bunfs/") ||
19
+ entry?.startsWith?.("B:/~BUN")
20
+ );
18
21
  }
19
22
 
20
23
  export function getExeDirname() {
@@ -3,7 +3,8 @@
3
3
  // 1. Injects assets to global.internalAssets
4
4
  // as { "./path/in/tar":file.bytes() }
5
5
  // 2. Sets global.assetsLoaderPromise
6
- import "./assetsLoader.mjs"
7
-
8
- import "../src/index.js"
6
+ // 3. Starts the main program only after the assets are ready
7
+ import "./assetsLoader.mjs";
9
8
 
9
+ await globalThis.assetsLoaderPromise;
10
+ await import("../src/index.js");
@@ -4,4 +4,4 @@ sd=$(dirname "$0")
4
4
 
5
5
  cd "$sd"/..
6
6
 
7
- tar -cvf single-exe/assets.tar demos runtime README.md CHANGELOG.md src/cui/server.mjs src/cui/rpc.mjs testapp.md
7
+ tar -cvf single-exe/assets.tar demos runtime README.md CHANGELOG.md cdp-maze.js src/cui/server.mjs src/cui/rpc.mjs testapp.md
@@ -0,0 +1,106 @@
1
+ const IDENTITY_RE = /^([A-Za-z_][\w:-]*)(?:#([A-Za-z_][\w:-]*))?((?:\.[A-Za-z_][\w:-]*)*)$/;
2
+
3
+ function parseIdentity(value) {
4
+ const match = String(value ?? "").match(IDENTITY_RE);
5
+ if (!match) return null;
6
+ return {
7
+ tag: match[1],
8
+ id: match[2] || null,
9
+ classes: match[3] ? match[3].slice(1).split(".") : [],
10
+ };
11
+ }
12
+
13
+ function parseEventAttributes(text) {
14
+ const events = new Map();
15
+ let offset = 0;
16
+ while (offset < text.length) {
17
+ while (/\s/.test(text[offset] ?? "")) offset++;
18
+ if (offset >= text.length || text[offset] !== "@") break;
19
+ offset++;
20
+ const nameStart = offset;
21
+ while (/[A-Za-z0-9_.:-]/.test(text[offset] ?? "")) offset++;
22
+ const name = text.slice(nameStart, offset);
23
+ while (/\s/.test(text[offset] ?? "")) offset++;
24
+ if (!name || text[offset] !== "=") break;
25
+ offset++;
26
+ while (/\s/.test(text[offset] ?? "")) offset++;
27
+ if (text[offset] !== '"') break;
28
+ offset++;
29
+
30
+ let code = "";
31
+ let closed = false;
32
+ while (offset < text.length) {
33
+ const ch = text[offset++];
34
+ if (ch === '"') {
35
+ closed = true;
36
+ break;
37
+ }
38
+ if (ch === "\\" && offset < text.length) {
39
+ const next = text[offset++];
40
+ code += next === '"' || next === "\\" ? next : `\\${next}`;
41
+ } else {
42
+ code += ch;
43
+ }
44
+ }
45
+ if (!closed) break;
46
+ const [eventName, ...modifiers] = name.split(".");
47
+ if (eventName === "keydown")
48
+ events.set(eventName, { code, modifiers: [...new Set(modifiers.filter(Boolean))] });
49
+ }
50
+ return events;
51
+ }
52
+
53
+ export function parseFenceDeclarations(markdown) {
54
+ const lines = String(markdown ?? "").split(/\r?\n/);
55
+ const declarations = [];
56
+ let fence = null;
57
+
58
+ for (let index = 0; index < lines.length; index++) {
59
+ const line = lines[index];
60
+ if (fence) {
61
+ const closing = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/);
62
+ if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length)
63
+ fence = null;
64
+ continue;
65
+ }
66
+
67
+ const opening = line.match(/^ {0,3}(`{3,}|~{3,})([^]*)$/);
68
+ if (!opening) continue;
69
+ fence = { marker: opening[1][0], length: opening[1].length };
70
+ const info = String(opening[2] ?? "").trim();
71
+ const firstSpace = info.search(/\s/);
72
+ const identityText = firstSpace < 0 ? info : info.slice(0, firstSpace);
73
+ const attributesText = firstSpace < 0 ? "" : info.slice(firstSpace);
74
+ const identity = parseIdentity(identityText);
75
+ if (!identity) continue;
76
+ declarations.push({
77
+ ...identity,
78
+ identity: identityText,
79
+ events: parseEventAttributes(attributesText),
80
+ line: index + 1,
81
+ source: line.trim(),
82
+ });
83
+ }
84
+
85
+ return declarations;
86
+ }
87
+
88
+ export function fenceEventMap(markdown) {
89
+ const result = new Map();
90
+ for (const declaration of parseFenceDeclarations(markdown)) {
91
+ if (
92
+ !["text", "textarea"].includes(declaration.tag)
93
+ || !declaration.id
94
+ || declaration.events.size === 0
95
+ || result.has(declaration.id)
96
+ ) continue;
97
+ result.set(declaration.id, declaration);
98
+ }
99
+ return result;
100
+ }
101
+
102
+ export function inlineFenceEventCode(handler) {
103
+ if (!handler) return "";
104
+ const prefix = handler.modifiers.includes("prevent") ? "event.preventDefault();" : "";
105
+ return prefix + handler.code;
106
+ }
@@ -1,3 +1,5 @@
1
+ import { parseFenceDeclarations } from "./fence-events.mjs";
2
+
1
3
  function markdownHeadingDeclarations(markdown) {
2
4
  const lines = String(markdown).split(/\r?\n/);
3
5
  const declarations = [];
@@ -51,34 +53,14 @@ function markdownHeadingDeclarations(markdown) {
51
53
  }
52
54
 
53
55
  function fencedBlockDeclarations(markdown) {
54
- const lines = String(markdown).split(/\r?\n/);
55
- const declarations = [];
56
- let fence = null;
57
-
58
- for (let index = 0; index < lines.length; index++) {
59
- const line = lines[index];
60
- if (!fence) {
61
- const opening = line.match(/^ {0,3}(`{3,}|~{3,})\s*(\S+)?\s*$/);
62
- if (!opening) continue;
63
- fence = { marker: opening[1][0], length: opening[1].length };
64
- const identity = String(opening[2] ?? "").match(/^([A-Za-z_][\w:-]*)(?:#([A-Za-z_][\w:-]*))?(?:\.[A-Za-z_][\w:-]*)*$/);
65
- if (identity?.[2]) {
66
- declarations.push({
67
- id: identity[2],
68
- kind: `${identity[1]} fenced block`,
69
- line: index + 1,
70
- source: line.trim(),
71
- });
72
- }
73
- continue;
74
- }
75
-
76
- const closing = line.match(/^ {0,3}(`{3,}|~{3,})\s*$/);
77
- if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length)
78
- fence = null;
79
- }
80
-
81
- return declarations;
56
+ return parseFenceDeclarations(markdown)
57
+ .filter((declaration) => declaration.id)
58
+ .map((declaration) => ({
59
+ id: declaration.id,
60
+ kind: `${declaration.tag} fenced block`,
61
+ line: declaration.line,
62
+ source: declaration.source,
63
+ }));
82
64
  }
83
65
 
84
66
  export function checkMarkdownIdCollisions(markdown) {
@@ -1,7 +1,7 @@
1
1
  import { appendFileSync, writeFileSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
 
4
- export const KITTY_DEBUG_LOG = resolve(import.meta.dir, "../..", "kitty-placement.log");
4
+ export const KITTY_DEBUG_LOG = resolve(import.meta.dirname, "../..", "kitty-placement.log");
5
5
  export const KITTY_DEBUG_ENABLED = /^(1|true|yes|on)$/i.test(
6
6
  String(process.env.JSMDCUI_KITTY_DEBUG ?? ""),
7
7
  );
@@ -117,6 +117,10 @@ function stableImageId(pathname, line, data) {
117
117
  return (hash >>> 0) % 2147483646 + 1;
118
118
  }
119
119
 
120
+ async function convertToKittyPng(data) {
121
+ return Buffer.from(await new Bun.Image(data).png().toBuffer());
122
+ }
123
+
120
124
  export function fitKittyImageToWidth(image, maxCols) {
121
125
  const originalCols = Math.max(1, Math.trunc(Number(image?.cols) || 1));
122
126
  const originalRows = Math.max(1, Math.trunc(Number(image?.rows) || 1));
@@ -151,8 +155,14 @@ export async function prepareKittyImages(ansiText, markdownPath, terminalCols =
151
155
  if (!(await file.exists())) throw new Error("missing image");
152
156
  data = Buffer.from(await file.arrayBuffer());
153
157
  }
154
- const size = imageSize(data);
158
+ let size = imageSize(data);
155
159
  if (!size?.width || !size?.height) throw new Error("unsupported image");
160
+ if (options.kittyMode === "compat" && size.mime !== "image/png") {
161
+ data = await convertToKittyPng(data);
162
+ size = imageSize(data);
163
+ if (size?.mime !== "image/png" || !size.width || !size.height)
164
+ throw new Error("PNG conversion failed");
165
+ }
156
166
  const estimatedCols = Math.max(1, Math.round(size.width / 8));
157
167
  const cols = Math.min(maxCols, estimatedCols);
158
168
  const rows = Math.max(1, Math.round((cols * size.height) / size.width / 2));
package/src/cui/rpc.mjs CHANGED
@@ -451,15 +451,18 @@ function safeFrontValue(value)
451
451
  };
452
452
  }
453
453
 
454
- export async function evalFront(mod, text)
454
+ export async function evalFront(mod, text, scope = {})
455
455
  {
456
456
  try{
457
457
 
458
458
  text = text.replace(/^javascript:/, "");
459
459
 
460
- const entries = Object.entries(mod).filter(([name]) => name !== "$");
460
+ const entryMap = new Map(Object.entries(mod).filter(([name]) => name !== "$"));
461
461
  if (typeof globalThis.$ === "function")
462
- entries.push(["$", globalThis.$]);
462
+ entryMap.set("$", globalThis.$);
463
+ for (const [name, value] of Object.entries(scope))
464
+ entryMap.set(name, value);
465
+ const entries = [...entryMap];
463
466
  const names = entries.map(([name]) => name);
464
467
  const values = entries.map(([, value]) => safeFrontValue(value));
465
468
 
@@ -50,7 +50,7 @@ export function main()
50
50
 
51
51
  const basePath = "/" + crypto.randomUUID()
52
52
  const pathname = basePath + "/"
53
- const server = Bun.serve({
53
+ const serverOptions = {
54
54
  port: Number(process.env.PORT || 3000),
55
55
  development: {
56
56
  hmr: true,
@@ -101,7 +101,18 @@ const server = Bun.serve({
101
101
  fetch() {
102
102
  return new Response("Not Found", { status: 404 });
103
103
  },
104
- });
104
+ };
105
+
106
+ let server;
107
+ try {
108
+ server = Bun.serve(serverOptions);
109
+ } catch (error) {
110
+ const addressInUse = error?.code === "EADDRINUSE"
111
+ || error?.cause?.code === "EADDRINUSE"
112
+ || /EADDRINUSE|address already in use/i.test(String(error?.message || error));
113
+ if (serverOptions.port !== 3000 || !addressInUse) throw error;
114
+ server = Bun.serve({ ...serverOptions, port: 0 });
115
+ }
105
116
 
106
117
  console.error(mda("- Bun RPC server listening on"));
107
118
  console.log(`http://localhost:${server.port}${pathname}`);