@contentstack/studio-registry 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/cjs/index.cjs +529 -84
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/esm/component-registry/registry-options-processor.js +27 -0
  4. package/dist/esm/component-registry/registry-options-processor.js.map +1 -1
  5. package/dist/esm/component-registry/registry.constant.js +3 -0
  6. package/dist/esm/component-registry/registry.constant.js.map +1 -1
  7. package/dist/esm/component-registry/registry.js +171 -4
  8. package/dist/esm/component-registry/registry.js.map +1 -1
  9. package/dist/esm/component-registry/singleton.js +59 -0
  10. package/dist/esm/component-registry/singleton.js.map +1 -0
  11. package/dist/esm/data-binder/cslp.js +4 -1
  12. package/dist/esm/data-binder/cslp.js.map +1 -1
  13. package/dist/esm/data-binder/retrieve-data.js +107 -30
  14. package/dist/esm/data-binder/retrieve-data.js.map +1 -1
  15. package/dist/esm/data-binder/retrieve-data.util.js +70 -52
  16. package/dist/esm/data-binder/retrieve-data.util.js.map +1 -1
  17. package/dist/esm/data-binder/strategies/contentstack.js +19 -0
  18. package/dist/esm/data-binder/strategies/contentstack.js.map +1 -0
  19. package/dist/esm/data-binder/strategies/dataSourceCapabilities.js +12 -0
  20. package/dist/esm/data-binder/strategies/dataSourceCapabilities.js.map +1 -0
  21. package/dist/esm/data-binder/strategies/query.js +17 -0
  22. package/dist/esm/data-binder/strategies/query.js.map +1 -0
  23. package/dist/esm/data-binder/strategies/repeater.js +18 -0
  24. package/dist/esm/data-binder/strategies/repeater.js.map +1 -0
  25. package/dist/esm/data-binder/strategies/template.js +16 -0
  26. package/dist/esm/data-binder/strategies/template.js.map +1 -0
  27. package/dist/esm/data-binder/strategies/utils.js +20 -0
  28. package/dist/esm/data-binder/strategies/utils.js.map +1 -0
  29. package/dist/esm/data-binder/strategy-registry.js +20 -0
  30. package/dist/esm/data-binder/strategy-registry.js.map +1 -0
  31. package/dist/esm/index.d.ts +132 -3
  32. package/dist/esm/index.js +2 -1
  33. package/dist/esm/index.js.map +1 -1
  34. package/package.json +13 -10
@@ -64,6 +64,7 @@ const DATA_SOURCES = {
64
64
  TEMPLATE: "template",
65
65
  CONTENTSTACK: "contentstack",
66
66
  REPEATER: "repeater",
67
+ QUERY: "contentstack_queries",
67
68
  SYMBOL_PROPS: "symbol_props",
68
69
  };
69
70
  const INTERNAL_COMPONENT_SECTIONS = {
@@ -124,6 +125,7 @@ const INTERNAL_COMPONENTS_NAMES = {
124
125
  LINK: "link",
125
126
  LINK_CONTAINER: "link-container",
126
127
  TEXT: "text",
128
+ NUMBER: "number",
127
129
  BUTTON: "button",
128
130
  JSON_RTE: "json-rte",
129
131
  COLLAPSIBLE_TEXT: "collapsible-text",
@@ -160,6 +162,7 @@ const BUILT_IN_COMPONENTS = {
160
162
  LINK: "link",
161
163
  LINK_CONTAINER: "link-container",
162
164
  TEXT: "text",
165
+ NUMBER: "number",
163
166
  BUTTON: "button",
164
167
  JSON_RTE: "json-rte",
165
168
  COLLAPSIBLE_TEXT: "collapsible-text",
@@ -4033,6 +4036,7 @@ function processRegistryOptionsProps(props) {
4033
4036
  delete processedProps[field].validate;
4034
4037
  }
4035
4038
  }
4039
+ validateSlotCountPropLinkages(props, processedProps);
4036
4040
  return { props: processedProps, validators: propValidators };
4037
4041
  }
4038
4042
  function getExpandedPropTypes(prop) {
@@ -4049,6 +4053,32 @@ function getExpandedPropTypes(prop) {
4049
4053
  };
4050
4054
  return propTypeMapping[prop];
4051
4055
  }
4056
+ function validateSlotCountPropLinkages(originalProps, processedProps) {
4057
+ if (!originalProps)
4058
+ return;
4059
+ for (const [field, prop] of Object.entries(originalProps)) {
4060
+ if (typeof prop === "string" || prop.type !== "slot")
4061
+ continue;
4062
+ const slotProp = prop;
4063
+ if (!slotProp.countProp)
4064
+ continue;
4065
+ const linkedProp = originalProps[slotProp.countProp];
4066
+ const linkedPropType = typeof linkedProp === "string" ? linkedProp : linkedProp?.type;
4067
+ if (!linkedProp || linkedPropType !== "number") {
4068
+ throw new Error(`Slot "${field}" references countProp "${slotProp.countProp}" which must be a registered number prop.`);
4069
+ }
4070
+ if (!slotProp.itemFactory || typeof slotProp.itemFactory !== "function") {
4071
+ throw new Error(`Slot "${field}" with countProp must provide an itemFactory function.`);
4072
+ }
4073
+ const existingSlotProp = processedProps[field];
4074
+ processedProps[field] = {
4075
+ ...existingSlotProp,
4076
+ countProp: slotProp.countProp,
4077
+ itemFactory: slotProp.itemFactory,
4078
+ itemTemplate: slotProp.itemFactory(),
4079
+ };
4080
+ }
4081
+ }
4052
4082
  function getBlockStyleSections() {
4053
4083
  return STYLE_SECTION_CATEGORIES.block;
4054
4084
  }
@@ -4069,6 +4099,10 @@ class ComponentRegistry {
4069
4099
  componentRegistry = new Map();
4070
4100
  propValidatorRegistry = new Map();
4071
4101
  config;
4102
+ // Lazy loading infrastructure
4103
+ componentLoaders = new Map();
4104
+ loadedComponents = new Set();
4105
+ loadingPromises = new Map();
4072
4106
  constructor(config) {
4073
4107
  // TODO process options
4074
4108
  this.config = config || getDefaultComponentRegistryOptions();
@@ -4078,6 +4112,9 @@ class ComponentRegistry {
4078
4112
  this.getComponents = this.getComponents.bind(this);
4079
4113
  this.getComponent = this.getComponent.bind(this);
4080
4114
  this.hasComponent = this.hasComponent.bind(this);
4115
+ this.registerLazyComponent = this.registerLazyComponent.bind(this);
4116
+ this.loadComponent = this.loadComponent.bind(this);
4117
+ this.loadComponents = this.loadComponents.bind(this);
4081
4118
  }
4082
4119
  setConfig(config = {}) {
4083
4120
  if (config.allowedBuiltInComponents !== undefined) {
@@ -4122,9 +4159,12 @@ class ComponentRegistry {
4122
4159
  const { type: name } = componentConfig;
4123
4160
  this.componentRegistry.set(name, componentConfig);
4124
4161
  });
4125
- // sync unregistered components
4162
+ // sync unregistered components (never remove system / built-in entries)
4126
4163
  this.componentRegistry.forEach((componentConfig) => {
4127
4164
  if (!updatedConfig.some((c) => c.type === componentConfig.type)) {
4165
+ if (SYSTEM_COMPONENTS.has(componentConfig.type)) {
4166
+ return;
4167
+ }
4128
4168
  this.unregisterComponent(componentConfig.type);
4129
4169
  }
4130
4170
  });
@@ -4247,7 +4287,24 @@ class ComponentRegistry {
4247
4287
  if (!this.componentRegistry.has(name)) {
4248
4288
  throw new Error(`Component with type '${name}' is not registered.`);
4249
4289
  }
4250
- return this.componentRegistry.get(name);
4290
+ const componentSchema = this.componentRegistry.get(name);
4291
+ // Check if this is a lazy component that hasn't been loaded yet
4292
+ if (componentSchema.component === null && this.componentLoaders.has(name)) {
4293
+ const errorMessage = [
4294
+ `Component '${name}' is registered as lazy but hasn't been loaded yet.`,
4295
+ "",
4296
+ "This usually happens when:",
4297
+ "1. fetchSpec() was not awaited before rendering",
4298
+ "2. The component is being used in editor mode without being loaded",
4299
+ "3. There was an error during component loading",
4300
+ "",
4301
+ "Fix: Ensure fetchSpec() is properly awaited:",
4302
+ " const spec = await fetchSpec({ ... });",
4303
+ " return <ComposableStudio spec={spec} />;",
4304
+ ].join("\n");
4305
+ throw new Error(errorMessage);
4306
+ }
4307
+ return componentSchema;
4251
4308
  }
4252
4309
  /**
4253
4310
  * Retrieves a component from the component registry by its name.
@@ -4273,11 +4330,9 @@ class ComponentRegistry {
4273
4330
  unregisterComponent(node) {
4274
4331
  const name = typeof node === "string" ? node : this.getComponentName(node);
4275
4332
  if (!this.componentRegistry.has(name)) {
4276
- console.error(`Component with type '${name}' is not registered.`);
4277
4333
  return;
4278
4334
  }
4279
4335
  if (SYSTEM_COMPONENTS.has(name)) {
4280
- console.error(`Component with type '${name}' is a system component and cannot be unregistered.`);
4281
4336
  return;
4282
4337
  }
4283
4338
  this.componentRegistry.delete(name);
@@ -4316,6 +4371,203 @@ class ComponentRegistry {
4316
4371
  }
4317
4372
  return type;
4318
4373
  }
4374
+ /**
4375
+ * Registers a lazy-loadable component with a loader function.
4376
+ * The component will be loaded on-demand when needed.
4377
+ *
4378
+ * @param config - Component configuration without the component itself
4379
+ * @param loader - Function that returns a Promise resolving to the component
4380
+ * @param registryType - Type of registry (internal or user-defined), defaults to user-defined
4381
+ */
4382
+ registerLazyComponent(config, loader, registryType = "user-defined") {
4383
+ const { type } = config;
4384
+ if (!type) {
4385
+ throw new Error("Component type is required.");
4386
+ }
4387
+ // For internal components, allow registration even if already exists
4388
+ // This is needed for built-in component lazy loading
4389
+ const isInternal = registryType === "internal";
4390
+ if (this.componentRegistry.has(type) &&
4391
+ !this.config.overrideDefaultComponents &&
4392
+ !isInternal) {
4393
+ throw new Error(`Component with type '${type}' is already registered.`);
4394
+ }
4395
+ if (SYSTEM_COMPONENTS.has(type) && !isInternal) {
4396
+ throw new Error(`Component with type '${type}' is a system component and cannot be overridden.`);
4397
+ }
4398
+ // Store the loader
4399
+ this.componentLoaders.set(type, loader);
4400
+ // Register a placeholder in the registry with _lazy flag
4401
+ const { processedOptions, propValidators } = processRegistryOptions({
4402
+ ...config,
4403
+ component: null, // Placeholder, will be loaded later
4404
+ }, {
4405
+ registry: registryType,
4406
+ });
4407
+ // Mark as lazy for internal tracking
4408
+ processedOptions._lazy = true;
4409
+ this.componentRegistry.set(type, processedOptions);
4410
+ this.propValidatorRegistry.set(type, propValidators);
4411
+ }
4412
+ /**
4413
+ * Loads a single component if it's registered as lazy and not yet loaded.
4414
+ * Returns immediately if already loaded or not a lazy component.
4415
+ *
4416
+ * @param componentType - The type of component to load
4417
+ * @returns Promise that resolves when the component is loaded
4418
+ */
4419
+ async loadComponent(componentType) {
4420
+ // Already loaded
4421
+ if (this.loadedComponents.has(componentType)) {
4422
+ return;
4423
+ }
4424
+ // Already loading
4425
+ if (this.loadingPromises.has(componentType)) {
4426
+ return this.loadingPromises.get(componentType);
4427
+ }
4428
+ // Not a lazy component or not registered
4429
+ const loader = this.componentLoaders.get(componentType);
4430
+ if (!loader) {
4431
+ return;
4432
+ }
4433
+ const loadPromise = (async () => {
4434
+ try {
4435
+ const component = await loader();
4436
+ // Update the registry with the loaded component
4437
+ const existingConfig = this.componentRegistry.get(componentType);
4438
+ if (existingConfig) {
4439
+ const updatedConfig = {
4440
+ ...existingConfig,
4441
+ component,
4442
+ };
4443
+ delete updatedConfig._lazy;
4444
+ this.componentRegistry.set(componentType, updatedConfig);
4445
+ }
4446
+ this.loadedComponents.add(componentType);
4447
+ this.loadingPromises.delete(componentType);
4448
+ }
4449
+ catch (error) {
4450
+ this.loadingPromises.delete(componentType);
4451
+ console.error(`Failed to load component '${componentType}':`, error);
4452
+ throw error;
4453
+ }
4454
+ })();
4455
+ this.loadingPromises.set(componentType, loadPromise);
4456
+ return loadPromise;
4457
+ }
4458
+ /**
4459
+ * Loads multiple components in parallel.
4460
+ * Deduplicates requests and uses caching.
4461
+ *
4462
+ * @param componentTypes - Array of component types to load
4463
+ * @returns Promise that resolves when all components are loaded
4464
+ */
4465
+ async loadComponents(componentTypes) {
4466
+ const uniqueTypes = Array.from(new Set(componentTypes));
4467
+ await Promise.all(uniqueTypes.map((type) => this.loadComponent(type)));
4468
+ }
4469
+ /**
4470
+ * Checks if a component is registered as lazy-loadable.
4471
+ *
4472
+ * @param componentType - The type of component to check
4473
+ * @returns true if the component is lazy-loadable
4474
+ */
4475
+ isLazyComponent(componentType) {
4476
+ return this.componentLoaders.has(componentType);
4477
+ }
4478
+ /**
4479
+ * Checks if a lazy component has been loaded.
4480
+ *
4481
+ * @param componentType - The type of component to check
4482
+ * @returns true if the component has been loaded
4483
+ */
4484
+ isComponentLoaded(componentType) {
4485
+ return this.loadedComponents.has(componentType);
4486
+ }
4487
+ /**
4488
+ * Checks if a component has a loader registered (lazy) or is already registered (eager).
4489
+ * This is useful for SSR validation to ensure components are available before rendering.
4490
+ *
4491
+ * @param componentType - The type of component to check
4492
+ * @returns true if the component has a loader or is registered
4493
+ */
4494
+ hasComponentLoader(componentType) {
4495
+ return (this.componentLoaders.has(componentType) ||
4496
+ this.componentRegistry.has(componentType));
4497
+ }
4498
+ /**
4499
+ * Gets all component types that have loaders registered (lazy components).
4500
+ * Useful for debugging and SSR setup validation.
4501
+ *
4502
+ * @returns Array of component types with lazy loaders
4503
+ */
4504
+ getLazyComponentTypes() {
4505
+ return Array.from(this.componentLoaders.keys());
4506
+ }
4507
+ /**
4508
+ * Gets all registered component types (both lazy and eager).
4509
+ * Useful for debugging and validation.
4510
+ *
4511
+ * @returns Array of all registered component types
4512
+ */
4513
+ getAllComponentTypes() {
4514
+ return Array.from(this.componentRegistry.keys());
4515
+ }
4516
+ }
4517
+
4518
+ /**
4519
+ * Singleton instance of ComponentRegistry.
4520
+ * This ensures all packages (studio-client, studio-react, etc.) use the same registry instance.
4521
+ *
4522
+ * Using a singleton pattern here is appropriate because:
4523
+ * 1. There should only be one component registry per application
4524
+ * 2. Multiple packages need to access the same instance
4525
+ * 3. Avoids circular dependencies between packages
4526
+ */
4527
+ let instance = null;
4528
+ /**
4529
+ * Gets the singleton ComponentRegistry instance.
4530
+ * Creates it if it doesn't exist yet.
4531
+ *
4532
+ * @returns The singleton ComponentRegistry instance
4533
+ *
4534
+ * @example
4535
+ * ```typescript
4536
+ * import { getComponentRegistryInstance } from '@contentstack/studio-registry';
4537
+ *
4538
+ * const registry = getComponentRegistryInstance();
4539
+ * await registry.loadComponent('my-component');
4540
+ * ```
4541
+ */
4542
+ function getComponentRegistryInstance() {
4543
+ if (!instance) {
4544
+ instance = new ComponentRegistry();
4545
+ }
4546
+ return instance;
4547
+ }
4548
+ /**
4549
+ * Resets the singleton instance.
4550
+ * Primarily useful for testing to ensure a clean state between tests.
4551
+ *
4552
+ * @example
4553
+ * ```typescript
4554
+ * import { resetComponentRegistryInstance } from '@contentstack/studio-registry';
4555
+ *
4556
+ * beforeEach(() => {
4557
+ * resetComponentRegistryInstance();
4558
+ * });
4559
+ * ```
4560
+ */
4561
+ function resetComponentRegistryInstance() {
4562
+ instance = null;
4563
+ }
4564
+ /**
4565
+ * Checks if the singleton instance has been created.
4566
+ *
4567
+ * @returns true if the instance exists, false otherwise
4568
+ */
4569
+ function hasComponentRegistryInstance() {
4570
+ return instance !== null;
4319
4571
  }
4320
4572
 
4321
4573
  const SIZE_TOKENS = {
@@ -5173,6 +5425,9 @@ class JSONRTERegistry {
5173
5425
  * @returns The path of the CSLP path.
5174
5426
  */
5175
5427
  function getCslpPath(binding) {
5428
+ if (typeof binding !== "string") {
5429
+ return "";
5430
+ }
5176
5431
  const bindingParts = binding.split(".");
5177
5432
  const lastPart = bindingParts.pop();
5178
5433
  const cslpPath = bindingParts.join(".") + ".$." + lastPart;
@@ -5293,6 +5548,92 @@ function removeCurrentBindingKey(entry, bindingMap, currentBindingKey) {
5293
5548
  return [key, newValue];
5294
5549
  }
5295
5550
 
5551
+ /**
5552
+ * Extracts the binding path string from a Contentstack-like binding object.
5553
+ * Flattens nested path objects into a dot-notation string.
5554
+ */
5555
+ const getBindingStringForCS = (binding) => {
5556
+ //TODO: fix this types and data source uid
5557
+ const path = binding.value.path;
5558
+ const flattenPath = (path) => {
5559
+ if (!path || Object.keys(path).length === 0)
5560
+ return "";
5561
+ const key = Object.keys(path)[0];
5562
+ const value = path[key];
5563
+ const flattenValue = flattenPath(value);
5564
+ return flattenValue ? `${key}.${flattenValue}` : key;
5565
+ };
5566
+ return flattenPath(path);
5567
+ };
5568
+
5569
+ const getContentstackBindingString = (binding) => {
5570
+ // STORED AT dataSources.contentstack.ct_uid:euid.<bindingString>
5571
+ const { _content_type_uid, uid } = binding.value;
5572
+ const entryKey = `${_content_type_uid}:${uid}`;
5573
+ return [
5574
+ DATA_SOURCES_PREFIX,
5575
+ DATA_SOURCES.CONTENTSTACK,
5576
+ entryKey,
5577
+ getBindingStringForCS(binding),
5578
+ ]
5579
+ .filter(Boolean)
5580
+ .join(".");
5581
+ };
5582
+
5583
+ const getQueryBindingString = (binding) => {
5584
+ // STORED AT dataSources.query.<queryUID>.<bindingString>
5585
+ // Binding value structure: { queryUID: string, path: CSBindingPath }
5586
+ const { queryUID } = binding.value;
5587
+ const suffix = getBindingStringForCS(binding);
5588
+ // Keep the full path including "data" and "count" - the schema structure is the source of truth
5589
+ const finalPath = [DATA_SOURCES_PREFIX, DATA_SOURCES.QUERY, queryUID, suffix]
5590
+ .filter(Boolean)
5591
+ .join(".");
5592
+ return finalPath;
5593
+ };
5594
+
5595
+ const getRepeaterBindingString = (binding) => {
5596
+ const { repeaterUID } = binding.value;
5597
+ return [
5598
+ DATA_SOURCES_PREFIX,
5599
+ DATA_SOURCES.REPEATER,
5600
+ repeaterUID,
5601
+ "context",
5602
+ getBindingStringForCS(binding),
5603
+ ]
5604
+ .filter(Boolean)
5605
+ .join(".");
5606
+ };
5607
+
5608
+ const getTemplateBindingString = (binding) => {
5609
+ // STORED AT dataSources.template.<bindingString>
5610
+ return [
5611
+ DATA_SOURCES_PREFIX,
5612
+ DATA_SOURCES.TEMPLATE,
5613
+ getBindingStringForCS(binding),
5614
+ ]
5615
+ .filter(Boolean)
5616
+ .join(".");
5617
+ };
5618
+
5619
+ class DataSourceStrategyRegistry {
5620
+ static instance;
5621
+ strategies = new Map();
5622
+ constructor() { }
5623
+ static getInstance() {
5624
+ if (!DataSourceStrategyRegistry.instance) {
5625
+ DataSourceStrategyRegistry.instance = new DataSourceStrategyRegistry();
5626
+ }
5627
+ return DataSourceStrategyRegistry.instance;
5628
+ }
5629
+ register(type, strategy) {
5630
+ this.strategies.set(type, strategy);
5631
+ }
5632
+ get(type) {
5633
+ return this.strategies.get(type);
5634
+ }
5635
+ }
5636
+
5296
5637
  /**
5297
5638
  * Retrieves the default static value for a given property type.
5298
5639
  *
@@ -5365,60 +5706,68 @@ function getPlaceHolderComponent(placeholders, prop, type) {
5365
5706
  : getDefaultPropStaticValue(type);
5366
5707
  return placeholderComponent;
5367
5708
  }
5368
- const getBindingStringForCS = (binding) => {
5369
- //TODO: fix this types and data source uid
5370
- const path = binding.value.path;
5371
- const flattenPath = (path) => {
5372
- if (Object.keys(path).length === 0)
5373
- return "";
5374
- const key = Object.keys(path)[0];
5375
- const value = path[key];
5376
- const flattenValue = flattenPath(value);
5377
- return flattenValue ? `${key}.${flattenValue}` : key;
5378
- };
5379
- return flattenPath(path);
5380
- };
5709
+ // Register default strategies (Side-effect initialization)
5710
+ const registry = DataSourceStrategyRegistry.getInstance();
5711
+ registry.register(DATA_SOURCES.CONTENTSTACK, {
5712
+ getBindingString: (binding) => getContentstackBindingString(binding),
5713
+ });
5714
+ registry.register(DATA_SOURCES.TEMPLATE, {
5715
+ getBindingString: (binding) => getTemplateBindingString(binding),
5716
+ });
5717
+ registry.register(DATA_SOURCES.QUERY, {
5718
+ getBindingString: (binding) => getQueryBindingString(binding),
5719
+ convertPath: (path) => path.split("."),
5720
+ });
5721
+ registry.register(DATA_SOURCES.REPEATER, {
5722
+ getBindingString: (binding) => getRepeaterBindingString(binding),
5723
+ });
5724
+ registry.register(DATA_SOURCES.COMPONENT_PROPS, {
5725
+ getBindingString: (binding) => [DATA_SOURCES.COMPONENT_PROPS, binding.value].filter(Boolean).join("."),
5726
+ });
5727
+ registry.register(DATA_SOURCES.STATIC_VALUE, {
5728
+ getBindingString: (binding) => [DATA_SOURCES.STATIC_VALUE, binding.value].filter(Boolean).join("."),
5729
+ });
5730
+ registry.register(DATA_SOURCES.SYMBOL_PROPS, {
5731
+ getBindingString: (binding) => [DATA_SOURCES.SYMBOL_PROPS, binding.value].filter(Boolean).join("."),
5732
+ });
5381
5733
  const getBindingString = (binding) => {
5382
- if (binding.type === DATA_SOURCES.TEMPLATE) {
5383
- // STORED AT dataSources.template.<bindingString>
5384
- return [
5385
- DATA_SOURCES_PREFIX,
5386
- DATA_SOURCES.TEMPLATE,
5387
- getBindingStringForCS(binding),
5388
- ].join(".");
5389
- }
5390
- if (binding.type === DATA_SOURCES.CONTENTSTACK) {
5391
- // STORED AT dataSources.contentstack.ct_uid:euid.<bindingString>
5392
- const { _content_type_uid, uid } = binding.value;
5393
- const entryKey = `${_content_type_uid}:${uid}`;
5394
- return [
5395
- DATA_SOURCES_PREFIX,
5396
- DATA_SOURCES.CONTENTSTACK,
5397
- entryKey,
5398
- getBindingStringForCS(binding),
5399
- ].join(".");
5400
- }
5401
- if (binding.type === DATA_SOURCES.REPEATER) {
5402
- const { repeaterUID } = binding.value;
5403
- return [
5404
- DATA_SOURCES_PREFIX,
5405
- DATA_SOURCES.REPEATER,
5406
- repeaterUID,
5407
- "context",
5408
- getBindingStringForCS(binding),
5409
- ].join(".");
5410
- }
5411
- if (binding.type === DATA_SOURCES.COMPONENT_PROPS) {
5412
- return [DATA_SOURCES.COMPONENT_PROPS, binding.value].join(".");
5413
- }
5414
- if (binding.type === DATA_SOURCES.STATIC_VALUE) {
5415
- return [DATA_SOURCES.STATIC_VALUE, binding.value].join(".");
5416
- }
5417
- if (binding.type === DATA_SOURCES.SYMBOL_PROPS) {
5418
- return [DATA_SOURCES.SYMBOL_PROPS, binding.value].join(".");
5734
+ const strategy = DataSourceStrategyRegistry.getInstance().get(binding.type);
5735
+ if (strategy) {
5736
+ return strategy.getBindingString(binding);
5419
5737
  }
5738
+ // Fallback for simple string bindings
5420
5739
  return binding.value;
5421
5740
  };
5741
+ const convertBindingPath = (bindingType, path) => {
5742
+ const strategy = DataSourceStrategyRegistry.getInstance().get(bindingType);
5743
+ if (strategy && strategy.convertPath) {
5744
+ return strategy.convertPath(path);
5745
+ }
5746
+ return path;
5747
+ };
5748
+ const getFlattenedData = (data) => {
5749
+ if (data && typeof data === "object" && !Array.isArray(data)) {
5750
+ const keys = Object.keys(data).filter((key) => key !== "$" && key !== "_metadata");
5751
+ if (keys.length === 1) {
5752
+ return getFlattenedData(data[keys[0]]);
5753
+ }
5754
+ }
5755
+ return data;
5756
+ };
5757
+ /**
5758
+ * Composition/static data often stores single-select choice as `string[]` (one element).
5759
+ * `isDataMatchingPropType` treats `choice` as a `string` or `string[]` (multi-select);
5760
+ * single-select stored as `string[]` must still be unwrapped here before the type-mismatch fallback.
5761
+ */
5762
+ function normalizeSingleSelectChoiceValue(resolvedData, prop) {
5763
+ if (prop.type !== "choice" || ("multiSelect" in prop && prop.multiSelect)) {
5764
+ return resolvedData;
5765
+ }
5766
+ if (Array.isArray(resolvedData)) {
5767
+ return resolvedData[0];
5768
+ }
5769
+ return resolvedData;
5770
+ }
5422
5771
  const resolveMetadataBindings = (node, data) => {
5423
5772
  if (!node.metadata?.bindings)
5424
5773
  return;
@@ -5441,13 +5790,18 @@ const getRepeaterContextPath = (binding) => {
5441
5790
  };
5442
5791
  function isDataMatchingPropType(data, type) {
5443
5792
  const dataType = getDataType(data);
5793
+ if (type === "choice") {
5794
+ return (dataType === "string" ||
5795
+ (dataType === "array" &&
5796
+ Array.isArray(data) &&
5797
+ data.every((item) => typeof item === "string")));
5798
+ }
5444
5799
  const map = {
5445
- string: dataType === "string",
5800
+ string: dataType === "string" || dataType === "number" || dataType === "boolean",
5446
5801
  boolean: dataType === "boolean",
5447
5802
  number: dataType === "number",
5448
5803
  object: dataType === "object",
5449
5804
  array: dataType === "array",
5450
- choice: dataType === "string",
5451
5805
  href: dataType === "string",
5452
5806
  imageurl: dataType === "string",
5453
5807
  datestring: dataType === "string",
@@ -5465,6 +5819,14 @@ function getDataType(data) {
5465
5819
  return typeof data;
5466
5820
  }
5467
5821
 
5822
+ const dataSourceCapabilities = {
5823
+ [DATA_SOURCES.CONTENTSTACK]: { supportsCslp: true },
5824
+ [DATA_SOURCES.COMPONENT_PROPS]: { supportsCslp: true },
5825
+ [DATA_SOURCES.TEMPLATE]: { supportsCslp: true },
5826
+ [DATA_SOURCES.REPEATER]: { supportsCslp: true },
5827
+ [DATA_SOURCES.QUERY]: { supportsCslp: true }, // Verified: Query supports CSLP now
5828
+ };
5829
+
5468
5830
  // Responsible for resolving props to values
5469
5831
  function retrievePropValue(args) {
5470
5832
  const { data, componentOptions, node, cslp, placeholders = {}, getSlots, jsonRTE, isCompositionBeingEdited, } = args;
@@ -5504,13 +5866,34 @@ function retrievePropValue(args) {
5504
5866
  return;
5505
5867
  }
5506
5868
  const nodePropConfig = nodeProps[field];
5507
- const { binding: bindedField } = nodePropConfig || {};
5869
+ const { binding: bindedField, value: staticValue } = nodePropConfig || {};
5508
5870
  //TODO: Get proper data for design
5509
5871
  const placeholderComponent = getPlaceHolderComponent(placeholders, prop, type);
5510
- const fallbackValue = defaultValue ?? placeholderComponent;
5872
+ const fallbackValue = staticValue !== undefined
5873
+ ? staticValue
5874
+ : (defaultValue ?? placeholderComponent);
5511
5875
  const dataPath = bindedField && getBindingString(bindedField);
5512
5876
  if ((type === "array" || type === "object") && dataPath) {
5513
- const bindedData = get(data, dataPath);
5877
+ let pathForGet = dataPath;
5878
+ // Use strategy-based path conversion (Agnostic)
5879
+ if (bindedField?.type && typeof dataPath === "string") {
5880
+ pathForGet = convertBindingPath(bindedField.type, dataPath);
5881
+ }
5882
+ let bindedData = get(data, pathForGet);
5883
+ // Strictly handle QueryResult { entries: Entry[], count: number } structure.
5884
+ // If we're expecting an array and the bindedData matches the QueryResult pattern,
5885
+ // we extract the entries array.
5886
+ if (type === "array" &&
5887
+ bindedData &&
5888
+ typeof bindedData === "object" &&
5889
+ !Array.isArray(bindedData) &&
5890
+ "entries" in bindedData &&
5891
+ Array.isArray(bindedData.entries)) {
5892
+ bindedData = bindedData.entries;
5893
+ }
5894
+ // Note: If bindedData is a direct array [], it will fall through.
5895
+ // As per the requirement "expects {result: [], count: number} only and no direct []",
5896
+ // we are now enforcing the unwrapping for the expected object structure.
5514
5897
  const bindingMap = nodePropConfig.bindingMap;
5515
5898
  const isBindingMapEmpty = Object.keys(bindingMap || {}).length === 0;
5516
5899
  const transformedData = !isBindingMapEmpty
@@ -5518,21 +5901,35 @@ function retrievePropValue(args) {
5518
5901
  : bindedData;
5519
5902
  resolvedData = transformedData ?? fallbackValue;
5520
5903
  if (type === "array") {
5521
- const cslpObj = getCslpTag({ bindedField: dataPath, data });
5522
- if (cslpObj["data-cslp"]) {
5523
- mappedData[`$${field}Items`] = transformedData.map((_, idx) => {
5524
- return { "data-cslp": `${cslpObj["data-cslp"]}.$${idx}` };
5525
- });
5904
+ const isCSLPAbleType = bindedField?.type &&
5905
+ dataSourceCapabilities[bindedField.type]?.supportsCslp;
5906
+ if (cslp.appendTags &&
5907
+ isCSLPAbleType &&
5908
+ Array.isArray(transformedData)) {
5909
+ const cslpObj = getCslpTag({ bindedField: dataPath, data });
5910
+ if (cslpObj["data-cslp"]) {
5911
+ mappedData[`$${field}Items`] = transformedData.map((_, idx) => {
5912
+ return { "data-cslp": `${cslpObj["data-cslp"]}.$${idx}` };
5913
+ });
5914
+ }
5915
+ }
5916
+ if (isCompositionBeingEdited &&
5917
+ isCSLPAbleType &&
5918
+ Array.isArray(resolvedData) &&
5919
+ resolvedData.length === 0) {
5920
+ resolvedData = [{}];
5526
5921
  }
5527
5922
  }
5528
5923
  }
5529
- else if (dataPath) {
5924
+ else if (dataPath &&
5925
+ !(type === "choice" && bindedField?.type === "static_value")) {
5530
5926
  resolvedData = get(data, dataPath, fallbackValue);
5531
5927
  // Handle primitive values in repeater context
5532
5928
  // When the array contains primitives (strings, numbers, etc.) instead of objects,
5533
5929
  // the binding path will be like: dataSources.repeater.{uid}.context.{fieldName}
5534
5930
  // But context IS the primitive value, so accessing context.fieldName returns undefined.
5535
5931
  // In this case, we should return the context itself.
5932
+ let handledRepeaterContext = false;
5536
5933
  if (dataPath.includes("dataSources.repeater")) {
5537
5934
  const pathParts = dataPath.split(".");
5538
5935
  // Check if path is: dataSources.repeater.{uid}.context.{fieldName}
@@ -5545,29 +5942,76 @@ function retrievePropValue(args) {
5545
5942
  const isPrimitive = typeof contextValue !== "object" || contextValue === null;
5546
5943
  if (isPrimitive) {
5547
5944
  resolvedData = contextValue;
5945
+ handledRepeaterContext = true;
5548
5946
  }
5549
5947
  }
5550
5948
  }
5551
5949
  }
5552
- if (type === "choice") {
5553
- if (!prop.multiSelect) {
5554
- // we are explicitly checking for single select choice type to ensure we don't have a mismatch in the data type.
5555
- if (Array.isArray(resolvedData)) {
5556
- resolvedData = resolvedData[0];
5950
+ // Unwrap single-key objects (common in Contentstack Modular Blocks)
5951
+ // We only do this if we are not explicitly expecting an object or array.
5952
+ // Skip if we already handled the repeater context case above.
5953
+ if (type !== "object" && type !== "array" && !handledRepeaterContext) {
5954
+ resolvedData = getFlattenedData(resolvedData);
5955
+ resolvedData = normalizeSingleSelectChoiceValue(resolvedData, prop);
5956
+ // Fallback to static value if the resolved data is still not matching the expected primitive type
5957
+ // This ensures that if a binding returns an object (e.g. during a structural change), we don't crash React
5958
+ // and instead show the static value entered by the user.
5959
+ if (!isDataMatchingPropType(resolvedData, type)) {
5960
+ if (type === "string") {
5961
+ const actualType = getDataType(resolvedData);
5962
+ if (actualType === "object" || actualType === "array") {
5963
+ resolvedData =
5964
+ "This content may not display correctly in this view. Please contact your development team to update the component so it can support this type of content.";
5965
+ }
5966
+ else {
5967
+ resolvedData =
5968
+ staticValue !== undefined ? staticValue : fallbackValue;
5969
+ }
5970
+ }
5971
+ else {
5972
+ resolvedData =
5973
+ staticValue !== undefined ? staticValue : fallbackValue;
5557
5974
  }
5558
5975
  }
5559
5976
  }
5977
+ // Normalize data type: convert arrays to single values for single-select props
5978
+ if (type === "choice" &&
5979
+ !prop.multiSelect &&
5980
+ Array.isArray(resolvedData)) {
5981
+ // Single-select props (choice, etc.) should receive single values, not arrays
5982
+ resolvedData = resolvedData[0];
5983
+ }
5560
5984
  }
5561
5985
  else {
5562
- resolvedData = fallbackValue;
5563
- // TODO: THIS IS A TEMPORARY FIX TO HANDLE THE CASE WHERE THE DATA TYPE IS NOT MATCHING THE PROP TYPE. WE WILL REMOVE THIS ELSE BLOCK.
5564
- if (type === "choice") {
5565
- if (!prop.multiSelect) {
5566
- // we are explicitly checking for single select choice type to ensure we don't have a mismatch in the data type.
5567
- if (Array.isArray(resolvedData)) {
5568
- resolvedData = resolvedData[0];
5986
+ // For choice props, explicitly retrieve saved values from static content store
5987
+ if (type === "choice" && bindedField?.type === "static_value") {
5988
+ const staticContentKey = bindedField.value; // e.g., "B575hDbLkWhPSfB-alignment"
5989
+ // Try to find the saved value in the static content store
5990
+ let savedValue = undefined;
5991
+ // Check if we have access to the static_value from data
5992
+ if (data.static_value && typeof data.static_value === "object") {
5993
+ // Look for the value directly by key
5994
+ if (typeof staticContentKey === "string") {
5995
+ savedValue = data.static_value[staticContentKey];
5569
5996
  }
5570
5997
  }
5998
+ if (savedValue !== undefined) {
5999
+ resolvedData = savedValue;
6000
+ }
6001
+ else {
6002
+ resolvedData =
6003
+ staticValue !== undefined ? staticValue : fallbackValue;
6004
+ }
6005
+ }
6006
+ else {
6007
+ resolvedData = staticValue !== undefined ? staticValue : fallbackValue;
6008
+ }
6009
+ // Normalize data type: convert arrays to single values for single-select props
6010
+ if (type === "choice" &&
6011
+ !prop.multiSelect &&
6012
+ Array.isArray(resolvedData)) {
6013
+ // Single-select props (choice, etc.) should receive single values, not arrays
6014
+ resolvedData = resolvedData[0];
5571
6015
  }
5572
6016
  }
5573
6017
  // TODO: @ravencolevol: In case of the missing string value, we are providing a placeholder component, failing this check. We have to revisit the placeholder component logic.
@@ -5606,13 +6050,8 @@ function retrievePropValue(args) {
5606
6050
  if (type === "json_rte") {
5607
6051
  mappedData["jsonConfig"] = jsonRTE;
5608
6052
  }
5609
- const cslpAbleTypes = [
5610
- DATA_SOURCES.CONTENTSTACK,
5611
- DATA_SOURCES.COMPONENT_PROPS,
5612
- DATA_SOURCES.TEMPLATE,
5613
- DATA_SOURCES.REPEATER,
5614
- ];
5615
- const isCSLPAbleType = bindedField?.type && cslpAbleTypes.includes(bindedField.type);
6053
+ const isCSLPAbleType = bindedField?.type &&
6054
+ dataSourceCapabilities[bindedField.type]?.supportsCslp;
5616
6055
  if (cslp.appendTags && dataPath && isCSLPAbleType) {
5617
6056
  const cslpValue = getCslpTag({ bindedField: dataPath, data });
5618
6057
  if (cslpValue) {
@@ -5726,20 +6165,26 @@ exports.JSONRTERegistry = JSONRTERegistry;
5726
6165
  exports.STYLE_SECTIONS_OPTIONS = STYLE_SECTIONS_OPTIONS;
5727
6166
  exports.STYLE_SECTION_CATEGORIES = STYLE_SECTION_CATEGORIES;
5728
6167
  exports.SYSTEM_COMPONENTS = SYSTEM_COMPONENTS;
6168
+ exports.convertBindingPath = convertBindingPath;
5729
6169
  exports.getBindingString = getBindingString;
6170
+ exports.getComponentRegistryInstance = getComponentRegistryInstance;
5730
6171
  exports.getCslpPath = getCslpPath;
5731
6172
  exports.getCslpTag = getCslpTag;
5732
6173
  exports.getDataType = getDataType;
5733
6174
  exports.getDefaultPropStaticValue = getDefaultPropStaticValue;
5734
6175
  exports.getDesignClassesNames = getDesignClassesNames;
6176
+ exports.getFlattenedData = getFlattenedData;
5735
6177
  exports.getPlaceHolderComponent = getPlaceHolderComponent;
5736
6178
  exports.getRepeaterBinding = getRepeaterBinding;
5737
6179
  exports.getRepeaterContextPath = getRepeaterContextPath;
5738
6180
  exports.getSlotData = getSlotData;
5739
6181
  exports.getSymbolUIDFromNode = getSymbolUIDFromNode;
5740
6182
  exports.getSymbolUIDFromUID = getSymbolUIDFromUID;
6183
+ exports.hasComponentRegistryInstance = hasComponentRegistryInstance;
5741
6184
  exports.isDataMatchingPropType = isDataMatchingPropType;
5742
6185
  exports.isKnownType = isKnownType;
6186
+ exports.normalizeSingleSelectChoiceValue = normalizeSingleSelectChoiceValue;
6187
+ exports.resetComponentRegistryInstance = resetComponentRegistryInstance;
5743
6188
  exports.resolveMetadataBindings = resolveMetadataBindings;
5744
6189
  exports.retrievePropValue = retrievePropValue;
5745
6190
  //# sourceMappingURL=index.cjs.map