@fragments-sdk/cli 0.11.1 → 0.13.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 (89) hide show
  1. package/dist/ai-client-I6MDWNYA.js +21 -0
  2. package/dist/bin.js +419 -410
  3. package/dist/bin.js.map +1 -1
  4. package/dist/{chunk-HRFUSSZI.js → chunk-3SOAPJDX.js} +2 -2
  5. package/dist/{chunk-D5PYOXEI.js → chunk-4K7EAQ5L.js} +148 -13
  6. package/dist/{chunk-D5PYOXEI.js.map → chunk-4K7EAQ5L.js.map} +1 -1
  7. package/dist/chunk-DXX6HADE.js +443 -0
  8. package/dist/chunk-DXX6HADE.js.map +1 -0
  9. package/dist/chunk-EYXVAMEX.js +626 -0
  10. package/dist/chunk-EYXVAMEX.js.map +1 -0
  11. package/dist/{chunk-ZM4ZQZWZ.js → chunk-FO6EBJWP.js} +39 -37
  12. package/dist/chunk-FO6EBJWP.js.map +1 -0
  13. package/dist/{chunk-OQO55NKV.js → chunk-QM7SVOGF.js} +120 -12
  14. package/dist/chunk-QM7SVOGF.js.map +1 -0
  15. package/dist/{chunk-5G3VZH43.js → chunk-RF3C6LGA.js} +281 -351
  16. package/dist/chunk-RF3C6LGA.js.map +1 -0
  17. package/dist/{chunk-WXSR2II7.js → chunk-SM674YAS.js} +58 -6
  18. package/dist/chunk-SM674YAS.js.map +1 -0
  19. package/dist/chunk-SXTKFDCR.js +104 -0
  20. package/dist/chunk-SXTKFDCR.js.map +1 -0
  21. package/dist/{chunk-PW7QTQA6.js → chunk-UV5JQV3R.js} +2 -2
  22. package/dist/core/index.js +13 -1
  23. package/dist/{discovery-NEOY4MPN.js → discovery-VSGC76JN.js} +3 -3
  24. package/dist/{generate-FBHSXR3D.js → generate-QZXOXYFW.js} +4 -4
  25. package/dist/index.js +7 -6
  26. package/dist/index.js.map +1 -1
  27. package/dist/init-XK6PRUE5.js +636 -0
  28. package/dist/init-XK6PRUE5.js.map +1 -0
  29. package/dist/mcp-bin.js +2 -2
  30. package/dist/{scan-CJF2DOQW.js → scan-CHQHXWVD.js} +6 -6
  31. package/dist/scan-generate-U3RFVDTX.js +1115 -0
  32. package/dist/scan-generate-U3RFVDTX.js.map +1 -0
  33. package/dist/{service-TQYWY65E.js → service-MMEKG4MZ.js} +3 -3
  34. package/dist/{snapshot-SV2JOFZH.js → snapshot-53TUR3HW.js} +2 -2
  35. package/dist/{static-viewer-NUBFPKWH.js → static-viewer-KKCR4KXR.js} +3 -3
  36. package/dist/static-viewer-KKCR4KXR.js.map +1 -0
  37. package/dist/{test-Z5LVO724.js → test-5UCKXYSC.js} +4 -4
  38. package/dist/{tokens-CE46OTMD.js → tokens-L46MK5AW.js} +5 -5
  39. package/dist/{viewer-DLLJIMCK.js → viewer-M2EQQSGE.js} +14 -14
  40. package/dist/viewer-M2EQQSGE.js.map +1 -0
  41. package/package.json +11 -9
  42. package/src/ai-client.ts +156 -0
  43. package/src/bin.ts +99 -2
  44. package/src/build.ts +95 -33
  45. package/src/commands/__tests__/drift-sync.test.ts +252 -0
  46. package/src/commands/__tests__/scan-generate.test.ts +497 -45
  47. package/src/commands/enhance.ts +11 -35
  48. package/src/commands/govern.ts +122 -0
  49. package/src/commands/init.ts +288 -260
  50. package/src/commands/scan-generate.ts +740 -139
  51. package/src/commands/scan.ts +37 -32
  52. package/src/commands/setup.ts +143 -52
  53. package/src/commands/sync.ts +357 -0
  54. package/src/commands/validate.ts +43 -1
  55. package/src/core/component-extractor.test.ts +282 -0
  56. package/src/core/component-extractor.ts +1030 -0
  57. package/src/core/discovery.ts +93 -7
  58. package/src/service/enhance/props-extractor.ts +235 -13
  59. package/src/validators.ts +236 -0
  60. package/src/viewer/vite-plugin.ts +1 -1
  61. package/dist/chunk-5G3VZH43.js.map +0 -1
  62. package/dist/chunk-OQO55NKV.js.map +0 -1
  63. package/dist/chunk-WXSR2II7.js.map +0 -1
  64. package/dist/chunk-ZM4ZQZWZ.js.map +0 -1
  65. package/dist/init-UFGK5TCN.js +0 -867
  66. package/dist/init-UFGK5TCN.js.map +0 -1
  67. package/dist/scan-generate-SJAN5MVI.js +0 -691
  68. package/dist/scan-generate-SJAN5MVI.js.map +0 -1
  69. package/dist/viewer-DLLJIMCK.js.map +0 -1
  70. package/src/ai.ts +0 -266
  71. package/src/commands/init-framework.ts +0 -414
  72. package/src/mcp/bin.ts +0 -36
  73. package/src/migrate/bin.ts +0 -114
  74. package/src/theme/index.ts +0 -77
  75. package/src/viewer/bin.ts +0 -86
  76. package/src/viewer/cli/health.ts +0 -256
  77. package/src/viewer/cli/index.ts +0 -33
  78. package/src/viewer/cli/scan.ts +0 -124
  79. package/src/viewer/cli/utils.ts +0 -174
  80. /package/dist/{discovery-NEOY4MPN.js.map → ai-client-I6MDWNYA.js.map} +0 -0
  81. /package/dist/{chunk-HRFUSSZI.js.map → chunk-3SOAPJDX.js.map} +0 -0
  82. /package/dist/{chunk-PW7QTQA6.js.map → chunk-UV5JQV3R.js.map} +0 -0
  83. /package/dist/{scan-CJF2DOQW.js.map → discovery-VSGC76JN.js.map} +0 -0
  84. /package/dist/{generate-FBHSXR3D.js.map → generate-QZXOXYFW.js.map} +0 -0
  85. /package/dist/{service-TQYWY65E.js.map → scan-CHQHXWVD.js.map} +0 -0
  86. /package/dist/{static-viewer-NUBFPKWH.js.map → service-MMEKG4MZ.js.map} +0 -0
  87. /package/dist/{snapshot-SV2JOFZH.js.map → snapshot-53TUR3HW.js.map} +0 -0
  88. /package/dist/{test-Z5LVO724.js.map → test-5UCKXYSC.js.map} +0 -0
  89. /package/dist/{tokens-CE46OTMD.js.map → tokens-L46MK5AW.js.map} +0 -0
@@ -0,0 +1,636 @@
1
+ import { createRequire as __banner_createRequire } from 'module'; const require = __banner_createRequire(import.meta.url);
2
+ import {
3
+ addStylesImport,
4
+ addThemeProvider,
5
+ addTranspilePackages,
6
+ detectSetupFramework,
7
+ findEntryFile
8
+ } from "./chunk-DXX6HADE.js";
9
+ import "./chunk-D2CDBRNU.js";
10
+ import {
11
+ BRAND
12
+ } from "./chunk-QM7SVOGF.js";
13
+ import "./chunk-Z7EY4VHE.js";
14
+
15
+ // src/commands/init.ts
16
+ import { writeFile, mkdir, access } from "fs/promises";
17
+ import { resolve, join, relative } from "path";
18
+ import { spawn } from "child_process";
19
+ import pc from "picocolors";
20
+ import fg from "fast-glob";
21
+ async function detectProject(projectRoot) {
22
+ const configPath = join(projectRoot, BRAND.configFile);
23
+ const legacyConfigPath = join(projectRoot, BRAND.legacyConfigFile);
24
+ let hasConfig = false;
25
+ let foundConfigPath = null;
26
+ try {
27
+ await access(configPath);
28
+ hasConfig = true;
29
+ foundConfigPath = configPath;
30
+ } catch {
31
+ try {
32
+ await access(legacyConfigPath);
33
+ hasConfig = true;
34
+ foundConfigPath = legacyConfigPath;
35
+ } catch {
36
+ }
37
+ }
38
+ const storyFiles = await fg(
39
+ ["**/*.stories.tsx", "**/*.stories.ts", "**/*.stories.jsx", "**/*.stories.js"],
40
+ {
41
+ cwd: projectRoot,
42
+ ignore: ["**/node_modules/**", "**/dist/**", "**/build/**", "**/.storybook/**"]
43
+ }
44
+ );
45
+ const componentFiles = await fg(
46
+ ["**/components/**/*.tsx", "**/Components/**/*.tsx", "src/**/*.tsx"],
47
+ {
48
+ cwd: projectRoot,
49
+ ignore: [
50
+ "**/node_modules/**",
51
+ "**/dist/**",
52
+ "**/build/**",
53
+ "**/*.stories.*",
54
+ "**/*.fragment.*",
55
+ "**/*.test.*",
56
+ "**/*.spec.*",
57
+ "**/*.d.ts",
58
+ "**/index.tsx"
59
+ // Skip barrel files
60
+ ]
61
+ }
62
+ );
63
+ const nonComponentPatterns = /\.(styles|utils|helpers|constants|types|hooks|context|config|mock|fixture)\./i;
64
+ const nonComponentNames = /^(index|types|utils|helpers|constants|hooks|providers|layout|use[A-Z])/;
65
+ const likelyComponents = componentFiles.filter((f) => {
66
+ const fileName = f.split("/").pop() || "";
67
+ const baseName = fileName.replace(/\.tsx$/, "");
68
+ return !nonComponentPatterns.test(fileName) && !nonComponentNames.test(baseName);
69
+ });
70
+ let suggestedComponentPath = "src/components";
71
+ if (likelyComponents.length > 0) {
72
+ const firstComponent = likelyComponents[0];
73
+ const parts = firstComponent.split("/");
74
+ const componentsIndex = parts.findIndex(
75
+ (p) => p.toLowerCase() === "components"
76
+ );
77
+ if (componentsIndex !== -1) {
78
+ suggestedComponentPath = parts.slice(0, componentsIndex + 1).join("/");
79
+ }
80
+ }
81
+ const scenario = storyFiles.length > 0 ? "stories" : likelyComponents.length > 0 ? "components" : "fresh";
82
+ return {
83
+ storyFiles,
84
+ componentFiles: likelyComponents,
85
+ hasConfig,
86
+ configPath: foundConfigPath,
87
+ suggestedComponentPath,
88
+ scenario
89
+ };
90
+ }
91
+ function generateConfig(options) {
92
+ const includeStr = options.includePaths.map((p) => ` '${p}'`).join(",\n");
93
+ const componentStr = options.componentPaths.map((p) => ` '${p}'`).join(",\n");
94
+ return `import type { FragmentsConfig } from '@fragments-sdk/cli';
95
+
96
+ const config: FragmentsConfig = {
97
+ // Glob patterns for finding fragment/story files
98
+ include: [
99
+ ${includeStr}
100
+ ],
101
+
102
+ // Glob patterns to exclude
103
+ exclude: ['**/node_modules/**'],
104
+
105
+ // Glob patterns for finding component files (for auto-documentation)
106
+ components: [
107
+ ${componentStr}
108
+ ],
109
+
110
+ // Framework (react, vue, svelte)
111
+ framework: '${options.framework}',
112
+ ${options.themeBlock || ""}${options.snapshotsBlock || ""}};
113
+
114
+ export default config;
115
+ `;
116
+ }
117
+ function generateExampleComponent() {
118
+ return `import React from 'react';
119
+
120
+ export interface ButtonProps {
121
+ /** Button label */
122
+ children: React.ReactNode;
123
+ /** Visual style variant */
124
+ variant?: 'primary' | 'secondary' | 'ghost';
125
+ /** Button size */
126
+ size?: 'sm' | 'md' | 'lg';
127
+ /** Disabled state */
128
+ disabled?: boolean;
129
+ /** Click handler */
130
+ onClick?: () => void;
131
+ }
132
+
133
+ export function Button({
134
+ children,
135
+ variant = 'primary',
136
+ size = 'md',
137
+ disabled = false,
138
+ onClick,
139
+ }: ButtonProps) {
140
+ const baseStyles = 'inline-flex items-center justify-center font-medium rounded-md transition-colors';
141
+
142
+ const variantStyles = {
143
+ primary: 'bg-blue-600 text-white hover:bg-blue-700',
144
+ secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',
145
+ ghost: 'bg-transparent text-gray-700 hover:bg-gray-100',
146
+ };
147
+
148
+ const sizeStyles = {
149
+ sm: 'px-3 py-1.5 text-sm',
150
+ md: 'px-4 py-2 text-base',
151
+ lg: 'px-6 py-3 text-lg',
152
+ };
153
+
154
+ return (
155
+ <button
156
+ className={\`\${baseStyles} \${variantStyles[variant]} \${sizeStyles[size]}\`}
157
+ disabled={disabled}
158
+ onClick={onClick}
159
+ >
160
+ {children}
161
+ </button>
162
+ );
163
+ }
164
+ `;
165
+ }
166
+ function generateExampleFragment() {
167
+ return `import React from 'react';
168
+ import { defineFragment } from '@fragments-sdk/cli/core';
169
+ import { Button } from './Button';
170
+
171
+ export default defineFragment({
172
+ component: Button,
173
+
174
+ meta: {
175
+ name: 'Button',
176
+ description: 'Interactive button for triggering actions',
177
+ category: 'Actions',
178
+ status: 'stable',
179
+ },
180
+
181
+ usage: {
182
+ when: [
183
+ 'Triggering an action (save, submit, delete)',
184
+ 'Form submission',
185
+ 'Opening dialogs or menus',
186
+ ],
187
+ whenNot: [
188
+ 'Simple navigation (use Link)',
189
+ 'Toggling state (use Switch)',
190
+ ],
191
+ guidelines: [
192
+ 'Use Primary for the main action in a context',
193
+ 'Only one Primary button per section',
194
+ ],
195
+ },
196
+
197
+ props: {
198
+ children: {
199
+ type: 'node',
200
+ required: true,
201
+ description: 'Button label content',
202
+ },
203
+ variant: {
204
+ type: 'enum',
205
+ values: ['primary', 'secondary', 'ghost'],
206
+ default: 'primary',
207
+ description: 'Visual style variant',
208
+ },
209
+ size: {
210
+ type: 'enum',
211
+ values: ['sm', 'md', 'lg'],
212
+ default: 'md',
213
+ description: 'Button size',
214
+ },
215
+ },
216
+
217
+ variants: [
218
+ {
219
+ name: 'Primary',
220
+ description: 'Default action button',
221
+ code: \`import { Button } from './Button';
222
+
223
+ <Button variant="primary">Save Changes</Button>\`,
224
+ render: () => <Button variant="primary">Save Changes</Button>,
225
+ },
226
+ {
227
+ name: 'Secondary',
228
+ description: 'Less prominent action',
229
+ code: \`import { Button } from './Button';
230
+
231
+ <Button variant="secondary">Cancel</Button>\`,
232
+ render: () => <Button variant="secondary">Cancel</Button>,
233
+ },
234
+ {
235
+ name: 'Ghost',
236
+ description: 'Minimal visual weight',
237
+ code: \`import { Button } from './Button';
238
+
239
+ <Button variant="ghost">Learn More</Button>\`,
240
+ render: () => <Button variant="ghost">Learn More</Button>,
241
+ },
242
+ {
243
+ name: 'Sizes',
244
+ description: 'Available size options',
245
+ code: \`import { Button } from './Button';
246
+
247
+ <>
248
+ <Button size="sm">Small</Button>
249
+ <Button size="md">Medium</Button>
250
+ <Button size="lg">Large</Button>
251
+ </>\`,
252
+ render: () => (
253
+ <>
254
+ <Button size="sm">Small</Button>
255
+ <Button size="md">Medium</Button>
256
+ <Button size="lg">Large</Button>
257
+ </>
258
+ ),
259
+ },
260
+ ],
261
+ });
262
+ `;
263
+ }
264
+ function startDevServer(projectRoot) {
265
+ console.log(pc.dim("\nStarting development server...\n"));
266
+ const isWindows = process.platform === "win32";
267
+ const cmd = isWindows ? "npx.cmd" : "npx";
268
+ const child = spawn(cmd, [BRAND.cliCommand, "dev"], {
269
+ cwd: projectRoot,
270
+ stdio: "inherit"
271
+ });
272
+ child.on("error", (err) => {
273
+ console.error(pc.red("Failed to start dev server:"), err.message);
274
+ });
275
+ }
276
+ function mapFrameworkLabel(framework) {
277
+ const labels = {
278
+ "nextjs-app": "Next.js (App Router)",
279
+ "nextjs-pages": "Next.js (Pages Router)",
280
+ "vite": "Vite",
281
+ "remix": "Remix",
282
+ "astro": "Astro"
283
+ };
284
+ return labels[framework] || "Unknown";
285
+ }
286
+ async function runInteractiveConfigure(detection, scenario) {
287
+ const { input, confirm, select } = await import("@inquirer/prompts");
288
+ const componentPath = await input({
289
+ message: "Where are your components located?",
290
+ default: detection.suggestedComponentPath
291
+ });
292
+ let createExample = scenario === "fresh";
293
+ if (scenario === "fresh") {
294
+ createExample = await confirm({
295
+ message: "Create an example Button component to get started?",
296
+ default: true
297
+ });
298
+ }
299
+ let themeBlock = "";
300
+ const configureTheme = await confirm({
301
+ message: "Configure theme seeds? (brand color, density, radius)",
302
+ default: false
303
+ });
304
+ if (configureTheme) {
305
+ const brand = await input({
306
+ message: "Brand color (hex)",
307
+ default: "#18181b",
308
+ validate: (v) => /^#[0-9a-fA-F]{6}$/.test(v) || "Enter a valid hex color (e.g., #6366f1)"
309
+ });
310
+ const neutral = await select({
311
+ message: "Neutral palette",
312
+ choices: [
313
+ { value: "stone", name: "Stone (warm gray)" },
314
+ { value: "ice", name: "Ice (cool blue-gray)" },
315
+ { value: "earth", name: "Earth (olive/khaki)" },
316
+ { value: "sand", name: "Sand (warm beige)" },
317
+ { value: "fire", name: "Fire (warm red-gray)" }
318
+ ],
319
+ default: "stone"
320
+ });
321
+ const density = await select({
322
+ message: "Spacing density",
323
+ choices: [
324
+ { value: "compact", name: "Compact (tighter spacing)" },
325
+ { value: "default", name: "Default" },
326
+ { value: "relaxed", name: "Relaxed (more breathing room)" }
327
+ ],
328
+ default: "default"
329
+ });
330
+ const radiusStyle = await select({
331
+ message: "Border radius style",
332
+ choices: [
333
+ { value: "sharp", name: "Sharp (0px)" },
334
+ { value: "subtle", name: "Subtle (2px)" },
335
+ { value: "default", name: "Default (6px)" },
336
+ { value: "rounded", name: "Rounded (10px)" },
337
+ { value: "pill", name: "Pill (999px)" }
338
+ ],
339
+ default: "default"
340
+ });
341
+ const themeEntries = [];
342
+ if (brand !== "#18181b") themeEntries.push(` brand: '${brand}'`);
343
+ if (neutral !== "stone") themeEntries.push(` neutral: '${neutral}'`);
344
+ if (density !== "default") themeEntries.push(` density: '${density}'`);
345
+ if (radiusStyle !== "default") themeEntries.push(` radiusStyle: '${radiusStyle}'`);
346
+ if (themeEntries.length > 0) {
347
+ themeBlock = `
348
+ // Theme seed values (derives 120+ CSS custom properties)
349
+ theme: {
350
+ ${themeEntries.join(",\n")},
351
+ },
352
+ `;
353
+ }
354
+ }
355
+ let snapshotsBlock = "";
356
+ const enableSnapshots = await confirm({
357
+ message: "Enable visual snapshot tests per component variant?",
358
+ default: false
359
+ });
360
+ if (enableSnapshots) {
361
+ snapshotsBlock = `
362
+ // Visual snapshot testing
363
+ snapshots: {
364
+ enabled: true,
365
+ },
366
+ `;
367
+ }
368
+ const startServer = await confirm({
369
+ message: "Start the viewer now?",
370
+ default: true
371
+ });
372
+ return {
373
+ componentPath,
374
+ createExample,
375
+ startServer,
376
+ themeBlock,
377
+ snapshotsBlock
378
+ };
379
+ }
380
+ async function init(options = {}) {
381
+ const projectRoot = resolve(options.projectRoot || process.cwd());
382
+ const errors = [];
383
+ if (options.scan) {
384
+ const scanPath = resolve(projectRoot, options.scan);
385
+ try {
386
+ await access(scanPath);
387
+ } catch {
388
+ console.error(pc.red(`
389
+ Scan path not found: ${scanPath}
390
+ `));
391
+ return {
392
+ success: false,
393
+ scenario: "scan",
394
+ storiesFound: 0,
395
+ componentsFound: 0,
396
+ errors: [`Scan path not found: ${scanPath}`]
397
+ };
398
+ }
399
+ const { scanGenerate } = await import("./scan-generate-U3RFVDTX.js");
400
+ const scanResult = await scanGenerate({
401
+ scanPath,
402
+ force: options.force,
403
+ verbose: true,
404
+ enrich: options.enrich,
405
+ dryRun: options.dryRun,
406
+ provider: options.provider,
407
+ apiKey: options.apiKey,
408
+ model: options.model
409
+ });
410
+ const relScanPath = relative(projectRoot, scanPath);
411
+ const configPath2 = join(projectRoot, BRAND.configFile);
412
+ const configContent2 = generateConfig({
413
+ includePaths: [`${relScanPath}/**/*.fragment.tsx`],
414
+ componentPaths: [`${relScanPath}/**/*.tsx`],
415
+ framework: "react"
416
+ });
417
+ try {
418
+ await writeFile(configPath2, configContent2, "utf-8");
419
+ console.log(pc.green(`\u2713 Created ${BRAND.configFile}`));
420
+ } catch (e) {
421
+ errors.push(`Failed to create config: ${e}`);
422
+ }
423
+ if (scanResult.success) {
424
+ console.log(pc.cyan("Next steps:"));
425
+ if (options.enrich && !options.dryRun) {
426
+ console.log(` 1. Review AI-enriched fields (usage.when, a11yRules, scenarioTags) in generated files`);
427
+ if (scanResult.generated.some((g) => g.todoCount > 0)) {
428
+ console.log(` 2. Search remaining ${pc.bold("TODO:")} markers and fill in human knowledge`);
429
+ }
430
+ } else {
431
+ console.log(` 1. Search generated files for ${pc.bold("TODO:")} markers and fill in human knowledge`);
432
+ }
433
+ console.log(` ${options.enrich ? "3" : "2"}. Run ${pc.bold(`${BRAND.cliCommand} dev`)} to preview your components`);
434
+ console.log(` ${options.enrich ? "4" : "3"}. Run ${pc.bold(`${BRAND.cliCommand} build`)} to compile fragments.json`);
435
+ console.log();
436
+ }
437
+ return {
438
+ success: scanResult.success && errors.length === 0,
439
+ configPath: errors.length === 0 ? configPath2 : void 0,
440
+ scenario: "scan",
441
+ storiesFound: 0,
442
+ componentsFound: scanResult.generated.length,
443
+ errors: [
444
+ ...errors,
445
+ ...scanResult.errors.map((e) => `${e.name}: ${e.error}`)
446
+ ]
447
+ };
448
+ }
449
+ console.log(pc.cyan(`
450
+ ${BRAND.name} init
451
+ `));
452
+ const detection = await detectProject(projectRoot);
453
+ if (detection.hasConfig && !options.force) {
454
+ if (options.configure) {
455
+ console.log(pc.yellow(` ! Config exists: ${BRAND.configFile} (will overwrite)`));
456
+ } else {
457
+ console.log(pc.green(` \u2713 Already initialized`) + pc.dim(` (${BRAND.configFile} exists)`));
458
+ console.log();
459
+ console.log(pc.dim(` Run ${pc.bold(`${BRAND.cliCommand} init --force`)} to reinitialize`));
460
+ console.log(pc.dim(` Run ${pc.bold(`${BRAND.cliCommand} init --configure`)} to customize theme, snapshots, etc.`));
461
+ console.log();
462
+ return {
463
+ success: true,
464
+ scenario: detection.scenario,
465
+ storiesFound: detection.storyFiles.length,
466
+ componentsFound: detection.componentFiles.length,
467
+ errors: []
468
+ };
469
+ }
470
+ }
471
+ let scenario;
472
+ if (detection.storyFiles.length > 0) {
473
+ scenario = "stories";
474
+ console.log(pc.green(` \u2713 Found ${detection.storyFiles.length} Storybook stories`));
475
+ } else if (detection.componentFiles.length > 0) {
476
+ scenario = "components";
477
+ console.log(pc.green(` \u2713 Found ${detection.componentFiles.length} components`) + pc.dim(` in ${detection.suggestedComponentPath}`));
478
+ } else {
479
+ scenario = "fresh";
480
+ console.log(pc.dim(` \xB7 No existing components found`));
481
+ }
482
+ const framework = await detectSetupFramework(projectRoot);
483
+ console.log(pc.green(` \u2713 Detected ${mapFrameworkLabel(framework)}`));
484
+ let componentPath = detection.suggestedComponentPath;
485
+ let createExample = scenario === "fresh";
486
+ let startServer = false;
487
+ let themeBlock = "";
488
+ let snapshotsBlock = "";
489
+ if (options.configure) {
490
+ const config = await runInteractiveConfigure(detection, scenario);
491
+ componentPath = config.componentPath;
492
+ createExample = config.createExample;
493
+ startServer = config.startServer;
494
+ themeBlock = config.themeBlock;
495
+ snapshotsBlock = config.snapshotsBlock;
496
+ }
497
+ const includePaths = [
498
+ `${componentPath}/**/*.fragment.tsx`
499
+ ];
500
+ if (scenario === "stories") {
501
+ includePaths.push(`${componentPath}/**/*.stories.tsx`);
502
+ includePaths.push(`${componentPath}/**/*.stories.ts`);
503
+ }
504
+ const configPath = join(projectRoot, BRAND.configFile);
505
+ const configContent = generateConfig({
506
+ includePaths,
507
+ componentPaths: [`${componentPath}/**/*.tsx`],
508
+ framework: "react",
509
+ themeBlock,
510
+ snapshotsBlock
511
+ });
512
+ try {
513
+ await writeFile(configPath, configContent, "utf-8");
514
+ console.log(pc.green(` \u2713 Created ${BRAND.configFile}`));
515
+ } catch (e) {
516
+ errors.push(`Failed to create config: ${e}`);
517
+ }
518
+ const entryFile = await findEntryFile(projectRoot, framework);
519
+ if (entryFile) {
520
+ try {
521
+ const stylesResult = await addStylesImport(projectRoot, entryFile);
522
+ if (stylesResult.modified) {
523
+ console.log(pc.green(` \u2713 Added styles import to ${entryFile}`));
524
+ } else {
525
+ console.log(pc.dim(` \xB7 ${stylesResult.message}`));
526
+ }
527
+ } catch (e) {
528
+ errors.push(`Failed to add styles import: ${e instanceof Error ? e.message : e}`);
529
+ }
530
+ try {
531
+ const providerResult = await addThemeProvider(projectRoot, entryFile, framework);
532
+ if (providerResult.modified) {
533
+ console.log(pc.green(` \u2713 Added ThemeProvider to ${entryFile}`));
534
+ } else {
535
+ console.log(pc.dim(` \xB7 ${providerResult.message}`));
536
+ }
537
+ } catch (e) {
538
+ errors.push(`Failed to add ThemeProvider: ${e instanceof Error ? e.message : e}`);
539
+ }
540
+ } else {
541
+ console.log(pc.yellow(` ! Could not detect entry file \u2014 add styles import manually`));
542
+ console.log(pc.dim(` import '@fragments-sdk/ui/styles'`));
543
+ }
544
+ if (framework === "nextjs-app" || framework === "nextjs-pages") {
545
+ try {
546
+ const transpileResult = await addTranspilePackages(projectRoot);
547
+ if (transpileResult.modified) {
548
+ console.log(pc.green(` \u2713 ${transpileResult.message}`));
549
+ } else {
550
+ console.log(pc.dim(` \xB7 ${transpileResult.message}`));
551
+ }
552
+ } catch (e) {
553
+ errors.push(`Failed to update next.config: ${e instanceof Error ? e.message : e}`);
554
+ }
555
+ }
556
+ if (scenario === "fresh" && createExample) {
557
+ const exampleDir = join(projectRoot, componentPath, "Button");
558
+ try {
559
+ await mkdir(exampleDir, { recursive: true });
560
+ await writeFile(
561
+ join(exampleDir, "Button.tsx"),
562
+ generateExampleComponent(),
563
+ "utf-8"
564
+ );
565
+ console.log(
566
+ pc.green(` \u2713 Created ${relative(projectRoot, join(exampleDir, "Button.tsx"))}`)
567
+ );
568
+ await writeFile(
569
+ join(exampleDir, "Button.fragment.tsx"),
570
+ generateExampleFragment(),
571
+ "utf-8"
572
+ );
573
+ console.log(
574
+ pc.green(
575
+ ` \u2713 Created ${relative(projectRoot, join(exampleDir, "Button.fragment.tsx"))}`
576
+ )
577
+ );
578
+ } catch (e) {
579
+ errors.push(`Failed to create example component: ${e}`);
580
+ }
581
+ }
582
+ if (scenario === "components" || scenario === "stories") {
583
+ try {
584
+ const { scan } = await import("./scan-CHQHXWVD.js");
585
+ const scanResult = await scan({
586
+ config: configPath,
587
+ verbose: false,
588
+ quiet: true
589
+ });
590
+ if (scanResult.success) {
591
+ console.log(pc.green(` \u2713 Generated fragments.json`) + pc.dim(` (${scanResult.componentCount} components)`));
592
+ } else {
593
+ console.log(pc.dim(` \xB7 Auto-documentation will run when you start the dev server`));
594
+ }
595
+ } catch {
596
+ console.log(
597
+ pc.dim(` \xB7 Auto-documentation will run when you start the dev server`)
598
+ );
599
+ }
600
+ }
601
+ console.log();
602
+ if (errors.length > 0) {
603
+ console.log(pc.red(` ${errors.length} error(s) occurred:`));
604
+ for (const error of errors) {
605
+ console.log(pc.red(` - ${error}`));
606
+ }
607
+ console.log();
608
+ } else {
609
+ console.log(pc.green(` Done!`) + pc.dim(` Setup complete.
610
+ `));
611
+ if (startServer) {
612
+ startDevServer(projectRoot);
613
+ } else {
614
+ console.log(` ${pc.bold("Get started:")}`);
615
+ console.log(` ${pc.dim("$")} ${BRAND.cliCommand} dev`);
616
+ console.log();
617
+ if (!options.configure) {
618
+ console.log(` ${pc.bold("Customize:")} theme seeds, snapshots, and more`);
619
+ console.log(` ${pc.dim("$")} ${BRAND.cliCommand} init --configure`);
620
+ console.log();
621
+ }
622
+ }
623
+ }
624
+ return {
625
+ success: errors.length === 0,
626
+ configPath: errors.length === 0 ? configPath : void 0,
627
+ scenario,
628
+ storiesFound: detection.storyFiles.length,
629
+ componentsFound: detection.componentFiles.length,
630
+ errors
631
+ };
632
+ }
633
+ export {
634
+ init
635
+ };
636
+ //# sourceMappingURL=init-XK6PRUE5.js.map