@ikas/component-cli 1.4.0-beta.21 → 1.4.0-beta.210

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 (176) hide show
  1. package/dist/build-tools.d.ts +37 -0
  2. package/dist/build-tools.d.ts.map +1 -0
  3. package/dist/build-tools.js +36 -0
  4. package/dist/build-tools.js.map +1 -0
  5. package/dist/commands/add-sections-to-page.d.ts +3 -0
  6. package/dist/commands/add-sections-to-page.d.ts.map +1 -0
  7. package/dist/commands/add-sections-to-page.js +39 -0
  8. package/dist/commands/add-sections-to-page.js.map +1 -0
  9. package/dist/commands/add.d.ts.map +1 -1
  10. package/dist/commands/add.js +11 -2
  11. package/dist/commands/add.js.map +1 -1
  12. package/dist/commands/build.d.ts.map +1 -1
  13. package/dist/commands/build.js +5 -165
  14. package/dist/commands/build.js.map +1 -1
  15. package/dist/commands/config.d.ts +35 -0
  16. package/dist/commands/config.d.ts.map +1 -1
  17. package/dist/commands/config.js +1082 -147
  18. package/dist/commands/config.js.map +1 -1
  19. package/dist/commands/create-design-tokens.d.ts +24 -0
  20. package/dist/commands/create-design-tokens.d.ts.map +1 -0
  21. package/dist/commands/create-design-tokens.js +334 -0
  22. package/dist/commands/create-design-tokens.js.map +1 -0
  23. package/dist/commands/create-global-variable.d.ts +3 -0
  24. package/dist/commands/create-global-variable.d.ts.map +1 -0
  25. package/dist/commands/create-global-variable.js +73 -0
  26. package/dist/commands/create-global-variable.js.map +1 -0
  27. package/dist/commands/create-page.d.ts +3 -0
  28. package/dist/commands/create-page.d.ts.map +1 -0
  29. package/dist/commands/create-page.js +31 -0
  30. package/dist/commands/create-page.js.map +1 -0
  31. package/dist/commands/delete-page.d.ts +3 -0
  32. package/dist/commands/delete-page.d.ts.map +1 -0
  33. package/dist/commands/delete-page.js +28 -0
  34. package/dist/commands/delete-page.js.map +1 -0
  35. package/dist/commands/delete-theme-globals.d.ts +4 -0
  36. package/dist/commands/delete-theme-globals.d.ts.map +1 -0
  37. package/dist/commands/delete-theme-globals.js +48 -0
  38. package/dist/commands/delete-theme-globals.js.map +1 -0
  39. package/dist/commands/dev.d.ts.map +1 -1
  40. package/dist/commands/dev.js +218 -31
  41. package/dist/commands/dev.js.map +1 -1
  42. package/dist/commands/enable-builtin-pages.d.ts +3 -0
  43. package/dist/commands/enable-builtin-pages.d.ts.map +1 -0
  44. package/dist/commands/enable-builtin-pages.js +27 -0
  45. package/dist/commands/enable-builtin-pages.js.map +1 -0
  46. package/dist/commands/get-component-props.d.ts +3 -0
  47. package/dist/commands/get-component-props.d.ts.map +1 -0
  48. package/dist/commands/get-component-props.js +32 -0
  49. package/dist/commands/get-component-props.js.map +1 -0
  50. package/dist/commands/get-page-by-type.d.ts +3 -0
  51. package/dist/commands/get-page-by-type.d.ts.map +1 -0
  52. package/dist/commands/get-page-by-type.js +25 -0
  53. package/dist/commands/get-page-by-type.js.map +1 -0
  54. package/dist/commands/get-section-values.d.ts +3 -0
  55. package/dist/commands/get-section-values.d.ts.map +1 -0
  56. package/dist/commands/get-section-values.js +39 -0
  57. package/dist/commands/get-section-values.js.map +1 -0
  58. package/dist/commands/list-builtin-pages.d.ts +3 -0
  59. package/dist/commands/list-builtin-pages.d.ts.map +1 -0
  60. package/dist/commands/list-builtin-pages.js +28 -0
  61. package/dist/commands/list-builtin-pages.js.map +1 -0
  62. package/dist/commands/list-entities.d.ts +3 -0
  63. package/dist/commands/list-entities.d.ts.map +1 -0
  64. package/dist/commands/list-entities.js +32 -0
  65. package/dist/commands/list-entities.js.map +1 -0
  66. package/dist/commands/list-page-sections.d.ts.map +1 -1
  67. package/dist/commands/list-page-sections.js +8 -2
  68. package/dist/commands/list-page-sections.js.map +1 -1
  69. package/dist/commands/list-theme-globals.d.ts +3 -0
  70. package/dist/commands/list-theme-globals.d.ts.map +1 -0
  71. package/dist/commands/list-theme-globals.js +22 -0
  72. package/dist/commands/list-theme-globals.js.map +1 -0
  73. package/dist/commands/move-page-section.d.ts +3 -0
  74. package/dist/commands/move-page-section.d.ts.map +1 -0
  75. package/dist/commands/move-page-section.js +62 -0
  76. package/dist/commands/move-page-section.js.map +1 -0
  77. package/dist/commands/publish-theme.d.ts +3 -0
  78. package/dist/commands/publish-theme.d.ts.map +1 -0
  79. package/dist/commands/publish-theme.js +29 -0
  80. package/dist/commands/publish-theme.js.map +1 -0
  81. package/dist/commands/publish.d.ts.map +1 -1
  82. package/dist/commands/publish.js +54 -3
  83. package/dist/commands/publish.js.map +1 -1
  84. package/dist/commands/remove-page-section.d.ts +3 -0
  85. package/dist/commands/remove-page-section.d.ts.map +1 -0
  86. package/dist/commands/remove-page-section.js +40 -0
  87. package/dist/commands/remove-page-section.js.map +1 -0
  88. package/dist/commands/search-products.d.ts +3 -0
  89. package/dist/commands/search-products.d.ts.map +1 -0
  90. package/dist/commands/search-products.js +40 -0
  91. package/dist/commands/search-products.js.map +1 -0
  92. package/dist/commands/update-builtin-page-prop.d.ts +3 -0
  93. package/dist/commands/update-builtin-page-prop.d.ts.map +1 -0
  94. package/dist/commands/update-builtin-page-prop.js +49 -0
  95. package/dist/commands/update-builtin-page-prop.js.map +1 -0
  96. package/dist/commands/update-global-variable.d.ts +3 -0
  97. package/dist/commands/update-global-variable.d.ts.map +1 -0
  98. package/dist/commands/update-global-variable.js +70 -0
  99. package/dist/commands/update-global-variable.js.map +1 -0
  100. package/dist/commands/update-page-sections.d.ts +3 -0
  101. package/dist/commands/update-page-sections.d.ts.map +1 -0
  102. package/dist/commands/update-page-sections.js +39 -0
  103. package/dist/commands/update-page-sections.js.map +1 -0
  104. package/dist/commands/update-section-prop.d.ts.map +1 -1
  105. package/dist/commands/update-section-prop.js +25 -8
  106. package/dist/commands/update-section-prop.js.map +1 -1
  107. package/dist/commands/upload-image.d.ts.map +1 -1
  108. package/dist/commands/upload-image.js +5 -46
  109. package/dist/commands/upload-image.js.map +1 -1
  110. package/dist/commands/upload-images.d.ts +3 -0
  111. package/dist/commands/upload-images.d.ts.map +1 -0
  112. package/dist/commands/upload-images.js +48 -0
  113. package/dist/commands/upload-images.js.map +1 -0
  114. package/dist/index.d.ts.map +1 -1
  115. package/dist/index.js +54 -1
  116. package/dist/index.js.map +1 -1
  117. package/dist/types.d.ts +51 -0
  118. package/dist/types.d.ts.map +1 -1
  119. package/dist/utils/archive-project.d.ts +69 -0
  120. package/dist/utils/archive-project.d.ts.map +1 -0
  121. package/dist/utils/archive-project.js +202 -0
  122. package/dist/utils/archive-project.js.map +1 -0
  123. package/dist/utils/compile.d.ts +17 -2
  124. package/dist/utils/compile.d.ts.map +1 -1
  125. package/dist/utils/compile.js +750 -117
  126. package/dist/utils/compile.js.map +1 -1
  127. package/dist/utils/component-helpers.d.ts +167 -2
  128. package/dist/utils/component-helpers.d.ts.map +1 -1
  129. package/dist/utils/component-helpers.js +452 -29
  130. package/dist/utils/component-helpers.js.map +1 -1
  131. package/dist/utils/css-import-resolver.d.ts +4 -1
  132. package/dist/utils/css-import-resolver.d.ts.map +1 -1
  133. package/dist/utils/css-import-resolver.js +9 -1
  134. package/dist/utils/css-import-resolver.js.map +1 -1
  135. package/dist/utils/editor-action-client.d.ts +4 -3
  136. package/dist/utils/editor-action-client.d.ts.map +1 -1
  137. package/dist/utils/editor-action-client.js +55 -19
  138. package/dist/utils/editor-action-client.js.map +1 -1
  139. package/dist/utils/esm-transform.d.ts +30 -0
  140. package/dist/utils/esm-transform.d.ts.map +1 -1
  141. package/dist/utils/esm-transform.js +169 -2
  142. package/dist/utils/esm-transform.js.map +1 -1
  143. package/dist/utils/find-component-for-file.d.ts +12 -0
  144. package/dist/utils/find-component-for-file.d.ts.map +1 -0
  145. package/dist/utils/find-component-for-file.js +24 -0
  146. package/dist/utils/find-component-for-file.js.map +1 -0
  147. package/dist/utils/forbid-deep-imports.d.ts +3 -0
  148. package/dist/utils/forbid-deep-imports.d.ts.map +1 -0
  149. package/dist/utils/forbid-deep-imports.js +54 -0
  150. package/dist/utils/forbid-deep-imports.js.map +1 -0
  151. package/dist/utils/forbid-external-packages.d.ts +26 -0
  152. package/dist/utils/forbid-external-packages.d.ts.map +1 -0
  153. package/dist/utils/forbid-external-packages.js +99 -0
  154. package/dist/utils/forbid-external-packages.js.map +1 -0
  155. package/dist/utils/load-image.d.ts +16 -0
  156. package/dist/utils/load-image.d.ts.map +1 -0
  157. package/dist/utils/load-image.js +50 -0
  158. package/dist/utils/load-image.js.map +1 -0
  159. package/dist/utils/vendor-storefront.d.ts +13 -0
  160. package/dist/utils/vendor-storefront.d.ts.map +1 -0
  161. package/dist/utils/vendor-storefront.js +91 -0
  162. package/dist/utils/vendor-storefront.js.map +1 -0
  163. package/dist/utils/websocket-server.d.ts +119 -5
  164. package/dist/utils/websocket-server.d.ts.map +1 -1
  165. package/dist/utils/websocket-server.js +255 -44
  166. package/dist/utils/websocket-server.js.map +1 -1
  167. package/package.json +19 -2
  168. package/templates/add/section.css +11 -0
  169. package/dist/commands/create.d.ts +0 -4
  170. package/dist/commands/create.d.ts.map +0 -1
  171. package/dist/commands/create.js +0 -228
  172. package/dist/commands/create.js.map +0 -1
  173. package/dist/commands/proxy.d.ts +0 -39
  174. package/dist/commands/proxy.d.ts.map +0 -1
  175. package/dist/commands/proxy.js +0 -210
  176. package/dist/commands/proxy.js.map +0 -1
@@ -1,7 +1,8 @@
1
1
  import { Command } from "commander";
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
- import { PROP_TYPES, toPascalCase, generateTypesFile, generateGlobalTypesFile, collectUsedEnumIds, generateComponentFile, generateStylesFile, generateProjectId, generateComponentId, generateUniqueId, updateBarrelExport, findPropGroup, collectPropGroupIds, movePropGroupInTree, validateFilteredComponentIds, } from "../utils/component-helpers.js";
4
+ import { runEditorAction } from "../utils/editor-action-client.js";
5
+ import { PROP_TYPES, toPascalCase, generateTypesFile, isBuiltInEnumTypeId, normalizeEnumOptionsInput, generateGlobalTypesFile, collectUsedEnumIds, generateComponentFile, generateStylesFile, generateProjectId, isValidProjectId, generateComponentId, generateUniqueId, updateBarrelExport, findPropGroup, collectPropGroupIds, movePropGroupInTree, validateFilteredComponentIds, visibilityGateError, } from "../utils/component-helpers.js";
5
6
  function loadConfig() {
6
7
  const configPath = path.resolve(process.cwd(), "ikas.config.json");
7
8
  if (!fs.existsSync(configPath)) {
@@ -31,7 +32,10 @@ function resolveComponent(config, ref) {
31
32
  success: false,
32
33
  error: "Component reference required: pass --id (preferred) or --name (exact PascalCase). " +
33
34
  "Run `ikas-component config list-components` to see canonical ids.",
34
- validComponents: config.components.map((c) => ({ id: c.id, name: c.name })),
35
+ validComponents: config.components.map((c) => ({
36
+ id: c.id,
37
+ name: c.name,
38
+ })),
35
39
  }));
36
40
  process.exit(1);
37
41
  }
@@ -52,7 +56,10 @@ function resolveComponent(config, ref) {
52
56
  ? `Component not found: id="${id}".`
53
57
  : `Component not found: name="${name}". Names are matched exactly (PascalCase, no normalization).`,
54
58
  lookup: id ? { id } : { name },
55
- validComponents: config.components.map((c) => ({ id: c.id, name: c.name })),
59
+ validComponents: config.components.map((c) => ({
60
+ id: c.id,
61
+ name: c.name,
62
+ })),
56
63
  hint: "Use --id (preferred) or exact PascalCase --name. " +
57
64
  "Run `ikas-component config list-components` to see canonical ids.",
58
65
  }));
@@ -90,6 +97,11 @@ function assertKnownComponentIds(input, config) {
90
97
  }
91
98
  return input;
92
99
  }
100
+ // The set of component ids that currently exist in the project, for validateComponentDefaultValue's
101
+ // existence check. Undefined when no config is loaded, which makes the check a no-op (back-compat).
102
+ function existingComponentIdSet(config) {
103
+ return config ? new Set(config.components.map((c) => c.id)) : undefined;
104
+ }
93
105
  function regenerateTypes(component, componentType, config) {
94
106
  const componentDir = path.resolve(process.cwd(), path.dirname(component.entry));
95
107
  const typesPath = path.join(componentDir, "types.ts");
@@ -156,7 +168,113 @@ const ALLOWED_PROP_FIELDS = new Set([
156
168
  "enumTypeId",
157
169
  "filteredComponentIds",
158
170
  "privateVarMap",
171
+ "numberRangeData",
172
+ "requiredProp",
173
+ "requiredPropValue",
174
+ "requiredEnumOptionId",
175
+ "requiredEnumOptionValue",
159
176
  ]);
177
+ // Emit the standard CLI error envelope and exit(1) when a validator returned a message; a no-op
178
+ // when the message is null. Collapses the repeated `if (err) { console.log(...); process.exit(1) }`
179
+ // tail that follows every default-value validator call.
180
+ function failIf(error) {
181
+ if (error) {
182
+ console.log(JSON.stringify({ success: false, error }));
183
+ process.exit(1);
184
+ }
185
+ }
186
+ /**
187
+ * A `--requiredPropValue` flag as a boolean. Commander hands every flag over as a string, and this is
188
+ * the one place that turns it back; anything other than true/false is refused rather than coerced,
189
+ * since "0" or "off" silently becoming `true` is exactly the kind of gate nobody would think to
190
+ * check.
191
+ */
192
+ function parseRequiredPropValue(raw, where) {
193
+ if (raw === undefined)
194
+ return undefined;
195
+ if (typeof raw === "boolean")
196
+ return raw;
197
+ if (raw === "true")
198
+ return true;
199
+ if (raw === "false")
200
+ return false;
201
+ failIf(`--requiredPropValue for ${where} must be "true" or "false" (got "${raw}").`);
202
+ return undefined;
203
+ }
204
+ /**
205
+ * Validate/sanitize a numberRangeData object for a NUMBER_RANGE prop. Accepts an object
206
+ * or a JSON string. min/max/interval are truncated to integers; only a positive interval
207
+ * is kept (0/negative would yield an invalid slider step). Exits with a structured error
208
+ * on malformed input.
209
+ */
210
+ function parseNumberRangeData(raw, propName) {
211
+ const fail = (error) => {
212
+ console.log(JSON.stringify({ success: false, error }));
213
+ process.exit(1);
214
+ };
215
+ let obj = raw;
216
+ if (typeof raw === "string") {
217
+ try {
218
+ obj = JSON.parse(raw);
219
+ }
220
+ catch {
221
+ fail(`Invalid --numberRangeData JSON for prop "${propName}": ${raw}`);
222
+ }
223
+ }
224
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
225
+ fail(`numberRangeData for prop "${propName}" must be an object { min, max, interval?, unit? }.`);
226
+ }
227
+ const o = obj;
228
+ const asInt = (v, field) => {
229
+ if (v === undefined || v === null)
230
+ return undefined;
231
+ if (typeof v !== "number" || !Number.isFinite(v)) {
232
+ fail(`numberRangeData.${field} for prop "${propName}" must be a finite number.`);
233
+ }
234
+ return Math.trunc(v);
235
+ };
236
+ const min = asInt(o.min, "min");
237
+ const max = asInt(o.max, "max");
238
+ const interval = asInt(o.interval, "interval");
239
+ const unit = typeof o.unit === "string" && o.unit.trim() ? o.unit.trim() : undefined;
240
+ if (min !== undefined && max !== undefined && min >= max) {
241
+ fail(`numberRangeData for prop "${propName}": min (${min}) must be less than max (${max}).`);
242
+ }
243
+ return {
244
+ ...(min !== undefined ? { min } : {}),
245
+ ...(max !== undefined ? { max } : {}),
246
+ ...(interval !== undefined && interval > 0 ? { interval } : {}),
247
+ ...(unit ? { unit } : {}),
248
+ };
249
+ }
250
+ const numberRangeDataRequiredError = (propName) => `numberRangeData with min and max is required for NUMBER_RANGE prop "${propName}". ` +
251
+ `Provide it, e.g. --numberRangeData '{"min":0,"max":100,"interval":5,"unit":"px"}' ` +
252
+ `(or a "numberRangeData" field inside --props). interval and unit are optional.`;
253
+ // A NUMBER_RANGE slider config is complete only with both bounds; interval/unit stay optional.
254
+ export const isNumberRangeComplete = (data) => data.min !== undefined && data.max !== undefined;
255
+ /**
256
+ * A NUMBER_RANGE prop must carry a slider config with at least min and max — the editor UI marks
257
+ * Minimum/Maksimum Değer as required, so a prop authored without them yields a half-configured
258
+ * slider. Enforce it at creation time: reject when numberRangeData is absent or missing min/max.
259
+ */
260
+ export function requireNumberRangeData(raw, propName) {
261
+ if (raw === undefined) {
262
+ console.log(JSON.stringify({
263
+ success: false,
264
+ error: numberRangeDataRequiredError(propName),
265
+ }));
266
+ process.exit(1);
267
+ }
268
+ const parsed = parseNumberRangeData(raw, propName);
269
+ if (!isNumberRangeComplete(parsed)) {
270
+ console.log(JSON.stringify({
271
+ success: false,
272
+ error: numberRangeDataRequiredError(propName),
273
+ }));
274
+ process.exit(1);
275
+ }
276
+ return parsed;
277
+ }
160
278
  /**
161
279
  * Parse and validate the --props JSON flag for add-component.
162
280
  * Returns validated ComponentProp[] or exits with error.
@@ -182,6 +300,8 @@ async function parsePropsFlag(propsJson, config, configPath) {
182
300
  }
183
301
  const seenNames = new Set();
184
302
  const props = [];
303
+ // Loop-invariant: build the known-id set once for the whole batch, not per prop.
304
+ const existingComponentIds = existingComponentIdSet(config);
185
305
  for (const raw of rawProps) {
186
306
  const r = raw;
187
307
  const unknownFields = Object.keys(r).filter((k) => !ALLOWED_PROP_FIELDS.has(k));
@@ -234,6 +354,36 @@ async function parsePropsFlag(propsJson, config, configPath) {
234
354
  }));
235
355
  process.exit(1);
236
356
  }
357
+ // Dynamic (merchant-data reference) props can't carry a static default.
358
+ rejectDynamicDefault(r.name, propType, r.defaultValue);
359
+ // Validate LINK / LIST_OF_LINK defaultValue shape (reject JSON strings and legacy { href })
360
+ if ((propType === "LINK" || propType === "LIST_OF_LINK") &&
361
+ r.defaultValue !== undefined) {
362
+ const linkError = validateLinkDefaultValue(propType, r.defaultValue, r.name);
363
+ failIf(linkError);
364
+ }
365
+ // Validate SVG / SVG_LIST defaultValue (reject malformed/oversized/unsafe SVG)
366
+ if ((propType === "SVG" || propType === "SVG_LIST") &&
367
+ r.defaultValue !== undefined) {
368
+ const svgError = validateSvgDefaultValue(propType, r.defaultValue, r.name);
369
+ failIf(svgError);
370
+ }
371
+ // Validate COMPONENT / COMPONENT_LIST defaultValue (reference-only child code components)
372
+ if ((propType === "COMPONENT" || propType === "COMPONENT_LIST") &&
373
+ r.defaultValue !== undefined) {
374
+ failIf(validateComponentDefaultValue(propType, r.defaultValue, r.name, r.filteredComponentIds, existingComponentIds));
375
+ }
376
+ // Validate TYPE (structured/style) defaultValue shape — must be an object (or an array for an
377
+ // _array typeId), never a bare string that would be emitted as a wrong-shaped default.
378
+ if (propType === "TYPE" && r.defaultValue !== undefined) {
379
+ const typeError = validateTypeDefaultValue(r.defaultValue, r.name, r.typeId);
380
+ failIf(typeError);
381
+ }
382
+ // Validate NUMBER defaultValue — reject empty/non-finite (Number("") silently becomes 0).
383
+ if (propType === "NUMBER" && r.defaultValue !== undefined) {
384
+ const numError = validateNumberDefaultValue(r.defaultValue, r.name);
385
+ failIf(numError);
386
+ }
237
387
  // Auto-generate displayName if omitted
238
388
  const displayName = typeof r.displayName === "string" && r.displayName
239
389
  ? r.displayName
@@ -258,7 +408,10 @@ async function parsePropsFlag(propsJson, config, configPath) {
258
408
  process.exit(1);
259
409
  }
260
410
  // Validate enum type exists (checks config then live dev server)
261
- if (config && configPath && typeof r.enumTypeId === "string" && !r.enumTypeId.startsWith("@ikas/")) {
411
+ if (config &&
412
+ configPath &&
413
+ typeof r.enumTypeId === "string" &&
414
+ !isBuiltInEnumTypeId(r.enumTypeId)) {
262
415
  const resolved = await resolveEnumType(r.enumTypeId, config, configPath);
263
416
  if (!resolved) {
264
417
  console.log(JSON.stringify({
@@ -277,9 +430,7 @@ async function parsePropsFlag(propsJson, config, configPath) {
277
430
  ...(typeof r.description === "string" && r.description
278
431
  ? { description: r.description }
279
432
  : {}),
280
- ...(r.defaultValue !== undefined
281
- ? { defaultValue: r.defaultValue }
282
- : {}),
433
+ ...(r.defaultValue !== undefined ? { defaultValue: r.defaultValue } : {}),
283
434
  ...(typeof r.groupId === "string" && r.groupId
284
435
  ? { groupId: r.groupId }
285
436
  : {}),
@@ -289,15 +440,47 @@ async function parsePropsFlag(propsJson, config, configPath) {
289
440
  ...(propType === "ENUM" && typeof r.enumTypeId === "string"
290
441
  ? { enumTypeId: r.enumTypeId }
291
442
  : {}),
292
- ...((propType === "COMPONENT" || propType === "COMPONENT_LIST") && r.filteredComponentIds && Array.isArray(r.filteredComponentIds)
293
- ? { filteredComponentIds: assertKnownComponentIds(r.filteredComponentIds, config) }
443
+ ...((propType === "COMPONENT" || propType === "COMPONENT_LIST") &&
444
+ r.filteredComponentIds &&
445
+ Array.isArray(r.filteredComponentIds)
446
+ ? {
447
+ filteredComponentIds: assertKnownComponentIds(r.filteredComponentIds, config),
448
+ }
449
+ : {}),
450
+ ...((propType === "COMPONENT" || propType === "COMPONENT_LIST") &&
451
+ r.privateVarMap &&
452
+ typeof r.privateVarMap === "object"
453
+ ? {
454
+ privateVarMap: r.privateVarMap,
455
+ }
456
+ : {}),
457
+ ...(propType === "NUMBER_RANGE"
458
+ ? { numberRangeData: requireNumberRangeData(r.numberRangeData, r.name) }
459
+ : {}),
460
+ ...(r.requiredProp !== undefined
461
+ ? { requiredProp: r.requiredProp }
462
+ : {}),
463
+ ...(r.requiredPropValue !== undefined
464
+ ? { requiredPropValue: r.requiredPropValue }
294
465
  : {}),
295
- ...((propType === "COMPONENT" || propType === "COMPONENT_LIST") && r.privateVarMap && typeof r.privateVarMap === "object"
296
- ? { privateVarMap: r.privateVarMap }
466
+ ...(r.requiredEnumOptionId !== undefined
467
+ ? { requiredEnumOptionId: r.requiredEnumOptionId }
468
+ : {}),
469
+ ...(r.requiredEnumOptionValue !== undefined
470
+ ? { requiredEnumOptionValue: r.requiredEnumOptionValue }
297
471
  : {}),
298
472
  };
299
473
  props.push(prop);
300
474
  }
475
+ // Gates are checked once the whole batch is parsed: a prop may name one declared after it, and
476
+ // cycle detection needs every prop in hand. The batch IS the component's prop list here — the
477
+ // component itself does not exist yet — so it stands in as one.
478
+ const batch = { name: "the new component", props };
479
+ for (const prop of props) {
480
+ failIf(visibilityGateError(batch, prop, `prop "${prop.name}"`, {
481
+ selfPropName: prop.name,
482
+ }));
483
+ }
301
484
  return props;
302
485
  }
303
486
  // --- Subcommands ---
@@ -325,11 +508,25 @@ async function addComponent(name, options) {
325
508
  if (!config.projectId) {
326
509
  config.projectId = generateProjectId();
327
510
  }
511
+ else if (!isValidProjectId(config.projectId)) {
512
+ // A malformed projectId (hand-edited config) breaks the editor's republish
513
+ // stability: published/local id prefixes stop matching and every publish
514
+ // INSERTs duplicate design elements. Fail fast instead of corrupting data.
515
+ console.log(JSON.stringify({
516
+ success: false,
517
+ error: `Invalid projectId "${config.projectId}" in ikas.config.json. ` +
518
+ "projectId must be at least 6 alphanumeric characters (no '-' or '_'). " +
519
+ "Restore the original generated value — do not hand-edit it.",
520
+ }));
521
+ process.exit(1);
522
+ }
328
523
  // Parse --props (and validate filteredComponentIds) BEFORE any filesystem side-effects
329
524
  // so a bad payload doesn't leave an empty component directory behind.
330
525
  const props = options.props
331
526
  ? await parsePropsFlag(options.props, config, configPath)
332
527
  : [];
528
+ // Reject section-disallowed TYPE props at definition time (best-effort, needs dev server)
529
+ await assertTypeIdsUsable(componentType, props.flatMap((p) => (p.type === "TYPE" && p.typeId ? [p.typeId] : [])));
333
530
  const componentId = generateComponentId(config.projectId);
334
531
  const componentDir = path.resolve(process.cwd(), `src/components/${pascalName}`);
335
532
  // Create directory
@@ -420,6 +617,10 @@ async function addProp(ref, options) {
420
617
  }));
421
618
  process.exit(1);
422
619
  }
620
+ // Reject section-disallowed types at definition time (best-effort, needs dev server)
621
+ if (propType === "TYPE" && options.typeId) {
622
+ await assertTypeIdsUsable(component.type, [options.typeId]);
623
+ }
423
624
  // Validate enumTypeId for ENUM props
424
625
  if (propType === "ENUM" && !options.enumTypeId) {
425
626
  console.log(JSON.stringify({
@@ -430,7 +631,9 @@ async function addProp(ref, options) {
430
631
  }
431
632
  // Validate that enumTypeId references an existing enum type
432
633
  // (checks config.customTypes first, then falls back to the live dev server)
433
- if (propType === "ENUM" && options.enumTypeId && !options.enumTypeId.startsWith("@ikas/")) {
634
+ if (propType === "ENUM" &&
635
+ options.enumTypeId &&
636
+ !isBuiltInEnumTypeId(options.enumTypeId)) {
434
637
  const resolved = await resolveEnumType(options.enumTypeId, config, configPath);
435
638
  if (!resolved) {
436
639
  console.log(JSON.stringify({
@@ -460,50 +663,117 @@ async function addProp(ref, options) {
460
663
  }
461
664
  // Parse filteredComponentIds JSON for COMPONENT/COMPONENT_LIST
462
665
  let parsedFilteredIds;
463
- if (options.filteredComponentIds && (propType === "COMPONENT" || propType === "COMPONENT_LIST")) {
666
+ if (options.filteredComponentIds &&
667
+ (propType === "COMPONENT" || propType === "COMPONENT_LIST")) {
464
668
  try {
465
669
  parsedFilteredIds = JSON.parse(options.filteredComponentIds);
466
670
  if (!Array.isArray(parsedFilteredIds)) {
467
- console.log(JSON.stringify({ success: false, error: "--filteredComponentIds must be a JSON array of strings." }));
671
+ console.log(JSON.stringify({
672
+ success: false,
673
+ error: "--filteredComponentIds must be a JSON array of strings.",
674
+ }));
468
675
  process.exit(1);
469
676
  }
470
677
  }
471
678
  catch {
472
- console.log(JSON.stringify({ success: false, error: `Invalid --filteredComponentIds JSON: ${options.filteredComponentIds}` }));
679
+ console.log(JSON.stringify({
680
+ success: false,
681
+ error: `Invalid --filteredComponentIds JSON: ${options.filteredComponentIds}`,
682
+ }));
473
683
  process.exit(1);
474
684
  }
475
685
  assertKnownComponentIds(parsedFilteredIds, config);
476
686
  }
477
687
  // Parse privateVarMap JSON for COMPONENT/COMPONENT_LIST
478
688
  let parsedPrivateVarMap;
479
- if (options.privateVarMap && (propType === "COMPONENT" || propType === "COMPONENT_LIST")) {
689
+ if (options.privateVarMap &&
690
+ (propType === "COMPONENT" || propType === "COMPONENT_LIST")) {
480
691
  try {
481
692
  parsedPrivateVarMap = JSON.parse(options.privateVarMap);
482
- if (typeof parsedPrivateVarMap !== "object" || Array.isArray(parsedPrivateVarMap)) {
483
- console.log(JSON.stringify({ success: false, error: "--privateVarMap must be a JSON object mapping keys to {id, typeId}." }));
693
+ if (typeof parsedPrivateVarMap !== "object" ||
694
+ Array.isArray(parsedPrivateVarMap)) {
695
+ console.log(JSON.stringify({
696
+ success: false,
697
+ error: "--privateVarMap must be a JSON object mapping keys to {id, typeId}.",
698
+ }));
484
699
  process.exit(1);
485
700
  }
486
701
  }
487
702
  catch {
488
- console.log(JSON.stringify({ success: false, error: `Invalid --privateVarMap JSON: ${options.privateVarMap}` }));
703
+ console.log(JSON.stringify({
704
+ success: false,
705
+ error: `Invalid --privateVarMap JSON: ${options.privateVarMap}`,
706
+ }));
489
707
  process.exit(1);
490
708
  }
491
709
  }
710
+ rejectDynamicDefault(options.name, propType, options.defaultValue);
711
+ const parsedDefaultValue = options.defaultValue !== undefined
712
+ ? parseDefaultValue(options.defaultValue, propType)
713
+ : undefined;
714
+ if ((propType === "LINK" || propType === "LIST_OF_LINK") &&
715
+ parsedDefaultValue !== undefined) {
716
+ const linkError = validateLinkDefaultValue(propType, parsedDefaultValue, options.name);
717
+ failIf(linkError);
718
+ }
719
+ if ((propType === "SVG" || propType === "SVG_LIST") &&
720
+ parsedDefaultValue !== undefined) {
721
+ const svgError = validateSvgDefaultValue(propType, parsedDefaultValue, options.name);
722
+ failIf(svgError);
723
+ }
724
+ if ((propType === "COMPONENT" || propType === "COMPONENT_LIST") &&
725
+ parsedDefaultValue !== undefined) {
726
+ failIf(validateComponentDefaultValue(propType, parsedDefaultValue, options.name, parsedFilteredIds, existingComponentIdSet(config)));
727
+ }
728
+ if (propType === "TYPE" && parsedDefaultValue !== undefined) {
729
+ const typeError = validateTypeDefaultValue(parsedDefaultValue, options.name, options.typeId);
730
+ failIf(typeError);
731
+ }
732
+ // Validate against the raw flag string so an empty --defaultValue (Number("") → 0) is caught.
733
+ if (propType === "NUMBER" && options.defaultValue !== undefined) {
734
+ const numError = validateNumberDefaultValue(options.defaultValue, options.name);
735
+ failIf(numError);
736
+ }
737
+ const parsedVisibilityValue = parseRequiredPropValue(options.requiredPropValue, `prop "${options.name}"`);
738
+ const parsedNumberRangeData = propType === "NUMBER_RANGE"
739
+ ? requireNumberRangeData(options.numberRangeData, options.name)
740
+ : undefined;
741
+ if (propType === "NUMBER_RANGE" && parsedDefaultValue !== undefined) {
742
+ const nrError = validateNumberRangeDefaultValue(parsedDefaultValue, parsedNumberRangeData, options.name);
743
+ failIf(nrError);
744
+ }
492
745
  const newProp = {
493
746
  name: options.name,
494
747
  displayName: options.displayName,
495
748
  type: propType,
496
749
  required: options.required ?? false,
497
750
  ...(options.description ? { description: options.description } : {}),
498
- ...(options.defaultValue !== undefined
499
- ? { defaultValue: parseDefaultValue(options.defaultValue, propType) }
751
+ ...(parsedDefaultValue !== undefined
752
+ ? { defaultValue: parsedDefaultValue }
500
753
  : {}),
501
754
  ...(options.group ? { groupId: options.group } : {}),
502
755
  ...(options.typeId ? { typeId: options.typeId } : {}),
503
756
  ...(options.enumTypeId ? { enumTypeId: options.enumTypeId } : {}),
504
757
  ...(parsedFilteredIds ? { filteredComponentIds: parsedFilteredIds } : {}),
505
758
  ...(parsedPrivateVarMap ? { privateVarMap: parsedPrivateVarMap } : {}),
759
+ ...(parsedNumberRangeData
760
+ ? { numberRangeData: parsedNumberRangeData }
761
+ : {}),
762
+ ...(options.requiredProp ? { requiredProp: options.requiredProp } : {}),
763
+ ...(parsedVisibilityValue !== undefined
764
+ ? { requiredPropValue: parsedVisibilityValue }
765
+ : {}),
766
+ ...(options.requiredProp && options.requiredEnumOptionValue !== undefined
767
+ ? {
768
+ // The editor has no separate option id; the value doubles as one.
769
+ requiredEnumOptionId: options.requiredEnumOptionValue,
770
+ requiredEnumOptionValue: options.requiredEnumOptionValue,
771
+ }
772
+ : {}),
506
773
  };
774
+ failIf(visibilityGateError(component, newProp, `prop "${newProp.name}"`, {
775
+ selfPropName: newProp.name,
776
+ }));
507
777
  component.props.push(newProp);
508
778
  saveConfig(configPath, config);
509
779
  // Regenerate types.ts and global types
@@ -516,25 +786,446 @@ async function addProp(ref, options) {
516
786
  name: newProp.name,
517
787
  displayName: newProp.displayName,
518
788
  type: newProp.type,
519
- required: newProp.required,
520
789
  ...(newProp.groupId ? { groupId: newProp.groupId } : {}),
521
790
  ...(newProp.enumTypeId ? { enumTypeId: newProp.enumTypeId } : {}),
522
- ...(newProp.filteredComponentIds ? { filteredComponentIds: newProp.filteredComponentIds } : {}),
523
- ...(newProp.privateVarMap ? { privateVarMap: newProp.privateVarMap } : {}),
791
+ ...(newProp.filteredComponentIds
792
+ ? { filteredComponentIds: newProp.filteredComponentIds }
793
+ : {}),
794
+ ...(newProp.privateVarMap
795
+ ? { privateVarMap: newProp.privateVarMap }
796
+ : {}),
797
+ ...(newProp.numberRangeData
798
+ ? { numberRangeData: newProp.numberRangeData }
799
+ : {}),
800
+ ...(newProp.requiredProp
801
+ ? {
802
+ requiredProp: newProp.requiredProp,
803
+ ...(newProp.requiredEnumOptionValue !== undefined
804
+ ? { requiredEnumOptionValue: newProp.requiredEnumOptionValue }
805
+ : { requiredPropValue: newProp.requiredPropValue ?? true }),
806
+ }
807
+ : {}),
524
808
  },
525
809
  }));
526
810
  }
527
- function parseDefaultValue(value, propType) {
811
+ export function parseDefaultValue(value, propType) {
528
812
  switch (propType) {
529
813
  case "NUMBER":
530
814
  return Number(value);
531
815
  case "BOOLEAN":
532
816
  return value === "true";
817
+ case "COMPONENT":
818
+ case "COMPONENT_LIST":
819
+ case "LINK":
820
+ case "LIST_OF_LINK":
821
+ case "SVG_LIST":
822
+ case "NUMBER_RANGE":
823
+ case "TYPE":
824
+ // These all carry a typed value (object/array), not a scalar. The --defaultValue flag arrives
825
+ // as a string, so parse it here; if it is not valid JSON, return the raw string so the type's
826
+ // validator (validateLinkDefaultValue / validateSvgDefaultValue / validateNumberRangeDefaultValue
827
+ // / validateTypeDefaultValue / validateComponentDefaultValue) can report a precise error instead
828
+ // of silently storing a bad shape.
829
+ try {
830
+ return JSON.parse(value);
831
+ }
832
+ catch {
833
+ return value;
834
+ }
533
835
  default:
534
836
  return value;
535
837
  }
536
838
  }
537
- function updateProp(ref, options) {
839
+ // Prop types whose value is a dynamic reference to merchant storefront data (products, media,
840
+ // categories, brands, blogs, raffles). They resolve at storefront render time, so a static config
841
+ // default is invalid and is rejected on add/update-prop. Keep in sync with @ikas/editor-models
842
+ // DYNAMIC_PROP_TYPES (the CLI must not depend on that private package).
843
+ export const DYNAMIC_PROP_TYPES = [
844
+ "IMAGE",
845
+ "IMAGE_LIST",
846
+ "VIDEO",
847
+ "PRODUCT",
848
+ "PRODUCT_LIST",
849
+ "PRODUCT_ATTRIBUTE",
850
+ "PRODUCT_ATTRIBUTE_LIST",
851
+ "BRAND",
852
+ "BRAND_LIST",
853
+ "CATEGORY",
854
+ "CATEGORY_LIST",
855
+ "BLOG",
856
+ "BLOG_LIST",
857
+ "BLOG_CATEGORY",
858
+ "BLOG_CATEGORY_LIST",
859
+ "RAFFLE",
860
+ "RAFFLE_LIST",
861
+ ];
862
+ const dynamicPropDefaultError = (propName, propType) => `defaultValue is not allowed for prop "${propName}" of type ${propType}. ${propType} resolves to merchant storefront data at render time, so it can't carry a static default — omit defaultValue.`;
863
+ // Reject a static default on a dynamic (merchant-data reference) prop type: print the standard
864
+ // error and exit. No-op when the type isn't dynamic or no default was supplied.
865
+ export const rejectDynamicDefault = (propName, propType, defaultValue) => {
866
+ if (DYNAMIC_PROP_TYPES.includes(propType) && defaultValue !== undefined) {
867
+ console.log(JSON.stringify({
868
+ success: false,
869
+ error: dynamicPropDefaultError(propName, propType),
870
+ }));
871
+ process.exit(1);
872
+ }
873
+ };
874
+ const nonEmpty = (v) => typeof v === "string" && v.trim().length > 0;
875
+ // FILE is intentionally excluded from CLI-authored defaults: a code-component / AI-authored default
876
+ // can't reference a store-specific uploaded file, so a "FILE" link default is always rejected. Store
877
+ // owners can still create FILE links manually in the editor (editor-core keeps FILE in its own set).
878
+ const VALID_LINK_TYPES = ["PAGE", "EXTERNAL"];
879
+ const LINK_SHAPE_HELP = 'A link must be an object: { "linkType": "EXTERNAL", "label": "Text", "externalLink": "https://...", "subLinks": [] } ' +
880
+ 'for external links, or { "linkType": "PAGE", "label": "Text", "pageType": "INDEX", "subLinks": [] } for store pages. ' +
881
+ "Do NOT pass a JSON string or a { label, href } shape.";
882
+ // Returns the index of the first array element that fails `fn`, as an error string, or null.
883
+ const firstError = (arr, fn) => arr.reduce((acc, item, index) => acc ?? fn(item, index), null);
884
+ const validateSingleLink = (link, propName, path) => {
885
+ const where = `defaultValue for prop "${propName}"${path}`;
886
+ if (typeof link === "string") {
887
+ return `${where} is a JSON string but must be an object. ${LINK_SHAPE_HELP}`;
888
+ }
889
+ if (!link || typeof link !== "object" || Array.isArray(link)) {
890
+ return `${where} must be a link object. ${LINK_SHAPE_HELP}`;
891
+ }
892
+ const l = link;
893
+ if ("href" in l && !("linkType" in l)) {
894
+ return `${where} uses a legacy { href } shape without "linkType". Use "linkType" + "externalLink"/"pageType" instead. ${LINK_SHAPE_HELP}`;
895
+ }
896
+ if (typeof l.linkType !== "string" ||
897
+ !VALID_LINK_TYPES.includes(l.linkType)) {
898
+ return `${where} must have a valid "linkType" (one of ${VALID_LINK_TYPES.join(", ")}). ${LINK_SHAPE_HELP}`;
899
+ }
900
+ // Require the destination field for the declared linkType, so a link that points nowhere never
901
+ // reaches a published theme. A PAGE default carries a pageType (pageId is per-store, filled on
902
+ // materialization); pageId alone is also accepted for a specific page.
903
+ if (l.linkType === "PAGE" && !nonEmpty(l.pageType) && !nonEmpty(l.pageId)) {
904
+ return `${where}: a "PAGE" link needs a "pageType" (e.g. "INDEX") — or a "pageId" for a specific page. ${LINK_SHAPE_HELP}`;
905
+ }
906
+ if (l.linkType === "EXTERNAL" && !nonEmpty(l.externalLink)) {
907
+ return `${where}: an "EXTERNAL" link needs a non-empty "externalLink" URL. ${LINK_SHAPE_HELP}`;
908
+ }
909
+ if (l.subLinks !== undefined && !Array.isArray(l.subLinks)) {
910
+ return `${where}: "subLinks" must be an array (use [] when there are none).`;
911
+ }
912
+ if (Array.isArray(l.subLinks)) {
913
+ return firstError(l.subLinks, (sl, i) => validateSingleLink(sl, propName, `${path}.subLinks[${i}]`));
914
+ }
915
+ return null;
916
+ };
917
+ // Validates a LINK / LIST_OF_LINK defaultValue. Returns an error message, or null if valid.
918
+ // These defaults are a frequent source of bad data: agents tend to pass a JSON string or a
919
+ // legacy { label, href } shape. Rejecting them at authoring time keeps malformed link values
920
+ // out of published themes.
921
+ export function validateLinkDefaultValue(propType, value, propName) {
922
+ if (value === undefined || value === null)
923
+ return null;
924
+ if (propType === "LINK") {
925
+ return validateSingleLink(value, propName, "");
926
+ }
927
+ // LIST_OF_LINK
928
+ if (typeof value === "string") {
929
+ return `defaultValue for prop "${propName}" is a JSON string but must be an object { "links": [...] }. ${LINK_SHAPE_HELP}`;
930
+ }
931
+ if (!value ||
932
+ typeof value !== "object" ||
933
+ Array.isArray(value) ||
934
+ !Array.isArray(value.links)) {
935
+ return `defaultValue for prop "${propName}" must be an object with a "links" array: { "links": [ <link>, ... ] }. ${LINK_SHAPE_HELP}`;
936
+ }
937
+ const links = value.links;
938
+ return firstError(links, (link, i) => validateSingleLink(link, propName, `.links[${i}]`));
939
+ }
940
+ const COMPONENT_SHAPE_HELP = "A COMPONENT / COMPONENT_LIST default must be an object listing child code components: " +
941
+ '{ "components": [ { "codeComponentId": "<id>" } ] }. Only code components are allowed; each entry ' +
942
+ 'needs a string "codeComponentId" (no componentId, no inline propValues).';
943
+ /**
944
+ * Validate a COMPONENT / COMPONENT_LIST defaultValue. Reference-only: each entry must name a code
945
+ * component via `codeComponentId`. Rejects non-CC (`componentId`) children, missing ids, more than
946
+ * one entry for a single COMPONENT, and ids outside the prop's filteredComponentIds allowlist.
947
+ * Returns an error message, or null if valid.
948
+ */
949
+ export function validateComponentDefaultValue(propType, value, propName, filteredComponentIds, existingComponentIds) {
950
+ if (value === undefined || value === null)
951
+ return null;
952
+ const where = `defaultValue for prop "${propName}"`;
953
+ if (typeof value === "string") {
954
+ return `${where} is a JSON string but must be an object. ${COMPONENT_SHAPE_HELP}`;
955
+ }
956
+ if (!value ||
957
+ typeof value !== "object" ||
958
+ Array.isArray(value) ||
959
+ !Array.isArray(value.components)) {
960
+ return `${where} must be an object with a "components" array. ${COMPONENT_SHAPE_HELP}`;
961
+ }
962
+ const components = value.components;
963
+ if (propType === "COMPONENT" && components.length > 1) {
964
+ return `${where}: a COMPONENT prop holds a single child — provide at most one entry (use COMPONENT_LIST for many).`;
965
+ }
966
+ const allow = filteredComponentIds && filteredComponentIds.length
967
+ ? new Set(filteredComponentIds)
968
+ : null;
969
+ return firstError(components, (entry, i) => {
970
+ const at = `${where}.components[${i}]`;
971
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
972
+ return `${at} must be an object { "codeComponentId": "<id>" }. ${COMPONENT_SHAPE_HELP}`;
973
+ }
974
+ const e = entry;
975
+ if ("componentId" in e && !("codeComponentId" in e)) {
976
+ return `${at} references a non-code component (componentId). Only code components are allowed as defaults. ${COMPONENT_SHAPE_HELP}`;
977
+ }
978
+ if (typeof e.codeComponentId !== "string" ||
979
+ e.codeComponentId.trim().length === 0) {
980
+ return `${at} must have a non-empty string "codeComponentId". ${COMPONENT_SHAPE_HELP}`;
981
+ }
982
+ if (allow && !allow.has(e.codeComponentId)) {
983
+ return `${at}: "${e.codeComponentId}" is not in this prop's filteredComponentIds allowlist.`;
984
+ }
985
+ // Reject a reference to a component that does not exist in the project (deleted, renamed, or
986
+ // never created). A dangling default would seed a ghost entry on every placement that renders
987
+ // nothing. Only enforced when the caller supplies the known-component set (the config-backed
988
+ // add-prop / update-prop / batch sites); pure-shape callers pass no set and skip this check.
989
+ if (existingComponentIds && !existingComponentIds.has(e.codeComponentId)) {
990
+ return `${at}: no component with id "${e.codeComponentId}" exists in this project. Create it first (config add-component) or reference an existing component id (config list).`;
991
+ }
992
+ return null;
993
+ });
994
+ }
995
+ const SVG_DEFAULT_HELP = "An SVG default must be a single well-formed <svg>…</svg> string ≤ 64 KB with no embedded base64 raster images. " +
996
+ 'Tip: the editor uses each svg\'s `class` attribute as its display name — set class="my-icon" to name it; ' +
997
+ "SVG_LIST items with no class show as svg-1, svg-2, ….";
998
+ // Keep the cap and base64 pattern in sync with @ikas/editor-models validate-svg.ts (the
999
+ // authoritative validator). Duplicated here on purpose — see validateSvgShape below.
1000
+ const SVG_MAX_SIZE_KB = 64;
1001
+ const SVG_BASE64_RASTER_RE = /data:image\/[a-z0-9.+-]+;base64/i;
1002
+ const SVG_SHAPE_RE = /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!DOCTYPE[^>]*>\s*)?<svg[\s>][\s\S]*<\/svg>\s*$/i;
1003
+ // Count TOP-LEVEL <svg> roots without a DOM: scan svg open/close tags in order and track
1004
+ // nesting depth. A root is any <svg> opened at depth 0. This matches the editor's DOM-based
1005
+ // single-root check — it rejects siblings (`<svg/><svg/>`) while allowing a nested <svg>.
1006
+ // Self-closing <svg .../> counts as a root but opens no nesting level.
1007
+ function svgRootCount(input) {
1008
+ const tags = input.match(/<svg\b[^>]*>|<\/svg\s*>/gi) || [];
1009
+ return tags.reduce((acc, tag) => {
1010
+ if (tag.startsWith("</"))
1011
+ return { depth: Math.max(0, acc.depth - 1), roots: acc.roots };
1012
+ const roots = acc.depth === 0 ? acc.roots + 1 : acc.roots;
1013
+ const depth = /\/>\s*$/.test(tag) ? acc.depth : acc.depth + 1;
1014
+ return { depth, roots };
1015
+ }, { depth: 0, roots: 0 }).roots;
1016
+ }
1017
+ // Lightweight, dependency-free SVG structure check. This standalone CLI is publishable and
1018
+ // must not depend on the private @ikas/editor-models package (nor pull a DOM/DOMPurify into a
1019
+ // CLI), so it mirrors the RULES of the editor's validateSvg (size, base64, single <svg> root)
1020
+ // for fast authoring feedback. The authoritative sanitize runs in the editor/upload path.
1021
+ // Returns a rejection reason, or null if the shape is acceptable.
1022
+ function validateSvgShape(input) {
1023
+ if (typeof input !== "string" || input.trim() === "")
1024
+ return "empty or not a string";
1025
+ if (Buffer.byteLength(input, "utf8") > SVG_MAX_SIZE_KB * 1024)
1026
+ return `exceeds ${SVG_MAX_SIZE_KB} KB`;
1027
+ if (SVG_BASE64_RASTER_RE.test(input))
1028
+ return "embedded base64 raster image not allowed";
1029
+ if (!SVG_SHAPE_RE.test(input))
1030
+ return "not a single-root <svg> document";
1031
+ if (svgRootCount(input) !== 1)
1032
+ return "must be exactly one <svg> root";
1033
+ return null;
1034
+ }
1035
+ // Validates an SVG / SVG_LIST defaultValue. Returns an error message, or null if valid.
1036
+ // Authoring an SVG default is a common mistake source for agents; rejecting here (with an
1037
+ // instructive message) keeps malformed/oversized SVGs out of published components.
1038
+ export function validateSvgDefaultValue(propType, value, propName) {
1039
+ if (value === undefined || value === null)
1040
+ return null;
1041
+ if (propType === "SVG") {
1042
+ const reason = validateSvgShape(value);
1043
+ return reason
1044
+ ? `defaultValue for prop "${propName}" is not a valid SVG: ${reason}. ${SVG_DEFAULT_HELP}`
1045
+ : null;
1046
+ }
1047
+ // SVG_LIST
1048
+ if (!Array.isArray(value)) {
1049
+ return `defaultValue for prop "${propName}" must be an array of SVG strings: [ "<svg>…</svg>", ... ]. ${SVG_DEFAULT_HELP}`;
1050
+ }
1051
+ return firstError(value, (svg, i) => {
1052
+ const reason = validateSvgShape(svg);
1053
+ return reason
1054
+ ? `defaultValue[${i}] for prop "${propName}" is not a valid SVG: ${reason}. ${SVG_DEFAULT_HELP}`
1055
+ : null;
1056
+ });
1057
+ }
1058
+ const NUMBER_RANGE_DEFAULT_HELP = 'A NUMBER_RANGE default must be an object { "value": <number>, "unit": "px" | null }. ' +
1059
+ "When the prop defines numberRangeData, value must be within [min, max] and on the interval grid (min + k·interval).";
1060
+ // Validates a NUMBER_RANGE defaultValue. Returns an error message, or null if valid.
1061
+ // Checks the { value, unit } shape and — when the prop carries numberRangeData — that the
1062
+ // value is within [min, max] and lands on the interval grid, mirroring the editor's slider
1063
+ // so an agent can't author an out-of-range or off-step default.
1064
+ export function validateNumberRangeDefaultValue(value, numberRangeData, propName) {
1065
+ if (value === undefined || value === null)
1066
+ return null;
1067
+ const where = `defaultValue for prop "${propName}"`;
1068
+ if (typeof value === "string") {
1069
+ return `${where} is a JSON string but must be an object. ${NUMBER_RANGE_DEFAULT_HELP}`;
1070
+ }
1071
+ if (typeof value !== "object" || Array.isArray(value)) {
1072
+ return `${where} must be an object. ${NUMBER_RANGE_DEFAULT_HELP}`;
1073
+ }
1074
+ const v = value;
1075
+ if (typeof v.value !== "number" || !Number.isFinite(v.value)) {
1076
+ return `${where}: "value" must be a finite number. ${NUMBER_RANGE_DEFAULT_HELP}`;
1077
+ }
1078
+ if (v.unit !== undefined && v.unit !== null && typeof v.unit !== "string") {
1079
+ return `${where}: "unit" must be a string or null. ${NUMBER_RANGE_DEFAULT_HELP}`;
1080
+ }
1081
+ if (numberRangeData) {
1082
+ const { min, max, interval } = numberRangeData;
1083
+ if (min !== undefined && v.value < min) {
1084
+ return `${where}: value ${v.value} is below the configured min (${min}).`;
1085
+ }
1086
+ if (max !== undefined && v.value > max) {
1087
+ return `${where}: value ${v.value} is above the configured max (${max}).`;
1088
+ }
1089
+ if (interval !== undefined &&
1090
+ interval > 0 &&
1091
+ min !== undefined &&
1092
+ (v.value - min) % interval !== 0) {
1093
+ return `${where}: value ${v.value} is not on the interval grid (min ${min} + k·${interval}).`;
1094
+ }
1095
+ }
1096
+ return null;
1097
+ }
1098
+ const NUMBER_DEFAULT_HELP = "A NUMBER default must be a finite number, e.g. --defaultValue 42.";
1099
+ // Validates a NUMBER defaultValue. Returns an error message, or null if valid. Guards two footguns:
1100
+ // an empty/whitespace flag string (Number("") === 0 would silently store 0) and a non-numeric or
1101
+ // non-finite value (e.g. "42px" → NaN, "Infinity"). The flag path passes the raw --defaultValue
1102
+ // string; the --props path passes the already-parsed JSON value — both are handled here.
1103
+ export function validateNumberDefaultValue(value, propName) {
1104
+ if (value === undefined || value === null)
1105
+ return null;
1106
+ const where = `defaultValue for prop "${propName}"`;
1107
+ if (typeof value === "string") {
1108
+ if (value.trim() === "") {
1109
+ return `${where} is empty, but NUMBER requires a finite number. ${NUMBER_DEFAULT_HELP}`;
1110
+ }
1111
+ if (!Number.isFinite(Number(value))) {
1112
+ return `${where} ("${value}") is not a finite number. ${NUMBER_DEFAULT_HELP}`;
1113
+ }
1114
+ return null;
1115
+ }
1116
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1117
+ return `${where} must be a finite number. ${NUMBER_DEFAULT_HELP}`;
1118
+ }
1119
+ return null;
1120
+ }
1121
+ const STYLE_TYPE_DEFAULT_HELP = "A size/style TYPE default must be an object matching the type's shape: " +
1122
+ '{ "value": <number>, "unit": "px" | "rem" | "%" | "vh" | "vw" } (or { "css": "<raw css>" }). ' +
1123
+ "Author it via add-component --props '[…]' or --defaultValue '<json>'.";
1124
+ const BP_STOREFRONT_PREFIX = "@ikas/bp-storefront-models-";
1125
+ // The size/style types that share the { css?, value?, unit? } shape. This is EXACTLY the set of
1126
+ // TYPE typeIds whose default the generator emits (mirror of DYNAMIC_STYLE_TYPE_IDS in
1127
+ // @ikas/blueprint-modules design-generator/generate-helpers/styles.ts — the standalone CLI must not
1128
+ // depend on that package, so it is hand-maintained here and kept in sync by a parity test). Every
1129
+ // OTHER TYPE typeId (BorderStyleType, BoxShadowStyleType, GridTemplateColumnsStyleType, string-union
1130
+ // styles like TextAlignStyleType, IkasProduct, custom types) has a DIFFERENT value shape, so their
1131
+ // defaults are not shape-checked (and are dead code in the generator anyway).
1132
+ const SIZE_STYLE_TYPE_NAMES = [
1133
+ "SizeStyleType",
1134
+ "PaddingStyleType",
1135
+ "PaddingTopStyleType",
1136
+ "PaddingRightStyleType",
1137
+ "PaddingBottomStyleType",
1138
+ "PaddingLeftStyleType",
1139
+ "MarginStyleType",
1140
+ "MarginTopStyleType",
1141
+ "MarginRightStyleType",
1142
+ "MarginBottomStyleType",
1143
+ "MarginLeftStyleType",
1144
+ "BorderRadiusStyleType",
1145
+ "BorderRadiusTopLeftStyleType",
1146
+ "BorderRadiusTopRightStyleType",
1147
+ "BorderRadiusBottomRightStyleType",
1148
+ "BorderRadiusBottomLeftStyleType",
1149
+ "FontSizeStyleType",
1150
+ "LineHeightStyleType",
1151
+ "LetterSpacingStyleType",
1152
+ "HeightStyleType",
1153
+ "MinHeightStyleType",
1154
+ "MaxHeightStyleType",
1155
+ "WidthStyleType",
1156
+ "MinWidthStyleType",
1157
+ "MaxWidthStyleType",
1158
+ "GapStyleType",
1159
+ "BorderWidthStyleType",
1160
+ "TopStyleType",
1161
+ "RightStyleType",
1162
+ "BottomStyleType",
1163
+ "LeftStyleType",
1164
+ ];
1165
+ // Validates a single style-type default object. Every size style type shares the optional
1166
+ // { css?, value?, unit? } shape, so inner fields are checked loosely — the key rejection is a
1167
+ // non-object (e.g. a bare JSON string, the common failure when a --defaultValue flag is not parsed).
1168
+ function styleDefaultObjectError(value, where) {
1169
+ if (typeof value === "string") {
1170
+ return `${where} is a JSON string but must be an object. ${STYLE_TYPE_DEFAULT_HELP}`;
1171
+ }
1172
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1173
+ return `${where} must be an object. ${STYLE_TYPE_DEFAULT_HELP}`;
1174
+ }
1175
+ const v = value;
1176
+ // css/value/unit are all optional, and the editor treats an explicit null as "unset" (it accepts
1177
+ // { value: null }). So only type-check a field that is present AND non-null — otherwise the CLI
1178
+ // would be stricter than the authoritative editor and reject a value it would happily accept.
1179
+ // Unknown fields ARE rejected below: every size-style type shares exactly this { css?, value?, unit? }
1180
+ // shape, so an extra key is always a mistake (this matches the editor). The per-type value-DOMAIN
1181
+ // (which units a given type allows — BorderWidth also permits em/vmin/vmax while the rest are
1182
+ // px/rem/%/vh/vw) stays editor-side: it is per-type and can't be mirrored offline without drift.
1183
+ if (v.css !== undefined && v.css !== null && typeof v.css !== "string") {
1184
+ return `${where}: "css" must be a string. ${STYLE_TYPE_DEFAULT_HELP}`;
1185
+ }
1186
+ if (v.value !== undefined &&
1187
+ v.value !== null &&
1188
+ (typeof v.value !== "number" || !Number.isFinite(v.value))) {
1189
+ return `${where}: "value" must be a finite number. ${STYLE_TYPE_DEFAULT_HELP}`;
1190
+ }
1191
+ if (v.unit !== undefined && v.unit !== null && typeof v.unit !== "string") {
1192
+ return `${where}: "unit" must be a string. ${STYLE_TYPE_DEFAULT_HELP}`;
1193
+ }
1194
+ const unknownKey = Object.keys(v).find((k) => k !== "css" && k !== "value" && k !== "unit");
1195
+ if (unknownKey) {
1196
+ return `${where}: unknown field "${unknownKey}". A size/style default allows only "css", "value", "unit". ${STYLE_TYPE_DEFAULT_HELP}`;
1197
+ }
1198
+ return null;
1199
+ }
1200
+ // Validates a TYPE prop defaultValue — but ONLY for the size/style types whose shape we know
1201
+ // ({ css?, value?, unit? }). Any other TYPE typeId (color/border/box-shadow/grid/string-union
1202
+ // styles, IkasProduct, custom types) has a different value shape we can't verify offline, so its
1203
+ // default is passed through unchecked. The generator only emits a default for these size/style
1204
+ // types anyway. Returns an error message, or null if valid / not a size-style type.
1205
+ export function validateTypeDefaultValue(value, propName, typeId) {
1206
+ if (value === undefined || value === null)
1207
+ return null;
1208
+ if (typeof typeId !== "string" || !typeId.startsWith(BP_STOREFRONT_PREFIX)) {
1209
+ return null;
1210
+ }
1211
+ // Strip the prefix and an optional _array suffix to get the base type name.
1212
+ const withoutPrefix = typeId.slice(BP_STOREFRONT_PREFIX.length);
1213
+ const isArray = withoutPrefix.endsWith("_array");
1214
+ const baseName = isArray
1215
+ ? withoutPrefix.slice(0, -"_array".length)
1216
+ : withoutPrefix;
1217
+ if (!SIZE_STYLE_TYPE_NAMES.includes(baseName))
1218
+ return null;
1219
+ const where = `defaultValue for prop "${propName}"`;
1220
+ if (isArray) {
1221
+ if (!Array.isArray(value)) {
1222
+ return `${where} must be an array for an _array TYPE prop: [ { "value": …, "unit": … }, … ]. ${STYLE_TYPE_DEFAULT_HELP}`;
1223
+ }
1224
+ return firstError(value, (el, i) => styleDefaultObjectError(el, `${where}[${i}]`));
1225
+ }
1226
+ return styleDefaultObjectError(value, where);
1227
+ }
1228
+ async function updateProp(ref, options) {
538
1229
  const { config, configPath } = loadConfig();
539
1230
  const component = resolveComponent(config, ref);
540
1231
  const propIndex = component.props.findIndex((p) => p.name === options.prop);
@@ -566,8 +1257,87 @@ function updateProp(ref, options) {
566
1257
  if (options.description !== undefined) {
567
1258
  prop.description = options.description || undefined;
568
1259
  }
1260
+ // Resolve numberRangeData before defaultValue so a NUMBER_RANGE default can be validated
1261
+ // against the (possibly just-updated) slider config in the same call.
1262
+ if (options.numberRangeData !== undefined) {
1263
+ if (options.numberRangeData === "" || options.numberRangeData === "none") {
1264
+ delete prop.numberRangeData;
1265
+ }
1266
+ else {
1267
+ prop.numberRangeData = parseNumberRangeData(options.numberRangeData, prop.name);
1268
+ }
1269
+ }
1270
+ // A NUMBER_RANGE prop must keep a valid slider config (min + max). Enforce the invariant only when
1271
+ // this update touches the type or numberRangeData — a benign update (e.g. displayName) on an
1272
+ // existing prop must still pass. This catches switching a prop TO NUMBER_RANGE without a config, or
1273
+ // clearing/blanking numberRangeData on a NUMBER_RANGE prop.
1274
+ if ((options.type !== undefined || options.numberRangeData !== undefined) &&
1275
+ prop.type === "NUMBER_RANGE" &&
1276
+ (!prop.numberRangeData || !isNumberRangeComplete(prop.numberRangeData))) {
1277
+ console.log(JSON.stringify({
1278
+ success: false,
1279
+ error: numberRangeDataRequiredError(prop.name),
1280
+ }));
1281
+ process.exit(1);
1282
+ }
1283
+ // Resolve filteredComponentIds before defaultValue so a COMPONENT / COMPONENT_LIST default can be
1284
+ // validated against the (possibly just-updated) allowlist in the same call.
1285
+ if (options.filteredComponentIds !== undefined) {
1286
+ if (options.filteredComponentIds === "" ||
1287
+ options.filteredComponentIds === "none") {
1288
+ delete prop.filteredComponentIds;
1289
+ }
1290
+ else {
1291
+ try {
1292
+ const parsed = JSON.parse(options.filteredComponentIds);
1293
+ if (!Array.isArray(parsed)) {
1294
+ console.log(JSON.stringify({
1295
+ success: false,
1296
+ error: "--filteredComponentIds must be a JSON array of strings.",
1297
+ }));
1298
+ process.exit(1);
1299
+ }
1300
+ assertKnownComponentIds(parsed, config);
1301
+ prop.filteredComponentIds = parsed;
1302
+ }
1303
+ catch (err) {
1304
+ if (err instanceof SyntaxError) {
1305
+ console.log(JSON.stringify({
1306
+ success: false,
1307
+ error: `Invalid --filteredComponentIds JSON: ${options.filteredComponentIds}`,
1308
+ }));
1309
+ process.exit(1);
1310
+ }
1311
+ throw err;
1312
+ }
1313
+ }
1314
+ }
569
1315
  if (options.defaultValue !== undefined) {
570
- prop.defaultValue = parseDefaultValue(options.defaultValue, prop.type);
1316
+ rejectDynamicDefault(prop.name, prop.type, options.defaultValue);
1317
+ const parsed = parseDefaultValue(options.defaultValue, prop.type);
1318
+ // Validate against the raw flag string so an empty --defaultValue (Number("") → 0) is caught.
1319
+ if (prop.type === "NUMBER") {
1320
+ const numError = validateNumberDefaultValue(options.defaultValue, prop.name);
1321
+ failIf(numError);
1322
+ }
1323
+ if (prop.type === "LINK" || prop.type === "LIST_OF_LINK") {
1324
+ const linkError = validateLinkDefaultValue(prop.type, parsed, prop.name);
1325
+ failIf(linkError);
1326
+ }
1327
+ if ((prop.type === "COMPONENT" || prop.type === "COMPONENT_LIST") &&
1328
+ parsed !== undefined) {
1329
+ failIf(validateComponentDefaultValue(prop.type, parsed, prop.name, prop.filteredComponentIds, existingComponentIdSet(config)));
1330
+ }
1331
+ if (prop.type === "NUMBER_RANGE") {
1332
+ const nrError = validateNumberRangeDefaultValue(parsed, prop.numberRangeData, prop.name);
1333
+ failIf(nrError);
1334
+ }
1335
+ if (prop.type === "TYPE") {
1336
+ // Prefer a typeId supplied in this same update over the stored one.
1337
+ const typeError = validateTypeDefaultValue(parsed, prop.name, options.typeId ?? prop.typeId);
1338
+ failIf(typeError);
1339
+ }
1340
+ prop.defaultValue = parsed;
571
1341
  }
572
1342
  if (options.group !== undefined) {
573
1343
  if (options.group === "" || options.group === "none") {
@@ -600,6 +1370,13 @@ function updateProp(ref, options) {
600
1370
  prop.typeId = options.typeId;
601
1371
  }
602
1372
  }
1373
+ // Reject section-disallowed types when the caller changes type/typeId;
1374
+ // untouched legacy props stay editable (displayName, group, ...).
1375
+ if ((options.type !== undefined || options.typeId !== undefined) &&
1376
+ prop.type === "TYPE" &&
1377
+ prop.typeId) {
1378
+ await assertTypeIdsUsable(component.type, [prop.typeId]);
1379
+ }
603
1380
  if (options.enumTypeId !== undefined) {
604
1381
  if (options.enumTypeId === "" || options.enumTypeId === "none") {
605
1382
  delete prop.enumTypeId;
@@ -608,29 +1385,6 @@ function updateProp(ref, options) {
608
1385
  prop.enumTypeId = options.enumTypeId;
609
1386
  }
610
1387
  }
611
- if (options.filteredComponentIds !== undefined) {
612
- if (options.filteredComponentIds === "" || options.filteredComponentIds === "none") {
613
- delete prop.filteredComponentIds;
614
- }
615
- else {
616
- try {
617
- const parsed = JSON.parse(options.filteredComponentIds);
618
- if (!Array.isArray(parsed)) {
619
- console.log(JSON.stringify({ success: false, error: "--filteredComponentIds must be a JSON array of strings." }));
620
- process.exit(1);
621
- }
622
- assertKnownComponentIds(parsed, config);
623
- prop.filteredComponentIds = parsed;
624
- }
625
- catch (err) {
626
- if (err instanceof SyntaxError) {
627
- console.log(JSON.stringify({ success: false, error: `Invalid --filteredComponentIds JSON: ${options.filteredComponentIds}` }));
628
- process.exit(1);
629
- }
630
- throw err;
631
- }
632
- }
633
- }
634
1388
  if (options.privateVarMap !== undefined) {
635
1389
  if (options.privateVarMap === "" || options.privateVarMap === "none") {
636
1390
  delete prop.privateVarMap;
@@ -639,17 +1393,50 @@ function updateProp(ref, options) {
639
1393
  try {
640
1394
  const parsed = JSON.parse(options.privateVarMap);
641
1395
  if (typeof parsed !== "object" || Array.isArray(parsed)) {
642
- console.log(JSON.stringify({ success: false, error: "--privateVarMap must be a JSON object mapping keys to {id, typeId}." }));
1396
+ console.log(JSON.stringify({
1397
+ success: false,
1398
+ error: "--privateVarMap must be a JSON object mapping keys to {id, typeId}.",
1399
+ }));
643
1400
  process.exit(1);
644
1401
  }
645
1402
  prop.privateVarMap = parsed;
646
1403
  }
647
1404
  catch {
648
- console.log(JSON.stringify({ success: false, error: `Invalid --privateVarMap JSON: ${options.privateVarMap}` }));
1405
+ console.log(JSON.stringify({
1406
+ success: false,
1407
+ error: `Invalid --privateVarMap JSON: ${options.privateVarMap}`,
1408
+ }));
649
1409
  process.exit(1);
650
1410
  }
651
1411
  }
652
1412
  }
1413
+ if (options.requiredProp !== undefined) {
1414
+ if (options.requiredProp === "" || options.requiredProp === "none") {
1415
+ // Every field goes together — see `IProp.requiredPropId`.
1416
+ delete prop.requiredProp;
1417
+ delete prop.requiredPropValue;
1418
+ delete prop.requiredEnumOptionId;
1419
+ delete prop.requiredEnumOptionValue;
1420
+ }
1421
+ else {
1422
+ prop.requiredProp = options.requiredProp;
1423
+ }
1424
+ }
1425
+ if (options.requiredEnumOptionValue !== undefined && prop.requiredProp) {
1426
+ prop.requiredEnumOptionId = options.requiredEnumOptionValue;
1427
+ prop.requiredEnumOptionValue = options.requiredEnumOptionValue;
1428
+ delete prop.requiredPropValue;
1429
+ }
1430
+ if (options.requiredPropValue !== undefined && prop.requiredProp) {
1431
+ delete prop.requiredEnumOptionId;
1432
+ delete prop.requiredEnumOptionValue;
1433
+ prop.requiredPropValue = parseRequiredPropValue(options.requiredPropValue, `prop "${prop.name}"`);
1434
+ }
1435
+ // Re-checked on every update, not only when a visibility flag is passed: flipping `required`, or
1436
+ // renaming the prop this one hangs on, can invalidate a gate that was sound when it was written.
1437
+ failIf(visibilityGateError(component, prop, `prop "${prop.name}"`, {
1438
+ selfPropName: prop.name,
1439
+ }));
653
1440
  saveConfig(configPath, config);
654
1441
  // Regenerate types.ts and global types
655
1442
  regenerateTypes(component, undefined, config);
@@ -661,12 +1448,24 @@ function updateProp(ref, options) {
661
1448
  name: prop.name,
662
1449
  displayName: prop.displayName,
663
1450
  type: prop.type,
664
- required: prop.required,
665
1451
  ...(prop.groupId ? { groupId: prop.groupId } : {}),
666
1452
  ...(prop.typeId ? { typeId: prop.typeId } : {}),
667
1453
  ...(prop.enumTypeId ? { enumTypeId: prop.enumTypeId } : {}),
668
- ...(prop.filteredComponentIds ? { filteredComponentIds: prop.filteredComponentIds } : {}),
1454
+ ...(prop.filteredComponentIds
1455
+ ? { filteredComponentIds: prop.filteredComponentIds }
1456
+ : {}),
669
1457
  ...(prop.privateVarMap ? { privateVarMap: prop.privateVarMap } : {}),
1458
+ ...(prop.numberRangeData
1459
+ ? { numberRangeData: prop.numberRangeData }
1460
+ : {}),
1461
+ ...(prop.requiredProp
1462
+ ? {
1463
+ requiredProp: prop.requiredProp,
1464
+ ...(prop.requiredEnumOptionValue !== undefined
1465
+ ? { requiredEnumOptionValue: prop.requiredEnumOptionValue }
1466
+ : { requiredPropValue: prop.requiredPropValue ?? true }),
1467
+ }
1468
+ : {}),
670
1469
  },
671
1470
  }));
672
1471
  }
@@ -729,7 +1528,10 @@ function removeComponent(ref) {
729
1528
  removedComponentId: component.id,
730
1529
  removedComponentName: component.name,
731
1530
  removedDirectory: path.relative(process.cwd(), componentDir),
732
- remainingComponents: config.components.map((c) => ({ id: c.id, name: c.name })),
1531
+ remainingComponents: config.components.map((c) => ({
1532
+ id: c.id,
1533
+ name: c.name,
1534
+ })),
733
1535
  }));
734
1536
  }
735
1537
  function addPropGroup(ref, options) {
@@ -750,7 +1552,24 @@ function addPropGroup(ref, options) {
750
1552
  id: options.id,
751
1553
  name: options.name,
752
1554
  ...(options.description ? { description: options.description } : {}),
1555
+ ...(options.requiredProp ? { requiredProp: options.requiredProp } : {}),
1556
+ ...(options.requiredProp && options.requiredEnumOptionValue !== undefined
1557
+ ? {
1558
+ requiredEnumOptionId: options.requiredEnumOptionValue,
1559
+ requiredEnumOptionValue: options.requiredEnumOptionValue,
1560
+ }
1561
+ : {}),
1562
+ ...(options.requiredProp &&
1563
+ options.requiredEnumOptionValue === undefined &&
1564
+ options.requiredPropValue !== undefined
1565
+ ? {
1566
+ requiredPropValue: parseRequiredPropValue(options.requiredPropValue, `group "${options.id}"`),
1567
+ }
1568
+ : {}),
753
1569
  };
1570
+ failIf(visibilityGateError(component, newGroup, `group "${newGroup.id}"`, {
1571
+ group: newGroup,
1572
+ }));
754
1573
  if (options.parent) {
755
1574
  const found = findPropGroup(component.propGroups, options.parent);
756
1575
  if (!found) {
@@ -782,6 +1601,14 @@ function addPropGroup(ref, options) {
782
1601
  id: newGroup.id,
783
1602
  name: newGroup.name,
784
1603
  ...(options.parent ? { parentId: options.parent } : {}),
1604
+ ...(newGroup.requiredProp
1605
+ ? {
1606
+ requiredProp: newGroup.requiredProp,
1607
+ ...(newGroup.requiredEnumOptionValue !== undefined
1608
+ ? { requiredEnumOptionValue: newGroup.requiredEnumOptionValue }
1609
+ : { requiredPropValue: newGroup.requiredPropValue ?? true }),
1610
+ }
1611
+ : {}),
785
1612
  },
786
1613
  }));
787
1614
  }
@@ -807,6 +1634,34 @@ function updatePropGroup(ref, options) {
807
1634
  found.group.name = options.name;
808
1635
  if (options.description !== undefined)
809
1636
  found.group.description = options.description || undefined;
1637
+ if (options.requiredProp !== undefined) {
1638
+ if (options.requiredProp === "" || options.requiredProp === "none") {
1639
+ // Every field goes together — see `IThemePropGroup.requiredPropId`.
1640
+ delete found.group.requiredProp;
1641
+ delete found.group.requiredPropValue;
1642
+ delete found.group.requiredEnumOptionId;
1643
+ delete found.group.requiredEnumOptionValue;
1644
+ }
1645
+ else {
1646
+ found.group.requiredProp = options.requiredProp;
1647
+ }
1648
+ }
1649
+ if (options.requiredEnumOptionValue !== undefined &&
1650
+ found.group.requiredProp) {
1651
+ found.group.requiredEnumOptionId = options.requiredEnumOptionValue;
1652
+ found.group.requiredEnumOptionValue = options.requiredEnumOptionValue;
1653
+ delete found.group.requiredPropValue;
1654
+ }
1655
+ if (options.requiredPropValue !== undefined && found.group.requiredProp) {
1656
+ delete found.group.requiredEnumOptionId;
1657
+ delete found.group.requiredEnumOptionValue;
1658
+ found.group.requiredPropValue = parseRequiredPropValue(options.requiredPropValue, `group "${found.group.id}"`);
1659
+ }
1660
+ // Re-checked on every update: moving a prop into this group can invalidate a gate that was sound
1661
+ // when it was written.
1662
+ failIf(visibilityGateError(component, found.group, `group "${found.group.id}"`, {
1663
+ group: found.group,
1664
+ }));
810
1665
  saveConfig(configPath, config);
811
1666
  console.log(JSON.stringify({
812
1667
  success: true,
@@ -814,6 +1669,16 @@ function updatePropGroup(ref, options) {
814
1669
  updatedPropGroup: {
815
1670
  id: found.group.id,
816
1671
  name: found.group.name,
1672
+ ...(found.group.requiredProp
1673
+ ? {
1674
+ requiredProp: found.group.requiredProp,
1675
+ ...(found.group.requiredEnumOptionValue !== undefined
1676
+ ? {
1677
+ requiredEnumOptionValue: found.group.requiredEnumOptionValue,
1678
+ }
1679
+ : { requiredPropValue: found.group.requiredPropValue ?? true }),
1680
+ }
1681
+ : {}),
817
1682
  },
818
1683
  }));
819
1684
  }
@@ -836,10 +1701,10 @@ function removePropGroup(ref, options) {
836
1701
  process.exit(1);
837
1702
  }
838
1703
  if (found.parent) {
839
- found.parent.children = found.parent.children.filter(c => c.id !== options.id);
1704
+ found.parent.children = found.parent.children.filter((c) => c.id !== options.id);
840
1705
  }
841
1706
  else {
842
- component.propGroups = component.propGroups.filter(g => g.id !== options.id);
1707
+ component.propGroups = component.propGroups.filter((g) => g.id !== options.id);
843
1708
  }
844
1709
  // Clear groupId from props referencing the deleted group
845
1710
  for (const prop of component.props) {
@@ -852,7 +1717,7 @@ function removePropGroup(ref, options) {
852
1717
  success: true,
853
1718
  componentName: component.name,
854
1719
  removedPropGroup: options.id,
855
- remainingPropGroups: component.propGroups.map(g => g.id),
1720
+ remainingPropGroups: component.propGroups.map((g) => g.id),
856
1721
  }));
857
1722
  }
858
1723
  function movePropGroup(ref, options) {
@@ -869,7 +1734,10 @@ function movePropGroup(ref, options) {
869
1734
  component.propGroups = movePropGroupInTree(component.propGroups, options.id, options.parent || null, options.index);
870
1735
  }
871
1736
  catch (e) {
872
- console.log(JSON.stringify({ success: false, error: e.message || "Failed to move prop group" }));
1737
+ console.log(JSON.stringify({
1738
+ success: false,
1739
+ error: e.message || "Failed to move prop group",
1740
+ }));
873
1741
  process.exit(1);
874
1742
  }
875
1743
  saveConfig(configPath, config);
@@ -925,7 +1793,9 @@ function listComponents() {
925
1793
  required: p.required,
926
1794
  ...(p.groupId ? { groupId: p.groupId } : {}),
927
1795
  })),
928
- ...(c.propGroups && c.propGroups.length > 0 ? { propGroups: c.propGroups } : {}),
1796
+ ...(c.propGroups && c.propGroups.length > 0
1797
+ ? { propGroups: c.propGroups }
1798
+ : {}),
929
1799
  }));
930
1800
  console.log(JSON.stringify({
931
1801
  success: true,
@@ -939,7 +1809,9 @@ function listComponents() {
939
1809
  async function addEnum(options) {
940
1810
  const { config, configPath } = loadConfig();
941
1811
  // Validate name
942
- if (!options.name || typeof options.name !== "string" || !options.name.trim()) {
1812
+ if (!options.name ||
1813
+ typeof options.name !== "string" ||
1814
+ !options.name.trim()) {
943
1815
  console.log(JSON.stringify({ success: false, error: "Enum name is required." }));
944
1816
  process.exit(1);
945
1817
  }
@@ -967,10 +1839,10 @@ async function addEnum(options) {
967
1839
  }));
968
1840
  process.exit(1);
969
1841
  }
970
- // Parse and validate options JSON
971
- let enumOptions;
1842
+ // Parse and validate options JSON (object form, or the `[{ name, value }]` array form)
1843
+ let parsedOptions;
972
1844
  try {
973
- enumOptions = JSON.parse(options.options);
1845
+ parsedOptions = JSON.parse(options.options);
974
1846
  }
975
1847
  catch {
976
1848
  console.log(JSON.stringify({
@@ -979,15 +1851,12 @@ async function addEnum(options) {
979
1851
  }));
980
1852
  process.exit(1);
981
1853
  }
982
- if (typeof enumOptions !== "object" ||
983
- Array.isArray(enumOptions) ||
984
- Object.keys(enumOptions).length === 0) {
985
- console.log(JSON.stringify({
986
- success: false,
987
- error: 'Options must be a non-empty JSON object, e.g. \'{"Small":"sm","Medium":"md","Large":"lg"}\'.',
988
- }));
1854
+ const normalizedOptions = normalizeEnumOptionsInput(parsedOptions);
1855
+ if ("error" in normalizedOptions) {
1856
+ console.log(JSON.stringify({ success: false, error: normalizedOptions.error }));
989
1857
  process.exit(1);
990
1858
  }
1859
+ const enumOptions = normalizedOptions.options;
991
1860
  const enumId = generateUniqueId();
992
1861
  config.customTypes.push({
993
1862
  id: enumId,
@@ -1037,9 +1906,9 @@ function updateEnum(options) {
1037
1906
  enumType.name = options.name;
1038
1907
  }
1039
1908
  if (options.options !== undefined) {
1040
- let enumOptions;
1909
+ let parsedOptions;
1041
1910
  try {
1042
- enumOptions = JSON.parse(options.options);
1911
+ parsedOptions = JSON.parse(options.options);
1043
1912
  }
1044
1913
  catch {
1045
1914
  console.log(JSON.stringify({
@@ -1048,16 +1917,12 @@ function updateEnum(options) {
1048
1917
  }));
1049
1918
  process.exit(1);
1050
1919
  }
1051
- if (typeof enumOptions !== "object" ||
1052
- Array.isArray(enumOptions) ||
1053
- Object.keys(enumOptions).length === 0) {
1054
- console.log(JSON.stringify({
1055
- success: false,
1056
- error: 'Options must be a non-empty JSON object.',
1057
- }));
1920
+ const normalizedOptions = normalizeEnumOptionsInput(parsedOptions);
1921
+ if ("error" in normalizedOptions) {
1922
+ console.log(JSON.stringify({ success: false, error: normalizedOptions.error }));
1058
1923
  process.exit(1);
1059
1924
  }
1060
- enumType.enumOptions = enumOptions;
1925
+ enumType.enumOptions = normalizedOptions.options;
1061
1926
  }
1062
1927
  saveConfig(configPath, config);
1063
1928
  // Regenerate global types and all component types
@@ -1072,7 +1937,7 @@ function updateEnum(options) {
1072
1937
  enumOptions: enumType.enumOptions,
1073
1938
  }));
1074
1939
  }
1075
- function removeEnum(options) {
1940
+ async function removeEnum(options) {
1076
1941
  const { config, configPath } = loadConfig();
1077
1942
  if (!config.customTypes)
1078
1943
  config.customTypes = [];
@@ -1096,6 +1961,26 @@ function removeEnum(options) {
1096
1961
  }
1097
1962
  }
1098
1963
  }
1964
+ // A theme ENUM global variable can select from this enum too. Those live in the editor's
1965
+ // project, not in ikas.config.json, so ask the connected editor (best effort: with no dev
1966
+ // server / editor the removal proceeds and the result carries a warning). The editor itself
1967
+ // refuses to delete a type its globals reference, so this mirrors that guard for the CLI path.
1968
+ const liveGlobals = await fetchLiveThemeGlobals();
1969
+ const referencingGlobals = liveGlobals
1970
+ ? Object.values(liveGlobals).filter((s) => s.type === "ENUM" && s.enumTypeId === options.id)
1971
+ : [];
1972
+ if (referencingGlobals.length > 0) {
1973
+ const names = referencingGlobals
1974
+ .map((s) => `"${s.displayName}" (${s.name})`)
1975
+ .join(", ");
1976
+ console.log(JSON.stringify({
1977
+ success: false,
1978
+ error: `Cannot remove enum "${config.customTypes[enumIndex].name}": theme global variable(s) ${names} ` +
1979
+ `in the connected editor select from it. Change or delete those globals first ` +
1980
+ `(update-global-variable --enum-type-id / delete-global-variable).`,
1981
+ }));
1982
+ process.exit(1);
1983
+ }
1099
1984
  const removed = config.customTypes.splice(enumIndex, 1)[0];
1100
1985
  saveConfig(configPath, config);
1101
1986
  // Regenerate global types and all component types
@@ -1107,6 +1992,11 @@ function removeEnum(options) {
1107
1992
  success: true,
1108
1993
  removedEnumId: removed.id,
1109
1994
  removedEnumName: removed.name,
1995
+ ...(liveGlobals === null
1996
+ ? {
1997
+ warning: "Editor not connected — could not verify that no theme global variable selects from this enum.",
1998
+ }
1999
+ : {}),
1110
2000
  }));
1111
2001
  }
1112
2002
  function listEnums() {
@@ -1126,8 +2016,7 @@ function listEnums() {
1126
2016
  }
1127
2017
  // --- Command registration ---
1128
2018
  export function createConfigCommand() {
1129
- const config = new Command("config")
1130
- .description("Non-interactive commands for managing ikas.config.json (designed for AI agents and scripting)");
2019
+ const config = new Command("config").description("Non-interactive commands for managing ikas.config.json (designed for AI agents and scripting)");
1131
2020
  config
1132
2021
  .command("add-component")
1133
2022
  .description("Add a new component to the project")
@@ -1136,7 +2025,7 @@ export function createConfigCommand() {
1136
2025
  .option("--isHeader", "Mark this section as the store header (only for type: section)")
1137
2026
  .option("--isFooter", "Mark this section as the store footer (only for type: section)")
1138
2027
  .option("--props <json>", "JSON array of props. Required per entry: name, type. Optional: displayName (auto from name), required, description, defaultValue, groupId, typeId (TYPE props), enumTypeId (ENUM props), filteredComponentIds, privateVarMap. " +
1139
- "Example: '[{\"name\":\"title\",\"type\":\"TEXT\",\"required\":true,\"defaultValue\":\"Hello\",\"groupId\":\"basic\"}]'")
2028
+ 'Example: \'[{"name":"title","type":"TEXT","required":true,"defaultValue":"Hello","groupId":"basic"}]\'')
1140
2029
  .action((options) => {
1141
2030
  addComponent(options.name, options);
1142
2031
  });
@@ -1155,7 +2044,11 @@ export function createConfigCommand() {
1155
2044
  .option("--typeId <typeId>", "Type ID for TYPE props (required when type is TYPE)")
1156
2045
  .option("--enumTypeId <enumTypeId>", "Enum type ID for ENUM props (required when type is ENUM)")
1157
2046
  .option("--filteredComponentIds <json>", "JSON array of component IDs to restrict selection (for COMPONENT/COMPONENT_LIST)")
1158
- .option("--privateVarMap <json>", 'JSON object mapping variable keys to {id, typeId} (for COMPONENT/COMPONENT_LIST)')
2047
+ .option("--privateVarMap <json>", "JSON object mapping variable keys to {id, typeId} (for COMPONENT/COMPONENT_LIST)")
2048
+ .option("--numberRangeData <json>", 'JSON slider config for NUMBER_RANGE props, e.g. \'{"min":0,"max":100,"interval":5,"unit":"px"}\'')
2049
+ .option("--requiredProp <propName>", 'Show this only while the named BOOLEAN or ENUM prop satisfies the condition ("Koşullu Prop")')
2050
+ .option("--requiredPropValue <boolean>", "For a BOOLEAN --requiredProp: which state shows it, true (default) or false")
2051
+ .option("--requiredEnumOptionValue <value>", "For an ENUM --requiredProp: the option value that shows it")
1159
2052
  .action((options) => {
1160
2053
  addProp({ id: options.componentId, name: options.component }, options);
1161
2054
  });
@@ -1175,6 +2068,10 @@ export function createConfigCommand() {
1175
2068
  .option("--enumTypeId <enumTypeId>", "Enum type ID for ENUM props (use 'none' to clear)")
1176
2069
  .option("--filteredComponentIds <json>", "JSON array of component IDs (use 'none' to clear)")
1177
2070
  .option("--privateVarMap <json>", "JSON object mapping variable keys to {id, typeId} (use 'none' to clear)")
2071
+ .option("--numberRangeData <json>", "JSON slider config for NUMBER_RANGE props (use 'none' to clear)")
2072
+ .option("--requiredProp <propName>", "BOOLEAN or ENUM prop that gates this prop in the editor panel (use 'none' to clear)")
2073
+ .option("--requiredPropValue <boolean>", "For a BOOLEAN --requiredProp: which state shows it, true (default) or false")
2074
+ .option("--requiredEnumOptionValue <value>", "For an ENUM --requiredProp: the option value that shows it")
1178
2075
  .action((options) => {
1179
2076
  updateProp({ id: options.componentId, name: options.component }, options);
1180
2077
  });
@@ -1216,6 +2113,9 @@ export function createConfigCommand() {
1216
2113
  .requiredOption("--name <name>", "Display name in editor")
1217
2114
  .option("--description <description>", "Group description")
1218
2115
  .option("--parent <parentId>", "Parent group ID (for nesting, max 1 level)")
2116
+ .option("--requiredProp <propName>", 'Show this only while the named BOOLEAN or ENUM prop satisfies the condition ("Koşullu Prop")')
2117
+ .option("--requiredPropValue <boolean>", "For a BOOLEAN --requiredProp: which state shows it, true (default) or false")
2118
+ .option("--requiredEnumOptionValue <value>", "For an ENUM --requiredProp: the option value that shows it")
1219
2119
  .action((options) => {
1220
2120
  addPropGroup({ id: options.componentId, name: options.component }, options);
1221
2121
  });
@@ -1227,6 +2127,9 @@ export function createConfigCommand() {
1227
2127
  .requiredOption("--id <id>", "Group ID to update")
1228
2128
  .option("--name <name>", "New display name")
1229
2129
  .option("--description <description>", "New description")
2130
+ .option("--requiredProp <propName>", "BOOLEAN or ENUM prop that gates this group in the editor panel (use 'none' to clear)")
2131
+ .option("--requiredPropValue <boolean>", "For a BOOLEAN --requiredProp: which state shows it, true (default) or false")
2132
+ .option("--requiredEnumOptionValue <value>", "For an ENUM --requiredProp: the option value that shows it")
1230
2133
  .action((options) => {
1231
2134
  updatePropGroup({ id: options.componentId, name: options.component }, options);
1232
2135
  });
@@ -1246,7 +2149,7 @@ export function createConfigCommand() {
1246
2149
  .option("--component <name>", "Component name — exact match (PascalCase, as stored in ikas.config.json)")
1247
2150
  .requiredOption("--id <id>", "Group ID to move")
1248
2151
  .option("--parent <parentId>", "Target parent group ID (omit to move to root)")
1249
- .option("--index <index>", "Zero-based insertion index within the target parent (appends when omitted)", v => parseInt(v, 10))
2152
+ .option("--index <index>", "Zero-based insertion index within the target parent (appends when omitted)", (v) => parseInt(v, 10))
1250
2153
  .action((options) => {
1251
2154
  movePropGroup({ id: options.componentId, name: options.component }, options);
1252
2155
  });
@@ -1273,7 +2176,7 @@ export function createConfigCommand() {
1273
2176
  .command("add-enum")
1274
2177
  .description("Create a custom enum type (offline, no editor needed)")
1275
2178
  .requiredOption("--name <name>", "Enum name (e.g. Size, AspectRatio)")
1276
- .requiredOption("--options <json>", 'JSON object of label→value pairs, e.g. \'{"Small":"sm","Medium":"md","Large":"lg"}\'')
2179
+ .requiredOption("--options <json>", 'JSON object of label→value pairs, e.g. \'{"Small":"sm","Medium":"md","Large":"lg"}\' (an array \'[{"name":"Small","value":"sm"}]\' is also accepted)')
1277
2180
  .action(async (options) => {
1278
2181
  await addEnum(options);
1279
2182
  });
@@ -1282,16 +2185,16 @@ export function createConfigCommand() {
1282
2185
  .description("Update a custom enum type")
1283
2186
  .requiredOption("--id <id>", "Enum ID to update")
1284
2187
  .option("--name <name>", "New enum name")
1285
- .option("--options <json>", "New JSON object of label→value pairs")
2188
+ .option("--options <json>", "New JSON object of label→value pairs (an array of { name, value } is also accepted)")
1286
2189
  .action((options) => {
1287
2190
  updateEnum(options);
1288
2191
  });
1289
2192
  config
1290
2193
  .command("remove-enum")
1291
- .description("Remove a custom enum type (fails if any prop references it)")
2194
+ .description("Remove a custom enum type (fails if any prop references it, or — while the editor is connected — if a theme ENUM global variable selects from it)")
1292
2195
  .requiredOption("--id <id>", "Enum ID to remove")
1293
- .action((options) => {
1294
- removeEnum(options);
2196
+ .action(async (options) => {
2197
+ await removeEnum(options);
1295
2198
  });
1296
2199
  config
1297
2200
  .command("list-enums")
@@ -1306,54 +2209,15 @@ export function createConfigCommand() {
1306
2209
  * Returns the matching type (with enumOptions) if found, null otherwise.
1307
2210
  */
1308
2211
  async function fetchLiveEditorEnumById(enumId) {
1309
- const { WebSocket } = await import("ws");
1310
- const WS_URL = "ws://localhost:5201";
1311
- const TIMEOUT_MS = 1500;
1312
- return new Promise((resolve) => {
1313
- let ws;
1314
- let settled = false;
1315
- const finish = (value) => {
1316
- if (settled)
1317
- return;
1318
- settled = true;
1319
- try {
1320
- ws?.close();
1321
- }
1322
- catch {
1323
- /* ignore */
1324
- }
1325
- resolve(value);
1326
- };
1327
- try {
1328
- ws = new WebSocket(WS_URL);
1329
- }
1330
- catch {
1331
- resolve(null);
1332
- return;
2212
+ const types = await fetchLiveEditorTypes();
2213
+ const match = types?.find((t) => t.category === "enum" && t.id === enumId);
2214
+ return match
2215
+ ? {
2216
+ id: match.id,
2217
+ name: match.name,
2218
+ ...(match.enumOptions ? { enumOptions: match.enumOptions } : {}),
1333
2219
  }
1334
- const timeout = setTimeout(() => finish(null), TIMEOUT_MS);
1335
- ws.on("open", () => {
1336
- ws.send(JSON.stringify({ type: "request-types" }));
1337
- });
1338
- ws.on("message", (data) => {
1339
- try {
1340
- const message = JSON.parse(data.toString());
1341
- if (message.type === "types-list") {
1342
- clearTimeout(timeout);
1343
- const types = message.payload?.types || [];
1344
- const match = types.find((t) => t.category === "enum" && t.id === enumId);
1345
- finish(match ? { id: match.id, name: match.name, ...(match.enumOptions ? { enumOptions: match.enumOptions } : {}) } : null);
1346
- }
1347
- }
1348
- catch {
1349
- // Ignore non-JSON messages
1350
- }
1351
- });
1352
- ws.on("error", () => {
1353
- clearTimeout(timeout);
1354
- finish(null);
1355
- });
1356
- });
2220
+ : null;
1357
2221
  }
1358
2222
  /**
1359
2223
  * Best-effort lookup of an enum by PascalCase name in the live editor session.
@@ -1363,8 +2227,37 @@ async function fetchLiveEditorEnumById(enumId) {
1363
2227
  * must treat null as "could not verify, fall back to on-disk check only".
1364
2228
  */
1365
2229
  async function fetchLiveEditorEnumByName(pascalName) {
2230
+ const types = await fetchLiveEditorTypes();
2231
+ const match = types?.find((t) => t.category === "enum" && toPascalCase(t.name) === pascalName);
2232
+ return match ? { id: match.id, name: match.name } : null;
2233
+ }
2234
+ /**
2235
+ * Best-effort read of the connected editor's theme global variables (the same editor action
2236
+ * `list-theme-globals` runs). Returns null on any failure — no dev server, no editor connected,
2237
+ * timeout — and callers must treat null as "could not verify, allow".
2238
+ */
2239
+ async function fetchLiveThemeGlobals() {
2240
+ try {
2241
+ const result = await runEditorAction("list-theme-globals", {}, { timeoutMs: 1500 });
2242
+ if (!result.success)
2243
+ return null;
2244
+ const settings = result.payload?.settings;
2245
+ return settings && typeof settings === "object" ? settings : null;
2246
+ }
2247
+ catch {
2248
+ return null;
2249
+ }
2250
+ }
2251
+ /**
2252
+ * Best-effort fetch of the editor's synced type list (with category /
2253
+ * sectionAllowed / enumOptions metadata). Returns null on any failure (no dev
2254
+ * server, timeout) — callers must treat null as "could not verify, allow".
2255
+ */
2256
+ async function fetchLiveEditorTypes() {
1366
2257
  const { WebSocket } = await import("ws");
1367
- const WS_URL = "ws://localhost:5201";
2258
+ // `client=control` keeps this short-lived socket out of the dev server's
2259
+ // `editor-action` target pool — it only reads types, it can't apply commands.
2260
+ const WS_URL = "ws://localhost:5201/?client=control";
1368
2261
  const TIMEOUT_MS = 1500;
1369
2262
  return new Promise((resolve) => {
1370
2263
  let ws;
@@ -1397,9 +2290,7 @@ async function fetchLiveEditorEnumByName(pascalName) {
1397
2290
  const message = JSON.parse(data.toString());
1398
2291
  if (message.type === "types-list") {
1399
2292
  clearTimeout(timeout);
1400
- const types = message.payload?.types || [];
1401
- const match = types.find((t) => t.category === "enum" && toPascalCase(t.name) === pascalName);
1402
- finish(match ? { id: match.id, name: match.name } : null);
2293
+ finish(message.payload?.types || []);
1403
2294
  }
1404
2295
  }
1405
2296
  catch {
@@ -1412,9 +2303,52 @@ async function fetchLiveEditorEnumByName(pascalName) {
1412
2303
  });
1413
2304
  });
1414
2305
  }
2306
+ /**
2307
+ * Definition-time guard for TYPE-prop typeIds, verified against the live
2308
+ * editor's type list (skipped when the dev server is unreachable or the type
2309
+ * is unknown to the editor). Two rules:
2310
+ * - deprecated types are rejected on ANY component: they are legacy
2311
+ * render-only types — old themes may still carry values, but new props must
2312
+ * not be defined with them.
2313
+ * - on section components, only section-allowed (style) types pass — any other
2314
+ * type renders an empty placeholder merchants cannot fill, and section-level
2315
+ * bindings cannot supply a value either, so the prop would be dead weight.
2316
+ * On violation prints the standard { success: false } envelope and exits.
2317
+ */
2318
+ async function assertTypeIdsUsable(componentType, typeIds) {
2319
+ if (typeIds.length === 0)
2320
+ return;
2321
+ const types = await fetchLiveEditorTypes();
2322
+ if (!types)
2323
+ return;
2324
+ const matches = typeIds.flatMap((typeId) => {
2325
+ const match = types.find((t) => t.id === typeId);
2326
+ return match ? [match] : [];
2327
+ });
2328
+ const legacy = matches.find((t) => t.deprecated === true);
2329
+ if (legacy) {
2330
+ console.log(JSON.stringify({
2331
+ success: false,
2332
+ error: `Type "${legacy.id}" is a legacy render-only type — values of it may still exist in old themes, but NEW props must not use it. Pick a current style type instead (run "config list-types" to see them).`,
2333
+ }));
2334
+ process.exit(1);
2335
+ }
2336
+ if (componentType !== "section")
2337
+ return;
2338
+ const disallowed = matches.find((t) => t.sectionAllowed === false);
2339
+ if (!disallowed)
2340
+ return;
2341
+ console.log(JSON.stringify({
2342
+ success: false,
2343
+ error: `Type "${disallowed.id}" is not allowed for TYPE props on section components — merchants cannot fill it in the editor (sections only support style types). Run "config list-types --component-type section" to see allowed types, or use a dedicated prop type (e.g. PRODUCT, CATEGORY) for domain data.`,
2344
+ }));
2345
+ process.exit(1);
2346
+ }
1415
2347
  async function listTypes(componentType) {
1416
2348
  const { WebSocket } = await import("ws");
1417
- const WS_URL = "ws://localhost:5201";
2349
+ // `client=control` keeps this short-lived socket out of the dev server's
2350
+ // `editor-action` target pool — it only reads types, it can't apply commands.
2351
+ const WS_URL = "ws://localhost:5201/?client=control";
1418
2352
  const TIMEOUT_MS = 5000;
1419
2353
  await new Promise((resolve) => {
1420
2354
  let ws;
@@ -1424,7 +2358,7 @@ async function listTypes(componentType) {
1424
2358
  catch {
1425
2359
  console.log(JSON.stringify({
1426
2360
  success: false,
1427
- error: "Failed to connect to dev server. Make sure 'ikas-component dev' is running.",
2361
+ error: "Failed to connect to dev server. Make sure 'ikas theme dev' is running.",
1428
2362
  }));
1429
2363
  process.exit(1);
1430
2364
  return;
@@ -1445,7 +2379,8 @@ async function listTypes(componentType) {
1445
2379
  const message = JSON.parse(data.toString());
1446
2380
  if (message.type === "types-list") {
1447
2381
  clearTimeout(timeout);
1448
- let types = message.payload.types;
2382
+ // Legacy render-only types are never offered for new props.
2383
+ let types = message.payload.types.filter((t) => !t.deprecated);
1449
2384
  if (componentType === "section") {
1450
2385
  types = types.filter((t) => t.sectionAllowed);
1451
2386
  }
@@ -1465,7 +2400,7 @@ async function listTypes(componentType) {
1465
2400
  clearTimeout(timeout);
1466
2401
  console.log(JSON.stringify({
1467
2402
  success: false,
1468
- error: "Failed to connect to dev server. Make sure 'ikas-component dev' is running.",
2403
+ error: "Failed to connect to dev server. Make sure 'ikas theme dev' is running.",
1469
2404
  }));
1470
2405
  process.exit(1);
1471
2406
  });