jsgotty 1.1.6 → 1.1.8

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.
package/gotty.js CHANGED
@@ -3323,3 +3323,8 @@ if (require.main === module) {
3323
3323
  process.exitCode = 1;
3324
3324
  });
3325
3325
  }
3326
+
3327
+ // The guard above is inlined to false once this file is bundled, because
3328
+ // the bundle entry point is single-exe/entry.mjs rather than this file.
3329
+ // Export the starter so that entry point can call it.
3330
+ module.exports.bootstrap = bootstrap;
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "jsgotty",
3
- "version": "1.1.6",
3
+ "version": "1.1.8",
4
4
  "description": "Share your terminal as a web application: A JavaScript rewrite of GoTTY",
5
5
  "bin": {
6
6
  "jsgotty": "./gotty.js"
7
7
  },
8
8
  "type": "commonjs",
9
+ "assets": [
10
+ "static",
11
+ "README.md",
12
+ "README.en.md"
13
+ ],
9
14
  "dependencies": {
10
15
  "node-addon-api": "^7.1.1",
11
16
  "ws": "^8.18.3"
@@ -1,80 +1,382 @@
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
+ # 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
+ Bundles a project's runtime assets into one `bun build --compile` binary, so
4
+ the executable carries its own `static/`, templates, documentation and so on.
8
5
 
9
- ```shell
10
- bun build --compile --bytecode --minify ./entry.mjs --outfile=binname
11
- ```
6
+ Assets are declared once, in `package.json`:
12
7
 
13
- - You'll get a binname executable
8
+ ```json
9
+ {
10
+ "assets": ["static", "README.md", "README.en.md"]
11
+ }
12
+ ```
13
+
14
+ Paths are relative to the project root. Folders are packed recursively; only
15
+ regular files are stored, so symlinks and empty folders leave no trace.
16
+
17
+ ## The two back ends
18
+
19
+ The default packs everything into a gzipped `assets.tar` that is embedded as a
20
+ single file and unpacked into memory at startup. Setting `ASSETS_BUNFS=1` at
21
+ build time switches to `bun build --compile --asset`, which stores the files
22
+ individually inside the binary's virtual filesystem instead.
23
+
24
+ Reading code never sees the difference — `assetsHelper` answers the same keys
25
+ either way. The trade is binary size against startup cost:
26
+
27
+ | | tar (default) | `ASSETS_BUNFS=1` |
28
+ | --- | --- | --- |
29
+ | Stored as | one gzipped archive | individual files, uncompressed |
30
+ | Size, for jsgotty's 3.45 MB of assets | **0.70 MB** | 3.45 MB |
31
+ | Work before `main` runs | decode the archive, copy every file into memory | **none** |
32
+ | Startup cost, same assets | ~16 ms | **0 ms** |
33
+ | Resident memory | whole payload, always | only what is read |
34
+ | Maturity | in use | experimental |
35
+
36
+ Text compresses well, so the tar usually wins on size by a wide margin — for
37
+ jsgotty most of the payload is `static/`, whose JavaScript and CSS shrink to a
38
+ fifth. What it costs is paid on every run, whether or not the program touches a
39
+ single asset. Reach for `ASSETS_BUNFS=1` when that startup work, or holding the
40
+ whole payload in memory, matters more than the extra megabytes on disk.
41
+
42
+ ## Adopting it in another project
43
+
44
+ Copy `single-exe/` to the project root. Nothing inside it hard-codes its own
45
+ name or depth, so it can be renamed or moved — but the importing code has to
46
+ follow, so staying at the root is the easy path. Three edits point it at the
47
+ project around it.
48
+
49
+ 1. **`assetsPacker.js`, the first two lines.** They are the only place the
50
+ asset root is written down, and a static import specifier cannot be
51
+ computed, so both must be literal:
52
+
53
+ ```js
54
+ import pkg from "../package.json" with { type: "json" };
55
+ export const ASSETS_ROOT = "..";
56
+ ```
57
+
58
+ 2. **`entry.mjs`, the import of the program.** It names what to start, and
59
+ entry.mjs is the compiled entry point in both back ends:
60
+
61
+ ```js
62
+ await import("../src/index.js");
63
+ ```
64
+
65
+ **Keep the `await`.** It reads like a formality — nothing here needs the
66
+ module object — but together with the `await globalThis.assetsLoaderPromise`
67
+ line above it, it is the only top-level `await` the compiled program writes
68
+ anywhere, and `--bytecode` reads exactly that to decide the program starts
69
+ asynchronously. Turn both into `.then(…)` and the build produces an
70
+ executable that exits 0 without running a line.
71
+ [Why](#the-await-in-entrymjs-is-load-bearing) explains the trap.
72
+
73
+ 3. **`package.json`.** Add the `assets` array shown above.
74
+
75
+ Everything else — `compiled.js`, `assetsHelper.js`, `assetsLoader.mjs` — is
76
+ project independent, with one exception: `buildHtmlBundleImageMap` defaults its
77
+ attribute name to jsmdcui's `data-mdcui-src`, so pass your own.
78
+
79
+ Node's own entry path must not import `assetsLoader.mjs` or `entry.mjs`; those
80
+ are Bun only. `assetsHelper.js` and `compiled.js` run under Node 20.11+.
81
+
82
+ ## Reading assets
83
+
84
+ Import from `assetsHelper.js`. Keys are the same package-relative paths that
85
+ appear in `package.json`.
86
+
87
+ | Function | Returns |
88
+ | --- | --- |
89
+ | `readInternalAssetText(path)` | string, or `null` when not embedded |
90
+ | `readInternalAssetBytes(path)` | `Uint8Array`, or `null` |
91
+ | `readAssetText(path)` | string, falling back to the file on disk |
92
+ | `readAssetBytes(path)` | `Uint8Array`, same fallback |
93
+ | `hasInternalAssets()` | whether this package has anything embedded |
94
+ | `listInternalAssetPaths(prefix?)` | every embedded path under `prefix` |
95
+ | `listInternalAssetDirs(prefix?)` | the immediate child names under `prefix` |
96
+ | `assetPath(...parts)` | joins parts into a key |
97
+ | `SELF` | this package's namespace, `assets/<name>@<version>` |
98
+
99
+ The read functions are synchronous for embedded assets on both back ends.
100
+ `readAssetText` / `readAssetBytes` are async only because of the disk
101
+ fallback, which is what makes the same code work from a source checkout.
102
+
103
+ **Only the read functions fall back to disk.** The listing functions report
104
+ what is embedded and nothing else, so from a source checkout they return an
105
+ empty array. Branch on `hasInternalAssets()` and read the directory yourself:
106
+
107
+ ```js
108
+ import { readdirSync } from "node:fs";
109
+ import { join } from "node:path";
110
+ import { readAssetText, hasInternalAssets, listInternalAssetDirs } from "../single-exe/assetsHelper.js";
111
+ import { REPO_ROOT } from "../single-exe/compiled.js";
112
+
113
+ // Embedded or on disk, this one already works either way.
114
+ const index = await readAssetText("static/index.html");
115
+
116
+ // Listing does not, so pick the source.
117
+ const staticDirs = hasInternalAssets()
118
+ ? listInternalAssetDirs("static")
119
+ : readdirSync(join(REPO_ROOT, "static"));
120
+ ```
121
+
122
+ ## Building
123
+
124
+ `compiled.js` exports the build entry points. Wire `buildEarlyExit` into the
125
+ CLI and it handles `--build-exe` and `--build-for <target>`:
126
+
127
+ ```js
128
+ import { buildEarlyExit, IS_COMPILED, REPO_ROOT } from "./single-exe/compiled.js";
129
+
130
+ await buildEarlyExit(process.argv, "myapp");
131
+ ```
132
+
133
+ `REPO_ROOT` is the project root in a checkout and the executable's own folder
134
+ once compiled, which is where `--assets-extract` writes. `IS_COMPILED` tells
135
+ the two apart.
136
+
137
+ ### Chaining file/folder assets across dependencies
138
+
139
+ A build first bundles once to write a metafile, then treats every
140
+ `assetsPacker.js` appearing in its `inputs` as a participant. Each package
141
+ vendors its own `single-exe/`, and its `assetsHelper` imports its
142
+ `assetsPacker`, so a packer lands in that graph exactly when the package is
143
+ reachable from the entry point. There is no registration step, and anything
144
+ tree-shaken away brings nothing with it.
145
+
146
+ The packers then run one after another, each adding its files under its own
147
+ `assets/<name>@<version>/` namespace — appending into the shared `assets.tar`
148
+ by default, or copying into the shared `build/assets` tree under
149
+ `ASSETS_BUNFS=1`. Only once every packer has finished does the real compile
150
+ run, so the archive is complete and, by default, compressed by then.
151
+
152
+ That namespace is why `ASSETS_BUNFS=1` stages every package into one fixed
153
+ `build/assets`. `--asset` keeps only the **basename** of the path it is given
154
+ and preserves everything below it, so the folder's own name becomes the root
155
+ inside the binary:
156
+
157
+ ```
158
+ --asset ./build/assets with build/assets/jsgotty@1.1.6/static/index.html
159
+ -> assets/jsgotty@1.1.6/static/index.html
160
+ ```
161
+
162
+ Pass `./build/assets/jsgotty@1.1.6` instead and `build/assets/` is gone: the
163
+ files land at `jsgotty@1.1.6/...` and every package gets its own root. One
164
+ folder named `assets`, everyone copying into it, is what makes the keys come
165
+ out the same as the ones the tar back end writes.
166
+
167
+ `assetsPacker.js` also runs standalone; `--help` documents its flags.
168
+
169
+ ## Why the loader hands over a Promise
170
+
171
+ `entry.mjs` imports `assetsLoader.mjs`, awaits `globalThis.assetsLoaderPromise`,
172
+ and only then imports the main program. The indirection is deliberate: the
173
+ loader carries a Bun-only import,
14
174
 
15
- # Single Executable Intro
175
+ ```js
176
+ import assets from "./assets.tar" with { type: "file" };
177
+ ```
178
+
179
+ and if the main program imported the loader, that dependency would land in its
180
+ module graph. Node could then no longer load the program at all — not even to
181
+ fall back to reading the assets from disk.
182
+
183
+ Keeping the loader behind `entry.mjs` means the main program never mentions it,
184
+ so Node 20.11+ runs the same file directly against on-disk assets while Bun
185
+ runs it through the bootstrap. The Promise is that boundary, not a workaround
186
+ for missing top-level await.
187
+
188
+ `ASSETS_BUNFS=1` sidesteps the question: there is no tar to load, so the build
189
+ writes `.bunfs-entry.mjs` next to `entry.mjs` — the same file with the loader
190
+ import removed — compiles that, and deletes it afterwards. A copy rather than a
191
+ stub, because entry.mjs may do more than import the program: a CommonJS main
192
+ that starts itself from `require.main === module` needs the exported starter
193
+ called instead, and that call has to survive. jsgotty is exactly that case; see
194
+ [below](#the-entry-import-calls-an-exported-starter).
195
+
196
+ ## The `await` in entry.mjs is load-bearing
16
197
 
17
- This folder contains the Bun single-exe bootstrap used by the project.
198
+ `--bytecode` decides whether a program starts asynchronously by looking for a
199
+ top-level `await` **written in some file's own source**. The bundler moves a
200
+ module into a lazy init function whenever something dynamically imports it, and
201
+ a module moved that way takes its top-level `await` with it — what stays behind
202
+ is an `await init_x()` the bundler wrote itself, which does not count. If no
203
+ file wrote one, the executable is evaluated on the synchronous path, its
204
+ suspended startup is dropped, and it exits 0 having run nothing. No error, at
205
+ any `--minify` setting, however small the program.
18
206
 
19
- ## Entry Flow
207
+ `entry.mjs` is immune because it writes its own, and one is enough. Every other
208
+ `await` in the graph — all of `assetsLoader.mjs`'s, for one — sits inside a
209
+ function and cannot help. It is also why bunfs builds compile a copy of that
210
+ file rather than handing the main program to `bun build` directly: a main
211
+ program that reaches top-level await only through its imports writes none of
212
+ its own.
20
213
 
21
- - `entry.mjs` imports `assetsLoader.mjs` first
22
- - `assetsLoader.mjs` loads `assets.tar` with `Bun.Archive` and mounts it as `globalThis.internalAssets`
23
- - `assetsLoaderPromise` is exposed on `globalThis`
24
- - The main program waits for `assetsLoaderPromise` if it exists
214
+ Upstream: `src/bundler/linker_context/postProcessJSChunk.rs` skips exactly the
215
+ modules the bundler moved, still true on oven-sh/bun `main` at 8eb5b6e2b5
216
+ (2026-08-22). Until that changes, treat entry.mjs's `await`s as API.
25
217
 
26
- That keeps the main program bootable even if asset loading reports errors.
218
+ ## Environment variables
27
219
 
28
- ## Assets Loading
220
+ | Variable | When | Effect |
221
+ | --- | --- | --- |
222
+ | `ASSETS_BUNFS=1` | build | use `--asset` instead of the tar |
223
+ | `ASSETS_NO_GZIP=1` | build | leave `assets.tar` uncompressed |
224
+ | `ASSETS_DEBUG=1` | run | print how long unpacking took |
29
225
 
30
- - Bundled assets are loaded sequentially with `await file.bytes()`
31
- - Load failures are collected and printed to `stderr`
32
- - Asset loading never rejects the bootstrap promise
33
- - When loading succeeds, the archive is available through `globalThis.internalAssets`
226
+ ## Runtime flags
34
227
 
35
- ## CLI Flags
228
+ | Flag | Effect |
229
+ | --- | --- |
230
+ | `--assets-list` | print every embedded path and exit |
231
+ | `--assets-extract` | write the assets next to the executable and exit |
232
+ | `--assets-external` | ignore embedded assets and read from disk |
36
233
 
37
- - `--assets-list`
38
- - Lists all entries inside bundled `assets.tar`
39
- - Exits early before the main program starts
234
+ These are handled by `assetsLoader.mjs`, so they exist in tar builds only.
40
235
 
41
- - `--assets-extract`
42
- - Extracts bundled assets to the same directory as the executable
43
- - Exits early before the main program starts
236
+ ## Advanced usage
44
237
 
45
- - `--assets-external`
46
- - Skips loading bundled assets into `globalThis.internalAssets`
47
- - Forces the main program and runtime helpers to use the external file tree
48
- - Keeps the bootstrap alive while leaving `internalAssets` falsy
238
+ ### Forwarding arguments to `bun build`
49
239
 
50
- ## Adapting this folder
240
+ Anything after `--build-exe`, or after the target given to `--build-for`, is
241
+ passed straight through to `bun build`:
51
242
 
52
- This single-exe folder is intended for reuse by other projects. Usually you
53
- only need to edit these project-specific files first:
243
+ ```shell
244
+ bun ./gotty.js --build-exe --sourcemap
245
+ bun ./gotty.js --build-for bun-linux-x64 --sourcemap
246
+ ```
247
+
248
+ Order matters. The flags have to come after the build switch, or Bun consumes
249
+ them before the program ever starts:
250
+
251
+ ```shell
252
+ # Wrong: Bun parses this define before any of your code runs
253
+ bun --define MY_APP=../app.md ./gotty.js --build-exe
54
254
 
55
- - `entry.mjs`
56
- - `packAssets.sh`
255
+ # Right
256
+ bun ./gotty.js --build-exe --define MY_APP=../app.md
257
+ ```
258
+
259
+ ### `--define` with a string value
57
260
 
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.
261
+ **Bun expects `--define` values to be JSON literals, so a string has to arrive
262
+ already quoted.** A bare path is read as an identifier and the build fails or
263
+ inlines something unintended. Quoting it through a shell is awkward, so
264
+ `compiled.js` exports a helper that does it:
61
265
 
62
266
  ```js
63
- const compiledHelper = await import("./single-exe/compiled.js").catch(() => null);
64
- await compiledHelper?.buildEarlyExit?.(process.argv, "my-bin");
267
+ import { buildEarlyExit, stringifyNonPrimitiveDefineValues } from "./single-exe/compiled.js";
268
+
269
+ stringifyNonPrimitiveDefineValues(process.argv, "MY_APP");
270
+ await buildEarlyExit(process.argv, "my-bin");
65
271
  ```
66
272
 
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`.
273
+ Call it before `buildEarlyExit`, once per define name you want treated as a
274
+ string. It rewrites the value in place:
70
275
 
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`.
276
+ ```js
277
+ ["--define", "MY_APP=../app.md"] // what the user typed
278
+ ["--define", 'MY_APP="../app.md"'] // what Bun receives
279
+ ```
280
+
281
+ `--define=MY_APP=../app.md` works the same way. Numbers, booleans, `null` and
282
+ `undefined` are left alone, so only genuine strings get quoted.
283
+
284
+ ### Images from an imported HTML bundle
285
+
286
+ A compiled binary exposes an imported HTML entry as a `homepage` object:
287
+ `homepage.index` is the compiled HTML and `homepage.files` lists the
288
+ content-hashed assets by their path inside the binary. `assetsHelper` can map
289
+ the *original* image references back to those paths, without copying any image
290
+ bytes into memory.
291
+
292
+ Bun rewrites `src` during the build, so keep the original reference in a custom
293
+ attribute of your own choosing:
294
+
295
+ ```html
296
+ <!-- source -->
297
+ <img src="./images/photo.jpg" data-original-image="./images/photo.jpg">
298
+
299
+ <!-- compiled -->
300
+ <img src="/photo-abcd1234.jpg" data-original-image="./images/photo.jpg">
301
+ ```
302
+
303
+ Then build the map once, in a compiled binary only:
76
304
 
77
305
  ```js
78
- const compiledHelper = await import("./single-exe/compiled.js").catch(() => null);
79
- const repoRoot = compiledHelper?.REPO_ROOT
306
+ import { buildHtmlBundleImageMap, canonicalHtmlBundleImageHref } from "../single-exe/assetsHelper.js";
307
+ import { IS_COMPILED } from "../single-exe/compiled.js";
308
+
309
+ const images = IS_COMPILED
310
+ ? await buildHtmlBundleImageMap(homepage, "data-original-image")
311
+ : null;
312
+
313
+ const path = images?.get(canonicalHtmlBundleImageHref(originalHref));
314
+ const bytes = path ? await Bun.file(path).bytes() : null;
315
+ ```
316
+
317
+ `buildHtmlBundleImageMap` returns a `Map` from canonical original reference to
318
+ the path inside the binary; it decodes HTML entities and percent encoding so a
319
+ reference written either way still matches. Reading stays lazy — the bytes are
320
+ only touched when you use the returned path.
321
+
322
+ Lower level, if you already hold a rewritten public path such as
323
+ `/photo-abcd1234.jpg`: `findHtmlBundleAsset(homepage, publicPath, options)`
324
+ finds its `homepage.files` entry, `findHtmlBundleImageAsset()` restricts that
325
+ to `image/*`, and `htmlBundleImageAssetPath()` returns just the path.
326
+
327
+ Never hard-code `/$bunfs/root/` or `B:/~BUN/`; always use the path that
328
+ `homepage.files` reports.
329
+
330
+ ## jsgotty specifics
331
+
332
+ The rest of this file is generic. These names belong to jsgotty itself and are
333
+ not reserved by the bootstrap — an adopting project picks its own.
334
+
335
+ Building is optional; running `bun gotty.js` from a checkout, as the root
336
+ `README.md` describes, remains the usual way to run jsgotty.
337
+
338
+ ```shell
339
+ bun ./gotty.js --build-exe
340
+ bun ./gotty.js --build-for bun-linux-x64
341
+ ```
342
+
343
+ Both produce `jsgt`: `gotty.js` calls `buildEarlyExit(process.argv, "jsgt")`
344
+ from `bootstrap()`, before any CLI parsing, so the build switches exit before
345
+ a server is ever started. Neither works from an already compiled binary.
346
+
347
+ The three packed entries — `static`, `README.md`, `README.en.md` — are what the
348
+ HTTP server hands out: `index.html`, `manifest.json`, `help.md`, the frontend
349
+ JavaScript and CSS, and the two READMEs behind the help pages.
350
+
351
+ ### The entry import calls an exported starter
352
+
353
+ `gotty.js` is CommonJS and starts itself from `require.main === module`. With
354
+ `entry.mjs` as the bundle's entry point that guard is inlined to `false`, so
355
+ the import cannot rely on it and calls the export instead:
356
+
357
+ ```js
358
+ const { bootstrap } = await import("../gotty.js");
359
+
360
+ await bootstrap();
361
+ ```
362
+
363
+ Both back ends go through it: `ASSETS_BUNFS=1` compiles a copy of `entry.mjs`,
364
+ so `gotty.js` is never the entry point and the guard stays `false` in either
365
+ mode. Handing `gotty.js` to `bun build` directly instead would compile it as
366
+ the entry, Bun would rewrite the guard to `import.meta.main` — true — and it
367
+ would start itself; that path is not taken, and `bootstrap` is what starts the
368
+ program in both builds.
369
+
370
+ ### `packAssets.sh`
371
+
372
+ The original implementation, kept as a reference: a hand-written tar of the
373
+ three asset entries, from before `assetsPacker.js` and its `package.json`
374
+ declaration existed. `buildExecutable()` in `compiled.js` is the matching
375
+ build path and still runs it, but `buildExe` now points at `buildExeAssets`,
376
+ so nothing in the current flow calls either. It is the shortest way to see
377
+ what the packer produces, and it still packs an `assets.tar` by hand:
378
+
379
+ ```shell
380
+ bun ./single-exe/packAssets.sh
381
+ bun build --compile --bytecode --minify ./single-exe/entry.mjs --outfile=jsgt
80
382
  ```