tina4-nodejs 3.13.164 → 3.13.165
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/CLAUDE.md +2 -2
- package/package.json +1 -1
- package/packages/cli/dist/bin.js +732 -653
- package/packages/cli/src/bin.ts +5 -2
- package/packages/cli/src/commands/lint.ts +3 -1
- package/packages/core/dist/index.js +653 -576
- package/packages/core/src/batchSpawn.ts +129 -0
- package/packages/core/src/devAdmin.ts +7 -8
- package/packages/core/src/fakeData.ts +4 -1
- package/packages/core/src/mcp.ts +4 -1
- package/packages/core/src/portTakeover.ts +31 -13
- package/packages/core/src/projectIndex.ts +3 -4
- package/packages/core/src/projectIndexStorage.ts +9 -1
- package/packages/core/src/response.ts +4 -1
- package/packages/core/src/routeDiscovery.ts +8 -2
- package/packages/core/src/server.ts +18 -15
- package/packages/core/src/session.ts +5 -0
- package/packages/core/src/sessionHandlers/databaseHandler.ts +16 -0
- package/packages/orm/dist/index.js +687 -610
- package/packages/orm/src/model.ts +2 -1
- package/types/core/src/batchSpawn.d.ts +28 -0
- package/types/core/src/portTakeover.d.ts +15 -0
- package/types/core/src/projectIndexStorage.d.ts +5 -0
- package/types/core/src/session.d.ts +5 -0
- package/types/core/src/sessionHandlers/databaseHandler.d.ts +8 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright (c) 2026 Code Infinity
|
|
3
|
+
SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
|
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
|
+
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Run a program that may be a Windows batch file (`.cmd` / `.bat`).
|
|
11
|
+
*
|
|
12
|
+
* Since the 2024 BatBadBut fix (CVE-2024-27980) Node refuses to spawn a batch
|
|
13
|
+
* file without a shell: `spawnSync("C:\\...\\npm.cmd", args)` fails with EINVAL.
|
|
14
|
+
* The other three Tina4 frameworks start batch files directly, so `npm.cmd`
|
|
15
|
+
* and a `tina4.cmd` client have to work here too.
|
|
16
|
+
*
|
|
17
|
+
* Handing the arguments to `shell: true` is not the fix: Node joins them with
|
|
18
|
+
* spaces and no escaping, so an argument such as `a&calc` would run `calc`.
|
|
19
|
+
* Instead the command line is built here the way cross-spawn builds it
|
|
20
|
+
* (https://qntm.org/cmd): each argument is quoted, embedded quotes and the
|
|
21
|
+
* backslashes before them are escaped, and every cmd.exe metacharacter is
|
|
22
|
+
* caret-escaped TWICE - once for the `cmd /c` line, once more because a batch
|
|
23
|
+
* file re-parses the `%*` it forwards. The line goes to cmd.exe verbatim
|
|
24
|
+
* (`windowsVerbatimArguments`) so libuv adds no quoting of its own.
|
|
25
|
+
*
|
|
26
|
+
* Anything that is not a batch file, and every non-Windows platform, is spawned
|
|
27
|
+
* exactly as before.
|
|
28
|
+
*/
|
|
29
|
+
import { spawnSync } from "node:child_process";
|
|
30
|
+
import type { SpawnSyncOptions, SpawnSyncReturns } from "node:child_process";
|
|
31
|
+
import { existsSync, statSync } from "node:fs";
|
|
32
|
+
import { delimiter, extname, join } from "node:path";
|
|
33
|
+
|
|
34
|
+
/** cmd.exe metacharacters, the same set cross-spawn escapes. */
|
|
35
|
+
const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
|
|
36
|
+
|
|
37
|
+
/** True when `file` is a batch file that Node will not spawn without a shell. */
|
|
38
|
+
export function isBatchFile(file: string, platform: NodeJS.Platform = process.platform): boolean {
|
|
39
|
+
return platform === "win32" && /\.(cmd|bat)$/i.test(file);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One argument, quoted and escaped for a batch file run through `cmd /d /s /c`. */
|
|
43
|
+
export function escapeBatchArgument(arg: string): string {
|
|
44
|
+
let quoted = String(arg)
|
|
45
|
+
// backslashes before a quote double, and the quote is backslash-escaped
|
|
46
|
+
.replace(/(\\*)"/g, '$1$1\\"')
|
|
47
|
+
// backslashes before the closing quote we are about to add double too
|
|
48
|
+
.replace(/(\\*)$/, "$1$1");
|
|
49
|
+
quoted = `"${quoted}"`;
|
|
50
|
+
return quoted.replace(CMD_META, "^$1").replace(CMD_META, "^$1");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The batch file's own path, escaped for the head of the `cmd /c` line. */
|
|
54
|
+
function escapeBatchCommand(file: string): string {
|
|
55
|
+
return file.replace(CMD_META, "^$1");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Resolve a bare program name such as `npm` to the file Windows would run.
|
|
60
|
+
*
|
|
61
|
+
* Without a shell, Windows' CreateProcess only adds `.exe`, so `npm` (which is
|
|
62
|
+
* `npm.cmd`) is never found and the spawn fails with ENOENT. This walks PATH
|
|
63
|
+
* with PATHEXT the way cmd.exe does. A name that already has a directory or an
|
|
64
|
+
* extension, every other platform, and a name that is not found are returned
|
|
65
|
+
* unchanged, so the spawn reports its own error exactly as before.
|
|
66
|
+
*/
|
|
67
|
+
export function findExecutable(name: string, platform: NodeJS.Platform = process.platform): string {
|
|
68
|
+
if (platform !== "win32" || /[\\/]/.test(name) || extname(name) !== "") return name;
|
|
69
|
+
const exts = (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
|
70
|
+
const dirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
|
|
71
|
+
// PATH order first, then PATHEXT order within each directory, as cmd.exe does.
|
|
72
|
+
const candidates = dirs.flatMap((dir) => exts.map((ext) => join(dir, name + ext.toLowerCase())));
|
|
73
|
+
return candidates.find(isRegularFile) ?? name;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** True when `path` exists and is a file (a directory named `npm.cmd` is not). */
|
|
77
|
+
function isRegularFile(path: string): boolean {
|
|
78
|
+
try {
|
|
79
|
+
return existsSync(path) && statSync(path).isFile();
|
|
80
|
+
} catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `spawnSync`, except that a batch file on Windows runs through cmd.exe with
|
|
87
|
+
* every argument escaped. Returns what spawnSync returns either way.
|
|
88
|
+
*/
|
|
89
|
+
export function spawnSyncAllowingBatch(
|
|
90
|
+
file: string,
|
|
91
|
+
args: readonly string[],
|
|
92
|
+
options: SpawnSyncOptions = {},
|
|
93
|
+
): SpawnSyncReturns<Buffer | string> {
|
|
94
|
+
if (!isBatchFile(file)) return spawnSync(file, args, options);
|
|
95
|
+
const line = [escapeBatchCommand(file), ...args.map(escapeBatchArgument)].join(" ");
|
|
96
|
+
const shell = process.env.comspec || "cmd.exe";
|
|
97
|
+
return spawnSync(shell, ["/d", "/s", "/c", `"${line}"`], {
|
|
98
|
+
...options,
|
|
99
|
+
windowsVerbatimArguments: true,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `execFileSync` for a bare program name (`npm`, `npx`) that may be a batch
|
|
105
|
+
* file: resolves it with {@link findExecutable}, runs it with
|
|
106
|
+
* {@link spawnSyncAllowingBatch}, and like execFileSync returns stdout and
|
|
107
|
+
* throws on a spawn error or a non-zero exit (the error carries `status`,
|
|
108
|
+
* `stdout` and `stderr`).
|
|
109
|
+
*/
|
|
110
|
+
export function execFileSyncAllowingBatch(
|
|
111
|
+
name: string,
|
|
112
|
+
args: readonly string[],
|
|
113
|
+
options: SpawnSyncOptions = {},
|
|
114
|
+
): string {
|
|
115
|
+
const result = spawnSyncAllowingBatch(findExecutable(name), args, { encoding: "utf-8", ...options });
|
|
116
|
+
if (result.error) throw result.error;
|
|
117
|
+
const stdout = String(result.stdout ?? "");
|
|
118
|
+
const stderr = String(result.stderr ?? "");
|
|
119
|
+
if (result.status !== 0) {
|
|
120
|
+
const err = new Error(
|
|
121
|
+
`Command failed: ${name} ${args.join(" ")} (exit ${result.status ?? result.signal})\n${stderr}`.trim(),
|
|
122
|
+
) as Error & { status: number | null; stdout: string; stderr: string };
|
|
123
|
+
err.status = result.status;
|
|
124
|
+
err.stdout = stdout;
|
|
125
|
+
err.stderr = stderr;
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
return stdout;
|
|
129
|
+
}
|
|
@@ -21,6 +21,7 @@ import { cpus as osCpus } from "node:os";
|
|
|
21
21
|
import { rtrimSlashes } from "./slashTrim.js";
|
|
22
22
|
import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync, copyFileSync, statSync, openSync, closeSync, fstatSync, fchmodSync, ftruncateSync, constants, realpathSync, lstatSync } from "node:fs";
|
|
23
23
|
import { join, dirname, resolve, relative, sep, basename } from "node:path";
|
|
24
|
+
import { execFileSyncAllowingBatch } from "./batchSpawn.js";
|
|
24
25
|
import { fileURLToPath } from "node:url";
|
|
25
26
|
import type { Router } from "./router.js";
|
|
26
27
|
import type { RouteHandler, Tina4Request } from "./types.js";
|
|
@@ -2752,13 +2753,12 @@ const handleDepsInstall: RouteHandler = async (req, res) => {
|
|
|
2752
2753
|
return;
|
|
2753
2754
|
}
|
|
2754
2755
|
try {
|
|
2755
|
-
const { execFileSync } = await import("node:child_process");
|
|
2756
2756
|
const args = ["install", dev ? "--save-dev" : "--save", pkg];
|
|
2757
|
-
|
|
2757
|
+
// npm is npm.cmd on Windows, which execFileSync cannot find or start.
|
|
2758
|
+
const output = execFileSyncAllowingBatch("npm", args, {
|
|
2758
2759
|
cwd: resolve(process.cwd()),
|
|
2759
2760
|
timeout: 120_000,
|
|
2760
|
-
|
|
2761
|
-
}).toString();
|
|
2761
|
+
});
|
|
2762
2762
|
res.json({ ok: true, package: pkg, output });
|
|
2763
2763
|
} catch (e) {
|
|
2764
2764
|
res.json({ error: (e as Error).message }, 500);
|
|
@@ -2994,12 +2994,11 @@ const handleScaffoldRun: RouteHandler = async (req, res) => {
|
|
|
2994
2994
|
return;
|
|
2995
2995
|
}
|
|
2996
2996
|
try {
|
|
2997
|
-
|
|
2998
|
-
const output =
|
|
2997
|
+
// npx is npx.cmd on Windows, which execFileSync cannot find or start.
|
|
2998
|
+
const output = execFileSyncAllowingBatch("npx", ["tina4nodejs", "generate", kind, name], {
|
|
2999
2999
|
cwd: resolve(process.cwd()),
|
|
3000
3000
|
timeout: 30_000,
|
|
3001
|
-
|
|
3002
|
-
}).toString();
|
|
3001
|
+
});
|
|
3003
3002
|
res.json({ ok: true, kind, name, output });
|
|
3004
3003
|
} catch (e) {
|
|
3005
3004
|
res.json({ error: (e as Error).message }, 500);
|
|
@@ -27,6 +27,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
27
27
|
import { randomInt, randomUUID } from "node:crypto";
|
|
28
28
|
import { existsSync, readdirSync } from "node:fs";
|
|
29
29
|
import { resolve, join } from "node:path";
|
|
30
|
+
import { pathToFileURL } from "node:url";
|
|
30
31
|
|
|
31
32
|
// ── Word Banks ───────────────────────────────────────────────────
|
|
32
33
|
|
|
@@ -352,7 +353,9 @@ export class FakeData {
|
|
|
352
353
|
for (const file of files) {
|
|
353
354
|
const fullPath = join(dir, file);
|
|
354
355
|
try {
|
|
355
|
-
|
|
356
|
+
// A raw path is not an import specifier: D:\... reads as a URL scheme,
|
|
357
|
+
// and a # anywhere in the path starts a URL fragment.
|
|
358
|
+
const mod = await import(pathToFileURL(fullPath).href);
|
|
356
359
|
if (typeof mod.default === "function") {
|
|
357
360
|
await mod.default();
|
|
358
361
|
}
|
package/packages/core/src/mcp.ts
CHANGED
|
@@ -27,6 +27,7 @@ import { rtrimSlashes } from "./slashTrim.js";
|
|
|
27
27
|
import * as path from "node:path";
|
|
28
28
|
import * as os from "node:os";
|
|
29
29
|
import { spawnSync } from "node:child_process";
|
|
30
|
+
import { findExecutable, spawnSyncAllowingBatch } from "./batchSpawn.js";
|
|
30
31
|
import { createRequire } from "node:module";
|
|
31
32
|
import { randomBytes } from "node:crypto";
|
|
32
33
|
import { TINA4_VERSION } from "./version.js";
|
|
@@ -1109,7 +1110,9 @@ function verifyNodeSyntax(absPath: string, relPath: string): string | null {
|
|
|
1109
1110
|
if (!target) return null;
|
|
1110
1111
|
const { cmd, args } = syntaxCheckCommand(absPath, target.ext);
|
|
1111
1112
|
try {
|
|
1112
|
-
|
|
1113
|
+
// npx is npx.cmd on Windows: a plain spawnSync gets ENOENT, which reads as
|
|
1114
|
+
// "tsc not installed" below and skips the check without a word.
|
|
1115
|
+
const proc = spawnSyncAllowingBatch(findExecutable(cmd), args, {
|
|
1113
1116
|
encoding: "utf-8",
|
|
1114
1117
|
timeout: 5000,
|
|
1115
1118
|
cwd: path.dirname(path.dirname(absPath)),
|
|
@@ -177,20 +177,37 @@ function sleepSync(ms: number): void {
|
|
|
177
177
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
-
// Listens on argv host:port and exits 0 once bound,
|
|
181
|
-
//
|
|
182
|
-
//
|
|
180
|
+
// Listens on argv host:port and exits 0 once bound, PROBE_HELD when the bind
|
|
181
|
+
// fails with EADDRINUSE, and PROBE_OTHER on any other bind error. A child
|
|
182
|
+
// process, because takeOverPort is synchronous and a Node bind is not. The host
|
|
183
|
+
// and port arrive as argv, never interpolated into the code.
|
|
184
|
+
const PROBE_HELD = 3;
|
|
185
|
+
const PROBE_OTHER = 4;
|
|
183
186
|
const BIND_PROBE = 'const s = require("node:net").createServer();'
|
|
184
|
-
+
|
|
187
|
+
+ `s.on("error", (e) => process.exit(e && e.code === "EADDRINUSE" ? ${PROBE_HELD} : ${PROBE_OTHER}));`
|
|
185
188
|
+ 's.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
|
|
186
189
|
|
|
187
|
-
/**
|
|
188
|
-
|
|
190
|
+
/** What a bind probe learned about a port. */
|
|
191
|
+
export type BindProbe = "free" | "held" | "unknown";
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Try a plain TCP listener on `host`:`port` (the same net.listen the server
|
|
195
|
+
* uses) and report what happened.
|
|
196
|
+
*
|
|
197
|
+
* Only a bind that fails with EADDRINUSE is "held". A probe that times out,
|
|
198
|
+
* cannot start, or hits any other bind error (EACCES, EADDRNOTAVAIL) is
|
|
199
|
+
* "unknown": it says nothing about whether something holds the port, so the
|
|
200
|
+
* caller must not report the port as in use. The real bind then decides, and
|
|
201
|
+
* it fails loudly with the true error. A probe is a child `node`, so on a slow
|
|
202
|
+
* host (arm64 under emulation, a small board, a CPU-throttled container) the
|
|
203
|
+
* child alone can take longer than the timeout to start.
|
|
204
|
+
*/
|
|
205
|
+
export function probeBind(host: string, port: number, timeout = 5000): BindProbe {
|
|
189
206
|
try {
|
|
190
|
-
execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout
|
|
191
|
-
return
|
|
192
|
-
} catch {
|
|
193
|
-
return
|
|
207
|
+
execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout });
|
|
208
|
+
return "free";
|
|
209
|
+
} catch (err) {
|
|
210
|
+
return (err as { status?: number | null }).status === PROBE_HELD ? "held" : "unknown";
|
|
194
211
|
}
|
|
195
212
|
}
|
|
196
213
|
|
|
@@ -198,12 +215,13 @@ function bindable(host: string, port: number): boolean {
|
|
|
198
215
|
* The result to return before any holder lookup, or null to carry on.
|
|
199
216
|
*
|
|
200
217
|
* Takeover is refused when opted out or outside dev mode. Before a bind, the
|
|
201
|
-
* caller passes the host it will bind:
|
|
202
|
-
*
|
|
218
|
+
* caller passes the host it will bind: unless a probe sees that port held,
|
|
219
|
+
* there is nothing to refuse and nothing to say (an inconclusive probe leaves
|
|
220
|
+
* the decision to the real bind).
|
|
203
221
|
*/
|
|
204
222
|
function refusal(port: number, dev: boolean, noTakeover: boolean, host?: string): TakeoverResult | null {
|
|
205
223
|
if (dev && !noTakeover) return null;
|
|
206
|
-
if (host !== undefined &&
|
|
224
|
+
if (host !== undefined && probeBind(host, port) !== "held") {
|
|
207
225
|
return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
|
|
208
226
|
}
|
|
209
227
|
if (noTakeover) {
|
|
@@ -17,9 +17,8 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
17
17
|
* Python) using regex. No LLM involvement — pure static analysis.
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
-
import * as path from "node:path";
|
|
21
20
|
import * as fs from "node:fs";
|
|
22
|
-
import { extract, indexPath, loadRaw, projectRoot, saveRaw, walk } from "./projectIndexStorage.js";
|
|
21
|
+
import { extract, indexKey, indexPath, loadRaw, projectRoot, saveRaw, walk } from "./projectIndexStorage.js";
|
|
23
22
|
import type { IndexData } from "./projectIndexStorage.js";
|
|
24
23
|
|
|
25
24
|
export interface FileRoute {
|
|
@@ -80,7 +79,7 @@ export const ProjectIndex = {
|
|
|
80
79
|
const found: string[] = [];
|
|
81
80
|
walk(root, found);
|
|
82
81
|
for (const fp of found) {
|
|
83
|
-
const rel =
|
|
82
|
+
const rel = indexKey(root, fp);
|
|
84
83
|
seen.add(rel);
|
|
85
84
|
let mtime: number;
|
|
86
85
|
try {
|
|
@@ -106,7 +105,7 @@ export const ProjectIndex = {
|
|
|
106
105
|
updated,
|
|
107
106
|
removed: removed.length,
|
|
108
107
|
total: Object.keys(files).length,
|
|
109
|
-
path:
|
|
108
|
+
path: indexKey(root, indexPath()),
|
|
110
109
|
};
|
|
111
110
|
},
|
|
112
111
|
|
|
@@ -31,6 +31,14 @@ export interface IndexData {
|
|
|
31
31
|
generated_at: number;
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/**
|
|
35
|
+
* The index key for a file: its path relative to `root`, always `/`-separated
|
|
36
|
+
* so the same file has the same key on every OS (PHP's rule).
|
|
37
|
+
*/
|
|
38
|
+
export function indexKey(root: string, fullPath: string): string {
|
|
39
|
+
return path.relative(root, fullPath).split(path.sep).join("/");
|
|
40
|
+
}
|
|
41
|
+
|
|
34
42
|
export function projectRoot(): string {
|
|
35
43
|
return path.resolve(process.cwd());
|
|
36
44
|
}
|
|
@@ -69,7 +77,7 @@ export function extract(fullPath: string): FileEntry {
|
|
|
69
77
|
return {};
|
|
70
78
|
}
|
|
71
79
|
const entry: FileEntry = {
|
|
72
|
-
path:
|
|
80
|
+
path: indexKey(projectRoot(), fullPath),
|
|
73
81
|
size: st.size,
|
|
74
82
|
mtime: Math.floor(st.mtimeMs / 1000),
|
|
75
83
|
language: languageFor(fullPath),
|
|
@@ -9,6 +9,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
9
9
|
import type { ServerResponse } from "node:http";
|
|
10
10
|
import fs from "node:fs";
|
|
11
11
|
import nodePath from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
12
13
|
import { once } from "node:events";
|
|
13
14
|
import type { Tina4Response, CookieOptions } from "./types.js";
|
|
14
15
|
import { currentCspNonce } from "./csp.js";
|
|
@@ -108,7 +109,9 @@ export async function getFrond(): Promise<InstanceType<any>> {
|
|
|
108
109
|
* Syncs custom filters/globals from the user engine.
|
|
109
110
|
*/
|
|
110
111
|
export async function getFrameworkFrond(): Promise<InstanceType<any> | null> {
|
|
111
|
-
|
|
112
|
+
// fileURLToPath, not a string replace of "file://": the URL of a module under
|
|
113
|
+
// C:\ is file:///C:/..., and any path with a space or # is percent-encoded.
|
|
114
|
+
const frameworkDir = nodePath.resolve(nodePath.dirname(fileURLToPath(import.meta.url)), "..", "templates");
|
|
112
115
|
if (!_frameworkFrond && fs.existsSync(frameworkDir)) {
|
|
113
116
|
try {
|
|
114
117
|
const { Frond, setCspNonceProvider } = await import("../../frond/src/engine.js");
|
|
@@ -8,6 +8,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
8
8
|
|
|
9
9
|
import { readdirSync, statSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
|
|
10
10
|
import { join, relative, basename, extname } from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
11
12
|
import type { RouteDefinition, RouteHandler, RouteMeta } from "./types.js";
|
|
12
13
|
|
|
13
14
|
const VALID_METHODS = new Set(["get", "post", "put", "delete", "patch"]);
|
|
@@ -71,7 +72,9 @@ export async function discoverRoutes(routesDir: string): Promise<RouteDefinition
|
|
|
71
72
|
try {
|
|
72
73
|
// Cache-bust for hot-reload, keyed on mtime: identical content reuses the
|
|
73
74
|
// same module URL (no needless re-import), an edit produces a fresh URL.
|
|
74
|
-
|
|
75
|
+
// pathToFileURL, not a hand-built file:// string: it percent-encodes #, ? and %, which
|
|
76
|
+
// would otherwise end the path early, and writes a drive letter correctly.
|
|
77
|
+
const moduleUrl = `${pathToFileURL(filePath).href}?t=${currentMtime}`;
|
|
75
78
|
const mod = await import(moduleUrl);
|
|
76
79
|
|
|
77
80
|
const handler: RouteHandler = mod.default ?? mod.handler;
|
|
@@ -146,7 +149,10 @@ function recordBrokenImport(filePath: string, error: Error): void {
|
|
|
146
149
|
try {
|
|
147
150
|
const brokenDir = join(process.cwd(), "data", ".broken");
|
|
148
151
|
if (!existsSync(brokenDir)) mkdirSync(brokenDir, { recursive: true });
|
|
149
|
-
|
|
152
|
+
// `:` too: an absolute Windows path starts with a drive letter, and on NTFS
|
|
153
|
+
// a colon in a file name writes an alternate data stream instead of a file,
|
|
154
|
+
// so no *.broken listing would ever see the marker.
|
|
155
|
+
const slug = filePath.replace(/[/\\:]/g, "_");
|
|
150
156
|
const payload = JSON.stringify({
|
|
151
157
|
type: "auto_discover_failure",
|
|
152
158
|
file: filePath,
|
|
@@ -14,7 +14,7 @@ import { resolve, dirname, join, relative } from "node:path";
|
|
|
14
14
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
15
15
|
import { isatty } from "node:tty";
|
|
16
16
|
import { fileURLToPath } from "node:url";
|
|
17
|
-
import {
|
|
17
|
+
import { execFile } from "node:child_process";
|
|
18
18
|
import cluster from "node:cluster";
|
|
19
19
|
import os from "node:os";
|
|
20
20
|
import type { Socket } from "node:net";
|
|
@@ -24,6 +24,7 @@ import { enforceRouteAuth } from "./authGate.js";
|
|
|
24
24
|
import { discoverRoutes } from "./routeDiscovery.js";
|
|
25
25
|
import {
|
|
26
26
|
takeOverPort,
|
|
27
|
+
probeBind,
|
|
27
28
|
isDev as isTakeoverDev,
|
|
28
29
|
noTakeoverOptedOut,
|
|
29
30
|
writePidfile,
|
|
@@ -412,22 +413,17 @@ export function killPort(port: number): void {
|
|
|
412
413
|
}
|
|
413
414
|
|
|
414
415
|
/**
|
|
415
|
-
* Check if *port* is
|
|
416
|
-
* The auto-increment behaviour is intentionally
|
|
417
|
-
* claims the requested port.
|
|
416
|
+
* Check if *port* is held; if it is, reclaim it through the guarded takeover
|
|
417
|
+
* path and return *port*. The auto-increment behaviour is intentionally
|
|
418
|
+
* removed — the server always claims the requested port.
|
|
419
|
+
*
|
|
420
|
+
* Only a probe that sees EADDRINUSE counts as held. A probe that times out on a
|
|
421
|
+
* slow start says nothing about the port, so the real bind decides: it used to
|
|
422
|
+
* count as "in use", and a production server on a slow host refused a free port.
|
|
418
423
|
*/
|
|
419
424
|
function findAvailablePort(start: number): number {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
const s = require("net").createServer();
|
|
423
|
-
s.listen(${start}, "0.0.0.0", () => { s.close(); process.exit(0); });
|
|
424
|
-
s.on("error", () => process.exit(1));
|
|
425
|
-
`], { timeout: 1000 });
|
|
426
|
-
return start;
|
|
427
|
-
} catch {
|
|
428
|
-
killPort(start);
|
|
429
|
-
return start;
|
|
430
|
-
}
|
|
425
|
+
if (probeBind("0.0.0.0", start) === "held") killPort(start);
|
|
426
|
+
return start;
|
|
431
427
|
}
|
|
432
428
|
|
|
433
429
|
/**
|
|
@@ -2147,6 +2143,13 @@ function startProductionCluster(port: number, host: string): {
|
|
|
2147
2143
|
Debug: OFF (Log level: ${logLevel})
|
|
2148
2144
|
${reset}`);
|
|
2149
2145
|
}
|
|
2146
|
+
// Round-robin, so every worker gets requests. Node already defaults to it
|
|
2147
|
+
// everywhere except Windows, where the default is SCHED_NONE (the OS picks a
|
|
2148
|
+
// worker, and under load it may keep picking the same one). Must be set before
|
|
2149
|
+
// the first fork. An operator's explicit NODE_CLUSTER_SCHED_POLICY wins.
|
|
2150
|
+
if (process.env.NODE_CLUSTER_SCHED_POLICY === undefined) {
|
|
2151
|
+
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
2152
|
+
}
|
|
2150
2153
|
for (let i = 0; i < numCPUs; i++) cluster.fork();
|
|
2151
2154
|
cluster.on("exit", (worker, code) => {
|
|
2152
2155
|
if (code !== 0) {
|
|
@@ -181,6 +181,11 @@ export interface SessionHandler {
|
|
|
181
181
|
destroy(sessionId: string): void;
|
|
182
182
|
/** Garbage-collect expired sessions. Optional — Redis/Valkey/Mongo handle TTL natively. */
|
|
183
183
|
gc?(maxLifetime: number): void;
|
|
184
|
+
/**
|
|
185
|
+
* Release a connection the handler opened itself. Optional; idempotent; the
|
|
186
|
+
* next read or write reopens it.
|
|
187
|
+
*/
|
|
188
|
+
close?(): void;
|
|
184
189
|
}
|
|
185
190
|
|
|
186
191
|
// ── File Session Handler ──────────────────────────────────────────
|
|
@@ -244,6 +244,22 @@ export class DatabaseSessionHandler implements SessionHandler {
|
|
|
244
244
|
return this.sqliteHandle;
|
|
245
245
|
}
|
|
246
246
|
|
|
247
|
+
/**
|
|
248
|
+
* Release the SQLite connection this handler opened, so its file (and the
|
|
249
|
+
* WAL's -wal / -shm side files) is no longer held open: on Windows an open
|
|
250
|
+
* file cannot be deleted or replaced. Idempotent, and the next read or write
|
|
251
|
+
* reopens the connection. A server engine needs nothing here - each call goes
|
|
252
|
+
* through the sync bridge, which holds no connection between calls.
|
|
253
|
+
*/
|
|
254
|
+
close(): void {
|
|
255
|
+
if (this.sqliteHandle === null) return;
|
|
256
|
+
try {
|
|
257
|
+
this.sqliteHandle.close();
|
|
258
|
+
} finally {
|
|
259
|
+
this.sqliteHandle = null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
247
263
|
private get engine(): string {
|
|
248
264
|
return this.target === null ? "sqlite" : this.target.engine;
|
|
249
265
|
}
|