@contentstack/studio-client 1.4.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 (59) hide show
  1. package/dist/composable-studio/initializer-sdk.js +1 -9
  2. package/dist/composable-studio/initializer-sdk.js.map +1 -1
  3. package/dist/composable-studio/sdk.js +618 -184
  4. package/dist/composable-studio/sdk.js.map +1 -1
  5. package/dist/composable-studio/studio-intelligence.manager.js +135 -0
  6. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -0
  7. package/dist/config/config.schema.js +10 -0
  8. package/dist/config/config.schema.js.map +1 -1
  9. package/dist/config/process-user-config.js +6 -0
  10. package/dist/config/process-user-config.js.map +1 -1
  11. package/dist/config/stack-sdk-wrapper.js +2 -2
  12. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  13. package/dist/design/handle-active-style-change.js +0 -3
  14. package/dist/design/handle-active-style-change.js.map +1 -1
  15. package/dist/dnd/dnd-manager.js +25 -7
  16. package/dist/dnd/dnd-manager.js.map +1 -1
  17. package/dist/dnd/{utils.js → scroll-utils.js} +2 -27
  18. package/dist/dnd/scroll-utils.js.map +1 -0
  19. package/dist/hidden-element-notification/hidden-element-notification-event.js +7 -0
  20. package/dist/hidden-element-notification/hidden-element-notification-event.js.map +1 -1
  21. package/dist/highlight-node/highlight-node-manager.js +7 -1
  22. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  23. package/dist/highlight-node/highlight-node.js +34 -17
  24. package/dist/highlight-node/highlight-node.js.map +1 -1
  25. package/dist/index.d.ts +227 -23
  26. package/dist/index.js +8 -4
  27. package/dist/index.js.map +1 -1
  28. package/dist/node_modules/fflate/esm/browser.js +384 -0
  29. package/dist/node_modules/fflate/esm/browser.js.map +1 -0
  30. package/dist/packages/studio-internal/dist/utils/spec-compression.js +43 -0
  31. package/dist/packages/studio-internal/dist/utils/spec-compression.js.map +1 -0
  32. package/dist/query/expression-resolver.js +124 -0
  33. package/dist/query/expression-resolver.js.map +1 -0
  34. package/dist/query/query-executor.js +327 -0
  35. package/dist/query/query-executor.js.map +1 -0
  36. package/dist/shared/dnd-events.js +39 -0
  37. package/dist/shared/dnd-events.js.map +1 -0
  38. package/dist/url-change/url-change.js +65 -0
  39. package/dist/url-change/url-change.js.map +1 -0
  40. package/dist/utils/composable-studio-error.js +1 -0
  41. package/dist/utils/composable-studio-error.js.map +1 -1
  42. package/dist/utils/conditionBlock.js +17 -5
  43. package/dist/utils/conditionBlock.js.map +1 -1
  44. package/dist/utils/constants.js +4 -1
  45. package/dist/utils/constants.js.map +1 -1
  46. package/dist/utils/error-messages.default.js +1 -1
  47. package/dist/utils/error-messages.default.js.map +1 -1
  48. package/dist/utils/http-error.constants.js +11 -2
  49. package/dist/utils/http-error.constants.js.map +1 -1
  50. package/dist/utils/is-inside-iframe.js +16 -0
  51. package/dist/utils/is-inside-iframe.js.map +1 -0
  52. package/dist/utils/reference_fetcher.js +98 -12
  53. package/dist/utils/reference_fetcher.js.map +1 -1
  54. package/dist/utils/sdk.js +3 -0
  55. package/dist/utils/sdk.js.map +1 -1
  56. package/dist/utils/spec-analyzer.js +95 -0
  57. package/dist/utils/spec-analyzer.js.map +1 -0
  58. package/package.json +14 -10
  59. package/dist/dnd/utils.js.map +0 -1
@@ -1,21 +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
- import { entriesFromResponse, setTemplateEntryInDS, setStaticEntryInDS } from '../utils/sdk.js';
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';
19
+ import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
17
20
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
18
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);
19
26
  function getAuthErrorMessage(err) {
20
27
  const detail = err?.error_message ||
21
28
  err?.errors?.api_key?.[0] ||
@@ -44,18 +51,39 @@ function classifyApiError(err) {
44
51
  message: getAuthErrorMessage(err),
45
52
  };
46
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
+ }
47
71
  // Check for network errors (no response, timeout, connection refused)
48
- // Empty response object often indicates network failure
49
- const isEmptyResponse = err && typeof err === "object" && Object.keys(err).length === 0;
50
- 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
51
81
  return {
52
82
  errorType: ComposableStudioErrors.NETWORK_ERROR,
53
- message: isEmptyResponse
54
- ? getErrorMessage(ErrorMessageKey.NETWORK_ERROR_EMPTY)
55
- : getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
56
- detail: err?.message ||
57
- getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
58
- }),
83
+ message: getErrorMessage(ErrorMessageKey.NETWORK_ERROR_GENERIC, {
84
+ detail: err?.message ||
85
+ getErrorMessage(ErrorMessageKey.NETWORK_ERROR_DETAIL_DEFAULT),
86
+ }),
59
87
  };
60
88
  }
61
89
  // Check for 404 - composition not found
@@ -292,12 +320,73 @@ function getParentTagsValue(dataValue, tagsAsObject) {
292
320
  return { "data-cslp-parent-field": dataValue };
293
321
  }
294
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
+ }
295
375
  function generateSdk(userConfig) {
296
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
297
381
  if (clientRendererModeUtil.isInsideStudioFrame()) {
298
382
  const hash = new URLSearchParams(window.location.search).get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
299
383
  config.stackSdk.livePreviewQuery?.(hash);
300
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
301
390
  async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
302
391
  const { variantAlias, locale } = options;
303
392
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
@@ -344,96 +433,151 @@ function generateSdk(userConfig) {
344
433
  }
345
434
  else {
346
435
  //TODO: Add logger support general to have studio prefix
347
- console.error("Unable to resolve entry", entry.reason);
436
+ if (process.env.NODE_ENV === "development") {
437
+ console.log("Message handling fallback");
438
+ }
348
439
  }
349
440
  }
350
441
  }
351
442
  else {
352
- 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
+ }
353
446
  }
354
447
  }
355
448
  }
356
- catch (err) {
357
- 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
+ }
358
453
  }
359
454
  }
360
455
  /**
361
456
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
457
+ * Supports custom fetcher overrides (per-query > global > SDK default).
362
458
  */
363
- async function fetchTemplateEntry(options, data) {
459
+ async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
364
460
  if (!config.stackSdk) {
365
- console.error("Fetching template entry not possible without stackSdk");
366
461
  return;
367
462
  }
368
- const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = options;
463
+ const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
369
464
  if (!connected_content_type) {
370
465
  return;
371
466
  }
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;
372
472
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
373
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
374
- const queryOptions = {
375
- references: includeQueries,
376
- variantAlias: options.variantAlias,
377
- locale: options.locale || config.locale, // Use override locale or default
378
- };
379
- if (!isInsideVB) {
380
- queryOptions.only = onlyQueries;
381
- }
382
- let dataQuery = config.stackSdk
383
- .ctQuery(connected_content_type, queryOptions)
384
- .limit(1);
385
- if ("url" in compositionQuery) {
386
- dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
387
- }
388
- // We used the `find` instead of `findOne` because it
389
- // caused issues with the fetch data.
390
- const response = await dataQuery.find().catch((err) => {
391
- const { errorType, message } = classifyApiError(err);
392
- console.error("SDK Error (connected data):", {
393
- errorType,
394
- message,
395
- originalError: err,
396
- });
397
- // For connected data, use specific error or fall back to FETCHING_CONNECTED_DATA_FAILED
398
- const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
399
- ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
400
- : errorType;
401
- throw new ComposableStudioError(finalErrorType, finalErrorType === ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
402
- ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
403
- : message, {
404
- options,
405
- response: err,
406
- statusCode: err?.status || err?.statusCode,
407
- errorCode: err?.error_code,
473
+ const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
474
+ const isStudioAware = _enhancementMode === "studio-aware";
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
481
+ const queryOptions = {
482
+ references: allIncludeQueries,
483
+ variantAlias: resolvedOptions.variantAlias,
484
+ locale: resolvedOptions.locale || config.locale,
485
+ };
486
+ // Smart 'only' parameter handling - ignore in Visual Builder OR Studio-aware mode
487
+ if (!isInsideVB && !(isInsideStudio && isStudioAware)) {
488
+ queryOptions.only = onlyQueries;
489
+ }
490
+ // When Studio-aware: Skip 'only' to fetch all fields for data binding
491
+ let dataQuery = config.stackSdk
492
+ .ctQuery(connected_content_type, queryOptions)
493
+ .limit(1);
494
+ // Resolution priority: templateEntryUid > url > first entry (original logic)
495
+ if (resolvedOptions.templateEntryUid) {
496
+ console.log("📌 SDK using templateEntryUid:", resolvedOptions.templateEntryUid);
497
+ dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
498
+ }
499
+ else if ("url" in compositionQuery && compositionQuery.url) {
500
+ dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
501
+ }
502
+ const response = await dataQuery.find().catch((err) => {
503
+ const { errorType, message } = classifyApiError(err);
504
+ const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
505
+ ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
506
+ : errorType;
507
+ throw new ComposableStudioError(finalErrorType, finalErrorType ===
508
+ ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
509
+ ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
510
+ : message, {
511
+ options: fetchOptions,
512
+ response: err,
513
+ statusCode: err?.status || err?.statusCode,
514
+ errorCode: err?.error_code,
515
+ });
408
516
  });
409
- });
410
- const entries = entriesFromResponse(response);
411
- if (!entries?.[0]) {
412
- console.error("Preview/Template entry not found", {
413
- contentType: connected_content_type,
414
- compositionQuery,
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",
415
530
  });
416
- throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
417
- contentType: connected_content_type,
418
- }), {
419
- contentType: connected_content_type,
420
- hasStackSdk: !!config.stackSdk,
531
+ if (!entries?.[0]) {
532
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
533
+ contentType: connected_content_type,
534
+ }), {
535
+ contentType: connected_content_type,
536
+ hasStackSdk: !!config.stackSdk,
537
+ compositionQuery,
538
+ options: fetchOptions,
539
+ troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
540
+ });
541
+ }
542
+ return entries[0];
543
+ };
544
+ const customFetcher = perQueryFetchTemplateEntry ?? config.fetchTemplateEntry;
545
+ let entry;
546
+ if (customFetcher) {
547
+ entry = await customFetcher({
548
+ compositionEntry,
421
549
  compositionQuery,
422
- options,
423
- troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
550
+ connectedContentType: connected_content_type,
551
+ options: resolvedOptions,
552
+ includeReferences: includeQueries,
553
+ only: isInsideVB ? [] : onlyQueries,
554
+ stackSdk: config.stackSdk.sdk,
555
+ defaultFetch: defaultImpl,
424
556
  });
557
+ if (!entry) {
558
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
559
+ contentType: connected_content_type,
560
+ }));
561
+ }
562
+ }
563
+ else {
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
+ }
425
571
  }
426
- const entry = entries[0];
427
572
  if (config.cslp.appendTags) {
428
573
  addEditableTags(entry, connected_content_type, true, entry.locale);
429
574
  }
430
575
  setTemplateEntryInDS(data.dataSources, entry);
431
- if (!isCompositionBeingEdited(options?.composableUid || ""))
576
+ if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
432
577
  return;
433
578
  }
434
579
  async function fetchData(compositionEntry, queryOptions, options) {
435
580
  const { variantAlias, locale } = options || {};
436
- // This will iterate over ui and collect all data to fetch ( entries and depth of refrerences for both template and static contentstack)
437
581
  const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, compositionEntry.connected_content_type || "", options);
438
582
  const data = {
439
583
  [DATA_SOURCES_PREFIX]: {},
@@ -446,42 +590,295 @@ function generateSdk(userConfig) {
446
590
  includeQueries: templateReferencesPath,
447
591
  onlyQueries: templateOnlyKeys,
448
592
  composableUid: compositionEntry.composable_uid,
449
- variantAlias: variantAlias,
450
- locale: locale,
451
- }, data),
593
+ }, data, compositionEntry, options),
452
594
  resolveStaticData(contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, data, {
453
595
  variantAlias: variantAlias,
454
596
  locale: locale,
455
597
  }),
598
+ resolveQueryData(compositionEntry, data, {
599
+ variantAlias,
600
+ locale: locale || config.locale,
601
+ }),
456
602
  ]);
457
603
  return data;
458
604
  }
459
- async function fetchSpec(queryOptions, options) {
605
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
460
606
  if (!config.stackSdk) {
461
607
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
462
608
  }
463
- const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions);
464
- const data = await fetchData(compositionEntry, queryOptions, options);
465
- const page = typeof compositionEntry.ui === "string"
466
- ? JSON.parse(compositionEntry.ui)
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);
616
+ const ui = typeof compositionEntry.ui === "string"
617
+ ? decompressSpec(compositionEntry.ui)
467
618
  : compositionEntry.ui;
468
- const ui = page;
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
+ }
469
686
  return {
470
687
  data,
471
688
  ui,
472
689
  compositionEntry,
473
- //TODO: Need to fetch symbols from the server
474
690
  symbols: symbolEntries,
475
- 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
+ },
476
697
  };
477
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
+ }
781
+ /**
782
+ * Reusable helper to fetch data from Contentstack
783
+ * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
784
+ *
785
+ * @param querySpec - Full QuerySpec with filters, sorting, pagination, etc.
786
+ * @param context - RuntimeContext for expression resolution (URL params, etc.)
787
+ * @returns Promise with data array and count
788
+ */
789
+ async function fetchContentstackData(querySpec, context = {}, options) {
790
+ if (!config.stackSdk) {
791
+ return { entries: [], count: 0 };
792
+ }
793
+ try {
794
+ // Use QueryExecutor to execute the full QuerySpec
795
+ // This supports filters, sorting, pagination, includes, only, and expression resolution
796
+ const { QueryExecutor } = await import('../query/query-executor.js');
797
+ const executor = new QueryExecutor(config.stackSdk.sdk);
798
+ // Execute query using QueryExecutor
799
+ // ExpressionResolver inside QueryExecutor will resolve expressions at execution time
800
+ const result = await executor.execute(querySpec, 1, context, options);
801
+ const entries = result.entries || [];
802
+ const count = result.count || 0;
803
+ // Add editable tags (CSLP)
804
+ if (config.cslp.appendTags && Array.isArray(entries)) {
805
+ entries.forEach((entry) => {
806
+ addEditableTags(entry, querySpec.contentType, true, entry.locale || "en-us");
807
+ });
808
+ }
809
+ return {
810
+ entries: entries,
811
+ count: count,
812
+ };
813
+ }
814
+ catch (error) {
815
+ if (process.env.NODE_ENV === "development") {
816
+ console.error("Error resolving query data:", error);
817
+ }
818
+ return { entries: [], count: 0 };
819
+ }
820
+ }
821
+ async function resolveQueryData(compositionEntry, data, options) {
822
+ if (!compositionEntry.data_sources) {
823
+ return;
824
+ }
825
+ let dataSources = [];
826
+ try {
827
+ const parsed = JSON.parse(compositionEntry.data_sources);
828
+ dataSources = Array.isArray(parsed) ? parsed : Object.values(parsed);
829
+ }
830
+ catch (error) {
831
+ if (process.env.NODE_ENV === "development") {
832
+ console.error("Error parsing data sources JSON:", error);
833
+ }
834
+ return;
835
+ }
836
+ const queriesDS = dataSources.find((ds) => ds.uid === "contentstack_queries" || ds.id === "contentstack_queries");
837
+ if (!queriesDS || !queriesDS.data) {
838
+ return;
839
+ }
840
+ const queries = queriesDS.data || queriesDS.queries || [];
841
+ if (!Array.isArray(queries))
842
+ return;
843
+ const queryResults = {};
844
+ // Build RuntimeContext for expression resolution
845
+ // In SDK, use window.location.href for URL params
846
+ const urlParams = {};
847
+ if (typeof window !== "undefined" && window.location) {
848
+ const searchParams = new URLSearchParams(window.location.search);
849
+ searchParams.forEach((value, key) => {
850
+ urlParams[key] = value;
851
+ });
852
+ }
853
+ const context = {
854
+ url: {
855
+ params: urlParams,
856
+ path: {}, // Can be extended if path params are needed
857
+ hash: typeof window !== "undefined" ? window.location.hash : undefined,
858
+ },
859
+ // NO componentProps or user context - expressions only support URL params and time
860
+ };
861
+ await Promise.all(queries.map(async (queryConfig) => {
862
+ const { uid, spec } = queryConfig;
863
+ if (!uid || !spec?.contentType)
864
+ return;
865
+ // Use fetchContentstackData with full QuerySpec
866
+ // This now uses QueryExecutor internally to support filters, sorting, etc.
867
+ const result = await fetchContentstackData(spec, context, options);
868
+ queryResults[uid] = result;
869
+ }));
870
+ if (!data.dataSources[DATA_SOURCES.QUERY]) {
871
+ data.dataSources[DATA_SOURCES.QUERY] = {};
872
+ }
873
+ Object.assign(data.dataSources[DATA_SOURCES.QUERY], queryResults);
874
+ }
478
875
  function getLightConfig() {
479
876
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
480
877
  }
481
878
  function getSeoMetadata(ui) {
482
879
  return ui.metadata.seo || null;
483
880
  }
484
- return {
881
+ const sdkSingleton = {
485
882
  internal: {
486
883
  getConfig() {
487
884
  return config;
@@ -490,6 +887,7 @@ function generateSdk(userConfig) {
490
887
  // Once we fetch the data, we need to perform certain operation to store the UI and data.
491
888
  // Hence, we moved this to the internal method.
492
889
  fetchSpec,
890
+ fetchMultipleSpecs,
493
891
  fetchData,
494
892
  fetchTemplateEntry,
495
893
  getSeoMetadata,
@@ -572,13 +970,24 @@ function generateSdk(userConfig) {
572
970
  getConfig: getLightConfig,
573
971
  },
574
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;
575
985
  }
576
986
  const parseUI = (ui) => {
577
987
  try {
578
- return JSON.parse(ui);
988
+ return decompressSpec(ui);
579
989
  }
580
990
  catch (error) {
581
- console.error("UI parsing error", error);
582
991
  throw new ComposableStudioError(ComposableStudioErrors.UI_PARSING_ERROR, getErrorMessage(ErrorMessageKey.UI_PARSING_ERROR), { ui, error });
583
992
  }
584
993
  };
@@ -598,113 +1007,138 @@ function getAllSymbols(compositionEntry) {
598
1007
  }
599
1008
  /**
600
1009
  * This function fetches UI Composition from defined options.
1010
+ * Supports custom fetcher overrides (per-query > global > SDK default).
601
1011
  **/
602
- async function fetchComposition(config, options, locale) {
603
- let uiQuery;
604
- if ("composableUid" in options) {
605
- uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
606
- locale: config.locale,
607
- }), "composable_uid", options.composableUid);
608
- const response = await uiQuery
609
- .find()
610
- .then((res) => {
611
- let response;
612
- if (Array.isArray(res)) {
613
- response = res[0][0];
614
- }
615
- else {
616
- response = res.entries[0];
617
- }
618
- if (!response) {
619
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
620
- compositionUid: options.composableUid,
1012
+ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1013
+ const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
1014
+ const locale = resolvedOptions.locale;
1015
+ const defaultImpl = async () => {
1016
+ if ("composableUid" in queryOptions) {
1017
+ const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
1018
+ locale: locale || config.locale,
1019
+ }), "composable_uid", queryOptions.composableUid);
1020
+ return await uiQuery
1021
+ .find()
1022
+ .then((res) => {
1023
+ let response;
1024
+ if (Array.isArray(res)) {
1025
+ response = res[0][0];
1026
+ }
1027
+ else {
1028
+ response = res.entries[0];
1029
+ }
1030
+ if (!response) {
1031
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
1032
+ compositionUid: queryOptions.composableUid,
1033
+ hasStackSdk: !!config.stackSdk,
1034
+ options: queryOptions,
1035
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1036
+ });
1037
+ }
1038
+ return response;
1039
+ })
1040
+ .catch((err) => {
1041
+ if (err instanceof ComposableStudioError)
1042
+ throw err;
1043
+ const { errorType, message } = classifyApiError(err);
1044
+ throw new ComposableStudioError(errorType, message, {
1045
+ compositionUid: queryOptions.composableUid,
621
1046
  hasStackSdk: !!config.stackSdk,
622
- options,
623
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1047
+ statusCode: err?.status || err?.statusCode || "none",
1048
+ errorCode: err?.error_code || "none",
1049
+ errorMessage: err?.error_message || err?.message || "none",
1050
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
624
1051
  });
625
- }
626
- return response;
627
- })
628
- .catch((err) => {
629
- const { errorType, message } = classifyApiError(err);
630
- console.error("SDK Error:", { errorType, message, originalError: err });
631
- throw new ComposableStudioError(errorType, message, {
632
- compositionUid: options.composableUid,
633
- hasStackSdk: !!config.stackSdk,
634
- statusCode: err?.status || err?.statusCode || "none",
635
- errorCode: err?.error_code || "none",
636
- errorMessage: err?.error_message || err?.message || "none",
637
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
638
1052
  });
639
- });
640
- return {
641
- compositionEntry: response,
642
- symbolEntries: getAllSymbols(response),
643
- };
644
- }
645
- else if ("url" in options) {
646
- const possibleEntryUrlPatterns = getUrlPatterns(options.url);
647
- return await config.stackSdk
648
- .ctQuery(config.contentTypeUid, {
649
- includeAll: true,
650
- includeAllDepth: INCLUDE_DEPTH_COUNT,
651
- locale: config.locale,
652
- query: {
653
- url: {
654
- $in: possibleEntryUrlPatterns,
1053
+ }
1054
+ else if ("url" in queryOptions) {
1055
+ const possibleEntryUrlPatterns = getUrlPatterns(queryOptions.url);
1056
+ return await config.stackSdk
1057
+ .ctQuery(config.contentTypeUid, {
1058
+ includeAll: true,
1059
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
1060
+ locale: locale || config.locale,
1061
+ query: {
1062
+ url: {
1063
+ $in: possibleEntryUrlPatterns,
1064
+ },
1065
+ $or: [
1066
+ { place_composition_as: "page" },
1067
+ { place_composition_as: "" },
1068
+ { place_composition_as: null },
1069
+ { place_composition_as: undefined },
1070
+ { place_composition_as: { $exists: false } },
1071
+ { connected_content_type: { $exists: true } },
1072
+ ],
655
1073
  },
656
- $or: [
657
- { place_composition_as: "page" },
658
- { place_composition_as: "" },
659
- { place_composition_as: { $exists: false } },
660
- { connected_content_type: true },
661
- ],
662
- },
663
- })
664
- .find()
665
- .then((res) => {
666
- const entries = entriesFromResponse(res);
667
- const entry = getCompositionFromSlug(options.url, entries);
668
- if (!entry) {
669
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
670
- url: options.url,
671
- }), {
672
- url: options.url,
1074
+ })
1075
+ .find()
1076
+ .then((res) => {
1077
+ const entries = entriesFromResponse(res);
1078
+ const entry = getCompositionFromSlug(queryOptions.url, entries);
1079
+ if (!entry) {
1080
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
1081
+ url: queryOptions.url,
1082
+ }), {
1083
+ url: queryOptions.url,
1084
+ hasStackSdk: !!config.stackSdk,
1085
+ searchedPatterns: possibleEntryUrlPatterns,
1086
+ entriesFound: entries.length,
1087
+ options: queryOptions,
1088
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
1089
+ });
1090
+ }
1091
+ return entry;
1092
+ })
1093
+ .catch((err) => {
1094
+ if (err instanceof ComposableStudioError)
1095
+ throw err;
1096
+ const { errorType, message } = classifyApiError(err);
1097
+ throw new ComposableStudioError(errorType, message, {
1098
+ url: queryOptions.url,
673
1099
  hasStackSdk: !!config.stackSdk,
674
- searchedPatterns: possibleEntryUrlPatterns,
675
- entriesFound: entries.length,
676
- options,
677
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
1100
+ statusCode: err?.status || err?.statusCode || "none",
1101
+ errorCode: err?.error_code || "none",
1102
+ errorMessage: err?.error_message || err?.message || "none",
1103
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
678
1104
  });
679
- }
680
- return {
681
- compositionEntry: entry,
682
- symbolEntries: getAllSymbols(entry),
683
- };
684
- })
685
- .catch((err) => {
686
- // This error is different. Here, we have issues while fetching the entries.
687
- const { errorType, message } = classifyApiError(err);
688
- console.error("SDK Error (URL-based fetch):", {
689
- errorType,
690
- message,
691
- originalError: err,
692
1105
  });
693
- throw new ComposableStudioError(errorType, message, {
694
- url: options.url,
695
- hasStackSdk: !!config.stackSdk,
696
- statusCode: err?.status || err?.statusCode || "none",
697
- errorCode: err?.error_code || "none",
698
- errorMessage: err?.error_message || err?.message || "none",
699
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
1106
+ }
1107
+ else {
1108
+ throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
1109
+ options: queryOptions,
700
1110
  });
1111
+ }
1112
+ };
1113
+ const customFetcher = perQueryFetchComposition ?? config.fetchComposition;
1114
+ if (customFetcher) {
1115
+ const entry = await customFetcher({
1116
+ compositionQuery: queryOptions,
1117
+ contentTypeUid: config.contentTypeUid,
1118
+ options: resolvedOptions,
1119
+ stackSdk: config.stackSdk.sdk,
1120
+ defaultFetch: defaultImpl,
701
1121
  });
1122
+ if (!entry) {
1123
+ const isUrlBased = "url" in queryOptions;
1124
+ throw new ComposableStudioError(isUrlBased
1125
+ ? ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL
1126
+ : ComposableStudioErrors.COMPOSITION_NOT_FOUND, isUrlBased
1127
+ ? getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
1128
+ url: queryOptions.url,
1129
+ })
1130
+ : getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404));
1131
+ }
1132
+ return {
1133
+ compositionEntry: entry,
1134
+ symbolEntries: getAllSymbols(entry),
1135
+ };
702
1136
  }
703
- else {
704
- throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
705
- options,
706
- });
707
- }
1137
+ const entry = await defaultImpl();
1138
+ return {
1139
+ compositionEntry: entry,
1140
+ symbolEntries: getAllSymbols(entry),
1141
+ };
708
1142
  }
709
1143
 
710
1144
  export { classifyApiError, generateSdk, parseUI };