typenative 0.7.0 → 0.7.1
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/bin/node/assert.js +2 -2
- package/bin/node/child_process.js +66 -8
- package/bin/node/fs.js +1012 -4
- package/bin/node/histogram.js +1991 -0
- package/bin/node/process.js +14 -2
- package/bin/node/sqlite.js +1488 -5
- package/bin/node/stream.js +2 -1
- package/bin/node/system_extra.js +3 -270
- package/bin/node/test.js +39 -1
- package/bin/node/test_report.js +47 -1
- package/bin/node/test_run.js +57 -2
- package/bin/node/util.js +8 -5
- package/bin/node/webassembly.js +20 -5
- package/bin/node/webview.js +3257 -244
- package/bin/node/zlib.js +118 -14
- package/bin/node/zlib_iter.js +585 -0
- package/bin/transpiler.js +1370 -258
- package/bin/version.js +1 -1
- package/govendor/software.sslmate.com/src/go-pkcs12/.gitattributes +10 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/LICENSE +28 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/README.md +31 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/bmp-string.go +63 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/crypto.go +331 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/errors.go +23 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/go.mod +3 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/internal/rc2/rc2.go +271 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/mac.go +202 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/pbkdf.go +184 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/pkcs12.go +1000 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/safebags.go +107 -0
- package/package.json +10 -1
- package/types/tsconfig.json +17 -0
- package/types/typenative-npm.d.ts +492 -12
- package/types/typenative.d.ts +88 -2
- package/.gitattributes +0 -1
- package/.github/workflows/ci.yml +0 -68
- package/.github/workflows/npm-publish-github-packages.yml +0 -88
- package/CHANGELOG.md +0 -1746
- package/CONTRIBUTION.md +0 -133
- package/conformance.md +0 -1497
- package/examples/README.md +0 -114
- package/examples/angular-templates/README.md +0 -141
- package/examples/angular-templates/bench.mjs +0 -173
- package/examples/angular-templates/dom-type-globals.d.ts +0 -21
- package/examples/angular-templates/dom-type-stubs.ts +0 -21
- package/examples/angular-templates/main.ts +0 -135
- package/examples/angular-templates/parity.mjs +0 -157
- package/examples/angular-templates/run-node.mjs +0 -69
- package/examples/angular-templates/vendor/angular/compiler/LICENSE +0 -21
- package/examples/desktop-notes/README.md +0 -106
- package/examples/desktop-notes/bench.mjs +0 -125
- package/examples/desktop-notes/main.ts +0 -131
- package/examples/desktop-notes/package-lock.json +0 -726
- package/examples/desktop-notes/package.json +0 -9
- package/examples/desktop-notes/ui.ts +0 -176
- package/examples/dupe-finder/README.md +0 -78
- package/examples/dupe-finder/bench.mjs +0 -120
- package/examples/dupe-finder/main.ts +0 -87
- package/examples/fibonacci/README.md +0 -89
- package/examples/fibonacci/bench.mjs +0 -87
- package/examples/fibonacci/main.ts +0 -21
- package/examples/hello-world/README.md +0 -62
- package/examples/hello-world/bench.mjs +0 -66
- package/examples/hello-world/main.ts +0 -7
- package/examples/json-server/README.md +0 -132
- package/examples/json-server/bench.mjs +0 -263
- package/examples/json-server/main.ts +0 -67
- package/examples/mandelbrot-png/README.md +0 -63
- package/examples/mandelbrot-png/bench.mjs +0 -95
- package/examples/mandelbrot-png/main.ts +0 -98
- package/examples/mandelbrot-png/preview.png +0 -0
- package/examples/marked-cli/README.md +0 -174
- package/examples/marked-cli/bench.mjs +0 -178
- package/examples/marked-cli/main.ts +0 -410
- package/examples/marked-cli/parity.mjs +0 -185
- package/examples/marked-cli/vendor/marked/LICENSE +0 -44
- package/examples/marked-cli/vendor/marked/VENDOR.md +0 -26
- package/examples/openai-chat/README.md +0 -148
- package/examples/openai-chat/bench.mjs +0 -175
- package/examples/openai-chat/main.ts +0 -488
- package/examples/react-compiler/README.md +0 -185
- package/examples/react-compiler/bench.mjs +0 -181
- package/examples/react-compiler/main.ts +0 -324
- package/examples/react-compiler/parity.mjs +0 -362
- package/examples/react-compiler/run-node.mjs +0 -90
- package/examples/react-compiler/vendor/babel/LICENSE +0 -22
- package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +0 -15
- package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +0 -51
- package/examples/react-compiler/vendor/charcodes/package.json +0 -25
- package/examples/react-compiler/vendor/invariant/LICENSE +0 -21
- package/examples/react-compiler/vendor/invariant/invariant.cjs +0 -51
- package/examples/react-compiler/vendor/invariant/invariant.d.cts +0 -11
- package/examples/react-compiler/vendor/invariant/types/LICENSE +0 -21
- package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +0 -19
- package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +0 -19
- package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +0 -19
- package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +0 -19
- package/examples/react-compiler/vendor/js-tokens/LICENSE +0 -21
- package/examples/react-compiler/vendor/js-tokens/index.cjs +0 -23
- package/examples/react-compiler/vendor/js-tokens/index.d.cts +0 -13
- package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +0 -20
- package/examples/react-compiler/vendor/jsesc/jsesc.cjs +0 -337
- package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +0 -384
- package/examples/react-compiler/vendor/jsesc/types/LICENSE +0 -21
- package/examples/react-compiler/vendor/picocolors/LICENSE +0 -15
- package/examples/react-compiler/vendor/picocolors/picocolors.cjs +0 -75
- package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +0 -5
- package/examples/react-compiler/vendor/picocolors/types.d.ts +0 -51
- package/examples/react-compiler/vendor/react-compiler/LICENSE +0 -21
- package/examples/react-compiler/vendor/stubs/babel-core.ts +0 -31
- package/examples/react-compiler/vendor/stubs/debug.ts +0 -18
- package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +0 -13
- package/examples/react-compiler/vendor/stubs/pretty-format.ts +0 -18
- package/examples/react-compiler/vendor/zod/LICENSE +0 -21
- package/examples/react-compiler/vendor/zod-validation-error/LICENSE +0 -9
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +0 -5
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +0 -49
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +0 -48
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +0 -50
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +0 -6
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +0 -126
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +0 -39
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +0 -78
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +0 -2
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +0 -131
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +0 -54
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +0 -40
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +0 -76
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +0 -76
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +0 -27
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +0 -27
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +0 -13
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +0 -61
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +0 -38
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +0 -20
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +0 -5
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +0 -8
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +0 -11
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +0 -20
- package/examples/react-compiler/vendor.mjs +0 -688
- package/examples/todo-cli/README.md +0 -69
- package/examples/todo-cli/bench.mjs +0 -89
- package/examples/todo-cli/main.ts +0 -92
- package/examples/yaml-cli/README.md +0 -152
- package/examples/yaml-cli/bench.mjs +0 -265
- package/examples/yaml-cli/main.ts +0 -251
- package/examples/yaml-cli/parity.mjs +0 -156
- package/examples/yaml-cli/vendor/yaml/LICENSE +0 -13
- package/examples/yaml-cli/vendor/yaml/VENDOR.md +0 -25
- package/performance/README.md +0 -248
- package/performance/any-dynamic.ts +0 -21
- package/performance/any-record-view.ts +0 -20
- package/performance/arr-for-of.ts +0 -29
- package/performance/arr-hof.ts +0 -21
- package/performance/arr-push-index.ts +0 -15
- package/performance/arr-push-local.ts +0 -39
- package/performance/arr-slice-concat.ts +0 -24
- package/performance/arr-sort.ts +0 -21
- package/performance/async-await.ts +0 -24
- package/performance/async-promise-all.ts +0 -38
- package/performance/bigint-arith.ts +0 -36
- package/performance/buf-encode.ts +0 -29
- package/performance/class-accessors.ts +0 -48
- package/performance/class-dispatch.ts +0 -52
- package/performance/date-format.ts +0 -18
- package/performance/events-emit.ts +0 -27
- package/performance/exc-throw-rare.ts +0 -25
- package/performance/exc-try-catch.ts +0 -26
- package/performance/fn-closures.ts +0 -29
- package/performance/fn-recursion-tree.ts +0 -31
- package/performance/fn-rest-spread.ts +0 -43
- package/performance/gen-for-of.ts +0 -46
- package/performance/gen-next.ts +0 -32
- package/performance/iter-helpers.ts +0 -38
- package/performance/json-any.ts +0 -30
- package/performance/json-roundtrip.ts +0 -27
- package/performance/map-delete.ts +0 -24
- package/performance/map-iterate.ts +0 -26
- package/performance/map-number-keys.ts +0 -37
- package/performance/map-string-keys.ts +0 -22
- package/performance/num-arith-loop.ts +0 -14
- package/performance/num-bitwise.ts +0 -21
- package/performance/num-hash-imul.ts +0 -36
- package/performance/num-mod-int.ts +0 -16
- package/performance/num-to-string.ts +0 -16
- package/performance/obj-alloc.ts +0 -32
- package/performance/obj-keys-entries.ts +0 -44
- package/performance/obj-optional-chain.ts +0 -42
- package/performance/obj-record-dict.ts +0 -24
- package/performance/obj-spread-destructure.ts +0 -40
- package/performance/regex-exec.ts +0 -29
- package/performance/regex-replace-fn.ts +0 -24
- package/performance/regex-site.ts +0 -28
- package/performance/set-ops.ts +0 -20
- package/performance/str-char-scan.ts +0 -35
- package/performance/str-concat-plus.ts +0 -18
- package/performance/str-concat.ts +0 -24
- package/performance/str-methods.ts +0 -24
- package/performance/str-short-scan.ts +0 -26
- package/performance/str-split-join.ts +0 -23
- package/performance/str-switch-compare.ts +0 -50
- package/performance/str-template.ts +0 -16
- package/performance/str-unicode.ts +0 -25
- package/performance/typed-array.ts +0 -30
- package/performance/union-switch.ts +0 -57
- package/performance/union-typeof.ts +0 -40
- package/performance/wasm-call.ts +0 -63
- package/tsparser/check.go +0 -158
- package/tsparser/go.mod +0 -14
- package/tsparser/go.sum +0 -22
- package/tsparser/main.go +0 -363
- package/tsparser/tsparser.exe +0 -4
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
# Hello World
|
|
2
|
-
|
|
3
|
-
The smallest possible TypeNative program — a `console.log` with an optional
|
|
4
|
-
name from `process.argv`. It is the "hello world" of both TypeScript and
|
|
5
|
-
native compilation: no work is done at all, so benchmarking it measures pure
|
|
6
|
-
**runtime startup cost**.
|
|
7
|
-
|
|
8
|
-
## The code
|
|
9
|
-
|
|
10
|
-
```ts
|
|
11
|
-
// main.ts
|
|
12
|
-
const name = process.argv[2] ?? 'world';
|
|
13
|
-
console.log(`Hello, ${name}!`);
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## Run it
|
|
17
|
-
|
|
18
|
-
With Node.js:
|
|
19
|
-
|
|
20
|
-
```sh
|
|
21
|
-
node main.ts Ada
|
|
22
|
-
# Hello, Ada!
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
With TypeNative (compile to a native binary and run it):
|
|
26
|
-
|
|
27
|
-
```sh
|
|
28
|
-
npx typenative --source main.ts --output dist/hello.exe
|
|
29
|
-
./dist/hello.exe Ada
|
|
30
|
-
# Hello, Ada!
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
From a checkout of this repository, use the local CLI instead of `npx`:
|
|
34
|
-
|
|
35
|
-
```sh
|
|
36
|
-
node bin/cli.js --source examples/hello-world/main.ts --script # compile + run
|
|
37
|
-
node bin/cli.js --source examples/hello-world/main.ts --output dist/hello.exe
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
(`--script` compiles and runs in one step; passing program arguments requires a
|
|
41
|
-
built binary, as shown above.)
|
|
42
|
-
|
|
43
|
-
## Benchmark: Node.js vs TypeNative
|
|
44
|
-
|
|
45
|
-
Reproduce with `node bench.mjs [runs=30]`. The script compiles `main.ts` with
|
|
46
|
-
the TypeNative CLI, then times **complete process runs** (spawn to exit) of
|
|
47
|
-
the same program under both runtimes. Since the program does no work, the
|
|
48
|
-
numbers are almost entirely startup time.
|
|
49
|
-
|
|
50
|
-
**Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
|
|
51
|
-
TypeNative 0.7.0, default (non-`--release`) build.
|
|
52
|
-
|
|
53
|
-
| Runtime | min | median | mean | max |
|
|
54
|
-
|------------|------------|------------|------------|------------|
|
|
55
|
-
| Node.js | 43.61 ms | 45.19 ms | 46.53 ms | 56.21 ms |
|
|
56
|
-
| TypeNative | 4.50 ms | 4.90 ms | 8.04 ms | 99.60 ms |
|
|
57
|
-
|
|
58
|
-
**TypeNative starts 9.2x faster** (median). The compiled binary is a
|
|
59
|
-
self-contained 2.7 MB executable: there is no runtime to boot, no module
|
|
60
|
-
system to initialize, and no JIT to warm up, so process-to-output latency is
|
|
61
|
-
an order of magnitude lower. For CLI tools that are invoked frequently, this
|
|
62
|
-
is the difference users notice.
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
// Startup benchmark: Node.js vs TypeNative for the hello-world program.
|
|
2
|
-
//
|
|
3
|
-
// Compiles main.ts to a native binary with the TypeNative CLI from this repo
|
|
4
|
-
// checkout (../../bin/cli.js), then times complete process runs (spawn to
|
|
5
|
-
// exit) of the same program under both runtimes. Because the program itself
|
|
6
|
-
// does almost no work, this mostly measures runtime startup cost.
|
|
7
|
-
//
|
|
8
|
-
// Usage: node bench.mjs [runs=30]
|
|
9
|
-
|
|
10
|
-
import { spawnSync } from 'node:child_process';
|
|
11
|
-
import fs from 'node:fs';
|
|
12
|
-
import path from 'node:path';
|
|
13
|
-
import { fileURLToPath } from 'node:url';
|
|
14
|
-
|
|
15
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
-
const repoRoot = path.resolve(here, '..', '..');
|
|
17
|
-
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
18
|
-
const runs = Number(process.argv[2] ?? '30') || 30;
|
|
19
|
-
const exeName = process.platform === 'win32' ? 'hello.exe' : 'hello';
|
|
20
|
-
const exePath = path.join(here, 'dist', exeName);
|
|
21
|
-
|
|
22
|
-
function stats(samples) {
|
|
23
|
-
const sorted = [...samples].sort((a, b) => a - b);
|
|
24
|
-
const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
|
|
25
|
-
return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function fmt(ms) {
|
|
29
|
-
return `${ms.toFixed(2)} ms`.padStart(11);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function timeRuns(command, args) {
|
|
33
|
-
const samples = [];
|
|
34
|
-
for (let i = 0; i < runs; i++) {
|
|
35
|
-
const t0 = performance.now();
|
|
36
|
-
const result = spawnSync(command, args, { cwd: here, encoding: 'utf8' });
|
|
37
|
-
const elapsed = performance.now() - t0;
|
|
38
|
-
if (result.status !== 0) {
|
|
39
|
-
console.error(`run failed: ${command} ${args.join(' ')}\n${result.stderr}`);
|
|
40
|
-
process.exit(1);
|
|
41
|
-
}
|
|
42
|
-
samples.push(elapsed);
|
|
43
|
-
}
|
|
44
|
-
return stats(samples);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// 1. Compile hello-world to a native binary.
|
|
48
|
-
fs.mkdirSync(path.join(here, 'dist'), { recursive: true });
|
|
49
|
-
console.log('Compiling main.ts to a native binary with TypeNative...');
|
|
50
|
-
const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', path.join('dist', exeName)], {
|
|
51
|
-
cwd: here,
|
|
52
|
-
stdio: 'inherit',
|
|
53
|
-
});
|
|
54
|
-
if (build.status !== 0) process.exit(build.status ?? 1);
|
|
55
|
-
|
|
56
|
-
// 2. Time full process runs under both runtimes.
|
|
57
|
-
console.log(`\nTiming ${runs} full process runs of each runtime...\n`);
|
|
58
|
-
const nodeStats = timeRuns(process.execPath, ['main.ts']);
|
|
59
|
-
const nativeStats = timeRuns(exePath, []);
|
|
60
|
-
|
|
61
|
-
console.log(`Startup time, ${runs} runs (full process: spawn -> exit):\n`);
|
|
62
|
-
console.log('| Runtime | min | median | mean | max |');
|
|
63
|
-
console.log('|------------|-------------|-------------|-------------|-------------|');
|
|
64
|
-
console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |`);
|
|
65
|
-
console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |`);
|
|
66
|
-
console.log(`\nTypeNative starts ${(nodeStats.median / nativeStats.median).toFixed(1)}x faster (median).`);
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
// The smallest possible TypeNative program: print a greeting to stdout.
|
|
2
|
-
// An optional name can be passed as the first CLI argument:
|
|
3
|
-
//
|
|
4
|
-
// node main.ts Ada -> Hello, Ada!
|
|
5
|
-
// ./hello Ada -> Hello, Ada!
|
|
6
|
-
const name = process.argv[2] ?? 'world';
|
|
7
|
-
console.log(`Hello, ${name}!`);
|
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
# JSON Server
|
|
2
|
-
|
|
3
|
-
A tiny JSON API for managing todos, built with nothing but the Node standard
|
|
4
|
-
library — `node:http`, `JSON`, and `URL`. The todos live in memory, so the
|
|
5
|
-
same file is a complete, dependency-free web server under Node.js and as a
|
|
6
|
-
compiled TypeNative binary.
|
|
7
|
-
|
|
8
|
-
## The code
|
|
9
|
-
|
|
10
|
-
```ts
|
|
11
|
-
// main.ts (abridged — see main.ts for the full server)
|
|
12
|
-
import http from 'node:http';
|
|
13
|
-
|
|
14
|
-
interface Todo {
|
|
15
|
-
id: number;
|
|
16
|
-
title: string;
|
|
17
|
-
done: boolean;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const todos: Todo[] = [];
|
|
21
|
-
let nextId = 1;
|
|
22
|
-
|
|
23
|
-
const server = http.createServer((req, res) => {
|
|
24
|
-
let body = '';
|
|
25
|
-
req.on('data', (chunk) => { body += String(chunk); });
|
|
26
|
-
req.on('end', () => {
|
|
27
|
-
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
28
|
-
|
|
29
|
-
if (req.method === 'GET' && url.pathname === '/todos') {
|
|
30
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
31
|
-
res.end(JSON.stringify(todos));
|
|
32
|
-
} else if (req.method === 'POST' && url.pathname === '/todos') {
|
|
33
|
-
const input = JSON.parse(body) as { title: string };
|
|
34
|
-
// ... validate, create, respond 201 ...
|
|
35
|
-
} else {
|
|
36
|
-
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
37
|
-
res.end(JSON.stringify({ error: 'no route' }));
|
|
38
|
-
}
|
|
39
|
-
});
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
server.listen(3000, '127.0.0.1');
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
## Routes
|
|
46
|
-
|
|
47
|
-
| Route | Method | Description |
|
|
48
|
-
|-----------------|--------|----------------------------------------------|
|
|
49
|
-
| `/todos` | GET | List all todos |
|
|
50
|
-
| `/todos/<id>` | GET | Fetch one todo (404 if missing) |
|
|
51
|
-
| `/todos` | POST | Create a todo: `{ "title": "..." }` → 201 |
|
|
52
|
-
| anything else | * | `404` with a JSON error |
|
|
53
|
-
|
|
54
|
-
A missing `title` returns `400` with a JSON error. (The example keeps
|
|
55
|
-
`JSON.parse` unguarded, so invalid JSON throws — under Node and the compiled
|
|
56
|
-
binary alike, an uncaught throw ends the process.)
|
|
57
|
-
|
|
58
|
-
## Run it
|
|
59
|
-
|
|
60
|
-
With Node.js:
|
|
61
|
-
|
|
62
|
-
```sh
|
|
63
|
-
node main.ts # listens on http://127.0.0.1:3000
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
With TypeNative (compile to a single self-contained binary — no Node
|
|
67
|
-
required on the machine that runs it):
|
|
68
|
-
|
|
69
|
-
```sh
|
|
70
|
-
npx typenative --source main.ts --output dist/server.exe
|
|
71
|
-
./dist/server.exe # optional port argument or PORT env var
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
From a checkout of this repository, use the local CLI instead of `npx`:
|
|
75
|
-
|
|
76
|
-
```sh
|
|
77
|
-
node bin/cli.js --source examples/json-server/main.ts --script
|
|
78
|
-
node bin/cli.js --source examples/json-server/main.ts --output dist/server.exe
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
Try it:
|
|
82
|
-
|
|
83
|
-
```sh
|
|
84
|
-
curl -s http://127.0.0.1:3000/todos # []
|
|
85
|
-
curl -s -X POST -d '{"title":"write examples"}' \
|
|
86
|
-
http://127.0.0.1:3000/todos # {"id":1,...}
|
|
87
|
-
curl -s http://127.0.0.1:3000/todos/1 # one todo
|
|
88
|
-
curl -s -w "%{http_code}" -X POST -d '{}' http://127.0.0.1:3000/todos # 400
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
## Benchmark: Node.js vs TypeNative
|
|
92
|
-
|
|
93
|
-
Reproduce with `node bench.mjs [gets=20000] [posts=10000]`. The script
|
|
94
|
-
compiles `main.ts` with the TypeNative CLI, starts the server under each
|
|
95
|
-
runtime, seeds 50 todos, and drives load over keep-alive connections at
|
|
96
|
-
concurrency 16 (identical client for both). It measures requests/second plus
|
|
97
|
-
p50/p99 latency per request for `GET /todos` (20,000 requests, ~50-item JSON
|
|
98
|
-
response) and `POST /todos` (10,000 requests).
|
|
99
|
-
|
|
100
|
-
The load generator is built to stay out of the way, like `wrk` or
|
|
101
|
-
`autocannon`: 8 worker threads × 2 raw keep-alive sockets send prebuilt
|
|
102
|
-
request bytes and read each response just far enough to find its end. A
|
|
103
|
-
plain `node:http` client would cap out far below either server, so
|
|
104
|
-
with it both servers would simply tie at the client's limit.
|
|
105
|
-
|
|
106
|
-
**Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
|
|
107
|
-
TypeNative 0.7.0, default (non-`--release`) build, client
|
|
108
|
-
and server on the same machine. Re-run variation is about ±20%; across runs
|
|
109
|
-
TypeNative was 1.6–1.7x Node on GET and 1.4–1.8x on POST. The numbers below are
|
|
110
|
-
medians over three runs.
|
|
111
|
-
|
|
112
|
-
| Runtime | Endpoint | req/s | p50 (ms) | p99 (ms) |
|
|
113
|
-
|------------|-------------|-------:|---------:|---------:|
|
|
114
|
-
| Node.js | GET /todos | 57265 | 0.24 | 0.68 |
|
|
115
|
-
| TypeNative | GET /todos | 94068 | 0.15 | 0.44 |
|
|
116
|
-
| Node.js | POST /todos | 60173 | 0.23 | 0.50 |
|
|
117
|
-
| TypeNative | POST /todos | 102328 | 0.14 | 0.43 |
|
|
118
|
-
|
|
119
|
-
**TypeNative serves ~1.6x more GET and ~1.7x more POST requests per second
|
|
120
|
-
here**, with lower median latency on both routes. The compiled server reads
|
|
121
|
-
requests and writes
|
|
122
|
-
responses on each connection's goroutine, and a handler that answers
|
|
123
|
-
synchronously (`writeHead` + `end`, as both routes do) builds the response
|
|
124
|
-
bytes right there, in one write: it never queues an operation for the event
|
|
125
|
-
loop, which keeps the per-request hand-off to JavaScript to a single baton
|
|
126
|
-
pass. JavaScript still runs one thing at a time, but at 94–102k req/s the
|
|
127
|
-
parallel socket I/O and HTTP handling stay ahead of that one thread.
|
|
128
|
-
|
|
129
|
-
On top of that, the binary starts in a few milliseconds instead of ~45 ms and
|
|
130
|
-
is a single 13.1 MB executable with zero dependencies — `scp` it to a server and
|
|
131
|
-
run it, no Node install, no `node_modules` — and CPU-heavy work inside a
|
|
132
|
-
handler runs ~2x faster (see the [fibonacci example](../fibonacci/README.md)).
|
|
@@ -1,263 +0,0 @@
|
|
|
1
|
-
// HTTP throughput benchmark: Node.js vs TypeNative for the JSON server.
|
|
2
|
-
//
|
|
3
|
-
// Compiles main.ts to a native binary with the TypeNative CLI from this repo
|
|
4
|
-
// checkout (../../bin/cli.js), then runs the full comparison:
|
|
5
|
-
//
|
|
6
|
-
// 1. starts the server under Node.js, seeds 50 todos, drives load, stops it
|
|
7
|
-
// 2. starts the compiled binary, seeds 50 todos, drives load, stops it
|
|
8
|
-
//
|
|
9
|
-
// Load is two phases per runtime, over keep-alive connections at concurrency
|
|
10
|
-
// 16, measuring req/s plus p50/p99 latency per request:
|
|
11
|
-
// - GET /todos 20,000 requests (a ~50-item JSON list per response)
|
|
12
|
-
// - POST /todos 10,000 requests (create a todo)
|
|
13
|
-
//
|
|
14
|
-
// The client is built to stay out of the way, like wrk or autocannon: worker
|
|
15
|
-
// threads (8 x 2 connections) send prebuilt request bytes over raw keep-alive
|
|
16
|
-
// sockets and read each response only far enough to find its end. A plain
|
|
17
|
-
// node:http client tops out at ~8-11k req/s on its own here, which would
|
|
18
|
-
// measure the client rather than the servers.
|
|
19
|
-
//
|
|
20
|
-
// Usage: node bench.mjs [gets=20000] [posts=10000]
|
|
21
|
-
|
|
22
|
-
import { spawn, spawnSync } from 'node:child_process';
|
|
23
|
-
import net from 'node:net';
|
|
24
|
-
import fs from 'node:fs';
|
|
25
|
-
import path from 'node:path';
|
|
26
|
-
import { fileURLToPath } from 'node:url';
|
|
27
|
-
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
28
|
-
|
|
29
|
-
const WORKERS = 8;
|
|
30
|
-
const CONNECTIONS_PER_WORKER = 2;
|
|
31
|
-
const CONCURRENCY = WORKERS * CONNECTIONS_PER_WORKER;
|
|
32
|
-
|
|
33
|
-
// The complete response at the start of buf: { status, length } (null while
|
|
34
|
-
// more bytes are needed). Bodies end by Content-Length or chunked encoding.
|
|
35
|
-
function parseResponse(buf) {
|
|
36
|
-
const headEnd = buf.indexOf('\r\n\r\n');
|
|
37
|
-
if (headEnd < 0) return null;
|
|
38
|
-
const head = buf.toString('latin1', 0, headEnd);
|
|
39
|
-
const status = Number(head.slice(9, 12));
|
|
40
|
-
const bodyStart = headEnd + 4;
|
|
41
|
-
const contentLength = /\r\ncontent-length:\s*(\d+)/i.exec(head);
|
|
42
|
-
if (contentLength) {
|
|
43
|
-
const end = bodyStart + Number(contentLength[1]);
|
|
44
|
-
return buf.length >= end ? { status, length: end } : null;
|
|
45
|
-
}
|
|
46
|
-
if (/\r\ntransfer-encoding:\s*chunked/i.test(head)) {
|
|
47
|
-
for (let at = bodyStart; ; ) {
|
|
48
|
-
const lineEnd = buf.indexOf('\r\n', at);
|
|
49
|
-
if (lineEnd < 0) return null;
|
|
50
|
-
const size = parseInt(buf.toString('latin1', at, lineEnd), 16);
|
|
51
|
-
const next = lineEnd + 2 + size + 2;
|
|
52
|
-
if (buf.length < next) return null;
|
|
53
|
-
if (size === 0) return { status, length: next };
|
|
54
|
-
at = next;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
return { status, length: bodyStart };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// A keep-alive connection with one request in flight at a time;
|
|
61
|
-
// send(bytes) resolves with the response status
|
|
62
|
-
function connect(host, port) {
|
|
63
|
-
return new Promise((resolve, reject) => {
|
|
64
|
-
let buffered = Buffer.alloc(0);
|
|
65
|
-
let pending = null;
|
|
66
|
-
const socket = net.connect(port, host, () => resolve(connection));
|
|
67
|
-
socket.setNoDelay(true);
|
|
68
|
-
const connection = {
|
|
69
|
-
send: (bytes) =>
|
|
70
|
-
new Promise((onStatus, onError) => {
|
|
71
|
-
pending = { onStatus, onError };
|
|
72
|
-
socket.write(bytes);
|
|
73
|
-
}),
|
|
74
|
-
close: () => socket.destroy(),
|
|
75
|
-
};
|
|
76
|
-
socket.on('data', (chunk) => {
|
|
77
|
-
buffered = buffered.length > 0 ? Buffer.concat([buffered, chunk]) : chunk;
|
|
78
|
-
const response = parseResponse(buffered);
|
|
79
|
-
if (response && pending) {
|
|
80
|
-
buffered = buffered.subarray(response.length);
|
|
81
|
-
const { onStatus } = pending;
|
|
82
|
-
pending = null;
|
|
83
|
-
onStatus(response.status);
|
|
84
|
-
}
|
|
85
|
-
});
|
|
86
|
-
socket.on('error', (err) => (pending ? pending.onError(err) : reject(err)));
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// Worker thread: sends its share of one phase's requests over its own
|
|
91
|
-
// connections, then returns each request's latency
|
|
92
|
-
async function runWorker({ base, method, reqPath, body, total }) {
|
|
93
|
-
const target = new URL(base);
|
|
94
|
-
const request = Buffer.from(
|
|
95
|
-
`${method} ${reqPath} HTTP/1.1\r\nHost: ${target.host}\r\n` +
|
|
96
|
-
(body ? `Content-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n` : '') +
|
|
97
|
-
`\r\n${body ?? ''}`
|
|
98
|
-
);
|
|
99
|
-
const latencies = new Float64Array(total);
|
|
100
|
-
let dispatched = 0;
|
|
101
|
-
const connections = await Promise.all(
|
|
102
|
-
Array.from({ length: CONNECTIONS_PER_WORKER }, () => connect(target.hostname, Number(target.port)))
|
|
103
|
-
);
|
|
104
|
-
|
|
105
|
-
// Wait for the go signal so every worker starts at once
|
|
106
|
-
await new Promise((resolve) => parentPort.once('message', resolve));
|
|
107
|
-
await Promise.all(
|
|
108
|
-
connections.map(async (connection) => {
|
|
109
|
-
for (;;) {
|
|
110
|
-
const index = dispatched;
|
|
111
|
-
dispatched += 1;
|
|
112
|
-
if (index >= total) return;
|
|
113
|
-
const start = performance.now();
|
|
114
|
-
const status = await connection.send(request);
|
|
115
|
-
latencies[index] = performance.now() - start;
|
|
116
|
-
if (status !== 200 && status !== 201) throw new Error(`${method} ${reqPath} -> ${status}`);
|
|
117
|
-
}
|
|
118
|
-
})
|
|
119
|
-
);
|
|
120
|
-
for (const connection of connections) connection.close();
|
|
121
|
-
parentPort.postMessage(latencies, [latencies.buffer]);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
if (!isMainThread) {
|
|
125
|
-
parentPort.postMessage('ready');
|
|
126
|
-
await runWorker(workerData);
|
|
127
|
-
process.exit(0);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
131
|
-
const repoRoot = path.resolve(here, '..', '..');
|
|
132
|
-
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
133
|
-
const GET_REQUESTS = Number(process.argv[2] ?? '20000') || 20000;
|
|
134
|
-
const POST_REQUESTS = Number(process.argv[3] ?? '10000') || 10000;
|
|
135
|
-
const SEEDED = 50;
|
|
136
|
-
const exeName = process.platform === 'win32' ? 'server.exe' : 'server';
|
|
137
|
-
const exePath = path.join(here, 'dist', exeName);
|
|
138
|
-
|
|
139
|
-
function sleep(ms) {
|
|
140
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// Starts a server (node main.ts or the native binary) and resolves with its
|
|
144
|
-
// port once it prints its "listening on ..." banner and answers requests.
|
|
145
|
-
async function startServer(label, command, args) {
|
|
146
|
-
const child = spawn(command, args, { cwd: here, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
147
|
-
let stdout = '';
|
|
148
|
-
const port = await new Promise((resolve, reject) => {
|
|
149
|
-
const timer = setTimeout(() => reject(new Error(`${label}: no port banner, output:\n${stdout}`)), 20000);
|
|
150
|
-
child.stdout.on('data', (chunk) => {
|
|
151
|
-
stdout += chunk;
|
|
152
|
-
const match = stdout.match(/listening on http:\/\/127\.0\.0\.1:(\d+)/);
|
|
153
|
-
if (match) {
|
|
154
|
-
clearTimeout(timer);
|
|
155
|
-
resolve(Number(match[1]));
|
|
156
|
-
}
|
|
157
|
-
});
|
|
158
|
-
child.on('exit', (code) => {
|
|
159
|
-
clearTimeout(timer);
|
|
160
|
-
reject(new Error(`${label}: server exited early (code ${code}):\n${stdout}`));
|
|
161
|
-
});
|
|
162
|
-
});
|
|
163
|
-
const base = `http://127.0.0.1:${port}`;
|
|
164
|
-
for (let i = 0; i < 100; i++) {
|
|
165
|
-
try {
|
|
166
|
-
const res = await fetch(`${base}/todos`);
|
|
167
|
-
if (res.ok) return { child, base };
|
|
168
|
-
} catch {
|
|
169
|
-
// not accepting connections yet
|
|
170
|
-
}
|
|
171
|
-
await sleep(100);
|
|
172
|
-
}
|
|
173
|
-
child.kill();
|
|
174
|
-
throw new Error(`${label}: server never became ready`);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
async function seed(base) {
|
|
178
|
-
for (let i = 0; i < SEEDED; i++) {
|
|
179
|
-
const res = await fetch(`${base}/todos`, { method: 'POST', body: JSON.stringify({ title: `task ${i + 1}` }) });
|
|
180
|
-
if (res.status !== 201) throw new Error(`seed request failed with status ${res.status}`);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// One load phase spread over the worker threads; returns req/s and latencies.
|
|
185
|
-
async function benchPhase(base, { method, reqPath, body, total }) {
|
|
186
|
-
const workers = Array.from({ length: WORKERS }, (_, i) => {
|
|
187
|
-
const share = Math.floor(total / WORKERS) + (i < total % WORKERS ? 1 : 0);
|
|
188
|
-
return new Worker(fileURLToPath(import.meta.url), {
|
|
189
|
-
workerData: { base, method, reqPath, body, total: share },
|
|
190
|
-
});
|
|
191
|
-
});
|
|
192
|
-
const finished = workers.map(
|
|
193
|
-
(worker) =>
|
|
194
|
-
new Promise((resolve, reject) => {
|
|
195
|
-
worker.on('message', (message) => {
|
|
196
|
-
if (message !== 'ready') resolve(message);
|
|
197
|
-
});
|
|
198
|
-
worker.on('error', reject);
|
|
199
|
-
})
|
|
200
|
-
);
|
|
201
|
-
await Promise.all(
|
|
202
|
-
workers.map((worker) => new Promise((resolve) => worker.once('message', resolve)))
|
|
203
|
-
);
|
|
204
|
-
|
|
205
|
-
const t0 = performance.now();
|
|
206
|
-
for (const worker of workers) worker.postMessage('go');
|
|
207
|
-
const results = await Promise.all(finished);
|
|
208
|
-
const elapsedSec = (performance.now() - t0) / 1000;
|
|
209
|
-
|
|
210
|
-
const sorted = results.flatMap((latencies) => Array.from(latencies)).sort((a, b) => a - b);
|
|
211
|
-
return {
|
|
212
|
-
rps: total / elapsedSec,
|
|
213
|
-
p50: sorted[Math.floor(total * 0.5)],
|
|
214
|
-
p99: sorted[Math.min(total - 1, Math.floor(total * 0.99))],
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
async function measure(label, command, args) {
|
|
219
|
-
console.log(`\nBenchmarking ${label}...`);
|
|
220
|
-
const { child, base } = await startServer(label, command, args);
|
|
221
|
-
try {
|
|
222
|
-
await seed(base);
|
|
223
|
-
const get = await benchPhase(base, { method: 'GET', reqPath: '/todos', total: GET_REQUESTS });
|
|
224
|
-
console.log(` GET /todos ${GET_REQUESTS.toLocaleString()} req -> ${get.rps.toFixed(0)} req/s`);
|
|
225
|
-
const post = await benchPhase(base, {
|
|
226
|
-
method: 'POST',
|
|
227
|
-
reqPath: '/todos',
|
|
228
|
-
body: JSON.stringify({ title: 'bench item' }),
|
|
229
|
-
total: POST_REQUESTS,
|
|
230
|
-
});
|
|
231
|
-
console.log(` POST /todos ${POST_REQUESTS.toLocaleString()} req -> ${post.rps.toFixed(0)} req/s`);
|
|
232
|
-
return { get, post };
|
|
233
|
-
} finally {
|
|
234
|
-
child.kill();
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
function row(label, phase, result) {
|
|
239
|
-
return `| ${label.padEnd(10)} | ${phase.padEnd(13)} | ${result.rps.toFixed(0).padStart(9)} | ${result.p50.toFixed(2).padStart(8)} | ${result.p99.toFixed(2).padStart(8)} |`;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// 1. Compile the server to a native binary.
|
|
243
|
-
fs.mkdirSync(path.join(here, 'dist'), { recursive: true });
|
|
244
|
-
console.log('Compiling main.ts to a native binary with TypeNative...');
|
|
245
|
-
const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', path.join('dist', exeName)], {
|
|
246
|
-
cwd: here,
|
|
247
|
-
stdio: 'inherit',
|
|
248
|
-
});
|
|
249
|
-
if (build.status !== 0) process.exit(build.status ?? 1);
|
|
250
|
-
|
|
251
|
-
// 2. Load-test both runtimes.
|
|
252
|
-
const nodeStats = await measure('Node.js', process.execPath, ['main.ts']);
|
|
253
|
-
const nativeStats = await measure('TypeNative', exePath, []);
|
|
254
|
-
|
|
255
|
-
// 3. Report.
|
|
256
|
-
console.log(`\nThroughput (keep-alive, concurrency ${CONCURRENCY}, ${SEEDED} todos seeded):\n`);
|
|
257
|
-
console.log('| Runtime | Endpoint | req/s | p50 (ms) | p99 (ms) |');
|
|
258
|
-
console.log('|------------|---------------|---------|----------|----------|');
|
|
259
|
-
console.log(row('Node.js', 'GET /todos', nodeStats.get));
|
|
260
|
-
console.log(row('TypeNative', 'GET /todos', nativeStats.get));
|
|
261
|
-
console.log(row('Node.js', 'POST /todos', nodeStats.post));
|
|
262
|
-
console.log(row('TypeNative', 'POST /todos', nativeStats.post));
|
|
263
|
-
console.log(`\nTypeNative serves ${(nativeStats.get.rps / nodeStats.get.rps).toFixed(1)}x more GET and ${(nativeStats.post.rps / nodeStats.post.rps).toFixed(1)}x more POST requests per second.`);
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
// A tiny JSON API built with nothing but the Node standard library
|
|
2
|
-
// (node:http). The todos live in memory, so the same file is a complete,
|
|
3
|
-
// dependency-free web server under Node.js and as a compiled TypeNative
|
|
4
|
-
// binary.
|
|
5
|
-
//
|
|
6
|
-
// Routes:
|
|
7
|
-
// GET /todos list all todos
|
|
8
|
-
// GET /todos/<id> fetch one todo (404 if missing)
|
|
9
|
-
// POST /todos create a todo from a JSON body: { "title": "..." }
|
|
10
|
-
//
|
|
11
|
-
// node main.ts [port] (default 3000; PORT env var also honored)
|
|
12
|
-
// ./server [port]
|
|
13
|
-
import http from 'node:http';
|
|
14
|
-
|
|
15
|
-
interface Todo {
|
|
16
|
-
id: number;
|
|
17
|
-
title: string;
|
|
18
|
-
done: boolean;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
const todos: Todo[] = [];
|
|
22
|
-
let nextId = 1;
|
|
23
|
-
|
|
24
|
-
function send(res: http.ServerResponse, status: number, body: string): void {
|
|
25
|
-
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
26
|
-
res.end(body);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const server = http.createServer((req, res) => {
|
|
30
|
-
let body = '';
|
|
31
|
-
req.on('data', (chunk) => {
|
|
32
|
-
body += String(chunk);
|
|
33
|
-
});
|
|
34
|
-
req.on('end', () => {
|
|
35
|
-
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
36
|
-
|
|
37
|
-
if (req.method === 'GET' && url.pathname === '/todos') {
|
|
38
|
-
send(res, 200, JSON.stringify(todos));
|
|
39
|
-
} else if (req.method === 'GET' && url.pathname.startsWith('/todos/')) {
|
|
40
|
-
const id = Number(url.pathname.slice('/todos/'.length));
|
|
41
|
-
const todo = todos.find((t) => t.id === id);
|
|
42
|
-
if (todo) {
|
|
43
|
-
send(res, 200, JSON.stringify(todo));
|
|
44
|
-
} else {
|
|
45
|
-
send(res, 404, JSON.stringify({ error: 'todo not found' }));
|
|
46
|
-
}
|
|
47
|
-
} else if (req.method === 'POST' && url.pathname === '/todos') {
|
|
48
|
-
const input = JSON.parse(body) as { title: string };
|
|
49
|
-
if (!input.title) {
|
|
50
|
-
send(res, 400, JSON.stringify({ error: 'title is required' }));
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
const todo: Todo = { id: nextId, title: input.title, done: false };
|
|
54
|
-
nextId += 1;
|
|
55
|
-
todos.push(todo);
|
|
56
|
-
send(res, 201, JSON.stringify(todo));
|
|
57
|
-
} else {
|
|
58
|
-
send(res, 404, JSON.stringify({ error: 'no route' }));
|
|
59
|
-
}
|
|
60
|
-
});
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
const port = Number(process.argv[2] ?? process.env.PORT ?? '3000');
|
|
64
|
-
server.listen(port, '127.0.0.1', () => {
|
|
65
|
-
const address = server.address() as { port: number };
|
|
66
|
-
console.log(`Todo API listening on http://127.0.0.1:${address.port}`);
|
|
67
|
-
});
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
# Mandelbrot PNG
|
|
2
|
-
|
|
3
|
-
Renders the Mandelbrot set and writes it as a PNG. The PNG encoder is about
|
|
4
|
-
40 lines of TypeScript on top of `node:zlib` (`deflateSync` for the pixel
|
|
5
|
-
data, `crc32` for the chunk checksums). The program needs no image library,
|
|
6
|
-
no native addon such as `sharp` or `canvas`, and no `node_modules`: the
|
|
7
|
-
compiled binary is a single 4.2 MB file.
|
|
8
|
-
|
|
9
|
-
Demonstrates: a tight floating-point loop, a function returning a tuple that
|
|
10
|
-
the caller destructures, `Uint8Array` / `DataView` big-endian writes,
|
|
11
|
-
`zlib.deflateSync` + `zlib.crc32`, `Math.log2` / `Math.cos`, and
|
|
12
|
-
`fs.writeFileSync` of binary data.
|
|
13
|
-
|
|
14
|
-

|
|
15
|
-
|
|
16
|
-
## Run it
|
|
17
|
-
|
|
18
|
-
With Node.js:
|
|
19
|
-
|
|
20
|
-
```sh
|
|
21
|
-
node main.ts 1920 1080 mandelbrot.png
|
|
22
|
-
# Rendered 1920x1080 in 533 ms, encoded 416056 bytes in 50 ms -> mandelbrot.png
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
With TypeNative:
|
|
26
|
-
|
|
27
|
-
```sh
|
|
28
|
-
npx typenative --source main.ts --output dist/mandelbrot.exe
|
|
29
|
-
./dist/mandelbrot.exe 1920 1080 mandelbrot.png
|
|
30
|
-
# Rendered 1920x1080 in 534 ms, encoded 418872 bytes in 46 ms -> mandelbrot.png
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
From a checkout of this repository:
|
|
34
|
-
|
|
35
|
-
```sh
|
|
36
|
-
node bin/cli.js --source examples/mandelbrot-png/main.ts --output dist/mandelbrot.exe
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
The two PNGs aren't byte-identical, because Node's deflate is zlib and
|
|
40
|
-
TypeNative's is Go's `compress/flate`. They do decode to **identical pixels**.
|
|
41
|
-
|
|
42
|
-
## Benchmark: Node.js vs TypeNative
|
|
43
|
-
|
|
44
|
-
Reproduce with `node bench.mjs [width=1920] [height=1080] [runs=10]`. The
|
|
45
|
-
script compiles `main.ts`, times **complete process runs** (spawn to exit) of
|
|
46
|
-
both runtimes rendering the same image, then decodes both PNGs (checking every
|
|
47
|
-
chunk CRC) and compares the pixels.
|
|
48
|
-
|
|
49
|
-
**Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
|
|
50
|
-
TypeNative 0.7.0, default (non-`--release`) build.
|
|
51
|
-
|
|
52
|
-
| Runtime | min | median | mean | max |
|
|
53
|
-
|------------|-----------|-----------|-----------|-----------|
|
|
54
|
-
| Node.js | 455.84 ms | 462.40 ms | 467.48 ms | 507.02 ms |
|
|
55
|
-
| TypeNative | 416.75 ms | 418.66 ms | 432.57 ms | 558.33 ms |
|
|
56
|
-
|
|
57
|
-
**TypeNative is 1.1x faster end to end** (median). There's no JIT warm-up.
|
|
58
|
-
The render loop itself takes about the same time in both runtimes. V8 compiles a tight float loop like the escape-time
|
|
59
|
-
iteration into machine code about as good as Go's. The difference is mostly
|
|
60
|
-
Node's startup. For recursion and
|
|
61
|
-
call-heavy code the compute gap is larger (see [fibonacci](../fibonacci/),
|
|
62
|
-
2.1x). This example's main advantage is distribution: one dependency-free
|
|
63
|
-
binary that writes images.
|