@reqvire-org/ads-guard 0.5.18 → 0.5.20

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 CHANGED
@@ -74,7 +74,9 @@ files are never checked. The report counts them.
74
74
 
75
75
  | Code | Meaning | What to do |
76
76
  | --- | --- | --- |
77
- | `design-usage/local-markup` | An element or a local component that is not imported from the design system. | Render a design-system owner. An arrangement the screen needs is a pattern of the design system. |
77
+ | `design-usage/local-markup` | Markup the application creates itself: an element (`<div>`), a tag whose type is a string (`const Tag = "div"`, a polymorphic `as`), or `h("div")` / `jsx("div")`. | Render a design-system owner. An arrangement the screen needs is a pattern of the design system. |
78
+ | `design-usage/unlisted-component` | A component of a package not listed in `allow`: imported, read off a namespace (`motion.div`), or made by a package's factory (`styled("div")`). Reported where it is read, whatever is done with it afterwards. | Render a design-system owner. A component that renders no design of its own (a router's outlet, a provider, `Suspense`, `Fragment`) goes in `allow`. |
79
+ | `design-usage/unchecked-component` | A component declared in an application file the guard does not check (outside `include`, or excluded). | Check that file too, or render a design-system owner. |
78
80
  | `design-usage/component-outside-pattern` | A component of the design system rendered outside every pattern. | A pattern arranges the screen; a component fills a pattern, as its child or in a slot prop. |
79
81
  | `design-usage/design-prop` | `style`, `className`, `css` or `dangerouslySetInnerHTML`. | Choose the treatment through the owner's own props. |
80
82
  | `design-usage/spread-props` | A JSX spread. | Pass each prop explicitly. |
@@ -82,6 +84,21 @@ files are never checked. The report counts them.
82
84
  | `design-usage/hidden-definition` | A recipe, profile or custom-property reference in a string. | Design belongs in the design system. |
83
85
  | `design-usage/design-import` | An ADS authoring macro. | Declare design in the design system. |
84
86
 
87
+ Design is markup and style; components are composition. The application's own
88
+ components pass wherever they are rendered: an `App` that routes, a route's
89
+ `<Page>` held in state, a lazily loaded `<Body>`, `memo` or `lazy` of its own
90
+ components. Their bodies are checked like any other source, so every element in
91
+ them must still come from the design system. A component from a package enters
92
+ only through `allow`; anything else that renders and comes from a package is a
93
+ finding where it is read. A factory whose arguments are only the application's
94
+ own code (`memo(Row)`, `lazy(() => import("./Page"))`, `forwardRef(fn)`) makes
95
+ one of its own components.
96
+
97
+ The guard reads the application with its own types: each file opens in the
98
+ TypeScript project of its nearest `tsconfig.json` (an inferred project without
99
+ one), so it resolves imports and aliases as the application does. Where a type
100
+ cannot be told (`any`), nothing is concluded from it.
101
+
85
102
  Document metadata is not design and is accepted anywhere: `<title>`, `<meta>`,
86
103
  `<script>` and a `<link>` that is not a stylesheet.
87
104
 
@@ -96,7 +113,7 @@ What a library contributes decides how an application uses it.
96
113
  | The library gives | Examples | Use |
97
114
  | --- | --- | --- |
98
115
  | Functions and hooks | Image URL builders, a router's hooks, date utilities | Freely. They are behavior. |
99
- | Components that render nothing | `Suspense`, `Outlet`, providers | List them in `allow`. |
116
+ | Components that render nothing | `Suspense`, `Fragment`, `Outlet`, providers | List them in `allow`. |
100
117
  | Components with their own design | A styled component library, a framework's image component | Do not render them. Take the library's function and let the design system own the element. |
101
118
 
102
119
  ### Images
@@ -129,7 +146,9 @@ if (result.kind === "ok") console.log(result.value.findings);
129
146
  await closeDesignUsage(); // releases the parser
130
147
  ```
131
148
 
132
- `checkDesignUsage(sources, entry, allowance)` checks texts you supply;
149
+ `checkDesignUsage(sources, entry, allowance)` checks texts you supply, by syntax
150
+ alone (every component tag that is not the design system's is reported);
151
+ `runGuard` reads the application's files with their types;
133
152
  `designSystemEntry(specifier, entryFile)` reads which exports are patterns.
134
153
 
135
154
  ## Long-form content
@@ -1,7 +1,7 @@
1
1
  // src/design-usage.mts
2
2
  import { readFileSync as readFileSync2 } from "node:fs";
3
- import path2 from "node:path";
4
- import { isExportDeclaration, isNamedExports, isStringLiteral as isStringLiteral2 } from "typescript/ast";
3
+ import path3 from "node:path";
4
+ import { isExportDeclaration, isNamedExports, isStringLiteral as isStringLiteral3 } from "typescript/ast";
5
5
 
6
6
  // src/analysis/design-usage.mts
7
7
  import {
@@ -256,6 +256,16 @@ async function parseSource(file, text, scriptKind) {
256
256
  return (await lease).sourceFile;
257
257
  });
258
258
  }
259
+ function withOpenFiles(files, run) {
260
+ return use(async (current) => {
261
+ const snapshot = await current.createSnapshot({ openFiles: files.map((file) => path.resolve(file)) });
262
+ try {
263
+ return await run(snapshot);
264
+ } finally {
265
+ await snapshot.dispose();
266
+ }
267
+ });
268
+ }
259
269
  function parseConfigText(file, text) {
260
270
  return use(async (current) => {
261
271
  const virtual = path.resolve(path.dirname(file), `.ads-config-${++sequence}.json`);
@@ -320,6 +330,258 @@ var ts = {
320
330
  sys
321
331
  };
322
332
 
333
+ // src/guard/components.mts
334
+ import path2 from "node:path";
335
+ import {
336
+ SyntaxKind as SyntaxKind2,
337
+ isArrowFunction as isArrowFunction2,
338
+ isCallExpression,
339
+ isFunctionExpression as isFunctionExpression2,
340
+ isIdentifier as isIdentifier2,
341
+ isImportDeclaration as isImportDeclaration2,
342
+ isJsxElement as isJsxElement2,
343
+ isJsxOpeningElement as isJsxOpeningElement2,
344
+ isJsxSelfClosingElement as isJsxSelfClosingElement2,
345
+ isNamedImports as isNamedImports2,
346
+ isNamespaceImport as isNamespaceImport2,
347
+ isNoSubstitutionTemplateLiteral as isNoSubstitutionTemplateLiteral2,
348
+ isObjectLiteralExpression,
349
+ isArrayLiteralExpression,
350
+ isPropertyAccessExpression as isPropertyAccessExpression2,
351
+ isStringLiteral as isStringLiteral2,
352
+ isTaggedTemplateExpression,
353
+ isTemplateExpression
354
+ } from "typescript/ast";
355
+ import { SignatureKind, SymbolFlags as SymbolFlags2, TypeFlags as TypeFlags2 } from "typescript/async";
356
+ var FRAMEWORK_FACTORIES = new Set(["h", "createElement", "jsx", "jsxs", "jsxDEV"]);
357
+ var NOT_A_VALUE = TypeFlags2.Any | TypeFlags2.Unknown | TypeFlags2.Never | TypeFlags2.Void | TypeFlags2.Undefined | TypeFlags2.Null;
358
+ var intrinsic = (tag) => /^[a-z]/.test(tag) && !tag.includes(".");
359
+ var relative = (specifier) => specifier.startsWith(".") || specifier.startsWith("/");
360
+ var walk2 = (node, visit) => {
361
+ visit(node);
362
+ node.forEachChild((child) => walk2(child, visit));
363
+ };
364
+
365
+ class FileReading {
366
+ source;
367
+ checker;
368
+ scope;
369
+ #element;
370
+ constructor(source, checker, scope) {
371
+ this.source = source;
372
+ this.checker = checker;
373
+ this.scope = scope;
374
+ }
375
+ async element() {
376
+ if (this.#element !== undefined)
377
+ return this.#element;
378
+ let first;
379
+ walk2(this.source, (node) => {
380
+ if (first === undefined && (isJsxElement2(node) || isJsxSelfClosingElement2(node)))
381
+ first = node;
382
+ });
383
+ this.#element = first === undefined ? null : await this.checker.getTypeAtLocation(first);
384
+ if (this.#element !== null && (this.#element.flags & NOT_A_VALUE) !== 0)
385
+ this.#element = null;
386
+ return this.#element;
387
+ }
388
+ async renders(type, depth = 0) {
389
+ if ((type.flags & NOT_A_VALUE) !== 0 || depth > 2)
390
+ return false;
391
+ if ((type.flags & TypeFlags2.Union) !== 0) {
392
+ for (const member of await type.getTypes() ?? [])
393
+ if (await this.renders(member, depth + 1))
394
+ return true;
395
+ return false;
396
+ }
397
+ const element = await this.element();
398
+ if (element === null)
399
+ return false;
400
+ for (const signature of await this.checker.getSignaturesOfType(type, SignatureKind.Call)) {
401
+ const result = await this.checker.getReturnTypeOfSignature(signature);
402
+ if ((result.flags & NOT_A_VALUE) === 0 && await this.checker.isTypeAssignableTo(element, result))
403
+ return true;
404
+ }
405
+ for (const signature of await this.checker.getSignaturesOfType(type, SignatureKind.Construct)) {
406
+ const instance = await this.checker.getReturnTypeOfSignature(signature);
407
+ if ((await this.checker.getPropertiesOfType(instance)).some((property) => property.name === "render"))
408
+ return true;
409
+ }
410
+ return false;
411
+ }
412
+ async origin(node) {
413
+ let symbol = await this.checker.getSymbolAtLocation(node);
414
+ if (symbol === undefined)
415
+ return { kind: "unknown" };
416
+ if ((symbol.flags & SymbolFlags2.Alias) !== 0)
417
+ symbol = await this.checker.getAliasedSymbol(symbol);
418
+ const files = symbol.declarations.map((declaration) => path2.resolve(String(declaration.path)));
419
+ if (files.length === 0)
420
+ return { kind: "unknown" };
421
+ if (files.some((file) => this.#checked(file)))
422
+ return { kind: "application" };
423
+ if (files.some((file) => this.#inDesignSystem(file)))
424
+ return { kind: "design-system" };
425
+ return { kind: "elsewhere", file: files[0] ?? "" };
426
+ }
427
+ #checked(file) {
428
+ return this.scope.checked.has(file) || [...this.scope.checked].some((checked) => checked.toLowerCase() === file.toLowerCase());
429
+ }
430
+ #inDesignSystem(file) {
431
+ const folder = this.scope.designSystem.toLowerCase() + path2.sep;
432
+ return file.toLowerCase().startsWith(folder);
433
+ }
434
+ }
435
+ function packageOf(file) {
436
+ const parts = file.split(path2.sep);
437
+ const at = parts.lastIndexOf("node_modules");
438
+ if (at < 0)
439
+ return file;
440
+ const first = parts[at + 1] ?? "";
441
+ return first.startsWith("@") ? `${first}/${parts[at + 2] ?? ""}` : first;
442
+ }
443
+ async function typedDesignUsage(source, checker, scope, syntactic) {
444
+ const reading = new FileReading(source, checker, scope);
445
+ const settled = [];
446
+ const imported = new Map;
447
+ const namespaces = new Map;
448
+ const flagged = new Set;
449
+ const flaggedNames = new Set;
450
+ for (const statement of source.statements) {
451
+ if (!isImportDeclaration2(statement) || !isStringLiteral2(statement.moduleSpecifier) || statement.importClause?.phaseModifier === SyntaxKind2.TypeKeyword)
452
+ continue;
453
+ const specifier = statement.moduleSpecifier.text;
454
+ if (relative(specifier) || specifier === scope.publicEntry || specifier.startsWith("node:"))
455
+ continue;
456
+ const clause = statement.importClause;
457
+ if (clause === undefined)
458
+ continue;
459
+ if (clause.name !== undefined)
460
+ imported.set(clause.name.text, [specifier, "default"]);
461
+ const bindings = clause.namedBindings;
462
+ if (bindings !== undefined && isNamespaceImport2(bindings))
463
+ namespaces.set(bindings.name.text, specifier);
464
+ else if (bindings !== undefined && isNamedImports2(bindings)) {
465
+ for (const element of bindings.elements)
466
+ if (!element.isTypeOnly)
467
+ imported.set(element.name.text, [specifier, (element.propertyName ?? element.name).text]);
468
+ }
469
+ }
470
+ const allowed = (specifier, name) => scope.allow.get(specifier)?.has(name) === true;
471
+ const unlisted = (node, name, from) => {
472
+ if (flagged.has(node))
473
+ return;
474
+ flagged.add(node);
475
+ settled.push({ node, problem: { kind: "unlisted-component", name, from } });
476
+ };
477
+ for (const statement of source.statements) {
478
+ if (!isImportDeclaration2(statement) || !isStringLiteral2(statement.moduleSpecifier))
479
+ continue;
480
+ const clause = statement.importClause;
481
+ if (clause === undefined || clause.phaseModifier === SyntaxKind2.TypeKeyword)
482
+ continue;
483
+ const names = [clause.name, ...clause.namedBindings !== undefined && isNamedImports2(clause.namedBindings) ? clause.namedBindings.elements.filter((element) => !element.isTypeOnly).map((element) => element.name) : []];
484
+ for (const name of names) {
485
+ if (name === undefined)
486
+ continue;
487
+ const binding = imported.get(name.text);
488
+ if (binding === undefined || allowed(...binding) || FRAMEWORK_FACTORIES.has(binding[1]))
489
+ continue;
490
+ if (await reading.renders(await checker.getTypeAtLocation(name))) {
491
+ unlisted(name, binding[1] === "default" ? name.text : binding[1], binding[0]);
492
+ flaggedNames.add(name.text);
493
+ }
494
+ }
495
+ }
496
+ const designProblems = new Map;
497
+ for (const usage of syntactic) {
498
+ if (usage.problem.kind !== "local-markup") {
499
+ settled.push(usage);
500
+ continue;
501
+ }
502
+ designProblems.set(usage.node, usage);
503
+ }
504
+ const members = [];
505
+ walk2(source, (node) => {
506
+ if (isPropertyAccessExpression2(node) && isIdentifier2(node.expression)) {
507
+ const base = node.expression.text;
508
+ const specifier = namespaces.get(base) ?? imported.get(base)?.[0];
509
+ if (specifier !== undefined && !allowed(specifier, node.name.text))
510
+ members.push(node);
511
+ }
512
+ });
513
+ for (const member of members) {
514
+ if (!isPropertyAccessExpression2(member) || !isIdentifier2(member.expression))
515
+ continue;
516
+ const specifier = namespaces.get(member.expression.text) ?? imported.get(member.expression.text)?.[0] ?? "";
517
+ if (flaggedNames.has(member.expression.text))
518
+ continue;
519
+ if (await reading.renders(await checker.getTypeAtLocation(member)))
520
+ unlisted(member, `${member.expression.text}.${member.name.text}`, specifier);
521
+ }
522
+ const calls = [];
523
+ walk2(source, (node) => {
524
+ if (isCallExpression(node) || isTaggedTemplateExpression(node))
525
+ calls.push(node);
526
+ });
527
+ for (const call of calls) {
528
+ const callee = isCallExpression(call) ? call.expression : isTaggedTemplateExpression(call) ? call.tag : undefined;
529
+ if (callee === undefined)
530
+ continue;
531
+ const root = isIdentifier2(callee) ? callee : isPropertyAccessExpression2(callee) && isIdentifier2(callee.expression) ? callee.expression : undefined;
532
+ if (root === undefined)
533
+ continue;
534
+ const specifier = imported.get(root.text)?.[0] ?? namespaces.get(root.text);
535
+ if (specifier === undefined)
536
+ continue;
537
+ const name = isIdentifier2(callee) ? imported.get(callee.text)?.[1] ?? callee.text : isPropertyAccessExpression2(callee) ? callee.name.text : "";
538
+ if (isCallExpression(call) && FRAMEWORK_FACTORIES.has(name)) {
539
+ const [first] = call.arguments;
540
+ if (first !== undefined && (isStringLiteral2(first) || isNoSubstitutionTemplateLiteral2(first) || ((await checker.getTypeAtLocation(first)).flags & TypeFlags2.StringLike) !== 0))
541
+ settled.push({ node: call, problem: { kind: "local-markup", tag: isStringLiteral2(first) || isNoSubstitutionTemplateLiteral2(first) ? first.text : first.getText() } });
542
+ continue;
543
+ }
544
+ if (allowed(specifier, name))
545
+ continue;
546
+ if (!await reading.renders(await checker.getTypeAtLocation(call)))
547
+ continue;
548
+ const literal = (argument) => isStringLiteral2(argument) || isNoSubstitutionTemplateLiteral2(argument) || isTemplateExpression(argument) || isObjectLiteralExpression(argument) || isArrayLiteralExpression(argument);
549
+ const args = isCallExpression(call) ? [...call.arguments] : [];
550
+ const own = !isTaggedTemplateExpression(call) && args.length > 0 && args.every((argument) => !literal(argument)) && (await Promise.all(args.map(async (argument) => isArrowFunction2(argument) || isFunctionExpression2(argument) || (await reading.origin(argument)).kind !== "elsewhere"))).every(Boolean);
551
+ if (!own)
552
+ unlisted(call, name, specifier);
553
+ }
554
+ for (const [node, usage] of designProblems) {
555
+ if (usage.problem.kind !== "local-markup")
556
+ continue;
557
+ const tag = isJsxOpeningElement2(node) || isJsxSelfClosingElement2(node) ? node.tagName : undefined;
558
+ if (tag === undefined || intrinsic(usage.problem.tag)) {
559
+ settled.push(usage);
560
+ continue;
561
+ }
562
+ if (((await checker.getTypeAtLocation(tag)).flags & TypeFlags2.StringLike) !== 0) {
563
+ settled.push(usage);
564
+ continue;
565
+ }
566
+ const root = isIdentifier2(tag) ? tag : isPropertyAccessExpression2(tag) && isIdentifier2(tag.expression) ? tag.expression : undefined;
567
+ if (root !== undefined && (imported.has(root.text) || namespaces.has(root.text))) {
568
+ const [specifier, name] = imported.get(root.text) ?? [namespaces.get(root.text) ?? "", root.text];
569
+ const exported = isPropertyAccessExpression2(tag) ? tag.name.text : name;
570
+ if (!allowed(specifier, exported) && !flaggedNames.has(root.text) && !flagged.has(tag))
571
+ unlisted(tag, isPropertyAccessExpression2(tag) ? tag.getText() : exported, specifier);
572
+ continue;
573
+ }
574
+ const origin = await reading.origin(tag);
575
+ if (origin.kind !== "elsewhere")
576
+ continue;
577
+ if (origin.file.split(path2.sep).includes("node_modules"))
578
+ unlisted(tag, tag.getText(), packageOf(origin.file));
579
+ else
580
+ settled.push({ node: tag, problem: { kind: "unchecked-component", name: tag.getText(), file: path2.relative(scope.root, origin.file).split(path2.sep).join("/") } });
581
+ }
582
+ return settled.sort((a, b) => a.node.pos - b.node.pos);
583
+ }
584
+
323
585
  // src/design-usage.mts
324
586
  var wording = {
325
587
  "design-import": (problem) => [`${problem.specifier} authors design, which belongs to the design system.`, "Declare the design in the design system and import the owner from its public entry."],
@@ -327,7 +589,15 @@ var wording = {
327
589
  `The component ${problem.name} is rendered outside every pattern, so nothing owns its place on the screen.`,
328
590
  "Render it inside the pattern that arranges this screen (as its child or in a slot prop); if no pattern does, add one to the design system."
329
591
  ],
330
- "local-markup": (problem) => [`<${problem.tag}> is not imported from the design system.`, "Render a design-system owner; an arrangement or element the screen needs belongs in a pattern of the design system."],
592
+ "local-markup": (problem) => [`<${problem.tag}> is markup the application creates itself, not a design-system owner.`, "Render a design-system owner; an arrangement or element the screen needs belongs in a pattern of the design system."],
593
+ "unlisted-component": (problem) => [
594
+ `${problem.name} is a component of ${problem.from}, which the guard does not list: its markup and styles are not the design system's.`,
595
+ `Render a design-system owner instead. If it renders no design of its own (a router's outlet, a provider, Suspense), list it in "allow" under "${problem.from}".`
596
+ ],
597
+ "unchecked-component": (problem) => [
598
+ `${problem.name} is declared in ${problem.file}, which the guard does not check, so its markup and styles are not seen.`,
599
+ `Check that file too (in the guard's "include", not "exclude"), or render a design-system owner.`
600
+ ],
331
601
  "spread-props": () => ["A spread passes props nothing can see.", "Pass each prop explicitly."],
332
602
  "design-prop": (problem) => [`${problem.attribute} supplies design from outside the design system.`, "Remove it; choose the treatment through the owner's own props."],
333
603
  "imperative-design": (problem) => [`${problem.member} writes styles or creates DOM by hand.`, "Remove the write; render design-system owners with props."],
@@ -340,7 +610,7 @@ var describe = (problem) => {
340
610
  async function checkDesignUsage2(sources, entry, allowance = {}) {
341
611
  const findings = [];
342
612
  for (const { file, text } of sources) {
343
- const source = await parseSource(path2.resolve(file), text);
613
+ const source = await parseSource(path3.resolve(file), text);
344
614
  for (const { node, problem } of designUsageProblems(source, entry, allowance)) {
345
615
  const at = source.getLineAndCharacterOfPosition(node.getStart(source));
346
616
  const [message, repair] = describe(problem);
@@ -349,11 +619,33 @@ async function checkDesignUsage2(sources, entry, allowance = {}) {
349
619
  }
350
620
  return findings;
351
621
  }
622
+ async function checkApplicationDesignUsage(root, files, entry, designSystem, allowance = {}) {
623
+ const absolute = files.map((file) => path3.resolve(root, file));
624
+ if (absolute.length === 0)
625
+ return [];
626
+ const scope = { root: path3.resolve(root), checked: new Set(absolute), designSystem: path3.resolve(designSystem), publicEntry: entry.publicEntry, allow: allowance.components ?? new Map };
627
+ return withOpenFiles(absolute, async (snapshot) => {
628
+ const findings = [];
629
+ for (const [index, file] of absolute.entries()) {
630
+ const project = await snapshot.getDefaultProjectForFile(file);
631
+ const source = project === undefined ? undefined : await project.program.getSourceFile(file);
632
+ if (project === undefined || source === undefined)
633
+ throw new Error(`TypeScript could not open ${files[index]} in a project.`);
634
+ const syntactic = designUsageProblems(source, entry, allowance);
635
+ for (const { node, problem } of await typedDesignUsage(source, project.checker, scope, syntactic)) {
636
+ const at = source.getLineAndCharacterOfPosition(node.getStart(source));
637
+ const [message, repair] = describe(problem);
638
+ findings.push({ file: files[index] ?? file, line: at.line + 1, column: at.character + 1, code: `design-usage/${problem.kind}`, message, repair });
639
+ }
640
+ }
641
+ return findings;
642
+ });
643
+ }
352
644
  async function designSystemEntry2(publicEntry, entryFile) {
353
- const source = await parseSource(path2.resolve(entryFile), readFileSync2(entryFile, "utf8"));
645
+ const source = await parseSource(path3.resolve(entryFile), readFileSync2(entryFile, "utf8"));
354
646
  const patterns = new Set;
355
647
  for (const statement of source.statements) {
356
- if (!isExportDeclaration(statement) || statement.isTypeOnly || statement.moduleSpecifier === undefined || !isStringLiteral2(statement.moduleSpecifier))
648
+ if (!isExportDeclaration(statement) || statement.isTypeOnly || statement.moduleSpecifier === undefined || !isStringLiteral3(statement.moduleSpecifier))
357
649
  continue;
358
650
  if (!statement.moduleSpecifier.text.startsWith("./patterns/"))
359
651
  continue;
@@ -370,7 +662,7 @@ var closeDesignUsage2 = () => closeSyntax();
370
662
 
371
663
  // src/guard/config.mts
372
664
  import { existsSync as existsSync2, readFileSync as readFileSync3, statSync } from "node:fs";
373
- import path3 from "node:path";
665
+ import path4 from "node:path";
374
666
 
375
667
  // src/result.mts
376
668
  var ok = (value) => ({ kind: "ok", value });
@@ -384,11 +676,11 @@ var GUARD_CONFIG_FILE2 = "ads-guard.config.json";
384
676
  var FIELDS = ["designSystem", "entry", "include", "exclude", "allow"];
385
677
  var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "");
386
678
  var insideRoot = (root, relative) => {
387
- const resolved = path3.resolve(root, relative);
388
- return !/[*?[\]{}]/.test(relative) && (resolved === root || resolved.startsWith(root + path3.sep));
679
+ const resolved = path4.resolve(root, relative);
680
+ return !/[*?[\]{}]/.test(relative) && (resolved === root || resolved.startsWith(root + path4.sep));
389
681
  };
390
682
  function readGuardConfig2(root) {
391
- const file = path3.join(root, GUARD_CONFIG_FILE2);
683
+ const file = path4.join(root, GUARD_CONFIG_FILE2);
392
684
  if (!existsSync2(file))
393
685
  return err([`${GUARD_CONFIG_FILE2} is missing in ${root}. Create it with "designSystem" and "include".`]);
394
686
  let value;
@@ -406,20 +698,20 @@ function readGuardConfig2(root) {
406
698
  const { designSystem, entry, include, exclude = [], allow = {} } = value;
407
699
  if (typeof designSystem !== "string" || designSystem.trim() === "")
408
700
  problems.push('"designSystem" is the specifier the application imports the design system by, such as "@acme/design".');
409
- if (entry !== undefined && (typeof entry !== "string" || !insideRoot(root, entry) || !existsSync2(path3.resolve(root, entry))))
701
+ if (entry !== undefined && (typeof entry !== "string" || !insideRoot(root, entry) || !existsSync2(path4.resolve(root, entry))))
410
702
  problems.push(`"entry" is the path of the design system's public entry file, relative to this file. It does not exist.`);
411
703
  if (!isStrings(include) || include.length === 0)
412
704
  problems.push(`"include" lists the folders with the application's sources, such as ["src"].`);
413
705
  else
414
706
  for (const folder of include)
415
- if (!insideRoot(root, folder) || !existsSync2(path3.resolve(root, folder)) || !statSync(path3.resolve(root, folder)).isDirectory())
707
+ if (!insideRoot(root, folder) || !existsSync2(path4.resolve(root, folder)) || !statSync(path4.resolve(root, folder)).isDirectory())
416
708
  problems.push(`"include" names ${folder}, which is not a folder under this file. Wildcards are not supported.`);
417
709
  if (!isStrings(exclude))
418
710
  problems.push('"exclude" lists folders and files, such as ["src/generated"].');
419
711
  else if (isStrings(include))
420
712
  for (const item of exclude) {
421
- const resolved = path3.resolve(root, item);
422
- const within = include.some((folder) => resolved.startsWith(path3.resolve(root, folder) + path3.sep));
713
+ const resolved = path4.resolve(root, item);
714
+ const within = include.some((folder) => resolved.startsWith(path4.resolve(root, folder) + path4.sep));
423
715
  if (!insideRoot(root, item) || !existsSync2(resolved))
424
716
  problems.push(`"exclude" names ${item}, which does not exist. Remove it. Wildcards are not supported.`);
425
717
  else if (!within)
@@ -449,40 +741,40 @@ function readGuardConfig2(root) {
449
741
  }
450
742
 
451
743
  // src/guard/run.mts
452
- import { existsSync as existsSync3, readFileSync as readFileSync5 } from "node:fs";
744
+ import { existsSync as existsSync3 } from "node:fs";
453
745
  import { createRequire as createRequire2 } from "node:module";
454
- import path6 from "node:path";
746
+ import path7 from "node:path";
455
747
 
456
748
  // src/guard/files.mts
457
749
  import { readdirSync, statSync as statSync2 } from "node:fs";
458
- import path4 from "node:path";
750
+ import path5 from "node:path";
459
751
  var SOURCE = /\.[cm]?[jt]sx$/;
460
752
  var TEST = /(?:\.(?:test|spec)\.[cm]?[jt]sx?$)|(?:^|\/)(?:__tests__|__mocks__)\//;
461
753
  var SKIPPED_FOLDERS = new Set(["node_modules"]);
462
- function walk2(folder, visit) {
754
+ function walk3(folder, visit) {
463
755
  for (const entry of readdirSync(folder, { withFileTypes: true })) {
464
756
  if (entry.name.startsWith(".") || SKIPPED_FOLDERS.has(entry.name))
465
757
  continue;
466
- const file = path4.join(folder, entry.name);
758
+ const file = path5.join(folder, entry.name);
467
759
  if (entry.isDirectory())
468
- walk2(file, visit);
760
+ walk3(file, visit);
469
761
  else if (entry.isFile() && SOURCE.test(entry.name))
470
762
  visit(file);
471
763
  }
472
764
  }
473
765
  function guardScope(root, include, exclude, designSystemFolder) {
474
- const relative = (file) => path4.relative(root, file).split(path4.sep).join("/");
475
- const excludedPaths = exclude.map((item) => path4.resolve(root, item));
766
+ const relative = (file) => path5.relative(root, file).split(path5.sep).join("/");
767
+ const excludedPaths = exclude.map((item) => path5.resolve(root, item));
476
768
  const excluded = new Map(exclude.map((item) => [item, 0]));
477
769
  const files = new Set;
478
770
  let tests = 0, designSystem = 0;
479
771
  for (const folder of include)
480
- walk2(path4.resolve(root, folder), (file) => {
481
- const index = excludedPaths.findIndex((item) => file === item || file.startsWith(item + path4.sep) || statSync2(item).isFile() && file === item);
772
+ walk3(path5.resolve(root, folder), (file) => {
773
+ const index = excludedPaths.findIndex((item) => file === item || file.startsWith(item + path5.sep) || statSync2(item).isFile() && file === item);
482
774
  const name = exclude[index];
483
775
  if (name !== undefined)
484
776
  excluded.set(name, (excluded.get(name) ?? 0) + 1);
485
- else if (designSystemFolder !== null && file.startsWith(designSystemFolder + path4.sep))
777
+ else if (designSystemFolder !== null && file.startsWith(designSystemFolder + path5.sep))
486
778
  designSystem++;
487
779
  else if (TEST.test(relative(file)))
488
780
  tests++;
@@ -495,7 +787,7 @@ function guardScope(root, include, exclude, designSystemFolder) {
495
787
  // src/guard/externals.mts
496
788
  import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
497
789
  import { createRequire } from "node:module";
498
- import path5 from "node:path";
790
+ import path6 from "node:path";
499
791
  import { pathToFileURL } from "node:url";
500
792
  var MARK = /export \{ ([\w$]+)(?: as ([\w$]+))? \} from "([^"]+)";\n\/\* ads-external (\{[^*]*\}) \*\//g;
501
793
  var PROBE = "ads-external-probe";
@@ -507,7 +799,7 @@ function declared(folder) {
507
799
  for (const entry of readdirSync2(directory)) {
508
800
  if (entry === "node_modules" || entry.startsWith("."))
509
801
  continue;
510
- const file = path5.join(directory, entry);
802
+ const file = path6.join(directory, entry);
511
803
  if (statSync3(file).isDirectory())
512
804
  visit(file, depth + 1);
513
805
  else if (/\.ads\.[cm]?[jt]s$/.test(entry)) {
@@ -523,10 +815,10 @@ function declared(folder) {
523
815
  return found;
524
816
  }
525
817
  async function verifyExternals(root, entry) {
526
- const externals = declared(path5.dirname(entry));
818
+ const externals = declared(path6.dirname(entry));
527
819
  if (externals.length === 0)
528
820
  return [];
529
- const require2 = createRequire(path5.join(root, "package.json"));
821
+ const require2 = createRequire(path6.join(root, "package.json"));
530
822
  let react;
531
823
  let server;
532
824
  try {
@@ -569,23 +861,23 @@ async function verifyExternals(root, entry) {
569
861
  var ENTRY_NAMES = ["index.ts", "index.tsx", "index.mts", "index.js", "index.mjs"];
570
862
  function entryFile(root, config) {
571
863
  if (config.entry !== undefined) {
572
- const configured = path6.resolve(root, config.entry);
864
+ const configured = path7.resolve(root, config.entry);
573
865
  return ok(configured);
574
866
  }
575
867
  const specifier = config.designSystem;
576
868
  if (specifier.startsWith(".")) {
577
- const target = path6.resolve(root, specifier);
578
- const found = [target, ...ENTRY_NAMES.map((name) => path6.join(target, name))].find((candidate) => existsSync3(candidate) && /\.[cm]?[jt]sx?$/.test(candidate));
869
+ const target = path7.resolve(root, specifier);
870
+ const found = [target, ...ENTRY_NAMES.map((name) => path7.join(target, name))].find((candidate) => existsSync3(candidate) && /\.[cm]?[jt]sx?$/.test(candidate));
579
871
  return found === undefined ? err(`"designSystem" is ${specifier}, and no entry file is at ${target}.`) : ok(found);
580
872
  }
581
873
  try {
582
- return ok(createRequire2(path6.join(root, "package.json")).resolve(specifier));
874
+ return ok(createRequire2(path7.join(root, "package.json")).resolve(specifier));
583
875
  } catch {
584
876
  return err(`"designSystem" is ${specifier}, which does not resolve as a package from ${root}. If it is an alias of the bundler or of TypeScript, add "entry" with the path of the design system's public entry file.`);
585
877
  }
586
878
  }
587
879
  async function runGuard2(root) {
588
- const absolute = path6.resolve(root);
880
+ const absolute = path7.resolve(root);
589
881
  const config = readGuardConfig2(absolute);
590
882
  if (config.kind === "err")
591
883
  return config;
@@ -593,16 +885,15 @@ async function runGuard2(root) {
593
885
  if (located.kind === "err")
594
886
  return err([located.error]);
595
887
  const entry = await designSystemEntry2(config.value.designSystem, located.value);
596
- const folder = path6.dirname(located.value);
597
- const scope = guardScope(absolute, config.value.include, config.value.exclude, folder.startsWith(absolute + path6.sep) ? folder : null);
598
- const sources = scope.files.map((file) => ({ file, text: readFileSync5(path6.join(absolute, file), "utf8") }));
599
- const findings = await checkDesignUsage2(sources, entry, { components: config.value.allow, metadata: true });
600
- const inside = located.value.startsWith(absolute + path6.sep);
888
+ const folder = path7.dirname(located.value);
889
+ const scope = guardScope(absolute, config.value.include, config.value.exclude, folder.startsWith(absolute + path7.sep) ? folder : null);
890
+ const findings = await checkApplicationDesignUsage(absolute, scope.files, entry, folder, { components: config.value.allow, metadata: true });
891
+ const inside = located.value.startsWith(absolute + path7.sep);
601
892
  const externals = await verifyExternals(absolute, located.value);
602
893
  return ok({
603
894
  ok: findings.length === 0 && externals.every((item) => item.problem === null),
604
895
  designSystem: config.value.designSystem,
605
- entry: inside ? path6.relative(absolute, located.value).split(path6.sep).join("/") : located.value,
896
+ entry: inside ? path7.relative(absolute, located.value).split(path7.sep).join("/") : located.value,
606
897
  patterns: entry.patterns.size,
607
898
  checked: scope.files.length,
608
899
  scope: { excluded: scope.excluded, tests: scope.tests, designSystem: scope.designSystem },
package/dist/cli.mjs CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  GUARD_CONFIG_FILE2,
5
5
  runGuard2,
6
6
  guardText2
7
- } from "./chunk-63g3wrkz.mjs";
7
+ } from "./chunk-2c315vb2.mjs";
8
8
 
9
9
  // src/guard/cli.mts
10
10
  var HELP = `ads-guard [directory] [--json]
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  readGuardConfig2,
7
7
  runGuard2,
8
8
  guardText2
9
- } from "./chunk-63g3wrkz.mjs";
9
+ } from "./chunk-2c315vb2.mjs";
10
10
  export {
11
11
  GUARD_CONFIG_FILE2 as GUARD_CONFIG_FILE,
12
12
  checkDesignUsage2 as checkDesignUsage,
@@ -10,7 +10,10 @@ export type DesignUsageProblem =
10
10
  readonly kind: "component-outside-pattern";
11
11
  readonly name: string;
12
12
  }
13
- /** JSX other than something imported from the design system: a native element or a local component. */
13
+ /**
14
+ * JSX other than something imported from the design system: a native element or a local component. The guard
15
+ * settles a component tag with types (src/guard/components.mts): only markup the application creates stays.
16
+ */
14
17
  | {
15
18
  readonly kind: "local-markup";
16
19
  readonly tag: string;
@@ -1,12 +1,18 @@
1
1
  import * as ast from "typescript/ast";
2
2
  import type { Node, ScriptKind, SourceFile } from "typescript/ast";
3
- import { JsxEmit, ModuleKind, ModuleResolutionKind, SymbolFlags, TypeFlags, TypeFormatFlags, type Diagnostic, type ParsedCommandLine, type ReadConfigFileResponse, type TranspileOptions, type TranspileOutput } from "typescript/async";
3
+ import { JsxEmit, ModuleKind, ModuleResolutionKind, SymbolFlags, TypeFlags, TypeFormatFlags, type Diagnostic, type ParsedCommandLine, type ReadConfigFileResponse, type Snapshot, type TranspileOptions, type TranspileOutput } from "typescript/async";
4
4
  import { type PathMappedOptions } from "./compiler-options.mts";
5
5
  /** Closes the idle client. A caller also waits for a close already in flight (the
6
6
  * idle timer's, say), so it never returns while the native process is still closing. */
7
7
  export declare function closeSyntax(): Promise<void>;
8
8
  /** Parses `text` as `file`; inside an analysis, the captured revision's own AST is reused. */
9
9
  export declare function parseSource(file: string, text: string, scriptKind?: ScriptKind): Promise<SourceFile>;
10
+ /**
11
+ * Runs `run` with a snapshot that has `files` open, each in its own project as an editor would load it: the configured
12
+ * project of the nearest `tsconfig.json` that includes it, else an inferred project. The application's own compiler
13
+ * configuration decides resolution and types; ADS supplies none. The snapshot is released after `run`.
14
+ */
15
+ export declare function withOpenFiles<T>(files: readonly string[], run: (snapshot: Snapshot) => Promise<T>): Promise<T>;
10
16
  /** Reads configuration `text` as if it were a file beside `file`, without writing it. */
11
17
  export declare function parseConfigText(file: string, text: string): Promise<ReadConfigFileResponse>;
12
18
  /** A TypeScript configuration's compiler options, and what kept it (or a configuration it extends) from parsing. */
@@ -1,5 +1,7 @@
1
- import { type DesignSystemEntry, type DesignUsageAllowance, type DesignUsageProblem } from "./analysis/design-usage.mts";
1
+ import { type DesignSystemEntry, type DesignUsageAllowance } from "./analysis/design-usage.mts";
2
+ import { type GuardUsageProblem } from "./guard/components.mts";
2
3
  export type { DesignSystemEntry, DesignUsageAllowance, DesignUsageProblem } from "./analysis/design-usage.mts";
4
+ export type { GuardUsageProblem } from "./guard/components.mts";
3
5
  /** One finding in a source file: where, which rule, and what to do. */
4
6
  export interface DesignUsageFinding {
5
7
  readonly file: string;
@@ -8,7 +10,7 @@ export interface DesignUsageFinding {
8
10
  /** 1-based. */
9
11
  readonly column: number;
10
12
  /** `design-usage/<kind>`: stable, for filtering and reports. */
11
- readonly code: `design-usage/${DesignUsageProblem["kind"]}`;
13
+ readonly code: `design-usage/${GuardUsageProblem["kind"]}`;
12
14
  readonly message: string;
13
15
  readonly repair: string;
14
16
  }
@@ -23,6 +25,13 @@ export interface DesignUsageSource {
23
25
  * patterns ({@link designSystemEntry} reads both from the design system's public entry file).
24
26
  */
25
27
  export declare function checkDesignUsage(sources: readonly DesignUsageSource[], entry: DesignSystemEntry, allowance?: DesignUsageAllowance): Promise<readonly DesignUsageFinding[]>;
28
+ /**
29
+ * The design-use findings of an application's `files` (relative to `root`), read with the application's own types:
30
+ * each file opens in its TypeScript project, so a component the application declares in a checked file is composition,
31
+ * a tag whose type is a string is markup, and a component read from a package is a finding unless `allowance` lists
32
+ * it (src/guard/components.mts). `designSystem` is the folder of the design system's public entry.
33
+ */
34
+ export declare function checkApplicationDesignUsage(root: string, files: readonly string[], entry: DesignSystemEntry, designSystem: string, allowance?: DesignUsageAllowance): Promise<readonly DesignUsageFinding[]>;
26
35
  /**
27
36
  * The design system as the check needs it, read from its public entry file (the emitted or
28
37
  * authored `index.ts`): `publicEntry` is the specifier sources import it by, and its patterns are
@@ -0,0 +1,38 @@
1
+ import type { Node, SourceFile } from "typescript/ast";
2
+ import { type Checker } from "typescript/async";
3
+ import type { DesignUsage, DesignUsageProblem } from "../analysis/design-usage.mts";
4
+ /** What the guard reports beside the shared design-use problems: a component read from a package it does not list. */
5
+ export type GuardUsageProblem = DesignUsageProblem | {
6
+ readonly kind: "unlisted-component";
7
+ readonly name: string;
8
+ readonly from: string;
9
+ }
10
+ /** A component declared in an application file the guard does not check: its markup is not seen. */
11
+ | {
12
+ readonly kind: "unchecked-component";
13
+ readonly name: string;
14
+ readonly file: string;
15
+ };
16
+ /** A guard problem at its node. */
17
+ export interface GuardUsage {
18
+ readonly node: Node;
19
+ readonly problem: GuardUsageProblem;
20
+ }
21
+ /** Where the guard's evidence comes from: the files it checks and the design system's folder. */
22
+ export interface ComponentScope {
23
+ /** Absolute paths of the files the guard checks. */
24
+ readonly checked: ReadonlySet<string>;
25
+ /** The folder of the design system's public entry: what is declared under it is the design system's. */
26
+ readonly designSystem: string;
27
+ /** The specifier the design system is imported by (`@ds`). */
28
+ readonly publicEntry: string;
29
+ /** The application's root: unchecked files are named relative to it. */
30
+ readonly root: string;
31
+ /** Components of other packages that carry no design, by specifier and exported name (`default` for a default export). */
32
+ readonly allow: ReadonlyMap<string, ReadonlySet<string>>;
33
+ }
34
+ /**
35
+ * Settles the syntactic reading's `local-markup` problems of `source` with types, and adds what only types show: a
36
+ * component read from a package the configuration does not list, and markup made by a framework factory.
37
+ */
38
+ export declare function typedDesignUsage(source: SourceFile, checker: Checker, scope: ComponentScope, syntactic: readonly DesignUsage[]): Promise<readonly GuardUsage[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reqvire-org/ads-guard",
3
- "version": "0.5.18",
3
+ "version": "0.5.20",
4
4
  "description": "Confirms that an application's source does no design of its own and uses its ADS design system only.",
5
5
  "repository": {
6
6
  "type": "git",