@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/dist/paths.js ADDED
@@ -0,0 +1,288 @@
1
+ /**
2
+ * tsconfig `paths` resolution for the extractor.
3
+ *
4
+ * Scope of this module:
5
+ *
6
+ * 1. Walk up from a starting directory until a `tsconfig.json` is
7
+ * found (or filesystem root is reached).
8
+ * 2. Parse the file with a minimal JSONC stripper (line/block
9
+ * comments + trailing commas). Full JSONC is out of scope; the
10
+ * shapes tsconfig files use in practice are well-covered.
11
+ * 3. Surface `compilerOptions.baseUrl` and `compilerOptions.paths`
12
+ * as a normalized {@link TsconfigPaths} object.
13
+ * 4. Match an import specifier against the configured paths and
14
+ * return one or more candidate file paths (absolute, no
15
+ * extension) for the extractor's existing extension-probe to
16
+ * consume.
17
+ *
18
+ * Known limits (documented in `docs/component-blocks.md`):
19
+ *
20
+ * - The `extends` chain is not followed in v0.1. A tsconfig that puts
21
+ * `paths` in a base config will not be picked up; only the leaf
22
+ * tsconfig is read. Most real projects either don't extend, or
23
+ * re-declare paths in the leaf, so this covers the common case.
24
+ * - `paths` keys are matched longest-prefix-first as TS does, but only
25
+ * the simple `prefix/*` and exact-match forms are supported. Multiple
26
+ * wildcards in a single pattern (`@/**`) are intentionally rejected.
27
+ */
28
+ import { existsSync, readFileSync, statSync } from 'node:fs';
29
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
30
+ /**
31
+ * Walk up from `start` looking for a `tsconfig.json`. Returns the
32
+ * absolute path of the first one found, or `null` if we reach the
33
+ * filesystem root without finding one. Symlinks are not followed
34
+ * specially — `existsSync` reports them transparently.
35
+ */
36
+ export function findTsconfig(start) {
37
+ let current = resolve(start);
38
+ // Stop after a fixed maximum to defend against pathological inputs.
39
+ for (let i = 0; i < 64; i++) {
40
+ const candidate = join(current, 'tsconfig.json');
41
+ if (safeIsFile(candidate))
42
+ return candidate;
43
+ const parent = dirname(current);
44
+ if (parent === current)
45
+ return null;
46
+ current = parent;
47
+ }
48
+ return null;
49
+ }
50
+ function safeIsFile(path) {
51
+ if (!existsSync(path))
52
+ return false;
53
+ try {
54
+ return statSync(path).isFile();
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ /**
61
+ * Read a tsconfig file from disk and surface its `baseUrl`/`paths`.
62
+ * Returns `null` when:
63
+ * - the file can't be read or parsed,
64
+ * - the file has no `compilerOptions.paths` block,
65
+ * - or `paths` is set but `baseUrl` is missing (TS itself requires
66
+ * `baseUrl` for path resolution in TS < 4.1; we mirror that strict
67
+ * stance to avoid silently making up the wrong base directory).
68
+ */
69
+ export function readTsconfig(tsconfigPath) {
70
+ let raw;
71
+ try {
72
+ raw = readFileSync(tsconfigPath, 'utf-8');
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ let parsed;
78
+ try {
79
+ parsed = JSON.parse(stripJsonc(raw));
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ if (!isPlainObject(parsed))
85
+ return null;
86
+ const compilerOptions = parsed.compilerOptions;
87
+ if (!isPlainObject(compilerOptions))
88
+ return null;
89
+ const paths = compilerOptions.paths;
90
+ if (!isPlainObject(paths))
91
+ return null;
92
+ // baseUrl is required for paths to resolve; tsconfig dir is the
93
+ // implicit base when baseUrl is not set in TS >= 4.1 BUT the spec
94
+ // is that paths are relative to baseUrl when set, and to the tsconfig
95
+ // dir otherwise. We follow the modern convention.
96
+ const tsconfigDir = dirname(tsconfigPath);
97
+ const baseUrlRaw = compilerOptions.baseUrl;
98
+ const baseUrl = typeof baseUrlRaw === 'string' && baseUrlRaw.length > 0
99
+ ? isAbsolute(baseUrlRaw)
100
+ ? baseUrlRaw
101
+ : resolve(tsconfigDir, baseUrlRaw)
102
+ : tsconfigDir;
103
+ // Normalize the paths map: drop entries whose value isn't an array
104
+ // of strings to defend against malformed configs.
105
+ const normalizedPaths = {};
106
+ for (const [key, value] of Object.entries(paths)) {
107
+ if (typeof key !== 'string')
108
+ continue;
109
+ if (!Array.isArray(value))
110
+ continue;
111
+ const stringValues = value.filter((v) => typeof v === 'string');
112
+ if (stringValues.length === 0)
113
+ continue;
114
+ normalizedPaths[key] = stringValues;
115
+ }
116
+ if (Object.keys(normalizedPaths).length === 0)
117
+ return null;
118
+ return { baseUrl, paths: normalizedPaths, tsconfigPath };
119
+ }
120
+ /**
121
+ * Match an import specifier against the given tsconfig path mappings
122
+ * and return candidate absolute base paths (no extension). The caller
123
+ * is expected to probe these with the same extension-resolution rules
124
+ * as relative imports (`.tsx`, `.ts`, `/index.tsx`, `/index.ts`, plus
125
+ * the `.js` → `.ts`/`.tsx` rewrite).
126
+ *
127
+ * TypeScript matches paths *longest pattern first* so a specific
128
+ * pattern like `@app/widgets/*` wins over a catch-all `@app/*`. We
129
+ * mirror that ordering by sorting keys by descending pattern length.
130
+ */
131
+ export function resolveTsconfigPath(config, importSpec) {
132
+ const patterns = Object.keys(config.paths).sort((a, b) => keySpecificity(b) - keySpecificity(a));
133
+ for (const pattern of patterns) {
134
+ const captured = matchPattern(pattern, importSpec);
135
+ if (captured === null)
136
+ continue;
137
+ const replacements = config.paths[pattern];
138
+ if (!replacements)
139
+ continue;
140
+ const candidates = [];
141
+ for (const replacement of replacements) {
142
+ if (replacement.includes('*')) {
143
+ if (captured === '')
144
+ continue;
145
+ candidates.push(resolveAgainstBase(config.baseUrl, replacement.replace('*', captured)));
146
+ }
147
+ else {
148
+ candidates.push(resolveAgainstBase(config.baseUrl, replacement));
149
+ }
150
+ }
151
+ return candidates;
152
+ }
153
+ return [];
154
+ }
155
+ /**
156
+ * Match a tsconfig path pattern (prefix/star, prefix/star/suffix, or
157
+ * an exact name) against an import spec. Returns the captured
158
+ * substring for star matches, an empty string for exact matches, or
159
+ * null for no match.
160
+ *
161
+ * We deliberately reject patterns with more than one star —
162
+ * multi-glob tsconfig paths are vanishingly rare in CMS projects and
163
+ * the additional code surface isn't worth the rounding-error
164
+ * coverage.
165
+ */
166
+ function matchPattern(pattern, spec) {
167
+ const starCount = (pattern.match(/\*/g) ?? []).length;
168
+ if (starCount === 0) {
169
+ return pattern === spec ? '' : null;
170
+ }
171
+ if (starCount > 1)
172
+ return null;
173
+ const starIndex = pattern.indexOf('*');
174
+ const prefix = pattern.slice(0, starIndex);
175
+ const suffix = pattern.slice(starIndex + 1);
176
+ if (!spec.startsWith(prefix))
177
+ return null;
178
+ if (!spec.endsWith(suffix))
179
+ return null;
180
+ if (spec.length < prefix.length + suffix.length)
181
+ return null;
182
+ return spec.slice(prefix.length, spec.length - suffix.length);
183
+ }
184
+ function keySpecificity(pattern) {
185
+ // Longer non-wildcard portion => more specific. A pattern with no
186
+ // wildcard wins over any pattern with a wildcard at the same length.
187
+ const wildcardless = pattern.replace(/\*/g, '');
188
+ return wildcardless.length * 2 + (pattern.includes('*') ? 0 : 1);
189
+ }
190
+ function resolveAgainstBase(baseUrl, relative) {
191
+ return isAbsolute(relative) ? relative : resolve(baseUrl, relative);
192
+ }
193
+ /**
194
+ * Strip JSONC features (line comments, block comments, trailing
195
+ * commas) so the result can be fed to {@link JSON.parse}. This is the
196
+ * minimum subset that tsconfigs need in practice; full JSONC is out
197
+ * of scope. Strings are tracked so we don't strip comment-looking
198
+ * substrings that live inside quoted values.
199
+ */
200
+ export function stripJsonc(input) {
201
+ // First pass: remove comments, but keep string content verbatim.
202
+ let stripped = '';
203
+ let i = 0;
204
+ const len = input.length;
205
+ while (i < len) {
206
+ const c = input[i];
207
+ if (c === '"' || c === "'") {
208
+ // Copy the string verbatim, honoring backslash escapes.
209
+ const quote = c;
210
+ stripped += quote;
211
+ i++;
212
+ while (i < len) {
213
+ const ch = input[i];
214
+ stripped += ch;
215
+ if (ch === '\\' && i + 1 < len) {
216
+ stripped += input[i + 1];
217
+ i += 2;
218
+ continue;
219
+ }
220
+ i++;
221
+ if (ch === quote)
222
+ break;
223
+ }
224
+ continue;
225
+ }
226
+ if (c === '/' && input[i + 1] === '/') {
227
+ while (i < len && input[i] !== '\n')
228
+ i++;
229
+ continue;
230
+ }
231
+ if (c === '/' && input[i + 1] === '*') {
232
+ i += 2;
233
+ while (i < len - 1 && !(input[i] === '*' && input[i + 1] === '/'))
234
+ i++;
235
+ i += 2;
236
+ continue;
237
+ }
238
+ stripped += c;
239
+ i++;
240
+ }
241
+ // Second pass: drop trailing commas in objects / arrays, but only
242
+ // outside string literals. A whole-output regex would happily strip
243
+ // commas inside preserved string values like "data,}", silently
244
+ // corrupting JSON content.
245
+ let out = '';
246
+ let j = 0;
247
+ const strLen = stripped.length;
248
+ while (j < strLen) {
249
+ const c = stripped[j];
250
+ if (c === '"' || c === "'") {
251
+ const quote = c;
252
+ out += quote;
253
+ j++;
254
+ while (j < strLen) {
255
+ const ch = stripped[j];
256
+ out += ch;
257
+ if (ch === '\\' && j + 1 < strLen) {
258
+ out += stripped[j + 1];
259
+ j += 2;
260
+ continue;
261
+ }
262
+ j++;
263
+ if (ch === quote)
264
+ break;
265
+ }
266
+ continue;
267
+ }
268
+ if (c === ',') {
269
+ // Peek past whitespace; if the next non-whitespace char is a
270
+ // closing brace/bracket/paren, drop the comma.
271
+ let k = j + 1;
272
+ while (k < strLen && /\s/.test(stripped[k]))
273
+ k++;
274
+ const next = stripped[k];
275
+ if (next === '}' || next === ']' || next === ')') {
276
+ j++;
277
+ continue;
278
+ }
279
+ }
280
+ out += c;
281
+ j++;
282
+ }
283
+ return out;
284
+ }
285
+ function isPlainObject(v) {
286
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
287
+ }
288
+ //# sourceMappingURL=paths.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths.js","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC5D,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,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gBACV,CAAC;gBACD,CAAC,EAAE,CAAA;gBACH,IAAI,EAAE,KAAK,KAAK;oBAAE,MAAK;YACzB,CAAC;YACD,SAAQ;QACV,CAAC;QACD,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;YACd,6DAA6D;YAC7D,+CAA+C;YAC/C,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YACb,OAAO,CAAC,GAAG,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAE,CAAC;gBAAE,CAAC,EAAE,CAAA;YACjD,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;YACxB,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;gBACjD,CAAC,EAAE,CAAA;gBACH,SAAQ;YACV,CAAC;QACH,CAAC;QACD,GAAG,IAAI,CAAC,CAAA;QACR,CAAC,EAAE,CAAA;IACL,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,SAAS,aAAa,CAAC,CAAU;IAC/B,OAAO,CAAC,KAAK,IAAI,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;AACjE,CAAC"}
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Public types for `@prenta/component-blocks`.
3
+ *
4
+ * A {@link Manifest} is the JSON output of running the extractor against
5
+ * a directory of React components. It maps every exported component to
6
+ * its prop schema as a structured {@link PropType} tree. The CMS field
7
+ * type `componentBlock` consumes a Manifest to render the correct admin
8
+ * form, validate stored content, and surface migration prompts when a
9
+ * prop shape changes.
10
+ */
11
+ /**
12
+ * The structured shape of a single prop's type. A discriminated union by
13
+ * `kind` so consumers can render forms via exhaustive switch statements
14
+ * without falling back to `string` parsing.
15
+ *
16
+ * `kind: 'reference'` is the escape hatch for prop types that reference
17
+ * an imported declaration we couldn't follow (e.g. a type imported from
18
+ * a node_modules package). Consumers should treat it as opaque and let
19
+ * editors paste raw JSON for the time being — the next slice resolves
20
+ * common references (`ReactNode`, generic record types) explicitly.
21
+ */
22
+ export type PropType = {
23
+ kind: 'string';
24
+ } | {
25
+ kind: 'number';
26
+ } | {
27
+ kind: 'boolean';
28
+ } | {
29
+ kind: 'literal';
30
+ value: string | number | boolean;
31
+ } | {
32
+ kind: 'enum';
33
+ values: (string | number)[];
34
+ } | {
35
+ kind: 'object';
36
+ fields: PropSpec[];
37
+ } | {
38
+ kind: 'array';
39
+ itemType: PropType;
40
+ } | {
41
+ kind: 'union';
42
+ types: PropType[];
43
+ } | {
44
+ kind: 'reference';
45
+ targetType: string;
46
+ } | {
47
+ kind: 'unknown';
48
+ };
49
+ export interface PropSpec {
50
+ name: string;
51
+ type: PropType;
52
+ required: boolean;
53
+ description?: string;
54
+ /**
55
+ * The literal default value parsed from the component's destructuring
56
+ * default (e.g. `{ alignment = 'center' }`). Primitive only; we don't
57
+ * try to evaluate function defaults at extraction time.
58
+ */
59
+ defaultValue?: string | number | boolean | null;
60
+ }
61
+ export interface ComponentSpec {
62
+ /** The component's identifier as declared (e.g. `Hero`). */
63
+ name: string;
64
+ /** Component display name as seen in dev tools (often same as `name`). */
65
+ displayName: string;
66
+ /** Path to the source file the component was extracted from. */
67
+ filePath: string;
68
+ /** JSDoc summary of the component itself, if present. */
69
+ description?: string;
70
+ props: PropSpec[];
71
+ }
72
+ export interface Manifest {
73
+ /**
74
+ * Manifest schema version. Bump only on breaking shape changes; the
75
+ * CMS field type validates this on load and refuses unknown majors.
76
+ */
77
+ version: 1;
78
+ /** ISO timestamp the manifest was generated. */
79
+ generatedAt: string;
80
+ /** Absolute or repo-relative root directory the components were read from. */
81
+ rootDir: string;
82
+ components: ComponentSpec[];
83
+ }
84
+ /**
85
+ * Severity classification for a single change between two manifests.
86
+ *
87
+ * - `breaking` — saved content authored against the old manifest will
88
+ * fail validation under the new one without a migration. Common
89
+ * triggers: removed prop, type change, required-becoming-stricter
90
+ * (optional → required), enum value removed, component renamed away.
91
+ * - `safe` — adding optional capabilities (new optional prop, new
92
+ * enum value, required → optional). Existing content is still valid.
93
+ * - `unknown` — we can detect a structural difference but can't
94
+ * classify it without more information. Typically reference or union
95
+ * shapes where the resolver lost specificity.
96
+ */
97
+ export type ChangeSeverity = 'breaking' | 'safe' | 'unknown';
98
+ /**
99
+ * Granular description of a single prop transition between manifests.
100
+ * The shape is intentionally flat so a downstream `migrate` CLI can
101
+ * walk a list of these and either apply automatic fixes or surface
102
+ * them as interactive prompts.
103
+ */
104
+ export interface PropChange {
105
+ name: string;
106
+ severity: ChangeSeverity;
107
+ reason: string;
108
+ oldType?: PropType;
109
+ newType?: PropType;
110
+ oldRequired?: boolean;
111
+ newRequired?: boolean;
112
+ oldDefaultValue?: string | number | boolean | null;
113
+ newDefaultValue?: string | number | boolean | null;
114
+ }
115
+ /** Per-component diff: prop additions, removals, and shape changes. */
116
+ export interface ComponentChange {
117
+ name: string;
118
+ /** Props that exist in the new manifest but not the old. */
119
+ addedProps: PropSpec[];
120
+ /** Props that exist in the old manifest but not the new. */
121
+ removedProps: PropSpec[];
122
+ /** Props that exist in both but have changed shape/required/default. */
123
+ changedProps: PropChange[];
124
+ }
125
+ /** Top-level diff between two manifests. */
126
+ export interface ManifestDiff {
127
+ /** Components present in the new manifest but absent from the old. */
128
+ addedComponents: ComponentSpec[];
129
+ /** Components present in the old manifest but absent from the new. */
130
+ removedComponents: ComponentSpec[];
131
+ /** Components that exist in both but have prop-level differences. */
132
+ changedComponents: ComponentChange[];
133
+ /**
134
+ * The most severe per-change severity observed anywhere in the diff.
135
+ * `null` when both manifests are structurally identical. Useful for
136
+ * CI integrations that need a single yes/no answer about whether a
137
+ * deploy will require a content migration.
138
+ */
139
+ worstSeverity: ChangeSeverity | null;
140
+ }
141
+ /**
142
+ * A stored component-block value as it sits in a CMS document. Mirrors
143
+ * the shape that `cms-core`'s validator expects and that the admin form
144
+ * round-trips through; defined here so migration logic can ship in this
145
+ * package without a dependency on `cms-admin`.
146
+ */
147
+ export interface ComponentBlockValue {
148
+ component: string;
149
+ props: Record<string, unknown>;
150
+ }
151
+ /**
152
+ * What the migrator did to a single prop while bringing a stored value
153
+ * forward to the new manifest. These are *informational* — every
154
+ * action listed here was applied automatically. Anything the migrator
155
+ * couldn't resolve is surfaced as a {@link MigrationIssue} instead.
156
+ */
157
+ /**
158
+ * What the migrator did to a stored prop value. Only emitted variants
159
+ * are listed — a no-op (the stored value still validates against the
160
+ * new manifest) produces no {@link MigrationChange} at all, so
161
+ * downstream consumers writing exhaustive switches don't carry a
162
+ * permanently-dead branch.
163
+ */
164
+ export type MigrationAction = 'dropped' | 'defaulted';
165
+ export interface MigrationChange {
166
+ component: string;
167
+ prop: string;
168
+ action: MigrationAction;
169
+ oldValue?: unknown;
170
+ newValue?: unknown;
171
+ reason: string;
172
+ }
173
+ /**
174
+ * The kinds of unresolvable transitions the migrator surfaces for
175
+ * manual editor follow-up. Each is paired with a human-readable
176
+ * `reason` and (where useful) a `hint` that tells the editor exactly
177
+ * what action satisfies the gap.
178
+ */
179
+ export type MigrationIssueKind = 'component-removed' | 'component-unknown' | 'required-without-default' | 'became-required-missing' | 'type-changed' | 'enum-value-invalid' | 'unresolvable';
180
+ export interface MigrationIssue {
181
+ component: string;
182
+ prop?: string;
183
+ kind: MigrationIssueKind;
184
+ reason: string;
185
+ hint?: string;
186
+ oldValue?: unknown;
187
+ }
188
+ export interface MigrationResult {
189
+ /**
190
+ * The migrated value, or `null` when the migrator can't produce a
191
+ * meaningful new value. Two cases produce `null`:
192
+ *
193
+ * - The source component was in the old manifest but is no longer
194
+ * in the new one (`removed-component` issue).
195
+ * - The input doesn't structurally resemble a stored
196
+ * `{ component, props }` pair (`component-unknown` issue).
197
+ *
198
+ * Callers decide whether to drop the block or surface the loss to
199
+ * an editor. The accompanying {@link MigrationIssue} explains which
200
+ * case occurred.
201
+ */
202
+ value: ComponentBlockValue | null;
203
+ changes: MigrationChange[];
204
+ issues: MigrationIssue[];
205
+ }
206
+ /** Input options for {@link extractManifest}. */
207
+ export interface ExtractOptions {
208
+ /**
209
+ * Directory to scan for component source files. The extractor walks
210
+ * this directory looking for files matching {@link filePattern}.
211
+ */
212
+ rootDir: string;
213
+ /**
214
+ * Glob pattern (relative to `rootDir`) matching files to extract.
215
+ * Defaults to `**\/*.tsx`.
216
+ */
217
+ filePattern?: string;
218
+ /**
219
+ * Optional path to a `tsconfig.json` for type resolution. Defaults to
220
+ * a generated config that supports modern React + ESM.
221
+ */
222
+ tsconfigPath?: string;
223
+ /**
224
+ * Optional filter — return `false` to skip a component by name. Useful
225
+ * for excluding internal helpers that happen to be exported.
226
+ */
227
+ shouldInclude?: (componentName: string, filePath: string) => boolean;
228
+ }
229
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,MAAM,QAAQ,GAChB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;CAAE,GACrD;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;CAAE,GAC7C;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,QAAQ,EAAE,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE,GACrC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,QAAQ,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,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B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,kBAAkB,CAAA;IACxB,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED,MAAM,WAAW,eAAe;IAC9B;;;;;;;;;;;;OAYG;IACH,KAAK,EAAE,mBAAmB,GAAG,IAAI,CAAA;IACjC,OAAO,EAAE,eAAe,EAAE,CAAA;IAC1B,MAAM,EAAE,cAAc,EAAE,CAAA;CACzB;AAED,iDAAiD;AACjD,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAA;IACf;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;;OAGG;IACH,aAAa,CAAC,EAAE,CAAC,aAAa,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAA;CACrE"}
package/dist/types.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Public types for `@prenta/component-blocks`.
3
+ *
4
+ * A {@link Manifest} is the JSON output of running the extractor against
5
+ * a directory of React components. It maps every exported component to
6
+ * its prop schema as a structured {@link PropType} tree. The CMS field
7
+ * type `componentBlock` consumes a Manifest to render the correct admin
8
+ * form, validate stored content, and surface migration prompts when a
9
+ * prop shape changes.
10
+ */
11
+ export {};
12
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@prenta/component-blocks",
3
+ "version": "0.3.0",
4
+ "license": "MIT",
5
+ "description": "Extract a Manifest of React component props for use as type-aware CMS blocks.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/actuate-media/prenta.git",
9
+ "directory": "packages/component-blocks"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "bin": {
18
+ "prenta-component-blocks": "./dist/cli.js"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./cli": {
27
+ "types": "./dist/cli.d.ts",
28
+ "import": "./dist/cli.js",
29
+ "default": "./dist/cli.js"
30
+ },
31
+ "./discriminated-union": {
32
+ "types": "./dist/discriminated-union.d.ts",
33
+ "import": "./dist/discriminated-union.js",
34
+ "default": "./dist/discriminated-union.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "dependencies": {
42
+ "react-docgen-typescript": "^2.2.2"
43
+ },
44
+ "peerDependencies": {
45
+ "typescript": ">=5.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^22.0.0",
49
+ "@types/react": "^19.0.0",
50
+ "react": "^19.2.0",
51
+ "typescript": "^5.7.0",
52
+ "vitest": "^4.1.0"
53
+ },
54
+ "scripts": {
55
+ "build": "tsc --project tsconfig.json",
56
+ "dev": "tsc --project tsconfig.json --watch --preserveWatchOutput",
57
+ "type-check": "tsc --noEmit",
58
+ "test": "vitest run",
59
+ "clean": "rm -rf dist .turbo"
60
+ }
61
+ }