typenative 0.4.1 → 0.5.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 (151) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +62 -22
  3. package/ROUND2-HANDOFF.md +200 -0
  4. package/bin/cli.js +1 -0
  5. package/bin/index.js +13 -2
  6. package/bin/main.js +1 -0
  7. package/bin/node/assert.js +2 -2
  8. package/bin/node/async_hooks.js +1 -1
  9. package/bin/node/buffer.js +16 -5
  10. package/bin/node/child_process.js +7 -7
  11. package/bin/node/cluster.js +3 -3
  12. package/bin/node/crypto_keys.js +21 -21
  13. package/bin/node/dgram.js +1 -1
  14. package/bin/node/diagnostics_channel.js +3 -3
  15. package/bin/node/dns.js +2 -2
  16. package/bin/node/events.js +3 -3
  17. package/bin/node/fetch.js +2 -2
  18. package/bin/node/fs.js +3 -3
  19. package/bin/node/fs_watch.js +5 -5
  20. package/bin/node/http.js +3 -3
  21. package/bin/node/http2.js +3 -3
  22. package/bin/node/net.js +8 -8
  23. package/bin/node/path.js +17 -3
  24. package/bin/node/process.js +34 -11
  25. package/bin/node/readline.js +1 -1
  26. package/bin/node/registry.js +4 -1
  27. package/bin/node/sqlite.js +6 -6
  28. package/bin/node/stream.js +81 -15
  29. package/bin/node/stream_web.js +10 -10
  30. package/bin/node/system_extra.js +3 -3
  31. package/bin/node/test.js +674 -366
  32. package/bin/node/test_coverage.js +187 -0
  33. package/bin/node/test_report.js +1392 -0
  34. package/bin/node/test_run.js +575 -0
  35. package/bin/node/timers.js +4 -4
  36. package/bin/node/tls.js +5 -5
  37. package/bin/node/util.js +31 -7
  38. package/bin/node/util_extra.js +7 -7
  39. package/bin/node/webview.js +654 -0
  40. package/bin/node/worker_threads.js +1 -1
  41. package/bin/node/zlib.js +3 -3
  42. package/bin/parse-node.js +4 -0
  43. package/bin/transpiler.js +10390 -1178
  44. package/bin/version.js +1 -1
  45. package/conformance.md +468 -340
  46. package/examples/README.md +47 -10
  47. package/examples/desktop-notes/README.md +108 -0
  48. package/examples/desktop-notes/bench.mjs +125 -0
  49. package/examples/desktop-notes/main.ts +131 -0
  50. package/examples/desktop-notes/package-lock.json +726 -0
  51. package/examples/desktop-notes/package.json +9 -0
  52. package/examples/desktop-notes/ui.ts +176 -0
  53. package/examples/dupe-finder/README.md +76 -0
  54. package/examples/dupe-finder/bench.mjs +120 -0
  55. package/examples/dupe-finder/main.ts +87 -0
  56. package/examples/mandelbrot-png/README.md +65 -0
  57. package/examples/mandelbrot-png/bench.mjs +95 -0
  58. package/examples/mandelbrot-png/main.ts +98 -0
  59. package/examples/mandelbrot-png/preview.png +0 -0
  60. package/examples/marked-cli/README.md +159 -0
  61. package/examples/marked-cli/bench.mjs +178 -0
  62. package/examples/marked-cli/main.ts +292 -0
  63. package/examples/marked-cli/parity.mjs +185 -0
  64. package/examples/marked-cli/vendor/marked/LICENSE +44 -0
  65. package/examples/marked-cli/vendor/marked/VENDOR.md +26 -0
  66. package/examples/todo-cli/README.md +69 -0
  67. package/examples/todo-cli/bench.mjs +89 -0
  68. package/examples/todo-cli/main.ts +92 -0
  69. package/examples/yaml-cli/README.md +136 -0
  70. package/examples/yaml-cli/bench.mjs +265 -0
  71. package/examples/yaml-cli/main.ts +29 -0
  72. package/examples/yaml-cli/parity.mjs +156 -0
  73. package/examples/yaml-cli/vendor/yaml/LICENSE +13 -0
  74. package/examples/yaml-cli/vendor/yaml/VENDOR.md +25 -0
  75. package/govendor/github.com/jchv/go-webview2/LICENSE +22 -0
  76. package/govendor/github.com/jchv/go-webview2/README.md +21 -0
  77. package/govendor/github.com/jchv/go-webview2/common.go +84 -0
  78. package/govendor/github.com/jchv/go-webview2/go.mod +3 -0
  79. package/govendor/github.com/jchv/go-webview2/internal/w32/w32.go +194 -0
  80. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_386.go +14 -0
  81. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_64bit.go +15 -0
  82. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_COLOR.go +8 -0
  83. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.go +9 -0
  84. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_KEY_EVENT_KIND.go +10 -0
  85. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_MOVE_FOCUS_REASON.go +9 -0
  86. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_PHYSICAL_KEY_STATUS.go +10 -0
  87. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_WEB_RESOURCE_CONTEXT.go +23 -0
  88. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventArgs.go +78 -0
  89. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventHandler.go +52 -0
  90. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller.go +132 -0
  91. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller2.go +74 -0
  92. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2CreateCoreWebView2ControllerCompletedHandler.go +48 -0
  93. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventArgs.go +17 -0
  94. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventHandler.go +48 -0
  95. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Settings.go +270 -0
  96. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequest.go +43 -0
  97. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventArgs.go +51 -0
  98. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventHandler.go +48 -0
  99. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceResponse.go +21 -0
  100. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_2.go +21 -0
  101. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_3.go +60 -0
  102. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebViewSettings.go +396 -0
  103. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium.go +361 -0
  104. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_386.go +24 -0
  105. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_amd64.go +22 -0
  106. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_arm64.go +26 -0
  107. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc.go +13 -0
  108. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go17.go +51 -0
  109. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go18.go +16 -0
  110. package/govendor/github.com/jchv/go-webview2/pkg/edge/corewebview2.go +411 -0
  111. package/govendor/github.com/jchv/go-webview2/pkg/edge/guid.go +223 -0
  112. package/govendor/github.com/jchv/go-webview2/webview.go +482 -0
  113. package/govendor/github.com/jchv/go-webview2/webviewloader/README.md +3 -0
  114. package/govendor/github.com/jchv/go-webview2/webviewloader/module.go +153 -0
  115. package/govendor/github.com/jchv/go-webview2/webviewloader/module_386.go +6 -0
  116. package/govendor/github.com/jchv/go-webview2/webviewloader/module_amd64.go +6 -0
  117. package/govendor/github.com/jchv/go-webview2/webviewloader/module_arm64.go +6 -0
  118. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/arm64/WebView2Loader.dll +0 -0
  119. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x64/WebView2Loader.dll +0 -0
  120. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x86/WebView2Loader.dll +0 -0
  121. package/govendor/github.com/jchv/go-winloader/LICENSE.md +7 -0
  122. package/govendor/github.com/jchv/go-winloader/README.md +124 -0
  123. package/govendor/github.com/jchv/go-winloader/common.go +11 -0
  124. package/govendor/github.com/jchv/go-winloader/go.mod +3 -0
  125. package/govendor/github.com/jchv/go-winloader/internal/loader/loader.go +25 -0
  126. package/govendor/github.com/jchv/go-winloader/internal/loader/machine.go +53 -0
  127. package/govendor/github.com/jchv/go-winloader/internal/memloader/cache.go +42 -0
  128. package/govendor/github.com/jchv/go-winloader/internal/memloader/loader.go +253 -0
  129. package/govendor/github.com/jchv/go-winloader/internal/pe/export.go +76 -0
  130. package/govendor/github.com/jchv/go-winloader/internal/pe/format.go +522 -0
  131. package/govendor/github.com/jchv/go-winloader/internal/pe/import.go +106 -0
  132. package/govendor/github.com/jchv/go-winloader/internal/pe/module.go +91 -0
  133. package/govendor/github.com/jchv/go-winloader/internal/pe/reloc.go +177 -0
  134. package/govendor/github.com/jchv/go-winloader/internal/pe/util.go +40 -0
  135. package/govendor/github.com/jchv/go-winloader/internal/vmem/common.go +55 -0
  136. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_other.go +71 -0
  137. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_windows.go +179 -0
  138. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_other.go +17 -0
  139. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_windows.go +73 -0
  140. package/govendor/github.com/jchv/go-winloader/internal/winloader/loader_windows.go +64 -0
  141. package/govendor/github.com/jchv/go-winloader/internal/winloader/machine_windows.go +32 -0
  142. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_386.go +9 -0
  143. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_amd64.go +9 -0
  144. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_arm64.go +9 -0
  145. package/govendor/github.com/jchv/go-winloader/loader_other.go +24 -0
  146. package/govendor/github.com/jchv/go-winloader/loader_windows.go +33 -0
  147. package/govendor/manifest.txt +3 -1
  148. package/package.json +1 -1
  149. package/tsparser/main.go +4 -0
  150. package/types/typenative-npm.d.ts +190 -2
  151. package/types/typenative.d.ts +98 -31
@@ -4,14 +4,31 @@ Small, complete TypeNative programs, each runnable as-is under **both**
4
4
  Node.js and a compiled TypeNative binary, with a `bench.mjs` that measures
5
5
  Node vs TypeNative on the same workload and a README documenting the results.
6
6
 
7
- | Example | Demonstrates | Headline result (this machine*) |
8
- |----------------------------------------------|--------------------------------------------------------------------------|--------------------------------------------------|
9
- | [hello-world](hello-world/) | `console.log`, `process.argv`, template literals | **7.0x faster startup** (14.7 ms vs 103.5 ms) |
10
- | [fibonacci](fibonacci/) | Recursion, `perf_hooks` timing, CPU-bound number crunching | **1.9x faster compute** (50.2 ms vs 94.8 ms) |
11
- | [json-server](json-server/) | `node:http` web server with GET + POST JSON routes, zero dependencies | **1.3x higher HTTP throughput** (17.8k vs 13.4k GET req/s) |
7
+ | Example | Demonstrates | Headline result (this machine*) |
8
+ |-----------------------------------|----------------------------------------------------------------------------|--------------------------------------------------------------|
9
+ | [hello-world](hello-world/) | `console.log`, `process.argv`, template literals | **7.0x faster startup** (14.7 ms vs 103.5 ms) |
10
+ | [fibonacci](fibonacci/) | Recursion, `perf_hooks` timing, CPU-bound number crunching | **1.9x faster compute** (50.2 ms vs 94.8 ms) |
11
+ | [json-server](json-server/) | `node:http` web server with GET + POST JSON routes, zero dependencies | **1.3x higher HTTP throughput** (17.8k vs 13.4k GET req/s) |
12
+ | [todo-cli](todo-cli/) | A to-do CLI persisting to a JSON file, run many times a day | **6.8x faster per command** (16.3 ms vs 111.4 ms) |
13
+ | [dupe-finder](dupe-finder/) | Recursive directory walk, SHA-256 hashing, JSON report written to disk | **1.6x faster scan** (412 ms vs 674 ms, 2,000 files) |
14
+ | [mandelbrot-png](mandelbrot-png/) | Fractal render + hand-written PNG encoder on `node:zlib`, no image library | **1.2x faster**, steadier (597 ms vs 744 ms) |
15
+ | [desktop-notes](desktop-notes/) | Notes app in a native webview window, UI compiled into one binary | **4.8x faster launch, 4.7x less memory** (15 vs 73 MiB) |
16
+ | [yaml-cli](yaml-cli/) | The `yaml` package's own CLI from its unmodified source, 100% Node parity | **27x faster per call** (9 vs 250 ms); 3.6x slower on 10 MB† |
17
+ | [marked-cli](marked-cli/) | The `marked` markdown CLI from its unmodified source, 100% Node parity | **7.6x faster per call** (19 vs 148 ms); 5.2x slower on 10 MB‡ |
12
18
 
13
19
  \* Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0, TypeNative
14
- 0.4.0. See each example's README for full methodology and numbers.
20
+ 0.4.0 (hello-world, fibonacci, json-server), 0.4.2 (desktop-notes) and 0.4.1
21
+ (the rest). See each example's README for full methodology and numbers.
22
+
23
+ † Measured on a Linux container (4 vCPUs, Xeon @ 2.80GHz), Node v24.22.2,
24
+ Go 1.26.0. The native binary is faster up to about 150–200 KB of input per run.
25
+ yaml-cli's [parity.mjs](yaml-cli/parity.mjs) also checks every output against
26
+ Node byte for byte on the yaml-test-suite (1,608 cases).
27
+
28
+ ‡ Measured on a Linux container (4 vCPUs, Xeon @ 2.10GHz), Node v24.22.1,
29
+ Go 1.26.0. The native binary is faster up to about 150–200 KB of markdown per
30
+ run. marked-cli's [parity.mjs](marked-cli/parity.mjs) checks every output
31
+ against Node byte for byte on marked's spec suites (2,859 cases).
15
32
 
16
33
  ## Running an example
17
34
 
@@ -37,6 +54,9 @@ cd examples/fibonacci
37
54
  node main.ts 35
38
55
  ```
39
56
 
57
+ desktop-notes also needs `npm install` in its folder first, for the webview
58
+ package. Its compiled build doesn't.
59
+
40
60
  ## Reproducing the benchmarks
41
61
 
42
62
  Each example folder contains a self-contained harness that compiles the
@@ -46,9 +66,26 @@ example with the repo's own CLI and compares both runtimes:
46
66
  cd examples/hello-world && node bench.mjs
47
67
  cd examples/fibonacci && node bench.mjs 35 15
48
68
  cd examples/json-server && node bench.mjs
69
+ cd examples/todo-cli && node bench.mjs
70
+ cd examples/dupe-finder && node bench.mjs
71
+ cd examples/mandelbrot-png && node bench.mjs
72
+ cd examples/desktop-notes && npm install && node bench.mjs
73
+ cd examples/yaml-cli && node bench.mjs # and node parity.mjs
74
+ cd examples/marked-cli && node bench.mjs # and node parity.mjs
49
75
  ```
50
76
 
51
- Across the three, TypeNative wins process startup (~7x), CPU-bound compute
52
- (~2x) and HTTP throughput (~1.3x, with lower median latency). The READMEs
53
- report what was measured, including run-to-run variation and how each load
54
- was generated.
77
+ TypeNative's clearest wins are process startup and memory. Startup is about
78
+ 7x faster, which is what you feel in a CLI like todo-cli. A long-running app
79
+ like desktop-notes idles at about a fifth of Node's memory. Disk- and
80
+ hash-bound work (dupe-finder) and HTTP serving gain 1.3–1.6x. Pure
81
+ floating-point loops (mandelbrot-png) run at about the same speed as V8's
82
+ JIT, and recursion-heavy code (fibonacci) runs about 2x faster. Every example
83
+ also ships as one dependency-free binary. The READMEs report what was
84
+ measured, including run-to-run variation and how each load was generated.
85
+
86
+ ## Build check
87
+
88
+ `npm run conformance` type-checks and builds every `examples/*/main.ts` (as
89
+ `example-<name>`), so a change to TypeNative that breaks an example fails the
90
+ suite. Run just these with `node scripts/conformance.mjs example`. See the
91
+ [Examples section of conformance.md](../conformance.md#examples).
@@ -0,0 +1,108 @@
1
+ # Desktop Notes
2
+
3
+ A desktop notes app in a native webview window. It's a `node:http` server that
4
+ edits plain Markdown files in a folder, and its UI renders in a window opened
5
+ with the [`@webviewjs/webview`](https://www.npmjs.com/package/@webviewjs/webview)
6
+ API. The HTML, CSS and JS live in [ui.ts](ui.ts) as a TypeScript string, so the
7
+ compiled binary is the whole app. There is no Electron, no bundled Chromium, no
8
+ Node runtime and no asset folder to ship next to it.
9
+
10
+ The same `main.ts` runs both ways. Under Node.js the import is the npm package.
11
+ Compiled, it's TypeNative's built-in version, so the binary needs neither the
12
+ package nor a C toolchain.
13
+
14
+ Demonstrates: a webview window, `node:http` routing with GET / PUT / POST /
15
+ DELETE, request bodies, `fs` reads, writes, listing and `statSync`, a local `.ts`
16
+ module import, `setInterval`, `process.memoryUsage()` and `process.exit`.
17
+
18
+ ## How it works
19
+
20
+ - `GET /` serves the page from `ui.ts`. `/api/notes` lists notes (name, size,
21
+ modified time), and `/api/notes/<name>` reads, saves (`PUT`) or deletes one.
22
+ Note names are restricted to `[\w\- ]`, so they can't escape the folder.
23
+ - The editor autosaves 400 ms after you stop typing. Notes are plain
24
+ `<name>.md` files, so you can also edit them with any other tool.
25
+ - The window loads the page from that local server. Closing it ends the app. Text
26
+ the autosave hasn't reached goes out as a `navigator.sendBeacon` on
27
+ `beforeunload`, and the app waits 300 ms for it to arrive.
28
+ - **Under Node.js the window gets a process of its own**, which is this script
29
+ run with `--window <url>`. On Windows the npm package's event pump can hold the
30
+ JS thread for as long as the window is idle, and the server needs that thread.
31
+ Compiled apps run the window on its own thread, so they stay one process.
32
+ - The webview's profile lives in a folder the app chooses with
33
+ `createWebContext`. The default sits beside the executable, which is read-only
34
+ for `node.exe` under Program Files.
35
+
36
+ ## Run it
37
+
38
+ Under Node.js, install the webview package first. This example pins
39
+ `1.0.0-rc.4`, because the `latest` tag (0.6.0) froze more readily in testing.
40
+
41
+ ```sh
42
+ npm install
43
+ node main.ts # notes in ~/Notes, opens the window
44
+ node main.ts --dir ./my-notes # another folder
45
+ node main.ts --no-open --port 8080 # server only: open http://127.0.0.1:8080
46
+ ```
47
+
48
+ With TypeNative, build once and ship the single file. `--gui` leaves out the
49
+ console window on Windows:
50
+
51
+ ```sh
52
+ npx typenative --source main.ts --output dist/notes.exe --gui --release
53
+ ./dist/notes.exe
54
+ ```
55
+
56
+ From a checkout of this repository:
57
+
58
+ ```sh
59
+ node bin/cli.js --source examples/desktop-notes/main.ts --output dist/notes.exe --gui
60
+ ```
61
+
62
+ ## What the window is on each platform
63
+
64
+ | Platform | Compiled with TypeNative | Under Node.js |
65
+ |--------------------------------------|--------------------------------------|----------------------|
66
+ | Windows | Embedded WebView2 | Embedded WebView2 |
67
+ | Windows without the WebView2 runtime | Edge or Chrome in app mode | Not supported |
68
+ | macOS | Chrome, Edge or Chromium in app mode | Embedded WebKit |
69
+ | Linux | Chrome, Edge or Chromium in app mode | Embedded WebKitGTK |
70
+
71
+ **Only Windows has been run end to end.** The macOS and Linux builds compile, but
72
+ neither column has been tried on those systems. TypeNative uses no cgo, which rules
73
+ out WebKit on those platforms for now, so a compiled app there needs a browser
74
+ installed and shows the browser's window frame. Node.js on Linux needs the WebKitGTK
75
+ libraries.
76
+
77
+ ## Benchmark: Node.js vs TypeNative
78
+
79
+ Reproduce with `npm install`, then `node bench.mjs [runs=10]`. The script compiles
80
+ `main.ts`, fills a temp notes folder with 200 notes for each runtime, and then
81
+ alternates between the runtimes. Each run starts the app headless (`--no-open`) and
82
+ times **spawn until `GET /` answers 200**, which is what the user waits for before
83
+ the window can paint. It then lists the notes, opens 20 of them, saves one, and
84
+ reads the app's own **resident memory** from `/api/info`.
85
+
86
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0,
87
+ TypeNative 0.4.2, default (non-`--release`) build.
88
+
89
+ | Spawn → first page | min | median | mean | max |
90
+ |--------------------|-----------|-----------|-----------|-----------|
91
+ | Node.js | 212.53 ms | 246.86 ms | 241.53 ms | 273.47 ms |
92
+ | TypeNative | 42.59 ms | 51.29 ms | 119.99 ms | 719.02 ms |
93
+
94
+ | Resident memory | min | median | mean | max |
95
+ |-----------------|----------|----------|----------|----------|
96
+ | Node.js | 71.4 MiB | 72.6 MiB | 72.6 MiB | 73.5 MiB |
97
+ | TypeNative | 11.1 MiB | 15.3 MiB | 13.4 MiB | 15.8 MiB |
98
+
99
+ **TypeNative serves the first page 4.8x sooner and uses 4.7x less memory**
100
+ (median). One TypeNative run took 719 ms, which is why its mean is so far above its
101
+ median. The app is a single 12.4 MiB binary with the UI included, or 8.7 MiB with
102
+ `--gui --release`. An Electron build of the same app would ship about 100 MiB of
103
+ Chromium and Node. This app uses the webview the OS already has, and its backend
104
+ idles at about 15 MiB.
105
+
106
+ These figures cover the headless server process only. They leave out the webview's
107
+ own processes, which are about the same for both runtimes, and the extra window
108
+ process Node.js runs.
@@ -0,0 +1,125 @@
1
+ // Launch + memory benchmark: Node.js vs TypeNative for the notes app.
2
+ //
3
+ // Compiles main.ts to a native binary with the TypeNative CLI from this repo
4
+ // checkout (../../bin/cli.js), then for each runtime, repeatedly:
5
+ // 1. starts the app headless (--no-open) on a free port, over a temp notes
6
+ // folder holding 200 notes,
7
+ // 2. measures the time from spawn until GET / answers 200 (what the user
8
+ // waits for before the window can paint),
9
+ // 3. lists the notes, opens 20 of them and saves one (warm-up), then reads
10
+ // the app's own resident memory (RSS) from /api/info,
11
+ // 4. stops it.
12
+ //
13
+ // Usage: node bench.mjs [runs=10]
14
+
15
+ import { spawn, spawnSync } from 'node:child_process';
16
+ import fs from 'node:fs';
17
+ import net from 'node:net';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ const here = path.dirname(fileURLToPath(import.meta.url));
23
+ const repoRoot = path.resolve(here, '..', '..');
24
+ const cli = path.join(repoRoot, 'bin', 'cli.js');
25
+ const runs = Number(process.argv[2] ?? '10') || 10;
26
+ const exeName = process.platform === 'win32' ? 'notes.exe' : 'notes';
27
+ const exePath = path.join(here, 'dist', exeName);
28
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'notes-bench-'));
29
+
30
+ function stats(samples) {
31
+ const sorted = [...samples].sort((a, b) => a - b);
32
+ const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
33
+ return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
34
+ }
35
+
36
+ const fmt = (n, unit) => `${n.toFixed(unit === 'ms' ? 2 : 1)} ${unit}`.padStart(11);
37
+
38
+ function freePort() {
39
+ return new Promise((resolve) => {
40
+ const server = net.createServer().listen(0, '127.0.0.1', () => {
41
+ const { port } = server.address();
42
+ server.close(() => resolve(port));
43
+ });
44
+ });
45
+ }
46
+
47
+ async function waitFor200(url, deadline) {
48
+ while (performance.now() < deadline) {
49
+ try {
50
+ const res = await fetch(url);
51
+ await res.arrayBuffer();
52
+ if (res.status === 200) return;
53
+ } catch {
54
+ // not listening yet
55
+ }
56
+ await new Promise((r) => setTimeout(r, 2));
57
+ }
58
+ throw new Error(`no answer from ${url}`);
59
+ }
60
+
61
+ async function measure(command, args, notesDir) {
62
+ const port = await freePort();
63
+ const base = `http://127.0.0.1:${port}`;
64
+ const t0 = performance.now();
65
+ const child = spawn(command, [...args, '--no-open', '--port', String(port), '--dir', notesDir], { cwd: here, stdio: 'ignore' });
66
+ try {
67
+ await waitFor200(`${base}/`, t0 + 10000);
68
+ const ready = performance.now() - t0;
69
+ const notes = await (await fetch(`${base}/api/notes`)).json();
70
+ for (const note of notes.slice(0, 20)) await (await fetch(`${base}/api/notes/${encodeURIComponent(note.name)}`)).text();
71
+ await fetch(`${base}/api/notes/Bench`, { method: 'PUT', body: 'saved by bench.mjs\n'.repeat(100) });
72
+ const info = await (await fetch(`${base}/api/info`)).json();
73
+ return { ready, rssMiB: info.rss / 1024 / 1024 };
74
+ } finally {
75
+ child.kill();
76
+ }
77
+ }
78
+
79
+ if (!fs.existsSync(path.join(here, 'node_modules', '@webviewjs', 'webview'))) {
80
+ console.error('Run npm install in this folder first: main.ts needs @webviewjs/webview under Node.js');
81
+ process.exit(1);
82
+ }
83
+
84
+ // 1. Compile the app to a native binary.
85
+ fs.mkdirSync(path.join(here, 'dist'), { recursive: true });
86
+ console.log('Compiling main.ts to a native binary with TypeNative...');
87
+ const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', path.join('dist', exeName)], {
88
+ cwd: here,
89
+ stdio: 'inherit',
90
+ });
91
+ if (build.status !== 0) process.exit(build.status ?? 1);
92
+
93
+ // 2. A notes folder per runtime, 200 notes of a few KiB each.
94
+ const dirs = { node: path.join(tmpDir, 'node'), native: path.join(tmpDir, 'native') };
95
+ for (const dir of Object.values(dirs)) {
96
+ fs.mkdirSync(dir);
97
+ for (let i = 0; i < 200; i++) {
98
+ fs.writeFileSync(path.join(dir, `Note ${i}.md`), `# Note ${i}\n\n` + `Line of text for note ${i}.\n`.repeat(100));
99
+ }
100
+ }
101
+
102
+ // 3. Alternate runtimes so background load affects both alike.
103
+ console.log(`\nStarting each runtime ${runs} times...\n`);
104
+ const results = { node: [], native: [] };
105
+ for (let i = 0; i < runs; i++) {
106
+ results.node.push(await measure(process.execPath, ['main.ts'], dirs.node));
107
+ results.native.push(await measure(exePath, [], dirs.native));
108
+ }
109
+ fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
110
+
111
+ const table = (title, key, unit) => {
112
+ console.log(`${title}, ${runs} runs:\n`);
113
+ console.log('| Runtime | min | median | mean | max |');
114
+ console.log('|------------|-------------|-------------|-------------|-------------|');
115
+ for (const [label, name] of [['Node.js ', 'node'], ['TypeNative', 'native']]) {
116
+ const s = stats(results[name].map((r) => r[key]));
117
+ console.log(`| ${label} |${fmt(s.min, unit)} |${fmt(s.median, unit)} |${fmt(s.mean, unit)} |${fmt(s.max, unit)} |`);
118
+ }
119
+ const ratio = stats(results.node.map((r) => r[key])).median / stats(results.native.map((r) => r[key])).median;
120
+ console.log(`\nTypeNative: ${ratio.toFixed(1)}x ${key === 'ready' ? 'faster' : 'less memory'} (median).\n`);
121
+ };
122
+ table('Spawn until GET / answers 200', 'ready', 'ms');
123
+ table('Resident memory after listing, opening 20 notes and saving one', 'rssMiB', 'MiB');
124
+ const size = fs.statSync(exePath).size / 1024 / 1024;
125
+ console.log(`Native binary: ${size.toFixed(1)} MiB, the whole app (UI included).`);
@@ -0,0 +1,131 @@
1
+ // A desktop notes app: a local web server plus a native webview window, editing
2
+ // plain Markdown files in a folder on disk. The UI (./ui.ts) is compiled into
3
+ // the binary, so the result is one small executable that opens a window: no
4
+ // Electron, no Node runtime, no files next to it.
5
+ //
6
+ // node main.ts [--dir <folder>] [--port N] [--no-open] (npm install first)
7
+ // ./notes [--dir <folder>] [--port N] [--no-open]
8
+ //
9
+ // Notes live in ~/Notes by default. The window comes from @webviewjs/webview:
10
+ // the npm package under Node.js, TypeNative's built-in version when compiled,
11
+ // and the app quits when it closes. With --no-open it only serves
12
+ // http://127.0.0.1:<port> and runs until stopped.
13
+ import { Application } from '@webviewjs/webview';
14
+ import { spawn } from 'node:child_process';
15
+ import fs from 'node:fs';
16
+ import http from 'node:http';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { page } from './ui.ts';
20
+
21
+ interface NoteInfo {
22
+ name: string;
23
+ size: number;
24
+ modified: number;
25
+ }
26
+
27
+ function flag(name: string): string | undefined {
28
+ const i = process.argv.indexOf(name);
29
+ return i >= 0 ? process.argv[i + 1] : undefined;
30
+ }
31
+
32
+ const dir = path.resolve(flag('--dir') ?? path.join(os.homedir(), 'Notes'));
33
+ const port = Number(flag('--port') ?? '0');
34
+ const openWindow = !process.argv.includes('--no-open');
35
+ fs.mkdirSync(dir, { recursive: true });
36
+
37
+ // Note names map straight to file names, so only allow safe characters
38
+ function noteFile(name: string): string | undefined {
39
+ return /^[\w\- ]{1,100}$/.test(name) ? path.join(dir, `${name}.md`) : undefined;
40
+ }
41
+
42
+ function listNotes(): NoteInfo[] {
43
+ const notes: NoteInfo[] = [];
44
+ for (const file of fs.readdirSync(dir)) {
45
+ if (!file.endsWith('.md')) continue;
46
+ const stat = fs.statSync(path.join(dir, file));
47
+ notes.push({ name: file.slice(0, -3), size: stat.size, modified: stat.mtimeMs });
48
+ }
49
+ return notes.sort((a, b) => b.modified - a.modified);
50
+ }
51
+
52
+ function send(res: http.ServerResponse, status: number, type: string, body: string): void {
53
+ res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' });
54
+ res.end(body);
55
+ }
56
+
57
+ const server = http.createServer((req, res) => {
58
+ let body = '';
59
+ req.on('data', (chunk) => {
60
+ body += String(chunk);
61
+ });
62
+ req.on('end', () => {
63
+ const url = req.url ?? '/';
64
+ const method = req.method ?? 'GET';
65
+ if (url === '/') {
66
+ send(res, 200, 'text/html; charset=utf-8', page);
67
+ } else if (url === '/api/info') {
68
+ const info = { dir: dir, runtime: path.basename(process.execPath), rss: process.memoryUsage().rss };
69
+ send(res, 200, 'application/json', JSON.stringify(info));
70
+ } else if (url === '/api/notes') {
71
+ send(res, 200, 'application/json', JSON.stringify(listNotes()));
72
+ } else if (url.startsWith('/api/notes/')) {
73
+ const file = noteFile(decodeURIComponent(url.slice('/api/notes/'.length)));
74
+ if (!file) {
75
+ send(res, 400, 'text/plain', 'invalid note name');
76
+ } else if (method === 'GET') {
77
+ if (fs.existsSync(file)) send(res, 200, 'text/markdown; charset=utf-8', fs.readFileSync(file, 'utf8'));
78
+ else send(res, 404, 'text/plain', 'no such note');
79
+ } else if (method === 'PUT' || method === 'POST') {
80
+ // POST too: the window's last save on close arrives as a beacon
81
+ fs.writeFileSync(file, body);
82
+ send(res, 204, 'text/plain', '');
83
+ } else if (method === 'DELETE') {
84
+ fs.rmSync(file, { force: true });
85
+ send(res, 204, 'text/plain', '');
86
+ } else {
87
+ send(res, 405, 'text/plain', 'method not allowed');
88
+ }
89
+ } else {
90
+ send(res, 404, 'text/plain', 'not found');
91
+ }
92
+ });
93
+ });
94
+
95
+ function openAppWindow(url: string, onClosed: () => void): void {
96
+ const app = new Application();
97
+ // The webview's profile folder: its default, beside the executable, is read-only
98
+ // for node.exe under Program Files
99
+ const profile = app.createWebContext({ dataDirectory: path.join(os.tmpdir(), 'desktop-notes-webview') });
100
+ const win = app.createBrowserWindow({ title: 'Notes', width: 1000, height: 700, logical: true });
101
+ win.createWebview({ url: url, webContext: profile });
102
+ app.on('application-close-requested', onClosed);
103
+ app.run();
104
+ }
105
+
106
+ // The window's last save is a beacon sent as it closes: let it arrive
107
+ function quit(): void {
108
+ setTimeout(() => process.exit(0), 300);
109
+ }
110
+
111
+ // On Windows the npm package's event pump can hold the JS thread for as long as
112
+ // its window is idle, and the server needs that thread: under Node.js the window
113
+ // gets a process of its own, this same script run with --window <url>
114
+ const underNode = path.basename(process.execPath, '.exe') === 'node';
115
+ const windowUrl = flag('--window');
116
+
117
+ if (windowUrl) {
118
+ openAppWindow(windowUrl, () => process.exit(0));
119
+ } else {
120
+ server.listen(port, '127.0.0.1', () => {
121
+ const address = server.address() as { port: number };
122
+ const url = `http://127.0.0.1:${address.port}/`;
123
+ console.log(`Notes in ${dir} on ${url}`);
124
+ if (!openWindow) return;
125
+ if (underNode) {
126
+ spawn(process.execPath, [process.argv[1], '--window', url], { stdio: 'inherit' }).on('exit', quit);
127
+ } else {
128
+ openAppWindow(url, quit);
129
+ }
130
+ });
131
+ }