typenative 0.5.0 → 0.6.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/.github/workflows/ci.yml +2 -2
- package/.github/workflows/npm-publish-github-packages.yml +2 -2
- package/CHANGELOG.md +339 -0
- package/CONTRIBUTION.md +2 -1
- package/README.md +16 -7
- package/bin/cli.js +1 -0
- package/bin/index.js +62 -3
- package/bin/main.js +1 -0
- package/bin/node/core.js +46 -0
- package/bin/node/events.js +154 -15
- package/bin/node/http.js +1265 -127
- package/bin/node/process.js +13 -0
- package/bin/node/punycode.js +2 -2
- package/bin/node/stream.js +56 -7
- package/bin/node/stream_web.js +2 -2
- package/bin/node/timers.js +4 -2
- package/bin/node/url.js +28 -3
- package/bin/parse-node.js +2 -2
- package/bin/regex_vm.js +2105 -0
- package/bin/transpiler.js +17970 -4419
- package/bin/typecheck-node.js +2 -1
- package/bin/version.js +1 -1
- package/conformance.md +57 -15
- package/examples/README.md +50 -28
- package/examples/angular-templates/README.md +141 -0
- package/examples/angular-templates/bench.mjs +173 -0
- package/examples/angular-templates/dom-type-globals.d.ts +21 -0
- package/examples/angular-templates/dom-type-stubs.ts +21 -0
- package/examples/angular-templates/main.ts +135 -0
- package/examples/angular-templates/parity.mjs +157 -0
- package/examples/angular-templates/run-node.mjs +69 -0
- package/examples/angular-templates/vendor/angular/compiler/LICENSE +21 -0
- package/examples/desktop-notes/README.md +11 -13
- package/examples/dupe-finder/README.md +7 -5
- package/examples/fibonacci/README.md +7 -7
- package/examples/hello-world/README.md +6 -6
- package/examples/json-server/README.md +22 -18
- package/examples/mandelbrot-png/README.md +11 -13
- package/examples/marked-cli/README.md +60 -44
- package/examples/marked-cli/main.ts +122 -4
- package/examples/openai-chat/README.md +148 -0
- package/examples/openai-chat/bench.mjs +175 -0
- package/examples/openai-chat/main.ts +488 -0
- package/examples/react-compiler/README.md +185 -0
- package/examples/react-compiler/bench.mjs +181 -0
- package/examples/react-compiler/main.ts +324 -0
- package/examples/react-compiler/parity.mjs +362 -0
- package/examples/react-compiler/run-node.mjs +90 -0
- package/examples/react-compiler/vendor/babel/LICENSE +22 -0
- package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +15 -0
- package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +51 -0
- package/examples/react-compiler/vendor/charcodes/package.json +25 -0
- package/examples/react-compiler/vendor/invariant/LICENSE +21 -0
- package/examples/react-compiler/vendor/invariant/invariant.cjs +51 -0
- package/examples/react-compiler/vendor/invariant/invariant.d.cts +11 -0
- package/examples/react-compiler/vendor/invariant/types/LICENSE +21 -0
- package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +19 -0
- package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +19 -0
- package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +19 -0
- package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +19 -0
- package/examples/react-compiler/vendor/js-tokens/LICENSE +21 -0
- package/examples/react-compiler/vendor/js-tokens/index.cjs +23 -0
- package/examples/react-compiler/vendor/js-tokens/index.d.cts +13 -0
- package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +20 -0
- package/examples/react-compiler/vendor/jsesc/jsesc.cjs +337 -0
- package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +384 -0
- package/examples/react-compiler/vendor/jsesc/types/LICENSE +21 -0
- package/examples/react-compiler/vendor/picocolors/LICENSE +15 -0
- package/examples/react-compiler/vendor/picocolors/picocolors.cjs +75 -0
- package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +5 -0
- package/examples/react-compiler/vendor/picocolors/types.d.ts +51 -0
- package/examples/react-compiler/vendor/react-compiler/LICENSE +21 -0
- package/examples/react-compiler/vendor/stubs/babel-core.ts +31 -0
- package/examples/react-compiler/vendor/stubs/debug.ts +18 -0
- package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +13 -0
- package/examples/react-compiler/vendor/stubs/pretty-format.ts +18 -0
- package/examples/react-compiler/vendor/zod/LICENSE +21 -0
- package/examples/react-compiler/vendor/zod-validation-error/LICENSE +9 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +5 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +49 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +48 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +50 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +6 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +126 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +39 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +12 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +78 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +2 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +12 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +12 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +131 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +54 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +12 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +40 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +12 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +76 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +76 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +27 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +27 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +13 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +61 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +38 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +20 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +5 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +8 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +11 -0
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +20 -0
- package/examples/react-compiler/vendor.mjs +688 -0
- package/examples/todo-cli/README.md +9 -9
- package/examples/yaml-cli/README.md +50 -34
- package/examples/yaml-cli/main.ts +236 -14
- package/package.json +8 -5
- package/performance/README.md +196 -0
- package/performance/any-dynamic.ts +21 -0
- package/performance/any-record-view.ts +20 -0
- package/performance/arr-hof.ts +21 -0
- package/performance/arr-push-index.ts +15 -0
- package/performance/arr-sort.ts +21 -0
- package/performance/async-await.ts +24 -0
- package/performance/class-dispatch.ts +52 -0
- package/performance/events-emit.ts +27 -0
- package/performance/exc-throw-rare.ts +25 -0
- package/performance/exc-try-catch.ts +26 -0
- package/performance/fn-closures.ts +29 -0
- package/performance/fn-recursion-tree.ts +31 -0
- package/performance/gen-for-of.ts +46 -0
- package/performance/json-roundtrip.ts +27 -0
- package/performance/map-delete.ts +24 -0
- package/performance/map-string-keys.ts +22 -0
- package/performance/num-arith-loop.ts +14 -0
- package/performance/num-bitwise.ts +21 -0
- package/performance/num-mod-int.ts +16 -0
- package/performance/num-to-string.ts +16 -0
- package/performance/obj-alloc.ts +32 -0
- package/performance/regex-exec.ts +29 -0
- package/performance/regex-site.ts +28 -0
- package/performance/set-ops.ts +20 -0
- package/performance/str-char-scan.ts +35 -0
- package/performance/str-concat-plus.ts +18 -0
- package/performance/str-concat.ts +24 -0
- package/performance/str-short-scan.ts +26 -0
- package/performance/str-split-join.ts +23 -0
- package/performance/str-template.ts +16 -0
- package/performance/union-switch.ts +57 -0
- package/tsparser/check.go +2 -1
- package/tsparser/main.go +1 -0
- package/types/typenative-npm.d.ts +3 -2
- package/types/typenative.d.ts +42 -12
- package/ROUND2-HANDOFF.md +0 -200
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# React Compiler
|
|
2
|
+
|
|
3
|
+
The React Compiler, natively. [vendor/react-compiler/](vendor/react-compiler/)
|
|
4
|
+
holds `babel-plugin-react-compiler`'s TypeScript source (the compiler's
|
|
5
|
+
`packages/babel-plugin-react-compiler/src`, MIT licensed), and
|
|
6
|
+
[vendor/babel/](vendor/babel/) the Babel packages it runs on (parser, types,
|
|
7
|
+
traverse, generator, template, code-frame and helpers), with zod 4 and its
|
|
8
|
+
other npm dependencies. [main.ts](main.ts) parses a component or hook with the
|
|
9
|
+
Babel parser, runs the compiler's full pipeline (HIR building, dozens of
|
|
10
|
+
transform passes, code generation) on it, and prints the auto-memoized output
|
|
11
|
+
the Babel plugin would emit, plus one `// CompileSuccess` or `// CompileError`
|
|
12
|
+
line per function from the compiler's own logger.
|
|
13
|
+
|
|
14
|
+
This is the largest and deepest real codebase TypeNative compiles: about 470
|
|
15
|
+
vendored files whose graph is full of import cycles (the React Compiler's
|
|
16
|
+
entrypoint barrels re-export each other's modules), built on Babel's
|
|
17
|
+
`NodePath`/`Scope` machinery (mixin-built classes with prototype methods
|
|
18
|
+
assigned at module init through computed keys, function values carrying
|
|
19
|
+
expando properties, `$constructor`-style factory functions that read `this`
|
|
20
|
+
under `new`), zod schemas validated at startup, discriminated unions narrowed
|
|
21
|
+
across dozens of passes, generators, and `WeakMap`s.
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
react-compile # compile the built-in demo component
|
|
27
|
+
react-compile app.jsx # compile a component file
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The first line of the input can carry the compiler's test pragmas, as in its
|
|
31
|
+
own fixtures: `// @compilationMode:"infer" @enableJsxOutlining`. A file the
|
|
32
|
+
compiler rejects prints `// compile error: …` and exits with code 1.
|
|
33
|
+
|
|
34
|
+
## Run it
|
|
35
|
+
|
|
36
|
+
With Node.js (the vendored sources use enums, so types are compiled first —
|
|
37
|
+
`run-node.mjs` does that once and caches the result):
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
node run-node.mjs app.jsx
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
With TypeNative:
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
npx typenative --source main.ts --output dist/react-compile
|
|
47
|
+
./dist/react-compile app.jsx
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
From a checkout of this repository:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
node bin/cli.js --source examples/react-compiler/main.ts --output dist/react-compile
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The vendored sources are checked upstream by their own toolchains, not tsc
|
|
57
|
+
(Babel does not type-check its sources with tsc), so the example's
|
|
58
|
+
[tsconfig.json](tsconfig.json) sets `noCheck`: `main.ts` itself is still
|
|
59
|
+
checked, with the vendored tree's imports resolved.
|
|
60
|
+
|
|
61
|
+
## Status: what works natively
|
|
62
|
+
|
|
63
|
+
Compiling `main.ts` links ~470 vendored modules and builds a native binary.
|
|
64
|
+
The transpiler work this needed is in TypeNative itself (see the CHANGELOG):
|
|
65
|
+
module initialization now follows the import graph's evaluation order with
|
|
66
|
+
JS's cycle semantics; `new F()` on a constructor-function value gets JS `new`
|
|
67
|
+
semantics; dynamic `fn.bind()`, `Object.assign` onto function values,
|
|
68
|
+
computed `C.prototype[k] = fn` assignments, and dynamic array-method calls
|
|
69
|
+
that share their name with a class method all behave as in JS; and an empty
|
|
70
|
+
object literal is no longer a zero-size Go value (every `{}' was one shared
|
|
71
|
+
object).
|
|
72
|
+
|
|
73
|
+
At runtime the binary initializes every module the way Node evaluates them —
|
|
74
|
+
zod's whole schema graph constructs and `parseEnvironmentConfig` fills in
|
|
75
|
+
every default — and the compiler's whole pipeline runs as it does under
|
|
76
|
+
Node: the Babel parser parses the program (JSX and TypeScript included),
|
|
77
|
+
traverse dispatches visitors, Scope collects bindings, the lowering builds
|
|
78
|
+
the HIR, every inference, validation and memoization pass runs, and the
|
|
79
|
+
Babel generator prints the result. Every parity fixture's output — the
|
|
80
|
+
memoized code, the `// CompileSuccess` counts, the compile errors with their
|
|
81
|
+
code frames — is byte-identical to Node's.
|
|
82
|
+
|
|
83
|
+
Most of what this took was JS object and array identity, which Go's value
|
|
84
|
+
semantics break unless the transpiler keeps it: an object converted to
|
|
85
|
+
another struct type stays one object (union members are views of the same
|
|
86
|
+
memory; a converted object is the same converted object every time); arrays
|
|
87
|
+
stay shared references through any-typed fields, getters, dynamic calls and
|
|
88
|
+
`splice`; a callee's changes to a converted argument (an array, a Map or Set,
|
|
89
|
+
an object's fields) are written back to the caller's; and `slice` copies.
|
|
90
|
+
The rest were JS semantics at the edges: getters in object literals stay
|
|
91
|
+
live, `Object.prototype` methods read as values, default parameters apply to
|
|
92
|
+
an explicit `undefined`, `null` and `undefined` stay apart where code tells
|
|
93
|
+
them apart, Map misses read as `undefined`, and keys written as `undefined`
|
|
94
|
+
are own keys.
|
|
95
|
+
|
|
96
|
+
## Parity with Node.js
|
|
97
|
+
|
|
98
|
+
[node parity.mjs](parity.mjs) compiles `main.ts` to a native binary and runs
|
|
99
|
+
the compiler over each fixture (components and hooks through
|
|
100
|
+
`useState`/`useMemo`/`useRef`/`useEffect` and custom hooks, the compiler's test
|
|
101
|
+
pragmas, `"use no memo"`, and the error paths) with both runtimes.
|
|
102
|
+
stdout, stderr and the exit code must match byte for byte — including the memo
|
|
103
|
+
slot and block counts in the `// CompileSuccess` lines. Failures are written
|
|
104
|
+
to `.cache/failures/`. All 15 fixtures match:
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
node parity.mjs
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Benchmark
|
|
111
|
+
|
|
112
|
+
Reproduce with `node bench.mjs [runs=30] [sizeRuns=5] [kilobytes=8,16,32,64]`.
|
|
113
|
+
The script compiles `main.ts`, then times **complete process runs** (spawn to
|
|
114
|
+
exit) of `react-compile` under both runtimes, alternating Node and native runs,
|
|
115
|
+
and stops if the two outputs ever differ. `TN_PARALLEL=0` forces the
|
|
116
|
+
single-process path for both runtimes:
|
|
117
|
+
|
|
118
|
+
- **(a) per-call latency:** the built-in demo (a `TodoList` component and a
|
|
119
|
+
`useTotal` hook), the size of a file a build compiles once per process.
|
|
120
|
+
- **(b) scaling:** generated component files from 8 to 64 KB (screens of
|
|
121
|
+
components with state, derived lists, handlers and conditionals, from a
|
|
122
|
+
fixed-seed generator, so every machine gets the same input).
|
|
123
|
+
|
|
124
|
+
**Environment:** Windows 11 Pro, AMD Ryzen 5 7600 (6 cores, 12 threads),
|
|
125
|
+
Node v26.13.0, Go 1.27.4, TypeNative 0.6.1, default (non-`--release`) build.
|
|
126
|
+
The binary is 29.9 MB.
|
|
127
|
+
|
|
128
|
+
(a) `react-compile` (built-in demo), 5 runs each:
|
|
129
|
+
|
|
130
|
+
| Runtime | min | median | mean | max |
|
|
131
|
+
| ---------- | --------- | --------- | --------- | --------- |
|
|
132
|
+
| Node.js | 347.32 ms | 348.88 ms | 349.49 ms | 353.65 ms |
|
|
133
|
+
| TypeNative | 97.67 ms | 99.61 ms | 107.70 ms | 142.96 ms |
|
|
134
|
+
|
|
135
|
+
(b) `react-compile generated-screen.jsx`, 5 runs per size (medians):
|
|
136
|
+
|
|
137
|
+
| Source | Node.js | TypeNative | TypeNative vs Node |
|
|
138
|
+
| ----------------- | ---------- | ---------- | ------------------ |
|
|
139
|
+
| 9 KB, 238 lines | 704.90 ms | 275.08 ms | 2.6x faster |
|
|
140
|
+
| 17 KB, 460 lines | 761.71 ms | 332.94 ms | 2.3x faster |
|
|
141
|
+
| 32 KB, 892 lines | 874.53 ms | 418.38 ms | 2.1x faster |
|
|
142
|
+
| 64 KB, 1774 lines | 1,030.31 ms| 615.05 ms | 1.7x faster |
|
|
143
|
+
|
|
144
|
+
**Per call, TypeNative is 3.5x faster** (100 ms vs 349 ms, median). Node
|
|
145
|
+
spends most of a short run loading and compiling the ~470 vendored modules;
|
|
146
|
+
the native binary starts with them compiled in.
|
|
147
|
+
|
|
148
|
+
**TypeNative is now faster on large inputs too.** Most of the gap was the
|
|
149
|
+
compiler's passes running through TypeNative's dynamic paths (any-typed
|
|
150
|
+
property reads, prototype-method dispatch, reflection-based struct
|
|
151
|
+
conversions) on every node of every pass, where V8's inline caches make the
|
|
152
|
+
same operations nearly free. Two rounds of profiling narrowed it:
|
|
153
|
+
|
|
154
|
+
- The plain functions Babel assigns to `NodePath.prototype` (`visit`,
|
|
155
|
+
`setScope`, `setContext`, …) declare `this: NodePath`; that now types
|
|
156
|
+
`__this` as `*NodePath_Final`, so `this.opts`, `this.parentPath` and the
|
|
157
|
+
rest are direct field reads and writes instead of plan lookups on every
|
|
158
|
+
AST node.
|
|
159
|
+
- Dynamic calls of the program's own function types (the visitor callbacks,
|
|
160
|
+
prototype methods and Babel's `call`/`apply` shapes) go through a generated
|
|
161
|
+
`tnCallValueTyped` case per Go func type, converting arguments directly
|
|
162
|
+
instead of `reflect.Value.Call`.
|
|
163
|
+
- Getters and setters of a class are recognized while a module is emitting
|
|
164
|
+
even before its class is visited (`classMember`), and optional calls to
|
|
165
|
+
members a class adds to its prototype at run time go through the guarded
|
|
166
|
+
dynamic call.
|
|
167
|
+
- Earlier work still applies: in-place `s += part` on Babel's output buffer
|
|
168
|
+
(printing was quadratic in the output size), the accessor / view-copy /
|
|
169
|
+
added-property registries skipped for types that never had an entry,
|
|
170
|
+
prototype methods called directly, generators as Go range functions, typed
|
|
171
|
+
dispatchers for shared method signatures, and Go integer loop counters.
|
|
172
|
+
|
|
173
|
+
**Large files compile their independent top-level functions in parallel.**
|
|
174
|
+
`main.ts` splits the input at top-level function boundaries when the file has
|
|
175
|
+
enough of them for at least two workers and nothing but imports/comments
|
|
176
|
+
before the first (and only blanks/comments between); each contiguous run is
|
|
177
|
+
padded to keep the
|
|
178
|
+
original line numbers, compiled by a worker process, and the parent joins the
|
|
179
|
+
per-function output. Compiler-generated `_temp` functions are suffixed per
|
|
180
|
+
chunk so the merged program has no name collisions. Under Node the same code
|
|
181
|
+
spawns Node workers, which must re-import the compiler per worker; a
|
|
182
|
+
TypeNative worker starts from the compiled binary, which is why the native
|
|
183
|
+
build now wins on the large sizes instead of only on startup. The merged
|
|
184
|
+
output is byte-identical between the two runtimes (and the small fixtures,
|
|
185
|
+
below eight functions, take the single-process path).
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Benchmark: Node.js vs TypeNative for the React Compiler, both compiling
|
|
2
|
+
// React components and hooks to their auto-memoized form.
|
|
3
|
+
//
|
|
4
|
+
// Compiles main.ts to a native binary with the TypeNative CLI from this repo
|
|
5
|
+
// checkout (../../bin/cli.js), then measures:
|
|
6
|
+
// (a) per-call latency: complete process runs (spawn to exit) on the
|
|
7
|
+
// built-in demo (two components with hooks, derived lists, JSX with
|
|
8
|
+
// conditionals, lists and event handlers);
|
|
9
|
+
// (b) scaling: generated component files of growing size (8 to 64 KB by
|
|
10
|
+
// default), each a screen of cards with hooks, derived arrays,
|
|
11
|
+
// conditionals and JSX lists, from a fixed-seed generator, so every
|
|
12
|
+
// machine gets the same input. Under Node the file runs through
|
|
13
|
+
// run-node.mjs (the vendored compiler sources use enums, which Node's
|
|
14
|
+
// type stripping cannot run; the TypeScript compile is cached).
|
|
15
|
+
// Runs alternate Node and native, so drift on the machine hits both alike.
|
|
16
|
+
// Both runtimes' output must be identical, or the benchmark stops.
|
|
17
|
+
//
|
|
18
|
+
// Usage: node bench.mjs [runs=30] [sizeRuns=5] [kilobytes=8,16,32,64]
|
|
19
|
+
|
|
20
|
+
import { spawnSync } from 'node:child_process';
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
|
|
25
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
26
|
+
const repoRoot = path.resolve(here, '..', '..');
|
|
27
|
+
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
28
|
+
const cache = path.join(here, '.cache');
|
|
29
|
+
const exePath = path.join(cache, process.platform === 'win32' ? 'react-compile.exe' : 'react-compile');
|
|
30
|
+
const bigPath = path.join(cache, 'generated-screen.jsx');
|
|
31
|
+
const runs = Number(process.argv[2] ?? '30') || 30;
|
|
32
|
+
const sizeRuns = Number(process.argv[3] ?? '5') || 5;
|
|
33
|
+
const sizes = (process.argv[4] ?? '8,16,32,64').split(',').map(Number).filter((n) => n > 0);
|
|
34
|
+
|
|
35
|
+
// Deterministic pseudo-random numbers (a fixed-seed LCG): the same components
|
|
36
|
+
// on every run and every machine
|
|
37
|
+
let seed = 42;
|
|
38
|
+
function rand(n) {
|
|
39
|
+
seed = (seed * 1103515245 + 12345) % 2147483648;
|
|
40
|
+
return Math.floor(seed / 65536) % n;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const WORDS = ['user', 'order', 'item', 'price', 'label', 'status', 'owner', 'total', 'title', 'count', 'tag', 'note'];
|
|
44
|
+
const HOOKS = ['useState', 'useReducer', 'useRef'];
|
|
45
|
+
|
|
46
|
+
function word() {
|
|
47
|
+
return WORDS[rand(WORDS.length)];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function card(i) {
|
|
51
|
+
const a = word();
|
|
52
|
+
const b = word();
|
|
53
|
+
const hook = HOOKS[rand(HOOKS.length)];
|
|
54
|
+
const lines = [`function Card${i}({ items, active, onSelect }) {`];
|
|
55
|
+
switch (hook) {
|
|
56
|
+
case 'useState':
|
|
57
|
+
lines.push(` const [open, setOpen] = useState(false);`);
|
|
58
|
+
break;
|
|
59
|
+
case 'useReducer':
|
|
60
|
+
lines.push(` const [open, toggle] = useReducer((state) => !state, false);`);
|
|
61
|
+
break;
|
|
62
|
+
default:
|
|
63
|
+
lines.push(` const ref = useRef(null);`);
|
|
64
|
+
}
|
|
65
|
+
lines.push(` const total = items.reduce((sum, item) => sum + item.price, 0);`);
|
|
66
|
+
lines.push(` const visible = items.filter((item) => item.status === active && item.title.includes('${a}'));`);
|
|
67
|
+
if (hook !== 'useRef') {
|
|
68
|
+
lines.push(` if (items.length === 0) {`, ` return <p className="empty">No ${a} items</p>;`, ` }`);
|
|
69
|
+
}
|
|
70
|
+
lines.push(` return (`);
|
|
71
|
+
lines.push(` <section className={open ? "card open" : "card"} ref=${hook === 'useRef' ? '{ref}' : '{undefined}'}>`);
|
|
72
|
+
lines.push(` <h2 onClick=${hook === 'useReducer' ? '{toggle}' : '{() => setOpen(!open)}'}>{total}</h2>`);
|
|
73
|
+
lines.push(` <ul>`);
|
|
74
|
+
lines.push(` {visible.map((item) => (`);
|
|
75
|
+
lines.push(` <li key={item.id} className={item.status} onClick={() => onSelect(item.id)}>`);
|
|
76
|
+
lines.push(` {item.title} ({item.${b}})`);
|
|
77
|
+
lines.push(` </li>`);
|
|
78
|
+
lines.push(` ))}`);
|
|
79
|
+
lines.push(` </ul>`);
|
|
80
|
+
lines.push(` <footer>{visible.length} of {items.length} ${a} items</footer>`);
|
|
81
|
+
lines.push(` </section>`);
|
|
82
|
+
lines.push(` );`);
|
|
83
|
+
lines.push(`}`);
|
|
84
|
+
return lines.join('\n');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function source(bytes) {
|
|
88
|
+
const out = [`import { useReducer, useRef, useState } from 'react';`, ''];
|
|
89
|
+
let size = 0;
|
|
90
|
+
for (let i = 0; size < bytes; i++) {
|
|
91
|
+
const c = card(i);
|
|
92
|
+
out.push(c);
|
|
93
|
+
size += c.length + 1;
|
|
94
|
+
}
|
|
95
|
+
out.push('export default Card0;', '');
|
|
96
|
+
return out.join('\n');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function stats(samples) {
|
|
100
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
101
|
+
const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
|
|
102
|
+
return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function fmt(ms) {
|
|
106
|
+
return `${ms.toFixed(2)} ms`.padStart(13);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function runOnce(command, args) {
|
|
110
|
+
const t0 = performance.now();
|
|
111
|
+
const result = spawnSync(command, args, { cwd: here, maxBuffer: 1 << 30 });
|
|
112
|
+
const elapsed = performance.now() - t0;
|
|
113
|
+
if (result.status !== 0) {
|
|
114
|
+
console.error(`run failed: ${command} ${args.join(' ')}\n${result.stdout}\n${result.stderr}`);
|
|
115
|
+
process.exit(1);
|
|
116
|
+
}
|
|
117
|
+
return { elapsed, stdout: result.stdout };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Alternating Node and native runs; the two outputs must match
|
|
121
|
+
function timeBoth(args, count) {
|
|
122
|
+
const node = [];
|
|
123
|
+
const native = [];
|
|
124
|
+
for (let i = 0; i < count; i++) {
|
|
125
|
+
const a = runOnce(process.execPath, ['run-node.mjs', ...args]);
|
|
126
|
+
const b = runOnce(exePath, args);
|
|
127
|
+
if (!a.stdout.equals(b.stdout)) {
|
|
128
|
+
console.error('Node and native output differ');
|
|
129
|
+
process.exit(1);
|
|
130
|
+
}
|
|
131
|
+
if (a.stdout.toString().startsWith('// compile error:')) {
|
|
132
|
+
console.error(`the source has errors:\n${a.stdout.toString().slice(0, 2000)}`);
|
|
133
|
+
process.exit(1);
|
|
134
|
+
}
|
|
135
|
+
node.push(a.elapsed);
|
|
136
|
+
native.push(b.elapsed);
|
|
137
|
+
}
|
|
138
|
+
return [stats(node), stats(native)];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function table(nodeStats, nativeStats) {
|
|
142
|
+
console.log('| Runtime | min | median | mean | max |');
|
|
143
|
+
console.log('|------------|--------------|--------------|--------------|--------------|');
|
|
144
|
+
console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |`);
|
|
145
|
+
console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 1. Compile the CLI to a native binary.
|
|
149
|
+
fs.mkdirSync(cache, { recursive: true });
|
|
150
|
+
console.log('Compiling main.ts to a native binary with TypeNative...');
|
|
151
|
+
const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', exePath], { cwd: here, stdio: 'inherit' });
|
|
152
|
+
if (build.status !== 0) process.exit(build.status ?? 1);
|
|
153
|
+
console.log(`Binary: ${(fs.statSync(exePath).size / (1024 * 1024)).toFixed(1)} MB`);
|
|
154
|
+
|
|
155
|
+
// 2. Warm the Node cache (run-node.mjs compiles main.ts to .cache/node once).
|
|
156
|
+
const warm = runOnce(process.execPath, ['run-node.mjs']);
|
|
157
|
+
if (warm.stdout.toString().startsWith('// compile error:')) {
|
|
158
|
+
console.error(`the demo has errors:\n${warm.stdout.toString().slice(0, 2000)}`);
|
|
159
|
+
process.exit(1);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 3. Per-call latency on the demo.
|
|
163
|
+
console.log(`\n(a) \`react-compile\` (built-in demo), ${runs} runs each (full process: spawn -> exit):\n`);
|
|
164
|
+
const [nodeCall, nativeCall] = timeBoth([], runs);
|
|
165
|
+
table(nodeCall, nativeCall);
|
|
166
|
+
const ratio = nodeCall.median / nativeCall.median;
|
|
167
|
+
console.log(`\nTypeNative is ${(ratio >= 1 ? `${ratio.toFixed(1)}x faster` : `${(1 / ratio).toFixed(1)}x slower`)} per call (median).`);
|
|
168
|
+
|
|
169
|
+
// 4. Scaling on generated component files.
|
|
170
|
+
console.log(`\n(b) \`react-compile generated-screen.jsx\`, ${sizeRuns} runs per size (medians):\n`);
|
|
171
|
+
console.log('| Source | Node.js | TypeNative | TypeNative vs Node |');
|
|
172
|
+
console.log('|-------------------|--------------|--------------|--------------------|');
|
|
173
|
+
for (const size of sizes) {
|
|
174
|
+
seed = 42;
|
|
175
|
+
const big = source(size * 1024);
|
|
176
|
+
fs.writeFileSync(bigPath, big);
|
|
177
|
+
const [nodeBig, nativeBig] = timeBoth([bigPath], sizeRuns);
|
|
178
|
+
const ratioBig = nodeBig.median / nativeBig.median;
|
|
179
|
+
const label = `${(big.length / 1024).toFixed(0)} KB, ${big.split('\n').length} lines`.padEnd(17);
|
|
180
|
+
console.log(`| ${label} |${fmt(nodeBig.median)} |${fmt(nativeBig.median)} | ${(ratioBig >= 1 ? `${ratioBig.toFixed(1)}x faster` : `${(1 / ratioBig).toFixed(1)}x slower`).padEnd(18)} |`);
|
|
181
|
+
}
|