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,157 +0,0 @@
|
|
|
1
|
-
// Parity check: Node.js vs the TypeNative build of the Angular template compiler.
|
|
2
|
-
//
|
|
3
|
-
// Fetches the component templates of Angular's own compiler compliance tests
|
|
4
|
-
// (packages/compiler-cli/test/compliance/test_cases, at a pinned commit) into
|
|
5
|
-
// .cache/, compiles main.ts to a native binary with the TypeNative CLI from
|
|
6
|
-
// this repo checkout, then compiles every template with both runtimes. stdout,
|
|
7
|
-
// stderr and the exit code must match byte for byte. Failures are written to
|
|
8
|
-
// .cache/failures/.
|
|
9
|
-
//
|
|
10
|
-
// The corpus: every external .html template, and every inline `template:`
|
|
11
|
-
// string literal (backtick strings with `${…}` substitutions and concatenated
|
|
12
|
-
// strings are left out: their text is only known when the test file runs).
|
|
13
|
-
//
|
|
14
|
-
// Usage: node parity.mjs [filter] (filter: a substring of a case id)
|
|
15
|
-
|
|
16
|
-
import { spawn, spawnSync } from 'node:child_process';
|
|
17
|
-
import fs from 'node:fs';
|
|
18
|
-
import os from 'node:os';
|
|
19
|
-
import path from 'node:path';
|
|
20
|
-
import { fileURLToPath } from 'node:url';
|
|
21
|
-
|
|
22
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
23
|
-
const repoRoot = path.resolve(here, '..', '..');
|
|
24
|
-
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
25
|
-
const cache = path.join(here, '.cache');
|
|
26
|
-
const upstream = path.join(cache, 'angular-src');
|
|
27
|
-
const COMMIT = '939171c6f92eb9e7401afa142a343aff4f3ff859';
|
|
28
|
-
const TEST_CASES = 'packages/compiler-cli/test/compliance/test_cases';
|
|
29
|
-
const casesDir = path.join(upstream, TEST_CASES);
|
|
30
|
-
const inputsDir = path.join(cache, 'templates');
|
|
31
|
-
const failuresDir = path.join(cache, 'failures');
|
|
32
|
-
const exePath = path.join(cache, process.platform === 'win32' ? 'ng-compile.exe' : 'ng-compile');
|
|
33
|
-
const filter = process.argv[2] ?? '';
|
|
34
|
-
|
|
35
|
-
function run(command, args, options = {}) {
|
|
36
|
-
const result = spawnSync(command, args, { stdio: 'inherit', ...options });
|
|
37
|
-
if (result.status !== 0) {
|
|
38
|
-
console.error(`${command} ${args.join(' ')} failed`);
|
|
39
|
-
process.exit(1);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// The compliance test cases at the pinned commit (a sparse, blobless fetch)
|
|
44
|
-
function fetchCases() {
|
|
45
|
-
if (fs.existsSync(casesDir)) return;
|
|
46
|
-
fs.mkdirSync(upstream, { recursive: true });
|
|
47
|
-
console.log(`Fetching angular/angular ${COMMIT.slice(0, 7)} ${TEST_CASES} ...`);
|
|
48
|
-
const git = (...args) => run('git', ['-C', upstream, ...args]);
|
|
49
|
-
git('init', '--quiet');
|
|
50
|
-
git('remote', 'add', 'origin', 'https://github.com/angular/angular.git');
|
|
51
|
-
git('sparse-checkout', 'set', TEST_CASES);
|
|
52
|
-
git('fetch', '--quiet', '--depth', '1', '--filter=blob:none', 'origin', COMMIT);
|
|
53
|
-
git('checkout', '--quiet', 'FETCH_HEAD');
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// A JS string literal's body with its escapes resolved
|
|
57
|
-
function unescape(body) {
|
|
58
|
-
return body.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|\r?\n|.)/g, (_, c) => {
|
|
59
|
-
if (c[0] === 'u') return String.fromCodePoint(parseInt(c[1] === '{' ? c.slice(2, -1) : c.slice(1), 16));
|
|
60
|
-
if (c[0] === 'x') return String.fromCharCode(parseInt(c.slice(1), 16));
|
|
61
|
-
if (c === '\n' || c === '\r\n') return '';
|
|
62
|
-
return { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' }[c] ?? c;
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// The `template:` string literals of a test file
|
|
67
|
-
function inlineTemplates(file) {
|
|
68
|
-
const src = fs.readFileSync(file, 'utf8');
|
|
69
|
-
const found = [];
|
|
70
|
-
const re = /\btemplate:\s*/g;
|
|
71
|
-
while (re.exec(src)) {
|
|
72
|
-
const start = re.lastIndex;
|
|
73
|
-
const quote = src[start];
|
|
74
|
-
if (quote !== '`' && quote !== "'" && quote !== '"') continue;
|
|
75
|
-
let end = start + 1;
|
|
76
|
-
let substitution = false;
|
|
77
|
-
while (end < src.length && src[end] !== quote) {
|
|
78
|
-
if (src[end] === '\\') end++;
|
|
79
|
-
else if (quote === '`' && src[end] === '$' && src[end + 1] === '{') substitution = true;
|
|
80
|
-
end++;
|
|
81
|
-
}
|
|
82
|
-
if (substitution || src.slice(end + 1).trimStart().startsWith('+')) continue;
|
|
83
|
-
found.push(unescape(src.slice(start + 1, end)));
|
|
84
|
-
}
|
|
85
|
-
return found;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function listCases() {
|
|
89
|
-
const cases = [];
|
|
90
|
-
const walk = (dir) => {
|
|
91
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
92
|
-
const file = path.join(dir, entry.name);
|
|
93
|
-
const id = path.relative(casesDir, file).split(path.sep).join('/');
|
|
94
|
-
if (entry.isDirectory()) walk(file);
|
|
95
|
-
else if (entry.name.endsWith('.html')) cases.push({ id, template: fs.readFileSync(file, 'utf8') });
|
|
96
|
-
else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') && !entry.name.includes('golden')) {
|
|
97
|
-
inlineTemplates(file).forEach((template, index) => cases.push({ id: `${id}#${index}`, template }));
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
walk(casesDir);
|
|
102
|
-
return cases;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function spawnCollect(command, args) {
|
|
106
|
-
return new Promise((resolve) => {
|
|
107
|
-
const child = spawn(command, args, { cwd: here });
|
|
108
|
-
let stdout = '';
|
|
109
|
-
let stderr = '';
|
|
110
|
-
const timer = setTimeout(() => child.kill('SIGKILL'), 60_000);
|
|
111
|
-
child.stdout.on('data', (d) => (stdout += d));
|
|
112
|
-
child.stderr.on('data', (d) => (stderr += d));
|
|
113
|
-
child.on('close', (code, signal) => {
|
|
114
|
-
clearTimeout(timer);
|
|
115
|
-
resolve({ stdout, stderr, code: signal ? signal : code });
|
|
116
|
-
});
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
fetchCases();
|
|
121
|
-
const cases = listCases().filter((c) => c.id.includes(filter));
|
|
122
|
-
console.log(`Compiling main.ts with TypeNative ...`);
|
|
123
|
-
run(process.execPath, [cli, '--source', path.join(here, 'main.ts'), '--output', exePath], { cwd: repoRoot });
|
|
124
|
-
run(process.execPath, [path.join(here, 'run-node.mjs'), '--build'], { cwd: here });
|
|
125
|
-
|
|
126
|
-
fs.rmSync(failuresDir, { recursive: true, force: true });
|
|
127
|
-
fs.rmSync(inputsDir, { recursive: true, force: true });
|
|
128
|
-
fs.mkdirSync(failuresDir, { recursive: true });
|
|
129
|
-
fs.mkdirSync(inputsDir, { recursive: true });
|
|
130
|
-
|
|
131
|
-
let passed = 0;
|
|
132
|
-
let next = 0;
|
|
133
|
-
const failed = [];
|
|
134
|
-
async function worker() {
|
|
135
|
-
while (next < cases.length) {
|
|
136
|
-
const index = next++;
|
|
137
|
-
const { id, template } = cases[index];
|
|
138
|
-
const input = path.join(inputsDir, `${index}.html`);
|
|
139
|
-
fs.writeFileSync(input, template);
|
|
140
|
-
const [node, native] = await Promise.all([
|
|
141
|
-
spawnCollect(process.execPath, [path.join(here, 'run-node.mjs'), input]),
|
|
142
|
-
spawnCollect(exePath, [input])
|
|
143
|
-
]);
|
|
144
|
-
if (node.stdout === native.stdout && node.stderr === native.stderr && node.code === native.code) {
|
|
145
|
-
passed++;
|
|
146
|
-
continue;
|
|
147
|
-
}
|
|
148
|
-
failed.push(id);
|
|
149
|
-
const report = (name, r) => `--- ${name} (exit ${r.code})\n${r.stdout}${r.stderr ? `--- ${name} stderr\n${r.stderr}` : ''}`;
|
|
150
|
-
fs.writeFileSync(path.join(failuresDir, `${index}.txt`), `${id}\n--- template\n${template}\n${report('node', node)}${report('native', native)}`);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
await Promise.all(Array.from({ length: Math.max(1, Math.min(8, os.availableParallelism() - 1)) }, worker));
|
|
154
|
-
|
|
155
|
-
for (const id of failed.sort()) console.log(`FAIL ${id}`);
|
|
156
|
-
console.log(`${passed}/${cases.length} templates match (${((100 * passed) / Math.max(1, cases.length)).toFixed(2)}%)`);
|
|
157
|
-
process.exitCode = failed.length > 0 ? 1 : 0;
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
// Runs main.ts under Node.js, compiled to JavaScript.
|
|
2
|
-
//
|
|
3
|
-
// Node runs TypeScript itself only by stripping types (Node 26 removed
|
|
4
|
-
// --experimental-transform-types), and Angular's compiler source uses enums
|
|
5
|
-
// and other syntax that mode rejects. So this compiles main.ts and every file
|
|
6
|
-
// it imports to JavaScript with the `typescript` package of this repository
|
|
7
|
-
// (into .cache/node/, rebuilt when a source file is newer than the build),
|
|
8
|
-
// then runs .cache/node/main.js with the given arguments. That is also how the
|
|
9
|
-
// compiler runs for Node users: the published @angular/compiler is JavaScript.
|
|
10
|
-
//
|
|
11
|
-
// Usage: node run-node.mjs [template.html]
|
|
12
|
-
// node run-node.mjs --build (build only; used by parity.mjs and bench.mjs)
|
|
13
|
-
|
|
14
|
-
import fs from 'node:fs';
|
|
15
|
-
import { createRequire } from 'node:module';
|
|
16
|
-
import path from 'node:path';
|
|
17
|
-
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
18
|
-
|
|
19
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
-
const outDir = path.join(here, '.cache', 'node');
|
|
21
|
-
export const nodeMain = path.join(outDir, 'main.js');
|
|
22
|
-
|
|
23
|
-
function newestSource(dir, newest = 0) {
|
|
24
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
25
|
-
const full = path.join(dir, entry.name);
|
|
26
|
-
if (entry.isDirectory()) newest = newestSource(full, newest);
|
|
27
|
-
else newest = Math.max(newest, fs.statSync(full).mtimeMs);
|
|
28
|
-
}
|
|
29
|
-
return newest;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function buildNode() {
|
|
33
|
-
const sources = Math.max(
|
|
34
|
-
fs.statSync(path.join(here, 'main.ts')).mtimeMs,
|
|
35
|
-
fs.statSync(path.join(here, 'dom-type-stubs.ts')).mtimeMs,
|
|
36
|
-
newestSource(path.join(here, 'vendor'))
|
|
37
|
-
);
|
|
38
|
-
if (fs.existsSync(nodeMain) && fs.statSync(nodeMain).mtimeMs >= sources) return;
|
|
39
|
-
|
|
40
|
-
const ts = createRequire(path.join(here, '..', '..', 'package.json'))('typescript');
|
|
41
|
-
fs.rmSync(outDir, { recursive: true, force: true });
|
|
42
|
-
const program = ts.createProgram([path.join(here, 'main.ts')], {
|
|
43
|
-
target: ts.ScriptTarget.ES2024,
|
|
44
|
-
module: ts.ModuleKind.ESNext,
|
|
45
|
-
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
46
|
-
rewriteRelativeImportExtensions: true,
|
|
47
|
-
allowImportingTsExtensions: true,
|
|
48
|
-
resolveJsonModule: true,
|
|
49
|
-
esModuleInterop: true,
|
|
50
|
-
lib: [],
|
|
51
|
-
types: [],
|
|
52
|
-
noLib: true,
|
|
53
|
-
noCheck: true,
|
|
54
|
-
skipLibCheck: true,
|
|
55
|
-
rootDir: here,
|
|
56
|
-
outDir,
|
|
57
|
-
});
|
|
58
|
-
const result = program.emit();
|
|
59
|
-
for (const d of result.diagnostics) console.error(ts.flattenDiagnosticMessageText(d.messageText, '\n'));
|
|
60
|
-
fs.writeFileSync(path.join(outDir, 'package.json'), '{ "type": "module" }\n');
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
64
|
-
buildNode();
|
|
65
|
-
if (process.argv[2] !== '--build') {
|
|
66
|
-
process.argv = [process.argv[0], nodeMain, ...process.argv.slice(2)];
|
|
67
|
-
await import(pathToFileURL(nodeMain).href);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
The MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2010-2026 Google LLC. https://angular.dev/license
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in
|
|
13
|
-
all copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
-
THE SOFTWARE.
|
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
# Desktop Notes
|
|
2
|
-
|
|
3
|
-
A desktop notes app in a native webview window. It's a `node:http` server that
|
|
4
|
-
edits plain Markdown files in a folder, and its UI renders in a window opened
|
|
5
|
-
with the [`@webviewjs/webview`](https://www.npmjs.com/package/@webviewjs/webview)
|
|
6
|
-
API. The HTML, CSS and JS live in [ui.ts](ui.ts) as a TypeScript string, so the
|
|
7
|
-
compiled binary is the whole app. There is no Electron, no bundled Chromium, no
|
|
8
|
-
Node runtime and no asset folder to ship next to it.
|
|
9
|
-
|
|
10
|
-
The same `main.ts` runs both ways. Under Node.js the import is the npm package.
|
|
11
|
-
Compiled, it's TypeNative's built-in version, so the binary needs neither the
|
|
12
|
-
package nor a C toolchain.
|
|
13
|
-
|
|
14
|
-
Demonstrates: a webview window, `node:http` routing with GET / PUT / POST /
|
|
15
|
-
DELETE, request bodies, `fs` reads, writes, listing and `statSync`, a local `.ts`
|
|
16
|
-
module import, `setInterval`, `process.memoryUsage()` and `process.exit`.
|
|
17
|
-
|
|
18
|
-
## How it works
|
|
19
|
-
|
|
20
|
-
- `GET /` serves the page from `ui.ts`. `/api/notes` lists notes (name, size,
|
|
21
|
-
modified time), and `/api/notes/<name>` reads, saves (`PUT`) or deletes one.
|
|
22
|
-
Note names are restricted to `[\w\- ]`, so they can't escape the folder.
|
|
23
|
-
- The editor autosaves 400 ms after you stop typing. Notes are plain
|
|
24
|
-
`<name>.md` files, so you can also edit them with any other tool.
|
|
25
|
-
- The window loads the page from that local server. Closing it ends the app. Text
|
|
26
|
-
the autosave hasn't reached goes out as a `navigator.sendBeacon` on
|
|
27
|
-
`beforeunload`, and the app waits 300 ms for it to arrive.
|
|
28
|
-
- **Under Node.js the window gets a process of its own**, which is this script
|
|
29
|
-
run with `--window <url>`. On Windows the npm package's event pump can hold the
|
|
30
|
-
JS thread for as long as the window is idle, and the server needs that thread.
|
|
31
|
-
Compiled apps run the window on its own thread, so they stay one process.
|
|
32
|
-
- The webview's profile lives in a folder the app chooses with
|
|
33
|
-
`createWebContext`. The default sits beside the executable, which is read-only
|
|
34
|
-
for `node.exe` under Program Files.
|
|
35
|
-
|
|
36
|
-
## Run it
|
|
37
|
-
|
|
38
|
-
Under Node.js, install the webview package first. This example pins
|
|
39
|
-
`1.0.0-rc.4`, because the `latest` tag (0.6.0) froze more readily in testing.
|
|
40
|
-
|
|
41
|
-
```sh
|
|
42
|
-
npm install
|
|
43
|
-
node main.ts # notes in ~/Notes, opens the window
|
|
44
|
-
node main.ts --dir ./my-notes # another folder
|
|
45
|
-
node main.ts --no-open --port 8080 # server only: open http://127.0.0.1:8080
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
With TypeNative, build once and ship the single file. `--gui` leaves out the
|
|
49
|
-
console window on Windows:
|
|
50
|
-
|
|
51
|
-
```sh
|
|
52
|
-
npx typenative --source main.ts --output dist/notes.exe --gui --release
|
|
53
|
-
./dist/notes.exe
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
From a checkout of this repository:
|
|
57
|
-
|
|
58
|
-
```sh
|
|
59
|
-
node bin/cli.js --source examples/desktop-notes/main.ts --output dist/notes.exe --gui
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
## What the window is on each platform
|
|
63
|
-
|
|
64
|
-
| Platform | Compiled with TypeNative | Under Node.js |
|
|
65
|
-
|--------------------------------------|--------------------------------------|----------------------|
|
|
66
|
-
| Windows | Embedded WebView2 | Embedded WebView2 |
|
|
67
|
-
| Windows without the WebView2 runtime | Edge or Chrome in app mode | Not supported |
|
|
68
|
-
| macOS | Chrome, Edge or Chromium in app mode | Embedded WebKit |
|
|
69
|
-
| Linux | Chrome, Edge or Chromium in app mode | Embedded WebKitGTK |
|
|
70
|
-
|
|
71
|
-
**Only Windows has been run end to end.** The macOS and Linux builds compile, but
|
|
72
|
-
neither column has been tried on those systems. TypeNative uses no cgo, which rules
|
|
73
|
-
out WebKit on those platforms for now, so a compiled app there needs a browser
|
|
74
|
-
installed and shows the browser's window frame. Node.js on Linux needs the WebKitGTK
|
|
75
|
-
libraries.
|
|
76
|
-
|
|
77
|
-
## Benchmark: Node.js vs TypeNative
|
|
78
|
-
|
|
79
|
-
Reproduce with `npm install`, then `node bench.mjs [runs=10]`. The script compiles
|
|
80
|
-
`main.ts`, fills a temp notes folder with 200 notes for each runtime, and then
|
|
81
|
-
alternates between the runtimes. Each run starts the app headless (`--no-open`) and
|
|
82
|
-
times **spawn until `GET /` answers 200**, which is what the user waits for before
|
|
83
|
-
the window can paint. It then lists the notes, opens 20 of them, saves one, and
|
|
84
|
-
reads the app's own **resident memory** from `/api/info`.
|
|
85
|
-
|
|
86
|
-
**Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
|
|
87
|
-
TypeNative 0.7.0, default (non-`--release`) build.
|
|
88
|
-
|
|
89
|
-
| Spawn → first page | min | median | mean | max |
|
|
90
|
-
|--------------------|-----------|-----------|-----------|-----------|
|
|
91
|
-
| Node.js | 82.24 ms | 97.52 ms | 98.04 ms | 133.78 ms |
|
|
92
|
-
| TypeNative | 21.90 ms | 24.81 ms | 27.97 ms | 59.85 ms |
|
|
93
|
-
|
|
94
|
-
| Resident memory | min | median | mean | max |
|
|
95
|
-
|-----------------|----------|----------|----------|----------|
|
|
96
|
-
| Node.js | 70.2 MiB | 71.7 MiB | 71.5 MiB | 72.0 MiB |
|
|
97
|
-
| TypeNative | 6.8 MiB | 10.8 MiB | 10.0 MiB | 10.8 MiB |
|
|
98
|
-
|
|
99
|
-
**TypeNative serves the first page 3.9x sooner and uses 6.7x less memory**
|
|
100
|
-
(median). The app is a single 14.3 MiB binary with the UI included. An Electron
|
|
101
|
-
build of the same app would ship about 100 MiB of Chromium and Node. This app uses
|
|
102
|
-
the webview the OS already has, and its backend idles at about 11 MiB.
|
|
103
|
-
|
|
104
|
-
These figures cover the headless server process only. They leave out the webview's
|
|
105
|
-
own processes, which are about the same for both runtimes, and the extra window
|
|
106
|
-
process Node.js runs.
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
// Launch + memory benchmark: Node.js vs TypeNative for the notes app.
|
|
2
|
-
//
|
|
3
|
-
// Compiles main.ts to a native binary with the TypeNative CLI from this repo
|
|
4
|
-
// checkout (../../bin/cli.js), then for each runtime, repeatedly:
|
|
5
|
-
// 1. starts the app headless (--no-open) on a free port, over a temp notes
|
|
6
|
-
// folder holding 200 notes,
|
|
7
|
-
// 2. measures the time from spawn until GET / answers 200 (what the user
|
|
8
|
-
// waits for before the window can paint),
|
|
9
|
-
// 3. lists the notes, opens 20 of them and saves one (warm-up), then reads
|
|
10
|
-
// the app's own resident memory (RSS) from /api/info,
|
|
11
|
-
// 4. stops it.
|
|
12
|
-
//
|
|
13
|
-
// Usage: node bench.mjs [runs=10]
|
|
14
|
-
|
|
15
|
-
import { spawn, spawnSync } from 'node:child_process';
|
|
16
|
-
import fs from 'node:fs';
|
|
17
|
-
import net from 'node:net';
|
|
18
|
-
import os from 'node:os';
|
|
19
|
-
import path from 'node:path';
|
|
20
|
-
import { fileURLToPath } from 'node:url';
|
|
21
|
-
|
|
22
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
23
|
-
const repoRoot = path.resolve(here, '..', '..');
|
|
24
|
-
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
25
|
-
const runs = Number(process.argv[2] ?? '10') || 10;
|
|
26
|
-
const exeName = process.platform === 'win32' ? 'notes.exe' : 'notes';
|
|
27
|
-
const exePath = path.join(here, 'dist', exeName);
|
|
28
|
-
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'notes-bench-'));
|
|
29
|
-
|
|
30
|
-
function stats(samples) {
|
|
31
|
-
const sorted = [...samples].sort((a, b) => a - b);
|
|
32
|
-
const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
|
|
33
|
-
return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const fmt = (n, unit) => `${n.toFixed(unit === 'ms' ? 2 : 1)} ${unit}`.padStart(11);
|
|
37
|
-
|
|
38
|
-
function freePort() {
|
|
39
|
-
return new Promise((resolve) => {
|
|
40
|
-
const server = net.createServer().listen(0, '127.0.0.1', () => {
|
|
41
|
-
const { port } = server.address();
|
|
42
|
-
server.close(() => resolve(port));
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function waitFor200(url, deadline) {
|
|
48
|
-
while (performance.now() < deadline) {
|
|
49
|
-
try {
|
|
50
|
-
const res = await fetch(url);
|
|
51
|
-
await res.arrayBuffer();
|
|
52
|
-
if (res.status === 200) return;
|
|
53
|
-
} catch {
|
|
54
|
-
// not listening yet
|
|
55
|
-
}
|
|
56
|
-
await new Promise((r) => setTimeout(r, 2));
|
|
57
|
-
}
|
|
58
|
-
throw new Error(`no answer from ${url}`);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async function measure(command, args, notesDir) {
|
|
62
|
-
const port = await freePort();
|
|
63
|
-
const base = `http://127.0.0.1:${port}`;
|
|
64
|
-
const t0 = performance.now();
|
|
65
|
-
const child = spawn(command, [...args, '--no-open', '--port', String(port), '--dir', notesDir], { cwd: here, stdio: 'ignore' });
|
|
66
|
-
try {
|
|
67
|
-
await waitFor200(`${base}/`, t0 + 10000);
|
|
68
|
-
const ready = performance.now() - t0;
|
|
69
|
-
const notes = await (await fetch(`${base}/api/notes`)).json();
|
|
70
|
-
for (const note of notes.slice(0, 20)) await (await fetch(`${base}/api/notes/${encodeURIComponent(note.name)}`)).text();
|
|
71
|
-
await fetch(`${base}/api/notes/Bench`, { method: 'PUT', body: 'saved by bench.mjs\n'.repeat(100) });
|
|
72
|
-
const info = await (await fetch(`${base}/api/info`)).json();
|
|
73
|
-
return { ready, rssMiB: info.rss / 1024 / 1024 };
|
|
74
|
-
} finally {
|
|
75
|
-
child.kill();
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
if (!fs.existsSync(path.join(here, 'node_modules', '@webviewjs', 'webview'))) {
|
|
80
|
-
console.error('Run npm install in this folder first: main.ts needs @webviewjs/webview under Node.js');
|
|
81
|
-
process.exit(1);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// 1. Compile the app to a native binary.
|
|
85
|
-
fs.mkdirSync(path.join(here, 'dist'), { recursive: true });
|
|
86
|
-
console.log('Compiling main.ts to a native binary with TypeNative...');
|
|
87
|
-
const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', path.join('dist', exeName)], {
|
|
88
|
-
cwd: here,
|
|
89
|
-
stdio: 'inherit',
|
|
90
|
-
});
|
|
91
|
-
if (build.status !== 0) process.exit(build.status ?? 1);
|
|
92
|
-
|
|
93
|
-
// 2. A notes folder per runtime, 200 notes of a few KiB each.
|
|
94
|
-
const dirs = { node: path.join(tmpDir, 'node'), native: path.join(tmpDir, 'native') };
|
|
95
|
-
for (const dir of Object.values(dirs)) {
|
|
96
|
-
fs.mkdirSync(dir);
|
|
97
|
-
for (let i = 0; i < 200; i++) {
|
|
98
|
-
fs.writeFileSync(path.join(dir, `Note ${i}.md`), `# Note ${i}\n\n` + `Line of text for note ${i}.\n`.repeat(100));
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// 3. Alternate runtimes so background load affects both alike.
|
|
103
|
-
console.log(`\nStarting each runtime ${runs} times...\n`);
|
|
104
|
-
const results = { node: [], native: [] };
|
|
105
|
-
for (let i = 0; i < runs; i++) {
|
|
106
|
-
results.node.push(await measure(process.execPath, ['main.ts'], dirs.node));
|
|
107
|
-
results.native.push(await measure(exePath, [], dirs.native));
|
|
108
|
-
}
|
|
109
|
-
fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
110
|
-
|
|
111
|
-
const table = (title, key, unit) => {
|
|
112
|
-
console.log(`${title}, ${runs} runs:\n`);
|
|
113
|
-
console.log('| Runtime | min | median | mean | max |');
|
|
114
|
-
console.log('|------------|-------------|-------------|-------------|-------------|');
|
|
115
|
-
for (const [label, name] of [['Node.js ', 'node'], ['TypeNative', 'native']]) {
|
|
116
|
-
const s = stats(results[name].map((r) => r[key]));
|
|
117
|
-
console.log(`| ${label} |${fmt(s.min, unit)} |${fmt(s.median, unit)} |${fmt(s.mean, unit)} |${fmt(s.max, unit)} |`);
|
|
118
|
-
}
|
|
119
|
-
const ratio = stats(results.node.map((r) => r[key])).median / stats(results.native.map((r) => r[key])).median;
|
|
120
|
-
console.log(`\nTypeNative: ${ratio.toFixed(1)}x ${key === 'ready' ? 'faster' : 'less memory'} (median).\n`);
|
|
121
|
-
};
|
|
122
|
-
table('Spawn until GET / answers 200', 'ready', 'ms');
|
|
123
|
-
table('Resident memory after listing, opening 20 notes and saving one', 'rssMiB', 'MiB');
|
|
124
|
-
const size = fs.statSync(exePath).size / 1024 / 1024;
|
|
125
|
-
console.log(`Native binary: ${size.toFixed(1)} MiB, the whole app (UI included).`);
|
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
// A desktop notes app: a local web server plus a native webview window, editing
|
|
2
|
-
// plain Markdown files in a folder on disk. The UI (./ui.ts) is compiled into
|
|
3
|
-
// the binary, so the result is one small executable that opens a window: no
|
|
4
|
-
// Electron, no Node runtime, no files next to it.
|
|
5
|
-
//
|
|
6
|
-
// node main.ts [--dir <folder>] [--port N] [--no-open] (npm install first)
|
|
7
|
-
// ./notes [--dir <folder>] [--port N] [--no-open]
|
|
8
|
-
//
|
|
9
|
-
// Notes live in ~/Notes by default. The window comes from @webviewjs/webview:
|
|
10
|
-
// the npm package under Node.js, TypeNative's built-in version when compiled,
|
|
11
|
-
// and the app quits when it closes. With --no-open it only serves
|
|
12
|
-
// http://127.0.0.1:<port> and runs until stopped.
|
|
13
|
-
import { Application } from '@webviewjs/webview';
|
|
14
|
-
import { spawn } from 'node:child_process';
|
|
15
|
-
import fs from 'node:fs';
|
|
16
|
-
import http from 'node:http';
|
|
17
|
-
import os from 'node:os';
|
|
18
|
-
import path from 'node:path';
|
|
19
|
-
import { page } from './ui.ts';
|
|
20
|
-
|
|
21
|
-
interface NoteInfo {
|
|
22
|
-
name: string;
|
|
23
|
-
size: number;
|
|
24
|
-
modified: number;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function flag(name: string): string | undefined {
|
|
28
|
-
const i = process.argv.indexOf(name);
|
|
29
|
-
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const dir = path.resolve(flag('--dir') ?? path.join(os.homedir(), 'Notes'));
|
|
33
|
-
const port = Number(flag('--port') ?? '0');
|
|
34
|
-
const openWindow = !process.argv.includes('--no-open');
|
|
35
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
36
|
-
|
|
37
|
-
// Note names map straight to file names, so only allow safe characters
|
|
38
|
-
function noteFile(name: string): string | undefined {
|
|
39
|
-
return /^[\w\- ]{1,100}$/.test(name) ? path.join(dir, `${name}.md`) : undefined;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function listNotes(): NoteInfo[] {
|
|
43
|
-
const notes: NoteInfo[] = [];
|
|
44
|
-
for (const file of fs.readdirSync(dir)) {
|
|
45
|
-
if (!file.endsWith('.md')) continue;
|
|
46
|
-
const stat = fs.statSync(path.join(dir, file));
|
|
47
|
-
notes.push({ name: file.slice(0, -3), size: stat.size, modified: stat.mtimeMs });
|
|
48
|
-
}
|
|
49
|
-
return notes.sort((a, b) => b.modified - a.modified);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function send(res: http.ServerResponse, status: number, type: string, body: string): void {
|
|
53
|
-
res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' });
|
|
54
|
-
res.end(body);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const server = http.createServer((req, res) => {
|
|
58
|
-
let body = '';
|
|
59
|
-
req.on('data', (chunk) => {
|
|
60
|
-
body += String(chunk);
|
|
61
|
-
});
|
|
62
|
-
req.on('end', () => {
|
|
63
|
-
const url = req.url ?? '/';
|
|
64
|
-
const method = req.method ?? 'GET';
|
|
65
|
-
if (url === '/') {
|
|
66
|
-
send(res, 200, 'text/html; charset=utf-8', page);
|
|
67
|
-
} else if (url === '/api/info') {
|
|
68
|
-
const info = { dir: dir, runtime: path.basename(process.execPath), rss: process.memoryUsage().rss };
|
|
69
|
-
send(res, 200, 'application/json', JSON.stringify(info));
|
|
70
|
-
} else if (url === '/api/notes') {
|
|
71
|
-
send(res, 200, 'application/json', JSON.stringify(listNotes()));
|
|
72
|
-
} else if (url.startsWith('/api/notes/')) {
|
|
73
|
-
const file = noteFile(decodeURIComponent(url.slice('/api/notes/'.length)));
|
|
74
|
-
if (!file) {
|
|
75
|
-
send(res, 400, 'text/plain', 'invalid note name');
|
|
76
|
-
} else if (method === 'GET') {
|
|
77
|
-
if (fs.existsSync(file)) send(res, 200, 'text/markdown; charset=utf-8', fs.readFileSync(file, 'utf8'));
|
|
78
|
-
else send(res, 404, 'text/plain', 'no such note');
|
|
79
|
-
} else if (method === 'PUT' || method === 'POST') {
|
|
80
|
-
// POST too: the window's last save on close arrives as a beacon
|
|
81
|
-
fs.writeFileSync(file, body);
|
|
82
|
-
send(res, 204, 'text/plain', '');
|
|
83
|
-
} else if (method === 'DELETE') {
|
|
84
|
-
fs.rmSync(file, { force: true });
|
|
85
|
-
send(res, 204, 'text/plain', '');
|
|
86
|
-
} else {
|
|
87
|
-
send(res, 405, 'text/plain', 'method not allowed');
|
|
88
|
-
}
|
|
89
|
-
} else {
|
|
90
|
-
send(res, 404, 'text/plain', 'not found');
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
function openAppWindow(url: string, onClosed: () => void): void {
|
|
96
|
-
const app = new Application();
|
|
97
|
-
// The webview's profile folder: its default, beside the executable, is read-only
|
|
98
|
-
// for node.exe under Program Files
|
|
99
|
-
const profile = app.createWebContext({ dataDirectory: path.join(os.tmpdir(), 'desktop-notes-webview') });
|
|
100
|
-
const win = app.createBrowserWindow({ title: 'Notes', width: 1000, height: 700, logical: true });
|
|
101
|
-
win.createWebview({ url: url, webContext: profile });
|
|
102
|
-
app.on('application-close-requested', onClosed);
|
|
103
|
-
app.run();
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// The window's last save is a beacon sent as it closes: let it arrive
|
|
107
|
-
function quit(): void {
|
|
108
|
-
setTimeout(() => process.exit(0), 300);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// On Windows the npm package's event pump can hold the JS thread for as long as
|
|
112
|
-
// its window is idle, and the server needs that thread: under Node.js the window
|
|
113
|
-
// gets a process of its own, this same script run with --window <url>
|
|
114
|
-
const underNode = path.basename(process.execPath, '.exe') === 'node';
|
|
115
|
-
const windowUrl = flag('--window');
|
|
116
|
-
|
|
117
|
-
if (windowUrl) {
|
|
118
|
-
openAppWindow(windowUrl, () => process.exit(0));
|
|
119
|
-
} else {
|
|
120
|
-
server.listen(port, '127.0.0.1', () => {
|
|
121
|
-
const address = server.address() as { port: number };
|
|
122
|
-
const url = `http://127.0.0.1:${address.port}/`;
|
|
123
|
-
console.log(`Notes in ${dir} on ${url}`);
|
|
124
|
-
if (!openWindow) return;
|
|
125
|
-
if (underNode) {
|
|
126
|
-
spawn(process.execPath, [process.argv[1], '--window', url], { stdio: 'inherit' }).on('exit', quit);
|
|
127
|
-
} else {
|
|
128
|
-
openAppWindow(url, quit);
|
|
129
|
-
}
|
|
130
|
-
});
|
|
131
|
-
}
|