@edjbarron/ux-guard 0.0.0-stage → 0.6.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.
@@ -0,0 +1,581 @@
1
+ import { createRequire } from 'node:module';
2
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { resolveExistingRepositoryPath } from './config.mjs';
5
+ import { baselineFromScan, DEBT_RULES, scanFiles, scanSource } from './patterns.mjs';
6
+ import { ConfigError } from './yaml.mjs';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const SOURCE_EXTENSIONS = new Set(['.jsx', '.tsx']);
10
+ const TEST_SUFFIXES = ['.test.jsx', '.test.tsx', '.spec.jsx', '.spec.tsx'];
11
+ const SKIP_DIRECTORIES = new Set(['build', 'coverage', 'dist', 'node_modules']);
12
+ const NATIVE_CONTROLS = new Set(['button', 'input', 'select', 'textarea']);
13
+ const PRESENTATION_PROPS = new Set(['size', 'variant']);
14
+ const CONTROL_NAME =
15
+ /(?:^|\.)(?:.*Button|.*Input|.*Icon|Autocomplete|Checkbox|Combobox|Radio|SegmentedControl|Select|Slider|Switch|Textarea)$/;
16
+ const ICON_PACKAGE =
17
+ /(?:^|[-/])icons?(?:$|[-/])|fontawesome|heroicons|lucide|phosphor|@mui\/icons-material/;
18
+
19
+ export function discoverProject(root, explicitTypeScript) {
20
+ const manifests = findNamedFiles(root, (name) => name === 'package.json').map((path) => readManifest(root, path));
21
+ const dependencies = dependencyIndex(manifests);
22
+ const runtime = loadDiscoveryTypeScript(root, explicitTypeScript, manifests);
23
+ const project = readTypeScriptProjects(runtime.ts, root);
24
+ const moduleMap = new Map();
25
+ const nativeControls = {};
26
+ const styles = { classNameAttributes: 0, inlineStyleAttributes: 0, stylesheetImports: {} };
27
+ const texts = new Map();
28
+
29
+ for (const file of project.files) {
30
+ const text = readFileSync(resolveExistingRepositoryPath(root, file, `discovery source ${file}`), 'utf8');
31
+ texts.set(file, text);
32
+ inspectSource(runtime.ts, file, text, dependencies, moduleMap, nativeControls, styles);
33
+ }
34
+
35
+ const iconModules = [...moduleMap.keys()].filter(isIconPackage).sort();
36
+ const discoveryConfig = {
37
+ patterns: {
38
+ components: { module: '', names: [], props: [] },
39
+ icons: { modules: iconModules, allowed: [] },
40
+ },
41
+ };
42
+ const debt = Object.fromEntries(DEBT_RULES.map((rule) => [rule, {}]));
43
+ for (const [file, text] of texts) {
44
+ const result = scanSource(runtime.ts, file, text, discoveryConfig);
45
+ for (const rule of DEBT_RULES) {
46
+ if (result.debt[rule] > 0) debt[rule][file] = result.debt[rule];
47
+ }
48
+ }
49
+
50
+ const libraries = renderLibraries(moduleMap, dependencies);
51
+ const candidate = buildCandidate(runtime, project, libraries, root);
52
+ const baselineConfig = { patterns: candidate.configFragment.patterns };
53
+ const baseline = baselineFromScan(scanFiles(runtime.ts, root, baselineConfig, project.files));
54
+
55
+ return {
56
+ version: 1,
57
+ kind: 'ux-guard-discovery',
58
+ approval: {
59
+ status: 'review-required',
60
+ observedUsageIsApprovedPolicy: false,
61
+ filesWritten: false,
62
+ },
63
+ inputs: {
64
+ typescript: runtime.configPath,
65
+ typescriptVersion: runtime.ts.version,
66
+ typescriptSource: runtime.source,
67
+ manifests: manifests.map(({ path, name }) => ({ path, name })),
68
+ tsconfigs: project.tsconfigs,
69
+ diagnostics: project.diagnostics,
70
+ },
71
+ observed: {
72
+ files: project.files.length,
73
+ sourceRoots: project.sourceRoots,
74
+ componentLibraries: libraries.filter((library) => !library.iconLibrary),
75
+ iconLibraries: libraries.filter((library) => library.iconLibrary),
76
+ nativeControls: sortRecord(nativeControls),
77
+ styling: {
78
+ classNameAttributes: styles.classNameAttributes,
79
+ inlineStyleAttributes: styles.inlineStyleAttributes,
80
+ stylesheetImports: sortRecord(styles.stylesheetImports),
81
+ },
82
+ debt,
83
+ },
84
+ candidate: {
85
+ status: 'review-required',
86
+ configIsComplete: false,
87
+ missingDecisions: [
88
+ 'catalog path and navigation sources',
89
+ 'approved component modules, controls, and props',
90
+ 'approved icon libraries',
91
+ 'pattern baseline destination',
92
+ 'source-root and exclusion review',
93
+ ],
94
+ configFragment: candidate.configFragment,
95
+ baseline: {
96
+ status: 'candidate-observation-only',
97
+ approved: false,
98
+ value: baseline,
99
+ },
100
+ notes: candidate.notes,
101
+ },
102
+ };
103
+ }
104
+
105
+ export function candidateFromDiscovery(report) {
106
+ return {
107
+ version: 1,
108
+ kind: 'ux-guard-policy-candidate',
109
+ approval: {
110
+ status: 'unapproved',
111
+ reviewer: '',
112
+ reviewedAt: '',
113
+ patternPolicyReviewed: false,
114
+ },
115
+ config: report.candidate.configFragment,
116
+ observedBaseline: {
117
+ status: 'unapproved-observation-only',
118
+ approved: false,
119
+ value: report.candidate.baseline.value,
120
+ },
121
+ review: {
122
+ missingDecisions: report.candidate.missingDecisions,
123
+ notes: report.candidate.notes,
124
+ },
125
+ };
126
+ }
127
+
128
+ export function setupProposalFromDiscovery(report) {
129
+ return {
130
+ ...candidateFromDiscovery(report),
131
+ kind: 'ux-guard-setup-proposal',
132
+ };
133
+ }
134
+
135
+ export function renderDiscovery(report) {
136
+ const debtTotal = (rule) => Object.values(report.observed.debt[rule]).reduce((sum, count) => sum + count, 0);
137
+ const lines = [
138
+ 'UX project discovery (review required)',
139
+ report.approval.filesWritten
140
+ ? 'Observed usage is inventory, not approved policy. Only an unapproved candidate artifact was written.'
141
+ : 'Observed usage is inventory, not approved policy. No files were written.',
142
+ `TypeScript: ${report.inputs.typescript} (${report.inputs.typescriptSource})`,
143
+ `Source: ${report.observed.files} files in ${report.observed.sourceRoots.length} candidate roots`,
144
+ ];
145
+ for (const sourceRoot of report.observed.sourceRoots) {
146
+ lines.push(` ${sourceRoot.path}: ${sourceRoot.files} files (${sourceRoot.productionFiles} non-test JSX)`);
147
+ }
148
+ lines.push('Observed component libraries:');
149
+ for (const library of report.observed.componentLibraries) {
150
+ lines.push(` ${library.module}: ${library.jsxUses} JSX uses, ${library.components.length} components`);
151
+ }
152
+ if (report.observed.componentLibraries.length === 0) lines.push(' (none)');
153
+ lines.push('Observed icon libraries (not automatically allowed):');
154
+ for (const library of report.observed.iconLibraries) {
155
+ lines.push(` ${library.module}: ${library.jsxUses} JSX uses in ${library.files.length} files`);
156
+ }
157
+ if (report.observed.iconLibraries.length === 0) lines.push(' (none)');
158
+ const native = Object.entries(report.observed.nativeControls).map(([name, count]) => `${name} ${count}`).join(', ');
159
+ lines.push(`Native controls: ${native || 'none'}`);
160
+ lines.push(
161
+ `Styling: ${report.observed.styling.inlineStyleAttributes} inline style attributes, ` +
162
+ `${report.observed.styling.classNameAttributes} className attributes, ` +
163
+ `${Object.values(report.observed.styling.stylesheetImports).reduce((sum, count) => sum + count, 0)} stylesheet imports`,
164
+ );
165
+ lines.push(`Debt observations: ${DEBT_RULES.map((rule) => `${rule} ${debtTotal(rule)}`).join(', ')}`);
166
+ const components = report.candidate.configFragment.patterns.components;
167
+ lines.push('Candidate pattern profile (requires review):');
168
+ lines.push(` roots: ${report.candidate.configFragment.patterns.roots.join(', ') || '(none)'}`);
169
+ lines.push(` component module: ${components.module || '(none)'}`);
170
+ lines.push(` controls: ${components.names.join(', ') || '(none)'}`);
171
+ lines.push(` props: ${components.props.join(', ') || '(none)'}`);
172
+ lines.push(' allowed icon libraries: none selected');
173
+ lines.push(
174
+ `Candidate baseline: ${Object.keys(report.candidate.baseline.value.controlValues).length} control keys; ` +
175
+ (report.approval.filesWritten ? 'observation only, included in the unapproved candidate' : 'observation only, not written'),
176
+ );
177
+ lines.push('Use --format json for aliases, prop values, file-level debt, and the complete candidate artifacts.');
178
+ return `${lines.join('\n')}\n`;
179
+ }
180
+
181
+ function findNamedFiles(root, accepts) {
182
+ const files = [];
183
+ const walk = (directory) => {
184
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
185
+ if (entry.isDirectory()) {
186
+ if (entry.name.startsWith('.') || SKIP_DIRECTORIES.has(entry.name)) continue;
187
+ walk(join(directory, entry.name));
188
+ } else if (entry.isFile() && accepts(entry.name)) {
189
+ files.push(join(directory, entry.name));
190
+ }
191
+ }
192
+ };
193
+ walk(root);
194
+ return files;
195
+ }
196
+
197
+ function readManifest(root, path) {
198
+ let manifest;
199
+ try {
200
+ manifest = JSON.parse(readFileSync(path, 'utf8'));
201
+ } catch {
202
+ throw new ConfigError(`${toRelative(root, path)} is not valid JSON`);
203
+ }
204
+ return {
205
+ path: toRelative(root, path),
206
+ directory: dirname(path),
207
+ name: typeof manifest.name === 'string' ? manifest.name : null,
208
+ dependencies: {
209
+ dependencies: manifest.dependencies ?? {},
210
+ devDependencies: manifest.devDependencies ?? {},
211
+ peerDependencies: manifest.peerDependencies ?? {},
212
+ },
213
+ };
214
+ }
215
+
216
+ function dependencyIndex(manifests) {
217
+ const index = new Map();
218
+ for (const manifest of manifests) {
219
+ for (const [scope, entries] of Object.entries(manifest.dependencies)) {
220
+ for (const [name, version] of Object.entries(entries)) {
221
+ const declarations = index.get(name) ?? [];
222
+ declarations.push({ manifest: manifest.path, scope, version });
223
+ index.set(name, declarations);
224
+ }
225
+ }
226
+ }
227
+ return index;
228
+ }
229
+
230
+ function loadDiscoveryTypeScript(root, explicit, manifests) {
231
+ const candidates = [];
232
+ if (explicit) candidates.push({ path: isAbsolute(explicit) ? explicit : resolve(root, explicit), source: '--typescript' });
233
+ if (!explicit) {
234
+ candidates.push({
235
+ path: require.resolve('typescript'),
236
+ source: 'ux-guard exact dependency',
237
+ });
238
+ }
239
+ for (const manifest of manifests) {
240
+ if (!Object.values(manifest.dependencies).some((entries) => typeof entries.typescript === 'string')) continue;
241
+ candidates.push({ path: join(manifest.directory, 'node_modules/typescript'), source: manifest.path });
242
+ try {
243
+ const resolved = createRequire(join(manifest.directory, 'package.json')).resolve('typescript');
244
+ candidates.push({ path: resolved, source: manifest.path });
245
+ } catch {
246
+ // The declared peer or dependency may not be installed in this package.
247
+ }
248
+ }
249
+ const tried = new Set();
250
+ for (const candidate of candidates) {
251
+ if (tried.has(candidate.path)) continue;
252
+ tried.add(candidate.path);
253
+ try {
254
+ const ts = require(candidate.path);
255
+ if (typeof ts.createSourceFile === 'function' && typeof ts.parseJsonConfigFileContent === 'function') {
256
+ return { ts, configPath: toConfigPath(root, candidate.path), source: candidate.source };
257
+ }
258
+ } catch {
259
+ // Try the next deterministic candidate.
260
+ }
261
+ }
262
+ throw new ConfigError('discover could not load TypeScript; install it in a package or pass --typescript <path>');
263
+ }
264
+
265
+ function readTypeScriptProjects(ts, root) {
266
+ const configPaths = findNamedFiles(root, (name) => /^tsconfig(?:\.[^.]+)?\.json$/.test(name));
267
+ if (configPaths.length === 0) throw new ConfigError('discover found no tsconfig files');
268
+ const diagnostics = [];
269
+ const files = new Set();
270
+ const roots = new Map();
271
+ const tsconfigs = [];
272
+ for (const configPath of configPaths) {
273
+ const configName = toRelative(root, configPath);
274
+ const loaded = ts.readConfigFile(configPath, ts.sys.readFile);
275
+ if (loaded.error) {
276
+ diagnostics.push({ tsconfig: configName, message: diagnosticText(ts, loaded.error) });
277
+ continue;
278
+ }
279
+ const parsed = ts.parseJsonConfigFileContent(loaded.config, ts.sys, dirname(configPath), undefined, configPath);
280
+ for (const error of parsed.errors) diagnostics.push({ tsconfig: configName, message: diagnosticText(ts, error) });
281
+ const jsxFiles = parsed.fileNames.filter((file) => SOURCE_EXTENSIONS.has(extname(file).toLowerCase()) && isInside(root, file));
282
+ for (const file of jsxFiles) {
283
+ const relativeFile = toRelative(root, file);
284
+ if (!isTestFile(relativeFile)) files.add(relativeFile);
285
+ }
286
+ tsconfigs.push(configName);
287
+ for (const includeRoot of configIncludeRoots(configPath, loaded.config, jsxFiles)) {
288
+ if (!isInside(root, includeRoot.path)) continue;
289
+ const path = toRelative(root, includeRoot.path);
290
+ const current = roots.get(path) ?? { path, files: new Set(), productionFiles: new Set(), tsconfigs: new Set() };
291
+ for (const file of includeRoot.files) {
292
+ current.files.add(toRelative(root, file));
293
+ if (!isTestFile(file)) current.productionFiles.add(toRelative(root, file));
294
+ }
295
+ current.tsconfigs.add(configName);
296
+ roots.set(path, current);
297
+ }
298
+ }
299
+ if (files.size === 0) throw new ConfigError('discover found no non-test JSX or TSX source files');
300
+ return {
301
+ files: [...files].sort(),
302
+ sourceRoots: [...roots.values()]
303
+ .filter((entry) => entry.productionFiles.size > 0)
304
+ .map((entry) => ({
305
+ path: entry.path,
306
+ files: entry.files.size,
307
+ productionFiles: entry.productionFiles.size,
308
+ tsconfigs: [...entry.tsconfigs].sort(),
309
+ }))
310
+ .sort((a, b) => a.path.localeCompare(b.path)),
311
+ tsconfigs: tsconfigs.sort(),
312
+ diagnostics,
313
+ };
314
+ }
315
+
316
+ function configIncludeRoots(configPath, rawConfig, files) {
317
+ const configDirectory = dirname(configPath);
318
+ const includes = Array.isArray(rawConfig.include) && rawConfig.include.length ? rawConfig.include : ['.'];
319
+ const roots = [];
320
+ for (const include of includes) {
321
+ if (typeof include !== 'string') continue;
322
+ const wildcard = include.search(/[*?]/);
323
+ let prefix = wildcard === -1 ? include : include.slice(0, wildcard);
324
+ prefix = prefix.replace(/[\\/]+$/, '') || '.';
325
+ let path = resolve(configDirectory, prefix);
326
+ if (existsSync(path) && !statSync(path).isDirectory()) path = dirname(path);
327
+ const matching = files.filter((file) => isInside(path, file));
328
+ if (matching.length) roots.push({ path, files: matching });
329
+ }
330
+ return roots;
331
+ }
332
+
333
+ function inspectSource(ts, file, text, dependencies, moduleMap, nativeControls, styles) {
334
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, sourceKind(ts, file));
335
+ const bindings = new Map();
336
+ for (const statement of source.statements) {
337
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
338
+ const importSource = statement.moduleSpecifier.text;
339
+ if (/\.(?:css|less|sass|scss|styl)$/.test(importSource)) {
340
+ styles.stylesheetImports[importSource] = (styles.stylesheetImports[importSource] ?? 0) + 1;
341
+ }
342
+ const module = packageName(importSource);
343
+ if (!module || !dependencies.has(module)) continue;
344
+ const record = moduleRecord(moduleMap, module);
345
+ record.importSources.add(importSource);
346
+ record.files.add(file);
347
+ record.importDeclarations += 1;
348
+ const clause = statement.importClause;
349
+ if (!clause) continue;
350
+ if (clause.name) bindings.set(clause.name.text, { module, importSource, imported: 'default', kind: 'default' });
351
+ const named = clause.namedBindings;
352
+ if (named && ts.isNamedImports(named)) {
353
+ for (const element of named.elements) {
354
+ bindings.set(element.name.text, {
355
+ module,
356
+ importSource,
357
+ imported: (element.propertyName ?? element.name).text,
358
+ kind: 'named',
359
+ });
360
+ }
361
+ } else if (named && ts.isNamespaceImport(named)) {
362
+ bindings.set(named.name.text, { module, importSource, imported: '*', kind: 'namespace' });
363
+ }
364
+ }
365
+
366
+ const visit = (node) => {
367
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
368
+ const tag = node.tagName.getText(source);
369
+ if (NATIVE_CONTROLS.has(tag)) nativeControls[tag] = (nativeControls[tag] ?? 0) + 1;
370
+ const [local, ...member] = tag.split('.');
371
+ const binding = bindings.get(local);
372
+ if (binding) {
373
+ const name =
374
+ binding.kind === 'namespace'
375
+ ? member.join('.')
376
+ : [binding.imported === 'default' ? local : binding.imported, ...member].filter(Boolean).join('.');
377
+ if (name) {
378
+ const record = moduleRecord(moduleMap, binding.module);
379
+ const component = record.components.get(name) ?? {
380
+ name,
381
+ importKind: binding.kind,
382
+ jsxUses: 0,
383
+ aliases: new Map(),
384
+ importSources: new Set(),
385
+ props: new Map(),
386
+ };
387
+ component.jsxUses += 1;
388
+ component.aliases.set(tag, (component.aliases.get(tag) ?? 0) + 1);
389
+ component.importSources.add(binding.importSource);
390
+ for (const attribute of node.attributes.properties) {
391
+ if (!ts.isJsxAttribute(attribute)) continue;
392
+ const prop = attribute.name.getText(source);
393
+ const propRecord = component.props.get(prop) ?? { occurrences: 0, values: new Map() };
394
+ propRecord.occurrences += 1;
395
+ for (const value of attributeValues(ts, attribute)) {
396
+ propRecord.values.set(value, (propRecord.values.get(value) ?? 0) + 1);
397
+ }
398
+ component.props.set(prop, propRecord);
399
+ if (prop === 'className') styles.classNameAttributes += 1;
400
+ if (prop === 'style') styles.inlineStyleAttributes += 1;
401
+ }
402
+ record.components.set(name, component);
403
+ }
404
+ } else {
405
+ for (const attribute of node.attributes.properties) {
406
+ if (!ts.isJsxAttribute(attribute)) continue;
407
+ const prop = attribute.name.getText(source);
408
+ if (prop === 'className') styles.classNameAttributes += 1;
409
+ if (prop === 'style') styles.inlineStyleAttributes += 1;
410
+ }
411
+ }
412
+ }
413
+ ts.forEachChild(node, visit);
414
+ };
415
+ visit(source);
416
+ }
417
+
418
+ function moduleRecord(moduleMap, module) {
419
+ const record = moduleMap.get(module) ?? {
420
+ module,
421
+ importSources: new Set(),
422
+ files: new Set(),
423
+ importDeclarations: 0,
424
+ components: new Map(),
425
+ };
426
+ moduleMap.set(module, record);
427
+ return record;
428
+ }
429
+
430
+ function renderLibraries(moduleMap, dependencies) {
431
+ return [...moduleMap.values()]
432
+ .map((record) => {
433
+ const components = [...record.components.values()]
434
+ .map((component) => ({
435
+ name: component.name,
436
+ importKind: component.importKind,
437
+ jsxUses: component.jsxUses,
438
+ aliases: [...component.aliases].map(([local, count]) => ({ local, count })).sort((a, b) => a.local.localeCompare(b.local)),
439
+ importSources: [...component.importSources].sort(),
440
+ props: [...component.props]
441
+ .map(([name, prop]) => ({
442
+ name,
443
+ occurrences: prop.occurrences,
444
+ values: [...prop.values].map(([value, count]) => ({ value, count })).sort((a, b) => a.value.localeCompare(b.value)),
445
+ }))
446
+ .sort((a, b) => a.name.localeCompare(b.name)),
447
+ }))
448
+ .sort((a, b) => a.name.localeCompare(b.name));
449
+ return {
450
+ module: record.module,
451
+ iconLibrary: isIconPackage(record.module),
452
+ declarations: dependencies.get(record.module).slice().sort((a, b) => a.manifest.localeCompare(b.manifest)),
453
+ importSources: [...record.importSources].sort(),
454
+ importDeclarations: record.importDeclarations,
455
+ files: [...record.files].sort(),
456
+ jsxUses: components.reduce((sum, component) => sum + component.jsxUses, 0),
457
+ components,
458
+ };
459
+ })
460
+ .filter((library) => library.jsxUses > 0 || library.iconLibrary)
461
+ .sort((a, b) => a.module.localeCompare(b.module));
462
+ }
463
+
464
+ function buildCandidate(runtime, project, libraries, root) {
465
+ const ranked = libraries
466
+ .filter((library) => !library.iconLibrary)
467
+ .map((library) => ({
468
+ library,
469
+ controls: library.components.filter(
470
+ (component) =>
471
+ component.importKind === 'named' &&
472
+ component.importSources.includes(library.module) &&
473
+ !component.name.includes('.') &&
474
+ CONTROL_NAME.test(component.name),
475
+ ),
476
+ }))
477
+ .map((entry) => ({ ...entry, score: entry.controls.reduce((sum, component) => sum + component.jsxUses, 0) }))
478
+ .filter((entry) => entry.score > 0)
479
+ .sort((a, b) => b.score - a.score || a.library.module.localeCompare(b.library.module));
480
+ const selected = ranked[0];
481
+ const names = selected?.controls.map((component) => component.name).sort() ?? [];
482
+ const props = [...PRESENTATION_PROPS]
483
+ .filter((prop) => selected?.controls.some((component) => component.props.some((entry) => entry.name === prop)))
484
+ .sort();
485
+ const roots = minimalRoots(project.sourceRoots.map((entry) => entry.path));
486
+ const extensions = [...new Set(project.files.map((file) => extname(file).toLowerCase()))].sort();
487
+ const icons = libraries.filter((library) => library.iconLibrary).map((library) => library.module).sort();
488
+ const notes = [
489
+ 'This fragment is evidence for review, not an enforceable .uxguard.json.',
490
+ 'No icon library is allowed automatically; choose approved libraries and regenerate the baseline.',
491
+ 'The candidate baseline snapshots observations under this unapproved fragment and must not be installed as policy without review.',
492
+ ];
493
+ if (!selected) notes.push('No imported control component module could be selected deterministically.');
494
+ if (props.length === 0) notes.push('No size or variant values were observed on candidate controls.');
495
+ if (icons.length === 0) notes.push('No icon package was identified from declared dependency names.');
496
+ return {
497
+ configFragment: {
498
+ version: 2,
499
+ patterns: {
500
+ roots,
501
+ extensions,
502
+ exclude: TEST_SUFFIXES,
503
+ baseline: '',
504
+ components: {
505
+ module: selected?.library.module ?? '',
506
+ names,
507
+ props,
508
+ },
509
+ icons: {
510
+ modules: icons,
511
+ allowed: [],
512
+ },
513
+ },
514
+ },
515
+ notes,
516
+ };
517
+ }
518
+
519
+ function attributeValues(ts, attribute) {
520
+ const init = attribute.initializer;
521
+ if (!init) return ['true'];
522
+ if (ts.isStringLiteral(init)) return [init.text];
523
+ if (!ts.isJsxExpression(init) || !init.expression) return ['dynamic'];
524
+ return expressionValues(ts, init.expression);
525
+ }
526
+
527
+ function expressionValues(ts, expression) {
528
+ while (ts.isParenthesizedExpression(expression)) expression = expression.expression;
529
+ if (ts.isStringLiteralLike(expression) || ts.isNumericLiteral(expression)) return [expression.text];
530
+ if (ts.isConditionalExpression(expression)) {
531
+ return [...expressionValues(ts, expression.whenTrue), ...expressionValues(ts, expression.whenFalse)];
532
+ }
533
+ return ['dynamic'];
534
+ }
535
+
536
+ function packageName(importSource) {
537
+ if (importSource.startsWith('.') || importSource.startsWith('/')) return null;
538
+ const parts = importSource.split('/');
539
+ return importSource.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
540
+ }
541
+
542
+ function isIconPackage(name) {
543
+ return ICON_PACKAGE.test(name);
544
+ }
545
+
546
+ function isTestFile(path) {
547
+ return TEST_SUFFIXES.some((suffix) => path.endsWith(suffix));
548
+ }
549
+
550
+ function sourceKind(ts, file) {
551
+ return file.endsWith('.jsx') ? ts.ScriptKind.JSX : ts.ScriptKind.TSX;
552
+ }
553
+
554
+ function diagnosticText(ts, diagnostic) {
555
+ return ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
556
+ }
557
+
558
+ function sortRecord(record) {
559
+ return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));
560
+ }
561
+
562
+ function minimalRoots(paths) {
563
+ const selected = [];
564
+ for (const path of paths.sort((a, b) => a.length - b.length || a.localeCompare(b))) {
565
+ if (!selected.some((parent) => path === parent || path.startsWith(`${parent}/`))) selected.push(path);
566
+ }
567
+ return selected.sort();
568
+ }
569
+
570
+ function toConfigPath(root, path) {
571
+ return isInside(root, path) ? toRelative(root, path) : path;
572
+ }
573
+
574
+ function toRelative(root, path) {
575
+ return relative(root, path).split(sep).join('/');
576
+ }
577
+
578
+ function isInside(parent, child) {
579
+ const path = relative(parent, child);
580
+ return path === '' || (!path.startsWith(`..${sep}`) && path !== '..' && !isAbsolute(path));
581
+ }