@intijs/cli 0.0.0-stage → 0.1.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 (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -2
  3. package/bin/inti-dev.ts +40 -0
  4. package/bin/inti.js +54 -0
  5. package/dist/commands/dev.d.ts +2 -0
  6. package/dist/commands/dev.d.ts.map +1 -0
  7. package/dist/commands/dev.js +12 -0
  8. package/dist/commands/generate.d.ts +25 -0
  9. package/dist/commands/generate.d.ts.map +1 -0
  10. package/dist/commands/generate.js +149 -0
  11. package/dist/commands/sync.d.ts +2 -0
  12. package/dist/commands/sync.d.ts.map +1 -0
  13. package/dist/commands/sync.js +114 -0
  14. package/dist/generator/ai-generator.d.ts +14 -0
  15. package/dist/generator/ai-generator.d.ts.map +1 -0
  16. package/dist/generator/ai-generator.js +55 -0
  17. package/dist/generator/component-generator.d.ts +42 -0
  18. package/dist/generator/component-generator.d.ts.map +1 -0
  19. package/dist/generator/component-generator.js +228 -0
  20. package/dist/generator/index.d.ts +5 -0
  21. package/dist/generator/index.d.ts.map +1 -0
  22. package/dist/generator/index.js +3 -0
  23. package/dist/generator/sdk-generator.d.ts +7 -0
  24. package/dist/generator/sdk-generator.d.ts.map +1 -0
  25. package/dist/generator/sdk-generator.js +114 -0
  26. package/dist/generator/types-generator.d.ts +16 -0
  27. package/dist/generator/types-generator.d.ts.map +1 -0
  28. package/dist/generator/types-generator.js +155 -0
  29. package/dist/index.d.ts +8 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +7 -0
  32. package/package.json +49 -4
  33. package/src/commands/dev.ts +14 -0
  34. package/src/commands/generate.ts +194 -0
  35. package/src/commands/sync.ts +134 -0
  36. package/src/generator/ai-generator.ts +62 -0
  37. package/src/generator/component-generator.ts +314 -0
  38. package/src/generator/index.ts +4 -0
  39. package/src/generator/types-generator.ts +167 -0
  40. package/src/index.ts +10 -0
@@ -0,0 +1,314 @@
1
+ /**
2
+ * @module component-generator
3
+ * Generates Astro component files from CMS schema introspection.
4
+ * Each collection in the schema produces a ready-to-use `.astro` component
5
+ * with typed props, semantic HTML, and Visual Bridge compatibility attributes.
6
+ */
7
+
8
+ import type { SchemaDefinition, SchemaCollection, SchemaField, FieldType } from '@intijs/core/adapters';
9
+
10
+ // ============================================
11
+ // Public Types
12
+ // ============================================
13
+
14
+ /** Options for the Astro component generator */
15
+ export interface ComponentGeneratorOptions {
16
+ /** Directory where generated components will be written */
17
+ outputDir: string;
18
+ /** Whether to overwrite existing component files (default: false) */
19
+ overwrite?: boolean;
20
+ /** Generate with or without Tailwind/UnoCSS utility classes (default: 'styled') */
21
+ style?: 'minimal' | 'styled';
22
+ /** Include a typed Astro Props interface in the frontmatter (default: true) */
23
+ includeProps?: boolean;
24
+ /** Include JSDoc comments in the generated component (default: true) */
25
+ includeJsDoc?: boolean;
26
+ }
27
+
28
+ /** Represents a single generated component and its metadata */
29
+ export interface GeneratedComponent {
30
+ /** PascalCase component name derived from the collection */
31
+ name: string;
32
+ /** Output filename, e.g. `BlogPost.astro` */
33
+ filename: string;
34
+ /** Full resolved path on disk */
35
+ path: string;
36
+ /** Complete file content ready to be written */
37
+ content: string;
38
+ /** Whether this component did not previously exist on disk */
39
+ isNew: boolean;
40
+ }
41
+
42
+ // ============================================
43
+ // Title-like field heuristics
44
+ // ============================================
45
+
46
+ /** Field names that should be rendered as headings rather than paragraphs */
47
+ const TITLE_FIELD_PATTERNS = [
48
+ 'title', 'name', 'heading', 'headline', 'subject', 'label',
49
+ ];
50
+
51
+ /**
52
+ * Determine whether a field name looks like a "title" field.
53
+ * Used to decide between `<h2>` and `<p>` for plain string fields.
54
+ */
55
+ function isTitleField(fieldName: string): boolean {
56
+ const lower = fieldName.toLowerCase();
57
+ return TITLE_FIELD_PATTERNS.some(p => lower === p || lower.endsWith(`_${p}`) || lower.endsWith(`${p}`));
58
+ }
59
+
60
+ // ============================================
61
+ // Kebab-case helper
62
+ // ============================================
63
+
64
+ /**
65
+ * Convert a PascalCase or camelCase string to kebab-case.
66
+ * e.g. `BlogPost` → `blog-post`
67
+ */
68
+ function toKebabCase(str: string): string {
69
+ return str
70
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
71
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
72
+ .toLowerCase();
73
+ }
74
+
75
+ // ============================================
76
+ // Component Content Generation
77
+ // ============================================
78
+
79
+ /**
80
+ * Generate the complete `.astro` file content for a single collection.
81
+ */
82
+ function generateComponentContent(
83
+ collection: SchemaCollection,
84
+ options: Required<Pick<ComponentGeneratorOptions, 'style' | 'includeProps' | 'includeJsDoc'>>,
85
+ ): string {
86
+ const { name, fields } = collection;
87
+ const kebab = toKebabCase(name);
88
+ const styled = options.style === 'styled';
89
+
90
+ // --- Frontmatter ---
91
+ const frontmatterLines: string[] = ['---'];
92
+
93
+ if (options.includeJsDoc) {
94
+ frontmatterLines.push(
95
+ '/**',
96
+ ` * ${name} Block Component`,
97
+ ` * Auto-generated by Inti CLI - Customize as needed`,
98
+ ` * @see https://github.com/intijs/inti/blob/main/apps/docs/src/content/docs/registry/components.mdx`,
99
+ ' */',
100
+ );
101
+ }
102
+
103
+ frontmatterLines.push(`import type { ${name} } from '../../lib/inti/inti.types';`);
104
+ frontmatterLines.push('');
105
+
106
+ if (options.includeProps) {
107
+ frontmatterLines.push('interface Props {');
108
+ if (options.includeJsDoc) frontmatterLines.push(' /** Block data from CMS */');
109
+ frontmatterLines.push(` data: ${name};`);
110
+ if (options.includeJsDoc) frontmatterLines.push(' /** Block ID for Visual Bridge */');
111
+ frontmatterLines.push(' blockId?: string;');
112
+ if (options.includeJsDoc) frontmatterLines.push(' /** Document ID in CMS */');
113
+ frontmatterLines.push(' documentId?: string;');
114
+ frontmatterLines.push('}');
115
+ frontmatterLines.push('');
116
+ }
117
+
118
+ frontmatterLines.push('const { data, blockId, documentId } = Astro.props;');
119
+ frontmatterLines.push('---');
120
+
121
+ // --- Template ---
122
+ const templateLines: string[] = [];
123
+
124
+ const sectionClass = styled
125
+ ? `class="inti-block inti-block--${kebab} p-6"`
126
+ : `class="inti-block inti-block--${kebab}"`;
127
+
128
+ templateLines.push('');
129
+ templateLines.push(`<section`);
130
+ templateLines.push(` ${sectionClass}`);
131
+ templateLines.push(` data-inti-block="${name}"`);
132
+ templateLines.push(` data-inti-block-id={blockId}`);
133
+ templateLines.push(` data-inti-document-id={documentId}`);
134
+ templateLines.push(`>`);
135
+
136
+ // Render each field
137
+ for (const field of fields) {
138
+ const fieldLines = generateFieldMarkup(field, styled);
139
+ templateLines.push(...fieldLines);
140
+ }
141
+
142
+ templateLines.push(`</section>`);
143
+
144
+ return [...frontmatterLines, ...templateLines, ''].join('\n');
145
+ }
146
+
147
+ /**
148
+ * Generate the HTML template lines for a single schema field.
149
+ */
150
+ function generateFieldMarkup(field: SchemaField, styled: boolean): string[] {
151
+ const { name: f, type, required } = field;
152
+ const lines: string[] = [];
153
+ const indent = ' ';
154
+
155
+ // Determine whether the field needs conditional rendering
156
+ const needsConditional = !required;
157
+
158
+ /**
159
+ * Wraps content lines in a conditional `{data.field && (...)}` block
160
+ * when the field is optional.
161
+ */
162
+ const wrap = (inner: string[]): string[] => {
163
+ if (!needsConditional) {
164
+ return inner.map(l => `${indent}${l}`);
165
+ }
166
+ const out: string[] = [];
167
+ out.push('');
168
+ out.push(`${indent}{data.${f} && (`);
169
+ inner.forEach(l => out.push(`${indent}${indent}${l}`));
170
+ out.push(`${indent})}`);
171
+ return out;
172
+ };
173
+
174
+ switch (type) {
175
+ case 'string':
176
+ if (isTitleField(f)) {
177
+ lines.push(...wrap([
178
+ styled
179
+ ? `<h2 class="text-3xl font-bold mb-4">{data.${f}}</h2>`
180
+ : `<h2>{data.${f}}</h2>`,
181
+ ]));
182
+ } else {
183
+ lines.push(...wrap([
184
+ styled
185
+ ? `<p class="mb-2">{data.${f}}</p>`
186
+ : `<p>{data.${f}}</p>`,
187
+ ]));
188
+ }
189
+ break;
190
+
191
+ case 'text':
192
+ case 'richtext':
193
+ lines.push(...wrap([
194
+ styled
195
+ ? `<div class="prose max-w-none" set:html={data.${f}} />`
196
+ : `<div set:html={data.${f}} />`,
197
+ ]));
198
+ break;
199
+
200
+ case 'media':
201
+ lines.push(...wrap([
202
+ styled ? `<figure class="mb-6">` : `<figure>`,
203
+ ` <img`,
204
+ ` src={data.${f}.url}`,
205
+ ` alt={data.${f}.alt || ''}`,
206
+ ` loading="lazy"`,
207
+ styled
208
+ ? ` class="w-full rounded-lg object-cover"`
209
+ : ` `,
210
+ ` />`,
211
+ `</figure>`,
212
+ ]));
213
+ break;
214
+
215
+ case 'number':
216
+ lines.push(...wrap([
217
+ styled
218
+ ? `<span class="font-mono">{data.${f}}</span>`
219
+ : `<span>{data.${f}}</span>`,
220
+ ]));
221
+ break;
222
+
223
+ case 'boolean':
224
+ lines.push('');
225
+ lines.push(`${indent}{data.${f} && (`);
226
+ lines.push(`${indent}${indent}${styled
227
+ ? `<span class="inline-block px-2 py-1 text-sm bg-green-100 text-green-800 rounded">${f}</span>`
228
+ : `<span>${f}</span>`
229
+ }`);
230
+ lines.push(`${indent})}`);
231
+ break;
232
+
233
+ case 'date':
234
+ case 'datetime':
235
+ lines.push(...wrap([
236
+ `<time`,
237
+ ` datetime={new Date(data.${f}).toISOString()}`,
238
+ styled
239
+ ? ` class="text-sm text-gray-500 mb-4 block"`
240
+ : ` `,
241
+ `>`,
242
+ ` {new Date(data.${f}).toLocaleDateString()}`,
243
+ `</time>`,
244
+ ]));
245
+ break;
246
+
247
+ case 'relation':
248
+ lines.push('');
249
+ lines.push(`${indent}<!-- TODO: Render related "${f}" data (relation) -->`);
250
+ lines.push(`${indent}<slot name="${f}" />`);
251
+ break;
252
+
253
+ case 'json':
254
+ lines.push(...wrap([
255
+ `<pre>{JSON.stringify(data.${f}, null, 2)}</pre>`,
256
+ ]));
257
+ break;
258
+
259
+ case 'blocks':
260
+ case 'component':
261
+ lines.push('');
262
+ lines.push(`${indent}<!-- TODO: Render nested "${f}" blocks/components -->`);
263
+ lines.push(`${indent}<slot name="${f}" />`);
264
+ break;
265
+
266
+ default:
267
+ lines.push(...wrap([
268
+ `<span>{data.${f}}</span>`,
269
+ ]));
270
+ break;
271
+ }
272
+
273
+ return lines;
274
+ }
275
+
276
+ // ============================================
277
+ // Public API
278
+ // ============================================
279
+
280
+ /**
281
+ * Generate Astro component files for every collection in the schema.
282
+ *
283
+ * @param schema - The introspected CMS schema definition
284
+ * @param options - Generation options (output dir, style, overwrite, etc.)
285
+ * @returns An array of {@link GeneratedComponent} objects ready for writing to disk
286
+ */
287
+ export function generateAstroComponents(
288
+ schema: SchemaDefinition,
289
+ options: ComponentGeneratorOptions,
290
+ ): GeneratedComponent[] {
291
+ const {
292
+ outputDir,
293
+ overwrite = false,
294
+ style = 'styled',
295
+ includeProps = true,
296
+ includeJsDoc = true,
297
+ } = options;
298
+
299
+ const resolvedOpts = { style, includeProps, includeJsDoc } as const;
300
+
301
+ return schema.collections.map(collection => {
302
+ const filename = `${collection.name}.astro`;
303
+ const fullPath = `${outputDir}/${filename}`;
304
+
305
+ return {
306
+ name: collection.name,
307
+ filename,
308
+ path: fullPath,
309
+ content: generateComponentContent(collection, resolvedOpts),
310
+ // `isNew` is determined at write-time by the command; default true here
311
+ isNew: true,
312
+ };
313
+ });
314
+ }
@@ -0,0 +1,4 @@
1
+ export { generateTypeDefinitions } from './types-generator.js';
2
+ export { generateAIManifest, generateMockData } from './ai-generator.js';
3
+ export { generateAstroComponents } from './component-generator.js';
4
+ export type { ComponentGeneratorOptions, GeneratedComponent } from './component-generator.js';
@@ -0,0 +1,167 @@
1
+ import type { SchemaDefinition, SchemaCollection, FieldType } from '@intijs/core/adapters';
2
+
3
+ /**
4
+ * Generates `inti.types.ts` from the CMS schema.
5
+ *
6
+ * The types describe what the adapters return, not the CMS API:
7
+ * content is always read with the adapter, and this only gives it shape.
8
+ * That is why dates are strings (they arrive as JSON) and media accept
9
+ * either an id or an object (each CMS returns one or the other).
10
+ *
11
+ * The generated file has to compile with nothing but `@intijs/core`
12
+ * installed: a test compiles it with `tsc --strict`. It used to
13
+ * reference a `MediaAsset` it neither declared nor imported, and a single
14
+ * image field was enough to break compilation.
15
+ */
16
+ export function generateTypeDefinitions(schema: SchemaDefinition): string {
17
+ const interfaces = schema.collections.map((collection) => generateCollectionInterface(collection));
18
+ const blockCollections = schema.collections.filter((collection) => collection.blockType);
19
+
20
+ return `// AUTO-GENERATED BY INTI SYNC - DO NOT EDIT
21
+ // Source: ${schema.source}
22
+ // Version: ${schema.version}
23
+ // Generated at: ${new Date().toISOString()}
24
+
25
+ import type { IntiBlock } from '@intijs/core/types';
26
+
27
+ /**
28
+ * A media item as the adapter returns it: an id or an object, depending on the
29
+ * CMS and the field's configuration. <IntiImage> accepts both.
30
+ */
31
+ export type IntiMedia =
32
+ | string
33
+ | { url?: string; alt?: string; width?: number; height?: number; [key: string]: unknown };
34
+
35
+ ${interfaces.join('\n\n')}
36
+
37
+ // ============================================
38
+ // Collection Names (for type-safe references)
39
+ // ============================================
40
+
41
+ export type CollectionName =
42
+ ${schema.collections.map((c) => ` | '${c.name}'`).join('\n') || " never"};
43
+ ${generateTypedBlocks(blockCollections)}
44
+ // ============================================
45
+ // Helper Types
46
+ // ============================================
47
+
48
+ export type WithId<T> = T & { id: string };
49
+ `;
50
+ }
51
+
52
+ /**
53
+ * Types for a page's blocks: a `type → data` map and a
54
+ * union discriminated by `type`. With it, checking `block.type` leaves
55
+ * `block.data` typed:
56
+ *
57
+ * const blocks = page.blocks as IntiTypedBlock[];
58
+ * if (blocks[0].type === 'hero') blocks[0].data.headline; // string
59
+ */
60
+ function generateTypedBlocks(collections: SchemaCollection[]): string {
61
+ if (collections.length === 0) {
62
+ return `
63
+ // This CMS does not describe its block types in the schema, so a page's
64
+ // blocks cannot be typed.
65
+ export type IntiTypedBlock = IntiBlock;
66
+ `;
67
+ }
68
+
69
+ const entries = collections
70
+ .map((collection) => ` ${JSON.stringify(collection.blockType)}: ${collection.name};`)
71
+ .join('\n');
72
+
73
+ return `
74
+ // ============================================
75
+ // Typed blocks
76
+ // ============================================
77
+
78
+ /** Data for each block type, by its \`IntiBlock.type\` */
79
+ export interface IntiBlockDataMap {
80
+ ${entries}
81
+ }
82
+
83
+ /**
84
+ * A page block with its data typed according to its \`type\`.
85
+ *
86
+ * The adapter returns \`IntiBlock[]\`; this gives it shape without changing anything at
87
+ * runtime:
88
+ *
89
+ * \`\`\`ts
90
+ * const blocks = page.blocks as IntiTypedBlock[];
91
+ * for (const block of blocks) {
92
+ * if (block.type === ${JSON.stringify(collections[0].blockType)}) block.data; // typed
93
+ * }
94
+ * \`\`\`
95
+ */
96
+ export type IntiTypedBlock = {
97
+ [K in keyof IntiBlockDataMap]: Omit<IntiBlock, 'type' | 'data'> & {
98
+ type: K;
99
+ data: IntiBlockDataMap[K];
100
+ };
101
+ }[keyof IntiBlockDataMap];
102
+ `;
103
+ }
104
+
105
+ function generateCollectionInterface(collection: SchemaCollection): string {
106
+ const fields = collection.fields.map((field) => {
107
+ const tsType = fieldTypeToTypescript(field.type);
108
+ const optional = field.required ? '' : '?';
109
+ const docs = [field.description, fieldTypeNote(field.type)].filter(Boolean).join(' — ');
110
+ const jsDoc = docs ? ` /** ${docs} */\n` : '';
111
+ return `${jsDoc} ${safeKey(field.name)}${optional}: ${tsType};`;
112
+ });
113
+
114
+ const jsDoc = collection.description ? `/**\n * ${collection.description}\n */\n` : '';
115
+
116
+ return `${jsDoc}export interface ${collection.name} {
117
+ ${fields.join('\n')}
118
+ }`;
119
+ }
120
+
121
+ /** A field name with hyphens or spaces needs quotes */
122
+ function safeKey(name: string): string {
123
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
124
+ }
125
+
126
+ function fieldTypeToTypescript(type: FieldType): string {
127
+ switch (type) {
128
+ case 'string':
129
+ case 'text':
130
+ case 'richtext':
131
+ return 'string';
132
+ case 'number':
133
+ return 'number';
134
+ case 'boolean':
135
+ return 'boolean';
136
+ // They arrive as JSON: they are ISO strings, not Date objects. Typing them as
137
+ // Date let `date.getTime()` compile, which fails at runtime.
138
+ case 'date':
139
+ case 'datetime':
140
+ return 'string';
141
+ case 'media':
142
+ return 'IntiMedia';
143
+ case 'relation':
144
+ return 'string';
145
+ case 'blocks':
146
+ return 'IntiBlock[]';
147
+ case 'json':
148
+ case 'component':
149
+ return 'Record<string, unknown>';
150
+ default:
151
+ return 'unknown';
152
+ }
153
+ }
154
+
155
+ function fieldTypeNote(type: FieldType): string | undefined {
156
+ switch (type) {
157
+ case 'date':
158
+ case 'datetime':
159
+ return 'ISO 8601';
160
+ case 'richtext':
161
+ return 'HTML';
162
+ case 'relation':
163
+ return 'id of the related entry';
164
+ default:
165
+ return undefined;
166
+ }
167
+ }
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ // CLI exports
2
+ export { syncCommand } from './commands/sync.js';
3
+ export { devCommand } from './commands/dev.js';
4
+ export { generateCommand } from './commands/generate.js';
5
+ export type { GenerateCommandOptions } from './commands/generate.js';
6
+
7
+ // Generator exports
8
+ export { generateTypeDefinitions } from './generator/index.js';
9
+ export { generateAstroComponents } from './generator/index.js';
10
+ export type { ComponentGeneratorOptions, GeneratedComponent } from './generator/index.js';