@estiva-app/ui 0.21.1 → 0.22.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.
Files changed (58) hide show
  1. package/dist/Avatar.d.ts +3 -0
  2. package/dist/Avatar.d.ts.map +1 -1
  3. package/dist/ChipInput.d.ts +3 -0
  4. package/dist/ChipInput.d.ts.map +1 -1
  5. package/dist/CommandPalette.d.ts +6 -0
  6. package/dist/CommandPalette.d.ts.map +1 -1
  7. package/dist/IdentityMenu.d.ts +3 -0
  8. package/dist/IdentityMenu.d.ts.map +1 -1
  9. package/dist/Menu.d.ts +7 -0
  10. package/dist/Menu.d.ts.map +1 -1
  11. package/dist/Skeleton.d.ts +2 -0
  12. package/dist/Skeleton.d.ts.map +1 -1
  13. package/dist/Toast.d.ts +5 -0
  14. package/dist/Toast.d.ts.map +1 -1
  15. package/dist/Toolbar.d.ts +4 -0
  16. package/dist/Toolbar.d.ts.map +1 -1
  17. package/dist/Tooltip.d.ts +4 -0
  18. package/dist/Tooltip.d.ts.map +1 -1
  19. package/dist/index.js.map +2 -2
  20. package/dist/registry/build-GOVLABI6.js +13 -0
  21. package/dist/registry/build-GOVLABI6.js.map +7 -0
  22. package/dist/registry/build.d.ts +29 -0
  23. package/dist/registry/build.d.ts.map +1 -0
  24. package/dist/registry/chunk-IJNCYVH4.js +163 -0
  25. package/dist/registry/chunk-IJNCYVH4.js.map +7 -0
  26. package/dist/registry/chunk-MRSBS5OP.js +99 -0
  27. package/dist/registry/chunk-MRSBS5OP.js.map +7 -0
  28. package/dist/registry/chunk-QDYGB3QN.js +352 -0
  29. package/dist/registry/chunk-QDYGB3QN.js.map +7 -0
  30. package/dist/registry/cli.d.ts +2 -0
  31. package/dist/registry/cli.d.ts.map +1 -0
  32. package/dist/registry/cli.js +121 -0
  33. package/dist/registry/cli.js.map +7 -0
  34. package/dist/registry/find.d.ts +43 -0
  35. package/dist/registry/find.d.ts.map +1 -0
  36. package/dist/registry/index.d.ts +14 -0
  37. package/dist/registry/index.d.ts.map +1 -0
  38. package/dist/registry/index.js +26 -0
  39. package/dist/registry/index.js.map +7 -0
  40. package/dist/registry/schema.d.ts +147 -0
  41. package/dist/registry/schema.d.ts.map +1 -0
  42. package/package.json +15 -2
  43. package/registry.json +4470 -0
  44. package/src/Avatar.tsx +3 -0
  45. package/src/ChipInput.tsx +3 -0
  46. package/src/CommandPalette.tsx +6 -0
  47. package/src/IdentityMenu.tsx +3 -0
  48. package/src/Menu.tsx +7 -0
  49. package/src/Skeleton.tsx +2 -0
  50. package/src/Toast.tsx +5 -0
  51. package/src/Toolbar.tsx +4 -0
  52. package/src/Tooltip.tsx +4 -0
  53. package/src/registry/build.ts +590 -0
  54. package/src/registry/cli.ts +141 -0
  55. package/src/registry/find.ts +195 -0
  56. package/src/registry/index.ts +24 -0
  57. package/src/registry/registry.test.ts +448 -0
  58. package/src/registry/schema.ts +268 -0
@@ -0,0 +1,590 @@
1
+ /// <reference types="node" />
2
+ /**
3
+ * The catalogue's builder (UIG-12): it reads the code and writes
4
+ * `registry.json`. Nothing here is kept by hand, and CI rebuilds it and fails
5
+ * on a difference, so the file cannot drift from what it describes.
6
+ *
7
+ * **Why a parser and not a regex.** This package's components are flat in
8
+ * `src/`, with `.tsx`, `.mdx`, `.stories.tsx` and sometimes `.test.tsx` side by
9
+ * side, and **a file is not a component**: eleven files export more than one
10
+ * name — `Menu.tsx` alone exports seven — and `Skeleton.tsx` exports no
11
+ * `Skeleton` at all. Pairing by filename gets `FieldLine`, `MenuItem` and every
12
+ * one of those wrong. The target set is what `src/index.ts` exports, read with
13
+ * TypeScript's own parser, and everything else is looked up from there.
14
+ *
15
+ * TypeScript is the app's own install, as it is for the gate pieces
16
+ * (`build.mjs`): every package this names stays external.
17
+ */
18
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
19
+ import { join } from 'node:path'
20
+ import ts from 'typescript'
21
+ import { OWNED_BEHAVIOURS } from '../eslint/index'
22
+ import { SCHEMA_VERSION, type EntryBehaviour, type EntryKind, type EntryProp, type EntryVariant, type Registry, type RegistryEntry } from './schema'
23
+
24
+ export interface BuildOptions {
25
+ /** The repository's top folder. */
26
+ root?: string
27
+ /** The name this registry's entries are recorded under. One repo per registry until UIG-13. */
28
+ repo?: string
29
+ }
30
+
31
+ /** One name as `index.ts` exports it. */
32
+ interface RawExport {
33
+ name: string
34
+ /** The sibling it comes from, without `./`. */
35
+ module: string
36
+ isType: boolean
37
+ }
38
+
39
+ /** What the parser found above and about one exported declaration. */
40
+ interface Declared {
41
+ /** The doc comment, cleaned, or `''`. */
42
+ doc: string
43
+ deprecated: boolean
44
+ /**
45
+ * Its first parameter's type, as written. Kept as the node and resolved after
46
+ * the whole file is walked: a props interface is often declared *below* the
47
+ * component that takes it.
48
+ */
49
+ propsType?: ts.TypeNode
50
+ }
51
+
52
+ const PACKAGE_IMPORT = '@estiva-app/ui'
53
+
54
+ /**
55
+ * Storybook's own `sanitize`, which is what turns a title and a story's export
56
+ * name into the id in the URL. Copied rather than imported: `storybook` is a
57
+ * dev dependency of this repo and must not become a runtime dependency of the
58
+ * builder, which apps run. A test holds this to the ids a real Storybook build
59
+ * produces.
60
+ */
61
+ function sanitize(name: string): string {
62
+ return name
63
+ .toLowerCase()
64
+ .replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/g, '-')
65
+ .replace(/-+/g, '-')
66
+ .replace(/^-+/, '')
67
+ .replace(/-+$/, '')
68
+ }
69
+
70
+ /**
71
+ * Storybook's `storyNameFromExport`, which is lodash's `startCase`: an export
72
+ * called `WithCounts` is the story "With Counts", and its id is
73
+ * `navigation-tabs--with-counts`, not `--withcounts`.
74
+ *
75
+ * Measured against a real `storybook build` (2026-09-18): without this, 11 of
76
+ * the 81 ids resolved nowhere — every export whose name is more than one word.
77
+ * Written out rather than pulled from lodash or `@storybook/csf`, neither of
78
+ * which may become a runtime dependency of a builder that apps run.
79
+ */
80
+ function storyNameFromExport(key: string): string {
81
+ return key
82
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
83
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
84
+ .replace(/([a-zA-Z])([0-9])/g, '$1 $2')
85
+ .replace(/([0-9])([a-zA-Z])/g, '$1 $2')
86
+ .replace(/[_-]+/g, ' ')
87
+ .trim()
88
+ }
89
+
90
+ const toId = (title: string, name: string) => `${sanitize(title)}--${sanitize(storyNameFromExport(name))}`
91
+
92
+ /** Read `src/index.ts`. Its `export { … } from './Sibling'` statements are the target set. */
93
+ export function readIndexExports(source: string): RawExport[] {
94
+ const file = ts.createSourceFile('index.ts', source, ts.ScriptTarget.Latest, true)
95
+ const found: RawExport[] = []
96
+ for (const statement of file.statements) {
97
+ if (!ts.isExportDeclaration(statement)) continue
98
+ const from = statement.moduleSpecifier
99
+ const clause = statement.exportClause
100
+ if (!from || !ts.isStringLiteral(from) || !clause || !ts.isNamedExports(clause)) continue
101
+ for (const element of clause.elements) {
102
+ found.push({ name: element.name.text, module: from.text.replace(/^\.\//, ''), isType: statement.isTypeOnly || element.isTypeOnly })
103
+ }
104
+ }
105
+ return found
106
+ }
107
+
108
+ /**
109
+ * The doc comment immediately above a declaration, cleaned of its markers.
110
+ * `''` when there is none.
111
+ *
112
+ * `headerPos` is where the **file's** own header comment starts, and a
113
+ * declaration never gets to claim it. Measured: `Skeleton.tsx` opens with a
114
+ * paragraph about the whole family and `export function SkeletonBar` follows it
115
+ * directly, so the bar was given the family's description — right-looking, and
116
+ * wrong. Refusing it turns that into a build failure with the export's name in
117
+ * it, which is a line somebody then writes.
118
+ */
119
+ function docAbove(source: string, node: ts.Node, headerPos: number | null = null): string {
120
+ const ranges = ts.getLeadingCommentRanges(source, node.getFullStart()) ?? []
121
+ const jsdoc = ranges.filter((range) => source.slice(range.pos, range.pos + 3) === '/**').pop()
122
+ if (!jsdoc) return ''
123
+ if (headerPos !== null && jsdoc.pos === headerPos) return ''
124
+ // Only a comment that sits against the declaration describes it: anything
125
+ // with a blank line or another statement between them is about something else.
126
+ const between = source.slice(jsdoc.end, node.getStart())
127
+ if (between.trim() !== '') return ''
128
+ return source
129
+ .slice(jsdoc.pos, jsdoc.end)
130
+ .split(/\r?\n/)
131
+ .map((line) => line.trim().replace(/^\/\*\*/, '').replace(/\*\/$/, '').replace(/^\*/, '').trim())
132
+ .join('\n')
133
+ .trim()
134
+ }
135
+
136
+ /**
137
+ * The first sentence of a block of prose, which is the purpose.
138
+ *
139
+ * A sentence ends at `.`, `!` or `?` followed by a space and something that
140
+ * starts a new one. A very short first sentence takes the next as well —
141
+ * "A list of actions from a trigger." is a purpose; "One row, two parts." is
142
+ * not, on its own.
143
+ */
144
+ function firstSentence(prose: string): string {
145
+ const flat = prose
146
+ .split(/\n\s*\n/)[0]
147
+ .split('\n')
148
+ .filter((line) => !line.trim().startsWith('@'))
149
+ .join(' ')
150
+ .replace(/\*\*/g, '')
151
+ .replace(/\s+/g, ' ')
152
+ .trim()
153
+ const parts = flat.split(/(?<=[.!?])\s+(?=[A-Z`'"‘“])/)
154
+ let line = parts[0] ?? ''
155
+ if (line.length < 40 && parts[1]) line = `${line} ${parts[1]}`
156
+ return line.trim()
157
+ }
158
+
159
+ /** A page's opening paragraph: everything between its `# Heading` and the first blank line. */
160
+ function pageOpening(mdx: string): string {
161
+ const lines = mdx.split(/\r?\n/)
162
+ const heading = lines.findIndex((line) => /^#\s+\S/.test(line))
163
+ if (heading < 0) return ''
164
+ const paragraph: string[] = []
165
+ for (const line of lines.slice(heading + 1)) {
166
+ const text = line.trim()
167
+ if (text === '') {
168
+ if (paragraph.length) break
169
+ continue
170
+ }
171
+ // A canvas, an import or the next heading: the opening paragraph is over,
172
+ // or there never was one.
173
+ if (text.startsWith('<') || text.startsWith('#')) break
174
+ paragraph.push(text)
175
+ }
176
+ return paragraph.join(' ')
177
+ }
178
+
179
+ /**
180
+ * A property's name, however it is written.
181
+ *
182
+ * **A quoted name is a name.** `'aria-label'?: string` cannot be written as an
183
+ * identifier, so a reader that takes identifiers only drops it — and with it
184
+ * every accessible name this package declares. Found by comparing against
185
+ * `react-docgen`, a parser with none of this one's assumptions: 13 props over
186
+ * 10 files, two of them required (`Reaction`, `Toolbar`).
187
+ */
188
+ function propName(member: ts.TypeElement): string | null {
189
+ if (!member.name) return null
190
+ if (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) return member.name.text
191
+ return null
192
+ }
193
+
194
+ /** A union of string literals, following one local type alias if the property points at one. */
195
+ function literalUnion(type: ts.TypeNode | undefined, aliases: Map<string, ts.TypeNode>, seen = new Set<string>()): string[] | null {
196
+ if (!type) return null
197
+ if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName)) {
198
+ const name = type.typeName.text
199
+ if (seen.has(name)) return null
200
+ seen.add(name)
201
+ const alias = aliases.get(name)
202
+ return alias ? literalUnion(alias, aliases, seen) : null
203
+ }
204
+ if (ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal)) return [type.literal.text]
205
+ if (!ts.isUnionTypeNode(type)) return null
206
+ const values: string[] = []
207
+ for (const member of type.types) {
208
+ // `'small' | 'default' | undefined` is still a set of two words.
209
+ if (member.kind === ts.SyntaxKind.UndefinedKeyword || member.kind === ts.SyntaxKind.NullKeyword) continue
210
+ const inner = literalUnion(member, aliases, seen)
211
+ if (!inner) return null
212
+ values.push(...inner)
213
+ }
214
+ return values.length > 1 ? values : null
215
+ }
216
+
217
+ /** Everything one sibling file says about the names it exports. */
218
+ /** A type’s finished props and word-choices, read by the module that declares them. */
219
+ interface Resolved {
220
+ props: EntryProp[]
221
+ variants: EntryVariant[]
222
+ }
223
+
224
+ /** Ask another file of this package for a type it declares, already resolved. */
225
+ type Sibling = (module: string, typeName: string) => Resolved | undefined
226
+
227
+ function readModule(source: string, sibling: Sibling = () => undefined) {
228
+ const file = ts.createSourceFile('module.tsx', source, ts.ScriptTarget.Latest, true)
229
+ const declarations = new Map<string, Declared>()
230
+ const aliases = new Map<string, ts.TypeNode>()
231
+ const shapes = new Map<string, ts.TypeElement[]>()
232
+ /** What each interface extends, as written — `Omit<IdentityMenuProps, 'compact'>` and all. */
233
+ const bases = new Map<string, ts.ExpressionWithTypeArguments[]>()
234
+ /** Which module each imported name came from. */
235
+ const importedFrom = new Map<string, string>()
236
+
237
+ const propsTypeOf = (parameters: readonly ts.ParameterDeclaration[]): ts.TypeNode | undefined => parameters[0]?.type
238
+
239
+ /**
240
+ * The props type of `const X = …`.
241
+ *
242
+ * A plain function expression carries it on its first parameter. `forwardRef`
243
+ * carries it as its **second type argument** and leaves the inner function's
244
+ * parameter bare — `TextInput`, whose `size` was missed until this read it.
245
+ */
246
+ const propsOfInitializer = (initializer: ts.Expression | undefined): ts.TypeNode | undefined => {
247
+ if (!initializer) return undefined
248
+ if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) return propsTypeOf(initializer.parameters)
249
+ if (ts.isCallExpression(initializer)) {
250
+ const callee = ts.isPropertyAccessExpression(initializer.expression) ? initializer.expression.name.text : ts.isIdentifier(initializer.expression) ? initializer.expression.text : ''
251
+ if (callee === 'forwardRef' && initializer.typeArguments?.[1]) return initializer.typeArguments[1]
252
+ // `memo(function X({ … }: Props) { … })` and anything else that wraps a
253
+ // function written out at the call.
254
+ const wrapped = initializer.arguments.find((argument) => ts.isArrowFunction(argument) || ts.isFunctionExpression(argument))
255
+ if (wrapped) return propsTypeOf((wrapped as ts.ArrowFunction | ts.FunctionExpression).parameters)
256
+ }
257
+ return undefined
258
+ }
259
+
260
+ // The file's header comment: the first `/**` above the first thing that is
261
+ // not an import. It belongs to the file, whatever export happens to follow it.
262
+ const opening = file.statements.find((statement) => !ts.isImportDeclaration(statement))
263
+ const headerPos = opening ? ((ts.getLeadingCommentRanges(source, opening.getFullStart()) ?? []).find((range) => source.slice(range.pos, range.pos + 3) === '/**')?.pos ?? null) : null
264
+
265
+ for (const statement of file.statements) {
266
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
267
+ const bindings = statement.importClause?.namedBindings
268
+ if (bindings && ts.isNamedImports(bindings)) {
269
+ for (const element of bindings.elements) importedFrom.set(element.name.text, statement.moduleSpecifier.text)
270
+ }
271
+ }
272
+ if (ts.isTypeAliasDeclaration(statement)) aliases.set(statement.name.text, statement.type)
273
+ if (ts.isInterfaceDeclaration(statement)) {
274
+ shapes.set(statement.name.text, [...statement.members])
275
+ // The whole clause, not its name: `extends Omit<IdentityMenuProps,
276
+ // 'compact'>` reads as the name `Omit` and loses both the type it wraps
277
+ // and the key it drops.
278
+ const extended = (statement.heritageClauses ?? []).flatMap((clause) => [...clause.types])
279
+ if (extended.length) bases.set(statement.name.text, extended)
280
+ }
281
+ if (ts.isTypeAliasDeclaration(statement) && ts.isTypeLiteralNode(statement.type)) shapes.set(statement.name.text, [...statement.type.members])
282
+
283
+ const exported = ts.canHaveModifiers(statement) && ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
284
+ if (!exported) continue
285
+ const doc = docAbove(source, statement, headerPos)
286
+ const deprecated = /(^|\n)@deprecated\b/.test(doc) || /\*\s*@deprecated\b/.test(source.slice(Math.max(0, statement.getFullStart()), statement.getStart()))
287
+
288
+ if (ts.isFunctionDeclaration(statement) && statement.name) {
289
+ declarations.set(statement.name.text, { doc, deprecated, propsType: propsTypeOf(statement.parameters) })
290
+ continue
291
+ }
292
+ if (ts.isVariableStatement(statement)) {
293
+ for (const declaration of statement.declarationList.declarations) {
294
+ if (!ts.isIdentifier(declaration.name)) continue
295
+ declarations.set(declaration.name.text, { doc, deprecated, propsType: propsOfInitializer(declaration.initializer) })
296
+ }
297
+ }
298
+ }
299
+ /**
300
+ * A type's props and its word-choices, **resolved in the file that declares
301
+ * them**.
302
+ *
303
+ * This is the whole shape of the thing, and the reason for it is a bug that
304
+ * looked like nothing: a `ts.TypeElement` carries positions into *its own*
305
+ * source text, so handing a sibling's node to this file's `getText`, `aliases`
306
+ * and `docAbove` reads the wrong file at those offsets. `ToolbarButton` came
307
+ * out with `variant: "ats over what it a"` and `children: "omeAndEndK"` —
308
+ * real prop names, and slices of another file for their types. Nothing caught
309
+ * it: the names were right, and the cross-check against `react-docgen`
310
+ * compared names.
311
+ *
312
+ * So a sibling never returns nodes. It returns finished props, read by the
313
+ * module that owns them, and this file only merges them.
314
+ */
315
+ const EMPTY: Resolved = { props: [], variants: [] }
316
+
317
+ /** The keys named by an `Omit`/`Pick` argument: `'a'` or `'a' | 'b'`. */
318
+ const keysOf = (type: ts.TypeNode | undefined): string[] | null => {
319
+ if (!type) return null
320
+ if (ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal)) return [type.literal.text]
321
+ if (!ts.isUnionTypeNode(type)) return null
322
+ const keys: string[] = []
323
+ for (const member of type.types) {
324
+ if (!ts.isLiteralTypeNode(member) || !ts.isStringLiteral(member.literal)) return null
325
+ keys.push(member.literal.text)
326
+ }
327
+ return keys
328
+ }
329
+
330
+ /** `Omit` drops the keys it names, `Pick` keeps only them. Unreadable keys change nothing. */
331
+ const narrow = (resolved: Resolved, how: 'Omit' | 'Pick', keys: string[] | null): Resolved => {
332
+ if (!keys) return resolved
333
+ const named = new Set(keys)
334
+ const keep = (name: string) => (how === 'Omit' ? !named.has(name) : named.has(name))
335
+ return { props: resolved.props.filter((prop) => keep(prop.name)), variants: resolved.variants.filter((variant) => keep(variant.prop)) }
336
+ }
337
+
338
+ /** The first of each name wins, so what a type declares itself beats what it inherits. */
339
+ const merge = (parts: Resolved[]): Resolved => {
340
+ const props: EntryProp[] = []
341
+ const variants: EntryVariant[] = []
342
+ const seenProp = new Set<string>()
343
+ const seenVariant = new Set<string>()
344
+ for (const part of parts) {
345
+ for (const prop of part.props) if (!seenProp.has(prop.name)) (seenProp.add(prop.name), props.push(prop))
346
+ for (const variant of part.variants) if (!seenVariant.has(variant.prop)) (seenVariant.add(variant.prop), variants.push(variant))
347
+ }
348
+ return { props, variants }
349
+ }
350
+
351
+ /**
352
+ * What a prop takes, in a word a person reads. The type as written is the
353
+ * fallback, not the answer: `(next: string) => void` tells a reader nothing
354
+ * they cannot guess, and "a handler" tells them what to pass.
355
+ */
356
+ const takes = (type: ts.TypeNode | undefined, values: string[] | null): string => {
357
+ if (values) return values.join(' | ')
358
+ if (!type) return 'anything'
359
+ const written = type.getText(file).replace(/\s+/g, ' ').trim()
360
+ if (written === 'boolean') return 'true/false'
361
+ if (written === 'number') return 'number'
362
+ if (written === 'string') return 'text'
363
+ if (/^React(Node|Element)\b/.test(written)) return 'anything'
364
+ if (written.includes('=>')) return 'a handler'
365
+ return written.length > 60 ? `${written.slice(0, 57)}…` : written
366
+ }
367
+
368
+ /** Members of this file, read with this file's text and aliases. */
369
+ const fromMembers = (members: readonly ts.TypeElement[]): Resolved => {
370
+ const props: EntryProp[] = []
371
+ const variants: EntryVariant[] = []
372
+ for (const member of members) {
373
+ const name = propName(member)
374
+ if (name === null || !ts.isPropertySignature(member)) continue
375
+ const values = literalUnion(member.type, aliases)
376
+ const note = firstSentence(docAbove(source, member))
377
+ props.push({ name, takes: takes(member.type, values), required: !member.questionToken, note: note || null })
378
+ if (values) variants.push({ prop: name, values })
379
+ }
380
+ return { props, variants }
381
+ }
382
+
383
+ const resolveNode = (type: ts.TypeNode | undefined, seen: Set<string>): Resolved => {
384
+ if (!type || seen.size > 12) return EMPTY
385
+ // `{ tone?: 'primary' | 'secondary' }` written out at the parameter.
386
+ if (ts.isTypeLiteralNode(type)) return fromMembers(type.members)
387
+ if (ts.isIntersectionTypeNode(type)) return merge(type.types.map((side) => resolveNode(side, seen)))
388
+ if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName)) {
389
+ const named = type.typeName.text
390
+ if (named === 'Omit' || named === 'Pick') {
391
+ return narrow(resolveNode(type.typeArguments?.[0], seen), named, keysOf(type.typeArguments?.[1]))
392
+ }
393
+ return resolveName(named, seen)
394
+ }
395
+ return EMPTY
396
+ }
397
+
398
+ /** A heritage clause is not a `TypeNode`, and carries the same `Omit<…>` shapes. */
399
+ const resolveBase = (base: ts.ExpressionWithTypeArguments, seen: Set<string>): Resolved => {
400
+ if (!ts.isIdentifier(base.expression)) return EMPTY
401
+ const named = base.expression.text
402
+ if (named === 'Omit' || named === 'Pick') {
403
+ return narrow(resolveNode(base.typeArguments?.[0], seen), named, keysOf(base.typeArguments?.[1]))
404
+ }
405
+ return resolveName(named, seen)
406
+ }
407
+
408
+ /**
409
+ * A named type: its own props, plus everything it extends **within this
410
+ * package**.
411
+ *
412
+ * It stops at React and Base UI on purpose. `ToolbarButtonProps extends
413
+ * IconButtonProps` is ours, and `variant`, `pressed` and `tooltip` are things
414
+ * `ToolbarButton` genuinely takes; `ButtonProps extends
415
+ * ComponentPropsWithRef<'button'>` is the DOM, and listing `onCopy` and
416
+ * `spellCheck` would bury the answer. The rule is where the type is declared,
417
+ * not what it is called.
418
+ */
419
+ function resolveName(name: string, seen: Set<string>): Resolved {
420
+ if (seen.has(name) || seen.size > 12) return EMPTY
421
+ seen.add(name)
422
+ const own = shapes.get(name)
423
+ if (own) {
424
+ const inherited = (bases.get(name) ?? []).map((base) => resolveBase(base, seen))
425
+ return merge([fromMembers(own), ...inherited])
426
+ }
427
+ // `type ToolbarInputProps = TextInputProps` — an alias, not an interface.
428
+ const alias = aliases.get(name)
429
+ if (alias) return resolveNode(alias, seen)
430
+ // Not declared here at all. Follow the import, but only into this package.
431
+ const from = importedFrom.get(name)
432
+ return (from?.startsWith('./') ? sibling(from.slice(2), name) : undefined) ?? EMPTY
433
+ }
434
+
435
+ /** What one declaration's first parameter takes. */
436
+ const resolve = (propsType: ts.TypeNode | undefined): Resolved => resolveNode(propsType, new Set())
437
+
438
+ return { declarations, resolve, resolveName: (name: string) => resolveName(name, new Set()) }
439
+ }
440
+
441
+ /** The `title` a stories file gives Storybook, and the stories it exports. */
442
+ function readStories(source: string): { title: string | null; stories: string[] } {
443
+ const file = ts.createSourceFile('x.stories.tsx', source, ts.ScriptTarget.Latest, true)
444
+ let title: string | null = null
445
+ const stories: string[] = []
446
+ for (const statement of file.statements) {
447
+ if (ts.isVariableStatement(statement)) {
448
+ for (const declaration of statement.declarationList.declarations) {
449
+ if (!ts.isIdentifier(declaration.name)) continue
450
+ const initializer = declaration.initializer
451
+ const object = initializer && ts.isSatisfiesExpression(initializer) ? initializer.expression : initializer
452
+ if (declaration.name.text === 'meta' && object && ts.isObjectLiteralExpression(object)) {
453
+ for (const property of object.properties) {
454
+ if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'title' && ts.isStringLiteral(property.initializer)) {
455
+ title = property.initializer.text
456
+ }
457
+ }
458
+ }
459
+ const exported = ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
460
+ if (exported && declaration.name.text !== 'meta') stories.push(declaration.name.text)
461
+ }
462
+ }
463
+ }
464
+ return { title, stories }
465
+ }
466
+
467
+ const isAllCaps = (name: string) => /^[A-Z0-9_]+$/.test(name)
468
+
469
+ /** What a name is. A constant and a function are both helpers; only a `use…` is a hook. */
470
+ function kindOf(name: string): EntryKind {
471
+ if (/^use[A-Z]/.test(name)) return 'hook'
472
+ return /^[A-Z]/.test(name) && !isAllCaps(name) ? 'component' : 'helper'
473
+ }
474
+
475
+ /** What UIG-8's enumeration says this component owns. */
476
+ function behavioursOf(name: string): EntryBehaviour[] {
477
+ return OWNED_BEHAVIOURS.filter((owned) => owned.owners.includes(name)).map((owned) => ({ id: owned.id, behaviour: owned.behaviour }))
478
+ }
479
+
480
+ /**
481
+ * Read the repository and return the catalogue.
482
+ *
483
+ * Throws on anything it cannot explain — a missing sibling, a name with no
484
+ * purpose anywhere. A registry that quietly drops what it could not read is
485
+ * worse than no registry, because a reader cannot tell the difference between
486
+ * "we have nothing for that" and "the builder gave up".
487
+ */
488
+ export function buildRegistry({ root = process.cwd(), repo = 'estiva-ui' }: BuildOptions = {}): Registry {
489
+ const src = join(root, 'src')
490
+ const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name: string; version: string }
491
+ const files = new Set(readdirSync(src))
492
+ const exported = readIndexExports(readFileSync(join(src, 'index.ts'), 'utf8'))
493
+ const values = exported.filter((entry) => !entry.isType)
494
+
495
+ type Module = ReturnType<typeof readModule> & { file: string }
496
+ const modules = new Map<string, Module>()
497
+ const moduleOf = (name: string): Module => {
498
+ const held = modules.get(name)
499
+ if (held) return held
500
+ const file = ['.tsx', '.ts'].map((extension) => `${name}${extension}`).find((candidate) => files.has(candidate))
501
+ if (!file) throw new Error(`src/index.ts exports from './${name}', which is not a file in src/`)
502
+ // The callback lets one file's props type reach a type declared in another
503
+ // — `ToolbarButtonProps extends IconButtonProps`. It is only called later,
504
+ // by which time this module is in the cache, so the recursion terminates.
505
+ const read = { ...readModule(readFileSync(join(src, file), 'utf8'), (module, typeName) => moduleOf(module).resolveName(typeName)), file: `src/${file}` }
506
+ modules.set(name, read)
507
+ return read
508
+ }
509
+
510
+ const problems: string[] = []
511
+ const entries: RegistryEntry[] = []
512
+
513
+ for (const value of values) {
514
+ const module = moduleOf(value.module)
515
+ const declared = module.declarations.get(value.name)
516
+ if (!declared) {
517
+ problems.push(`${value.name} is exported from './${value.module}' but is not declared there`)
518
+ continue
519
+ }
520
+
521
+ // A name with a page of its own takes its purpose from the page; the rest
522
+ // are documented on a sibling's page, and take it from the comment above
523
+ // the export. Every one of them has one — the build fails below if not.
524
+ const pageFile = files.has(`${value.name}.mdx`) ? `src/${value.name}.mdx` : null
525
+ const fromPage = pageFile ? firstSentence(pageOpening(readFileSync(join(root, pageFile), 'utf8'))) : ''
526
+ const fromComment = firstSentence(declared.doc)
527
+ const purpose = fromPage || fromComment
528
+ if (!purpose) {
529
+ problems.push(`${value.name} has no purpose: no opening paragraph on its page, and no doc comment above it in ${module.file}`)
530
+ continue
531
+ }
532
+
533
+ // A name with stories of its own uses them; otherwise the sibling's, which
534
+ // is the page that documents it.
535
+ const storiesFile = files.has(`${value.name}.stories.tsx`) ? `${value.name}.stories.tsx` : files.has(`${value.module}.stories.tsx`) ? `${value.module}.stories.tsx` : null
536
+ const stories = storiesFile ? readStories(readFileSync(join(src, storiesFile), 'utf8')) : { title: null, stories: [] }
537
+ const title = stories.title
538
+ const story = stories.stories.includes(value.name) ? value.name : stories.stories[0]
539
+
540
+ const shape = module.resolve(declared.propsType)
541
+
542
+ entries.push({
543
+ name: value.name,
544
+ repo,
545
+ kind: kindOf(value.name),
546
+ importPath: PACKAGE_IMPORT,
547
+ sourceFile: module.file,
548
+ purpose,
549
+ purposeFrom: fromPage ? 'page' : 'comment',
550
+ props: shape.props,
551
+ variants: shape.variants,
552
+ ownsBehaviours: behavioursOf(value.name),
553
+ status: declared.deprecated ? 'deprecated' : 'stable',
554
+ migrationStage: null,
555
+ docsId: title ? `${sanitize(title)}--docs` : null,
556
+ storyId: title && story ? toId(title, story) : null,
557
+ docPage: pageFile,
558
+ })
559
+ }
560
+
561
+ if (problems.length) throw new Error(`the registry cannot be built:\n ${problems.join('\n ')}`)
562
+
563
+ entries.sort((a, b) => a.name.localeCompare(b.name))
564
+
565
+ return {
566
+ schemaVersion: SCHEMA_VERSION,
567
+ builtFrom: {
568
+ repo,
569
+ package: manifest.name,
570
+ packageVersion: manifest.version,
571
+ exports: values.length,
572
+ typeExports: exported.length - values.length,
573
+ },
574
+ storybook: {
575
+ docsPath: '/?path=/docs/{docsId}',
576
+ storyPath: '/?path=/story/{storyId}',
577
+ devUrl: 'http://localhost:6008',
578
+ },
579
+ entries,
580
+ // Nothing is excluded: every value export is an entry, helpers and the one
581
+ // hook included, each marked by `kind`. The field stays because the count
582
+ // has to reconcile out loud — see validateRegistry.
583
+ excluded: [],
584
+ }
585
+ }
586
+
587
+ /** The committed file's text, so a check and a write produce the same bytes. */
588
+ export function serializeRegistry(registry: Registry): string {
589
+ return `${JSON.stringify(registry, null, 2)}\n`
590
+ }