@prenta/component-blocks 0.3.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.
- package/CHANGELOG.md +230 -0
- package/LICENSE +21 -0
- package/README.md +88 -0
- package/dist/cli.d.ts +24 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +306 -0
- package/dist/cli.js.map +1 -0
- package/dist/diff.d.ts +38 -0
- package/dist/diff.d.ts.map +1 -0
- package/dist/diff.js +524 -0
- package/dist/diff.js.map +1 -0
- package/dist/discriminated-union.d.ts +89 -0
- package/dist/discriminated-union.d.ts.map +1 -0
- package/dist/discriminated-union.js +131 -0
- package/dist/discriminated-union.js.map +1 -0
- package/dist/extract.d.ts +117 -0
- package/dist/extract.d.ts.map +1 -0
- package/dist/extract.js +1036 -0
- package/dist/extract.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/migrate.d.ts +59 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +312 -0
- package/dist/migrate.js.map +1 -0
- package/dist/paths.d.ts +77 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +288 -0
- package/dist/paths.js.map +1 -0
- package/dist/types.d.ts +229 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +12 -0
- package/dist/types.js.map +1 -0
- package/package.json +61 -0
package/dist/extract.js
ADDED
|
@@ -0,0 +1,1036 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extractor — turns a directory of React component source files into a
|
|
3
|
+
* structured {@link Manifest}.
|
|
4
|
+
*
|
|
5
|
+
* Implementation strategy:
|
|
6
|
+
*
|
|
7
|
+
* 1. Walk `rootDir` recursively for `.tsx` files (skipping `node_modules`
|
|
8
|
+
* and dot-folders). `filePattern` overrides the extension match.
|
|
9
|
+
* 2. Run each file through `react-docgen-typescript` to extract per-prop
|
|
10
|
+
* type strings, JSDoc, defaults, and required-ness.
|
|
11
|
+
* 3. Convert each prop's `type.name` string into our structured
|
|
12
|
+
* {@link PropType} discriminated union. This is the load-bearing step
|
|
13
|
+
* — the rest of the CMS (admin form generator, validator, migration
|
|
14
|
+
* diff tool) consumes the structured tree, not the original string.
|
|
15
|
+
*
|
|
16
|
+
* Why type-string parsing rather than going straight through the TS
|
|
17
|
+
* Compiler API: `react-docgen-typescript` already does the hard work of
|
|
18
|
+
* picking the right declaration per file, handling forwardRef/memo, and
|
|
19
|
+
* resolving aliased types. Replacing it with raw TypeChecker would
|
|
20
|
+
* double the surface area for an extractor that ships in v0.1.
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
|
23
|
+
import { dirname, join, relative, resolve, extname, sep } from 'node:path';
|
|
24
|
+
import { findTsconfig, readTsconfig, resolveTsconfigPath } from './paths.js';
|
|
25
|
+
import { withCompilerOptions } from 'react-docgen-typescript';
|
|
26
|
+
const DEFAULT_PATTERN_EXT = '.tsx';
|
|
27
|
+
// ─── Type-string parser ──────────────────────────────────────────────
|
|
28
|
+
/**
|
|
29
|
+
* Parse a TypeScript type as it appears in `react-docgen-typescript`'s
|
|
30
|
+
* `PropItem.type.name` field into a structured {@link PropType}. The
|
|
31
|
+
* input is a single-line string like `string | number`, `{ a: string }`,
|
|
32
|
+
* `("left" | "right")`, `string[]`, etc.
|
|
33
|
+
*
|
|
34
|
+
* `typeAliases` is an optional map of type-alias names → their RHS
|
|
35
|
+
* source string, gathered from the same source file. When a reference
|
|
36
|
+
* matches an alias, it's recursively resolved. This is what makes
|
|
37
|
+
* `items: FeatureItem[]` extract correctly as an array of the
|
|
38
|
+
* FeatureItem object shape, instead of an opaque reference.
|
|
39
|
+
*/
|
|
40
|
+
export function parsePropType(typeName, typeAliases = new Map()) {
|
|
41
|
+
if (!typeName)
|
|
42
|
+
return { kind: 'unknown' };
|
|
43
|
+
const trimmed = stripOuterParens(typeName.trim());
|
|
44
|
+
if (trimmed === 'string')
|
|
45
|
+
return { kind: 'string' };
|
|
46
|
+
if (trimmed === 'number')
|
|
47
|
+
return { kind: 'number' };
|
|
48
|
+
if (trimmed === 'boolean')
|
|
49
|
+
return { kind: 'boolean' };
|
|
50
|
+
if (trimmed === 'true')
|
|
51
|
+
return { kind: 'literal', value: true };
|
|
52
|
+
if (trimmed === 'false')
|
|
53
|
+
return { kind: 'literal', value: false };
|
|
54
|
+
const stringLit = /^"((?:[^"\\]|\\.)*)"$|^'((?:[^'\\]|\\.)*)'$/.exec(trimmed);
|
|
55
|
+
if (stringLit) {
|
|
56
|
+
const value = stringLit[1] ?? stringLit[2] ?? '';
|
|
57
|
+
return { kind: 'literal', value };
|
|
58
|
+
}
|
|
59
|
+
if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
60
|
+
return { kind: 'literal', value: Number(trimmed) };
|
|
61
|
+
}
|
|
62
|
+
const unionParts = splitTopLevel(trimmed, '|')
|
|
63
|
+
.map((p) => p.trim())
|
|
64
|
+
.filter(Boolean);
|
|
65
|
+
if (unionParts.length > 1) {
|
|
66
|
+
const subTypes = unionParts.map((p) => parsePropType(p, typeAliases));
|
|
67
|
+
if (subTypes.every((t) => t.kind === 'literal')) {
|
|
68
|
+
const values = subTypes.map((t) => t.value);
|
|
69
|
+
const allStrings = values.every((v) => typeof v === 'string');
|
|
70
|
+
const allNumbers = values.every((v) => typeof v === 'number');
|
|
71
|
+
if (allStrings || allNumbers) {
|
|
72
|
+
return { kind: 'enum', values: values };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { kind: 'union', types: subTypes };
|
|
76
|
+
}
|
|
77
|
+
if (trimmed.endsWith('[]')) {
|
|
78
|
+
return {
|
|
79
|
+
kind: 'array',
|
|
80
|
+
itemType: parsePropType(trimmed.slice(0, -2), typeAliases),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const arrayMatch = /^Array<(.+)>$/.exec(trimmed);
|
|
84
|
+
if (arrayMatch) {
|
|
85
|
+
return { kind: 'array', itemType: parsePropType(arrayMatch[1], typeAliases) };
|
|
86
|
+
}
|
|
87
|
+
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
|
|
88
|
+
const fields = parseObjectFields(trimmed.slice(1, -1), typeAliases);
|
|
89
|
+
if (fields.length > 0)
|
|
90
|
+
return { kind: 'object', fields };
|
|
91
|
+
}
|
|
92
|
+
// Try to resolve same-file type aliases (e.g. `FeatureItem` declared as
|
|
93
|
+
// `interface FeatureItem { ... }` or `type FeatureItem = { ... }` in
|
|
94
|
+
// the same source file). This is what makes `items: FeatureItem[]`
|
|
95
|
+
// extract as an inline object schema rather than an opaque reference.
|
|
96
|
+
const resolved = typeAliases.get(trimmed);
|
|
97
|
+
if (resolved && resolved !== trimmed) {
|
|
98
|
+
// Guard against self-referential aliases by removing the entry on
|
|
99
|
+
// recursion (one-pass resolution is enough for first slice).
|
|
100
|
+
const next = new Map(typeAliases);
|
|
101
|
+
next.delete(trimmed);
|
|
102
|
+
return parsePropType(resolved, next);
|
|
103
|
+
}
|
|
104
|
+
return { kind: 'reference', targetType: trimmed };
|
|
105
|
+
}
|
|
106
|
+
function stripOuterParens(s) {
|
|
107
|
+
if (s.startsWith('(') && s.endsWith(')')) {
|
|
108
|
+
let depth = 0;
|
|
109
|
+
for (let i = 0; i < s.length; i++) {
|
|
110
|
+
const c = s[i];
|
|
111
|
+
if (c === '(')
|
|
112
|
+
depth++;
|
|
113
|
+
else if (c === ')') {
|
|
114
|
+
depth--;
|
|
115
|
+
if (depth === 0 && i < s.length - 1)
|
|
116
|
+
return s;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return s.slice(1, -1).trim();
|
|
120
|
+
}
|
|
121
|
+
return s;
|
|
122
|
+
}
|
|
123
|
+
function splitTopLevel(s, delim) {
|
|
124
|
+
const delims = Array.isArray(delim) ? delim : [delim];
|
|
125
|
+
const out = [];
|
|
126
|
+
let buf = '';
|
|
127
|
+
let depth = 0;
|
|
128
|
+
let inSingle = false;
|
|
129
|
+
let inDouble = false;
|
|
130
|
+
for (let i = 0; i < s.length; i++) {
|
|
131
|
+
const c = s[i];
|
|
132
|
+
if (!inSingle && !inDouble) {
|
|
133
|
+
if (c === '<' || c === '(' || c === '[' || c === '{')
|
|
134
|
+
depth++;
|
|
135
|
+
else if (c === '>' || c === ')' || c === ']' || c === '}') {
|
|
136
|
+
// `=>` in function types (`() => void`) is NOT a bracket close.
|
|
137
|
+
// Without this guard, `onClick: () => void` would drive depth
|
|
138
|
+
// negative and corrupt the split point for the next field.
|
|
139
|
+
if (c === '>' && s[i - 1] === '=') {
|
|
140
|
+
// skip — treat as part of the arrow operator
|
|
141
|
+
}
|
|
142
|
+
else if (depth > 0) {
|
|
143
|
+
depth--;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (c === '"' && !inSingle)
|
|
148
|
+
inDouble = !inDouble;
|
|
149
|
+
else if (c === "'" && !inDouble)
|
|
150
|
+
inSingle = !inSingle;
|
|
151
|
+
if (delims.includes(c) && depth === 0 && !inSingle && !inDouble) {
|
|
152
|
+
out.push(buf);
|
|
153
|
+
buf = '';
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
buf += c;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (buf)
|
|
160
|
+
out.push(buf);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
function parseObjectFields(inner, typeAliases = new Map()) {
|
|
164
|
+
const props = [];
|
|
165
|
+
// Object-field segments inside a resolved interface body can carry
|
|
166
|
+
// leading JSDoc/line comments; strip them so `name` is just the ident.
|
|
167
|
+
// Interface bodies use newlines as separators; inline object literals
|
|
168
|
+
// use `;` or `,`. Accept any of the three as a top-level delimiter.
|
|
169
|
+
const stripped = stripComments(inner);
|
|
170
|
+
for (const segRaw of splitTopLevel(stripped, [';', '\n', ','])) {
|
|
171
|
+
const seg = segRaw.trim();
|
|
172
|
+
if (!seg)
|
|
173
|
+
continue;
|
|
174
|
+
const colon = findTopLevelChar(seg, ':');
|
|
175
|
+
if (colon === -1)
|
|
176
|
+
continue;
|
|
177
|
+
let key = seg.slice(0, colon).trim();
|
|
178
|
+
const value = seg.slice(colon + 1).trim();
|
|
179
|
+
const optional = key.endsWith('?');
|
|
180
|
+
if (optional)
|
|
181
|
+
key = key.slice(0, -1).trim();
|
|
182
|
+
if (!key)
|
|
183
|
+
continue;
|
|
184
|
+
props.push({
|
|
185
|
+
name: key,
|
|
186
|
+
type: parsePropType(value, typeAliases),
|
|
187
|
+
required: !optional,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return props;
|
|
191
|
+
}
|
|
192
|
+
function stripComments(s) {
|
|
193
|
+
let out = '';
|
|
194
|
+
let i = 0;
|
|
195
|
+
let inSingle = false;
|
|
196
|
+
let inDouble = false;
|
|
197
|
+
while (i < s.length) {
|
|
198
|
+
const c = s[i];
|
|
199
|
+
if (!inSingle && !inDouble) {
|
|
200
|
+
if (c === '/' && s[i + 1] === '/') {
|
|
201
|
+
while (i < s.length && s[i] !== '\n')
|
|
202
|
+
i++;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (c === '/' && s[i + 1] === '*') {
|
|
206
|
+
i += 2;
|
|
207
|
+
while (i < s.length && !(s[i] === '*' && s[i + 1] === '/'))
|
|
208
|
+
i++;
|
|
209
|
+
i += 2;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (c === '"' && !inSingle)
|
|
214
|
+
inDouble = !inDouble;
|
|
215
|
+
else if (c === "'" && !inDouble)
|
|
216
|
+
inSingle = !inSingle;
|
|
217
|
+
out += c;
|
|
218
|
+
i++;
|
|
219
|
+
}
|
|
220
|
+
return out;
|
|
221
|
+
}
|
|
222
|
+
function findTopLevelChar(s, char) {
|
|
223
|
+
let depth = 0;
|
|
224
|
+
let inSingle = false;
|
|
225
|
+
let inDouble = false;
|
|
226
|
+
for (let i = 0; i < s.length; i++) {
|
|
227
|
+
const c = s[i];
|
|
228
|
+
if (!inSingle && !inDouble) {
|
|
229
|
+
if (c === '<' || c === '(' || c === '[' || c === '{')
|
|
230
|
+
depth++;
|
|
231
|
+
else if (c === '>' || c === ')' || c === ']' || c === '}') {
|
|
232
|
+
if (c === '>' && s[i - 1] === '=') {
|
|
233
|
+
// `=>` arrow — not a bracket close
|
|
234
|
+
}
|
|
235
|
+
else if (depth > 0) {
|
|
236
|
+
depth--;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (c === '"' && !inSingle)
|
|
241
|
+
inDouble = !inDouble;
|
|
242
|
+
else if (c === "'" && !inDouble)
|
|
243
|
+
inSingle = !inSingle;
|
|
244
|
+
if (c === char && depth === 0 && !inSingle && !inDouble)
|
|
245
|
+
return i;
|
|
246
|
+
}
|
|
247
|
+
return -1;
|
|
248
|
+
}
|
|
249
|
+
// ─── Same-file type-alias collector ──────────────────────────────────
|
|
250
|
+
/**
|
|
251
|
+
* Scan a TypeScript source file for top-level type aliases and inline
|
|
252
|
+
* their definitions into a Map. Handles:
|
|
253
|
+
*
|
|
254
|
+
* - `export interface X { ... }`
|
|
255
|
+
* - `interface X { ... }`
|
|
256
|
+
* - `export type X = { ... }`
|
|
257
|
+
* - `export type X = "a" | "b"`
|
|
258
|
+
*
|
|
259
|
+
* Brace-matching is used to find the close of object types; for
|
|
260
|
+
* non-object `type X = ...` aliases, the value runs until the next
|
|
261
|
+
* top-level newline that isn't inside braces.
|
|
262
|
+
*
|
|
263
|
+
* This is deliberately a string-level scanner rather than a full TS
|
|
264
|
+
* Compiler API pass — the goal is "cover the 90% case" without taking a
|
|
265
|
+
* dependency on the compiler API surface, which we'd then have to keep
|
|
266
|
+
* in sync with TypeScript releases. Cross-file imports are out of scope
|
|
267
|
+
* for v0.1 and resolve to `{ kind: 'reference' }`.
|
|
268
|
+
*/
|
|
269
|
+
export function collectTypeAliases(source) {
|
|
270
|
+
const out = new Map();
|
|
271
|
+
let i = 0;
|
|
272
|
+
const len = source.length;
|
|
273
|
+
while (i < len) {
|
|
274
|
+
// Skip line comments
|
|
275
|
+
if (source[i] === '/' && source[i + 1] === '/') {
|
|
276
|
+
while (i < len && source[i] !== '\n')
|
|
277
|
+
i++;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
// Skip block comments
|
|
281
|
+
if (source[i] === '/' && source[i + 1] === '*') {
|
|
282
|
+
i += 2;
|
|
283
|
+
while (i < len && !(source[i] === '*' && source[i + 1] === '/'))
|
|
284
|
+
i++;
|
|
285
|
+
i += 2;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
// Skip string literals (very rough — we only need to avoid keywords
|
|
289
|
+
// inside strings; we don't care about preserving the content).
|
|
290
|
+
if (source[i] === '"' || source[i] === "'" || source[i] === '`') {
|
|
291
|
+
const quote = source[i];
|
|
292
|
+
i++;
|
|
293
|
+
while (i < len && source[i] !== quote) {
|
|
294
|
+
if (source[i] === '\\')
|
|
295
|
+
i++;
|
|
296
|
+
i++;
|
|
297
|
+
}
|
|
298
|
+
i++;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
// `interface Name { ... }`
|
|
302
|
+
const ifaceMatch = matchKeyword(source, i, 'interface');
|
|
303
|
+
if (ifaceMatch !== -1) {
|
|
304
|
+
const nameStart = skipWhitespace(source, ifaceMatch);
|
|
305
|
+
const nameEnd = readIdent(source, nameStart);
|
|
306
|
+
if (nameEnd > nameStart) {
|
|
307
|
+
const name = source.slice(nameStart, nameEnd);
|
|
308
|
+
// Walk forward to the body `{`, tracking bracket nesting so we
|
|
309
|
+
// don't mistake an object inside `extends Foo<{ ... }>` for the
|
|
310
|
+
// interface body. Only a `{` at depth 0 begins the body.
|
|
311
|
+
const bodyStart = findInterfaceBodyOpen(source, nameEnd);
|
|
312
|
+
if (bodyStart !== -1) {
|
|
313
|
+
const close = matchBrace(source, bodyStart);
|
|
314
|
+
if (close !== -1) {
|
|
315
|
+
out.set(name, source.slice(bodyStart, close + 1));
|
|
316
|
+
i = close + 1;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// `type Name = ...`
|
|
323
|
+
const typeMatch = matchKeyword(source, i, 'type');
|
|
324
|
+
if (typeMatch !== -1) {
|
|
325
|
+
const nameStart = skipWhitespace(source, typeMatch);
|
|
326
|
+
const nameEnd = readIdent(source, nameStart);
|
|
327
|
+
if (nameEnd > nameStart) {
|
|
328
|
+
const name = source.slice(nameStart, nameEnd);
|
|
329
|
+
let j = skipWhitespace(source, nameEnd);
|
|
330
|
+
// Skip generic params.
|
|
331
|
+
if (source[j] === '<') {
|
|
332
|
+
const close = matchBracket(source, j, '<', '>');
|
|
333
|
+
if (close !== -1)
|
|
334
|
+
j = close + 1;
|
|
335
|
+
}
|
|
336
|
+
j = skipWhitespace(source, j);
|
|
337
|
+
if (source[j] === '=') {
|
|
338
|
+
j = skipWhitespace(source, j + 1);
|
|
339
|
+
const value = readTypeRhs(source, j);
|
|
340
|
+
if (value.trim()) {
|
|
341
|
+
out.set(name, value.trim());
|
|
342
|
+
i = j + value.length;
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
i++;
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
function findInterfaceBodyOpen(source, fromIndex) {
|
|
353
|
+
// Walk forward through an interface's extends/generic clause until we
|
|
354
|
+
// land on the body-opening `{` at depth 0. Tracks `<`, `(`, `[`
|
|
355
|
+
// nesting; ignores `>` that's part of `=>` (defensive — interfaces
|
|
356
|
+
// shouldn't contain arrow types in their heritage, but stay robust).
|
|
357
|
+
let depth = 0;
|
|
358
|
+
let inSingle = false;
|
|
359
|
+
let inDouble = false;
|
|
360
|
+
for (let i = fromIndex; i < source.length; i++) {
|
|
361
|
+
const c = source[i];
|
|
362
|
+
if (!inSingle && !inDouble) {
|
|
363
|
+
if (c === '{' && depth === 0)
|
|
364
|
+
return i;
|
|
365
|
+
if (c === '<' || c === '(' || c === '[')
|
|
366
|
+
depth++;
|
|
367
|
+
else if (c === '>' || c === ')' || c === ']') {
|
|
368
|
+
if (c === '>' && source[i - 1] === '=')
|
|
369
|
+
continue;
|
|
370
|
+
if (depth > 0)
|
|
371
|
+
depth--;
|
|
372
|
+
}
|
|
373
|
+
else if (c === ';' && depth === 0) {
|
|
374
|
+
// Declaration ended without a body (e.g. `interface X;` —
|
|
375
|
+
// technically invalid but stay defensive).
|
|
376
|
+
return -1;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (c === '"' && !inSingle)
|
|
380
|
+
inDouble = !inDouble;
|
|
381
|
+
else if (c === "'" && !inDouble)
|
|
382
|
+
inSingle = !inSingle;
|
|
383
|
+
}
|
|
384
|
+
return -1;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Parse `import type? { A, B as C } from 'spec'` and
|
|
388
|
+
* `import type? Default from 'spec'` declarations into a Map keyed by
|
|
389
|
+
* the *local* name (the name as referenced in this file). The mapped
|
|
390
|
+
* value records the module specifier plus the *original* exported name
|
|
391
|
+
* (which differs when an `as` rename is used).
|
|
392
|
+
*
|
|
393
|
+
* String-level scanner, like {@link collectTypeAliases}. We don't try to
|
|
394
|
+
* cover side-effect imports (`import './style.css'`) or dynamic imports
|
|
395
|
+
* — only the declarative `import ... from '...'` form that's relevant
|
|
396
|
+
* for type resolution. Re-exports (`export { Foo } from './bar'`) are
|
|
397
|
+
* NOT followed in v0.1.
|
|
398
|
+
*/
|
|
399
|
+
export function collectImports(source) {
|
|
400
|
+
const out = new Map();
|
|
401
|
+
const len = source.length;
|
|
402
|
+
let i = 0;
|
|
403
|
+
while (i < len) {
|
|
404
|
+
if (source[i] === '/' && source[i + 1] === '/') {
|
|
405
|
+
while (i < len && source[i] !== '\n')
|
|
406
|
+
i++;
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (source[i] === '/' && source[i + 1] === '*') {
|
|
410
|
+
i += 2;
|
|
411
|
+
while (i < len && !(source[i] === '*' && source[i + 1] === '/'))
|
|
412
|
+
i++;
|
|
413
|
+
i += 2;
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (source[i] === '"' || source[i] === "'" || source[i] === '`') {
|
|
417
|
+
const quote = source[i];
|
|
418
|
+
i++;
|
|
419
|
+
while (i < len && source[i] !== quote) {
|
|
420
|
+
if (source[i] === '\\')
|
|
421
|
+
i++;
|
|
422
|
+
i++;
|
|
423
|
+
}
|
|
424
|
+
i++;
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
const importIdx = matchKeyword(source, i, 'import');
|
|
428
|
+
if (importIdx === -1) {
|
|
429
|
+
i++;
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
// Find the end of this `import ... from 'spec'` statement.
|
|
433
|
+
// Bail out cheaply if it's not a `from` import (side-effect or dynamic).
|
|
434
|
+
let j = skipWhitespace(source, importIdx);
|
|
435
|
+
// Optional `type` modifier — entire-statement type-only.
|
|
436
|
+
if (source.startsWith('type', j) && /\s/.test(source[j + 4] ?? '')) {
|
|
437
|
+
j = skipWhitespace(source, j + 4);
|
|
438
|
+
}
|
|
439
|
+
// Default import (e.g. `import Foo from '...'`)
|
|
440
|
+
let defaultLocal = null;
|
|
441
|
+
let namedStart = -1;
|
|
442
|
+
let namedEnd = -1;
|
|
443
|
+
if (source[j] !== '{' && source[j] !== '*') {
|
|
444
|
+
const defaultEnd = readIdent(source, j);
|
|
445
|
+
if (defaultEnd > j) {
|
|
446
|
+
defaultLocal = source.slice(j, defaultEnd);
|
|
447
|
+
j = skipWhitespace(source, defaultEnd);
|
|
448
|
+
if (source[j] === ',')
|
|
449
|
+
j = skipWhitespace(source, j + 1);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (source[j] === '*') {
|
|
453
|
+
// `import * as Ns from '...'` — namespace imports aren't useful
|
|
454
|
+
// for type resolution; skip to `from`.
|
|
455
|
+
while (j < len && !source.startsWith('from', j))
|
|
456
|
+
j++;
|
|
457
|
+
}
|
|
458
|
+
else if (source[j] === '{') {
|
|
459
|
+
const close = matchBracket(source, j, '{', '}');
|
|
460
|
+
if (close === -1) {
|
|
461
|
+
// matchKeyword already returns the index past `import`, so we
|
|
462
|
+
// only need to advance to importIdx (not importIdx + 'import'.length).
|
|
463
|
+
// Adding the keyword length again would skip 6 characters into
|
|
464
|
+
// whatever follows the import and could land inside a string
|
|
465
|
+
// literal, breaking subsequent imports' parsing.
|
|
466
|
+
i = importIdx;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
namedStart = j + 1;
|
|
470
|
+
namedEnd = close;
|
|
471
|
+
j = close + 1;
|
|
472
|
+
j = skipWhitespace(source, j);
|
|
473
|
+
}
|
|
474
|
+
// Expect `from 'spec'`
|
|
475
|
+
if (!source.startsWith('from', j)) {
|
|
476
|
+
i = importIdx;
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
j = skipWhitespace(source, j + 'from'.length);
|
|
480
|
+
const quote = source[j];
|
|
481
|
+
if (quote !== '"' && quote !== "'") {
|
|
482
|
+
i = importIdx;
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const specStart = j + 1;
|
|
486
|
+
let specEnd = specStart;
|
|
487
|
+
while (specEnd < len && source[specEnd] !== quote) {
|
|
488
|
+
if (source[specEnd] === '\\')
|
|
489
|
+
specEnd++;
|
|
490
|
+
specEnd++;
|
|
491
|
+
}
|
|
492
|
+
const moduleSpec = source.slice(specStart, specEnd);
|
|
493
|
+
if (defaultLocal) {
|
|
494
|
+
out.set(defaultLocal, { module: moduleSpec, sourceName: 'default' });
|
|
495
|
+
}
|
|
496
|
+
if (namedStart !== -1) {
|
|
497
|
+
const namedSegment = source.slice(namedStart, namedEnd);
|
|
498
|
+
for (const partRaw of splitTopLevel(namedSegment, [','])) {
|
|
499
|
+
const part = stripComments(partRaw).trim();
|
|
500
|
+
if (!part)
|
|
501
|
+
continue;
|
|
502
|
+
// Skip per-import `type` modifier on individual specifiers.
|
|
503
|
+
let head = part;
|
|
504
|
+
if (head.startsWith('type '))
|
|
505
|
+
head = head.slice(5).trim();
|
|
506
|
+
// Format: `Foo` OR `Foo as Bar`
|
|
507
|
+
const asMatch = /^([\w$]+)\s+as\s+([\w$]+)$/.exec(head);
|
|
508
|
+
if (asMatch) {
|
|
509
|
+
out.set(asMatch[2], { module: moduleSpec, sourceName: asMatch[1] });
|
|
510
|
+
}
|
|
511
|
+
else if (/^[\w$]+$/.test(head)) {
|
|
512
|
+
out.set(head, { module: moduleSpec, sourceName: head });
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
i = specEnd + 1;
|
|
517
|
+
}
|
|
518
|
+
return out;
|
|
519
|
+
}
|
|
520
|
+
function isRelativeImport(spec) {
|
|
521
|
+
return spec.startsWith('./') || spec.startsWith('../') || spec.startsWith('/');
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Resolve an import specifier against the importing file's directory.
|
|
525
|
+
* Tries `.tsx`, `.ts`, `/index.tsx`, `/index.ts` in order. Returns the
|
|
526
|
+
* absolute path on success, `null` if the file can't be located.
|
|
527
|
+
*
|
|
528
|
+
* Non-relative imports (`@/foo`, `package-name`) are not resolved in
|
|
529
|
+
* v0.1 — they require tsconfig path support and a node_modules walker
|
|
530
|
+
* respectively. PR #3 of the Phase 4 roadmap adds tsconfig path
|
|
531
|
+
* resolution; node_modules types stay out of scope because the typical
|
|
532
|
+
* CMS content shape never touches them.
|
|
533
|
+
*/
|
|
534
|
+
export function resolveImportPath(fromFile, importSpec, tsconfig) {
|
|
535
|
+
// tsconfig path aliases get tried before relative resolution because
|
|
536
|
+
// a relative spec is always relative; an alias-looking spec is
|
|
537
|
+
// unambiguous. Relative imports skip the alias check entirely.
|
|
538
|
+
if (!isRelativeImport(importSpec)) {
|
|
539
|
+
if (!tsconfig)
|
|
540
|
+
return null;
|
|
541
|
+
for (const base of resolveTsconfigPath(tsconfig, importSpec)) {
|
|
542
|
+
const hit = probeCandidatesForBase(base, importSpec);
|
|
543
|
+
if (hit)
|
|
544
|
+
return hit;
|
|
545
|
+
}
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
const baseDir = dirname(fromFile);
|
|
549
|
+
const target = resolve(baseDir, importSpec);
|
|
550
|
+
const hit = probeCandidatesForBase(target, importSpec);
|
|
551
|
+
return hit;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Apply the same extension-resolution rules to a candidate base path
|
|
555
|
+
* (without extension) that we previously applied inline. Exposed so
|
|
556
|
+
* tsconfig path resolution and relative resolution share one
|
|
557
|
+
* implementation.
|
|
558
|
+
*/
|
|
559
|
+
function probeCandidatesForBase(target, importSpec) {
|
|
560
|
+
const candidates = [];
|
|
561
|
+
const ext = extname(importSpec);
|
|
562
|
+
// TypeScript's NodeNext / ESM resolution requires `.js` extensions on
|
|
563
|
+
// relative imports even when the source is `.ts`/`.tsx`. We honor
|
|
564
|
+
// that by mapping `.js` → `.ts`/`.tsx` before checking disk.
|
|
565
|
+
if (ext === '.js') {
|
|
566
|
+
const stem = target.endsWith('.js') ? target.slice(0, -3) : target;
|
|
567
|
+
candidates.push(stem + '.tsx', stem + '.ts', target);
|
|
568
|
+
}
|
|
569
|
+
else if (ext === '.jsx') {
|
|
570
|
+
const stem = target.endsWith('.jsx') ? target.slice(0, -4) : target;
|
|
571
|
+
candidates.push(stem + '.tsx', stem + '.ts', target);
|
|
572
|
+
}
|
|
573
|
+
else if (ext !== '') {
|
|
574
|
+
// Spec carried a non-.js extension — try the literal path first.
|
|
575
|
+
candidates.push(target);
|
|
576
|
+
candidates.push(target + '.tsx', target + '.ts');
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
candidates.push(target + '.tsx', target + '.ts', join(target, 'index.tsx'), join(target, 'index.ts'));
|
|
580
|
+
}
|
|
581
|
+
for (const candidate of candidates) {
|
|
582
|
+
if (existsSync(candidate))
|
|
583
|
+
return candidate;
|
|
584
|
+
}
|
|
585
|
+
return null;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Build the alias map for a source file, walking same-file aliases
|
|
589
|
+
* first and then pulling in cross-file aliases via {@link collectImports}
|
|
590
|
+
* + {@link resolveImportPath}. The `cache` Map dedupes file reads
|
|
591
|
+
* within a single extraction run; `visited` provides cycle detection.
|
|
592
|
+
*
|
|
593
|
+
* Returns a Map keyed by the *local* name (the name as referenced in
|
|
594
|
+
* `rootFile`). Aliases imported under `as` aliases are stored under
|
|
595
|
+
* the local alias, so `parsePropType` resolves them correctly without
|
|
596
|
+
* extra logic.
|
|
597
|
+
*/
|
|
598
|
+
export function buildAliasContext(rootFile, cache = new Map(), visited = new Set(), tsconfig) {
|
|
599
|
+
if (visited.has(rootFile))
|
|
600
|
+
return new Map();
|
|
601
|
+
visited.add(rootFile);
|
|
602
|
+
let context = cache.get(rootFile);
|
|
603
|
+
if (!context) {
|
|
604
|
+
let source;
|
|
605
|
+
try {
|
|
606
|
+
source = readFileSync(rootFile, 'utf-8');
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
return new Map();
|
|
610
|
+
}
|
|
611
|
+
context = {
|
|
612
|
+
aliases: collectTypeAliases(source),
|
|
613
|
+
imports: collectImports(source),
|
|
614
|
+
};
|
|
615
|
+
cache.set(rootFile, context);
|
|
616
|
+
}
|
|
617
|
+
// Start with same-file aliases — they take priority over imports
|
|
618
|
+
// with the same local name (TypeScript would have errored at compile
|
|
619
|
+
// time on the collision, but stay defensive).
|
|
620
|
+
const out = new Map(context.aliases);
|
|
621
|
+
for (const [localName, ref] of context.imports) {
|
|
622
|
+
if (out.has(localName))
|
|
623
|
+
continue;
|
|
624
|
+
// Allow either relative imports or tsconfig path aliases. Non-
|
|
625
|
+
// relative specs that don't match any path alias are treated as
|
|
626
|
+
// external (node_modules) and skipped.
|
|
627
|
+
const importedFile = resolveImportPath(rootFile, ref.module, tsconfig);
|
|
628
|
+
if (!importedFile)
|
|
629
|
+
continue;
|
|
630
|
+
// Recursively get the imported file's aliases. Pass a *copy* of
|
|
631
|
+
// visited so siblings don't see each other's visit (the cycle we
|
|
632
|
+
// care about is purely ancestral).
|
|
633
|
+
const childAliases = buildAliasContext(importedFile, cache, new Set(visited), tsconfig);
|
|
634
|
+
const sourceAlias = childAliases.get(ref.sourceName);
|
|
635
|
+
if (sourceAlias)
|
|
636
|
+
out.set(localName, sourceAlias);
|
|
637
|
+
}
|
|
638
|
+
return out;
|
|
639
|
+
}
|
|
640
|
+
function matchKeyword(source, i, keyword) {
|
|
641
|
+
// Returns the index just past `keyword` if it's a standalone token at
|
|
642
|
+
// `i` (preceded by start-of-input or whitespace + optional `export`),
|
|
643
|
+
// otherwise -1.
|
|
644
|
+
const prevChar = i === 0 ? '' : source[i - 1];
|
|
645
|
+
if (prevChar && /\w/.test(prevChar))
|
|
646
|
+
return -1;
|
|
647
|
+
let j = i;
|
|
648
|
+
if (source.startsWith('export', j)) {
|
|
649
|
+
j = skipWhitespace(source, j + 'export'.length);
|
|
650
|
+
}
|
|
651
|
+
if (!source.startsWith(keyword, j))
|
|
652
|
+
return -1;
|
|
653
|
+
const nextChar = source[j + keyword.length];
|
|
654
|
+
if (nextChar && /\w/.test(nextChar))
|
|
655
|
+
return -1;
|
|
656
|
+
return j + keyword.length;
|
|
657
|
+
}
|
|
658
|
+
function skipWhitespace(source, i) {
|
|
659
|
+
while (i < source.length && /\s/.test(source[i]))
|
|
660
|
+
i++;
|
|
661
|
+
return i;
|
|
662
|
+
}
|
|
663
|
+
function readIdent(source, i) {
|
|
664
|
+
let j = i;
|
|
665
|
+
while (j < source.length && /[\w$]/.test(source[j]))
|
|
666
|
+
j++;
|
|
667
|
+
return j;
|
|
668
|
+
}
|
|
669
|
+
function matchBrace(source, openIndex) {
|
|
670
|
+
return matchBracket(source, openIndex, '{', '}');
|
|
671
|
+
}
|
|
672
|
+
function matchBracket(source, openIndex, open, close) {
|
|
673
|
+
let depth = 0;
|
|
674
|
+
let inSingle = false;
|
|
675
|
+
let inDouble = false;
|
|
676
|
+
let inTemplate = false;
|
|
677
|
+
for (let i = openIndex; i < source.length; i++) {
|
|
678
|
+
const c = source[i];
|
|
679
|
+
if (!inSingle && !inDouble && !inTemplate) {
|
|
680
|
+
if (c === '"') {
|
|
681
|
+
inDouble = true;
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
if (c === "'") {
|
|
685
|
+
inSingle = true;
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
if (c === '`') {
|
|
689
|
+
inTemplate = true;
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
if (c === open)
|
|
693
|
+
depth++;
|
|
694
|
+
else if (c === close) {
|
|
695
|
+
// When matching `<`/`>` brackets, the `>` in `=>` is the arrow
|
|
696
|
+
// operator, not a generic close. Without this guard, a type
|
|
697
|
+
// alias like `type X<T = () => void> = T` would drive depth
|
|
698
|
+
// negative inside the generic args list. Same bug class that
|
|
699
|
+
// bit the other 4 scanners; fixing here for symmetry.
|
|
700
|
+
if (close === '>' && source[i - 1] === '=')
|
|
701
|
+
continue;
|
|
702
|
+
depth--;
|
|
703
|
+
if (depth === 0)
|
|
704
|
+
return i;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
else {
|
|
708
|
+
if (inDouble && c === '"')
|
|
709
|
+
inDouble = false;
|
|
710
|
+
else if (inSingle && c === "'")
|
|
711
|
+
inSingle = false;
|
|
712
|
+
else if (inTemplate && c === '`')
|
|
713
|
+
inTemplate = false;
|
|
714
|
+
else if (c === '\\')
|
|
715
|
+
i++;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return -1;
|
|
719
|
+
}
|
|
720
|
+
function readTypeRhs(source, i) {
|
|
721
|
+
// Read until end-of-statement: `;` at depth 0, or a newline that's
|
|
722
|
+
// NOT followed by a continuation token (`|`, `&`, `,`, `(`, `?`, `[`).
|
|
723
|
+
// This is what makes multi-line union aliases work:
|
|
724
|
+
//
|
|
725
|
+
// type Alignment =
|
|
726
|
+
// | "left"
|
|
727
|
+
// | "center"
|
|
728
|
+
// | "right"
|
|
729
|
+
//
|
|
730
|
+
// The first `\n` after `=` looks like the end, but the next line
|
|
731
|
+
// starts with `|` so we keep reading. Without this, the alias map
|
|
732
|
+
// would store only `"left"`, silently corrupting downstream type
|
|
733
|
+
// resolution.
|
|
734
|
+
let depth = 0;
|
|
735
|
+
let inSingle = false;
|
|
736
|
+
let inDouble = false;
|
|
737
|
+
const start = i;
|
|
738
|
+
for (let j = i; j < source.length; j++) {
|
|
739
|
+
const c = source[j];
|
|
740
|
+
if (!inSingle && !inDouble) {
|
|
741
|
+
if (c === '{' || c === '(' || c === '[' || c === '<')
|
|
742
|
+
depth++;
|
|
743
|
+
else if (c === '}' || c === ')' || c === ']' || c === '>') {
|
|
744
|
+
// `=>` arrow operator — the `>` is not a bracket close.
|
|
745
|
+
if (c === '>' && source[j - 1] === '=') {
|
|
746
|
+
// fall through — treat as a normal character
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
if (depth === 0)
|
|
750
|
+
return source.slice(start, j);
|
|
751
|
+
depth--;
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
else if (depth === 0) {
|
|
756
|
+
if (c === ';')
|
|
757
|
+
return source.slice(start, j);
|
|
758
|
+
if (c === '\n') {
|
|
759
|
+
if (isTypeContinuation(source, j + 1))
|
|
760
|
+
continue;
|
|
761
|
+
return source.slice(start, j);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
if (c === '"' && !inSingle)
|
|
766
|
+
inDouble = !inDouble;
|
|
767
|
+
else if (c === "'" && !inDouble)
|
|
768
|
+
inSingle = !inSingle;
|
|
769
|
+
}
|
|
770
|
+
return source.slice(start);
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Returns `true` when the characters starting at `from` indicate the
|
|
774
|
+
* previous type-RHS line continues onto this one. We peek past leading
|
|
775
|
+
* whitespace and look for an operator that can only start a continuation
|
|
776
|
+
* (`|`, `&`, `,`, `?`, `[`, `(`, `{`) or a closing bracket that would
|
|
777
|
+
* mean we're still inside a structural type.
|
|
778
|
+
*
|
|
779
|
+
* `{` matters for multi-line intersection types:
|
|
780
|
+
*
|
|
781
|
+
* type X = { a: string } &
|
|
782
|
+
* { b: number }
|
|
783
|
+
*
|
|
784
|
+
* Without it, the alias collected for `X` would be just
|
|
785
|
+
* `{ a: string } &` and downstream resolution would fail.
|
|
786
|
+
*/
|
|
787
|
+
function isTypeContinuation(source, from) {
|
|
788
|
+
let i = from;
|
|
789
|
+
while (i < source.length && (source[i] === ' ' || source[i] === '\t'))
|
|
790
|
+
i++;
|
|
791
|
+
if (i >= source.length)
|
|
792
|
+
return false;
|
|
793
|
+
const c = source[i];
|
|
794
|
+
if (c === '\n')
|
|
795
|
+
return false; // blank line ends the type
|
|
796
|
+
return (c === '|' ||
|
|
797
|
+
c === '&' ||
|
|
798
|
+
c === ',' ||
|
|
799
|
+
c === '?' ||
|
|
800
|
+
c === '[' ||
|
|
801
|
+
c === '(' ||
|
|
802
|
+
c === '{' ||
|
|
803
|
+
c === ')' ||
|
|
804
|
+
c === ']' ||
|
|
805
|
+
c === '}');
|
|
806
|
+
}
|
|
807
|
+
// ─── Default value parser ────────────────────────────────────────────
|
|
808
|
+
function parseDefaultValue(raw) {
|
|
809
|
+
if (raw === undefined || raw === null)
|
|
810
|
+
return undefined;
|
|
811
|
+
if (typeof raw === 'string') {
|
|
812
|
+
const trimmed = raw.trim();
|
|
813
|
+
if (trimmed === 'true' || trimmed === 'false')
|
|
814
|
+
return trimmed === 'true';
|
|
815
|
+
if (/^-?\d+(?:\.\d+)?$/.test(trimmed))
|
|
816
|
+
return Number(trimmed);
|
|
817
|
+
const stringLit = /^"((?:[^"\\]|\\.)*)"$|^'((?:[^'\\]|\\.)*)'$/.exec(trimmed);
|
|
818
|
+
if (stringLit)
|
|
819
|
+
return stringLit[1] ?? stringLit[2] ?? '';
|
|
820
|
+
return trimmed;
|
|
821
|
+
}
|
|
822
|
+
if (typeof raw === 'number' || typeof raw === 'boolean')
|
|
823
|
+
return raw;
|
|
824
|
+
return undefined;
|
|
825
|
+
}
|
|
826
|
+
// ─── File walking ────────────────────────────────────────────────────
|
|
827
|
+
/**
|
|
828
|
+
* Convert an absolute file path into a POSIX-style path relative to
|
|
829
|
+
* the manifest's rootDir. We force forward slashes so manifests stay
|
|
830
|
+
* portable between Windows and Unix authors — otherwise a manifest
|
|
831
|
+
* generated on Windows would have backslash paths that a Linux CI run
|
|
832
|
+
* can't load as React module specifiers.
|
|
833
|
+
*/
|
|
834
|
+
function toPosixRelative(rootAbs, file) {
|
|
835
|
+
const rel = relative(rootAbs, file);
|
|
836
|
+
if (sep === '/')
|
|
837
|
+
return rel;
|
|
838
|
+
return rel.split(sep).join('/');
|
|
839
|
+
}
|
|
840
|
+
function walk(root, ext) {
|
|
841
|
+
const out = [];
|
|
842
|
+
const stack = [root];
|
|
843
|
+
while (stack.length > 0) {
|
|
844
|
+
const dir = stack.pop();
|
|
845
|
+
let entries;
|
|
846
|
+
try {
|
|
847
|
+
entries = readdirSync(dir);
|
|
848
|
+
}
|
|
849
|
+
catch {
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
for (const entry of entries) {
|
|
853
|
+
if (entry === 'node_modules' || entry === 'dist' || entry.startsWith('.'))
|
|
854
|
+
continue;
|
|
855
|
+
const full = join(dir, entry);
|
|
856
|
+
let s;
|
|
857
|
+
try {
|
|
858
|
+
s = statSync(full);
|
|
859
|
+
}
|
|
860
|
+
catch {
|
|
861
|
+
continue;
|
|
862
|
+
}
|
|
863
|
+
if (s.isDirectory()) {
|
|
864
|
+
stack.push(full);
|
|
865
|
+
}
|
|
866
|
+
else if (extname(full) === ext) {
|
|
867
|
+
out.push(full);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return out.sort();
|
|
872
|
+
}
|
|
873
|
+
function patternToExt(pattern) {
|
|
874
|
+
if (!pattern)
|
|
875
|
+
return DEFAULT_PATTERN_EXT;
|
|
876
|
+
// Convert simple `**/*.ext` patterns to a bare extension match.
|
|
877
|
+
const m = /\*\.(\w+)$/.exec(pattern);
|
|
878
|
+
if (m)
|
|
879
|
+
return `.${m[1]}`;
|
|
880
|
+
return DEFAULT_PATTERN_EXT;
|
|
881
|
+
}
|
|
882
|
+
// ─── PropItem → PropType bridge ──────────────────────────────────────
|
|
883
|
+
/**
|
|
884
|
+
* `react-docgen-typescript` represents a literal-union prop with
|
|
885
|
+
* `type.name === 'enum'` and a `type.value: { value: string }[]` array
|
|
886
|
+
* holding the literals (with `shouldExtractLiteralValuesFromEnum: true`).
|
|
887
|
+
* Honor that shape, otherwise fall back to {@link parsePropType} on
|
|
888
|
+
* `type.name`.
|
|
889
|
+
*/
|
|
890
|
+
function propItemToType(prop, aliases) {
|
|
891
|
+
const t = prop.type;
|
|
892
|
+
if (!t)
|
|
893
|
+
return { kind: 'unknown' };
|
|
894
|
+
if (t.name === 'enum' && Array.isArray(t.value)) {
|
|
895
|
+
const rawValues = t.value
|
|
896
|
+
.map((v) => (typeof v === 'object' && v && 'value' in v ? v.value : v))
|
|
897
|
+
.filter((v) => typeof v === 'string');
|
|
898
|
+
const parsed = rawValues
|
|
899
|
+
.map((raw) => parsePropType(raw))
|
|
900
|
+
.filter((p) => p.kind === 'literal');
|
|
901
|
+
if (parsed.length > 0) {
|
|
902
|
+
const values = parsed.map((p) => p.value);
|
|
903
|
+
const allStrings = values.every((v) => typeof v === 'string');
|
|
904
|
+
const allNumbers = values.every((v) => typeof v === 'number');
|
|
905
|
+
if (allStrings || allNumbers) {
|
|
906
|
+
return { kind: 'enum', values: values };
|
|
907
|
+
}
|
|
908
|
+
return {
|
|
909
|
+
kind: 'union',
|
|
910
|
+
types: parsed.map((p) => ({ kind: 'literal', value: p.value })),
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
// If literal extraction failed, fall through to raw parsing.
|
|
914
|
+
if (t.raw)
|
|
915
|
+
return parsePropType(t.raw, aliases);
|
|
916
|
+
}
|
|
917
|
+
return parsePropType(t.name, aliases);
|
|
918
|
+
}
|
|
919
|
+
// ─── Public extractor ────────────────────────────────────────────────
|
|
920
|
+
// Skip props inherited from HTML/React intrinsic interfaces so the
|
|
921
|
+
// emitted manifest reflects what the COMPONENT defines, not what its
|
|
922
|
+
// root element accepts. Without this filter, every component looks like
|
|
923
|
+
// it has 200+ ARIA/event props which is useless for the CMS form.
|
|
924
|
+
const SKIP_PROP_NAMES = new Set(['key', 'ref']);
|
|
925
|
+
export function extractManifest(opts) {
|
|
926
|
+
const rootAbs = resolve(opts.rootDir);
|
|
927
|
+
const ext = patternToExt(opts.filePattern);
|
|
928
|
+
const parserOptions = {
|
|
929
|
+
savePropValueAsString: true,
|
|
930
|
+
shouldExtractLiteralValuesFromEnum: true,
|
|
931
|
+
shouldRemoveUndefinedFromOptional: true,
|
|
932
|
+
propFilter: (prop) => {
|
|
933
|
+
// Filter out HTML intrinsic / React inherited props by checking
|
|
934
|
+
// the declaration's file path. Anything from `node_modules` or
|
|
935
|
+
// from React's own types is noise.
|
|
936
|
+
if (prop.parent?.fileName) {
|
|
937
|
+
if (prop.parent.fileName.includes('node_modules'))
|
|
938
|
+
return false;
|
|
939
|
+
if (prop.parent.fileName.endsWith('react/index.d.ts'))
|
|
940
|
+
return false;
|
|
941
|
+
}
|
|
942
|
+
if (SKIP_PROP_NAMES.has(prop.name))
|
|
943
|
+
return false;
|
|
944
|
+
return true;
|
|
945
|
+
},
|
|
946
|
+
};
|
|
947
|
+
const parser = withCompilerOptions({
|
|
948
|
+
jsx: 4 /* ReactJSX */,
|
|
949
|
+
module: 99 /* ESNext */,
|
|
950
|
+
target: 99 /* ESNext */,
|
|
951
|
+
moduleResolution: 100 /* Bundler */,
|
|
952
|
+
esModuleInterop: true,
|
|
953
|
+
allowSyntheticDefaultImports: true,
|
|
954
|
+
strict: false,
|
|
955
|
+
skipLibCheck: true,
|
|
956
|
+
}, parserOptions);
|
|
957
|
+
const files = walk(rootAbs, ext);
|
|
958
|
+
const components = [];
|
|
959
|
+
// Shared cache across the entire extraction run so a type alias
|
|
960
|
+
// declared once and imported from N components is read from disk
|
|
961
|
+
// exactly once. Cuts O(files × imports) into O(files).
|
|
962
|
+
const aliasCache = new Map();
|
|
963
|
+
// Locate the nearest tsconfig once per extraction run so the
|
|
964
|
+
// resolver can honor `compilerOptions.paths` aliases like `@/lib`
|
|
965
|
+
// in addition to relative imports. We start the search at rootAbs;
|
|
966
|
+
// most projects keep the tsconfig at or above their source root.
|
|
967
|
+
const tsconfigPath = findTsconfig(rootAbs);
|
|
968
|
+
const tsconfig = tsconfigPath ? readTsconfig(tsconfigPath) : null;
|
|
969
|
+
for (const file of files) {
|
|
970
|
+
let docs = [];
|
|
971
|
+
try {
|
|
972
|
+
docs = parser.parse(file);
|
|
973
|
+
}
|
|
974
|
+
catch {
|
|
975
|
+
// Silently skip files that don't parse — they're typically tests or
|
|
976
|
+
// non-component .tsx files. Caller can opt in to logging via the
|
|
977
|
+
// CLI's `--verbose` flag (added in the next slice).
|
|
978
|
+
continue;
|
|
979
|
+
}
|
|
980
|
+
// Build the alias context for this file — same-file `interface
|
|
981
|
+
// FeatureItem { ... }` first, then any cross-file imports it pulls
|
|
982
|
+
// in via `import type { Foo } from './types'`. That's what makes
|
|
983
|
+
// `items: FeatureItem[]` resolve to the inline shape even when
|
|
984
|
+
// FeatureItem lives in a sibling file.
|
|
985
|
+
let aliases;
|
|
986
|
+
try {
|
|
987
|
+
aliases = buildAliasContext(file, aliasCache, new Set(), tsconfig);
|
|
988
|
+
}
|
|
989
|
+
catch {
|
|
990
|
+
aliases = new Map();
|
|
991
|
+
}
|
|
992
|
+
for (const doc of docs) {
|
|
993
|
+
const include = opts.shouldInclude?.(doc.displayName, file) ?? true;
|
|
994
|
+
if (!include)
|
|
995
|
+
continue;
|
|
996
|
+
const props = [];
|
|
997
|
+
for (const propKey of Object.keys(doc.props)) {
|
|
998
|
+
const prop = doc.props[propKey];
|
|
999
|
+
const propSpec = {
|
|
1000
|
+
name: prop.name,
|
|
1001
|
+
type: propItemToType(prop, aliases),
|
|
1002
|
+
required: Boolean(prop.required),
|
|
1003
|
+
};
|
|
1004
|
+
if (prop.description)
|
|
1005
|
+
propSpec.description = prop.description;
|
|
1006
|
+
const dv = parseDefaultValue(prop.defaultValue?.value);
|
|
1007
|
+
if (dv !== undefined)
|
|
1008
|
+
propSpec.defaultValue = dv;
|
|
1009
|
+
props.push(propSpec);
|
|
1010
|
+
}
|
|
1011
|
+
components.push({
|
|
1012
|
+
name: doc.displayName,
|
|
1013
|
+
displayName: doc.displayName,
|
|
1014
|
+
filePath: toPosixRelative(rootAbs, file),
|
|
1015
|
+
...(doc.description ? { description: doc.description } : {}),
|
|
1016
|
+
props,
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
return {
|
|
1021
|
+
version: 1,
|
|
1022
|
+
generatedAt: new Date().toISOString(),
|
|
1023
|
+
rootDir: opts.rootDir,
|
|
1024
|
+
components,
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Convenience wrapper that extracts and writes the manifest to disk.
|
|
1029
|
+
* Used by the CLI but also exposed for build-tool integrations.
|
|
1030
|
+
*/
|
|
1031
|
+
export function extractToFile(opts) {
|
|
1032
|
+
const manifest = extractManifest(opts);
|
|
1033
|
+
writeFileSync(opts.outFile, JSON.stringify(manifest, null, 2), 'utf-8');
|
|
1034
|
+
return manifest;
|
|
1035
|
+
}
|
|
1036
|
+
//# sourceMappingURL=extract.js.map
|