@contentstack/studio-client 1.6.0 → 1.7.1

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 (86) hide show
  1. package/dist/breakpoints/BreakpointManager.js +18 -5
  2. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  3. package/dist/canvas/canvas.utils.js +1 -1
  4. package/dist/canvas/canvas.utils.js.map +1 -1
  5. package/dist/composable-studio/build-scoped-data.js +170 -0
  6. package/dist/composable-studio/build-scoped-data.js.map +1 -0
  7. package/dist/composable-studio/collect-data-needs.js +344 -0
  8. package/dist/composable-studio/collect-data-needs.js.map +1 -0
  9. package/dist/composable-studio/composition-metadata.js +75 -0
  10. package/dist/composable-studio/composition-metadata.js.map +1 -0
  11. package/dist/composable-studio/composition-placement.types.js +7 -0
  12. package/dist/composable-studio/composition-placement.types.js.map +1 -0
  13. package/dist/composable-studio/sdk.js +2169 -192
  14. package/dist/composable-studio/sdk.js.map +1 -1
  15. package/dist/composable-studio/studio-intelligence.manager.js +2 -12
  16. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  17. package/dist/config/default-config.js +1 -0
  18. package/dist/config/default-config.js.map +1 -1
  19. package/dist/config/stack-sdk-wrapper.js +86 -0
  20. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  21. package/dist/context-menu/context-menu.js +1 -0
  22. package/dist/context-menu/context-menu.js.map +1 -1
  23. package/dist/dnd/dnd-manager.js +1 -0
  24. package/dist/dnd/dnd-manager.js.map +1 -1
  25. package/dist/highlight-node/highlight-node-manager.js +1 -0
  26. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  27. package/dist/highlight-node/highlight-node.js +5 -1
  28. package/dist/highlight-node/highlight-node.js.map +1 -1
  29. package/dist/index.d.ts +1033 -294
  30. package/dist/index.js +13 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/json-rte-registry/embedded-entry-conversion.js +186 -0
  33. package/dist/json-rte-registry/embedded-entry-conversion.js.map +1 -0
  34. package/dist/json-rte-registry/index.js +73 -33
  35. package/dist/json-rte-registry/index.js.map +1 -1
  36. package/dist/json-rte-registry/stack-sdk-store.js +10 -0
  37. package/dist/json-rte-registry/stack-sdk-store.js.map +1 -0
  38. package/dist/query/query-executor.js +182 -27
  39. package/dist/query/query-executor.js.map +1 -1
  40. package/dist/studio-internal/dist/utils/section-slot-walker.js +63 -0
  41. package/dist/studio-internal/dist/utils/section-slot-walker.js.map +1 -0
  42. package/dist/{packages/studio-internal → studio-internal}/dist/utils/spec-compression.js +1 -1
  43. package/dist/studio-internal/dist/utils/spec-compression.js.map +1 -0
  44. package/dist/url-metadata/build-template-query.js +124 -0
  45. package/dist/url-metadata/build-template-query.js.map +1 -0
  46. package/dist/url-metadata/parse-url-metadata.js +75 -0
  47. package/dist/url-metadata/parse-url-metadata.js.map +1 -0
  48. package/dist/url-metadata/rank-url-matches.js +100 -0
  49. package/dist/url-metadata/rank-url-matches.js.map +1 -0
  50. package/dist/url-metadata/select-url-winner.js +45 -0
  51. package/dist/url-metadata/select-url-winner.js.map +1 -0
  52. package/dist/url-metadata/shouldUseUrlMetadataPath.js +22 -0
  53. package/dist/url-metadata/shouldUseUrlMetadataPath.js.map +1 -0
  54. package/dist/url-metadata/types.js +50 -0
  55. package/dist/url-metadata/types.js.map +1 -0
  56. package/dist/url-metadata/url-pattern-matcher.js +311 -0
  57. package/dist/url-metadata/url-pattern-matcher.js.map +1 -0
  58. package/dist/utils/build-composition-fetch-query.js +19 -0
  59. package/dist/utils/build-composition-fetch-query.js.map +1 -0
  60. package/dist/utils/canvas.js +14 -0
  61. package/dist/utils/canvas.js.map +1 -1
  62. package/dist/utils/constants.js +19 -2
  63. package/dist/utils/constants.js.map +1 -1
  64. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js +11 -1
  65. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js.map +1 -1
  66. package/dist/utils/editor-mode.js +142 -0
  67. package/dist/utils/editor-mode.js.map +1 -0
  68. package/dist/utils/editor-utils.js +9 -0
  69. package/dist/utils/editor-utils.js.map +1 -1
  70. package/dist/utils/is-composition-being-edited.js.map +1 -1
  71. package/dist/utils/query-param.js +1 -1
  72. package/dist/utils/query-param.js.map +1 -1
  73. package/dist/utils/reference_fetcher.js +61 -6
  74. package/dist/utils/reference_fetcher.js.map +1 -1
  75. package/dist/utils/sdk.js +16 -1
  76. package/dist/utils/sdk.js.map +1 -1
  77. package/dist/utils/spec-analyzer.js +21 -4
  78. package/dist/utils/spec-analyzer.js.map +1 -1
  79. package/package.json +8 -10
  80. package/dist/get-composition-from-slug/get-composition-from-slug.js +0 -59
  81. package/dist/get-composition-from-slug/get-composition-from-slug.js.map +0 -1
  82. package/dist/node_modules/fflate/esm/browser.js +0 -384
  83. package/dist/node_modules/fflate/esm/browser.js.map +0 -1
  84. package/dist/packages/studio-internal/dist/utils/spec-compression.js.map +0 -1
  85. package/dist/utils/get-url-patterns.js +0 -40
  86. package/dist/utils/get-url-patterns.js.map +0 -1
@@ -1,28 +1,675 @@
1
1
  import { COMPOSABLE_STUDIO_QUERY_PARAM, composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
2
2
  import { INTERNAL_COMPONENTS_NAMES, DATA_SOURCES, getComponentRegistryInstance, DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
3
- import { pick } from 'lodash-es';
3
+ import { get, pick } from 'lodash-es';
4
4
  import { processUserConfig } from '../config/process-user-config.js';
5
- import { getCompositionFromSlug } from '../get-composition-from-slug/get-composition-from-slug.js';
5
+ import { setStackSdkInstance } from '../json-rte-registry/stack-sdk-store.js';
6
6
  import { SCHEMA_VERSION, SDK_VERSION, INCLUDE_DEPTH_COUNT } from '../utils/constants.js';
7
7
  import { isCompositionBeingEdited } from '../utils/is-composition-being-edited.js';
8
- import { setTemplateEntryInDS, entriesFromResponse, setStaticEntryInDS } from '../utils/sdk.js';
8
+ import { setTemplateEntryInDS, setStaticEntryInDS, entriesFromResponse, getBindingStringForCS } from '../utils/sdk.js';
9
+ import '../utils/editor-mode.js';
9
10
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
10
11
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
11
12
  import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
12
13
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
13
14
  import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
14
- import { getUrlPatterns } from '../utils/get-url-patterns.js';
15
+ import { getPageLinkedPlacementFilter } from '../utils/build-composition-fetch-query.js';
16
+ import { resolveByUrlSource } from '../url-metadata/build-template-query.js';
17
+ import { parseUrlMetadata } from '../url-metadata/parse-url-metadata.js';
18
+ import { rankUrlMatches } from '../url-metadata/rank-url-matches.js';
19
+ import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
20
+ import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
21
+ import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
15
22
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
16
- import { getEntriesQueries } from '../utils/reference_fetcher.js';
23
+ import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
24
+ import { collectAllDataNeeds, stableHashQuery, parseExternalDataForComponentProps } from './collect-data-needs.js';
25
+ import { buildScopedDataSources } from './build-scoped-data.js';
17
26
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
18
27
  import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
19
- import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
28
+ import { decompressSpec } from '../studio-internal/dist/utils/spec-compression.js';
20
29
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
21
30
 
22
31
  // ✅ HYBRID APPROACH: List of internal components that should always be available
23
32
  // These include both built-in components AND system components (like "page")
24
33
  // All are registered synchronously during React initialization via getBasicComponents()
25
34
  const INTERNAL_COMPONENT_TYPES = Object.values(INTERNAL_COMPONENTS_NAMES);
35
+ const SECTION_COMPOSITION_NODE_TYPE = "section-composition";
36
+ function findParentRepeaterUidInTree(ui, compositionUID) {
37
+ function traverse(node, nearestRepeaterUID) {
38
+ if (node.type === "section-composition" &&
39
+ node.metadata?.compositionUID === compositionUID) {
40
+ return nearestRepeaterUID;
41
+ }
42
+ const updatedRepeaterUID = node.type === "repeater" ? node.uid : nearestRepeaterUID;
43
+ for (const slotId of Object.keys(node.slots || {})) {
44
+ for (const child of node.slots[slotId] || []) {
45
+ const result = traverse(child, updatedRepeaterUID);
46
+ if (result !== undefined)
47
+ return result;
48
+ }
49
+ }
50
+ return undefined;
51
+ }
52
+ if (!ui)
53
+ return null;
54
+ const result = traverse(ui, null);
55
+ return result !== undefined ? result : null;
56
+ }
57
+ function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null) {
58
+ if (!dataSources["section_compositions"]) {
59
+ dataSources["section_compositions"] = {};
60
+ }
61
+ dataSources["section_compositions"][sectionUid] = {
62
+ selectedField,
63
+ uidRemapping: {},
64
+ parentRepeaterUID,
65
+ };
66
+ }
67
+ function findMatchingSectionSchema(section, templateEntry) {
68
+ const linkedSchemas = section.linked_schemas || [];
69
+ if (!linkedSchemas.length)
70
+ return null;
71
+ if (!templateEntry?._content_type_uid) {
72
+ return linkedSchemas[0] || null;
73
+ }
74
+ return (linkedSchemas.find((schema) => schema.content_type_uid === templateEntry._content_type_uid) || null);
75
+ }
76
+ function resolveSectionContext(section, templateEntry) {
77
+ const matchingSchema = findMatchingSectionSchema(section, templateEntry);
78
+ if (matchingSchema) {
79
+ return { selectedField: matchingSchema.selected_field };
80
+ }
81
+ if (!(section.linked_schemas || []).length) {
82
+ return { selectedField: undefined };
83
+ }
84
+ return null;
85
+ }
86
+ function getTemplateContentTypeForComposition(compositionEntry) {
87
+ if (compositionEntry.connected_content_type) {
88
+ return compositionEntry.connected_content_type;
89
+ }
90
+ if (compositionEntry.place_composition_as === "section" &&
91
+ compositionEntry.linked_schemas?.length) {
92
+ return compositionEntry.linked_schemas[0]?.content_type_uid || "";
93
+ }
94
+ return "";
95
+ }
96
+ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries) {
97
+ const templateEntry = data.dataSources?.[DATA_SOURCES.TEMPLATE];
98
+ if (!templateEntry || Array.isArray(templateEntry))
99
+ return;
100
+ if (compositionEntry.place_composition_as === "section") {
101
+ const ownContext = resolveSectionContext(compositionEntry, templateEntry);
102
+ if (ownContext) {
103
+ setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null);
104
+ }
105
+ }
106
+ const rootUI = compositionEntry.ui ?? null;
107
+ sectionEntries.forEach((sectionEntry) => {
108
+ const sectionContext = resolveSectionContext(sectionEntry, templateEntry);
109
+ if (!sectionContext)
110
+ return;
111
+ const parentRepeaterUID = findParentRepeaterUidInTree(rootUI, sectionEntry.uid);
112
+ setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID);
113
+ });
114
+ }
115
+ /**
116
+ * Walks the UI tree and visits every section-composition node,
117
+ * yielding (instanceUid, compositionUid) pairs for building
118
+ * per-instance scoped data source maps.
119
+ */
120
+ function walkUiForCompositionMapping(ui, visit) {
121
+ if (!ui)
122
+ return;
123
+ const node = ui;
124
+ if (node.type === SECTION_COMPOSITION_NODE_TYPE &&
125
+ node.metadata?.compositionUID &&
126
+ node.uid) {
127
+ visit(node.uid, node.metadata.compositionUID);
128
+ }
129
+ if (node.slots && typeof node.slots === "object") {
130
+ for (const slotNodes of Object.values(node.slots)) {
131
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
132
+ for (const c of arr)
133
+ walkUiForCompositionMapping(c, visit);
134
+ }
135
+ }
136
+ if (Array.isArray(node.children)) {
137
+ for (const c of node.children)
138
+ walkUiForCompositionMapping(c, visit);
139
+ }
140
+ }
141
+ function collectSectionCompositionUIDs(ui, accumulator = new Set()) {
142
+ if (!ui)
143
+ return accumulator;
144
+ if (ui.type === SECTION_COMPOSITION_NODE_TYPE &&
145
+ ui.metadata?.compositionUID) {
146
+ accumulator.add(ui.metadata.compositionUID);
147
+ }
148
+ if (ui.slots && typeof ui.slots === "object") {
149
+ Object.values(ui.slots).forEach((slotNodes) => {
150
+ if (Array.isArray(slotNodes)) {
151
+ slotNodes.forEach((child) => collectSectionCompositionUIDs(child, accumulator));
152
+ }
153
+ else if (slotNodes && typeof slotNodes === "object") {
154
+ collectSectionCompositionUIDs(slotNodes, accumulator);
155
+ }
156
+ });
157
+ }
158
+ if (Array.isArray(ui.children)) {
159
+ ui.children.forEach((child) => collectSectionCompositionUIDs(child, accumulator));
160
+ }
161
+ return accumulator;
162
+ }
163
+ /**
164
+ * Map of `section-slot` uid → its authored `defaultSection` uid for a section's
165
+ * UI (COMS-1659). Mirrors the studio-side helper; used to emit a virtual
166
+ * binding/instance for an empty slot's default so the default's data is fetched
167
+ * and scoped (otherwise an internal Repeater receives the bare object →
168
+ * "items.map is not a function").
169
+ */
170
+ function collectSlotDefaultUids(ui, out = {}) {
171
+ if (!ui || typeof ui !== "object")
172
+ return out;
173
+ const defaultUid = ui.metadata?.defaultSection?.uid;
174
+ if (ui.type === "section-slot" &&
175
+ typeof defaultUid === "string" &&
176
+ defaultUid &&
177
+ ui.uid) {
178
+ out[ui.uid] = defaultUid;
179
+ }
180
+ if (ui.slots && typeof ui.slots === "object") {
181
+ for (const slotNodes of Object.values(ui.slots)) {
182
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
183
+ for (const c of arr)
184
+ collectSlotDefaultUids(c, out);
185
+ }
186
+ }
187
+ if (Array.isArray(ui.children)) {
188
+ for (const c of ui.children)
189
+ collectSlotDefaultUids(c, out);
190
+ }
191
+ return out;
192
+ }
193
+ /**
194
+ * Strip a field path down to CDA include[]/only[]-safe segments: drop array
195
+ * indices (`x[0]` → `x`), modular-block numeric prefixes (`2_block` → `block`),
196
+ * pure-numeric segments, and the `entries` array wrapper. Shared by the
197
+ * instance walk (ancestor prefix composition) and the template-ref merge.
198
+ */
199
+ function sanitizeFieldPath(path) {
200
+ return path
201
+ .split(".")
202
+ .map((seg) => seg.replace(/\[\d+\]$/, "").replace(/^\d+_/, ""))
203
+ .filter((seg) => seg.length > 0 && !/^\d+$/.test(seg) && seg !== "entries");
204
+ }
205
+ /**
206
+ * Compose the page-template projection root for a placed section's reference
207
+ * field paths.
208
+ *
209
+ * Normally a section's references are rooted at its page-rooted prefix:
210
+ * `[...ancestorPrefix, ...selectedField]`. But when the section sits inside a
211
+ * page `Repeater(reference)+reference-ConditionBlock`, the enclosing reference
212
+ * is ALREADY in `ancestorPrefix`, and the section's own `selectedField`
213
+ * re-expresses that SAME reference with the target-CT uid tacked on as a
214
+ * discriminator (e.g. `reference.test_purpose`). That ctUid is NOT a data key,
215
+ * and re-appending the reference double-counts it — yielding an invalid CDA
216
+ * only[] key like `reference.reference.test_purpose.title` that the API
217
+ * silently ignores, so the referenced entry's fields (e.g. `title`) never come
218
+ * back and the section renders its component default on the deployed site.
219
+ *
220
+ * When `referenceCtUids` is non-empty (an enclosing reference ConditionBlock
221
+ * was seen), drop those ctUid segments and collapse the leading overlap with
222
+ * `ancestorPrefix`, so the section's fields root at the reference exactly like a
223
+ * page-DIRECT binding does (`only[reference][]=title`). When it is empty, every
224
+ * other shape (wrapper chains, cross-CT ref-target binds) keeps the original
225
+ * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
226
+ */
227
+ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
228
+ const dropCtUids = new Set(referenceCtUids);
229
+ const sf = sanitizeFieldPath(selectedField).filter((seg) => !dropCtUids.has(seg));
230
+ // Collapse the leading overlap with `ancestorPrefix`. A section whose
231
+ // `selected_field` is rooted at the PAGE content type re-declares the
232
+ // ancestor's path FROM THE PAGE ROOT — e.g. nested passthrough sections each
233
+ // bound to `modular_blocks.ref_block`, or a section inside a page
234
+ // Repeater(reference)+reference-CB whose field re-expresses the enclosing
235
+ // `reference`. Its sanitized field then STARTS WITH `ancestorPrefix`;
236
+ // concatenating blindly double-counts those segments and yields an invalid CDA
237
+ // include[]/only[] (`modular_blocks.modular_blocks.ref_block…`) that the API
238
+ // silently drops, so the reference never resolves and the section renders its
239
+ // component default on the deployed site. A true relative wrapper chain
240
+ // (ancestor `related_articles` + field `author`) does NOT overlap and extends
241
+ // normally.
242
+ const remainder = ancestorPrefix.length > 0 &&
243
+ sf.length >= ancestorPrefix.length &&
244
+ ancestorPrefix.every((seg, i) => seg === sf[i])
245
+ ? sf.slice(ancestorPrefix.length)
246
+ : sf;
247
+ return [...ancestorPrefix, ...remainder];
248
+ }
249
+ /**
250
+ * Extend an accumulated ancestor prefix by a nested section's `selected_field`,
251
+ * collapsing the leading overlap for page-root-absolute fields (same rationale
252
+ * as `composeSectionTemplatePrefix`). Used while walking the page UI so a chain
253
+ * of nested passthrough sections that each re-declare an overlapping ct-rooted
254
+ * `selected_field` does not accumulate duplicated segments.
255
+ */
256
+ function extendAncestorPrefix(ancestorPrefix, selectedField) {
257
+ const sf = sanitizeFieldPath(selectedField);
258
+ const overlaps = ancestorPrefix.length > 0 &&
259
+ sf.length >= ancestorPrefix.length &&
260
+ ancestorPrefix.every((seg, i) => seg === sf[i]);
261
+ return overlaps ? [...sf] : [...ancestorPrefix, ...sf];
262
+ }
263
+ /**
264
+ * Walk a section composition's authored UI and map every internal repeater's
265
+ * uid to its PAGE-ROOTED schema field path (starting from `prefix`, the
266
+ * section's composed reference prefix). A modular-block ConditionBlock
267
+ * contributes its block-uid segment; a reference ConditionBlock's target-CT
268
+ * uid is NOT a schema segment and is skipped. Used so a page-authored binding
269
+ * that references a section-internal repeater (forwarded through a passthrough
270
+ * slot) can resolve the correct reference subtree for its only[]/include[]
271
+ * projection instead of rooting at the page BASE.
272
+ */
273
+ function mapSectionRepeaterPaths(node, runningPath, map) {
274
+ if (!node || typeof node !== "object")
275
+ return;
276
+ let childPath = runningPath;
277
+ if (node.type === "condition-block") {
278
+ const cond = node.metadata?.condition;
279
+ if (cond?.type === "modular_block" && typeof cond.value === "string") {
280
+ childPath = [...runningPath, cond.value];
281
+ }
282
+ }
283
+ if (node.type === "repeater") {
284
+ const binding = node.props?.items?.binding;
285
+ if (binding) {
286
+ childPath = [
287
+ ...runningPath,
288
+ ...sanitizeFieldPath(getBindingStringForCS(binding)),
289
+ ];
290
+ if (node.uid)
291
+ map.set(node.uid, childPath);
292
+ }
293
+ }
294
+ if (node.slots && typeof node.slots === "object") {
295
+ for (const slotNodes of Object.values(node.slots)) {
296
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
297
+ for (const c of arr)
298
+ mapSectionRepeaterPaths(c, childPath, map);
299
+ }
300
+ }
301
+ if (Array.isArray(node.children)) {
302
+ for (const c of node.children)
303
+ mapSectionRepeaterPaths(c, childPath, map);
304
+ }
305
+ }
306
+ /**
307
+ * Walk the PAGE UI and, for every node whose binding is a REPEATER binding
308
+ * referencing a repeater already in `map` (a section-internal repeater, or a
309
+ * page repeater resolved earlier in this same walk), project the binding's
310
+ * field path onto only[] keys rooted at the referenced repeater's page-rooted
311
+ * path — and register the node's own resolved path so its descendants chain
312
+ * correctly.
313
+ *
314
+ * Fixes the deployed-render gap where a page-authored Repeater/Text bound to a
315
+ * section-internal reference repeater (e.g. an `mg` group on the referenced CT,
316
+ * forwarded through a passthrough slot) had its only[] projected at the page
317
+ * BASE (`only[BASE][]=mg`). The referenced entry then came back without that
318
+ * field and the binding rendered blank standalone. `getEntriesQueries` can't
319
+ * see the section-internal repeater's reference path, so it is composed here.
320
+ */
321
+ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
322
+ if (!node || typeof node !== "object")
323
+ return;
324
+ const project = (binding, ownUid, isRepeater) => {
325
+ if (!binding || binding.type !== DATA_SOURCES.REPEATER)
326
+ return;
327
+ const parentPath = map.get(binding.value?.repeaterUID);
328
+ if (!parentPath)
329
+ return;
330
+ const segs = sanitizeFieldPath(getBindingStringForCS(binding));
331
+ const acc = [...parentPath];
332
+ for (const seg of segs) {
333
+ onlyOut.push([acc.join("."), seg]);
334
+ acc.push(seg);
335
+ }
336
+ // Register this node's own resolved path so nested bindings that reference
337
+ // it (e.g. a Text inside this Repeater) root under the composed path.
338
+ if (isRepeater && ownUid)
339
+ map.set(ownUid, acc);
340
+ };
341
+ if (node.type === "repeater") {
342
+ project(node.props?.items?.binding, node.uid, true);
343
+ }
344
+ // Component field bindings (Text, etc.) live on individual props.
345
+ const props = node.props;
346
+ if (props && typeof props === "object") {
347
+ for (const key of Object.keys(props)) {
348
+ const b = props[key]?.binding;
349
+ if (b && key !== "items")
350
+ project(b);
351
+ }
352
+ }
353
+ if (node.slots && typeof node.slots === "object") {
354
+ for (const slotNodes of Object.values(node.slots)) {
355
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
356
+ for (const c of arr)
357
+ projectCrossBoundaryRepeaterBindings(c, map, onlyOut);
358
+ }
359
+ }
360
+ if (Array.isArray(node.children)) {
361
+ for (const c of node.children)
362
+ projectCrossBoundaryRepeaterBindings(c, map, onlyOut);
363
+ }
364
+ }
365
+ /**
366
+ * Resolve a section-composition node's effective `selectedField`. Resolution
367
+ * order MUST match the render side (`collect-data-needs`'s declaredField) so
368
+ * the fetch scopes the section against the SAME field the renderer reads:
369
+ * 1. per-instance override on `metadata.sectionBindingOverride`,
370
+ * 2. legacy `metadata.selectedField`,
371
+ * 3. linked_schemas default — the field declared for the page CT, else the
372
+ * first schema's `selected_field`.
373
+ *
374
+ * A repeater-nested section is NOT forced to scope-root: its declared
375
+ * `selected_field` still applies and scopes each iteration item further (e.g. a
376
+ * reference-chain section bound to ct2's `reference_to_ct3` iterates that
377
+ * referenced array per ct2 item). The render side never forced "" here, so
378
+ * forcing it on the fetch side starved exactly those sections of their nested
379
+ * reference data (the internal Repeater then received the bare iteration object
380
+ * instead of the array → "items.map is not a function").
381
+ */
382
+ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
383
+ const override = node.metadata?.sectionBindingOverride;
384
+ let selectedField = typeof override?.selectedField === "string"
385
+ ? override.selectedField
386
+ : node.metadata?.selectedField;
387
+ if (selectedField == null) {
388
+ const linked = (sectionsByUid.get(node.metadata?.compositionUID)
389
+ ?.linked_schemas || []);
390
+ selectedField =
391
+ linked.find((s) => s.content_type_uid === pageContentTypeUid)
392
+ ?.selected_field ??
393
+ linked[0]?.selected_field ??
394
+ "";
395
+ }
396
+ return selectedField || "";
397
+ }
398
+ /**
399
+ * Walks the page UI tree and resolves every section-composition instance's
400
+ * effective binding (selectedField + uidRemapping) AND its page-rooted
401
+ * `ancestorPrefix` — the composed reference path of the wrapper sections it is
402
+ * nested inside. The template fetch roots each section's references at
403
+ * `[...ancestorPrefix, ...selectedField]` so nested wrapper chains fetch the
404
+ * full reference depth (W1.selectedField → W2.selectedField → …).
405
+ */
406
+ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
407
+ const out = [];
408
+ const walk = (node, parentRepeaterUID, ancestorPrefix,
409
+ // Binding field path of the nearest enclosing TEMPLATE-bound Repeater that
410
+ // hasn't yet been confirmed as a reference. A Repeater's template binding
411
+ // alone can't be told apart from a plain array; the reference condition-
412
+ // block dropped inside it is the signal (mirrors `reference_fetcher`, which
413
+ // only records a repeater ref path at the reference condition-block). When
414
+ // we reach that block we commit this path into the prefix so a section
415
+ // nested in the repeater roots its references under the reference field.
416
+ enclosingRepeaterRefField,
417
+ // Target-CT uids from the enclosing reference ConditionBlock(s) on the path
418
+ // to this node (see SectionInstanceBinding.referenceCtUids).
419
+ refCtUids,
420
+ // compositionUIDs already expanded as slot defaults on THIS path (COMS-1659
421
+ // cycle guard) — a circular default chain (A→B→A) would otherwise recurse
422
+ // forever here; expanding a default already on the path is cut.
423
+ defaultAncestors = new Set()) => {
424
+ if (!node || typeof node !== "object")
425
+ return;
426
+ const nextRepeater = node.type === "repeater" && node.uid ? node.uid : parentRepeaterUID;
427
+ // Children that descend into THIS node's slots inherit `ancestorPrefix`,
428
+ // extended by this node's reference path when it is a wrapper section.
429
+ let childPrefix = ancestorPrefix;
430
+ let childRepeaterRefField = enclosingRepeaterRefField;
431
+ let childRefCtUids = refCtUids;
432
+ // Remember a Repeater's template binding path; it becomes a reference hop
433
+ // only once a reference condition-block downstream confirms the field is a
434
+ // reference (committed below). A CONTENTSTACK/REPEATER-typed binding is not
435
+ // a page-template reference path, so it never extends the prefix.
436
+ if (node.type === "repeater") {
437
+ const itemsBinding = node.props?.items?.binding;
438
+ childRepeaterRefField =
439
+ itemsBinding?.type === DATA_SOURCES.TEMPLATE
440
+ ? getBindingStringForCS(itemsBinding) || null
441
+ : null;
442
+ }
443
+ // A reference condition-block confirms the enclosing repeater iterates a
444
+ // reference field. Commit that field into the prefix so slotted sections
445
+ // (selectedField "") fetch/project their fields under e.g.
446
+ // `reference_to_ct2`, not the page root. Clear it afterwards so a deeper
447
+ // structure doesn't double-count the same hop.
448
+ if (node.type === "condition-block" &&
449
+ node.metadata?.condition?.type === "reference" &&
450
+ enclosingRepeaterRefField) {
451
+ childPrefix = [
452
+ ...ancestorPrefix,
453
+ ...getSchemaPath(enclosingRepeaterRefField),
454
+ ];
455
+ childRepeaterRefField = null;
456
+ // Record the narrowed target CT so a slotted section can drop this uid
457
+ // from its own selectedField when rooting field projections.
458
+ const cbCtUid = node.metadata?.condition?.value;
459
+ if (typeof cbCtUid === "string" && cbCtUid) {
460
+ childRefCtUids = [...refCtUids, cbCtUid];
461
+ }
462
+ }
463
+ if (node.type === SECTION_COMPOSITION_NODE_TYPE &&
464
+ node.metadata?.compositionUID &&
465
+ node.uid) {
466
+ const compositionUid = node.metadata.compositionUID;
467
+ const selectedField = resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid);
468
+ const override = node.metadata?.sectionBindingOverride;
469
+ const uidRemapping = override?.uidRemapping ?? node.metadata.uidRemapping ?? {};
470
+ out.push({
471
+ instanceUid: node.uid,
472
+ compositionUid,
473
+ selectedField,
474
+ uidRemapping,
475
+ parentRepeaterUID,
476
+ ancestorPrefix,
477
+ referenceCtUids: refCtUids,
478
+ });
479
+ // A whole-CT wrapper (selectedField "") adds no segment — correct, it
480
+ // creates no reference hop. A reference-bound wrapper extends the prefix
481
+ // so its slot children's references resolve from that reference. Collapse
482
+ // the leading overlap so a chain of nested passthrough sections that each
483
+ // re-declare an overlapping page-root-absolute selected_field (e.g.
484
+ // `modular_blocks` → `modular_blocks.ref_block` → `modular_blocks.ref_block`)
485
+ // does not double-count segments into an invalid include[] path.
486
+ childPrefix = extendAncestorPrefix(ancestorPrefix, selectedField);
487
+ // Empty slots fall back to their authored default section (COMS-1659).
488
+ // The default isn't a real child in the page UI, so synthesize the same
489
+ // node the renderer makes and walk it here — otherwise the default's data
490
+ // (e.g. an internal Repeater's array) is never fetched/scoped.
491
+ const sectionUi = sectionsByUid.get(compositionUid)?.ui;
492
+ const slotDefaults = sectionUi ? collectSlotDefaultUids(sectionUi) : {};
493
+ const placementSlots = (node.slots || {});
494
+ // This section's compositionUID joins the default-expansion path; a
495
+ // default whose uid is already on the path closes a cycle — skip it.
496
+ const chain = new Set(defaultAncestors).add(compositionUid);
497
+ for (const [slotUid, defaultUid] of Object.entries(slotDefaults)) {
498
+ const filled = Array.isArray(placementSlots[slotUid])
499
+ ? placementSlots[slotUid]
500
+ : [];
501
+ if (filled.length > 0)
502
+ continue; // placement filled it → no default
503
+ if (chain.has(defaultUid))
504
+ continue; // circular default chain → cut
505
+ const synth = {
506
+ type: SECTION_COMPOSITION_NODE_TYPE,
507
+ // Prefix with the enclosing placement instance uid to match the render-
508
+ // side synth uid (`${instanceUid}-${slotUid}-default-${defaultUid}`); a
509
+ // slot-uid-only key diverges from the render lookup and starves the
510
+ // default's data scoping. COMS-1659 / 4a.
511
+ uid: `${node.uid ? `${node.uid}-` : ""}${slotUid}-default-${defaultUid}`,
512
+ metadata: { compositionUID: defaultUid },
513
+ slots: {},
514
+ };
515
+ walk(synth, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, chain);
516
+ }
517
+ }
518
+ if (node.slots && typeof node.slots === "object") {
519
+ for (const slotNodes of Object.values(node.slots)) {
520
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
521
+ for (const c of arr)
522
+ walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
523
+ }
524
+ }
525
+ if (Array.isArray(node.children)) {
526
+ // children (non-slot) stay in the same scope as this node.
527
+ for (const c of node.children)
528
+ walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
529
+ }
530
+ };
531
+ walk(ui, null, [], null, []);
532
+ return out;
533
+ }
534
+ async function fetchSectionCompositionEntries(config, sectionUids, options) {
535
+ if (!config.stackSdk || sectionUids.length === 0) {
536
+ return [];
537
+ }
538
+ const response = await config.stackSdk
539
+ .ctQuery(config.contentTypeUid, {
540
+ includeAll: true,
541
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
542
+ locale: options?.locale || config.locale,
543
+ })
544
+ .containedIn("uid", sectionUids)
545
+ .find();
546
+ return entriesFromResponse(response).map((entry) => ({
547
+ ...entry,
548
+ ui: typeof entry.ui === "string"
549
+ ? decompressSpec(entry.ui)
550
+ : entry.ui,
551
+ }));
552
+ }
553
+ /**
554
+ * The section uids a composition/section directly references: its native
555
+ * `linked_sections` (which, since COMS-1659, also carries each slot's default
556
+ * section) unioned with any `section-composition` nodes embedded in its `ui`.
557
+ * One depth level of the nested-section graph.
558
+ */
559
+ /**
560
+ * Adds FULL section entries inlined on `entry.linked_sections` (resolved by
561
+ * `includeAll` depth) into `map`, RECURSIVELY — an inline section's own inline
562
+ * linked_sections are absorbed too. So when CDA resolves a chain A→B→C→D inline
563
+ * within the include depth, one fetch captures the whole chain and the depth-K
564
+ * loop issues no further calls. Bare uid-only references (deeper than the
565
+ * include depth, or unpublished) are left for the loop to fetch. Returns the
566
+ * uids newly added so the caller can follow their references.
567
+ */
568
+ function harvestInlineLinkedSections(entry, map) {
569
+ const added = [];
570
+ const linked = entry.linked_sections;
571
+ if (!Array.isArray(linked))
572
+ return added;
573
+ for (const candidate of linked) {
574
+ if (candidate &&
575
+ typeof candidate === "object" &&
576
+ "ui" in candidate &&
577
+ "uid" in candidate) {
578
+ const e = candidate;
579
+ if (map.has(e.uid))
580
+ continue;
581
+ const ui = typeof e.ui === "string"
582
+ ? decompressSpec(e.ui)
583
+ : e.ui;
584
+ map.set(e.uid, { ...e, ui });
585
+ added.push(e.uid);
586
+ added.push(...harvestInlineLinkedSections(e, map)); // recurse into inline chain
587
+ }
588
+ }
589
+ return added;
590
+ }
591
+ function referencedSectionUidsOf(entry) {
592
+ const uids = new Set();
593
+ const linked = entry.linked_sections;
594
+ if (Array.isArray(linked)) {
595
+ for (const l of linked) {
596
+ const uid = l?.uid;
597
+ if (typeof uid === "string" && uid)
598
+ uids.add(uid);
599
+ }
600
+ }
601
+ const ui = typeof entry.ui === "string"
602
+ ? decompressSpec(entry.ui)
603
+ : entry.ui;
604
+ if (ui)
605
+ for (const u of collectSectionCompositionUIDs(ui))
606
+ uids.add(u);
607
+ return Array.from(uids);
608
+ }
609
+ async function getAllSectionCompositions(config, compositionEntry, options) {
610
+ const map = new Map();
611
+ // 1. Pull inline linked_sections from the initial composition response —
612
+ // recursively, so a fully inline-resolved chain is captured up front.
613
+ harvestInlineLinkedSections(compositionEntry, map);
614
+ // 2. Resolve the full nested-section graph with a depth-K batched fetch
615
+ // (COMS-1659). Each round fetches an entire level in one `containedIn`
616
+ // call, then follows the just-fetched sections' references (incl. slot
617
+ // defaults via `linked_sections`) to the next level. A page-global `map`
618
+ // dedups shared/diamond sections; `requested` prevents refetching a uid
619
+ // that returned nothing (deleted section) or closing a cycle. Rounds =
620
+ // nesting depth, not section count; breadth at a level is one call.
621
+ const ui = typeof compositionEntry.ui === "string"
622
+ ? decompressSpec(compositionEntry.ui)
623
+ : compositionEntry.ui;
624
+ const requested = new Set();
625
+ // Seed the frontier from the page UI + the page's linked_sections, plus the
626
+ // refs of any inline-seeded sections (so their children get discovered).
627
+ let frontier = new Set([
628
+ ...collectSectionCompositionUIDs(ui),
629
+ ...referencedSectionUidsOf(compositionEntry),
630
+ ]);
631
+ for (const seeded of map.values()) {
632
+ for (const ref of referencedSectionUidsOf(seeded))
633
+ frontier.add(ref);
634
+ }
635
+ while (true) {
636
+ const toFetch = Array.from(frontier).filter((uid) => uid && !map.has(uid) && !requested.has(uid));
637
+ if (toFetch.length === 0)
638
+ break;
639
+ toFetch.forEach((uid) => requested.add(uid));
640
+ let fetched = [];
641
+ try {
642
+ fetched = await fetchSectionCompositionEntries(config, toFetch, options);
643
+ }
644
+ catch (err) {
645
+ if (process.env.NODE_ENV === "development") {
646
+ console.error("getAllSectionCompositions: level fetch failed", toFetch, err);
647
+ }
648
+ break;
649
+ }
650
+ frontier = new Set();
651
+ for (const s of fetched) {
652
+ if (!map.has(s.uid))
653
+ map.set(s.uid, s);
654
+ // Absorb any sections CDA resolved inline on this one (recursively), so
655
+ // an inline-resolved chain within the include depth needs no more calls.
656
+ const harvested = harvestInlineLinkedSections(s, map);
657
+ // Follow references of this section AND everything harvested from it;
658
+ // anything already in `map` (inline-resolved) is skipped, so only the
659
+ // truly-missing next level is queued.
660
+ for (const uid of [s.uid, ...harvested]) {
661
+ const known = map.get(uid);
662
+ if (!known)
663
+ continue;
664
+ for (const ref of referencedSectionUidsOf(known)) {
665
+ if (!map.has(ref) && !requested.has(ref))
666
+ frontier.add(ref);
667
+ }
668
+ }
669
+ }
670
+ }
671
+ return map;
672
+ }
26
673
  function getAuthErrorMessage(err) {
27
674
  const detail = err?.error_message ||
28
675
  err?.errors?.api_key?.[0] ||
@@ -31,6 +678,310 @@ function getAuthErrorMessage(err) {
31
678
  getErrorMessage(ErrorMessageKey.INVALID_CREDENTIALS_DEFAULT);
32
679
  return getErrorMessage(ErrorMessageKey.AUTHENTICATION_ERROR, { detail });
33
680
  }
681
+ /**
682
+ * SEO bindings are stored in the UI metadata with the same nested `value.path`
683
+ * shape used by the normal data-binding system:
684
+ *
685
+ * { type: "template", value: { path: { title: {} } } }
686
+ *
687
+ * For SEO we only need the final property path as a dot-separated string
688
+ * (`title`, `seo.title`, etc.), so this helper converts the nested path object
689
+ * into a plain path string that can be used with `lodash/get`.
690
+ */
691
+ /**
692
+ * SEO bindings are stored in UI metadata with the nested `value.path` shape
693
+ * used by the rest of the data-binding system:
694
+ *
695
+ * { type: "template", value: { path: { title: {} } } }
696
+ * { type: "template", value: { path: { seo: { title: {} } } } }
697
+ *
698
+ * The path is always a SINGLE-KEY chain at each level — bindings target one
699
+ * leaf field, not multiple siblings. If a multi-key object is encountered
700
+ * (shouldn't happen given how Studio writes these), we warn in dev and pick
701
+ * the first key so SEO doesn't silently break, but the upstream caller should
702
+ * be fixed.
703
+ *
704
+ * Returns a dot-separated path (`"title"`, `"seo.title"`) usable with
705
+ * `lodash/get`, or `""` when the binding has no path.
706
+ */
707
+ function flattenBindingPathFromValue(binding) {
708
+ const path = binding.value
709
+ ?.path;
710
+ if (!path || typeof path !== "object")
711
+ return "";
712
+ const flattenPath = (value) => {
713
+ if (!value)
714
+ return "";
715
+ const keys = Object.keys(value);
716
+ if (keys.length === 0)
717
+ return "";
718
+ if (keys.length > 1 && process.env.NODE_ENV === "development") {
719
+ console.warn(`[studio-sdk] SEO binding path has multiple keys at one level (${keys.join(", ")}); using "${keys[0]}". Studio is expected to write single-key chains.`);
720
+ }
721
+ const key = keys[0];
722
+ const next = value[key];
723
+ const suffix = next && typeof next === "object"
724
+ ? flattenPath(next)
725
+ : "";
726
+ return suffix ? `${key}.${suffix}` : key;
727
+ };
728
+ return flattenPath(path);
729
+ }
730
+ function isTemplateBinding(binding) {
731
+ return binding.type === DATA_SOURCES.TEMPLATE || binding.type === "template";
732
+ }
733
+ /**
734
+ * Resolve a single SEO field value (`pageTitle`, `pageDescription`,
735
+ * `openGraphImage`, `metaProps[].value`) from either:
736
+ *
737
+ * 1. the static value saved on the composition, or
738
+ * 2. the currently resolved template entry data in `spec.data`
739
+ *
740
+ * Branches:
741
+ * - No binding → keep saved static value.
742
+ * - `static_value` binding → use binding literal (fall back to static).
743
+ * - `template` binding → read template entry at the flattened path.
744
+ * - Otherwise → fall back to static.
745
+ *
746
+ * Returns the resolved primitive as a string. Non-primitive resolved values
747
+ * (which shouldn't happen for SEO fields) fall back to the static value
748
+ * rather than coercing an object to "[object Object]".
749
+ */
750
+ function resolveSeoBindingValue(staticValue, binding, specData) {
751
+ const fallback = (staticValue ?? "").trim();
752
+ if (!binding || typeof binding !== "object" || binding.type == null) {
753
+ return fallback;
754
+ }
755
+ if (binding.type === "static_value" ||
756
+ binding.type === DATA_SOURCES.STATIC_VALUE) {
757
+ return typeof binding.value === "string" && binding.value.trim()
758
+ ? binding.value.trim()
759
+ : fallback;
760
+ }
761
+ if (!specData || !isTemplateBinding(binding)) {
762
+ return fallback;
763
+ }
764
+ const templateEntry = specData.dataSources?.[DATA_SOURCES.TEMPLATE];
765
+ const subPath = flattenBindingPathFromValue(binding);
766
+ if (!templateEntry || !subPath) {
767
+ return fallback;
768
+ }
769
+ const resolved = get(templateEntry, subPath);
770
+ // SEO fields are expected to resolve to a primitive. Anything else (an
771
+ // object, a missing path, an empty string) falls back to the static value
772
+ // so consumers always see a string.
773
+ if (resolved === undefined ||
774
+ resolved === null ||
775
+ resolved === "" ||
776
+ typeof resolved === "object") {
777
+ return fallback;
778
+ }
779
+ return String(resolved);
780
+ }
781
+ /**
782
+ * Pure SEO resolver. Merges the composition's saved SEO metadata
783
+ * (`ui.metadata.seo`) with resolved values from `specData` (bound title /
784
+ * description / OG image / meta props read from the template entry). Shared by
785
+ * the SDK's `getSeoMetadata` and exposed for BYO-data callers who resolve SEO
786
+ * against data they supply themselves — see `resolveSeoMetadata` in
787
+ * `@contentstack/studio-react`.
788
+ */
789
+ function getSeoMetadataPure(ui, specData) {
790
+ const seo = ui.metadata.seo;
791
+ if (!seo)
792
+ return null;
793
+ return {
794
+ ...seo,
795
+ pageTitle: resolveSeoBindingValue(seo.pageTitle, seo.pageTitleBinding, specData),
796
+ pageDescription: resolveSeoBindingValue(seo.pageDescription, seo.pageDescriptionBinding, specData),
797
+ openGraphImage: resolveSeoBindingValue(seo.openGraphImage, seo.openGraphImageBinding, specData),
798
+ metaProps: (seo.metaProps || []).map((prop) => {
799
+ const resolved = resolveSeoBindingValue(prop.value, prop.binding, specData);
800
+ // Both `value` and `previewValue` reflect the resolved value when the
801
+ // meta prop is bound, so canvas/SSR consumers stay in sync.
802
+ return { ...prop, value: resolved, previewValue: resolved };
803
+ }),
804
+ };
805
+ }
806
+ /**
807
+ * Pure per-instance section scoping. Given a composition's `pageUi` + its
808
+ * section composition entries + an ALREADY-RESOLVED `dataSources` pool, derive
809
+ * the `section_scoped_data` map (per section-instance uid). No network.
810
+ *
811
+ * Reused in two places:
812
+ * 1. `fetchData` — after the CDA fetch has populated `data.dataSources`.
813
+ * 2. BYO-data rendering (`StudioComposition`) — the caller supplies
814
+ * `dataSources`; embedded sections scope without any refetch.
815
+ *
816
+ * Returns `{}` when there are no section compositions (e.g. a standalone
817
+ * section rendered as the root reads `dataSources.template` directly).
818
+ */
819
+ function buildSectionScopedData(compositionEntry, pageUi, sectionEntries, dataSources) {
820
+ if (!sectionEntries.length)
821
+ return {};
822
+ // Convert the sectionEntries array to a Map<compositionUid, entry> for collectAllDataNeeds.
823
+ const sectionEntriesMap = new Map(sectionEntries.map((sec) => [sec.uid, sec]));
824
+ const { needsBySection } = collectAllDataNeeds(compositionEntry, pageUi, sectionEntriesMap);
825
+ // Build per-section-composition maps of (entryUid -> poolKey) and
826
+ // (queryUid -> stableHash) by re-parsing each section's data_sources.
827
+ // Pool key format matches what setStaticEntryInDS uses: `${ct_uid}:${entry_uid}`.
828
+ const compEntryDsToPoolKey = new Map();
829
+ const compQueryDsToPoolKey = new Map();
830
+ for (const sec of sectionEntries) {
831
+ const entryMap = new Map();
832
+ const queryMap = new Map();
833
+ try {
834
+ const parsed = JSON.parse(sec.data_sources ?? "[]");
835
+ const list = Array.isArray(parsed)
836
+ ? parsed
837
+ : Object.values(parsed);
838
+ for (const ds of list) {
839
+ if (ds?.uid === "contentstack") {
840
+ // Support both { data: { entries: [...] } } and legacy { data: [...] } formats.
841
+ const rawEntries = Array.isArray(ds.data?.entries)
842
+ ? ds.data.entries
843
+ : Array.isArray(ds.data)
844
+ ? ds.data
845
+ : [];
846
+ for (const e of rawEntries) {
847
+ const ct = e.content_type_uid ?? e._content_type_uid;
848
+ if (ct && e.uid)
849
+ entryMap.set(e.uid, `${ct}:${e.uid}`);
850
+ }
851
+ }
852
+ if (ds?.uid === "queries" ||
853
+ ds?.uid === DATA_SOURCES.QUERY ||
854
+ ds?.id === DATA_SOURCES.QUERY) {
855
+ const items = Array.isArray(ds.data)
856
+ ? ds.data
857
+ : (ds.data?.queries ?? []);
858
+ for (const q of items) {
859
+ if (q?.uid && q?.spec)
860
+ queryMap.set(q.uid, stableHashQuery(q.spec));
861
+ }
862
+ }
863
+ }
864
+ }
865
+ catch {
866
+ // malformed JSON — skip; already logged in collectAllDataNeeds
867
+ }
868
+ compEntryDsToPoolKey.set(sec.uid, entryMap);
869
+ compQueryDsToPoolKey.set(sec.uid, queryMap);
870
+ }
871
+ // Per-section-composition map of preprocessed `static_value` (key -> value).
872
+ const compStaticValue = new Map();
873
+ for (const sec of sectionEntries) {
874
+ compStaticValue.set(sec.uid, preProcessStaticValues(sec.static_value || {}));
875
+ }
876
+ // Build per-instance pool-key maps from per-section-composition maps.
877
+ const instanceEntryDs = new Map();
878
+ const instanceQueryDs = new Map();
879
+ const instanceStaticValue = new Map();
880
+ walkUiForCompositionMapping(pageUi, (instanceUid, compositionUid) => {
881
+ const e = compEntryDsToPoolKey.get(compositionUid);
882
+ const q = compQueryDsToPoolKey.get(compositionUid);
883
+ const sv = compStaticValue.get(compositionUid);
884
+ if (e)
885
+ instanceEntryDs.set(instanceUid, e);
886
+ if (q)
887
+ instanceQueryDs.set(instanceUid, q);
888
+ if (sv)
889
+ instanceStaticValue.set(instanceUid, sv);
890
+ });
891
+ // dataSources.contentstack is already keyed by pool key (`${ct_uid}:${uid}`).
892
+ const csEntries = dataSources?.contentstack ?? {};
893
+ const entriesByKey = new Map(Object.entries(csEntries));
894
+ // Build queriesByKey (hash -> result) by combining page + section query uid->hash maps.
895
+ const queriesByKey = new Map();
896
+ const csQueries = dataSources?.contentstack_queries ?? {};
897
+ const recordQueryFromDsMap = (dsMap) => {
898
+ for (const [dsUid, poolKey] of dsMap.entries()) {
899
+ const q = csQueries[dsUid];
900
+ if (q !== undefined)
901
+ queriesByKey.set(poolKey, q);
902
+ }
903
+ };
904
+ // Page's own queries:
905
+ try {
906
+ const parsed = JSON.parse(compositionEntry.data_sources ?? "[]");
907
+ const list = Array.isArray(parsed) ? parsed : Object.values(parsed);
908
+ const pageQueryMap = new Map();
909
+ for (const ds of list) {
910
+ if (ds?.uid === "queries" ||
911
+ ds?.uid === DATA_SOURCES.QUERY ||
912
+ ds?.id === DATA_SOURCES.QUERY) {
913
+ const items = Array.isArray(ds.data)
914
+ ? ds.data
915
+ : (ds.data?.queries ?? []);
916
+ for (const q of items) {
917
+ if (q?.uid && q?.spec)
918
+ pageQueryMap.set(q.uid, stableHashQuery(q.spec));
919
+ }
920
+ }
921
+ }
922
+ recordQueryFromDsMap(pageQueryMap);
923
+ }
924
+ catch {
925
+ // ignore — page data_sources already parsed earlier
926
+ }
927
+ for (const [, dsMap] of instanceQueryDs.entries())
928
+ recordQueryFromDsMap(dsMap);
929
+ return buildScopedDataSources({
930
+ entriesByKey,
931
+ queriesByKey,
932
+ sectionEntryDsToPoolKey: instanceEntryDs,
933
+ sectionQueryDsToPoolKey: instanceQueryDs,
934
+ sectionStaticValueByInstance: instanceStaticValue,
935
+ }, needsBySection, dataSources);
936
+ }
937
+ /**
938
+ * Client-only lazy component loading + missing-component validation for a
939
+ * fetched `ui`. Extracted so the spec-only `fetchCompositionSpecOnly` path can
940
+ * reuse the same registry checks `fetchSpec` performs (built-in vs custom
941
+ * component errors, then `loadComponents`).
942
+ */
943
+ async function ensureUiComponentsLoaded(ui, sectionEntries) {
944
+ const componentRegistry = getComponentRegistryInstance();
945
+ const usedComponents = analyzeUsedComponents(ui);
946
+ const sectionComponentTypes = new Set(sectionEntries.keys());
947
+ const missingBuiltInComponents = [];
948
+ const missingCustomComponents = [];
949
+ usedComponents.forEach((type) => {
950
+ if (sectionComponentTypes.has(type))
951
+ return;
952
+ if (!componentRegistry.hasComponentLoader(type)) {
953
+ if (INTERNAL_COMPONENT_TYPES.includes(type)) {
954
+ missingBuiltInComponents.push(type);
955
+ }
956
+ else {
957
+ missingCustomComponents.push(type);
958
+ }
959
+ }
960
+ });
961
+ if (missingBuiltInComponents.length > 0) {
962
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, [
963
+ `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
964
+ "",
965
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
966
+ "Fix: make sure the package root is imported at least once before fetch:",
967
+ ' import "@contentstack/studio-react";',
968
+ ].join("\n"));
969
+ }
970
+ if (missingCustomComponents.length > 0) {
971
+ throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, [
972
+ `[Composable Studio SDK] Custom components not registered: ${missingCustomComponents.join(", ")}`,
973
+ "",
974
+ "Ensure all registerComponent() calls complete before fetching the composition.",
975
+ ].join("\n"));
976
+ }
977
+ try {
978
+ await componentRegistry.loadComponents(Array.from(usedComponents));
979
+ }
980
+ catch (error) {
981
+ console.error("Error loading components lazily:", error);
982
+ throw error;
983
+ }
984
+ }
34
985
  /**
35
986
  * Helper function to detect and classify API errors
36
987
  * @internal - Exported for testing purposes
@@ -357,9 +1308,12 @@ function sendInitStudioSignal(config) {
357
1308
  sdkFramework: "react",
358
1309
  timestamp: Date.now(),
359
1310
  globalLocale: config.locale,
360
- globalVariantAlias: undefined, // Config doesn't have variantAlias - handled per query
1311
+ globalVariantAlias: config.variantAlias,
361
1312
  requestedUrl: window.location.href,
362
1313
  uid: `sdk-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1314
+ configPassedToTheSdk: {
1315
+ contentTypeUid: config.contentTypeUid,
1316
+ },
363
1317
  };
364
1318
  // Send via Advanced Post Message using static imports
365
1319
  composableStudioEventManager
@@ -374,22 +1328,168 @@ function sendInitStudioSignal(config) {
374
1328
  }
375
1329
  function generateSdk(userConfig) {
376
1330
  const config = processUserConfig(userConfig);
377
- // ✅ HYBRID APPROACH: Register internal components immediately during SDK init
378
- // This ensures all internal components (page, section, text, etc.) are available
379
- // ✅ HYBRID APPROACH: Component registration moved to React layer (useStudioInit)
380
- // This avoids cyclic dependencies while ensuring components are available before fetchSpec
381
1331
  if (clientRendererModeUtil.isInsideStudioFrame()) {
382
- const hash = new URLSearchParams(window.location.search).get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
1332
+ const sp = new URLSearchParams(window.location.search);
1333
+ const hash = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
383
1334
  config.stackSdk.livePreviewQuery?.(hash);
1335
+ // Studio is the source of truth for locale/variant when the SDK runs
1336
+ // inside its iframe. Overriding the user-supplied config values here
1337
+ // means every SDK-side fetch (initial spec, linked-entry references,
1338
+ // section fetches) automatically uses the right locale/variant, and
1339
+ // both INIT_STUDIO.globalLocale/globalVariantAlias and the per-query
1340
+ // GET_COMPOSITION_SPEC payload round-trip them back to Studio.
1341
+ const urlLocale = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE);
1342
+ if (urlLocale) {
1343
+ config.locale = urlLocale;
1344
+ }
1345
+ const urlVariantAlias = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS);
1346
+ if (urlVariantAlias) {
1347
+ config.variantAlias = urlVariantAlias;
1348
+ }
384
1349
  }
1350
+ if (config.stackSdk)
1351
+ setStackSdkInstance(config.stackSdk);
1352
+ /**
1353
+ * The variant alias every SDK-side data fetch should use, in priority order:
1354
+ * 1. The `cs-variant-alias` URL param when running inside Studio — Studio
1355
+ * (and the Visual Builder navbar behind it) is the source of truth for the
1356
+ * variant being previewed.
1357
+ * 2. The per-fetch `options.variantAlias` (host-supplied, e.g. a Personalize
1358
+ * alias passed to `fetchSpec`).
1359
+ * 3. `config.variantAlias` — the SDK-level default. Inside Studio the init
1360
+ * block above already copies `cs-variant-alias` into it, so this also acts
1361
+ * as the no-search-param fallback.
1362
+ *
1363
+ * Centralized because the stack-sdk-wrapper applies a variant ONLY from the
1364
+ * per-query option — unlike locale, it has no `config.variantAlias` fallback.
1365
+ * So the resolved value must be handed to every fetch explicitly (template
1366
+ * entry, bound contentstack entries, and dynamic queries); otherwise a
1367
+ * Studio-selected variant renders on the page entry but silently skips all
1368
+ * secondary data. Mirrors `resolveLocale`'s studio-search-param-first order.
1369
+ */
1370
+ /**
1371
+ * The search params for the CURRENT fetch. In CSR the SDK fetches in the browser, so
1372
+ * they come from `window.location.search`; in SSR the fetch runs server-side where
1373
+ * `window` is blind, so the caller threads the forwarded request query string as
1374
+ * `searchParams`. Request-scoped — never reads shared mutable state, so concurrent SSR
1375
+ * requests cannot clobber one another.
1376
+ */
1377
+ const getRequestSearchParams = (searchParams) => searchParams ??
1378
+ (typeof window !== "undefined"
1379
+ ? new URLSearchParams(window.location.search)
1380
+ : undefined);
1381
+ /**
1382
+ * Whether this fetch is rendering the Studio editor preview — the `cs-composable-studio`
1383
+ * flag is on the iframe URL. Replaces the `window`-only `isInsideStudioFrame()` in the
1384
+ * fetch path so SSR (server-side, `window`-blind) is detected via the forwarded params.
1385
+ */
1386
+ const isInStudio = (searchParams) => getRequestSearchParams(searchParams)?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ?? false;
1387
+ /**
1388
+ * Whether this fetch renders inside an editor (Studio OR Visual Builder). Editor fetches
1389
+ * widen the query (all fields, no `only` projection). VB is browser-only so it still
1390
+ * comes from the global mode util; Studio is searchParams-aware (so it works in SSR).
1391
+ */
1392
+ const isEditorFetch = (searchParams) => isInStudio(searchParams) ||
1393
+ clientRendererModeUtil.isInsideVisualBuilderFrame();
1394
+ /**
1395
+ * Read a Studio iframe-URL param (locale, variant, template-entry) for the current
1396
+ * fetch — the author's live editor choices. Returns undefined outside the editor.
1397
+ */
1398
+ const readStudioParam = (param, searchParams) => {
1399
+ const params = getRequestSearchParams(searchParams);
1400
+ if (!params?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED))
1401
+ return undefined;
1402
+ return params.get(param) || undefined;
1403
+ };
1404
+ const resolveEffectiveVariantAlias = (optionVariantAlias, searchParams) => {
1405
+ const studioVariant = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS, searchParams);
1406
+ return studioVariant || optionVariantAlias || config.variantAlias;
1407
+ };
1408
+ /**
1409
+ * The locale every SDK-side data fetch should use, in priority order:
1410
+ * 1. The `cs-locale` URL param when running inside Studio — Studio is the
1411
+ * source of truth for the previewed locale.
1412
+ * 2. A URL-pattern `{{locale}}` capture (only known after URL matching, so
1413
+ * callers pass it in as `patternLocale`).
1414
+ * 3. The per-fetch `options.locale` (`optionLocale`).
1415
+ * 4. `config.locale` — the SDK-level default (also overridden with `cs-locale`
1416
+ * inside Studio by the init block above).
1417
+ * 5. `config.stackSdk.locale` — the underlying delivery stack's own configured
1418
+ * locale (its `_locale`/`Stack({ locale })`). Makes the stack-locale floor
1419
+ * *explicit* rather than relying on the delivery SDK's implicit auto-apply
1420
+ * (the TS SDK auto-applies it; the legacy JS SDK applies none) — so behavior
1421
+ * is deterministic across SDK flavors. When all tiers are empty the locale is
1422
+ * omitted and the CMS returns its master copy (with `include_fallback`).
1423
+ *
1424
+ * Mirrors resolveEffectiveVariantAlias. Centralized so the template entry, bound
1425
+ * contentstack entries, and dynamic queries all resolve locale identically —
1426
+ * previously only the template entry saw the URL-pattern locale; the secondary
1427
+ * fetches dropped it.
1428
+ */
1429
+ const resolveLocale = (patternLocale, optionLocale, searchParams) => {
1430
+ const studioLocale = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE, searchParams);
1431
+ return (studioLocale ||
1432
+ patternLocale ||
1433
+ optionLocale ||
1434
+ config.locale ||
1435
+ config.stackSdk?.locale);
1436
+ };
1437
+ /**
1438
+ * Resolve the URL-pattern locale for a composition ONCE per fetch, and return
1439
+ * the `matchResult` so fetchTemplateEntry can reuse it instead of re-matching.
1440
+ *
1441
+ * The locale is captured by matching the requested URL against the
1442
+ * composition's `url_metadata` pattern (a `{{locale}}` placeholder). Hoisting
1443
+ * it here lets fetchData hand the captured locale to the bound-entry and
1444
+ * dynamic-query fetches too — previously only the template entry saw it. Locale
1445
+ * is safe to vary per URL because Contentstack fallback always terminates at
1446
+ * master, so an unpublished locale yields the master copy (never empty/stale).
1447
+ *
1448
+ * Environment is deliberately NOT resolved here. Unlike locale it has no
1449
+ * fallback, so a per-URL environment that diverges from where the composition
1450
+ * is published would serve a split/stale snapshot. Environment is the
1451
+ * connection (SDK-init) environment, applied uniformly to composition AND data
1452
+ * — see ADR-0002 §Environment.
1453
+ *
1454
+ * Returns no locale for the templateEntryUid path, the direct
1455
+ * content_type_url_pattern source, and legacy compositions (no `{{...}}`
1456
+ * captures there).
1457
+ */
1458
+ const resolveUrlPatternContext = (compositionEntry, compositionQuery, connectedContentType) => {
1459
+ const empty = {
1460
+ matchResult: undefined,
1461
+ patternLocale: undefined,
1462
+ };
1463
+ const parsedMetadata = compositionEntry.url_metadata
1464
+ ? parseUrlMetadata(compositionEntry.url_metadata)
1465
+ : null;
1466
+ const url = "url" in compositionQuery ? compositionQuery.url : undefined;
1467
+ if (!parsedMetadata ||
1468
+ !url ||
1469
+ !compositionEntry.url ||
1470
+ parsedMetadata.url_source ===
1471
+ COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
1472
+ return empty;
1473
+ }
1474
+ const matchResult = matchCompositionUrl(url, compositionEntry.url, compositionEntry.composable_uid, {
1475
+ includeReferences: parsedMetadata.url_queries?.include,
1476
+ connected_content_type: connectedContentType,
1477
+ });
1478
+ return {
1479
+ matchResult,
1480
+ patternLocale: matchResult.matched
1481
+ ? matchResult.variables?.metadata?.locale
1482
+ : undefined,
1483
+ };
1484
+ };
385
1485
  isSdkInitDebugEnabled();
386
1486
  // REMOVED: sendSDKInitializedSignal - replaced by INIT_STUDIO via Advanced Post Message
387
1487
  // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
388
1488
  // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
389
1489
  // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
390
- async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
1490
+ async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}, searchParams) {
391
1491
  const { variantAlias, locale } = options;
392
- const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
1492
+ const isInsideEditor = isEditorFetch(searchParams);
393
1493
  try {
394
1494
  const promises = [];
395
1495
  for (const _content_type_uid in staticBindingQueries) {
@@ -397,8 +1497,8 @@ function generateSdk(userConfig) {
397
1497
  for (const entry_uid in staticBindingQueries[_content_type_uid]) {
398
1498
  const references = staticBindingQueries[_content_type_uid][entry_uid];
399
1499
  let onlyQuery = [];
400
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
401
- if (!isInsideVB) {
1500
+ // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1501
+ if (!isInsideEditor) {
402
1502
  onlyQuery =
403
1503
  staticBindingOnlyQueries[_content_type_uid][entry_uid] || [];
404
1504
  // We need locale for redirect to the correct locale.
@@ -456,7 +1556,7 @@ function generateSdk(userConfig) {
456
1556
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
457
1557
  * Supports custom fetcher overrides (per-query > global > SDK default).
458
1558
  */
459
- async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
1559
+ async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions, urlPatternContext, searchParams) {
460
1560
  if (!config.stackSdk) {
461
1561
  return;
462
1562
  }
@@ -468,11 +1568,147 @@ function generateSdk(userConfig) {
468
1568
  // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
469
1569
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
470
1570
  const _studioIntelligence = enhancedOptions?._studioIntelligence;
471
- const _enhancementMode = enhancedOptions?._enhancementMode;
472
1571
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
473
- const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
474
- const isStudioAware = _enhancementMode === "studio-aware";
1572
+ // searchParams-aware so the all-fields projection (the `only`-suppression gates below)
1573
+ // fires for an SSR editor fetch, where the window-based util would report false.
1574
+ const isInsideStudio = isInStudio(searchParams);
1575
+ // Studio override: when running inside Studio and the iframe URL carries
1576
+ // `cs-template-entry-uid`, prefer it over any host-passed `templateEntryUid`.
1577
+ // This lets the user pick a preview entry from Studio's navbar that
1578
+ // overrides a host-hardcoded UID, while leaving the host's behaviour intact
1579
+ // in production (the param is only honored when isInsideStudio).
1580
+ //
1581
+ const studioOverride = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.TEMPLATE_ENTRY_UID, searchParams);
1582
+ if (studioOverride) {
1583
+ resolvedOptions.templateEntryUid = studioOverride;
1584
+ }
1585
+ // Locale/variant resolution is shared across all SDK fetches — see
1586
+ // resolveEffectiveVariantAlias (studio `cs-variant-alias` > per-fetch option > config).
1587
+ const resolveVariant = () => resolveEffectiveVariantAlias(resolvedOptions.variantAlias, searchParams);
475
1588
  const defaultImpl = async () => {
1589
+ // Resolution priority: templateEntryUid > url_metadata path > legacy path
1590
+ if (resolvedOptions.templateEntryUid) {
1591
+ // Enhanced include queries with Studio Intelligence
1592
+ const allIncludeQueries = [
1593
+ ...includeQueries,
1594
+ ...(_studioIntelligence?.includeReferences || []),
1595
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
1596
+ const queryOptions = {
1597
+ references: allIncludeQueries,
1598
+ variantAlias: resolveVariant(),
1599
+ // No URL pattern in this branch — pattern locale is N/A.
1600
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
1601
+ };
1602
+ // Smart 'only' parameter handling - only apply in production
1603
+ if (!isInsideVB && !isInsideStudio) {
1604
+ queryOptions.only = onlyQueries;
1605
+ }
1606
+ let dataQuery = config.stackSdk
1607
+ .ctQuery(connected_content_type, queryOptions)
1608
+ .limit(1);
1609
+ dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
1610
+ const response = await dataQuery.find().catch((err) => {
1611
+ const { errorType, message } = classifyApiError(err);
1612
+ const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
1613
+ ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1614
+ : errorType;
1615
+ throw new ComposableStudioError(finalErrorType, finalErrorType ===
1616
+ ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1617
+ ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
1618
+ : message, {
1619
+ options: fetchOptions,
1620
+ response: err,
1621
+ statusCode: err?.status || err?.statusCode,
1622
+ errorCode: err?.error_code,
1623
+ });
1624
+ });
1625
+ const entries = entriesFromResponse(response);
1626
+ if (!entries?.[0]) {
1627
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1628
+ contentType: connected_content_type,
1629
+ }), {
1630
+ contentType: connected_content_type,
1631
+ hasStackSdk: !!config.stackSdk,
1632
+ compositionQuery,
1633
+ options: fetchOptions,
1634
+ troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
1635
+ });
1636
+ }
1637
+ return entries[0];
1638
+ }
1639
+ // Check if we should use url_metadata path
1640
+ const parsedMetadata = compositionEntry.url_metadata
1641
+ ? parseUrlMetadata(compositionEntry.url_metadata)
1642
+ : null;
1643
+ if (parsedMetadata && "url" in compositionQuery && compositionQuery.url) {
1644
+ // Metadata path: resolve using url_queries + extracted variables
1645
+ try {
1646
+ // Enhanced include queries with Studio Intelligence
1647
+ const allIncludeQueries = [
1648
+ ...includeQueries,
1649
+ ...(_studioIntelligence?.includeReferences || []),
1650
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
1651
+ // Smart 'only' parameter handling for onlyQueries
1652
+ const finalOnlyQueries = !isInsideVB && !isInsideStudio ? onlyQueries : undefined;
1653
+ if (parsedMetadata.url_source ===
1654
+ COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
1655
+ // content_type_url_pattern: Direct URL match (no pattern variables).
1656
+ let directQuery = config.stackSdk
1657
+ .ctQuery(connected_content_type, {
1658
+ references: allIncludeQueries,
1659
+ variantAlias: resolveVariant(),
1660
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
1661
+ only: finalOnlyQueries,
1662
+ })
1663
+ .limit(1);
1664
+ directQuery = config.stackSdk.where(directQuery, "url", compositionQuery.url);
1665
+ const response = await directQuery.find();
1666
+ const entries = entriesFromResponse(response);
1667
+ if (entries?.[0]) {
1668
+ return entries[0];
1669
+ }
1670
+ }
1671
+ else {
1672
+ // Other sources: Use template matching + extracted variables
1673
+ if (!compositionEntry.url) {
1674
+ throw new Error("Composition entry missing URL pattern for template matching");
1675
+ }
1676
+ // Match the composition URL pattern to extract variables. Reuse the
1677
+ // match fetchData already computed for the whole page
1678
+ // (resolveUrlPatternContext) when provided — same inputs, so this is
1679
+ // a true resolve-once rather than a second identical match.
1680
+ const matchResult = urlPatternContext?.matchResult ??
1681
+ matchCompositionUrl(compositionQuery.url, compositionEntry.url, compositionEntry.composable_uid, {
1682
+ includeReferences: parsedMetadata.url_queries?.include,
1683
+ connected_content_type,
1684
+ });
1685
+ if (matchResult.matched && matchResult.variables) {
1686
+ const patternMetadata = matchResult.variables.metadata;
1687
+ // Build query using extracted variables and metadata
1688
+ const templateQuery = resolveByUrlSource(config.stackSdk, parsedMetadata.url_source, compositionQuery, matchResult.variables, parsedMetadata.url_queries, connected_content_type, {
1689
+ references: allIncludeQueries,
1690
+ variantAlias: resolveVariant(),
1691
+ locale: resolveLocale(patternMetadata.locale, resolvedOptions.locale, searchParams),
1692
+ branch: patternMetadata.branch,
1693
+ // environment intentionally omitted: it is the connection
1694
+ // (SDK-init) env, uniform across composition + data. Per-URL
1695
+ // {{environment}} has no fallback and would split the snapshot
1696
+ // (see ADR-0002 §Environment).
1697
+ only: finalOnlyQueries,
1698
+ });
1699
+ const response = await templateQuery.find();
1700
+ const entries = entriesFromResponse(response);
1701
+ if (entries?.[0]) {
1702
+ return entries[0];
1703
+ }
1704
+ }
1705
+ }
1706
+ }
1707
+ catch (metadataError) {
1708
+ console.warn("Metadata template resolution failed, falling back to legacy:", metadataError);
1709
+ }
1710
+ }
1711
+ // Legacy path: Original implementation
476
1712
  // Enhanced include queries with Studio Intelligence
477
1713
  const allIncludeQueries = [
478
1714
  ...includeQueries,
@@ -480,23 +1716,21 @@ function generateSdk(userConfig) {
480
1716
  ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
481
1717
  const queryOptions = {
482
1718
  references: allIncludeQueries,
483
- variantAlias: resolvedOptions.variantAlias,
484
- locale: resolvedOptions.locale || config.locale,
1719
+ variantAlias: resolveVariant(),
1720
+ // No URL pattern in this branch — pattern locale is N/A. Forward
1721
+ // searchParams so the SSR editor's cs-locale is honored here too
1722
+ // (window is blind on the server); matches every sibling branch.
1723
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
485
1724
  };
486
- // Smart 'only' parameter handling - ignore in Visual Builder OR Studio-aware mode
487
- if (!isInsideVB && !(isInsideStudio && isStudioAware)) {
1725
+ // Smart 'only' parameter handling - only apply in production
1726
+ if (!isInsideVB && !isInsideStudio) {
488
1727
  queryOptions.only = onlyQueries;
489
1728
  }
490
- // When Studio-aware: Skip 'only' to fetch all fields for data binding
491
1729
  let dataQuery = config.stackSdk
492
1730
  .ctQuery(connected_content_type, queryOptions)
493
1731
  .limit(1);
494
- // Resolution priority: templateEntryUid > url > first entry (original logic)
495
- if (resolvedOptions.templateEntryUid) {
496
- console.log("📌 SDK using templateEntryUid:", resolvedOptions.templateEntryUid);
497
- dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
498
- }
499
- else if ("url" in compositionQuery && compositionQuery.url) {
1732
+ // Legacy URL matching (note: this is likely incorrect for patterned URLs as mentioned in plan)
1733
+ if ("url" in compositionQuery && compositionQuery.url) {
500
1734
  dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
501
1735
  }
502
1736
  const response = await dataQuery.find().catch((err) => {
@@ -515,19 +1749,6 @@ function generateSdk(userConfig) {
515
1749
  });
516
1750
  });
517
1751
  const entries = entriesFromResponse(response);
518
- console.log("📥 SDK Template Entry Query Response:", {
519
- totalEntries: entries?.length || 0,
520
- firstEntry: entries?.[0]
521
- ? {
522
- uid: entries[0].uid,
523
- title: entries[0].title,
524
- url: entries[0].url,
525
- }
526
- : null,
527
- allEntryTitles: entries?.map((e) => e.title) || [],
528
- connectedContentType: connected_content_type,
529
- queryUrl: "url" in compositionQuery ? compositionQuery.url : "no-url",
530
- });
531
1752
  if (!entries?.[0]) {
532
1753
  throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
533
1754
  contentType: connected_content_type,
@@ -550,7 +1771,7 @@ function generateSdk(userConfig) {
550
1771
  connectedContentType: connected_content_type,
551
1772
  options: resolvedOptions,
552
1773
  includeReferences: includeQueries,
553
- only: isInsideVB ? [] : onlyQueries,
1774
+ only: isInsideStudio || isInsideVB ? [] : onlyQueries,
554
1775
  stackSdk: config.stackSdk.sdk,
555
1776
  defaultFetch: defaultImpl,
556
1777
  });
@@ -576,33 +1797,396 @@ function generateSdk(userConfig) {
576
1797
  if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
577
1798
  return;
578
1799
  }
579
- async function fetchData(compositionEntry, queryOptions, options) {
1800
+ async function fetchData(compositionEntry, queryOptions, options, sectionEntries = [], searchParams) {
580
1801
  const { variantAlias, locale } = options || {};
581
- const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, compositionEntry.connected_content_type || "", options);
1802
+ // Read all saved reference include paths from compositionEntry.data_sources.resolvedReferences.
1803
+ // Covers toggle ON paths, directly-bound field paths, and condition block binding paths.
1804
+ // Works in both embedded and standalone modes — compositionEntry is always present.
1805
+ // Restores what the April 9 refactor removed (generateQueryDetails referencePaths) but safely:
1806
+ // resolvedReferences contains only validated reference paths, never inferred tree paths.
1807
+ const rawDataSources = (() => {
1808
+ try {
1809
+ const raw = compositionEntry.data_sources;
1810
+ return Array.isArray(raw)
1811
+ ? raw
1812
+ : Object.values(typeof raw === "string" ? JSON.parse(raw) : (raw ?? {}));
1813
+ }
1814
+ catch {
1815
+ return [];
1816
+ }
1817
+ })();
1818
+ const extendQuery = {
1819
+ ...(options?.extendQuery ?? {}),
1820
+ };
1821
+ // Sanitize resolvedReferences paths before injecting into CDA include[].
1822
+ // Filters: pure numeric segments (picker-tree array indexes like "entries.0.cross_links")
1823
+ // and modular-block numeric prefixes ("2_block_1" → "block_1").
1824
+ // Applied uniformly to contentstack, template, and query DS paths.
1825
+ const sanitizeResolvedPaths = (paths) => [
1826
+ ...new Set(paths
1827
+ .filter((p) => typeof p === "string" && p.trim().length > 0)
1828
+ .map((p) => {
1829
+ const segments = p.split(".").filter(Boolean);
1830
+ const result = [];
1831
+ for (let i = 0; i < segments.length; i++) {
1832
+ const stripped = segments[i].replace(/^\d+_/, ""); // strip modular-block prefix
1833
+ // Skip pure numeric array indexes and "entries" array-wrapper segments —
1834
+ // neither is a valid Contentstack include[] field name.
1835
+ if (/^\d+$/.test(stripped) || stripped === "entries") {
1836
+ continue;
1837
+ }
1838
+ result.push(stripped);
1839
+ }
1840
+ return result.join(".");
1841
+ })
1842
+ .filter((p) => p.length > 0)),
1843
+ ];
1844
+ // Static entries (contentstack DS) → extendQuery[ctUid].includeReferences
1845
+ const csDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.CONTENTSTACK);
1846
+ if (csDS?.resolvedReferences && Array.isArray(csDS.data)) {
1847
+ for (const entry of csDS.data) {
1848
+ const raw = csDS.resolvedReferences[entry.uid] ?? [];
1849
+ const paths = sanitizeResolvedPaths(raw);
1850
+ if (!paths.length)
1851
+ continue;
1852
+ const ct = entry._content_type_uid;
1853
+ if (!extendQuery[ct])
1854
+ extendQuery[ct] = { includeReferences: [] };
1855
+ extendQuery[ct].includeReferences = [
1856
+ ...new Set([...(extendQuery[ct].includeReferences ?? []), ...paths]),
1857
+ ];
1858
+ }
1859
+ }
1860
+ // Template entry (contentstackPreview DS) → extendQuery[connectedContentTypeUid].includeReferences
1861
+ // Now safe to inject because sanitizeResolvedPaths filters out picker-tree
1862
+ // tracking paths (pure numeric indexes) before they reach the CDA query.
1863
+ const connectedContentTypeUid = compositionEntry.connected_content_type || "";
1864
+ const previewDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.TEMPLATE);
1865
+ if (previewDS?.resolvedReferences && connectedContentTypeUid) {
1866
+ const previewPaths = sanitizeResolvedPaths(Object.values(previewDS.resolvedReferences).flat());
1867
+ if (previewPaths.length) {
1868
+ if (!extendQuery[connectedContentTypeUid])
1869
+ extendQuery[connectedContentTypeUid] = { includeReferences: [] };
1870
+ extendQuery[connectedContentTypeUid].includeReferences = [
1871
+ ...new Set([
1872
+ ...(extendQuery[connectedContentTypeUid].includeReferences ?? []),
1873
+ ...previewPaths,
1874
+ ]),
1875
+ ];
1876
+ }
1877
+ }
1878
+ const resolvedOptions = { ...options, extendQuery };
1879
+ const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, connectedContentTypeUid, resolvedOptions);
1880
+ // When inside Studio, ensure ALL configured contentstack DS entries are in
1881
+ // contentstackEntriesReferencesPath — not just those with active bindings.
1882
+ // Entries without bindings are still shown in Studio's data picker and must
1883
+ // be fetched with their saved resolvedReferences include paths so that
1884
+ // isResolutionFresh() returns true and Studio skips its own CMA call.
1885
+ if (clientRendererModeUtil.isInsideStudioFrame() &&
1886
+ csDS?.data &&
1887
+ Array.isArray(csDS.data)) {
1888
+ for (const entry of csDS.data) {
1889
+ const { uid, _content_type_uid } = entry;
1890
+ if (!uid || !_content_type_uid)
1891
+ continue;
1892
+ if (contentstackEntriesReferencesPath[_content_type_uid]?.[uid] !==
1893
+ undefined)
1894
+ continue;
1895
+ const paths = sanitizeResolvedPaths(csDS.resolvedReferences?.[uid] ?? []);
1896
+ if (!contentstackEntriesReferencesPath[_content_type_uid]) {
1897
+ contentstackEntriesReferencesPath[_content_type_uid] = {};
1898
+ }
1899
+ contentstackEntriesReferencesPath[_content_type_uid][uid] = paths;
1900
+ // Also ensure the onlyKeys slot exists (empty = fetch all fields, correct for Studio)
1901
+ if (!contentstackEntriesOnlyKeys[_content_type_uid]) {
1902
+ contentstackEntriesOnlyKeys[_content_type_uid] = {};
1903
+ }
1904
+ if (!contentstackEntriesOnlyKeys[_content_type_uid][uid]) {
1905
+ contentstackEntriesOnlyKeys[_content_type_uid][uid] = [];
1906
+ }
1907
+ }
1908
+ }
1909
+ // The page composition's `static_value` lives at the top level; each
1910
+ // section composition's own `static_value` is carried per-instance via
1911
+ // `section_scoped_data[instanceUid].static_value` (built below) and
1912
+ // overlaid by SectionCompositionProvider inside the section subtree. This
1913
+ // keeps section keys scoped to their own subtree — siblings and the page
1914
+ // can't read each other's keys through `data.static_value`.
1915
+ // Surface the page composition's own `external_data` JSON as
1916
+ // `spec.data.component_props`. useDataWithSpec uses this as the fallback
1917
+ // when the consumer's `<StudioComponent componentProps={...} />`
1918
+ // doesn't supply state — and SectionCompositionProvider merges it under
1919
+ // each section's `componentPropsFallback` (page wins per top-level
1920
+ // key). The Studio editor's `useFetchCurrentUI` does the same injection
1921
+ // for the editor canvas; this branch keeps the SDK runtime in sync.
1922
+ const pageExternalProps = parseExternalDataForComponentProps(compositionEntry.data_sources);
582
1923
  const data = {
583
1924
  [DATA_SOURCES_PREFIX]: {},
584
1925
  [DATA_SOURCES.STATIC_VALUE]: preProcessStaticValues(compositionEntry.static_value || {}),
1926
+ ...(pageExternalProps ? { component_props: pageExternalProps } : {}),
585
1927
  };
1928
+ const templateContentTypeUid = getTemplateContentTypeForComposition(compositionEntry);
1929
+ // Resolve the URL-pattern locale ONCE for the whole page, so the bound-entry
1930
+ // and dynamic-query fetches honor a captured {{locale}} — not just the
1931
+ // template entry. (Environment is the connection env, not threaded per-URL —
1932
+ // see resolveUrlPatternContext / ADR-0002 §Environment.)
1933
+ const urlPatternContext = resolveUrlPatternContext(compositionEntry, queryOptions, templateContentTypeUid);
1934
+ const pageLocale = resolveLocale(urlPatternContext.patternLocale, locale, searchParams);
1935
+ // Resolve the effective variant once for the whole page (mirrors pageLocale); the
1936
+ // bound-entry and dynamic-query fetches below share it.
1937
+ const pageVariantAlias = resolveEffectiveVariantAlias(variantAlias, searchParams);
1938
+ // Build merged entry-reference paths covering page + all section data
1939
+ // sources, with unioned include[] per (ct_uid, entry_uid).
1940
+ const mergedRefs = JSON.parse(JSON.stringify(contentstackEntriesReferencesPath));
1941
+ const mergedOnly = JSON.parse(JSON.stringify(contentstackEntriesOnlyKeys));
1942
+ for (const section of sectionEntries) {
1943
+ // SectionCompositionEntry has ui: Node (already parsed). getEntriesQueries
1944
+ // expects ui as a string so decompressSpec can parse it — re-serialize here.
1945
+ const sectionAsCompositionEntry = {
1946
+ ...section,
1947
+ ui: typeof section.ui === "string"
1948
+ ? section.ui
1949
+ : JSON.stringify(section.ui),
1950
+ };
1951
+ const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
1952
+ // Union refs per ct_uid:entry_uid
1953
+ for (const ctUid of Object.keys(sectionRefs.contentstackEntriesReferencesPath)) {
1954
+ if (!mergedRefs[ctUid])
1955
+ mergedRefs[ctUid] = {};
1956
+ for (const entryUid of Object.keys(sectionRefs.contentstackEntriesReferencesPath[ctUid])) {
1957
+ const existing = mergedRefs[ctUid][entryUid] ?? [];
1958
+ const incoming = sectionRefs.contentstackEntriesReferencesPath[ctUid][entryUid];
1959
+ mergedRefs[ctUid][entryUid] = Array.from(new Set([...existing, ...incoming]));
1960
+ }
1961
+ }
1962
+ // Union onlyKeys
1963
+ for (const ctUid of Object.keys(sectionRefs.contentstackEntriesOnlyKeys)) {
1964
+ if (!mergedOnly[ctUid])
1965
+ mergedOnly[ctUid] = {};
1966
+ for (const entryUid of Object.keys(sectionRefs.contentstackEntriesOnlyKeys[ctUid])) {
1967
+ const existing = mergedOnly[ctUid][entryUid] ?? [];
1968
+ const incoming = sectionRefs.contentstackEntriesOnlyKeys[ctUid][entryUid];
1969
+ const seen = new Set(existing.map((p) => p.join("|")));
1970
+ for (const p of incoming) {
1971
+ const sig = p.join("|");
1972
+ if (!seen.has(sig)) {
1973
+ existing.push(p);
1974
+ seen.add(sig);
1975
+ }
1976
+ }
1977
+ mergedOnly[ctUid][entryUid] = existing;
1978
+ }
1979
+ }
1980
+ }
1981
+ // ---- Section template references → page template include/only ----
1982
+ // Each section renders against a scoped slice of the PAGE template entry
1983
+ // (data.dataSources.template, narrowed by selectedField). For a section's
1984
+ // reference fields to resolve at render, the CDA template fetch must pull
1985
+ // them in — remapped from the section's own schema namespace into the page
1986
+ // template namespace via the instance's selectedField (path prefix) and
1987
+ // uidRemapping (per-segment rename). getEntriesQueries(section) above only
1988
+ // contributed the section's *contentstack-entry* refs; its template refs
1989
+ // and field projections were dropped, so section-bound references came back
1990
+ // as bare stubs (or were never requested) and rendered blank standalone.
1991
+ // For nested wrapper chains, each section's references are rooted at its
1992
+ // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
1993
+ // reference chain (W1 → W2 → …) fetches the full nested include depth.
1994
+ const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
1995
+ const instanceBindings = collectSectionInstanceBindings(typeof compositionEntry.ui === "string"
1996
+ ? decompressSpec(compositionEntry.ui)
1997
+ : compositionEntry.ui, sectionsByUid, connectedContentTypeUid);
1998
+ const mergedTemplateRefs = [...templateReferencesPath];
1999
+ const mergedTemplateOnly = [...templateOnlyKeys];
2000
+ for (const binding of instanceBindings) {
2001
+ const section = sectionsByUid.get(binding.compositionUid);
2002
+ if (!section)
2003
+ continue;
2004
+ // Page-rooted prefix: enclosing wrapper reference path (ancestorPrefix)
2005
+ // composed with this instance's own selectedField. ancestorPrefix is
2006
+ // already sanitized + page-namespaced (ancestor selectedFields are real
2007
+ // field names), so only the instance's own selectedField is sanitized here.
2008
+ // Reference-ancestor placement: when the section sits inside a page
2009
+ // Repeater(reference)+reference-ConditionBlock (see
2010
+ // composeSectionTemplatePrefix).
2011
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2012
+ const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
2013
+ const sectionAsCompositionEntry = {
2014
+ ...section,
2015
+ ui: typeof section.ui === "string"
2016
+ ? section.ui
2017
+ : JSON.stringify(section.ui),
2018
+ };
2019
+ const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
2020
+ // Section reference include paths: UI-derived (reference conditions) plus
2021
+ // saved toggle paths from the SECTION's own data_sources[template].
2022
+ const sectionTemplateRefPaths = new Set(sectionRefs.templateReferencesPath);
2023
+ try {
2024
+ const sds = Array.isArray(section.data_sources)
2025
+ ? section.data_sources
2026
+ : typeof section.data_sources === "string"
2027
+ ? JSON.parse(section.data_sources)
2028
+ : [];
2029
+ const tmplDS = sds.find((ds) => ds?.uid === DATA_SOURCES.TEMPLATE);
2030
+ if (tmplDS?.resolvedReferences) {
2031
+ for (const p of Object.values(tmplDS.resolvedReferences).flat()) {
2032
+ if (typeof p === "string" && p.trim())
2033
+ sectionTemplateRefPaths.add(p);
2034
+ }
2035
+ }
2036
+ }
2037
+ catch {
2038
+ // malformed section data_sources — fall back to UI-derived refs only
2039
+ }
2040
+ for (const p of sectionTemplateRefPaths) {
2041
+ const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
2042
+ if (full)
2043
+ mergedTemplateRefs.push(full);
2044
+ }
2045
+ // Include + project EVERY cumulative hop of the composed prefix so each
2046
+ // reference in the chain is fetched and the next hop is reachable, e.g.
2047
+ // include[]=related_articles, include[]=related_articles.author
2048
+ // only[BASE][]=related_articles, only[related_articles][]=author
2049
+ {
2050
+ let parent = "BASE";
2051
+ const acc = [];
2052
+ for (const seg of prefix) {
2053
+ acc.push(seg);
2054
+ mergedTemplateRefs.push(acc.join("."));
2055
+ mergedTemplateOnly.push([parent, seg]);
2056
+ parent = acc.join(".");
2057
+ }
2058
+ }
2059
+ // Re-parent the section's field projections under the selectedField
2060
+ // subtree so the right fields come back on the referenced entries.
2061
+ for (const [parentKey, child] of sectionRefs.templateOnlyKeys) {
2062
+ const remappedChild = child.split(".").map(remapSeg).join(".");
2063
+ let newParent;
2064
+ if (parentKey === "BASE") {
2065
+ newParent = prefix.length ? prefix.join(".") : "BASE";
2066
+ }
2067
+ else {
2068
+ const remappedParent = parentKey.split(".").map(remapSeg).join(".");
2069
+ newParent = prefix.length
2070
+ ? `${prefix.join(".")}.${remappedParent}`
2071
+ : remappedParent;
2072
+ }
2073
+ mergedTemplateOnly.push([newParent, remappedChild]);
2074
+ }
2075
+ }
2076
+ // Cross-boundary repeater bindings: a page-authored Repeater/Text bound to a
2077
+ // SECTION-INTERNAL repeater (forwarded through a passthrough slot) — e.g. a
2078
+ // Repeater over the `mg` group on a referenced CT, with a Text bound to
2079
+ // `mg_label` inside it. `getEntriesQueries` walks the page at page-root and
2080
+ // can't see the section-internal repeater's reference path, so it roots
2081
+ // those only[] keys at BASE (`only[BASE][]=mg`) and the referenced entry
2082
+ // comes back without the field. Compose each section-internal repeater's
2083
+ // page-rooted path, then project the page bindings that reference them onto
2084
+ // the correct reference subtree (`only[modular_blocks.ref_block.reference][]=mg`).
2085
+ {
2086
+ const repeaterPathMap = new Map();
2087
+ for (const binding of instanceBindings) {
2088
+ const section = sectionsByUid.get(binding.compositionUid);
2089
+ if (!section)
2090
+ continue;
2091
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2092
+ const sectionUi = typeof section.ui === "string"
2093
+ ? decompressSpec(section.ui)
2094
+ : section.ui;
2095
+ mapSectionRepeaterPaths(sectionUi, prefix, repeaterPathMap);
2096
+ }
2097
+ if (repeaterPathMap.size > 0) {
2098
+ const pageUiForProjection = typeof compositionEntry.ui === "string"
2099
+ ? decompressSpec(compositionEntry.ui)
2100
+ : compositionEntry.ui;
2101
+ projectCrossBoundaryRepeaterBindings(pageUiForProjection, repeaterPathMap, mergedTemplateOnly);
2102
+ }
2103
+ }
2104
+ // ---- D7: fold the template entry into the reference union ----
2105
+ // When the template entry is ALSO a contentstack-entry reference (same
2106
+ // ct + uid), it would otherwise be fetched twice — once here as the
2107
+ // template, once by resolveStaticData. Fold it into the single template
2108
+ // fetch (unioned include[]) and drop it from the static pool; the fetched
2109
+ // template entry is copied into the static pool after the fetch (below) so
2110
+ // references to it still resolve. Only possible when the template uid is
2111
+ // known up front (Studio preview override / options.templateEntryUid);
2112
+ // url-pattern pages resolve the uid by matching inside fetchTemplateEntry,
2113
+ // so the overlap isn't detectable here and we keep the two-fetch fallback.
2114
+ const knownTemplateUid = (isInStudio(searchParams)
2115
+ ? readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.TEMPLATE_ENTRY_UID, searchParams)
2116
+ : undefined) ?? options?.templateEntryUid;
2117
+ let foldTemplateIntoStatic = false;
2118
+ if (knownTemplateUid &&
2119
+ templateContentTypeUid &&
2120
+ mergedRefs[templateContentTypeUid]?.[knownTemplateUid]) {
2121
+ foldTemplateIntoStatic = true;
2122
+ // include[] is additive — safe to union. only[] for the referenced
2123
+ // entry's own fields is unioned only when the template fetch is already
2124
+ // projected; pushing onto an empty (all-fields) projection would wrongly
2125
+ // restrict it. (In Studio only[] is ignored entirely.)
2126
+ mergedTemplateRefs.push(...mergedRefs[templateContentTypeUid][knownTemplateUid]);
2127
+ if (mergedTemplateOnly.length > 0) {
2128
+ mergedTemplateOnly.push(...(mergedOnly[templateContentTypeUid]?.[knownTemplateUid] ?? []));
2129
+ }
2130
+ delete mergedRefs[templateContentTypeUid][knownTemplateUid];
2131
+ if (mergedOnly[templateContentTypeUid]) {
2132
+ delete mergedOnly[templateContentTypeUid][knownTemplateUid];
2133
+ }
2134
+ }
2135
+ const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
2136
+ // A deep reference that lives inside a section slot only assembles its full
2137
+ // include[] path in this merged set (the page sees the slot child at the
2138
+ // wrong depth; the section sees its own reference repeater but not the
2139
+ // page-authored slot binding). Reconcile here so every merged include[]
2140
+ // segment is projected in only[] at its parent — otherwise the section's
2141
+ // restrictive projection (e.g. only[a.b][]=_content_type_uid) silently
2142
+ // strips the leaf reference and it renders blank.
2143
+ mergedTemplateOnly.push(...projectIncludePathsOntoOnlyKeys(dedupedTemplateRefs, mergedTemplateOnly));
2144
+ const seenOnly = new Set();
2145
+ const dedupedTemplateOnly = mergedTemplateOnly.filter(([p, c]) => {
2146
+ const sig = `${p}|${c}`;
2147
+ if (seenOnly.has(sig))
2148
+ return false;
2149
+ seenOnly.add(sig);
2150
+ return true;
2151
+ });
586
2152
  await Promise.all([
587
2153
  fetchTemplateEntry({
588
- connected_content_type: compositionEntry.connected_content_type || "",
2154
+ connected_content_type: templateContentTypeUid,
589
2155
  compositionQuery: queryOptions,
590
- includeQueries: templateReferencesPath,
591
- onlyQueries: templateOnlyKeys,
2156
+ includeQueries: dedupedTemplateRefs,
2157
+ onlyQueries: dedupedTemplateOnly,
592
2158
  composableUid: compositionEntry.composable_uid,
593
- }, data, compositionEntry, options),
594
- resolveStaticData(contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, data, {
595
- variantAlias: variantAlias,
596
- locale: locale,
597
- }),
2159
+ }, data, compositionEntry, resolvedOptions, urlPatternContext, searchParams),
2160
+ resolveStaticData(mergedRefs, mergedOnly, data, {
2161
+ variantAlias: pageVariantAlias,
2162
+ locale: pageLocale,
2163
+ }, searchParams),
598
2164
  resolveQueryData(compositionEntry, data, {
599
- variantAlias,
600
- locale: locale || config.locale,
601
- }),
2165
+ variantAlias: pageVariantAlias,
2166
+ locale: pageLocale,
2167
+ sectionEntries,
2168
+ }, searchParams),
602
2169
  ]);
2170
+ // D7: the folded template entry (fetched once, above) also feeds the static
2171
+ // entry pool so contentstack-entry references to it resolve without the
2172
+ // second fetch we removed from mergedRefs.
2173
+ if (foldTemplateIntoStatic) {
2174
+ const templateEntry = data.dataSources?.[DATA_SOURCES.TEMPLATE];
2175
+ if (templateEntry && !Array.isArray(templateEntry)) {
2176
+ setStaticEntryInDS(data.dataSources, templateContentTypeUid, [
2177
+ templateEntry,
2178
+ ]);
2179
+ }
2180
+ }
2181
+ attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
2182
+ // Build per-instance scoped data sources (pure) and attach to spec.
2183
+ const pageUi = typeof compositionEntry.ui === "string"
2184
+ ? decompressSpec(compositionEntry.ui)
2185
+ : compositionEntry.ui;
2186
+ data.section_scoped_data = buildSectionScopedData(compositionEntry, pageUi, sectionEntries, data.dataSources);
603
2187
  return data;
604
2188
  }
605
- async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
2189
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
606
2190
  if (!config.stackSdk) {
607
2191
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
608
2192
  }
@@ -611,22 +2195,44 @@ function generateSdk(userConfig) {
611
2195
  // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
612
2196
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
613
2197
  // Phase 3: Fetch with enhanced context (preserves custom fetchers)
614
- const { compositionEntry, symbolEntries } = await fetchComposition(config, queryOptions, enhancedOptions);
615
- const data = await fetchData(compositionEntry, queryOptions, enhancedOptions);
2198
+ const { compositionEntry, symbolEntries, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
616
2199
  const ui = typeof compositionEntry.ui === "string"
617
2200
  ? decompressSpec(compositionEntry.ui)
618
2201
  : compositionEntry.ui;
2202
+ const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
2203
+ const allSymbolEntries = [...symbolEntries];
2204
+ const seenSymbolUids = new Set(symbolEntries.map((symbol) => symbol.uid));
2205
+ for (const sectionEntry of sectionEntries.values()) {
2206
+ getAllSymbols(sectionEntry).forEach((symbol) => {
2207
+ if (seenSymbolUids.has(symbol.uid))
2208
+ return;
2209
+ seenSymbolUids.add(symbol.uid);
2210
+ allSymbolEntries.push(symbol);
2211
+ });
2212
+ }
2213
+ const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
619
2214
  // Lazy loading and SSR validation for production mode
620
2215
  // Skip if called from fetchMultipleSpecs (which handles loading in batch)
621
2216
  const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
622
- if (isProductionMode && ui && !skipComponentLoading) {
2217
+ // 1.3.0 rendering contract: server returns the spec as data only. The
2218
+ // renderer is `"use client"` and runs entirely on the client — that's
2219
+ // where registry-vs-spec validation belongs. Running it server-side
2220
+ // forces consumers to make their registration module server-evaluable,
2221
+ // which means dragging `"use client"` components into the server module
2222
+ // graph — exactly the failure mode the RFC asks us to avoid.
2223
+ const isServer = typeof window === "undefined";
2224
+ if (!isServer && isProductionMode && ui && !skipComponentLoading) {
623
2225
  const componentRegistry = getComponentRegistryInstance();
624
2226
  // SSR VALIDATION: Check if all required components are registered
625
2227
  // Built-in components should be registered automatically when @contentstack/studio-react is imported
626
2228
  const usedComponents = analyzeUsedComponents(ui);
2229
+ const sectionComponentTypes = new Set(sectionEntries.keys());
627
2230
  const missingBuiltInComponents = [];
628
2231
  const missingCustomComponents = [];
629
2232
  usedComponents.forEach((type) => {
2233
+ if (sectionComponentTypes.has(type)) {
2234
+ return;
2235
+ }
630
2236
  if (!componentRegistry.hasComponentLoader(type)) {
631
2237
  if (INTERNAL_COMPONENT_TYPES.includes(type)) {
632
2238
  missingBuiltInComponents.push(type);
@@ -641,21 +2247,12 @@ function generateSdk(userConfig) {
641
2247
  const errorMessage = [
642
2248
  `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
643
2249
  "",
644
- "❌ Built-in components should be automatically available when importing the SDK.",
645
- "This indicates a build, import, or packaging issue.",
2250
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
2251
+ "If you're seeing this, the package root was either not imported on this code path",
2252
+ "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
646
2253
  "",
647
- "Ensure you're importing from @contentstack/studio-react:",
648
- ' import { useCompositionData } from "@contentstack/studio-react";',
649
- "",
650
- "If using a bundler, verify the package is properly resolved and built.",
651
- "Check for console errors during module import.",
652
- "",
653
- "Manual registration workaround:",
654
- ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
655
- ' import { getBasicComponents } from "@contentstack/studio-react-components";',
656
- "",
657
- " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
658
- " registerComponents(components);",
2254
+ "Fix: make sure the package root is imported at least once before fetchSpec runs:",
2255
+ ' import "@contentstack/studio-react";',
659
2256
  ].join("\n");
660
2257
  throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
661
2258
  }
@@ -687,7 +2284,10 @@ function generateSdk(userConfig) {
687
2284
  data,
688
2285
  ui,
689
2286
  compositionEntry,
690
- symbols: symbolEntries,
2287
+ symbols: allSymbolEntries,
2288
+ sectionCompositions: Array.from(sectionEntries.values()),
2289
+ // Studio-only resolution diagnostics (URL metadata path); undefined otherwise.
2290
+ urlResolution,
691
2291
  config: {
692
2292
  ...getLightConfig(),
693
2293
  // Debug information for compatibility checking (type assertion for internal properties)
@@ -696,29 +2296,83 @@ function generateSdk(userConfig) {
696
2296
  },
697
2297
  };
698
2298
  }
2299
+ /**
2300
+ * Spec-only composition fetch. Resolves the composition STRUCTURE — `ui`,
2301
+ * `compositionEntry`, linked `sectionCompositions`, `config`, and the raw
2302
+ * `ui.metadata.seo` — but SKIPS the data fetch (`fetchData`/CDA) entirely and
2303
+ * omits symbols. `data` comes back empty; the caller supplies it at render
2304
+ * time (see `StudioComposition` in `@contentstack/studio-react`).
2305
+ *
2306
+ * Runs in both SSR and CSR (plain async, not a hook).
2307
+ */
2308
+ async function fetchCompositionSpecOnly(queryOptions, options, skipComponentLoading = false) {
2309
+ if (!config.stackSdk) {
2310
+ throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2311
+ }
2312
+ const studioIntelligence = await StudioIntelligenceManager.getStudioIntelligence(options, config);
2313
+ const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
2314
+ const { compositionEntry, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
2315
+ const ui = typeof compositionEntry.ui === "string"
2316
+ ? decompressSpec(compositionEntry.ui)
2317
+ : compositionEntry.ui;
2318
+ // Section composition entries are STRUCTURAL (their ui trees are needed to
2319
+ // render embedded section nodes and to compute section scoping) — keep them.
2320
+ const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
2321
+ // Client-only registry validation + lazy component loading (same contract as
2322
+ // fetchSpec: server returns the spec as data; validation belongs on the client).
2323
+ const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
2324
+ const isServer = typeof window === "undefined";
2325
+ if (!isServer && isProductionMode && ui && !skipComponentLoading) {
2326
+ await ensureUiComponentsLoaded(ui, sectionEntries);
2327
+ }
2328
+ return {
2329
+ // Data is intentionally empty — this is the bring-your-own-data path.
2330
+ data: { dataSources: {}, static_value: {} },
2331
+ ui,
2332
+ compositionEntry,
2333
+ // Symbols are deprecated for this path.
2334
+ symbols: [],
2335
+ sectionCompositions: Array.from(sectionEntries.values()),
2336
+ urlResolution,
2337
+ config: {
2338
+ ...getLightConfig(),
2339
+ _studioEnhanced: enhancedOptions._enhancementMode === "studio-aware",
2340
+ _enhancementMode: enhancedOptions._enhancementMode,
2341
+ },
2342
+ };
2343
+ }
699
2344
  async function fetchMultipleSpecs(queries, options) {
700
2345
  if (!config.stackSdk) {
701
2346
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
702
2347
  }
703
2348
  // Fetch all specs in parallel (skip individual component loading)
704
2349
  const specs = await Promise.all(queries.map((query) => fetchSpec(query, options, true)));
705
- // In production mode, perform union analysis and load components once
2350
+ // In production mode, perform union analysis and load components once.
2351
+ // Gated to client-only — see the equivalent block in `fetchSpec` for the
2352
+ // 1.3.0-contract reasoning (server returns spec as data; validation belongs
2353
+ // on the client where the renderer actually runs).
706
2354
  const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
707
- if (isProductionMode) {
2355
+ const isServer = typeof window === "undefined";
2356
+ if (!isServer && isProductionMode) {
708
2357
  const componentRegistry = getComponentRegistryInstance();
709
2358
  // Collect all unique component types from all specs
710
2359
  // Built-in components should be registered automatically when @contentstack/studio-react is imported
711
2360
  const allComponents = new Set();
2361
+ const allSectionComponents = new Set();
712
2362
  specs.forEach((spec) => {
713
2363
  if (spec.ui) {
714
2364
  const components = analyzeUsedComponents(spec.ui);
715
2365
  components.forEach((c) => allComponents.add(c));
716
2366
  }
2367
+ spec.sectionCompositions?.forEach((section) => allSectionComponents.add(section.uid));
717
2368
  });
718
2369
  // SSR VALIDATION: Check if all required components are registered
719
2370
  const missingBuiltInComponents = [];
720
2371
  const missingCustomComponents = [];
721
2372
  allComponents.forEach((type) => {
2373
+ if (allSectionComponents.has(type)) {
2374
+ return;
2375
+ }
722
2376
  if (!componentRegistry.hasComponentLoader(type)) {
723
2377
  if (INTERNAL_COMPONENT_TYPES.includes(type)) {
724
2378
  missingBuiltInComponents.push(type);
@@ -733,21 +2387,12 @@ function generateSdk(userConfig) {
733
2387
  const errorMessage = [
734
2388
  `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
735
2389
  "",
736
- "❌ Built-in components should be automatically available when importing the SDK.",
737
- "This indicates a build, import, or packaging issue.",
738
- "",
739
- "Ensure you're importing from @contentstack/studio-react:",
740
- ' import { useCompositionData } from "@contentstack/studio-react";',
741
- "",
742
- "If using a bundler, verify the package is properly resolved and built.",
743
- "Check for console errors during module import.",
744
- "",
745
- "Manual registration workaround:",
746
- ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
747
- ' import { getBasicComponents } from "@contentstack/studio-react-components";',
2390
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
2391
+ "If you're seeing this, the package root was either not imported on this code path",
2392
+ "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
748
2393
  "",
749
- " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
750
- " registerComponents(components);",
2394
+ "Fix: make sure the package root is imported at least once before fetchSpec runs:",
2395
+ ' import "@contentstack/studio-react";',
751
2396
  ].join("\n");
752
2397
  throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
753
2398
  }
@@ -818,38 +2463,93 @@ function generateSdk(userConfig) {
818
2463
  return { entries: [], count: 0 };
819
2464
  }
820
2465
  }
821
- async function resolveQueryData(compositionEntry, data, options) {
822
- if (!compositionEntry.data_sources) {
823
- return;
2466
+ async function resolveQueryData(compositionEntry, data, options, searchParams) {
2467
+ // Parse page data_sources (may be absent — sections may still declare queries).
2468
+ let pageDataSources = [];
2469
+ if (compositionEntry.data_sources) {
2470
+ try {
2471
+ const parsed = JSON.parse(compositionEntry.data_sources);
2472
+ pageDataSources = Array.isArray(parsed)
2473
+ ? parsed
2474
+ : Object.values(parsed);
2475
+ }
2476
+ catch (error) {
2477
+ if (process.env.NODE_ENV === "development") {
2478
+ console.error("Error parsing data sources JSON:", error);
2479
+ }
2480
+ }
824
2481
  }
825
- let dataSources = [];
826
- try {
827
- const parsed = JSON.parse(compositionEntry.data_sources);
828
- dataSources = Array.isArray(parsed) ? parsed : Object.values(parsed);
2482
+ const queriesDS = pageDataSources.find((ds) => ds.uid === DATA_SOURCES.QUERY || ds.id === DATA_SOURCES.QUERY);
2483
+ // Page-side queries (may be empty if page declares no queries).
2484
+ let queries = [];
2485
+ if (queriesDS) {
2486
+ const raw = queriesDS.data || queriesDS.queries || [];
2487
+ if (Array.isArray(raw))
2488
+ queries = raw;
829
2489
  }
830
- catch (error) {
831
- if (process.env.NODE_ENV === "development") {
832
- console.error("Error parsing data sources JSON:", error);
2490
+ // Stable-hash dedup across page queries + section queries.
2491
+ // We also track every uid (alias) that maps to a given hash so the
2492
+ // single resolved result can be fanned out to all of them — section
2493
+ // instances bind by their own data_source uid, which differs from
2494
+ // the page's, and section_scoped_data lookups go via uid.
2495
+ const queryDeduper = new Map();
2496
+ const aliasesByHash = new Map();
2497
+ const seedFromQueries = (items) => {
2498
+ for (const item of items) {
2499
+ if (!item?.spec || !item?.uid)
2500
+ continue;
2501
+ const hash = stableHashQuery(item.spec);
2502
+ if (!queryDeduper.has(hash))
2503
+ queryDeduper.set(hash, item);
2504
+ const aliases = aliasesByHash.get(hash) ?? [];
2505
+ if (!aliases.includes(item.uid))
2506
+ aliases.push(item.uid);
2507
+ aliasesByHash.set(hash, aliases);
2508
+ }
2509
+ };
2510
+ seedFromQueries(queries);
2511
+ // Aggregate resolvedReferences across page + section query data sources.
2512
+ const queriesResolvedRefs = {
2513
+ ...((queriesDS && queriesDS.resolvedReferences) || {}),
2514
+ };
2515
+ for (const sec of options?.sectionEntries ?? []) {
2516
+ try {
2517
+ const parsed = JSON.parse(sec.data_sources);
2518
+ const list = Array.isArray(parsed) ? parsed : Object.values(parsed);
2519
+ const qDs = list.find((d) => d?.uid === DATA_SOURCES.QUERY ||
2520
+ d?.uid === "queries" ||
2521
+ d?.id === DATA_SOURCES.QUERY);
2522
+ if (qDs) {
2523
+ const items = Array.isArray(qDs.data)
2524
+ ? qDs.data
2525
+ : (qDs.data?.queries ?? []);
2526
+ seedFromQueries(items);
2527
+ // Merge section's per-query resolvedReferences as well.
2528
+ if (qDs.resolvedReferences) {
2529
+ Object.assign(queriesResolvedRefs, qDs.resolvedReferences);
2530
+ }
2531
+ }
2532
+ }
2533
+ catch {
2534
+ /* per-section JSON failure already logged in collect-data-needs */
833
2535
  }
834
- return;
835
- }
836
- const queriesDS = dataSources.find((ds) => ds.uid === "contentstack_queries" || ds.id === "contentstack_queries");
837
- if (!queriesDS || !queriesDS.data) {
838
- return;
839
2536
  }
840
- const queries = queriesDS.data || queriesDS.queries || [];
841
- if (!Array.isArray(queries))
2537
+ const dedupedQueries = Array.from(queryDeduper.values());
2538
+ // Nothing to resolve (neither page nor any section declared a query).
2539
+ if (dedupedQueries.length === 0)
842
2540
  return;
843
2541
  const queryResults = {};
844
- // Build RuntimeContext for expression resolution
845
- // In SDK, use window.location.href for URL params
2542
+ // The request's search params (forwarded `searchParams` in SSR, `window.location.search`
2543
+ // in CSR), resolved once and reused for url.params and the in-Studio check below.
2544
+ const requestParams = getRequestSearchParams(searchParams);
2545
+ const isInsideStudio = requestParams?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ?? false;
2546
+ // Build RuntimeContext for expression resolution. URL params come from the request.
2547
+ // `url.hash` stays window-only — the fragment is never sent to a server, so SSR
2548
+ // (preview and production alike) cannot see it.
846
2549
  const urlParams = {};
847
- if (typeof window !== "undefined" && window.location) {
848
- const searchParams = new URLSearchParams(window.location.search);
849
- searchParams.forEach((value, key) => {
850
- urlParams[key] = value;
851
- });
852
- }
2550
+ requestParams?.forEach((value, key) => {
2551
+ urlParams[key] = value;
2552
+ });
853
2553
  const context = {
854
2554
  url: {
855
2555
  params: urlParams,
@@ -858,14 +2558,70 @@ function generateSdk(userConfig) {
858
2558
  },
859
2559
  // NO componentProps or user context - expressions only support URL params and time
860
2560
  };
861
- await Promise.all(queries.map(async (queryConfig) => {
2561
+ await Promise.all(dedupedQueries.map(async (queryConfig) => {
862
2562
  const { uid, spec } = queryConfig;
863
2563
  if (!uid || !spec?.contentType)
864
2564
  return;
865
- // Use fetchContentstackData with full QuerySpec
866
- // This now uses QueryExecutor internally to support filters, sorting, etc.
867
- const result = await fetchContentstackData(spec, context, options);
868
- queryResults[uid] = result;
2565
+ // Merge toggle/binding-driven include paths from resolvedReferences into the query spec.
2566
+ // QueryExecutor reads spec.params.include via normalizeReferenceIncludeParam → includeReference().
2567
+ //
2568
+ // D8: union resolvedReferences across EVERY alias that deduped to this
2569
+ // spec. Two data sources can share one query spec (same hash) yet toggle
2570
+ // DIFFERENT reference fields; resolvedReferences isn't part of the hash
2571
+ // (it's merged here, post-dedup), so using only the deduped uid's refs
2572
+ // would drop the other aliases' includes and their references would
2573
+ // render blank. Unioning executes the single query with all includes.
2574
+ const specHash = stableHashQuery(spec);
2575
+ const aliasUidsForRefs = aliasesByHash.get(specHash) ?? [uid];
2576
+ const togglePaths = [
2577
+ ...new Set(aliasUidsForRefs.flatMap((a) => queriesResolvedRefs[a] ?? [])),
2578
+ ]
2579
+ .map((p) => p
2580
+ .split(".")
2581
+ .filter((s) => !/^\d+$/.test(s) && s !== "entries")
2582
+ .join("."))
2583
+ .filter(Boolean);
2584
+ // When inside Studio, add editor params so the delivery SDK (preview API)
2585
+ // returns unpublished entries and full field metadata — matching CMA richness.
2586
+ // Studio's isResolutionFresh then sees non-empty entries and skips its CMA call.
2587
+ // (isInsideStudio is resolved once for the whole resolveQueryData call above.)
2588
+ const studioParams = isInsideStudio
2589
+ ? {
2590
+ include_publish_details: true,
2591
+ include_unpublished: true,
2592
+ include_fields: true,
2593
+ }
2594
+ : {};
2595
+ const needsMerge = togglePaths.length > 0 || Object.keys(studioParams).length > 0;
2596
+ const mergedSpec = needsMerge
2597
+ ? {
2598
+ ...spec,
2599
+ params: {
2600
+ ...studioParams,
2601
+ ...(spec.params ?? {}),
2602
+ ...(togglePaths.length
2603
+ ? {
2604
+ include: [
2605
+ ...new Set([
2606
+ ...(Array.isArray(spec.params?.include)
2607
+ ? spec.params.include
2608
+ : []),
2609
+ ...togglePaths,
2610
+ ]),
2611
+ ],
2612
+ }
2613
+ : {}),
2614
+ },
2615
+ }
2616
+ : spec;
2617
+ const result = await fetchContentstackData(mergedSpec, context, options);
2618
+ // Fan out result to every uid that resolved to this query spec
2619
+ // (page's data_source uid + each section instance's data_source uid).
2620
+ const hash = stableHashQuery(spec);
2621
+ const aliases = aliasesByHash.get(hash) ?? [uid];
2622
+ for (const alias of aliases) {
2623
+ queryResults[alias] = result;
2624
+ }
869
2625
  }));
870
2626
  if (!data.dataSources[DATA_SOURCES.QUERY]) {
871
2627
  data.dataSources[DATA_SOURCES.QUERY] = {};
@@ -875,8 +2631,14 @@ function generateSdk(userConfig) {
875
2631
  function getLightConfig() {
876
2632
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
877
2633
  }
878
- function getSeoMetadata(ui) {
879
- return ui.metadata.seo || null;
2634
+ /**
2635
+ * Studio stores SEO in `ui.metadata.seo`; template entry data is fetched
2636
+ * separately into `spec.data`. Delegate to the pure resolver so callers of
2637
+ * `specOptions.seo` receive resolved values instead of raw binding-only
2638
+ * metadata.
2639
+ */
2640
+ function getSeoMetadata(ui, specData) {
2641
+ return getSeoMetadataPure(ui, specData);
880
2642
  }
881
2643
  const sdkSingleton = {
882
2644
  internal: {
@@ -887,6 +2649,7 @@ function generateSdk(userConfig) {
887
2649
  // Once we fetch the data, we need to perform certain operation to store the UI and data.
888
2650
  // Hence, we moved this to the internal method.
889
2651
  fetchSpec,
2652
+ fetchCompositionSpecOnly,
890
2653
  fetchMultipleSpecs,
891
2654
  fetchData,
892
2655
  fetchTemplateEntry,
@@ -895,11 +2658,36 @@ function generateSdk(userConfig) {
895
2658
  public: {
896
2659
  // Exposing this method for the user to fetch the data.
897
2660
  /**
898
- * This method is used to fetch the composition data for the SSR.
2661
+ * Server-side composition fetcher. Resolves a composition + its bound
2662
+ * data into a `StudioComponentSpecOptions` object you can hand to
2663
+ * `<StudioComponent specOptions={...} />`.
2664
+ *
2665
+ * Pair with `useCompositionData` for CSR; the two cover the same use
2666
+ * cases on different render paths.
899
2667
  *
900
- * @param queryOptions - The query options for the composition.
901
- * @param options - The options for the composition.
902
- * @returns The composition data for the SSR.
2668
+ * IMPORTANT — this returns the spec options object **directly**, NOT
2669
+ * wrapped in `{ specOptions }`. Destructure accordingly:
2670
+ *
2671
+ * ```ts
2672
+ * // ✅ Correct
2673
+ * const specOptions = await sdk.fetchCompositionData({ url: "/about", searchQuery: "" });
2674
+ *
2675
+ * // ❌ Wrong — `specOptions` will be undefined
2676
+ * const { specOptions } = await sdk.fetchCompositionData(...);
2677
+ * ```
2678
+ *
2679
+ * There is **no `.public` namespace** on the SDK returned from
2680
+ * `studioSdk.init(...)` — call `sdk.fetchCompositionData(...)`,
2681
+ * not `sdk.public.fetchCompositionData(...)`.
2682
+ *
2683
+ * @param queryOptions - Identifies the composition (`compositionUid`,
2684
+ * `url`, `templateContentTypeUid`, or a combination) PLUS the
2685
+ * server-only `searchQuery` string for forwarding Studio iframe
2686
+ * overrides (locale, variant, preview entry, edit mode).
2687
+ * @param options - Optional modifiers: `variantAlias`, `locale`,
2688
+ * `templateEntryUid`, `extendQuery`, custom fetchers.
2689
+ * @returns `Promise<StudioComponentSpecOptions>` — the resolved spec
2690
+ * options object.
903
2691
  */
904
2692
  fetchCompositionData: async (queryOptions, options) => {
905
2693
  if (!config.stackSdk) {
@@ -910,43 +2698,46 @@ function generateSdk(userConfig) {
910
2698
  const urlSearchParam = new URLSearchParams(searchQuery);
911
2699
  // NOTE: Always keep this before fetching the spec. In SSR, we use the urlSearchParams
912
2700
  // to get the hash and then use it to fetch the composition.
913
- config.stackSdk.livePreviewQuery(urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
914
- urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH) ||
915
- "");
916
- const rendererModeUtil = new RendererModeUtil(urlSearchParam);
917
- // If queryOptions has composableUid and we are editing the current composition, we don't need to fetch the spec.
918
- if ("compositionUid" in queryOptions &&
919
- rendererModeUtil.isEditingCurrentComposition(queryOptions.compositionUid || "")) {
920
- return {
921
- spec: null,
922
- fetchOptions: {
923
- searchQuery: urlSearchParam.toString(),
924
- compositionQuery,
925
- config: getLightConfig(),
926
- options,
927
- mode: rendererModeUtil.getMode(queryOptions.compositionUid || ""),
928
- },
929
- hasSpec: true,
930
- hasTemplate: true,
931
- seo: null,
932
- };
933
- }
934
- const spec = await fetchSpec(compositionQuery, options);
935
- if (rendererModeUtil.isEditingCurrentComposition(spec.compositionEntry.composable_uid || "")) {
936
- return {
937
- spec: null,
938
- fetchOptions: {
939
- searchQuery: urlSearchParam.toString(),
940
- compositionQuery,
941
- config: getLightConfig(),
942
- options,
943
- mode: rendererModeUtil.getMode(spec.compositionEntry.composable_uid),
944
- },
945
- hasSpec: true,
946
- hasTemplate: true,
947
- seo: null,
948
- };
2701
+ //
2702
+ // Only invoke `livePreviewQuery` when the request URL actually carries
2703
+ // a preview hash. Passing an empty string explicitly disables live
2704
+ // preview on the delivery SDK for subsequent requests, which forces
2705
+ // SSR's `fetchSpec` to hit the delivery API even when the stack was
2706
+ // initialised with `live_preview.enable=true`. Skipping the reset
2707
+ // when there's no hash preserves the stack's initialised live-preview
2708
+ // state and matches CSR's `useCompositionData` behaviour, which never
2709
+ // resets the hash between fetches.
2710
+ const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
2711
+ urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
2712
+ if (previewHash) {
2713
+ config.stackSdk.livePreviewQuery(previewHash);
949
2714
  }
2715
+ const rendererModeUtil = new RendererModeUtil(urlSearchParam);
2716
+ // P4.2 (ADR-0005): always fetch and return the spec — uniformly for the
2717
+ // composition-uid and URL cases, whether or not it is being edited. The two
2718
+ // being-edited `null` returns are removed: returning `null` is what put SSR on
2719
+ // the served path (the iframe falls back to `getSpecFromParent` and asks Studio).
2720
+ // With the spec returned, SSR-being-edited now renders through the spec-provided
2721
+ // boundary and hands the spec to Studio via the push path (SDK_SPEC_RESOLVED,
2722
+ // emitted from EditableRendererHelper) — the same way CSR and production fetch.
2723
+ // The credential-less playground is unaffected: it never calls fetchCompositionData
2724
+ // (it uses `getSpecFromParent` directly) and stays on the served path.
2725
+ // Thread the forwarded request query (`searchQuery`) into the fetch so the
2726
+ // server-side resolvers see the author's live editor context (cs-locale,
2727
+ // cs-variant-alias, cs-template-entry-uid) — SSR resolves identically to CSR.
2728
+ // On the client this is the same window-derived context, so CSR is unchanged.
2729
+ const spec = await fetchSpec(compositionQuery, options, false, urlSearchParam);
2730
+ // Echo the resolved editor locale/variant back to Studio so the pushed
2731
+ // `sdkContext` reports the copy the SSR data was actually fetched in (e.g.
2732
+ // fr-fr) rather than the host's empty default — otherwise Studio's
2733
+ // diagnostics warn "rendered en-us" and Stage-2 entry/query adds would use
2734
+ // the wrong copy. Same precedence as the fetch (cs-locale > option >
2735
+ // config), read from the request query.
2736
+ const echoedOptions = {
2737
+ ...options,
2738
+ locale: resolveLocale(undefined, options?.locale, urlSearchParam),
2739
+ variantAlias: resolveEffectiveVariantAlias(options?.variantAlias, urlSearchParam),
2740
+ };
950
2741
  return {
951
2742
  spec,
952
2743
  hasSpec: !!spec.compositionEntry,
@@ -955,13 +2746,42 @@ function generateSdk(userConfig) {
955
2746
  // TODO: @Nilesh - see if we can remove this as this config is already available in the spec.
956
2747
  config: getLightConfig(),
957
2748
  compositionQuery,
958
- options,
2749
+ options: echoedOptions,
959
2750
  searchQuery: urlSearchParam.toString(),
960
2751
  mode: rendererModeUtil.getMode(spec.compositionEntry.composable_uid),
961
2752
  },
962
- seo: getSeoMetadata(spec.ui),
2753
+ seo: getSeoMetadata(spec.ui, spec.data),
963
2754
  };
964
2755
  },
2756
+ /**
2757
+ * Spec-only composition fetcher (bring-your-own-data). Resolves the
2758
+ * composition STRUCTURE — `ui`, `compositionEntry`, linked
2759
+ * `sectionCompositions`, `config`, raw `ui.metadata.seo` — and SKIPS the
2760
+ * data fetch. `spec.data` comes back empty; you supply the data at render
2761
+ * time via `<StudioComposition spec={spec} data={...} />`.
2762
+ *
2763
+ * Runs in both SSR and CSR (plain async, not a hook). In SSR, resolve a
2764
+ * `compositionUid` here and pass the returned `spec` to the component; in
2765
+ * CSR you may instead pass `compositionUid` to the component directly.
2766
+ *
2767
+ * @returns `Promise<StudioSpec>` — the composition spec with empty data.
2768
+ */
2769
+ fetchComposition: async (queryOptions, options) => {
2770
+ if (!config.stackSdk) {
2771
+ throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
2772
+ }
2773
+ const { searchQuery, ...compositionQueryInput } = queryOptions;
2774
+ const compositionQuery = convertCompositionQueryInputToCompositionQuery(compositionQueryInput);
2775
+ const urlSearchParam = new URLSearchParams(searchQuery);
2776
+ // Mirror fetchCompositionData: only reset live preview when a hash is
2777
+ // actually present, so we don't disable the stack's live-preview state.
2778
+ const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
2779
+ urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
2780
+ if (previewHash) {
2781
+ config.stackSdk.livePreviewQuery(previewHash);
2782
+ }
2783
+ return fetchCompositionSpecOnly(compositionQuery, options);
2784
+ },
965
2785
  /**
966
2786
  * This method is used to get the configuration for the client.
967
2787
  *
@@ -993,7 +2813,9 @@ const parseUI = (ui) => {
993
2813
  };
994
2814
  function getAllSymbols(compositionEntry) {
995
2815
  const res = [];
996
- const Q = [compositionEntry];
2816
+ const Q = [
2817
+ compositionEntry,
2818
+ ];
997
2819
  while (Q.length > 0) {
998
2820
  const curr = Q.shift();
999
2821
  const symbols = (curr?.symbols || []);
@@ -1005,6 +2827,99 @@ function getAllSymbols(compositionEntry) {
1005
2827
  }
1006
2828
  return res;
1007
2829
  }
2830
+ /** CDA entries page size for the lightweight candidate fetch. */
2831
+ const CANDIDATE_PAGE_SIZE = 100;
2832
+ /** Safety cap on candidate pages (server-side resolution will own this later). */
2833
+ const MAX_CANDIDATE_PAGES = 20;
2834
+ /**
2835
+ * Fetch every page-linked composition (lightweight: url + url_metadata +
2836
+ * composable_uid + connected_content_type) for URL resolution — legacy and
2837
+ * variable, linked and freeform. Section compositions are excluded by the page
2838
+ * placement filter. Paginates with skip/limit; `truncated` is true if the safety
2839
+ * cap is hit.
2840
+ */
2841
+ async function fetchAllPageCompositions(config, locale) {
2842
+ const all = [];
2843
+ for (let page = 0; page < MAX_CANDIDATE_PAGES; page++) {
2844
+ const res = await config.stackSdk
2845
+ .ctQuery(config.contentTypeUid, {
2846
+ locale: locale || config.locale,
2847
+ query: { ...getPageLinkedPlacementFilter() },
2848
+ only: [
2849
+ ["BASE", "url"],
2850
+ ["BASE", "url_metadata"],
2851
+ ["BASE", "composable_uid"],
2852
+ ["BASE", "connected_content_type"],
2853
+ ],
2854
+ })
2855
+ .limit(CANDIDATE_PAGE_SIZE)
2856
+ .skip(page * CANDIDATE_PAGE_SIZE)
2857
+ .find();
2858
+ const batch = entriesFromResponse(res);
2859
+ all.push(...batch);
2860
+ if (batch.length < CANDIDATE_PAGE_SIZE) {
2861
+ return { entries: all, truncated: false };
2862
+ }
2863
+ }
2864
+ return { entries: all, truncated: true };
2865
+ }
2866
+ /**
2867
+ * Decide which composition wins among the ranking's top-tier candidates.
2868
+ *
2869
+ * - Single top-tier candidate → it wins, no probe.
2870
+ * - Multiple → probe each tied *linked* candidate's connected content type (in
2871
+ * parallel) for an entry matching the URL. A freeform candidate (no content
2872
+ * type) is unconditionally valid. The first valid candidate in fetch order
2873
+ * wins; a residual multi-owner case is a content mistake surfaced by Studio
2874
+ * diagnostics, never an error.
2875
+ *
2876
+ * Returns the winner's composable_uid (or undefined if nothing owns the URL) and
2877
+ * the per-candidate ownership outcome for diagnostics.
2878
+ */
2879
+ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale) {
2880
+ const topTier = ranking.matches;
2881
+ // Happy path — a single (or no) top-tier candidate needs no probe.
2882
+ if (topTier.length <= 1) {
2883
+ return selectUrlWinner(topTier, new Map());
2884
+ }
2885
+ // Tie — probe each tied linked candidate's content type in parallel.
2886
+ const linkedMatches = topTier.filter((m) => m.connected_content_type);
2887
+ const probeOutcomes = await Promise.all(linkedMatches.map(async (m) => {
2888
+ const lightweight = candidatesByUid.get(m.composable_uid);
2889
+ // Legacy compositions persist no `url_metadata`. parseUrlMetadata maps an
2890
+ // absent/unknown source to the canonical LEGACY_URL metadata (url-non-empty
2891
+ // / url-equals query), so a tie of metadata-less legacy compositions still
2892
+ // gets probed by URL instead of bailing to "no winner" → COMPOSITION_NOT_
2893
+ // FOUND_BY_URL. Only an unmatched candidate (no captured variables / no
2894
+ // content type) is unprobeable.
2895
+ const meta = parseUrlMetadata(lightweight?.url_metadata);
2896
+ if (!m.variables || !m.connected_content_type) {
2897
+ return { uid: m.composable_uid, owns: false };
2898
+ }
2899
+ try {
2900
+ const probeQuery = resolveByUrlSource(config.stackSdk, meta.url_source, { url: requestUrl }, m.variables, meta.url_queries, m.connected_content_type, {
2901
+ references: [],
2902
+ only: [["BASE", "uid"]],
2903
+ locale: m.variables.metadata.locale || locale || config.locale,
2904
+ branch: m.variables.metadata.branch,
2905
+ // environment intentionally omitted — the ownership probe uses the
2906
+ // connection (SDK-init) env, consistent with how the page is served
2907
+ // (see ADR-0002 §Environment).
2908
+ });
2909
+ const res = await probeQuery.find();
2910
+ return {
2911
+ uid: m.composable_uid,
2912
+ owns: entriesFromResponse(res).length > 0,
2913
+ };
2914
+ }
2915
+ catch {
2916
+ // A failed probe counts as non-owning; another candidate may still own it.
2917
+ return { uid: m.composable_uid, owns: false };
2918
+ }
2919
+ }));
2920
+ const ownsByUid = new Map(probeOutcomes.map((r) => [r.uid, r.owns]));
2921
+ return selectUrlWinner(topTier, ownsByUid);
2922
+ }
1008
2923
  /**
1009
2924
  * This function fetches UI Composition from defined options.
1010
2925
  * Supports custom fetcher overrides (per-query > global > SDK default).
@@ -1012,6 +2927,9 @@ function getAllSymbols(compositionEntry) {
1012
2927
  async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1013
2928
  const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
1014
2929
  const locale = resolvedOptions.locale;
2930
+ // Captured by the URL metadata (Phase A) path for Studio resolution
2931
+ // diagnostics — every candidate considered, with specificity.
2932
+ let urlResolution;
1015
2933
  const defaultImpl = async () => {
1016
2934
  if ("composableUid" in queryOptions) {
1017
2935
  const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
@@ -1051,41 +2969,30 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1051
2969
  });
1052
2970
  });
1053
2971
  }
1054
- else if ("url" in queryOptions) {
1055
- const possibleEntryUrlPatterns = getUrlPatterns(queryOptions.url);
2972
+ else if ("templateContentTypeUid" in queryOptions) {
2973
+ // Fetch by connected content type - takes priority over url when both are present
2974
+ const placementFilter = getPageLinkedPlacementFilter();
1056
2975
  return await config.stackSdk
1057
2976
  .ctQuery(config.contentTypeUid, {
1058
2977
  includeAll: true,
1059
2978
  includeAllDepth: INCLUDE_DEPTH_COUNT,
1060
2979
  locale: locale || config.locale,
1061
2980
  query: {
1062
- url: {
1063
- $in: possibleEntryUrlPatterns,
1064
- },
1065
- $or: [
1066
- { place_composition_as: "page" },
1067
- { place_composition_as: "" },
1068
- { place_composition_as: null },
1069
- { place_composition_as: undefined },
1070
- { place_composition_as: { $exists: false } },
1071
- { connected_content_type: { $exists: true } },
1072
- ],
2981
+ connected_content_type: queryOptions.templateContentTypeUid,
2982
+ ...placementFilter,
1073
2983
  },
1074
2984
  })
2985
+ .limit(1) // First match as per plan
1075
2986
  .find()
1076
2987
  .then((res) => {
1077
2988
  const entries = entriesFromResponse(res);
1078
- const entry = getCompositionFromSlug(queryOptions.url, entries);
2989
+ const entry = entries[0];
1079
2990
  if (!entry) {
1080
- throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
1081
- url: queryOptions.url,
1082
- }), {
1083
- url: queryOptions.url,
2991
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
2992
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
1084
2993
  hasStackSdk: !!config.stackSdk,
1085
- searchedPatterns: possibleEntryUrlPatterns,
1086
- entriesFound: entries.length,
1087
2994
  options: queryOptions,
1088
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
2995
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1089
2996
  });
1090
2997
  }
1091
2998
  return entry;
@@ -1095,15 +3002,81 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1095
3002
  throw err;
1096
3003
  const { errorType, message } = classifyApiError(err);
1097
3004
  throw new ComposableStudioError(errorType, message, {
1098
- url: queryOptions.url,
3005
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
1099
3006
  hasStackSdk: !!config.stackSdk,
1100
3007
  statusCode: err?.status || err?.statusCode || "none",
1101
3008
  errorCode: err?.error_code || "none",
1102
3009
  errorMessage: err?.error_message || err?.message || "none",
1103
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
3010
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
1104
3011
  });
1105
3012
  });
1106
3013
  }
3014
+ else if ("url" in queryOptions) {
3015
+ // Unified resolution: rank ALL page-linked compositions (legacy +
3016
+ // variable, linked + freeform) in one pool, then disambiguate any
3017
+ // top-tier tie by probing each tied linked candidate's content type for an
3018
+ // entry matching the URL. The most-specific match is authoritative — no
3019
+ // descent to lower tiers, no legacy fallback.
3020
+ const requestUrl = queryOptions.url;
3021
+ try {
3022
+ // 1. Fetch every page-linked candidate (lightweight, paginated).
3023
+ const { entries: candidates, truncated } = await fetchAllPageCompositions(config, locale);
3024
+ if (truncated) {
3025
+ console.warn(`[Composable Studio SDK] Composition candidate list hit the pagination cap while resolving "${requestUrl}"; some compositions may not have been considered.`);
3026
+ }
3027
+ // 2. Rank the whole pool by literal-character specificity.
3028
+ const ranking = rankUrlMatches(requestUrl, candidates);
3029
+ if (ranking.composableUids.length > 0) {
3030
+ const candidatesByUid = new Map(candidates.map((c) => [c.composable_uid, c]));
3031
+ // 3. Disambiguate top-tier ties by entry existence.
3032
+ const { winnerUid, ownershipByUid } = await resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale);
3033
+ // 4. Record every considered candidate (all tiers) + ownership for
3034
+ // Studio diagnostics, before committing to a winner.
3035
+ urlResolution = {
3036
+ shortlisted: ranking.allMatches.map((d) => ({
3037
+ ...d,
3038
+ connectedEntryResult: ownershipByUid.get(d.composable_uid) ?? "not-checked",
3039
+ })),
3040
+ };
3041
+ if (winnerUid) {
3042
+ // 5. Full-fetch the winning composition only.
3043
+ const fullQuery = config.stackSdk.ctQuery(config.contentTypeUid, {
3044
+ includeAll: true,
3045
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
3046
+ locale: locale || config.locale,
3047
+ query: { composable_uid: winnerUid },
3048
+ });
3049
+ const fullRes = await fullQuery.find();
3050
+ const fullEntries = entriesFromResponse(fullRes);
3051
+ if (fullEntries[0]) {
3052
+ return fullEntries[0];
3053
+ }
3054
+ }
3055
+ }
3056
+ // Nothing matched, or no tied candidate owns the URL.
3057
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
3058
+ url: requestUrl,
3059
+ }), {
3060
+ url: requestUrl,
3061
+ hasStackSdk: !!config.stackSdk,
3062
+ options: queryOptions,
3063
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
3064
+ });
3065
+ }
3066
+ catch (err) {
3067
+ if (err instanceof ComposableStudioError)
3068
+ throw err;
3069
+ const { errorType, message } = classifyApiError(err);
3070
+ throw new ComposableStudioError(errorType, message, {
3071
+ url: requestUrl,
3072
+ hasStackSdk: !!config.stackSdk,
3073
+ statusCode: err?.status || err?.statusCode || "none",
3074
+ errorCode: err?.error_code || "none",
3075
+ errorMessage: err?.error_message || err?.message || "none",
3076
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
3077
+ });
3078
+ }
3079
+ }
1107
3080
  else {
1108
3081
  throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
1109
3082
  options: queryOptions,
@@ -1132,14 +3105,18 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1132
3105
  return {
1133
3106
  compositionEntry: entry,
1134
3107
  symbolEntries: getAllSymbols(entry),
3108
+ // Populated if the custom fetcher delegated to `defaultFetch` and it
3109
+ // resolved via the URL metadata path; otherwise undefined.
3110
+ urlResolution,
1135
3111
  };
1136
3112
  }
1137
3113
  const entry = await defaultImpl();
1138
3114
  return {
1139
3115
  compositionEntry: entry,
1140
3116
  symbolEntries: getAllSymbols(entry),
3117
+ urlResolution,
1141
3118
  };
1142
3119
  }
1143
3120
 
1144
- export { classifyApiError, generateSdk, parseUI };
3121
+ export { buildSectionScopedData, classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, getSeoMetadataPure, isTemplateBinding, mapSectionRepeaterPaths as mapSectionRepeaterPathsForTest, parseUI, projectCrossBoundaryRepeaterBindings as projectCrossBoundaryRepeaterBindingsForTest, resolveSeoBindingValue };
1145
3122
  //# sourceMappingURL=sdk.js.map