@astl/devkit 0.0.0 → 0.1.0

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/src/main.ts ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The `astl` commands. Issue messages come from the catalogs (`engine.describe` in the chosen UI locale); the rest of
3
+ * the output is for developers and stays English, like the problem titles of the grading protocol.
4
+ */
5
+
6
+ import { mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
7
+ import { basename, dirname, join, resolve, sep } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { type ParseArgsConfig, parseArgs } from 'node:util';
10
+ import { builtInDefinitions } from '@astl/components/definitions';
11
+ import type { Engine, Issue } from '@astl/core';
12
+ import { createEngine } from '@astl/engine';
13
+ import { builtInStyleTemplates } from '@astl/tokens';
14
+ import { CONFORMANCE_SECRET, runConformance } from './conformance.js';
15
+ import { documentsIn } from './sources.js';
16
+
17
+ export interface Io {
18
+ readonly stdout: (text: string) => void;
19
+ readonly stderr: (text: string) => void;
20
+ readonly env: Readonly<Record<string, string | undefined>>;
21
+ }
22
+
23
+ const processIo: Io = {
24
+ stdout: (text) => process.stdout.write(text),
25
+ stderr: (text) => process.stderr.write(text),
26
+ env: process.env,
27
+ };
28
+
29
+ export const USAGE = `Usage:
30
+ astl validate <files...> [--json] [--locale <tag>]
31
+ astl compile <file> --out <dir> --key-out <file> --salt <salt> [--secret-env <NAME>]
32
+ astl conformance [dir] [--update]
33
+
34
+ Commands:
35
+ validate Check exercise sources, or HTML pages with <astl-doc> inside, and print their issues in the
36
+ --locale UI language (default: from LC_ALL / LANG). Exits 1 when a document has errors.
37
+ compile Compile one source. Public: <dir>/view.html and meta.json. Private: the answer key at --key-out,
38
+ written with mode 0600 and refused inside <dir>. --salt (required, not empty, e.g. the exercise
39
+ id) keeps ids unique per exercise. The secret comes from the environment variable named by
40
+ --secret-env (default ASTL_SECRET), at least 16 bytes.
41
+ conformance Check the fixture folders under [dir] (default: the built-in components' fixtures): goldens,
42
+ determinism, the leak probe and grading cases. Missing goldens are written; --update rewrites
43
+ the ones that differ.
44
+ `;
45
+
46
+ /** The built-in components and style templates, as the CLI registers them. */
47
+ export function builtInEngine(secret: string): Engine {
48
+ return createEngine({ components: builtInDefinitions, secret, styleTemplates: builtInStyleTemplates });
49
+ }
50
+
51
+ /** POSIX message locale (`pl_PL.UTF-8` -> `pl-PL`); English for `C`, `POSIX` or nothing. */
52
+ function systemLocale(env: Io['env']): string {
53
+ const raw = env.LC_ALL || env.LC_MESSAGES || env.LANG || '';
54
+ const tag = raw.split(/[.@]/)[0]?.replace(/_/g, '-') ?? '';
55
+ return tag === '' || tag === 'C' || tag === 'POSIX' ? 'en' : tag;
56
+ }
57
+
58
+ function describeIssue(engine: Engine, issue: Issue, locale: string): string {
59
+ const where = issue.at.path === '' ? '' : ` at ${issue.at.path}`;
60
+ return `${issue.severity} ${issue.code}${where}\n ${engine.describe(issue, locale)}\n`;
61
+ }
62
+
63
+ const label = (file: string, index: number, count: number) => (count > 1 ? `${file} [${index + 1}]` : file);
64
+
65
+ async function validate(files: readonly string[], options: { json: boolean; locale: string }, io: Io) {
66
+ // Validation does not derive ids, so any secret will do.
67
+ const engine = builtInEngine(CONFORMANCE_SECRET);
68
+ const reports: unknown[] = [];
69
+ let failed = false;
70
+ for (const file of files) {
71
+ let text: string;
72
+ try {
73
+ text = await readFile(file, 'utf8');
74
+ } catch (error) {
75
+ io.stderr(`${file}: ${(error as Error).message}\n`);
76
+ failed = true;
77
+ continue;
78
+ }
79
+ const docs = documentsIn(text);
80
+ docs.forEach((doc, index) => {
81
+ const { ok, issues } = engine.validate(doc);
82
+ failed ||= !ok;
83
+ const name = label(file, index, docs.length);
84
+ if (options.json) {
85
+ const described = issues.map((issue) => ({
86
+ ...issue,
87
+ message: engine.describe(issue, options.locale),
88
+ }));
89
+ reports.push({ file, document: index + 1, ok, issues: described });
90
+ } else if (issues.length === 0) {
91
+ io.stdout(`${name}: ok\n`);
92
+ } else {
93
+ for (const issue of issues) io.stdout(`${name}: ${describeIssue(engine, issue, options.locale)}`);
94
+ }
95
+ });
96
+ }
97
+ if (options.json) io.stdout(`${JSON.stringify(reports, null, 2)}\n`);
98
+ return failed ? 1 : 0;
99
+ }
100
+
101
+ /** Absolute path with symlinks resolved as far as the path exists (the rest may not be created yet). */
102
+ async function resolveReal(path: string): Promise<string> {
103
+ const tail: string[] = [];
104
+ let dir = resolve(path);
105
+ for (;;) {
106
+ try {
107
+ return join(await realpath(dir), ...tail);
108
+ } catch {
109
+ const parent = dirname(dir);
110
+ if (parent === dir) return resolve(path);
111
+ tail.unshift(basename(dir));
112
+ dir = parent;
113
+ }
114
+ }
115
+ }
116
+
117
+ /** Through a fresh 0600 file and a rename: the key is never readable by others, not even an older key file's mode. */
118
+ async function writePrivate(file: string, content: string): Promise<void> {
119
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
120
+ await writeFile(temp, content, { mode: 0o600, flag: 'wx' });
121
+ try {
122
+ await rename(temp, file);
123
+ } catch (error) {
124
+ await rm(temp, { force: true });
125
+ throw error;
126
+ }
127
+ }
128
+
129
+ async function compile(
130
+ file: string,
131
+ options: { out: string; keyOut: string; secretEnv: string; salt: string; locale: string },
132
+ io: Io,
133
+ ): Promise<number> {
134
+ if (options.salt === '') {
135
+ io.stderr('astl compile: --salt must not be empty: without a salt, every exercise gets the same ids\n');
136
+ return 2;
137
+ }
138
+ const out = await resolveReal(options.out);
139
+ const keyFile = await resolveReal(options.keyOut);
140
+ if (keyFile === out || keyFile.startsWith(`${out}${sep}`)) {
141
+ io.stderr('astl compile: --key-out must be outside --out: the answer key is private, --out is public\n');
142
+ return 2;
143
+ }
144
+ const secret = io.env[options.secretEnv];
145
+ if (!secret) {
146
+ io.stderr(`astl compile: set ${options.secretEnv} to the compile secret (at least 16 bytes)\n`);
147
+ return 2;
148
+ }
149
+ let engine: Engine;
150
+ try {
151
+ engine = builtInEngine(secret);
152
+ } catch (error) {
153
+ io.stderr(`astl compile: ${(error as Error).message}\n`);
154
+ return 2;
155
+ }
156
+ let text: string;
157
+ try {
158
+ text = await readFile(file, 'utf8');
159
+ } catch (error) {
160
+ io.stderr(`${file}: ${(error as Error).message}\n`);
161
+ return 1;
162
+ }
163
+ const docs = documentsIn(text);
164
+ if (docs.length !== 1) {
165
+ io.stderr(`${file}: ${docs.length} <astl-doc> elements; compile one document at a time\n`);
166
+ return 1;
167
+ }
168
+ const result = await engine.compile(docs[0] as string, { salt: options.salt });
169
+ for (const issue of result.issues) io.stdout(`${file}: ${describeIssue(engine, issue, options.locale)}`);
170
+ if (!result.ok) return 1;
171
+ try {
172
+ await mkdir(dirname(keyFile), { recursive: true });
173
+ await writePrivate(keyFile, `${JSON.stringify(result.key, null, 2)}\n`);
174
+ await mkdir(out, { recursive: true });
175
+ await writeFile(join(out, 'view.html'), result.view);
176
+ await writeFile(join(out, 'meta.json'), `${JSON.stringify(result.metadata, null, 2)}\n`);
177
+ } catch (error) {
178
+ io.stderr(`astl compile: ${(error as Error).message}\n`);
179
+ return 1;
180
+ }
181
+ io.stdout(`${file}: wrote view.html and meta.json to ${options.out} (view ${result.viewHash})\n`);
182
+ io.stderr(
183
+ `astl compile: ${options.keyOut} is the answer key: keep it private, never serve it with the view\n`,
184
+ );
185
+ return 0;
186
+ }
187
+
188
+ async function conformance(dir: string | undefined, update: boolean, io: Io): Promise<number> {
189
+ const root = dir ?? fileURLToPath(new URL('./src/', import.meta.resolve('@astl/components/package.json')));
190
+ const outcomes = await runConformance(root, builtInEngine(CONFORMANCE_SECRET), { update });
191
+ for (const outcome of outcomes) {
192
+ io.stdout(`${outcome.failures.length === 0 ? 'ok ' : 'FAIL'} ${outcome.id}\n`);
193
+ for (const failure of outcome.failures) io.stdout(` ${failure}\n`);
194
+ for (const file of outcome.written) io.stdout(` wrote ${file}\n`);
195
+ }
196
+ const failed = outcomes.filter((o) => o.failures.length > 0).length;
197
+ io.stdout(`${outcomes.length} fixtures, ${failed} failed\n`);
198
+ return outcomes.length === 0 || failed > 0 ? 1 : 0;
199
+ }
200
+
201
+ type Command = 'validate' | 'compile' | 'conformance';
202
+
203
+ const OPTIONS: Readonly<Record<Command, NonNullable<ParseArgsConfig['options']>>> = {
204
+ validate: { json: { type: 'boolean' }, locale: { type: 'string' } },
205
+ compile: {
206
+ out: { type: 'string' },
207
+ 'key-out': { type: 'string' },
208
+ 'secret-env': { type: 'string' },
209
+ salt: { type: 'string' },
210
+ locale: { type: 'string' },
211
+ },
212
+ conformance: { update: { type: 'boolean' } },
213
+ };
214
+
215
+ /** Runs one command; resolves to the exit code (0 ok, 1 problems found, 2 usage or configuration error). */
216
+ export async function main(argv: readonly string[], io: Io = processIo): Promise<number> {
217
+ const [command, ...rest] = argv;
218
+ if (command === undefined || command === 'help' || command === '--help' || command === '-h') {
219
+ (command === undefined ? io.stderr : io.stdout)(USAGE);
220
+ return command === undefined ? 2 : 0;
221
+ }
222
+ if (!Object.hasOwn(OPTIONS, command)) {
223
+ io.stderr(`astl: unknown command "${command}"\n\n${USAGE}`);
224
+ return 2;
225
+ }
226
+ const name = command as Command;
227
+ let values: Readonly<Record<string, string | boolean | (string | boolean)[] | undefined>>;
228
+ let positionals: string[];
229
+ try {
230
+ ({ values, positionals } = parseArgs({
231
+ args: [...rest],
232
+ options: OPTIONS[name],
233
+ allowPositionals: true,
234
+ strict: true,
235
+ }));
236
+ } catch (error) {
237
+ io.stderr(`astl ${name}: ${(error as Error).message}\n\n${USAGE}`);
238
+ return 2;
239
+ }
240
+ const locale = typeof values.locale === 'string' ? values.locale : systemLocale(io.env);
241
+ switch (name) {
242
+ case 'validate':
243
+ if (positionals.length === 0) break;
244
+ return validate(positionals, { json: values.json === true, locale }, io);
245
+ case 'compile': {
246
+ if (positionals.length !== 1) break;
247
+ const { out, salt, 'key-out': keyOut, 'secret-env': secretEnv } = values;
248
+ if (typeof out !== 'string' || typeof keyOut !== 'string' || typeof salt !== 'string') {
249
+ const missing = ['out', 'key-out', 'salt'].filter((flag) => typeof values[flag] !== 'string');
250
+ io.stderr(`astl compile: missing ${missing.map((flag) => `--${flag}`).join(', ')}\n\n${USAGE}`);
251
+ return 2;
252
+ }
253
+ const env = typeof secretEnv === 'string' ? secretEnv : 'ASTL_SECRET';
254
+ return compile(positionals[0] as string, { out, keyOut, secretEnv: env, salt, locale }, io);
255
+ }
256
+ case 'conformance':
257
+ if (positionals.length > 1) break;
258
+ return conformance(positionals[0], values.update === true, io);
259
+ }
260
+ io.stderr(`astl ${name}: missing or extra arguments\n\n${USAGE}`);
261
+ return 2;
262
+ }
package/src/sources.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Documents in a file. A source file is one `<astl-doc>` and is checked as it is (so stray content is reported); an
3
+ * HTML page (HTML with answers) holds its documents inside `<astl-player>`, and each one is checked on its own.
4
+ */
5
+ const PAGE = /<(?:!doctype|html|head|body|astl-player)\b/i;
6
+ const DOC = /<astl-doc\b[\s\S]*?<\/astl-doc\s*>/gi;
7
+
8
+ export function documentsIn(text: string): string[] {
9
+ if (!PAGE.test(text)) return [text];
10
+ return text.match(DOC) ?? [text];
11
+ }