@contentstack/studio-client 4.0.0 → 4.2.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 (124) hide show
  1. package/dist/breakpoints/BreakpointManager.js +3 -2
  2. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  3. package/dist/breakpoints/breakpoint-origin.js +30 -0
  4. package/dist/breakpoints/breakpoint-origin.js.map +1 -0
  5. package/dist/canvas/canvas.type.js +1 -1
  6. package/dist/canvas/canvas.utils.js +213 -9
  7. package/dist/canvas/canvas.utils.js.map +1 -1
  8. package/dist/composable-studio/binding-defect-report.js +106 -0
  9. package/dist/composable-studio/binding-defect-report.js.map +1 -0
  10. package/dist/composable-studio/build-scoped-data.js +21 -11
  11. package/dist/composable-studio/build-scoped-data.js.map +1 -1
  12. package/dist/composable-studio/collect-data-needs.js +1 -1
  13. package/dist/composable-studio/data/pre-process-static-values.js +89 -19
  14. package/dist/composable-studio/data/pre-process-static-values.js.map +1 -1
  15. package/dist/composable-studio/delivery-setup-check.js +92 -0
  16. package/dist/composable-studio/delivery-setup-check.js.map +1 -0
  17. package/dist/composable-studio/resolution-failure-spec.js +53 -0
  18. package/dist/composable-studio/resolution-failure-spec.js.map +1 -0
  19. package/dist/composable-studio/resolution-telemetry.js +68 -0
  20. package/dist/composable-studio/resolution-telemetry.js.map +1 -0
  21. package/dist/composable-studio/sdk.js +683 -551
  22. package/dist/composable-studio/sdk.js.map +1 -1
  23. package/dist/composable-studio/section-binding/compute-all-section-auto-bindings.js +146 -0
  24. package/dist/composable-studio/section-binding/compute-all-section-auto-bindings.js.map +1 -0
  25. package/dist/composable-studio/section-binding/constants.js +27 -0
  26. package/dist/composable-studio/section-binding/constants.js.map +1 -0
  27. package/dist/composable-studio/section-binding/index.js +20 -0
  28. package/dist/composable-studio/section-binding/index.js.map +1 -0
  29. package/dist/composable-studio/section-binding/schema-path.js +112 -0
  30. package/dist/composable-studio/section-binding/schema-path.js.map +1 -0
  31. package/dist/composable-studio/section-binding/section-composition-auto-binding.js +815 -0
  32. package/dist/composable-studio/section-binding/section-composition-auto-binding.js.map +1 -0
  33. package/dist/composable-studio/section-binding/section-compositions.js +349 -0
  34. package/dist/composable-studio/section-binding/section-compositions.js.map +1 -0
  35. package/dist/composable-studio/section-binding/section-internal-ref-introspection.js +72 -0
  36. package/dist/composable-studio/section-binding/section-internal-ref-introspection.js.map +1 -0
  37. package/dist/composable-studio/section-binding/self-describe-section-bindings.js +132 -0
  38. package/dist/composable-studio/section-binding/self-describe-section-bindings.js.map +1 -0
  39. package/dist/composable-studio/section-binding/serialization.js +33 -0
  40. package/dist/composable-studio/section-binding/serialization.js.map +1 -0
  41. package/dist/composable-studio/section-data.js +5 -1
  42. package/dist/composable-studio/section-data.js.map +1 -1
  43. package/dist/composable-studio/setup-check-signal.js +48 -0
  44. package/dist/composable-studio/setup-check-signal.js.map +1 -0
  45. package/dist/composable-studio/studio-intelligence.manager.js +6 -2
  46. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  47. package/dist/composable-studio/weak-maps.js +3 -1
  48. package/dist/composable-studio/weak-maps.js.map +1 -1
  49. package/dist/config/config.schema.js +97 -104
  50. package/dist/config/config.schema.js.map +1 -1
  51. package/dist/config/process-user-config.js +41 -24
  52. package/dist/config/process-user-config.js.map +1 -1
  53. package/dist/config/stack-sdk-wrapper.js +22 -4
  54. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  55. package/dist/context-menu/context-menu.js +1 -0
  56. package/dist/context-menu/context-menu.js.map +1 -1
  57. package/dist/dnd/dnd-manager.js +29 -0
  58. package/dist/dnd/dnd-manager.js.map +1 -1
  59. package/dist/editor.d.ts +42 -1
  60. package/dist/highlight-node/highlight-node-manager.js +89 -14
  61. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  62. package/dist/highlight-node/highlight-node.js +16 -4
  63. package/dist/highlight-node/highlight-node.js.map +1 -1
  64. package/dist/highlight-node/history-shortcut.js +78 -0
  65. package/dist/highlight-node/history-shortcut.js.map +1 -0
  66. package/dist/index.d.ts +1099 -353
  67. package/dist/index.js +19 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/query/query-executor.js +51 -9
  70. package/dist/query/query-executor.js.map +1 -1
  71. package/dist/renderer-mode.d.ts +68 -0
  72. package/dist/renderer-mode.js +2 -0
  73. package/dist/renderer-mode.js.map +1 -0
  74. package/dist/url-metadata/entry-check-key.js +14 -0
  75. package/dist/url-metadata/entry-check-key.js.map +1 -0
  76. package/dist/url-metadata/select-url-winner.js +64 -12
  77. package/dist/url-metadata/select-url-winner.js.map +1 -1
  78. package/dist/url-metadata/types.js +10 -1
  79. package/dist/url-metadata/types.js.map +1 -1
  80. package/dist/url-metadata/url-pattern-matcher.js +11 -2
  81. package/dist/url-metadata/url-pattern-matcher.js.map +1 -1
  82. package/dist/utils/canvas.js +0 -1
  83. package/dist/utils/canvas.js.map +1 -1
  84. package/dist/utils/check-bindings.js +5 -3
  85. package/dist/utils/check-bindings.js.map +1 -1
  86. package/dist/utils/classify-response-error.js +243 -33
  87. package/dist/utils/classify-response-error.js.map +1 -1
  88. package/dist/utils/composable-studio-error.js +7 -0
  89. package/dist/utils/composable-studio-error.js.map +1 -1
  90. package/dist/utils/conditionBlock.js +19 -6
  91. package/dist/utils/conditionBlock.js.map +1 -1
  92. package/dist/utils/constants.js +11 -2
  93. package/dist/utils/constants.js.map +1 -1
  94. package/dist/utils/http-error.constants.js +24 -1
  95. package/dist/utils/http-error.constants.js.map +1 -1
  96. package/dist/utils/include-path-rules.js +3 -2
  97. package/dist/utils/include-path-rules.js.map +1 -1
  98. package/dist/utils/load-error-classifier.js +18 -0
  99. package/dist/utils/load-error-classifier.js.map +1 -0
  100. package/dist/utils/parse-ui.js +27 -5
  101. package/dist/utils/parse-ui.js.map +1 -1
  102. package/dist/utils/preview-hash-refused.js +75 -0
  103. package/dist/utils/preview-hash-refused.js.map +1 -0
  104. package/dist/utils/reference_fetcher.js +79 -12
  105. package/dist/utils/reference_fetcher.js.map +1 -1
  106. package/dist/utils/require-stack.js +83 -20
  107. package/dist/utils/require-stack.js.map +1 -1
  108. package/dist/utils/serialize-for-inline-script.js +19 -0
  109. package/dist/utils/serialize-for-inline-script.js.map +1 -0
  110. package/dist/utils/served-by.js +32 -13
  111. package/dist/utils/served-by.js.map +1 -1
  112. package/dist/utils/spec-analyzer.js +24 -1
  113. package/dist/utils/spec-analyzer.js.map +1 -1
  114. package/dist/utils/studio-error-codes.js +34 -2
  115. package/dist/utils/studio-error-codes.js.map +1 -1
  116. package/dist/utils/studio-error.js +68 -7
  117. package/dist/utils/studio-error.js.map +1 -1
  118. package/dist/visual-builder/composition-save-event.js +36 -5
  119. package/dist/visual-builder/composition-save-event.js.map +1 -1
  120. package/package.json +12 -8
  121. package/dist/studio-internal/dist/utils/section-slot-walker.js +0 -63
  122. package/dist/studio-internal/dist/utils/section-slot-walker.js.map +0 -1
  123. package/dist/studio-internal/dist/utils/spec-compression.js +0 -43
  124. package/dist/studio-internal/dist/utils/spec-compression.js.map +0 -1
@@ -1,45 +1,64 @@
1
+ import { normalizeUi, readLayout, withNormalizedDataSources, decompressSpec } from '@contentstack/studio-internal';
1
2
  import { COMPOSABLE_STUDIO_QUERY_PARAM, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger/constants';
2
3
  import { sendStudioEvent } from '../utils/studio-messaging.js';
3
- import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getStateStoreInstance, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
4
- import { get, pick, uniq, uniqBy, chunk, range } from 'lodash-es';
4
+ import { buildResolutionFailureSpec } from './resolution-failure-spec.js';
5
+ import { buildResolutionTelemetry } from './resolution-telemetry.js';
6
+ import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getStateStoreInstance, resolveFirstOfTypePath, parseFirstOfTypeSegment, getComponentRegistryInstance, DATA_SOURCES_PREFIX, loadBuiltInComponents } from '@contentstack/studio-registry';
7
+ import { get, pick, uniqBy, uniq, chunk, range } from 'lodash-es';
5
8
  import { processUserConfig } from '../config/process-user-config.js';
6
9
  import { setStackSdkInstance } from '../json-rte-registry/stack-sdk-store.js';
7
- import { requireStack } from '../utils/require-stack.js';
8
- import { parseUI } from '../utils/parse-ui.js';
10
+ import { requireStack, requireCompositionContentType } from '../utils/require-stack.js';
11
+ import { tryParseUI, parseUI } from '../utils/parse-ui.js';
9
12
  import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
10
13
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
11
- import { setTemplateEntryInDS, setStaticEntryInDS, getBindingStringForCS, entriesFromResponse } from '../utils/sdk.js';
14
+ import { getBindingStringForCS, setTemplateEntryInDS, setStaticEntryInDS, entriesFromResponse } from '../utils/sdk.js';
12
15
  import '../utils/editor-mode.js';
13
16
  import { ComposableStudioError } from '../utils/composable-studio-error.js';
14
17
  import '../utils/composition-not-found.js';
15
- import { createStudioError, buildStudioErrorContext, isSetupFault } from '../utils/studio-error.js';
18
+ import { isPreviewHashRefused, warnPreviewHashRefusedOnce, withoutPreviewParams } from '../utils/preview-hash-refused.js';
19
+ import { buildStudioErrorContext, createStudioError, isSetupFault } from '../utils/studio-error.js';
16
20
  import { StudioErrorCode } from '../utils/studio-error-codes.js';
17
21
  import '../utils/conditionBlock.js';
18
22
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
19
- import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
23
+ import { analyzeUsedComponents, analyzePlacedSectionUids } from '../utils/spec-analyzer.js';
20
24
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
21
- import { classifyResponseError, diagnoseUnreadableResponse } from '../utils/classify-response-error.js';
22
- import { reportDegraded, degradedReportingIsOn, DegradedCode } from '../utils/degraded-finding.js';
25
+ import { loadErrorClassifier } from '../utils/load-error-classifier.js';
26
+ import { degradedReportingIsOn, reportDegraded, DegradedCode } from '../utils/degraded-finding.js';
23
27
  import { countUnresolvedReferences } from '../utils/reference-stub.js';
24
- import { findBindingDefects } from '../utils/check-bindings.js';
25
- import { resolveServedBy } from '../utils/served-by.js';
28
+ import { captureRequestRoute, isUsableHash } from '../utils/served-by.js';
26
29
  import { getPageLinkedPlacementFilter } from '../utils/build-composition-fetch-query.js';
27
30
  import { resolveByUrlSource } from '../url-metadata/build-template-query.js';
31
+ import { entryCheckKey } from '../url-metadata/entry-check-key.js';
28
32
  import { parseUrlMetadata } from '../url-metadata/parse-url-metadata.js';
29
33
  import { rankUrlMatches } from '../url-metadata/rank-url-matches.js';
30
34
  import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
31
- import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
35
+ import { COMPOSITION_PREVIEW_URL_SOURCES, URL_WINNER_KIND } from '../url-metadata/types.js';
32
36
  import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
37
+ import { getStatusCode, isNetworkError } from '../utils/http-error.constants.js';
33
38
  import { indexModularBlocks, isModularBlockPath, compositionCarriesCompleteIncludes, dropImpliedParents } from '../utils/include-path-rules.js';
34
39
  import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
35
40
  import { applyUrlBudget, referencesExceedBudget } from '../utils/query-url-budget.js';
36
41
  import { collectAllDataNeeds, stableHashQuery, parseExternalDataForComponentProps } from './collect-data-needs.js';
37
- import { buildScopedDataSources } from './build-scoped-data.js';
42
+ import { buildScopedDataSources, scopeTemplateToSection } from './build-scoped-data.js';
38
43
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
39
- import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
40
- import { TEMPLATE_FETCH_ROOT_KEY, parseEntryFetchRootKey, resolveInstanceRootBinding, fetchRootFromBinding, resolveLegacySelectedFieldWithProvenance, isTemplateRootBinding, getRootBindingPath, resolveLegacySelectedField, isPageAbsoluteField, templateFetchRoot } from './section-data.js';
41
- import { decompressSpec } from '../studio-internal/dist/utils/spec-compression.js';
44
+ import { TEMPLATE_FETCH_ROOT_KEY, resolveInstanceRootBinding, fetchRootFromBinding, resolveLegacySelectedFieldWithProvenance, parseEntryFetchRootKey, isTemplateRootBinding, getRootBindingPath, resolveLegacySelectedField, isPageAbsoluteField, templateFetchRoot } from './section-data.js';
42
45
 
46
+ /**
47
+ * The query options with Studio Intelligence merged in. Studio Intelligence
48
+ * only exists inside the Studio canvas, so its manager loads there and nowhere
49
+ * else; outside, the options pass through marked as before (`legacy`).
50
+ */
51
+ async function withStudioIntelligence(options, config) {
52
+ if (!clientRendererModeUtil.isInsideStudioFrame()) {
53
+ return {
54
+ ...options,
55
+ _enhancementMode: "legacy",
56
+ };
57
+ }
58
+ const { StudioIntelligenceManager } = await import('./studio-intelligence.manager.js');
59
+ const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
60
+ return StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
61
+ }
43
62
  // ✅ HYBRID APPROACH: List of internal components that should always be available
44
63
  // These include both built-in components AND system components (like "page")
45
64
  // All are registered synchronously during React initialization via getBasicComponents()
@@ -111,6 +130,28 @@ function resolveSectionContext(section, templateEntry) {
111
130
  }
112
131
  return null;
113
132
  }
133
+ /**
134
+ * The data sources a composition's own bindings read from when it renders.
135
+ *
136
+ * A page reads its template entry whole. A section opened on its own reads only
137
+ * the part its linked schema points at (`blocks.block` → the first block), so
138
+ * checking its bindings against the whole entry reports fields as missing that
139
+ * the section renders fine.
140
+ */
141
+ function dataSourcesAsRendered(compositionEntry, dataSources) {
142
+ if (compositionEntry.place_composition_as !== "section")
143
+ return dataSources;
144
+ const template = dataSources?.[DATA_SOURCES.TEMPLATE];
145
+ if (!template || Array.isArray(template))
146
+ return dataSources;
147
+ const context = resolveSectionContext(compositionEntry, template);
148
+ if (!context?.selectedField)
149
+ return dataSources;
150
+ return {
151
+ ...dataSources,
152
+ [DATA_SOURCES.TEMPLATE]: scopeTemplateToSection(template, context.selectedField, context.cardinality),
153
+ };
154
+ }
114
155
  function getTemplateContentTypeForComposition(compositionEntry) {
115
156
  if (compositionEntry.connected_content_type) {
116
157
  return compositionEntry.connected_content_type;
@@ -229,7 +270,11 @@ function sanitizeFieldPath(path) {
229
270
  return path
230
271
  .split(".")
231
272
  .map((seg) => seg.replace(/\[\d+\]$/, "").replace(/^\d+_/, ""))
232
- .filter((seg) => seg.length > 0 && !/^\d+$/.test(seg) && seg !== "entries");
273
+ .filter((seg) => seg.length > 0 &&
274
+ !/^\d+$/.test(seg) &&
275
+ seg !== "entries" &&
276
+ // A first-of-type segment stands where an index would (COMS-2484).
277
+ parseFirstOfTypeSegment(seg) === undefined);
233
278
  }
234
279
  /**
235
280
  * Compose the page-template projection root for a placed section's reference
@@ -492,7 +537,11 @@ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
492
537
  * `[...ancestorPrefix, ...selectedField]` so nested wrapper chains fetch the
493
538
  * full reference depth (W1.selectedField → W2.selectedField → …).
494
539
  */
495
- function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
540
+ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid,
541
+ // When given, records the scope each node placed directly in a section
542
+ // instance's slot resolves its bindings in, keyed by that node's uid
543
+ // (`collectSlotChildScopes`).
544
+ slotChildScopes) {
496
545
  const out = [];
497
546
  const walk = (node, parentRepeaterUID,
498
547
  // The document `ancestorPrefix` counts from, threaded together with it so a
@@ -632,8 +681,10 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
632
681
  // a slot buried inside the wrapper's OWN Repeater/CB chain roots at the
633
682
  // full slot path (mirrors the editor's `indexSectionSlotsContext`).
634
683
  const wrapperUi = sectionsByUid.get(compositionUid)?.ui;
635
- if (wrapperUi) {
636
- const wrapperUiNode = typeof wrapperUi === "string" ? parseUI(wrapperUi) : wrapperUi;
684
+ const wrapperUiNode = wrapperUi
685
+ ? tryParseUI(wrapperUi, compositionUid)
686
+ : null;
687
+ if (wrapperUiNode) {
637
688
  slotSegments = new Map();
638
689
  mapSectionSlotSegments(wrapperUiNode, [], slotSegments);
639
690
  }
@@ -671,11 +722,24 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
671
722
  }
672
723
  }
673
724
  if (node.slots && typeof node.slots === "object") {
725
+ const isSectionInstance = node.type === SECTION_COMPOSITION_NODE_TYPE &&
726
+ !!node.metadata?.compositionUID &&
727
+ !!node.uid;
674
728
  for (const [slotUid, slotNodes] of Object.entries(node.slots ?? {})) {
675
729
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
676
730
  const slotPrefix = slotSegments
677
731
  ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
678
732
  : childPrefix;
733
+ if (slotChildScopes && isSectionInstance) {
734
+ for (const c of arr) {
735
+ if (c?.uid) {
736
+ slotChildScopes.set(c.uid, {
737
+ key: childFetchRoot.key,
738
+ prefix: slotPrefix,
739
+ });
740
+ }
741
+ }
742
+ }
679
743
  for (const c of arr)
680
744
  walk(c, nextRepeater, childFetchRoot, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
681
745
  }
@@ -694,19 +758,19 @@ async function fetchSectionCompositionEntries(config, sectionUids, options) {
694
758
  return [];
695
759
  }
696
760
  const response = await requireStack(config)
697
- .ctQuery(config.contentTypeUid, {
761
+ .ctQuery(requireCompositionContentType(config), {
698
762
  includeAll: true,
699
763
  includeAllDepth: INCLUDE_DEPTH_COUNT,
700
764
  locale: options?.locale || config.locale,
701
765
  })
702
766
  .containedIn("uid", sectionUids)
703
767
  .find();
704
- return entriesFromResponse(response).map((entry) => ({
705
- ...entry,
706
- ui: typeof entry.ui === "string"
707
- ? parseUI(entry.ui, entry.composable_uid)
708
- : entry.ui,
709
- }));
768
+ // A section whose layout cannot be read is left out: its placements render
769
+ // nothing, and the rest of the page still renders.
770
+ return entriesFromResponse(response).flatMap((entry) => {
771
+ const ui = tryParseUI(entry.ui, entry.composable_uid);
772
+ return ui ? [{ ...withNormalizedDataSources(entry), ui }] : [];
773
+ });
710
774
  }
711
775
  /**
712
776
  * The section uids a composition/section directly references: its native
@@ -721,7 +785,9 @@ async function fetchSectionCompositionEntries(config, sectionUids, options) {
721
785
  * not tell the SDK about a component it refers to. The two kinds take opposite
722
786
  * advice — ours register themselves on first import of the React package, so a
723
787
  * missing built-in means the package root was never imported, while a missing
724
- * custom one means a `registerComponent()` call had not run yet.
788
+ * custom one usually means the deployed build is older than the composition, or
789
+ * its registration had not run yet. The check only runs in the browser, so
790
+ * server-bundle causes do not apply.
725
791
  */
726
792
  function componentsNotRegistered(componentTypes, areBuiltIn, config) {
727
793
  return createStudioError({
@@ -735,19 +801,15 @@ function componentsNotRegistered(componentTypes, areBuiltIn, config) {
735
801
  cause: "The package root was never imported, so the built-in components never registered themselves.",
736
802
  fix: 'Import it once before fetching: import "@contentstack/studio-react";',
737
803
  },
738
- {
739
- cause: "The import was tree-shaken out of a server-only bundle.",
740
- fix: "Keep the root import in the bundle that runs the fetch.",
741
- },
742
804
  ]
743
805
  : [
744
806
  {
745
- cause: "The fetch ran before registerComponent() did.",
746
- fix: "Import the module that registers them above the code that fetches.",
807
+ cause: "This site's deployed build doesn't have them. Often they were added in Studio from a newer build, or renamed or removed in code.",
808
+ fix: "Deploy the build that registers them, or remove them from the composition.",
747
809
  },
748
810
  {
749
- cause: "The composition uses a component this build does not have.",
750
- fix: "Register it, or remove it from the composition.",
811
+ cause: "The fetch ran before registerComponent() or registerComponents() did.",
812
+ fix: "Import the module that registers them above the code that fetches.",
751
813
  },
752
814
  ],
753
815
  context: buildStudioErrorContext(config),
@@ -776,10 +838,10 @@ function harvestInlineLinkedSections(entry, map) {
776
838
  const e = candidate;
777
839
  if (map.has(e.uid))
778
840
  continue;
779
- const ui = typeof e.ui === "string"
780
- ? parseUI(e.ui, e.composable_uid)
781
- : e.ui;
782
- map.set(e.uid, { ...e, ui });
841
+ const ui = tryParseUI(e.ui, e.composable_uid);
842
+ if (!ui)
843
+ continue; // unreadable: left out, its placements render nothing
844
+ map.set(e.uid, { ...withNormalizedDataSources(e), ui });
783
845
  added.push(e.uid);
784
846
  added.push(...harvestInlineLinkedSections(e, map)); // recurse into inline chain
785
847
  }
@@ -798,9 +860,7 @@ function referencedSectionUidsOf(entry) {
798
860
  }
799
861
  // This reader takes a narrowed shape that carries no uid, so the diagnosis
800
862
  // names the case without naming the composition.
801
- const ui = typeof entry.ui === "string"
802
- ? parseUI(entry.ui)
803
- : entry.ui;
863
+ const ui = entry.ui ? tryParseUI(entry.ui) : null;
804
864
  if (ui)
805
865
  for (const u of collectSectionCompositionUIDs(ui))
806
866
  uids.add(u);
@@ -818,9 +878,7 @@ async function getAllSectionCompositions(config, compositionEntry, options) {
818
878
  // dedups shared/diamond sections; `requested` prevents refetching a uid
819
879
  // that returned nothing (deleted section) or closing a cycle. Rounds =
820
880
  // nesting depth, not section count; breadth at a level is one call.
821
- const ui = typeof compositionEntry.ui === "string"
822
- ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
823
- : compositionEntry.ui;
881
+ const ui = parseUI(compositionEntry.ui, compositionEntry.composable_uid);
824
882
  const requested = new Set();
825
883
  // Seed the frontier from the page UI + the page's linked_sections, plus the
826
884
  // refs of any inline-seeded sections (so their children get discovered).
@@ -958,7 +1016,7 @@ function resolveSeoBindingValue(staticValue, binding, specData) {
958
1016
  if (!templateEntry || !subPath) {
959
1017
  return fallback;
960
1018
  }
961
- const resolved = get(templateEntry, subPath);
1019
+ const resolved = get(templateEntry, resolveFirstOfTypePath(templateEntry, subPath));
962
1020
  // SEO fields are expected to resolve to a primitive. Anything else (an
963
1021
  // object, a missing path, an empty string) falls back to the static value
964
1022
  // so consumers always see a string.
@@ -979,7 +1037,9 @@ function resolveSeoBindingValue(staticValue, binding, specData) {
979
1037
  * `@contentstack/studio-react`.
980
1038
  */
981
1039
  function getSeoMetadataPure(ui, specData) {
982
- const seo = ui.metadata.seo;
1040
+ // An app can pass any layout here (bring your own data): read it through
1041
+ // normalizeUi so a missing metadata or a malformed seo yields no metadata.
1042
+ const seo = normalizeUi(ui)?.metadata?.seo;
983
1043
  if (!seo)
984
1044
  return null;
985
1045
  return {
@@ -1009,6 +1069,15 @@ function getSeoMetadataPure(ui, specData) {
1009
1069
  * section rendered as the root reads `dataSources.template` directly).
1010
1070
  */
1011
1071
  function buildSectionScopedData(compositionEntry, pageUi, sectionEntries, dataSources) {
1072
+ // An app can call this directly (bring your own data): read the layouts it
1073
+ // passes the way the fetch does, so a broken one cannot throw here.
1074
+ pageUi = normalizeUi(pageUi) ?? normalizeUi({});
1075
+ sectionEntries = (Array.isArray(sectionEntries) ? sectionEntries : [])
1076
+ .filter((sec) => !!sec && typeof sec === "object" && typeof sec.uid === "string")
1077
+ .flatMap((sec) => {
1078
+ const ui = readLayout(sec.ui);
1079
+ return ui ? [{ ...withNormalizedDataSources(sec), ui }] : [];
1080
+ });
1012
1081
  if (!sectionEntries.length)
1013
1082
  return {};
1014
1083
  // Convert the sectionEntries array to a Map<compositionUid, entry> for collectAllDataNeeds.
@@ -1132,32 +1201,100 @@ function buildSectionScopedData(compositionEntry, pageUi, sectionEntries, dataSo
1132
1201
  * reuse the same registry checks `fetchSpec` performs (built-in vs custom
1133
1202
  * component errors, then `loadComponents`).
1134
1203
  */
1135
- async function ensureUiComponentsLoaded(ui, sectionEntries) {
1204
+ /**
1205
+ * The registry check a client fetch runs before rendering: which component
1206
+ * types the layout uses that are not registered. A placed section whose section
1207
+ * did not load (deleted, unpublished, a stale `compositionUID`) is not a
1208
+ * component the app forgot to register: it renders nothing, so it is skipped and
1209
+ * named once in a warning instead of failing the whole page.
1210
+ */
1211
+ function checkUsedComponents(uis, loadedSectionUids) {
1136
1212
  const componentRegistry = getComponentRegistryInstance();
1137
- const usedComponents = analyzeUsedComponents(ui);
1138
- const sectionComponentTypes = new Set(sectionEntries.keys());
1139
- const missingBuiltInComponents = [];
1140
- const missingCustomComponents = [];
1141
- usedComponents.forEach((type) => {
1142
- if (sectionComponentTypes.has(type))
1143
- return;
1144
- if (!componentRegistry.hasComponentLoader(type)) {
1213
+ const used = new Set();
1214
+ const placedSections = new Set();
1215
+ for (const ui of uis) {
1216
+ analyzeUsedComponents(ui).forEach((type) => used.add(type));
1217
+ analyzePlacedSectionUids(ui).forEach((uid) => placedSections.add(uid));
1218
+ }
1219
+ const missingBuiltIn = [];
1220
+ const missingCustom = [];
1221
+ const missingSections = [];
1222
+ const toLoad = [];
1223
+ used.forEach((type) => {
1224
+ if (loadedSectionUids.has(type)) {
1225
+ toLoad.push(type);
1226
+ }
1227
+ else if (placedSections.has(type)) {
1228
+ missingSections.push(type);
1229
+ }
1230
+ else if (!componentRegistry.hasComponentLoader(type)) {
1145
1231
  if (INTERNAL_COMPONENT_TYPES.includes(type)) {
1146
- missingBuiltInComponents.push(type);
1232
+ missingBuiltIn.push(type);
1147
1233
  }
1148
1234
  else {
1149
- missingCustomComponents.push(type);
1235
+ missingCustom.push(type);
1150
1236
  }
1151
1237
  }
1238
+ else {
1239
+ toLoad.push(type);
1240
+ }
1152
1241
  });
1153
- if (missingBuiltInComponents.length > 0) {
1154
- throw componentsNotRegistered(missingBuiltInComponents, true);
1242
+ if (missingSections.length > 0) {
1243
+ console.warn(`[Contentstack Studio] Placed section(s) not found, rendering nothing in their place: ${missingSections.join(", ")}`);
1155
1244
  }
1156
- if (missingCustomComponents.length > 0) {
1157
- throw componentsNotRegistered(missingCustomComponents, false);
1245
+ return { missingBuiltIn, missingCustom, toLoad };
1246
+ }
1247
+ /**
1248
+ * `checkUsedComponents`, after asking the renderer package for its built-ins
1249
+ * when any are missing. `@contentstack/studio-react` registers them on first
1250
+ * use rather than on import, and a fetch in the browser can run before the
1251
+ * renderer has loaded; it leaves a loader for exactly this case. Only when no
1252
+ * loader ran, or the built-ins are still missing after it did, is a built-in
1253
+ * reported as not registered.
1254
+ */
1255
+ async function checkUsedComponentsLoadingBuiltIns(uis, loadedSectionUids) {
1256
+ const result = checkUsedComponents(uis, loadedSectionUids);
1257
+ if (result.missingBuiltIn.length === 0)
1258
+ return result;
1259
+ if (!(await loadBuiltInComponents()))
1260
+ return result;
1261
+ return checkUsedComponents(uis, loadedSectionUids);
1262
+ }
1263
+ /**
1264
+ * Starts fetching the code of the components these layouts use, without
1265
+ * waiting for it, so it arrives while the page's content loads rather than
1266
+ * after. Covers lazily registered components and the built-ins that load on
1267
+ * demand in the browser (rich text). Best effort: the check before rendering
1268
+ * still loads, and reports, whatever this did not.
1269
+ */
1270
+ function startLoadingUsedComponents(uis) {
1271
+ if (typeof window === "undefined")
1272
+ return;
1273
+ const types = new Set();
1274
+ for (const ui of uis)
1275
+ analyzeUsedComponents(ui).forEach((t) => types.add(t));
1276
+ if (types.size === 0)
1277
+ return;
1278
+ const registry = getComponentRegistryInstance();
1279
+ const builtInsMissing = [...types].some((type) => INTERNAL_COMPONENT_TYPES.includes(type) &&
1280
+ !registry.hasComponentLoader(type));
1281
+ void (builtInsMissing ? loadBuiltInComponents() : Promise.resolve())
1282
+ .then(() => registry.loadComponents([...types]))
1283
+ .catch(() => {
1284
+ // Reported by the check before rendering, which loads them again.
1285
+ });
1286
+ }
1287
+ async function ensureUiComponentsLoaded(ui, sectionEntries) {
1288
+ const componentRegistry = getComponentRegistryInstance();
1289
+ const { missingBuiltIn, missingCustom, toLoad } = await checkUsedComponentsLoadingBuiltIns([ui], new Set(sectionEntries.keys()));
1290
+ if (missingBuiltIn.length > 0) {
1291
+ throw componentsNotRegistered(missingBuiltIn, true);
1292
+ }
1293
+ if (missingCustom.length > 0) {
1294
+ throw componentsNotRegistered(missingCustom, false);
1158
1295
  }
1159
1296
  try {
1160
- await componentRegistry.loadComponents(Array.from(usedComponents));
1297
+ await componentRegistry.loadComponents(toLoad);
1161
1298
  }
1162
1299
  catch (error) {
1163
1300
  console.error("Error loading components lazily:", error);
@@ -1393,7 +1530,7 @@ function readSetupFacts(config) {
1393
1530
  // A boolean, never the value: the token must not cross this boundary.
1394
1531
  hasPreviewToken: Boolean(livePreview?.preview_token),
1395
1532
  previewHost: livePreview?.host,
1396
- hasPreviewHash: Boolean(livePreview?.live_preview),
1533
+ hasPreviewHash: isUsableHash(livePreview?.live_preview),
1397
1534
  };
1398
1535
  }
1399
1536
  function sendInitStudioSignal(config) {
@@ -1538,6 +1675,94 @@ function derivePlacementIncludePaths(compositionEntry, sectionEntries) {
1538
1675
  }
1539
1676
  return Object.fromEntries([...out].map(([key, paths]) => [key, [...paths]]));
1540
1677
  }
1678
+ /**
1679
+ * The scope every node placed directly in a section instance's slot resolves its
1680
+ * bindings in, keyed by that node's uid. Its descendants share it until another
1681
+ * section instance starts a scope of its own.
1682
+ *
1683
+ * A slot child is authored on the page but binds inside the section's data — a
1684
+ * text in an Author Card's slot bound to `company.name` needs `author.company` on
1685
+ * the page request, not `company`. This is the scope the render path roots those
1686
+ * paths at; a caller computing include[] paths at save uses it so the two cannot
1687
+ * drift apart. Like `derivePlacementIncludePaths`, it needs every placed section
1688
+ * in `sectionEntries`, with `ui` parsed.
1689
+ */
1690
+ function collectSlotChildScopes(compositionEntry, sectionEntries) {
1691
+ const pageUi = typeof compositionEntry.ui === "string"
1692
+ ? decompressSpec(compositionEntry.ui)
1693
+ : compositionEntry.ui;
1694
+ if (!pageUi)
1695
+ return {};
1696
+ const scopes = new Map();
1697
+ collectSectionInstanceBindings(pageUi, new Map(sectionEntries.map((s) => [s.uid, s])), compositionEntry.connected_content_type || "", scopes);
1698
+ return Object.fromEntries([...scopes].map(([uid, root]) => [
1699
+ uid,
1700
+ { fetchRootKey: root.key, prefix: [...root.prefix] },
1701
+ ]));
1702
+ }
1703
+ /**
1704
+ * Every section instance on the page (placed, nested in a slot, or defaulted into
1705
+ * one) with the scope its own bindings resolve in. A caller computing include[]
1706
+ * paths at save composes a section's section-relative binding paths onto
1707
+ * `prefix` (after `uidRemapping`) and files them under `fetchRootKey`, so a
1708
+ * reference the section reads lands on the request that fetches its data. Like
1709
+ * `derivePlacementIncludePaths`, it needs every placed section in
1710
+ * `sectionEntries`, with `ui` parsed.
1711
+ */
1712
+ function collectSectionPlacementScopes(compositionEntry, sectionEntries) {
1713
+ const pageUi = typeof compositionEntry.ui === "string"
1714
+ ? decompressSpec(compositionEntry.ui)
1715
+ : compositionEntry.ui;
1716
+ if (!pageUi)
1717
+ return [];
1718
+ return collectSectionInstanceBindings(pageUi, new Map(sectionEntries.map((s) => [s.uid, s])), compositionEntry.connected_content_type || "").map((binding) => ({
1719
+ instanceUid: binding.instanceUid,
1720
+ compositionUid: binding.compositionUid,
1721
+ fetchRootKey: binding.fetchRootKey,
1722
+ prefix: composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids, { pageAbsolute: binding.fieldIsPageAbsolute }),
1723
+ uidRemapping: { ...(binding.uidRemapping ?? {}) },
1724
+ }));
1725
+ }
1726
+ // Sets the request's preview hash on the delivery stack. On a server the stack
1727
+ // is shared by every request, so a request without a hash clears it, or an
1728
+ // earlier request's hash would leak into this one; clearing keeps live preview
1729
+ // enabled. In the browser the stack serves one visitor and the page may have
1730
+ // set the hash itself, so it is only ever replaced, never cleared.
1731
+ function applyRequestPreviewHash(deliveryStack, requestSearchParams) {
1732
+ const previewHash = requestSearchParams.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
1733
+ requestSearchParams.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH) ||
1734
+ "";
1735
+ const isServer = typeof window === "undefined";
1736
+ if (previewHash || isServer) {
1737
+ deliveryStack.livePreviewQuery(previewHash);
1738
+ }
1739
+ }
1740
+ /**
1741
+ * The language a request carries when nothing more specific (Studio's parameter,
1742
+ * the address) chose one: the fetch's own option, then the SDK config, then the
1743
+ * delivery stack's default. Shared by the resolver and the error reporting, so
1744
+ * a refusal always names the language that was actually sent.
1745
+ */
1746
+ function configuredLocale(config, optionLocale) {
1747
+ return optionLocale || config.locale || config.stackSdk?.locale;
1748
+ }
1749
+ /**
1750
+ * A locale code or variant alias read from the page URL, or `undefined` when it does not look like one.
1751
+ *
1752
+ * These values come from `window.location` (attacker-controllable) and end up as object keys when
1753
+ * include paths and references are grouped per locale/variant. Allow only the characters a locale
1754
+ * (`en-us`) or variant alias (`cs_personalize_0_1`, comma-separated lists) can contain, and never a
1755
+ * key that would reach `Object.prototype` (Snyk Code: Prototype Pollution).
1756
+ */
1757
+ const URL_TOKEN = /^[A-Za-z0-9_-]+(,[A-Za-z0-9_-]+)*$/;
1758
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
1759
+ function sanitizeUrlToken(value) {
1760
+ if (!value || value.length > 256 || !URL_TOKEN.test(value))
1761
+ return undefined;
1762
+ if (value.split(",").some((part) => FORBIDDEN_KEYS.has(part)))
1763
+ return undefined;
1764
+ return value;
1765
+ }
1541
1766
  function generateSdk(userConfig) {
1542
1767
  const config = processUserConfig(userConfig);
1543
1768
  if (clientRendererModeUtil.isInsideStudioFrame()) {
@@ -1550,11 +1775,11 @@ function generateSdk(userConfig) {
1550
1775
  // section fetches) automatically uses the right locale/variant, and
1551
1776
  // both INIT_STUDIO.globalLocale/globalVariantAlias and the per-query
1552
1777
  // GET_COMPOSITION_SPEC payload round-trip them back to Studio.
1553
- const urlLocale = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE);
1778
+ const urlLocale = sanitizeUrlToken(sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE));
1554
1779
  if (urlLocale) {
1555
1780
  config.locale = urlLocale;
1556
1781
  }
1557
- const urlVariantAlias = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS);
1782
+ const urlVariantAlias = sanitizeUrlToken(sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS));
1558
1783
  if (urlVariantAlias) {
1559
1784
  config.variantAlias = urlVariantAlias;
1560
1785
  }
@@ -1620,8 +1845,31 @@ function generateSdk(userConfig) {
1620
1845
  return undefined;
1621
1846
  return params.get(param) || undefined;
1622
1847
  };
1848
+ /**
1849
+ * The composition this render asks the URL resolver to prefer
1850
+ * (`cs-preferred-composition-uid`). Honoured inside Studio and on a preview
1851
+ * request, which is where Studio, the Visual Editor and Live Preview render:
1852
+ * a preview hash in the address, the stack being served by the preview
1853
+ * service (Live Preview hands a client-rendered page its hash by message, not
1854
+ * in the address), or inside the Visual Editor. A visitor's request ignores
1855
+ * it, so a query string can't change which template the live site renders.
1856
+ */
1857
+ const readPreferredCompositionUid = (searchParams) => {
1858
+ const params = getRequestSearchParams(searchParams);
1859
+ if (!params)
1860
+ return undefined;
1861
+ const isStudioOrPreview = params.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ||
1862
+ Boolean(params.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
1863
+ params.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH)) ||
1864
+ captureRequestRoute(config.stackSdk).servedBy === "preview" ||
1865
+ clientRendererModeUtil.isInsideVisualBuilderFrame();
1866
+ if (!isStudioOrPreview)
1867
+ return undefined;
1868
+ return (params.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREFERRED_COMPOSITION_UID) ||
1869
+ undefined);
1870
+ };
1623
1871
  const resolveEffectiveVariantAlias = (optionVariantAlias, searchParams) => {
1624
- const studioVariant = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS, searchParams);
1872
+ const studioVariant = sanitizeUrlToken(readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS, searchParams));
1625
1873
  return studioVariant || optionVariantAlias || config.variantAlias;
1626
1874
  };
1627
1875
  /**
@@ -1654,7 +1902,7 @@ function generateSdk(userConfig) {
1654
1902
  * with resolveLocale so the two cannot disagree about what was sent.
1655
1903
  */
1656
1904
  const resolveLocaleWithSource = (patternLocale, optionLocale, searchParams) => {
1657
- const studioLocale = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE, searchParams);
1905
+ const studioLocale = sanitizeUrlToken(readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE, searchParams));
1658
1906
  // Studio's own parameter is a setting an author chose, not part of the
1659
1907
  // address a visitor asked for, so it ranks as configuration.
1660
1908
  if (studioLocale)
@@ -1662,7 +1910,7 @@ function generateSdk(userConfig) {
1662
1910
  if (patternLocale)
1663
1911
  return { locale: patternLocale, source: "url-pattern" };
1664
1912
  return {
1665
- locale: optionLocale || config.locale || config.stackSdk?.locale,
1913
+ locale: configuredLocale(config, optionLocale),
1666
1914
  source: "configuration",
1667
1915
  };
1668
1916
  };
@@ -1719,106 +1967,6 @@ function generateSdk(userConfig) {
1719
1967
  // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
1720
1968
  // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
1721
1969
  // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
1722
- /**
1723
- * Names the entry a binding reads, for the middle of a sentence.
1724
- *
1725
- * A binding that names its own entry gets the uid and the content type,
1726
- * because in a project with many entries that is the whole of the lookup. A
1727
- * template binding names neither — it reads whichever entry the composition is
1728
- * connected to on this request — so it gets a phrase instead, and the sentence
1729
- * says less rather than printing a stand-in where a uid should be.
1730
- */
1731
- function describeBindingSubject(defect) {
1732
- if (!defect.entryUid || !defect.contentTypeUid) {
1733
- return "the entry this composition is connected to";
1734
- }
1735
- return `entry ${defect.entryUid} of "${defect.contentTypeUid}"`;
1736
- }
1737
- /**
1738
- * Says which bindings will render blank, and why.
1739
- *
1740
- * Walks every binding on the page, so it is skipped outright unless somebody
1741
- * will read the result.
1742
- *
1743
- * The missing-path case carries two causes and asserts neither, and that is
1744
- * the rule for this whole group rather than a hedge. We hold the entry, not
1745
- * the content type's schema, so a field that was renamed and a field the
1746
- * author simply has not filled in are the same absence from here. Picking one
1747
- * would send half of these readers to change something that is correct.
1748
- */
1749
- function reportBindingDefects(pageUi, data, request) {
1750
- if (!degradedReportingIsOn(config))
1751
- return;
1752
- for (const defect of findBindingDefects(pageUi, data.dataSources, request)) {
1753
- if (defect.code === DegradedCode.PREVIEW_ASSET_PROJECTION_NULL) {
1754
- reportDegraded({
1755
- code: DegradedCode.PREVIEW_ASSET_PROJECTION_NULL,
1756
- headline: `The asset at "${defect.path}" on ` +
1757
- describeBindingSubject(defect) +
1758
- " came back empty from the preview service. The same request " +
1759
- "returns it from the published CDN.",
1760
- causes: [
1761
- {
1762
- cause: "A known Preview API defect empties an asset asked for by a " +
1763
- "dotted path when a modular-blocks field is asked for beside it.",
1764
- fix: "Check the published site before changing anything — the binding is probably fine. Nothing in this project fixes it.",
1765
- },
1766
- {
1767
- cause: "The asset is genuinely not set on this entry.",
1768
- fix: "Set it, or leave it — the binding works either way.",
1769
- },
1770
- ],
1771
- findings: {
1772
- path: defect.path,
1773
- entryUid: defect.entryUid,
1774
- contentTypeUid: defect.contentTypeUid,
1775
- },
1776
- }, config);
1777
- continue;
1778
- }
1779
- if (defect.code === DegradedCode.BINDING_PATH_MISSING) {
1780
- reportDegraded({
1781
- code: DegradedCode.BINDING_PATH_MISSING,
1782
- headline: `The binding "${defect.path}" does not exist on ` +
1783
- describeBindingSubject(defect) +
1784
- ".",
1785
- causes: [
1786
- {
1787
- cause: "The field was renamed or removed on the content type.",
1788
- fix: "Re-point the binding at the field it should read.",
1789
- },
1790
- {
1791
- cause: "The field is there and nobody has filled it in yet.",
1792
- fix: "Nothing to fix here — add the content.",
1793
- },
1794
- ],
1795
- findings: {
1796
- path: defect.path,
1797
- entryUid: defect.entryUid,
1798
- contentTypeUid: defect.contentTypeUid,
1799
- },
1800
- }, config);
1801
- continue;
1802
- }
1803
- reportDegraded({
1804
- code: DegradedCode.BINDING_SHAPE_MISMATCH,
1805
- headline: `The binding "${defect.path}" reads a single value and resolved ` +
1806
- `to a ${defect.resolvedTo}.`,
1807
- causes: [
1808
- {
1809
- cause: "The binding points at a container rather than at a field inside it.",
1810
- fix: `Point it at a field within "${defect.path}".`,
1811
- },
1812
- ],
1813
- findings: {
1814
- path: defect.path,
1815
- entryUid: defect.entryUid,
1816
- contentTypeUid: defect.contentTypeUid,
1817
- resolvedTo: defect.resolvedTo,
1818
- },
1819
- }, config);
1820
- }
1821
- }
1822
1970
  /**
1823
1971
  * Says how many references came back as pointers rather than as entries.
1824
1972
  *
@@ -1956,7 +2104,7 @@ function generateSdk(userConfig) {
1956
2104
  setStaticEntryInDS(data.dataSources, ct_uid, entries);
1957
2105
  if (config.cslp.appendTags) {
1958
2106
  for (const entry of entries) {
1959
- addEditableTags(entry, ct_uid, true, entry?.locale || "en-us");
2107
+ addEditableTags(entry, ct_uid, true, entry?.locale || configuredLocale(config, locale));
1960
2108
  }
1961
2109
  }
1962
2110
  const returnedUids = new Set(entries.map((entry) => entry.uid));
@@ -1979,20 +2127,32 @@ function generateSdk(userConfig) {
1979
2127
  }
1980
2128
  /**
1981
2129
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
1982
- * Supports custom fetcher overrides (per-query > global > SDK default).
1983
2130
  */
1984
2131
  async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions, urlPatternContext, searchParams) {
1985
2132
  const { connected_content_type, compositionQuery, includeQueries, onlyQueries: requestedOnlyQueries, } = fetchOptions;
1986
2133
  if (!connected_content_type) {
1987
2134
  return;
1988
2135
  }
2136
+ // A section's entry is only something to preview against, picked in
2137
+ // Studio's navbar. While its content type has none, the section still
2138
+ // renders, each bound prop on its component's default, and Studio shows
2139
+ // "No preview entry". A template composition's entry is its content, so a
2140
+ // template composition still fails.
2141
+ const canRenderWithoutEntry = compositionEntry.place_composition_as === "section";
1989
2142
  // A page that binds many sections can push the projection past the Delivery
1990
2143
  // API's URL limit, which rejects the whole request and costs us the page.
1991
2144
  // The projection is an optimisation; the reference paths are not. Give up
1992
2145
  // the projection and accept a larger response rather than losing the entry.
2146
+ //
2147
+ // Visual Editor tags carry the entry's language, and a projection drops
2148
+ // `locale` unless it asks for it (the tags then fell back to "en-us", a
2149
+ // language a stack may not have).
2150
+ const projectedOnlyQueries = config.cslp.appendTags && requestedOnlyQueries.length > 0
2151
+ ? uniqBy([...requestedOnlyQueries, ["BASE", "locale"]], ([reference, field]) => `${reference}|${field}`)
2152
+ : requestedOnlyQueries;
1993
2153
  const urlBudget = applyUrlBudget({
1994
2154
  references: includeQueries,
1995
- only: requestedOnlyQueries,
2155
+ only: projectedOnlyQueries,
1996
2156
  });
1997
2157
  const onlyQueries = urlBudget.only;
1998
2158
  // Both of these are for whoever is building the site, not for its logs. The
@@ -2012,7 +2172,10 @@ function generateSdk(userConfig) {
2012
2172
  `API URL limit. This request is expected to fail with 414.`);
2013
2173
  }
2014
2174
  }
2015
- const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
2175
+ // A copy: the Studio override below writes `templateEntryUid` into it.
2176
+ const resolvedOptions = {
2177
+ ...compositionQueryOptions,
2178
+ };
2016
2179
  // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
2017
2180
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
2018
2181
  const _studioIntelligence = enhancedOptions?._studioIntelligence;
@@ -2033,7 +2196,13 @@ function generateSdk(userConfig) {
2033
2196
  // Locale/variant resolution is shared across all SDK fetches — see
2034
2197
  // resolveEffectiveVariantAlias (studio `cs-variant-alias` > per-fetch option > config).
2035
2198
  const resolveVariant = () => resolveEffectiveVariantAlias(resolvedOptions.variantAlias, searchParams);
2036
- const defaultImpl = async () => {
2199
+ /** What every lookup below does when it finds no entry. */
2200
+ const whenNoEntryFound = () => {
2201
+ if (canRenderWithoutEntry)
2202
+ return null;
2203
+ throw connectedEntryNotFoundError(connected_content_type, resolvedOptions?.templateEntryUid, config);
2204
+ };
2205
+ const queryTemplateEntry = async () => {
2037
2206
  // Resolution priority: templateEntryUid > url_metadata path > legacy path
2038
2207
  if (resolvedOptions.templateEntryUid) {
2039
2208
  // Enhanced include queries with Studio Intelligence
@@ -2055,37 +2224,22 @@ function generateSdk(userConfig) {
2055
2224
  .ctQuery(connected_content_type, queryOptions)
2056
2225
  .limit(1);
2057
2226
  dataQuery = requireStack(config).where(dataQuery, "uid", resolvedOptions.templateEntryUid);
2058
- const response = await dataQuery.find().catch((err) => {
2227
+ const response = await dataQuery.find().catch(async (err) => {
2059
2228
  // Classified by the same response rules as any other request. The
2060
2229
  // name it used to carry described the content it was after rather
2061
2230
  // than what went wrong, so a wrong api key and a delivery outage
2062
2231
  // both surfaced as "fetching connected data failed".
2063
- const servedByNow = resolveServedBy(config.stackSdk?.livePreviewConfig);
2064
- throw (classifyResponseError(err, config, { servedBy: servedByNow }) ??
2065
- diagnoseUnreadableResponse(err, config, { servedBy: servedByNow }));
2232
+ const routeNow = {
2233
+ ...captureRequestRoute(config.stackSdk),
2234
+ locale: queryOptions.locale,
2235
+ };
2236
+ const { classifyResponseError, diagnoseUnreadableResponse } = await loadErrorClassifier();
2237
+ throw (classifyResponseError(err, config, routeNow) ??
2238
+ diagnoseUnreadableResponse(err, config, routeNow));
2066
2239
  });
2067
2240
  const entries = entriesFromResponse(response);
2068
- if (!entries?.[0]) {
2069
- throw createStudioError({
2070
- code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2071
- headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2072
- causes: [
2073
- {
2074
- cause: `No entry of "${connected_content_type}" matches this composition.`,
2075
- fix: "Create one, or point the composition at a content type that has entries.",
2076
- },
2077
- {
2078
- cause: "The entry exists and is not published to this environment.",
2079
- fix: "Publish it, or check which environment this site reads.",
2080
- },
2081
- ],
2082
- context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2083
- findings: {
2084
- contentTypeUid: connected_content_type,
2085
- templateEntryUid: resolvedOptions?.templateEntryUid,
2086
- },
2087
- });
2088
- }
2241
+ if (!entries?.[0])
2242
+ return whenNoEntryFound();
2089
2243
  return entries[0];
2090
2244
  }
2091
2245
  // Check if we should use url_metadata path
@@ -2111,11 +2265,12 @@ function generateSdk(userConfig) {
2111
2265
  if (parsedMetadata.url_source ===
2112
2266
  COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
2113
2267
  // content_type_url_pattern: Direct URL match (no pattern variables).
2268
+ localeSent = resolveLocaleWithSource(undefined, resolvedOptions.locale, searchParams);
2114
2269
  let directQuery = requireStack(config)
2115
2270
  .ctQuery(connected_content_type, {
2116
2271
  references: allIncludeQueries,
2117
2272
  variantAlias: resolveVariant(),
2118
- locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
2273
+ locale: localeSent.locale,
2119
2274
  only: finalOnlyQueries,
2120
2275
  })
2121
2276
  .limit(1);
@@ -2168,11 +2323,13 @@ function generateSdk(userConfig) {
2168
2323
  // A setup or credential failure is not: retrying asks the same broken
2169
2324
  // connection the same question, then blames a missing page. So
2170
2325
  // anything we can diagnose is raised here instead of swallowed.
2171
- const diagnosed = classifyResponseError(metadataError, config, {
2326
+ const facts = {
2172
2327
  locale: localeSent.locale,
2173
2328
  localeSource: localeSent.source,
2174
2329
  url: compositionQuery.url,
2175
- });
2330
+ };
2331
+ const { classifyResponseError } = await loadErrorClassifier();
2332
+ const diagnosed = classifyResponseError(metadataError, config, facts);
2176
2333
  if (diagnosed)
2177
2334
  throw diagnosed;
2178
2335
  console.warn("Metadata template resolution failed, falling back to legacy:", metadataError);
@@ -2203,107 +2360,44 @@ function generateSdk(userConfig) {
2203
2360
  if ("url" in compositionQuery && compositionQuery.url) {
2204
2361
  dataQuery = requireStack(config).where(dataQuery, "url", compositionQuery.url);
2205
2362
  }
2206
- const response = await dataQuery.find().catch((err) => {
2363
+ const response = await dataQuery.find().catch(async (err) => {
2207
2364
  // Classified by the same response rules as any other request. The
2208
2365
  // name it used to carry described the content it was after rather
2209
2366
  // than what went wrong, so a wrong api key and a delivery outage
2210
2367
  // both surfaced as "fetching connected data failed".
2211
- const servedByNow = resolveServedBy(config.stackSdk?.livePreviewConfig);
2212
- throw (classifyResponseError(err, config, { servedBy: servedByNow }) ??
2213
- diagnoseUnreadableResponse(err, config, { servedBy: servedByNow }));
2368
+ const routeNow = {
2369
+ ...captureRequestRoute(config.stackSdk),
2370
+ locale: queryOptions.locale,
2371
+ };
2372
+ const { classifyResponseError, diagnoseUnreadableResponse } = await loadErrorClassifier();
2373
+ throw (classifyResponseError(err, config, routeNow) ??
2374
+ diagnoseUnreadableResponse(err, config, routeNow));
2214
2375
  });
2215
2376
  const entries = entriesFromResponse(response);
2216
- if (!entries?.[0]) {
2217
- throw createStudioError({
2218
- code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2219
- headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2220
- causes: [
2221
- {
2222
- cause: `No entry of "${connected_content_type}" matches this composition.`,
2223
- fix: "Create one, or point the composition at a content type that has entries.",
2224
- },
2225
- {
2226
- cause: "The entry exists and is not published to this environment.",
2227
- fix: "Publish it, or check which environment this site reads.",
2228
- },
2229
- ],
2230
- context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2231
- findings: {
2232
- contentTypeUid: connected_content_type,
2233
- templateEntryUid: resolvedOptions?.templateEntryUid,
2234
- },
2235
- });
2236
- }
2377
+ if (!entries?.[0])
2378
+ return whenNoEntryFound();
2237
2379
  return entries[0];
2238
2380
  };
2239
- const customFetcher = perQueryFetchTemplateEntry ?? config.fetchTemplateEntry;
2240
- let entry;
2241
- if (customFetcher) {
2242
- entry = await customFetcher({
2243
- compositionEntry,
2244
- compositionQuery,
2245
- connectedContentType: connected_content_type,
2246
- options: resolvedOptions,
2247
- includeReferences: includeQueries,
2248
- only: isInsideStudio || isInsideVB ? [] : onlyQueries,
2249
- stackSdk: config.stackSdk?.sdk,
2250
- defaultFetch: defaultImpl,
2251
- });
2252
- if (!entry) {
2253
- throw createStudioError({
2254
- code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2255
- headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2256
- causes: [
2257
- {
2258
- cause: `No entry of "${connected_content_type}" matches this composition.`,
2259
- fix: "Create one, or point the composition at a content type that has entries.",
2260
- },
2261
- {
2262
- cause: "The entry exists and is not published to this environment.",
2263
- fix: "Publish it, or check which environment this site reads.",
2264
- },
2265
- ],
2266
- context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2267
- findings: {
2268
- contentTypeUid: connected_content_type,
2269
- templateEntryUid: resolvedOptions?.templateEntryUid,
2270
- },
2271
- });
2272
- }
2273
- }
2274
- else {
2275
- entry = await defaultImpl();
2276
- // Check if defaultImpl returned empty/null entry (e.g., empty entry list from API)
2277
- if (!entry) {
2278
- throw createStudioError({
2279
- code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
2280
- headline: `No entry was found for the content type "${connected_content_type}" this composition is connected to.`,
2281
- causes: [
2282
- {
2283
- cause: `No entry of "${connected_content_type}" matches this composition.`,
2284
- fix: "Create one, or point the composition at a content type that has entries.",
2285
- },
2286
- {
2287
- cause: "The entry exists and is not published to this environment.",
2288
- fix: "Publish it, or check which environment this site reads.",
2289
- },
2290
- ],
2291
- context: buildStudioErrorContext(config, resolveServedBy(config.stackSdk?.livePreviewConfig)),
2292
- findings: {
2293
- contentTypeUid: connected_content_type,
2294
- templateEntryUid: resolvedOptions?.templateEntryUid,
2295
- },
2296
- });
2297
- }
2381
+ const entry = await queryTemplateEntry();
2382
+ // A section renders with no preview entry; anything else has thrown by now.
2383
+ if (!entry) {
2384
+ whenNoEntryFound();
2385
+ return;
2298
2386
  }
2299
2387
  if (config.cslp.appendTags) {
2300
- addEditableTags(entry, connected_content_type, true, entry.locale);
2388
+ // an entry without its own language is tagged with the one requested
2389
+ addEditableTags(entry, connected_content_type, true, entry.locale ||
2390
+ resolveLocale(undefined, resolvedOptions.locale, searchParams));
2301
2391
  }
2302
2392
  setTemplateEntryInDS(data.dataSources, entry);
2303
2393
  if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
2304
2394
  return;
2305
2395
  }
2306
2396
  async function fetchData(compositionEntry, queryOptions, options, sectionEntries = [], searchParams) {
2397
+ // data_sources read once into the shape every reader assumes (a no-op for
2398
+ // entries fetchSpec already normalized).
2399
+ compositionEntry = withNormalizedDataSources(compositionEntry);
2400
+ sectionEntries = sectionEntries.map(withNormalizedDataSources);
2307
2401
  const { variantAlias, locale } = options || {};
2308
2402
  // Read all saved reference include paths from compositionEntry.data_sources.resolvedReferences.
2309
2403
  // Covers toggle ON paths, directly-bound field paths, and condition block binding paths.
@@ -2338,7 +2432,9 @@ function generateSdk(userConfig) {
2338
2432
  const stripped = segments[i].replace(/^\d+_/, ""); // strip modular-block prefix
2339
2433
  // Skip pure numeric array indexes and "entries" array-wrapper segments —
2340
2434
  // neither is a valid Contentstack include[] field name.
2341
- if (/^\d+$/.test(stripped) || stripped === "entries") {
2435
+ if (/^\d+$/.test(stripped) ||
2436
+ stripped === "entries" ||
2437
+ parseFirstOfTypeSegment(stripped) !== undefined) {
2342
2438
  continue;
2343
2439
  }
2344
2440
  result.push(stripped);
@@ -2525,9 +2621,7 @@ function generateSdk(userConfig) {
2525
2621
  // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
2526
2622
  // reference chain (W1 → W2 → …) fetches the full nested include depth.
2527
2623
  const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
2528
- const pageUi = typeof compositionEntry.ui === "string"
2529
- ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
2530
- : compositionEntry.ui;
2624
+ const pageUi = parseUI(compositionEntry.ui, compositionEntry.composable_uid);
2531
2625
  const instanceBindings = collectSectionInstanceBindings(pageUi, sectionsByUid, connectedContentTypeUid);
2532
2626
  // The author's own modular-block choices, used below to drop the include[]
2533
2627
  // paths the Delivery API discards.
@@ -2693,10 +2787,9 @@ function generateSdk(userConfig) {
2693
2787
  if (!section)
2694
2788
  continue;
2695
2789
  const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2696
- const sectionUi = typeof section.ui === "string"
2697
- ? parseUI(section.ui, section.composable_uid)
2698
- : section.ui;
2699
- mapSectionRepeaterPaths(sectionUi, prefix, repeaterPathMap);
2790
+ const sectionUi = tryParseUI(section.ui, section.composable_uid);
2791
+ if (sectionUi)
2792
+ mapSectionRepeaterPaths(sectionUi, prefix, repeaterPathMap);
2700
2793
  }
2701
2794
  if (repeaterPathMap.size > 0) {
2702
2795
  projectCrossBoundaryRepeaterBindings(pageUi, repeaterPathMap, mergedTemplateOnly);
@@ -2818,7 +2911,7 @@ function generateSdk(userConfig) {
2818
2911
  // read once these have resolved can belong to somebody else's request — and
2819
2912
  // a diagnosis that names the wrong service is worse than none.
2820
2913
  const requestFacts = {
2821
- servedBy: resolveServedBy(config.stackSdk?.livePreviewConfig),
2914
+ servedBy: captureRequestRoute(config.stackSdk).servedBy,
2822
2915
  projection: dedupedTemplateOnly,
2823
2916
  };
2824
2917
  await Promise.all([
@@ -2841,7 +2934,13 @@ function generateSdk(userConfig) {
2841
2934
  }, searchParams),
2842
2935
  ]);
2843
2936
  reportUnresolvedReferences(data);
2844
- reportBindingDefects(pageUi, data, requestFacts);
2937
+ // Development or debug only, so its binding walk and wording load on demand:
2938
+ // published pages never download them. Awaited, so the report reads the
2939
+ // data exactly as it is here.
2940
+ if (degradedReportingIsOn(config)) {
2941
+ const { reportBindingDefects } = await import('./binding-defect-report.js');
2942
+ reportBindingDefects(config, pageUi, dataSourcesAsRendered(compositionEntry, data.dataSources), requestFacts);
2943
+ }
2845
2944
  // D7: the folded template entry (fetched once, above) also feeds the static
2846
2945
  // entry pool so contentstack-entry references to it resolve without the
2847
2946
  // second fetch we removed from mergedRefs.
@@ -2863,21 +2962,21 @@ function generateSdk(userConfig) {
2863
2962
  data.page_data_sources = data.dataSources;
2864
2963
  return data;
2865
2964
  }
2866
- async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
2965
+ async function fetchSpec(queryOptions, options, searchParams) {
2867
2966
  requireStack(config);
2868
- // Phase 1: Get Studio Intelligence if available (graceful fallback)
2869
- const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2870
- // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
2871
- const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2872
- // Phase 3: Fetch with enhanced context (preserves custom fetchers)
2873
- const { compositionEntry, urlResolution, requestContext } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams));
2874
- const ui = typeof compositionEntry.ui === "string"
2875
- ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
2876
- : compositionEntry.ui;
2967
+ // Phases 1-2: Studio Intelligence, inside the canvas only (graceful fallback;
2968
+ // user preferences win).
2969
+ const enhancedOptions = await withStudioIntelligence(options, config);
2970
+ // Phase 3: Fetch with enhanced context
2971
+ const { compositionEntry: fetchedEntry, urlResolution, requestContext, } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams), readPreferredCompositionUid(searchParams));
2972
+ // data_sources read once into the shape every reader assumes.
2973
+ const compositionEntry = withNormalizedDataSources(fetchedEntry);
2974
+ const ui = parseUI(compositionEntry.ui, compositionEntry.composable_uid);
2975
+ startLoadingUsedComponents([ui]);
2877
2976
  const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
2977
+ startLoadingUsedComponents(Array.from(sectionEntries.values(), (entry) => entry.ui));
2878
2978
  const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
2879
2979
  // Lazy loading and SSR validation for production mode
2880
- // Skip if called from fetchMultipleSpecs (which handles loading in batch)
2881
2980
  const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
2882
2981
  // 1.3.0 rendering contract: server returns the spec as data only. The
2883
2982
  // renderer is `"use client"` and runs entirely on the client — that's
@@ -2886,38 +2985,22 @@ function generateSdk(userConfig) {
2886
2985
  // which means dragging `"use client"` components into the server module
2887
2986
  // graph — exactly the failure mode the RFC asks us to avoid.
2888
2987
  const isServer = typeof window === "undefined";
2889
- if (!isServer && isProductionMode && ui && !skipComponentLoading) {
2988
+ if (!isServer && isProductionMode && ui) {
2890
2989
  const componentRegistry = getComponentRegistryInstance();
2891
2990
  // SSR VALIDATION: Check if all required components are registered
2892
- // Built-in components should be registered automatically when @contentstack/studio-react is imported
2893
- const usedComponents = analyzeUsedComponents(ui);
2894
- const sectionComponentTypes = new Set(sectionEntries.keys());
2895
- const missingBuiltInComponents = [];
2896
- const missingCustomComponents = [];
2897
- usedComponents.forEach((type) => {
2898
- if (sectionComponentTypes.has(type)) {
2899
- return;
2900
- }
2901
- if (!componentRegistry.hasComponentLoader(type)) {
2902
- if (INTERNAL_COMPONENT_TYPES.includes(type)) {
2903
- missingBuiltInComponents.push(type);
2904
- }
2905
- else {
2906
- missingCustomComponents.push(type);
2907
- }
2908
- }
2909
- });
2991
+ // Built-ins: @contentstack/studio-react registers them on first use; the check loads them when missing
2992
+ const { missingBuiltIn, missingCustom, toLoad } = await checkUsedComponentsLoadingBuiltIns([ui], new Set(sectionEntries.keys()));
2910
2993
  // Handle missing internal components (SDK import issue)
2911
- if (missingBuiltInComponents.length > 0) {
2912
- throw componentsNotRegistered(missingBuiltInComponents, true, config);
2994
+ if (missingBuiltIn.length > 0) {
2995
+ throw componentsNotRegistered(missingBuiltIn, true, config);
2913
2996
  }
2914
2997
  // Handle missing custom components (normal - user needs to register)
2915
- if (missingCustomComponents.length > 0) {
2916
- throw componentsNotRegistered(missingCustomComponents, false, config);
2998
+ if (missingCustom.length > 0) {
2999
+ throw componentsNotRegistered(missingCustom, false, config);
2917
3000
  }
2918
3001
  // Load the components
2919
3002
  try {
2920
- await componentRegistry.loadComponents(Array.from(usedComponents));
3003
+ await componentRegistry.loadComponents(toLoad);
2921
3004
  }
2922
3005
  catch (error) {
2923
3006
  console.error("Error loading components lazily:", error);
@@ -2949,14 +3032,18 @@ function generateSdk(userConfig) {
2949
3032
  *
2950
3033
  * Runs in both SSR and CSR (plain async, not a hook).
2951
3034
  */
2952
- async function fetchCompositionSpecOnly(queryOptions, options, skipComponentLoading = false) {
3035
+ async function fetchCompositionSpecOnly(queryOptions, options, skipComponentLoading = false,
3036
+ /**
3037
+ * The request's own query, forwarded by a server render. Undefined reads
3038
+ * the page's address, as in the browser.
3039
+ */
3040
+ searchParams) {
2953
3041
  requireStack(config);
2954
- const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2955
- const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2956
- const { compositionEntry, urlResolution, requestContext } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch());
2957
- const ui = typeof compositionEntry.ui === "string"
2958
- ? parseUI(compositionEntry.ui, compositionEntry.composable_uid)
2959
- : compositionEntry.ui;
3042
+ const enhancedOptions = await withStudioIntelligence(options, config);
3043
+ const { compositionEntry: fetchedEntry, urlResolution, requestContext, } = await fetchComposition(config, queryOptions, enhancedOptions, isEditorFetch(searchParams), readPreferredCompositionUid(searchParams));
3044
+ // data_sources read once into the shape every reader assumes.
3045
+ const compositionEntry = withNormalizedDataSources(fetchedEntry);
3046
+ const ui = parseUI(compositionEntry.ui, compositionEntry.composable_uid);
2960
3047
  // Section composition entries are STRUCTURAL (their ui trees are needed to
2961
3048
  // render embedded section nodes and to compute section scoping) — keep them.
2962
3049
  const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
@@ -2982,64 +3069,6 @@ function generateSdk(userConfig) {
2982
3069
  },
2983
3070
  };
2984
3071
  }
2985
- async function fetchMultipleSpecs(queries, options) {
2986
- requireStack(config);
2987
- // Fetch all specs in parallel (skip individual component loading)
2988
- const specs = await Promise.all(queries.map((query) => fetchSpec(query, options, true)));
2989
- // In production mode, perform union analysis and load components once.
2990
- // Gated to client-only — see the equivalent block in `fetchSpec` for the
2991
- // 1.3.0-contract reasoning (server returns spec as data; validation belongs
2992
- // on the client where the renderer actually runs).
2993
- const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
2994
- const isServer = typeof window === "undefined";
2995
- if (!isServer && isProductionMode) {
2996
- const componentRegistry = getComponentRegistryInstance();
2997
- // Collect all unique component types from all specs
2998
- // Built-in components should be registered automatically when @contentstack/studio-react is imported
2999
- const allComponents = new Set();
3000
- const allSectionComponents = new Set();
3001
- specs.forEach((spec) => {
3002
- if (spec.ui) {
3003
- const components = analyzeUsedComponents(spec.ui);
3004
- components.forEach((c) => allComponents.add(c));
3005
- }
3006
- spec.sectionCompositions?.forEach((section) => allSectionComponents.add(section.uid));
3007
- });
3008
- // SSR VALIDATION: Check if all required components are registered
3009
- const missingBuiltInComponents = [];
3010
- const missingCustomComponents = [];
3011
- allComponents.forEach((type) => {
3012
- if (allSectionComponents.has(type)) {
3013
- return;
3014
- }
3015
- if (!componentRegistry.hasComponentLoader(type)) {
3016
- if (INTERNAL_COMPONENT_TYPES.includes(type)) {
3017
- missingBuiltInComponents.push(type);
3018
- }
3019
- else {
3020
- missingCustomComponents.push(type);
3021
- }
3022
- }
3023
- });
3024
- // Handle missing internal components (SDK import issue)
3025
- if (missingBuiltInComponents.length > 0) {
3026
- throw componentsNotRegistered(missingBuiltInComponents, true, config);
3027
- }
3028
- // Handle missing custom components (normal - user needs to register)
3029
- if (missingCustomComponents.length > 0) {
3030
- throw componentsNotRegistered(missingCustomComponents, false, config);
3031
- }
3032
- // Load all unique components in parallel (deduplication happens automatically)
3033
- try {
3034
- await componentRegistry.loadComponents(Array.from(allComponents));
3035
- }
3036
- catch (error) {
3037
- console.error("Error loading components for multiple specs:", error);
3038
- throw error; // Re-throw to surface the actual loading error
3039
- }
3040
- }
3041
- return specs;
3042
- }
3043
3072
  /**
3044
3073
  * Reusable helper to fetch data from Contentstack
3045
3074
  * Now uses QueryExecutor internally to support full QuerySpec with filters, sorting, etc.
@@ -3090,7 +3119,7 @@ function generateSdk(userConfig) {
3090
3119
  // Add editable tags (CSLP)
3091
3120
  if (config.cslp.appendTags && Array.isArray(entries)) {
3092
3121
  entries.forEach((entry) => {
3093
- addEditableTags(entry, querySpec.contentType, true, entry.locale || "en-us");
3122
+ addEditableTags(entry, querySpec.contentType, true, entry.locale || configuredLocale(config, options?.locale));
3094
3123
  });
3095
3124
  }
3096
3125
  return {
@@ -3332,7 +3361,6 @@ function generateSdk(userConfig) {
3332
3361
  // Hence, we moved this to the internal method.
3333
3362
  fetchSpec,
3334
3363
  fetchCompositionSpecOnly,
3335
- fetchMultipleSpecs,
3336
3364
  fetchData,
3337
3365
  fetchTemplateEntry,
3338
3366
  getSeoMetadata,
@@ -3367,31 +3395,19 @@ function generateSdk(userConfig) {
3367
3395
  * server-only `searchQuery` string for forwarding Studio iframe
3368
3396
  * overrides (locale, variant, preview entry, edit mode).
3369
3397
  * @param options - Optional modifiers: `variantAlias`, `locale`,
3370
- * `templateEntryUid`, `extendQuery`, custom fetchers.
3398
+ * `templateEntryUid`. (`extendQuery` is deprecated: tick the
3399
+ * references in Studio instead.)
3371
3400
  * @returns `Promise<StudioComponentSpecOptions>` — the resolved spec
3372
3401
  * options object.
3402
+ *
3403
+ * On failure it rejects with a `ComposableStudioError`, except inside
3404
+ * Studio's canvas, where it resolves with a spec that shows the failure
3405
+ * and `resolutionTelemetry.error` says why.
3373
3406
  */
3374
3407
  fetchCompositionData: async (queryOptions, options) => {
3375
- requireStack(config);
3376
3408
  const { searchQuery, ...compositionQueryInput } = queryOptions;
3377
3409
  const compositionQuery = convertCompositionQueryInputToCompositionQuery(compositionQueryInput);
3378
3410
  const urlSearchParam = new URLSearchParams(searchQuery);
3379
- // NOTE: Always keep this before fetching the spec. In SSR, we use the urlSearchParams
3380
- // to get the hash and then use it to fetch the composition.
3381
- //
3382
- // Only invoke `livePreviewQuery` when the request URL actually carries
3383
- // a preview hash. Passing an empty string explicitly disables live
3384
- // preview on the delivery SDK for subsequent requests, which forces
3385
- // SSR's `fetchSpec` to hit the delivery API even when the stack was
3386
- // initialised with `live_preview.enable=true`. Skipping the reset
3387
- // when there's no hash preserves the stack's initialised live-preview
3388
- // state and matches CSR's `useCompositionData` behaviour, which never
3389
- // resets the hash between fetches.
3390
- const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
3391
- urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
3392
- if (previewHash) {
3393
- requireStack(config).livePreviewQuery(previewHash);
3394
- }
3395
3411
  const rendererModeUtil = new RendererModeUtil(urlSearchParam);
3396
3412
  // P4.2 (ADR-0005): always fetch and return the spec — uniformly for the
3397
3413
  // composition-uid and URL cases, whether or not it is being edited. The two
@@ -3406,7 +3422,63 @@ function generateSdk(userConfig) {
3406
3422
  // server-side resolvers see the author's live editor context (cs-locale,
3407
3423
  // cs-variant-alias, cs-template-entry-uid) — SSR resolves identically to CSR.
3408
3424
  // On the client this is the same window-derived context, so CSR is unchanged.
3409
- const spec = await fetchSpec(compositionQuery, options, false, urlSearchParam);
3425
+ //
3426
+ // Inside Studio's canvas a failure resolves instead of rejecting: the
3427
+ // HTTP status means nothing there, and a rejection is where the reason
3428
+ // used to get lost. Visitors still get the rejection. The setup check
3429
+ // sits inside for the same reason: an incomplete setup is the failure
3430
+ // the canvas most needs to name.
3431
+ const isStudioCanvasRequest = isInStudio(urlSearchParam);
3432
+ let spec;
3433
+ let resolutionTelemetry;
3434
+ let servedByPreview = false;
3435
+ try {
3436
+ // Keep this before fetching the spec: in SSR the hash comes from the
3437
+ // request's search params. It is reset per call, but concurrent requests
3438
+ // on one shared stack are still not isolated from each other.
3439
+ applyRequestPreviewHash(requireStack(config), urlSearchParam);
3440
+ servedByPreview =
3441
+ captureRequestRoute(config.stackSdk).servedBy === "preview";
3442
+ spec = await fetchSpec(compositionQuery, options, urlSearchParam);
3443
+ // Successes are reported too. Canvas only, so a visitor's page
3444
+ // carries nothing it did not carry before.
3445
+ if (isStudioCanvasRequest) {
3446
+ resolutionTelemetry = buildResolutionTelemetry({
3447
+ query: compositionQuery,
3448
+ options,
3449
+ spec,
3450
+ });
3451
+ }
3452
+ }
3453
+ catch (error) {
3454
+ // A refused preview hash outside Studio's canvas is an old or copied
3455
+ // preview link (or a bot's parameter), not a failure of this page:
3456
+ // answer it as the same request without the link would be answered.
3457
+ // The retry carries no hash, so it cannot come back here.
3458
+ if (!isStudioCanvasRequest &&
3459
+ servedByPreview &&
3460
+ isPreviewHashRefused(error)) {
3461
+ warnPreviewHashRefusedOnce();
3462
+ requireStack(config).livePreviewQuery("");
3463
+ return sdkSingleton.public.fetchCompositionData({
3464
+ ...queryOptions,
3465
+ searchQuery: withoutPreviewParams(urlSearchParam),
3466
+ }, options);
3467
+ }
3468
+ if (!isStudioCanvasRequest ||
3469
+ !(error instanceof ComposableStudioError)) {
3470
+ throw error;
3471
+ }
3472
+ // The developer gets the error itself, in the server log; Studio
3473
+ // gets a plain-data copy that travels with the page.
3474
+ console.error(error);
3475
+ resolutionTelemetry = buildResolutionTelemetry({
3476
+ query: compositionQuery,
3477
+ options,
3478
+ error,
3479
+ });
3480
+ spec = buildResolutionFailureSpec(resolutionTelemetry);
3481
+ }
3410
3482
  // Echo the resolved editor locale/variant back to Studio so the pushed
3411
3483
  // `sdkContext` reports the copy the SSR data was actually fetched in (e.g.
3412
3484
  // fr-fr) rather than the host's empty default — otherwise Studio's
@@ -3435,6 +3507,7 @@ function generateSdk(userConfig) {
3435
3507
  mode: rendererModeUtil.getMode(spec.compositionEntry.composable_uid),
3436
3508
  },
3437
3509
  seo: getSeoMetadata(spec.ui, spec.data),
3510
+ ...(resolutionTelemetry ? { resolutionTelemetry } : {}),
3438
3511
  };
3439
3512
  },
3440
3513
  /**
@@ -3455,14 +3528,28 @@ function generateSdk(userConfig) {
3455
3528
  const { searchQuery, ...compositionQueryInput } = queryOptions;
3456
3529
  const compositionQuery = convertCompositionQueryInputToCompositionQuery(compositionQueryInput);
3457
3530
  const urlSearchParam = new URLSearchParams(searchQuery);
3458
- // Mirror fetchCompositionData: only reset live preview when a hash is
3459
- // actually present, so we don't disable the stack's live-preview state.
3460
- const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
3461
- urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
3462
- if (previewHash) {
3463
- requireStack(config).livePreviewQuery(previewHash);
3531
+ applyRequestPreviewHash(requireStack(config), urlSearchParam);
3532
+ const servedByPreview = captureRequestRoute(config.stackSdk).servedBy === "preview";
3533
+ // A server has no page address, so Studio's parameters (editor mode,
3534
+ // the template being edited) arrive only in `searchQuery`. An empty one
3535
+ // leaves the browser reading its own address, as it always has.
3536
+ try {
3537
+ return await fetchCompositionSpecOnly(compositionQuery, options, false, urlSearchParam.toString() ? urlSearchParam : undefined);
3538
+ }
3539
+ catch (error) {
3540
+ // Same answer as fetchCompositionData gives a refused preview hash.
3541
+ if (!isInStudio(urlSearchParam) &&
3542
+ servedByPreview &&
3543
+ isPreviewHashRefused(error)) {
3544
+ warnPreviewHashRefusedOnce();
3545
+ requireStack(config).livePreviewQuery("");
3546
+ return sdkSingleton.public.fetchComposition({
3547
+ ...queryOptions,
3548
+ searchQuery: withoutPreviewParams(urlSearchParam),
3549
+ }, options);
3550
+ }
3551
+ throw error;
3464
3552
  }
3465
- return fetchCompositionSpecOnly(compositionQuery, options);
3466
3553
  },
3467
3554
  /**
3468
3555
  * This method is used to get the configuration for the client.
@@ -3477,6 +3564,10 @@ function generateSdk(userConfig) {
3477
3564
  if (clientRendererModeUtil.isInsideStudioFrame()) {
3478
3565
  // Inside Studio iframe - send INIT_STUDIO
3479
3566
  sendInitStudioSignal(config);
3567
+ // Live preview sends every canvas request to the preview host, so this is
3568
+ // the only request that tests the delivery setup the published site uses.
3569
+ // Canvas-only, so it loads here rather than in every visitor's bundle.
3570
+ void import('./setup-check-signal.js').then(({ startSetupCheck }) => startSetupCheck(config));
3480
3571
  }
3481
3572
  else if (clientRendererModeUtil.isInsideIframe()) {
3482
3573
  // Inside preview iframe - send INIT_STUDIO
@@ -3670,6 +3761,27 @@ function matchedNoEntryCauses(considered, servedBy, config) {
3670
3761
  },
3671
3762
  ];
3672
3763
  }
3764
+ /**
3765
+ * A connected composition resolved, but the entry it reads from did not. Which
3766
+ * service answered decides whether "not published" is a possible cause: the
3767
+ * preview service serves unpublished entries.
3768
+ */
3769
+ function connectedEntryNotFoundError(contentTypeUid, templateEntryUid, config) {
3770
+ const route = captureRequestRoute(config.stackSdk);
3771
+ return createStudioError({
3772
+ code: StudioErrorCode.CONNECTED_ENTRY_NOT_FOUND,
3773
+ headline: `No entry was found for the content type "${contentTypeUid}" this composition is connected to.`,
3774
+ causes: [
3775
+ {
3776
+ cause: `No entry of "${contentTypeUid}" matches this composition.`,
3777
+ fix: "Create one, or point the composition at a content type that has entries.",
3778
+ },
3779
+ ...unpublishedCause(route.servedBy, config, "The entry"),
3780
+ ],
3781
+ context: buildStudioErrorContext(config, route),
3782
+ findings: { contentTypeUid, templateEntryUid },
3783
+ });
3784
+ }
3673
3785
  /** Why a composition uid found nothing. Never claims the composition does not exist. */
3674
3786
  function uidNotFoundCauses(servedBy, config) {
3675
3787
  return [
@@ -3690,14 +3802,22 @@ function templateContentTypeCauses(contentTypeUid, servedBy, config) {
3690
3802
  ...unpublishedCause(servedBy, config, "A composition that uses it"),
3691
3803
  ];
3692
3804
  }
3693
- async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale) {
3805
+ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale,
3806
+ /**
3807
+ * The template the render asked to prefer (`cs-preferred-composition-uid`);
3808
+ * undefined outside Studio, the Visual Editor and Live Preview.
3809
+ */
3810
+ preferredUid) {
3694
3811
  const topTier = ranking.matches;
3695
3812
  // Happy path — a single (or no) top-tier candidate needs no probe.
3696
3813
  if (topTier.length <= 1) {
3697
- return selectUrlWinner(topTier, new Map());
3814
+ return selectUrlWinner(topTier, new Map(), preferredUid);
3698
3815
  }
3699
- // Tie — probe each tied linked candidate's content type in parallel.
3816
+ // Tie — probe each tied linked candidate's content type in parallel. Templates
3817
+ // on one content type at one URL send the same query, so each distinct query
3818
+ // is sent once and its answer is shared.
3700
3819
  const linkedMatches = topTier.filter((m) => m.connected_content_type);
3820
+ const checksByKey = new Map();
3701
3821
  const probeOutcomes = await Promise.all(linkedMatches.map(async (m) => {
3702
3822
  const lightweight = candidatesByUid.get(m.composable_uid);
3703
3823
  // Legacy compositions persist no `url_metadata`. parseUrlMetadata maps an
@@ -3710,32 +3830,49 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
3710
3830
  if (!m.variables || !m.connected_content_type) {
3711
3831
  return { uid: m.composable_uid, owns: false, answered: true };
3712
3832
  }
3713
- try {
3714
- const probeQuery = resolveByUrlSource(requireStack(config), meta.url_source, { url: requestUrl }, m.variables, meta.url_queries, m.connected_content_type, {
3715
- references: [],
3716
- only: [["BASE", "uid"]],
3717
- locale: m.variables.metadata.locale || locale || config.locale,
3718
- branch: m.variables.metadata.branch,
3719
- // environment intentionally omitted — the ownership probe uses the
3720
- // connection (SDK-init) env, consistent with how the page is served
3721
- // (see ADR-0002 §Environment).
3722
- });
3723
- const res = await probeQuery.find();
3724
- return {
3725
- uid: m.composable_uid,
3726
- owns: entriesFromResponse(res).length > 0,
3727
- answered: true,
3728
- };
3729
- }
3730
- catch (probeError) {
3731
- // A failed probe counts as non-owning so the others still get their say.
3732
- // `answered` is what stops that being mistaken for evidence: a check we
3733
- // could not make says nothing, and if none of them could be made there is
3734
- // no absence to report.
3735
- if (isSetupFault(probeError))
3736
- throw probeError;
3737
- return { uid: m.composable_uid, owns: false, answered: false };
3833
+ const contentType = m.connected_content_type;
3834
+ const variables = m.variables;
3835
+ const probeLocale = variables.metadata.locale || locale || config.locale;
3836
+ const branch = variables.metadata.branch;
3837
+ const key = entryCheckKey({
3838
+ contentType,
3839
+ urlSource: meta.url_source,
3840
+ urlQueries: meta.url_queries,
3841
+ variables,
3842
+ locale: probeLocale,
3843
+ branch,
3844
+ });
3845
+ let check = checksByKey.get(key);
3846
+ if (!check) {
3847
+ check = (async () => {
3848
+ try {
3849
+ const probeQuery = resolveByUrlSource(requireStack(config), meta.url_source, { url: requestUrl }, variables, meta.url_queries, contentType, {
3850
+ references: [],
3851
+ only: [["BASE", "uid"]],
3852
+ locale: probeLocale,
3853
+ branch,
3854
+ // environment intentionally omitted — the ownership probe uses the
3855
+ // connection (SDK-init) env, consistent with how the page is served.
3856
+ });
3857
+ const res = await probeQuery.find();
3858
+ return {
3859
+ owns: entriesFromResponse(res).length > 0,
3860
+ answered: true,
3861
+ };
3862
+ }
3863
+ catch (probeError) {
3864
+ // A failed probe counts as non-owning so the others still get their say.
3865
+ // `answered` is what stops that being mistaken for evidence: a check we
3866
+ // could not make says nothing, and if none of them could be made there is
3867
+ // no absence to report.
3868
+ if (isSetupFault(probeError))
3869
+ throw probeError;
3870
+ return { owns: false, answered: false };
3871
+ }
3872
+ })();
3873
+ checksByKey.set(key, check);
3738
3874
  }
3875
+ return { uid: m.composable_uid, ...(await check) };
3739
3876
  }));
3740
3877
  // Every check failing is an outage, not an answer. Reporting "no candidate owns
3741
3878
  // this address" here would 404 a page that exists.
@@ -3750,15 +3887,14 @@ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, lo
3750
3887
  },
3751
3888
  ],
3752
3889
  context: buildStudioErrorContext(config),
3753
- findings: { url: requestUrl, probeCount: probeOutcomes.length },
3890
+ findings: { url: requestUrl, probeCount: checksByKey.size },
3754
3891
  });
3755
3892
  }
3756
3893
  const ownsByUid = new Map(probeOutcomes.map((r) => [r.uid, r.owns]));
3757
- return selectUrlWinner(topTier, ownsByUid);
3894
+ return selectUrlWinner(topTier, ownsByUid, preferredUid);
3758
3895
  }
3759
3896
  /**
3760
3897
  * This function fetches UI Composition from defined options.
3761
- * Supports custom fetcher overrides (per-query > global > SDK default).
3762
3898
  **/
3763
3899
  async function fetchComposition(config, queryOptions, compositionQueryOptions,
3764
3900
  /**
@@ -3767,29 +3903,50 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions,
3767
3903
  * candidate scan for URL resolution so Studio's diagnostics list every
3768
3904
  * considered candidate; the exact-match fast path is production-only.
3769
3905
  */
3770
- isInsideEditor = false) {
3771
- const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
3772
- const locale = resolvedOptions.locale;
3906
+ isInsideEditor = false,
3907
+ /**
3908
+ * The template the render asked to prefer (`cs-preferred-composition-uid`),
3909
+ * read only inside Studio or on a preview request. A URL fetch shows it
3910
+ * instead of production's pick when the two tie on one content type; see
3911
+ * `selectUrlWinner`.
3912
+ */
3913
+ preferredCompositionUid) {
3914
+ const locale = compositionQueryOptions?.locale;
3915
+ // What a refused request actually carried, so its diagnosis names it.
3916
+ const sentLocale = configuredLocale(config, locale);
3773
3917
  // Captured by the URL metadata (Phase A) path for Studio resolution
3774
3918
  // diagnostics — every candidate considered, with specificity.
3775
3919
  let urlResolution;
3776
- // Which service this request reached. Set inside `defaultImpl`, which is what
3777
- // makes it honest in all three cases: the ordinary path records the real
3778
- // route, a custom fetcher that delegates records it too, and one that never
3779
- // delegates leaves it "unknown" rather than reporting a route we did not take.
3780
- let servedBy = "unknown";
3781
- const defaultImpl = async () => {
3920
+ // Which service this request reached. Settled inside `queryComposition` once
3921
+ // the stack is known to be usable; "unknown" until then.
3922
+ let route = { servedBy: "unknown" };
3923
+ // Read `route` when called, not now: it is only settled inside `queryComposition`.
3924
+ const classifyRefusal = async (err) => {
3925
+ const facts = { ...route, locale: sentLocale };
3926
+ const { classifyResponseError } = await loadErrorClassifier();
3927
+ return classifyResponseError(err, config, facts);
3928
+ };
3929
+ const queryComposition = async () => {
3782
3930
  // Settle the connection before any branch below can start falling back over
3783
3931
  // it. Every path here needs the stack, so this raises nothing new — it moves
3784
- // the raise out of the fallbacks and in front of them. A caller's own
3785
- // fetcher sits deliberately upstream of this: it may not need our stack.
3932
+ // the raise out of the fallbacks and in front of them.
3786
3933
  requireStack(config);
3934
+ // Same for the content type every branch queries. Left to the branches, an
3935
+ // empty one throws inside the exact-match lookup, which falls back and then
3936
+ // reports the throw as a request that never completed.
3937
+ requireCompositionContentType(config);
3787
3938
  // Read synchronously, before anything awaits: live-preview state is
3788
3939
  // process-wide, so a later read can belong to a different request.
3789
- servedBy = resolveServedBy(config.stackSdk?.livePreviewConfig);
3940
+ route = captureRequestRoute(config.stackSdk);
3790
3941
  if ("composableUid" in queryOptions) {
3791
3942
  const stack = requireStack(config);
3792
3943
  const uiQuery = stack.where(stack.ctQuery(config.contentTypeUid, {
3944
+ // Inline the linked sections, as the url and content-type lookups
3945
+ // do. Without it they come back as bare references and
3946
+ // getAllSectionCompositions fetches them in a second, sequential
3947
+ // request before the page's data can be fetched.
3948
+ includeAll: true,
3949
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
3793
3950
  locale: locale || config.locale,
3794
3951
  }), "composable_uid", queryOptions.composableUid);
3795
3952
  return await uiQuery
@@ -3806,8 +3963,8 @@ isInsideEditor = false) {
3806
3963
  throw createStudioError({
3807
3964
  code: StudioErrorCode.COMPOSITION_UID_NOT_FOUND,
3808
3965
  headline: `No composition with the uid "${queryOptions.composableUid}" in content type "${config.contentTypeUid}".`,
3809
- causes: uidNotFoundCauses(servedBy, config),
3810
- context: buildStudioErrorContext(config, servedBy),
3966
+ causes: uidNotFoundCauses(route.servedBy, config),
3967
+ context: buildStudioErrorContext(config, route),
3811
3968
  findings: {
3812
3969
  compositionUid: queryOptions.composableUid,
3813
3970
  contentTypeUid: config.contentTypeUid,
@@ -3816,21 +3973,22 @@ isInsideEditor = false) {
3816
3973
  }
3817
3974
  return response;
3818
3975
  })
3819
- .catch((err) => {
3976
+ .catch(async (err) => {
3820
3977
  if (err instanceof ComposableStudioError)
3821
3978
  throw err;
3822
- const diagnosed = classifyResponseError(err, config, { servedBy });
3979
+ const diagnosed = await classifyRefusal(err);
3823
3980
  if (diagnosed)
3824
3981
  throw diagnosed;
3982
+ const { diagnoseUnreadableResponse } = await loadErrorClassifier();
3825
3983
  // The request failed. Absence is settled on the success path above,
3826
3984
  // so nothing here is evidence that the page is missing.
3827
3985
  // An unplaceable 141 reads as a missing page, and which missing page
3828
3986
  // it is depends on what was asked for.
3829
- throw diagnoseUnreadableResponse(err, config, { servedBy }, () => createStudioError({
3987
+ throw diagnoseUnreadableResponse(err, config, route, () => createStudioError({
3830
3988
  code: StudioErrorCode.COMPOSITION_UID_NOT_FOUND,
3831
3989
  headline: `No composition with the uid "${queryOptions.composableUid}" was found in content type "${config.contentTypeUid}".`,
3832
- causes: uidNotFoundCauses(servedBy, config),
3833
- context: buildStudioErrorContext(config, servedBy),
3990
+ causes: uidNotFoundCauses(route.servedBy, config),
3991
+ context: buildStudioErrorContext(config, route),
3834
3992
  findings: {
3835
3993
  compositionUid: queryOptions.composableUid,
3836
3994
  contentTypeUid: config.contentTypeUid,
@@ -3860,8 +4018,8 @@ isInsideEditor = false) {
3860
4018
  throw createStudioError({
3861
4019
  code: StudioErrorCode.NO_COMPOSITION_FOR_TEMPLATE_CONTENT_TYPE,
3862
4020
  headline: `No composition is connected to the content type "${queryOptions.templateContentTypeUid}".`,
3863
- causes: templateContentTypeCauses(queryOptions.templateContentTypeUid, servedBy, config),
3864
- context: buildStudioErrorContext(config, servedBy),
4021
+ causes: templateContentTypeCauses(queryOptions.templateContentTypeUid, route.servedBy, config),
4022
+ context: buildStudioErrorContext(config, route),
3865
4023
  findings: {
3866
4024
  templateContentTypeUid: queryOptions.templateContentTypeUid,
3867
4025
  },
@@ -3869,21 +4027,22 @@ isInsideEditor = false) {
3869
4027
  }
3870
4028
  return entry;
3871
4029
  })
3872
- .catch((err) => {
4030
+ .catch(async (err) => {
3873
4031
  if (err instanceof ComposableStudioError)
3874
4032
  throw err;
3875
- const diagnosed = classifyResponseError(err, config, { servedBy });
4033
+ const diagnosed = await classifyRefusal(err);
3876
4034
  if (diagnosed)
3877
4035
  throw diagnosed;
4036
+ const { diagnoseUnreadableResponse } = await loadErrorClassifier();
3878
4037
  // The request failed. Absence is settled on the success path above,
3879
4038
  // so nothing here is evidence that the page is missing.
3880
4039
  // An unplaceable 141 reads as a missing page, and which missing page
3881
4040
  // it is depends on what was asked for.
3882
- throw diagnoseUnreadableResponse(err, config, { servedBy }, () => createStudioError({
4041
+ throw diagnoseUnreadableResponse(err, config, route, () => createStudioError({
3883
4042
  code: StudioErrorCode.NO_COMPOSITION_FOR_TEMPLATE_CONTENT_TYPE,
3884
4043
  headline: `No composition in this project is connected to the content type "${queryOptions.templateContentTypeUid}".`,
3885
- causes: templateContentTypeCauses(queryOptions.templateContentTypeUid, servedBy, config),
3886
- context: buildStudioErrorContext(config, servedBy),
4044
+ causes: templateContentTypeCauses(queryOptions.templateContentTypeUid, route.servedBy, config),
4045
+ context: buildStudioErrorContext(config, route),
3887
4046
  findings: {
3888
4047
  templateContentTypeUid: queryOptions.templateContentTypeUid,
3889
4048
  },
@@ -3926,12 +4085,13 @@ isInsideEditor = false) {
3926
4085
  hit.composable_uid,
3927
4086
  hit,
3928
4087
  ]));
3929
- const { winnerUid } = await resolveUrlWinner(config, requestUrl, ranking, hitsByUid, locale);
3930
- const winner = winnerUid
3931
- ? exactHits.find((hit) => hit.composable_uid === winnerUid)
3932
- : undefined;
3933
- if (winner) {
3934
- return winner;
4088
+ // No edited template here: this path runs only outside editors.
4089
+ const { winner } = await resolveUrlWinner(config, requestUrl, ranking, hitsByUid, locale);
4090
+ const winnerHit = winner.kind === URL_WINNER_KIND.NONE
4091
+ ? undefined
4092
+ : exactHits.find((hit) => hit.composable_uid === winner.uid);
4093
+ if (winnerHit) {
4094
+ return winnerHit;
3935
4095
  }
3936
4096
  }
3937
4097
  }
@@ -3947,6 +4107,20 @@ isInsideEditor = false) {
3947
4107
  fastPathError.code) {
3948
4108
  throw fastPathError;
3949
4109
  }
4110
+ // A refusal we can name (a language, an environment, a key) is the
4111
+ // same conclusion: the scan would send the same request and fail
4112
+ // the same way.
4113
+ const diagnosed = await classifyRefusal(fastPathError);
4114
+ if (diagnosed)
4115
+ throw diagnosed;
4116
+ // Nothing answered. The scan asks the same host and would sit out
4117
+ // the same timeout, long enough for Studio's own timer to give up
4118
+ // on the page before any diagnosis arrives.
4119
+ const status = getStatusCode(fastPathError);
4120
+ if (status === 0 ||
4121
+ (status === undefined && isNetworkError(fastPathError))) {
4122
+ throw fastPathError;
4123
+ }
3950
4124
  if (process.env.NODE_ENV === "development") {
3951
4125
  console.warn("[Contentstack Studio] Exact-match URL lookup failed; falling back to the candidate scan:", fastPathError);
3952
4126
  }
@@ -3959,7 +4133,7 @@ isInsideEditor = false) {
3959
4133
  if (ranking.composableUids.length > 0) {
3960
4134
  const candidatesByUid = new Map(candidates.map((c) => [c.composable_uid, c]));
3961
4135
  // 3. Disambiguate top-tier ties by entry existence.
3962
- const { winnerUid, ownershipByUid } = await resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale);
4136
+ const { winner, ownershipByUid } = await resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale, preferredCompositionUid);
3963
4137
  // 4. Record every considered candidate (all tiers) + ownership for
3964
4138
  // Studio diagnostics, before committing to a winner.
3965
4139
  urlResolution = {
@@ -3967,14 +4141,15 @@ isInsideEditor = false) {
3967
4141
  ...d,
3968
4142
  connectedEntryResult: ownershipByUid.get(d.composable_uid) ?? "not-checked",
3969
4143
  })),
4144
+ winner,
3970
4145
  };
3971
- if (winnerUid) {
4146
+ if (winner.kind !== URL_WINNER_KIND.NONE) {
3972
4147
  // 5. Full-fetch the winning composition only.
3973
4148
  const fullQuery = requireStack(config).ctQuery(config.contentTypeUid, {
3974
4149
  includeAll: true,
3975
4150
  includeAllDepth: INCLUDE_DEPTH_COUNT,
3976
4151
  locale: locale || config.locale,
3977
- query: { composable_uid: winnerUid },
4152
+ query: { composable_uid: winner.uid },
3978
4153
  });
3979
4154
  const fullRes = await fullQuery.find();
3980
4155
  const fullEntries = entriesFromResponse(fullRes);
@@ -3997,7 +4172,7 @@ isInsideEditor = false) {
3997
4172
  fix: "Nothing here will fix it — report it, and we will raise the cap or narrow the search.",
3998
4173
  },
3999
4174
  ],
4000
- context: buildStudioErrorContext(config, servedBy),
4175
+ context: buildStudioErrorContext(config, route),
4001
4176
  findings: { url: requestUrl, consideredCount: candidates.length },
4002
4177
  });
4003
4178
  }
@@ -4011,34 +4186,35 @@ isInsideEditor = false) {
4011
4186
  throw createStudioError({
4012
4187
  code: StudioErrorCode.URL_MATCHED_NO_ENTRY,
4013
4188
  headline: `${considered.length} compositions match "${requestUrl}", and none of them has an entry for it.`,
4014
- causes: matchedNoEntryCauses(considered, servedBy, config),
4015
- context: buildStudioErrorContext(config, servedBy),
4189
+ causes: matchedNoEntryCauses(considered, route.servedBy, config),
4190
+ context: buildStudioErrorContext(config, route),
4016
4191
  findings: { url: requestUrl, considered },
4017
4192
  });
4018
4193
  }
4019
4194
  throw createStudioError({
4020
4195
  code: StudioErrorCode.NO_COMPOSITION_FOR_URL,
4021
4196
  headline: `No composition matches "${requestUrl}". Considered ${candidates.length} compositions.`,
4022
- causes: notFoundByUrlCauses(requestUrl, servedBy, config),
4023
- context: buildStudioErrorContext(config, servedBy),
4197
+ causes: notFoundByUrlCauses(requestUrl, route.servedBy, config),
4198
+ context: buildStudioErrorContext(config, route),
4024
4199
  findings: { url: requestUrl, consideredCount: candidates.length },
4025
4200
  });
4026
4201
  }
4027
4202
  catch (err) {
4028
4203
  if (err instanceof ComposableStudioError)
4029
4204
  throw err;
4030
- const diagnosed = classifyResponseError(err, config, { servedBy });
4205
+ const diagnosed = await classifyRefusal(err);
4031
4206
  if (diagnosed)
4032
4207
  throw diagnosed;
4208
+ const { diagnoseUnreadableResponse } = await loadErrorClassifier();
4033
4209
  // The request failed. Absence is settled on the success path above,
4034
4210
  // so nothing here is evidence that the page is missing.
4035
4211
  // An unplaceable 141 reads as a missing page, and which missing page
4036
4212
  // it is depends on what was asked for.
4037
- throw diagnoseUnreadableResponse(err, config, { servedBy }, () => createStudioError({
4213
+ throw diagnoseUnreadableResponse(err, config, route, () => createStudioError({
4038
4214
  code: StudioErrorCode.NO_COMPOSITION_FOR_URL,
4039
4215
  headline: `No composition is set up for the address ${requestUrl}.`,
4040
- causes: notFoundByUrlCauses(requestUrl, servedBy, config),
4041
- context: buildStudioErrorContext(config, servedBy),
4216
+ causes: notFoundByUrlCauses(requestUrl, route.servedBy, config),
4217
+ context: buildStudioErrorContext(config, route),
4042
4218
  findings: { url: requestUrl, consideredCount: 0 },
4043
4219
  }));
4044
4220
  }
@@ -4053,64 +4229,20 @@ isInsideEditor = false) {
4053
4229
  fix: "Pass one of compositionUid, url or templateContentTypeUid.",
4054
4230
  },
4055
4231
  ],
4056
- context: buildStudioErrorContext(config, servedBy),
4232
+ context: buildStudioErrorContext(config, route),
4057
4233
  findings: { lookedIn: "call" },
4058
4234
  });
4059
4235
  }
4060
4236
  };
4061
- const customFetcher = perQueryFetchComposition ?? config.fetchComposition;
4062
- if (customFetcher) {
4063
- const entry = await customFetcher({
4064
- compositionQuery: queryOptions,
4065
- contentTypeUid: config.contentTypeUid,
4066
- options: resolvedOptions,
4067
- stackSdk: config.stackSdk?.sdk,
4068
- defaultFetch: defaultImpl,
4069
- });
4070
- if (!entry) {
4071
- // A caller's own fetcher returned nothing. Which not-found this is
4072
- // depends on what was asked for, and the two take opposite advice: an
4073
- // address that matches nothing is a routing problem, a uid that matches
4074
- // nothing is a content one.
4075
- const servedByNow = resolveServedBy(config.stackSdk?.livePreviewConfig);
4076
- const notFoundContext = buildStudioErrorContext(config, servedByNow);
4077
- if ("url" in queryOptions) {
4078
- throw createStudioError({
4079
- code: StudioErrorCode.NO_COMPOSITION_FOR_URL,
4080
- headline: `No composition is set up for the address ${queryOptions.url}.`,
4081
- causes: notFoundByUrlCauses(queryOptions.url, servedByNow, config),
4082
- context: notFoundContext,
4083
- findings: { url: queryOptions.url, consideredCount: 0 },
4084
- });
4085
- }
4086
- throw createStudioError({
4087
- code: StudioErrorCode.COMPOSITION_UID_NOT_FOUND,
4088
- headline: `No composition with the uid "${"composableUid" in queryOptions ? queryOptions.composableUid : ""}" was returned.`,
4089
- causes: uidNotFoundCauses(servedByNow, config),
4090
- context: notFoundContext,
4091
- findings: {
4092
- compositionUid: "composableUid" in queryOptions ? queryOptions.composableUid : "",
4093
- contentTypeUid: config.contentTypeUid,
4094
- },
4095
- });
4096
- }
4097
- return {
4098
- compositionEntry: entry,
4099
- // Populated if the custom fetcher delegated to `defaultFetch` and it
4100
- // resolved via the URL metadata path; otherwise undefined.
4101
- urlResolution,
4102
- // Built here rather than at the surface, so it reports the route this
4103
- // fetch actually took. A caller's own fetcher leaves `servedBy` unknown.
4104
- requestContext: buildStudioErrorContext(config, servedBy),
4105
- };
4106
- }
4107
- const entry = await defaultImpl();
4237
+ const entry = await queryComposition();
4108
4238
  return {
4109
4239
  compositionEntry: entry,
4110
4240
  urlResolution,
4111
- requestContext: buildStudioErrorContext(config, servedBy),
4241
+ // Built here rather than at the surface, so it reports the route this
4242
+ // fetch actually took.
4243
+ requestContext: buildStudioErrorContext(config, route),
4112
4244
  };
4113
4245
  }
4114
4246
 
4115
- export { buildSectionScopedData, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, derivePlacementIncludePaths, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, parseUI, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue };
4247
+ export { buildSectionScopedData, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, collectSectionPlacementScopes, collectSlotChildScopes, composeSectionTemplatePrefix, derivePlacementIncludePaths, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, parseUI, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue, sanitizeUrlToken };
4116
4248
  //# sourceMappingURL=sdk.js.map