@reqvire-org/ads-guard 0.0.0 → 0.5.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.
@@ -0,0 +1,556 @@
1
+ // src/design-usage.mts
2
+ import { readFileSync as readFileSync2 } from "node:fs";
3
+ import path2 from "node:path";
4
+ import { isExportDeclaration, isNamedExports, isStringLiteral as isStringLiteral2 } from "typescript/ast";
5
+
6
+ // src/analysis/design-usage.mts
7
+ import {
8
+ SyntaxKind,
9
+ isArrowFunction,
10
+ isElementAccessExpression,
11
+ isFunctionDeclaration,
12
+ isFunctionExpression,
13
+ isIdentifier,
14
+ isImportDeclaration,
15
+ isJsxAttribute,
16
+ isJsxElement,
17
+ isJsxOpeningElement,
18
+ isJsxSelfClosingElement,
19
+ isJsxSpreadAttribute,
20
+ isMethodDeclaration,
21
+ isNamedImports,
22
+ isNamespaceImport,
23
+ isNoSubstitutionTemplateLiteral,
24
+ isPropertyAccessExpression,
25
+ isPropertyAssignment,
26
+ isStringLiteral,
27
+ isVariableDeclaration
28
+ } from "typescript/ast";
29
+ function walk(node, visit) {
30
+ visit(node);
31
+ node.forEachChild((child) => walk(child, visit));
32
+ }
33
+ var STYLE_MEMBERS = ["style", "cssText", "setProperty", "insertRule", "adoptedStyleSheets", "createElement"];
34
+ var DESIGN_PROPS = ["style", "className", "css", "dangerouslySetInnerHTML"];
35
+ var authorsDesign = (specifier) => specifier.startsWith("@reqvire-org/ads/") && specifier !== "@reqvire-org/ads/showcase";
36
+ var METADATA_ELEMENTS = new Set(["title", "meta", "script", "link"]);
37
+ function designSystemImports(source, publicEntry) {
38
+ const names = new Map;
39
+ const namespaces = new Set;
40
+ for (const statement of source.statements) {
41
+ if (!isImportDeclaration(statement) || !isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== publicEntry)
42
+ continue;
43
+ const clause = statement.importClause;
44
+ if (clause === undefined || clause.phaseModifier === SyntaxKind.TypeKeyword)
45
+ continue;
46
+ const bindings = clause.namedBindings;
47
+ if (bindings !== undefined && isNamespaceImport(bindings))
48
+ namespaces.add(bindings.name.text);
49
+ else if (bindings !== undefined && isNamedImports(bindings)) {
50
+ for (const element of bindings.elements)
51
+ if (!element.isTypeOnly)
52
+ names.set(element.name.text, (element.propertyName ?? element.name).getText());
53
+ }
54
+ }
55
+ return { names, namespaces };
56
+ }
57
+ var tagOf = (node) => isJsxElement(node) ? node.openingElement.tagName : isJsxOpeningElement(node) || isJsxSelfClosingElement(node) ? node.tagName : undefined;
58
+ function inScreenFunction(node) {
59
+ for (let current = node.parent;current !== undefined; current = current.parent) {
60
+ if (isFunctionDeclaration(current))
61
+ return current.name !== undefined && /^[A-Z]/.test(current.name.text);
62
+ if (isArrowFunction(current) || isFunctionExpression(current)) {
63
+ const holder = current.parent;
64
+ if (isVariableDeclaration(holder) && isIdentifier(holder.name))
65
+ return /^[A-Z]/.test(holder.name.text);
66
+ return isPropertyAssignment(holder) && holder.name.getText() === "render";
67
+ }
68
+ if (isMethodDeclaration(current))
69
+ return current.name.getText() === "render";
70
+ }
71
+ return false;
72
+ }
73
+ function allowedImports(source, components) {
74
+ const allowed = new Set;
75
+ for (const statement of source.statements) {
76
+ if (!isImportDeclaration(statement) || !isStringLiteral(statement.moduleSpecifier))
77
+ continue;
78
+ const names = components.get(statement.moduleSpecifier.text);
79
+ const clause = statement.importClause;
80
+ if (names === undefined || clause === undefined || clause.phaseModifier === SyntaxKind.TypeKeyword)
81
+ continue;
82
+ if (clause.name !== undefined && names.has("default"))
83
+ allowed.add(clause.name.text);
84
+ const bindings = clause.namedBindings;
85
+ if (bindings !== undefined && isNamedImports(bindings)) {
86
+ for (const element of bindings.elements)
87
+ if (!element.isTypeOnly && names.has((element.propertyName ?? element.name).getText()))
88
+ allowed.add(element.name.text);
89
+ }
90
+ }
91
+ return allowed;
92
+ }
93
+ function isMetadata(node) {
94
+ if (!isJsxOpeningElement(node) && !isJsxSelfClosingElement(node))
95
+ return false;
96
+ if (!isIdentifier(node.tagName) || !METADATA_ELEMENTS.has(node.tagName.text))
97
+ return false;
98
+ if (node.tagName.text !== "link")
99
+ return true;
100
+ return !node.attributes.properties.some((attribute) => isJsxAttribute(attribute) && attribute.name.getText() === "rel" && attribute.initializer !== undefined && /stylesheet/.test(attribute.initializer.getText()));
101
+ }
102
+ function designUsageProblems(source, { publicEntry, patterns }, allowance = {}) {
103
+ const problems = [];
104
+ const { names, namespaces } = designSystemImports(source, publicEntry);
105
+ const allowed = allowedImports(source, allowance.components ?? new Map);
106
+ const isAllowed = (node) => isIdentifier(node) && allowed.has(node.text) || allowance.metadata === true && isMetadata(node.parent);
107
+ const exportedName = (tag) => isIdentifier(tag) ? names.get(tag.text) : isPropertyAccessExpression(tag) && isIdentifier(tag.expression) && namespaces.has(tag.expression.text) ? tag.name.text : undefined;
108
+ const fromDesignSystem = (tag) => exportedName(tag) !== undefined;
109
+ const isPattern = (tag) => tag !== undefined && patterns.has(exportedName(tag) ?? "");
110
+ const insidePattern = (node) => {
111
+ for (let current = node.parent;current !== undefined; current = current.parent) {
112
+ if (isJsxElement(current) && current.openingElement === node)
113
+ continue;
114
+ if (isPattern(tagOf(current)))
115
+ return true;
116
+ }
117
+ return false;
118
+ };
119
+ for (const statement of source.statements)
120
+ if (isImportDeclaration(statement) && isStringLiteral(statement.moduleSpecifier) && statement.importClause?.phaseModifier !== SyntaxKind.TypeKeyword && authorsDesign(statement.moduleSpecifier.text))
121
+ problems.push({ node: statement.moduleSpecifier, problem: { kind: "design-import", specifier: statement.moduleSpecifier.text } });
122
+ walk(source, (node) => {
123
+ if (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) {
124
+ if (isAllowed(node.tagName)) {} else if (!fromDesignSystem(node.tagName))
125
+ problems.push({ node, problem: { kind: "local-markup", tag: node.tagName.getText() } });
126
+ else if (!isPattern(node.tagName) && !insidePattern(node) && inScreenFunction(node))
127
+ problems.push({ node, problem: { kind: "component-outside-pattern", name: exportedName(node.tagName) ?? node.tagName.getText() } });
128
+ for (const attribute of node.attributes.properties) {
129
+ if (isJsxSpreadAttribute(attribute))
130
+ problems.push({ node: attribute, problem: { kind: "spread-props" } });
131
+ else if (isJsxAttribute(attribute) && DESIGN_PROPS.includes(attribute.name.getText()))
132
+ problems.push({ node: attribute, problem: { kind: "design-prop", attribute: attribute.name.getText() } });
133
+ }
134
+ } else if (isPropertyAccessExpression(node) && STYLE_MEMBERS.includes(node.name.text))
135
+ problems.push({ node, problem: { kind: "imperative-design", member: node.name.text } });
136
+ else if (isElementAccessExpression(node) && isStringLiteral(node.argumentExpression) && STYLE_MEMBERS.includes(node.argumentExpression.text))
137
+ problems.push({ node, problem: { kind: "imperative-design", member: node.argumentExpression.text } });
138
+ else if ((isStringLiteral(node) || isNoSubstitutionTemplateLiteral(node)) && /@ads-(recipe|profile)|var\(--/.test(node.text))
139
+ problems.push({ node, problem: { kind: "hidden-definition" } });
140
+ return;
141
+ });
142
+ return problems;
143
+ }
144
+
145
+ // src/analysis/syntax.mts
146
+ import * as ast from "typescript/ast";
147
+ import {
148
+ API,
149
+ JsxEmit,
150
+ ModuleKind,
151
+ ModuleResolutionKind,
152
+ SymbolFlags,
153
+ TypeFlags,
154
+ TypeFormatFlags
155
+ } from "typescript/async";
156
+ import { serverFS } from "typescript/fs";
157
+ import { existsSync, readFileSync } from "node:fs";
158
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
159
+ import path from "node:path";
160
+
161
+ // src/analysis/context.mts
162
+ import { AsyncLocalStorage } from "node:async_hooks";
163
+ var scope = new AsyncLocalStorage;
164
+ var programFacts = new WeakMap;
165
+ function currentAnalysis() {
166
+ return scope.getStore();
167
+ }
168
+
169
+ // src/analysis/syntax.mts
170
+ var resolutionScope = new AsyncLocalStorage2;
171
+ var MAX_RETAINED_SOURCES = 64;
172
+ var IDLE_MILLISECONDS = 1000;
173
+ var api;
174
+ var sequence = 0;
175
+ var pending = 0;
176
+ var idle;
177
+ var overlays = new Map;
178
+ var sources = new Map;
179
+ function client() {
180
+ clearTimeout(idle);
181
+ return api ??= new API({
182
+ cwd: process.cwd(),
183
+ runExternalCode: false,
184
+ fs: {
185
+ readFile: (file) => overlays.get(file) ?? serverFS.useOS,
186
+ fileExists: (file) => overlays.has(file) ? true : serverFS.useOS,
187
+ directoryExists: serverFS.useOS,
188
+ getAccessibleEntries: serverFS.useOS,
189
+ realpath: serverFS.useOS,
190
+ stat: serverFS.useOS,
191
+ writeFile: serverFS.error,
192
+ removeFile: serverFS.error
193
+ }
194
+ });
195
+ }
196
+ async function use(run) {
197
+ const current = client();
198
+ pending++;
199
+ try {
200
+ return await run(current);
201
+ } finally {
202
+ if (--pending === 0) {
203
+ idle = setTimeout(() => {
204
+ closeSyntax();
205
+ }, IDLE_MILLISECONDS);
206
+ idle.unref();
207
+ }
208
+ }
209
+ }
210
+ var closing = Promise.resolve();
211
+ function closeSyntax() {
212
+ clearTimeout(idle);
213
+ const current = api;
214
+ if (pending || !current)
215
+ return closing;
216
+ api = undefined;
217
+ const leases = [...sources.values()];
218
+ sources.clear();
219
+ closing = closing.catch(() => {}).then(async () => {
220
+ try {
221
+ for (const lease of leases)
222
+ await (await lease).dispose();
223
+ } finally {
224
+ await current.close();
225
+ }
226
+ });
227
+ return closing;
228
+ }
229
+ async function parseSource(file, text, scriptKind) {
230
+ const resolved = path.resolve(file);
231
+ const context = currentAnalysis();
232
+ if (context?.provideSource && context.readText?.(resolved) === text) {
233
+ const provided = await context.provideSource(resolved);
234
+ if (provided)
235
+ return provided;
236
+ }
237
+ return use(async (current) => {
238
+ const key = JSON.stringify([resolved, text, scriptKind]);
239
+ let lease = sources.get(key);
240
+ if (!lease) {
241
+ const created = current.createSourceFile(resolved, text, scriptKind === undefined ? {} : { scriptKind });
242
+ created.catch(() => {
243
+ if (sources.get(key) === created)
244
+ sources.delete(key);
245
+ });
246
+ lease = created;
247
+ }
248
+ sources.delete(key);
249
+ sources.set(key, lease);
250
+ for (const [oldest, previous] of sources) {
251
+ if (sources.size <= MAX_RETAINED_SOURCES)
252
+ break;
253
+ sources.delete(oldest);
254
+ await (await previous).dispose();
255
+ }
256
+ return (await lease).sourceFile;
257
+ });
258
+ }
259
+ function parseConfigText(file, text) {
260
+ return use(async (current) => {
261
+ const virtual = path.resolve(path.dirname(file), `.ads-config-${++sequence}.json`);
262
+ overlays.set(virtual, text);
263
+ try {
264
+ return await current.readConfigFile(virtual);
265
+ } finally {
266
+ overlays.delete(virtual);
267
+ }
268
+ });
269
+ }
270
+ var readConfig = (file) => use((current) => current.readConfigFile(path.resolve(file)));
271
+ var parseConfig = (config, directory) => use((current) => current.parseJsonConfigFileContent(config, { configDirectory: path.resolve(directory) }));
272
+ function findConfigFile(directory, exists = existsSync, name = "tsconfig.json") {
273
+ for (let current = path.resolve(directory);; ) {
274
+ const file = path.join(current, name);
275
+ if (exists(file))
276
+ return file;
277
+ const parent = path.dirname(current);
278
+ if (parent === current)
279
+ return;
280
+ current = parent;
281
+ }
282
+ }
283
+ var flattenDiagnosticMessageText = (message, separator = `
284
+ `) => typeof message === "string" || message === undefined ? message ?? "" : [
285
+ typeof message.messageText === "string" ? message.messageText : message.text ?? flattenDiagnosticMessageText(message.messageText, separator),
286
+ ...(message.next ?? message.messageChain ?? []).map((item) => flattenDiagnosticMessageText(item, separator))
287
+ ].join(separator);
288
+ var sys = {
289
+ fileExists: (file) => existsSync(file),
290
+ readFile: (file) => {
291
+ try {
292
+ return readFileSync(file, "utf8");
293
+ } catch {
294
+ return;
295
+ }
296
+ }
297
+ };
298
+ var isIterationStatement = (node) => ast.isForStatement(node) || ast.isForInStatement(node) || ast.isForOfStatement(node) || ast.isWhileStatement(node) || ast.isDoStatement(node);
299
+ var ts = {
300
+ ...ast,
301
+ ModuleKind,
302
+ ModuleResolutionKind,
303
+ JsxEmit,
304
+ SymbolFlags,
305
+ TypeFlags,
306
+ TypeFormatFlags,
307
+ isStringLiteralLike: ast.isStringLiteralLikeNode,
308
+ isFunctionLike: ast.isFunctionLikeDeclaration,
309
+ isPropertySignature: ast.isPropertySignatureDeclaration,
310
+ isParameter: ast.isParameterDeclaration,
311
+ isIterationStatement,
312
+ forEachChild: (node, visit) => node.forEachChild(visit),
313
+ createSourceFile: (file, text, _target, _parents, scriptKind) => parseSource(file, text, scriptKind),
314
+ readConfigFile: readConfig,
315
+ parseJsonConfigFileContent: (config, _host, directory) => parseConfig(config, directory),
316
+ parseConfigFileTextToJson: parseConfigText,
317
+ resolveProjectReferencePath: (reference) => reference.path.endsWith(".json") ? reference.path : path.join(reference.path, "tsconfig.json"),
318
+ flattenDiagnosticMessageText,
319
+ findConfigFile,
320
+ sys
321
+ };
322
+
323
+ // src/design-usage.mts
324
+ var wording = {
325
+ "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."],
326
+ "component-outside-pattern": (problem) => [
327
+ `The component ${problem.name} is rendered outside every pattern, so nothing owns its place on the screen.`,
328
+ "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
+ ],
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."],
331
+ "spread-props": () => ["A spread passes props nothing can see.", "Pass each prop explicitly."],
332
+ "design-prop": (problem) => [`${problem.attribute} supplies design from outside the design system.`, "Remove it; choose the treatment through the owner's own props."],
333
+ "imperative-design": (problem) => [`${problem.member} writes styles or creates DOM by hand.`, "Remove the write; render design-system owners with props."],
334
+ "hidden-definition": () => ["A string carries a recipe, profile or custom-property reference.", "Remove it; design belongs in the design system's owners, profiles and token sheets."]
335
+ };
336
+ var describe = (problem) => {
337
+ const kind = problem.kind;
338
+ return wording[kind](problem);
339
+ };
340
+ async function checkDesignUsage2(sources, entry, allowance = {}) {
341
+ const findings = [];
342
+ for (const { file, text } of sources) {
343
+ const source = await parseSource(path2.resolve(file), text);
344
+ for (const { node, problem } of designUsageProblems(source, entry, allowance)) {
345
+ const at = source.getLineAndCharacterOfPosition(node.getStart(source));
346
+ const [message, repair] = describe(problem);
347
+ findings.push({ file, line: at.line + 1, column: at.character + 1, code: `design-usage/${problem.kind}`, message, repair });
348
+ }
349
+ }
350
+ return findings;
351
+ }
352
+ async function designSystemEntry2(publicEntry, entryFile) {
353
+ const source = await parseSource(path2.resolve(entryFile), readFileSync2(entryFile, "utf8"));
354
+ const patterns = new Set;
355
+ for (const statement of source.statements) {
356
+ if (!isExportDeclaration(statement) || statement.isTypeOnly || statement.moduleSpecifier === undefined || !isStringLiteral2(statement.moduleSpecifier))
357
+ continue;
358
+ if (!statement.moduleSpecifier.text.startsWith("./patterns/"))
359
+ continue;
360
+ const clause = statement.exportClause;
361
+ if (clause !== undefined && isNamedExports(clause)) {
362
+ for (const element of clause.elements)
363
+ if (!element.isTypeOnly)
364
+ patterns.add(element.name.text);
365
+ }
366
+ }
367
+ return { publicEntry, patterns };
368
+ }
369
+ var closeDesignUsage2 = () => closeSyntax();
370
+
371
+ // src/guard/config.mts
372
+ import { existsSync as existsSync2, readFileSync as readFileSync3, statSync } from "node:fs";
373
+ import path3 from "node:path";
374
+
375
+ // src/result.mts
376
+ var ok = (value) => ({ kind: "ok", value });
377
+ var err = (error) => ({ kind: "err", error });
378
+
379
+ // src/unknown.mts
380
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Map);
381
+
382
+ // src/guard/config.mts
383
+ var GUARD_CONFIG_FILE2 = "ads-guard.config.json";
384
+ var FIELDS = ["designSystem", "entry", "include", "exclude", "allow"];
385
+ var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "");
386
+ var insideRoot = (root, relative) => {
387
+ const resolved = path3.resolve(root, relative);
388
+ return !/[*?[\]{}]/.test(relative) && (resolved === root || resolved.startsWith(root + path3.sep));
389
+ };
390
+ function readGuardConfig2(root) {
391
+ const file = path3.join(root, GUARD_CONFIG_FILE2);
392
+ if (!existsSync2(file))
393
+ return err([`${GUARD_CONFIG_FILE2} is missing in ${root}. Create it with "designSystem" and "include".`]);
394
+ let value;
395
+ try {
396
+ value = JSON.parse(readFileSync3(file, "utf8"));
397
+ } catch (error) {
398
+ return err([`${GUARD_CONFIG_FILE2} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]);
399
+ }
400
+ if (!isRecord(value))
401
+ return err([`${GUARD_CONFIG_FILE2} is a JSON object.`]);
402
+ const problems = [];
403
+ for (const key of Object.keys(value))
404
+ if (!FIELDS.includes(key))
405
+ problems.push(`"${key}" is not a field. The fields are ${FIELDS.join(", ")}.`);
406
+ const { designSystem, entry, include, exclude = [], allow = {} } = value;
407
+ if (typeof designSystem !== "string" || designSystem.trim() === "")
408
+ 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))))
410
+ problems.push(`"entry" is the path of the design system's public entry file, relative to this file. It does not exist.`);
411
+ if (!isStrings(include) || include.length === 0)
412
+ problems.push(`"include" lists the folders with the application's sources, such as ["src"].`);
413
+ else
414
+ for (const folder of include)
415
+ if (!insideRoot(root, folder) || !existsSync2(path3.resolve(root, folder)) || !statSync(path3.resolve(root, folder)).isDirectory())
416
+ problems.push(`"include" names ${folder}, which is not a folder under this file. Wildcards are not supported.`);
417
+ if (!isStrings(exclude))
418
+ problems.push('"exclude" lists folders and files, such as ["src/generated"].');
419
+ else if (isStrings(include))
420
+ 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));
423
+ if (!insideRoot(root, item) || !existsSync2(resolved))
424
+ problems.push(`"exclude" names ${item}, which does not exist. Remove it. Wildcards are not supported.`);
425
+ else if (!within)
426
+ problems.push(`"exclude" names ${item}, which is not under any "include" folder. Remove it.`);
427
+ }
428
+ const allowed = new Map;
429
+ if (!isRecord(allow))
430
+ problems.push('"allow" maps a package to the components it may render, such as { "react": ["Suspense"] }.');
431
+ else
432
+ for (const [specifier, names] of Object.entries(allow)) {
433
+ if (!isStrings(names) || names.length === 0)
434
+ problems.push(`"allow" lists the components of ${specifier} by name, such as ["Outlet"]. Use "default" for a default export.`);
435
+ else if (typeof designSystem === "string" && specifier === designSystem)
436
+ problems.push(`"allow" names the design system itself (${specifier}). Everything it exports is already allowed.`);
437
+ else
438
+ allowed.set(specifier, new Set(names));
439
+ }
440
+ if (problems.length > 0)
441
+ return err(problems);
442
+ return ok({
443
+ designSystem: String(designSystem),
444
+ ...typeof entry === "string" ? { entry } : {},
445
+ include: isStrings(include) ? include : [],
446
+ exclude: isStrings(exclude) ? exclude : [],
447
+ allow: allowed
448
+ });
449
+ }
450
+
451
+ // src/guard/run.mts
452
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
453
+ import { createRequire } from "node:module";
454
+ import path5 from "node:path";
455
+
456
+ // src/guard/files.mts
457
+ import { readdirSync, statSync as statSync2 } from "node:fs";
458
+ import path4 from "node:path";
459
+ var SOURCE = /\.[cm]?[jt]sx$/;
460
+ var TEST = /(?:\.(?:test|spec)\.[cm]?[jt]sx?$)|(?:^|\/)(?:__tests__|__mocks__)\//;
461
+ var SKIPPED_FOLDERS = new Set(["node_modules"]);
462
+ function walk2(folder, visit) {
463
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
464
+ if (entry.name.startsWith(".") || SKIPPED_FOLDERS.has(entry.name))
465
+ continue;
466
+ const file = path4.join(folder, entry.name);
467
+ if (entry.isDirectory())
468
+ walk2(file, visit);
469
+ else if (entry.isFile() && SOURCE.test(entry.name))
470
+ visit(file);
471
+ }
472
+ }
473
+ 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));
476
+ const excluded = new Map(exclude.map((item) => [item, 0]));
477
+ const files = new Set;
478
+ let tests = 0, designSystem = 0;
479
+ 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);
482
+ const name = exclude[index];
483
+ if (name !== undefined)
484
+ excluded.set(name, (excluded.get(name) ?? 0) + 1);
485
+ else if (designSystemFolder !== null && file.startsWith(designSystemFolder + path4.sep))
486
+ designSystem++;
487
+ else if (TEST.test(relative(file)))
488
+ tests++;
489
+ else
490
+ files.add(relative(file));
491
+ });
492
+ return { files: [...files].sort(), excluded: [...excluded].map(([name, count]) => ({ path: name, files: count })), tests, designSystem };
493
+ }
494
+
495
+ // src/guard/run.mts
496
+ var ENTRY_NAMES = ["index.ts", "index.tsx", "index.mts", "index.js", "index.mjs"];
497
+ function entryFile(root, config) {
498
+ if (config.entry !== undefined) {
499
+ const configured = path5.resolve(root, config.entry);
500
+ return ok(configured);
501
+ }
502
+ const specifier = config.designSystem;
503
+ if (specifier.startsWith(".")) {
504
+ const target = path5.resolve(root, specifier);
505
+ const found = [target, ...ENTRY_NAMES.map((name) => path5.join(target, name))].find((candidate) => existsSync3(candidate) && /\.[cm]?[jt]sx?$/.test(candidate));
506
+ return found === undefined ? err(`"designSystem" is ${specifier}, and no entry file is at ${target}.`) : ok(found);
507
+ }
508
+ try {
509
+ return ok(createRequire(path5.join(root, "package.json")).resolve(specifier));
510
+ } catch {
511
+ 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.`);
512
+ }
513
+ }
514
+ async function runGuard2(root) {
515
+ const absolute = path5.resolve(root);
516
+ const config = readGuardConfig2(absolute);
517
+ if (config.kind === "err")
518
+ return config;
519
+ const located = entryFile(absolute, config.value);
520
+ if (located.kind === "err")
521
+ return err([located.error]);
522
+ const entry = await designSystemEntry2(config.value.designSystem, located.value);
523
+ const folder = path5.dirname(located.value);
524
+ const scope = guardScope(absolute, config.value.include, config.value.exclude, folder.startsWith(absolute + path5.sep) ? folder : null);
525
+ const sources = scope.files.map((file) => ({ file, text: readFileSync4(path5.join(absolute, file), "utf8") }));
526
+ const findings = await checkDesignUsage2(sources, entry, { components: config.value.allow, metadata: true });
527
+ const inside = located.value.startsWith(absolute + path5.sep);
528
+ return ok({
529
+ ok: findings.length === 0,
530
+ designSystem: config.value.designSystem,
531
+ entry: inside ? path5.relative(absolute, located.value).split(path5.sep).join("/") : located.value,
532
+ patterns: entry.patterns.size,
533
+ checked: scope.files.length,
534
+ scope: { excluded: scope.excluded, tests: scope.tests, designSystem: scope.designSystem },
535
+ findings
536
+ });
537
+ }
538
+ function guardText2(report) {
539
+ const lines = report.findings.map((finding) => `${finding.file}:${finding.line}:${finding.column} ${finding.code}
540
+ ${finding.message}
541
+ ${finding.repair}`);
542
+ const left = [];
543
+ const excludedFiles = report.scope.excluded.reduce((sum, item) => sum + item.files, 0);
544
+ if (report.scope.excluded.length > 0)
545
+ left.push(`excluded ${report.scope.excluded.length} path${report.scope.excluded.length === 1 ? "" : "s"} (${excludedFiles} file${excludedFiles === 1 ? "" : "s"}): ${report.scope.excluded.map((item) => item.path).join(", ")}`);
546
+ if (report.scope.tests > 0)
547
+ left.push(`${report.scope.tests} test file${report.scope.tests === 1 ? "" : "s"}`);
548
+ if (report.scope.designSystem > 0)
549
+ left.push(`${report.scope.designSystem} file${report.scope.designSystem === 1 ? "" : "s"} of the design system`);
550
+ const summary = `Checked ${report.checked} file${report.checked === 1 ? "" : "s"} against ${report.designSystem} (${report.patterns} pattern${report.patterns === 1 ? "" : "s"})${left.length ? `; not checked: ${left.join("; ")}` : ""}.`;
551
+ const verdict = report.ok ? "The source uses the design system only." : `${report.findings.length} finding${report.findings.length === 1 ? "" : "s"}.`;
552
+ return [...lines, summary, verdict].join(`
553
+ `);
554
+ }
555
+
556
+ export { checkDesignUsage2, designSystemEntry2, closeDesignUsage2, GUARD_CONFIG_FILE2, readGuardConfig2, runGuard2, guardText2 };
package/dist/cli.mjs ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ closeDesignUsage2,
4
+ GUARD_CONFIG_FILE2,
5
+ runGuard2,
6
+ guardText2
7
+ } from "./chunk-mfayhtn4.mjs";
8
+
9
+ // src/guard/cli.mts
10
+ var HELP = `ads-guard [directory] [--json]
11
+
12
+ Confirms that the source of an application does no design of its own and uses its ADS design
13
+ system only: it renders what the design system exports, a pattern arranges each screen, and it
14
+ writes no markup, styling or design definition.
15
+
16
+ directory The folder that holds ${GUARD_CONFIG_FILE2} (default: the current folder)
17
+ --json Print the report as JSON
18
+
19
+ ${GUARD_CONFIG_FILE2}:
20
+ { "designSystem": "@acme/design", "include": ["src"], "exclude": [], "allow": { "react": ["Suspense"] } }
21
+ `;
22
+ async function main(argv) {
23
+ const flags = argv.filter((item) => item.startsWith("-"));
24
+ const positional = argv.filter((item) => !item.startsWith("-"));
25
+ if (flags.includes("--help") || flags.includes("-h")) {
26
+ process.stdout.write(HELP);
27
+ return 0;
28
+ }
29
+ const unknown = flags.find((flag) => flag !== "--json");
30
+ if (unknown !== undefined || positional.length > 1) {
31
+ process.stderr.write(`${unknown !== undefined ? `Unknown option ${unknown}.` : "Name one directory."}
32
+
33
+ ${HELP}`);
34
+ return 2;
35
+ }
36
+ const result = await runGuard2(positional[0] ?? ".");
37
+ if (result.kind === "err") {
38
+ process.stderr.write(`${result.error.join(`
39
+ `)}
40
+ `);
41
+ return 2;
42
+ }
43
+ process.stdout.write(flags.includes("--json") ? `${JSON.stringify(result.value, null, 2)}
44
+ ` : `${guardText2(result.value)}
45
+ `);
46
+ return result.value.ok ? 0 : 1;
47
+ }
48
+ var code = 2;
49
+ try {
50
+ code = await main(process.argv.slice(2));
51
+ } catch (error) {
52
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
53
+ `);
54
+ } finally {
55
+ await closeDesignUsage2();
56
+ }
57
+ process.exitCode = code;
package/dist/index.mjs ADDED
@@ -0,0 +1,18 @@
1
+ import {
2
+ checkDesignUsage2,
3
+ designSystemEntry2,
4
+ closeDesignUsage2,
5
+ GUARD_CONFIG_FILE2,
6
+ readGuardConfig2,
7
+ runGuard2,
8
+ guardText2
9
+ } from "./chunk-mfayhtn4.mjs";
10
+ export {
11
+ GUARD_CONFIG_FILE2 as GUARD_CONFIG_FILE,
12
+ checkDesignUsage2 as checkDesignUsage,
13
+ closeDesignUsage2 as closeDesignUsage,
14
+ designSystemEntry2 as designSystemEntry,
15
+ guardText2 as guardText,
16
+ readGuardConfig2 as readGuardConfig,
17
+ runGuard2 as runGuard
18
+ };
@@ -0,0 +1,12 @@
1
+ /** The compiler options this translation reads; every other option passes through unchanged. */
2
+ export interface PathMappedOptions {
3
+ readonly baseUrl?: string | undefined;
4
+ readonly paths?: Readonly<Record<string, readonly string[]>> | undefined;
5
+ }
6
+ /** Translate a consuming project's baseUrl into native compiler path mappings.
7
+ * TypeScript 7 no longer resolves imports through baseUrl; applications may
8
+ * still build with their own earlier compiler and retain that configuration. */
9
+ export declare function nativeCompilerOptions<T extends PathMappedOptions>(options: T, root: string): T | (Omit<T, "baseUrl"> & {
10
+ paths: Record<string, string[]>;
11
+ pathsBasePath: string;
12
+ });