@cameronsjo/artificer 0.18.1 → 0.22.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/README.md +65 -6
- package/bin/artificer.mjs +655 -0
- package/bin/lint-core.mjs +151 -0
- package/package.json +11 -3
- package/reference/SKILL.md +407 -0
- package/src/artificer-editorial.css +40 -0
- package/src/artificer-icons.js +122 -45
- package/src/artificer-theme.js +115 -25
- package/src/artificer-whimsy.css +15 -1
- package/src/artificer-whimsy.js +155 -12
- package/src/artificer.css +131 -8
- package/src/primitives.json +1093 -0
- package/src/theme-bootstrap.html +6 -3
- package/src/tokens.json +7 -4
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// artificer — the design-system CLI shipped inside @cameronsjo/artificer.
|
|
3
|
+
//
|
|
4
|
+
// One bin, subcommand router (adherence kit #219). `vendor` and `lint` today;
|
|
5
|
+
// `doctor` slots in later behind the same COMMANDS map. Plain Node (fs / path /
|
|
6
|
+
// crypto) — zero dependencies, so `npx @cameronsjo/artificer …` stays
|
|
7
|
+
// install-light.
|
|
8
|
+
//
|
|
9
|
+
// `vendor` copies the package's runtime (CSS/JS + tokens.json +
|
|
10
|
+
// primitives.json, the #199 mint ledger) and — opt-in — the fonts, into a
|
|
11
|
+
// consumer's repo, and stamps a provenance.json sidecar so a vendored copy can
|
|
12
|
+
// answer "where did this come from, is it current?" from the dest folder alone.
|
|
13
|
+
//
|
|
14
|
+
// `lint` runs Hard rule #1 (raw values that have a token) over the consumer's
|
|
15
|
+
// own CSS, version-locked to their vendored tokens.json. Engine: ./lint-core.mjs.
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
existsSync,
|
|
19
|
+
statSync,
|
|
20
|
+
lstatSync,
|
|
21
|
+
readdirSync,
|
|
22
|
+
readFileSync,
|
|
23
|
+
writeFileSync,
|
|
24
|
+
mkdirSync,
|
|
25
|
+
realpathSync,
|
|
26
|
+
} from 'node:fs';
|
|
27
|
+
import { join, dirname, resolve, relative, sep } from 'node:path';
|
|
28
|
+
import { fileURLToPath } from 'node:url';
|
|
29
|
+
import { createHash } from 'node:crypto';
|
|
30
|
+
import { lintText, report, buildTokenMaps, FONT_SCALE_EXEMPT } from './lint-core.mjs';
|
|
31
|
+
|
|
32
|
+
const BIN_DIR = dirname(fileURLToPath(import.meta.url));
|
|
33
|
+
|
|
34
|
+
// Distinct non-zero codes so a caller (or CI) can branch on the failure kind.
|
|
35
|
+
export const EXIT = {
|
|
36
|
+
OK: 0,
|
|
37
|
+
USAGE: 1, // bad/unknown command or flag; --help is a clean 0
|
|
38
|
+
SRC_MISSING: 3, // the package's src/ dir is not where it should be
|
|
39
|
+
NO_MATCH: 4, // the runtime glob matched nothing (never vendor an empty tree)
|
|
40
|
+
DEST_ESCAPE: 5, // --dest (or a symlink inside it) resolved outside the cwd
|
|
41
|
+
DEST_UNWRITABLE: 6, // could not write the dest tree
|
|
42
|
+
DRIFT_STRICT: 7, // --strict + a vendored file drifted from its stamp
|
|
43
|
+
COLLISION_STRICT: 8, // --strict + a pre-existing untracked file would be clobbered
|
|
44
|
+
LINT_VIOLATIONS: 2, // `lint` found raw-value violations (the engine's contract)
|
|
45
|
+
LINT_NO_FILES: 9, // `lint` glob matched no CSS files (never a silent green)
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// The runtime globs. Class-closure invariant (#205): a future
|
|
49
|
+
// `src/artificer-<new>.css|js` rides automatically — never a hand-list.
|
|
50
|
+
// `print.css` is a named exception: a documented runtime stylesheet (Path-A
|
|
51
|
+
// consumers link it as media="print") that predates the `artificer*` naming
|
|
52
|
+
// convention. It is one enumerated file, not hand-list creep. `primitives.json`
|
|
53
|
+
// is the second named entry (#199 Phase 4): the mint ledger the upgrade skill
|
|
54
|
+
// consumes — enumerated like tokens.json because the globs can't match it.
|
|
55
|
+
// `--fonts` additionally pulls the woff/woff2 assets by discovery, preserving
|
|
56
|
+
// their path under src/ so the CSS's relative `@font-face` URLs still resolve.
|
|
57
|
+
const RUNTIME_GLOBS = ['artificer*.css', 'artificer*.js', 'tokens.json', 'primitives.json', 'print.css'];
|
|
58
|
+
const FONT_GLOBS = ['**/*.woff', '**/*.woff2'];
|
|
59
|
+
|
|
60
|
+
// The interim cheatsheet ride-along (#78) is RETIRED (#199 PR-5): the
|
|
61
|
+
// primitives.json ledger is the machine-readable successor and the upgrade
|
|
62
|
+
// skill consumes it directly. reference/SKILL.md still ships in the npm
|
|
63
|
+
// package for humans. A previously vendored ARTIFICER-CHEATSHEET.md is left
|
|
64
|
+
// in place (vendor never deletes) — consumers may delete it freely.
|
|
65
|
+
|
|
66
|
+
const PROVENANCE = 'provenance.json';
|
|
67
|
+
const DEFAULT_DEST = 'public/artificer';
|
|
68
|
+
|
|
69
|
+
// ── glob ──────────────────────────────────────────────────────────────────
|
|
70
|
+
// A tiny POSIX-style matcher — enough for the fixed pattern set above, so the
|
|
71
|
+
// kit adds no glob dependency. `*` spans one segment, `**` spans any depth,
|
|
72
|
+
// `{a,b}` alternates, `?` one non-slash char.
|
|
73
|
+
const escapeRe = (s) => s.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
74
|
+
|
|
75
|
+
export function globToRegExp(glob) {
|
|
76
|
+
let re = '';
|
|
77
|
+
for (let i = 0; i < glob.length; i++) {
|
|
78
|
+
const c = glob[i];
|
|
79
|
+
if (c === '*') {
|
|
80
|
+
if (glob[i + 1] === '*') {
|
|
81
|
+
re += '.*';
|
|
82
|
+
i++;
|
|
83
|
+
if (glob[i + 1] === '/') i++; // `**/` also matches zero leading dirs
|
|
84
|
+
} else {
|
|
85
|
+
re += '[^/]*';
|
|
86
|
+
}
|
|
87
|
+
} else if (c === '?') {
|
|
88
|
+
re += '[^/]';
|
|
89
|
+
} else if (c === '{') {
|
|
90
|
+
const close = glob.indexOf('}', i);
|
|
91
|
+
if (close < 0) {
|
|
92
|
+
// Unbalanced brace — treat the `{` as a literal rather than mis-slicing
|
|
93
|
+
// (and re-entering the loop from a negative index).
|
|
94
|
+
re += '\\{';
|
|
95
|
+
} else {
|
|
96
|
+
const alts = glob.slice(i + 1, close).split(',').map(escapeRe);
|
|
97
|
+
re += `(?:${alts.join('|')})`;
|
|
98
|
+
i = close;
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
re += escapeRe(c);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return new RegExp(`^${re}$`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function matchGlobs(files, patterns) {
|
|
108
|
+
const res = patterns.map(globToRegExp);
|
|
109
|
+
return files.filter((f) => res.some((r) => r.test(f)));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Every file under `root`, as POSIX-relative paths. Uses lstat and skips
|
|
113
|
+
// symlinks — a symlinked dir could cycle (stack overflow) or point the walk
|
|
114
|
+
// outside the package root.
|
|
115
|
+
export function walkRelFiles(root) {
|
|
116
|
+
const out = [];
|
|
117
|
+
const rec = (dir, prefix) => {
|
|
118
|
+
for (const name of readdirSync(dir)) {
|
|
119
|
+
const abs = join(dir, name);
|
|
120
|
+
const rel = prefix ? `${prefix}/${name}` : name;
|
|
121
|
+
const st = lstatSync(abs);
|
|
122
|
+
if (st.isSymbolicLink()) continue;
|
|
123
|
+
if (st.isDirectory()) rec(abs, rel);
|
|
124
|
+
else out.push(rel);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
rec(root, '');
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Dirs never worth descending when expanding a consumer's lint glob.
|
|
132
|
+
const LINT_SKIP_DIRS = new Set(['node_modules', '.git']);
|
|
133
|
+
|
|
134
|
+
// Walk `root`, emitting paths POSIX-relative to `relBase`, skipping heavy/hidden
|
|
135
|
+
// dirs and symlinks — so a consumer `lint "**/*.css"` never descends
|
|
136
|
+
// node_modules. Missing/unreadable dirs are skipped, not fatal.
|
|
137
|
+
function walkForLint(root, relBase) {
|
|
138
|
+
const out = [];
|
|
139
|
+
const rec = (dir) => {
|
|
140
|
+
let names;
|
|
141
|
+
try {
|
|
142
|
+
names = readdirSync(dir);
|
|
143
|
+
} catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
for (const name of names) {
|
|
147
|
+
if (LINT_SKIP_DIRS.has(name) || name.startsWith('.')) continue;
|
|
148
|
+
const abs = join(dir, name);
|
|
149
|
+
let st;
|
|
150
|
+
try {
|
|
151
|
+
st = lstatSync(abs);
|
|
152
|
+
} catch {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (st.isSymbolicLink()) continue;
|
|
156
|
+
if (st.isDirectory()) rec(abs);
|
|
157
|
+
else out.push(relative(relBase, abs).split(sep).join('/'));
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
rec(root);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Normalize a consumer glob and locate the static dir the walk starts from.
|
|
165
|
+
// A single leading `./` is stripped (idiomatic CI globs write it, but walk
|
|
166
|
+
// paths never carry it, so the regex would otherwise match nothing). `meta` is
|
|
167
|
+
// the index of the first wildcard, or -1 for a literal path.
|
|
168
|
+
export function globStaticBase(cwd, rawGlob) {
|
|
169
|
+
const glob = rawGlob.startsWith('./') ? rawGlob.slice(2) : rawGlob;
|
|
170
|
+
const meta = glob.search(/[*?{]/);
|
|
171
|
+
const staticPart = meta === -1 ? glob : glob.slice(0, meta);
|
|
172
|
+
const baseRel = staticPart.includes('/') ? staticPart.slice(0, staticPart.lastIndexOf('/')) : '';
|
|
173
|
+
return { glob, meta, baseAbs: resolve(cwd, baseRel) };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Expand consumer globs (relative to cwd) into a sorted, de-duped file list.
|
|
177
|
+
// A literal path (no wildcard) is an O(1) existence check; a wildcard glob
|
|
178
|
+
// bounds the walk to its static prefix. `**` crosses directories, `{a,b}`
|
|
179
|
+
// alternates (both via globToRegExp).
|
|
180
|
+
export function listFilesForGlobs(cwd, globs) {
|
|
181
|
+
const seen = new Set();
|
|
182
|
+
for (const raw of globs) {
|
|
183
|
+
const { glob, meta, baseAbs } = globStaticBase(cwd, raw);
|
|
184
|
+
if (meta === -1) {
|
|
185
|
+
const abs = resolve(cwd, glob);
|
|
186
|
+
if (existsSync(abs) && statSync(abs).isFile()) seen.add(relative(cwd, abs).split(sep).join('/'));
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (!existsSync(baseAbs)) continue;
|
|
190
|
+
const re = globToRegExp(glob);
|
|
191
|
+
if (statSync(baseAbs).isFile()) {
|
|
192
|
+
const rel = relative(cwd, baseAbs).split(sep).join('/');
|
|
193
|
+
if (re.test(rel)) seen.add(rel);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
for (const rel of walkForLint(baseAbs, cwd)) {
|
|
197
|
+
if (re.test(rel)) seen.add(rel);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return [...seen].sort();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ── dest containment (symlink-aware) ─────────────────────────────────────────
|
|
204
|
+
const within = (child, parent) => child === parent || child.startsWith(parent + sep);
|
|
205
|
+
|
|
206
|
+
// The deepest ancestor of `p` that exists on disk (p itself if it exists).
|
|
207
|
+
export function deepestExistingAncestor(p) {
|
|
208
|
+
let cur = p;
|
|
209
|
+
while (!existsSync(cur)) {
|
|
210
|
+
const parent = dirname(cur);
|
|
211
|
+
if (parent === cur) break;
|
|
212
|
+
cur = parent;
|
|
213
|
+
}
|
|
214
|
+
return cur;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// The first symlinked path component of `fileAbs` at or below `baseAbs`, or
|
|
218
|
+
// null. `resolve` is lexical — it does not deref symlinks — so a shipped
|
|
219
|
+
// symlink (dir OR file) inside the dest could redirect a write outside the
|
|
220
|
+
// repo. This catches it before any mkdir/write follows it.
|
|
221
|
+
export function firstSymlinkComponent(baseAbs, fileAbs) {
|
|
222
|
+
const parts = relative(baseAbs, fileAbs).split(sep).filter(Boolean);
|
|
223
|
+
let cur = baseAbs;
|
|
224
|
+
for (const part of parts) {
|
|
225
|
+
cur = join(cur, part);
|
|
226
|
+
let st;
|
|
227
|
+
try {
|
|
228
|
+
st = lstatSync(cur);
|
|
229
|
+
} catch {
|
|
230
|
+
st = null; // does not exist yet — nothing to follow
|
|
231
|
+
}
|
|
232
|
+
if (st && st.isSymbolicLink()) return cur;
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── provenance ──────────────────────────────────────────────────────────────
|
|
238
|
+
export const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
|
|
239
|
+
|
|
240
|
+
// Walk up from the bin's own location to the package root — npx-cache-safe,
|
|
241
|
+
// because it never consults the consumer's cwd or node_modules.
|
|
242
|
+
export function resolvePackageRoot(startDir) {
|
|
243
|
+
let dir = startDir;
|
|
244
|
+
for (;;) {
|
|
245
|
+
if (existsSync(join(dir, 'package.json'))) return dir;
|
|
246
|
+
const parent = dirname(dir);
|
|
247
|
+
if (parent === dir) {
|
|
248
|
+
throw new Error(`artificer: no package.json found upward from ${startDir}`);
|
|
249
|
+
}
|
|
250
|
+
dir = parent;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Prefer the readable `node_modules/@scope/pkg/package.json` tail when the
|
|
255
|
+
// package resolved from an install tree; otherwise a cwd-relative path.
|
|
256
|
+
export function computeResolvedFrom(pkgJsonAbs, cwd) {
|
|
257
|
+
const marker = `${sep}node_modules${sep}`;
|
|
258
|
+
const idx = pkgJsonAbs.lastIndexOf(marker);
|
|
259
|
+
if (idx >= 0) return pkgJsonAbs.slice(idx + 1).split(sep).join('/');
|
|
260
|
+
const rel = relative(cwd, pkgJsonAbs).split(sep).join('/');
|
|
261
|
+
return rel || 'package.json';
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Re-hash the currently-present vendored files and compare to a prior stamp.
|
|
265
|
+
// A mismatch/absence is a consumer hand-edit the re-vendor would clobber.
|
|
266
|
+
export function computeDrift(destDir, provenance) {
|
|
267
|
+
const drift = [];
|
|
268
|
+
for (const [name, hash] of Object.entries(provenance.files ?? {})) {
|
|
269
|
+
const abs = join(destDir, name);
|
|
270
|
+
if (!existsSync(abs)) {
|
|
271
|
+
drift.push({ name, reason: 'missing' });
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (sha256(readFileSync(abs)) !== hash) drift.push({ name, reason: 'edited' });
|
|
275
|
+
}
|
|
276
|
+
return drift;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ── arg parsing ───────────────────────────────────────────────────────────
|
|
280
|
+
export function parseVendorArgs(argv) {
|
|
281
|
+
const opts = { dest: DEFAULT_DEST, fonts: false, strict: false, help: false, errors: [] };
|
|
282
|
+
for (let i = 0; i < argv.length; i++) {
|
|
283
|
+
const a = argv[i];
|
|
284
|
+
if (a === '--help' || a === '-h') opts.help = true;
|
|
285
|
+
else if (a === '--fonts') opts.fonts = true;
|
|
286
|
+
else if (a === '--strict') opts.strict = true;
|
|
287
|
+
else if (a === '--dest') {
|
|
288
|
+
const v = argv[++i];
|
|
289
|
+
if (v === undefined) opts.errors.push('--dest requires a directory argument');
|
|
290
|
+
else opts.dest = v;
|
|
291
|
+
} else if (a.startsWith('--dest=')) {
|
|
292
|
+
opts.dest = a.slice('--dest='.length);
|
|
293
|
+
} else if (a === '--channel' || a.startsWith('--channel=')) {
|
|
294
|
+
// Documented extension point (owner ruling #7): only src/ ships today.
|
|
295
|
+
// --channel=min waits on #112's dist/ build.
|
|
296
|
+
opts.errors.push('--channel is a documented extension point, not implemented (only src/ ships today)');
|
|
297
|
+
} else {
|
|
298
|
+
opts.errors.push(`unknown option "${a}"`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return opts;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ── help ────────────────────────────────────────────────────────────────────
|
|
305
|
+
const HELP = `artificer — the Artificer design-system CLI
|
|
306
|
+
|
|
307
|
+
Usage:
|
|
308
|
+
npx @cameronsjo/artificer <command> [options]
|
|
309
|
+
|
|
310
|
+
Commands:
|
|
311
|
+
vendor Copy the runtime + a provenance sidecar into your project
|
|
312
|
+
lint Check your CSS for raw values that have a token (Hard rule #1)
|
|
313
|
+
|
|
314
|
+
Run "artificer <command> --help" for a command's options.`;
|
|
315
|
+
|
|
316
|
+
const VENDOR_HELP = `artificer vendor — copy the Artificer runtime into a no-bundler project
|
|
317
|
+
|
|
318
|
+
Usage:
|
|
319
|
+
npx @cameronsjo/artificer vendor [--dest <dir>] [--fonts] [--strict]
|
|
320
|
+
|
|
321
|
+
Copies the design-system runtime (artificer*.css, artificer*.js, tokens.json,
|
|
322
|
+
primitives.json — the machine-readable primitives ledger), and — with --fonts —
|
|
323
|
+
the woff2 assets, into your repo, then writes ${PROVENANCE} recording the
|
|
324
|
+
source, version, and a sha256 per file. (The ARTIFICER-CHEATSHEET.md ride-along
|
|
325
|
+
is retired; an old vendored copy can be deleted.) Re-run to update; a drifted (hand-edited) vendored file,
|
|
326
|
+
or an untracked file already in the dest, is reported, and --strict turns that
|
|
327
|
+
into a hard failure that does not overwrite. Re-vendoring adds and overwrites
|
|
328
|
+
but never deletes — delete the dest and re-run for a clean tree.
|
|
329
|
+
|
|
330
|
+
Options:
|
|
331
|
+
--dest <dir> Destination inside your repo (default: ${DEFAULT_DEST})
|
|
332
|
+
--fonts Also vendor the font files (off by default; bundlers resolve them)
|
|
333
|
+
--strict Exit non-zero, without overwriting, on drift or an untracked collision
|
|
334
|
+
--help, -h Show this help
|
|
335
|
+
|
|
336
|
+
Bundler (import) consumers do not need this — import from node_modules directly.`;
|
|
337
|
+
|
|
338
|
+
// ── vendor ───────────────────────────────────────────────────────────────────
|
|
339
|
+
export function vendor({ argv = [], cwd = process.cwd(), packageRoot, out = console.log, err = console.error } = {}) {
|
|
340
|
+
const opts = parseVendorArgs(argv);
|
|
341
|
+
if (opts.help) {
|
|
342
|
+
out(VENDOR_HELP);
|
|
343
|
+
return EXIT.OK;
|
|
344
|
+
}
|
|
345
|
+
if (opts.errors.length) {
|
|
346
|
+
for (const e of opts.errors) err(`artificer vendor: ${e}`);
|
|
347
|
+
err(VENDOR_HELP);
|
|
348
|
+
return EXIT.USAGE;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const root = packageRoot ?? resolvePackageRoot(BIN_DIR);
|
|
352
|
+
const srcDir = join(root, 'src');
|
|
353
|
+
if (!existsSync(srcDir) || !statSync(srcDir).isDirectory()) {
|
|
354
|
+
err(`artificer vendor: package source dir not found: ${srcDir}`);
|
|
355
|
+
return EXIT.SRC_MISSING;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Traversal guard, two layers. (1) Lexical: the resolved dest must sit
|
|
359
|
+
// inside cwd. (2) Symlink-aware: realpath the deepest existing ancestor of
|
|
360
|
+
// the dest and require it inside the realpath'd cwd — `resolve` never derefs
|
|
361
|
+
// symlinks, so a shipped `public -> ../outside` dir symlink passes the
|
|
362
|
+
// lexical check but escapes here.
|
|
363
|
+
const cwdAbs = resolve(cwd);
|
|
364
|
+
const destAbs = resolve(cwd, opts.dest);
|
|
365
|
+
if (!within(destAbs, cwdAbs)) {
|
|
366
|
+
err(`artificer vendor: refusing to vendor outside the current directory: ${destAbs}`);
|
|
367
|
+
return EXIT.DEST_ESCAPE;
|
|
368
|
+
}
|
|
369
|
+
const cwdReal = realpathSync(cwdAbs);
|
|
370
|
+
const ancestorReal = realpathSync(deepestExistingAncestor(destAbs));
|
|
371
|
+
if (!within(ancestorReal, cwdReal)) {
|
|
372
|
+
err(`artificer vendor: dest resolves outside the current directory via a symlink: ${ancestorReal}`);
|
|
373
|
+
return EXIT.DEST_ESCAPE;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const patterns = opts.fonts ? [...RUNTIME_GLOBS, ...FONT_GLOBS] : RUNTIME_GLOBS;
|
|
377
|
+
const matched = matchGlobs(walkRelFiles(srcDir), patterns).sort();
|
|
378
|
+
if (matched.length === 0) {
|
|
379
|
+
err(`artificer vendor: no runtime files matched ${patterns.join(', ')} under ${srcDir}`);
|
|
380
|
+
return EXIT.NO_MATCH;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Plan the copies: runtime only (dest path == src-relative path, so
|
|
384
|
+
// relative @font-face URLs survive). primitives.json rides in RUNTIME_GLOBS.
|
|
385
|
+
const copies = matched.map((rel) => ({ srcAbs: join(srcDir, rel), rel }));
|
|
386
|
+
|
|
387
|
+
const pkgJsonAbs = join(root, 'package.json');
|
|
388
|
+
const version = JSON.parse(readFileSync(pkgJsonAbs, 'utf8')).version;
|
|
389
|
+
|
|
390
|
+
// Prior stamp (if any) — read once for both the drift and collision passes.
|
|
391
|
+
const provAbs = join(destAbs, PROVENANCE);
|
|
392
|
+
let prev = null;
|
|
393
|
+
if (existsSync(provAbs)) {
|
|
394
|
+
try {
|
|
395
|
+
prev = JSON.parse(readFileSync(provAbs, 'utf8'));
|
|
396
|
+
} catch {
|
|
397
|
+
prev = null;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const prevFiles = prev?.files ?? {};
|
|
401
|
+
|
|
402
|
+
// Drift: a stamped file whose bytes no longer match — a consumer hand-edit
|
|
403
|
+
// the re-vendor would clobber.
|
|
404
|
+
const drift = prev ? computeDrift(destAbs, prev) : [];
|
|
405
|
+
|
|
406
|
+
// Pre-write pass over every planned dest: (1) refuse a symlinked path
|
|
407
|
+
// component (traversal via a shipped symlink), and (2) collect collisions —
|
|
408
|
+
// a real file already present that NO prior stamp tracks (a first-vendor
|
|
409
|
+
// clobber, sharp with `--dest .`).
|
|
410
|
+
const collisions = [];
|
|
411
|
+
for (const { rel } of copies) {
|
|
412
|
+
const dstAbs = join(destAbs, rel);
|
|
413
|
+
const link = firstSymlinkComponent(destAbs, dstAbs);
|
|
414
|
+
if (link) {
|
|
415
|
+
err(`artificer vendor: refusing to write through a symlink in the dest: ${link}`);
|
|
416
|
+
return EXIT.DEST_ESCAPE;
|
|
417
|
+
}
|
|
418
|
+
if (existsSync(dstAbs) && !(rel in prevFiles)) collisions.push(rel);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (drift.length) {
|
|
422
|
+
err(`artificer vendor: ${drift.length} vendored file(s) drifted from ${PROVENANCE}:`);
|
|
423
|
+
for (const d of drift) err(` ${d.name} (${d.reason})`);
|
|
424
|
+
}
|
|
425
|
+
if (collisions.length) {
|
|
426
|
+
err(`artificer vendor: ${collisions.length} existing file(s) not tracked by ${PROVENANCE} would be overwritten:`);
|
|
427
|
+
for (const c of collisions) err(` ${c}`);
|
|
428
|
+
}
|
|
429
|
+
// --strict: refuse to overwrite anything the consumer might own. Drift takes
|
|
430
|
+
// precedence over a first-vendor collision in the exit code.
|
|
431
|
+
if (opts.strict && drift.length) {
|
|
432
|
+
err('artificer vendor: --strict — refusing to overwrite; reconcile or drop the edits, then re-run.');
|
|
433
|
+
return EXIT.DRIFT_STRICT;
|
|
434
|
+
}
|
|
435
|
+
if (opts.strict && collisions.length) {
|
|
436
|
+
err('artificer vendor: --strict — refusing to overwrite untracked files; move them or pick a clean --dest.');
|
|
437
|
+
return EXIT.COLLISION_STRICT;
|
|
438
|
+
}
|
|
439
|
+
if (drift.length || collisions.length) {
|
|
440
|
+
err('artificer vendor: overwriting with the canonical bytes (re-run with --strict to block instead).');
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Copy + stamp. Bytes are copied verbatim — the sha256 is of exactly what
|
|
444
|
+
// both source and dest hold.
|
|
445
|
+
const files = {};
|
|
446
|
+
try {
|
|
447
|
+
mkdirSync(destAbs, { recursive: true });
|
|
448
|
+
// Post-mkdir re-check: the created dest must still realpath inside cwd.
|
|
449
|
+
if (!within(realpathSync(destAbs), cwdReal)) {
|
|
450
|
+
err(`artificer vendor: dest resolves outside the current directory via a symlink: ${realpathSync(destAbs)}`);
|
|
451
|
+
return EXIT.DEST_ESCAPE;
|
|
452
|
+
}
|
|
453
|
+
for (const { srcAbs, rel } of copies) {
|
|
454
|
+
const dstAbs = join(destAbs, rel);
|
|
455
|
+
mkdirSync(dirname(dstAbs), { recursive: true });
|
|
456
|
+
const buf = readFileSync(srcAbs);
|
|
457
|
+
writeFileSync(dstAbs, buf);
|
|
458
|
+
files[rel] = sha256(buf);
|
|
459
|
+
}
|
|
460
|
+
const provenance = {
|
|
461
|
+
source: 'cameronsjo/artificer',
|
|
462
|
+
version,
|
|
463
|
+
resolvedFrom: computeResolvedFrom(pkgJsonAbs, cwd),
|
|
464
|
+
vendoredAt: new Date().toISOString(),
|
|
465
|
+
files,
|
|
466
|
+
};
|
|
467
|
+
writeFileSync(provAbs, `${JSON.stringify(provenance, null, 2)}\n`);
|
|
468
|
+
} catch (e) {
|
|
469
|
+
if (['EACCES', 'EPERM', 'EROFS', 'ENOSPC'].includes(e.code)) {
|
|
470
|
+
err(`artificer vendor: cannot write to ${destAbs}: ${e.message}`);
|
|
471
|
+
return EXIT.DEST_UNWRITABLE;
|
|
472
|
+
}
|
|
473
|
+
throw e;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
out(`artificer vendor: wrote ${copies.length} file(s) → ${relative(cwd, destAbs) || '.'} (v${version})`);
|
|
477
|
+
for (const { rel } of copies) out(` ${rel}`);
|
|
478
|
+
out(` ${PROVENANCE}`);
|
|
479
|
+
return EXIT.OK;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// ── lint ─────────────────────────────────────────────────────────────────────
|
|
483
|
+
export function parseLintArgs(argv) {
|
|
484
|
+
const opts = { globs: [], advisory: false, tokens: null, help: false, errors: [] };
|
|
485
|
+
for (let i = 0; i < argv.length; i++) {
|
|
486
|
+
const a = argv[i];
|
|
487
|
+
if (a === '--help' || a === '-h') opts.help = true;
|
|
488
|
+
else if (a === '--advisory') opts.advisory = true;
|
|
489
|
+
else if (a === '--tokens') {
|
|
490
|
+
const v = argv[++i];
|
|
491
|
+
if (v === undefined) opts.errors.push('--tokens requires a path argument');
|
|
492
|
+
else opts.tokens = v;
|
|
493
|
+
} else if (a.startsWith('--tokens=')) {
|
|
494
|
+
opts.tokens = a.slice('--tokens='.length);
|
|
495
|
+
} else if (a.startsWith('-')) {
|
|
496
|
+
opts.errors.push(`unknown option "${a}"`);
|
|
497
|
+
} else {
|
|
498
|
+
opts.globs.push(a);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return opts;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// Resolve the token inventory in priority order, surfacing WHICH source won so a
|
|
505
|
+
// consumer can see the lockstep: --tokens > vendored dest > the package's own
|
|
506
|
+
// tokens.json (version-locked) > built-in workshop scale (last resort). A bad
|
|
507
|
+
// EXPLICIT --tokens is an error; a missing/broken DISCOVERED source falls
|
|
508
|
+
// through to the next.
|
|
509
|
+
export function resolveTokenMaps({ tokensArg, cwd, packageRoot }) {
|
|
510
|
+
const load = (abs, label) => {
|
|
511
|
+
try {
|
|
512
|
+
const json = JSON.parse(readFileSync(abs, 'utf8'));
|
|
513
|
+
const v = json.$version ? ` (tokens v${json.$version})` : '';
|
|
514
|
+
return { maps: buildTokenMaps(json), source: `${label}${v}` };
|
|
515
|
+
} catch {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
if (tokensArg) {
|
|
520
|
+
const abs = resolve(cwd, tokensArg);
|
|
521
|
+
if (!existsSync(abs)) return { error: `--tokens path not found: ${abs}` };
|
|
522
|
+
return load(abs, `--tokens ${tokensArg}`) ?? { error: `--tokens file is not valid JSON: ${abs}` };
|
|
523
|
+
}
|
|
524
|
+
const vendored = resolve(cwd, DEFAULT_DEST, 'tokens.json');
|
|
525
|
+
if (existsSync(vendored)) {
|
|
526
|
+
const r = load(vendored, `vendored ${relative(cwd, vendored).split(sep).join('/')}`);
|
|
527
|
+
if (r) return r;
|
|
528
|
+
}
|
|
529
|
+
const own = join(packageRoot, 'src', 'tokens.json');
|
|
530
|
+
if (existsSync(own)) {
|
|
531
|
+
const r = load(own, 'package src/tokens.json');
|
|
532
|
+
if (r) return r;
|
|
533
|
+
}
|
|
534
|
+
// Last resort: lintText's own built-ins (pass no maps).
|
|
535
|
+
return { maps: undefined, source: 'built-in workshop scale (no tokens.json found)' };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const LINT_HELP = `artificer lint — check your CSS for raw values that have a token (Hard rule #1)
|
|
539
|
+
|
|
540
|
+
Usage:
|
|
541
|
+
npx @cameronsjo/artificer lint <glob...> [--advisory] [--tokens <path>]
|
|
542
|
+
|
|
543
|
+
Flags raw hex, on-scale spacing/radius px, and near-scale font-size px that map
|
|
544
|
+
to a token, outside custom-property definitions and comments. A trailing
|
|
545
|
+
/* tuned */ exempts a line. The token inventory is read from (in order):
|
|
546
|
+
--tokens <path> → ./public/artificer/tokens.json (your vendored copy) →
|
|
547
|
+
the installed package's own src/tokens.json → the built-in scale.
|
|
548
|
+
The chosen source is printed, so the lint stays in lockstep with your version.
|
|
549
|
+
There is deliberately NO config file — the discipline is not per-consumer.
|
|
550
|
+
|
|
551
|
+
Options:
|
|
552
|
+
--advisory Report violations but exit 0 (default is strict: exit 2)
|
|
553
|
+
--tokens <path> Read the token inventory from this tokens.json
|
|
554
|
+
--help, -h Show this help`;
|
|
555
|
+
|
|
556
|
+
export function lint({ argv = [], cwd = process.cwd(), packageRoot, out = console.log, err = console.error } = {}) {
|
|
557
|
+
const opts = parseLintArgs(argv);
|
|
558
|
+
if (opts.help) {
|
|
559
|
+
out(LINT_HELP);
|
|
560
|
+
return EXIT.OK;
|
|
561
|
+
}
|
|
562
|
+
if (opts.errors.length) {
|
|
563
|
+
for (const e of opts.errors) err(`artificer lint: ${e}`);
|
|
564
|
+
err(LINT_HELP);
|
|
565
|
+
return EXIT.USAGE;
|
|
566
|
+
}
|
|
567
|
+
if (opts.globs.length === 0) {
|
|
568
|
+
err('artificer lint: no glob given (e.g. "src/**/*.css")');
|
|
569
|
+
err(LINT_HELP);
|
|
570
|
+
return EXIT.USAGE;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Containment: lint only reads within the project. A glob whose static base
|
|
574
|
+
// resolves outside cwd (a literal `../secret/*`, an absolute path, or a
|
|
575
|
+
// symlinked base) is refused loudly — not a silent "no files matched".
|
|
576
|
+
const cwdAbs = resolve(cwd);
|
|
577
|
+
const cwdReal = realpathSync(cwdAbs);
|
|
578
|
+
for (const raw of opts.globs) {
|
|
579
|
+
const { baseAbs } = globStaticBase(cwd, raw);
|
|
580
|
+
const ancestorReal = realpathSync(deepestExistingAncestor(baseAbs));
|
|
581
|
+
if (!within(baseAbs, cwdAbs) || !within(ancestorReal, cwdReal)) {
|
|
582
|
+
err(`artificer lint: glob resolves outside the project: ${raw}`);
|
|
583
|
+
return EXIT.USAGE;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const root = packageRoot ?? resolvePackageRoot(BIN_DIR);
|
|
588
|
+
const resolved = resolveTokenMaps({ tokensArg: opts.tokens, cwd, packageRoot: root });
|
|
589
|
+
if (resolved.error) {
|
|
590
|
+
err(`artificer lint: ${resolved.error}`);
|
|
591
|
+
return EXIT.USAGE;
|
|
592
|
+
}
|
|
593
|
+
err(`artificer lint: token source — ${resolved.source}`);
|
|
594
|
+
|
|
595
|
+
const files = listFilesForGlobs(cwd, opts.globs);
|
|
596
|
+
if (files.length === 0) {
|
|
597
|
+
err(`artificer lint: no files matched ${opts.globs.join(', ')} under ${cwd}`);
|
|
598
|
+
return EXIT.LINT_NO_FILES;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
let total = 0;
|
|
602
|
+
for (const rel of files) {
|
|
603
|
+
let text;
|
|
604
|
+
try {
|
|
605
|
+
text = readFileSync(join(cwd, rel), 'utf8');
|
|
606
|
+
} catch {
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
const v = lintText(text, { fontScale: !FONT_SCALE_EXEMPT.test(rel), tokens: resolved.maps });
|
|
610
|
+
if (v.length) {
|
|
611
|
+
report(rel, v, err);
|
|
612
|
+
total += v.length;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
if (total === 0) {
|
|
617
|
+
out(`artificer lint: 0 violations across ${files.length} file(s)`);
|
|
618
|
+
return EXIT.OK;
|
|
619
|
+
}
|
|
620
|
+
if (opts.advisory) {
|
|
621
|
+
err(`artificer lint: ${total} violation(s) across ${files.length} file(s) — advisory (exit 0)`);
|
|
622
|
+
return EXIT.OK;
|
|
623
|
+
}
|
|
624
|
+
err(`artificer lint: ${total} violation(s) across ${files.length} file(s) — run with --advisory to report without failing`);
|
|
625
|
+
return EXIT.LINT_VIOLATIONS;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// ── router ────────────────────────────────────────────────────────────────────
|
|
629
|
+
const COMMANDS = { vendor, lint };
|
|
630
|
+
|
|
631
|
+
export function route({ argv = [], cwd = process.cwd(), packageRoot, out = console.log, err = console.error } = {}) {
|
|
632
|
+
const [cmd, ...rest] = argv;
|
|
633
|
+
if (cmd === '--help' || cmd === '-h') {
|
|
634
|
+
out(HELP);
|
|
635
|
+
return EXIT.OK;
|
|
636
|
+
}
|
|
637
|
+
if (cmd === undefined) {
|
|
638
|
+
err(HELP);
|
|
639
|
+
return EXIT.USAGE;
|
|
640
|
+
}
|
|
641
|
+
const fn = COMMANDS[cmd];
|
|
642
|
+
if (!fn) {
|
|
643
|
+
err(`artificer: unknown command "${cmd}"`);
|
|
644
|
+
err(HELP);
|
|
645
|
+
return EXIT.USAGE;
|
|
646
|
+
}
|
|
647
|
+
return fn({ argv: rest, cwd, packageRoot, out, err });
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Run only when invoked as a script (deref symlinks so the npx .bin shim
|
|
651
|
+
// still counts as "main"); stay inert when imported by tests.
|
|
652
|
+
const invoked = process.argv[1] ? realpathSync(process.argv[1]) : '';
|
|
653
|
+
if (invoked === fileURLToPath(import.meta.url)) {
|
|
654
|
+
process.exit(route({ argv: process.argv.slice(2) }));
|
|
655
|
+
}
|