@ikas/code-components-mcp 1.4.0-beta.23 → 1.4.0-beta.231

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 (94) hide show
  1. package/data/framework.json +191 -78
  2. package/data/migration.json +10 -4
  3. package/data/section-templates/account-info-section/children/AccountFavorites/ikas-config-snippet.json +13 -0
  4. package/data/section-templates/account-info-section/children/AccountOrders/index.tsx +1 -1
  5. package/data/section-templates/account-info-section/ikas-config-snippet.json +19 -0
  6. package/data/section-templates/add-to-cart/ikas-config-snippet.json +17 -0
  7. package/data/section-templates/add-to-cart/index.tsx +16 -2
  8. package/data/section-templates/add-to-cart/sub-components/QuantitySelector/index.tsx +11 -3
  9. package/data/section-templates/add-to-cart/utils/cartLimits.ts +24 -0
  10. package/data/section-templates/blog-home-section/ikas-config-snippet.json +2 -0
  11. package/data/section-templates/blog-home-section/index.tsx +2 -1
  12. package/data/section-templates/blog-post-section/ikas-config-snippet.json +2 -0
  13. package/data/section-templates/blog-post-section/index.tsx +3 -2
  14. package/data/section-templates/bundle-products/hooks/useBundleProducts.ts +7 -6
  15. package/data/section-templates/bundle-products/ikas-config-snippet.json +20 -0
  16. package/data/section-templates/cart-section/components/EmptyState/index.tsx +1 -1
  17. package/data/section-templates/cart-section/sub-components/CartItem/index.tsx +66 -24
  18. package/data/section-templates/cart-section/sub-components/CartItem/styles.css +14 -0
  19. package/data/section-templates/cart-section/sub-components/QuantitySelector/index.tsx +11 -3
  20. package/data/section-templates/cart-section/utils/cartLimits.ts +24 -0
  21. package/data/section-templates/cart-section/utils/cartLineLimits.ts +100 -0
  22. package/data/section-templates/category-images-section/children/CategoryImageItem/ikas-config-snippet.json +4 -0
  23. package/data/section-templates/category-images-section/ikas-config-snippet.json +15 -0
  24. package/data/section-templates/category-list-section/children/CardProductName/ikas-config-snippet.json +2 -1
  25. package/data/section-templates/category-list-section/ikas-config-snippet.json +21 -0
  26. package/data/section-templates/category-list-section/index.tsx +2 -1
  27. package/data/section-templates/component-renderer/additional/ProductDetail/index.tsx +5 -1
  28. package/data/section-templates/component-renderer/ikas-config-snippet.json +13 -0
  29. package/data/section-templates/favorites/ikas-config-snippet.json +18 -1
  30. package/data/section-templates/features-section/ikas-config-snippet.json +13 -0
  31. package/data/section-templates/footer-section/ikas-config-snippet.json +15 -0
  32. package/data/section-templates/forgot-password-section/components/ForgotPasswordForm/index.tsx +1 -1
  33. package/data/section-templates/header-section/children/Announcements/ikas-config-snippet.json +7 -0
  34. package/data/section-templates/header-section/children/CookieBar/ikas-config-snippet.json +3 -0
  35. package/data/section-templates/header-section/children/Navbar/components/CartSidebar/index.tsx +2 -1
  36. package/data/section-templates/header-section/children/Navbar/components/SearchModal/index.tsx +2 -1
  37. package/data/section-templates/header-section/children/Navbar/ikas-config-snippet.json +27 -0
  38. package/data/section-templates/header-section/children/Navbar/index.tsx +6 -5
  39. package/data/section-templates/header-section/ikas-config-snippet.json +13 -0
  40. package/data/section-templates/header-section/sub-components/CartItem/index.tsx +66 -24
  41. package/data/section-templates/header-section/sub-components/CartItem/styles.css +14 -0
  42. package/data/section-templates/header-section/sub-components/QuantitySelector/index.tsx +11 -3
  43. package/data/section-templates/header-section/utils/cartLimits.ts +24 -0
  44. package/data/section-templates/header-section/utils/cartLineLimits.ts +100 -0
  45. package/data/section-templates/hero-slider-section/children/HeroSliderItem/ikas-config-snippet.json +18 -0
  46. package/data/section-templates/hero-slider-section/children/HeroSliderItem/index.tsx +12 -7
  47. package/data/section-templates/hero-slider-section/ikas-config-snippet.json +13 -0
  48. package/data/section-templates/image-handling/ikas-config-snippet.json +53 -0
  49. package/data/section-templates/image-handling/index.tsx +5 -1
  50. package/data/section-templates/login-section/ikas-config-snippet.json +2 -0
  51. package/data/section-templates/navigation/components/CartSidebar/index.tsx +2 -1
  52. package/data/section-templates/navigation/components/SearchModal/index.tsx +2 -1
  53. package/data/section-templates/navigation/ikas-config-snippet.json +27 -0
  54. package/data/section-templates/navigation/index.tsx +6 -5
  55. package/data/section-templates/navigation/sub-components/CartItem/index.tsx +66 -24
  56. package/data/section-templates/navigation/sub-components/CartItem/styles.css +14 -0
  57. package/data/section-templates/navigation/sub-components/QuantitySelector/index.tsx +11 -3
  58. package/data/section-templates/navigation/utils/cartLimits.ts +24 -0
  59. package/data/section-templates/navigation/utils/cartLineLimits.ts +100 -0
  60. package/data/section-templates/product-detail-section/children/ProductDetailAddToCart/ikas-config-snippet.json +17 -0
  61. package/data/section-templates/product-detail-section/children/ProductDetailAddToCart/index.tsx +16 -2
  62. package/data/section-templates/product-detail-section/children/ProductDetailBackInStock/components/BackInStockForm/index.tsx +92 -0
  63. package/data/section-templates/product-detail-section/children/ProductDetailBackInStock/ikas-config-snippet.json +175 -0
  64. package/data/section-templates/product-detail-section/children/ProductDetailBackInStock/index.tsx +141 -0
  65. package/data/section-templates/product-detail-section/children/ProductDetailBackInStock/styles.css +47 -0
  66. package/data/section-templates/product-detail-section/children/ProductDetailBackInStock/types.ts +25 -0
  67. package/data/section-templates/product-detail-section/children/ProductDetailBundleFurniture/ikas-config-snippet.json +18 -0
  68. package/data/section-templates/product-detail-section/children/ProductDetailBundleProduct/ikas-config-snippet.json +20 -0
  69. package/data/section-templates/product-detail-section/children/ProductDetailDescription/ikas-config-snippet.json +27 -0
  70. package/data/section-templates/product-detail-section/children/ProductDetailFeatures/ikas-config-snippet.json +29 -0
  71. package/data/section-templates/product-detail-section/children/ProductDetailNameFavorite/ikas-config-snippet.json +18 -1
  72. package/data/section-templates/product-detail-section/children/ProductDetailOffer/ikas-config-snippet.json +20 -0
  73. package/data/section-templates/product-detail-section/children/ProductDetailOptionSet/ikas-config-snippet.json +16 -0
  74. package/data/section-templates/product-detail-section/children/ProductDetailPrices/ikas-config-snippet.json +16 -0
  75. package/data/section-templates/product-detail-section/children/ProductDetailProductGroup/ikas-config-snippet.json +16 -0
  76. package/data/section-templates/product-detail-section/children/ProductDetailSku/ikas-config-snippet.json +16 -0
  77. package/data/section-templates/product-detail-section/children/ProductDetailVariant/ikas-config-snippet.json +17 -0
  78. package/data/section-templates/product-detail-section/hooks/useBundleProducts.ts +7 -6
  79. package/data/section-templates/product-detail-section/ikas-config-snippet.json +53 -0
  80. package/data/section-templates/product-detail-section/index.tsx +5 -1
  81. package/data/section-templates/product-detail-section/sub-components/Modal/index.tsx +120 -0
  82. package/data/section-templates/product-detail-section/sub-components/Modal/styles.css +70 -0
  83. package/data/section-templates/product-detail-section/sub-components/QuantitySelector/index.tsx +11 -3
  84. package/data/section-templates/product-detail-section/utils/cartLimits.ts +24 -0
  85. package/data/section-templates/product-pricing/ikas-config-snippet.json +16 -0
  86. package/data/section-templates/product-slider-section/children/CardProductName/ikas-config-snippet.json +2 -1
  87. package/data/section-templates/product-slider-section/ikas-config-snippet.json +17 -0
  88. package/data/section-templates/register-section/ikas-config-snippet.json +2 -0
  89. package/data/section-templates/variant-selection/ikas-config-snippet.json +17 -0
  90. package/data/storefront-api.json +1046 -80
  91. package/data/storefront-types.json +9868 -6037
  92. package/dist/index.js +2578 -257
  93. package/dist/index.js.map +1 -1
  94. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -98,9 +98,16 @@ function loadStorefrontTypes() {
98
98
  }
99
99
  return null;
100
100
  }
101
- const SUBTREE_KINDS = ["children", "components", "sub-components"];
101
+ const SUBTREE_KINDS = [
102
+ "children",
103
+ "components",
104
+ "sub-components",
105
+ ];
102
106
  function normalizeName(value) {
103
- return value.trim().replace(/^`+|`+$/g, "").trim();
107
+ return value
108
+ .trim()
109
+ .replace(/^`+|`+$/g, "")
110
+ .trim();
104
111
  }
105
112
  const storefrontData = loadStorefrontData();
106
113
  const frameworkData = loadJsonFile("../data/framework.json");
@@ -261,7 +268,11 @@ function searchMigrationTopics(query) {
261
268
  const descScore = matchScore(topic.description, query) * 2;
262
269
  const contentScore = matchScore(topic.content, query);
263
270
  const tagScore = topic.tags.some((t) => matchScore(t, query) > 0) ? 5 : 0;
264
- return { key, topic, score: titleScore + descScore + contentScore + tagScore };
271
+ return {
272
+ key,
273
+ topic,
274
+ score: titleScore + descScore + contentScore + tagScore,
275
+ };
265
276
  })
266
277
  .filter((item) => item.score > 0)
267
278
  .sort((a, b) => b.score - a.score);
@@ -288,7 +299,7 @@ function analyzeOldTheme(themeJson) {
288
299
  parts.push(`> **CRITICAL:** The old system (\`@ikas/storefront\`) and the new code-component system (\`@ikas/bp-storefront\`) are **entirely different packages**. Even when type names look the same (e.g., \`IkasImage\`, \`IkasProduct\`), they are different types with different properties. The prop type systems are also completely separate — old theme.json prop types and new ikas.config.json prop types have different semantics even when names match. **Never assume old-system knowledge applies to the new system.** Always use \`get_type_definition\`, \`get_model_guide\`, and \`get_function_doc\` to look up the correct new-system APIs.\n`);
289
300
  parts.push(`## Summary Statistics\n`);
290
301
  parts.push(`- **Components:** ${components.length}`);
291
- parts.push(`- **Custom Data Definitions:** ${customData.filter(cd => cd.isRoot).length}`);
302
+ parts.push(`- **Custom Data Definitions:** ${customData.filter((cd) => cd.isRoot).length}`);
292
303
  parts.push(`- **Prop Groups:** ${groups.length}`);
293
304
  // Component analysis
294
305
  parts.push(`\n## Components (${components.length})\n`);
@@ -327,7 +338,11 @@ function analyzeOldTheme(themeJson) {
327
338
  const typesSummary = Object.entries(propTypeCounts)
328
339
  .map(([t, c]) => `${t}×${c}`)
329
340
  .join(", ");
330
- const headerFooter = comp.isHeader ? " [HEADER]" : comp.isFooter ? " [FOOTER]" : "";
341
+ const headerFooter = comp.isHeader
342
+ ? " [HEADER]"
343
+ : comp.isFooter
344
+ ? " [FOOTER]"
345
+ : "";
331
346
  parts.push(`### ${comp.displayName || comp.dir || comp.id}${headerFooter}`);
332
347
  parts.push(`- **Dir:** \`${comp.dir || "?"}\` | **Props:** ${props.length} (${typesSummary})`);
333
348
  parts.push(`- **Recommended new type:** section`);
@@ -342,7 +357,7 @@ function analyzeOldTheme(themeJson) {
342
357
  parts.push("");
343
358
  }
344
359
  // Custom data analysis
345
- const rootCustomData = customData.filter(cd => cd.isRoot);
360
+ const rootCustomData = customData.filter((cd) => cd.isRoot);
346
361
  if (rootCustomData.length > 0) {
347
362
  parts.push(`\n## Custom Data Definitions (${rootCustomData.length})\n`);
348
363
  for (const cd of rootCustomData) {
@@ -352,7 +367,9 @@ function analyzeOldTheme(themeJson) {
352
367
  const describeNested = (items, indent) => {
353
368
  const lines = [];
354
369
  for (const item of items) {
355
- const key = item.key ? `\`${item.key}\`` : item.typescriptName || item.name || "unnamed";
370
+ const key = item.key
371
+ ? `\`${item.key}\``
372
+ : item.typescriptName || item.name || "unnamed";
356
373
  lines.push(`${indent}- ${key}: ${item.type}${item.isRequired ? " (required)" : ""}`);
357
374
  if (item.nestedData && item.nestedData.length > 0) {
358
375
  lines.push(...describeNested(item.nestedData, indent + " "));
@@ -364,7 +381,7 @@ function analyzeOldTheme(themeJson) {
364
381
  parts.push(...describeNested(cd.nestedData, " "));
365
382
  }
366
383
  if (cd.enumOptions && cd.enumOptions.length > 0) {
367
- parts.push(`- **Enum options:** ${cd.enumOptions.map(o => `"${o.value}"`).join(", ")}`);
384
+ parts.push(`- **Enum options:** ${cd.enumOptions.map((o) => `"${o.value}"`).join(", ")}`);
368
385
  }
369
386
  // Find which components reference this customData
370
387
  const referencingComponents = [];
@@ -446,7 +463,9 @@ function scanSharedSubcomponents(sourceDir) {
446
463
  const walk = (dir) => {
447
464
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
448
465
  if (entry.isDirectory()) {
449
- if (entry.name === "node_modules" || entry.name === "__generated__" || entry.name.startsWith("."))
466
+ if (entry.name === "node_modules" ||
467
+ entry.name === "__generated__" ||
468
+ entry.name.startsWith("."))
450
469
  continue;
451
470
  walk(path.join(dir, entry.name));
452
471
  }
@@ -481,10 +500,14 @@ function scanSharedSubcomponents(sourceDir) {
481
500
  if (!importPath.startsWith("."))
482
501
  continue;
483
502
  // Skip imports of generated types, utils, hooks
484
- if (importPath.includes("__generated__") || importPath.includes("/utils") || importPath.includes("/hooks"))
503
+ if (importPath.includes("__generated__") ||
504
+ importPath.includes("/utils") ||
505
+ importPath.includes("/hooks"))
485
506
  continue;
486
507
  // Extract base name from path
487
- const pathSegments = importPath.split("/").filter(s => s && s !== "." && s !== "..");
508
+ const pathSegments = importPath
509
+ .split("/")
510
+ .filter((s) => s && s !== "." && s !== "..");
488
511
  if (pathSegments.length === 0)
489
512
  continue;
490
513
  const lastSegment = pathSegments[pathSegments.length - 1];
@@ -495,7 +518,10 @@ function scanSharedSubcomponents(sourceDir) {
495
518
  continue;
496
519
  seenInFile.add(key);
497
520
  if (!importUsage.has(key)) {
498
- importUsage.set(key, { usingComponents: new Set(), rawImportPath: importPath });
521
+ importUsage.set(key, {
522
+ usingComponents: new Set(),
523
+ rawImportPath: importPath,
524
+ });
499
525
  }
500
526
  importUsage.get(key).usingComponents.add(componentDir);
501
527
  }
@@ -504,7 +530,7 @@ function scanSharedSubcomponents(sourceDir) {
504
530
  const shared = [];
505
531
  for (const [name, { usingComponents, rawImportPath }] of importUsage) {
506
532
  // Don't flag the component itself (e.g., Navbar imports from ../Navbar/something)
507
- const users = [...usingComponents].filter(c => c !== name);
533
+ const users = [...usingComponents].filter((c) => c !== name);
508
534
  if (users.length >= 3) {
509
535
  shared.push({ name, usedBy: users.sort(), importPaths: [rawImportPath] });
510
536
  }
@@ -521,7 +547,7 @@ function toKebabCase(s) {
521
547
  }
522
548
  function classifyComplexity(comp, customDataMap) {
523
549
  const props = comp.props || [];
524
- const customCount = props.filter(p => p.type === "CUSTOM").length;
550
+ const customCount = props.filter((p) => p.type === "CUSTOM").length;
525
551
  if (customCount === 0 && props.length < 10)
526
552
  return "simple";
527
553
  // Check for deeply nested CUSTOM (customData referencing another customData)
@@ -532,7 +558,9 @@ function classifyComplexity(comp, customDataMap) {
532
558
  if (cd?.nestedData) {
533
559
  const hasNested = (items) => {
534
560
  for (const item of items) {
535
- if (item.type === "DYNAMIC_LIST" || item.type === "STATIC_LIST" || item.customDataId)
561
+ if (item.type === "DYNAMIC_LIST" ||
562
+ item.type === "STATIC_LIST" ||
563
+ item.customDataId)
536
564
  return true;
537
565
  if (item.nestedData && hasNested(item.nestedData))
538
566
  return true;
@@ -564,7 +592,7 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
564
592
  parts.push(`# Theme Migration Plan — \`${projectName}\``);
565
593
  parts.push("");
566
594
  parts.push(`**Generated:** ${new Date().toISOString().slice(0, 10)}`);
567
- parts.push(`**Source:** ${components.length} old components, ${customData.filter(cd => cd.isRoot).length} custom data types, ${(theme.pages || []).length} pages`);
595
+ parts.push(`**Source:** ${components.length} old components, ${customData.filter((cd) => cd.isRoot).length} custom data types, ${(theme.pages || []).length} pages`);
568
596
  parts.push("");
569
597
  parts.push(`> ## READ THIS FIRST`);
570
598
  parts.push(`>`);
@@ -654,16 +682,22 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
654
682
  const cdType = cd.type || "?";
655
683
  let shape = "";
656
684
  if (cd.type === "ENUM") {
657
- const opts = (cd.enumOptions || []).map((o) => o.value || o.displayName).filter(Boolean);
685
+ const opts = (cd.enumOptions || [])
686
+ .map((o) => o.value || o.displayName)
687
+ .filter(Boolean);
658
688
  shape = ` — shape: \`enum {${opts.slice(0, 6).join(", ")}${opts.length > 6 ? ", ..." : ""}}\``;
659
689
  }
660
690
  else if (cd.nestedData && cd.nestedData.length > 0) {
661
691
  const first = cd.nestedData[0];
662
- const fields = (first?.nestedData || cd.nestedData || []).map((f) => `${f.key || f.name || "?"}: ${f.type || "?"}`).slice(0, 8);
692
+ const fields = (first?.nestedData || cd.nestedData || [])
693
+ .map((f) => `${f.key || f.name || "?"}: ${f.type || "?"}`)
694
+ .slice(0, 8);
663
695
  shape = ` — shape: \`{${fields.join(", ")}}\``;
664
696
  }
665
697
  const usedBy = cd.id ? usageByCustomDataId.get(cd.id) || [] : [];
666
- const usedByStr = usedBy.length > 0 ? ` — used by: ${usedBy.slice(0, 6).join(", ")}${usedBy.length > 6 ? `, +${usedBy.length - 6} more` : ""}` : ` — _not directly referenced by any section's props (may be nested inside another customData)_`;
698
+ const usedByStr = usedBy.length > 0
699
+ ? ` — used by: ${usedBy.slice(0, 6).join(", ")}${usedBy.length > 6 ? `, +${usedBy.length - 6} more` : ""}`
700
+ : ` — _not directly referenced by any section's props (may be nested inside another customData)_`;
667
701
  parts.push(`- \`${cdName}\` (${cdType})${shape}${usedByStr}`);
668
702
  }
669
703
  parts.push("");
@@ -697,7 +731,11 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
697
731
  const oldName = comp.displayName || comp.dir || comp.id || "Unknown";
698
732
  const kebabName = toKebabCase(comp.dir || comp.displayName || comp.id || "unknown");
699
733
  const newId = `${projectName}-${kebabName}`;
700
- const headerFooter = comp.isHeader ? " **[HEADER]**" : comp.isFooter ? " **[FOOTER]**" : "";
734
+ const headerFooter = comp.isHeader
735
+ ? " **[HEADER]**"
736
+ : comp.isFooter
737
+ ? " **[FOOTER]**"
738
+ : "";
701
739
  const propCount = (comp.props || []).length;
702
740
  // Detect children from CUSTOM DYNAMIC_LIST props
703
741
  const children = [];
@@ -707,8 +745,13 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
707
745
  if (cd && (cd.type === "DYNAMIC_LIST" || cd.type === "STATIC_LIST")) {
708
746
  const itemObj = cd.nestedData?.[0];
709
747
  if (itemObj) {
710
- const childName = itemObj.typescriptName || (itemObj.name ? itemObj.name.replace(/[^a-zA-Z0-9]/g, "") : `${oldName}Item`);
711
- const fields = (itemObj.nestedData || []).map((f) => f.key || f.name || "?").slice(0, 8);
748
+ const childName = itemObj.typescriptName ||
749
+ (itemObj.name
750
+ ? itemObj.name.replace(/[^a-zA-Z0-9]/g, "")
751
+ : `${oldName}Item`);
752
+ const fields = (itemObj.nestedData || [])
753
+ .map((f) => f.key || f.name || "?")
754
+ .slice(0, 8);
712
755
  children.push({ propName: p.name || "?", childName, fields });
713
756
  }
714
757
  }
@@ -767,11 +810,25 @@ function generateMigrationPlan(theme, projectName, oldSourceDir) {
767
810
  }
768
811
  // Known libraries we detect in old themes and want to flag for replacement
769
812
  const KNOWN_LIBRARIES = [
770
- "swiper", "@headlessui/react", "@heroicons/react", "recharts",
771
- "react-player", "react-simple-star-rating", "react-slider", "react-compound-slider",
772
- "react-zoom-pan-pinch", "react-hot-toast", "react-fast-marquee",
773
- "react-indiana-drag-scroll", "react-simple-typewriter", "react-timer-hook",
774
- "date-fns", "slugify", "classnames", "clsx", "@react-pdf/renderer",
813
+ "swiper",
814
+ "@headlessui/react",
815
+ "@heroicons/react",
816
+ "recharts",
817
+ "react-player",
818
+ "react-simple-star-rating",
819
+ "react-slider",
820
+ "react-compound-slider",
821
+ "react-zoom-pan-pinch",
822
+ "react-hot-toast",
823
+ "react-fast-marquee",
824
+ "react-indiana-drag-scroll",
825
+ "react-simple-typewriter",
826
+ "react-timer-hook",
827
+ "date-fns",
828
+ "slugify",
829
+ "classnames",
830
+ "clsx",
831
+ "@react-pdf/renderer",
775
832
  ];
776
833
  // Heuristic: member-access patterns on old storefront stores/singletons that likely need new-system equivalents
777
834
  const OLD_STOREFRONT_CALL_REGEX = /\b(customerStore|cartStore|productStore|categoryStore|orderStore|searchStore|favoritesStore|i18nStore|Router|useStore)\.\w+/g;
@@ -790,7 +847,8 @@ function scanSectionSource(componentDir, propNames) {
790
847
  // Collect all .tsx/.ts files in the component dir
791
848
  try {
792
849
  for (const entry of fs.readdirSync(componentDir, { withFileTypes: true })) {
793
- if (entry.isFile() && (entry.name.endsWith(".tsx") || entry.name.endsWith(".ts"))) {
850
+ if (entry.isFile() &&
851
+ (entry.name.endsWith(".tsx") || entry.name.endsWith(".ts"))) {
794
852
  result.sourceFiles.push(path.join(componentDir, entry.name));
795
853
  }
796
854
  }
@@ -807,7 +865,18 @@ function scanSectionSource(componentDir, propNames) {
807
865
  const subCompSet = new Map();
808
866
  const callSet = new Set();
809
867
  // Packages we treat as "framework" and don't flag for replacement (but do note in reactPackageUsage)
810
- const REACT_PACKAGES = new Set(["react", "react-dom", "next", "next/link", "next/image", "next/router", "next/head", "next/script", "mobx-react-lite", "mobx"]);
868
+ const REACT_PACKAGES = new Set([
869
+ "react",
870
+ "react-dom",
871
+ "next",
872
+ "next/link",
873
+ "next/image",
874
+ "next/router",
875
+ "next/head",
876
+ "next/script",
877
+ "mobx-react-lite",
878
+ "mobx",
879
+ ]);
811
880
  for (const file of result.sourceFiles) {
812
881
  let content;
813
882
  try {
@@ -821,7 +890,7 @@ function scanSectionSource(componentDir, propNames) {
821
890
  while ((m = importRegex.exec(content)) !== null) {
822
891
  const p = m[1];
823
892
  if (p.startsWith(".")) {
824
- const segs = p.split("/").filter(s => s && s !== "." && s !== "..");
893
+ const segs = p.split("/").filter((s) => s && s !== "." && s !== "..");
825
894
  const last = segs[segs.length - 1];
826
895
  if (last && /^[A-Z]/.test(last) && !last.includes("__generated__")) {
827
896
  subCompSet.set(last, p);
@@ -829,7 +898,9 @@ function scanSectionSource(componentDir, propNames) {
829
898
  }
830
899
  else if (!p.startsWith("@ikas/")) {
831
900
  // Classify: known library, react-family, or unknown-external
832
- const base = p.startsWith("@") ? p.split("/").slice(0, 2).join("/") : p.split("/")[0];
901
+ const base = p.startsWith("@")
902
+ ? p.split("/").slice(0, 2).join("/")
903
+ : p.split("/")[0];
833
904
  if (REACT_PACKAGES.has(p) || REACT_PACKAGES.has(base)) {
834
905
  reactSet.add(base);
835
906
  }
@@ -892,7 +963,10 @@ function scanSectionSource(componentDir, propNames) {
892
963
  }
893
964
  }
894
965
  }
895
- result.importedSubComponents = [...subCompSet.entries()].map(([name, p]) => ({ name, path: p }));
966
+ result.importedSubComponents = [...subCompSet.entries()].map(([name, p]) => ({
967
+ name,
968
+ path: p,
969
+ }));
896
970
  result.importedLibraries = [...libSet].sort();
897
971
  result.importedUnknownLibraries = [...unknownLibSet].sort();
898
972
  result.reactPackageUsage = [...reactSet].sort();
@@ -908,27 +982,38 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
908
982
  customDataMap.set(cd.id, cd);
909
983
  }
910
984
  // Find the component — try match by dir, displayName, id, or new-id
911
- const target = components.find(c => {
985
+ const target = components.find((c) => {
912
986
  if (!c)
913
987
  return false;
914
- if (c.dir === sectionName || c.displayName === sectionName || c.id === sectionName)
988
+ if (c.dir === sectionName ||
989
+ c.displayName === sectionName ||
990
+ c.id === sectionName)
915
991
  return true;
916
992
  const kebab = toKebabCase(c.dir || c.displayName || c.id || "");
917
993
  const newId = `${projectName}-${kebab}`;
918
994
  return newId === sectionName;
919
995
  });
920
996
  if (!target) {
921
- const available = components.map(c => c.dir || c.displayName || c.id).filter(Boolean).join(", ");
997
+ const available = components
998
+ .map((c) => c.dir || c.displayName || c.id)
999
+ .filter(Boolean)
1000
+ .join(", ");
922
1001
  return `Section "${sectionName}" not found in theme. Available: ${available}`;
923
1002
  }
924
1003
  const parts = [];
925
1004
  const oldName = target.displayName || target.dir || target.id || "Unknown";
926
1005
  const kebabName = toKebabCase(target.dir || target.displayName || target.id || "unknown");
927
1006
  const sectionId = `${projectName}-${kebabName}`;
928
- const sectionPascal = (target.dir || target.displayName || "").replace(/[^a-zA-Z0-9]/g, "") || kebabName.split("-").map(s => s[0]?.toUpperCase() + s.slice(1)).join("");
1007
+ const sectionPascal = (target.dir || target.displayName || "").replace(/[^a-zA-Z0-9]/g, "") ||
1008
+ kebabName
1009
+ .split("-")
1010
+ .map((s) => s[0]?.toUpperCase() + s.slice(1))
1011
+ .join("");
929
1012
  // Scan the old source for imports, libraries, field usage
930
- const propNames = (target.props || []).map(p => p.name || "").filter(Boolean);
931
- const sourceScan = (oldSourceDir && target.dir)
1013
+ const propNames = (target.props || [])
1014
+ .map((p) => p.name || "")
1015
+ .filter(Boolean);
1016
+ const sourceScan = oldSourceDir && target.dir
932
1017
  ? scanSectionSource(path.join(oldSourceDir, target.dir), propNames)
933
1018
  : null;
934
1019
  parts.push(`# Section Migration Plan: ${oldName}`);
@@ -974,7 +1059,7 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
974
1059
  }
975
1060
  if (sourceScan.reactPackageUsage.length > 0) {
976
1061
  parts.push("");
977
- parts.push(`**React/Next.js framework imports detected:** ${sourceScan.reactPackageUsage.map(p => `\`${p}\``).join(", ")}. These do NOT carry over — the new system is Preact. See \`get_migration_guide("react-to-preact")\` for conversion patterns (hooks, observer, event types, routing).`);
1062
+ parts.push(`**React/Next.js framework imports detected:** ${sourceScan.reactPackageUsage.map((p) => `\`${p}\``).join(", ")}. These do NOT carry over — the new system is Preact. See \`get_migration_guide("react-to-preact")\` for conversion patterns (hooks, observer, event types, routing).`);
978
1063
  }
979
1064
  if (sourceScan.oldStorefrontCalls.length > 0) {
980
1065
  parts.push("");
@@ -1020,7 +1105,11 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1020
1105
  if (oldType === "SLIDER") {
1021
1106
  newType = "NUMBER";
1022
1107
  notes = `Was SLIDER(min=${p.sliderData?.min}, max=${p.sliderData?.max}) — replace \`.value\` access with direct number`;
1023
- const prop = { name: newName, displayName: p.displayName || newName, type: "NUMBER" };
1108
+ const prop = {
1109
+ name: newName,
1110
+ displayName: p.displayName || newName,
1111
+ type: "NUMBER",
1112
+ };
1024
1113
  if (p.isRequired)
1025
1114
  prop.required = true;
1026
1115
  parentPropsJson.push(prop);
@@ -1028,7 +1117,11 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1028
1117
  else if (oldType === "PRODUCT_DETAIL") {
1029
1118
  newType = "PRODUCT";
1030
1119
  notes = "Renamed — PRODUCT_DETAIL → PRODUCT";
1031
- const prop = { name: newName, displayName: p.displayName || newName, type: "PRODUCT" };
1120
+ const prop = {
1121
+ name: newName,
1122
+ displayName: p.displayName || newName,
1123
+ type: "PRODUCT",
1124
+ };
1032
1125
  if (p.isRequired)
1033
1126
  prop.required = true;
1034
1127
  parentPropsJson.push(prop);
@@ -1039,7 +1132,10 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1039
1132
  if (cd.type === "DYNAMIC_LIST" || cd.type === "STATIC_LIST") {
1040
1133
  // Child component needed
1041
1134
  const itemObj = cd.nestedData?.[0];
1042
- const childName = itemObj?.typescriptName || (itemObj?.name ? itemObj.name.replace(/[^a-zA-Z0-9]/g, "") : `${sectionPascal}Item`);
1135
+ const childName = itemObj?.typescriptName ||
1136
+ (itemObj?.name
1137
+ ? itemObj.name.replace(/[^a-zA-Z0-9]/g, "")
1138
+ : `${sectionPascal}Item`);
1043
1139
  const childProps = [];
1044
1140
  const nestedWarnings = [];
1045
1141
  for (const f of (itemObj?.nestedData || [])) {
@@ -1050,11 +1146,18 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1050
1146
  fType = "NUMBER";
1051
1147
  else if (fType === "PRODUCT_DETAIL")
1052
1148
  fType = "PRODUCT";
1053
- else if (fType === "CUSTOM" || fType === "DYNAMIC_LIST" || fType === "STATIC_LIST" || fType === "OBJECT") {
1149
+ else if (fType === "CUSTOM" ||
1150
+ fType === "DYNAMIC_LIST" ||
1151
+ fType === "STATIC_LIST" ||
1152
+ fType === "OBJECT") {
1054
1153
  nestedWarnings.push(`\`${f.key}\` (${fType})`);
1055
1154
  fType = "COMPONENT_LIST";
1056
1155
  }
1057
- const prop = { name: f.key, displayName: f.name || f.key, type: fType };
1156
+ const prop = {
1157
+ name: f.key,
1158
+ displayName: f.name || f.key,
1159
+ type: fType,
1160
+ };
1058
1161
  if (f.isRequired)
1059
1162
  prop.required = true;
1060
1163
  childProps.push(prop);
@@ -1066,10 +1169,14 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1066
1169
  if (childProps.length === 0 && sourceScan?.propFieldUsage[oldName]) {
1067
1170
  const inferred = sourceScan.propFieldUsage[oldName];
1068
1171
  for (const fieldName of inferred) {
1069
- childProps.push({ name: fieldName, displayName: fieldName, type: "TEXT" });
1172
+ childProps.push({
1173
+ name: fieldName,
1174
+ displayName: fieldName,
1175
+ type: "TEXT",
1176
+ });
1070
1177
  }
1071
1178
  if (inferred.length > 0) {
1072
- notes = `Was CUSTOM → ${cd.type} with empty customData. **Inferred props from source usage:** ${inferred.map(f => `\`${f}\``).join(", ")}. Verify types and required flags — default inferred type is TEXT.`;
1179
+ notes = `Was CUSTOM → ${cd.type} with empty customData. **Inferred props from source usage:** ${inferred.map((f) => `\`${f}\``).join(", ")}. Verify types and required flags — default inferred type is TEXT.`;
1073
1180
  }
1074
1181
  }
1075
1182
  children.push({
@@ -1098,7 +1205,11 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1098
1205
  let fType = f.type;
1099
1206
  if (fType === "SLIDER")
1100
1207
  fType = "NUMBER";
1101
- const prop = { name: f.key, displayName: f.name || f.key, type: fType };
1208
+ const prop = {
1209
+ name: f.key,
1210
+ displayName: f.name || f.key,
1211
+ type: fType,
1212
+ };
1102
1213
  if (f.isRequired)
1103
1214
  prop.required = true;
1104
1215
  parentPropsJson.push(prop);
@@ -1113,7 +1224,8 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1113
1224
  }
1114
1225
  else if (cd.type === "ENUM") {
1115
1226
  newType = "ENUM";
1116
- const enumName = cd.typescriptName || (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : "Enum");
1227
+ const enumName = cd.typescriptName ||
1228
+ (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : "Enum");
1117
1229
  const options = (cd.enumOptions || []).reduce((acc, o) => {
1118
1230
  if (o.displayName && o.value)
1119
1231
  acc[o.displayName] = o.value;
@@ -1121,7 +1233,12 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1121
1233
  }, {});
1122
1234
  enumsNeeded.push({ name: enumName, options });
1123
1235
  notes = `Was CUSTOM (ENUM) — create enum \`${enumName}\` via \`config add-enum\` first, then reference its enumId here`;
1124
- const prop = { name: newName, displayName: p.displayName || newName, type: "ENUM", enumTypeId: `<ENUM_ID_FROM_add-enum_${enumName}>` };
1236
+ const prop = {
1237
+ name: newName,
1238
+ displayName: p.displayName || newName,
1239
+ type: "ENUM",
1240
+ enumTypeId: `<ENUM_ID_FROM_add-enum_${enumName}>`,
1241
+ };
1125
1242
  if (p.isRequired)
1126
1243
  prop.required = true;
1127
1244
  parentPropsJson.push(prop);
@@ -1130,7 +1247,11 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1130
1247
  }
1131
1248
  else {
1132
1249
  // Direct mapping
1133
- const prop = { name: newName, displayName: p.displayName || newName, type: newType };
1250
+ const prop = {
1251
+ name: newName,
1252
+ displayName: p.displayName || newName,
1253
+ type: newType,
1254
+ };
1134
1255
  if (p.isRequired)
1135
1256
  prop.required = true;
1136
1257
  parentPropsJson.push(prop);
@@ -1139,7 +1260,9 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1139
1260
  }
1140
1261
  parts.push("");
1141
1262
  // Custom Data Decision Callouts — per prop referencing a customData type
1142
- const customDataPropsForCallouts = (target.props || []).filter((p) => p.type === "CUSTOM" && p.customDataId && customDataMap.has(p.customDataId));
1263
+ const customDataPropsForCallouts = (target.props || []).filter((p) => p.type === "CUSTOM" &&
1264
+ p.customDataId &&
1265
+ customDataMap.has(p.customDataId));
1143
1266
  if (customDataPropsForCallouts.length > 0) {
1144
1267
  parts.push(`## Custom Data Decisions to Make`);
1145
1268
  parts.push("");
@@ -1154,7 +1277,9 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1154
1277
  let shape = "";
1155
1278
  let shapeKind = "unknown";
1156
1279
  if (cd.type === "ENUM") {
1157
- const opts = (cd.enumOptions || []).map((o) => o.value || o.displayName).filter(Boolean);
1280
+ const opts = (cd.enumOptions || [])
1281
+ .map((o) => o.value || o.displayName)
1282
+ .filter(Boolean);
1158
1283
  shape = `enum {${opts.slice(0, 6).join(", ")}${opts.length > 6 ? ", ..." : ""}}`;
1159
1284
  shapeKind = "enum";
1160
1285
  }
@@ -1187,7 +1312,8 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1187
1312
  if (shapeKind === "enum") {
1188
1313
  parts.push(`**Default: enum prop.** Flat scalar set; use \`config add-enum\`.`);
1189
1314
  parts.push("");
1190
- const enumName = cd.typescriptName || (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : "Enum");
1315
+ const enumName = cd.typescriptName ||
1316
+ (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : "Enum");
1191
1317
  const enumOptions = (cd.enumOptions || []).reduce((acc, o) => {
1192
1318
  if (o.displayName && o.value)
1193
1319
  acc[o.displayName] = o.value;
@@ -1222,7 +1348,10 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1222
1348
  parts.push(`> See \`get_migration_guide("component-composition-decision-guide")\` for when \`COMPONENT_LIST\` is overkill.`);
1223
1349
  parts.push("");
1224
1350
  }
1225
- const compName = cd.typescriptName || (cd.name ? cd.name.replace(/[^a-zA-Z0-9]/g, "") : `${sectionPascal}Item`);
1351
+ const compName = cd.typescriptName ||
1352
+ (cd.name
1353
+ ? cd.name.replace(/[^a-zA-Z0-9]/g, "")
1354
+ : `${sectionPascal}Item`);
1226
1355
  const compPropsForCli = [];
1227
1356
  for (const f of fieldSource) {
1228
1357
  if (!f.key)
@@ -1232,7 +1361,11 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1232
1361
  fType = "NUMBER";
1233
1362
  else if (fType === "PRODUCT_DETAIL")
1234
1363
  fType = "PRODUCT";
1235
- compPropsForCli.push({ name: f.key, displayName: f.name || f.key, type: fType });
1364
+ compPropsForCli.push({
1365
+ name: f.key,
1366
+ displayName: f.name || f.key,
1367
+ type: fType,
1368
+ });
1236
1369
  }
1237
1370
  parts.push("```bash");
1238
1371
  if (isMinimal) {
@@ -1271,7 +1404,10 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1271
1404
  existing.usedByProps.push(ch.propName);
1272
1405
  }
1273
1406
  else {
1274
- uniqueChildren.set(ch.childName, { child: ch, usedByProps: [ch.propName] });
1407
+ uniqueChildren.set(ch.childName, {
1408
+ child: ch,
1409
+ usedByProps: [ch.propName],
1410
+ });
1275
1411
  }
1276
1412
  }
1277
1413
  if (uniqueChildren.size > 0) {
@@ -1284,7 +1420,7 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1284
1420
  for (const { child: ch, usedByProps } of uniqueChildren.values()) {
1285
1421
  parts.push(`### \`${ch.childName}\``);
1286
1422
  const propsLabel = usedByProps.length > 1
1287
- ? `Used by parent props: ${usedByProps.map(p => `\`${p}\``).join(", ")} (${usedByProps.length}×)`
1423
+ ? `Used by parent props: ${usedByProps.map((p) => `\`${p}\``).join(", ")} (${usedByProps.length}×)`
1288
1424
  : `For parent prop: \`${usedByProps[0]}\``;
1289
1425
  parts.push(propsLabel);
1290
1426
  parts.push(`Old customData: "${ch.customDataName}"`);
@@ -1330,12 +1466,15 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1330
1466
  parts.push(`- **Every COMPONENT_LIST slot needs a child component to render individual items.** A product list needs a ProductCard child, a blog list needs a BlogCard child, etc. Check if the child already exists (run \`config list\` to see all components and their opaque ids; reuse the existing id in \`filteredComponentIds\`). If not, create it as a registered component and use the \`componentId\` from the CLI's response.`);
1331
1467
  }
1332
1468
  // Check if the section itself has data-driven list props (PRODUCT_LIST, BLOG_LIST, CATEGORY_LIST)
1333
- const dataListProps = (target.props || []).filter(p => p.type === "PRODUCT_LIST" || p.type === "BLOG_LIST" || p.type === "CATEGORY_LIST" || p.type === "BRAND_LIST");
1469
+ const dataListProps = (target.props || []).filter((p) => p.type === "PRODUCT_LIST" ||
1470
+ p.type === "BLOG_LIST" ||
1471
+ p.type === "CATEGORY_LIST" ||
1472
+ p.type === "BRAND_LIST");
1334
1473
  if (dataListProps.length > 0) {
1335
1474
  parts.push("");
1336
1475
  parts.push(`### Data-Driven List Rendering`);
1337
1476
  parts.push("");
1338
- parts.push(`This section has data-driven list props: ${dataListProps.map(p => `\`${p.name}\` (${p.type})`).join(", ")}.`);
1477
+ parts.push(`This section has data-driven list props: ${dataListProps.map((p) => `\`${p.name}\` (${p.type})`).join(", ")}.`);
1339
1478
  parts.push(`These are NOT COMPONENT_LIST — the data comes from dynamic queries (filters, categories, search), not hand-picked items. Render items **internally** by mapping over the data:`);
1340
1479
  parts.push("");
1341
1480
  parts.push("```tsx");
@@ -1362,9 +1501,22 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1362
1501
  parts.push(`See \`get_migration_guide("custom-data-conversion")\` → "Two Ways to Render Lists" for the full pattern.`);
1363
1502
  }
1364
1503
  // Detect form-page sections (0 or few props, name suggests a form/auth page)
1365
- const formKeywords = ["login", "register", "forgot", "recover", "password", "account", "email", "verification", "activate", "contact", "checkout", "address"];
1504
+ const formKeywords = [
1505
+ "login",
1506
+ "register",
1507
+ "forgot",
1508
+ "recover",
1509
+ "password",
1510
+ "account",
1511
+ "email",
1512
+ "verification",
1513
+ "activate",
1514
+ "contact",
1515
+ "checkout",
1516
+ "address",
1517
+ ];
1366
1518
  const lowerDir = (target.dir || "").toLowerCase();
1367
- const isLikelyFormPage = formKeywords.some(kw => lowerDir.includes(kw));
1519
+ const isLikelyFormPage = formKeywords.some((kw) => lowerDir.includes(kw));
1368
1520
  if (isLikelyFormPage) {
1369
1521
  parts.push("");
1370
1522
  parts.push(`### Form Page Pattern`);
@@ -1393,7 +1545,9 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1393
1545
  // Fallback heuristic only when source scan unavailable
1394
1546
  const heuristicLibs = [];
1395
1547
  const lowerName = oldName.toLowerCase();
1396
- if (lowerName.includes("slider") || lowerName.includes("carousel") || lowerName.includes("banner")) {
1548
+ if (lowerName.includes("slider") ||
1549
+ lowerName.includes("carousel") ||
1550
+ lowerName.includes("banner")) {
1397
1551
  heuristicLibs.push("swiper");
1398
1552
  }
1399
1553
  if (lowerName.includes("marquee"))
@@ -1402,7 +1556,9 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1402
1556
  heuristicLibs.push("react-player");
1403
1557
  if (lowerName.includes("chart"))
1404
1558
  heuristicLibs.push("recharts");
1405
- if (lowerName.includes("star") || lowerName.includes("rating") || lowerName.includes("review"))
1559
+ if (lowerName.includes("star") ||
1560
+ lowerName.includes("rating") ||
1561
+ lowerName.includes("review"))
1406
1562
  heuristicLibs.push("react-simple-star-rating");
1407
1563
  if (heuristicLibs.length > 0) {
1408
1564
  parts.push(`### Likely Library Replacements (heuristic — source not scanned)`);
@@ -1433,20 +1589,53 @@ function generateSectionMigrationPlan(theme, sectionName, projectName, oldSource
1433
1589
  return parts.join("\n");
1434
1590
  }
1435
1591
  // --- Search helpers ---
1592
+ /**
1593
+ * Strip every non-alphanumeric character and lowercase, so the SAME identifier written in
1594
+ * different conventions collapses to one form: `PRODUCT_ATTRIBUTE`, `IkasProductAttributeDetail`
1595
+ * and the prose "product attribute detail" all become `productattribute…`. Without this a query
1596
+ * for a prop type (which is always SCREAMING_SNAKE) can never reach the function/type docs that
1597
+ * spell the same concept in camelCase or prose — `search_docs("PRODUCT_ATTRIBUTE")` used to miss
1598
+ * `getAttributeDetailValues` entirely.
1599
+ */
1600
+ function squashIdentifier(text) {
1601
+ return text.replace(/[^a-z0-9]/gi, "").toLowerCase();
1602
+ }
1603
+ /** A query word worth matching separator-insensitively: an identifier, not prose. */
1604
+ function isIdentifierLike(word) {
1605
+ return (word.length > 3 &&
1606
+ (/[_\-.]/.test(word) ||
1607
+ /[a-z][A-Z]/.test(word) ||
1608
+ /^[A-Z0-9_]+$/.test(word)));
1609
+ }
1436
1610
  function matchScore(text, query) {
1437
1611
  const lower = text.toLowerCase();
1438
1612
  const queryLower = query.toLowerCase();
1439
- const words = queryLower.split(/\s+/).filter(Boolean);
1613
+ const words = query.split(/\s+/).filter(Boolean);
1440
1614
  let score = 0;
1441
1615
  // Exact substring match
1442
1616
  if (lower.includes(queryLower)) {
1443
1617
  score += 10;
1444
1618
  }
1445
- // Word matches
1619
+ // Word matches. Squashing the (potentially guide-sized) text is the expensive half of the
1620
+ // identifier check — compute it lazily, once per call, not once per query word.
1621
+ let squashedText = null;
1446
1622
  for (const word of words) {
1447
- if (lower.includes(word)) {
1623
+ const wordLower = word.toLowerCase();
1624
+ if (lower.includes(wordLower)) {
1448
1625
  score += 3;
1449
1626
  }
1627
+ else if (isIdentifierLike(word)) {
1628
+ // Same identifier, different convention (PRODUCT_ATTRIBUTE ↔ IkasProductAttributeDetail
1629
+ // ↔ "product attribute"). Scored below an exact word hit so literal matches still win.
1630
+ const squashed = squashIdentifier(word);
1631
+ if (squashed) {
1632
+ if (squashedText === null)
1633
+ squashedText = squashIdentifier(text);
1634
+ if (squashedText.includes(squashed)) {
1635
+ score += 2;
1636
+ }
1637
+ }
1638
+ }
1450
1639
  }
1451
1640
  // Name exact match bonus
1452
1641
  if (lower === queryLower) {
@@ -1474,8 +1663,7 @@ function levenshtein(a, b) {
1474
1663
  const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
1475
1664
  curr[j] = Math.min(curr[j - 1] + 1, // insertion
1476
1665
  prev[j] + 1, // deletion
1477
- prev[j - 1] + cost // substitution
1478
- );
1666
+ prev[j - 1] + cost);
1479
1667
  }
1480
1668
  for (let j = 0; j <= n; j++)
1481
1669
  prev[j] = curr[j];
@@ -1502,21 +1690,100 @@ function suggestClosestNames(input, candidates, opts) {
1502
1690
  .sort((a, b) => a.d - b.d);
1503
1691
  return edits.slice(0, max).map((s) => s.name);
1504
1692
  }
1693
+ /**
1694
+ * Formatted ` — matching sections: ...` suffix naming the guide sections that match the query,
1695
+ * so a hit buried mid-guide (e.g. "Quantity Limits" inside cart-patterns) is visible without
1696
+ * opening the full guide. Section bodies are scored on purpose: a query for an identifier that
1697
+ * appears only inside a section (an error code, a prop name) must still surface that section's
1698
+ * heading. Returns "" when the query matches most of the guide's sections — matchScore is
1699
+ * presence-based, so a broad query ("cart" against cart-patterns) ties every section and a
1700
+ * top-3 would just echo document order, hinting nothing.
1701
+ */
1702
+ // Topic content is loaded once at startup and never mutates, so the section parse is
1703
+ // memoized on the content string — a query only pays for scoring.
1704
+ const parsedSectionsCache = new Map();
1705
+ function parseSections(content) {
1706
+ const cached = parsedSectionsCache.get(content);
1707
+ if (cached)
1708
+ return cached;
1709
+ // Line walk instead of a heading-regex split: a `## ` line inside a fenced code block must
1710
+ // not become a pseudo-section (it would surface a heading that doesn't exist in the guide
1711
+ // and swallow the rest of the real section's body).
1712
+ const sections = [];
1713
+ let fenceOpen = false;
1714
+ for (const line of content.split("\n")) {
1715
+ if (/^\s*```/.test(line))
1716
+ fenceOpen = !fenceOpen;
1717
+ const headingMatch = fenceOpen ? null : line.match(/^#{2,4} (.+)/);
1718
+ if (headingMatch)
1719
+ sections.push({ heading: headingMatch[1].trim(), body: "" });
1720
+ else if (sections.length > 0)
1721
+ sections[sections.length - 1].body += line + "\n";
1722
+ }
1723
+ parsedSectionsCache.set(content, sections);
1724
+ return sections;
1725
+ }
1726
+ function sectionHint(content, query, topicTitle) {
1727
+ const sections = parseSections(content);
1728
+ const scored = [];
1729
+ for (const { heading, body } of sections) {
1730
+ // Heading hits weigh double. The floor of 3 drops sections whose only signal is a single
1731
+ // squashed-identifier body match (worth 2) — a literal word hit (3) or any heading match
1732
+ // clears it.
1733
+ const score = matchScore(heading, query) * 2 + matchScore(body, query);
1734
+ if (score >= 3)
1735
+ scored.push({ heading, score });
1736
+ }
1737
+ if (scored.length === 0)
1738
+ return "";
1739
+ scored.sort((a, b) => b.score - a.score);
1740
+ // The tie-guard below must only fire when the field is genuinely flat. A single common
1741
+ // query word ("cart") pushes every section past the floor, so counting raw matches would
1742
+ // also suppress steep fields where one section clearly won. Sections below 60% of the top
1743
+ // score are noise from such a word, not real matches — drop them before counting.
1744
+ const strong = scored.filter((s) => s.score >= scored[0].score * 0.6);
1745
+ if (strong.length > sections.length / 2)
1746
+ return "";
1747
+ // The guide's own title is usually its first `##` line, so it registers as a section.
1748
+ // Its heading is the exact text the result line already prints — listing it would burn
1749
+ // one of the three slots on a pure echo. Keep it in scoring (its body can be a genuine
1750
+ // hit and it counts toward the tie-guard), drop it from the output only. Headings are
1751
+ // already trimmed at parse time; trim the title too so stray whitespace in the JSON
1752
+ // cannot silently re-admit the echo.
1753
+ const title = topicTitle.trim();
1754
+ const named = strong.filter((s) => s.heading !== title);
1755
+ if (named.length === 0)
1756
+ return "";
1757
+ const top = named.slice(0, 3);
1758
+ return ` — matching sections: ${top.map((s) => `"${s.heading}"`).join(", ")}`;
1759
+ }
1505
1760
  function searchFunctions(query) {
1506
1761
  const scored = storefrontData.functions
1507
1762
  .map((fn) => {
1508
1763
  const nameScore = matchScore(fn.name, query) * 3;
1509
- const displayNameScore = fn.displayName ? matchScore(fn.displayName, query) * 3 : 0;
1764
+ const displayNameScore = fn.displayName
1765
+ ? matchScore(fn.displayName, query) * 3
1766
+ : 0;
1510
1767
  const descScore = matchScore(fn.description, query);
1511
- const catScore = fn.categories.some((c) => matchScore(c, query) > 0) ? 5 : 0;
1768
+ const catScore = fn.categories.some((c) => matchScore(c, query) > 0)
1769
+ ? 5
1770
+ : 0;
1512
1771
  const paramScore = fn.params.some((p) => matchScore(p.name, query) > 0 || matchScore(p.description, query) > 0)
1513
1772
  ? 2
1514
1773
  : 0;
1515
1774
  const sigScore = matchScore(fn.signature, query) * 2;
1516
- const typeScore = fn.parameterTypes?.some((t) => matchScore(t, query) > 0) ? 8 : 0;
1775
+ const typeScore = fn.parameterTypes?.some((t) => matchScore(t, query) > 0)
1776
+ ? 8
1777
+ : 0;
1517
1778
  return {
1518
1779
  fn,
1519
- score: nameScore + displayNameScore + descScore + catScore + paramScore + sigScore + typeScore,
1780
+ score: nameScore +
1781
+ displayNameScore +
1782
+ descScore +
1783
+ catScore +
1784
+ paramScore +
1785
+ sigScore +
1786
+ typeScore,
1520
1787
  };
1521
1788
  })
1522
1789
  .filter((item) => item.score > 0)
@@ -1530,7 +1797,11 @@ function searchFrameworkTopics(query) {
1530
1797
  const descScore = matchScore(topic.description, query) * 2;
1531
1798
  const contentScore = matchScore(topic.content, query);
1532
1799
  const tagScore = topic.tags.some((t) => matchScore(t, query) > 0) ? 5 : 0;
1533
- return { key, topic, score: titleScore + descScore + contentScore + tagScore };
1800
+ return {
1801
+ key,
1802
+ topic,
1803
+ score: titleScore + descScore + contentScore + tagScore,
1804
+ };
1534
1805
  })
1535
1806
  .filter((item) => item.score > 0)
1536
1807
  .sort((a, b) => b.score - a.score);
@@ -1545,14 +1816,34 @@ function searchTypes(query) {
1545
1816
  const propScore = td.properties?.some((p) => matchScore(p.name, query) > 0 || matchScore(p.type, query) > 0)
1546
1817
  ? 4
1547
1818
  : 0;
1548
- const enumScore = td.enumValues?.some((v) => matchScore(v, query) > 0) ? 4 : 0;
1549
- return { td, score: nameScore + domainScore + propScore + enumScore };
1819
+ const enumScore = td.enumValues?.some((v) => matchScore(v, query) > 0)
1820
+ ? 4
1821
+ : 0;
1822
+ const unionScore = td.unionValues?.some((v) => matchScore(v, query) > 0)
1823
+ ? 4
1824
+ : 0;
1825
+ return {
1826
+ td,
1827
+ score: nameScore + domainScore + propScore + enumScore + unionScore,
1828
+ };
1550
1829
  })
1551
1830
  .filter((item) => item.score > 0)
1552
1831
  .sort((a, b) => b.score - a.score);
1553
1832
  return scored.map((item) => item.td);
1554
1833
  }
1555
1834
  // --- Format helpers ---
1835
+ /**
1836
+ * Wrap a code snippet in a fenced block — unless it already carries its own fence. JSDoc `@example`
1837
+ * bodies are indexed verbatim, so every one of them arrives fenced; wrapping them again produced a
1838
+ * double ```` ``` ```` opener, which makes the block unparseable for anything extracting code from
1839
+ * the doc. Bare snippets still get fenced as typescript.
1840
+ */
1841
+ function asCodeBlock(snippet) {
1842
+ const trimmed = snippet.trim();
1843
+ return trimmed.startsWith("```")
1844
+ ? trimmed
1845
+ : ["```typescript", trimmed, "```"].join("\n");
1846
+ }
1556
1847
  function formatFunctionDoc(fn) {
1557
1848
  const lines = [];
1558
1849
  lines.push(`## ${fn.name}`);
@@ -1579,7 +1870,7 @@ function formatFunctionDoc(fn) {
1579
1870
  lines.push("", `**Returns:** \`${fn.returnType}\`${fn.returns ? ` - ${fn.returns}` : ""}`);
1580
1871
  }
1581
1872
  if (fn.example) {
1582
- lines.push("", "**Example:**", "```typescript", fn.example, "```");
1873
+ lines.push("", "**Example:**", asCodeBlock(fn.example));
1583
1874
  }
1584
1875
  if (fn.related.length > 0) {
1585
1876
  lines.push("", `**Related:** ${fn.related.map((r) => `\`${r}\``).join(", ")}`);
@@ -1587,8 +1878,12 @@ function formatFunctionDoc(fn) {
1587
1878
  return lines.join("\n");
1588
1879
  }
1589
1880
  function formatFunctionSummary(fn) {
1590
- const desc = fn.description ? fn.description.split(".")[0] + "." : "No description.";
1591
- const alias = fn.displayName && fn.displayName !== fn.name ? ` (alias: ${fn.displayName})` : "";
1881
+ const desc = fn.description
1882
+ ? fn.description.split(".")[0] + "."
1883
+ : "No description.";
1884
+ const alias = fn.displayName && fn.displayName !== fn.name
1885
+ ? ` (alias: ${fn.displayName})`
1886
+ : "";
1592
1887
  return `- \`${fn.name}\`${alias} - ${desc}`;
1593
1888
  }
1594
1889
  function formatTypeDefinition(td, opts = {}) {
@@ -1596,13 +1891,24 @@ function formatTypeDefinition(td, opts = {}) {
1596
1891
  const lines = [];
1597
1892
  lines.push(`## ${td.name}`);
1598
1893
  lines.push("", `**Kind:** ${td.kind} | **Domain:** ${td.domain}`);
1599
- if (td.kind === "type") {
1894
+ if (td.description) {
1895
+ lines.push("", td.description);
1896
+ }
1897
+ if (td.kind === "type" && td.unionValues) {
1898
+ lines.push("", "```typescript");
1899
+ lines.push(`type ${td.name} = ${td.unionValues.map((v) => `"${v}"`).join(" | ")};`);
1900
+ lines.push("```");
1901
+ }
1902
+ else if (td.kind === "type") {
1600
1903
  lines.push("", "```typescript");
1601
1904
  const extendsStr = td.extends ? ` & ${td.extends.join(" & ")}` : "";
1602
1905
  lines.push(`type ${td.name} = {`);
1603
1906
  if (td.properties) {
1604
1907
  for (const p of td.properties) {
1605
1908
  const opt = p.optional ? "?" : "";
1909
+ if (p.description) {
1910
+ lines.push(" /**", ...p.description.split("\n").map((l) => ` * ${l.trim()}`), " */");
1911
+ }
1606
1912
  lines.push(` ${p.name}${opt}: ${p.type};`);
1607
1913
  }
1608
1914
  }
@@ -1629,7 +1935,9 @@ function formatTypeDefinition(td, opts = {}) {
1629
1935
  const fn = storefrontData.functions.find((f) => f.name === fnName);
1630
1936
  if (fn) {
1631
1937
  const desc = fn.description ? fn.description.split(".")[0] + "." : "";
1632
- const alias = fn.displayName && fn.displayName !== fn.name ? ` (alias: ${fn.displayName})` : "";
1938
+ const alias = fn.displayName && fn.displayName !== fn.name
1939
+ ? ` (alias: ${fn.displayName})`
1940
+ : "";
1633
1941
  lines.push(`- **\`${fn.name}\`**${alias} — ${desc}`);
1634
1942
  lines.push(` \`${fn.signature}\``);
1635
1943
  }
@@ -1638,7 +1946,9 @@ function formatTypeDefinition(td, opts = {}) {
1638
1946
  }
1639
1947
  }
1640
1948
  lines.push("");
1641
- lines.push("Use `get_functions_for_type(\"" + td.name + "\")` for full documentation of these functions.");
1949
+ lines.push('Use `get_functions_for_type("' +
1950
+ td.name +
1951
+ '")` for full documentation of these functions.');
1642
1952
  }
1643
1953
  return lines.join("\n");
1644
1954
  }
@@ -1647,6 +1957,10 @@ function formatTypeSummary(td) {
1647
1957
  const count = td.enumValues?.length ?? 0;
1648
1958
  return `- \`${td.name}\` (enum, ${count} values) — domain: ${td.domain}`;
1649
1959
  }
1960
+ if (td.unionValues) {
1961
+ const values = td.unionValues.map((v) => `"${v}"`).join(" | ");
1962
+ return `- \`${td.name}\` (union: ${values}) — domain: ${td.domain}`;
1963
+ }
1650
1964
  const count = td.properties?.length ?? 0;
1651
1965
  const ext = td.extends ? ` extends ${td.extends.join(", ")}` : "";
1652
1966
  return `- \`${td.name}\` (${count} properties${ext}) — domain: ${td.domain}`;
@@ -1656,7 +1970,16 @@ const server = new McpServer({
1656
1970
  name: "ikas-code-components",
1657
1971
  version: "0.1.0",
1658
1972
  }, {
1659
- instructions: "Examples and section templates from this server are API reference only — reuse imports, function calls, and data-access patterns; create your own JSX structure, CSS class names, and visual design.",
1973
+ instructions: "Examples and section templates from this server are API reference only — reuse imports, function calls, and data-access patterns; create your own JSX structure, CSS class names, and visual design.\n\n" +
1974
+ "CONFIG FILE — HARD RULE: NEVER edit `ikas.config.json` directly (no file write, patch or search/replace). Change it ONLY through `ikas-component` commands (`ikas-component config add-component` / `add-prop` / `update-prop` / `add-enum`, …; `ikas-component config list` to inspect). `projectId` and every component `id` are generated once and are IMMUTABLE — never change them, and never copy an id returned by the editor (`list_imported_sections`, `list_page_sections`, …) into `ikas.config.json`. On a theme that INSTALLED this project as a design asset the editor reports PUBLISHED ids, whose prefix differs from this project's `projectId`; that difference is expected and is NOT drift to fix — pass the editor's id to the editor tools and leave the config untouched. A config id that does not start with the project's own `projectId` makes `ikas-component dev` / `publish` fail and can corrupt the published theme.\n\n" +
1975
+ "Live-editor actions (require `ikas theme dev` running with the editor connected): `list_editor_pages` → page ids; `list_imported_sections` → imported component ids; `import_section` → import a built component; `add_section_to_page` → place one section (`add_sections_to_page` places MANY at once and can set their props in the same call — fastest way to build a page); `list_page_sections` → the sections placed on a page (LEAN roster: per-placement `elementId`, `componentId`, `propCount`, which props are filled — NO schema/values, so it never truncates); `move_page_section` → reorder a section already placed on a page (by `direction` up/down or an absolute `to_index`) — the only way to change section order, since the editor UI offers it solely as a drag; `get_component_props` → a component's prop blueprint (types, ENUM valid `options`, COMPONENT_LIST `allowedComponentIds`) for any section OR child id; `get_section_values` → one section's current prop values (for read-modify-write); `get_page_by_type` → a theme page id by pageType (e.g. CATEGORY), to build PAGE links to entities (`create_page` adds that page if it does not exist yet, so you never guess a slug); `update_section_prop` → change a single prop value of a placed section (`update_page_sections` fills MANY sections/props of a page in ONE call — strongly prefer it to cut round-trips when filling content); `upload_image` → upload one image (file or URL) and get an image id (`upload_images` uploads many in one call — prefer it for several); `search_products` / `list_categories` / `list_brands` / `list_blogs` / `list_blog_categories` → find real entity ids for PRODUCT/CATEGORY/BRAND/BLOG/BLOG_CATEGORY prop values; `publish_theme` → publish the theme LIVE and get back the preview URL to review (guarded — needs `confirm:true`, and `confirm_production:true` for the main theme; only call it when the user explicitly asks to publish); `list_ready_made_pages` / `update_ready_made_page_prop` / `enable_ready_made_pages` → the ikas-rendered ready-made account/membership pages (login, register, my account, orders, …) — these are NOT sections and the section tools cannot edit them; use these three to enable the groups, read their prop schemas, and customize/localize them (logo, colors, texts). When the user asks to BUILD a login/register/password/my-account/orders/addresses page, FIRST offer these ready-made pages instead of assembling one from sections — they are fully functional out of the box and customizable (logo, colors, texts); build a custom section page only if the user prefers a custom design. Offer, don't flip: `enable_ready_made_pages` creates/removes pages, so get the user's explicit OK before calling it. For the full end-to-end process (placing a section and filling its content, with per-prop value shapes and COMPONENT_LIST rules), call `get_editor_workflow` first.\n\n" +
1976
+ "READY-MADE PAGES FIRST — HARD RULE for account/membership pages: USER-FACING NAME: name these in the USER'S OWN LANGUAGE — English: \"ikas's ready-made pages\", Turkish: \"ikas'ın hazır sayfaları\"; never mix the English term into a sentence in another language — the editor UI lists them as Membership Pages / My Account Pages; \"built-in\" is an internal term — keep it out of everything the user sees, including question/option labels. When the user asks for a login, register, forgot/recover-password, my-account, orders, order-detail, addresses, favorites or email-verification page, do NOT start coding a custom section page. STOP and ask the user FIRST whether to use ikas's ready-made version of that page (`list_ready_made_pages` shows it — fully functional out of the box, customized/localized via `update_ready_made_page_prop`, the whole group turned on with `enable_ready_made_pages`). Only build a custom section page AFTER the user explicitly chooses custom. When asking, list the ready-made option FIRST as the recommended default; the custom section option comes second. Never call `enable_ready_made_pages` without the user's OK — it creates/removes pages. Ready-made pages are born with ONLY their own ikas-rendered element: the theme's header/footer are NOT on them (the page draws its own top bar — logo, back-to-store link — and account nav). If the user wants the theme header/footer on a ready-made page, PLACE it there with add_section_to_page — sections can sit above/below that element — and suggest turning the page's own `showBrandBar` prop off to avoid double chrome.\n\n" +
1977
+ "To CHANGE/EDIT a prop value (text, color, boolean, number, etc.) of a section that is already on a page, this IS supported: call `list_page_sections(page_id)` to get the placement `elementId` and the prop names/ids, then `update_section_prop(page_id, element_id, prop_name|prop_id, value)`. Do not assume prop editing is unavailable.\n\n" +
1978
+ "TWO DISTINCT JOBS — do not confuse them, and do not jump to writing code for the second one:\n" +
1979
+ "(A) DEFINING props / authoring a component = changing which props a component HAS. This edits the component source/config (types.ts via `ikas-component config add-prop`/`add-component`, JSX in index.tsx, etc.) and requires a rebuild. Use this ONLY when the needed prop does not exist yet, or the user explicitly asks to build/modify the component's code or prop schema.\n" +
1980
+ "(B) SETTING prop VALUES / filling content = giving values to props that ALREADY exist on a section placed on a page. This is pure data entry via `list_page_sections` + `update_section_prop` (and `upload_image` for images). It writes NO code and needs NO rebuild.\n" +
1981
+ "When the user says things like 'fill this section', 'set the heading/title/text/image/link', 'populate', 'change the content/value', or 'enter this data', that is JOB (B): use `update_section_prop`. First call `list_page_sections` and check the existing `props` — if the prop is already there (it usually is), just set its value. Only fall back to JOB (A) if the required prop genuinely does not exist in that section's `props`. Writing a new component or adding a prop to fill in a value the section already supports is the wrong move.\n\n" +
1982
+ "COMMON (GLOBAL) SECTIONS — HEADER & FOOTER: these render on every page that CARRIES A PLACEMENT of them — pages created in the editor are seeded with one, EXCEPT ikas ready-made (built-in) account/membership pages, which are born WITHOUT the theme header/footer (see the ready-made rule above) — and their prop values are shared theme-wide, stored in ONE record on the INDEX (Home) page's placement. Reads and writes from any page are resolved to that record, and every response about such a section carries a `common` block (`isCommon`, `commonSectionType`, `canonicalPageId`, `canonicalElementId`, `valuesArePageSpecific: false`). Consequences: changing a header/footer prop from, say, a product-detail page changes it on ALL pages; and since the header/footer normally already holds the merchant's content, you must `get_section_values` first and change only what the user asked — never treat a prop as empty and never blind-fill 'missing' props, or you overwrite live content everywhere. If the INDEX page has no placement of the section there is no record at all: reads report nothing and writes fail until you add it to the INDEX page.",
1660
1983
  });
1661
1984
  // Tool: search_docs
1662
1985
  server.tool("search_docs", "Search across all ikas storefront API docs, framework guides, and migration guides. Returns matching functions, framework topics, and migration topics ranked by relevance.", { query: z.string().describe("Search keyword or phrase") }, async ({ query }) => {
@@ -1676,7 +1999,7 @@ server.tool("search_docs", "Search across all ikas storefront API docs, framewor
1676
1999
  if (topics.length > 0) {
1677
2000
  parts.push("\n## Matching Framework Topics\n");
1678
2001
  for (const item of topics) {
1679
- parts.push(`- **${item.topic.title}** (key: \`${item.key}\`) - ${item.topic.description}`);
2002
+ parts.push(`- **${item.topic.title}** (key: \`${item.key}\`) - ${item.topic.description}${sectionHint(item.topic.content, query, item.topic.title)}`);
1680
2003
  }
1681
2004
  parts.push("");
1682
2005
  parts.push("Use `get_framework_guide(topic)` to get full content for any topic.");
@@ -1692,18 +2015,25 @@ server.tool("search_docs", "Search across all ikas storefront API docs, framewor
1692
2015
  if (migrationTopics.length > 0) {
1693
2016
  parts.push("\n## Matching Migration Topics\n");
1694
2017
  for (const item of migrationTopics) {
1695
- parts.push(`- [migration] **${item.topic.title}** (key: \`${item.key}\`) - ${item.topic.description}`);
2018
+ parts.push(`- [migration] **${item.topic.title}** (key: \`${item.key}\`) - ${item.topic.description}${sectionHint(item.topic.content, query, item.topic.title)}`);
1696
2019
  }
1697
2020
  parts.push("");
1698
2021
  parts.push("Use `get_migration_guide(topic)` to get full content for any migration topic.");
1699
2022
  }
1700
- if (functions.length === 0 && topics.length === 0 && types.length === 0 && migrationTopics.length === 0) {
2023
+ if (functions.length === 0 &&
2024
+ topics.length === 0 &&
2025
+ types.length === 0 &&
2026
+ migrationTopics.length === 0) {
1701
2027
  parts.push(`No results found for "${query}". Try different keywords or use \`list_functions()\` to see all available functions.`);
1702
2028
  }
1703
2029
  return { content: [{ type: "text", text: parts.join("\n") }] };
1704
2030
  });
1705
2031
  // Tool: get_function_doc
1706
- server.tool("get_function_doc", "Get full documentation for a specific storefront API function including signature, parameters, return type, and example.", { name: z.string().describe("Function name (e.g. 'addItemToCart', 'Router.navigate')") }, async ({ name }) => {
2032
+ server.tool("get_function_doc", "Get full documentation for a specific storefront API function including signature, parameters, return type, and example.", {
2033
+ name: z
2034
+ .string()
2035
+ .describe("Function name (e.g. 'addItemToCart', 'Router.navigate')"),
2036
+ }, async ({ name }) => {
1707
2037
  const nameLower = name.toLowerCase();
1708
2038
  // Phase 1: canonical-name match wins. A real function name always outranks
1709
2039
  // any displayName alias so aliases can never shadow the function they're
@@ -1711,7 +2041,9 @@ server.tool("get_function_doc", "Get full documentation for a specific storefron
1711
2041
  // [BP-DISPLAY-NAME: hasCustomer] alias).
1712
2042
  const byName = storefrontData.functions.find((f) => f.name.toLowerCase() === nameLower);
1713
2043
  if (byName) {
1714
- return { content: [{ type: "text", text: formatFunctionDoc(byName) }] };
2044
+ return {
2045
+ content: [{ type: "text", text: formatFunctionDoc(byName) }],
2046
+ };
1715
2047
  }
1716
2048
  // Phase 2: fall back to displayName aliases.
1717
2049
  const byAlias = storefrontData.functions.filter((f) => f.displayName && f.displayName.toLowerCase() === nameLower);
@@ -1719,7 +2051,9 @@ server.tool("get_function_doc", "Get full documentation for a specific storefron
1719
2051
  const fn = byAlias[0];
1720
2052
  const note = `> Note: "${name}" is a display alias for \`${fn.name}\`.\n\n`;
1721
2053
  return {
1722
- content: [{ type: "text", text: note + formatFunctionDoc(fn) }],
2054
+ content: [
2055
+ { type: "text", text: note + formatFunctionDoc(fn) },
2056
+ ],
1723
2057
  };
1724
2058
  }
1725
2059
  if (byAlias.length > 1) {
@@ -1737,7 +2071,9 @@ server.tool("get_function_doc", "Get full documentation for a specific storefron
1737
2071
  (f.displayName && f.displayName.toLowerCase().includes(nameLower)));
1738
2072
  if (matches.length > 0) {
1739
2073
  const suggestions = matches.slice(0, 5).map((f) => {
1740
- const alias = f.displayName && f.displayName !== f.name ? ` (alias: ${f.displayName})` : "";
2074
+ const alias = f.displayName && f.displayName !== f.name
2075
+ ? ` (alias: ${f.displayName})`
2076
+ : "";
1741
2077
  return ` - ${f.name}${alias}`;
1742
2078
  });
1743
2079
  return {
@@ -1750,7 +2086,12 @@ server.tool("get_function_doc", "Get full documentation for a specific storefron
1750
2086
  };
1751
2087
  }
1752
2088
  return {
1753
- content: [{ type: "text", text: `Function "${name}" not found. Use \`list_functions()\` to see all available functions.` }],
2089
+ content: [
2090
+ {
2091
+ type: "text",
2092
+ text: `Function "${name}" not found. Use \`list_functions()\` to see all available functions.`,
2093
+ },
2094
+ ],
1754
2095
  };
1755
2096
  });
1756
2097
  // Tool: list_functions
@@ -1800,7 +2141,7 @@ server.tool("list_functions", "List storefront API functions. Without a `categor
1800
2141
  if (uncategorized > 0) {
1801
2142
  lines.push(`- \`Other\` (${uncategorized})`);
1802
2143
  }
1803
- lines.push("", "Call `list_functions(category: \"<name>\")` to see one-line summaries for a category.");
2144
+ lines.push("", 'Call `list_functions(category: "<name>")` to see one-line summaries for a category.');
1804
2145
  return { content: [{ type: "text", text: lines.join("\n") }] };
1805
2146
  }
1806
2147
  const catLower = category.toLowerCase();
@@ -1832,7 +2173,11 @@ server.tool("list_functions", "List storefront API functions. Without a `categor
1832
2173
  return { content: [{ type: "text", text: parts.join("\n") }] };
1833
2174
  });
1834
2175
  // Tool: get_code_example
1835
- server.tool("get_code_example", "Get an API usage reference for a specific task. Shows correct function calls, imports, and data-handling patterns from a real production theme. The JSX layout and CSS are illustrative only — create your own original visual design. Call `list_examples()` to see available example IDs.", { task: z.string().describe("Task description or example ID (call `list_examples()` for the full list)") }, async ({ task }) => {
2176
+ server.tool("get_code_example", "Get an API usage reference for a specific task. Shows correct function calls, imports, and data-handling patterns from a real production theme. The JSX layout and CSS are illustrative only — create your own original visual design. Call `list_examples()` to see available example IDs.", {
2177
+ task: z
2178
+ .string()
2179
+ .describe("Task description or example ID (call `list_examples()` for the full list)"),
2180
+ }, async ({ task }) => {
1836
2181
  const taskLower = task.toLowerCase();
1837
2182
  // Try exact ID match first
1838
2183
  let example = storefrontData.codeExamples.find((e) => e.id === taskLower);
@@ -1852,7 +2197,9 @@ server.tool("get_code_example", "Get an API usage reference for a specific task.
1852
2197
  }
1853
2198
  }
1854
2199
  if (!example) {
1855
- const available = storefrontData.codeExamples.map((e) => ` - \`${e.id}\` - ${e.title}`).join("\n");
2200
+ const available = storefrontData.codeExamples
2201
+ .map((e) => ` - \`${e.id}\` - ${e.title}`)
2202
+ .join("\n");
1856
2203
  return {
1857
2204
  content: [
1858
2205
  {
@@ -1875,20 +2222,30 @@ server.tool("get_code_example", "Get an API usage reference for a specific task.
1875
2222
  if (example.files && example.files.length > 0) {
1876
2223
  for (const file of example.files) {
1877
2224
  const ext = file.filename.split(".").pop() || "text";
1878
- const lang = ext === "tsx" || ext === "ts" ? "typescript" : ext === "css" ? "css" : ext === "json" ? "json" : "text";
2225
+ const lang = ext === "tsx" || ext === "ts"
2226
+ ? "typescript"
2227
+ : ext === "css"
2228
+ ? "css"
2229
+ : ext === "json"
2230
+ ? "json"
2231
+ : "text";
1879
2232
  // Add inline originality comments to CSS and TSX files
1880
2233
  let content = file.content;
1881
2234
  if (ext === "css") {
1882
- content = "/* EXAMPLE STYLING — create your own original CSS with different class names and design */\n" + content;
2235
+ content =
2236
+ "/* EXAMPLE STYLING — create your own original CSS with different class names and design */\n" +
2237
+ content;
1883
2238
  }
1884
2239
  else if (ext === "tsx") {
1885
- content = "// EXAMPLE COMPONENT — use the API patterns but create your own JSX structure and layout\n" + content;
2240
+ content =
2241
+ "// EXAMPLE COMPONENT — use the API patterns but create your own JSX structure and layout\n" +
2242
+ content;
1886
2243
  }
1887
2244
  parts.push(`### ${file.filename}`, "", `\`\`\`${lang}`, content, "```", "");
1888
2245
  }
1889
2246
  }
1890
2247
  else {
1891
- parts.push("```typescript", example.code, "```", "");
2248
+ parts.push(asCodeBlock(example.code), "");
1892
2249
  }
1893
2250
  parts.push(`**Reminder:** Use the API patterns above (function calls, imports, type handling) but create your own original HTML structure and CSS.`);
1894
2251
  parts.push("");
@@ -1896,63 +2253,95 @@ server.tool("get_code_example", "Get an API usage reference for a specific task.
1896
2253
  return { content: [{ type: "text", text: parts.join("\n") }] };
1897
2254
  });
1898
2255
  // Tool: get_framework_guide
1899
- server.tool("get_framework_guide", "Get a framework guide on a specific topic (e.g. 'ai-workflow', 'common-pitfalls', 'prop-types', 'css-scoping', 'form-handling'). Call `list_topics()` to see all available topic keys.", { topic: z.string().describe("Topic key or keyword (call `list_topics()` for the full list)") }, async ({ topic }) => {
2256
+ server.tool("get_framework_guide", "Get a framework guide on a specific topic (e.g. 'ai-workflow', 'common-pitfalls', 'prop-types', 'css-scoping', 'form-handling'). Call `list_topics()` to see all available topic keys.", {
2257
+ topic: z
2258
+ .string()
2259
+ .describe("Topic key or keyword (call `list_topics()` for the full list)"),
2260
+ }, async ({ topic }) => {
1900
2261
  const topicLower = topic.toLowerCase().replace(/\s+/g, "-");
1901
2262
  // Alias mapping for common alternative topic names
1902
2263
  const topicAliases = {
1903
2264
  "form-handling": "form-patterns",
1904
- "forms": "form-patterns",
2265
+ forms: "form-patterns",
1905
2266
  "data-fetching": "async-data-patterns",
1906
- "async": "async-data-patterns",
1907
- "loading": "async-data-patterns",
2267
+ async: "async-data-patterns",
2268
+ loading: "async-data-patterns",
1908
2269
  "sub-components": "sub-component-patterns",
1909
- "subcomponents": "sub-component-patterns",
1910
- "routing": "navigation-patterns",
1911
- "router": "navigation-patterns",
1912
- "observer": "component-structure",
1913
- "reactivity": "component-structure",
1914
- "pitfalls": "common-pitfalls",
1915
- "gotchas": "common-pitfalls",
1916
- "mistakes": "common-pitfalls",
1917
- "header": "header-footer-patterns",
1918
- "footer": "header-footer-patterns",
1919
- "blog": "blog-patterns",
1920
- "cart": "cart-patterns",
1921
- "account": "account-patterns",
2270
+ subcomponents: "sub-component-patterns",
2271
+ routing: "navigation-patterns",
2272
+ router: "navigation-patterns",
2273
+ observer: "component-structure",
2274
+ reactivity: "component-structure",
2275
+ pitfalls: "common-pitfalls",
2276
+ gotchas: "common-pitfalls",
2277
+ mistakes: "common-pitfalls",
2278
+ header: "header-footer-patterns",
2279
+ footer: "header-footer-patterns",
2280
+ blog: "blog-patterns",
2281
+ cart: "cart-patterns",
2282
+ account: "account-patterns",
1922
2283
  "product-detail": "product-detail-patterns",
1923
2284
  "product-list": "product-list-patterns",
1924
- "filtering": "product-list-patterns",
1925
- "reviews": "review-patterns",
1926
- "slider": "slider-overlay-patterns",
1927
- "overlay": "slider-overlay-patterns",
1928
- "modal": "slider-overlay-patterns",
1929
- "architecture": "real-world-architecture",
1930
- "theme": "real-world-architecture",
2285
+ filtering: "product-list-patterns",
2286
+ reviews: "review-patterns",
2287
+ slider: "slider-overlay-patterns",
2288
+ overlay: "slider-overlay-patterns",
2289
+ modal: "slider-overlay-patterns",
2290
+ architecture: "real-world-architecture",
2291
+ theme: "real-world-architecture",
1931
2292
  "global-styles": "global-css",
1932
- "global": "global-css",
2293
+ global: "global-css",
1933
2294
  "css-variables": "global-css",
1934
2295
  "custom-properties": "global-css",
2296
+ conditional: "conditional-visibility",
2297
+ "conditional-props": "conditional-visibility",
2298
+ visibility: "conditional-visibility",
2299
+ requiredprop: "conditional-visibility",
2300
+ "required-prop": "conditional-visibility",
2301
+ "dependent-props": "conditional-visibility",
2302
+ "show-hide": "conditional-visibility",
1935
2303
  };
1936
2304
  const resolvedTopic = topicAliases[topicLower] || topicLower;
1937
2305
  // Topics that involve MobX store reads get a reminder about root reactivity
1938
2306
  const storeTopics = new Set([
1939
- "product-detail-patterns", "product-list-patterns", "cart-patterns",
1940
- "account-patterns", "header-footer-patterns", "review-patterns",
1941
- "blog-patterns", "form-handling", "async-data-patterns",
1942
- "component-structure", "imports",
2307
+ "product-detail-patterns",
2308
+ "product-list-patterns",
2309
+ "cart-patterns",
2310
+ "account-patterns",
2311
+ "header-footer-patterns",
2312
+ "review-patterns",
2313
+ "blog-patterns",
2314
+ "form-handling",
2315
+ "async-data-patterns",
2316
+ "component-structure",
2317
+ "imports",
1943
2318
  ]);
1944
2319
  const observerReminder = "> **IMPORTANT: Do NOT use `observer()` on root component exports.** The ikas runtime wraps root renders in MobX `autorun()`, making them automatically reactive. All store reads (`cartStore`, `customerStore`, etc.) in root components are tracked automatically. Only use `observer()` on extracted sub-components.\n\n";
1945
2320
  // Try exact key match (with alias resolution)
1946
2321
  if (frameworkData.topics[resolvedTopic]) {
1947
2322
  const t = frameworkData.topics[resolvedTopic];
1948
2323
  const prefix = storeTopics.has(resolvedTopic) ? observerReminder : "";
1949
- return { content: [{ type: "text", text: `## ${t.title}\n\n${prefix}${t.content}` }] };
2324
+ return {
2325
+ content: [
2326
+ {
2327
+ type: "text",
2328
+ text: `## ${t.title}\n\n${prefix}${t.content}`,
2329
+ },
2330
+ ],
2331
+ };
1950
2332
  }
1951
2333
  // Try original topic key (without alias) in case it's a direct key
1952
2334
  if (resolvedTopic !== topicLower && frameworkData.topics[topicLower]) {
1953
2335
  const t = frameworkData.topics[topicLower];
1954
2336
  const prefix = storeTopics.has(topicLower) ? observerReminder : "";
1955
- return { content: [{ type: "text", text: `## ${t.title}\n\n${prefix}${t.content}` }] };
2337
+ return {
2338
+ content: [
2339
+ {
2340
+ type: "text",
2341
+ text: `## ${t.title}\n\n${prefix}${t.content}`,
2342
+ },
2343
+ ],
2344
+ };
1956
2345
  }
1957
2346
  // Try keyword search
1958
2347
  const matches = searchFrameworkTopics(topic);
@@ -1960,7 +2349,12 @@ server.tool("get_framework_guide", "Get a framework guide on a specific topic (e
1960
2349
  const best = matches[0];
1961
2350
  const prefix = storeTopics.has(best.key) ? observerReminder : "";
1962
2351
  return {
1963
- content: [{ type: "text", text: `## ${best.topic.title}\n\n${prefix}${best.topic.content}` }],
2352
+ content: [
2353
+ {
2354
+ type: "text",
2355
+ text: `## ${best.topic.title}\n\n${prefix}${best.topic.content}`,
2356
+ },
2357
+ ],
1964
2358
  };
1965
2359
  }
1966
2360
  const available = Object.entries(frameworkData.topics)
@@ -1976,16 +2370,27 @@ server.tool("get_framework_guide", "Get a framework guide on a specific topic (e
1976
2370
  };
1977
2371
  });
1978
2372
  // Tool: get_type_definition
1979
- server.tool("get_type_definition", "Get the full definition of a storefront type or enum by name (e.g. 'IkasProduct', 'IkasOrderStatus'). Shows all properties with types, extends, or enum values.", { name: z.string().describe("Type or enum name (e.g. 'IkasProduct', 'IkasOrderStatus')") }, async ({ name }) => {
2373
+ server.tool("get_type_definition", "Get the full definition of a storefront type or enum by name. Shows all properties with types, extends, enum values, or string-union values. Covers runtime models (e.g. 'IkasProduct', 'IkasOrderStatus'), theme-globals tokens returned by the getters (e.g. 'ThemeSetting', 'DesignToken', 'TypographyToken', 'ColorSchemeToken', 'BreakpointToken', 'KeyframeToken'), and style-prop TYPE shapes used by ikas.config.json props (e.g. 'BorderRadiusStyleType', 'PaddingStyleType', 'GapStyleType', 'SizeStyleType' and their '*StyleUnitType' unions). If a type reports as not found, it may not be indexed yet — fall back to reading the package's `.d.ts` (e.g. `@ikas/bp-storefront-config`) rather than typing the value as `any`.", {
2374
+ name: z
2375
+ .string()
2376
+ .describe("Type or enum name (e.g. 'IkasProduct', 'IkasOrderStatus')"),
2377
+ }, async ({ name }) => {
1980
2378
  if (!typesData) {
1981
2379
  return {
1982
- content: [{ type: "text", text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first." }],
2380
+ content: [
2381
+ {
2382
+ type: "text",
2383
+ text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first.",
2384
+ },
2385
+ ],
1983
2386
  };
1984
2387
  }
1985
2388
  const nameLower = name.toLowerCase();
1986
2389
  const td = typesData.types.find((t) => t.name.toLowerCase() === nameLower);
1987
2390
  if (td) {
1988
- return { content: [{ type: "text", text: formatTypeDefinition(td) }] };
2391
+ return {
2392
+ content: [{ type: "text", text: formatTypeDefinition(td) }],
2393
+ };
1989
2394
  }
1990
2395
  // Fuzzy match
1991
2396
  const matches = typesData.types.filter((t) => t.name.toLowerCase().includes(nameLower));
@@ -2001,14 +2406,28 @@ server.tool("get_type_definition", "Get the full definition of a storefront type
2001
2406
  };
2002
2407
  }
2003
2408
  return {
2004
- content: [{ type: "text", text: `Type "${name}" not found. Use \`list_types()\` to see all available types.` }],
2409
+ content: [
2410
+ {
2411
+ type: "text",
2412
+ text: `Type "${name}" not found. Use \`list_types()\` to see all available types.`,
2413
+ },
2414
+ ],
2005
2415
  };
2006
2416
  });
2007
2417
  // Tool: get_functions_for_type
2008
- server.tool("get_functions_for_type", "Get full documentation for all utility functions that operate on a given storefront type. For example, get_functions_for_type('IkasImage') returns getSrc, getDefaultSrc, getThumbnailSrc, createMediaSrcset with full signatures, descriptions, and examples.", { typeName: z.string().describe("Type name (e.g. 'IkasImage', 'IkasProduct', 'IkasOrder')") }, async ({ typeName }) => {
2418
+ server.tool("get_functions_for_type", "Get full documentation for all utility functions that operate on a given storefront type. For example, get_functions_for_type('IkasImage') returns getSrc, getDefaultSrc, getThumbnailSrc, createMediaSrcset with full signatures, descriptions, and examples.", {
2419
+ typeName: z
2420
+ .string()
2421
+ .describe("Type name (e.g. 'IkasImage', 'IkasProduct', 'IkasOrder')"),
2422
+ }, async ({ typeName }) => {
2009
2423
  if (!typesData) {
2010
2424
  return {
2011
- content: [{ type: "text", text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first." }],
2425
+ content: [
2426
+ {
2427
+ type: "text",
2428
+ text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first.",
2429
+ },
2430
+ ],
2012
2431
  };
2013
2432
  }
2014
2433
  const nameLower = typeName.toLowerCase();
@@ -2028,7 +2447,12 @@ server.tool("get_functions_for_type", "Get full documentation for all utility fu
2028
2447
  };
2029
2448
  }
2030
2449
  return {
2031
- content: [{ type: "text", text: `Type "${typeName}" not found. Use \`list_types()\` to see all available types.` }],
2450
+ content: [
2451
+ {
2452
+ type: "text",
2453
+ text: `Type "${typeName}" not found. Use \`list_types()\` to see all available types.`,
2454
+ },
2455
+ ],
2032
2456
  };
2033
2457
  }
2034
2458
  if (!td.relatedFunctions || td.relatedFunctions.length === 0) {
@@ -2059,7 +2483,10 @@ server.tool("get_functions_for_type", "Get full documentation for all utility fu
2059
2483
  });
2060
2484
  // Tool: get_model_guide
2061
2485
  server.tool("get_model_guide", "Get an overview of a storefront model type. By default returns the type definition, related function names with one-line summaries, matching example titles/IDs, and related type summaries. Pass `mode: 'full'` to inline full function docs and example code.", {
2062
- model: z.string().optional().describe("Model type name (e.g. 'IkasImage', 'IkasProduct', 'IkasOrder')"),
2486
+ model: z
2487
+ .string()
2488
+ .optional()
2489
+ .describe("Model type name (e.g. 'IkasImage', 'IkasProduct', 'IkasOrder')"),
2063
2490
  name: z.string().optional().describe("Alias for 'model'"),
2064
2491
  mode: z
2065
2492
  .enum(["summary", "full"])
@@ -2070,12 +2497,22 @@ server.tool("get_model_guide", "Get an overview of a storefront model type. By d
2070
2497
  const model = modelParam || nameParam;
2071
2498
  if (!model) {
2072
2499
  return {
2073
- content: [{ type: "text", text: "Please provide a model name (e.g. 'IkasProduct', 'IkasOrder'). Use the 'model' or 'name' parameter." }],
2500
+ content: [
2501
+ {
2502
+ type: "text",
2503
+ text: "Please provide a model name (e.g. 'IkasProduct', 'IkasOrder'). Use the 'model' or 'name' parameter.",
2504
+ },
2505
+ ],
2074
2506
  };
2075
2507
  }
2076
2508
  if (!typesData) {
2077
2509
  return {
2078
- content: [{ type: "text", text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first." }],
2510
+ content: [
2511
+ {
2512
+ type: "text",
2513
+ text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first.",
2514
+ },
2515
+ ],
2079
2516
  };
2080
2517
  }
2081
2518
  const modelLower = model.toLowerCase();
@@ -2097,7 +2534,12 @@ server.tool("get_model_guide", "Get an overview of a storefront model type. By d
2097
2534
  };
2098
2535
  }
2099
2536
  return {
2100
- content: [{ type: "text", text: `Model "${model}" not found. Use \`list_types()\` to see all available types.` }],
2537
+ content: [
2538
+ {
2539
+ type: "text",
2540
+ text: `Model "${model}" not found. Use \`list_types()\` to see all available types.`,
2541
+ },
2542
+ ],
2101
2543
  };
2102
2544
  }
2103
2545
  const parts = [`# Model Guide: ${td.name}\n`];
@@ -2205,13 +2647,23 @@ server.tool("get_model_guide", "Get an overview of a storefront model type. By d
2205
2647
  server.tool("search_types", "Search storefront types and enums by keyword (e.g. 'price', 'address', 'status'). Returns top matches ranked by relevance.", { query: z.string().describe("Search keyword or phrase") }, async ({ query }) => {
2206
2648
  if (!typesData) {
2207
2649
  return {
2208
- content: [{ type: "text", text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first." }],
2650
+ content: [
2651
+ {
2652
+ type: "text",
2653
+ text: "Type data not available. Run 'npm run docs:generate' in storefront-docs first.",
2654
+ },
2655
+ ],
2209
2656
  };
2210
2657
  }
2211
2658
  const results = searchTypes(query).slice(0, 15);
2212
2659
  if (results.length === 0) {
2213
2660
  return {
2214
- content: [{ type: "text", text: `No types found matching "${query}". Use \`list_types()\` to see all available types.` }],
2661
+ content: [
2662
+ {
2663
+ type: "text",
2664
+ text: `No types found matching "${query}". Use \`list_types()\` to see all available types.`,
2665
+ },
2666
+ ],
2215
2667
  };
2216
2668
  }
2217
2669
  const parts = [`## Type Search Results for "${query}"\n`];
@@ -2275,7 +2727,7 @@ server.tool("list_types", "List storefront types and enums. Use `domain` and/or
2275
2727
  for (const [d, count] of sorted) {
2276
2728
  lines.push(`- \`${d}\` (${count})`);
2277
2729
  }
2278
- lines.push("", "Call `list_types(domain: \"<name>\")` to see summaries for a domain.");
2730
+ lines.push("", 'Call `list_types(domain: "<name>")` to see summaries for a domain.');
2279
2731
  return { content: [{ type: "text", text: lines.join("\n") }] };
2280
2732
  }
2281
2733
  const domainLower = domain.toLowerCase();
@@ -2314,18 +2766,45 @@ server.tool("list_types", "List storefront types and enums. Use `domain` and/or
2314
2766
  return { content: [{ type: "text", text: parts.join("\n") }] };
2315
2767
  });
2316
2768
  // Tool: get_prop_types
2317
- server.tool("get_prop_types", "Get all available ikas.config.json prop types with descriptions, TypeScript types, and examples. Tip: Use `npx ikas-component config add-component --props '[...]'` to create a component with all props in one command, or `add-prop` to add props incrementally. NEVER manually edit types.ts — it is auto-generated by the CLI.", {}, async () => {
2769
+ server.tool("get_prop_types", 'Get all available ikas.config.json prop types with descriptions, TypeScript types, and examples. NOTE: these are the TypeScript prop-definition types for authoring a component — they are NOT the runtime JSON value shapes you write via `update_section_prop` (e.g. a TEXT prop is typed `string` here but written as `{ "value": "..." }`, and an IMAGE is `IkasImage | null` here but written as `{ "id": "..." }`). For the value shapes to pass to `update_section_prop`, see that tool\'s description. Tip: Use `npx ikas-component config add-component --props \'[...]\'` to create a component with all props in one command, or `add-prop` to add props incrementally. NEVER manually edit types.ts — it is auto-generated by the CLI.', {}, async () => {
2318
2770
  const propTypesTopic = frameworkData.topics["prop-types"];
2319
2771
  if (propTypesTopic) {
2320
2772
  return {
2321
- content: [{ type: "text", text: `## ${propTypesTopic.title}\n\n${propTypesTopic.content}` }],
2773
+ content: [
2774
+ {
2775
+ type: "text",
2776
+ text: `## ${propTypesTopic.title}\n\n${propTypesTopic.content}`,
2777
+ },
2778
+ ],
2322
2779
  };
2323
2780
  }
2324
2781
  return {
2325
- content: [{ type: "text", text: "Prop types documentation not available." }],
2782
+ content: [
2783
+ {
2784
+ type: "text",
2785
+ text: "Prop types documentation not available.",
2786
+ },
2787
+ ],
2326
2788
  };
2327
2789
  });
2328
2790
  // Tool: get_section_template
2791
+ // Starter templates that rebuild a page ikas already ships as a ready-made BUILT-IN page. Asked to
2792
+ // "build a login page", the agent reaches for the template before any other tool — so the
2793
+ // ask-the-user gate rides this response, where it cannot be skimmed past.
2794
+ const BUILTIN_COVERED_TEMPLATES = new Set([
2795
+ "login-section",
2796
+ "register-section",
2797
+ "forgot-password-section",
2798
+ "recover-password-section",
2799
+ "email-verification-section",
2800
+ "account-info-section",
2801
+ "favorites",
2802
+ ]);
2803
+ const BUILTIN_COVERED_BANNER = [
2804
+ "STOP — ASK THE USER BEFORE CODING THIS.",
2805
+ "This template rebuilds a page ikas already ships as a ready-made page: fully functional auth/account flows out of the box, customized and localized via `update_ready_made_page_prop`, the whole group enabled with `enable_ready_made_pages` (see `list_ready_made_pages`).",
2806
+ "If the user has not EXPLICITLY chosen a custom-coded page, do not write code yet. Ask them now: (a) ikas's ready-made page — instant, maintained by ikas — or (b) a custom section with full design freedom. List the ready-made option FIRST as the recommended default; custom comes second. Continue with this template ONLY after they explicitly choose custom.",
2807
+ ].join("\n");
2329
2808
  // Build the enum dynamically from the on-disk section templates directory
2330
2809
  const sectionTemplateKeys = sectionTemplateNames.length > 0
2331
2810
  ? sectionTemplateNames
@@ -2410,6 +2889,9 @@ server.tool("get_section_template", "Get the root files of a starter section tem
2410
2889
  (bundle.componentNames.length > 0 && !componentsFullyIncluded) ||
2411
2890
  (bundle.subComponentNames.length > 0 && !subComponentsFullyIncluded);
2412
2891
  const parts = [
2892
+ ...(BUILTIN_COVERED_TEMPLATES.has(normalizedType)
2893
+ ? [BUILTIN_COVERED_BANNER, ""]
2894
+ : []),
2413
2895
  `## ${bundle.title} — API Integration Pattern Reference`,
2414
2896
  "",
2415
2897
  ];
@@ -2419,7 +2901,8 @@ server.tool("get_section_template", "Get the root files of a starter section tem
2419
2901
  // the end of the response in the existing recipe-builder block.
2420
2902
  {
2421
2903
  const snippetStrForBanner = bundle.rootFiles["ikas-config-snippet.json"];
2422
- if (snippetStrForBanner && /<id-of-[A-Za-z0-9_]+>/.test(snippetStrForBanner)) {
2904
+ if (snippetStrForBanner &&
2905
+ /<id-of-[A-Za-z0-9_]+>/.test(snippetStrForBanner)) {
2423
2906
  const childMatches = Array.from(snippetStrForBanner.matchAll(/<id-of-([A-Za-z0-9_]+)>/g));
2424
2907
  const uniqueChildren = Array.from(new Set(childMatches.map((m) => m[1])));
2425
2908
  parts.push(`> 🔧 **CONTAINER SECTION — required wiring.** This template hosts ${uniqueChildren.length} child component${uniqueChildren.length === 1 ? "" : "s"} (${uniqueChildren.map((n) => `\`${n}\``).join(", ")}) via a \`COMPONENT_LIST\` slot. Creating the parent alone produces an empty, unusable section. **You MUST follow the full Setup Recipe below**: create each child → capture its \`componentId\` → wire them into the parent's \`filteredComponentIds\` with \`config update-prop\`. Component ids are opaque random strings (e.g. \`7ojrigep-Eml9n5sN3i\`) — they cannot be derived from names, and the CLI rejects unknown ids.`, "");
@@ -2543,7 +3026,10 @@ server.tool("get_section_template", "Get the root files of a starter section tem
2543
3026
  try {
2544
3027
  const childSnippet = JSON.parse(fs.readFileSync(childSnippetPath, "utf-8"));
2545
3028
  const childProps = (childSnippet.props || []).map((p) => {
2546
- const out = { name: p.name, type: p.type };
3029
+ const out = {
3030
+ name: p.name,
3031
+ type: p.type,
3032
+ };
2547
3033
  if (p.displayName)
2548
3034
  out.displayName = p.displayName;
2549
3035
  if (p.required)
@@ -2616,10 +3102,7 @@ server.tool("get_section_child", "Fetch one item's files from a section's childr
2616
3102
  .string()
2617
3103
  .optional()
2618
3104
  .describe("The item name as listed in `get_section_template`'s response (Children/Components/Sub-components)"),
2619
- child: z
2620
- .string()
2621
- .optional()
2622
- .describe("Alias for `name`"),
3105
+ child: z.string().optional().describe("Alias for `name`"),
2623
3106
  kind: z
2624
3107
  .enum(["children", "components", "sub-components"])
2625
3108
  .optional()
@@ -2775,14 +3258,21 @@ server.tool("list_section_types", "List all available `get_section_template` sec
2775
3258
  ];
2776
3259
  for (const name of sectionTemplateNames) {
2777
3260
  const meta = loadSectionMeta(name);
2778
- lines.push(`- \`${name}\`${meta ? ` — ${meta.title}` : ""}`);
3261
+ const builtinMark = BUILTIN_COVERED_TEMPLATES.has(name)
3262
+ ? " [ikas ships a ready-made page for this — ask the user before coding a custom one; see list_ready_made_pages]"
3263
+ : "";
3264
+ lines.push(`- \`${name}\`${meta ? ` — ${meta.title}` : ""}${builtinMark}`);
2779
3265
  }
2780
3266
  lines.push("", "Call `get_section_template(sectionType)` to fetch one.");
2781
3267
  return { content: [{ type: "text", text: lines.join("\n") }] };
2782
3268
  });
2783
3269
  // --- Migration tools ---
2784
3270
  // Tool: analyze_old_theme
2785
- server.tool("analyze_old_theme", "Analyze an old ikas storefront theme.json and produce a structured migration report. Shows all components, custom data definitions, prop type breakdown, and migration recommendations. Use this as the first step when converting an old theme.", { theme_json: z.string().describe("The raw JSON content of the old theme.json file") }, async ({ theme_json }) => {
3271
+ server.tool("analyze_old_theme", "Analyze an old ikas storefront theme.json and produce a structured migration report. Shows all components, custom data definitions, prop type breakdown, and migration recommendations. Use this as the first step when converting an old theme.", {
3272
+ theme_json: z
3273
+ .string()
3274
+ .describe("The raw JSON content of the old theme.json file"),
3275
+ }, async ({ theme_json }) => {
2786
3276
  try {
2787
3277
  const parsed = JSON.parse(theme_json);
2788
3278
  const analysis = analyzeOldTheme(parsed);
@@ -2790,102 +3280,162 @@ server.tool("analyze_old_theme", "Analyze an old ikas storefront theme.json and
2790
3280
  }
2791
3281
  catch (err) {
2792
3282
  return {
2793
- content: [{ type: "text", text: `Error parsing theme.json: ${err instanceof Error ? err.message : String(err)}. Make sure you're passing valid JSON.` }],
3283
+ content: [
3284
+ {
3285
+ type: "text",
3286
+ text: `Error parsing theme.json: ${err instanceof Error ? err.message : String(err)}. Make sure you're passing valid JSON.`,
3287
+ },
3288
+ ],
2794
3289
  };
2795
3290
  }
2796
3291
  });
2797
3292
  // Tool: get_migration_guide
2798
3293
  const migrationTopicAliases = {
2799
- "overview": "migration-overview",
2800
- "migrate": "migration-overview",
2801
- "custom": "custom-data-conversion",
3294
+ overview: "migration-overview",
3295
+ migrate: "migration-overview",
3296
+ custom: "custom-data-conversion",
2802
3297
  "custom-data": "custom-data-conversion",
2803
- "customdata": "custom-data-conversion",
3298
+ customdata: "custom-data-conversion",
2804
3299
  "dynamic-list": "custom-data-conversion",
2805
3300
  "component-list": "custom-data-conversion",
2806
- "slider": "prop-type-mapping",
2807
- "props": "prop-type-mapping",
3301
+ slider: "prop-type-mapping",
3302
+ props: "prop-type-mapping",
2808
3303
  "prop-mapping": "prop-type-mapping",
2809
- "types": "prop-type-mapping",
2810
- "react": "react-to-preact",
2811
- "preact": "react-to-preact",
2812
- "observer": "react-to-preact",
2813
- "libraries": "library-replacements",
2814
- "swiper": "library-replacements",
2815
- "headlessui": "library-replacements",
2816
- "tailwind": "library-replacements",
2817
- "tailwindcss": "library-replacements",
2818
- "recharts": "library-replacements",
2819
- "marquee": "library-replacements",
2820
- "imports": "storefront-import-mapping",
2821
- "storefront": "storefront-import-mapping",
3304
+ types: "prop-type-mapping",
3305
+ react: "react-to-preact",
3306
+ preact: "react-to-preact",
3307
+ observer: "react-to-preact",
3308
+ libraries: "library-replacements",
3309
+ swiper: "library-replacements",
3310
+ headlessui: "library-replacements",
3311
+ tailwind: "library-replacements",
3312
+ tailwindcss: "library-replacements",
3313
+ recharts: "library-replacements",
3314
+ marquee: "library-replacements",
3315
+ imports: "storefront-import-mapping",
3316
+ storefront: "storefront-import-mapping",
2822
3317
  "bp-storefront": "storefront-import-mapping",
2823
3318
  "theme-json": "theme-json-anatomy",
2824
- "anatomy": "theme-json-anatomy",
2825
- "decompose": "component-decomposition-strategy",
2826
- "decomposition": "component-decomposition-strategy",
2827
- "strategy": "component-decomposition-strategy",
2828
- "project": "complete-project-generation",
2829
- "generate": "complete-project-generation",
2830
- "generation": "complete-project-generation",
2831
- "settings": "settings-conversion",
2832
- "colors": "settings-conversion",
2833
- "fonts": "settings-conversion",
2834
- "find": "finding-new-system-equivalents",
2835
- "search": "finding-new-system-equivalents",
2836
- "discover": "finding-new-system-equivalents",
2837
- "equivalent": "finding-new-system-equivalents",
2838
- "equivalents": "finding-new-system-equivalents",
2839
- "replacement": "finding-new-system-equivalents",
3319
+ anatomy: "theme-json-anatomy",
3320
+ decompose: "component-decomposition-strategy",
3321
+ decomposition: "component-decomposition-strategy",
3322
+ strategy: "component-decomposition-strategy",
3323
+ project: "complete-project-generation",
3324
+ generate: "complete-project-generation",
3325
+ generation: "complete-project-generation",
3326
+ settings: "settings-conversion",
3327
+ colors: "settings-conversion",
3328
+ fonts: "settings-conversion",
3329
+ find: "finding-new-system-equivalents",
3330
+ search: "finding-new-system-equivalents",
3331
+ discover: "finding-new-system-equivalents",
3332
+ equivalent: "finding-new-system-equivalents",
3333
+ equivalents: "finding-new-system-equivalents",
3334
+ replacement: "finding-new-system-equivalents",
2840
3335
  };
2841
3336
  const migrationTopicKeys = migrationData
2842
3337
  ? Object.keys(migrationData.topics)
2843
3338
  : [];
2844
- server.tool("get_migration_guide", `Get a migration guide for converting old ikas themes to the new code-component system. **Start with \`get_migration_guide("iterative-workflow")\` if you're new to this MCP** — it explains the MCP-vs-LLM responsibility split and the four phases.${migrationTopicKeys.length > 0 ? ` Available topics: ${migrationTopicKeys.join(", ")}. Also supports aliases like "custom", "slider", "react", "libraries", "imports", "settings".` : ""} Call with topic "list" to see all available topics.`, { topic: z.string().describe("Migration topic key, alias, or 'list' to see all topics") }, async ({ topic }) => {
3339
+ server.tool("get_migration_guide", `Get a migration guide for converting old ikas themes to the new code-component system. **Start with \`get_migration_guide("iterative-workflow")\` if you're new to this MCP** — it explains the MCP-vs-LLM responsibility split and the four phases.${migrationTopicKeys.length > 0 ? ` Available topics: ${migrationTopicKeys.join(", ")}. Also supports aliases like "custom", "slider", "react", "libraries", "imports", "settings".` : ""} Call with topic "list" to see all available topics.`, {
3340
+ topic: z
3341
+ .string()
3342
+ .describe("Migration topic key, alias, or 'list' to see all topics"),
3343
+ }, async ({ topic }) => {
2845
3344
  if (!migrationData) {
2846
- return { content: [{ type: "text", text: "Migration data not available. Ensure data/migration.json exists." }] };
3345
+ return {
3346
+ content: [
3347
+ {
3348
+ type: "text",
3349
+ text: "Migration data not available. Ensure data/migration.json exists.",
3350
+ },
3351
+ ],
3352
+ };
2847
3353
  }
2848
3354
  if (topic.toLowerCase() === "list") {
2849
3355
  const available = Object.entries(migrationData.topics)
2850
3356
  .map(([key, t]) => `- \`${key}\` — ${t.title}: ${t.description}`)
2851
3357
  .join("\n");
2852
- return { content: [{ type: "text", text: `## Available Migration Topics\n\n${available}` }] };
3358
+ return {
3359
+ content: [
3360
+ {
3361
+ type: "text",
3362
+ text: `## Available Migration Topics\n\n${available}`,
3363
+ },
3364
+ ],
3365
+ };
2853
3366
  }
2854
3367
  const topicLower = topic.toLowerCase().replace(/\s+/g, "-");
2855
3368
  const resolvedTopic = migrationTopicAliases[topicLower] || topicLower;
2856
3369
  if (migrationData.topics[resolvedTopic]) {
2857
3370
  const t = migrationData.topics[resolvedTopic];
2858
- return { content: [{ type: "text", text: `## ${t.title}\n\n${t.content}` }] };
3371
+ return {
3372
+ content: [
3373
+ { type: "text", text: `## ${t.title}\n\n${t.content}` },
3374
+ ],
3375
+ };
2859
3376
  }
2860
3377
  // Try original key
2861
3378
  if (resolvedTopic !== topicLower && migrationData.topics[topicLower]) {
2862
3379
  const t = migrationData.topics[topicLower];
2863
- return { content: [{ type: "text", text: `## ${t.title}\n\n${t.content}` }] };
3380
+ return {
3381
+ content: [
3382
+ { type: "text", text: `## ${t.title}\n\n${t.content}` },
3383
+ ],
3384
+ };
2864
3385
  }
2865
3386
  // Keyword search
2866
3387
  const matches = searchMigrationTopics(topic);
2867
3388
  if (matches.length > 0) {
2868
3389
  const best = matches[0];
2869
- return { content: [{ type: "text", text: `## ${best.topic.title}\n\n${best.topic.content}` }] };
3390
+ return {
3391
+ content: [
3392
+ {
3393
+ type: "text",
3394
+ text: `## ${best.topic.title}\n\n${best.topic.content}`,
3395
+ },
3396
+ ],
3397
+ };
2870
3398
  }
2871
3399
  const available = Object.entries(migrationData.topics)
2872
3400
  .map(([key, t]) => ` - \`${key}\` - ${t.title}`)
2873
3401
  .join("\n");
2874
3402
  return {
2875
- content: [{ type: "text", text: `Migration topic "${topic}" not found. Available topics:\n${available}` }],
3403
+ content: [
3404
+ {
3405
+ type: "text",
3406
+ text: `Migration topic "${topic}" not found. Available topics:\n${available}`,
3407
+ },
3408
+ ],
2876
3409
  };
2877
3410
  });
2878
3411
  // Tool: get_migration_example
2879
- server.tool("get_migration_example", `Get a concrete before/after migration example showing how to convert an old theme component to the new code-component system.${migrationExampleNames.length > 0 ? ` Available examples: ${migrationExampleNames.join(", ")}.` : ""} Call with example "list" to see all examples.`, { example: z.string().describe("Example name or 'list' to see all examples") }, async ({ example }) => {
3412
+ server.tool("get_migration_example", `Get a concrete before/after migration example showing how to convert an old theme component to the new code-component system.${migrationExampleNames.length > 0 ? ` Available examples: ${migrationExampleNames.join(", ")}.` : ""} Call with example "list" to see all examples.`, {
3413
+ example: z.string().describe("Example name or 'list' to see all examples"),
3414
+ }, async ({ example }) => {
2880
3415
  if (example.toLowerCase() === "list") {
2881
3416
  if (migrationExampleNames.length === 0) {
2882
- return { content: [{ type: "text", text: "No migration examples available." }] };
3417
+ return {
3418
+ content: [
3419
+ { type: "text", text: "No migration examples available." },
3420
+ ],
3421
+ };
2883
3422
  }
2884
- const list = migrationExampleNames.map((name) => {
3423
+ const list = migrationExampleNames
3424
+ .map((name) => {
2885
3425
  const ex = loadMigrationExample(name);
2886
- return ex ? `- \`${name}\` — ${ex.title}: ${ex.description}` : `- \`${name}\``;
2887
- }).join("\n");
2888
- return { content: [{ type: "text", text: `## Available Migration Examples\n\n${list}` }] };
3426
+ return ex
3427
+ ? `- \`${name}\` — ${ex.title}: ${ex.description}`
3428
+ : `- \`${name}\``;
3429
+ })
3430
+ .join("\n");
3431
+ return {
3432
+ content: [
3433
+ {
3434
+ type: "text",
3435
+ text: `## Available Migration Examples\n\n${list}`,
3436
+ },
3437
+ ],
3438
+ };
2889
3439
  }
2890
3440
  const exampleLower = example.toLowerCase();
2891
3441
  let exName = migrationExampleNames.find((n) => n === exampleLower);
@@ -2895,19 +3445,26 @@ server.tool("get_migration_example", `Get a concrete before/after migration exam
2895
3445
  if (!exName) {
2896
3446
  const available = migrationExampleNames.join(", ");
2897
3447
  return {
2898
- content: [{ type: "text", text: `Migration example "${example}" not found. Available: ${available}` }],
3448
+ content: [
3449
+ {
3450
+ type: "text",
3451
+ text: `Migration example "${example}" not found. Available: ${available}`,
3452
+ },
3453
+ ],
2899
3454
  };
2900
3455
  }
2901
3456
  const ex = loadMigrationExample(exName);
2902
3457
  if (!ex) {
2903
- return { content: [{ type: "text", text: `Failed to load migration example "${exName}".` }] };
3458
+ return {
3459
+ content: [
3460
+ {
3461
+ type: "text",
3462
+ text: `Failed to load migration example "${exName}".`,
3463
+ },
3464
+ ],
3465
+ };
2904
3466
  }
2905
- const parts = [
2906
- `## ${ex.title}`,
2907
- "",
2908
- ex.description,
2909
- "",
2910
- ];
3467
+ const parts = [`## ${ex.title}`, "", ex.description, ""];
2911
3468
  for (const [filename, content] of Object.entries(ex.files)) {
2912
3469
  const ext = filename.split(".").pop() || "text";
2913
3470
  const lang = ext === "tsx" || ext === "ts"
@@ -2926,13 +3483,31 @@ server.tool("get_migration_example", `Get a concrete before/after migration exam
2926
3483
  });
2927
3484
  // Tool: plan_migration
2928
3485
  server.tool("plan_migration", "Generate the **initial** migration plan and (when `project_root` is provided) write it to <project_root>/MIGRATION.md. **This is the only time the MCP writes that file.** From here, you own it: tick checkboxes as you finish work, log custom-data decisions, scan the old source for atomic components (Button, Input, Card, etc.) that theme.json doesn't see, and append them to MIGRATION.md yourself. theme.json is incomplete by design — the MCP can only describe what's listed there. Pass `theme_json_path` for large themes (raw `theme_json` string is supported for backward compat but fails on real-world sizes).", {
2929
- theme_json: z.string().optional().describe("Raw JSON content of the old theme.json. EITHER this OR theme_json_path is required (not both). For real themes use theme_json_path — raw strings exceed tool/context limits at production sizes."),
2930
- theme_json_path: z.string().optional().describe("Absolute path to the old theme.json file on disk. Preferred for any real-world theme."),
2931
- project_name: z.string().optional().describe("Target new project name, used to prefix migration-tracking IDs (default: 'my-theme')"),
2932
- old_source_dir: z.string().optional().describe("Absolute path to the old project's src/ directory. When provided, the tool scans .tsx files to detect shared sub-components used across 3+ components. This scan is partial — atomic components used by only 1-2 sections will be missed and must be added by the LLM."),
2933
- project_root: z.string().optional().describe("Absolute path to the new project root. When provided, the MCP writes MIGRATION.md to <project_root>/MIGRATION.md and returns a short summary instead of the full markdown body."),
2934
- overwrite: z.boolean().optional().describe("If MIGRATION.md already exists at <project_root>/MIGRATION.md and is non-empty, refuse the write unless this is true. Default: false."),
2935
- }, async ({ theme_json, theme_json_path, project_name, old_source_dir, project_root, overwrite }) => {
3486
+ theme_json: z
3487
+ .string()
3488
+ .optional()
3489
+ .describe("Raw JSON content of the old theme.json. EITHER this OR theme_json_path is required (not both). For real themes use theme_json_path — raw strings exceed tool/context limits at production sizes."),
3490
+ theme_json_path: z
3491
+ .string()
3492
+ .optional()
3493
+ .describe("Absolute path to the old theme.json file on disk. Preferred for any real-world theme."),
3494
+ project_name: z
3495
+ .string()
3496
+ .optional()
3497
+ .describe("Target new project name, used to prefix migration-tracking IDs (default: 'my-theme')"),
3498
+ old_source_dir: z
3499
+ .string()
3500
+ .optional()
3501
+ .describe("Absolute path to the old project's src/ directory. When provided, the tool scans .tsx files to detect shared sub-components used across 3+ components. This scan is partial — atomic components used by only 1-2 sections will be missed and must be added by the LLM."),
3502
+ project_root: z
3503
+ .string()
3504
+ .optional()
3505
+ .describe("Absolute path to the new project root. When provided, the MCP writes MIGRATION.md to <project_root>/MIGRATION.md and returns a short summary instead of the full markdown body."),
3506
+ overwrite: z
3507
+ .boolean()
3508
+ .optional()
3509
+ .describe("If MIGRATION.md already exists at <project_root>/MIGRATION.md and is non-empty, refuse the write unless this is true. Default: false."),
3510
+ }, async ({ theme_json, theme_json_path, project_name, old_source_dir, project_root, overwrite, }) => {
2936
3511
  try {
2937
3512
  const parsed = resolveThemeJson(theme_json, theme_json_path);
2938
3513
  const projectName = project_name || "my-theme";
@@ -2993,18 +3568,37 @@ server.tool("plan_migration", "Generate the **initial** migration plan and (when
2993
3568
  }
2994
3569
  catch (err) {
2995
3570
  return {
2996
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
3571
+ content: [
3572
+ {
3573
+ type: "text",
3574
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
3575
+ },
3576
+ ],
2997
3577
  };
2998
3578
  }
2999
3579
  });
3000
3580
  // Tool: get_section_migration_plan
3001
3581
  server.tool("get_section_migration_plan", "Returns concrete CLI commands and prop conversions for one section. For each prop that references a customData type, you'll see a 'Decide: enum or component?' callout — log your decision in MIGRATION.md under `## Custom Data Decisions`. Pass `theme_json_path` for large themes.", {
3002
- theme_json: z.string().optional().describe("Raw JSON content of the old theme.json. EITHER this OR theme_json_path is required (not both)."),
3003
- theme_json_path: z.string().optional().describe("Absolute path to the old theme.json file on disk. Preferred for any real-world theme."),
3004
- section_name: z.string().describe("Old component name (e.g. 'Navbar', 'ProductGrid') or dir name, OR the new section ID (e.g. 'my-theme-navbar')"),
3005
- project_name: z.string().optional().describe("Target new project name (must match what was used in plan_migration). Default: 'my-theme'"),
3006
- old_source_dir: z.string().optional().describe("Absolute path to old src/ directory (used to output exact source file paths to read)"),
3007
- }, async ({ theme_json, theme_json_path, section_name, project_name, old_source_dir }) => {
3582
+ theme_json: z
3583
+ .string()
3584
+ .optional()
3585
+ .describe("Raw JSON content of the old theme.json. EITHER this OR theme_json_path is required (not both)."),
3586
+ theme_json_path: z
3587
+ .string()
3588
+ .optional()
3589
+ .describe("Absolute path to the old theme.json file on disk. Preferred for any real-world theme."),
3590
+ section_name: z
3591
+ .string()
3592
+ .describe("Old component name (e.g. 'Navbar', 'ProductGrid') or dir name, OR the new section ID (e.g. 'my-theme-navbar')"),
3593
+ project_name: z
3594
+ .string()
3595
+ .optional()
3596
+ .describe("Target new project name (must match what was used in plan_migration). Default: 'my-theme'"),
3597
+ old_source_dir: z
3598
+ .string()
3599
+ .optional()
3600
+ .describe("Absolute path to old src/ directory (used to output exact source file paths to read)"),
3601
+ }, async ({ theme_json, theme_json_path, section_name, project_name, old_source_dir, }) => {
3008
3602
  try {
3009
3603
  const parsed = resolveThemeJson(theme_json, theme_json_path);
3010
3604
  const projectName = project_name || "my-theme";
@@ -3013,7 +3607,12 @@ server.tool("get_section_migration_plan", "Returns concrete CLI commands and pro
3013
3607
  }
3014
3608
  catch (err) {
3015
3609
  return {
3016
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
3610
+ content: [
3611
+ {
3612
+ type: "text",
3613
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
3614
+ },
3615
+ ],
3017
3616
  };
3018
3617
  }
3019
3618
  });
@@ -3043,13 +3642,22 @@ function resolveIkasComponentBinary(projectRoot) {
3043
3642
  async function runIkasComponentCli(projectRoot, args) {
3044
3643
  const bin = resolveIkasComponentBinary(projectRoot);
3045
3644
  return new Promise((resolve) => {
3046
- execFile(bin, args, { cwd: projectRoot, windowsHide: true }, (err, stdout, stderr) => {
3645
+ execFile(bin, args,
3646
+ // Large editor responses (e.g. list_categories on a big store, or
3647
+ // add_sections_to_page echoing many sections) easily exceed Node's default
3648
+ // 1MB stdout buffer, which truncates output mid-JSON and yields a
3649
+ // "no parseable JSON" error. Give it generous headroom.
3650
+ { cwd: projectRoot, windowsHide: true, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
3047
3651
  const exitCode = err && typeof err.code === "number"
3048
3652
  ? err.code
3049
3653
  : err
3050
3654
  ? 1
3051
3655
  : 0;
3052
- resolve({ stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "", exitCode });
3656
+ resolve({
3657
+ stdout: stdout?.toString() ?? "",
3658
+ stderr: stderr?.toString() ?? "",
3659
+ exitCode,
3660
+ });
3053
3661
  });
3054
3662
  });
3055
3663
  }
@@ -3057,24 +3665,68 @@ function parseCliJson(stdout) {
3057
3665
  const trimmed = stdout.trim();
3058
3666
  if (!trimmed)
3059
3667
  return null;
3060
- // CLI prints exactly one JSON object on stdout; if multiple lines appeared
3061
- // (e.g., warnings on stderr leaked), take the last non-empty line.
3062
- const last = trimmed.split("\n").map(l => l.trim()).filter(Boolean).pop();
3063
- if (!last)
3064
- return null;
3668
+ // Fast path: the CLI prints exactly one JSON object on stdout.
3065
3669
  try {
3066
- return JSON.parse(last);
3670
+ return JSON.parse(trimmed);
3067
3671
  }
3068
3672
  catch {
3673
+ // Fallback: if anything leaked onto stdout before/after the JSON, scan the
3674
+ // lines and return the last one that parses as JSON.
3675
+ const lines = trimmed
3676
+ .split("\n")
3677
+ .map((l) => l.trim())
3678
+ .filter(Boolean);
3679
+ for (let i = lines.length - 1; i >= 0; i--) {
3680
+ try {
3681
+ return JSON.parse(lines[i]);
3682
+ }
3683
+ catch {
3684
+ // keep scanning
3685
+ }
3686
+ }
3069
3687
  return null;
3070
3688
  }
3071
3689
  }
3072
- async function callEditorAction(projectRoot, args) {
3073
- try {
3074
- const { stdout, stderr, exitCode } = await runIkasComponentCli(projectRoot, args);
3075
- const parsed = parseCliJson(stdout);
3076
- if (parsed) {
3077
- return { content: [{ type: "text", text: JSON.stringify(parsed, null, 2) }] };
3690
+ // Coerce a JSON-ARRAY argument (points / settings / colors) into the single JSON-array string the
3691
+ // CLI expects. Agents sometimes send these PRE-STRINGIFIED (a JSON string instead of a real array);
3692
+ // a blind JSON.stringify would then double-encode it ("[...]" -> "\"[...]\"") and the CLI rejects it
3693
+ // with "must be a JSON array". So pass a string through as-is (the CLI parses + validates it) and
3694
+ // only stringify real arrays/values. NOTE: only for array args — a scalar `value` arg must NOT use
3695
+ // this (a plain string there is a literal value, not stringified JSON).
3696
+ function toJsonArrayArg(value) {
3697
+ return typeof value === "string" ? value : JSON.stringify(value ?? []);
3698
+ }
3699
+ /**
3700
+ * The `confirm` parameter shared by the destructive editor tools.
3701
+ *
3702
+ * Spelled out at length on purpose: a one-word "confirmation" flag reads to a model as a
3703
+ * formality to fill in, and the whole point is that it stands for a human's answer.
3704
+ */
3705
+ const CONFIRM_PARAM_DESCRIPTION = "Must be `true`, and only after the USER has explicitly agreed to this specific deletion. It stands for their consent, not for your own confidence \u2014 never set it to clear up something you merely believe is unused, and never re-run with it after a refusal without asking first. The merchant's content goes with the deletion and only the editor's undo stack can bring it back.";
3706
+ /** Reply for a destructive tool called without consent. The dev-server action refuses too. */
3707
+ function destructiveConfirmRefusal() {
3708
+ return {
3709
+ content: [
3710
+ {
3711
+ type: "text",
3712
+ text: JSON.stringify({
3713
+ success: false,
3714
+ error: "Refused: `confirm` was not true. This deletes the merchant's content and can only be undone from the editor's undo stack. Ask the user whether to proceed, and pass confirm: true only after they agree.",
3715
+ }, null, 2),
3716
+ },
3717
+ ],
3718
+ };
3719
+ }
3720
+ async function callEditorAction(projectRoot, args) {
3721
+ try {
3722
+ const { stdout, stderr, exitCode } = await runIkasComponentCli(projectRoot, args);
3723
+ const parsed = parseCliJson(stdout);
3724
+ if (parsed) {
3725
+ return {
3726
+ content: [
3727
+ { type: "text", text: JSON.stringify(parsed, null, 2) },
3728
+ ],
3729
+ };
3078
3730
  }
3079
3731
  return {
3080
3732
  content: [
@@ -3097,38 +3749,77 @@ async function callEditorAction(projectRoot, args) {
3097
3749
  };
3098
3750
  }
3099
3751
  }
3752
+ //
3100
3753
  // Tool: list_editor_pages
3101
- server.tool("list_editor_pages", "List pages in the connected editor's project. Returns id, name, pageType, slug for each page. Requires `ikas-component dev` to be running with the editor connected. Use the returned `id`s as the `pageId` argument to `add_section_to_page`.", {
3102
- project_root: z.string().describe("Absolute path to the code-component project (where `node_modules/.bin/ikas-component` lives)."),
3103
- port: z.number().optional().describe("Dev server WebSocket port (default 5201)."),
3754
+ server.tool("list_editor_pages", "List pages in the connected editor's project. Returns id, name, pageType, slug for each page. Requires `ikas theme dev` to be running with the editor connected. Use the returned `id`s as the `pageId` argument to `add_section_to_page`.", {
3755
+ project_root: z
3756
+ .string()
3757
+ .describe("Absolute path to the code-component project (where `node_modules/.bin/ikas-component` lives)."),
3758
+ port: z
3759
+ .number()
3760
+ .optional()
3761
+ .describe("Dev server WebSocket port (default 5201)."),
3104
3762
  }, async ({ project_root, port }) => {
3105
3763
  const args = ["list-pages", ...(port ? ["--port", String(port)] : [])];
3106
3764
  return callEditorAction(project_root, args);
3107
3765
  });
3108
3766
  // Tool: list_imported_sections
3109
- server.tool("list_imported_sections", "List section-type code components already imported into the editor's project (theme.codeComponents, filtered to type=section). Use to confirm a component is ready to be placed on a page. The component must be built (`ikas-component build`/`dev`) and imported (`import_section`) before it can be added to a page. The returned `id` is the editor's id for the imported component — normally identical to the id in `ikas.config.json`, but it can differ if the dev component was deleted and re-scaffolded after a previous import. Always use the `id` from this tool, not from `ikas.config.json`, when calling `add_section_to_page`.", {
3110
- project_root: z.string().describe("Absolute path to the code-component project."),
3111
- port: z.number().optional().describe("Dev server WebSocket port (default 5201)."),
3767
+ server.tool("list_imported_sections", "List section-type code components already imported into the editor's project (theme.codeComponents, filtered to type=section). Use to confirm a component is ready to be placed on a page. The component must be built (`ikas-component build`/`dev`) and imported (`import_section`) before it can be added to a page. The returned `id` is the editor's id for the imported component — normally identical to the id in `ikas.config.json`, but it can differ if the dev component was deleted and re-scaffolded after a previous import, or when the theme installed this project as a design asset (the editor then reports the published id). Always use the `id` from this tool, not from `ikas.config.json`, when calling `add_section_to_page`. A differing id is NEVER a reason to edit `ikas.config.json` — config ids are immutable.", {
3768
+ project_root: z
3769
+ .string()
3770
+ .describe("Absolute path to the code-component project."),
3771
+ port: z
3772
+ .number()
3773
+ .optional()
3774
+ .describe("Dev server WebSocket port (default 5201)."),
3112
3775
  }, async ({ project_root, port }) => {
3113
- const args = ["list-imported", "--sections-only", ...(port ? ["--port", String(port)] : [])];
3776
+ const args = [
3777
+ "list-imported",
3778
+ "--sections-only",
3779
+ ...(port ? ["--port", String(port)] : []),
3780
+ ];
3114
3781
  return callEditorAction(project_root, args);
3115
3782
  });
3116
3783
  // Tool: import_section
3117
3784
  server.tool("import_section", "Import a built section-type code component into the editor's project. This copies the compiled JS/CSS/props into `theme.codeComponents` and auto-creates the wrapper section needed to place it on a page. Idempotent: re-running updates the existing entry in place. Required before `add_section_to_page`. The component must have been built (`ikas-component build`/`dev`).", {
3118
- project_root: z.string().describe("Absolute path to the code-component project."),
3119
- component_id: z.string().describe("Component id from `ikas.config.json` (strict — no name resolution)."),
3120
- port: z.number().optional().describe("Dev server WebSocket port (default 5201)."),
3785
+ project_root: z
3786
+ .string()
3787
+ .describe("Absolute path to the code-component project."),
3788
+ component_id: z
3789
+ .string()
3790
+ .describe("Component id from `ikas.config.json` (strict — no name resolution)."),
3791
+ port: z
3792
+ .number()
3793
+ .optional()
3794
+ .describe("Dev server WebSocket port (default 5201)."),
3121
3795
  }, async ({ project_root, component_id, port }) => {
3122
- const args = ["import", "--id", component_id, ...(port ? ["--port", String(port)] : [])];
3796
+ const args = [
3797
+ "import",
3798
+ "--id",
3799
+ component_id,
3800
+ ...(port ? ["--port", String(port)] : []),
3801
+ ];
3123
3802
  return callEditorAction(project_root, args);
3124
3803
  });
3125
3804
  // Tool: add_section_to_page
3126
- server.tool("add_section_to_page", "Place an already-imported section-type code component on a page in the editor. Equivalent to right-clicking the section in the dev-components panel and choosing \"Add to Page\". Errors if the component is not imported, is not section-type, or the page id is unknown. Use `list_editor_pages` to discover page ids and `list_imported_sections` to discover component ids.", {
3127
- project_root: z.string().describe("Absolute path to the code-component project."),
3128
- component_id: z.string().describe("Imported code component id from `list_imported_sections` — NOT the id in `ikas.config.json` (the two are usually the same but can diverge after a rescaffold)."),
3805
+ server.tool("add_section_to_page", "Place a SINGLE already-imported section-type code component on a page. Use this ONLY when adding exactly one section. If you are adding more than one section — or building/populating a page — call `add_sections_to_page` instead: it places them all AND fills their props in ONE call. Calling this tool repeatedly (one section per call) is the slow path and should be avoided. Equivalent to right-clicking the section in the dev-components panel and choosing \"Add to Page\". Errors if the component is not imported, is not section-type, or the page id is unknown. Use `list_editor_pages` to discover page ids and `list_imported_sections` to discover component ids. After placing, change the section's prop values with `update_section_prop` / `update_page_sections` (use `list_page_sections` to get the placement's `elementId` and prop names).", {
3806
+ project_root: z
3807
+ .string()
3808
+ .describe("Absolute path to the code-component project."),
3809
+ component_id: z
3810
+ .string()
3811
+ .describe("Imported code component id from `list_imported_sections` — NOT the id in `ikas.config.json` (the two are usually the same but can diverge after a rescaffold or on a theme that installed the project as a design asset; never edit the config to make them match)."),
3129
3812
  page_id: z.string().describe("Target page id (from `list_editor_pages`)."),
3130
- index: z.number().int().nonnegative().optional().describe("Zero-based insertion index in the page; appends when omitted."),
3131
- port: z.number().optional().describe("Dev server WebSocket port (default 5201)."),
3813
+ index: z
3814
+ .number()
3815
+ .int()
3816
+ .nonnegative()
3817
+ .optional()
3818
+ .describe("Zero-based insertion index in the page; appends when omitted."),
3819
+ port: z
3820
+ .number()
3821
+ .optional()
3822
+ .describe("Dev server WebSocket port (default 5201)."),
3132
3823
  }, async ({ project_root, component_id, page_id, index, port }) => {
3133
3824
  const args = [
3134
3825
  "add-to-page",
@@ -3141,8 +3832,1638 @@ server.tool("add_section_to_page", "Place an already-imported section-type code
3141
3832
  ];
3142
3833
  return callEditorAction(project_root, args);
3143
3834
  });
3144
- // --- Start server ---
3835
+ // Tool: add_sections_to_page
3836
+ server.tool("add_sections_to_page", "Place MANY sections on a page in a SINGLE call — and optionally set each section's prop values AT placement time, so you skip the separate fill step. The fastest way to build a page: one round-trip instead of one add (and one fill) per section. Pass `sections`, each `{ component_id, index?, updates?: [{ prop_name|prop_id, value }] }`; values use the same per-type shapes as update_section_prop / get_editor_workflow. Returns the new `elementId` for each placement (plus written prop results). Built-but-unimported section AND child code components are auto-imported. All update values are validated before anything is placed. Use `list_editor_pages` for page ids and `list_imported_sections` for component ids. Placing a COMMON (global) section — the theme's header/footer — is special: it has ONE shared set of prop values stored on the INDEX (Home) page's placement, so `updates` land there and change that section on every page (the result carries a `common` block), and placing it with `updates` on a non-INDEX page while the INDEX page does not have it is rejected — place and fill it on the INDEX page instead.", {
3837
+ project_root: z
3838
+ .string()
3839
+ .describe("Absolute path to the code-component project."),
3840
+ page_id: z.string().describe("Target page id (from `list_editor_pages`)."),
3841
+ sections: z
3842
+ .array(z.strictObject({
3843
+ component_id: z
3844
+ .string()
3845
+ .describe("Imported (or built) section-type code component id."),
3846
+ index: z
3847
+ .number()
3848
+ .int()
3849
+ .nonnegative()
3850
+ .optional()
3851
+ .describe("Zero-based insertion index; appends when omitted."),
3852
+ updates: z
3853
+ .array(z.strictObject({
3854
+ prop_id: z
3855
+ .string()
3856
+ .optional()
3857
+ .describe("Blueprint prop id (provide this or prop_name)."),
3858
+ prop_name: z
3859
+ .string()
3860
+ .optional()
3861
+ .describe("Blueprint prop name (alternative to prop_id)."),
3862
+ value: z
3863
+ .any()
3864
+ .describe("Prop value, same shape update_section_prop expects for that type."),
3865
+ }))
3866
+ .optional()
3867
+ .describe("Optional prop values to set on this section right after placing it."),
3868
+ }))
3869
+ .describe("Non-empty array of sections to place (in order), each with its componentId and optional prop updates."),
3870
+ port: z
3871
+ .number()
3872
+ .optional()
3873
+ .describe("Dev server WebSocket port (default 5201)."),
3874
+ }, async ({ project_root, page_id, sections, port }) => {
3875
+ const normalized = (sections || []).map((s) => ({
3876
+ componentId: s.component_id,
3877
+ ...(typeof s.index === "number" ? { index: s.index } : {}),
3878
+ ...(s.updates
3879
+ ? {
3880
+ updates: s.updates.map((u) => ({
3881
+ ...(u.prop_id ? { propId: u.prop_id } : {}),
3882
+ ...(u.prop_name ? { propName: u.prop_name } : {}),
3883
+ value: u.value,
3884
+ })),
3885
+ }
3886
+ : {}),
3887
+ }));
3888
+ const args = [
3889
+ "add-sections-to-page",
3890
+ "--page-id",
3891
+ page_id,
3892
+ "--sections",
3893
+ JSON.stringify(normalized),
3894
+ ...(port ? ["--port", String(port)] : []),
3895
+ ];
3896
+ return callEditorAction(project_root, args);
3897
+ });
3898
+ // Tool: list_page_sections
3899
+ server.tool("list_page_sections", "List the sections placed on a page — a LEAN ROSTER that never truncates: per-placement `elementId` (the identity of THIS placement — there can be multiple of the same section), `sectionId`, `componentId`, `name`, `propCount`, and `setPropNames` (which props already have a value). It deliberately omits the prop SCHEMA and the prop VALUES (both can be large — Header alone can have ~80 props). To get a section's prop schema (types, ENUM options, allowed children) call `get_component_props(componentId)`; to read its current values call `get_section_values(element_id)`. Use the returned `elementId` with `update_section_prop` / `update_page_sections`. Use `list_editor_pages` for page ids. COMMON (global) sections — the theme's header and footer — carry an extra `common` field (`isCommon`, `commonSectionType`, `canonicalPageId`/`canonicalElementId`, `valuesArePageSpecific: false`): their prop values are NOT page-specific, they are shared by every page and stored on the INDEX (Home) page's placement, so `setPropNames` for them reflects that one shared record and any write from any page changes the header/footer everywhere. A page customized per storefront-routing/specification holds a SEPARATE set of placements with its own section order in each state: this lists the BASE layer by default and reports the available states in `pageStates` (plus a `scope` field) — pass `sf_routing_id`/`specification_id` to list a state's own placements instead, which is what `move_page_section` needs when reordering that state.", {
3900
+ project_root: z
3901
+ .string()
3902
+ .describe("Absolute path to the code-component project."),
3903
+ page_id: z.string().describe("Target page id (from `list_editor_pages`)."),
3904
+ sf_routing_id: z
3905
+ .string()
3906
+ .optional()
3907
+ .describe("List a routing-customized state of the page instead of the base layer. Ids come from the `pageStates` block this tool returns for a customized page."),
3908
+ specification_id: z
3909
+ .string()
3910
+ .optional()
3911
+ .describe("Specification of the customized state to list (used together with `sf_routing_id`)."),
3912
+ port: z
3913
+ .number()
3914
+ .optional()
3915
+ .describe("Dev server WebSocket port (default 5201)."),
3916
+ }, async ({ project_root, page_id, sf_routing_id, specification_id, port }) => {
3917
+ const args = [
3918
+ "list-page-sections",
3919
+ "--page-id",
3920
+ page_id,
3921
+ ...(sf_routing_id ? ["--sf-routing-id", sf_routing_id] : []),
3922
+ ...(specification_id ? ["--specification-id", specification_id] : []),
3923
+ ...(port ? ["--port", String(port)] : []),
3924
+ ];
3925
+ return callEditorAction(project_root, args);
3926
+ });
3927
+ // Tool: move_page_section
3928
+ server.tool("move_page_section", "Reorder a section that is ALREADY placed on a page — the only way to change section order, since the editor UI offers it solely as a drag in the layers tree. Target the placement by its `element_id` from `list_page_sections` (NOT the sectionId/componentId — a page can hold several placements of the same section and each moves independently). Give EITHER `direction` (\"up\"/\"down\", one position — use this for a simple nudge) OR `to_index` (absolute 0-based position), never both. Indices are 0-based and count ONLY placed sections, in exactly the order `list_page_sections` returns them, so you can read that list, pick a target position from it, and pass it straight back. The result returns `fromIndex`, `resultIndex` (where the section ACTUALLY ended up) and `sections` (the full resulting order) — assert on `resultIndex`/`sections` rather than assuming the move landed where you asked; if it lands somewhere other than requested a `note` says so. A reorder that does not take effect comes back as an ERROR, never as a success that changed nothing, so a successful result means the section really moved. Out-of-range indices are rejected with the valid range (and the section's current index) instead of being clamped. Passing a `sectionId`/`componentId` where an `element_id` belongs is detected and the error names the elementId you actually wanted. COMMON (global) sections — the theme's header and footer — are REJECTED: their position is fixed by the theme, so there is nothing to reorder. SCOPE: by default this reorders the page's BASE layer. A page customized per storefront-routing/specification keeps a SEPARATE set of placements and its own section order in each of those states — pass `sf_routing_id` (and `specification_id`) to reorder one of them instead, and read that state's current order with `list_page_sections` using the SAME ids. Whenever the page has any state the result carries `scope`, `pageStates` and `pageStatesNote`: do not report a reorder as verified on such a page without checking them, since reordering the base layer leaves every state exactly as it was. The state must ALREADY exist — creating one duplicates the whole page and is a deliberate editor action, so an unknown routing/specification is rejected with the list of existing states rather than created. To place a NEW section at a specific position use `add_sections_to_page` with its `index` instead; this tool only moves existing placements.", {
3929
+ project_root: z
3930
+ .string()
3931
+ .describe("Absolute path to the code-component project."),
3932
+ page_id: z.string().describe("Target page id (from `list_editor_pages`)."),
3933
+ element_id: z
3934
+ .string()
3935
+ .describe("Placed-section elementId to move (from `list_page_sections`)."),
3936
+ direction: z
3937
+ .enum(["up", "down"])
3938
+ .optional()
3939
+ .describe("Move one position up or down. Provide this or `to_index`, not both."),
3940
+ to_index: z
3941
+ .number()
3942
+ .int()
3943
+ .min(0)
3944
+ .optional()
3945
+ .describe("Absolute 0-based target position among the page's placed sections. Provide this or `direction`, not both."),
3946
+ sf_routing_id: z
3947
+ .string()
3948
+ .optional()
3949
+ .describe("Reorder a routing-customized state of the page instead of the base layer. Ids come from the `pageStates` block returned by `list_page_sections`. The state must already exist."),
3950
+ specification_id: z
3951
+ .string()
3952
+ .optional()
3953
+ .describe("Specification of the customized state to reorder (used together with `sf_routing_id`)."),
3954
+ port: z
3955
+ .number()
3956
+ .optional()
3957
+ .describe("Dev server WebSocket port (default 5201)."),
3958
+ }, async ({ project_root, page_id, element_id, direction, to_index, sf_routing_id, specification_id, port, }) => {
3959
+ const args = [
3960
+ "move-page-section",
3961
+ "--page-id",
3962
+ page_id,
3963
+ "--element-id",
3964
+ element_id,
3965
+ ...(direction ? ["--direction", direction] : []),
3966
+ ...(to_index !== undefined ? ["--to-index", String(to_index)] : []),
3967
+ ...(sf_routing_id ? ["--sf-routing-id", sf_routing_id] : []),
3968
+ ...(specification_id ? ["--specification-id", specification_id] : []),
3969
+ ...(port ? ["--port", String(port)] : []),
3970
+ ];
3971
+ return callEditorAction(project_root, args);
3972
+ });
3973
+ // Tool: get_component_props
3974
+ server.tool("get_component_props", "Get prop blueprints straight from the editor (the source of truth) for one or MANY components in a single call — for any section OR child code component ids. Returns `{ components: [...] }`, each prop carrying its `id`, `name`, `type`, `required`, `default`, and crucially: a ready-to-use `writeExample` (the EXACT value shape to pass to update_section_prop / update_page_sections — e.g. PRODUCT_LIST, BLOG_LIST, COMPONENT_LIST, LINK) plus a `writeNote` for variants, so you do NOT have to guess or trial-write the JSON; for ENUM props the `options` (valid `value`s); and for COMPONENT/COMPONENT_LIST props the `allowedComponentIds` (which children the slot permits — when empty, an `allowedComponentsNote` says any imported code component is allowed). Use this (its `writeExample`/`options`/`allowedComponentIds`) instead of guessing or reading ikas.config.json. Pass ALL the section/child ids you need at once (batch). Child component ids come from a parent prop's `allowedComponentIds` (or get_section_template).", {
3975
+ project_root: z
3976
+ .string()
3977
+ .describe("Absolute path to the code-component project."),
3978
+ component_ids: z
3979
+ .array(z.string())
3980
+ .describe("Section/child code-component ids to resolve (batch). From list_imported_sections or a COMPONENT_LIST prop's allowedComponentIds."),
3981
+ port: z
3982
+ .number()
3983
+ .optional()
3984
+ .describe("Dev server WebSocket port (default 5201)."),
3985
+ }, async ({ project_root, component_ids, port }) => {
3986
+ const args = [
3987
+ "get-component-props",
3988
+ "--component-ids",
3989
+ (component_ids || []).join(","),
3990
+ ...(port ? ["--port", String(port)] : []),
3991
+ ];
3992
+ return callEditorAction(project_root, args);
3993
+ });
3994
+ // Tool: get_section_values
3995
+ server.tool("get_section_values", "Get the CURRENT prop values of one or MANY placed sections (each with its full `propValues` plus blueprint `props` — every prop carrying a `writeExample`/`writeNote` for the exact value shape, plus ENUM `options` and COMPONENT_LIST `allowedComponentIds`). `list_page_sections` is lean and omits values to avoid truncation; use this to read sections' values — needed for read-modify-write of a COMPONENT_LIST, or to inspect the exact stored shape of an existing value. Returns `{ sections: [...] }`. Pass all the elementIds you need at once (batch). COMMON (global) sections — the theme's header and footer — keep ONE shared set of prop values for the whole theme, stored on the INDEX (Home) page's placement; for those this tool reads the values FROM that canonical placement (a non-INDEX placement stores nothing of its own) and returns a `common` block naming `canonicalPageId`/`canonicalElementId`. So the values you get for a header/footer are the live ones the page actually renders no matter which page_id you ask from — do NOT read defaults as \"empty\" and blind-fill them, and remember any write goes to that same shared record and changes all pages. A prop bound to a theme GLOBAL variable stores no value in `propValues` — it is listed in the section's `bindings` map instead (`{ \"<propName>\": { boundGlobal: \"_<id>\", displayName, type } }`); treat such a prop as SET, not empty, and do not overwrite it with a static value unless asked (a static write removes the binding).", {
3996
+ project_root: z
3997
+ .string()
3998
+ .describe("Absolute path to the code-component project."),
3999
+ page_id: z.string().describe("Target page id (from `list_editor_pages`)."),
4000
+ element_ids: z
4001
+ .array(z.string())
4002
+ .describe("Placed-section elementIds to read (batch). From `list_page_sections`."),
4003
+ locale: z
4004
+ .string()
4005
+ .optional()
4006
+ .describe("A store language (e.g. `en`): the values as that language shows them on these placements (its own value, else the section's translation, else the base value). Read before `update_section_prop` with `locale`. When the result lists several `routings`, they may differ: read and write one with `routing`."),
4007
+ routing: z
4008
+ .string()
4009
+ .optional()
4010
+ .describe("One routing of the store, by path (e.g. `/test2`) or id: as `locale`, for that routing alone. A language several routings show (`/en`, `/test2`) gives each its own values, link labels included; `locale` reads the first and writes all of them."),
4011
+ port: z
4012
+ .number()
4013
+ .optional()
4014
+ .describe("Dev server WebSocket port (default 5201)."),
4015
+ }, async ({ project_root, page_id, element_ids, locale, routing, port }) => {
4016
+ const args = [
4017
+ "get-section-values",
4018
+ "--page-id",
4019
+ page_id,
4020
+ "--element-ids",
4021
+ (element_ids || []).join(","),
4022
+ ...(locale ? ["--locale", locale] : []),
4023
+ ...(routing ? ["--routing", routing] : []),
4024
+ ...(port ? ["--port", String(port)] : []),
4025
+ ];
4026
+ return callEditorAction(project_root, args);
4027
+ });
4028
+ // Tool: update_section_prop
4029
+ server.tool("update_section_prop", 'Change a single prop value of a section placed on a page. This is the tool for FILLING/SETTING content (heading, text, image, link, etc.) on an existing section — it is pure data entry: it writes NO component code and needs NO rebuild. Do not author a new prop or component to set a value the section already supports; first check the section\'s existing `props` via `list_page_sections`. Target the specific placement by its `element_id` (from `list_page_sections`) and the prop by `prop_id` or `prop_name` (also from `list_page_sections`). `value` is the prop value object as stored by the editor — for scalar props it is wrapped as `{ "value": <scalar> }` (e.g. `{ "value": "Hello" }` for TEXT, `{ "value": true }` for BOOLEAN, `{ "value": 12 }` for NUMBER, `{ "value": "#FF0000" }` for COLOR, `{ "value": "<enum-key>" }` for ENUM). A COLOR prop can ALSO bind to a global theme color instead of a literal hex — pass `{ "patternValueId": "<id>" }` (the color id from `list_theme_globals` → `colors[].id`) and the prop tracks that global color live (resolved to `var(--<id>)` at render); the id is validated and an unknown one is REJECTED. Richer object prop types use their own object shape and are NOT `{ "value": ... }`-wrapped (full catalog in `get_editor_workflow`): IMAGE = `{ "id": "<asset-id>", "altText"?: "<alt>", "isVideo"?: false }` (the `id` MUST reference an already-uploaded asset — call `upload_image` with a `file_path`/`image_url` to get one, or reuse an existing `id` from another section\'s `propValues`); IMAGE_LIST = `{ "images": [ <image>, ... ] }`; VIDEO = `{ "video": { "id": "<asset-id>" }, "thumbnailImage"?: { "id": "..." }, "autoplay"?: false, "controls"?: true, "loop"?: false, "muted"?: false }` (NOT a bare `{ "id": ... }`); SVG = `{ "value": "<svg markup>" }` (value-wrapped, like a scalar); SVG_LIST = `{ "svgs": [ "<svg>", ... ] }`; TYPE (style props such as BorderRadiusStyleType/PaddingStyleType/GapStyleType) = the type-shaped object ITSELF, e.g. `{ "value": 8, "unit": "px" }` — get the exact field structure from the prop\'s `writeExample`/`typeName` in `get_component_props` or `get_type_definition("<typeName>")`; unknown fields, wrong field types, and invalid union values (e.g. `"unit": "banana"`) are REJECTED; entity props PRODUCT/CATEGORY/BRAND/BLOG/BLOG_CATEGORY/RAFFLE = `{ "<entity>Id": "...", "usePageData"?: false }` (e.g. `{ "categoryId": "..." }`) — get real ids from `search_products` (PRODUCT), `list_categories`, `list_brands`, `list_blogs`, `list_blog_categories`; PRODUCT_ATTRIBUTE = `{ "productId": "...", "variantId": "...", "attributeId": "..." }` — `variantId` is REQUIRED alongside `productId` (without it the value resolves with `product: null` and the component renders nothing), or bind to the page product with `{ "attributeId": "...", "usePageData": true }` on a product detail page; PRODUCT_ATTRIBUTE_LIST = the same with `"attributeIds": [ "..." ]`, and note the component receives a SINGLE wrapper object, never an array (read both with `getAttributeDetailValues()` / `getAttributeListValues()` — see `get_framework_guide("prop-types")`); list/collection props are typed objects keyed by a `<entity>ListType` discriminator: PRODUCT_LIST = `{ "id": "<unique>", "productListType": "STATIC", "productIds": [ { "productId": "...", "variantId": "..." } ], "initialLimit"?: 12 }` — note productIds is an array of {productId, variantId} PAIRS (from search_products), not bare ids; productListType ∈ ALL|STATIC|DISCOUNTED|RECOMMENDED|CATEGORY|SEARCH|LAST_VIEWED|RELATED_PRODUCTS|VIEWED_TOGETHER|PURCHASED_TOGETHER, and for a dynamic type use e.g. `{ "id": "<unique>", "productListType": "CATEGORY", "category": "<id from list_categories>" }` (the field is `category`, NOT `categoryId` — `categoryId` is only the standalone CATEGORY entity prop; no productIds here) or `"ALL"` (no ids). Unknown sub-fields inside a PRODUCT_LIST (e.g. `categoryId`) are REJECTED, not silently stored. CATEGORY_LIST = `{ "categoryListType": "STATIC", "categoryIds": ["..."] }` or `{ "categoryListType": "ALL" }`. BRAND_LIST = `{ "brandListType": "STATIC", "brandIds": ["..."] }` or ALL. BLOG_LIST = `{ "blogListType": "STATIC", "blogIds": ["..."] }`, `{ "blogListType": "CATEGORY", "categoryId": "..." }`, or ALL. BLOG_CATEGORY_LIST = `{ "blogCategoryListType": "STATIC", "blogCategoryIds": ["..."] }` or ALL. (Get the entity ids from search_products / list_*; you can also read an existing value with `get_section_values` to copy its exact shape.) LINK = a single link object `{ "id": "<unique-short-id>", "linkType": "PAGE"|"EXTERNAL"|"FILE", "label": "...", "openInNewTab"?: false, "subLinks": [] }` plus the target for its type — for PAGE add `"pageId"` AND `"pageType"` (both from `list_editor_pages`, e.g. pageType "INDEX"; for dynamic page types like PRODUCT/CATEGORY/BLOG also add the target `"itemId"`), for EXTERNAL add `"externalLink": "https://..."`. Examples: PAGE → `{ "id": "k3p9x", "linkType": "PAGE", "label": "Home", "pageId": "<page-id>", "pageType": "INDEX", "openInNewTab": false, "subLinks": [] }`; EXTERNAL → `{ "id": "m7q2z", "linkType": "EXTERNAL", "label": "Docs", "externalLink": "https://example.com", "openInNewTab": true, "subLinks": [] }`. To link to an ENTITY (category/brand/blog/blog-category) do NOT guess a slug — get the entity id from `list_categories`/`list_brands`/`list_blogs`/`list_blog_categories` and the page id from `get_page_by_type("<TYPE>")`, then build `{ "id": "<unique>", "linkType": "PAGE", "label": "...", "pageId": <pageId>, "pageType": "<TYPE>", "itemId": <entityId>, "subLinks": [] }`. LIST_OF_LINK = `{ "links": [ <link>, ... ] }` (each item is a link object as above). A link\'s label on the other routings is its `translations`, each routing showing its own `{ "locale", "label", "sfRoutingId" }`, else its language\'s `{ "locale", "label" }`, else `label`. Do NOT write these by hand: write the link with only its label changed using `locale` (every routing of that language) or `routing` (one routing), and the label becomes that translation, with no copy of the links (see below). A link sent without `translations` keeps its stored ones (matched by its `id`), so a link list can be resent with new links but without its labels; `"translations": null` drops them. Hand-written ones are REJECTED unless there is at most one per language and per routing and each `sfRoutingId` is a routing with a path whose language is the record\'s `locale`; the labels of a routing the store no longer has are dropped (the result\'s `removedRoutingLabels` names them). On a PRODUCT/CATEGORY/BRAND link with `itemId`, `"useItemNameTranslations": true` shows the item\'s own name in each language instead, its `translations` never showing; the name is fetched when the page renders, not stored (the result\'s `itemNamesNote` says so). A translatable value may hold `"pinned": true`: the editor\'s mark that it is this placement\'s own and stays so when its language\'s default text changes — send it back as read. PRODUCT = `{ "productId": "...", "variantId"?: "..." }`. This SAME unwrapped shape applies whether the prop sits at section level OR nested inside a COMPONENT_LIST entry\'s `propValues` — there is no section-vs-nested difference. IMPORTANT: pass `value` as the parsed JSON object/array itself, NEVER as a JSON string (a stringified value is double-encoded and stored as a useless string). Values are validated server-side (deeply, including nested COMPONENT_LIST children): wrong shapes AND wrong semantics are REJECTED with an explanatory error instead of being silently stored. This includes: a `{ "value": [...] }` wrapper for a COMPONENT_LIST; a `{ "value": ... }`-wrapped IMAGE; `props` instead of `propValues`; a missing/duplicate entry `id`; a child referenced by the wrong key (a code component MUST use `codeComponentId`, a theme component `componentId`) or by an id that does not exist (child ids are opaque — take them from `get_section_template` / `list_imported_sections`, never invent them); and any `propValues` key that is not a real prop of that child component (the error lists the valid prop names). Auto-import: a referenced child code component that has been BUILT but not yet imported into the theme is imported automatically before the value is set (the response lists any such ids under `autoImported`); only children that are not built at all fail with a "no imported code component" error — build them first (`ikas-component build`/`dev`). For any prop type you are unsure about, inspect the existing value with `get_section_values` and match its exact shape. The change is applied with undo support.\n\n' +
4030
+ "COMMON (global) sections — the theme's HEADER and FOOTER: these render on every page that carries a placement of them (ikas ready-made account/membership pages are born without one) and have ONE shared set of prop values, stored on the INDEX (Home) page's placement. Whichever page_id you write from, the value lands on that single record and changes the header/footer on ALL pages; the response carries a `common` block (`commonSectionType`, `canonicalPageId`, `canonicalElementId`) saying so, and the echoed `value` is read back from that canonical placement. Therefore: ALWAYS `get_section_values` first and change only the prop the user asked about — the props are already filled with the merchant's content even when you are on a page you have not inspected, so blind-filling \"empty-looking\" props overwrites the live header/footer everywhere. If the INDEX page has no placement of the section, there is no record to write to and the call fails telling you to add it to the INDEX page first.\n\n" +
4031
+ "ONE LANGUAGE OF THIS PLACEMENT (`locale`): with `locale` (a store language, e.g. `en`) the value is written for that language on THIS placement only, as the editor's canvas does with that language selected — the tool for a section that should read differently per page in a language (the translations page translates a section once, for every placement), and for a link's label in that language (a LINK / LIST_OF_LINK, or a link inside a COMPONENT_LIST entry): send the value as `get_section_values` with the same `locale` shows it, with ONLY labels changed, and they become that language's link translations (the links keep following the base). Any other change (a link's page, URL, order, a new link) gives that language its own copy of the links, which stops following the base. Without `locale` the base value is written: the base language's, and every other language's that has no value of its own (a translatable prop — TEXT, RICH_TEXT, IMAGE, IMAGE_LIST, VIDEO — shows the section's translation in that language first: update_translations). The base language itself takes no `locale` (refused). A prop bound to a global shows the binding in every language, so `locale` is refused for it. Read what a language shows with `get_section_values` and the same `locale` first; the result echoes `locale` and the `routings` written ({ sfRoutingId, path, locale }). ONE ROUTING (`routing`, e.g. `/test2`): a language several routings show (`/en`, `/test2`) gives each its own values, link labels included, and `locale` writes to all of them. When `get_section_values` with `locale` lists several `routings` (and a `routingsNote`), read with `routing` and write back with the SAME `routing` — writing those values with `locale` replaces the other routings' own labels.\n\nBIND TO A GLOBAL VARIABLE (Theme Setting): instead of a static `value`, pass `bind_global` = the global's `name` (its `variableName`, the `_<id>` form) from `list_theme_globals`. The prop becomes a LIVE dynamic value that always reflects that global's current value — editing the global in Theme Settings updates every bound prop. Use this to wire content to a project-wide setting (e.g. a shared announcement text, brand color, or logo image) rather than duplicating a literal. Pick a global whose type matches the prop (TEXT↔TEXT/RICH_TEXT, NUMBER↔NUMBER, BOOLEAN↔BOOLEAN, IMAGE↔IMAGE, COLOR↔COLOR, ENUM↔ENUM of the SAME enum type — the prop's `enumTypeId` must equal the setting's `enumTypeId`; a mismatch is REJECTED, …). Provide `value` OR `bind_global`, not both. Writing a static `value` to a prop that is bound to a global (see `bindings` in `get_section_values`) REPLACES the binding — the prop stops following the global, and the result carries `unboundGlobal` + a `warning`. To change what a bound prop shows, update the global (`update_theme_global`) instead. To bind a prop of a COMPONENT_LIST CHILD, also pass `list_path` (the `{ propId, index }` steps down to the child) and set `prop_id` to the child's prop id. Works for every section type, including built-in / code-component sections that have no blueprint.\n\n" +
4032
+ 'COMPONENT_LIST / COMPONENT props: the value is NOT wrapped in `{ "value": ... }`. A COMPONENT_LIST value is `{ "components": [ <entry>, ... ] }`; a single COMPONENT value is one `<entry>`. Each entry = `{ "id": "<unique-id>", "codeComponentId": "<child-id>" | "componentId": "<child-id>", "propValues": { "<childPropName>": <wrapped-value>, ... } }`. Rules: (1) `id` is a unique short alphanumeric string identifying THIS entry — generate a fresh one per new entry and NEVER reuse an existing entry\'s id. (2) Use `codeComponentId` for code components, `componentId` for built-in theme components. (3) `propValues` is keyed by the CHILD component\'s prop NAMES, each using the same scalar wrappers as above (nesting is recursive — a child may itself hold a COMPONENT_LIST). (4) `update_section_prop` REPLACES the whole prop value — there is NO partial/deep merge. ALWAYS send the COMPLETE, fully-nested value for the prop: every existing entry (with its id), every nested `propValues`, and every nested COMPONENT_LIST at every depth. To change anything (even one deeply-nested scalar, or to add/remove/reorder a child), READ-MODIFY-WRITE: take the current `{ "components": [...] }` from `get_section_values`, edit it in place (preserving all other entries, ids, and nested structures), then send the ENTIRE updated object back. Sending only the changed part — a single entry, or a child without its siblings — wipes everything you omitted. (5) You can only add child component types the prop permits — call `get_component_props(parentComponentId)` to read the COMPONENT_LIST prop\'s `allowedComponentIds`, then `get_component_props(childId)` to learn that child\'s props (names, types, ENUM `options`/valid values) instead of guessing or reading ikas.config.json. The allowed set is wired at build/config time per the `get_section_template` setup recipe (`config update-prop`), not here.\n\n' +
4033
+ 'Example — a full COMPONENT_LIST `value` with two children, where the second child itself nests another COMPONENT_LIST (note: scalar leaves are `{ "value": ... }`-wrapped, COMPONENT_LIST values are `{ "components": [...] }` and are NOT wrapped, every entry has a unique `id`, and this is the COMPLETE value you would send even to change just one field): ' +
4034
+ `{ "components": [ { "id": "a1b2c", "codeComponentId": "7ojrigep-Eml9n5sN3i", "propValues": { "heading": { "value": "Featured" }, "visible": { "value": true } } }, { "id": "d3e4f", "codeComponentId": "x2plk9zq-Qw8rt", "propValues": { "title": { "value": "Sub group" }, "cards": { "components": [ { "id": "g5h6i", "codeComponentId": "card01ab-Zz12", "propValues": { "label": { "value": "Card 1" } } }, { "id": "j7k8l", "codeComponentId": "card01ab-Zz12", "propValues": { "label": { "value": "Card 2" } } } ] } } } ] }`, {
4035
+ project_root: z
4036
+ .string()
4037
+ .describe("Absolute path to the code-component project."),
4038
+ page_id: z.string().describe("Target page id (from `list_editor_pages`)."),
4039
+ element_id: z
4040
+ .string()
4041
+ .describe("Placed-section elementId identifying THIS placement on the page (from `list_page_sections`)."),
4042
+ prop_id: z
4043
+ .string()
4044
+ .optional()
4045
+ .describe("Blueprint prop id to update (from `list_page_sections`). Provide this or `prop_name`."),
4046
+ prop_name: z
4047
+ .string()
4048
+ .optional()
4049
+ .describe("Blueprint prop name to update (alternative to `prop_id`)."),
4050
+ value: z
4051
+ .any()
4052
+ .optional()
4053
+ .describe('The prop value object to store, e.g. `{ "value": "Hello" }`. Match the shape of the existing value from `get_section_values` for non-scalar prop types. Omit when using `bind_global`.'),
4054
+ bind_global: z
4055
+ .string()
4056
+ .optional()
4057
+ .describe("Bind this prop to a project GLOBAL variable (Theme Setting) as a LIVE dynamic value instead of writing a static `value` — the prop then always reflects that global's current value (edited in Theme Settings). Pass the global's `name` (its `variableName`, the `_<id>` form) from `list_theme_globals`. Provide `value` OR `bind_global`, not both. Writing a static `value` to a prop that is bound to a global (see `bindings` in `get_section_values`) REPLACES the binding — the prop stops following the global, and the result carries `unboundGlobal` + a `warning`. To change what a bound prop shows, update the global (`update_theme_global`) instead. Bindable globals include TEXT / RICH_TEXT / NUMBER / BOOLEAN / IMAGE / COLOR / BORDER / SHADOW / ENUM settings; pick a global whose type matches the prop (an ENUM prop only binds an ENUM setting of the same enum type). (This is the general theme-global binding; a COLOR prop can alternatively take an inline `{ \"patternValueId\" }` for theme colors.)"),
4058
+ locale: z
4059
+ .string()
4060
+ .optional()
4061
+ .describe("A store language (e.g. `en`): write that language's value of THIS placement only, instead of the base value. Not with `bind_global`; not the base language."),
4062
+ routing: z
4063
+ .string()
4064
+ .optional()
4065
+ .describe("One routing of the store, by path (e.g. `/test2`) or id: as `locale`, for that routing alone. A language several routings show (`/en`, `/test2`) gives each its own values, link labels included; `locale` reads the first and writes all of them."),
4066
+ list_path: z
4067
+ .array(z.strictObject({ propId: z.string(), index: z.number() }))
4068
+ .optional()
4069
+ .describe("Only with `bind_global`: bind a prop of a COMPONENT_LIST child instead of a section-level prop. An array of `{ propId, index }` steps from the section down to the target child; `prop_id` is then the CHILD's prop id (from `get_component_props`)."),
4070
+ port: z
4071
+ .number()
4072
+ .optional()
4073
+ .describe("Dev server WebSocket port (default 5201)."),
4074
+ }, async ({ project_root, page_id, element_id, prop_id, prop_name, value, bind_global, list_path, locale, routing, port, }) => {
4075
+ const args = [
4076
+ "update-section-prop",
4077
+ "--page-id",
4078
+ page_id,
4079
+ "--element-id",
4080
+ element_id,
4081
+ ...(prop_id ? ["--prop-id", prop_id] : []),
4082
+ ...(prop_name ? ["--prop-name", prop_name] : []),
4083
+ ...(locale ? ["--locale", locale] : []),
4084
+ ...(routing ? ["--routing", routing] : []),
4085
+ ...(bind_global
4086
+ ? [
4087
+ "--bind-global",
4088
+ bind_global,
4089
+ ...(list_path ? ["--list-path", JSON.stringify(list_path)] : []),
4090
+ ]
4091
+ : [
4092
+ "--value",
4093
+ // The CLI JSON.parses --value. If `value` is already a JSON string, pass
4094
+ // it through verbatim — re-stringifying it would double-encode it and the
4095
+ // editor would store a string instead of the object/array.
4096
+ typeof value === "string" ? value : JSON.stringify(value),
4097
+ ]),
4098
+ ...(port ? ["--port", String(port)] : []),
4099
+ ];
4100
+ return callEditorAction(project_root, args);
4101
+ });
4102
+ // Tool: upload_image
4103
+ server.tool("upload_image", 'Upload an image to the connected editor\'s project and get back its image `id`. Provide the image via `file_path` (a local path) OR `image_url`. This is the ONLY way to obtain a real image id — an id cannot be invented. Use the returned `id`: (1) as an IMAGE prop value for `update_section_prop` (e.g. `{ "id": "<returned-id>", "altText": "...", "isVideo": false }`), or (2) as an IMAGE theme global\'s value for `create_theme_global`/`update_theme_global` (e.g. `{ "id": "<returned-id>" }`). An id cannot be invented — an unreal one is stored as given and renders as a broken image, so always use a `upload_image` id or one already listed by `list_theme_globals`. Neither tool uploads; both only reference an existing image id. Supported types: png, jpg, jpeg, webp, gif; max 10MB. Requires the editor to be embedded in the ikas admin panel (the admin panel performs the actual upload; a standalone editor cannot upload and will error/time out).', {
4104
+ project_root: z
4105
+ .string()
4106
+ .describe("Absolute path to the code-component project."),
4107
+ file_path: z
4108
+ .string()
4109
+ .optional()
4110
+ .describe("Local image file path (.png, .jpg, .jpeg, .webp, .gif). Provide this or `image_url`."),
4111
+ image_url: z
4112
+ .string()
4113
+ .optional()
4114
+ .describe("Image URL to fetch and upload (alternative to `file_path`)."),
4115
+ alt_text: z
4116
+ .string()
4117
+ .optional()
4118
+ .describe("Alt text to store with the image."),
4119
+ port: z
4120
+ .number()
4121
+ .optional()
4122
+ .describe("Dev server WebSocket port (default 5201)."),
4123
+ }, async ({ project_root, file_path, image_url, alt_text, port }) => {
4124
+ const args = [
4125
+ "upload-image",
4126
+ ...(file_path ? ["--file", file_path] : []),
4127
+ ...(image_url ? ["--url", image_url] : []),
4128
+ ...(alt_text ? ["--alt", alt_text] : []),
4129
+ ...(port ? ["--port", String(port)] : []),
4130
+ ];
4131
+ return callEditorAction(project_root, args);
4132
+ });
4133
+ // Tool: update_page_sections
4134
+ server.tool("update_page_sections", "Fill MANY placed sections of a page in a SINGLE call — the fastest way to populate a whole page (one round-trip for the entire page instead of one call per section/prop). Takes `sections`, each `{ element_id, updates: [{ prop_name|prop_id, value }] }`; values use the same per-type shapes as update_section_prop / get_editor_workflow. All-or-nothing across the whole page: every value is resolved and deeply validated (and built-but-unimported child code components auto-imported) before anything is written — one invalid value rejects the entire page update. An update item may instead bind a prop to a project GLOBAL variable (Theme Setting) as a live dynamic value: use `{ prop_id|prop_name, bind_global }` where `bind_global` is the global's `name` (its `variableName`) from `list_theme_globals` — omit `value`. Add `list_path` (an array of `{ propId, index }` steps) to bind a prop of a COMPONENT_LIST child (then `prop_id` is the child's prop id). Static value writes are applied first, then bindings. Prefer this over many update_section_prop(s) calls. If any targeted section is a COMMON (global) one — the theme's header/footer — its values are shared by every page and stored on the INDEX (Home) page's placement: the write goes there and changes that section on ALL pages, the result's `common` block says so, and the echoed values are read back from that canonical placement. Read those sections with `get_section_values` first and only change what was asked; a header/footer missing from the INDEX page has no record to write to and rejects the whole call. Pass `locale` to write ONE language's values of these placements instead of the base values, as update_section_prop's `locale` does (no bind_global items then).", {
4135
+ project_root: z
4136
+ .string()
4137
+ .describe("Absolute path to the code-component project."),
4138
+ page_id: z.string().describe("Target page id (from list_editor_pages)."),
4139
+ sections: z
4140
+ .array(z.strictObject({
4141
+ element_id: z
4142
+ .string()
4143
+ .describe("Placed-section elementId (from list_page_sections)."),
4144
+ updates: z
4145
+ .array(z.strictObject({
4146
+ prop_id: z
4147
+ .string()
4148
+ .optional()
4149
+ .describe("Blueprint prop id (provide this or prop_name)."),
4150
+ prop_name: z
4151
+ .string()
4152
+ .optional()
4153
+ .describe("Blueprint prop name (alternative to prop_id)."),
4154
+ value: z
4155
+ .any()
4156
+ .optional()
4157
+ .describe("Prop value, same shape update_section_prop expects for that type. Omit when using bind_global."),
4158
+ bind_global: z
4159
+ .string()
4160
+ .optional()
4161
+ .describe("Bind this prop to a project GLOBAL variable (Theme Setting) as a live dynamic value instead of a static value. The global's `name` (variableName) from list_theme_globals. Provide value OR bind_global."),
4162
+ list_path: z
4163
+ .array(z.strictObject({ propId: z.string(), index: z.number() }))
4164
+ .optional()
4165
+ .describe("Only with bind_global: `{ propId, index }` steps down to a COMPONENT_LIST child; prop_id is then the child's prop id."),
4166
+ }))
4167
+ .describe("Non-empty array of prop updates for this section."),
4168
+ }))
4169
+ .describe("Non-empty array of sections to fill, each with its elementId and prop updates."),
4170
+ locale: z
4171
+ .string()
4172
+ .optional()
4173
+ .describe("A store language (e.g. `en`): write that language's values of these placements only, instead of the base values. Not with bind_global items; not the base language."),
4174
+ routing: z
4175
+ .string()
4176
+ .optional()
4177
+ .describe("One routing of the store, by path (e.g. `/test2`) or id: as `locale`, for that routing alone. A language several routings show (`/en`, `/test2`) gives each its own values, link labels included; `locale` reads the first and writes all of them."),
4178
+ port: z
4179
+ .number()
4180
+ .optional()
4181
+ .describe("Dev server WebSocket port (default 5201)."),
4182
+ }, async ({ project_root, page_id, sections, locale, routing, port }) => {
4183
+ const normalized = (sections || []).map((s) => ({
4184
+ elementId: s.element_id,
4185
+ updates: (s.updates || []).map((u) => ({
4186
+ ...(u.prop_id ? { propId: u.prop_id } : {}),
4187
+ ...(u.prop_name ? { propName: u.prop_name } : {}),
4188
+ ...(u.bind_global
4189
+ ? {
4190
+ bindGlobal: u.bind_global,
4191
+ ...(u.list_path ? { listPath: u.list_path } : {}),
4192
+ }
4193
+ : { value: u.value }),
4194
+ })),
4195
+ }));
4196
+ const args = [
4197
+ "update-page-sections",
4198
+ "--page-id",
4199
+ page_id,
4200
+ "--sections",
4201
+ JSON.stringify(normalized),
4202
+ ...(locale ? ["--locale", locale] : []),
4203
+ ...(routing ? ["--routing", routing] : []),
4204
+ ...(port ? ["--port", String(port)] : []),
4205
+ ];
4206
+ return callEditorAction(project_root, args);
4207
+ });
4208
+ // Tool: upload_images
4209
+ server.tool("upload_images", "Upload MANY images in one call (batch upload_image) and get their ids back in order — the host uploads them all in a single round-trip. Pass `images`, each `{ file_path?, image_url?, alt_text? }`. Returns an array of { id, fileName, altText, isVideo } in the same order; use each id in an IMAGE prop value. Prefer this over multiple upload_image calls when a section/page needs several images. Supported: png/jpg/jpeg/webp/gif, max 10MB each. Requires the editor embedded in the ikas admin panel.", {
4210
+ project_root: z
4211
+ .string()
4212
+ .describe("Absolute path to the code-component project."),
4213
+ images: z
4214
+ .array(z.strictObject({
4215
+ file_path: z
4216
+ .string()
4217
+ .optional()
4218
+ .describe("Local image file path (provide this or image_url)."),
4219
+ image_url: z
4220
+ .string()
4221
+ .optional()
4222
+ .describe("Image URL to fetch (alternative to file_path)."),
4223
+ alt_text: z.string().optional().describe("Alt text for this image."),
4224
+ }))
4225
+ .describe("Non-empty array of images to upload."),
4226
+ port: z
4227
+ .number()
4228
+ .optional()
4229
+ .describe("Dev server WebSocket port (default 5201)."),
4230
+ }, async ({ project_root, images, port }) => {
4231
+ const manifest = (images || []).map((im) => ({
4232
+ ...(im.file_path ? { file: im.file_path } : {}),
4233
+ ...(im.image_url ? { url: im.image_url } : {}),
4234
+ ...(im.alt_text ? { alt: im.alt_text } : {}),
4235
+ }));
4236
+ const args = [
4237
+ "upload-images",
4238
+ "--manifest",
4239
+ JSON.stringify(manifest),
4240
+ ...(port ? ["--port", String(port)] : []),
4241
+ ];
4242
+ return callEditorAction(project_root, args);
4243
+ });
4244
+ // Tool: search_products
4245
+ server.tool("search_products", 'Search the connected store\'s products to obtain a real productId (and first variantId) for a PRODUCT prop value. Returns products with productId, variantId, name, slug, variantCount, and `imageSrc` (the full-resolution CDN URL of the product\'s main image). To use that product image in an IMAGE prop, you CANNOT reuse a product image id directly (it is not a theme asset) — pass the `imageSrc` URL to `upload_image(image_url: <imageSrc>)` (or `upload_images`), then use the returned id in the IMAGE value. This gives real product imagery instead of external/placeholder URLs. Use the result in update_section_prop as `{ "productId": "<productId>", "variantId": "<variantId>" }`. Pass `query` for free-text search, or `product_ids` to resolve specific ids. Requires the editor embedded in the ikas admin panel (the admin panel runs the search; a standalone editor cannot).', {
4246
+ project_root: z
4247
+ .string()
4248
+ .describe("Absolute path to the code-component project."),
4249
+ query: z
4250
+ .string()
4251
+ .optional()
4252
+ .describe("Free-text product search (name, sku, barcode)."),
4253
+ product_ids: z
4254
+ .array(z.string())
4255
+ .optional()
4256
+ .describe("Specific product ids to resolve directly (alternative to `query`)."),
4257
+ per_page: z.number().optional().describe("Results per page."),
4258
+ port: z
4259
+ .number()
4260
+ .optional()
4261
+ .describe("Dev server WebSocket port (default 5201)."),
4262
+ }, async ({ project_root, query, product_ids, per_page, port }) => {
4263
+ const args = [
4264
+ "search-products",
4265
+ ...(query ? ["--query", query] : []),
4266
+ ...(product_ids && product_ids.length
4267
+ ? ["--ids", product_ids.join(",")]
4268
+ : []),
4269
+ ...(typeof per_page === "number" ? ["--per-page", String(per_page)] : []),
4270
+ ...(port ? ["--port", String(port)] : []),
4271
+ ];
4272
+ return callEditorAction(project_root, args);
4273
+ });
4274
+ // Tool: list_categories
4275
+ server.tool("list_categories", 'List the store\'s product categories and their ids, to fill a CATEGORY prop value `{ "categoryId": "<id>" }`. Returns categoryId, name, slug, parentId for each. Returns all categories (no query). To link to a category from a LINK prop, also call `get_page_by_type("CATEGORY")` for the page id, then build `{ "linkType": "PAGE", "pageId": <pageId>, "pageType": "CATEGORY", "itemId": <categoryId>, "id": <unique>, "label": "..." }`. Requires the editor embedded in the ikas admin panel.', {
4276
+ project_root: z
4277
+ .string()
4278
+ .describe("Absolute path to the code-component project."),
4279
+ port: z
4280
+ .number()
4281
+ .optional()
4282
+ .describe("Dev server WebSocket port (default 5201)."),
4283
+ }, async ({ project_root, port }) => {
4284
+ const args = [
4285
+ "list-entities",
4286
+ "--kind",
4287
+ "category",
4288
+ ...(port ? ["--port", String(port)] : []),
4289
+ ];
4290
+ return callEditorAction(project_root, args);
4291
+ });
4292
+ // Tool: list_brands
4293
+ server.tool("list_brands", 'List the store\'s product brands and their ids, to fill a BRAND prop value `{ "brandId": "<id>" }`. Returns brandId, name, slug for each. Returns all brands (no query). To link to a brand from a LINK prop, also call `get_page_by_type("BRAND")` for the page id, then build `{ "linkType": "PAGE", "pageId": <pageId>, "pageType": "BRAND", "itemId": <brandId>, "id": <unique>, "label": "..." }`. Requires the editor embedded in the ikas admin panel.', {
4294
+ project_root: z
4295
+ .string()
4296
+ .describe("Absolute path to the code-component project."),
4297
+ port: z
4298
+ .number()
4299
+ .optional()
4300
+ .describe("Dev server WebSocket port (default 5201)."),
4301
+ }, async ({ project_root, port }) => {
4302
+ const args = [
4303
+ "list-entities",
4304
+ "--kind",
4305
+ "brand",
4306
+ ...(port ? ["--port", String(port)] : []),
4307
+ ];
4308
+ return callEditorAction(project_root, args);
4309
+ });
4310
+ // Tool: list_blogs
4311
+ server.tool("list_blogs", 'List the store\'s blogs and their ids, to fill a BLOG prop value `{ "blogId": "<id>" }`. Returns blogId, name, slug for each. Accepts an optional `query` for free-text search. To link to a blog from a LINK prop, also call `get_page_by_type("BLOG")` for the page id, then build `{ "linkType": "PAGE", "pageId": <pageId>, "pageType": "BLOG", "itemId": <blogId>, "id": <unique>, "label": "..." }`. Requires the editor embedded in the ikas admin panel.', {
4312
+ project_root: z
4313
+ .string()
4314
+ .describe("Absolute path to the code-component project."),
4315
+ query: z.string().optional().describe("Free-text blog search."),
4316
+ port: z
4317
+ .number()
4318
+ .optional()
4319
+ .describe("Dev server WebSocket port (default 5201)."),
4320
+ }, async ({ project_root, query, port }) => {
4321
+ const args = [
4322
+ "list-entities",
4323
+ "--kind",
4324
+ "blog",
4325
+ ...(query ? ["--query", query] : []),
4326
+ ...(port ? ["--port", String(port)] : []),
4327
+ ];
4328
+ return callEditorAction(project_root, args);
4329
+ });
4330
+ // Tool: list_blog_categories
4331
+ server.tool("list_blog_categories", 'List the store\'s blog categories and their ids, to fill a BLOG_CATEGORY prop value `{ "blogCategoryId": "<id>" }`. Returns blogCategoryId, name, slug for each. Accepts an optional `query` for free-text search. To link to a blog category from a LINK prop, also call `get_page_by_type("BLOG_CATEGORY")` for the page id, then build `{ "linkType": "PAGE", "pageId": <pageId>, "pageType": "BLOG_CATEGORY", "itemId": <blogCategoryId>, "id": <unique>, "label": "..." }`. Requires the editor embedded in the ikas admin panel.', {
4332
+ project_root: z
4333
+ .string()
4334
+ .describe("Absolute path to the code-component project."),
4335
+ query: z.string().optional().describe("Free-text blog-category search."),
4336
+ port: z
4337
+ .number()
4338
+ .optional()
4339
+ .describe("Dev server WebSocket port (default 5201)."),
4340
+ }, async ({ project_root, query, port }) => {
4341
+ const args = [
4342
+ "list-entities",
4343
+ "--kind",
4344
+ "blog-category",
4345
+ ...(query ? ["--query", query] : []),
4346
+ ...(port ? ["--port", String(port)] : []),
4347
+ ];
4348
+ return callEditorAction(project_root, args);
4349
+ });
4350
+ // Tool: get_page_by_type
4351
+ server.tool("get_page_by_type", 'Resolve a theme page\'s id from its pageType (CATEGORY, PRODUCT, BRAND, BLOG, BLOG_CATEGORY, INDEX, …). Use this to get the `pageId` needed to build a PAGE link to an entity: pair it with the entity id from list_categories/list_brands/list_blogs/list_blog_categories — `{ linkType:"PAGE", pageId:<this pageId>, pageType:<type>, itemId:<entityId>, id:<unique>, label:... }`. Returns `pageId: null` (with a note) if no page of that type exists yet — in that case call `create_page(page_type)` to add it, then use the returned pageId (do not guess a slug/EXTERNAL URL).', {
4352
+ project_root: z
4353
+ .string()
4354
+ .describe("Absolute path to the code-component project."),
4355
+ page_type: z
4356
+ .string()
4357
+ .describe("Page type to resolve, e.g. CATEGORY, PRODUCT, BRAND, BLOG, BLOG_CATEGORY, INDEX."),
4358
+ port: z
4359
+ .number()
4360
+ .optional()
4361
+ .describe("Dev server WebSocket port (default 5201)."),
4362
+ }, async ({ project_root, page_type, port }) => {
4363
+ const args = [
4364
+ "get-page-by-type",
4365
+ "--page-type",
4366
+ page_type,
4367
+ ...(port ? ["--port", String(port)] : []),
4368
+ ];
4369
+ return callEditorAction(project_root, args);
4370
+ });
4371
+ // Tool: create_page
4372
+ server.tool("create_page", 'Create a theme page of a given pageType in the connected editor. Use this when get_page_by_type returns `pageId: null` for a dynamic page (CATEGORY/PRODUCT/BRAND/BLOG/BLOG_CATEGORY) you need to link to: create the page, then build a PAGE link `{ linkType:"PAGE", pageId:<this pageId>, pageType:<type>, itemId:<entityId>, id:<unique>, label:... }` — do NOT guess a slug/EXTERNAL URL. Non-CUSTOM page types are unique per theme: if one already exists it is returned unchanged (`alreadyExisted: true`). CUSTOM pages require `name` and a unique `slug`. Account sub-pages (ADDRESSES/ORDERS/ORDER_DETAIL/FAVORITE_PRODUCTS/RAFFLE_ACCOUNT) need an ACCOUNT page first. Returns `{ pageType, pageId, name, slug }`. Requires `ikas theme dev` running with the editor connected.', {
4373
+ project_root: z
4374
+ .string()
4375
+ .describe("Absolute path to the code-component project."),
4376
+ page_type: z
4377
+ .string()
4378
+ .describe("Page type to create, e.g. CATEGORY, PRODUCT, BRAND, BLOG, BLOG_CATEGORY, INDEX, CUSTOM."),
4379
+ name: z
4380
+ .string()
4381
+ .optional()
4382
+ .describe("Page name. Required for CUSTOM pages; ignored otherwise."),
4383
+ slug: z
4384
+ .string()
4385
+ .optional()
4386
+ .describe("Page slug. Required (and unique) for CUSTOM pages; ignored otherwise."),
4387
+ port: z
4388
+ .number()
4389
+ .optional()
4390
+ .describe("Dev server WebSocket port (default 5201)."),
4391
+ }, async ({ project_root, page_type, name, slug, port }) => {
4392
+ const args = [
4393
+ "create-page",
4394
+ "--page-type",
4395
+ page_type,
4396
+ ...(name ? ["--name", name] : []),
4397
+ ...(slug ? ["--slug", slug] : []),
4398
+ ...(port ? ["--port", String(port)] : []),
4399
+ ];
4400
+ return callEditorAction(project_root, args);
4401
+ });
4402
+ // Tool: delete_page
4403
+ server.tool("delete_page", "Delete a theme page and every section placed on it. DESTRUCTIVE and effectively one-way from here (only the editor's own undo stack can bring it back) — ALWAYS get the user's explicit OK before calling it, and never call it to \"clean up\" a page you merely think is unused. Takes the page id from `list_editor_pages` / `get_page_by_type`; there is no name resolution. Refused for the pages a theme cannot run without — INDEX (home), CHECKOUT and NOT_FOUND (404) — and for an ikas-rendered ready-made account page, which must be turned off by its group with `enable_ready_made_pages` so the cleanup that flow does actually runs. Deleting the page currently open in the editor moves it to the home page first. Returns the deleted page's `{ pageId, pageType, name, slug }` plus `remainingPages`. Requires `ikas theme dev` running with the editor connected.", {
4404
+ project_root: z
4405
+ .string()
4406
+ .describe("Absolute path to the code-component project."),
4407
+ page_id: z
4408
+ .string()
4409
+ .describe("Id of the page to delete (from `list_editor_pages` or `get_page_by_type`). Strict — no name resolution."),
4410
+ confirm: z.boolean().describe(CONFIRM_PARAM_DESCRIPTION),
4411
+ port: z
4412
+ .number()
4413
+ .optional()
4414
+ .describe("Dev server WebSocket port (default 5201)."),
4415
+ }, async ({ project_root, page_id, confirm, port }) => {
4416
+ if (confirm !== true)
4417
+ return destructiveConfirmRefusal();
4418
+ const args = [
4419
+ "delete-page",
4420
+ "--id",
4421
+ page_id,
4422
+ "--yes",
4423
+ ...(port ? ["--port", String(port)] : []),
4424
+ ];
4425
+ return callEditorAction(project_root, args);
4426
+ });
4427
+ // Tool: remove_page_section
4428
+ server.tool("remove_page_section", "Remove ONE section placement from a page — the delete counterpart of `add_section_to_page` / `move_page_section`. DESTRUCTIVE: it takes the merchant's content in that section with it, so get the user's explicit OK first. The checkout section on the CHECKOUT page is refused — the checkout page requires it, so never offer to remove it. Target the PLACEMENT by `element_id` from `list_page_sections`, never the `sectionId` or `componentId` — the same section placed twice has two independent placements and each is removed on its own (passing the wrong id is rejected with the elementId you meant). A common (header/footer) section on the home page is HIDDEN rather than deleted, because the INDEX placement is where a common section's prop values live for EVERY page; the reply says so with `hidden: true`, and `add_section_to_page` brings it back with its values intact. A page customized per routing/specification holds its own placements per state: pass `sf_routing_id`/`specification_id` to remove from that state, otherwise only the BASE layer is touched (the reply lists the states it left alone). Returns the removed placement plus the page's remaining `sections`. Requires `ikas theme dev` running with the editor connected.", {
4429
+ project_root: z
4430
+ .string()
4431
+ .describe("Absolute path to the code-component project."),
4432
+ page_id: z
4433
+ .string()
4434
+ .describe("Id of the page holding the placement (from `list_editor_pages`)."),
4435
+ element_id: z
4436
+ .string()
4437
+ .describe("The PLACEMENT's elementId from `list_page_sections` — not the sectionId and not the componentId."),
4438
+ sf_routing_id: z
4439
+ .string()
4440
+ .optional()
4441
+ .describe("Remove from this customized routing state instead of the page's base layer. The state must already exist."),
4442
+ specification_id: z
4443
+ .string()
4444
+ .optional()
4445
+ .describe("Remove from this customized specification state instead of the page's base layer. The state must already exist."),
4446
+ confirm: z.boolean().describe(CONFIRM_PARAM_DESCRIPTION),
4447
+ port: z
4448
+ .number()
4449
+ .optional()
4450
+ .describe("Dev server WebSocket port (default 5201)."),
4451
+ }, async ({ project_root, page_id, element_id, sf_routing_id, specification_id, confirm, port, }) => {
4452
+ if (confirm !== true)
4453
+ return destructiveConfirmRefusal();
4454
+ const args = [
4455
+ "remove-page-section",
4456
+ "--page-id",
4457
+ page_id,
4458
+ "--element-id",
4459
+ element_id,
4460
+ "--yes",
4461
+ ...(sf_routing_id ? ["--sf-routing-id", sf_routing_id] : []),
4462
+ ...(specification_id ? ["--specification-id", specification_id] : []),
4463
+ ...(port ? ["--port", String(port)] : []),
4464
+ ];
4465
+ return callEditorAction(project_root, args);
4466
+ });
4467
+ // Tool: publish_theme
4468
+ // Tool: list_ready_made_pages
4469
+ server.tool("list_ready_made_pages", "List the ikas-rendered ready-made (\"built-in\") account/membership pages (login, register, forgot/recover password, my account, orders, addresses, favorites, email verification) and how to customize them. These pages are rendered by ikas's own components, NOT by sections: a ready-made page carries no sections, so `list_page_sections` shows nothing and `update_section_prop` cannot touch it — `update_ready_made_page_prop` is the write tool. Without arguments returns the roster: per-group (`membership` = login/register/password flows, `account` = my-account pages) enabled state, every ready-made page type with its theme pageId and which props the merchant already edited, plus the SHARED SCOPES (logo, palette, account-menu labels — values edited once that reach every page in the scope's group). Pass `page_type` (e.g. LOGIN) or `scope_id` for that page's/scope's FULL prop schema (types, defaults, ENUM options, translations) and current values (`values` = what the page renders with; `ownValues` = what this page's own layer stores). Pass `sf_routing_id` to read what one storefront routing/locale sees — the no-argument call lists the store's routings (id, path, locale; `isDefault: true` = the base, needing no sf_routing_id). Typical branding flow: read the theme's palette via `list_theme_globals`, then set the shared scope's colors as `{ \"patternValueId\": \"<global color id>\" }` bindings so the pages follow the theme's colors live.", {
4470
+ project_root: z
4471
+ .string()
4472
+ .describe("Absolute path to the code-component project."),
4473
+ page_type: z
4474
+ .string()
4475
+ .optional()
4476
+ .describe("One ready-made page's full prop schema and values (e.g. LOGIN, ACCOUNT, ORDERS)."),
4477
+ scope_id: z
4478
+ .string()
4479
+ .optional()
4480
+ .describe("One shared scope's full prop schema and values (scope ids come from the no-argument call)."),
4481
+ sf_routing_id: z
4482
+ .string()
4483
+ .optional()
4484
+ .describe("Read the values one storefront routing/locale sees (default: the base routing)."),
4485
+ port: z
4486
+ .number()
4487
+ .optional()
4488
+ .describe("Dev server WebSocket port (default 5201)."),
4489
+ }, async ({ project_root, page_type, scope_id, sf_routing_id, port }) => {
4490
+ const args = [
4491
+ "list-builtin-pages",
4492
+ ...(page_type ? ["--page-type", page_type] : []),
4493
+ ...(scope_id ? ["--scope-id", scope_id] : []),
4494
+ ...(sf_routing_id ? ["--sf-routing-id", sf_routing_id] : []),
4495
+ ...(port ? ["--port", String(port)] : []),
4496
+ ];
4497
+ return callEditorAction(project_root, args);
4498
+ });
4499
+ // Tool: update_ready_made_page_prop
4500
+ server.tool("update_ready_made_page_prop", 'Set, bind, or clear ONE prop of an ikas-rendered ready-made account/membership page — the write half of `list_ready_made_pages`, and the ONLY way to customize those pages (they have no sections, so `update_section_prop` cannot reach them). Target a page\'s own prop with `page_type` (e.g. LOGIN) or a SHARED prop — logo, palette, menu labels, edited once for every page in the scope\'s group — with `scope_id`. Identify the prop by `prop_id` or `prop_name` from `list_ready_made_pages`. VALUES ARE RAW (no `{ "value": ... }` envelope — an envelope is tolerated and unwrapped): TEXT = the plain string; BOOLEAN = true/false; NUMBER = a number; ENUM = one of the prop\'s `enumOptions` VALUES; COLOR = "#rrggbb" OR `{ "patternValueId": "<global color id>" }` to follow a theme color live (ids from `list_theme_globals` → colors[].id — prefer the binding when branding, so a palette change updates the pages); IMAGE = `{ "id": "<image id>" }` (id from `upload_image`); LINK/LIST_OF_LINK = copy the shape from `list_ready_made_pages` values. `bind_global` (a global\'s `name` from `list_theme_globals`) makes the prop follow a Theme Setting instead of holding a value; `clear: true` deletes the stored value so the prop falls back to the shared value or the manifest default. `sf_routing_id` writes one routing\'s override — use it to localize texts per language; without it you write the base value every routing inherits. Writes are undoable in the editor.', {
4501
+ project_root: z
4502
+ .string()
4503
+ .describe("Absolute path to the code-component project."),
4504
+ page_type: z
4505
+ .string()
4506
+ .optional()
4507
+ .describe("Page type whose OWN prop to write (e.g. LOGIN). Pass this or scope_id."),
4508
+ scope_id: z
4509
+ .string()
4510
+ .optional()
4511
+ .describe("Shared scope whose prop to write — reaches every ready-made page in its group."),
4512
+ prop_id: z
4513
+ .string()
4514
+ .optional()
4515
+ .describe("Prop id from list_ready_made_pages. Provide this or prop_name."),
4516
+ prop_name: z
4517
+ .string()
4518
+ .optional()
4519
+ .describe("Prop name (alternative to prop_id)."),
4520
+ value: z
4521
+ .any()
4522
+ .optional()
4523
+ .describe("The RAW value (see the tool description for per-type shapes). Omit when using bind_global or clear."),
4524
+ bind_global: z
4525
+ .string()
4526
+ .optional()
4527
+ .describe("Bind the prop to a global variable (Theme Setting) — pass the global's `name` from list_theme_globals."),
4528
+ clear: z
4529
+ .boolean()
4530
+ .optional()
4531
+ .describe("true deletes the stored value; the prop falls back to the shared value or the manifest default."),
4532
+ sf_routing_id: z
4533
+ .string()
4534
+ .optional()
4535
+ .describe("Write one storefront routing's override (localization). Omit to write the base value."),
4536
+ port: z
4537
+ .number()
4538
+ .optional()
4539
+ .describe("Dev server WebSocket port (default 5201)."),
4540
+ }, async ({ project_root, page_type, scope_id, prop_id, prop_name, value, bind_global, clear, sf_routing_id, port, }) => {
4541
+ const args = [
4542
+ "update-builtin-page-prop",
4543
+ ...(page_type ? ["--page-type", page_type] : []),
4544
+ ...(scope_id ? ["--scope-id", scope_id] : []),
4545
+ ...(prop_id ? ["--prop-id", prop_id] : []),
4546
+ ...(prop_name ? ["--prop-name", prop_name] : []),
4547
+ ...(bind_global
4548
+ ? ["--bind-global", bind_global]
4549
+ : clear
4550
+ ? ["--clear"]
4551
+ : value !== undefined
4552
+ ? [
4553
+ "--value",
4554
+ // ALWAYS JSON-encode: the CLI JSON.parses --value (raw-string fallback), so a
4555
+ // verbatim TEXT string that happens to parse — "2024", "true", "null" — would
4556
+ // arrive as a number/boolean/clear. Encoded, it round-trips as the string it is.
4557
+ JSON.stringify(value),
4558
+ ]
4559
+ : []),
4560
+ ...(sf_routing_id ? ["--sf-routing-id", sf_routing_id] : []),
4561
+ ...(port ? ["--port", String(port)] : []),
4562
+ ];
4563
+ return callEditorAction(project_root, args);
4564
+ });
4565
+ // Tool: enable_ready_made_pages
4566
+ server.tool("enable_ready_made_pages", 'Turn one GROUP of ikas-rendered ready-made pages on or off: "membership" (login, register, forgot/recover password, email verification) or "account" (my account, orders, order detail, addresses, favorites). Enabling records the choice and creates any page of the group the theme does not have yet — each born rendered by ikas\'s own component; customize them right after with `update_ready_made_page_prop`. Disabling removes ONLY the untouched pages the toggle itself created — a page the merchant built on is never deleted. The flip is one undo step in the editor. Check the current state first with `list_ready_made_pages`.', {
4567
+ project_root: z
4568
+ .string()
4569
+ .describe("Absolute path to the code-component project."),
4570
+ group: z
4571
+ .enum(["membership", "account"])
4572
+ .describe('"membership" = login/register/password flows; "account" = my-account pages.'),
4573
+ enabled: z
4574
+ .boolean()
4575
+ .describe("true to enable the group, false to disable it."),
4576
+ confirm: z
4577
+ .boolean()
4578
+ .optional()
4579
+ .describe(`Disabling only (it removes pages). ${CONFIRM_PARAM_DESCRIPTION}`),
4580
+ port: z
4581
+ .number()
4582
+ .optional()
4583
+ .describe("Dev server WebSocket port (default 5201)."),
4584
+ }, async ({ project_root, group, enabled, confirm, port }) => {
4585
+ if (!enabled && confirm !== true)
4586
+ return destructiveConfirmRefusal();
4587
+ const args = [
4588
+ "enable-builtin-pages",
4589
+ "--group",
4590
+ group,
4591
+ "--enabled",
4592
+ String(enabled),
4593
+ ...(enabled ? [] : ["--yes"]),
4594
+ ...(port ? ["--port", String(port)] : []),
4595
+ ];
4596
+ return callEditorAction(project_root, args);
4597
+ });
4598
+ // Tool: list_translations
4599
+ server.tool("list_translations", 'Read the editor\'s translations page — everything its two sides hold. `mode: "store"` = store content: sections\' and components\' translatable prop values (TEXT, RICH_TEXT, IMAGE, IMAGE_LIST, VIDEO), element texts, the storefront\'s common texts (`common`, per store language only), the global texts/images (`global`), and the code component projects\' UI texts (`i18n`: the `src/i18n` files read with `t()`; one item per top-level group, `<projectId>:<group>`; key = the dotted path; "default" = default.json). `mode: "editor"` = the editor texts: item names, prop labels/descriptions, group names/descriptions, and the global settings\' names (`global`: one item per settings list). Locales: "default" is the base texts every language falls back to (no record); otherwise a store language (store mode) or an added editor language (editor mode). Without `area`: the languages, the addable ones, routing languages, and each language\'s translated/total by area — start here. With `area` + `locale`: the area\'s items with progress. With `item_id`: the item\'s fields — `key` (what update_translations takes), `kind` (the value\'s shape), `source` (the text it is translated from), `value` (now), `required`, and `editedOverAsset` when the field holds an edit over a design asset\'s value (resettable). `only_missing: true` keeps the empty fields. Requires `ikas theme dev` running with the editor connected.', {
4600
+ project_root: z
4601
+ .string()
4602
+ .describe("Absolute path to the code-component project."),
4603
+ mode: z.enum(["store", "editor"]).describe("store = store content; editor = editor texts."),
4604
+ area: z
4605
+ .enum(["sections", "components", "common", "global", "i18n"])
4606
+ .optional()
4607
+ .describe("The page's sidebar list (editor mode has no `common` or `i18n`). Omit for the languages and progress."),
4608
+ locale: z
4609
+ .string()
4610
+ .optional()
4611
+ .describe('"default" or a language code. Required with `area`.'),
4612
+ item_id: z
4613
+ .string()
4614
+ .optional()
4615
+ .describe("An item id from the area's list: returns its fields."),
4616
+ only_missing: z
4617
+ .boolean()
4618
+ .optional()
4619
+ .describe("With item_id: only the fields without a value in `locale`."),
4620
+ port: z
4621
+ .number()
4622
+ .optional()
4623
+ .describe("Dev server WebSocket port (default 5201)."),
4624
+ }, async ({ project_root, mode, area, locale, item_id, only_missing, port }) => {
4625
+ const args = [
4626
+ "list-translations",
4627
+ "--mode",
4628
+ mode,
4629
+ ...(area ? ["--area", area] : []),
4630
+ ...(locale ? ["--locale", locale] : []),
4631
+ ...(item_id ? ["--item", item_id] : []),
4632
+ ...(only_missing ? ["--only-missing"] : []),
4633
+ ...(port ? ["--port", String(port)] : []),
4634
+ ];
4635
+ return callEditorAction(project_root, args);
4636
+ });
4637
+ // Tool: update_translations
4638
+ server.tool("update_translations", 'Write translations in ONE language through the editor\'s translations page, as a batch: each edit is `{ area, item_id, key, value }`, or `{ area, item_id, key, reset: true }` to put back the design asset\'s value of a field listed with `editedOverAsset`. Take `key` and `kind` from `list_translations` with `item_id` — never guess keys. VALUES BY KIND: text = a string; richText = an HTML string (e.g. "<p>Hi</p>"); image = `{ "id": "<image id>", "altText"?: string }` (id from `upload_image`), or `{ "altText": string }` alone in a language to translate only the alt text: the image stays the default\'s and follows it; imageList = `{ "images": [{ "id": ..., "altText"?: string }] }`, or `{ "images": [{ "altText": string }, ...] }` for the default images\' alt texts by their place; video = `{ "video": { "id": ... }, "thumbnailImage"?: { "id": ... }, "autoplay"?, "controls"?, "loop"?, "muted"?: boolean }`; globalImage = `{ "id": ..., "altText"?: string }`, or `{ "altText": string }` as image; `null` empties the field (a cleared common text takes ikas\'s own back); emptying a field that holds a value needs `confirm: true`, after the user agreed. STRICT: every edit is checked before anything is written — the language must be added, the item and key must exist, the value must match the kind (unknown keys rejected), a default name/label or UI text (`i18n`) base text cannot be empty, a UI text\'s translation must use exactly its base text\'s `{{params}}`, and a global setting\'s default name must pass the page\'s rules; one bad edit and NOTHING is written (the reply lists each error). The batch is one undo step in the editor; the open translations page reloads (or warns its unsaved edits). Edits of the connected project\'s code components are written on to its ikas.config.json, its UI texts to its `src/i18n/*.json`. A section\'s `source` is its own default, which every placement without a value of its own shows: a placement\'s value (update_section_prop) can differ. Translate from `source`, keep HTML structure in rich text, do not translate brand names.', {
4639
+ project_root: z
4640
+ .string()
4641
+ .describe("Absolute path to the code-component project."),
4642
+ mode: z.enum(["store", "editor"]).describe("store = store content; editor = editor texts."),
4643
+ locale: z
4644
+ .string()
4645
+ .describe('"default" (the base texts) or an added language code.'),
4646
+ edits: z
4647
+ .array(z.strictObject({
4648
+ area: z.enum(["sections", "components", "common", "global", "i18n"]),
4649
+ item_id: z.string(),
4650
+ key: z.string(),
4651
+ value: z.any().optional(),
4652
+ reset: z.literal(true).optional(),
4653
+ }))
4654
+ .min(1)
4655
+ .describe("The edits; a field at most once."),
4656
+ confirm: z
4657
+ .boolean()
4658
+ .optional()
4659
+ .describe("Required when an edit empties (value: null) a field that holds a value. Ask the user first; pass true only after they agreed."),
4660
+ port: z
4661
+ .number()
4662
+ .optional()
4663
+ .describe("Dev server WebSocket port (default 5201)."),
4664
+ }, async ({ project_root, mode, locale, edits, confirm, port }) => {
4665
+ const args = [
4666
+ "update-translations",
4667
+ "--mode",
4668
+ mode,
4669
+ "--locale",
4670
+ locale,
4671
+ "--edits",
4672
+ JSON.stringify(edits),
4673
+ ...(confirm ? ["--yes"] : []),
4674
+ ...(port ? ["--port", String(port)] : []),
4675
+ ];
4676
+ return callEditorAction(project_root, args);
4677
+ });
4678
+ // Tool: manage_translation_languages
4679
+ server.tool("manage_translation_languages", 'Add languages to the editor\'s translations page or delete one, as its language settings do. `mode: "store"`: store languages — any language code (`list_translations` lists the addable ones); a new one gets ikas\'s built-in common texts. `mode: "editor"`: the editor languages the editor texts are translated into (tr/en). Pass `add` (codes) OR `remove` (one code). DESTRUCTIVE removal: it deletes every text in that language (and with `remove_page_values`, a routing language\'s page values) — ask the user first and pass `confirm: true` only after they agreed. Adding is one undo step.', {
4680
+ project_root: z
4681
+ .string()
4682
+ .describe("Absolute path to the code-component project."),
4683
+ mode: z.enum(["store", "editor"]).describe("store = store languages; editor = editor languages."),
4684
+ add: z
4685
+ .array(z.string())
4686
+ .optional()
4687
+ .describe("Language codes to add (e.g. [\"de\", \"fr\"])."),
4688
+ remove: z.string().optional().describe("The language code to delete."),
4689
+ remove_page_values: z
4690
+ .boolean()
4691
+ .optional()
4692
+ .describe("With remove on a store language that has a storefront routing: also remove its page values."),
4693
+ confirm: z.boolean().optional().describe(CONFIRM_PARAM_DESCRIPTION),
4694
+ port: z
4695
+ .number()
4696
+ .optional()
4697
+ .describe("Dev server WebSocket port (default 5201)."),
4698
+ }, async ({ project_root, mode, add, remove, remove_page_values, confirm, port }) => {
4699
+ if (remove !== undefined && confirm !== true)
4700
+ return destructiveConfirmRefusal();
4701
+ const args = [
4702
+ "translation-languages",
4703
+ "--mode",
4704
+ mode,
4705
+ ...(add ? ["--add", add.join(",")] : []),
4706
+ ...(remove !== undefined
4707
+ ? ["--remove", remove, "--yes", ...(remove_page_values ? ["--remove-page-values"] : [])]
4708
+ : []),
4709
+ ...(port ? ["--port", String(port)] : []),
4710
+ ];
4711
+ return callEditorAction(project_root, args);
4712
+ });
4713
+ server.tool("publish_theme", "Publish the current theme LIVE — the same action as the editor's Publish button (uploads the whole project to the storefront). This is REAL and customer-facing: the published site changes. SAFETY: it publishes nothing unless `confirm: true` is passed; if you omit it you get a dry-run with the `previewUrl` and a warning describing the impact. The MAIN/production theme additionally requires `confirm_production: true` (its URL is the live customer-facing domain). Use this when the user explicitly asks to publish/go live — do NOT publish on your own initiative. On success returns `{ published: true, previewUrl, isMainTheme }`; open `previewUrl` to review the result. Requires `ikas theme dev` running with the editor connected.", {
4714
+ project_root: z
4715
+ .string()
4716
+ .describe("Absolute path to the code-component project."),
4717
+ confirm: z
4718
+ .boolean()
4719
+ .optional()
4720
+ .describe("Set true to actually publish. Omitted/false = dry-run (returns previewUrl + warning, publishes nothing)."),
4721
+ confirm_production: z
4722
+ .boolean()
4723
+ .optional()
4724
+ .describe("Required IN ADDITION to confirm when the target is the MAIN/production theme (live customer-facing site)."),
4725
+ port: z
4726
+ .number()
4727
+ .optional()
4728
+ .describe("Dev server WebSocket port (default 5201)."),
4729
+ }, async ({ project_root, confirm, confirm_production, port }) => {
4730
+ const args = [
4731
+ "publish-theme",
4732
+ ...(confirm ? ["--confirm"] : []),
4733
+ ...(confirm_production ? ["--confirm-production"] : []),
4734
+ ...(port ? ["--port", String(port)] : []),
4735
+ ];
4736
+ return callEditorAction(project_root, args);
4737
+ });
4738
+ // Tool: get_editor_workflow
4739
+ const EDITOR_WORKFLOW_GUIDE = [
4740
+ "# Editor workflow: placing sections and filling their content on a page",
4741
+ "",
4742
+ "Use this when the user wants to add a section to a page and/or fill in its content (heading, text, image, link, slides, etc.) in the live editor. These are LIVE-EDITOR actions and require `ikas theme dev` running with the editor connected; image upload additionally requires the editor to be embedded in the ikas admin panel (the admin panel performs the upload — a standalone editor cannot upload).",
4743
+ "",
4744
+ "## Account & membership pages: ASK before you build",
4745
+ "If the page the user wants is a login, register, forgot/recover-password, my-account, orders, order-detail, addresses, favorites or email-verification page: do NOT code a custom section page yet. ikas ships ready-made versions of exactly these pages — fully functional (real auth/order/address flows), customizable (logo, colors, texts) and localizable via update_ready_made_page_prop, the whole group enabled at once with enable_ready_made_pages. FIRST ask the user which they want: the ready-made page (fast, maintained by ikas) or a custom section page (full design freedom) — list the ready-made option FIRST as the recommended default, custom second. Only start coding after the user explicitly chooses custom — and never call enable_ready_made_pages without the user's OK, it creates/removes pages. Start discovery with list_ready_made_pages. USER-FACING NAME: name these in the USER'S OWN LANGUAGE — English: \"ikas's ready-made pages\", Turkish: \"ikas'ın hazır sayfaları\"; never mix the English term into a sentence in another language — the editor UI lists them as Membership Pages / My Account Pages; \"built-in\" is an internal term — keep it out of everything the user sees, including question/option labels. Note: a ready-made page is born with ONLY its own ikas-rendered element — the theme's header/footer are NOT on it (the page draws its own top bar — logo, back-to-store link — and account nav). If the user wants the theme header/footer there, place it with add_section_to_page (sections can sit above/below that element) and suggest turning the page's `showBrandBar` prop off to avoid double chrome.",
4746
+ "",
4747
+ "## Two distinct jobs — do not confuse them",
4748
+ "- (A) DEFINE props / author component code — changing WHICH props a component has. Edits component source/config (config add-prop/add-component, index.tsx) and needs a rebuild. Do this ONLY when a needed prop does not exist yet, or the user explicitly asks to build/modify the component.",
4749
+ "- (B) SET prop VALUES / fill content — giving values to props that ALREADY exist on a placed section. Pure data entry via list_page_sections + update_section_prop (+ upload_image). No code, no rebuild.",
4750
+ "When the user says 'fill this section', 'set the title/text/image/link', 'populate', 'change the content' → that is JOB (B). Do NOT write a component or add a prop to fill a value the section already supports.",
4751
+ "",
4752
+ "## Step-by-step (JOB B — fill content)",
4753
+ "1. list_editor_pages → choose the target page_id.",
4754
+ "2. list_page_sections(page_id) → for each placed section: its per-placement elementId, blueprint props (id, name, type), and setPropNames (which props already have a value). It is LEAN — no prop VALUES, so it never truncates. To read a section's current values (e.g. to read-modify-write a COMPONENT_LIST), call get_section_values(page_id, element_id). A section returned with a `common` field is the theme's header/footer — its values are theme-wide, not this page's; read the 'COMMON (global) sections' section below BEFORE touching it. (If the section is not on the page yet, see 'Placing a section' below.)",
4755
+ "3. To set props (fewest round-trips = fastest): update_page_sections(page_id, sections:[{element_id, updates:[{prop_name,value}]}]) fills the WHOLE page (or one section, or just one prop — it scales to all cases) in ONE call (best). update_section_prop sets a single prop, for quick one-offs. Pass each value as a parsed JSON object/array, NEVER a JSON string.",
4756
+ "4. For image props: upload_images(images:[{file_path|image_url, alt_text}]) uploads many in ONE call (preferred); upload_image for a single one. Use the returned id(s) in IMAGE values. Do uploads BEFORE the update call so you have the ids.",
4757
+ "Speed tip: each tool call is a round-trip — gather first (one list_page_sections), batch your uploads (upload_images) and your writes (update_page_sections), rather than calling per-prop/per-image.",
4758
+ "",
4759
+ "## COMMON (global) sections: the header and the footer",
4760
+ "The theme's header and footer are COMMON sections: they render on every page that carries a placement of them (pages created in the editor are seeded with one — EXCEPT ikas ready-made (built-in) account/membership pages, which are born without the theme header/footer) and their prop values are SHARED by the whole theme — there is exactly ONE record, kept on the INDEX (Home) page's placement. A placement of the same section on any other page stores NOTHING of its own.",
4761
+ '- How to recognize one: list_page_sections / get_section_values / the write results return a `common` block for it — `isCommon: true`, `commonSectionType: "header"|"footer"`, `valuesArePageSpecific: false`, plus `canonicalPageId`/`canonicalElementId` (the INDEX placement that holds the values). A page containing one also gets a top-level `commonSectionsNote`.',
4762
+ "- READS are redirected for you: get_section_values / list_page_sections report a common section's values FROM the INDEX placement, whatever page_id you pass. So what you see is what the page actually renders — no need to re-read from the INDEX page.",
4763
+ "- WRITES are redirected too: update_section_prop / update_page_sections / add_sections_to_page store the value on that INDEX record, so the change applies to the header/footer on ALL pages. The echoed value is read back from the canonical placement, so it reflects what was really stored.",
4764
+ '- THE TRAP to avoid: a header/footer is normally already filled with the merchant\'s content. Never conclude a prop is empty and never blind-fill "missing" props — you would overwrite live content on every page, including pages you never opened. Always get_section_values first and change ONLY the prop the user asked about.',
4765
+ "- If the INDEX page has no placement of the section, there is no record: reads return nothing and writes are REJECTED (\"Index page does not have the common section!\"). Fix it by placing the section on the INDEX page (add_section_to_page with the INDEX page id — get it from list_editor_pages / get_page_by_type('INDEX')) and setting its props there; it then renders on the other pages too.",
4766
+ "",
4767
+ "## Building a whole page fast (placing + filling)",
4768
+ "- add_sections_to_page(page_id, sections:[{component_id, index?, updates:[{prop_name,value}]}]) places MANY sections AND sets their props in ONE call, returning each new elementId. This is the fastest path — prefer it over add_section_to_page per section followed by separate fills. Built-but-unimported section/child components are auto-imported.",
4769
+ "- For a single section: list_imported_sections (confirm imported; else import_section, after building) → add_section_to_page(component_id, page_id, index?) → then list_page_sections to get its elementId.",
4770
+ "- REORDERING an already-placed section is a different tool: move_page_section(page_id, element_id, direction:'up'|'down' | to_index:<n>). The `index` on add_* only positions a NEW placement; it cannot move an existing one, and the editor UI exposes reordering solely as a drag, so this tool is the only way. Indices are 0-based over the placed sections in list_page_sections order; the result returns `resultIndex` + the full resulting `sections` order — assert on those. Header/footer (COMMON) sections cannot be reordered and are rejected.",
4771
+ "",
4772
+ "## Value shapes by prop type (what to pass as `value`)",
4773
+ '- Scalars are WRAPPED: TEXT/RICH_TEXT { "value": "..." }, BOOLEAN { "value": true }, NUMBER { "value": 12 }, COLOR { "value": "#FF0000" }, ENUM { "value": "<key>" }, DATE { "value": ... }.',
4774
+ '- SVG is value-wrapped: { "value": "<svg markup>" }. NUMBER_RANGE: { "value": <number>, "unit": "px"|null }.',
4775
+ '- SVG naming: the editor shows each svg\'s `class` attribute as its display name in the list; add class="my-icon" to name it. SVG_LIST items with no class render as svg-1, svg-2, ….',
4776
+ '- Object props are NOT wrapped (no { "value": ... }):',
4777
+ ' - IMAGE: { "id": "<asset-id>", "altText"?: "...", "isVideo"?: false } — get the id from upload_image. Same shape at section level AND nested in a component list. IMAGE_LIST: { "images": [ <image>, ... ] }.',
4778
+ ' - VIDEO: { "video": { "id": "<asset-id>" }, "thumbnailImage"?: { "id": "..." }, "autoplay"?: false, "controls"?: true, "loop"?: false, "muted"?: false } — NOT a bare { "id": ... }. SVG_LIST: { "svgs": [ "<svg>", ... ] }.',
4779
+ ' - LINK: { "id": "<unique>", "linkType": "PAGE"|"EXTERNAL"|"FILE", "label": "...", "subLinks": [] } plus target — for a static page: pageId + pageType (from list_editor_pages); for EXTERNAL: externalLink. To link to a CATEGORY/BRAND/BLOG/BLOG_CATEGORY entity, do NOT guess a slug — get the entity id from list_categories/list_brands/list_blogs/list_blog_categories and the page id from get_page_by_type(\'<TYPE>\'), then build { id, linkType:\'PAGE\', label, pageId:<pageId>, pageType:\'<TYPE>\', itemId:<entityId>, subLinks:[] }. LIST_OF_LINK = { "links": [ <link>, ... ] }. Optional on any link (sub-links too): "translations": [ { "locale": "en", "label": "Home" } ] = its label on the other routings: a routing\'s own { "locale", "label", "sfRoutingId" }, else its language\'s { "locale", "label" }, else "label". Do NOT write them by hand: write the link with only its label changed using update_section_prop `locale` (every routing of that language) or `routing` (one routing) and it becomes that translation, the links still following the base; a link sent without "translations" keeps its stored ones (by its id), so new links can be added to a list without resending its labels; on a PRODUCT/CATEGORY/BRAND link with itemId, "useItemNameTranslations": true shows that item\'s own name in each language instead of "label".',
4780
+ ' - Entity props PRODUCT/CATEGORY/BRAND/BLOG/BLOG_CATEGORY/RAFFLE: { "<entity>Id": "...", "usePageData"?: false } — e.g. { "productId": "...", "variantId"?: "..." }, { "categoryId": "..." }. Get real ids (never invent them) from: search_products (PRODUCT), list_categories (CATEGORY), list_brands (BRAND), list_blogs (BLOG), list_blog_categories (BLOG_CATEGORY). (RAFFLE has no lookup tool yet — read an existing value or ask the user.)',
4781
+ " - List/collection props (PRODUCT_LIST/CATEGORY_LIST/BRAND_LIST/BLOG_LIST/…): typed objects keyed by a <entity>ListType discriminator plus initialSort/initialLimit. The id field DEPENDS on the type — for PRODUCT_LIST: STATIC → productIds:[{productId,variantId}] (from search_products); CATEGORY → category:'<categoryId>' (from list_categories) — the field is `category`, NOT `categoryId` (categoryId is ONLY the standalone CATEGORY entity prop above); ALL/DISCOUNTED/RECOMMENDED/etc → no id field. Get the exact field set + writeNote from get_component_props, or read+edit an existing value via get_section_values. Unknown sub-fields (e.g. categoryId inside a PRODUCT_LIST) are REJECTED.",
4782
+ ' - COMPONENT_LIST: { "components": [ { "id": "<unique>", "codeComponentId": "<child-id>", "propValues": { "<childProp>": <value>, ... } }, ... ] }. A single COMPONENT prop is one such entry. childProp values use these same per-type shapes, recursively.',
4783
+ "",
4784
+ "## COMPONENT_LIST rules (the part most often gotten wrong)",
4785
+ "- READ-MODIFY-WRITE: update_section_prop REPLACES the whole prop value. To add/edit/remove one child, take the CURRENT { components: [...] } from get_section_values, edit it, and resend the ENTIRE array (with all existing entries and their ids). Sending only your new entry wipes the rest.",
4786
+ "- Each entry needs a UNIQUE id (a short string you generate; it does not need to match anything). Do not reuse another entry's id.",
4787
+ '- Reference a code component with "codeComponentId" and a built-in theme component with "componentId" — not the other way around. Use "propValues" (not "props").',
4788
+ "- Child ids are opaque — take them from get_section_template / list_imported_sections; never invent them.",
4789
+ "- Auto-import: a referenced child that is BUILT but not yet imported is imported automatically (returned under autoImported). A child that is not built at all errors — build it first.",
4790
+ "",
4791
+ "## Reading prop schemas (avoid guessing)",
4792
+ "- get_component_props(componentId) → a component's props with types, required, default, ENUM `options` (the valid values to set), and COMPONENT_LIST `allowedComponentIds` (valid children). Works for any section OR child id. Use it BEFORE filling — to know prop names, enum values, and which children a slot allows — instead of guessing or reading ikas.config.json.",
4793
+ "- For a COMPONENT_LIST: get_component_props(parent) → its allowedComponentIds → get_component_props(child) → the child's props/enums. Then build the components array.",
4794
+ "- get_section_values(element_id) → one placed section's current values (read-modify-write of a COMPONENT_LIST, or to copy an existing value's exact shape).",
4795
+ "- Real entity ids/images: search_products returns productId + variantId + imageSrc (the product image URL). To use that image in an IMAGE prop, you can't reuse a product image id — upload it: upload_image(image_url: imageSrc) → use the returned id. list_categories/list_brands/list_blogs/list_blog_categories return the entity ids; to LINK to one, also call get_page_by_type('<TYPE>') for the page id and build a PAGE link { linkType:'PAGE', pageId, pageType, itemId:<entityId>, id, label }. IMPORTANT: if get_page_by_type returns pageId:null, that dynamic page does NOT exist in the theme yet — do NOT guess a slug/EXTERNAL URL. Call create_page('<TYPE>') to add it (non-CUSTOM types are unique and returned as-is if already present), then use the returned pageId to build the PAGE link. Always have a real pageId before building a PAGE link.",
4796
+ "",
4797
+ "## Validation",
4798
+ "Values are validated server-side (deeply, including nested children). Wrong shape or wrong semantics (double-encoded string, { value } wrapper on an object prop, props vs propValues, missing/duplicate id, wrong reference key, nonexistent component id, unknown prop name) are REJECTED with an explanatory error instead of being stored silently. Read the error and fix the value; if unsure of a shape, read it with get_section_values and match it.",
4799
+ "",
4800
+ "## Translations (other languages)",
4801
+ "update_section_prop / update_page_sections write the base value; with `locale` they write one language's value of that placement only (a section reading differently per page in a language, a link list of its own in a language; a link's label written alone with `locale` or `routing` becomes its translation in that language or routing, without a copy). A section's texts in another language for every placement, the common and global texts, the editor texts (names, labels), the code components' UI texts (`i18n`) and the languages themselves are the translations page's: list_translations (start without an area: languages and progress) → list_translations with area/locale/item_id for the field keys → update_translations (a checked batch in one language) → manage_translation_languages to add a language (deleting one needs the user's OK).",
4802
+ ].join("\n");
4803
+ server.tool("get_editor_workflow", "Read this FIRST when the user wants to place a section on a page or fill/edit a section's content (text, image, link, slides, component lists) in the live editor. Returns the complete step-by-step workflow for the live-editor tools (list_editor_pages, list_imported_sections, import_section, add_section_to_page, list_page_sections, update_section_prop, upload_image), the per-prop-type value shapes, the COMPONENT_LIST read-modify-write rules, how COMMON (global) header/footer sections keep one theme-wide set of values on the INDEX page (and how not to overwrite them), and how validation/auto-import behave. Use it to avoid the common mistake of writing component code to set a value a section already supports.", {}, async () => {
4804
+ return {
4805
+ content: [{ type: "text", text: EDITOR_WORKFLOW_GUIDE }],
4806
+ };
4807
+ });
4808
+ // Tool: list_theme_globals
4809
+ server.tool("list_theme_globals", "List the theme's global settings from the connected editor: global variables (Theme Settings) and design tokens (colors, typography, breakpoints, keyframes, color schemes). Call this BEFORE generating sections/components so you reuse the theme's existing variables and tokens (read them in component code via `getThemeSetting`/`getThemeColors`/... from `@ikas/bp-storefront`). Includes items created manually in the editor UI. Requires `ikas theme dev` running with the editor connected. Two shape gotchas when consuming the result at runtime: (1) color schemes — `colorSchemes.schemes` holds only `{id,name}` slot LABELS; the actual colors live in `colorSchemes.values[].colorsByScheme` keyed by slot id, so iterate `values[].colorsByScheme` (iterating `schemes` renders empty). (2) An IMAGE setting's `value` is an image REFERENCE like `{id:'theme-images/<uuid>'}` with no `.url` — resolve it via `getDefaultSrc`/`getSrc`. (3) Each keyframe now includes its animation `settings` (type-dependent { property, value } entries — duration/iteration/timing/etc. for keyframe, transition for transition) and each point's resolved `styles`, so you can read back the full animation config, not just the `ref`. (4) Each typography entry may include `supportedFontWeights` — the exact numeric weights that text style's font actually ships (e.g. `[400]` for Modak); when present, only set `font_weight` to a value in this list (via `update_text_style`/`create_theme_global`), otherwise the write is rejected. If the field is absent the font's weight set couldn't be determined — fall back to 400 or rely on the validation error. Each typography entry also carries `isDefault` (true for the theme's default/global text style — the editor's \"Make Default Style\"); toggle it via `update_text_style`'s `is_default`. (5) Token NAMES are NOT unique — a theme can contain two tokens with the SAME name (e.g. colors pulled from two different design assets), so NEVER match a token by its human name. ALWAYS identify a token by its `id` (globally unique). IN COMPONENT CODE: prefer embedding the token's id-derived STABLE ref directly — color → cssVar `var(--<id>)`, typography → `className` `_<id>`, keyframe (animation-name) → `ref` `_<id>` — so you don't look anything up at runtime. If you DO need to pick a token out of a `getThemeColors()` / `getThemeTypography()` / `getThemeKeyframes()` / `getThemeColorSchemes()` array, match on `.id` (e.g. `getThemeColors().find(c => c.id === \"<id>\")`), NEVER on `.name`. EXCEPTION — global variables/settings: `getThemeSetting(name)` takes the token's `name`, but here `name` is the unique runtime key (`variableName`, the `_<id>` form returned in this list), which IS safe; do NOT pass a setting's human `displayName`. The update/delete tools also identify a token ONLY by `id` (they do NOT look up by name — on those tools `name` means the NEW name when renaming). Always take the `id` (or, for settings, the `name`/variableName) from THIS list. (6) GROUPING convention: a \"/\" in a token's NAME organizes it into a group in the editor UI — the text before the first \"/\" is the group, the rest is the item label. This applies to COLORS (e.g. \"Brand/Primary\"), TEXT STYLES (e.g. \"Heading/H1\"), and COLOR-SCHEME SLOTS (e.g. \"PrimaryButton/Background\"). When you create globals (via `create_theme_global`/`update_theme_color_scheme`), use \"/\"-prefixed names to keep related tokens grouped and tidy; reuse an existing group's exact prefix so they nest together. (7) ENUM settings: a setting with `type: \"ENUM\"` selects one option of a PROJECT enum and carries `enumTypeId` (the enum's id — the same one an ENUM prop declares as `enumTypeId`) and `options` (`{ label: value }`); its `value` is always one of those option VALUES (never a label), or null when unset. The response's top-level `enumTypes` array lists the project enums a new ENUM setting may select from (`{ id, name, options }`) — use an `id` from it as `enum_type_id` in `create_theme_global`. An ENUM prop can be bound (`bind_global`) only to an ENUM setting of the SAME enum.", {
4810
+ project_root: z
4811
+ .string()
4812
+ .describe("Absolute path to the code-component project (where `node_modules/.bin/ikas-component` lives)."),
4813
+ port: z
4814
+ .number()
4815
+ .optional()
4816
+ .describe("Dev server WebSocket port (default 5201)."),
4817
+ }, async ({ project_root, port }) => {
4818
+ const args = [
4819
+ "list-theme-globals",
4820
+ ...(port ? ["--port", String(port)] : []),
4821
+ ];
4822
+ return callEditorAction(project_root, args);
4823
+ });
4824
+ // Shared text-style (typography) font-property schema — kept in lock-step with the editor's
4825
+ // "Update Text Style" modal fields (no color/text-align, since that modal doesn't expose them).
4826
+ // Each enum prop documents its accepted values so a bad value is caught with a clear error. Spread
4827
+ // into both create_theme_global (typography) and update_text_style so the two never drift apart.
4828
+ const textStyleFontParams = {
4829
+ font_family: z
4830
+ .string()
4831
+ .optional()
4832
+ .describe('A real font family the editor offers — a Google Fonts name with EXACT casing (e.g. "Inter", "Roboto", ' +
4833
+ '"Poppins"), or a font already used by an existing text style in list_theme_globals. An unknown font ' +
4834
+ "(or wrong casing) is rejected; do NOT invent a family name."),
4835
+ font_size: z.string().optional(),
4836
+ font_weight: z
4837
+ .string()
4838
+ .optional()
4839
+ .describe("font-weight as a number (e.g. \"600\"); append 'i' for italic (e.g. \"600i\"). A PLAIN number with no 'i' " +
4840
+ "is upright and REMOVES italic if the text style was italic (italic is carried by the weight — re-send the " +
4841
+ "weight without 'i' to turn it off). Must be a weight the chosen " +
4842
+ 'font ships — if it isn\'t, the error lists the supported weights; when unsure use "400".'),
4843
+ line_height: z.string().optional(),
4844
+ letter_spacing: z.string().optional(),
4845
+ text_decoration: z
4846
+ .string()
4847
+ .optional()
4848
+ .describe("text-decoration: none | underline | line-through"),
4849
+ text_transform: z
4850
+ .string()
4851
+ .optional()
4852
+ .describe("text-transform: none | uppercase | lowercase | capitalize"),
4853
+ text_overflow: z
4854
+ .string()
4855
+ .optional()
4856
+ .describe("text-overflow: clip | ellipsis — ellipsis only truncates with white_space: nowrap and overflow: hidden in the component CSS"),
4857
+ white_space: z
4858
+ .string()
4859
+ .optional()
4860
+ .describe("white-space: normal | pre | pre-wrap | pre-line | wrap | nowrap | collapse"),
4861
+ line_break: z
4862
+ .string()
4863
+ .optional()
4864
+ .describe("line-break: auto | loose | normal | strict | anywhere"),
4865
+ word_break: z
4866
+ .string()
4867
+ .optional()
4868
+ .describe("word-break: normal | break-all | keep-all"),
4869
+ text_wrap_style: z
4870
+ .string()
4871
+ .optional()
4872
+ .describe("text-wrap-style: auto | balance | pretty | stable"),
4873
+ };
4874
+ // Turn the supplied text-style font params into `ikas-component` CLI flags (omitted ones dropped).
4875
+ // The editor validates each value and rejects an unsupported one with the offending value + allowed set.
4876
+ function textStyleFontArgs(input) {
4877
+ const map = {
4878
+ "--font-family": input.font_family,
4879
+ "--font-size": input.font_size,
4880
+ "--font-weight": input.font_weight,
4881
+ "--line-height": input.line_height,
4882
+ "--letter-spacing": input.letter_spacing,
4883
+ "--text-decoration": input.text_decoration,
4884
+ "--text-transform": input.text_transform,
4885
+ "--text-overflow": input.text_overflow,
4886
+ "--white-space": input.white_space,
4887
+ "--line-break": input.line_break,
4888
+ "--word-break": input.word_break,
4889
+ "--text-wrap-style": input.text_wrap_style,
4890
+ };
4891
+ // An empty string is passed through: with breakpoint_id it removes that override.
4892
+ return Object.entries(map).flatMap(([flag, value]) => value != null ? [flag, value] : []);
4893
+ }
4894
+ // Per-breakpoint text-style overrides in one call. `.strict()` so a non-responsive property
4895
+ // (e.g. text_transform) is rejected instead of silently dropped.
4896
+ const textStyleBreakpointsParam = z
4897
+ .array(z
4898
+ .object({
4899
+ breakpoint_id: z
4900
+ .string()
4901
+ .describe("Existing theme breakpoint id from `list_theme_globals`."),
4902
+ font_size: z.string().optional(),
4903
+ font_weight: z
4904
+ .string()
4905
+ .optional()
4906
+ .describe('Plain number, e.g. "500" (the style\'s italic is kept).'),
4907
+ line_height: z.string().optional(),
4908
+ letter_spacing: z.string().optional(),
4909
+ })
4910
+ .strict())
4911
+ .optional()
4912
+ .describe("RESPONSIVE overrides for several breakpoints in ONE call: [{ breakpoint_id, font_size?, font_weight?, " +
4913
+ "line_height?, letter_spacing? }]. Only these 4 properties, each needs a desktop value (set in this same " +
4914
+ 'call or earlier), "" removes an override. Validated as a whole: one invalid entry rejects the call and ' +
4915
+ "nothing is written. Breakpoints are not created here.");
4916
+ function textStyleBreakpointsArgs(breakpoints) {
4917
+ if (!breakpoints)
4918
+ return [];
4919
+ const json = breakpoints.map((bp) => ({
4920
+ breakpointId: bp.breakpoint_id,
4921
+ fontSize: bp.font_size,
4922
+ fontWeight: bp.font_weight,
4923
+ lineHeight: bp.line_height,
4924
+ letterSpacing: bp.letter_spacing,
4925
+ }));
4926
+ return ["--breakpoints", JSON.stringify(json)];
4927
+ }
4928
+ // Tool: create_theme_global
4929
+ server.tool("create_theme_global", "Create a theme global setting in the connected editor. `kind` selects what to create:\n" +
4930
+ '- globalVariable: requires display_name + type (TEXT|RICH_TEXT|IMAGE|COLOR|NUMBER|BOOLEAN|BORDER|SHADOW|ENUM); value optional. Pass `value` as a REAL JSON value, never a stringified JSON. Value shapes — TEXT/COLOR: string; RICH_TEXT: HTML string; NUMBER: number; BOOLEAN: real JSON boolean true/false (NOT the string "true"); IMAGE: an image REFERENCE object { id: "theme-images/<uuid>" } (NOT { url }) — the id MUST come from a REAL upload: call `upload_image` (file_path or image_url) and use the id it returns, or reuse an id already listed by `list_theme_globals`. NEVER invent an id — it is stored as given and renders as a broken image, so if you have no image, omit `value` and let the merchant set it from the "Theme Settings" panel; BORDER: { width: { value, unit }, style, color } (width.value must be a number); SHADOW: { x, y, blur, spread, color, position: "outside"|"inside" }; ENUM: a setting that selects ONE option of a PROJECT enum — pass `enum_type_id` (an enum id from `list_theme_globals` → `enumTypes[]`; the same enum an ENUM prop declares as `enumTypeId`; built-in @ikas/* enums are REJECTED) and `value` = one of that enum\'s option VALUES (the strings in its `options`, e.g. "bottom"), NOT a label; omit `value` to leave it unset. Once created, an ENUM prop of the SAME enum can be bound to it with `update_section_prop` `bind_global`, and in component code `themeValue("_<id>")` from `./global-types` narrows to the enum\'s union type. For object types (IMAGE/BORDER/SHADOW) pass an actual JSON object, not a JSON-encoded string. Every value is validated server-side and a wrong shape is REJECTED, not silently stored.\n' +
4931
+ '- color: requires name + value — a CONCRETE color (hex e.g. "#ff0000", rgb()/hsl() or a CSS color name). A color token cannot alias another color, so a "var(...)" reference is REJECTED here (to reuse another theme color, reference its cssVar in component code, or in a colorScheme slot). TIP: a "/" in the `name` GROUPS the color in the editor UI (e.g. "Brand/Primary", "Brand/Accent" appear under a "Brand" group); use this to organize related colors. To CHANGE an existing color later, use `update_theme_color` (edits in place, keeps the cssVar stable) — do NOT delete+recreate.\n' +
4932
+ '- typography: requires name + at least one text-style property. These are exactly the fields the editor\'s "Update Text Style" modal exposes — nothing else (in particular there is NO color or text-align on a text style). VALUE FORMATS (all validated; a bad value is rejected with the offending value and the allowed set): font_weight is one of 100,200,300,400,500,600,700,800,900 (append \'i\' for italic, e.g. "600i") AND must be a weight the chosen font actually ships (many fonts provide only a subset, e.g. "Modak" only ships 400) — if unavailable the call fails and lists the supported weights, so when unsure use 400; stored as a numeric weight + a font-style entry; font_size is a number WITH a unit (e.g. "16px", "1.2rem", "80%"); line_height is "normal", a unitless number (e.g. "1.5") or a length; letter_spacing is "normal" or a length (e.g. "0.02em", "0.5px"); font_family is a real font the editor offers (a Google Fonts name with EXACT casing, e.g. "Inter") — an unknown/invented family is rejected; text_decoration is none|underline|line-through; text_transform is none|uppercase|lowercase|capitalize; text_overflow is clip|ellipsis; white_space is normal|pre|pre-wrap|pre-line|wrap|nowrap|collapse; line_break is auto|loose|normal|strict|anywhere; word_break is normal|break-all|keep-all; text_wrap_style is auto|balance|pretty|stable. TIP: a "/" in the `name` GROUPS the text style in the editor UI (e.g. "Heading/H1", "Heading/H2" appear under a "Heading" group); use this to organize related styles. Optional `breakpoints` sets responsive overrides in the same call (see the param). To CHANGE an existing text style later, use `update_text_style` (edits in place, keeps the `className` stable) — do NOT delete+recreate, which changes the id/className.\n' +
4933
+ "- breakpoint: requires name + width (a positive INTEGER, in px — no decimals). To CHANGE an existing breakpoint later, use `update_theme_breakpoint` (edits in place, keeps the id).\n" +
4934
+ "- keyframe: requires name + points (array of { point, styles? }) where each style is { property, value } using a CSS property name (opacity, transform, filter, background, color, …); keyframe_type defaults to \"keyframe\". Optional `settings` = animation-level config as { property, value } entries, TYPE-DEPENDENT: for keyframe — animation-duration, animation-iteration-count, animation-play-state, animation-delay, animation-timing-function, animation-direction, animation-fill-mode, animation-timeline, animation-range, transform-origin, backface-visibility; for transition — transition, backface-visibility. Setting these means the editor drives the animation timing (you don't have to hand-write `animation:` CSS). Use the keyframe's `ref` as the CSS animation-name. For a TRANSITION keyframe, put the target/hover-state styles on the 100% point (points[1].styles) — the 0% point is ignored (the start state is the element's own normal state). To CHANGE an existing keyframe later, use `update_theme_keyframe` (edits in place, keeps the `ref` stable) — do NOT delete+recreate, which changes the ref and breaks references.\n" +
4935
+ '- colorScheme: requires name + colors (array of { slotId? | newSlotName?, value }) — each color targets ONE color SLOT, EITHER by `slotId` (an EXISTING slot\'s id, from `list_theme_globals` → colorSchemes.schemes[].id or a `colorsByScheme` key — the id-keyed path) OR by `newSlotName` (a name to CREATE-or-reuse a slot; write-only, for the standard vocabulary and brand-new slots). Pass EXACTLY ONE of the two per entry. `value` is EITHER a literal color (hex/rgb/hsl or a CSS color name, e.g. "#0b1120") OR a REFERENCE to an existing theme color, passed as that color\'s cssVar from `list_theme_globals` (e.g. "var(--<colorId>)"). A `var(--id)` value is stored as a linked reference (editing the global color updates the scheme too and the dependency is tracked) — do NOT inline a hex you copied from a global color; pass its cssVar. SLOT IDENTITY: `colorSchemes.schemes` lists each slot as `{id, name}`. To set a color on an EXISTING slot, find it there by name and pass its `slotId` (names are NOT unique — two design assets can each have a "Background" — so when ambiguous disambiguate via the scheme\'s existing `colorsByScheme` keys); use `newSlotName` only to add a slot the scheme does not have yet. When creating slots use the theme\'s STANDARD slot names so components resolve them: "Background", "Heading", "Text", "Link", "HoverLink", "Border", and per button "PrimaryButton/Background", "PrimaryButton/Text", "PrimaryButton/Border", "PrimaryButton/HoverBackground", "PrimaryButton/HoverText", "PrimaryButton/HoverBorder" (and the same six under "SecondaryButton/"); a "/" groups the slot in the editor UI. A scheme should normally define EVERY slot it uses; omitted slots fall back to the default scheme\'s color. A mistaken slot can be removed with `delete_theme_global` kind `colorSchemeSlot` (by slot id), or renamed in place (id stays stable) with `rename_theme_color_scheme_slot`. To CHANGE an existing scheme later, use `update_theme_color_scheme` (edits in place, keeps the className stable; merges colors by slot, and can set/clear its default flag via `is_default`).\n' +
4936
+ "Read created items back with `list_theme_globals`. Requires `ikas theme dev` running with the editor connected.", {
4937
+ project_root: z
4938
+ .string()
4939
+ .describe("Absolute path to the code-component project."),
4940
+ kind: z
4941
+ .enum([
4942
+ "globalVariable",
4943
+ "color",
4944
+ "typography",
4945
+ "breakpoint",
4946
+ "keyframe",
4947
+ "colorScheme",
4948
+ ])
4949
+ .describe("What to create."),
4950
+ name: z.string().optional().describe("Name (design tokens)."),
4951
+ display_name: z
4952
+ .string()
4953
+ .optional()
4954
+ .describe("Human label (globalVariable)."),
4955
+ type: z.string().optional().describe("globalVariable value type."),
4956
+ value: z
4957
+ .any()
4958
+ .optional()
4959
+ .describe("globalVariable default value (shape depends on type — see tool description), or color hex string."),
4960
+ enum_type_id: z
4961
+ .string()
4962
+ .optional()
4963
+ .describe("globalVariable of type ENUM only: id of the project enum the setting selects from (from `list_theme_globals` → `enumTypes[]`). Required for ENUM, invalid for other types."),
4964
+ ...textStyleFontParams,
4965
+ breakpoints: textStyleBreakpointsParam.describe("typography only: " + textStyleBreakpointsParam.description),
4966
+ width: z
4967
+ .number()
4968
+ .int()
4969
+ .optional()
4970
+ .describe("breakpoint width in px (positive integer, no decimals)."),
4971
+ keyframe_type: z.enum(["keyframe", "transition"]).optional(),
4972
+ points: z.any().optional().describe("keyframe points array."),
4973
+ settings: z
4974
+ .any()
4975
+ .optional()
4976
+ .describe("keyframe animation settings: array of { property, value } (type-dependent — see tool description)."),
4977
+ colors: z
4978
+ .any()
4979
+ .optional()
4980
+ .describe('colorScheme colors: array of { slotId? | newSlotName?, value } — target an EXISTING slot by `slotId` (its id from list_theme_globals → colorSchemes.schemes / colorsByScheme keys) OR create/reuse one by `newSlotName` (use the standard slot names, "/" to group, e.g. "PrimaryButton/Background"). Exactly one per entry. value = a literal color hex/rgb/hsl/name, OR an existing theme color\'s cssVar "var(--<colorId>)" to store a linked reference.'),
4981
+ port: z
4982
+ .number()
4983
+ .optional()
4984
+ .describe("Dev server WebSocket port (default 5201)."),
4985
+ }, async (input) => {
4986
+ const p = input.port ? ["--port", String(input.port)] : [];
4987
+ let args;
4988
+ switch (input.kind) {
4989
+ case "globalVariable":
4990
+ args = [
4991
+ "create-global-variable",
4992
+ "--display-name",
4993
+ String(input.display_name ?? ""),
4994
+ "--type",
4995
+ String(input.type ?? ""),
4996
+ ...(input.value !== undefined
4997
+ ? ["--value", JSON.stringify(input.value)]
4998
+ : []),
4999
+ ...(input.enum_type_id
5000
+ ? ["--enum-type-id", String(input.enum_type_id)]
5001
+ : []),
5002
+ ...p,
5003
+ ];
5004
+ break;
5005
+ case "color":
5006
+ args = [
5007
+ "create-color",
5008
+ "--name",
5009
+ String(input.name ?? ""),
5010
+ "--value",
5011
+ String(input.value ?? ""),
5012
+ ...p,
5013
+ ];
5014
+ break;
5015
+ case "typography":
5016
+ args = [
5017
+ "create-text-style",
5018
+ "--name",
5019
+ String(input.name ?? ""),
5020
+ ...textStyleFontArgs(input),
5021
+ ...textStyleBreakpointsArgs(input.breakpoints),
5022
+ ...p,
5023
+ ];
5024
+ break;
5025
+ case "breakpoint":
5026
+ args = [
5027
+ "create-breakpoint",
5028
+ "--name",
5029
+ String(input.name ?? ""),
5030
+ "--width",
5031
+ String(input.width ?? ""),
5032
+ ...p,
5033
+ ];
5034
+ break;
5035
+ case "keyframe":
5036
+ args = [
5037
+ "create-keyframe",
5038
+ "--name",
5039
+ String(input.name ?? ""),
5040
+ ...(input.keyframe_type ? ["--type", input.keyframe_type] : []),
5041
+ "--points",
5042
+ toJsonArrayArg(input.points),
5043
+ ...(input.settings !== undefined
5044
+ ? ["--settings", toJsonArrayArg(input.settings)]
5045
+ : []),
5046
+ ...p,
5047
+ ];
5048
+ break;
5049
+ case "colorScheme":
5050
+ args = [
5051
+ "create-color-scheme",
5052
+ "--name",
5053
+ String(input.name ?? ""),
5054
+ "--colors",
5055
+ toJsonArrayArg(input.colors),
5056
+ ...p,
5057
+ ];
5058
+ break;
5059
+ default:
5060
+ return {
5061
+ content: [
5062
+ {
5063
+ type: "text",
5064
+ text: `Error: unknown kind "${input.kind}"`,
5065
+ },
5066
+ ],
5067
+ };
5068
+ }
5069
+ return callEditorAction(input.project_root, args);
5070
+ });
5071
+ // Tool: update_theme_global
5072
+ server.tool("update_theme_global", "Update an existing global variable in the connected editor (e.g. fix its value or change its type). Identify it by `name` (the runtime key from `list_theme_globals`). Only the fields you pass are changed. Value shapes follow `create_theme_global` — pass `value` as REAL JSON (objects/booleans, never stringified); BOOLEAN is a real boolean, BORDER/SHADOW are real objects; IMAGE is an image REFERENCE object { id: \"theme-images/<uuid>\" } whose id MUST come from `upload_image` or an existing `list_theme_globals` entry — an invented id renders as a broken image; ENUM `value` is one of the enum's option VALUES (see the setting's `options` in `list_theme_globals`), and `enum_type_id` re-points the setting at another project enum. Changing `type` or `enum_type_id` of a global that props are bound to is REJECTED (the error names the places) — unbind those props first. Values are validated server-side; a wrong shape is REJECTED, not silently stored.", {
5073
+ project_root: z
5074
+ .string()
5075
+ .describe("Absolute path to the code-component project."),
5076
+ name: z
5077
+ .string()
5078
+ .describe("The variable's runtime key (from `list_theme_globals`)."),
5079
+ display_name: z.string().optional().describe("New label."),
5080
+ type: z
5081
+ .string()
5082
+ .optional()
5083
+ .describe("New value type (TEXT|RICH_TEXT|IMAGE|COLOR|NUMBER|BOOLEAN|BORDER|SHADOW|ENUM)."),
5084
+ value: z
5085
+ .any()
5086
+ .optional()
5087
+ .describe('New value as REAL JSON (shape depends on type; e.g. BOOLEAN: true/false, NUMBER: 12, IMAGE: { id: "theme-images/<uuid>" } from upload_image, ENUM: an option VALUE string — see create_theme_global). An invented IMAGE id renders as a broken image.'),
5088
+ enum_type_id: z
5089
+ .string()
5090
+ .optional()
5091
+ .describe('ENUM only: the project enum to select from (from `list_theme_globals` → `enumTypes[]`); may be passed alone to re-point an unbound ENUM global, or together with `type: "ENUM"`.'),
5092
+ port: z
5093
+ .number()
5094
+ .optional()
5095
+ .describe("Dev server WebSocket port (default 5201)."),
5096
+ }, async ({ project_root, name, display_name, type, value, enum_type_id, port, }) => {
5097
+ const args = [
5098
+ "update-global-variable",
5099
+ "--name",
5100
+ name,
5101
+ ...(display_name !== undefined ? ["--display-name", display_name] : []),
5102
+ ...(type !== undefined ? ["--type", type] : []),
5103
+ ...(value !== undefined ? ["--value", JSON.stringify(value)] : []),
5104
+ ...(enum_type_id !== undefined ? ["--enum-type-id", enum_type_id] : []),
5105
+ ...(port ? ["--port", String(port)] : []),
5106
+ ];
5107
+ return callEditorAction(project_root, args);
5108
+ });
5109
+ // Tool: update_theme_keyframe
5110
+ server.tool("update_theme_keyframe", "Update an existing theme keyframe IN PLACE in the connected editor. Prefer this over delete+recreate: " +
5111
+ "it keeps the keyframe's id, so its runtime `ref` (the CSS animation-name `_<id>`) stays STABLE and every " +
5112
+ "existing reference to it keeps working. Identify the keyframe by `id` (REQUIRED — globally unique, from " +
5113
+ "`list_theme_globals`); name-based lookup is intentionally NOT supported here because names can collide across " +
5114
+ "design assets. To rename, pass `name` (the new name) together with `id`. " +
5115
+ "`points` REPLACES the keyframe's points: an array of { point, styles? } where `point` is a CSS " +
5116
+ 'keyframe offset (e.g. "0%", "50%", "100%") and each style is { property, value } using a CSS property ' +
5117
+ "name (opacity, transform, filter, background, color, …). Pass `points` as REAL JSON (not a stringified array). " +
5118
+ "For a TRANSITION keyframe, put the target/hover-state styles on the 100% point (points[1].styles) — the 0% " +
5119
+ "point is ignored (the start state is the element's own normal state). " +
5120
+ "Optional `settings` REPLACES the keyframe's animation settings (type-dependent { property, value } entries — " +
5121
+ "see `create_theme_global`); OMIT it to keep the existing settings, or pass [] to clear them. " +
5122
+ "Requires `ikas theme dev` running with the editor connected.", {
5123
+ project_root: z
5124
+ .string()
5125
+ .describe("Absolute path to the code-component project."),
5126
+ id: z
5127
+ .string()
5128
+ .describe("Keyframe id (REQUIRED) from `list_theme_globals`. The token is always identified by id."),
5129
+ name: z
5130
+ .string()
5131
+ .optional()
5132
+ .describe("Optional NEW name to rename the keyframe to. NOT used to find the token — lookup is always by id."),
5133
+ keyframe_type: z
5134
+ .enum(["keyframe", "transition"])
5135
+ .optional()
5136
+ .describe("Optional new keyframe type."),
5137
+ points: z
5138
+ .any()
5139
+ .describe("New keyframe points array of { point, styles? } — REPLACES the existing points."),
5140
+ settings: z
5141
+ .any()
5142
+ .optional()
5143
+ .describe("New animation settings { property, value } array (type-dependent — see create_theme_global). Omit to keep existing; [] to clear."),
5144
+ port: z
5145
+ .number()
5146
+ .optional()
5147
+ .describe("Dev server WebSocket port (default 5201)."),
5148
+ }, async ({ project_root, id, name, keyframe_type, points, settings, port }) => {
5149
+ const args = [
5150
+ "update-keyframe",
5151
+ "--id",
5152
+ id,
5153
+ ...(name !== undefined ? ["--name", name] : []),
5154
+ ...(keyframe_type ? ["--type", keyframe_type] : []),
5155
+ "--points",
5156
+ toJsonArrayArg(points),
5157
+ ...(settings !== undefined
5158
+ ? ["--settings", toJsonArrayArg(settings)]
5159
+ : []),
5160
+ ...(port ? ["--port", String(port)] : []),
5161
+ ];
5162
+ return callEditorAction(project_root, args);
5163
+ });
5164
+ // Tool: update_text_style
5165
+ server.tool("update_text_style", "Update an existing theme typography token (text style) IN PLACE in the connected editor. Prefer this over " +
5166
+ "delete+recreate: it keeps the text style's id, so its `className` (`_<id>`) — and every section bound to it — " +
5167
+ "stays STABLE. Identify the text style by `id` (REQUIRED — globally unique, from `list_theme_globals`); " +
5168
+ "name-based lookup is intentionally NOT supported here because names can collide across design assets. " +
5169
+ "To rename, pass `name` (the new name) together with `id`. Pass only the properties you want to change; omitted " +
5170
+ 'ones keep their existing values. The settable properties are exactly the editor\'s "Update Text Style" modal ' +
5171
+ "fields — there is NO color or text-align on a text style. VALUE FORMATS (all validated; a bad value is rejected " +
5172
+ "with the offending value and the allowed set): font_weight is one of 100…900 (append 'i' for italic, e.g. " +
5173
+ '"600i") AND must be a weight the chosen font actually ships — many fonts only provide a subset (e.g. "Modak" ' +
5174
+ "only ships 400); if a weight isn't available the call fails and the error lists the supported weights, so when " +
5175
+ 'unsure use 400; font_size is a number with a unit (e.g. "16px"); line_height is "normal", a unitless number ' +
5176
+ 'or a length; letter_spacing is "normal" or a length (e.g. "0.02em"); font_family is a real font the editor ' +
5177
+ 'offers (a Google Fonts name with EXACT casing, e.g. "Inter") — an unknown/invented family is rejected; ' +
5178
+ "text_decoration is none|underline|" +
5179
+ "line-through; text_transform is none|uppercase|lowercase|capitalize; text_overflow is clip|ellipsis (ellipsis also needs white_space: nowrap here and overflow: hidden in the component CSS); white_space " +
5180
+ "is normal|pre|pre-wrap|pre-line|wrap|nowrap|collapse; line_break is auto|loose|normal|strict|anywhere; word_break " +
5181
+ "is normal|break-all|keep-all; text_wrap_style is auto|balance|pretty|stable. Set `is_default: true` to make " +
5182
+ 'this text style the theme\'s default/global style (the editor\'s right-click "Make Default Style" / "Global ' +
5183
+ "Stil Yap\") — any other default in the group is cleared; `is_default: false` removes the flag. A text style's " +
5184
+ "current default state is readable from `list_theme_globals` (each typography entry's `isDefault`). " +
5185
+ "RESPONSIVE: pass `breakpoint_id` (an existing breakpoint id from `list_theme_globals`) to set that breakpoint's " +
5186
+ "overrides instead of the desktop values. Then ONLY font_size, font_weight, line_height and letter_spacing are " +
5187
+ "allowed, each needs a desktop value on the style first, font_weight is a plain number (the style's italic is kept — italic is " +
5188
+ 'shared by all breakpoints) and an empty string ("") removes that override so the value is inherited again. Overrides cascade ' +
5189
+ "desktop-first and chained: a property a breakpoint does not override comes from the nearest WIDER breakpoint that overrides it, else desktop; `list_theme_globals` returns them per typography " +
5190
+ "entry under `breakpoints` (`overrides` = own values, `resolved` = effective values). Breakpoints are NOT created " +
5191
+ "by this tool. To write SEVERAL breakpoints (optionally together with desktop values) in one call, use " +
5192
+ "`breakpoints` instead of `breakpoint_id`. Requires " +
5193
+ "`ikas theme dev` running with the editor connected.", {
5194
+ project_root: z
5195
+ .string()
5196
+ .describe("Absolute path to the code-component project."),
5197
+ id: z
5198
+ .string()
5199
+ .describe("Text style id (REQUIRED) from `list_theme_globals`. The token is always identified by id."),
5200
+ name: z
5201
+ .string()
5202
+ .optional()
5203
+ .describe("Optional NEW name to rename the text style to. NOT used to find the token — lookup is always by id."),
5204
+ ...textStyleFontParams,
5205
+ is_default: z
5206
+ .boolean()
5207
+ .optional()
5208
+ .describe("true → make this the theme's default/global text style (clears any other default); false → remove the " +
5209
+ "default flag. Omit to leave the default state unchanged."),
5210
+ breakpoint_id: z
5211
+ .string()
5212
+ .optional()
5213
+ .describe("Existing theme breakpoint id from `list_theme_globals`. When set, the font params are written as that " +
5214
+ 'breakpoint\'s overrides (font_size/font_weight/line_height/letter_spacing only; "" removes one).'),
5215
+ breakpoints: textStyleBreakpointsParam,
5216
+ port: z
5217
+ .number()
5218
+ .optional()
5219
+ .describe("Dev server WebSocket port (default 5201)."),
5220
+ }, async (input) => {
5221
+ const { project_root, id, name, is_default, breakpoint_id, breakpoints, port, } = input;
5222
+ const args = [
5223
+ "update-text-style",
5224
+ "--id",
5225
+ id,
5226
+ ...(breakpoint_id !== undefined ? ["--breakpoint", breakpoint_id] : []),
5227
+ ...(name !== undefined ? ["--name", name] : []),
5228
+ ...textStyleFontArgs(input),
5229
+ ...textStyleBreakpointsArgs(breakpoints),
5230
+ ...(is_default === true
5231
+ ? ["--default"]
5232
+ : is_default === false
5233
+ ? ["--no-default"]
5234
+ : []),
5235
+ ...(port ? ["--port", String(port)] : []),
5236
+ ];
5237
+ return callEditorAction(project_root, args);
5238
+ });
5239
+ // Tool: update_theme_color
5240
+ server.tool("update_theme_color", "Update an existing theme color token IN PLACE in the connected editor. Prefer this over delete+recreate: " +
5241
+ "it keeps the color's id, so its cssVar (`var(--<id>)`) — and every element style bound to it — stays STABLE. " +
5242
+ "Identify it by `id` (REQUIRED — globally unique, from `list_theme_globals`); name-based lookup is intentionally " +
5243
+ "NOT supported here because a theme can have two colors with the same name (e.g. from two different design assets). " +
5244
+ "To rename, pass `name` (the new name) together with `id`. Pass `value` to change the color — a CONCRETE " +
5245
+ 'color (hex/rgb/hsl or a CSS color name), NOT a "var(...)" reference (a color token can\'t alias another ' +
5246
+ "color); omit it to only rename. Requires `ikas-component " +
5247
+ "dev` running with the editor connected.", {
5248
+ project_root: z
5249
+ .string()
5250
+ .describe("Absolute path to the code-component project."),
5251
+ id: z
5252
+ .string()
5253
+ .describe("Color id (REQUIRED) from `list_theme_globals`. The token is always identified by id."),
5254
+ name: z
5255
+ .string()
5256
+ .optional()
5257
+ .describe("Optional NEW name to rename the color to. NOT used to find the token — lookup is always by id."),
5258
+ value: z
5259
+ .string()
5260
+ .optional()
5261
+ .describe('New color value — a concrete color (e.g. "#ff0000", rgb/hsl/name), not a "var(...)" reference. Omit to only rename.'),
5262
+ port: z
5263
+ .number()
5264
+ .optional()
5265
+ .describe("Dev server WebSocket port (default 5201)."),
5266
+ }, async ({ project_root, id, name, value, port }) => {
5267
+ const args = [
5268
+ "update-color",
5269
+ "--id",
5270
+ id,
5271
+ ...(name !== undefined ? ["--name", name] : []),
5272
+ ...(value !== undefined ? ["--value", value] : []),
5273
+ ...(port ? ["--port", String(port)] : []),
5274
+ ];
5275
+ return callEditorAction(project_root, args);
5276
+ });
5277
+ // Tool: update_theme_breakpoint
5278
+ server.tool("update_theme_breakpoint", "Update an existing theme breakpoint IN PLACE in the connected editor (keeps its id). Identify it by `id` " +
5279
+ "(REQUIRED — globally unique, from `list_theme_globals`); name-based lookup is intentionally NOT supported here " +
5280
+ "because names can collide across design assets. To rename, pass `name` (the new name) together with `id`. " +
5281
+ "Pass `width` (px) to change it; omit it to only rename. " +
5282
+ "Requires `ikas theme dev` running with the editor connected.", {
5283
+ project_root: z
5284
+ .string()
5285
+ .describe("Absolute path to the code-component project."),
5286
+ id: z
5287
+ .string()
5288
+ .describe("Breakpoint id (REQUIRED) from `list_theme_globals`. The token is always identified by id."),
5289
+ name: z
5290
+ .string()
5291
+ .optional()
5292
+ .describe("Optional NEW name to rename the breakpoint to. NOT used to find the token — lookup is always by id."),
5293
+ width: z
5294
+ .number()
5295
+ .int()
5296
+ .optional()
5297
+ .describe("New breakpoint width in px (positive integer, no decimals). Omit to only rename."),
5298
+ port: z
5299
+ .number()
5300
+ .optional()
5301
+ .describe("Dev server WebSocket port (default 5201)."),
5302
+ }, async ({ project_root, id, name, width, port }) => {
5303
+ const args = [
5304
+ "update-breakpoint",
5305
+ "--id",
5306
+ id,
5307
+ ...(name !== undefined ? ["--name", name] : []),
5308
+ ...(width !== undefined ? ["--width", String(width)] : []),
5309
+ ...(port ? ["--port", String(port)] : []),
5310
+ ];
5311
+ return callEditorAction(project_root, args);
5312
+ });
5313
+ // Tool: update_theme_color_scheme
5314
+ server.tool("update_theme_color_scheme", "Update an existing theme color scheme (palette) IN PLACE in the connected editor. Prefer this over " +
5315
+ "delete+recreate: it keeps the scheme's id, so its className (`_<id>`) stays STABLE. Identify it by `id` " +
5316
+ "(REQUIRED — globally unique, from `list_theme_globals`); name-based lookup is intentionally NOT supported here " +
5317
+ "because names can collide across design assets. To rename, pass `name` (the new name) together with `id`. " +
5318
+ "`colors` is an array of { slotId? | newSlotName?, value } — each entry targets ONE slot, EITHER by " +
5319
+ "`slotId` (an EXISTING slot's id, from list_theme_globals colorsByScheme keys / colorSchemes.schemes — the " +
5320
+ "id-keyed path; slot names ARE listed in colorSchemes.schemes but are not unique, so prefer the scheme's colorsByScheme keys to get the right id) OR by `newSlotName` (create/reuse " +
5321
+ 'a slot by name; use the standard slot names, "/" to group, e.g. "PrimaryButton/Background"); value = a ' +
5322
+ 'literal color hex/rgb/hsl/name, OR an existing theme color\'s cssVar "var(--<colorId>)" from ' +
5323
+ "list_theme_globals to store it as a LINKED reference — pass the cssVar, not a hex copied from a global color) " +
5324
+ "and MERGES by slot — only the slots you pass change. Pass `colors` as REAL " +
5325
+ "JSON (not a stringified array). Set `is_default: true` to make this the theme's DEFAULT scheme (the " +
5326
+ "fallback whose colors fill any slot a non-default scheme leaves unset); this is exclusive — the editor " +
5327
+ "automatically clears the default flag from any other scheme in the same group, so there is always exactly " +
5328
+ "one default. Set `is_default: false` to remove the default flag from this scheme. Omit all of name/colors/" +
5329
+ "is_default to no-op. Requires `ikas theme dev` running with the editor connected.", {
5330
+ project_root: z
5331
+ .string()
5332
+ .describe("Absolute path to the code-component project."),
5333
+ id: z
5334
+ .string()
5335
+ .describe("Color scheme id (REQUIRED) from `list_theme_globals`. The token is always identified by id."),
5336
+ name: z
5337
+ .string()
5338
+ .optional()
5339
+ .describe("Optional NEW name to rename the color scheme to. NOT used to find the token — lookup is always by id."),
5340
+ colors: z
5341
+ .any()
5342
+ .optional()
5343
+ .describe('Array of { slotId? | newSlotName?, value } to set — target an existing slot by `slotId` (from list_theme_globals colorsByScheme keys / colorSchemes.schemes) or create/reuse by `newSlotName`; value = a literal color hex/rgb/hsl/name, OR an existing theme color\'s cssVar "var(--<colorId>)" (linked reference). Merges by slot. Omit to only rename.'),
5344
+ is_default: z
5345
+ .boolean()
5346
+ .optional()
5347
+ .describe("true = make this the default scheme (exclusive — the editor clears the default flag from every other scheme in its group); false = remove the default flag. Omit to leave the default unchanged. The result echoes the persisted `isDefault`."),
5348
+ port: z
5349
+ .number()
5350
+ .optional()
5351
+ .describe("Dev server WebSocket port (default 5201)."),
5352
+ }, async ({ project_root, id, name, colors, is_default, port }) => {
5353
+ const args = [
5354
+ "update-color-scheme",
5355
+ "--id",
5356
+ id,
5357
+ ...(name !== undefined ? ["--name", name] : []),
5358
+ ...(colors !== undefined ? ["--colors", toJsonArrayArg(colors)] : []),
5359
+ ...(is_default === true
5360
+ ? ["--default"]
5361
+ : is_default === false
5362
+ ? ["--no-default"]
5363
+ : []),
5364
+ ...(port ? ["--port", String(port)] : []),
5365
+ ];
5366
+ return callEditorAction(project_root, args);
5367
+ });
5368
+ // Tool: rename_theme_color_scheme_slot
5369
+ server.tool("rename_theme_color_scheme_slot", 'Rename a color scheme SLOT (a scheme key like "Background" or "PrimaryButton/Text") IN PLACE in the ' +
5370
+ "connected editor. A slot's id is STABLE, so renaming keeps every runtime reference intact " +
5371
+ "(`var(--<slotId>)` in CSS, `colorsByScheme[slotId]` in component code) — only the human display name " +
5372
+ "changes; nothing rebinds. Identify the slot by `id` (REQUIRED — the slot id from `list_theme_globals` → " +
5373
+ "colorSchemes.schemes[].id or a `colorsByScheme` key); name-based lookup is intentionally NOT supported " +
5374
+ 'because slot names can collide across design assets. `name` is the NEW slot name (a "/" groups it in the ' +
5375
+ 'editor UI, e.g. "PrimaryButton/Background"). Only non-design-asset (user/theme) slots can be renamed here. ' +
5376
+ "This renames the slot itself across ALL schemes that use it (a slot is shared) — it does NOT rename a single " +
5377
+ "scheme/palette (for that use `update_theme_color_scheme`). Requires `ikas theme dev` running with the " +
5378
+ "editor connected.", {
5379
+ project_root: z
5380
+ .string()
5381
+ .describe("Absolute path to the code-component project."),
5382
+ id: z
5383
+ .string()
5384
+ .min(1, "id is REQUIRED — the slot id from list_theme_globals (colorSchemes.schemes[].id / colorsByScheme keys).")
5385
+ .describe("Slot id (REQUIRED) from `list_theme_globals` → colorSchemes.schemes[].id / colorsByScheme keys. The slot is always identified by id."),
5386
+ name: z
5387
+ .string()
5388
+ .min(1, "name is REQUIRED — the new slot name (non-empty).")
5389
+ .describe('The NEW slot name (non-empty). A "/" groups it in the editor UI (e.g. "PrimaryButton/Background").'),
5390
+ port: z
5391
+ .number()
5392
+ .optional()
5393
+ .describe("Dev server WebSocket port (default 5201)."),
5394
+ }, async ({ project_root, id, name, port }) => {
5395
+ const args = [
5396
+ "rename-color-scheme-slot",
5397
+ "--id",
5398
+ id,
5399
+ "--name",
5400
+ name,
5401
+ ...(port ? ["--port", String(port)] : []),
5402
+ ];
5403
+ return callEditorAction(project_root, args);
5404
+ });
5405
+ // Tool: delete_theme_global
5406
+ server.tool("delete_theme_global", 'Delete a theme global setting from the connected editor. For `kind: globalVariable` pass `name` (the runtime key); for design-token kinds (color | typography | breakpoint | keyframe | colorScheme) pass the token `id`. For `kind: colorSchemeSlot` pass the color SLOT id (from `list_theme_globals` → colorSchemes.schemes[].id or a `colorsByScheme` key) — this deletes the slot itself across ALL schemes (use it to clean up a junk slot created by a typo); it CASCADES: the slot\'s color is removed from every scheme and any element/component style bound to that slot is cleared, so only delete a slot you are sure is unused. Only non-design-asset (user/theme) slots can be deleted here. Get names/ids from `list_theme_globals`. Deleting a non-existent id fails with a "not found" error (it does NOT report a false success), so a success result means the token really existed and was removed.', {
5407
+ project_root: z
5408
+ .string()
5409
+ .describe("Absolute path to the code-component project."),
5410
+ kind: z
5411
+ .enum([
5412
+ "globalVariable",
5413
+ "color",
5414
+ "typography",
5415
+ "breakpoint",
5416
+ "keyframe",
5417
+ "colorScheme",
5418
+ "colorSchemeSlot",
5419
+ ])
5420
+ .describe("What to delete."),
5421
+ name: z
5422
+ .string()
5423
+ .optional()
5424
+ .describe("globalVariable runtime key (from `list_theme_globals`)."),
5425
+ id: z
5426
+ .string()
5427
+ .optional()
5428
+ .describe("design-token id, or for colorSchemeSlot the slot id from `list_theme_globals` → colorSchemes.schemes."),
5429
+ confirm: z.boolean().describe(CONFIRM_PARAM_DESCRIPTION),
5430
+ port: z
5431
+ .number()
5432
+ .optional()
5433
+ .describe("Dev server WebSocket port (default 5201)."),
5434
+ }, async ({ project_root, kind, name, id, confirm, port }) => {
5435
+ if (confirm !== true)
5436
+ return destructiveConfirmRefusal();
5437
+ const p = [...(port ? ["--port", String(port)] : []), "--yes"];
5438
+ const args = kind === "globalVariable"
5439
+ ? ["delete-global-variable", "--name", String(name ?? ""), ...p]
5440
+ : [
5441
+ "delete-design-token",
5442
+ "--token-type",
5443
+ kind,
5444
+ "--id",
5445
+ String(id ?? ""),
5446
+ ...p,
5447
+ ];
5448
+ return callEditorAction(project_root, args);
5449
+ });
5450
+ // --- Start server ---
5451
+ /**
5452
+ * Every tool's arguments are checked strictly: an unknown argument (a typo, an invented field) is an error the
5453
+ * agent sees, not one dropped in silence while the call goes on without it.
5454
+ */
5455
+ function makeToolArgumentsStrict() {
5456
+ // The SDK builds a lenient object from each tool's fields; the same fields make the strict one (nested
5457
+ // objects are declared with `z.strictObject`).
5458
+ const tools = server._registeredTools;
5459
+ for (const tool of Object.values(tools)) {
5460
+ const shape = tool.inputSchema?.shape ?? tool.inputSchema?._zod?.def?.shape;
5461
+ if (shape)
5462
+ tool.inputSchema = z.strictObject(shape);
5463
+ }
5464
+ }
3145
5465
  async function main() {
5466
+ makeToolArgumentsStrict();
3146
5467
  const transport = new StdioServerTransport();
3147
5468
  await server.connect(transport);
3148
5469
  }