@fragments-sdk/cli 0.7.14 → 0.7.16

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 (67) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/{chunk-CRTN6BIW.js → chunk-QLTLLQBI.js} +2 -2
  3. package/dist/{chunk-TQOGBAOZ.js → chunk-WLXFE6XW.js} +91 -2
  4. package/dist/chunk-WLXFE6XW.js.map +1 -0
  5. package/dist/core/index.d.ts +44 -3
  6. package/dist/core/index.js +11 -3
  7. package/dist/{defineFragment-C6PFzZyo.d.ts → defineFragment-BI9KoPrs.d.ts} +1 -1
  8. package/dist/{generate-ZPERYZLF.js → generate-ICIPKCKV.js} +2 -2
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.js +2 -2
  11. package/dist/init-DIZ6UNBL.js +806 -0
  12. package/dist/init-DIZ6UNBL.js.map +1 -0
  13. package/dist/mcp-bin.js +2 -2
  14. package/dist/{scan-BSMLGBX4.js → scan-X3DI2X5G.js} +2 -2
  15. package/dist/{service-QACVPR37.js → service-JEWWTSKI.js} +2 -2
  16. package/dist/{static-viewer-2RQD5QLR.js → static-viewer-JIWCYKVK.js} +2 -2
  17. package/dist/{tokens-A3BZIQPB.js → tokens-K2AGUUOJ.js} +2 -2
  18. package/dist/{viewer-CNLZQUFO.js → viewer-QKIAPTPG.js} +126 -15
  19. package/dist/viewer-QKIAPTPG.js.map +1 -0
  20. package/package.json +3 -2
  21. package/src/commands/init-framework.ts +414 -0
  22. package/src/commands/init.ts +41 -1
  23. package/src/core/__tests__/preview-runtime.test.tsx +111 -0
  24. package/src/core/index.ts +13 -0
  25. package/src/core/preview-runtime.tsx +144 -0
  26. package/src/viewer/components/App.tsx +8 -3
  27. package/src/viewer/components/FragmentRenderer.tsx +61 -0
  28. package/src/viewer/components/HealthDashboard.tsx +1 -1
  29. package/src/viewer/components/IsolatedPreviewFrame.tsx +10 -8
  30. package/src/viewer/components/PreviewFrameHost.tsx +27 -60
  31. package/src/viewer/components/PropsTable.tsx +2 -2
  32. package/src/viewer/components/RuntimeToolsRegistrar.tsx +17 -0
  33. package/src/viewer/components/SkeletonLoader.tsx +114 -125
  34. package/src/viewer/components/VariantMatrix.tsx +3 -3
  35. package/src/viewer/components/ViewerStateSync.tsx +52 -0
  36. package/src/viewer/components/WebMCPDevTools.tsx +509 -0
  37. package/src/viewer/components/WebMCPIntegration.tsx +47 -0
  38. package/src/viewer/components/WebMCPStatusIndicator.tsx +60 -0
  39. package/src/viewer/entry.tsx +32 -5
  40. package/src/viewer/hooks/useA11yService.ts +1 -135
  41. package/src/viewer/hooks/useCompiledFragments.ts +42 -0
  42. package/src/viewer/index.html +1 -1
  43. package/src/viewer/public/favicon.ico +0 -0
  44. package/src/viewer/server.ts +59 -3
  45. package/src/viewer/vendor/shared/src/DocsHeaderBar.tsx +19 -0
  46. package/src/viewer/vendor/shared/src/DocsPageAsideHost.tsx +1 -1
  47. package/src/viewer/vendor/shared/src/DocsSearchCommand.tsx +69 -104
  48. package/src/viewer/vite-plugin.ts +76 -1
  49. package/src/viewer/webmcp/__tests__/analytics.test.ts +108 -0
  50. package/src/viewer/webmcp/analytics.ts +165 -0
  51. package/src/viewer/webmcp/index.ts +3 -0
  52. package/src/viewer/webmcp/posthog-bridge.ts +39 -0
  53. package/src/viewer/webmcp/runtime-tools.ts +152 -0
  54. package/src/viewer/webmcp/scan-utils.ts +135 -0
  55. package/src/viewer/webmcp/use-tool-analytics.ts +69 -0
  56. package/src/viewer/webmcp/viewer-state.ts +45 -0
  57. package/dist/chunk-TQOGBAOZ.js.map +0 -1
  58. package/dist/init-GID2DXB3.js +0 -498
  59. package/dist/init-GID2DXB3.js.map +0 -1
  60. package/dist/viewer-CNLZQUFO.js.map +0 -1
  61. package/src/viewer/components/StoryRenderer.tsx +0 -121
  62. /package/dist/{chunk-CRTN6BIW.js.map → chunk-QLTLLQBI.js.map} +0 -0
  63. /package/dist/{generate-ZPERYZLF.js.map → generate-ICIPKCKV.js.map} +0 -0
  64. /package/dist/{scan-BSMLGBX4.js.map → scan-X3DI2X5G.js.map} +0 -0
  65. /package/dist/{service-QACVPR37.js.map → service-JEWWTSKI.js.map} +0 -0
  66. /package/dist/{static-viewer-2RQD5QLR.js.map → static-viewer-JIWCYKVK.js.map} +0 -0
  67. /package/dist/{tokens-A3BZIQPB.js.map → tokens-K2AGUUOJ.js.map} +0 -0
@@ -0,0 +1,806 @@
1
+ import { createRequire as __banner_createRequire } from 'module'; const require = __banner_createRequire(import.meta.url);
2
+ import "./chunk-WLXFE6XW.js";
3
+ import "./chunk-7CRC46HV.js";
4
+ import {
5
+ BRAND
6
+ } from "./chunk-EKLMXTWU.js";
7
+ import "./chunk-Z7EY4VHE.js";
8
+
9
+ // src/commands/init.ts
10
+ import { writeFile as writeFile2, mkdir, access as access2 } from "fs/promises";
11
+ import { resolve, join as join2, relative, dirname, basename } from "path";
12
+ import { spawn } from "child_process";
13
+ import pc2 from "picocolors";
14
+ import fg from "fast-glob";
15
+ import { input, confirm } from "@inquirer/prompts";
16
+
17
+ // src/commands/init-framework.ts
18
+ import { readFile, writeFile, access } from "fs/promises";
19
+ import { join } from "path";
20
+ import pc from "picocolors";
21
+ async function detectFramework(projectRoot) {
22
+ try {
23
+ const pkgPath = join(projectRoot, "package.json");
24
+ const pkgContent = await readFile(pkgPath, "utf-8");
25
+ const pkg = JSON.parse(pkgContent);
26
+ const allDeps = {
27
+ ...pkg.dependencies,
28
+ ...pkg.devDependencies
29
+ };
30
+ if (allDeps["next"]) {
31
+ return { framework: "nextjs", detectedBy: "next" };
32
+ }
33
+ if (allDeps["@remix-run/react"]) {
34
+ return { framework: "remix", detectedBy: "@remix-run/react" };
35
+ }
36
+ if (allDeps["astro"]) {
37
+ return { framework: "astro", detectedBy: "astro" };
38
+ }
39
+ if (allDeps["vite"]) {
40
+ return { framework: "vite", detectedBy: "vite" };
41
+ }
42
+ return { framework: "unknown", detectedBy: null };
43
+ } catch {
44
+ return { framework: "unknown", detectedBy: null };
45
+ }
46
+ }
47
+ function generateGlobalsSCSS(seeds) {
48
+ const withClauses = [];
49
+ if (seeds?.brand) {
50
+ withClauses.push(` $fui-brand: ${seeds.brand}`);
51
+ }
52
+ if (seeds?.neutral) {
53
+ withClauses.push(` $fui-neutral: "${seeds.neutral}"`);
54
+ }
55
+ if (seeds?.density) {
56
+ withClauses.push(` $fui-density: "${seeds.density}"`);
57
+ }
58
+ if (seeds?.radiusStyle) {
59
+ withClauses.push(` $fui-radius-style: "${seeds.radiusStyle}"`);
60
+ }
61
+ const useStatement = withClauses.length > 0 ? `@use '@fragments-sdk/ui/styles' with (
62
+ ${withClauses.join(",\n")}
63
+ );` : `@use '@fragments-sdk/ui/styles';`;
64
+ return `// Fragments SDK Global Styles
65
+ // Customize seed values to theme the entire design system.
66
+ // See: https://usefragments.com/docs/theming
67
+ ${useStatement}
68
+ `;
69
+ }
70
+ function generateProviders() {
71
+ return `'use client';
72
+
73
+ import { ThemeProvider } from '@fragments-sdk/ui';
74
+
75
+ export function Providers({ children }: { children: React.ReactNode }) {
76
+ return (
77
+ <ThemeProvider defaultTheme="system" attribute="data-theme">
78
+ {children}
79
+ </ThemeProvider>
80
+ );
81
+ }
82
+ `;
83
+ }
84
+ async function setupNextJS(projectRoot, options) {
85
+ const result = {
86
+ framework: "nextjs",
87
+ filesCreated: [],
88
+ packagesToInstall: [],
89
+ configModified: [],
90
+ warnings: []
91
+ };
92
+ try {
93
+ const pkgContent = await readFile(
94
+ join(projectRoot, "package.json"),
95
+ "utf-8"
96
+ );
97
+ const pkg = JSON.parse(pkgContent);
98
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
99
+ if (!allDeps["sass"]) {
100
+ result.packagesToInstall.push("sass");
101
+ }
102
+ } catch {
103
+ }
104
+ const nextConfigPaths = [
105
+ "next.config.ts",
106
+ "next.config.mjs",
107
+ "next.config.js"
108
+ ];
109
+ for (const configName of nextConfigPaths) {
110
+ const configPath = join(projectRoot, configName);
111
+ try {
112
+ await access(configPath);
113
+ const content = await readFile(configPath, "utf-8");
114
+ if (!content.includes("transpilePackages")) {
115
+ if (content.includes("const nextConfig")) {
116
+ const updated = content.replace(
117
+ /const nextConfig\s*=\s*\{/,
118
+ `const nextConfig = {
119
+ transpilePackages: ['@fragments-sdk/ui'],`
120
+ );
121
+ await writeFile(configPath, updated, "utf-8");
122
+ result.configModified.push(configName);
123
+ } else {
124
+ result.warnings.push(
125
+ `Could not auto-modify ${configName}. Add transpilePackages: ['@fragments-sdk/ui'] manually.`
126
+ );
127
+ }
128
+ }
129
+ break;
130
+ } catch {
131
+ continue;
132
+ }
133
+ }
134
+ const globalsPath = join(projectRoot, "src", "styles", "globals.scss");
135
+ try {
136
+ await access(globalsPath);
137
+ result.warnings.push(
138
+ "src/styles/globals.scss already exists. Skipped generation."
139
+ );
140
+ } catch {
141
+ await writeFile(globalsPath, generateGlobalsSCSS(options.seeds), "utf-8");
142
+ result.filesCreated.push("src/styles/globals.scss");
143
+ }
144
+ const providersPath = join(projectRoot, "src", "providers.tsx");
145
+ try {
146
+ await access(providersPath);
147
+ result.warnings.push("src/providers.tsx already exists. Skipped.");
148
+ } catch {
149
+ await writeFile(providersPath, generateProviders(), "utf-8");
150
+ result.filesCreated.push("src/providers.tsx");
151
+ }
152
+ return result;
153
+ }
154
+ async function setupVite(projectRoot, options) {
155
+ const result = {
156
+ framework: "vite",
157
+ filesCreated: [],
158
+ packagesToInstall: [],
159
+ configModified: [],
160
+ warnings: []
161
+ };
162
+ try {
163
+ const pkgContent = await readFile(
164
+ join(projectRoot, "package.json"),
165
+ "utf-8"
166
+ );
167
+ const pkg = JSON.parse(pkgContent);
168
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
169
+ if (!allDeps["sass"]) {
170
+ result.packagesToInstall.push("sass");
171
+ }
172
+ } catch {
173
+ }
174
+ const globalsPath = join(projectRoot, "src", "styles", "globals.scss");
175
+ try {
176
+ await access(globalsPath);
177
+ result.warnings.push(
178
+ "src/styles/globals.scss already exists. Skipped generation."
179
+ );
180
+ } catch {
181
+ await writeFile(globalsPath, generateGlobalsSCSS(options.seeds), "utf-8");
182
+ result.filesCreated.push("src/styles/globals.scss");
183
+ }
184
+ const providersPath = join(projectRoot, "src", "providers.tsx");
185
+ try {
186
+ await access(providersPath);
187
+ result.warnings.push("src/providers.tsx already exists. Skipped.");
188
+ } catch {
189
+ await writeFile(providersPath, generateProviders(), "utf-8");
190
+ result.filesCreated.push("src/providers.tsx");
191
+ }
192
+ return result;
193
+ }
194
+ async function setupRemix(projectRoot, options) {
195
+ const result = {
196
+ framework: "remix",
197
+ filesCreated: [],
198
+ packagesToInstall: [],
199
+ configModified: [],
200
+ warnings: []
201
+ };
202
+ result.packagesToInstall.push("sass");
203
+ const globalsPath = join(projectRoot, "app", "styles", "globals.scss");
204
+ try {
205
+ await access(globalsPath);
206
+ result.warnings.push(
207
+ "app/styles/globals.scss already exists. Skipped generation."
208
+ );
209
+ } catch {
210
+ await writeFile(globalsPath, generateGlobalsSCSS(options.seeds), "utf-8");
211
+ result.filesCreated.push("app/styles/globals.scss");
212
+ }
213
+ const providersPath = join(projectRoot, "app", "providers.tsx");
214
+ try {
215
+ await access(providersPath);
216
+ result.warnings.push("app/providers.tsx already exists. Skipped.");
217
+ } catch {
218
+ await writeFile(providersPath, generateProviders(), "utf-8");
219
+ result.filesCreated.push("app/providers.tsx");
220
+ }
221
+ result.warnings.push(
222
+ "Add @fragments-sdk/ui to serverDependenciesToBundle in remix.config if using source imports."
223
+ );
224
+ return result;
225
+ }
226
+ async function setupAstro(projectRoot, options) {
227
+ const result = {
228
+ framework: "astro",
229
+ filesCreated: [],
230
+ packagesToInstall: [],
231
+ configModified: [],
232
+ warnings: []
233
+ };
234
+ result.packagesToInstall.push("sass");
235
+ const globalsPath = join(projectRoot, "src", "styles", "globals.scss");
236
+ try {
237
+ await access(globalsPath);
238
+ result.warnings.push(
239
+ "src/styles/globals.scss already exists. Skipped generation."
240
+ );
241
+ } catch {
242
+ await writeFile(globalsPath, generateGlobalsSCSS(options.seeds), "utf-8");
243
+ result.filesCreated.push("src/styles/globals.scss");
244
+ }
245
+ return result;
246
+ }
247
+ async function setupFramework(options) {
248
+ const { projectRoot } = options;
249
+ let framework = options.framework;
250
+ if (!framework || framework === "unknown") {
251
+ const detection = await detectFramework(projectRoot);
252
+ framework = detection.framework;
253
+ if (detection.detectedBy) {
254
+ console.log(
255
+ pc.green(` Detected ${frameworkLabel(framework)}`) + pc.dim(` (via ${detection.detectedBy})`)
256
+ );
257
+ }
258
+ } else {
259
+ console.log(pc.green(` Framework: ${frameworkLabel(framework)}`));
260
+ }
261
+ switch (framework) {
262
+ case "nextjs":
263
+ return setupNextJS(projectRoot, options);
264
+ case "vite":
265
+ return setupVite(projectRoot, options);
266
+ case "remix":
267
+ return setupRemix(projectRoot, options);
268
+ case "astro":
269
+ return setupAstro(projectRoot, options);
270
+ default:
271
+ return {
272
+ framework: "unknown",
273
+ filesCreated: [],
274
+ packagesToInstall: ["sass"],
275
+ configModified: [],
276
+ warnings: [
277
+ "Could not detect framework. Install sass and import @fragments-sdk/ui/styles manually."
278
+ ]
279
+ };
280
+ }
281
+ }
282
+ function frameworkLabel(framework) {
283
+ switch (framework) {
284
+ case "nextjs":
285
+ return "Next.js";
286
+ case "vite":
287
+ return "Vite";
288
+ case "remix":
289
+ return "Remix";
290
+ case "astro":
291
+ return "Astro";
292
+ default:
293
+ return "Unknown";
294
+ }
295
+ }
296
+
297
+ // src/commands/init.ts
298
+ async function detectProject(projectRoot) {
299
+ console.log(pc2.dim("\nScanning project...\n"));
300
+ const configPath = join2(projectRoot, BRAND.configFile);
301
+ const legacyConfigPath = join2(projectRoot, BRAND.legacyConfigFile);
302
+ let hasConfig = false;
303
+ let foundConfigPath = null;
304
+ try {
305
+ await access2(configPath);
306
+ hasConfig = true;
307
+ foundConfigPath = configPath;
308
+ } catch {
309
+ try {
310
+ await access2(legacyConfigPath);
311
+ hasConfig = true;
312
+ foundConfigPath = legacyConfigPath;
313
+ } catch {
314
+ }
315
+ }
316
+ const storyFiles = await fg(
317
+ ["**/*.stories.tsx", "**/*.stories.ts", "**/*.stories.jsx", "**/*.stories.js"],
318
+ {
319
+ cwd: projectRoot,
320
+ ignore: ["**/node_modules/**", "**/dist/**", "**/build/**", "**/.storybook/**"]
321
+ }
322
+ );
323
+ const componentFiles = await fg(
324
+ ["**/components/**/*.tsx", "**/Components/**/*.tsx", "src/**/*.tsx"],
325
+ {
326
+ cwd: projectRoot,
327
+ ignore: [
328
+ "**/node_modules/**",
329
+ "**/dist/**",
330
+ "**/build/**",
331
+ "**/*.stories.*",
332
+ "**/*.fragment.*",
333
+ "**/*.test.*",
334
+ "**/*.spec.*",
335
+ "**/*.d.ts",
336
+ "**/index.tsx"
337
+ // Skip barrel files
338
+ ]
339
+ }
340
+ );
341
+ const nonComponentPatterns = /\.(styles|utils|helpers|constants|types|hooks|context|config|mock|fixture)\./i;
342
+ const nonComponentNames = /^(index|types|utils|helpers|constants|hooks|providers|layout|use[A-Z])/;
343
+ const likelyComponents = componentFiles.filter((f) => {
344
+ const fileName = f.split("/").pop() || "";
345
+ const baseName = fileName.replace(/\.tsx$/, "");
346
+ return !nonComponentPatterns.test(fileName) && !nonComponentNames.test(baseName);
347
+ });
348
+ let suggestedComponentPath = "src/components";
349
+ if (likelyComponents.length > 0) {
350
+ const firstComponent = likelyComponents[0];
351
+ const parts = firstComponent.split("/");
352
+ const componentsIndex = parts.findIndex(
353
+ (p) => p.toLowerCase() === "components"
354
+ );
355
+ if (componentsIndex !== -1) {
356
+ suggestedComponentPath = parts.slice(0, componentsIndex + 1).join("/");
357
+ }
358
+ }
359
+ return {
360
+ storyFiles,
361
+ componentFiles: likelyComponents,
362
+ hasConfig,
363
+ configPath: foundConfigPath,
364
+ suggestedComponentPath
365
+ };
366
+ }
367
+ function generateConfig(options) {
368
+ const includeStr = options.includePaths.map((p) => ` '${p}'`).join(",\n");
369
+ const componentStr = options.componentPaths.map((p) => ` '${p}'`).join(",\n");
370
+ return `import type { FragmentsConfig } from '@fragments-sdk/cli';
371
+
372
+ const config: FragmentsConfig = {
373
+ // Glob patterns for finding fragment/story files
374
+ include: [
375
+ ${includeStr}
376
+ ],
377
+
378
+ // Glob patterns to exclude
379
+ exclude: ['**/node_modules/**'],
380
+
381
+ // Glob patterns for finding component files (for auto-documentation)
382
+ components: [
383
+ ${componentStr}
384
+ ],
385
+
386
+ // Framework (react, vue, svelte)
387
+ framework: '${options.framework}',
388
+ };
389
+
390
+ export default config;
391
+ `;
392
+ }
393
+ function generateExampleComponent() {
394
+ return `import React from 'react';
395
+
396
+ export interface ButtonProps {
397
+ /** Button label */
398
+ children: React.ReactNode;
399
+ /** Visual style variant */
400
+ variant?: 'primary' | 'secondary' | 'ghost';
401
+ /** Button size */
402
+ size?: 'sm' | 'md' | 'lg';
403
+ /** Disabled state */
404
+ disabled?: boolean;
405
+ /** Click handler */
406
+ onClick?: () => void;
407
+ }
408
+
409
+ export function Button({
410
+ children,
411
+ variant = 'primary',
412
+ size = 'md',
413
+ disabled = false,
414
+ onClick,
415
+ }: ButtonProps) {
416
+ const baseStyles = 'inline-flex items-center justify-center font-medium rounded-md transition-colors';
417
+
418
+ const variantStyles = {
419
+ primary: 'bg-blue-600 text-white hover:bg-blue-700',
420
+ secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',
421
+ ghost: 'bg-transparent text-gray-700 hover:bg-gray-100',
422
+ };
423
+
424
+ const sizeStyles = {
425
+ sm: 'px-3 py-1.5 text-sm',
426
+ md: 'px-4 py-2 text-base',
427
+ lg: 'px-6 py-3 text-lg',
428
+ };
429
+
430
+ return (
431
+ <button
432
+ className={\`\${baseStyles} \${variantStyles[variant]} \${sizeStyles[size]}\`}
433
+ disabled={disabled}
434
+ onClick={onClick}
435
+ >
436
+ {children}
437
+ </button>
438
+ );
439
+ }
440
+ `;
441
+ }
442
+ function generateExampleFragment() {
443
+ return `import React from 'react';
444
+ import { defineFragment } from '@fragments-sdk/cli/core';
445
+ import { Button } from './Button';
446
+
447
+ export default defineFragment({
448
+ component: Button,
449
+
450
+ meta: {
451
+ name: 'Button',
452
+ description: 'Interactive button for triggering actions',
453
+ category: 'Actions',
454
+ status: 'stable',
455
+ },
456
+
457
+ usage: {
458
+ when: [
459
+ 'Triggering an action (save, submit, delete)',
460
+ 'Form submission',
461
+ 'Opening dialogs or menus',
462
+ ],
463
+ whenNot: [
464
+ 'Simple navigation (use Link)',
465
+ 'Toggling state (use Switch)',
466
+ ],
467
+ guidelines: [
468
+ 'Use Primary for the main action in a context',
469
+ 'Only one Primary button per section',
470
+ ],
471
+ },
472
+
473
+ props: {
474
+ children: {
475
+ type: 'node',
476
+ required: true,
477
+ description: 'Button label content',
478
+ },
479
+ variant: {
480
+ type: 'enum',
481
+ values: ['primary', 'secondary', 'ghost'],
482
+ default: 'primary',
483
+ description: 'Visual style variant',
484
+ },
485
+ size: {
486
+ type: 'enum',
487
+ values: ['sm', 'md', 'lg'],
488
+ default: 'md',
489
+ description: 'Button size',
490
+ },
491
+ },
492
+
493
+ variants: [
494
+ {
495
+ name: 'Primary',
496
+ description: 'Default action button',
497
+ code: \`import { Button } from './Button';
498
+
499
+ <Button variant="primary">Save Changes</Button>\`,
500
+ render: () => <Button variant="primary">Save Changes</Button>,
501
+ },
502
+ {
503
+ name: 'Secondary',
504
+ description: 'Less prominent action',
505
+ code: \`import { Button } from './Button';
506
+
507
+ <Button variant="secondary">Cancel</Button>\`,
508
+ render: () => <Button variant="secondary">Cancel</Button>,
509
+ },
510
+ {
511
+ name: 'Ghost',
512
+ description: 'Minimal visual weight',
513
+ code: \`import { Button } from './Button';
514
+
515
+ <Button variant="ghost">Learn More</Button>\`,
516
+ render: () => <Button variant="ghost">Learn More</Button>,
517
+ },
518
+ {
519
+ name: 'Sizes',
520
+ description: 'Available size options',
521
+ code: \`import { Button } from './Button';
522
+
523
+ <>
524
+ <Button size="sm">Small</Button>
525
+ <Button size="md">Medium</Button>
526
+ <Button size="lg">Large</Button>
527
+ </>\`,
528
+ render: () => (
529
+ <>
530
+ <Button size="sm">Small</Button>
531
+ <Button size="md">Medium</Button>
532
+ <Button size="lg">Large</Button>
533
+ </>
534
+ ),
535
+ },
536
+ ],
537
+ });
538
+ `;
539
+ }
540
+ function toPascalCase(str) {
541
+ return str.replace(/[-_.](\w)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toUpperCase());
542
+ }
543
+ function generateFragmentStub(componentName, importPath) {
544
+ return `import React from 'react';
545
+ import { defineFragment } from '@fragments-sdk/cli/core';
546
+ import { ${componentName} } from '${importPath}';
547
+
548
+ export default defineFragment({
549
+ component: ${componentName},
550
+
551
+ meta: {
552
+ name: '${componentName}',
553
+ description: '${componentName} component',
554
+ category: 'general',
555
+ status: 'beta',
556
+ },
557
+
558
+ usage: {
559
+ when: ['TODO: describe when to use ${componentName}'],
560
+ whenNot: ['TODO: describe when not to use ${componentName}'],
561
+ },
562
+
563
+ props: {},
564
+
565
+ variants: [
566
+ {
567
+ name: 'Default',
568
+ description: 'Default ${componentName}',
569
+ code: \`<${componentName} />\`,
570
+ render: () => <${componentName} />,
571
+ },
572
+ ],
573
+ });
574
+ `;
575
+ }
576
+ function startDevServer(projectRoot) {
577
+ console.log(pc2.dim("\nStarting development server...\n"));
578
+ const isWindows = process.platform === "win32";
579
+ const cmd = isWindows ? "npx.cmd" : "npx";
580
+ const child = spawn(cmd, [BRAND.cliCommand, "dev"], {
581
+ cwd: projectRoot,
582
+ stdio: "inherit"
583
+ });
584
+ child.on("error", (err) => {
585
+ console.error(pc2.red("Failed to start dev server:"), err.message);
586
+ });
587
+ }
588
+ async function init(options = {}) {
589
+ const projectRoot = resolve(options.projectRoot || process.cwd());
590
+ const errors = [];
591
+ console.log(pc2.cyan(`
592
+ \u2728 Welcome to ${BRAND.name}!
593
+ `));
594
+ const detection = await detectProject(projectRoot);
595
+ if (detection.hasConfig && !options.force) {
596
+ console.log(pc2.yellow(`\u26A0 Config already exists: ${BRAND.configFile}`));
597
+ if (!options.yes) {
598
+ const overwrite = await confirm({
599
+ message: "Do you want to reinitialize? (This will overwrite your config)",
600
+ default: false
601
+ });
602
+ if (!overwrite) {
603
+ console.log(pc2.dim(`
604
+ Keeping existing configuration. Run \`${BRAND.cliCommand} dev\` to start.
605
+ `));
606
+ return {
607
+ success: true,
608
+ scenario: "stories",
609
+ storiesFound: detection.storyFiles.length,
610
+ componentsFound: detection.componentFiles.length,
611
+ errors: []
612
+ };
613
+ }
614
+ }
615
+ }
616
+ let scenario;
617
+ if (detection.storyFiles.length > 0) {
618
+ scenario = "stories";
619
+ console.log(pc2.green(`\u2713 Found ${detection.storyFiles.length} Storybook story file(s)`));
620
+ console.log(pc2.dim(` ${detection.storyFiles.slice(0, 3).join("\n ")}`));
621
+ if (detection.storyFiles.length > 3) {
622
+ console.log(pc2.dim(` ... and ${detection.storyFiles.length - 3} more`));
623
+ }
624
+ console.log();
625
+ console.log(
626
+ pc2.cyan("Great news! ") + "Fragments can load your existing stories automatically."
627
+ );
628
+ } else if (detection.componentFiles.length > 0) {
629
+ scenario = "components";
630
+ console.log(pc2.green(`\u2713 Found ${detection.componentFiles.length} component file(s)`));
631
+ console.log(pc2.dim(` ${detection.componentFiles.slice(0, 3).join("\n ")}`));
632
+ if (detection.componentFiles.length > 3) {
633
+ console.log(pc2.dim(` ... and ${detection.componentFiles.length - 3} more`));
634
+ }
635
+ console.log();
636
+ console.log(
637
+ pc2.cyan("No stories found, but that's fine! ") + "Fragments can auto-generate documentation from your TypeScript."
638
+ );
639
+ } else {
640
+ scenario = "fresh";
641
+ console.log(pc2.yellow("No components or stories found."));
642
+ console.log();
643
+ console.log(pc2.cyan("Let's create your first fragment!"));
644
+ }
645
+ console.log();
646
+ let componentPath = detection.suggestedComponentPath;
647
+ let runScan = scenario === "components";
648
+ let createExample = scenario === "fresh";
649
+ let startServer = true;
650
+ if (!options.yes) {
651
+ componentPath = await input({
652
+ message: "Where are your components located?",
653
+ default: detection.suggestedComponentPath
654
+ });
655
+ if (scenario === "components") {
656
+ runScan = await confirm({
657
+ message: "Auto-generate documentation from TypeScript?",
658
+ default: true
659
+ });
660
+ } else {
661
+ createExample = await confirm({
662
+ message: "Create an example Button component to get started?",
663
+ default: true
664
+ });
665
+ }
666
+ startServer = await confirm({
667
+ message: "Start the viewer now?",
668
+ default: true
669
+ });
670
+ }
671
+ console.log(pc2.dim("\nCreating configuration...\n"));
672
+ const includePaths = [
673
+ `${componentPath}/**/*.fragment.tsx`
674
+ ];
675
+ if (scenario === "stories") {
676
+ includePaths.push(`${componentPath}/**/*.stories.tsx`);
677
+ includePaths.push(`${componentPath}/**/*.stories.ts`);
678
+ }
679
+ const configPath = join2(projectRoot, BRAND.configFile);
680
+ const configContent = generateConfig({
681
+ includePaths,
682
+ componentPaths: [`${componentPath}/**/*.tsx`],
683
+ framework: "react"
684
+ });
685
+ try {
686
+ await writeFile2(configPath, configContent, "utf-8");
687
+ console.log(pc2.green(`\u2713 Created ${BRAND.configFile}`));
688
+ } catch (e) {
689
+ errors.push(`Failed to create config: ${e}`);
690
+ }
691
+ if (scenario === "fresh" && createExample) {
692
+ const exampleDir = join2(projectRoot, componentPath, "Button");
693
+ try {
694
+ await mkdir(exampleDir, { recursive: true });
695
+ await writeFile2(
696
+ join2(exampleDir, "Button.tsx"),
697
+ generateExampleComponent(),
698
+ "utf-8"
699
+ );
700
+ console.log(
701
+ pc2.green(`\u2713 Created ${relative(projectRoot, join2(exampleDir, "Button.tsx"))}`)
702
+ );
703
+ await writeFile2(
704
+ join2(exampleDir, "Button.fragment.tsx"),
705
+ generateExampleFragment(),
706
+ "utf-8"
707
+ );
708
+ console.log(
709
+ pc2.green(
710
+ `\u2713 Created ${relative(projectRoot, join2(exampleDir, "Button.fragment.tsx"))}`
711
+ )
712
+ );
713
+ } catch (e) {
714
+ errors.push(`Failed to create example component: ${e}`);
715
+ }
716
+ }
717
+ if (scenario === "components" && runScan) {
718
+ let stubsCreated = 0;
719
+ for (const compFile of detection.componentFiles) {
720
+ const absPath = join2(projectRoot, compFile);
721
+ const dir = dirname(absPath);
722
+ const fileName = basename(compFile, ".tsx");
723
+ const componentName = toPascalCase(fileName);
724
+ const fragmentPath = join2(dir, `${fileName}.fragment.tsx`);
725
+ try {
726
+ await access2(fragmentPath);
727
+ continue;
728
+ } catch {
729
+ }
730
+ try {
731
+ const stub = generateFragmentStub(componentName, `./${fileName}`);
732
+ await writeFile2(fragmentPath, stub, "utf-8");
733
+ stubsCreated++;
734
+ } catch {
735
+ }
736
+ }
737
+ if (stubsCreated > 0) {
738
+ console.log(pc2.green(`\u2713 Generated ${stubsCreated} fragment stub(s)`));
739
+ }
740
+ console.log(pc2.dim("\nGenerating documentation from source code...\n"));
741
+ try {
742
+ const { scan } = await import("./scan-X3DI2X5G.js");
743
+ await scan({
744
+ config: configPath,
745
+ verbose: false
746
+ });
747
+ } catch (e) {
748
+ console.log(
749
+ pc2.yellow(`Note: Auto-documentation will run when you start the dev server.`)
750
+ );
751
+ }
752
+ }
753
+ console.log(pc2.dim("\nConfiguring framework integration...\n"));
754
+ const frameworkOverride = options.framework;
755
+ const frameworkResult = await setupFramework({
756
+ projectRoot,
757
+ framework: frameworkOverride
758
+ });
759
+ if (frameworkResult.filesCreated.length > 0) {
760
+ for (const file of frameworkResult.filesCreated) {
761
+ console.log(pc2.green(`\u2713 Created ${file}`));
762
+ }
763
+ }
764
+ if (frameworkResult.configModified.length > 0) {
765
+ for (const file of frameworkResult.configModified) {
766
+ console.log(pc2.green(`\u2713 Updated ${file}`));
767
+ }
768
+ }
769
+ if (frameworkResult.packagesToInstall.length > 0) {
770
+ const pkgs = frameworkResult.packagesToInstall.join(" ");
771
+ console.log(
772
+ pc2.yellow(`
773
+ \u26A0 Install required dependencies: `) + pc2.bold(`pnpm add -D ${pkgs}`)
774
+ );
775
+ }
776
+ for (const warning of frameworkResult.warnings) {
777
+ console.log(pc2.yellow(` Note: ${warning}`));
778
+ }
779
+ if (errors.length === 0) {
780
+ console.log(pc2.green("\n\u2713 Setup complete!\n"));
781
+ if (startServer) {
782
+ const serverMessage = scenario === "stories" ? `Your ${detection.storyFiles.length} stories are loading...` : scenario === "components" ? `Your ${detection.componentFiles.length} components are being documented...` : `Your first component is ready!`;
783
+ console.log(pc2.cyan(serverMessage));
784
+ startDevServer(projectRoot);
785
+ } else {
786
+ console.log(pc2.cyan("Next steps:"));
787
+ console.log(` 1. Run ${pc2.bold(`${BRAND.cliCommand} dev`)} to start the viewer`);
788
+ if (scenario === "fresh") {
789
+ console.log(` 2. Edit ${pc2.bold(`${componentPath}/Button/Button.fragment.tsx`)}`);
790
+ }
791
+ console.log();
792
+ }
793
+ }
794
+ return {
795
+ success: errors.length === 0,
796
+ configPath: errors.length === 0 ? configPath : void 0,
797
+ scenario,
798
+ storiesFound: detection.storyFiles.length,
799
+ componentsFound: detection.componentFiles.length,
800
+ errors
801
+ };
802
+ }
803
+ export {
804
+ init
805
+ };
806
+ //# sourceMappingURL=init-DIZ6UNBL.js.map