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,324 @@
|
|
|
1
|
+
// React Compiler, natively: the vendored babel-plugin-react-compiler source
|
|
2
|
+
// compiles React components and hooks to their auto-memoized form, the way
|
|
3
|
+
// the Babel plugin does, on the vendored Babel parser, traverse and generator
|
|
4
|
+
// (no @babel/core). The output is the same as running this file under Node.
|
|
5
|
+
//
|
|
6
|
+
// node run-node.mjs [file.jsx]
|
|
7
|
+
// typenative --source main.ts --output react-compile && ./react-compile [file.jsx]
|
|
8
|
+
//
|
|
9
|
+
// The first line of the input can carry the compiler's test pragmas, as in
|
|
10
|
+
// the compiler's own fixtures: `// @compilationMode:"infer" @enableJsxOutlining`.
|
|
11
|
+
|
|
12
|
+
import * as fs from 'node:fs';
|
|
13
|
+
import * as nodePath from 'node:path';
|
|
14
|
+
import * as nodeOs from 'node:os';
|
|
15
|
+
import { spawn } from 'node:child_process';
|
|
16
|
+
import { parse, type ParserPlugin } from './vendor/babel/parser/src/index.ts';
|
|
17
|
+
import traverse, { type NodePath } from './vendor/babel/traverse/src/index.ts';
|
|
18
|
+
import generate from './vendor/babel/generator/src/index.ts';
|
|
19
|
+
import type * as t from './vendor/babel/types/src/index.ts';
|
|
20
|
+
import { CompilerError } from './vendor/react-compiler/src/CompilerError.ts';
|
|
21
|
+
import {
|
|
22
|
+
compileProgram,
|
|
23
|
+
type LoggerEvent,
|
|
24
|
+
type PluginOptions,
|
|
25
|
+
} from './vendor/react-compiler/src/Entrypoint/index.ts';
|
|
26
|
+
import { parseConfigPragmaForTests } from './vendor/react-compiler/src/Utils/TestUtils.ts';
|
|
27
|
+
|
|
28
|
+
const DEMO = `// @compilationMode:"infer"
|
|
29
|
+
import { useState } from 'react';
|
|
30
|
+
|
|
31
|
+
export function TodoList({ todos, filter, onToggle }) {
|
|
32
|
+
const [query, setQuery] = useState('');
|
|
33
|
+
const visible = todos.filter(
|
|
34
|
+
(todo) => (filter === 'all' || todo.status === filter) && todo.title.includes(query),
|
|
35
|
+
);
|
|
36
|
+
const remaining = todos.filter((todo) => todo.status !== 'done').length;
|
|
37
|
+
|
|
38
|
+
if (todos.length === 0) {
|
|
39
|
+
return <p className="empty">Nothing to do</p>;
|
|
40
|
+
}
|
|
41
|
+
return (
|
|
42
|
+
<section>
|
|
43
|
+
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
|
|
44
|
+
<ul>
|
|
45
|
+
{visible.map((todo) => (
|
|
46
|
+
<li key={todo.id} className={todo.status} onClick={() => onToggle(todo.id)}>
|
|
47
|
+
{todo.title}
|
|
48
|
+
</li>
|
|
49
|
+
))}
|
|
50
|
+
</ul>
|
|
51
|
+
<footer>{remaining} of {todos.length} left</footer>
|
|
52
|
+
</section>
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function useTotal(items, taxRate) {
|
|
57
|
+
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
|
58
|
+
const tax = subtotal * taxRate;
|
|
59
|
+
return { subtotal, tax, total: subtotal + tax };
|
|
60
|
+
}
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
function position(loc: t.SourceLocation | null | undefined): string {
|
|
64
|
+
return loc ? `${loc.start.line}:${loc.start.column}` : '?';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A logger event as a comment line (the first line of an error's text: a
|
|
68
|
+
// pipeline error carries its stack, which differs between runtimes)
|
|
69
|
+
function describe(event: LoggerEvent): string {
|
|
70
|
+
switch (event.kind) {
|
|
71
|
+
case 'CompileSuccess':
|
|
72
|
+
return (
|
|
73
|
+
`// CompileSuccess ${event.fnName ?? '(anonymous)'} at ${position(event.fnLoc)}: ` +
|
|
74
|
+
`${event.memoSlots} slots, ${event.memoBlocks} blocks, ${event.memoValues} values, ` +
|
|
75
|
+
`${event.prunedMemoBlocks} pruned blocks, ${event.prunedMemoValues} pruned values`
|
|
76
|
+
);
|
|
77
|
+
case 'CompileError': {
|
|
78
|
+
const description = event.detail.description ? `. ${event.detail.description}` : '';
|
|
79
|
+
return `// CompileError at ${position(event.detail.loc ?? event.fnLoc)}: [${event.detail.category}] ${event.detail.reason}${description}`;
|
|
80
|
+
}
|
|
81
|
+
case 'CompileDiagnostic':
|
|
82
|
+
return `// CompileDiagnostic at ${position(event.fnLoc)}: [${event.detail.category}] ${event.detail.reason}`;
|
|
83
|
+
case 'CompileSkip':
|
|
84
|
+
return `// CompileSkip at ${position(event.fnLoc)}: ${event.reason}`;
|
|
85
|
+
case 'PipelineError':
|
|
86
|
+
case 'CompileUnexpectedThrow':
|
|
87
|
+
return `// ${event.kind} at ${position(event.fnLoc)}: ${event.data.split('\n')[0]}`;
|
|
88
|
+
case 'Timing':
|
|
89
|
+
return '// Timing';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function compile(source: string, filename: string): string {
|
|
94
|
+
const { code, events } = compileParts(source, filename);
|
|
95
|
+
return [code, ...events].join('\n');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function compileParts(source: string, filename: string): { code: string; events: string[] } {
|
|
99
|
+
const firstLine = source.substring(0, source.indexOf('\n'));
|
|
100
|
+
const flow = firstLine.includes('@flow');
|
|
101
|
+
const plugins: ParserPlugin[] = flow
|
|
102
|
+
? ['flow', 'jsx']
|
|
103
|
+
: ['typescript', 'jsx', 'explicitResourceManagement'];
|
|
104
|
+
const ast = parse(source, {
|
|
105
|
+
sourceFilename: filename,
|
|
106
|
+
sourceType: firstLine.includes('@script') ? 'script' : 'module',
|
|
107
|
+
plugins,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// The options the compiler's fixture runner (snap) uses
|
|
111
|
+
const events: LoggerEvent[] = [];
|
|
112
|
+
const config = parseConfigPragmaForTests(firstLine, { compilationMode: 'all' });
|
|
113
|
+
const opts: PluginOptions = {
|
|
114
|
+
...config,
|
|
115
|
+
environment: {
|
|
116
|
+
...config.environment,
|
|
117
|
+
assertValidMutableRanges: true,
|
|
118
|
+
validatePreserveExistingMemoizationGuarantees: firstLine.includes(
|
|
119
|
+
'@validatePreserveExistingMemoizationGuarantees',
|
|
120
|
+
),
|
|
121
|
+
},
|
|
122
|
+
logger: {
|
|
123
|
+
logEvent: (_filename: string | null, event: LoggerEvent): void => {
|
|
124
|
+
events.push(event);
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
enableReanimatedCheck: false,
|
|
128
|
+
target: '19',
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
traverse(ast, {
|
|
132
|
+
Program(program: NodePath<t.Program>) {
|
|
133
|
+
compileProgram(program, {
|
|
134
|
+
opts,
|
|
135
|
+
filename,
|
|
136
|
+
comments: ast.comments ?? [],
|
|
137
|
+
code: source,
|
|
138
|
+
});
|
|
139
|
+
program.skip();
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const code = generate(ast, {}, source).code;
|
|
144
|
+
return { code, events: events.map(describe) };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Large files of independent top-level functions: a worker process compiles
|
|
148
|
+
// each contiguous run of functions, and the parent joins their output. The
|
|
149
|
+
// per-function output is independent, and each chunk is padded so source
|
|
150
|
+
// positions (the // CompileSuccess lines) stay the ones of the whole file.
|
|
151
|
+
// Under Node each worker re-imports the compiler (expensive); TypeNative's
|
|
152
|
+
// workers start from the compiled binary. TN_PARALLEL=0 disables it.
|
|
153
|
+
const MAX_WORKERS = 6;
|
|
154
|
+
const MIN_FUNCTIONS = 8;
|
|
155
|
+
|
|
156
|
+
type Chunk = { first: string; text: string };
|
|
157
|
+
|
|
158
|
+
function splitSource(source: string): Chunk[] | undefined {
|
|
159
|
+
// (compiler temps are renamed per chunk; a source using such a name keeps
|
|
160
|
+
// the single-process path)
|
|
161
|
+
if (/\b_temp\d*\b/.test(source)) return undefined;
|
|
162
|
+
const lines = source.split('\n');
|
|
163
|
+
const starts: { name: string; line: number }[] = [];
|
|
164
|
+
for (let i = 0; i < lines.length; i++) {
|
|
165
|
+
const match = /^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/.exec(lines[i]);
|
|
166
|
+
if (match) starts.push({ name: match[1], line: i });
|
|
167
|
+
}
|
|
168
|
+
if (starts.length < MIN_FUNCTIONS) return undefined;
|
|
169
|
+
// (the header must be imports / comments only: the chunks share it)
|
|
170
|
+
const header = lines.slice(0, starts[0].line);
|
|
171
|
+
if (header.some((l) => l.trim() !== '' && !/^(import\b|\/\/|\/\*|\*|'use |"use )/.test(l.trim()))) return undefined;
|
|
172
|
+
// (each function runs to the line before the next one; brace-counted, so
|
|
173
|
+
// templates and strings with braces could fool it — then no parallelism)
|
|
174
|
+
const ranges: { name: string; start: number; end: number }[] = [];
|
|
175
|
+
for (let i = 0; i < starts.length; i++) {
|
|
176
|
+
const start = starts[i].line;
|
|
177
|
+
const limit = i + 1 < starts.length ? starts[i + 1].line : lines.length;
|
|
178
|
+
let depth = 0;
|
|
179
|
+
let end = -1;
|
|
180
|
+
for (let j = start; j < limit; j++) {
|
|
181
|
+
for (const ch of lines[j]) {
|
|
182
|
+
if (ch === '{') depth++;
|
|
183
|
+
else if (ch === '}') depth--;
|
|
184
|
+
}
|
|
185
|
+
if (depth === 0 && j > start) { end = j; break; }
|
|
186
|
+
}
|
|
187
|
+
if (end < 0 || !/^\}/.test(lines[end])) return undefined;
|
|
188
|
+
// (only functions are split: anything else between them — variables,
|
|
189
|
+
// statements — would be dropped, so such a file compiles in one process)
|
|
190
|
+
if (i + 1 < starts.length) {
|
|
191
|
+
for (let j = end + 1; j < starts[i + 1].line; j++) {
|
|
192
|
+
const text = lines[j].trim();
|
|
193
|
+
if (text !== '' && !/^(\/\/|\/\*|\*)/.test(text)) return undefined;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
ranges.push({ name: starts[i].name, start, end });
|
|
197
|
+
}
|
|
198
|
+
const workers = Math.min(MAX_WORKERS, Math.ceil(ranges.length / 10));
|
|
199
|
+
// (one worker would only add a process start: compile in this one)
|
|
200
|
+
if (workers < 2) return undefined;
|
|
201
|
+
const chunks: Chunk[] = [];
|
|
202
|
+
const per = Math.ceil(ranges.length / workers);
|
|
203
|
+
for (let i = 0; i < ranges.length; i += per) {
|
|
204
|
+
const group = ranges.slice(i, i + per);
|
|
205
|
+
const firstStart = group[0].start;
|
|
206
|
+
const padding = Math.max(0, firstStart - header.length);
|
|
207
|
+
const pad: string[] = [];
|
|
208
|
+
for (let k = 0; k < padding; k++) pad.push('');
|
|
209
|
+
const body = lines.slice(firstStart, group[group.length - 1].end + 1);
|
|
210
|
+
// the last chunk carries the rest of the file (export default …)
|
|
211
|
+
const tail = i + per >= ranges.length ? lines.slice(group[group.length - 1].end + 1) : [];
|
|
212
|
+
chunks.push({
|
|
213
|
+
first: group[0].name,
|
|
214
|
+
text: [...header, ...pad, ...body, ...tail].join('\n'),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
return chunks;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function runWorkerProcess(chunkFile: string): Promise<string> {
|
|
221
|
+
return new Promise((resolve, reject) => {
|
|
222
|
+
const nodeMain = process.env.TN_NODE_MAIN;
|
|
223
|
+
const args = nodeMain ? [nodeMain, chunkFile, '--worker'] : [chunkFile, '--worker'];
|
|
224
|
+
const child = spawn(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
225
|
+
let out = '';
|
|
226
|
+
let err = '';
|
|
227
|
+
child.stdout?.on('data', (data: unknown) => (out += String(data)));
|
|
228
|
+
child.stderr?.on('data', (data: unknown) => (err += String(data)));
|
|
229
|
+
child.on('error', (e: unknown) => {
|
|
230
|
+
reject(e);
|
|
231
|
+
});
|
|
232
|
+
child.on('close', (code: number | null) => {
|
|
233
|
+
if (code === 0) {
|
|
234
|
+
resolve(out);
|
|
235
|
+
} else {
|
|
236
|
+
reject(new Error(err || `worker exited with ${code}`));
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function parallelCompile(source: string, filename: string, chunks: Chunk[]): Promise<string> {
|
|
243
|
+
const dir = fs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), 'tn-react-compile-'));
|
|
244
|
+
try {
|
|
245
|
+
const files: string[] = [];
|
|
246
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
247
|
+
const file = nodePath.join(dir, `chunk${i}.jsx`);
|
|
248
|
+
fs.writeFileSync(file, chunks[i].text);
|
|
249
|
+
files.push(file);
|
|
250
|
+
}
|
|
251
|
+
const outputs: string[] = await Promise.all(files.map(runWorkerProcess));
|
|
252
|
+
const codes: string[] = [];
|
|
253
|
+
const events: string[] = [];
|
|
254
|
+
for (const text of outputs) {
|
|
255
|
+
const part = JSON.parse(text) as { code: string; events: string[] };
|
|
256
|
+
codes.push(part.code);
|
|
257
|
+
for (const event of part.events) events.push(event);
|
|
258
|
+
}
|
|
259
|
+
let prefix = '';
|
|
260
|
+
const sections: string[] = [];
|
|
261
|
+
let needsMemoCache = false;
|
|
262
|
+
for (let i = 0; i < codes.length; i++) {
|
|
263
|
+
const marker = `function ${chunks[i].first}(`;
|
|
264
|
+
const at = codes[i].indexOf(marker);
|
|
265
|
+
if (at < 0) throw new Error(`chunk ${i}: ${marker} not found`);
|
|
266
|
+
if (i === 0) prefix = codes[i].slice(0, at);
|
|
267
|
+
if (codes[i].includes('react/compiler-runtime')) needsMemoCache = true;
|
|
268
|
+
// (each chunk numbers its generated _temp functions from 0: keep them
|
|
269
|
+
// apart across the merged program)
|
|
270
|
+
const section = codes[i].slice(at).replace(/\b_temp(\d*)\b/g, (_m, n: string) => `_temp${n}__tn${i}`).trimEnd();
|
|
271
|
+
sections.push(section);
|
|
272
|
+
}
|
|
273
|
+
// (chunk 0 may not need the memo cache import when a later one does)
|
|
274
|
+
if (needsMemoCache && !prefix.includes('react/compiler-runtime')) {
|
|
275
|
+
prefix = `import { c as _c } from "react/compiler-runtime";\n${prefix}`;
|
|
276
|
+
}
|
|
277
|
+
return [prefix + sections.join('\n'), ...events].join('\n');
|
|
278
|
+
} finally {
|
|
279
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const workerMode = process.argv.includes('--worker');
|
|
284
|
+
const fileArgs = process.argv.slice(1).filter((a) => !a.startsWith('--'));
|
|
285
|
+
const file = workerMode ? fileArgs[fileArgs.length - 1] : process.argv[2];
|
|
286
|
+
const source = file ? fs.readFileSync(file, 'utf-8') : DEMO;
|
|
287
|
+
const filename = file ?? 'demo.jsx';
|
|
288
|
+
|
|
289
|
+
function printError(e: unknown): void {
|
|
290
|
+
// (an error the compiler or the parser throws, as a comment: the same
|
|
291
|
+
// under both runtimes)
|
|
292
|
+
const message = e instanceof CompilerError ? e.withPrintedMessage(source, { eslint: false }).message : (e as Error).message;
|
|
293
|
+
console.log(`// compile error: ${message}`);
|
|
294
|
+
// TN_DEBUG_ERRORS=1 surfaces the thrown value and its stack (a pass
|
|
295
|
+
// failure whose message is empty prints as `undefined` otherwise)
|
|
296
|
+
if (process.env.TN_DEBUG_ERRORS) {
|
|
297
|
+
console.log(`// debug: typeof=${typeof e} string=${String(e)}`);
|
|
298
|
+
const stack = (e as Error)?.stack;
|
|
299
|
+
if (stack) console.log(stack);
|
|
300
|
+
}
|
|
301
|
+
process.exitCode = 1;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (workerMode) {
|
|
305
|
+
try {
|
|
306
|
+
console.log(JSON.stringify(compileParts(source, filename)));
|
|
307
|
+
} catch (e) {
|
|
308
|
+
printError(e);
|
|
309
|
+
}
|
|
310
|
+
} else {
|
|
311
|
+
try {
|
|
312
|
+
// (a worker re-runs this module; under Node it needs the module's path)
|
|
313
|
+
const nodeRuntime = !process.env.TN_NODE_MAIN && /(^|[\\/])node(\.exe)?$/i.test(process.execPath);
|
|
314
|
+
const chunks = process.env.TN_PARALLEL === '0' || nodeRuntime ? undefined : splitSource(source);
|
|
315
|
+
console.log(chunks ? await parallelCompile(source, filename, chunks) : compile(source, filename));
|
|
316
|
+
} catch {
|
|
317
|
+
// (a worker failed: the whole file, compiled in this process)
|
|
318
|
+
try {
|
|
319
|
+
console.log(compile(source, filename));
|
|
320
|
+
} catch (e) {
|
|
321
|
+
printError(e);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
// Parity check: Node.js vs the TypeNative build of the React Compiler.
|
|
2
|
+
//
|
|
3
|
+
// Compiles main.ts to a native binary with the TypeNative CLI from this repo
|
|
4
|
+
// checkout, then runs the vendored React Compiler over each fixture below with
|
|
5
|
+
// both runtimes. stdout, stderr and the exit code must match byte for byte —
|
|
6
|
+
// including the `// CompileSuccess`/`// CompileError` lines the compiler's
|
|
7
|
+
// logger produces, so memo slot and block counts are checked too. Failures are
|
|
8
|
+
// written to .cache/failures/.
|
|
9
|
+
//
|
|
10
|
+
// The fixtures mirror what the compiler's own test fixtures cover: components
|
|
11
|
+
// and hooks, the compiler's test pragmas on the first line, JSX with
|
|
12
|
+
// conditionals, lists and event handlers, and the error paths (a compile
|
|
13
|
+
// error, a skipped function, an unparseable file).
|
|
14
|
+
//
|
|
15
|
+
// Usage: node parity.mjs [filter] (filter: a substring of a fixture name)
|
|
16
|
+
|
|
17
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import os from 'node:os';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
|
|
23
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
const repoRoot = path.resolve(here, '..', '..');
|
|
25
|
+
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
26
|
+
const cache = path.join(here, '.cache');
|
|
27
|
+
const fixturesDir = path.join(cache, 'fixtures');
|
|
28
|
+
const failuresDir = path.join(cache, 'failures');
|
|
29
|
+
const exePath = path.join(cache, process.platform === 'win32' ? 'react-compile.exe' : 'react-compile');
|
|
30
|
+
const filter = process.argv[2] ?? '';
|
|
31
|
+
|
|
32
|
+
function run(command, args, options = {}) {
|
|
33
|
+
const result = spawnSync(command, args, { stdio: 'inherit', ...options });
|
|
34
|
+
if (result.status !== 0) {
|
|
35
|
+
console.error(`${command} ${args.join(' ')} failed`);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A component with hooks, a derived list, conditionals and event handlers,
|
|
41
|
+
// the shape of a real screen
|
|
42
|
+
const todoList = `// @compilationMode:"infer"
|
|
43
|
+
import { useState } from 'react';
|
|
44
|
+
|
|
45
|
+
export function TodoList({ todos, filter, onToggle }) {
|
|
46
|
+
const [query, setQuery] = useState('');
|
|
47
|
+
const visible = todos.filter(
|
|
48
|
+
(todo) => (filter === 'all' || todo.status === filter) && todo.title.includes(query),
|
|
49
|
+
);
|
|
50
|
+
const remaining = todos.filter((todo) => todo.status !== 'done').length;
|
|
51
|
+
|
|
52
|
+
if (todos.length === 0) {
|
|
53
|
+
return <p className="empty">Nothing to do</p>;
|
|
54
|
+
}
|
|
55
|
+
return (
|
|
56
|
+
<section>
|
|
57
|
+
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
|
|
58
|
+
<ul>
|
|
59
|
+
{visible.map((todo) => (
|
|
60
|
+
<li key={todo.id} className={todo.status} onClick={() => onToggle(todo.id)}>
|
|
61
|
+
{todo.title}
|
|
62
|
+
</li>
|
|
63
|
+
))}
|
|
64
|
+
</ul>
|
|
65
|
+
<footer>{remaining} of {todos.length} left</footer>
|
|
66
|
+
</section>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function useTotal(items, taxRate) {
|
|
71
|
+
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
|
|
72
|
+
const tax = subtotal * taxRate;
|
|
73
|
+
return { subtotal, tax, total: subtotal + tax };
|
|
74
|
+
}
|
|
75
|
+
`;
|
|
76
|
+
|
|
77
|
+
const FIXTURES = {
|
|
78
|
+
// The example's built-in demo (infer mode: only components and hooks)
|
|
79
|
+
'demo-infer': todoList,
|
|
80
|
+
// All mode: plain functions compile too (memo slots on every function)
|
|
81
|
+
'mode-all': `import { useState } from 'react';
|
|
82
|
+
|
|
83
|
+
export function Component({ label }) {
|
|
84
|
+
const [count, setCount] = useState(0);
|
|
85
|
+
return (
|
|
86
|
+
<button onClick={() => setCount(count + 1)}>
|
|
87
|
+
{label}: {count}
|
|
88
|
+
</button>
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function helper(values) {
|
|
93
|
+
return values.map((v) => v * 2).join(',');
|
|
94
|
+
}
|
|
95
|
+
`,
|
|
96
|
+
// Annotation mode: only "use memo" functions compile, others are skipped
|
|
97
|
+
'mode-annotation': `// @compilationMode:"annotation"
|
|
98
|
+
export function Component({ items }) {
|
|
99
|
+
"use memo";
|
|
100
|
+
return <ul>{items.map((item) => <li key={item.id}>{item.title}</li>)}</ul>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function Skipped({ items }) {
|
|
104
|
+
return <ul>{items.map((item) => <li key={item.id}>{item.title}</li>)}</ul>;
|
|
105
|
+
}
|
|
106
|
+
`,
|
|
107
|
+
// JSX outlining: large JSX subtrees are extracted into their own functions
|
|
108
|
+
'jsx-outlining': `// @enableJsxOutlining
|
|
109
|
+
export function Dashboard({ user, stats, onRefresh }) {
|
|
110
|
+
const unread = stats.filter((s) => !s.read).length;
|
|
111
|
+
return (
|
|
112
|
+
<div className="dashboard">
|
|
113
|
+
<header>
|
|
114
|
+
<h1>Welcome back, {user.name}</h1>
|
|
115
|
+
<span className={unread > 0 ? 'badge active' : 'badge'}>{unread} unread</span>
|
|
116
|
+
<button onClick={() => onRefresh()}>Refresh</button>
|
|
117
|
+
</header>
|
|
118
|
+
<main>
|
|
119
|
+
{stats.map((stat) => (
|
|
120
|
+
<div key={stat.id} className="stat">
|
|
121
|
+
<h3>{stat.title}</h3>
|
|
122
|
+
<p>{stat.value}</p>
|
|
123
|
+
</div>
|
|
124
|
+
))}
|
|
125
|
+
</main>
|
|
126
|
+
<footer>{user.email}</footer>
|
|
127
|
+
</div>
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
`,
|
|
131
|
+
// Hooks through a custom hook, mutable refs, effects
|
|
132
|
+
'hooks-and-refs': `import { useEffect, useRef, useState } from 'react';
|
|
133
|
+
|
|
134
|
+
export function useCounter(start) {
|
|
135
|
+
const [count, setCount] = useState(start);
|
|
136
|
+
const increment = () => setCount((c) => c + 1);
|
|
137
|
+
const reset = () => setCount(start);
|
|
138
|
+
return { count, increment, reset };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function Stopwatch({ running }) {
|
|
142
|
+
const { count, increment, reset } = useCounter(0);
|
|
143
|
+
const last = useRef(null);
|
|
144
|
+
useEffect(() => {
|
|
145
|
+
last.current = count;
|
|
146
|
+
}, [count]);
|
|
147
|
+
return (
|
|
148
|
+
<p onClick={increment} onDoubleClick={reset}>
|
|
149
|
+
{count} (was {last.current})
|
|
150
|
+
</p>
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
`,
|
|
154
|
+
// Control flow: nested conditionals, ternaries, fragments, void tags
|
|
155
|
+
'control-flow': `export function Panel({ open, kind, children }) {
|
|
156
|
+
if (!open) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
return (
|
|
160
|
+
<>
|
|
161
|
+
<div className={kind === 'error' ? 'panel error' : 'panel'}>
|
|
162
|
+
{kind === 'error' ? <strong>Something went wrong</strong> : <span>Info</span>}
|
|
163
|
+
{children}
|
|
164
|
+
<br />
|
|
165
|
+
<hr />
|
|
166
|
+
</div>
|
|
167
|
+
<img src="x.png" alt="an image" />
|
|
168
|
+
</>
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
`,
|
|
172
|
+
// Values captured by closures stay reactive; destructuring in parameters
|
|
173
|
+
'closures-and-destructuring': `import { useMemo, useState } from 'react';
|
|
174
|
+
|
|
175
|
+
export function SortableList({ entries, compare }) {
|
|
176
|
+
const [key, setKey] = useState('name');
|
|
177
|
+
const [reverse, setReverse] = useState(false);
|
|
178
|
+
const sorted = useMemo(() => {
|
|
179
|
+
const copy = [...entries];
|
|
180
|
+
copy.sort((a, b) => (a[key] < b[key] ? -1 : 1));
|
|
181
|
+
if (reverse) copy.reverse();
|
|
182
|
+
return copy;
|
|
183
|
+
}, [entries, key, reverse]);
|
|
184
|
+
return (
|
|
185
|
+
<ol data-key={key}>
|
|
186
|
+
{sorted.map(({ id, name }) => (
|
|
187
|
+
<li key={id} onClick={() => setKey(name)}>
|
|
188
|
+
{name}
|
|
189
|
+
</li>
|
|
190
|
+
))}
|
|
191
|
+
<li onClick={() => setReverse(!reverse)}>reverse</li>
|
|
192
|
+
</ol>
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
`,
|
|
196
|
+
// "use no memo": the compiler skips the function and logs why
|
|
197
|
+
'skip-use-no-memo': `export function Unmemoized({ text }) {
|
|
198
|
+
"use no memo";
|
|
199
|
+
return <p>{text}</p>;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function Memoized({ text }) {
|
|
203
|
+
return <p>{text}</p>;
|
|
204
|
+
}
|
|
205
|
+
`,
|
|
206
|
+
// A compile error: hooks cannot run conditionally
|
|
207
|
+
'error-conditional-hook': `import { useState } from 'react';
|
|
208
|
+
|
|
209
|
+
export function Component({ enabled }) {
|
|
210
|
+
if (enabled) {
|
|
211
|
+
const [value, setValue] = useState(0);
|
|
212
|
+
return <button onClick={() => setValue(value + 1)}>{value}</button>;
|
|
213
|
+
}
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
`,
|
|
217
|
+
// A compile error: mutating props during render
|
|
218
|
+
'error-mutate-prop': `export function Component({ items }) {
|
|
219
|
+
items.sort((a, b) => a.id - b.id);
|
|
220
|
+
return items.map((item) => <li key={item.id}>{item.title}</li>);
|
|
221
|
+
}
|
|
222
|
+
`,
|
|
223
|
+
// A compile error: unknown hook-like call in a component
|
|
224
|
+
'error-unknown-hook': `import { useUnknown } from 'somewhere';
|
|
225
|
+
|
|
226
|
+
export function Component() {
|
|
227
|
+
const value = useUnknown();
|
|
228
|
+
return <p>{value}</p>;
|
|
229
|
+
}
|
|
230
|
+
`,
|
|
231
|
+
// A file the parser rejects: the error is printed as a comment, exit 1
|
|
232
|
+
'parse-error': `export function Broken({
|
|
233
|
+
return <div>never parsed</div>;
|
|
234
|
+
}
|
|
235
|
+
`,
|
|
236
|
+
// TypeScript source: the parser runs with the typescript plugin
|
|
237
|
+
'typescript-syntax': `import { useState } from 'react';
|
|
238
|
+
|
|
239
|
+
type Item = { id: number; title: string; done?: boolean };
|
|
240
|
+
|
|
241
|
+
export function Checklist({ initial }: { initial: Item[] }) {
|
|
242
|
+
const [items, setItems] = useState<Item[]>(initial);
|
|
243
|
+
const done = items.filter((item): item is Item & { done: true } => item.done === true).length;
|
|
244
|
+
return (
|
|
245
|
+
<ul>
|
|
246
|
+
{items.map((item) => (
|
|
247
|
+
<li key={item.id} onClick={() => setItems(items.map((i) => (i.id === item.id ? { ...i, done: !i.done } : i)))}>
|
|
248
|
+
{item.done ? '\\u2713' : '\\u25cb'} {item.title}
|
|
249
|
+
</li>
|
|
250
|
+
))}
|
|
251
|
+
<footer>{done}/{items.length} done</footer>
|
|
252
|
+
</ul>
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
`,
|
|
256
|
+
// Preserve existing memoization: manual useMemo/useCallback must survive
|
|
257
|
+
'validate-manual-memo': `// @validatePreserveExistingMemoizationGuarantees
|
|
258
|
+
import { useCallback, useMemo } from 'react';
|
|
259
|
+
|
|
260
|
+
export function Grid({ rows, cols, onSelect }) {
|
|
261
|
+
const cells = useMemo(() => {
|
|
262
|
+
const out = [];
|
|
263
|
+
for (const row of rows) {
|
|
264
|
+
for (const col of cols) {
|
|
265
|
+
out.push({ row, col });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return out;
|
|
269
|
+
}, [rows, cols]);
|
|
270
|
+
const select = useCallback((cell) => onSelect(cell.row, cell.col), [onSelect]);
|
|
271
|
+
return (
|
|
272
|
+
<table>
|
|
273
|
+
{cells.map((cell) => (
|
|
274
|
+
<td key={\`\${cell.row}:\${cell.col}\`} onClick={() => select(cell)}>
|
|
275
|
+
{cell.row} / {cell.col}
|
|
276
|
+
</td>
|
|
277
|
+
))}
|
|
278
|
+
</table>
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
`,
|
|
282
|
+
// State updates in effects and event handlers; optional chaining
|
|
283
|
+
'effects-and-optional-chains': `import { useEffect, useState } from 'react';
|
|
284
|
+
|
|
285
|
+
export function Ticker({ interval, onPause }) {
|
|
286
|
+
const [ticks, setTicks] = useState(0);
|
|
287
|
+
useEffect(() => {
|
|
288
|
+
if (interval == null) return;
|
|
289
|
+
const id = setInterval(() => setTicks((t) => t + 1), interval);
|
|
290
|
+
return () => clearInterval(id);
|
|
291
|
+
}, [interval]);
|
|
292
|
+
return (
|
|
293
|
+
<div>
|
|
294
|
+
<span>{ticks} ticks</span>
|
|
295
|
+
{onPause != null && <button onClick={() => onPause?.(ticks)}>Pause</button>}
|
|
296
|
+
</div>
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
`,
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
function spawnCollect(command, args) {
|
|
303
|
+
return new Promise((resolve) => {
|
|
304
|
+
const child = spawn(command, args, { cwd: here });
|
|
305
|
+
let stdout = '';
|
|
306
|
+
let stderr = '';
|
|
307
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 60_000);
|
|
308
|
+
child.stdout.on('data', (d) => (stdout += d));
|
|
309
|
+
child.stderr.on('data', (d) => (stderr += d));
|
|
310
|
+
child.on('close', (code, signal) => {
|
|
311
|
+
clearTimeout(timer);
|
|
312
|
+
resolve({ stdout, stderr, code: signal ? signal : code });
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const names = Object.keys(FIXTURES).filter((name) => name.includes(filter));
|
|
318
|
+
if (names.length === 0) {
|
|
319
|
+
console.error(`no fixtures match "${filter}"`);
|
|
320
|
+
process.exit(1);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
console.log('Compiling main.ts with TypeNative ...');
|
|
324
|
+
run(process.execPath, [cli, '--source', path.join(here, 'main.ts'), '--output', exePath], { cwd: repoRoot });
|
|
325
|
+
// (the Node build once, up front: fixtures run in parallel, and each
|
|
326
|
+
// run-node.mjs would otherwise rebuild a stale cache at the same time)
|
|
327
|
+
run(process.execPath, ['run-node.mjs', '--build'], { cwd: here });
|
|
328
|
+
|
|
329
|
+
fs.rmSync(failuresDir, { recursive: true, force: true });
|
|
330
|
+
fs.mkdirSync(failuresDir, { recursive: true });
|
|
331
|
+
fs.mkdirSync(fixturesDir, { recursive: true });
|
|
332
|
+
|
|
333
|
+
let passed = 0;
|
|
334
|
+
let next = 0;
|
|
335
|
+
const failed = [];
|
|
336
|
+
async function worker() {
|
|
337
|
+
while (next < names.length) {
|
|
338
|
+
const index = next++;
|
|
339
|
+
const name = names[index];
|
|
340
|
+
const file = path.join(fixturesDir, `${name}.jsx`);
|
|
341
|
+
fs.writeFileSync(file, FIXTURES[name]);
|
|
342
|
+
const [node, native] = await Promise.all([
|
|
343
|
+
spawnCollect(process.execPath, ['run-node.mjs', file]),
|
|
344
|
+
spawnCollect(exePath, [file])
|
|
345
|
+
]);
|
|
346
|
+
if (node.stdout === native.stdout && node.stderr === native.stderr && node.code === native.code) {
|
|
347
|
+
passed++;
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
failed.push(name);
|
|
351
|
+
const report = (label, r) => `--- ${label} (exit ${r.code})\n${r.stdout}${r.stderr ? `--- ${label} stderr\n${r.stderr}` : ''}`;
|
|
352
|
+
fs.writeFileSync(
|
|
353
|
+
path.join(failuresDir, `${index}-${name}.txt`),
|
|
354
|
+
`${name}\n--- source\n${FIXTURES[name]}\n${report('node', node)}${report('native', native)}`
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(8, os.availableParallelism() - 1)) }, worker));
|
|
359
|
+
|
|
360
|
+
for (const name of failed.sort()) console.log(`FAIL ${name}`);
|
|
361
|
+
console.log(`${passed}/${names.length} fixtures match (${((100 * passed) / Math.max(1, names.length)).toFixed(2)}%)`);
|
|
362
|
+
process.exitCode = failed.length > 0 ? 1 : 0;
|