@contentstack/studio-client 1.5.0 → 1.6.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 (39) hide show
  1. package/dist/composable-studio/sdk.js +335 -54
  2. package/dist/composable-studio/sdk.js.map +1 -1
  3. package/dist/composable-studio/studio-intelligence.manager.js +135 -0
  4. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -0
  5. package/dist/config/stack-sdk-wrapper.js +2 -2
  6. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  7. package/dist/design/handle-active-style-change.js +0 -3
  8. package/dist/design/handle-active-style-change.js.map +1 -1
  9. package/dist/dnd/dnd-manager.js +25 -7
  10. package/dist/dnd/dnd-manager.js.map +1 -1
  11. package/dist/dnd/{utils.js → scroll-utils.js} +2 -27
  12. package/dist/dnd/scroll-utils.js.map +1 -0
  13. package/dist/hidden-element-notification/hidden-element-notification-event.js +7 -0
  14. package/dist/hidden-element-notification/hidden-element-notification-event.js.map +1 -1
  15. package/dist/highlight-node/highlight-node-manager.js +7 -1
  16. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  17. package/dist/highlight-node/highlight-node.js +4 -4
  18. package/dist/highlight-node/highlight-node.js.map +1 -1
  19. package/dist/index.d.ts +39 -12
  20. package/dist/index.js +3 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/shared/dnd-events.js +39 -0
  23. package/dist/shared/dnd-events.js.map +1 -0
  24. package/dist/utils/composable-studio-error.js +1 -0
  25. package/dist/utils/composable-studio-error.js.map +1 -1
  26. package/dist/utils/conditionBlock.js +1 -1
  27. package/dist/utils/conditionBlock.js.map +1 -1
  28. package/dist/utils/constants.js +4 -1
  29. package/dist/utils/constants.js.map +1 -1
  30. package/dist/utils/error-messages.default.js +1 -1
  31. package/dist/utils/error-messages.default.js.map +1 -1
  32. package/dist/utils/http-error.constants.js +11 -2
  33. package/dist/utils/http-error.constants.js.map +1 -1
  34. package/dist/utils/reference_fetcher.js +8 -18
  35. package/dist/utils/reference_fetcher.js.map +1 -1
  36. package/dist/utils/spec-analyzer.js +95 -0
  37. package/dist/utils/spec-analyzer.js.map +1 -0
  38. package/package.json +13 -9
  39. package/dist/dnd/utils.js.map +0 -1
@@ -1,22 +1,28 @@
1
- import { COMPOSABLE_STUDIO_QUERY_PARAM } from '@contentstack/studio-messenger';
2
- import { DATA_SOURCES, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
1
+ import { COMPOSABLE_STUDIO_QUERY_PARAM, composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
2
+ import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
3
  import { pick } from 'lodash-es';
4
4
  import { processUserConfig } from '../config/process-user-config.js';
5
5
  import { getCompositionFromSlug } from '../get-composition-from-slug/get-composition-from-slug.js';
6
- import { INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
6
+ import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
7
7
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
8
8
  import { setTemplateEntryInDS, entriesFromResponse, setStaticEntryInDS } from '../utils/sdk.js';
9
9
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
10
10
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
11
- import { getEntriesQueries } from '../utils/reference_fetcher.js';
12
- import { preProcessStaticValues } from './data/pre-process-static-values.js';
11
+ import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
13
12
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
13
+ import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
14
14
  import { getUrlPatterns } from '../utils/get-url-patterns.js';
15
15
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
16
- import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
16
+ import { getEntriesQueries } from '../utils/reference_fetcher.js';
17
+ import { preProcessStaticValues } from './data/pre-process-static-values.js';
18
+ import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
17
19
  import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
18
20
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
19
21
 
22
+ // ✅ HYBRID APPROACH: List of internal components that should always be available
23
+ // These include both built-in components AND system components (like "page")
24
+ // All are registered synchronously during React initialization via getBasicComponents()
25
+ const INTERNAL_COMPONENT_TYPES = Object.values(INTERNAL_COMPONENTS_NAMES);
20
26
  function getAuthErrorMessage(err) {
21
27
  const detail = err?.error_message ||
22
28
  err?.errors?.api_key?.[0] ||
@@ -45,18 +51,39 @@ function classifyApiError(err) {
45
51
  message: getAuthErrorMessage(err),
46
52
  };
47
53
  }
54
+ // Check for empty entry response (200 OK but no entries found)
55
+ // This happens when API succeeds but returns empty entry list
56
+ // Note: Pure empty objects {} should be treated as network errors, not empty responses
57
+ const isEmptyEntryResponse = statusCode === 200 &&
58
+ err &&
59
+ typeof err === "object" &&
60
+ err.entries &&
61
+ Array.isArray(err.entries) &&
62
+ err.entries.length === 0;
63
+ if (isEmptyEntryResponse) {
64
+ return {
65
+ errorType: ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND,
66
+ message: getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
67
+ contentType: "the composition",
68
+ }),
69
+ };
70
+ }
48
71
  // Check for network errors (no response, timeout, connection refused)
49
- // Empty response object often indicates network failure
50
- const isEmptyResponse = err && typeof err === "object" && Object.keys(err).length === 0;
51
- if ((!statusCode && isNetworkError(err)) || isEmptyResponse) {
72
+ if (!statusCode && isNetworkError(err)) {
73
+ // For empty objects, use the specific empty error message
74
+ if (typeof err === "object" && Object.keys(err).length === 0) {
75
+ return {
76
+ errorType: ComposableStudioErrors.NETWORK_ERROR,
77
+ message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY),
78
+ };
79
+ }
80
+ // For other network errors, use the generic message with detail
52
81
  return {
53
82
  errorType: ComposableStudioErrors.NETWORK_ERROR,
54
- message: isEmptyResponse
55
- ? getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY)
56
- : getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
57
- detail: err?.message ||
58
- getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
59
- }),
83
+ message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
84
+ detail: err?.message ||
85
+ getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
86
+ }),
60
87
  };
61
88
  }
62
89
  // Check for 404 - composition not found
@@ -293,12 +320,73 @@ function getParentTagsValue(dataValue, tagsAsObject) {
293
320
  return { "data-cslp-parent-field": dataValue };
294
321
  }
295
322
  }
323
+ /**
324
+ * Legacy variable removed - SDK initialization is now handled by INIT_STUDIO system
325
+ * @deprecated - was used for old sdk-initialized handshake, now consolidated to INIT_STUDIO
326
+ */
327
+ /**
328
+ * Dev-only console logs for SDK init. `process.env.NODE_ENV` can be wrong inside Vite’s
329
+ * prebundled `@contentstack/studio-client` graph — use `?csSdkDebug=1` on the canvas URL or
330
+ * `localStorage.setItem('csSdkDebug','1')` + reload to force logs on.
331
+ */
332
+ function isSdkInitDebugEnabled() {
333
+ if (typeof window !== "undefined") {
334
+ try {
335
+ if (new URLSearchParams(window.location.search).get("csSdkDebug") === "1") {
336
+ return true;
337
+ }
338
+ if (window.localStorage?.getItem("csSdkDebug") === "1") {
339
+ return true;
340
+ }
341
+ }
342
+ catch {
343
+ /* ignore */
344
+ }
345
+ }
346
+ return (typeof process !== "undefined" && process.env.NODE_ENV === "development");
347
+ }
348
+ /**
349
+ * 🚀 RESTORED: Send INIT_STUDIO via Advanced Post Message from the right place
350
+ * This fires IMMEDIATELY when SDK is created, ensuring proper timing (like original handshake)
351
+ */
352
+ function sendInitStudioSignal(config) {
353
+ try {
354
+ const initPayload = {
355
+ sdkVersion: SDK_VERSION,
356
+ schemaVersion: SCHEMA_VERSION,
357
+ sdkFramework: "react",
358
+ timestamp: Date.now(),
359
+ globalLocale: config.locale,
360
+ globalVariantAlias: undefined, // Config doesn't have variantAlias - handled per query
361
+ requestedUrl: window.location.href,
362
+ uid: `sdk-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
363
+ };
364
+ // Send via Advanced Post Message using static imports
365
+ composableStudioEventManager
366
+ ?.send(POST_MESSAGE_EVENTS.INIT_STUDIO, initPayload)
367
+ .catch((error) => {
368
+ console.warn("⚠️ SDK: INIT_STUDIO failed:", error);
369
+ });
370
+ }
371
+ catch (error) {
372
+ console.warn("⚠️ SDK: Could not send INIT_STUDIO from generateSdk:", error);
373
+ }
374
+ }
296
375
  function generateSdk(userConfig) {
297
376
  const config = processUserConfig(userConfig);
377
+ // ✅ HYBRID APPROACH: Register internal components immediately during SDK init
378
+ // This ensures all internal components (page, section, text, etc.) are available
379
+ // ✅ HYBRID APPROACH: Component registration moved to React layer (useStudioInit)
380
+ // This avoids cyclic dependencies while ensuring components are available before fetchSpec
298
381
  if (clientRendererModeUtil.isInsideStudioFrame()) {
299
382
  const hash = new URLSearchParams(window.location.search).get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
300
383
  config.stackSdk.livePreviewQuery?.(hash);
301
384
  }
385
+ isSdkInitDebugEnabled();
386
+ // REMOVED: sendSDKInitializedSignal - replaced by INIT_STUDIO via Advanced Post Message
387
+ // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
388
+ // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
389
+ // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
302
390
  async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
303
391
  const { variantAlias, locale } = options;
304
392
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
@@ -345,17 +433,23 @@ function generateSdk(userConfig) {
345
433
  }
346
434
  else {
347
435
  //TODO: Add logger support general to have studio prefix
348
- console.error("Unable to resolve entry", entry.reason);
436
+ if (process.env.NODE_ENV === "development") {
437
+ console.log("Message handling fallback");
438
+ }
349
439
  }
350
440
  }
351
441
  }
352
442
  else {
353
- console.error("Unable to resolve content type", ct_uid, ct_entries.reason);
443
+ if (process.env.NODE_ENV === "development") {
444
+ console.log("Unhandled message case");
445
+ }
354
446
  }
355
447
  }
356
448
  }
357
- catch (err) {
358
- console.error("Error while resolving static data", err);
449
+ catch (error) {
450
+ if (process.env.NODE_ENV === "development") {
451
+ console.error("Error in message listener:", error);
452
+ }
359
453
  }
360
454
  }
361
455
  /**
@@ -364,7 +458,6 @@ function generateSdk(userConfig) {
364
458
  */
365
459
  async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
366
460
  if (!config.stackSdk) {
367
- console.error("Fetching template entry not possible without stackSdk");
368
461
  return;
369
462
  }
370
463
  const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
@@ -372,33 +465,42 @@ function generateSdk(userConfig) {
372
465
  return;
373
466
  }
374
467
  const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
468
+ // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
469
+ const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
470
+ const _studioIntelligence = enhancedOptions?._studioIntelligence;
471
+ const _enhancementMode = enhancedOptions?._enhancementMode;
375
472
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
473
+ const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
474
+ const isStudioAware = _enhancementMode === "studio-aware";
376
475
  const defaultImpl = async () => {
476
+ // Enhanced include queries with Studio Intelligence
477
+ const allIncludeQueries = [
478
+ ...includeQueries,
479
+ ...(_studioIntelligence?.includeReferences || []),
480
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
377
481
  const queryOptions = {
378
- references: includeQueries,
482
+ references: allIncludeQueries,
379
483
  variantAlias: resolvedOptions.variantAlias,
380
484
  locale: resolvedOptions.locale || config.locale,
381
485
  };
382
- if (!isInsideVB) {
486
+ // Smart 'only' parameter handling - ignore in Visual Builder OR Studio-aware mode
487
+ if (!isInsideVB && !(isInsideStudio && isStudioAware)) {
383
488
  queryOptions.only = onlyQueries;
384
489
  }
490
+ // When Studio-aware: Skip 'only' to fetch all fields for data binding
385
491
  let dataQuery = config.stackSdk
386
492
  .ctQuery(connected_content_type, queryOptions)
387
493
  .limit(1);
388
- // Resolution priority: templateEntryUid > url > first entry
494
+ // Resolution priority: templateEntryUid > url > first entry (original logic)
389
495
  if (resolvedOptions.templateEntryUid) {
496
+ console.log("📌 SDK using templateEntryUid:", resolvedOptions.templateEntryUid);
390
497
  dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
391
498
  }
392
- else if ("url" in compositionQuery) {
499
+ else if ("url" in compositionQuery && compositionQuery.url) {
393
500
  dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
394
501
  }
395
502
  const response = await dataQuery.find().catch((err) => {
396
503
  const { errorType, message } = classifyApiError(err);
397
- console.error("SDK Error (connected data):", {
398
- errorType,
399
- message,
400
- originalError: err,
401
- });
402
504
  const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
403
505
  ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
404
506
  : errorType;
@@ -413,11 +515,20 @@ function generateSdk(userConfig) {
413
515
  });
414
516
  });
415
517
  const entries = entriesFromResponse(response);
518
+ console.log("📥 SDK Template Entry Query Response:", {
519
+ totalEntries: entries?.length || 0,
520
+ firstEntry: entries?.[0]
521
+ ? {
522
+ uid: entries[0].uid,
523
+ title: entries[0].title,
524
+ url: entries[0].url,
525
+ }
526
+ : null,
527
+ allEntryTitles: entries?.map((e) => e.title) || [],
528
+ connectedContentType: connected_content_type,
529
+ queryUrl: "url" in compositionQuery ? compositionQuery.url : "no-url",
530
+ });
416
531
  if (!entries?.[0]) {
417
- console.error("Preview/Template entry not found", {
418
- contentType: connected_content_type,
419
- compositionQuery,
420
- });
421
532
  throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
422
533
  contentType: connected_content_type,
423
534
  }), {
@@ -451,6 +562,12 @@ function generateSdk(userConfig) {
451
562
  }
452
563
  else {
453
564
  entry = await defaultImpl();
565
+ // Check if defaultImpl returned empty/null entry (e.g., empty entry list from API)
566
+ if (!entry) {
567
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
568
+ contentType: connected_content_type,
569
+ }));
570
+ }
454
571
  }
455
572
  if (config.cslp.appendTags) {
456
573
  addEditableTags(entry, connected_content_type, true, entry.locale);
@@ -485,23 +602,182 @@ function generateSdk(userConfig) {
485
602
  ]);
486
603
  return data;
487
604
  }
488
- async function fetchSpec(queryOptions, options) {
605
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
489
606
  if (!config.stackSdk) {
490
607
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
491
608
  }
492
- const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions, options);
493
- const data = await fetchData(compositionEntry, queryOptions, options);
609
+ // Phase 1: Get Studio Intelligence if available (graceful fallback)
610
+ const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
611
+ // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
612
+ const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
613
+ // Phase 3: Fetch with enhanced context (preserves custom fetchers)
614
+ const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions, enhancedOptions);
615
+ const data = await fetchData(compositionEntry, queryOptions, enhancedOptions);
494
616
  const ui = typeof compositionEntry.ui === "string"
495
617
  ? decompressSpec(compositionEntry.ui)
496
618
  : compositionEntry.ui;
619
+ // Lazy loading and SSR validation for production mode
620
+ // Skip if called from fetchMultipleSpecs (which handles loading in batch)
621
+ const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
622
+ if (isProductionMode && ui && !skipComponentLoading) {
623
+ const componentRegistry = getComponentRegistryInstance();
624
+ // SSR VALIDATION: Check if all required components are registered
625
+ // Built-in components should be registered automatically when @contentstack/studio-react is imported
626
+ const usedComponents = analyzeUsedComponents(ui);
627
+ const missingBuiltInComponents = [];
628
+ const missingCustomComponents = [];
629
+ usedComponents.forEach((type) => {
630
+ if (!componentRegistry.hasComponentLoader(type)) {
631
+ if (INTERNAL_COMPONENT_TYPES.includes(type)) {
632
+ missingBuiltInComponents.push(type);
633
+ }
634
+ else {
635
+ missingCustomComponents.push(type);
636
+ }
637
+ }
638
+ });
639
+ // Handle missing internal components (SDK import issue)
640
+ if (missingBuiltInComponents.length > 0) {
641
+ const errorMessage = [
642
+ `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
643
+ "",
644
+ "❌ Built-in components should be automatically available when importing the SDK.",
645
+ "This indicates a build, import, or packaging issue.",
646
+ "",
647
+ "Ensure you're importing from @contentstack/studio-react:",
648
+ ' import { useCompositionData } from "@contentstack/studio-react";',
649
+ "",
650
+ "If using a bundler, verify the package is properly resolved and built.",
651
+ "Check for console errors during module import.",
652
+ "",
653
+ "Manual registration workaround:",
654
+ ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
655
+ ' import { getBasicComponents } from "@contentstack/studio-react-components";',
656
+ "",
657
+ " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
658
+ " registerComponents(components);",
659
+ ].join("\n");
660
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
661
+ }
662
+ // Handle missing custom components (normal - user needs to register)
663
+ if (missingCustomComponents.length > 0) {
664
+ const errorMessage = [
665
+ `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
666
+ "",
667
+ "This error occurs when fetchSpec() is called before custom components are registered.",
668
+ "In SSR environments, ensure all registerComponent() calls complete before fetchSpec().",
669
+ "",
670
+ "Fix: Import your component registry module at the top of your server file:",
671
+ ' import "./components/registry"; // Register custom components',
672
+ " const spec = await fetchSpec({ ... }); // Now safe to use",
673
+ "",
674
+ ].join("\n");
675
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
676
+ }
677
+ // Load the components
678
+ try {
679
+ await componentRegistry.loadComponents(Array.from(usedComponents));
680
+ }
681
+ catch (error) {
682
+ console.error("Error loading components lazily:", error);
683
+ throw error; // Re-throw to surface the actual loading error
684
+ }
685
+ }
497
686
  return {
498
687
  data,
499
688
  ui,
500
689
  compositionEntry,
501
690
  symbols: symbolEntries,
502
- config: getLightConfig(),
691
+ config: {
692
+ ...getLightConfig(),
693
+ // Debug information for compatibility checking (type assertion for internal properties)
694
+ _studioEnhanced: enhancedOptions._enhancementMode === "studio-aware",
695
+ _enhancementMode: enhancedOptions._enhancementMode,
696
+ },
503
697
  };
504
698
  }
699
+ async function fetchMultipleSpecs(queries, options) {
700
+ if (!config.stackSdk) {
701
+ throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
702
+ }
703
+ // Fetch all specs in parallel (skip individual component loading)
704
+ const specs = await Promise.all(queries.map((query) => fetchSpec(query, options, true)));
705
+ // In production mode, perform union analysis and load components once
706
+ const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
707
+ if (isProductionMode) {
708
+ const componentRegistry = getComponentRegistryInstance();
709
+ // Collect all unique component types from all specs
710
+ // Built-in components should be registered automatically when @contentstack/studio-react is imported
711
+ const allComponents = new Set();
712
+ specs.forEach((spec) => {
713
+ if (spec.ui) {
714
+ const components = analyzeUsedComponents(spec.ui);
715
+ components.forEach((c) => allComponents.add(c));
716
+ }
717
+ });
718
+ // SSR VALIDATION: Check if all required components are registered
719
+ const missingBuiltInComponents = [];
720
+ const missingCustomComponents = [];
721
+ allComponents.forEach((type) => {
722
+ if (!componentRegistry.hasComponentLoader(type)) {
723
+ if (INTERNAL_COMPONENT_TYPES.includes(type)) {
724
+ missingBuiltInComponents.push(type);
725
+ }
726
+ else {
727
+ missingCustomComponents.push(type);
728
+ }
729
+ }
730
+ });
731
+ // Handle missing internal components (SDK import issue)
732
+ if (missingBuiltInComponents.length > 0) {
733
+ const errorMessage = [
734
+ `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
735
+ "",
736
+ "❌ Built-in components should be automatically available when importing the SDK.",
737
+ "This indicates a build, import, or packaging issue.",
738
+ "",
739
+ "Ensure you're importing from @contentstack/studio-react:",
740
+ ' import { useCompositionData } from "@contentstack/studio-react";',
741
+ "",
742
+ "If using a bundler, verify the package is properly resolved and built.",
743
+ "Check for console errors during module import.",
744
+ "",
745
+ "Manual registration workaround:",
746
+ ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
747
+ ' import { getBasicComponents } from "@contentstack/studio-react-components";',
748
+ "",
749
+ " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
750
+ " registerComponents(components);",
751
+ ].join("\n");
752
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
753
+ }
754
+ // Handle missing custom components (normal - user needs to register)
755
+ if (missingCustomComponents.length > 0) {
756
+ const errorMessage = [
757
+ `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
758
+ "",
759
+ "This error occurs when fetchMultipleSpecs() is called before custom components are registered.",
760
+ "In SSR environments, ensure all registerComponent() calls complete before fetchMultipleSpecs().",
761
+ "",
762
+ "Fix: Import your component registry module at the top of your server file:",
763
+ ' import "./components/registry"; // Register custom components',
764
+ " const specs = await fetchMultipleSpecs([...]); // Now safe to use",
765
+ "",
766
+ `Missing components: ${missingCustomComponents.join(", ")}`,
767
+ ].join("\n");
768
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
769
+ }
770
+ // Load all unique components in parallel (deduplication happens automatically)
771
+ try {
772
+ await componentRegistry.loadComponents(Array.from(allComponents));
773
+ }
774
+ catch (error) {
775
+ console.error("Error loading components for multiple specs:", error);
776
+ throw error; // Re-throw to surface the actual loading error
777
+ }
778
+ }
779
+ return specs;
780
+ }
505
781
  /**
506
782
  * Reusable helper to fetch data from Contentstack
507
783
  * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
@@ -512,7 +788,6 @@ function generateSdk(userConfig) {
512
788
  */
513
789
  async function fetchContentstackData(querySpec, context = {}, options) {
514
790
  if (!config.stackSdk) {
515
- console.warn("Stack SDK not available for fetchContentstackData");
516
791
  return { entries: [], count: 0 };
517
792
  }
518
793
  try {
@@ -536,8 +811,10 @@ function generateSdk(userConfig) {
536
811
  count: count,
537
812
  };
538
813
  }
539
- catch (err) {
540
- console.error(`[SDK] Failed to fetch data for ${querySpec.contentType}`, err);
814
+ catch (error) {
815
+ if (process.env.NODE_ENV === "development") {
816
+ console.error("Error resolving query data:", error);
817
+ }
541
818
  return { entries: [], count: 0 };
542
819
  }
543
820
  }
@@ -550,8 +827,10 @@ function generateSdk(userConfig) {
550
827
  const parsed = JSON.parse(compositionEntry.data_sources);
551
828
  dataSources = Array.isArray(parsed) ? parsed : Object.values(parsed);
552
829
  }
553
- catch (e) {
554
- console.warn("[SDK] Failed to parse data_sources from composition", e);
830
+ catch (error) {
831
+ if (process.env.NODE_ENV === "development") {
832
+ console.error("Error parsing data sources JSON:", error);
833
+ }
555
834
  return;
556
835
  }
557
836
  const queriesDS = dataSources.find((ds) => ds.uid === "contentstack_queries" || ds.id === "contentstack_queries");
@@ -599,7 +878,7 @@ function generateSdk(userConfig) {
599
878
  function getSeoMetadata(ui) {
600
879
  return ui.metadata.seo || null;
601
880
  }
602
- return {
881
+ const sdkSingleton = {
603
882
  internal: {
604
883
  getConfig() {
605
884
  return config;
@@ -608,6 +887,7 @@ function generateSdk(userConfig) {
608
887
  // Once we fetch the data, we need to perform certain operation to store the UI and data.
609
888
  // Hence, we moved this to the internal method.
610
889
  fetchSpec,
890
+ fetchMultipleSpecs,
611
891
  fetchData,
612
892
  fetchTemplateEntry,
613
893
  getSeoMetadata,
@@ -690,13 +970,24 @@ function generateSdk(userConfig) {
690
970
  getConfig: getLightConfig,
691
971
  },
692
972
  };
973
+ // 🚀 RESTORED: Send INIT_STUDIO immediately like the original handshake (synchronous)
974
+ if (typeof window !== "undefined") {
975
+ if (clientRendererModeUtil.isInsideStudioFrame()) {
976
+ // Inside Studio iframe - send INIT_STUDIO
977
+ sendInitStudioSignal(config);
978
+ }
979
+ else if (clientRendererModeUtil.isInsideIframe()) {
980
+ // Inside preview iframe - send INIT_STUDIO
981
+ sendInitStudioSignal(config);
982
+ }
983
+ }
984
+ return sdkSingleton;
693
985
  }
694
986
  const parseUI = (ui) => {
695
987
  try {
696
988
  return decompressSpec(ui);
697
989
  }
698
990
  catch (error) {
699
- console.error("UI parsing error", error);
700
991
  throw new ComposableStudioError(ComposableStudioErrors.UI_PARSING_ERROR, getErrorMessage(ErrorMessageKey.UI_PARSING_ERROR), { ui, error });
701
992
  }
702
993
  };
@@ -750,11 +1041,6 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
750
1041
  if (err instanceof ComposableStudioError)
751
1042
  throw err;
752
1043
  const { errorType, message } = classifyApiError(err);
753
- console.error("SDK Error:", {
754
- errorType,
755
- message,
756
- originalError: err,
757
- });
758
1044
  throw new ComposableStudioError(errorType, message, {
759
1045
  compositionUid: queryOptions.composableUid,
760
1046
  hasStackSdk: !!config.stackSdk,
@@ -808,11 +1094,6 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
808
1094
  if (err instanceof ComposableStudioError)
809
1095
  throw err;
810
1096
  const { errorType, message } = classifyApiError(err);
811
- console.error("SDK Error (URL-based fetch):", {
812
- errorType,
813
- message,
814
- originalError: err,
815
- });
816
1097
  throw new ComposableStudioError(errorType, message, {
817
1098
  url: queryOptions.url,
818
1099
  hasStackSdk: !!config.stackSdk,