@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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Discriminated-union detection for component prop types.
3
+ *
4
+ * A discriminated union (aka tagged / sum type) is the TypeScript idiom
5
+ * for "this prop is one of N shapes, distinguished by a literal tag
6
+ * field":
7
+ *
8
+ * type CTA =
9
+ * | { kind: 'link'; href: string; label: string }
10
+ * | { kind: 'modal'; modalId: string; label: string }
11
+ *
12
+ * The extractor turns this into a `{ kind: 'union', types: [...] }`
13
+ * `PropType` with two `object` variants. Without further analysis,
14
+ * the admin form has to fall back to a JSON textarea — the editor has
15
+ * to type the JSON correctly, including the discriminator. With
16
+ * detection, we can render a `<select>` for the tag and a recursive
17
+ * object form for the chosen variant's remaining fields.
18
+ *
19
+ * The detection rule is intentionally strict:
20
+ *
21
+ * 1. Every variant must be an `object` `PropType`.
22
+ * 2. There must exist a single field name common to every variant
23
+ * whose type on every variant is a `literal` of the same
24
+ * primitive flavour (string / number / boolean).
25
+ * 3. The literal values must be pairwise distinct (otherwise it isn't
26
+ * a meaningful discriminator).
27
+ * 4. The discriminator field must be required on every variant.
28
+ *
29
+ * If any rule fails, the helper returns `null` and the caller falls
30
+ * back to the JSON textarea (preserving the prior behaviour exactly).
31
+ *
32
+ * Why a separate module: the same detection is useful in three places
33
+ * — the admin form (picker), the migrator (variant transitions), and
34
+ * future diff output (variant gained / removed). Keeping it pure +
35
+ * dependency-free here keeps every consumer in sync.
36
+ */
37
+ /**
38
+ * Inspect a union PropType. Returns the detected discriminator + per-
39
+ * variant breakdown, or `null` if the union doesn't satisfy the rules
40
+ * documented at the top of this file.
41
+ *
42
+ * Idempotent and side-effect free — safe to call once per render.
43
+ */
44
+ export function detectDiscriminator(union) {
45
+ if (union.kind !== 'union')
46
+ return null;
47
+ if (union.types.length < 2)
48
+ return null;
49
+ // Every variant must be an object.
50
+ const objectVariants = [];
51
+ for (const variant of union.types) {
52
+ if (variant.kind !== 'object')
53
+ return null;
54
+ objectVariants.push(variant);
55
+ }
56
+ // Candidate fields = required-literal fields on the first variant.
57
+ // We then intersect with every other variant to find fields present
58
+ // and literal-typed on all of them.
59
+ const firstFields = objectVariants[0].fields;
60
+ const candidates = firstFields.filter((f) => f.required && f.type.kind === 'literal');
61
+ if (candidates.length === 0)
62
+ return null;
63
+ for (const candidate of candidates) {
64
+ const detection = tryField(candidate.name, objectVariants);
65
+ if (detection)
66
+ return detection;
67
+ }
68
+ return null;
69
+ }
70
+ function tryField(fieldName, variants) {
71
+ const values = [];
72
+ let kind = null;
73
+ for (const variant of variants) {
74
+ const field = variant.fields.find((f) => f.name === fieldName);
75
+ if (!field)
76
+ return null;
77
+ if (!field.required)
78
+ return null;
79
+ if (field.type.kind !== 'literal')
80
+ return null;
81
+ const flavour = typeof field.type.value;
82
+ if (flavour !== 'string' && flavour !== 'number' && flavour !== 'boolean')
83
+ return null;
84
+ if (kind === null)
85
+ kind = flavour;
86
+ else if (kind !== flavour)
87
+ return null;
88
+ values.push(field.type.value);
89
+ }
90
+ // Pairwise distinct — a non-distinct "discriminator" doesn't
91
+ // actually discriminate.
92
+ const seen = new Set();
93
+ for (const value of values) {
94
+ if (seen.has(value))
95
+ return null;
96
+ seen.add(value);
97
+ }
98
+ const detectedVariants = variants.map((variant, i) => ({
99
+ value: values[i],
100
+ type: variant,
101
+ remainingFields: variant.fields.filter((f) => f.name !== fieldName),
102
+ }));
103
+ return {
104
+ field: fieldName,
105
+ kind: kind ?? 'string',
106
+ variants: detectedVariants,
107
+ };
108
+ }
109
+ /**
110
+ * Convenience: given a value (typically `{ kind: 'link', ... }`) and a
111
+ * detected union, locate the variant whose discriminator value matches.
112
+ * Returns `null` when the value isn't an object, the discriminator
113
+ * field is missing, or no variant matches.
114
+ *
115
+ * Used by the admin form to keep the picker in sync with the stored
116
+ * value, and by the validator + migrator to route deeper checks into
117
+ * the correct variant's schema.
118
+ */
119
+ export function findVariant(value, union) {
120
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
121
+ return null;
122
+ const fieldValue = value[union.field];
123
+ if (fieldValue === undefined)
124
+ return null;
125
+ for (const variant of union.variants) {
126
+ if (variant.value === fieldValue)
127
+ return variant;
128
+ }
129
+ return null;
130
+ }
131
+ //# sourceMappingURL=discriminated-union.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discriminated-union.js","sourceRoot":"","sources":["../src/discriminated-union.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAqCH;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAe;IACjD,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,IAAI,CAAA;IACvC,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,IAAI,CAAA;IAEvC,mCAAmC;IACnC,MAAM,cAAc,GAAiD,EAAE,CAAA;IACvE,KAAK,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAClC,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QAC1C,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC9B,CAAC;IAED,mEAAmE;IACnE,oEAAoE;IACpE,oCAAoC;IACpC,MAAM,WAAW,GAAG,cAAc,CAAC,CAAC,CAAE,CAAC,MAAM,CAAA;IAC7C,MAAM,UAAU,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAA;IACrF,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IAExC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,MAAM,SAAS,GAAG,QAAQ,CAAC,SA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AAC,CAAA;IACjB,CAAC;IAED,MAAM,gBAAgB,GAA2B,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAC7E,KAAK,EAAE,MAAM,CAAC,CAAC,CAAE;QACjB,IAAI,EAAE,OAAO;QACb,eAAe,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC;KACpE,CAAC,CAAC,CAAA;IAEH,OAAO;QACL,KAAK,EAAE,SAAS;QAChB,IAAI,EAAE,IAAI,IAAI,QAAQ;QACtB,QAAQ,EAAE,gBAAgB;KAC3B,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,WAAW,CACzB,KAAc,EACd,KAAyB;IAEzB,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAA;IACpF,MAAM,UAAU,GAAI,KAAiC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;IAClE,IAAI,UAAU,KAAK,SAAS;QAAE,OAAO,IAAI,CAAA;IACzC,KAAK,MAAM,OAAO,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACrC,IAAI,OAAO,CAAC,KAAK,KAAK,UAAU;YAAE,OAAO,OAAO,CAAA;IAClD,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC"}
@@ -0,0 +1,117 @@
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 { type TsconfigPaths } from './paths.js';
23
+ import type { ExtractOptions, Manifest, PropType } from './types.js';
24
+ /**
25
+ * Parse a TypeScript type as it appears in `react-docgen-typescript`'s
26
+ * `PropItem.type.name` field into a structured {@link PropType}. The
27
+ * input is a single-line string like `string | number`, `{ a: string }`,
28
+ * `("left" | "right")`, `string[]`, etc.
29
+ *
30
+ * `typeAliases` is an optional map of type-alias names → their RHS
31
+ * source string, gathered from the same source file. When a reference
32
+ * matches an alias, it's recursively resolved. This is what makes
33
+ * `items: FeatureItem[]` extract correctly as an array of the
34
+ * FeatureItem object shape, instead of an opaque reference.
35
+ */
36
+ export declare function parsePropType(typeName: string | undefined | null, typeAliases?: Map<string, string>): PropType;
37
+ /**
38
+ * Scan a TypeScript source file for top-level type aliases and inline
39
+ * their definitions into a Map. Handles:
40
+ *
41
+ * - `export interface X { ... }`
42
+ * - `interface X { ... }`
43
+ * - `export type X = { ... }`
44
+ * - `export type X = "a" | "b"`
45
+ *
46
+ * Brace-matching is used to find the close of object types; for
47
+ * non-object `type X = ...` aliases, the value runs until the next
48
+ * top-level newline that isn't inside braces.
49
+ *
50
+ * This is deliberately a string-level scanner rather than a full TS
51
+ * Compiler API pass — the goal is "cover the 90% case" without taking a
52
+ * dependency on the compiler API surface, which we'd then have to keep
53
+ * in sync with TypeScript releases. Cross-file imports are out of scope
54
+ * for v0.1 and resolve to `{ kind: 'reference' }`.
55
+ */
56
+ export declare function collectTypeAliases(source: string): Map<string, string>;
57
+ /**
58
+ * Per-file scan output: the same-file type aliases ({@link collectTypeAliases})
59
+ * plus a map of imported type names → their module specifier and the
60
+ * name they were exported under in the source module.
61
+ */
62
+ export interface FileTypeContext {
63
+ /** Local name → RHS source text of the type. */
64
+ aliases: Map<string, string>;
65
+ /** Local name → { module: '../foo', sourceName: 'OriginalName' } */
66
+ imports: Map<string, {
67
+ module: string;
68
+ sourceName: string;
69
+ }>;
70
+ }
71
+ /**
72
+ * Parse `import type? { A, B as C } from 'spec'` and
73
+ * `import type? Default from 'spec'` declarations into a Map keyed by
74
+ * the *local* name (the name as referenced in this file). The mapped
75
+ * value records the module specifier plus the *original* exported name
76
+ * (which differs when an `as` rename is used).
77
+ *
78
+ * String-level scanner, like {@link collectTypeAliases}. We don't try to
79
+ * cover side-effect imports (`import './style.css'`) or dynamic imports
80
+ * — only the declarative `import ... from '...'` form that's relevant
81
+ * for type resolution. Re-exports (`export { Foo } from './bar'`) are
82
+ * NOT followed in v0.1.
83
+ */
84
+ export declare function collectImports(source: string): FileTypeContext['imports'];
85
+ /**
86
+ * Resolve an import specifier against the importing file's directory.
87
+ * Tries `.tsx`, `.ts`, `/index.tsx`, `/index.ts` in order. Returns the
88
+ * absolute path on success, `null` if the file can't be located.
89
+ *
90
+ * Non-relative imports (`@/foo`, `package-name`) are not resolved in
91
+ * v0.1 — they require tsconfig path support and a node_modules walker
92
+ * respectively. PR #3 of the Phase 4 roadmap adds tsconfig path
93
+ * resolution; node_modules types stay out of scope because the typical
94
+ * CMS content shape never touches them.
95
+ */
96
+ export declare function resolveImportPath(fromFile: string, importSpec: string, tsconfig?: TsconfigPaths | null): string | null;
97
+ /**
98
+ * Build the alias map for a source file, walking same-file aliases
99
+ * first and then pulling in cross-file aliases via {@link collectImports}
100
+ * + {@link resolveImportPath}. The `cache` Map dedupes file reads
101
+ * within a single extraction run; `visited` provides cycle detection.
102
+ *
103
+ * Returns a Map keyed by the *local* name (the name as referenced in
104
+ * `rootFile`). Aliases imported under `as` aliases are stored under
105
+ * the local alias, so `parsePropType` resolves them correctly without
106
+ * extra logic.
107
+ */
108
+ export declare function buildAliasContext(rootFile: string, cache?: Map<string, FileTypeContext>, visited?: Set<string>, tsconfig?: TsconfigPaths | null): Map<string, string>;
109
+ export declare function extractManifest(opts: ExtractOptions): Manifest;
110
+ /**
111
+ * Convenience wrapper that extracts and writes the manifest to disk.
112
+ * Used by the CLI but also exposed for build-tool integrations.
113
+ */
114
+ export declare function extractToFile(opts: ExtractOptions & {
115
+ outFile: string;
116
+ }): Manifest;
117
+ //# sourceMappingURL=extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract.d.ts","sourceRoot":"","sources":["../src/extract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAKH,OAAO,EAAmD,KAAK,aAAa,EAAE,MAAM,YAAY,CAAA;AAIhG,OAAO,KAAK,EAAiB,cAAc,EAAE,QAAQ,EAAY,QAAQ,EAAE,MAAM,YAAY,CAAA;AAM7F;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,EACnC,WAAW,GAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAa,GAC3C,QAAQ,CAkEV;AAuID;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAmFtE;AAgCD;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,gDAAgD;IAChD,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC5B,oEAAoE;IACpE,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAC7D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CAAC,S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