@reqvire-org/ads-guard 0.0.0 → 0.5.1
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/LICENSE +21 -0
- package/README.md +145 -4
- package/dist/chunk-qm6jh9dj.mjs +642 -0
- package/dist/cli.mjs +57 -0
- package/dist/index.mjs +18 -0
- package/dist/types/analysis/compiler-options.d.mts +12 -0
- package/dist/types/analysis/context.d.mts +46 -0
- package/dist/types/analysis/design-usage.d.mts +72 -0
- package/dist/types/analysis/module-resolvers.d.mts +12 -0
- package/dist/types/analysis/semantic.d.mts +87 -0
- package/dist/types/analysis/syntax.d.mts +498 -0
- package/dist/types/design-usage.d.mts +33 -0
- package/dist/types/guard/config.d.mts +20 -0
- package/dist/types/guard/files.d.mts +16 -0
- package/dist/types/guard/index.d.mts +6 -0
- package/dist/types/guard/run.d.mts +20 -0
- package/dist/types/prose-model.d.mts +81 -0
- package/dist/types/result.d.mts +34 -0
- package/dist/types/unknown.d.mts +9 -0
- package/package.json +30 -4
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
// src/design-usage.mts
|
|
2
|
+
import { existsSync as existsSync2, 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
|
+
|
|
30
|
+
// src/prose-model.mts
|
|
31
|
+
var PROSE_ELEMENTS = {
|
|
32
|
+
paragraph: ["p"],
|
|
33
|
+
heading1: ["h1"],
|
|
34
|
+
heading2: ["h2"],
|
|
35
|
+
heading3: ["h3"],
|
|
36
|
+
heading4: ["h4"],
|
|
37
|
+
heading5: ["h5"],
|
|
38
|
+
heading6: ["h6"],
|
|
39
|
+
list: ["ul", "ol"],
|
|
40
|
+
item: ["li"],
|
|
41
|
+
quote: ["blockquote"],
|
|
42
|
+
rule: ["hr"],
|
|
43
|
+
pre: ["pre"],
|
|
44
|
+
table: ["table"],
|
|
45
|
+
headerCell: ["th"],
|
|
46
|
+
cell: ["td"],
|
|
47
|
+
figure: ["figure"],
|
|
48
|
+
caption: ["figcaption"],
|
|
49
|
+
media: ["img", "video", "iframe"],
|
|
50
|
+
descriptions: ["dl"],
|
|
51
|
+
term: ["dt"],
|
|
52
|
+
definition: ["dd"],
|
|
53
|
+
link: ["a"],
|
|
54
|
+
strong: ["strong", "b"],
|
|
55
|
+
emphasis: ["em", "i"],
|
|
56
|
+
deleted: ["del", "s"],
|
|
57
|
+
code: ["code"],
|
|
58
|
+
sub: ["sub"],
|
|
59
|
+
sup: ["sup"],
|
|
60
|
+
kbd: ["kbd"],
|
|
61
|
+
mark: ["mark"]
|
|
62
|
+
};
|
|
63
|
+
var PROSE_ELEMENT_NAMES = Object.keys(PROSE_ELEMENTS);
|
|
64
|
+
var PROSE_TAGS = new Map(PROSE_ELEMENT_NAMES.flatMap((name) => PROSE_ELEMENTS[name].map((tag) => [tag, name])));
|
|
65
|
+
var PROSE_STRUCTURE = new Map([
|
|
66
|
+
["thead", "table"],
|
|
67
|
+
["tbody", "table"],
|
|
68
|
+
["tfoot", "table"],
|
|
69
|
+
["tr", "table"],
|
|
70
|
+
["br", null]
|
|
71
|
+
]);
|
|
72
|
+
var isProseTag = (tag) => PROSE_TAGS.has(tag) || PROSE_STRUCTURE.has(tag);
|
|
73
|
+
var PROSE_MANIFEST = "ads-prose.json";
|
|
74
|
+
function parseProseManifest(text) {
|
|
75
|
+
const owners = new Map;
|
|
76
|
+
let value;
|
|
77
|
+
try {
|
|
78
|
+
value = JSON.parse(text);
|
|
79
|
+
} catch {
|
|
80
|
+
return owners;
|
|
81
|
+
}
|
|
82
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
83
|
+
return owners;
|
|
84
|
+
for (const [name, tags] of Object.entries(value))
|
|
85
|
+
if (Array.isArray(tags))
|
|
86
|
+
owners.set(name, new Set(tags.filter((tag) => typeof tag === "string" && isProseTag(tag))));
|
|
87
|
+
return owners;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/analysis/design-usage.mts
|
|
91
|
+
function walk(node, visit) {
|
|
92
|
+
visit(node);
|
|
93
|
+
node.forEachChild((child) => walk(child, visit));
|
|
94
|
+
}
|
|
95
|
+
var STYLE_MEMBERS = ["style", "cssText", "setProperty", "insertRule", "adoptedStyleSheets", "createElement"];
|
|
96
|
+
var DESIGN_PROPS = ["style", "className", "css", "dangerouslySetInnerHTML"];
|
|
97
|
+
var authorsDesign = (specifier) => specifier.startsWith("@reqvire-org/ads/") && specifier !== "@reqvire-org/ads/showcase";
|
|
98
|
+
var METADATA_ELEMENTS = new Set(["title", "meta", "script", "link"]);
|
|
99
|
+
function designSystemImports(source, publicEntry) {
|
|
100
|
+
const names = new Map;
|
|
101
|
+
const namespaces = new Set;
|
|
102
|
+
for (const statement of source.statements) {
|
|
103
|
+
if (!isImportDeclaration(statement) || !isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== publicEntry)
|
|
104
|
+
continue;
|
|
105
|
+
const clause = statement.importClause;
|
|
106
|
+
if (clause === undefined || clause.phaseModifier === SyntaxKind.TypeKeyword)
|
|
107
|
+
continue;
|
|
108
|
+
const bindings = clause.namedBindings;
|
|
109
|
+
if (bindings !== undefined && isNamespaceImport(bindings))
|
|
110
|
+
namespaces.add(bindings.name.text);
|
|
111
|
+
else if (bindings !== undefined && isNamedImports(bindings)) {
|
|
112
|
+
for (const element of bindings.elements)
|
|
113
|
+
if (!element.isTypeOnly)
|
|
114
|
+
names.set(element.name.text, (element.propertyName ?? element.name).getText());
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { names, namespaces };
|
|
118
|
+
}
|
|
119
|
+
var tagOf = (node) => isJsxElement(node) ? node.openingElement.tagName : isJsxOpeningElement(node) || isJsxSelfClosingElement(node) ? node.tagName : undefined;
|
|
120
|
+
function inScreenFunction(node) {
|
|
121
|
+
for (let current = node.parent;current !== undefined; current = current.parent) {
|
|
122
|
+
if (isFunctionDeclaration(current))
|
|
123
|
+
return current.name !== undefined && /^[A-Z]/.test(current.name.text);
|
|
124
|
+
if (isArrowFunction(current) || isFunctionExpression(current)) {
|
|
125
|
+
const holder = current.parent;
|
|
126
|
+
if (isVariableDeclaration(holder) && isIdentifier(holder.name))
|
|
127
|
+
return /^[A-Z]/.test(holder.name.text);
|
|
128
|
+
return isPropertyAssignment(holder) && holder.name.getText() === "render";
|
|
129
|
+
}
|
|
130
|
+
if (isMethodDeclaration(current))
|
|
131
|
+
return current.name.getText() === "render";
|
|
132
|
+
}
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
function allowedImports(source, components) {
|
|
136
|
+
const allowed = new Set;
|
|
137
|
+
for (const statement of source.statements) {
|
|
138
|
+
if (!isImportDeclaration(statement) || !isStringLiteral(statement.moduleSpecifier))
|
|
139
|
+
continue;
|
|
140
|
+
const names = components.get(statement.moduleSpecifier.text);
|
|
141
|
+
const clause = statement.importClause;
|
|
142
|
+
if (names === undefined || clause === undefined || clause.phaseModifier === SyntaxKind.TypeKeyword)
|
|
143
|
+
continue;
|
|
144
|
+
if (clause.name !== undefined && names.has("default"))
|
|
145
|
+
allowed.add(clause.name.text);
|
|
146
|
+
const bindings = clause.namedBindings;
|
|
147
|
+
if (bindings !== undefined && isNamedImports(bindings)) {
|
|
148
|
+
for (const element of bindings.elements)
|
|
149
|
+
if (!element.isTypeOnly && names.has((element.propertyName ?? element.name).getText()))
|
|
150
|
+
allowed.add(element.name.text);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return allowed;
|
|
154
|
+
}
|
|
155
|
+
function isMetadata(node) {
|
|
156
|
+
if (!isJsxOpeningElement(node) && !isJsxSelfClosingElement(node))
|
|
157
|
+
return false;
|
|
158
|
+
if (!isIdentifier(node.tagName) || !METADATA_ELEMENTS.has(node.tagName.text))
|
|
159
|
+
return false;
|
|
160
|
+
if (node.tagName.text !== "link")
|
|
161
|
+
return true;
|
|
162
|
+
return !node.attributes.properties.some((attribute) => isJsxAttribute(attribute) && attribute.name.getText() === "rel" && attribute.initializer !== undefined && /stylesheet/.test(attribute.initializer.getText()));
|
|
163
|
+
}
|
|
164
|
+
function designUsageProblems(source, { publicEntry, patterns, prose = new Map }, allowance = {}) {
|
|
165
|
+
const problems = [];
|
|
166
|
+
const { names, namespaces } = designSystemImports(source, publicEntry);
|
|
167
|
+
const allowed = allowedImports(source, allowance.components ?? new Map);
|
|
168
|
+
const isAllowed = (node) => isIdentifier(node) && allowed.has(node.text) || allowance.metadata === true && isMetadata(node.parent);
|
|
169
|
+
const exportedName = (tag) => isIdentifier(tag) ? names.get(tag.text) : isPropertyAccessExpression(tag) && isIdentifier(tag.expression) && namespaces.has(tag.expression.text) ? tag.name.text : undefined;
|
|
170
|
+
const fromDesignSystem = (tag) => exportedName(tag) !== undefined;
|
|
171
|
+
const isPattern = (tag) => tag !== undefined && patterns.has(exportedName(tag) ?? "");
|
|
172
|
+
const insidePattern = (node) => {
|
|
173
|
+
for (let current = node.parent;current !== undefined; current = current.parent) {
|
|
174
|
+
if (isJsxElement(current) && current.openingElement === node)
|
|
175
|
+
continue;
|
|
176
|
+
if (isPattern(tagOf(current)))
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
return false;
|
|
180
|
+
};
|
|
181
|
+
const proseOwner = (node) => {
|
|
182
|
+
for (let current = node.parent;current !== undefined; current = current.parent) {
|
|
183
|
+
if (!isJsxElement(current) || current.openingElement === node)
|
|
184
|
+
continue;
|
|
185
|
+
const tag = current.openingElement.tagName;
|
|
186
|
+
if (isIdentifier(tag) && isProseTag(tag.text))
|
|
187
|
+
continue;
|
|
188
|
+
const name = exportedName(tag);
|
|
189
|
+
const tags = name === undefined ? undefined : prose.get(name);
|
|
190
|
+
return name === undefined || tags === undefined ? undefined : { name, tags };
|
|
191
|
+
}
|
|
192
|
+
return;
|
|
193
|
+
};
|
|
194
|
+
for (const statement of source.statements)
|
|
195
|
+
if (isImportDeclaration(statement) && isStringLiteral(statement.moduleSpecifier) && statement.importClause?.phaseModifier !== SyntaxKind.TypeKeyword && authorsDesign(statement.moduleSpecifier.text))
|
|
196
|
+
problems.push({ node: statement.moduleSpecifier, problem: { kind: "design-import", specifier: statement.moduleSpecifier.text } });
|
|
197
|
+
walk(source, (node) => {
|
|
198
|
+
if (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) {
|
|
199
|
+
if (isAllowed(node.tagName)) {} else if (!fromDesignSystem(node.tagName)) {
|
|
200
|
+
const tag = node.tagName.getText();
|
|
201
|
+
const owner = isIdentifier(node.tagName) && isProseTag(tag) ? proseOwner(node) : undefined;
|
|
202
|
+
if (owner === undefined)
|
|
203
|
+
problems.push({ node, problem: { kind: "local-markup", tag } });
|
|
204
|
+
else if (!owner.tags.has(tag))
|
|
205
|
+
problems.push({ node, problem: { kind: "prose-element-undeclared", tag, owner: owner.name } });
|
|
206
|
+
} else if (!isPattern(node.tagName) && !insidePattern(node) && inScreenFunction(node))
|
|
207
|
+
problems.push({ node, problem: { kind: "component-outside-pattern", name: exportedName(node.tagName) ?? node.tagName.getText() } });
|
|
208
|
+
for (const attribute of node.attributes.properties) {
|
|
209
|
+
if (isJsxSpreadAttribute(attribute))
|
|
210
|
+
problems.push({ node: attribute, problem: { kind: "spread-props" } });
|
|
211
|
+
else if (isJsxAttribute(attribute) && DESIGN_PROPS.includes(attribute.name.getText()))
|
|
212
|
+
problems.push({ node: attribute, problem: { kind: "design-prop", attribute: attribute.name.getText() } });
|
|
213
|
+
}
|
|
214
|
+
} else if (isPropertyAccessExpression(node) && STYLE_MEMBERS.includes(node.name.text))
|
|
215
|
+
problems.push({ node, problem: { kind: "imperative-design", member: node.name.text } });
|
|
216
|
+
else if (isElementAccessExpression(node) && isStringLiteral(node.argumentExpression) && STYLE_MEMBERS.includes(node.argumentExpression.text))
|
|
217
|
+
problems.push({ node, problem: { kind: "imperative-design", member: node.argumentExpression.text } });
|
|
218
|
+
else if ((isStringLiteral(node) || isNoSubstitutionTemplateLiteral(node)) && /@ads-(recipe|profile)|var\(--/.test(node.text))
|
|
219
|
+
problems.push({ node, problem: { kind: "hidden-definition" } });
|
|
220
|
+
return;
|
|
221
|
+
});
|
|
222
|
+
return problems;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// src/analysis/syntax.mts
|
|
226
|
+
import * as ast from "typescript/ast";
|
|
227
|
+
import {
|
|
228
|
+
API,
|
|
229
|
+
JsxEmit,
|
|
230
|
+
ModuleKind,
|
|
231
|
+
ModuleResolutionKind,
|
|
232
|
+
SymbolFlags,
|
|
233
|
+
TypeFlags,
|
|
234
|
+
TypeFormatFlags
|
|
235
|
+
} from "typescript/async";
|
|
236
|
+
import { serverFS } from "typescript/fs";
|
|
237
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
238
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
239
|
+
import path from "node:path";
|
|
240
|
+
|
|
241
|
+
// src/analysis/context.mts
|
|
242
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
243
|
+
var scope = new AsyncLocalStorage;
|
|
244
|
+
var programFacts = new WeakMap;
|
|
245
|
+
function currentAnalysis() {
|
|
246
|
+
return scope.getStore();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/analysis/syntax.mts
|
|
250
|
+
var resolutionScope = new AsyncLocalStorage2;
|
|
251
|
+
var MAX_RETAINED_SOURCES = 64;
|
|
252
|
+
var IDLE_MILLISECONDS = 1000;
|
|
253
|
+
var api;
|
|
254
|
+
var sequence = 0;
|
|
255
|
+
var pending = 0;
|
|
256
|
+
var idle;
|
|
257
|
+
var overlays = new Map;
|
|
258
|
+
var sources = new Map;
|
|
259
|
+
function client() {
|
|
260
|
+
clearTimeout(idle);
|
|
261
|
+
return api ??= new API({
|
|
262
|
+
cwd: process.cwd(),
|
|
263
|
+
runExternalCode: false,
|
|
264
|
+
fs: {
|
|
265
|
+
readFile: (file) => overlays.get(file) ?? serverFS.useOS,
|
|
266
|
+
fileExists: (file) => overlays.has(file) ? true : serverFS.useOS,
|
|
267
|
+
directoryExists: serverFS.useOS,
|
|
268
|
+
getAccessibleEntries: serverFS.useOS,
|
|
269
|
+
realpath: serverFS.useOS,
|
|
270
|
+
stat: serverFS.useOS,
|
|
271
|
+
writeFile: serverFS.error,
|
|
272
|
+
removeFile: serverFS.error
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
async function use(run) {
|
|
277
|
+
const current = client();
|
|
278
|
+
pending++;
|
|
279
|
+
try {
|
|
280
|
+
return await run(current);
|
|
281
|
+
} finally {
|
|
282
|
+
if (--pending === 0) {
|
|
283
|
+
idle = setTimeout(() => {
|
|
284
|
+
closeSyntax();
|
|
285
|
+
}, IDLE_MILLISECONDS);
|
|
286
|
+
idle.unref();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
var closing = Promise.resolve();
|
|
291
|
+
function closeSyntax() {
|
|
292
|
+
clearTimeout(idle);
|
|
293
|
+
const current = api;
|
|
294
|
+
if (pending || !current)
|
|
295
|
+
return closing;
|
|
296
|
+
api = undefined;
|
|
297
|
+
const leases = [...sources.values()];
|
|
298
|
+
sources.clear();
|
|
299
|
+
closing = closing.catch(() => {}).then(async () => {
|
|
300
|
+
try {
|
|
301
|
+
for (const lease of leases)
|
|
302
|
+
await (await lease).dispose();
|
|
303
|
+
} finally {
|
|
304
|
+
await current.close();
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
return closing;
|
|
308
|
+
}
|
|
309
|
+
async function parseSource(file, text, scriptKind) {
|
|
310
|
+
const resolved = path.resolve(file);
|
|
311
|
+
const context = currentAnalysis();
|
|
312
|
+
if (context?.provideSource && context.readText?.(resolved) === text) {
|
|
313
|
+
const provided = await context.provideSource(resolved);
|
|
314
|
+
if (provided)
|
|
315
|
+
return provided;
|
|
316
|
+
}
|
|
317
|
+
return use(async (current) => {
|
|
318
|
+
const key = JSON.stringify([resolved, text, scriptKind]);
|
|
319
|
+
let lease = sources.get(key);
|
|
320
|
+
if (!lease) {
|
|
321
|
+
const created = current.createSourceFile(resolved, text, scriptKind === undefined ? {} : { scriptKind });
|
|
322
|
+
created.catch(() => {
|
|
323
|
+
if (sources.get(key) === created)
|
|
324
|
+
sources.delete(key);
|
|
325
|
+
});
|
|
326
|
+
lease = created;
|
|
327
|
+
}
|
|
328
|
+
sources.delete(key);
|
|
329
|
+
sources.set(key, lease);
|
|
330
|
+
for (const [oldest, previous] of sources) {
|
|
331
|
+
if (sources.size <= MAX_RETAINED_SOURCES)
|
|
332
|
+
break;
|
|
333
|
+
sources.delete(oldest);
|
|
334
|
+
await (await previous).dispose();
|
|
335
|
+
}
|
|
336
|
+
return (await lease).sourceFile;
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
function parseConfigText(file, text) {
|
|
340
|
+
return use(async (current) => {
|
|
341
|
+
const virtual = path.resolve(path.dirname(file), `.ads-config-${++sequence}.json`);
|
|
342
|
+
overlays.set(virtual, text);
|
|
343
|
+
try {
|
|
344
|
+
return await current.readConfigFile(virtual);
|
|
345
|
+
} finally {
|
|
346
|
+
overlays.delete(virtual);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
var readConfig = (file) => use((current) => current.readConfigFile(path.resolve(file)));
|
|
351
|
+
var parseConfig = (config, directory) => use((current) => current.parseJsonConfigFileContent(config, { configDirectory: path.resolve(directory) }));
|
|
352
|
+
function findConfigFile(directory, exists = existsSync, name = "tsconfig.json") {
|
|
353
|
+
for (let current = path.resolve(directory);; ) {
|
|
354
|
+
const file = path.join(current, name);
|
|
355
|
+
if (exists(file))
|
|
356
|
+
return file;
|
|
357
|
+
const parent = path.dirname(current);
|
|
358
|
+
if (parent === current)
|
|
359
|
+
return;
|
|
360
|
+
current = parent;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
var flattenDiagnosticMessageText = (message, separator = `
|
|
364
|
+
`) => typeof message === "string" || message === undefined ? message ?? "" : [
|
|
365
|
+
typeof message.messageText === "string" ? message.messageText : message.text ?? flattenDiagnosticMessageText(message.messageText, separator),
|
|
366
|
+
...(message.next ?? message.messageChain ?? []).map((item) => flattenDiagnosticMessageText(item, separator))
|
|
367
|
+
].join(separator);
|
|
368
|
+
var sys = {
|
|
369
|
+
fileExists: (file) => existsSync(file),
|
|
370
|
+
readFile: (file) => {
|
|
371
|
+
try {
|
|
372
|
+
return readFileSync(file, "utf8");
|
|
373
|
+
} catch {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
var isIterationStatement = (node) => ast.isForStatement(node) || ast.isForInStatement(node) || ast.isForOfStatement(node) || ast.isWhileStatement(node) || ast.isDoStatement(node);
|
|
379
|
+
var ts = {
|
|
380
|
+
...ast,
|
|
381
|
+
ModuleKind,
|
|
382
|
+
ModuleResolutionKind,
|
|
383
|
+
JsxEmit,
|
|
384
|
+
SymbolFlags,
|
|
385
|
+
TypeFlags,
|
|
386
|
+
TypeFormatFlags,
|
|
387
|
+
isStringLiteralLike: ast.isStringLiteralLikeNode,
|
|
388
|
+
isFunctionLike: ast.isFunctionLikeDeclaration,
|
|
389
|
+
isPropertySignature: ast.isPropertySignatureDeclaration,
|
|
390
|
+
isParameter: ast.isParameterDeclaration,
|
|
391
|
+
isIterationStatement,
|
|
392
|
+
forEachChild: (node, visit) => node.forEachChild(visit),
|
|
393
|
+
createSourceFile: (file, text, _target, _parents, scriptKind) => parseSource(file, text, scriptKind),
|
|
394
|
+
readConfigFile: readConfig,
|
|
395
|
+
parseJsonConfigFileContent: (config, _host, directory) => parseConfig(config, directory),
|
|
396
|
+
parseConfigFileTextToJson: parseConfigText,
|
|
397
|
+
resolveProjectReferencePath: (reference) => reference.path.endsWith(".json") ? reference.path : path.join(reference.path, "tsconfig.json"),
|
|
398
|
+
flattenDiagnosticMessageText,
|
|
399
|
+
findConfigFile,
|
|
400
|
+
sys
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
// src/design-usage.mts
|
|
404
|
+
var wording = {
|
|
405
|
+
"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."],
|
|
406
|
+
"component-outside-pattern": (problem) => [
|
|
407
|
+
`The component ${problem.name} is rendered outside every pattern, so nothing owns its place on the screen.`,
|
|
408
|
+
"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."
|
|
409
|
+
],
|
|
410
|
+
"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."],
|
|
411
|
+
"prose-element-undeclared": (problem) => [
|
|
412
|
+
`<${problem.tag}> is content of ${problem.owner}, whose recipe declares no such element: it is drawn without a design.`,
|
|
413
|
+
`Declare the element in the prose recipe of ${problem.owner} (\`elements\`), or write the content with the elements it declares.`
|
|
414
|
+
],
|
|
415
|
+
"spread-props": () => ["A spread passes props nothing can see.", "Pass each prop explicitly."],
|
|
416
|
+
"design-prop": (problem) => [`${problem.attribute} supplies design from outside the design system.`, "Remove it; choose the treatment through the owner's own props."],
|
|
417
|
+
"imperative-design": (problem) => [`${problem.member} writes styles or creates DOM by hand.`, "Remove the write; render design-system owners with props."],
|
|
418
|
+
"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."]
|
|
419
|
+
};
|
|
420
|
+
var describe = (problem) => {
|
|
421
|
+
const kind = problem.kind;
|
|
422
|
+
return wording[kind](problem);
|
|
423
|
+
};
|
|
424
|
+
async function checkDesignUsage2(sources, entry, allowance = {}) {
|
|
425
|
+
const findings = [];
|
|
426
|
+
for (const { file, text } of sources) {
|
|
427
|
+
const source = await parseSource(path2.resolve(file), text);
|
|
428
|
+
for (const { node, problem } of designUsageProblems(source, entry, allowance)) {
|
|
429
|
+
const at = source.getLineAndCharacterOfPosition(node.getStart(source));
|
|
430
|
+
const [message, repair] = describe(problem);
|
|
431
|
+
findings.push({ file, line: at.line + 1, column: at.character + 1, code: `design-usage/${problem.kind}`, message, repair });
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return findings;
|
|
435
|
+
}
|
|
436
|
+
async function designSystemEntry2(publicEntry, entryFile) {
|
|
437
|
+
const source = await parseSource(path2.resolve(entryFile), readFileSync2(entryFile, "utf8"));
|
|
438
|
+
const patterns = new Set;
|
|
439
|
+
for (const statement of source.statements) {
|
|
440
|
+
if (!isExportDeclaration(statement) || statement.isTypeOnly || statement.moduleSpecifier === undefined || !isStringLiteral2(statement.moduleSpecifier))
|
|
441
|
+
continue;
|
|
442
|
+
if (!statement.moduleSpecifier.text.startsWith("./patterns/"))
|
|
443
|
+
continue;
|
|
444
|
+
const clause = statement.exportClause;
|
|
445
|
+
if (clause !== undefined && isNamedExports(clause)) {
|
|
446
|
+
for (const element of clause.elements)
|
|
447
|
+
if (!element.isTypeOnly)
|
|
448
|
+
patterns.add(element.name.text);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const manifest = path2.join(path2.dirname(path2.resolve(entryFile)), PROSE_MANIFEST);
|
|
452
|
+
const prose = existsSync2(manifest) ? parseProseManifest(readFileSync2(manifest, "utf8")) : new Map;
|
|
453
|
+
return { publicEntry, patterns, prose };
|
|
454
|
+
}
|
|
455
|
+
var closeDesignUsage2 = () => closeSyntax();
|
|
456
|
+
|
|
457
|
+
// src/guard/config.mts
|
|
458
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, statSync } from "node:fs";
|
|
459
|
+
import path3 from "node:path";
|
|
460
|
+
|
|
461
|
+
// src/result.mts
|
|
462
|
+
var ok = (value) => ({ kind: "ok", value });
|
|
463
|
+
var err = (error) => ({ kind: "err", error });
|
|
464
|
+
|
|
465
|
+
// src/unknown.mts
|
|
466
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Map);
|
|
467
|
+
|
|
468
|
+
// src/guard/config.mts
|
|
469
|
+
var GUARD_CONFIG_FILE2 = "ads-guard.config.json";
|
|
470
|
+
var FIELDS = ["designSystem", "entry", "include", "exclude", "allow"];
|
|
471
|
+
var isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "");
|
|
472
|
+
var insideRoot = (root, relative) => {
|
|
473
|
+
const resolved = path3.resolve(root, relative);
|
|
474
|
+
return !/[*?[\]{}]/.test(relative) && (resolved === root || resolved.startsWith(root + path3.sep));
|
|
475
|
+
};
|
|
476
|
+
function readGuardConfig2(root) {
|
|
477
|
+
const file = path3.join(root, GUARD_CONFIG_FILE2);
|
|
478
|
+
if (!existsSync3(file))
|
|
479
|
+
return err([`${GUARD_CONFIG_FILE2} is missing in ${root}. Create it with "designSystem" and "include".`]);
|
|
480
|
+
let value;
|
|
481
|
+
try {
|
|
482
|
+
value = JSON.parse(readFileSync3(file, "utf8"));
|
|
483
|
+
} catch (error) {
|
|
484
|
+
return err([`${GUARD_CONFIG_FILE2} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]);
|
|
485
|
+
}
|
|
486
|
+
if (!isRecord(value))
|
|
487
|
+
return err([`${GUARD_CONFIG_FILE2} is a JSON object.`]);
|
|
488
|
+
const problems = [];
|
|
489
|
+
for (const key of Object.keys(value))
|
|
490
|
+
if (!FIELDS.includes(key))
|
|
491
|
+
problems.push(`"${key}" is not a field. The fields are ${FIELDS.join(", ")}.`);
|
|
492
|
+
const { designSystem, entry, include, exclude = [], allow = {} } = value;
|
|
493
|
+
if (typeof designSystem !== "string" || designSystem.trim() === "")
|
|
494
|
+
problems.push('"designSystem" is the specifier the application imports the design system by, such as "@acme/design".');
|
|
495
|
+
if (entry !== undefined && (typeof entry !== "string" || !insideRoot(root, entry) || !existsSync3(path3.resolve(root, entry))))
|
|
496
|
+
problems.push(`"entry" is the path of the design system's public entry file, relative to this file. It does not exist.`);
|
|
497
|
+
if (!isStrings(include) || include.length === 0)
|
|
498
|
+
problems.push(`"include" lists the folders with the application's sources, such as ["src"].`);
|
|
499
|
+
else
|
|
500
|
+
for (const folder of include)
|
|
501
|
+
if (!insideRoot(root, folder) || !existsSync3(path3.resolve(root, folder)) || !statSync(path3.resolve(root, folder)).isDirectory())
|
|
502
|
+
problems.push(`"include" names ${folder}, which is not a folder under this file. Wildcards are not supported.`);
|
|
503
|
+
if (!isStrings(exclude))
|
|
504
|
+
problems.push('"exclude" lists folders and files, such as ["src/generated"].');
|
|
505
|
+
else if (isStrings(include))
|
|
506
|
+
for (const item of exclude) {
|
|
507
|
+
const resolved = path3.resolve(root, item);
|
|
508
|
+
const within = include.some((folder) => resolved.startsWith(path3.resolve(root, folder) + path3.sep));
|
|
509
|
+
if (!insideRoot(root, item) || !existsSync3(resolved))
|
|
510
|
+
problems.push(`"exclude" names ${item}, which does not exist. Remove it. Wildcards are not supported.`);
|
|
511
|
+
else if (!within)
|
|
512
|
+
problems.push(`"exclude" names ${item}, which is not under any "include" folder. Remove it.`);
|
|
513
|
+
}
|
|
514
|
+
const allowed = new Map;
|
|
515
|
+
if (!isRecord(allow))
|
|
516
|
+
problems.push('"allow" maps a package to the components it may render, such as { "react": ["Suspense"] }.');
|
|
517
|
+
else
|
|
518
|
+
for (const [specifier, names] of Object.entries(allow)) {
|
|
519
|
+
if (!isStrings(names) || names.length === 0)
|
|
520
|
+
problems.push(`"allow" lists the components of ${specifier} by name, such as ["Outlet"]. Use "default" for a default export.`);
|
|
521
|
+
else if (typeof designSystem === "string" && specifier === designSystem)
|
|
522
|
+
problems.push(`"allow" names the design system itself (${specifier}). Everything it exports is already allowed.`);
|
|
523
|
+
else
|
|
524
|
+
allowed.set(specifier, new Set(names));
|
|
525
|
+
}
|
|
526
|
+
if (problems.length > 0)
|
|
527
|
+
return err(problems);
|
|
528
|
+
return ok({
|
|
529
|
+
designSystem: String(designSystem),
|
|
530
|
+
...typeof entry === "string" ? { entry } : {},
|
|
531
|
+
include: isStrings(include) ? include : [],
|
|
532
|
+
exclude: isStrings(exclude) ? exclude : [],
|
|
533
|
+
allow: allowed
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/guard/run.mts
|
|
538
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
|
|
539
|
+
import { createRequire } from "node:module";
|
|
540
|
+
import path5 from "node:path";
|
|
541
|
+
|
|
542
|
+
// src/guard/files.mts
|
|
543
|
+
import { readdirSync, statSync as statSync2 } from "node:fs";
|
|
544
|
+
import path4 from "node:path";
|
|
545
|
+
var SOURCE = /\.[cm]?[jt]sx$/;
|
|
546
|
+
var TEST = /(?:\.(?:test|spec)\.[cm]?[jt]sx?$)|(?:^|\/)(?:__tests__|__mocks__)\//;
|
|
547
|
+
var SKIPPED_FOLDERS = new Set(["node_modules"]);
|
|
548
|
+
function walk2(folder, visit) {
|
|
549
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
|
550
|
+
if (entry.name.startsWith(".") || SKIPPED_FOLDERS.has(entry.name))
|
|
551
|
+
continue;
|
|
552
|
+
const file = path4.join(folder, entry.name);
|
|
553
|
+
if (entry.isDirectory())
|
|
554
|
+
walk2(file, visit);
|
|
555
|
+
else if (entry.isFile() && SOURCE.test(entry.name))
|
|
556
|
+
visit(file);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
function guardScope(root, include, exclude, designSystemFolder) {
|
|
560
|
+
const relative = (file) => path4.relative(root, file).split(path4.sep).join("/");
|
|
561
|
+
const excludedPaths = exclude.map((item) => path4.resolve(root, item));
|
|
562
|
+
const excluded = new Map(exclude.map((item) => [item, 0]));
|
|
563
|
+
const files = new Set;
|
|
564
|
+
let tests = 0, designSystem = 0;
|
|
565
|
+
for (const folder of include)
|
|
566
|
+
walk2(path4.resolve(root, folder), (file) => {
|
|
567
|
+
const index = excludedPaths.findIndex((item) => file === item || file.startsWith(item + path4.sep) || statSync2(item).isFile() && file === item);
|
|
568
|
+
const name = exclude[index];
|
|
569
|
+
if (name !== undefined)
|
|
570
|
+
excluded.set(name, (excluded.get(name) ?? 0) + 1);
|
|
571
|
+
else if (designSystemFolder !== null && file.startsWith(designSystemFolder + path4.sep))
|
|
572
|
+
designSystem++;
|
|
573
|
+
else if (TEST.test(relative(file)))
|
|
574
|
+
tests++;
|
|
575
|
+
else
|
|
576
|
+
files.add(relative(file));
|
|
577
|
+
});
|
|
578
|
+
return { files: [...files].sort(), excluded: [...excluded].map(([name, count]) => ({ path: name, files: count })), tests, designSystem };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// src/guard/run.mts
|
|
582
|
+
var ENTRY_NAMES = ["index.ts", "index.tsx", "index.mts", "index.js", "index.mjs"];
|
|
583
|
+
function entryFile(root, config) {
|
|
584
|
+
if (config.entry !== undefined) {
|
|
585
|
+
const configured = path5.resolve(root, config.entry);
|
|
586
|
+
return ok(configured);
|
|
587
|
+
}
|
|
588
|
+
const specifier = config.designSystem;
|
|
589
|
+
if (specifier.startsWith(".")) {
|
|
590
|
+
const target = path5.resolve(root, specifier);
|
|
591
|
+
const found = [target, ...ENTRY_NAMES.map((name) => path5.join(target, name))].find((candidate) => existsSync4(candidate) && /\.[cm]?[jt]sx?$/.test(candidate));
|
|
592
|
+
return found === undefined ? err(`"designSystem" is ${specifier}, and no entry file is at ${target}.`) : ok(found);
|
|
593
|
+
}
|
|
594
|
+
try {
|
|
595
|
+
return ok(createRequire(path5.join(root, "package.json")).resolve(specifier));
|
|
596
|
+
} catch {
|
|
597
|
+
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.`);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
async function runGuard2(root) {
|
|
601
|
+
const absolute = path5.resolve(root);
|
|
602
|
+
const config = readGuardConfig2(absolute);
|
|
603
|
+
if (config.kind === "err")
|
|
604
|
+
return config;
|
|
605
|
+
const located = entryFile(absolute, config.value);
|
|
606
|
+
if (located.kind === "err")
|
|
607
|
+
return err([located.error]);
|
|
608
|
+
const entry = await designSystemEntry2(config.value.designSystem, located.value);
|
|
609
|
+
const folder = path5.dirname(located.value);
|
|
610
|
+
const scope = guardScope(absolute, config.value.include, config.value.exclude, folder.startsWith(absolute + path5.sep) ? folder : null);
|
|
611
|
+
const sources = scope.files.map((file) => ({ file, text: readFileSync4(path5.join(absolute, file), "utf8") }));
|
|
612
|
+
const findings = await checkDesignUsage2(sources, entry, { components: config.value.allow, metadata: true });
|
|
613
|
+
const inside = located.value.startsWith(absolute + path5.sep);
|
|
614
|
+
return ok({
|
|
615
|
+
ok: findings.length === 0,
|
|
616
|
+
designSystem: config.value.designSystem,
|
|
617
|
+
entry: inside ? path5.relative(absolute, located.value).split(path5.sep).join("/") : located.value,
|
|
618
|
+
patterns: entry.patterns.size,
|
|
619
|
+
checked: scope.files.length,
|
|
620
|
+
scope: { excluded: scope.excluded, tests: scope.tests, designSystem: scope.designSystem },
|
|
621
|
+
findings
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
function guardText2(report) {
|
|
625
|
+
const lines = report.findings.map((finding) => `${finding.file}:${finding.line}:${finding.column} ${finding.code}
|
|
626
|
+
${finding.message}
|
|
627
|
+
${finding.repair}`);
|
|
628
|
+
const left = [];
|
|
629
|
+
const excludedFiles = report.scope.excluded.reduce((sum, item) => sum + item.files, 0);
|
|
630
|
+
if (report.scope.excluded.length > 0)
|
|
631
|
+
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(", ")}`);
|
|
632
|
+
if (report.scope.tests > 0)
|
|
633
|
+
left.push(`${report.scope.tests} test file${report.scope.tests === 1 ? "" : "s"}`);
|
|
634
|
+
if (report.scope.designSystem > 0)
|
|
635
|
+
left.push(`${report.scope.designSystem} file${report.scope.designSystem === 1 ? "" : "s"} of the design system`);
|
|
636
|
+
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("; ")}` : ""}.`;
|
|
637
|
+
const verdict = report.ok ? "The source uses the design system only." : `${report.findings.length} finding${report.findings.length === 1 ? "" : "s"}.`;
|
|
638
|
+
return [...lines, summary, verdict].join(`
|
|
639
|
+
`);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
export { checkDesignUsage2, designSystemEntry2, closeDesignUsage2, GUARD_CONFIG_FILE2, readGuardConfig2, runGuard2, guardText2 };
|