@astryxdesign/cli 0.7.3 → 0.7.4-canary.3f6ea7d

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.
Files changed (58) hide show
  1. package/README.md +5 -5
  2. package/api/discover/_adapter.mjs +22 -10
  3. package/api/discover/_catalog-view.d.mts +2 -0
  4. package/api/discover/_catalog-view.mjs +1 -0
  5. package/api/discover/_catalog-view.test.mjs +1 -0
  6. package/api/discover/detail/detail.mjs +1 -0
  7. package/api/discover/detail/detail.test.mjs +3 -0
  8. package/api/discover/detail/doc/doc.mjs +5 -1
  9. package/api/discover/detail/doc/doc.test.mjs +1 -0
  10. package/api/discover/detail/item/item.mjs +2 -0
  11. package/api/discover/detail/item/item.test.mjs +2 -0
  12. package/api/discover/discover.doc.mjs +4 -4
  13. package/api/discover/discover.type.d.mts +20 -0
  14. package/api/discover/discover.type.mjs +5 -0
  15. package/api/discover/list/list.test.mjs +2 -0
  16. package/api/discover/search/search.d.mts +3 -2
  17. package/api/discover/search/search.mjs +26 -7
  18. package/api/discover/search/search.test.mjs +67 -0
  19. package/api/doctor/_adapter.d.mts +40 -0
  20. package/api/doctor/_adapter.mjs +171 -1
  21. package/api/doctor/built-checks.d.mts +85 -0
  22. package/api/doctor/built-checks.mjs +807 -0
  23. package/api/doctor/built-checks.test.mjs +502 -0
  24. package/api/doctor/doctor.d.mts +6 -5
  25. package/api/doctor/doctor.doc.mjs +10 -0
  26. package/api/doctor/doctor.mjs +18 -3
  27. package/api/doctor/doctor.type.d.mts +6 -0
  28. package/api/doctor/doctor.type.mjs +3 -0
  29. package/api/integration/pack-check.mjs +6 -1
  30. package/api/integration/pack-check.test.mjs +14 -0
  31. package/api/theme/palette/generate/generate.d.mts +8 -0
  32. package/api/theme/palette/generate/generate.mjs +38 -11
  33. package/api/theme/palette/generate/generate.test.mjs +83 -4
  34. package/api/theme/palette/generate/generator.d.mts +6 -0
  35. package/api/theme/palette/generate/generator.mjs +6 -0
  36. package/api/theme/theme.type.d.mts +12 -1
  37. package/api/theme/theme.type.mjs +7 -1
  38. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  39. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +1 -1
  40. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +1 -1
  41. package/assets/templates/themes/gothic/gothicPaletteRefs.generated.ts +41 -0
  42. package/assets/templates/themes/gothic/gothicPalettes.generated.receipt.json +979 -0
  43. package/assets/templates/themes/gothic/gothicPalettes.generated.ts +271 -0
  44. package/assets/templates/themes/gothic/gothicTheme.ts +130 -160
  45. package/assets/templates/themes/gothic/palette.config.json +371 -0
  46. package/assets/templates/themes/stone/palette.config.json +262 -0
  47. package/assets/templates/themes/stone/stonePaletteRefs.generated.ts +51 -0
  48. package/assets/templates/themes/stone/stonePalettes.generated.receipt.json +840 -0
  49. package/assets/templates/themes/stone/stonePalettes.generated.ts +501 -0
  50. package/assets/templates/themes/stone/stoneTheme.ts +190 -207
  51. package/clients/cli/commands/discover.mjs +1 -1
  52. package/clients/cli/commands/discover.sources.test.mjs +6 -0
  53. package/clients/cli/commands/doctor.doc.mjs +12 -0
  54. package/clients/cli/commands/doctor.mjs +23 -8
  55. package/foundation/response/error-codes.test.mjs +9 -0
  56. package/foundation/response/response-types.doc.mjs +5 -5
  57. package/foundation/response/response-types.doc.test.mjs +29 -0
  58. package/package.json +9 -9
@@ -0,0 +1,807 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx doctor --built <path>`: did a finished build actually use
5
+ * Astryx, and how well? Two checks a coding agent runs before it delivers a
6
+ * page.
7
+ *
8
+ * @input A path: a project folder, a build output folder, or one file (a
9
+ * built `.html` page or a source file), and the package names whose
10
+ * components count as Astryx: every `@astryxdesign/*` package and each
11
+ * integration the project loads (its component catalog's providers).
12
+ * @output `built-astryx-usage`: fails when the path holds no import from those
13
+ * packages, no use of a component imported from them, and no Astryx
14
+ * stylesheet in built CSS or HTML. `built-astryx-purity`: warns with the
15
+ * findings of the source check in `astryx docs is-my-code-good` (raw
16
+ * elements Astryx has a component for, raw SVG and icon-library icons,
17
+ * inline styles, classes, StyleX declarations and imported stylesheets),
18
+ * each with its file and line; info, "not inspected", when the path holds
19
+ * no source with JSX (a bundle is build output, not source).
20
+ * @position Pure: the doctor adapter reads the files (readBuiltPath) and the
21
+ * integration package names (builtIntegrationPackages); nothing here runs
22
+ * project code, its configuration, or a browser. Plain `astryx doctor` does not run
23
+ * it.
24
+ */
25
+
26
+ import {
27
+ BUILT_FILE_LIMIT,
28
+ BUILT_FILE_MAX_MB,
29
+ readBuiltPath,
30
+ resolveBuiltPath,
31
+ } from './_adapter.mjs';
32
+ import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
33
+ import {parse as parseModule} from '@babel/parser';
34
+
35
+ /** Source files, read for imports and JSX. */
36
+ const SOURCE_EXT = new Set(['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs']);
37
+
38
+ /**
39
+ * The lowercased extension of a relative path, with its dot.
40
+ * @param {string} rel
41
+ */
42
+ function extensionOf(rel) {
43
+ const name = rel.slice(rel.lastIndexOf('/') + 1);
44
+ const dot = name.lastIndexOf('.');
45
+ return dot > 0 ? name.slice(dot).toLowerCase() : '';
46
+ }
47
+
48
+ /** Files that hold JSX by their extension. */
49
+ const JSX_EXT = new Set(['.tsx', '.jsx']);
50
+
51
+ /** A cheap test before parsing: a tag or fragment opens somewhere. */
52
+ const HAS_JSX = /<(?:[A-Za-z]|>)/;
53
+
54
+ /**
55
+ * Whether a `.js` or `.mjs` source file holds JSX, read from its parse, or
56
+ * null when it does not parse (Flow, decorators and the like the parser
57
+ * cannot read), so the file counts as not inspected.
58
+ * @param {string} text
59
+ * @returns {boolean | null}
60
+ */
61
+ function hasJsx(text) {
62
+ if (!HAS_JSX.test(text)) return false;
63
+ /** @type {any} */
64
+ let ast = null;
65
+ for (const plugins of /** @type {any[][]} */ ([
66
+ ['jsx'],
67
+ ['jsx', 'flow', ['decorators', {decoratorsBeforeExport: true}]],
68
+ ])) {
69
+ try {
70
+ ast = parseModule(text, {
71
+ sourceType: 'unambiguous',
72
+ plugins,
73
+ errorRecovery: true,
74
+ });
75
+ break;
76
+ } catch {
77
+ // try the next set of syntax plugins
78
+ }
79
+ }
80
+ if (!ast) return null;
81
+ /** @type {any[]} */
82
+ const stack = [ast.program];
83
+ while (stack.length > 0) {
84
+ const node = stack.pop();
85
+ if (!node || typeof node.type !== 'string') continue;
86
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') return true;
87
+ for (const key of Object.keys(node)) {
88
+ if (key === 'loc' || key.endsWith('Comments')) continue;
89
+ const value = node[key];
90
+ if (Array.isArray(value)) {
91
+ for (const child of value) stack.push(child);
92
+ } else if (value && typeof value === 'object') stack.push(value);
93
+ }
94
+ }
95
+ return false;
96
+ }
97
+
98
+ /** Built files, read for an Astryx stylesheet. */
99
+ const BUILT_EXT = new Set(['.css', '.html', '.htm', '.js', '.mjs']);
100
+
101
+ /** How many findings a check message names before it counts the rest. */
102
+ const SHOWN = 5;
103
+
104
+ /**
105
+ * Marks of Astryx's stylesheets that survive a production build: the cascade
106
+ * layers Core's and the themes' CSS declare, and Astryx's own custom
107
+ * properties.
108
+ */
109
+ const STYLESHEET_MARK =
110
+ /@layer\s+[^{;]*\bastryx-(?:base|theme)\b|--astryx-[\w-]+/;
111
+
112
+ /**
113
+ * Raw elements the rubric names a component for (`astryx docs
114
+ * is-my-code-good`, "Common component replacements"), with that owner.
115
+ * @type {Readonly<Record<string, string>>}
116
+ */
117
+ const RAW_ELEMENTS = Object.freeze({
118
+ div: '`VStack`, `HStack`, `Grid`, `Card`, `Section` or `Center`',
119
+ span: '`Text`',
120
+ p: '`Text`',
121
+ h1: '`Heading`',
122
+ h2: '`Heading`',
123
+ h3: '`Heading`',
124
+ h4: '`Heading`',
125
+ h5: '`Heading`',
126
+ h6: '`Heading`',
127
+ button: '`Button` or `IconButton`',
128
+ a: '`Link`',
129
+ nav: '`LayoutPanel`',
130
+ aside: '`LayoutPanel`',
131
+ header: '`LayoutHeader`',
132
+ main: '`LayoutContent`',
133
+ ul: '`List`',
134
+ ol: '`List`',
135
+ li: '`ListItem`',
136
+ input: 'the matching form control',
137
+ textarea: 'the matching form control',
138
+ select: 'the matching form control',
139
+ table: '`Table`',
140
+ tr: '`Table`',
141
+ td: '`Table`',
142
+ th: '`Table`',
143
+ hr: '`Divider`',
144
+ dialog: '`Dialog`',
145
+ details: '`Collapsible`',
146
+ summary: '`Collapsible`',
147
+ });
148
+
149
+ /** Raw SVG elements the rubric counts as hand-drawn icons. */
150
+ const SVG_ELEMENTS = new Set([
151
+ 'svg',
152
+ 'path',
153
+ 'circle',
154
+ 'rect',
155
+ 'line',
156
+ 'polyline',
157
+ 'polygon',
158
+ 'ellipse',
159
+ 'g',
160
+ ]);
161
+
162
+ /** Icon libraries whose components the rubric counts when used directly. */
163
+ const ICON_PACKAGES = [
164
+ 'lucide-react',
165
+ 'react-icons',
166
+ '@heroicons/react',
167
+ '@tabler/icons-react',
168
+ '@phosphor-icons/react',
169
+ 'react-feather',
170
+ '@mui/icons-material',
171
+ '@fortawesome/react-fontawesome',
172
+ '@radix-ui/react-icons',
173
+ ];
174
+
175
+ /**
176
+ * @typedef {object} BuiltFinding
177
+ * @property {string} category the rubric category: `Astryx components`,
178
+ * `Icons` or `Styling`
179
+ * @property {string} file relative to the checked path
180
+ * @property {number} line 1-based
181
+ * @property {string} message
182
+ */
183
+
184
+ /**
185
+ * @typedef {object} BuiltScan
186
+ * @property {number} sourceFiles
187
+ * @property {number} jsxFiles source files whose JSX was inspected
188
+ * @property {number} builtFiles
189
+ * @property {number} imports imports from Astryx packages
190
+ * @property {number} importFiles files with one
191
+ * @property {number} componentUses JSX uses of names imported from them
192
+ * @property {string[]} packages the Astryx packages imported, sorted
193
+ * @property {string[]} stylesheets built files with an Astryx stylesheet
194
+ * @property {BuiltFinding[]} findings
195
+ * @property {boolean} truncated whether the file limit cut the read short
196
+ * @property {number} unread source files over the size limit, unreadable, or
197
+ * not parsed
198
+ * @property {string[]} unreadFiles those files, relative to the path
199
+ * @property {number} missingLinks local files a built page links that are not
200
+ * there
201
+ */
202
+
203
+ /**
204
+ * Whether a package specifier names one of the Astryx packages.
205
+ * @param {string} spec
206
+ * @param {readonly string[]} packages
207
+ */
208
+ function isAstryxSpecifier(spec, packages) {
209
+ if (spec.startsWith('@astryxdesign/')) return true;
210
+ return packages.some(name => spec === name || spec.startsWith(`${name}/`));
211
+ }
212
+
213
+ /** @param {string} spec */
214
+ function isIconSpecifier(spec) {
215
+ return ICON_PACKAGES.some(
216
+ name => spec === name || spec.startsWith(`${name}/`),
217
+ );
218
+ }
219
+
220
+ /**
221
+ * The 1-based line of an offset.
222
+ * @param {string} text
223
+ * @param {number} at
224
+ */
225
+ function lineAt(text, at) {
226
+ if (text !== lineCache.text) {
227
+ /** @type {number[]} */
228
+ const starts = [0];
229
+ for (let i = text.indexOf('\n'); i >= 0; i = text.indexOf('\n', i + 1)) {
230
+ starts.push(i + 1);
231
+ }
232
+ lineCache = {text, starts};
233
+ }
234
+ const {starts} = lineCache;
235
+ let low = 0;
236
+ let high = starts.length - 1;
237
+ while (low < high) {
238
+ const mid = (low + high + 1) >> 1;
239
+ if (starts[mid] <= at) low = mid;
240
+ else high = mid - 1;
241
+ }
242
+ return low + 1;
243
+ }
244
+
245
+ /** The line starts of the last file lineAt read, found once per file. */
246
+ /** @type {{text: string | null, starts: number[]}} */
247
+ let lineCache = {text: null, starts: [0]};
248
+
249
+ /**
250
+ * Text with comments blanked out, keeping every offset, so a commented-out
251
+ * tag or import is not read. The comments are the ones `@babel/parser`
252
+ * finds, so a `//` or `/*` in a string or in JSX text is not one; a file it
253
+ * cannot parse falls back to a scan that skips string literals.
254
+ * @param {string} text
255
+ */
256
+ function withoutComments(text, ext = '', parsed = commentRanges(text, ext)) {
257
+ if (parsed) {
258
+ const out = text.split('');
259
+ for (const [start, end] of parsed) {
260
+ for (let j = start; j < end; j++) if (out[j] !== '\n') out[j] = ' ';
261
+ }
262
+ return out.join('');
263
+ }
264
+ return scanOutComments(text);
265
+ }
266
+
267
+ /**
268
+ * A source file's syntax tree from `@babel/parser` (TypeScript and JSX, then
269
+ * legacy decorators, then Flow), or null when no attempt parses it.
270
+ * @param {string} text
271
+ * @param {string} ext
272
+ * @returns {any}
273
+ */
274
+ function parseSource(text, ext) {
275
+ const typescript = /^\.[cm]?tsx?$/.test(ext);
276
+ const jsx = ext === '.tsx' || !typescript;
277
+ const base = [...(typescript ? ['typescript'] : []), ...(jsx ? ['jsx'] : [])];
278
+ for (const plugins of /** @type {any[][]} */ ([
279
+ base,
280
+ [...base, 'decorators-legacy'],
281
+ ...(typescript
282
+ ? []
283
+ : [['jsx', 'flow', ['decorators', {decoratorsBeforeExport: true}]]]),
284
+ ])) {
285
+ try {
286
+ return parseModule(text, {
287
+ sourceType: 'unambiguous',
288
+ plugins,
289
+ errorRecovery: true,
290
+ });
291
+ } catch {
292
+ // try the next set of syntax plugins
293
+ }
294
+ }
295
+ return null;
296
+ }
297
+
298
+ /**
299
+ * The comment ranges `@babel/parser` finds in a source file, or null when it
300
+ * cannot parse the file.
301
+ * @param {string} text
302
+ * @param {string} ext
303
+ * @param {any} [ast]
304
+ * @returns {Array<[number, number]> | null}
305
+ */
306
+ function commentRanges(text, ext, ast = parseSource(text, ext)) {
307
+ if (!ast) return null;
308
+ return (ast.comments ?? []).map(
309
+ (/** @type {any} */ c) =>
310
+ /** @type {[number, number]} */ ([c.start, c.end]),
311
+ );
312
+ }
313
+
314
+ /**
315
+ * The imports a parsed source file makes, read from its syntax tree so that
316
+ * an import written in a string, a template literal or JSX text (a code
317
+ * sample on a page) is not one: import and export-from declarations, and
318
+ * `require()` and `import()` of a string.
319
+ * @param {any} ast
320
+ * @returns {{spec: string, names: string[], at: number}[]}
321
+ */
322
+ function astImports(ast) {
323
+ /** @type {{spec: string, names: string[], at: number}[]} */
324
+ const found = [];
325
+ for (const node of ast.program.body) {
326
+ if (node.type === 'ImportDeclaration') {
327
+ found.push({
328
+ spec: node.source.value,
329
+ names: node.specifiers.map(
330
+ (/** @type {any} */ each) => each.local.name,
331
+ ),
332
+ at: node.start,
333
+ });
334
+ } else if (
335
+ (node.type === 'ExportNamedDeclaration' ||
336
+ node.type === 'ExportAllDeclaration') &&
337
+ node.source
338
+ ) {
339
+ found.push({spec: node.source.value, names: [], at: node.start});
340
+ }
341
+ }
342
+ /** @type {any[]} */
343
+ const stack = [ast.program];
344
+ while (stack.length > 0) {
345
+ const node = stack.pop();
346
+ if (!node || typeof node.type !== 'string') continue;
347
+ if (
348
+ node.type === 'CallExpression' &&
349
+ (node.callee?.type === 'Import' ||
350
+ (node.callee?.type === 'Identifier' &&
351
+ node.callee.name === 'require')) &&
352
+ node.arguments?.[0]?.type === 'StringLiteral'
353
+ ) {
354
+ found.push({spec: node.arguments[0].value, names: [], at: node.start});
355
+ }
356
+ for (const key of Object.keys(node)) {
357
+ if (key === 'loc' || key.endsWith('Comments')) continue;
358
+ const value = node[key];
359
+ if (Array.isArray(value)) {
360
+ for (const child of value) stack.push(child);
361
+ } else if (value && typeof value === 'object') stack.push(value);
362
+ }
363
+ }
364
+ return found;
365
+ }
366
+
367
+ /**
368
+ * Text with comments blanked by a scan that skips string literals, for a
369
+ * file the parser cannot read.
370
+ * @param {string} text
371
+ */
372
+ function scanOutComments(text) {
373
+ const out = text.split('');
374
+ /** @type {string | null} the quote of the string being read */
375
+ let quote = null;
376
+ for (let i = 0; i < text.length; i++) {
377
+ const char = text[i];
378
+ if (quote) {
379
+ if (char === '\\') i++;
380
+ else if (char === quote || (char === '\n' && quote !== '`')) quote = null;
381
+ continue;
382
+ }
383
+ if (char === '"' || char === "'" || char === '`') {
384
+ quote = char;
385
+ continue;
386
+ }
387
+ if (char !== '/') continue;
388
+ const next = text[i + 1];
389
+ if (next !== '/' && next !== '*') continue;
390
+ const end =
391
+ next === '/'
392
+ ? (text.indexOf('\n', i) + 1 || text.length + 1) - 1
393
+ : (text.indexOf('*/', i + 2) + 1 || text.length - 1) + 1;
394
+ for (let j = i; j < end; j++) if (out[j] !== '\n') out[j] = ' ';
395
+ i = end - 1;
396
+ }
397
+ return out.join('');
398
+ }
399
+
400
+ /**
401
+ * The imports of a source file: each specifier with the local names it binds.
402
+ * @param {string} text
403
+ * @returns {{spec: string, names: string[], at: number}[]}
404
+ */
405
+ function importsOf(text) {
406
+ /** @type {{spec: string, names: string[], at: number}[]} */
407
+ const found = [];
408
+ const fromImport =
409
+ /\bimport\s+(?:type\s+)?([^'";]*?)\s+from\s+['"]([^'"]+)['"]|\bimport\s+['"]([^'"]+)['"]/g;
410
+ for (const match of text.matchAll(fromImport)) {
411
+ const at = /** @type {number} */ (match.index);
412
+ if (match[3]) {
413
+ found.push({spec: match[3], names: [], at});
414
+ continue;
415
+ }
416
+ const clause = match[1];
417
+ /** @type {string[]} */
418
+ const names = [];
419
+ const braces = /\{([\s\S]*)\}/.exec(clause);
420
+ if (braces) {
421
+ for (const part of braces[1].split(',')) {
422
+ const local = part
423
+ .trim()
424
+ .replace(/^type\s+/, '')
425
+ .split(/\s+as\s+/)
426
+ .pop()
427
+ ?.trim();
428
+ if (local) names.push(local);
429
+ }
430
+ }
431
+ const outside = clause.replace(/\{[\s\S]*\}/, '');
432
+ for (const part of outside.split(',')) {
433
+ const name = part.trim().replace(/^\*\s+as\s+/, '');
434
+ if (/^[A-Za-z_$][\w$]*$/.test(name)) names.push(name);
435
+ }
436
+ found.push({spec: match[2], names, at});
437
+ }
438
+ // A barrel that re-exports a package reaches it as an import does.
439
+ for (const match of text.matchAll(
440
+ /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s+['"]([^'"]+)['"]/g,
441
+ )) {
442
+ found.push({
443
+ spec: match[1],
444
+ names: [],
445
+ at: /** @type {number} */ (match.index),
446
+ });
447
+ }
448
+ for (const match of text.matchAll(
449
+ /\brequire\(\s*['"]([^'"]+)['"]\s*\)|\bimport\(\s*['"]([^'"]+)['"]\s*\)/g,
450
+ )) {
451
+ found.push({
452
+ spec: match[1] ?? match[2],
453
+ names: [],
454
+ at: /** @type {number} */ (match.index),
455
+ });
456
+ }
457
+ return found;
458
+ }
459
+
460
+ /**
461
+ * The source findings of one JSX file.
462
+ * @param {string} text comments blanked
463
+ * @param {string} rel
464
+ * @param {Set<string>} iconNames local names imported from icon libraries
465
+ * @returns {BuiltFinding[]}
466
+ */
467
+ function jsxFindings(text, rel, iconNames) {
468
+ /** @type {BuiltFinding[]} */
469
+ const findings = [];
470
+ for (const match of text.matchAll(/<([a-z][a-z0-9]*)(?=[\s/>])([^>]*)/g)) {
471
+ const tag = match[1];
472
+ const at = /** @type {number} */ (match.index);
473
+ const line = lineAt(text, at);
474
+ if (SVG_ELEMENTS.has(tag)) {
475
+ // A helper's SVG counts once: by its root element.
476
+ if (tag === 'svg') {
477
+ findings.push({
478
+ category: 'Icons',
479
+ file: rel,
480
+ line,
481
+ message:
482
+ 'raw `<svg>`: render icons through `Icon`, `IconButton` or an icon prop',
483
+ });
484
+ }
485
+ continue;
486
+ }
487
+ const owner = RAW_ELEMENTS[tag];
488
+ if (!owner) continue;
489
+ // Native semantics the rubric keeps: hidden form state.
490
+ if (tag === 'input' && /\btype\s*=\s*["']hidden["']/.test(match[2])) {
491
+ continue;
492
+ }
493
+ findings.push({
494
+ category: 'Astryx components',
495
+ file: rel,
496
+ line,
497
+ message: `raw \`<${tag}>\`: use ${owner}`,
498
+ });
499
+ }
500
+ for (const name of iconNames) {
501
+ for (const match of text.matchAll(
502
+ new RegExp(`<${name.replace(/[$]/g, '\\$')}(?=[\\s/>])`, 'g'),
503
+ )) {
504
+ findings.push({
505
+ category: 'Icons',
506
+ file: rel,
507
+ line: lineAt(text, /** @type {number} */ (match.index)),
508
+ message: `\`<${name}>\` from an icon library: render it through \`Icon\` or an icon prop`,
509
+ });
510
+ }
511
+ }
512
+ for (const [pattern, what] of /** @type {const} */ ([
513
+ [/\bstyle\s*=\s*\{/g, 'an inline `style`'],
514
+ [/\bclassName\s*=/g, 'a `className`'],
515
+ ])) {
516
+ for (const match of text.matchAll(pattern)) {
517
+ findings.push({
518
+ category: 'Styling',
519
+ file: rel,
520
+ line: lineAt(text, /** @type {number} */ (match.index)),
521
+ message: `${what}: use a component prop or token first`,
522
+ });
523
+ }
524
+ }
525
+ return findings;
526
+ }
527
+
528
+ /**
529
+ * Read a path and gather the evidence both checks judge.
530
+ * @param {string} target an existing file or folder
531
+ * @param {readonly string[]} packages package names whose components count as
532
+ * Astryx, beside every `@astryxdesign/*` package
533
+ * @returns {BuiltScan}
534
+ */
535
+ export function scanBuilt(target, packages) {
536
+ const {files, truncated, missing = 0} = readBuiltPath(target);
537
+ /** @type {BuiltScan} */
538
+ const scan = {
539
+ sourceFiles: 0,
540
+ jsxFiles: 0,
541
+ builtFiles: 0,
542
+ imports: 0,
543
+ importFiles: 0,
544
+ componentUses: 0,
545
+ packages: [],
546
+ stylesheets: [],
547
+ findings: [],
548
+ truncated,
549
+ unread: 0,
550
+ unreadFiles: [],
551
+ missingLinks: missing,
552
+ };
553
+ const imported = new Set();
554
+ for (const {rel, built, read} of files) {
555
+ const ext = extensionOf(rel);
556
+ // A bundler emits no .tsx or .jsx, so one inside a folder named like
557
+ // build output is still source.
558
+ const isSource =
559
+ SOURCE_EXT.has(ext) &&
560
+ !rel.endsWith('.d.ts') &&
561
+ (!built || JSX_EXT.has(ext));
562
+ const isBuilt = BUILT_EXT.has(ext) && (built || !isSource);
563
+ if (!isSource && !isBuilt) continue;
564
+ const raw = read();
565
+ if (raw == null) {
566
+ if (isSource) {
567
+ scan.unread++;
568
+ scan.unreadFiles.push(rel);
569
+ }
570
+ continue;
571
+ }
572
+ if (isBuilt) {
573
+ scan.builtFiles++;
574
+ // A commented-out rule or import is not Astryx styling.
575
+ const styles =
576
+ ext === '.css' || ext === '.html' || ext === '.htm'
577
+ ? raw.replace(/\/\*[\s\S]*?\*\/|<!--[\s\S]*?-->/g, ' ')
578
+ : raw;
579
+ if (STYLESHEET_MARK.test(styles)) scan.stylesheets.push(rel);
580
+ // A stylesheet that imports an Astryx package's CSS, as the
581
+ // getting-started setup does, uses Astryx.
582
+ if (ext === '.css') {
583
+ for (const match of styles.matchAll(
584
+ /@import\s+(?:url\(\s*)?['"]?([^'")\s;]+)/g,
585
+ )) {
586
+ if (!isAstryxSpecifier(match[1], packages)) continue;
587
+ scan.imports++;
588
+ scan.importFiles++;
589
+ imported.add(
590
+ match[1]
591
+ .split('/')
592
+ .slice(0, match[1].startsWith('@') ? 2 : 1)
593
+ .join('/'),
594
+ );
595
+ }
596
+ }
597
+ }
598
+ if (!isSource) continue;
599
+ scan.sourceFiles++;
600
+ const ast = parseSource(raw, ext);
601
+ const ranges = commentRanges(raw, ext, ast);
602
+ const text = withoutComments(raw, ext, ranges);
603
+ const astryxNames = new Set();
604
+ const iconNames = new Set();
605
+ let fileImports = 0;
606
+ for (const {spec, names, at} of ast ? astImports(ast) : importsOf(text)) {
607
+ if (isAstryxSpecifier(spec, packages)) {
608
+ fileImports++;
609
+ imported.add(
610
+ spec.startsWith('@')
611
+ ? spec.split('/').slice(0, 2).join('/')
612
+ : spec.split('/')[0],
613
+ );
614
+ for (const name of names) astryxNames.add(name);
615
+ } else if (isIconSpecifier(spec)) {
616
+ for (const name of names) iconNames.add(name);
617
+ } else if (/\.(?:css|scss|sass|less)$/.test(spec)) {
618
+ scan.findings.push({
619
+ category: 'Styling',
620
+ file: rel,
621
+ line: lineAt(text, at),
622
+ message: `imports the stylesheet \`${spec}\`: use component props and tokens`,
623
+ });
624
+ }
625
+ }
626
+ for (const match of text.matchAll(/\bstylex\.create\s*\(/g)) {
627
+ scan.findings.push({
628
+ category: 'Styling',
629
+ file: rel,
630
+ line: lineAt(text, /** @type {number} */ (match.index)),
631
+ message:
632
+ 'a `stylex.create` declaration: use a component prop or token first',
633
+ });
634
+ }
635
+ scan.imports += fileImports;
636
+ if (fileImports > 0) scan.importFiles++;
637
+ for (const name of astryxNames) {
638
+ if (!/^[A-Z]/.test(name)) continue;
639
+ const uses = text.match(new RegExp(`<${name}(?=[\\s/>.])`, 'g'));
640
+ scan.componentUses += uses?.length ?? 0;
641
+ }
642
+ // A file the parser cannot read is not inspected: its imports still
643
+ // count, but no finding is read from it.
644
+ if (ranges === null && (JSX_EXT.has(ext) || /\.[cm]?js$/u.test(ext))) {
645
+ scan.unread++;
646
+ scan.unreadFiles.push(rel);
647
+ continue;
648
+ }
649
+ const jsx = /\.[cm]?js$/u.test(ext) ? hasJsx(text) : false;
650
+ if (jsx === null) {
651
+ scan.unread++;
652
+ scan.unreadFiles.push(rel);
653
+ continue;
654
+ }
655
+ if (JSX_EXT.has(ext) || jsx) {
656
+ scan.jsxFiles++;
657
+ for (const finding of jsxFindings(text, rel, iconNames)) {
658
+ scan.findings.push(finding);
659
+ }
660
+ }
661
+ }
662
+ scan.packages = [...imported].sort();
663
+ scan.findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
664
+ return scan;
665
+ }
666
+
667
+ /**
668
+ * @param {number} count
669
+ * @param {string} word
670
+ */
671
+ function plural(count, word) {
672
+ return `${count} ${word}${count === 1 ? '' : 's'}`;
673
+ }
674
+
675
+ /**
676
+ * The two checks for a path.
677
+ * @param {string} target as the caller gave it
678
+ * @param {{cwd: string, packages: readonly string[]}} options `packages`: the
679
+ * integration packages whose components count as Astryx
680
+ * @returns {import('./doctor.type.mjs').DoctorCheck[]}
681
+ */
682
+ export function checkBuilt(target, {cwd, packages}) {
683
+ const resolved = resolveBuiltPath(cwd, target);
684
+ if (resolved == null) {
685
+ return [
686
+ {
687
+ id: 'built-astryx-usage',
688
+ label: 'Built output uses Astryx',
689
+ status: 'fail',
690
+ message: `${target} does not exist, so nothing was checked.`,
691
+ fix: 'Pass the project folder, the build output folder, or the built HTML file.',
692
+ },
693
+ ];
694
+ }
695
+ const scan = scanBuilt(resolved, packages);
696
+ const used =
697
+ scan.imports > 0 || scan.componentUses > 0 || scan.stylesheets.length > 0;
698
+ const read = `${plural(scan.sourceFiles, 'source file')} and ${plural(scan.builtFiles, 'built file')}${scan.truncated ? ` (the first ${BUILT_FILE_LIMIT} files)` : ''}`;
699
+ const evidence = [
700
+ scan.imports > 0
701
+ ? `${plural(scan.imports, 'import')} from ${scan.packages.join(', ')} in ${plural(scan.importFiles, 'file')}`
702
+ : null,
703
+ scan.componentUses > 0
704
+ ? `${plural(scan.componentUses, 'component use')}`
705
+ : null,
706
+ scan.stylesheets.length > 0
707
+ ? `Astryx styles in ${scan.stylesheets.slice(0, 3).join(', ')}${scan.stylesheets.length > 3 ? ` and ${scan.stylesheets.length - 3} more` : ''}`
708
+ : null,
709
+ ].filter(Boolean);
710
+ /** @type {import('./doctor.type.mjs').DoctorCheck} */
711
+ const usage = used
712
+ ? {
713
+ id: 'built-astryx-usage',
714
+ label: 'Built output uses Astryx',
715
+ status: 'pass',
716
+ message: `Read ${read}: ${evidence.join('; ')}.`,
717
+ }
718
+ : scan.sourceFiles === 0 &&
719
+ scan.builtFiles === 0 &&
720
+ scan.unread === 0 &&
721
+ !scan.truncated
722
+ ? {
723
+ id: 'built-astryx-usage',
724
+ label: 'Built output uses Astryx',
725
+ status: 'fail',
726
+ message: `${target} holds no source or built files, so nothing was checked.`,
727
+ fix: 'Pass the project folder, the build output folder, or the built HTML file.',
728
+ }
729
+ : scan.truncated || scan.unread > 0 || scan.missingLinks > 0
730
+ ? {
731
+ id: 'built-astryx-usage',
732
+ label: 'Built output uses Astryx',
733
+ status: 'warn',
734
+ message: `Read ${read} and found no Astryx in them, but ${[scan.truncated ? `the rest past the first ${BUILT_FILE_LIMIT} files` : null, scan.unread > 0 ? `${plural(scan.unread, 'source file')} over ${BUILT_FILE_MAX_MB} MB, unreadable or unparsed` : null, scan.missingLinks > 0 ? `${plural(scan.missingLinks, 'file')} the page links but that are not there` : null].filter(Boolean).join(' and ')} went unread, so this does not show whether the output uses Astryx.`,
735
+ fix: `Run \`${formatCliCommand('doctor --built <folder>', cwd)}\` on the folder that holds the page itself, or on its build output.`,
736
+ }
737
+ : {
738
+ id: 'built-astryx-usage',
739
+ label: 'Built output uses Astryx',
740
+ status: 'fail',
741
+ message: `Read ${read}: no import from an Astryx package, no Astryx component, and no Astryx styles, so this output does not use Astryx.`,
742
+ fix: `Rebuild the page from an Astryx template: run \`${formatCliCommand('build "<what the page is>"', cwd)}\`, scaffold the template it names, and fill it with Astryx components. Do not deliver this output.`,
743
+ };
744
+ const unreadNames =
745
+ scan.unreadFiles.slice(0, SHOWN).join(', ') +
746
+ (scan.unreadFiles.length > SHOWN
747
+ ? ` and ${scan.unreadFiles.length - SHOWN} more`
748
+ : '');
749
+ const unreadNote =
750
+ scan.unread > 0
751
+ ? ` ${plural(scan.unread, 'source file')} went unread (over ${BUILT_FILE_MAX_MB} MB, unreadable or not parsed), so ${scan.unread === 1 ? 'it was' : 'they were'} not inspected: ${unreadNames}.`
752
+ : '';
753
+ /** @type {import('./doctor.type.mjs').DoctorCheck} */
754
+ let purity;
755
+ if (scan.jsxFiles === 0) {
756
+ purity = {
757
+ id: 'built-astryx-purity',
758
+ label: 'Source uses Astryx well',
759
+ status: 'info',
760
+ message: `Not inspected: ${plural(scan.sourceFiles, 'source file')} under ${target} and no JSX read among them, so components, icons and styles were not checked. A bundle or other build output is not source.${unreadNote}`,
761
+ fix: `Run \`${formatCliCommand('doctor --built <project folder>', cwd)}\` on the folder that holds the page's source.`,
762
+ };
763
+ } else if (
764
+ scan.findings.length === 0 &&
765
+ (scan.truncated || scan.unread > 0)
766
+ ) {
767
+ purity = {
768
+ id: 'built-astryx-purity',
769
+ label: 'Source uses Astryx well',
770
+ status: 'info',
771
+ message: `Not fully inspected: ${plural(scan.jsxFiles, 'source file')} with JSX had no finding${scan.truncated ? `, but only the first ${BUILT_FILE_LIMIT} files were read` : ''}.${unreadNote}`,
772
+ fix: `Run \`${formatCliCommand('doctor --built <folder>', cwd)}\` on the folder that holds the page's own source.`,
773
+ };
774
+ } else if (scan.findings.length === 0) {
775
+ purity = {
776
+ id: 'built-astryx-purity',
777
+ label: 'Source uses Astryx well',
778
+ status: 'pass',
779
+ message: `${plural(scan.jsxFiles, 'source file')} with JSX: no raw element Astryx has a component for, no hand-drawn or library icon, and no custom styling.`,
780
+ };
781
+ } else {
782
+ /** @type {Record<string, number>} */
783
+ const byCategory = {};
784
+ for (const finding of scan.findings) {
785
+ byCategory[finding.category] = (byCategory[finding.category] ?? 0) + 1;
786
+ }
787
+ const counts = Object.entries(byCategory)
788
+ .map(([category, count]) => `${category} ${count}`)
789
+ .join(', ');
790
+ const shown = scan.findings
791
+ .slice(0, SHOWN)
792
+ .map(finding => `${finding.file}:${finding.line} ${finding.message}`)
793
+ .join('; ');
794
+ const more =
795
+ scan.findings.length > SHOWN
796
+ ? `; and ${scan.findings.length - SHOWN} more`
797
+ : '';
798
+ purity = {
799
+ id: 'built-astryx-purity',
800
+ label: 'Source uses Astryx well',
801
+ status: 'warn',
802
+ message: `${plural(scan.findings.length, 'finding')} (${counts}): ${shown}${more}.${unreadNote}${scan.truncated ? ` Only the first ${BUILT_FILE_LIMIT} files were read.` : ''}`,
803
+ fix: `Replace each with the Astryx component, icon surface, prop or token it names; \`${formatCliCommand('docs is-my-code-good', cwd)}\` has the full rubric. Keep a raw element only where its native meaning is needed.`,
804
+ };
805
+ }
806
+ return [usage, purity];
807
+ }