@fragments-sdk/cli 0.5.0 → 0.5.2

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 (33) hide show
  1. package/dist/bin.js +7 -7
  2. package/dist/{chunk-UXRGD3DM.js → chunk-U4GQ2JTD.js} +2 -2
  3. package/dist/{chunk-B2TQKOLW.js → chunk-V7YLRR4C.js} +2 -238
  4. package/dist/chunk-V7YLRR4C.js.map +1 -0
  5. package/dist/{core-NJVKKLJ4.js → core-DKHB7FYV.js} +2 -2
  6. package/dist/{generate-OVGMDKCJ.js → generate-KL24VZVD.js} +2 -2
  7. package/dist/index.d.ts +2 -285
  8. package/dist/index.js +2 -2
  9. package/dist/{init-EOA7TTOR.js → init-NION5S3M.js} +5 -5
  10. package/dist/init-NION5S3M.js.map +1 -0
  11. package/dist/mcp-bin.js +26 -3
  12. package/dist/mcp-bin.js.map +1 -1
  13. package/dist/{scan-YN4LUDKY.js → scan-ESEXV7LF.js} +2 -2
  14. package/dist/{service-2T26CBWE.js → service-RWUMZ3EW.js} +2 -2
  15. package/dist/{static-viewer-CLJJRYHK.js → static-viewer-O37MJ5B6.js} +2 -2
  16. package/dist/{tokens-FHA2DO22.js → tokens-ITADYVPF.js} +2 -2
  17. package/dist/{viewer-XDPD52L7.js → viewer-YDGFDTK5.js} +11 -11
  18. package/package.json +3 -2
  19. package/src/commands/init.ts +2 -2
  20. package/src/core/context.ts +2 -380
  21. package/src/core/types.ts +11 -101
  22. package/src/mcp/__tests__/findFragmentsJson.test.ts +30 -0
  23. package/src/mcp/server.ts +40 -1
  24. package/dist/chunk-B2TQKOLW.js.map +0 -1
  25. package/dist/init-EOA7TTOR.js.map +0 -1
  26. /package/dist/{chunk-UXRGD3DM.js.map → chunk-U4GQ2JTD.js.map} +0 -0
  27. /package/dist/{core-NJVKKLJ4.js.map → core-DKHB7FYV.js.map} +0 -0
  28. /package/dist/{generate-OVGMDKCJ.js.map → generate-KL24VZVD.js.map} +0 -0
  29. /package/dist/{scan-YN4LUDKY.js.map → scan-ESEXV7LF.js.map} +0 -0
  30. /package/dist/{service-2T26CBWE.js.map → service-RWUMZ3EW.js.map} +0 -0
  31. /package/dist/{static-viewer-CLJJRYHK.js.map → static-viewer-O37MJ5B6.js.map} +0 -0
  32. /package/dist/{tokens-FHA2DO22.js.map → tokens-ITADYVPF.js.map} +0 -0
  33. /package/dist/{viewer-XDPD52L7.js.map → viewer-YDGFDTK5.js.map} +0 -0
package/src/mcp/server.ts CHANGED
@@ -152,6 +152,44 @@ function getWorkspaceDirs(rootDir: string): string[] {
152
152
  * Scan a directory's package.json deps for packages with a "fragments" field.
153
153
  * Uses Node.js module resolution (createRequire) to handle all package managers.
154
154
  */
155
+ /**
156
+ * Resolve a dependency's package.json path. Tries the standard subpath first,
157
+ * then falls back to resolving the package's main entry and walking up to
158
+ * find package.json — necessary when the package's `exports` map doesn't
159
+ * expose `./package.json`.
160
+ */
161
+ function resolveDepPackageJson(
162
+ localRequire: NodeRequire,
163
+ depName: string
164
+ ): string | null {
165
+ // Fast path: package exposes ./package.json in exports
166
+ try {
167
+ return localRequire.resolve(`${depName}/package.json`);
168
+ } catch {
169
+ // Blocked by exports map
170
+ }
171
+
172
+ // Fallback: resolve the package's main entry and walk up to package.json
173
+ try {
174
+ const mainPath = localRequire.resolve(depName);
175
+ let dir = dirname(mainPath);
176
+ while (true) {
177
+ const candidate = join(dir, 'package.json');
178
+ if (existsSync(candidate)) {
179
+ const pkg = JSON.parse(readFileSync(candidate, 'utf-8'));
180
+ if (pkg.name === depName) return candidate;
181
+ }
182
+ const parent = dirname(dir);
183
+ if (parent === dir) break;
184
+ dir = parent;
185
+ }
186
+ } catch {
187
+ // Package not resolvable at all
188
+ }
189
+
190
+ return null;
191
+ }
192
+
155
193
  function findFragmentsInDeps(dir: string, found: string[]): void {
156
194
  const pkgJsonPath = join(dir, 'package.json');
157
195
  if (!existsSync(pkgJsonPath)) return;
@@ -165,7 +203,8 @@ function findFragmentsInDeps(dir: string, found: string[]): void {
165
203
  const localRequire = createRequire(join(dir, 'noop.js'));
166
204
  for (const depName of Object.keys(allDeps)) {
167
205
  try {
168
- const depPkgPath = localRequire.resolve(`${depName}/package.json`);
206
+ const depPkgPath = resolveDepPackageJson(localRequire, depName);
207
+ if (!depPkgPath) continue;
169
208
  const depPkg = JSON.parse(readFileSync(depPkgPath, 'utf-8'));
170
209
  if (depPkg.fragments) {
171
210
  const fragmentsPath = join(dirname(depPkgPath), depPkg.fragments);
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/defineSegment.ts","../src/core/storyAdapter.ts","../src/core/storybook-csf.ts","../src/core/context.ts","../src/core/figma.ts","../src/core/token-parser.ts","../src/core/composition.ts"],"sourcesContent":["import type { SegmentDefinition, CompiledSegment, SegmentComponent, BlockDefinition, CompiledBlock } from './types.js';\nimport { segmentDefinitionSchema, blockDefinitionSchema } from './schema.js';\n\n/**\n * Define a segment for a component.\n *\n * This is the main API for creating segment documentation.\n * It provides runtime validation and type safety.\n *\n * @example\n * ```tsx\n * import { defineSegment } from '@fragments/core';\n * import { Button } from './Button';\n *\n * export default defineSegment({\n * component: Button,\n * meta: {\n * name: 'Button',\n * description: 'Primary action trigger',\n * category: 'actions',\n * },\n * usage: {\n * when: ['User needs to trigger an action'],\n * whenNot: ['Navigation without side effects'],\n * },\n * props: {\n * variant: {\n * type: 'enum',\n * values: ['primary', 'secondary'],\n * default: 'primary',\n * description: 'Visual style',\n * },\n * },\n * variants: [\n * {\n * name: 'Default',\n * description: 'Default button',\n * render: () => <Button>Click me</Button>,\n * },\n * ],\n * });\n * ```\n */\nexport function defineSegment<TProps>(\n definition: SegmentDefinition<TProps>\n): SegmentDefinition<TProps> {\n // Validate at runtime in development\n if (process.env.NODE_ENV !== 'production') {\n const result = segmentDefinitionSchema.safeParse(definition);\n if (!result.success) {\n const errors = result.error.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n');\n throw new Error(\n `Invalid segment definition for \"${definition.meta?.name || 'unknown'}\":\\n${errors}`\n );\n }\n }\n\n return definition;\n}\n\n/**\n * Alias for defineSegment - use this for new projects.\n * @see defineSegment\n */\nexport const defineFragment = defineSegment;\n\n/**\n * Compile a segment definition to JSON-serializable format.\n * Used for generating fragments.json for AI consumption.\n */\nexport function compileSegment(\n definition: SegmentDefinition,\n filePath: string\n): CompiledSegment {\n return {\n filePath,\n meta: definition.meta,\n usage: definition.usage,\n props: definition.props,\n relations: definition.relations,\n variants: definition.variants.map((v) => ({\n name: v.name,\n description: v.description,\n code: v.code,\n figma: v.figma,\n })),\n contract: definition.contract,\n _generated: definition._generated,\n };\n}\n\n/**\n * Define a composition block.\n *\n * Blocks are pure data describing how design system components\n * wire together for common use cases.\n */\nexport function defineBlock(definition: BlockDefinition): BlockDefinition {\n if (process.env.NODE_ENV !== 'production') {\n const result = blockDefinitionSchema.safeParse(definition);\n if (!result.success) {\n const errors = result.error.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n');\n throw new Error(\n `Invalid block definition for \"${definition.name || 'unknown'}\":\\n${errors}`\n );\n }\n }\n\n return definition;\n}\n\n/**\n * @deprecated Use defineBlock instead\n */\nexport const defineRecipe = defineBlock;\n\n/**\n * Compile a block definition to JSON-serializable format.\n */\nexport function compileBlock(\n definition: BlockDefinition,\n filePath: string\n): CompiledBlock {\n return {\n filePath,\n name: definition.name,\n description: definition.description,\n category: definition.category,\n components: definition.components,\n code: definition.code,\n tags: definition.tags,\n };\n}\n\n/**\n * @deprecated Use compileBlock instead\n */\nexport const compileRecipe = compileBlock;\n\n/**\n * Type helper for extracting props type from a component\n */\nexport type InferProps<T> = T extends SegmentComponent<infer P> ? P : never;\n","/**\n * Runtime adapter for converting Storybook CSF modules to Segment definitions.\n *\n * This operates on IMPORTED modules at runtime, not source code parsing.\n * By leveraging Vite's module system, we get 100% accurate render functions\n * without any regex or AST parsing complexity.\n *\n * Supports Storybook 8.x with both CSF2 (Template.bind) and CSF3 (object stories).\n */\n\nimport { createElement, type ComponentType, type ReactNode } from \"react\";\nimport { toId, storyNameFromExport, isExportStory } from \"./storybook-csf.js\";\nimport type {\n SegmentDefinition,\n SegmentMeta,\n SegmentUsage,\n PropDefinition,\n SegmentVariant,\n ControlType,\n VariantLoader,\n PlayFunction,\n PlayFunctionContext,\n VariantRenderOptions,\n} from \"./types.js\";\n\n// Re-export @storybook/csf utilities for use in other modules\nexport { toId, storyNameFromExport, isExportStory };\n\n/**\n * Storybook decorator function signature\n */\nexport type Decorator = (\n Story: () => ReactNode,\n context: StoryContext\n) => ReactNode;\n\n/**\n * Storybook loader function signature\n */\nexport type Loader = (context: StoryContext) => Promise<Record<string, unknown>>;\n\n/**\n * Storybook play function signature (internal, extends StoryContext)\n */\ntype StorybookPlayFunction = (context: StorybookPlayFunctionContext) => Promise<void>;\n\n/**\n * Context passed to Storybook play functions (extends StoryContext for compatibility)\n */\ninterface StorybookPlayFunctionContext extends StoryContext {\n canvasElement: HTMLElement;\n step: (name: string, fn: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Context passed to decorators and render functions\n */\nexport interface StoryContext {\n args: Record<string, unknown>;\n argTypes: Record<string, StoryArgType>;\n globals: Record<string, unknown>;\n parameters: Record<string, unknown>;\n id: string;\n kind: string;\n name: string;\n story: string;\n viewMode: \"story\" | \"docs\";\n loaded: Record<string, unknown>;\n abortSignal: AbortSignal;\n componentId: string;\n title: string;\n}\n\n/**\n * Storybook Meta (default export)\n */\nexport interface StoryMeta {\n title?: string;\n component?: ComponentType<unknown>;\n subcomponents?: Record<string, ComponentType<unknown>>;\n tags?: string[];\n parameters?: Record<string, unknown> & {\n docs?: {\n description?: {\n component?: string;\n };\n };\n };\n argTypes?: Record<string, StoryArgType>;\n args?: Record<string, unknown>;\n decorators?: Decorator[];\n loaders?: Loader[];\n render?: (args: Record<string, unknown>, context?: StoryContext) => ReactNode;\n // Story filtering\n includeStories?: string[] | RegExp;\n excludeStories?: string[] | RegExp;\n}\n\n/**\n * Storybook argType definition\n */\nexport interface StoryArgType {\n control?:\n | string\n | false\n | { type: string; min?: number; max?: number; step?: number; presetColors?: string[] };\n options?: string[];\n description?: string;\n table?: {\n defaultValue?: { summary: string };\n type?: { summary: string };\n category?: string;\n subcategory?: string;\n disable?: boolean;\n };\n type?: { name: string; required?: boolean };\n name?: string;\n defaultValue?: unknown;\n if?: { arg?: string; exists?: boolean };\n mapping?: Record<string, unknown>;\n action?: string;\n}\n\n/**\n * Storybook Story export (CSF3)\n */\nexport interface Story {\n args?: Record<string, unknown>;\n argTypes?: Record<string, StoryArgType>;\n render?: (args: Record<string, unknown>, context?: StoryContext) => ReactNode;\n decorators?: Decorator[];\n loaders?: Loader[];\n play?: StorybookPlayFunction;\n parameters?: Record<string, unknown> & {\n docs?: {\n description?: {\n story?: string;\n };\n };\n };\n name?: string;\n storyName?: string; // Legacy CSF2\n tags?: string[];\n}\n\n/**\n * CSF2 story function (from Template.bind({})) with args attached\n */\nexport type CSF2Story = ((args: Record<string, unknown>) => ReactNode) & {\n args?: Record<string, unknown>;\n argTypes?: Record<string, StoryArgType>;\n decorators?: Decorator[];\n loaders?: Loader[];\n play?: StorybookPlayFunction;\n parameters?: Record<string, unknown>;\n storyName?: string;\n};\n\n/**\n * A complete Storybook module with default meta and named story exports\n */\nexport interface StoryModule {\n default: StoryMeta;\n [exportName: string]: Story | CSF2Story | StoryMeta | unknown;\n}\n\n/**\n * Global configuration from preview.tsx\n */\nexport interface PreviewConfig {\n decorators?: Decorator[];\n parameters?: Record<string, unknown>;\n globalTypes?: Record<string, unknown>;\n args?: Record<string, unknown>;\n argTypes?: Record<string, StoryArgType>;\n loaders?: Loader[];\n}\n\n// Store for global preview config (set by previewLoader)\nlet globalPreviewConfig: PreviewConfig = {};\n\n/**\n * Set the global preview configuration loaded from .storybook/preview.tsx\n */\nexport function setPreviewConfig(config: PreviewConfig): void {\n globalPreviewConfig = config;\n}\n\n/**\n * Get the current global preview configuration\n */\nexport function getPreviewConfig(): PreviewConfig {\n return globalPreviewConfig;\n}\n\n/**\n * Convert a Storybook module to a Segment definition at runtime.\n *\n * @param storyModule - The imported Storybook module\n * @param filePath - File path for metadata extraction\n * @returns A complete SegmentDefinition ready for the viewer\n */\nexport function storyModuleToSegment(\n storyModule: StoryModule,\n filePath: string\n): SegmentDefinition | null {\n const meta = storyModule.default;\n const component = meta.component;\n\n // Stories without a component (e.g., documentation pages, icon galleries) are skipped\n if (!component) {\n return null;\n }\n\n const componentName = extractComponentName(meta, filePath);\n const category = extractCategory(meta.title);\n const props = convertArgTypes(meta.argTypes ?? {}, globalPreviewConfig.argTypes);\n const variants = extractVariants(storyModule, component, meta);\n\n // Extract Figma URL from parameters.design.url (storybook-addon-designs) or parameters.figma\n const figmaUrl = extractFigmaUrl(meta.parameters);\n\n const segmentMeta: SegmentMeta = {\n name: componentName,\n description:\n meta.parameters?.docs?.description?.component ??\n `${componentName} component`,\n category,\n tags: meta.tags?.filter((t) => t !== \"autodocs\"),\n status: \"stable\",\n figma: figmaUrl,\n };\n\n const usage: SegmentUsage = {\n when: [`Use ${componentName} for its intended purpose`],\n whenNot: [\"When a more specific component is available\"],\n };\n\n return {\n component,\n meta: segmentMeta,\n usage,\n props,\n variants,\n };\n}\n\n/**\n * Extract component name from meta or file path\n */\nfunction extractComponentName(meta: StoryMeta, filePath: string): string {\n // Try title (last segment of path like \"Components/Forms/Button\" -> \"Button\")\n if (meta.title) {\n const parts = meta.title.split(\"/\");\n return parts[parts.length - 1];\n }\n\n // Try component displayName\n if (meta.component?.displayName) {\n return meta.component.displayName;\n }\n\n // Try component name\n if (meta.component?.name && meta.component.name !== \"Component\") {\n return meta.component.name;\n }\n\n // Fallback: extract from file path\n const match = filePath.match(/([^/\\\\]+)\\.stories\\.(tsx?|jsx?)$/);\n return match?.[1] ?? \"Unknown\";\n}\n\n/**\n * Extract category from Storybook title path\n */\nfunction extractCategory(title?: string): string {\n if (!title) return \"general\";\n\n const parts = title.split(\"/\");\n // \"Components/Forms/Button\" -> \"forms\" (need at least 3 parts for a subcategory)\n if (parts.length >= 3) {\n return parts[parts.length - 2].toLowerCase();\n }\n // \"Components/Button\" -> \"general\" (no subcategory specified)\n return \"general\";\n}\n\n/**\n * Extract Figma URL from Storybook parameters\n * Supports storybook-addon-designs format and custom figma parameter\n */\nfunction extractFigmaUrl(parameters?: Record<string, unknown>): string | undefined {\n if (!parameters) return undefined;\n\n // Try storybook-addon-designs format: parameters.design.url\n const design = parameters.design as { url?: string; type?: string } | undefined;\n if (design?.url && typeof design.url === \"string\") {\n return design.url;\n }\n\n // Try custom figma parameter: parameters.figma\n if (typeof parameters.figma === \"string\") {\n return parameters.figma;\n }\n\n return undefined;\n}\n\n/**\n * Convert Storybook argTypes to Segment props\n * Merges global argTypes from preview config with meta argTypes\n */\nfunction convertArgTypes(\n argTypes: Record<string, StoryArgType>,\n globalArgTypes?: Record<string, StoryArgType>\n): Record<string, PropDefinition> {\n const props: Record<string, PropDefinition> = {};\n\n // Merge global and meta argTypes (meta takes precedence)\n const mergedArgTypes = { ...globalArgTypes, ...argTypes };\n\n for (const [name, argType] of Object.entries(mergedArgTypes)) {\n // Skip disabled argTypes\n if (argType.table?.disable) continue;\n // Skip action-only argTypes (no control)\n if (argType.control === false && argType.action) continue;\n\n // Extract control type and options\n const { controlType, controlOptions } = extractControlInfo(argType);\n\n props[name] = {\n type: inferPropType(argType),\n description: argType.description ?? `${name} prop`,\n ...(argType.options && { values: argType.options }),\n ...(argType.table?.defaultValue && {\n default: argType.table.defaultValue.summary,\n }),\n ...(argType.defaultValue !== undefined && {\n default: argType.defaultValue,\n }),\n ...(argType.type?.required && { required: true }),\n ...(controlType && { controlType }),\n ...(controlOptions && Object.keys(controlOptions).length > 0 && { controlOptions }),\n };\n }\n\n return props;\n}\n\n/**\n * Extract control type and options from a Storybook argType\n */\nfunction extractControlInfo(argType: StoryArgType): {\n controlType?: ControlType;\n controlOptions?: PropDefinition[\"controlOptions\"];\n} {\n // Handle no control or explicitly disabled control\n if (argType.control === undefined || argType.control === false) {\n return {};\n }\n\n const control = typeof argType.control === \"string\"\n ? { type: argType.control }\n : argType.control;\n\n // Map control type string to ControlType\n const validControlTypes: ControlType[] = [\n \"text\", \"number\", \"range\", \"boolean\", \"select\", \"multi-select\",\n \"radio\", \"inline-radio\", \"check\", \"inline-check\", \"object\", \"file\", \"color\", \"date\"\n ];\n\n const controlType = validControlTypes.includes(control.type as ControlType)\n ? (control.type as ControlType)\n : undefined;\n\n // Extract control options for controls that need them\n const controlOptions: PropDefinition[\"controlOptions\"] = {};\n\n if (control.min !== undefined) controlOptions.min = control.min;\n if (control.max !== undefined) controlOptions.max = control.max;\n if (control.step !== undefined) controlOptions.step = control.step;\n if (control.presetColors) controlOptions.presetColors = control.presetColors;\n\n return {\n controlType,\n controlOptions: Object.keys(controlOptions).length > 0 ? controlOptions : undefined,\n };\n}\n\n/**\n * Infer prop type from Storybook control/type\n * Handles all Storybook 8.x control types\n */\nfunction inferPropType(argType: StoryArgType): PropDefinition[\"type\"] {\n // Action argType → function\n if (argType.action) return \"function\";\n\n // If has options, it's an enum\n if (argType.options?.length) return \"enum\";\n\n // Check explicit type\n if (argType.type?.name) {\n const typeMap: Record<string, PropDefinition[\"type\"]> = {\n string: \"string\",\n number: \"number\",\n boolean: \"boolean\",\n object: \"object\",\n array: \"array\",\n function: \"function\",\n };\n const mapped = typeMap[argType.type.name];\n if (mapped) return mapped;\n }\n\n // Check control type\n const control =\n typeof argType.control === \"string\"\n ? argType.control\n : argType.control\n ? argType.control.type\n : undefined;\n\n if (control) {\n const controlMap: Record<string, PropDefinition[\"type\"]> = {\n // Text controls\n text: \"string\",\n\n // Number controls\n number: \"number\",\n range: \"number\",\n\n // Boolean controls\n boolean: \"boolean\",\n check: \"boolean\",\n \"inline-check\": \"boolean\",\n\n // Enum/selection controls\n select: \"enum\",\n \"multi-select\": \"enum\",\n radio: \"enum\",\n \"inline-radio\": \"enum\",\n\n // Object controls\n object: \"object\",\n file: \"object\",\n\n // Special string controls\n color: \"string\",\n date: \"string\",\n };\n const mapped = controlMap[control];\n if (mapped) return mapped;\n }\n\n return \"string\";\n}\n\n/**\n * Check if a value looks like a Storybook story\n * Handles both CSF 3 (objects) and CSF 2 (functions from Template.bind({}))\n */\nfunction isStory(value: unknown): value is Story | CSF2Story {\n // CSF 3: Story is an object with args/render/play\n if (typeof value === \"object\" && value !== null) {\n const obj = value as Record<string, unknown>;\n if (\"args\" in obj || \"render\" in obj || \"play\" in obj) return true;\n }\n\n // CSF 2: Story is a function (from Template.bind({})) with args attached\n if (typeof value === \"function\") {\n const fn = value as ((...args: unknown[]) => unknown) & { args?: unknown };\n if (\"args\" in fn) return true;\n }\n\n return false;\n}\n\n/**\n * Extract variants from story exports using @storybook/csf utilities\n */\nfunction extractVariants(\n storyModule: StoryModule,\n component: ComponentType<unknown>,\n meta: StoryMeta\n): SegmentVariant[] {\n const variants: SegmentVariant[] = [];\n\n for (const [exportName, exportValue] of Object.entries(storyModule)) {\n // Skip default export\n if (exportName === \"default\") continue;\n\n // Use isExportStory to filter based on includeStories/excludeStories\n if (!isExportStory(exportName, meta)) continue;\n\n // Check if it's a story\n if (!isStory(exportValue)) continue;\n\n const story = exportValue as Story | CSF2Story;\n\n // Get story name using storyNameFromExport\n const storyName =\n (typeof story === \"object\" && story.name) ||\n (typeof story === \"object\" && story.storyName) ||\n (typeof story === \"function\" && story.storyName) ||\n storyNameFromExport(exportName);\n\n // Generate story ID matching Storybook format\n const storyId = toId(meta.title || \"Unknown\", exportName);\n\n // Extract description based on story format\n let description = `${storyName} variant`;\n if (typeof story === \"object\" && story.parameters?.docs?.description?.story) {\n description = story.parameters.docs.description.story;\n }\n\n // Check for play function and capture it\n const storyPlayFn = typeof story === \"object\" ? story.play : story.play;\n const hasPlayFunction = !!storyPlayFn;\n\n // Create wrapped play function that adapts Storybook context to our PlayFunctionContext\n const wrappedPlay: PlayFunction | undefined = storyPlayFn\n ? async (context: PlayFunctionContext): Promise<void> => {\n // Build full Storybook context for compatibility\n const args = {\n ...globalPreviewConfig.args,\n ...meta.args,\n ...(typeof story === \"function\" ? story.args : story.args),\n };\n const fullContext = buildStoryContext(meta, story, args, storyId, storyName);\n\n // Merge our context with Storybook context\n const playContext = {\n ...fullContext,\n canvasElement: context.canvasElement,\n args: context.args,\n step: context.step,\n };\n\n await storyPlayFn(playContext as unknown as StorybookPlayFunctionContext);\n }\n : undefined;\n\n // Get story tags\n const storyTags = typeof story === \"object\" ? story.tags : undefined;\n\n // Collect loaders from global, meta, and story (in order)\n const loaders = collectLoaders(meta, story);\n\n // Compute the merged args for this variant (for code generation)\n const variantArgs = {\n ...globalPreviewConfig.args,\n ...meta.args,\n ...(typeof story === \"function\" ? story.args : story.args),\n };\n\n // Only include args if there are any defined\n const hasArgs = Object.keys(variantArgs).length > 0;\n\n variants.push({\n name: storyName,\n description,\n render: createRenderFunction(story, component, meta, storyId, storyName),\n // Store Storybook-specific metadata\n ...(hasPlayFunction && { hasPlayFunction: true }),\n ...(wrappedPlay && { play: wrappedPlay }),\n ...(storyId && { storyId }),\n ...(storyTags && { tags: storyTags }),\n ...(loaders.length > 0 && { loaders }),\n ...(hasArgs && { args: variantArgs }),\n });\n }\n\n return variants;\n}\n\n/**\n * Collect loaders from global, meta, and story levels\n * Returns wrapped loader functions that execute with context\n */\nfunction collectLoaders(\n meta: StoryMeta,\n story: Story | CSF2Story\n): VariantLoader[] {\n const allLoaders: Loader[] = [\n ...(globalPreviewConfig.loaders ?? []),\n ...(meta.loaders ?? []),\n ...(typeof story === \"function\" ? story.loaders ?? [] : story.loaders ?? []),\n ];\n\n if (allLoaders.length === 0) {\n return [];\n }\n\n // Wrap each loader to execute without requiring context at call time\n // The actual context will be built when the loader is executed\n return allLoaders.map((loader) => {\n return async (): Promise<Record<string, unknown>> => {\n // Create a minimal context for loader execution\n const minimalContext: StoryContext = {\n args: {},\n argTypes: {},\n globals: {},\n parameters: {},\n id: \"\",\n kind: meta.title || \"Unknown\",\n name: \"\",\n story: \"\",\n viewMode: \"story\",\n loaded: {},\n abortSignal: new AbortController().signal,\n componentId: \"\",\n title: meta.title || \"Unknown\",\n };\n return loader(minimalContext);\n };\n });\n}\n\n/**\n * Build a StoryContext for decorators and render functions\n */\nfunction buildStoryContext(\n meta: StoryMeta,\n story: Story | CSF2Story,\n args: Record<string, unknown>,\n storyId: string,\n storyName: string,\n loadedData?: Record<string, unknown>\n): StoryContext {\n const mergedArgs = {\n ...globalPreviewConfig.args,\n ...meta.args,\n ...(typeof story === \"object\" ? story.args : story.args),\n ...args,\n };\n\n const mergedArgTypes = {\n ...globalPreviewConfig.argTypes,\n ...meta.argTypes,\n ...(typeof story === \"object\" ? story.argTypes : story.argTypes),\n };\n\n const mergedParameters = {\n ...globalPreviewConfig.parameters,\n ...meta.parameters,\n ...(typeof story === \"object\" ? story.parameters : story.parameters),\n };\n\n return {\n args: mergedArgs,\n argTypes: mergedArgTypes ?? {},\n globals: {},\n parameters: mergedParameters ?? {},\n id: storyId,\n kind: meta.title || \"Unknown\",\n name: storyName,\n story: storyName,\n viewMode: \"story\",\n loaded: loadedData ?? {},\n abortSignal: new AbortController().signal,\n componentId: toId(meta.title || \"Unknown\", \"\"),\n title: meta.title || \"Unknown\",\n };\n}\n\n/**\n * Create a render function for a story\n * Handles both CSF 3 (objects) and CSF 2 (functions)\n * Applies decorators in correct order: story → meta → global (innermost first)\n * Accepts optional args overrides and loaded data from loaders\n */\nfunction createRenderFunction(\n story: Story | CSF2Story,\n component: ComponentType<unknown>,\n meta: StoryMeta,\n storyId: string,\n storyName: string\n): (options?: VariantRenderOptions) => ReactNode {\n return (options?: VariantRenderOptions) => {\n // Merge args: global → meta → story → runtime overrides\n const args = {\n ...globalPreviewConfig.args,\n ...meta.args,\n ...(typeof story === \"function\" ? story.args : story.args),\n ...options?.args, // Runtime overrides from viewer props panel\n };\n\n const loadedData = options?.loadedData;\n\n // Build the story context with loaded data\n const context = buildStoryContext(meta, story, args, storyId, storyName, loadedData);\n\n // Create the base render function\n let renderFn: () => ReactNode;\n\n if (typeof story === \"function\") {\n // CSF 2: Story is a function (from Template.bind({}))\n renderFn = () => story(args);\n } else if (story.render) {\n // CSF 3: Story has custom render function\n // Support both render(args) and render(args, context) signatures\n renderFn = () =>\n story.render!.length >= 2\n ? story.render!(args, context)\n : story.render!(args);\n } else if (meta.render) {\n // CSF 3: Meta has default render function\n renderFn = () =>\n meta.render!.length >= 2\n ? meta.render!(args, context)\n : meta.render!(args);\n } else {\n // Default: render component with args\n renderFn = () => createElement(component, args);\n }\n\n // Collect decorators in Storybook order\n // story → meta → global, then reverse to apply innermost first\n const allDecorators = [\n ...(globalPreviewConfig.decorators ?? []),\n ...(meta.decorators ?? []),\n ...(typeof story === \"function\" ? story.decorators ?? [] : story.decorators ?? []),\n ].reverse();\n\n // Apply decorators if any\n if (allDecorators.length > 0) {\n return applyDecorators(renderFn, allDecorators, context);\n }\n\n return renderFn();\n };\n}\n\n/**\n * Apply decorators in the correct order\n * Decorators wrap from innermost to outermost\n */\nfunction applyDecorators(\n renderFn: () => ReactNode,\n decorators: Decorator[],\n context: StoryContext\n): ReactNode {\n // Start with the base render function\n let storyFn: () => ReactNode = renderFn;\n\n // Each decorator wraps the previous one\n for (const decorator of decorators) {\n const wrappedFn = storyFn;\n storyFn = () => decorator(wrappedFn, context);\n }\n\n return storyFn();\n}\n\n/**\n * Convert PascalCase to Title Case\n * @deprecated Use storyNameFromExport from @storybook/csf instead\n */\nfunction pascalToTitle(name: string): string {\n return name.replace(/([A-Z])/g, \" $1\").trim();\n}\n","import {\n toId as storybookToId,\n storyNameFromExport as storybookStoryNameFromExport,\n isExportStory as storybookIsExportStory,\n} from \"@storybook/csf\";\n\nexport const toId: typeof storybookToId = (...args) => storybookToId(...args);\nexport const storyNameFromExport: typeof storybookStoryNameFromExport = (...args) =>\n storybookStoryNameFromExport(...args);\nexport const isExportStory: typeof storybookIsExportStory = (...args) =>\n storybookIsExportStory(...args);\n","import type { CompiledSegment, CompiledBlock, PropDefinition } from \"./types.js\";\n\n/**\n * Placeholder patterns to filter out from usage text.\n * These are generated by the migrate tool and provide no value.\n */\nconst PLACEHOLDER_PATTERNS = [\n /^\\w+ component is needed$/i,\n /^Alternative component is more appropriate$/i,\n /^Use \\w+ when you need/i,\n];\n\n/**\n * Filter out placeholder text from usage arrays\n */\nfunction filterPlaceholders(items: string[]): string[] {\n return items.filter(item =>\n !PLACEHOLDER_PATTERNS.some(pattern => pattern.test(item.trim()))\n );\n}\n\n/**\n * Options for context generation\n */\nexport interface ContextOptions {\n /** Output format */\n format?: \"markdown\" | \"json\";\n\n /** What to include in the output */\n include?: {\n /** Include prop details (default: true) */\n props?: boolean;\n /** Include variant list (default: true) */\n variants?: boolean;\n /** Include usage guidelines (default: true) */\n usage?: boolean;\n /** Include related components (default: false) */\n relations?: boolean;\n /** Include code examples (default: false) */\n code?: boolean;\n };\n\n /** Compact mode - minimal output for token efficiency */\n compact?: boolean;\n}\n\n/**\n * Result of context generation\n */\nexport interface ContextResult {\n /** The generated context content */\n content: string;\n /** Estimated token count */\n tokenEstimate: number;\n}\n\n/**\n * Generate AI-ready context from compiled segments and optional blocks\n */\nexport function generateContext(\n segments: CompiledSegment[],\n options: ContextOptions = {},\n blocks?: CompiledBlock[]\n): ContextResult {\n const format = options.format ?? \"markdown\";\n const compact = options.compact ?? false;\n\n const include = {\n props: options.include?.props ?? true,\n variants: options.include?.variants ?? true,\n usage: options.include?.usage ?? true,\n relations: options.include?.relations ?? false,\n code: options.include?.code ?? false,\n };\n\n // Sort segments by category, then name\n const sorted = [...segments].sort((a, b) => {\n const catCompare = a.meta.category.localeCompare(b.meta.category);\n if (catCompare !== 0) return catCompare;\n return a.meta.name.localeCompare(b.meta.name);\n });\n\n if (format === \"json\") {\n return generateJsonContext(sorted, include, compact, blocks);\n }\n\n return generateMarkdownContext(sorted, include, compact, blocks);\n}\n\n/**\n * Generate markdown context\n */\nfunction generateMarkdownContext(\n segments: CompiledSegment[],\n include: Required<NonNullable<ContextOptions[\"include\"]>>,\n compact: boolean,\n blocks?: CompiledBlock[]\n): ContextResult {\n const lines: string[] = [];\n\n lines.push(\"# Design System Reference\");\n lines.push(\"\");\n\n // Quick reference table\n lines.push(\"## Quick Reference\");\n lines.push(\"\");\n lines.push(\"| Component | Category | Use For |\");\n lines.push(\"|-----------|----------|---------|\");\n\n for (const segment of segments) {\n const filteredWhen = filterPlaceholders(segment.usage.when);\n const useFor = filteredWhen.slice(0, 2).join(\", \") || segment.meta.description;\n lines.push(`| ${segment.meta.name} | ${segment.meta.category} | ${truncate(useFor, 50)} |`);\n }\n\n lines.push(\"\");\n\n // If compact mode, stop here\n if (compact) {\n const content = lines.join(\"\\n\");\n return {\n content,\n tokenEstimate: estimateTokens(content),\n };\n }\n\n // Full component documentation\n lines.push(\"## Components\");\n lines.push(\"\");\n\n for (const segment of segments) {\n lines.push(`### ${segment.meta.name}`);\n lines.push(\"\");\n\n // Status line\n const statusParts = [`**Category:** ${segment.meta.category}`];\n if (segment.meta.status) {\n statusParts.push(`**Status:** ${segment.meta.status}`);\n }\n lines.push(statusParts.join(\" | \"));\n lines.push(\"\");\n\n if (segment.meta.description) {\n lines.push(segment.meta.description);\n lines.push(\"\");\n }\n\n // Usage guidelines (filter out placeholder text)\n const whenFiltered = filterPlaceholders(segment.usage.when);\n const whenNotFiltered = filterPlaceholders(segment.usage.whenNot);\n\n if (include.usage && (whenFiltered.length > 0 || whenNotFiltered.length > 0)) {\n if (whenFiltered.length > 0) {\n lines.push(\"**When to use:**\");\n for (const when of whenFiltered) {\n lines.push(`- ${when}`);\n }\n lines.push(\"\");\n }\n\n if (whenNotFiltered.length > 0) {\n lines.push(\"**When NOT to use:**\");\n for (const whenNot of whenNotFiltered) {\n lines.push(`- ${whenNot}`);\n }\n lines.push(\"\");\n }\n }\n\n // Props\n if (include.props && Object.keys(segment.props).length > 0) {\n lines.push(\"**Props:**\");\n for (const [name, prop] of Object.entries(segment.props)) {\n lines.push(`- \\`${name}\\`: ${formatPropType(prop)}${prop.required ? \" (required)\" : \"\"}`);\n }\n lines.push(\"\");\n }\n\n // Variants\n if (include.variants && segment.variants.length > 0) {\n const variantNames = segment.variants.map((v) => v.name).join(\", \");\n lines.push(`**Variants:** ${variantNames}`);\n lines.push(\"\");\n\n // Code examples\n if (include.code) {\n for (const variant of segment.variants) {\n if (variant.code) {\n lines.push(`*${variant.name}:*`);\n lines.push(\"```tsx\");\n lines.push(variant.code);\n lines.push(\"```\");\n lines.push(\"\");\n }\n }\n }\n }\n\n // Relations\n if (include.relations && segment.relations && segment.relations.length > 0) {\n lines.push(\"**Related:**\");\n for (const relation of segment.relations) {\n lines.push(`- ${relation.component} (${relation.relationship}): ${relation.note}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"---\");\n lines.push(\"\");\n }\n\n // Blocks section\n if (blocks && blocks.length > 0) {\n lines.push(\"## Blocks\");\n lines.push(\"\");\n lines.push(\"Composition patterns showing how components wire together.\");\n lines.push(\"\");\n\n for (const block of blocks) {\n lines.push(`### ${block.name}`);\n lines.push(\"\");\n lines.push(block.description);\n lines.push(\"\");\n lines.push(`**Category:** ${block.category}`);\n lines.push(`**Components:** ${block.components.join(\", \")}`);\n if (block.tags && block.tags.length > 0) {\n lines.push(`**Tags:** ${block.tags.join(\", \")}`);\n }\n lines.push(\"\");\n lines.push(\"```tsx\");\n lines.push(block.code);\n lines.push(\"```\");\n lines.push(\"\");\n lines.push(\"---\");\n lines.push(\"\");\n }\n }\n\n const content = lines.join(\"\\n\");\n return {\n content,\n tokenEstimate: estimateTokens(content),\n };\n}\n\n/**\n * Generate JSON context\n */\nfunction generateJsonContext(\n segments: CompiledSegment[],\n include: Required<NonNullable<ContextOptions[\"include\"]>>,\n compact: boolean,\n blocks?: CompiledBlock[]\n): ContextResult {\n const categories = [...new Set(segments.map((s) => s.meta.category))].sort();\n\n interface JsonComponent {\n category: string;\n description: string;\n status?: string;\n whenToUse?: string[];\n whenNotToUse?: string[];\n props?: Record<string, { type: string; required?: boolean; default?: unknown; description: string }>;\n variants?: string[];\n relations?: Array<{ component: string; relationship: string; note: string }>;\n }\n\n const components: Record<string, JsonComponent> = {};\n\n for (const segment of segments) {\n const component: JsonComponent = {\n category: segment.meta.category,\n description: segment.meta.description,\n };\n\n if (segment.meta.status) {\n component.status = segment.meta.status;\n }\n\n if (!compact) {\n if (include.usage) {\n const whenFiltered = filterPlaceholders(segment.usage.when);\n const whenNotFiltered = filterPlaceholders(segment.usage.whenNot);\n if (whenFiltered.length > 0) {\n component.whenToUse = whenFiltered;\n }\n if (whenNotFiltered.length > 0) {\n component.whenNotToUse = whenNotFiltered;\n }\n }\n\n if (include.props && Object.keys(segment.props).length > 0) {\n component.props = {};\n for (const [name, prop] of Object.entries(segment.props)) {\n component.props[name] = {\n type: formatPropType(prop),\n description: prop.description,\n };\n if (prop.required) {\n component.props[name].required = true;\n }\n if (prop.default !== undefined) {\n component.props[name].default = prop.default;\n }\n }\n }\n\n if (include.variants && segment.variants.length > 0) {\n component.variants = segment.variants.map((v) => v.name);\n }\n\n if (include.relations && segment.relations && segment.relations.length > 0) {\n component.relations = segment.relations.map((r) => ({\n component: r.component,\n relationship: r.relationship,\n note: r.note,\n }));\n }\n }\n\n components[segment.meta.name] = component;\n }\n\n // Build blocks map\n const blocksMap = blocks && blocks.length > 0\n ? Object.fromEntries(blocks.map(b => [b.name, {\n description: b.description,\n category: b.category,\n components: b.components,\n code: b.code,\n tags: b.tags,\n }]))\n : undefined;\n\n const output = {\n version: \"1.0\",\n generatedAt: new Date().toISOString(),\n summary: {\n totalComponents: segments.length,\n categories,\n ...(blocksMap && { totalBlocks: blocks!.length }),\n },\n components,\n ...(blocksMap && { blocks: blocksMap }),\n };\n\n const content = JSON.stringify(output, null, 2);\n return {\n content,\n tokenEstimate: estimateTokens(content),\n };\n}\n\n/**\n * Format a prop type for display\n */\nfunction formatPropType(prop: PropDefinition): string {\n if (prop.type === \"enum\" && prop.values) {\n return prop.values.map((v) => `\"${v}\"`).join(\" | \");\n }\n if (prop.default !== undefined) {\n return `${prop.type} (default: ${JSON.stringify(prop.default)})`;\n }\n return prop.type;\n}\n\n/**\n * Truncate string to max length\n */\nfunction truncate(str: string, maxLength: number): string {\n if (str.length <= maxLength) return str;\n return str.slice(0, maxLength - 3) + \"...\";\n}\n\n/**\n * Estimate token count (rough approximation: ~4 chars per token)\n */\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","/**\n * Figma property mapping DSL\n *\n * Provides helpers for mapping Figma component properties to code props.\n * Inspired by Figma Code Connect's API.\n *\n * @example\n * ```tsx\n * import { defineSegment, figma } from '@fragments/core';\n *\n * export default defineSegment({\n * component: Button,\n * meta: {\n * name: 'Button',\n * description: 'Primary action trigger',\n * category: 'actions',\n * figma: 'https://figma.com/file/abc/Design?node-id=1-2',\n * figmaProps: {\n * children: figma.string('Label'),\n * disabled: figma.boolean('Disabled'),\n * variant: figma.enum('Type', {\n * 'Primary': 'primary',\n * 'Secondary': 'secondary',\n * }),\n * },\n * },\n * // ...\n * });\n * ```\n */\n\nimport type {\n FigmaStringMapping,\n FigmaBooleanMapping,\n FigmaEnumMapping,\n FigmaInstanceMapping,\n FigmaChildrenMapping,\n FigmaTextContentMapping,\n} from './types.js';\n\n/**\n * Map a Figma text property to a string prop.\n *\n * @param figmaProperty - The name of the text property in Figma\n * @returns A string mapping descriptor\n *\n * @example\n * ```tsx\n * figmaProps: {\n * label: figma.string('Button Text'),\n * placeholder: figma.string('Placeholder'),\n * }\n * ```\n */\nfunction string(figmaProperty: string): FigmaStringMapping {\n return {\n __type: 'figma-string',\n figmaProperty,\n };\n}\n\n/**\n * Map a Figma boolean property to a boolean prop.\n * Optionally map true/false to different values.\n *\n * @param figmaProperty - The name of the boolean property in Figma\n * @param valueMapping - Optional mapping of true/false to other values\n * @returns A boolean mapping descriptor\n *\n * @example\n * ```tsx\n * figmaProps: {\n * disabled: figma.boolean('Disabled'),\n * // Map boolean to string values\n * size: figma.boolean('Large', { true: 'lg', false: 'md' }),\n * }\n * ```\n */\nfunction boolean(\n figmaProperty: string,\n valueMapping?: { true: unknown; false: unknown }\n): FigmaBooleanMapping {\n return {\n __type: 'figma-boolean',\n figmaProperty,\n valueMapping,\n };\n}\n\n/**\n * Map a Figma variant property to an enum prop.\n *\n * @param figmaProperty - The name of the variant property in Figma\n * @param valueMapping - Mapping of Figma values to code values\n * @returns An enum mapping descriptor\n *\n * @example\n * ```tsx\n * figmaProps: {\n * variant: figma.enum('Type', {\n * 'Primary': 'primary',\n * 'Secondary': 'secondary',\n * 'Outline': 'outline',\n * }),\n * size: figma.enum('Size', {\n * 'Small': 'sm',\n * 'Medium': 'md',\n * 'Large': 'lg',\n * }),\n * }\n * ```\n */\nfunction enumValue<T extends Record<string, unknown>>(\n figmaProperty: string,\n valueMapping: T\n): FigmaEnumMapping {\n return {\n __type: 'figma-enum',\n figmaProperty,\n valueMapping,\n };\n}\n\n/**\n * Reference a nested Figma component instance.\n * Use this when a prop accepts a component that's represented\n * as an instance swap in Figma.\n *\n * @param figmaProperty - The name of the instance property in Figma\n * @returns An instance mapping descriptor\n *\n * @example\n * ```tsx\n * figmaProps: {\n * icon: figma.instance('Icon'),\n * avatar: figma.instance('Avatar'),\n * }\n * ```\n */\nfunction instance(figmaProperty: string): FigmaInstanceMapping {\n return {\n __type: 'figma-instance',\n figmaProperty,\n };\n}\n\n/**\n * Render children from specific Figma layers.\n * Use this when children are represented as named layers in Figma.\n *\n * @param layers - Array of layer names to include as children\n * @returns A children mapping descriptor\n *\n * @example\n * ```tsx\n * figmaProps: {\n * children: figma.children(['Title', 'Description', 'Actions']),\n * }\n * ```\n */\nfunction children(layers: string[]): FigmaChildrenMapping {\n return {\n __type: 'figma-children',\n layers,\n };\n}\n\n/**\n * Extract text content from a Figma text layer.\n * Use this when a prop should be the actual text from a layer.\n *\n * @param layer - The name of the text layer in Figma\n * @returns A text content mapping descriptor\n *\n * @example\n * ```tsx\n * figmaProps: {\n * title: figma.textContent('Header Text'),\n * description: figma.textContent('Body Text'),\n * }\n * ```\n */\nfunction textContent(layer: string): FigmaTextContentMapping {\n return {\n __type: 'figma-text-content',\n layer,\n };\n}\n\n/**\n * Figma property mapping helpers.\n *\n * Use these to define how Figma properties map to your component props.\n * The mappings are used for:\n * - Generating accurate code snippets in Figma Dev Mode\n * - AI agents understanding the design-to-code relationship\n * - Automated design verification\n */\nexport const figma = {\n string,\n boolean,\n enum: enumValue,\n instance,\n children,\n textContent,\n} as const;\n\n/**\n * Helper type to check if a value is a Figma prop mapping\n */\nexport function isFigmaPropMapping(\n value: unknown\n): value is FigmaStringMapping | FigmaBooleanMapping | FigmaEnumMapping | FigmaInstanceMapping | FigmaChildrenMapping | FigmaTextContentMapping {\n if (typeof value !== 'object' || value === null || !('__type' in value)) {\n return false;\n }\n const typeValue = (value as Record<string, unknown>).__type;\n return typeof typeValue === 'string' && typeValue.startsWith('figma-');\n}\n\n/**\n * Resolve a Figma prop mapping to an actual value given Figma property values.\n *\n * @param mapping - The Figma prop mapping\n * @param figmaValues - Object containing Figma property values\n * @returns The resolved value for the code prop\n */\nexport function resolveFigmaMapping(\n mapping: FigmaStringMapping | FigmaBooleanMapping | FigmaEnumMapping | FigmaInstanceMapping | FigmaChildrenMapping | FigmaTextContentMapping,\n figmaValues: Record<string, unknown>\n): unknown {\n switch (mapping.__type) {\n case 'figma-string':\n return figmaValues[mapping.figmaProperty] ?? '';\n\n case 'figma-boolean': {\n const boolValue = figmaValues[mapping.figmaProperty] as boolean;\n if (mapping.valueMapping) {\n return boolValue ? mapping.valueMapping.true : mapping.valueMapping.false;\n }\n return boolValue;\n }\n\n case 'figma-enum': {\n const enumKey = figmaValues[mapping.figmaProperty] as string;\n return mapping.valueMapping[enumKey] ?? enumKey;\n }\n\n case 'figma-instance':\n // Instance mappings return the instance reference\n return figmaValues[mapping.figmaProperty];\n\n case 'figma-children':\n // Children mappings return array of layer contents\n return mapping.layers.map((layer) => figmaValues[layer]);\n\n case 'figma-text-content':\n return figmaValues[mapping.layer] ?? '';\n\n default:\n return undefined;\n }\n}\n","/**\n * Token Parser — extracts CSS custom property declarations from SCSS/CSS files.\n *\n * Parses files for `--prefix-*: value;` declarations and groups them\n * by SCSS comment sections (e.g., `// Typography`, `// Colors`).\n * Falls back to naming-convention-based categorization when comments\n * are absent.\n */\n\nexport interface ParsedToken {\n /** Full CSS variable name (e.g., \"--fui-color-accent\") */\n name: string;\n /** Category inferred from SCSS comment or naming convention */\n category: string;\n /** Description from inline comment, if any */\n description?: string;\n}\n\nexport interface TokenParseOutput {\n /** Detected prefix (e.g., \"--fui-\") */\n prefix: string;\n /** Tokens grouped by category */\n categories: Record<string, ParsedToken[]>;\n /** Total number of tokens found */\n total: number;\n}\n\n/**\n * Category inference from naming conventions.\n * Order matters — first match wins.\n */\nconst NAMING_RULES: Array<{ pattern: RegExp; category: string }> = [\n { pattern: /--\\w+-font-/, category: 'typography' },\n { pattern: /--\\w+-line-height-/, category: 'typography' },\n { pattern: /--\\w+-space-/, category: 'spacing' },\n { pattern: /--\\w+-padding-/, category: 'spacing' },\n { pattern: /--\\w+-radius-/, category: 'radius' },\n { pattern: /--\\w+-color-/, category: 'colors' },\n { pattern: /--\\w+-bg-/, category: 'surfaces' },\n { pattern: /--\\w+-text-/, category: 'text' },\n { pattern: /--\\w+-border/, category: 'borders' },\n { pattern: /--\\w+-shadow-/, category: 'shadows' },\n { pattern: /--\\w+-focus-/, category: 'focus' },\n { pattern: /--\\w+-transition-/, category: 'transitions' },\n { pattern: /--\\w+-scrollbar-/, category: 'scrollbar' },\n { pattern: /--\\w+-z-index/, category: 'z-index' },\n { pattern: /--\\w+-(button|input|touch)-/, category: 'component-sizing' },\n { pattern: /--\\w+-appshell-/, category: 'layout' },\n { pattern: /--\\w+-header-/, category: 'layout' },\n { pattern: /--\\w+-code-/, category: 'code' },\n { pattern: /--\\w+-tooltip-/, category: 'tooltip' },\n { pattern: /--\\w+-hero-/, category: 'marketing' },\n];\n\n/**\n * Infer category from a CSS variable name using naming conventions.\n */\nfunction inferCategory(name: string): string {\n for (const rule of NAMING_RULES) {\n if (rule.pattern.test(name)) {\n return rule.category;\n }\n }\n return 'other';\n}\n\n/**\n * Detect the most common prefix from a list of CSS variable names.\n * E.g., given [\"--fui-color-accent\", \"--fui-bg-primary\"] → \"--fui-\"\n */\nfunction detectPrefix(names: string[]): string {\n if (names.length === 0) return '--';\n\n // Find common prefix after \"--\"\n const stripped = names.map((n) => n.slice(2)); // remove \"--\"\n let prefix = '';\n const first = stripped[0];\n\n for (let i = 0; i < first.length; i++) {\n const ch = first[i];\n if (stripped.every((s) => s[i] === ch)) {\n prefix += ch;\n } else {\n break;\n }\n }\n\n // Trim to last hyphen to get clean prefix\n const lastHyphen = prefix.lastIndexOf('-');\n if (lastHyphen > 0) {\n prefix = prefix.slice(0, lastHyphen + 1);\n }\n\n return `--${prefix}`;\n}\n\n/**\n * Normalize a SCSS comment into a category name.\n * \"// Typography\" → \"typography\"\n * \"// Component heights\" → \"component-sizing\"\n * \"// Hero/Marketing gradient\" → \"marketing\"\n */\nfunction normalizeCategory(comment: string): string {\n const text = comment\n .trim()\n .replace(/^\\/\\/\\s*/, '')\n .replace(/^\\/\\*+\\s*/, '')\n .replace(/\\s*\\*+\\/$/, '')\n .trim()\n .toLowerCase();\n\n // Map common comment headings to clean category names\n const mappings: Record<string, string> = {\n 'base configuration': 'base',\n 'typography': 'typography',\n 'spacing (micro)': 'spacing',\n 'spacing': 'spacing',\n 'density padding': 'spacing',\n 'border radius': 'radius',\n 'transitions': 'transitions',\n 'colors': 'colors',\n 'surfaces': 'surfaces',\n 'text': 'text',\n 'borders': 'borders',\n 'shadows': 'shadows',\n 'focus': 'focus',\n 'scrollbar': 'scrollbar',\n 'component heights': 'component-sizing',\n 'appshell layout': 'layout',\n 'codeblock': 'code',\n 'tooltip': 'tooltip',\n 'hero/marketing gradient': 'marketing',\n };\n\n return mappings[text] ?? text.replace(/\\s+/g, '-');\n}\n\n/**\n * Parse a SCSS or CSS file and extract CSS custom property declarations.\n *\n * Handles two grouping strategies:\n * 1. Comment-based: Uses `// Category` comments above groups of declarations\n * 2. Naming-based: Falls back to inferring category from variable name patterns\n */\nexport function parseTokenFile(content: string, filePath: string): TokenParseOutput {\n const lines = content.split('\\n');\n const tokens: ParsedToken[] = [];\n const seenNames = new Set<string>();\n let currentCategory = 'other';\n let hasCommentCategories = false;\n\n // Regex for CSS custom property declarations\n // Matches: --name: value; (with optional SCSS interpolation)\n const varDeclRegex = /^\\s*(--[\\w-]+)\\s*:/;\n // Regex for section comments (// Category or /* Category */)\n // Allow any characters after uppercase start (including / for \"Hero/Marketing\")\n const sectionCommentRegex = /^\\s*\\/\\/\\s+([A-Z].+)$/;\n\n for (const line of lines) {\n // Check for section comment\n const commentMatch = line.match(sectionCommentRegex);\n if (commentMatch) {\n const normalized = normalizeCategory(commentMatch[0]);\n if (normalized) {\n currentCategory = normalized;\n hasCommentCategories = true;\n }\n continue;\n }\n\n // Check for CSS variable declaration\n const varMatch = line.match(varDeclRegex);\n if (varMatch) {\n const name = varMatch[1];\n\n // Deduplicate: keep only the first occurrence of each variable.\n // Dark mode and high contrast blocks redefine the same variables\n // with different values — we only want the canonical list.\n if (seenNames.has(name)) continue;\n seenNames.add(name);\n\n // Extract inline comment if present\n const inlineComment = line.match(/\\/\\/\\s*(.+)$/);\n const description = inlineComment ? inlineComment[1].trim() : undefined;\n\n tokens.push({\n name,\n category: hasCommentCategories ? currentCategory : inferCategory(name),\n description,\n });\n }\n }\n\n // Group by category\n const categories: Record<string, ParsedToken[]> = {};\n for (const token of tokens) {\n if (!categories[token.category]) {\n categories[token.category] = [];\n }\n categories[token.category].push(token);\n }\n\n // Detect prefix\n const prefix = detectPrefix(tokens.map((t) => t.name));\n\n return {\n prefix,\n categories,\n total: tokens.length,\n };\n}\n","import type { CompiledSegment, RelationshipType } from \"./types.js\";\n\n// --- Public types ---\n\nexport interface CompositionWarning {\n type:\n | \"missing_parent\"\n | \"missing_child\"\n | \"missing_composition\"\n | \"redundant_alternative\"\n | \"deprecated\"\n | \"experimental\";\n component: string;\n message: string;\n relatedComponent?: string;\n}\n\nexport interface CompositionSuggestion {\n component: string;\n reason: string;\n relationship: RelationshipType | \"category_gap\";\n sourceComponent: string;\n}\n\nexport interface CompositionGuideline {\n component: string;\n guideline: string;\n}\n\nexport interface CompositionAnalysis {\n /** The validated component names (filtered to those that exist) */\n components: string[];\n\n /** Components requested but not found in the registry */\n unknown: string[];\n\n /** Issues with the current selection */\n warnings: CompositionWarning[];\n\n /** Components to consider adding */\n suggestions: CompositionSuggestion[];\n\n /** Relevant usage guidelines for the selected components */\n guidelines: CompositionGuideline[];\n}\n\n// --- Category affinities ---\n\nconst CATEGORY_AFFINITIES: Record<string, string[]> = {\n forms: [\"feedback\"],\n actions: [\"feedback\"],\n};\n\n// --- Main function ---\n\n/**\n * Analyzes a set of components as a composition group.\n * Returns warnings about missing relations, usage conflicts,\n * and suggestions for additional components.\n *\n * Browser-safe: no Node.js APIs used.\n */\nexport function analyzeComposition(\n segments: Record<string, CompiledSegment>,\n componentNames: string[],\n _context?: string\n): CompositionAnalysis {\n const allNames = new Set(Object.keys(segments));\n\n // 1. Validate names\n const components: string[] = [];\n const unknown: string[] = [];\n for (const name of componentNames) {\n if (allNames.has(name)) {\n components.push(name);\n } else {\n unknown.push(name);\n }\n }\n\n const selectedSet = new Set(components);\n const warnings: CompositionWarning[] = [];\n const suggestions: CompositionSuggestion[] = [];\n const guidelines: CompositionGuideline[] = [];\n\n // Track suggestions to avoid duplicates\n const suggestedSet = new Set<string>();\n\n for (const name of components) {\n const segment = segments[name];\n\n // 2. Relation checks\n if (segment.relations) {\n for (const rel of segment.relations) {\n switch (rel.relationship) {\n case \"parent\":\n if (!selectedSet.has(rel.component)) {\n warnings.push({\n type: \"missing_parent\",\n component: name,\n message: `\"${name}\" expects to be wrapped by \"${rel.component}\"${rel.note ? `: ${rel.note}` : \"\"}`,\n relatedComponent: rel.component,\n });\n }\n break;\n\n case \"child\":\n if (!selectedSet.has(rel.component) && !suggestedSet.has(rel.component)) {\n suggestions.push({\n component: rel.component,\n reason: `\"${name}\" typically contains \"${rel.component}\"${rel.note ? `: ${rel.note}` : \"\"}`,\n relationship: \"child\",\n sourceComponent: name,\n });\n suggestedSet.add(rel.component);\n }\n break;\n\n case \"composition\":\n if (!selectedSet.has(rel.component)) {\n warnings.push({\n type: \"missing_composition\",\n component: name,\n message: `\"${name}\" is typically used together with \"${rel.component}\"${rel.note ? `: ${rel.note}` : \"\"}`,\n relatedComponent: rel.component,\n });\n }\n break;\n\n case \"sibling\":\n if (!selectedSet.has(rel.component) && !suggestedSet.has(rel.component)) {\n suggestions.push({\n component: rel.component,\n reason: `\"${rel.component}\" is a sibling of \"${name}\"${rel.note ? `: ${rel.note}` : \"\"}`,\n relationship: \"sibling\",\n sourceComponent: name,\n });\n suggestedSet.add(rel.component);\n }\n break;\n\n case \"alternative\":\n if (selectedSet.has(rel.component)) {\n warnings.push({\n type: \"redundant_alternative\",\n component: name,\n message: `\"${name}\" and \"${rel.component}\" are alternatives — using both may be redundant${rel.note ? `: ${rel.note}` : \"\"}`,\n relatedComponent: rel.component,\n });\n }\n break;\n }\n }\n }\n\n // 3. Usage conflict checks (whenNot)\n if (segment.usage?.whenNot) {\n for (const whenNotEntry of segment.usage.whenNot) {\n const lower = whenNotEntry.toLowerCase();\n for (const other of components) {\n if (other !== name && lower.includes(other.toLowerCase())) {\n guidelines.push({\n component: name,\n guideline: `Potential conflict with \"${other}\": ${whenNotEntry}`,\n });\n }\n }\n }\n }\n\n // 4. Status warnings\n if (segment.meta.status === \"deprecated\") {\n warnings.push({\n type: \"deprecated\",\n component: name,\n message: segment.meta.description\n ? `\"${name}\" is deprecated: ${segment.meta.description}`\n : `\"${name}\" is deprecated`,\n });\n } else if (segment.meta.status === \"experimental\") {\n warnings.push({\n type: \"experimental\",\n component: name,\n message: `\"${name}\" is experimental and may change without notice`,\n });\n }\n }\n\n // 5. Category gap analysis\n const selectedCategories = new Set(\n components.map((name) => segments[name].meta.category)\n );\n\n for (const [category, affinities] of Object.entries(CATEGORY_AFFINITIES)) {\n if (!selectedCategories.has(category)) continue;\n\n for (const neededCategory of affinities) {\n if (selectedCategories.has(neededCategory)) continue;\n\n // Find the best component from the needed category\n const candidate = findBestCategoryCandidate(\n segments,\n neededCategory,\n selectedSet,\n suggestedSet\n );\n if (candidate) {\n suggestions.push({\n component: candidate,\n reason: `Compositions using \"${category}\" components often benefit from a \"${neededCategory}\" component`,\n relationship: \"category_gap\",\n sourceComponent: components.find(\n (n) => segments[n].meta.category === category\n )!,\n });\n suggestedSet.add(candidate);\n }\n }\n }\n\n return { components, unknown, warnings, suggestions, guidelines };\n}\n\n/**\n * Find the best candidate component from a given category.\n * Prefers stable components and avoids already-selected or already-suggested ones.\n */\nfunction findBestCategoryCandidate(\n segments: Record<string, CompiledSegment>,\n category: string,\n selectedSet: Set<string>,\n suggestedSet: Set<string>\n): string | null {\n let best: string | null = null;\n let bestScore = -1;\n\n for (const [name, segment] of Object.entries(segments)) {\n if (segment.meta.category !== category) continue;\n if (selectedSet.has(name) || suggestedSet.has(name)) continue;\n\n const status = segment.meta.status ?? \"stable\";\n let score = 0;\n if (status === \"stable\") score = 3;\n else if (status === \"beta\") score = 2;\n else if (status === \"experimental\") score = 1;\n // deprecated gets 0\n\n if (score > bestScore) {\n bestScore = score;\n best = name;\n }\n }\n\n return best;\n}\n"],"mappings":";;;;;;;AA2CO,SAAS,cACd,YAC2B;AAE3B,MAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,UAAM,SAAS,wBAAwB,UAAU,UAAU;AAC3D,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,SAAS,OAAO,MAAM,OACzB,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,KAAK,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,EAClD,KAAK,IAAI;AACZ,YAAM,IAAI;AAAA,QACR,mCAAmC,WAAW,MAAM,QAAQ,SAAS;AAAA,EAAO,MAAM;AAAA,MAC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AEhB,aAAW,CAAC,MAAM,OAAO,KAAK,OAAO,QAAQ,QAAQ,GAAG;AACtD,QAAI,QAAQ,KAAK,aAAa,SAAU;AACxC,QAAI,YAAY,IAAI,IAAI,KAAK,aAAa,IAAI,IAAI,EAAG;AAErD,UAAM,SAAS,QAAQ,KAAK,UAAU;AACtC,QAAI,QAAQ;AACZ,QAAI,WAAW,SAAU,SAAQ;AAAA,aACxB,WAAW,OAAQ,SAAQ;AAAA,aAC3B,WAAW,eAAgB,SAAQ;AAG5C,QAAI,QAAQ,WAAW;AACrB,kBAAY;AACZ,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["content"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/init.ts"],"sourcesContent":["/**\n * fragments init - Smart interactive initialization\n *\n * Handles three scenarios:\n * 1. Stories found → Configure and load existing stories\n * 2. Components found (no stories) → Auto-generate documentation\n * 3. Fresh project → Guided setup with example component\n */\n\nimport { readFile, writeFile, mkdir, access } from \"node:fs/promises\";\nimport { resolve, join, relative } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport pc from \"picocolors\";\nimport { BRAND } from \"../core/index.js\";\nimport fg from \"fast-glob\";\nimport { input, confirm, select } from \"@inquirer/prompts\";\n\nexport interface InitOptions {\n /** Project root directory */\n projectRoot?: string;\n /** Force overwrite existing config */\n force?: boolean;\n /** Non-interactive mode - auto-detect and use defaults */\n yes?: boolean;\n}\n\nexport interface InitResult {\n success: boolean;\n configPath?: string;\n scenario: \"stories\" | \"components\" | \"fresh\";\n storiesFound: number;\n componentsFound: number;\n errors: string[];\n}\n\ninterface DetectionResult {\n storyFiles: string[];\n componentFiles: string[];\n hasConfig: boolean;\n configPath: string | null;\n suggestedComponentPath: string;\n}\n\n/**\n * Detect what exists in the project\n */\nasync function detectProject(projectRoot: string): Promise<DetectionResult> {\n console.log(pc.dim(\"\\nScanning project...\\n\"));\n\n // Check for existing config\n const configPath = join(projectRoot, BRAND.configFile);\n const legacyConfigPath = join(projectRoot, BRAND.legacyConfigFile);\n let hasConfig = false;\n let foundConfigPath: string | null = null;\n\n try {\n await access(configPath);\n hasConfig = true;\n foundConfigPath = configPath;\n } catch {\n try {\n await access(legacyConfigPath);\n hasConfig = true;\n foundConfigPath = legacyConfigPath;\n } catch {\n // No config\n }\n }\n\n // Scan for story files\n const storyFiles = await fg(\n [\"**/*.stories.tsx\", \"**/*.stories.ts\", \"**/*.stories.jsx\", \"**/*.stories.js\"],\n {\n cwd: projectRoot,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/.storybook/**\"],\n }\n );\n\n // Scan for component files (React components)\n const componentFiles = await fg(\n [\"**/components/**/*.tsx\", \"**/Components/**/*.tsx\", \"src/**/*.tsx\"],\n {\n cwd: projectRoot,\n ignore: [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/*.stories.*\",\n \"**/*.test.*\",\n \"**/*.spec.*\",\n \"**/*.d.ts\",\n \"**/index.tsx\", // Skip barrel files\n ],\n }\n );\n\n // Filter to likely component files (capitalized names, not utility files)\n const likelyComponents = componentFiles.filter((f) => {\n const fileName = f.split(\"/\").pop() || \"\";\n return /^[A-Z]/.test(fileName) && !fileName.includes(\".styles\");\n });\n\n // Suggest component path based on what we found\n let suggestedComponentPath = \"src/components\";\n if (likelyComponents.length > 0) {\n const firstComponent = likelyComponents[0];\n const parts = firstComponent.split(\"/\");\n const componentsIndex = parts.findIndex(\n (p) => p.toLowerCase() === \"components\"\n );\n if (componentsIndex !== -1) {\n suggestedComponentPath = parts.slice(0, componentsIndex + 1).join(\"/\");\n }\n }\n\n return {\n storyFiles,\n componentFiles: likelyComponents,\n hasConfig,\n configPath: foundConfigPath,\n suggestedComponentPath,\n };\n}\n\n/**\n * Generate config file content\n */\nfunction generateConfig(options: {\n includePaths: string[];\n componentPaths: string[];\n framework: string;\n}): string {\n const includeStr = options.includePaths.map((p) => ` '${p}'`).join(\",\\n\");\n const componentStr = options.componentPaths.map((p) => ` '${p}'`).join(\",\\n\");\n\n return `import type { FragmentsConfig } from '@fragments/core';\n\nconst config: FragmentsConfig = {\n // Glob patterns for finding fragment/story files\n include: [\n${includeStr}\n ],\n\n // Glob patterns to exclude\n exclude: ['**/node_modules/**'],\n\n // Glob patterns for finding component files (for auto-documentation)\n components: [\n${componentStr}\n ],\n\n // Framework (react, vue, svelte)\n framework: '${options.framework}',\n};\n\nexport default config;\n`;\n}\n\n/**\n * Generate example Button component\n */\nfunction generateExampleComponent(): string {\n return `import React from 'react';\n\nexport interface ButtonProps {\n /** Button label */\n children: React.ReactNode;\n /** Visual style variant */\n variant?: 'primary' | 'secondary' | 'ghost';\n /** Button size */\n size?: 'sm' | 'md' | 'lg';\n /** Disabled state */\n disabled?: boolean;\n /** Click handler */\n onClick?: () => void;\n}\n\nexport function Button({\n children,\n variant = 'primary',\n size = 'md',\n disabled = false,\n onClick,\n}: ButtonProps) {\n const baseStyles = 'inline-flex items-center justify-center font-medium rounded-md transition-colors';\n\n const variantStyles = {\n primary: 'bg-blue-600 text-white hover:bg-blue-700',\n secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300',\n ghost: 'bg-transparent text-gray-700 hover:bg-gray-100',\n };\n\n const sizeStyles = {\n sm: 'px-3 py-1.5 text-sm',\n md: 'px-4 py-2 text-base',\n lg: 'px-6 py-3 text-lg',\n };\n\n return (\n <button\n className={\\`\\${baseStyles} \\${variantStyles[variant]} \\${sizeStyles[size]}\\`}\n disabled={disabled}\n onClick={onClick}\n >\n {children}\n </button>\n );\n}\n`;\n}\n\n/**\n * Generate example Button fragment file\n */\nfunction generateExampleFragment(): string {\n return `import React from 'react';\nimport { defineFragment } from '@fragments/core';\nimport { Button } from './Button';\n\nexport default defineFragment({\n component: Button,\n\n meta: {\n name: 'Button',\n description: 'Interactive button for triggering actions',\n category: 'Actions',\n status: 'stable',\n },\n\n usage: {\n when: [\n 'Triggering an action (save, submit, delete)',\n 'Form submission',\n 'Opening dialogs or menus',\n ],\n whenNot: [\n 'Simple navigation (use Link)',\n 'Toggling state (use Switch)',\n ],\n guidelines: [\n 'Use Primary for the main action in a context',\n 'Only one Primary button per section',\n ],\n },\n\n props: {\n children: {\n type: 'node',\n required: true,\n description: 'Button label content',\n },\n variant: {\n type: 'enum',\n values: ['primary', 'secondary', 'ghost'],\n default: 'primary',\n description: 'Visual style variant',\n },\n size: {\n type: 'enum',\n values: ['sm', 'md', 'lg'],\n default: 'md',\n description: 'Button size',\n },\n },\n\n variants: [\n {\n name: 'Primary',\n description: 'Default action button',\n render: () => <Button variant=\"primary\">Save Changes</Button>,\n },\n {\n name: 'Secondary',\n description: 'Less prominent action',\n render: () => <Button variant=\"secondary\">Cancel</Button>,\n },\n {\n name: 'Ghost',\n description: 'Minimal visual weight',\n render: () => <Button variant=\"ghost\">Learn More</Button>,\n },\n {\n name: 'Sizes',\n description: 'Available size options',\n render: () => (\n <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>\n <Button size=\"sm\">Small</Button>\n <Button size=\"md\">Medium</Button>\n <Button size=\"lg\">Large</Button>\n </div>\n ),\n },\n ],\n});\n`;\n}\n\n/**\n * Start the dev server\n */\nfunction startDevServer(projectRoot: string): void {\n console.log(pc.dim(\"\\nStarting development server...\\n\"));\n\n // Use process.platform to determine the correct command\n const isWindows = process.platform === \"win32\";\n const cmd = isWindows ? \"npx.cmd\" : \"npx\";\n\n const child = spawn(cmd, [BRAND.cliCommand, \"dev\"], {\n cwd: projectRoot,\n stdio: \"inherit\",\n });\n\n child.on(\"error\", (err) => {\n console.error(pc.red(\"Failed to start dev server:\"), err.message);\n });\n}\n\n/**\n * Main init function - smart and interactive by default\n */\nexport async function init(options: InitOptions = {}): Promise<InitResult> {\n const projectRoot = resolve(options.projectRoot || process.cwd());\n const errors: string[] = [];\n\n console.log(pc.cyan(`\\n✨ Welcome to ${BRAND.name}!\\n`));\n\n // Step 1: Detect what exists\n const detection = await detectProject(projectRoot);\n\n // Check for existing config\n if (detection.hasConfig && !options.force) {\n console.log(pc.yellow(`⚠ Config already exists: ${BRAND.configFile}`));\n\n if (!options.yes) {\n const overwrite = await confirm({\n message: \"Do you want to reinitialize? (This will overwrite your config)\",\n default: false,\n });\n\n if (!overwrite) {\n console.log(pc.dim(`\\nKeeping existing configuration. Run \\`${BRAND.cliCommand} dev\\` to start.\\n`));\n return {\n success: true,\n scenario: \"stories\",\n storiesFound: detection.storyFiles.length,\n componentsFound: detection.componentFiles.length,\n errors: [],\n };\n }\n }\n }\n\n // Step 2: Determine scenario and show what we found\n let scenario: \"stories\" | \"components\" | \"fresh\";\n\n if (detection.storyFiles.length > 0) {\n scenario = \"stories\";\n console.log(pc.green(`✓ Found ${detection.storyFiles.length} Storybook story file(s)`));\n console.log(pc.dim(` ${detection.storyFiles.slice(0, 3).join(\"\\n \")}`));\n if (detection.storyFiles.length > 3) {\n console.log(pc.dim(` ... and ${detection.storyFiles.length - 3} more`));\n }\n console.log();\n console.log(\n pc.cyan(\"Great news! \") +\n \"Fragments can load your existing stories automatically.\"\n );\n } else if (detection.componentFiles.length > 0) {\n scenario = \"components\";\n console.log(pc.green(`✓ Found ${detection.componentFiles.length} component file(s)`));\n console.log(pc.dim(` ${detection.componentFiles.slice(0, 3).join(\"\\n \")}`));\n if (detection.componentFiles.length > 3) {\n console.log(pc.dim(` ... and ${detection.componentFiles.length - 3} more`));\n }\n console.log();\n console.log(\n pc.cyan(\"No stories found, but that's fine! \") +\n \"Fragments can auto-generate documentation from your TypeScript.\"\n );\n } else {\n scenario = \"fresh\";\n console.log(pc.yellow(\"No components or stories found.\"));\n console.log();\n console.log(pc.cyan(\"Let's create your first fragment!\"));\n }\n\n console.log();\n\n // Step 3: Gather configuration (interactive unless --yes)\n let componentPath = detection.suggestedComponentPath;\n let runScan = scenario === \"components\";\n let createExample = scenario === \"fresh\";\n let startServer = true;\n\n if (!options.yes) {\n // Ask about component location\n componentPath = await input({\n message: \"Where are your components located?\",\n default: detection.suggestedComponentPath,\n });\n\n if (scenario === \"components\") {\n // For component-only projects, ask about scanning\n runScan = await confirm({\n message: \"Auto-generate documentation from TypeScript?\",\n default: true,\n });\n } else {\n // Fresh project - ask about example\n createExample = await confirm({\n message: \"Create an example Button component to get started?\",\n default: true,\n });\n }\n\n // Ask about starting the server\n startServer = await confirm({\n message: \"Start the viewer now?\",\n default: true,\n });\n }\n\n // Step 4: Create configuration\n console.log(pc.dim(\"\\nCreating configuration...\\n\"));\n\n // Build include patterns\n // Note: Stories are loaded separately by the viewer, not via include patterns\n const includePaths: string[] = [\n `${componentPath}/**/*.fragment.tsx`,\n `${componentPath}/**/*.segment.tsx`, // Legacy support\n ];\n\n // Create config file\n const configPath = join(projectRoot, BRAND.configFile);\n const configContent = generateConfig({\n includePaths,\n componentPaths: [`${componentPath}/**/*.tsx`],\n framework: \"react\",\n });\n\n try {\n await writeFile(configPath, configContent, \"utf-8\");\n console.log(pc.green(`✓ Created ${BRAND.configFile}`));\n } catch (e) {\n errors.push(`Failed to create config: ${e}`);\n }\n\n // Step 5: Handle scenario-specific setup\n if (scenario === \"fresh\" && createExample) {\n // Create example component\n const exampleDir = join(projectRoot, componentPath, \"Button\");\n\n try {\n await mkdir(exampleDir, { recursive: true });\n\n // Write Button.tsx\n await writeFile(\n join(exampleDir, \"Button.tsx\"),\n generateExampleComponent(),\n \"utf-8\"\n );\n console.log(\n pc.green(`✓ Created ${relative(projectRoot, join(exampleDir, \"Button.tsx\"))}`)\n );\n\n // Write Button.fragment.tsx\n await writeFile(\n join(exampleDir, \"Button.fragment.tsx\"),\n generateExampleFragment(),\n \"utf-8\"\n );\n console.log(\n pc.green(\n `✓ Created ${relative(projectRoot, join(exampleDir, \"Button.fragment.tsx\"))}`\n )\n );\n } catch (e) {\n errors.push(`Failed to create example component: ${e}`);\n }\n }\n\n if (scenario === \"components\" && runScan) {\n // Run scan to generate fragments.json\n console.log(pc.dim(\"\\nGenerating documentation from source code...\\n\"));\n try {\n const { scan } = await import(\"./scan.js\");\n await scan({\n config: configPath,\n verbose: false,\n });\n } catch (e) {\n console.log(\n pc.yellow(`Note: Auto-documentation will run when you start the dev server.`)\n );\n }\n }\n\n // Step 6: Show next steps or start server\n if (errors.length === 0) {\n console.log(pc.green(\"\\n✓ Setup complete!\\n\"));\n\n if (startServer) {\n const serverMessage =\n scenario === \"stories\"\n ? `Your ${detection.storyFiles.length} stories are loading...`\n : scenario === \"components\"\n ? `Your ${detection.componentFiles.length} components are being documented...`\n : `Your first component is ready!`;\n\n console.log(pc.cyan(serverMessage));\n startDevServer(projectRoot);\n } else {\n console.log(pc.cyan(\"Next steps:\"));\n console.log(` 1. Run ${pc.bold(`${BRAND.cliCommand} dev`)} to start the viewer`);\n if (scenario === \"fresh\") {\n console.log(` 2. Edit ${pc.bold(`${componentPath}/Button/Button.fragment.tsx`)}`);\n }\n console.log();\n }\n }\n\n return {\n success: errors.length === 0,\n configPath: errors.length === 0 ? configPath : undefined,\n scenario,\n storiesFound: detection.storyFiles.length,\n componentsFound: detection.componentFiles.length,\n errors,\n };\n}\n"],"mappings":";;;;;;;AASA,SAAmB,WAAW,OAAO,cAAc;AACnD,SAAS,SAAS,MAAM,gBAAgB;AACxC,SAAS,aAAa;AACtB,OAAO,QAAQ;AAEf,OAAO,QAAQ;AACf,SAAS,OAAO,eAAuB;AA+BvC,eAAe,cAAc,aAA+C;AAC1E,UAAQ,IAAI,GAAG,IAAI,yBAAyB,CAAC;AAG7C,QAAM,aAAa,KAAK,aAAa,MAAM,UAAU;AACrD,QAAM,mBAAmB,KAAK,aAAa,MAAM,gBAAgB;AACjE,MAAI,YAAY;AAChB,MAAI,kBAAiC;AAErC,MAAI;AACF,UAAM,OAAO,UAAU;AACvB,gBAAY;AACZ,sBAAkB;AAAA,EACpB,QAAQ;AACN,QAAI;AACF,YAAM,OAAO,gBAAgB;AAC7B,kBAAY;AACZ,wBAAkB;AAAA,IACpB,QAAQ;AAAA,IAER;AAAA,EACF;AAGA,QAAM,aAAa,MAAM;AAAA,IACvB,CAAC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