@jskit-ai/jskit-catalog 0.2.115 → 0.2.117
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/app-guidance/AGENTS.block.md +47 -0
- package/catalog/packages.json +160 -160
- package/package.json +2 -1
- package/scripts/agents-block.mjs +121 -0
- package/scripts/browser-test-build.mjs +2 -2
- package/scripts/browser-test-servers.mjs +61 -46
- package/scripts/jskit.mjs +42 -7
- package/scripts/test-command.mjs +66 -36
- package/scripts/test-databases.mjs +6 -3
- package/scripts/test-environment.mjs +8 -4
- package/scripts/test-network-guard-preload.mjs +5 -0
- package/scripts/test-network-guard.mjs +133 -0
- package/scripts/test-runs.mjs +16 -0
- package/scripts/test-sources.mjs +256 -0
package/scripts/test-command.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { toPosixPath } from "./files.mjs";
|
|
|
8
8
|
import { BUDGET_VARIABLE, testConcurrency } from "./test-budget.mjs";
|
|
9
9
|
import { DATABASES_OPTION, testDatabaseRunFor } from "./test-databases.mjs";
|
|
10
10
|
import { useTestAppEnvironment } from "./test-environment.mjs";
|
|
11
|
+
import { networkGuardEnvironment, withoutNetworkGuard } from "./test-network-guard.mjs";
|
|
11
12
|
import { STOPS_VARIABLE } from "./test-file-stop.mjs";
|
|
12
13
|
import { reportTestTimes, writeFileStops } from "./test-time-report.mjs";
|
|
13
14
|
|
|
@@ -24,7 +25,10 @@ import { reportTestTimes, writeFileStops } from "./test-time-report.mjs";
|
|
|
24
25
|
// should run files in parallel never silently runs them one at a time. A budget set to what the databases allow
|
|
25
26
|
// (V64_TEST_CONCURRENCY) runs that way on purpose. With --list it prints the files that run would take, one per line,
|
|
26
27
|
// then `Total: <n> file(s)` (the closing line Playwright's --list prints), and runs nothing: a host checks that a run
|
|
27
|
-
// of named files takes exactly those before it sends them anywhere.
|
|
28
|
+
// of named files takes exactly those before it sends them anywhere. Every test file, and every process it starts with
|
|
29
|
+
// its environment, reaches only this machine and the test database (test-network-guard.mjs); a file that must reach
|
|
30
|
+
// an outside service says why on its first line, `// jskit-test: network - <reason>`, and runs without that guard, in
|
|
31
|
+
// a parallel run of its own after the others.
|
|
28
32
|
|
|
29
33
|
// node --test's own default (Node 26) when it is given no files.
|
|
30
34
|
const DEFAULT_PATTERN = "**/{test,test/**/*,test-*,*[._-]test}.{js,mjs,cjs,ts,mts,cts}";
|
|
@@ -35,7 +39,11 @@ const TEST_LIKE_PATTERN = "**/tests/**/*[._-]{integration,spec,specs,tests}.{js,
|
|
|
35
39
|
const OTHER_RUNNER_FOLDER = /(?:^|\/)(?:e2e|browser)\//u;
|
|
36
40
|
const OTHER_RUNNER_IMPORT = /\b(?:from|import|require)\s*\(?\s*["'](?:vitest|@playwright\/test)["']/u;
|
|
37
41
|
const MARKER = /^\s*\/\/\s*jskit-test:(.*)$/u;
|
|
38
|
-
const
|
|
42
|
+
const MARKED = /^\s*(alone|network)\s+-\s+(\S.*)$/u;
|
|
43
|
+
const MARKER_FORMS = Object.freeze({
|
|
44
|
+
alone: "`// jskit-test: alone - <why this file cannot run beside others>`",
|
|
45
|
+
network: "`// jskit-test: network - <why this file must reach an outside service>`"
|
|
46
|
+
});
|
|
39
47
|
const SHARD = "--test-shard";
|
|
40
48
|
// A run of only some of its files' tests, by name or `only`, says nothing about how long a whole file takes.
|
|
41
49
|
const TEST_FILTER = /^--test-(?:name-pattern|skip-pattern|only)(?:=|$)/u;
|
|
@@ -64,12 +72,13 @@ function missedTestFiles(defaultFiles, cwd) {
|
|
|
64
72
|
}
|
|
65
73
|
|
|
66
74
|
/**
|
|
67
|
-
* The files of a run that must run alone, from their first line. A marker that is
|
|
68
|
-
* (after a shebang) is an error, so a file never runs in parallel
|
|
69
|
-
*
|
|
75
|
+
* The files of a run that must run alone, or reach an outside service, from their first line. A marker that is
|
|
76
|
+
* malformed or not on the first line (after a shebang) is an error, so a file never runs in parallel, or unguarded,
|
|
77
|
+
* because its marker was missed.
|
|
78
|
+
* @returns {{ alone: Array<{ file: string, reason: string }>, network: Array<{ file: string, reason: string }>, problems: string[] }}
|
|
70
79
|
*/
|
|
71
|
-
function
|
|
72
|
-
const
|
|
80
|
+
function readMarkedFiles(files, cwd) {
|
|
81
|
+
const marked = { alone: [], network: [] };
|
|
73
82
|
const problems = [];
|
|
74
83
|
for (const file of files) {
|
|
75
84
|
const lines = readFileSync(path.resolve(cwd, file), "utf8").split("\n");
|
|
@@ -77,44 +86,49 @@ function readAloneFiles(files, cwd) {
|
|
|
77
86
|
lines.forEach((line, index) => {
|
|
78
87
|
const marker = MARKER.exec(line);
|
|
79
88
|
if (!marker) return;
|
|
80
|
-
const reason =
|
|
89
|
+
const [, kind, reason] = MARKED.exec(marker[1]) || [];
|
|
90
|
+
const meant = /^\s*network\b/u.test(marker[1]) ? MARKER_FORMS.network : MARKER_FORMS.alone;
|
|
81
91
|
if (index !== top) problems.push(`${file}:${index + 1}: a jskit-test marker belongs on the file's first line.`);
|
|
82
|
-
else if (!reason) problems.push(`${file}:${index + 1}: write it as
|
|
83
|
-
else
|
|
92
|
+
else if (!reason?.trim()) problems.push(`${file}:${index + 1}: write it as ${meant}.`);
|
|
93
|
+
else marked[kind].push({ file, reason: reason.trim() });
|
|
84
94
|
});
|
|
85
95
|
}
|
|
86
|
-
return {
|
|
96
|
+
return { ...marked, problems };
|
|
87
97
|
}
|
|
88
98
|
|
|
89
|
-
/** A reporter's file destination for
|
|
90
|
-
function
|
|
99
|
+
/** A reporter's file destination for a run of marked files, beside the parallel run's (`<name>.<kind><ext>`); streams stay. */
|
|
100
|
+
function markedDestination(destination, kind) {
|
|
91
101
|
if (STREAM_DESTINATIONS.has(destination)) return destination;
|
|
92
102
|
const { dir, name, ext } = path.parse(destination);
|
|
93
|
-
return path.join(dir, `${name}
|
|
103
|
+
return path.join(dir, `${name}.${kind}${ext}`);
|
|
94
104
|
}
|
|
95
105
|
|
|
96
106
|
/**
|
|
97
|
-
*
|
|
98
|
-
* `
|
|
107
|
+
* A run of marked files' options: the parallel run's, with each file destination moved beside it and without the
|
|
108
|
+
* shard, which `markedShard` has already applied to those files.
|
|
99
109
|
* @param {string[]} options
|
|
110
|
+
* @param {"alone" | "network"} kind
|
|
100
111
|
*/
|
|
101
|
-
function
|
|
112
|
+
function markedRunOptions(options, kind) {
|
|
102
113
|
const result = [];
|
|
103
114
|
for (let index = 0; index < options.length; index += 1) {
|
|
104
115
|
const option = options[index];
|
|
105
116
|
if (option === SHARD) index += 1;
|
|
106
117
|
else if (option.startsWith(`${SHARD}=`)) continue;
|
|
107
118
|
else if (option === DESTINATION && index + 1 < options.length) {
|
|
108
|
-
result.push(option,
|
|
119
|
+
result.push(option, markedDestination(options[index + 1], kind));
|
|
109
120
|
index += 1;
|
|
110
|
-
} else if (option.startsWith(`${DESTINATION}=`)) result.push(`${DESTINATION}=${
|
|
121
|
+
} else if (option.startsWith(`${DESTINATION}=`)) result.push(`${DESTINATION}=${markedDestination(option.slice(DESTINATION.length + 1), kind)}`);
|
|
111
122
|
else result.push(option);
|
|
112
123
|
}
|
|
113
124
|
return result;
|
|
114
125
|
}
|
|
115
126
|
|
|
116
|
-
/**
|
|
117
|
-
|
|
127
|
+
/**
|
|
128
|
+
* The marked files (alone or network) of this run's shard (`--test-shard=<index>/<total>`), as node --test picks a
|
|
129
|
+
* shard's files.
|
|
130
|
+
*/
|
|
131
|
+
function markedShard(files, options) {
|
|
118
132
|
const at = options.findIndex((option) => option === SHARD || option.startsWith(`${SHARD}=`));
|
|
119
133
|
if (at < 0) return files;
|
|
120
134
|
const [index, total] = (options[at] === SHARD ? options[at + 1] : options[at].slice(SHARD.length + 1)).split("/").map(Number);
|
|
@@ -122,7 +136,9 @@ function aloneShard(files, options) {
|
|
|
122
136
|
}
|
|
123
137
|
|
|
124
138
|
/**
|
|
125
|
-
* The node --test runs for these arguments: one in parallel within the budget, then the files that must
|
|
139
|
+
* The node --test runs for these arguments: one in parallel within the budget, then the files that must reach an
|
|
140
|
+
* outside service, in parallel too, then the files that must run alone. `guarded` says, for each run, whether its
|
|
141
|
+
* processes get the network guard: all but the run of network files.
|
|
126
142
|
* @param {string[]} args the arguments after `jskit test`
|
|
127
143
|
* @param {{ cwd?: string, concurrency?: number }} [options]
|
|
128
144
|
*/
|
|
@@ -144,24 +160,34 @@ function planTestRuns(args, { cwd = process.cwd(), concurrency = testConcurrency
|
|
|
144
160
|
`- ${missed.join("\n- ")}\nRename each to end in .test.js (a database test: <name>.integration.test.js), or ` +
|
|
145
161
|
"name the files to run.");
|
|
146
162
|
}
|
|
147
|
-
const { alone, problems } =
|
|
163
|
+
const { alone, network, problems } = readMarkedFiles(files, cwd);
|
|
148
164
|
if (problems.length > 0) throw new Error(`jskit test:\n- ${problems.join("\n- ")}`);
|
|
149
165
|
const parallel = ["--test", `--test-concurrency=${concurrency}`];
|
|
150
|
-
if (alone.length < 1
|
|
166
|
+
if (alone.length < 1 && network.length < 1) {
|
|
167
|
+
return { concurrency, files: files.length, paths: files, alone, network, runs: [[...parallel, ...args]], guarded: [true] };
|
|
168
|
+
}
|
|
151
169
|
|
|
152
170
|
const options = args.filter((argument) => !(matched.get(argument)?.length > 0));
|
|
153
|
-
const
|
|
154
|
-
const others = files.filter((file) => !
|
|
155
|
-
const
|
|
171
|
+
const marked = new Set([...alone, ...network].map((entry) => entry.file));
|
|
172
|
+
const others = files.filter((file) => !marked.has(file));
|
|
173
|
+
const shardNetwork = markedShard(network.map((entry) => entry.file), options);
|
|
174
|
+
const shardAlone = markedShard(alone.map((entry) => entry.file), options);
|
|
175
|
+
const runs = [
|
|
176
|
+
...(others.length > 0 ? [{ run: [...parallel, ...options, ...others], guarded: true }] : []),
|
|
177
|
+
...(shardNetwork.length > 0 ? [{ run: [...parallel, ...markedRunOptions(options, "network"), ...shardNetwork], guarded: false }] : []),
|
|
178
|
+
...(shardAlone.length > 0
|
|
179
|
+
? [{ run: ["--test", "--test-concurrency=1", ...markedRunOptions(options, "alone"), ...shardAlone], guarded: true }]
|
|
180
|
+
: [])
|
|
181
|
+
];
|
|
156
182
|
return {
|
|
157
183
|
concurrency,
|
|
158
|
-
files:
|
|
184
|
+
// The most files running at once: the guarded ones, then the network ones, each run in parallel.
|
|
185
|
+
files: Math.max(others.length, network.length),
|
|
159
186
|
paths: files,
|
|
160
187
|
alone,
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
]
|
|
188
|
+
network,
|
|
189
|
+
runs: runs.map(({ run }) => run),
|
|
190
|
+
guarded: runs.map(({ guarded }) => guarded)
|
|
165
191
|
};
|
|
166
192
|
}
|
|
167
193
|
|
|
@@ -247,6 +273,7 @@ async function runTests(args) {
|
|
|
247
273
|
}
|
|
248
274
|
process.stderr.write(`jskit test: ${plan.concurrency} test file(s) at a time (${databases ? "test databases" : source}).\n`);
|
|
249
275
|
for (const { file, reason } of plan.alone) process.stderr.write(`jskit test: ${file} runs alone: ${reason}\n`);
|
|
276
|
+
for (const { file, reason } of plan.network) process.stderr.write(`jskit test: ${file} reaches the network: ${reason}\n`);
|
|
250
277
|
const preload = [...(databases?.preload ? ["--import", pathToFileURL(databases.preload).href] : []), "--import", FILE_STOP];
|
|
251
278
|
const timesDirectory = mkdtempSync(path.join(os.tmpdir(), "jskit-test-times-"));
|
|
252
279
|
const stops = writeFileStops({ cwd: process.cwd(), files: plan.paths, directory: timesDirectory });
|
|
@@ -259,7 +286,11 @@ async function runTests(args) {
|
|
|
259
286
|
const env = {
|
|
260
287
|
NODE_COMPILE_CACHE: process.env.NODE_COMPILE_CACHE || path.resolve(COMPILE_CACHE),
|
|
261
288
|
[STOPS_VARIABLE]: stops,
|
|
262
|
-
...databases?.env
|
|
289
|
+
...databases?.env,
|
|
290
|
+
// Its test files, and what they start, reach only this machine and the test database; network files, anywhere.
|
|
291
|
+
...(plan.guarded[index]
|
|
292
|
+
? networkGuardEnvironment(process.env, "jskit test")
|
|
293
|
+
: { NODE_OPTIONS: withoutNetworkGuard(process.env.NODE_OPTIONS) })
|
|
263
294
|
};
|
|
264
295
|
const { code, signal } = await runNode([...preload, ...withTimeReporter(run, collected[index])], env);
|
|
265
296
|
if (exitCode === 0) exitCode = code;
|
|
@@ -278,9 +309,8 @@ async function runTests(args) {
|
|
|
278
309
|
if (exitCode === 0) exitCode = 1;
|
|
279
310
|
}
|
|
280
311
|
} finally {
|
|
281
|
-
// However the run ended,
|
|
282
|
-
|
|
283
|
-
if (ended) process.stderr.write(`jskit test: ${ended}.\n`);
|
|
312
|
+
// However the run ended, its settings go; its test databases stay for the next run, which restores them.
|
|
313
|
+
await databases?.cleanup();
|
|
284
314
|
rmSync(timesDirectory, { recursive: true, force: true });
|
|
285
315
|
}
|
|
286
316
|
return exitCode;
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import process from "node:process";
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import { readTableResourceSources } from "./data-access.mjs";
|
|
7
|
+
import { useTestAppEnvironment } from "./test-environment.mjs";
|
|
7
8
|
|
|
8
9
|
// `jskit test --databases`: each test file running at once gets a database of its own, a copy of TEST_DB_NAME restored
|
|
9
10
|
// from a schema snapshot, from the application's installed @jskit-ai/database-runtime and its knexfile.js, which loads
|
|
@@ -123,8 +124,8 @@ async function applicationTestDatabases(cwd, command) {
|
|
|
123
124
|
|
|
124
125
|
/**
|
|
125
126
|
* The run's databases for `count` files at once, or one file at a time on the connected database. Its `cleanup()` ends
|
|
126
|
-
* the run: it removes the run's settings and
|
|
127
|
-
*
|
|
127
|
+
* the run: it removes the run's settings, and the databases stay for the next run (an installed
|
|
128
|
+
* @jskit-ai/database-runtime from before drops the numbered copies, and answers what it dropped).
|
|
128
129
|
* @param {number} count at most the run's test budget, and no more than its test files
|
|
129
130
|
* @param {string} [cwd]
|
|
130
131
|
* @returns {Promise<{ concurrency: number, env: Record<string, string>, preload: string, summary: string,
|
|
@@ -137,12 +138,14 @@ async function testDatabaseRunFor(count, cwd = process.cwd()) {
|
|
|
137
138
|
|
|
138
139
|
/**
|
|
139
140
|
* `jskit migration-history`: the full-history migration proof of the application in `cwd` (proveMigrationHistory() in
|
|
140
|
-
* @jskit-ai/database-runtime), written to stdout, or why it failed to stderr. Answers the exit code.
|
|
141
|
+
* @jskit-ai/database-runtime), written to stdout, or why it failed to stderr. Answers the exit code. It runs as
|
|
142
|
+
* APP_ENV=test, as `jskit test` does, and throws where APP_ENV is staging or production.
|
|
141
143
|
* @param {string} [cwd]
|
|
142
144
|
* @returns {Promise<number>}
|
|
143
145
|
*/
|
|
144
146
|
async function runMigrationHistory(cwd = process.cwd()) {
|
|
145
147
|
const command = "jskit migration-history";
|
|
148
|
+
useTestAppEnvironment(process.env, command);
|
|
146
149
|
try {
|
|
147
150
|
const { knexConfig, schema, environment, runtime } = await applicationTestDatabases(cwd, command);
|
|
148
151
|
if (!runtime.proveMigrationHistory) {
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
// Tests run as APP_ENV=test: `jskit test` and the browser test servers set it, whatever the
|
|
2
|
-
// never sends real email or payments and the test databases may be prepared. A shell whose
|
|
3
|
-
// production belongs to a staging or production server, and no test runs there.
|
|
1
|
+
// Tests run as APP_ENV=test: `jskit test`, `jskit migration-history` and the browser test servers set it, whatever the
|
|
2
|
+
// shell says, so a test never sends real email or payments and the test databases may be prepared. A shell whose
|
|
3
|
+
// APP_ENV is staging or production belongs to a staging or production server, and no test runs there. They log at
|
|
4
|
+
// warn unless the shell's LOG_LEVEL asks for more, so a test server does not log every request and a failure stays
|
|
5
|
+
// readable (an app's logger options take their level from LOG_LEVEL).
|
|
4
6
|
|
|
5
7
|
const STAGING_AND_PRODUCTION = Object.freeze(["staging", "production"]);
|
|
6
8
|
|
|
7
9
|
/**
|
|
8
|
-
* Sets `env.APP_ENV` to test,
|
|
10
|
+
* Sets `env.APP_ENV` to test, and `env.LOG_LEVEL` to warn when it names no level; throws, naming the fix, when APP_ENV
|
|
11
|
+
* says staging or production.
|
|
9
12
|
* @param {Record<string, string | undefined>} env The process environment, changed in place.
|
|
10
13
|
* @param {string} command The command that runs the tests, for the refusal.
|
|
11
14
|
*/
|
|
@@ -18,6 +21,7 @@ function useTestAppEnvironment(env, command) {
|
|
|
18
21
|
);
|
|
19
22
|
}
|
|
20
23
|
env.APP_ENV = "test";
|
|
24
|
+
if (!String(env.LOG_LEVEL ?? "").trim()) env.LOG_LEVEL = "warn";
|
|
21
25
|
}
|
|
22
26
|
|
|
23
27
|
export { useTestAppEnvironment };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Preloaded through NODE_OPTIONS (`--import`) into every process `jskit test` and the browser test servers start, and
|
|
2
|
+
// so into the processes those start with the same environment: guards its outbound connections (test-network-guard.mjs).
|
|
3
|
+
import { installNetworkGuard } from "./test-network-guard.mjs";
|
|
4
|
+
|
|
5
|
+
installNetworkGuard();
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// The test network guard: a test, and every app server and process it starts, reaches only this machine and the test
|
|
2
|
+
// database. `jskit test` and the browser test servers give their processes NODE_OPTIONS with the guard's preload
|
|
3
|
+
// (test-network-guard-preload.mjs), so a process those start with the same environment is guarded too. Every outbound
|
|
4
|
+
// TCP connection a guarded Node process makes passes through net.Socket.prototype.connect (net.connect, tls.connect,
|
|
5
|
+
// http and https agents, fetch); the guard lets through loopback addresses, `localhost` names, unix sockets and named
|
|
6
|
+
// pipes, and the database host the environment names (DB_HOST, DATABASE_URL's host, read when the connection is made),
|
|
7
|
+
// and refuses every other host before any name is looked up: the socket fails with JSKIT_TEST_NETWORK_REFUSED, naming
|
|
8
|
+
// the host and the fix, and the same line goes to stderr once per host, so an app that swallows the error still shows
|
|
9
|
+
// it. A test that reaches a real outside service (an AI provider, a payment or mail API, a hosting API) costs money,
|
|
10
|
+
// sends real messages or changes real data whenever a developer's keys sit in the environment the test inherits. A file
|
|
11
|
+
// that must reach one says why on its first line, `// jskit-test: network - <reason>`, and `jskit test` runs it
|
|
12
|
+
// without the guard (test-command.mjs).
|
|
13
|
+
import net from "node:net";
|
|
14
|
+
import process from "node:process";
|
|
15
|
+
|
|
16
|
+
const NETWORK_REFUSED_CODE = "JSKIT_TEST_NETWORK_REFUSED";
|
|
17
|
+
// Names the command whose processes are guarded, for the refusal: `jskit test` or `jskit browser tests`.
|
|
18
|
+
const NETWORK_GUARD_VARIABLE = "JSKIT_TEST_NETWORK_GUARD";
|
|
19
|
+
const NETWORK_GUARD_PRELOAD = new URL("./test-network-guard-preload.mjs", import.meta.url).href;
|
|
20
|
+
const PRELOAD_OPTION = `--import=${NETWORK_GUARD_PRELOAD}`;
|
|
21
|
+
const INSTALLED = Symbol.for("@jskit-ai/jskit-catalog/testNetworkGuard");
|
|
22
|
+
const BROWSER_TESTS = "jskit browser tests";
|
|
23
|
+
|
|
24
|
+
// This machine: IPv4 loopback, IPv6 loopback and IPv4 loopback mapped into IPv6, and the unspecified addresses, which
|
|
25
|
+
// a connection on Linux reaches as this machine (a test connecting to the address its server listened on, `::`).
|
|
26
|
+
const LOOPBACK = new net.BlockList();
|
|
27
|
+
LOOPBACK.addSubnet("127.0.0.0", 8, "ipv4");
|
|
28
|
+
LOOPBACK.addAddress("0.0.0.0", "ipv4");
|
|
29
|
+
LOOPBACK.addAddress("::1", "ipv6");
|
|
30
|
+
LOOPBACK.addAddress("::", "ipv6");
|
|
31
|
+
LOOPBACK.addSubnet("::ffff:127.0.0.0", 104, "ipv6");
|
|
32
|
+
|
|
33
|
+
const hostName = (host) => String(host ?? "").trim().toLowerCase().replace(/^\[(.*)\]$/u, "$1").replace(/\.$/u, "");
|
|
34
|
+
|
|
35
|
+
/** The database hosts the environment names now: DB_HOST, and DATABASE_URL's host. */
|
|
36
|
+
function databaseHosts(env) {
|
|
37
|
+
const hosts = [hostName(env.DB_HOST)];
|
|
38
|
+
try {
|
|
39
|
+
hosts.push(hostName(new URL(String(env.DATABASE_URL ?? "")).hostname));
|
|
40
|
+
} catch {
|
|
41
|
+
// No DATABASE_URL, or one that names no host.
|
|
42
|
+
}
|
|
43
|
+
return hosts.filter(Boolean);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether a guarded test process may connect to `host`: loopback, a `localhost` name, or a database host `env` names.
|
|
48
|
+
* @param {string} host
|
|
49
|
+
* @param {Record<string, string | undefined>} env
|
|
50
|
+
*/
|
|
51
|
+
function isAllowedTestHost(host, env) {
|
|
52
|
+
const name = hostName(host);
|
|
53
|
+
if (name === "localhost" || name.endsWith(".localhost") || databaseHosts(env).includes(name)) return true;
|
|
54
|
+
const family = net.isIP(name);
|
|
55
|
+
return family !== 0 && LOOPBACK.check(name, family === 4 ? "ipv4" : "ipv6");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** NODE_OPTIONS without the guard's preload. */
|
|
59
|
+
function withoutNetworkGuard(nodeOptions) {
|
|
60
|
+
return String(nodeOptions ?? "").split(PRELOAD_OPTION).map((part) => part.trim()).filter(Boolean).join(" ");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The variables that guard the processes started with them: NODE_OPTIONS with the guard's preload added once, and the
|
|
65
|
+
* command that guards them, for the refusal.
|
|
66
|
+
* @param {Record<string, string | undefined>} env the environment the processes would get
|
|
67
|
+
* @param {string} command `jskit test` or `jskit browser tests`
|
|
68
|
+
*/
|
|
69
|
+
function networkGuardEnvironment(env, command) {
|
|
70
|
+
return {
|
|
71
|
+
NODE_OPTIONS: [withoutNetworkGuard(env.NODE_OPTIONS), PRELOAD_OPTION].filter(Boolean).join(" "),
|
|
72
|
+
[NETWORK_GUARD_VARIABLE]: command
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function refusal(command, host, port) {
|
|
77
|
+
const target = `${host}${port ? `:${port}` : ""}`;
|
|
78
|
+
const fix = command === BROWSER_TESTS
|
|
79
|
+
? "Stub it at the seam the app already uses: a test-only driver or env value, in browserTestConfig()'s `env` or its " +
|
|
80
|
+
"`prepare` module, pointing at a local fake."
|
|
81
|
+
: "Stub it at the seam the app already uses (an injected client or provider double, a test-only env value pointing " +
|
|
82
|
+
"at a local fake); a test file that must reach it says why on its first line: `// jskit-test: network - <reason>`.";
|
|
83
|
+
const error = new Error(`${command} refused a connection to ${target}: tests never reach an outside service. ${fix} ` +
|
|
84
|
+
"Tests reach only loopback, unix sockets and the database host (DB_HOST, DATABASE_URL).");
|
|
85
|
+
return Object.assign(error, { code: NETWORK_REFUSED_CODE, host, port });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Where a call to net.Socket.prototype.connect goes, as net reads its arguments: a path, or a host and port. */
|
|
89
|
+
function connectTarget(args) {
|
|
90
|
+
let first = args[0];
|
|
91
|
+
// net.connect() hands the socket its arguments already read, as an array.
|
|
92
|
+
if (Array.isArray(first)) first = first[0];
|
|
93
|
+
if (first !== null && typeof first === "object") {
|
|
94
|
+
if (first.path) return { path: String(first.path) };
|
|
95
|
+
return { host: first.host || "localhost", port: first.port };
|
|
96
|
+
}
|
|
97
|
+
if (typeof first === "string" && !/^\s*\d+\s*$/u.test(first)) return { path: first };
|
|
98
|
+
return { host: typeof args[1] === "string" && args[1] ? args[1] : "localhost", port: first };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Guards this process's outbound connections. Calling it again changes nothing.
|
|
103
|
+
* @param {{ env?: Record<string, string | undefined>, command?: string, stderr?: { write(text: string): unknown } }} [options]
|
|
104
|
+
*/
|
|
105
|
+
function installNetworkGuard({ env = process.env, command = env[NETWORK_GUARD_VARIABLE] || "jskit test", stderr = process.stderr } = {}) {
|
|
106
|
+
if (net.Socket.prototype.connect[INSTALLED]) return;
|
|
107
|
+
const connect = net.Socket.prototype.connect;
|
|
108
|
+
const reported = new Set();
|
|
109
|
+
function guardedConnect(...args) {
|
|
110
|
+
const target = connectTarget(args);
|
|
111
|
+
if (target.path !== undefined || isAllowedTestHost(target.host, env)) return connect.apply(this, args);
|
|
112
|
+
const error = refusal(command, hostName(target.host), target.port);
|
|
113
|
+
if (!reported.has(error.host)) {
|
|
114
|
+
reported.add(error.host);
|
|
115
|
+
stderr.write(`${error.message}\n`);
|
|
116
|
+
}
|
|
117
|
+
// As a failed connection does: the error comes after connect() returns, so its caller's listeners hear it.
|
|
118
|
+
process.nextTick(() => this.destroy(error));
|
|
119
|
+
return this;
|
|
120
|
+
}
|
|
121
|
+
guardedConnect[INSTALLED] = true;
|
|
122
|
+
net.Socket.prototype.connect = guardedConnect;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export {
|
|
126
|
+
NETWORK_GUARD_PRELOAD,
|
|
127
|
+
NETWORK_GUARD_VARIABLE,
|
|
128
|
+
NETWORK_REFUSED_CODE,
|
|
129
|
+
installNetworkGuard,
|
|
130
|
+
isAllowedTestHost,
|
|
131
|
+
networkGuardEnvironment,
|
|
132
|
+
withoutNetworkGuard
|
|
133
|
+
};
|
package/scripts/test-runs.mjs
CHANGED
|
@@ -10,6 +10,8 @@ import { fileExists, toPosixPath } from "./files.mjs";
|
|
|
10
10
|
// The one exception is a test file's own first line, `// jskit-test: alone - <reason>`, which `jskit test` honours.
|
|
11
11
|
// A Playwright config those scripts use bounds its whole run (globalTimeout) and, when it starts the app (webServer),
|
|
12
12
|
// does so through browserTestConfig(): the production build, and a server, port and database for each worker.
|
|
13
|
+
// An app's server/lib/loggerOptions.js (the foundation patterns') takes its level from LOG_LEVEL, which `jskit test` and
|
|
14
|
+
// the browser test servers set to warn, so a test server does not log every request.
|
|
13
15
|
|
|
14
16
|
const GUIDE = "https://mobily-enterprises.github.io/jskit-ai/guide/framework/typed-features#test-files-run-in-parallel";
|
|
15
17
|
const BUDGET_MODULE = "@jskit-ai/jskit-catalog/test-budget";
|
|
@@ -21,6 +23,7 @@ const PINNED_BUDGET = /^(?:V64_TEST_CONCURRENCY|PLAYWRIGHT_WORKERS)=/u;
|
|
|
21
23
|
const CONFIG_EXTENSIONS = Object.freeze(["ts", "mts", "cts", "js", "mjs", "cjs"]);
|
|
22
24
|
const SCRIPT_FILE = /\.(?:[cm]?[jt]s|jsx|tsx)$/u;
|
|
23
25
|
const FIXED_PLAYWRIGHT_WORKERS = /^(?:--workers(?:=.*)?|-j.*)$/u;
|
|
26
|
+
const LOGGER_OPTIONS = "server/lib/loggerOptions.js";
|
|
24
27
|
const FIXED_VITEST_WORKERS = /^--(?:max-?[wW]orkers|min-?[wW]orkers|no-file-?[pP]arallelism|file-?[pP]arallelism)(?:=.*)?$/u;
|
|
25
28
|
|
|
26
29
|
function commandsOf(script) {
|
|
@@ -127,6 +130,18 @@ function checkPlaywrightIsolation({ file, source, report }) {
|
|
|
127
130
|
}
|
|
128
131
|
}
|
|
129
132
|
|
|
133
|
+
// The app's logger options take their level from LOG_LEVEL.
|
|
134
|
+
async function checkLoggerLevel({ root, report }) {
|
|
135
|
+
const file = path.join(root, LOGGER_OPTIONS);
|
|
136
|
+
if (!(await fileExists(file))) return;
|
|
137
|
+
const source = await readFile(file, "utf8");
|
|
138
|
+
if (source.includes("LOG_LEVEL")) return;
|
|
139
|
+
report({ file: LOGGER_OPTIONS, line: lineOf(source, "function buildLoggerOptions"), rule: "test/log-level",
|
|
140
|
+
message: "buildLoggerOptions() takes no level from LOG_LEVEL, so a test server logs every request at info: give its " +
|
|
141
|
+
'options `level: String(runtimeEnv.LOG_LEVEL || "").trim() || "info"` and pass it server.js\'s runtimeEnv; ' +
|
|
142
|
+
"`jskit test` and the browser test servers set LOG_LEVEL=warn." });
|
|
143
|
+
}
|
|
144
|
+
|
|
130
145
|
// A config sets the runner's workers from the budget, and Vitest's never turns file parallelism off.
|
|
131
146
|
async function checkRunnerConfig({ root, configPath, directory, runner, report }) {
|
|
132
147
|
const { rule, setting, configNames, budget } = RUNNERS[runner];
|
|
@@ -196,6 +211,7 @@ async function checkTestRuns({ projectRoot, manifests }) {
|
|
|
196
211
|
}
|
|
197
212
|
}
|
|
198
213
|
for (const config of configs.values()) await checkRunnerConfig({ root, report, ...config });
|
|
214
|
+
await checkLoggerLevel({ root, report });
|
|
199
215
|
findings.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);
|
|
200
216
|
return { ok: findings.length < 1, findings, manifests: manifests.length };
|
|
201
217
|
}
|