@jskit-ai/jskit-catalog 0.2.141 → 0.2.142

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.
@@ -0,0 +1,398 @@
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ appendFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync
5
+ } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+
10
+ // `jskit verify`: an app's whole check (its Verification), the npm scripts package.json's jskitVerify.parts names, run
11
+ // in order and stopped at the first that fails, kept once per exact tree: a check that passed on the exact tree is never
12
+ // run again. A whole run that passes records exactly what it checked in node_modules/.cache/jskit/verify-passes/, and a
13
+ // whole run on the same inputs prints that record and runs nothing. The inputs are the project's tree (the tree of
14
+ // HEAD, with no working change), the trees of the other checkouts the run uses (jskitVerify.checkouts, a module of the
15
+ // app's that names them), every checkout's installed dependencies, the declared settings (jskitVerify.settings: a value
16
+ // naming a checkout, or a folder in one, is that checkout's tree, one naming a file is its contents, any other its
17
+ // digest, never the value itself), Node's version and the parts. A checkout with working changes, a setting naming a
18
+ // folder outside Git or one Git ignores, inputs that can't be read, a failed or interrupted run, a tree that changed
19
+ // while it ran, and a run of named files (`jskit verify <args>`, which go to the last part) run and record nothing.
20
+ //
21
+ // `jskit verify-pass`: the same rule for a CI run, which installs everything afresh: GitHub Actions keeps a passing
22
+ // run's record as an artifact named for the project's tree and the other repositories' commits it checked out, and this
23
+ // command names it, asks GitHub whether one is kept, and writes `name` and `reuse` to the step's outputs.
24
+
25
+ const GUIDE = "https://mobily-enterprises.github.io/jskit-ai/guide/framework/typed-features#a-check-runs-once-per-tree";
26
+ const SCHEMA = "jskit.verify-pass.v1";
27
+ const CI_SCHEMA = "jskit.verify-ci-pass.v1";
28
+ /** Where a project keeps its passes, relative to its root. */
29
+ export const PASS_FOLDER = path.join("node_modules", ".cache", "jskit", "verify-passes");
30
+ // What a run writes into node_modules as it goes (jskit test's file times, these records, Vite's caches), left out of
31
+ // the installed dependencies' fingerprint.
32
+ const RUN_CACHES = new Set([".cache", ".vite", ".vite-temp"]);
33
+ const SETTING_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*\*?$/u;
34
+ const COMMIT_ID = /^[0-9a-f]{40}$/u;
35
+ const CHECKOUT_NAME = /^[A-Za-z0-9][\w.-]*$/u;
36
+ const RUNS_ITSELF = /\bjskit\s+verify\b/u;
37
+
38
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
39
+ const short = (id) => String(id || "").slice(0, 12);
40
+
41
+ /** Git, reading only: no optional locks, and none of a hook's or caller's GIT_* settings. */
42
+ function git(root, args) {
43
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")));
44
+ return execFileSync("git", ["-C", root, ...args], {
45
+ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...env, GIT_OPTIONAL_LOCKS: "0" }, maxBuffer: 64 * 1024 * 1024
46
+ }).trim();
47
+ }
48
+
49
+ /**
50
+ * package.json's jskitVerify: the parts (npm scripts, each with the settings only it gets), the settings that are
51
+ * inputs, and the module naming the other checkouts. It throws, naming the fix, on a declaration it can't run.
52
+ * @param {string} projectRoot
53
+ */
54
+ export function readVerifyConfig(projectRoot) {
55
+ const manifestFile = path.join(projectRoot, "package.json");
56
+ const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
57
+ const declared = manifest.jskitVerify;
58
+ if (!declared || typeof declared !== "object" || !Array.isArray(declared.parts) || declared.parts.length === 0) {
59
+ throw new Error(`${manifestFile} declares no jskitVerify.parts, the npm scripts jskit verify runs in order: declare ` +
60
+ `them (${GUIDE}).`);
61
+ }
62
+ const scripts = manifest.scripts || {};
63
+ const parts = declared.parts.map((part) => {
64
+ const { script, env = {} } = typeof part === "string" ? { script: part } : (part ?? {});
65
+ if (typeof script !== "string" || !script || typeof env !== "object" || Array.isArray(env) ||
66
+ Object.values(env).some((value) => typeof value !== "string")) {
67
+ throw new Error(`jskitVerify.parts holds ${JSON.stringify(part)}: a part is a script's name, or { "script": "<name>", ` +
68
+ `"env": { "<NAME>": "<value>" } } (${GUIDE}).`);
69
+ }
70
+ if (typeof scripts[script] !== "string") throw new Error(`jskitVerify.parts names ${script}, which package.json's scripts lack.`);
71
+ if (RUNS_ITSELF.test(scripts[script])) {
72
+ throw new Error(`jskitVerify.parts names ${script}, which runs jskit verify itself: name the scripts it runs instead.`);
73
+ }
74
+ return Object.freeze({ script, env: Object.freeze({ ...env }) });
75
+ });
76
+ const settings = declared.settings ?? [];
77
+ if (!Array.isArray(settings) || settings.some((each) => typeof each !== "string" || !SETTING_PATTERN.test(each))) {
78
+ throw new Error(`jskitVerify.settings is ${JSON.stringify(settings)}: list setting names, a trailing * taking every ` +
79
+ `name it starts (["MYAPP_*", "APP_ENV"]) (${GUIDE}).`);
80
+ }
81
+ const checkouts = declared.checkouts ?? null;
82
+ if (checkouts !== null && (typeof checkouts !== "string" || !checkouts)) {
83
+ throw new Error(`jskitVerify.checkouts is ${JSON.stringify(checkouts)}: name the module, relative to package.json, ` +
84
+ `whose default export names the other checkouts the run uses (${GUIDE}).`);
85
+ }
86
+ return Object.freeze({ parts: Object.freeze(parts), settings: Object.freeze([...settings]), checkouts });
87
+ }
88
+
89
+ /** Whether Git ignores a path of a checkout (`git check-ignore` exits 0 for an ignored path, 1 for one it keeps). */
90
+ function ignored(top, inside) {
91
+ try {
92
+ git(top, ["check-ignore", "--quiet", "--", inside]);
93
+ return true;
94
+ } catch (error) {
95
+ if (error?.status === 1) return false;
96
+ throw error;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The checkout a folder is in, at its exact tree: HEAD's commit and tree, and the folder's path in it; or the problem
102
+ * that makes it none (not in Git, a folder Git ignores, or a checkout with uncommitted changes or untracked files).
103
+ * @param {string} folder
104
+ * @param {string} label how messages name it
105
+ * @returns {{ commit: string, tree: string, path: string } | { problem: string }}
106
+ */
107
+ export function exactTree(folder, label) {
108
+ let top;
109
+ try {
110
+ top = git(folder, ["rev-parse", "--show-toplevel"]);
111
+ } catch {
112
+ return { problem: `${label} names ${folder}, a folder outside Git, whose contents a record can't tell` };
113
+ }
114
+ const changes = git(top, ["status", "--porcelain", "--untracked-files=normal"]);
115
+ if (changes) {
116
+ const count = changes.split("\n").length;
117
+ return { problem: `${label} has ${count} uncommitted change${count === 1 ? "" : "s"} (${top})` };
118
+ }
119
+ const inside = path.relative(realpathSync(top), realpathSync(folder)).split(path.sep).join("/");
120
+ if (inside && ignored(top, inside)) {
121
+ return { problem: `${label} names ${folder}, which Git ignores in ${top}, so its contents are in no tree a record can tell` };
122
+ }
123
+ return { commit: git(top, ["rev-parse", "HEAD"]), tree: git(top, ["rev-parse", "HEAD^{tree}"]), path: inside };
124
+ }
125
+
126
+ /**
127
+ * A checkout's installed dependencies as an input: a digest of every file's path, size and modification time under its
128
+ * node_modules (links as links), so an `npm ci` or a package laid over by hand is another input though the lock is the
129
+ * same. A checkout with none installed is "none", whether or not a run's caches made its node_modules folder.
130
+ * @param {string} root
131
+ */
132
+ export function installedDependencies(root) {
133
+ const top = path.join(root, "node_modules");
134
+ if (!existsSync(top)) return "none";
135
+ const digest = createHash("sha256");
136
+ let files = 0;
137
+ const walk = (dir) => {
138
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
139
+ const file = path.join(dir, entry.name);
140
+ if (entry.isDirectory()) {
141
+ if (!RUN_CACHES.has(entry.name)) walk(file);
142
+ continue;
143
+ }
144
+ const { size, mtimeMs } = lstatSync(file);
145
+ digest.update(`${path.relative(top, file)}\0${size}\0${mtimeMs}\n`);
146
+ files += 1;
147
+ }
148
+ };
149
+ walk(top);
150
+ return files === 0 ? "none" : digest.digest("hex");
151
+ }
152
+
153
+ /** A declared setting as an input: its digest, and the checkouts (a folder in one) and files its value names. */
154
+ function settingInput(name, value) {
155
+ const input = { sha256: sha256(value), checkouts: [], files: [] };
156
+ for (const named of value.split(path.delimiter)) {
157
+ if (!path.isAbsolute(named) || !existsSync(named)) continue;
158
+ const kind = statSync(named);
159
+ if (kind.isFile()) {
160
+ input.files.push({ path: named, sha256: sha256(readFileSync(named)) });
161
+ } else if (kind.isDirectory()) {
162
+ const tree = exactTree(named, name);
163
+ if ("problem" in tree) return tree;
164
+ input.checkouts.push({ path: named, ...tree });
165
+ }
166
+ }
167
+ return input;
168
+ }
169
+
170
+ const declares = (patterns, name) => patterns.some((pattern) => (pattern.endsWith("*")
171
+ ? name.startsWith(pattern.slice(0, -1)) : name === pattern));
172
+
173
+ /** The other checkouts the run uses, by name, from the app's jskitVerify.checkouts module. */
174
+ async function namedCheckouts({ projectRoot, config, env }) {
175
+ if (!config.checkouts) return {};
176
+ // Imported by its contents, so a caller that runs jskit verify again in one process gets the module as it is now.
177
+ const file = path.resolve(projectRoot, config.checkouts);
178
+ const module = await import(`${pathToFileURL(file).href}?sha256=${sha256(readFileSync(file))}`);
179
+ const named = await module.default({ projectRoot, env });
180
+ if (!named || typeof named !== "object" || Object.entries(named).some(([name, folder]) =>
181
+ !CHECKOUT_NAME.test(name) || typeof folder !== "string" || !folder)) {
182
+ throw new Error(`${config.checkouts} names ${JSON.stringify(named)}: its default export returns { "<name>": "<folder>" }`);
183
+ }
184
+ return Object.fromEntries(Object.entries(named).map(([name, folder]) => [name, path.resolve(projectRoot, folder)]));
185
+ }
186
+
187
+ /**
188
+ * What a whole `jskit verify` checks, and its key; or the problem that makes the run no exact check.
189
+ * @param {{ projectRoot: string, config: ReturnType<typeof readVerifyConfig>, env: Record<string, string | undefined>,
190
+ * nodeVersion: string }} run
191
+ * @returns {Promise<{ key: string, inputs: object } | { problem: string }>}
192
+ */
193
+ export async function verifyInputs({ projectRoot, config, env, nodeVersion }) {
194
+ const project = exactTree(projectRoot, "The project");
195
+ if ("problem" in project) return project;
196
+ const checkouts = {};
197
+ for (const [name, folder] of Object.entries(await namedCheckouts({ projectRoot, config, env }))) {
198
+ if (!existsSync(folder)) return { problem: `${name} has no checkout at ${folder}` };
199
+ const tree = exactTree(folder, name);
200
+ if ("problem" in tree) return tree;
201
+ checkouts[name] = { ...tree, dependencies: installedDependencies(folder) };
202
+ }
203
+ const settings = {};
204
+ for (const name of Object.keys(env).filter((each) => declares(config.settings, each)).sort()) {
205
+ const input = settingInput(name, String(env[name] ?? ""));
206
+ if ("problem" in input) return input;
207
+ settings[name] = input;
208
+ }
209
+ const inputs = { schema: SCHEMA, command: "jskit verify", parts: config.parts, node: nodeVersion,
210
+ project: { ...project, dependencies: installedDependencies(projectRoot) }, checkouts, settings };
211
+ // The key is the trees', not the commits': a rebase or an empty commit keeps the tree, and so the pass.
212
+ const tree = ({ tree: id, path: inside, dependencies }) => ({ tree: id, path: inside, dependencies });
213
+ const keyed = {
214
+ ...inputs,
215
+ project: tree(inputs.project),
216
+ checkouts: Object.fromEntries(Object.entries(checkouts).map(([name, each]) => [name, tree(each)])),
217
+ settings: Object.fromEntries(Object.entries(settings).map(([name, input]) => [name, { ...input, checkouts: input.checkouts.map(tree) }]))
218
+ };
219
+ return { key: sha256(JSON.stringify(keyed)), inputs };
220
+ }
221
+
222
+ /** A pass's record file in a project. */
223
+ export const passFile = (root, key) => path.join(root, PASS_FOLDER, `${key}.json`);
224
+
225
+ /** The pass recorded under this key in the project, or null. */
226
+ export function readPass(root, key) {
227
+ try {
228
+ const record = JSON.parse(readFileSync(passFile(root, key), "utf8"));
229
+ return record?.schema === SCHEMA && record.key === key ? record : null;
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ /** Records a pass, whole or not at all. @param {string} root @param {{ key: string }} pass */
236
+ export function writePass(root, pass) {
237
+ const file = passFile(root, pass.key);
238
+ mkdirSync(path.dirname(file), { recursive: true });
239
+ writeFileSync(`${file}.${process.pid}`, `${JSON.stringify({ schema: SCHEMA, ...pass }, null, 2)}\n`);
240
+ renameSync(`${file}.${process.pid}`, file);
241
+ return file;
242
+ }
243
+
244
+ /** `npm run <script> <args>` in the project, its output the run's; its exit status. */
245
+ function npmPart({ script, args, cwd, env }) {
246
+ const result = spawnSync("npm", ["run", script, ...args], { cwd, env, stdio: "inherit" });
247
+ if (result.error) throw result.error;
248
+ return result.status ?? 1;
249
+ }
250
+
251
+ /** What a recorded pass checked, in one line. */
252
+ function passedAlready(pass, file, projectRoot) {
253
+ const { project, checkouts, node } = pass.inputs;
254
+ const others = Object.entries(checkouts).map(([name, each]) => `; ${name} ${short(each.commit)}`).join("");
255
+ return `it passed on this exact tree at ${pass.finishedAt} on ${pass.host} (the project ${short(project.commit)}, tree ` +
256
+ `${short(project.tree)}${others}; Node ${node}): not run again. Its record is ${path.relative(projectRoot, file)}; ` +
257
+ "remove it to run the check again.";
258
+ }
259
+
260
+ /**
261
+ * One `jskit verify` on the tools it is given (a test gives stand-ins); its exit status.
262
+ * @param {object} [tools]
263
+ * @param {string} [tools.projectRoot]
264
+ * @param {string[]} [tools.argv] words for the last part (`npm run verify -- <args>`)
265
+ * @param {Record<string, string | undefined>} [tools.env]
266
+ * @param {string} [tools.nodeVersion]
267
+ * @param {string} [tools.host] the machine, as the record names it
268
+ * @param {(part: { script: string, args: string[], cwd: string, env: object }) => number} [tools.runPart]
269
+ * @param {(line: string) => void} [tools.print]
270
+ * @param {() => number} [tools.now]
271
+ */
272
+ export async function runVerify({
273
+ projectRoot = process.cwd(), argv = [], env = process.env, nodeVersion = process.version, host = os.hostname(),
274
+ runPart = npmPart, print = (line) => process.stdout.write(`${line}\n`), now = Date.now
275
+ } = {}) {
276
+ const config = readVerifyConfig(projectRoot);
277
+ const log = (line) => print(`jskit verify: ${line}`);
278
+ // The record only spares a second run: inputs it can't read never stop the check, which then runs whole.
279
+ const read = async () => {
280
+ try {
281
+ return await verifyInputs({ projectRoot, config, env, nodeVersion });
282
+ } catch (error) {
283
+ return { problem: `its inputs could not be read (${error.message})` };
284
+ }
285
+ };
286
+ let before = null;
287
+ if (argv.length > 0) {
288
+ log(`${argv.join(" ")} narrows the run to part of the check: no pass is read or recorded.`);
289
+ } else {
290
+ before = await read();
291
+ if ("problem" in before) {
292
+ log(`${before.problem}: not an exact tree, so it runs whole and records nothing.`);
293
+ before = null;
294
+ } else {
295
+ const pass = readPass(projectRoot, before.key);
296
+ if (pass) {
297
+ log(passedAlready(pass, passFile(projectRoot, before.key), projectRoot));
298
+ return 0;
299
+ }
300
+ }
301
+ }
302
+ const startedAt = new Date(now()).toISOString();
303
+ for (const [index, part] of config.parts.entries()) {
304
+ const args = index === config.parts.length - 1 ? argv : [];
305
+ const status = runPart({ script: part.script, args, cwd: projectRoot, env: { ...env, ...part.env } });
306
+ if (status !== 0) {
307
+ log(`npm run ${part.script} failed (exit ${status}): nothing recorded.`);
308
+ return status;
309
+ }
310
+ }
311
+ if (!before) return 0;
312
+ const after = await read();
313
+ if ("problem" in after || after.key !== before.key) {
314
+ log(`every part passed, but the tree or its inputs changed while it ran (${"problem" in after ? after.problem
315
+ : "another key"}): this pass is not recorded.`);
316
+ return 0;
317
+ }
318
+ const file = writePass(projectRoot, { key: before.key, host, startedAt, finishedAt: new Date(now()).toISOString(), inputs: before.inputs });
319
+ log(`every part passed: recorded in ${path.relative(projectRoot, file)}, so jskit verify on this tree and inputs runs ` +
320
+ "nothing again.");
321
+ return 0;
322
+ }
323
+
324
+ /**
325
+ * A CI run's name for a pass: the project's tree and the commits of the other repositories it checked out.
326
+ * @param {{ tree: string, commits: Record<string, string> }} inputs
327
+ */
328
+ export function ciPassName({ tree, commits }) {
329
+ if (!COMMIT_ID.test(String(tree))) throw new Error(`The project's tree "${tree}" is not a tree id.`);
330
+ for (const [name, id] of Object.entries(commits)) {
331
+ if (!CHECKOUT_NAME.test(name)) throw new Error(`"${name}" is no name for a commit: use letters, digits, ., _ and -.`);
332
+ if (!COMMIT_ID.test(String(id))) throw new Error(`${name}'s commit "${id}" is not a commit id: resolve it before verifying.`);
333
+ }
334
+ const sorted = Object.fromEntries(Object.entries(commits).sort(([a], [b]) => (a < b ? -1 : 1)));
335
+ return `jskit-verify-pass-${sha256(JSON.stringify({ schema: CI_SCHEMA, tree, commits: sorted })).slice(0, 40)}`;
336
+ }
337
+
338
+ /**
339
+ * The run whose pass GitHub keeps under this name (an artifact of the repository's that has not expired), or null.
340
+ * @param {{ name: string, repository: string, token: string, fetch?: typeof globalThis.fetch }} where
341
+ */
342
+ export async function recordedCiPass({ name, repository, token, fetch = globalThis.fetch }) {
343
+ const url = `https://api.github.com/repos/${repository}/actions/artifacts?name=${encodeURIComponent(name)}&per_page=100`;
344
+ const response = await fetch(url, {
345
+ headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, "X-GitHub-Api-Version": "2022-11-28" }
346
+ });
347
+ if (!response.ok) throw new Error(`GitHub answered ${response.status} for the recorded passes`);
348
+ const { artifacts = [] } = await response.json();
349
+ const kept = artifacts.find((artifact) => artifact?.name === name && artifact.expired === false);
350
+ return kept ? { runId: kept.workflow_run?.id ?? null, headSha: kept.workflow_run?.head_sha ?? "", createdAt: kept.created_at ?? "" } : null;
351
+ }
352
+
353
+ /** `--commit <name>=<sha>` (or `--commit=<name>=<sha>`), repeated. */
354
+ function parseCommits(argv) {
355
+ const commits = {};
356
+ const args = [...argv];
357
+ while (args.length > 0) {
358
+ const argument = String(args.shift());
359
+ const value = argument === "--commit" ? args.shift() : argument.startsWith("--commit=") ? argument.slice("--commit=".length) : null;
360
+ if (value === null) throw new Error(`Unknown argument: ${argument}. Usage: jskit verify-pass [--commit <name>=<sha> ...]`);
361
+ const at = String(value ?? "").indexOf("=");
362
+ if (at < 1) throw new Error(`--commit takes <name>=<sha>, not "${value ?? ""}".`);
363
+ commits[value.slice(0, at)] = value.slice(at + 1);
364
+ }
365
+ return commits;
366
+ }
367
+
368
+ /**
369
+ * `jskit verify-pass [--commit <name>=<sha> ...]`: a CI run's first step. It names the pass for the project's exact tree
370
+ * and those commits, asks GitHub (GITHUB_TOKEN, GITHUB_REPOSITORY) whether one is kept, says so, and writes `name` and
371
+ * `reuse` to GITHUB_OUTPUT when the run has one. A record it can't read (no token, GitHub refusing) is none: the run
372
+ * verifies. It throws on a tree with working changes and on a commit that is no commit id.
373
+ */
374
+ export async function runVerifyPass({
375
+ projectRoot = process.cwd(), argv = [], env = process.env, fetch = globalThis.fetch,
376
+ print = (line) => process.stdout.write(`${line}\n`)
377
+ } = {}) {
378
+ const commits = parseCommits(argv);
379
+ const project = exactTree(projectRoot, "The project");
380
+ if ("problem" in project) throw new Error(`${project.problem}: a CI pass names an exact tree.`);
381
+ const name = ciPassName({ tree: project.tree, commits });
382
+ let found = null;
383
+ if (!env.GITHUB_TOKEN || !env.GITHUB_REPOSITORY) {
384
+ print("jskit verify-pass: there is no GITHUB_TOKEN and GITHUB_REPOSITORY to read recorded passes: verifying.");
385
+ } else {
386
+ try {
387
+ found = await recordedCiPass({ name, repository: env.GITHUB_REPOSITORY, token: env.GITHUB_TOKEN, fetch });
388
+ } catch (error) {
389
+ print(`jskit verify-pass: the recorded passes could not be read (${error.message}): verifying.`);
390
+ }
391
+ }
392
+ print(found
393
+ ? `jskit verify-pass: this exact tree and these commits passed in run ${found.runId} (commit ${short(found.headSha)}, ` +
394
+ `${found.createdAt}): not run again. Its record is the artifact ${name}; delete it to verify again.`
395
+ : `jskit verify-pass: no pass is recorded as ${name}: verifying.`);
396
+ if (env.GITHUB_OUTPUT) appendFileSync(env.GITHUB_OUTPUT, `name=${name}\nreuse=${found ? "true" : "false"}\n`);
397
+ return 0;
398
+ }