@contentstack/studio-client 1.7.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 (36) hide show
  1. package/dist/breakpoints/BreakpointManager.js +1 -0
  2. package/dist/breakpoints/BreakpointManager.js.map +1 -1
  3. package/dist/composable-studio/collect-data-needs.js +78 -4
  4. package/dist/composable-studio/collect-data-needs.js.map +1 -1
  5. package/dist/composable-studio/composition-metadata.js +75 -0
  6. package/dist/composable-studio/composition-metadata.js.map +1 -0
  7. package/dist/composable-studio/sdk.js +682 -191
  8. package/dist/composable-studio/sdk.js.map +1 -1
  9. package/dist/composable-studio/studio-intelligence.manager.js +1 -0
  10. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  11. package/dist/config/stack-sdk-wrapper.js +1 -0
  12. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  13. package/dist/context-menu/context-menu.js +1 -0
  14. package/dist/context-menu/context-menu.js.map +1 -1
  15. package/dist/dnd/dnd-manager.js +1 -0
  16. package/dist/dnd/dnd-manager.js.map +1 -1
  17. package/dist/highlight-node/highlight-node-manager.js +1 -0
  18. package/dist/highlight-node/highlight-node-manager.js.map +1 -1
  19. package/dist/highlight-node/highlight-node.js +1 -0
  20. package/dist/highlight-node/highlight-node.js.map +1 -1
  21. package/dist/index.d.ts +396 -229
  22. package/dist/index.js +3 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/studio-internal/dist/utils/section-slot-walker.js.map +1 -0
  25. package/dist/{packages/studio-internal → studio-internal}/dist/utils/spec-compression.js +1 -1
  26. package/dist/studio-internal/dist/utils/spec-compression.js.map +1 -0
  27. package/dist/utils/constants.js +1 -1
  28. package/dist/utils/editor-mode.js +142 -0
  29. package/dist/utils/editor-mode.js.map +1 -0
  30. package/dist/utils/reference_fetcher.js +1 -1
  31. package/package.json +8 -7
  32. package/dist/node_modules/fflate/esm/browser.js +0 -378
  33. package/dist/node_modules/fflate/esm/browser.js.map +0 -1
  34. package/dist/packages/studio-internal/dist/utils/section-slot-walker.js.map +0 -1
  35. package/dist/packages/studio-internal/dist/utils/spec-compression.js.map +0 -1
  36. /package/dist/{packages/studio-internal → studio-internal}/dist/utils/section-slot-walker.js +0 -0
@@ -1,11 +1,12 @@
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, get } from 'lodash-es';
3
+ import { get, pick } from 'lodash-es';
4
4
  import { processUserConfig } from '../config/process-user-config.js';
5
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, getBindingStringForCS } 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';
@@ -20,11 +21,11 @@ import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
20
21
  import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
21
22
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
22
23
  import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
23
- import { parseExternalDataForComponentProps, collectAllDataNeeds, stableHashQuery } from './collect-data-needs.js';
24
+ import { collectAllDataNeeds, stableHashQuery, parseExternalDataForComponentProps } from './collect-data-needs.js';
24
25
  import { buildScopedDataSources } from './build-scoped-data.js';
25
26
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
26
27
  import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
27
- import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
28
+ import { decompressSpec } from '../studio-internal/dist/utils/spec-compression.js';
28
29
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
29
30
 
30
31
  // ✅ HYBRID APPROACH: List of internal components that should always be available
@@ -159,6 +160,36 @@ function collectSectionCompositionUIDs(ui, accumulator = new Set()) {
159
160
  }
160
161
  return accumulator;
161
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
+ }
162
193
  /**
163
194
  * Strip a field path down to CDA include[]/only[]-safe segments: drop array
164
195
  * indices (`x[0]` → `x`), modular-block numeric prefixes (`2_block` → `block`),
@@ -194,11 +225,20 @@ function sanitizeFieldPath(path) {
194
225
  * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
195
226
  */
196
227
  function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
197
- if (referenceCtUids.length === 0) {
198
- return [...ancestorPrefix, ...sanitizeFieldPath(selectedField)];
199
- }
200
228
  const dropCtUids = new Set(referenceCtUids);
201
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.
202
242
  const remainder = ancestorPrefix.length > 0 &&
203
243
  sf.length >= ancestorPrefix.length &&
204
244
  ancestorPrefix.every((seg, i) => seg === sf[i])
@@ -206,6 +246,122 @@ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCt
206
246
  : sf;
207
247
  return [...ancestorPrefix, ...remainder];
208
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
+ }
209
365
  /**
210
366
  * Resolve a section-composition node's effective `selectedField`. Resolution
211
367
  * order MUST match the render side (`collect-data-needs`'s declaredField) so
@@ -260,7 +416,11 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
260
416
  enclosingRepeaterRefField,
261
417
  // Target-CT uids from the enclosing reference ConditionBlock(s) on the path
262
418
  // to this node (see SectionInstanceBinding.referenceCtUids).
263
- refCtUids) => {
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()) => {
264
424
  if (!node || typeof node !== "object")
265
425
  return;
266
426
  const nextRepeater = node.type === "repeater" && node.uid ? node.uid : parentRepeaterUID;
@@ -318,20 +478,54 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
318
478
  });
319
479
  // A whole-CT wrapper (selectedField "") adds no segment — correct, it
320
480
  // creates no reference hop. A reference-bound wrapper extends the prefix
321
- // so its slot children's references resolve from that reference.
322
- childPrefix = [...ancestorPrefix, ...sanitizeFieldPath(selectedField)];
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
+ }
323
517
  }
324
518
  if (node.slots && typeof node.slots === "object") {
325
519
  for (const slotNodes of Object.values(node.slots)) {
326
520
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
327
521
  for (const c of arr)
328
- walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids);
522
+ walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
329
523
  }
330
524
  }
331
525
  if (Array.isArray(node.children)) {
332
526
  // children (non-slot) stay in the same scope as this node.
333
527
  for (const c of node.children)
334
- walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids);
528
+ walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
335
529
  }
336
530
  };
337
531
  walk(ui, null, [], null, []);
@@ -356,41 +550,121 @@ async function fetchSectionCompositionEntries(config, sectionUids, options) {
356
550
  : entry.ui,
357
551
  }));
358
552
  }
359
- async function getAllSectionCompositions(config, compositionEntry, options) {
360
- const map = new Map();
361
- // 1. Pull inline linked_sections from the initial composition response.
362
- const linked = compositionEntry.linked_sections;
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;
363
594
  if (Array.isArray(linked)) {
364
- for (const candidate of linked) {
365
- // Skip bare references (uid only — fetch path) — handled by fallback.
366
- if (candidate && typeof candidate === "object" && "ui" in candidate) {
367
- const entry = candidate;
368
- const ui = typeof entry.ui === "string"
369
- ? decompressSpec(entry.ui)
370
- : entry.ui;
371
- map.set(entry.uid, { ...entry, ui });
372
- }
595
+ for (const l of linked) {
596
+ const uid = l?.uid;
597
+ if (typeof uid === "string" && uid)
598
+ uids.add(uid);
373
599
  }
374
600
  }
375
- // 2. Find any section-composition UIDs referenced in the UI tree that are
376
- // missing from `map`. These need a fallback fetch.
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.
377
621
  const ui = typeof compositionEntry.ui === "string"
378
622
  ? decompressSpec(compositionEntry.ui)
379
623
  : compositionEntry.ui;
380
- const referenced = Array.from(collectSectionCompositionUIDs(ui));
381
- const missing = referenced.filter((uid) => !map.has(uid));
382
- if (missing.length) {
383
- if (process.env.NODE_ENV === "development") {
384
- console.warn("getAllSectionCompositions: falling back to fetch for missing sections", missing);
385
- }
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 = [];
386
641
  try {
387
- const fetched = await fetchSectionCompositionEntries(config, missing, options);
388
- for (const s of fetched)
389
- map.set(s.uid, s);
642
+ fetched = await fetchSectionCompositionEntries(config, toFetch, options);
390
643
  }
391
644
  catch (err) {
392
645
  if (process.env.NODE_ENV === "development") {
393
- console.error("getAllSectionCompositions: fallback fetch failed", err);
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
+ }
394
668
  }
395
669
  }
396
670
  }
@@ -504,6 +778,210 @@ function resolveSeoBindingValue(staticValue, binding, specData) {
504
778
  }
505
779
  return String(resolved);
506
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
+ }
507
985
  /**
508
986
  * Helper function to detect and classify API errors
509
987
  * @internal - Exported for testing purposes
@@ -1595,6 +2073,65 @@ function generateSdk(userConfig) {
1595
2073
  mergedTemplateOnly.push([newParent, remappedChild]);
1596
2074
  }
1597
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
+ }
1598
2135
  const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
1599
2136
  // A deep reference that lives inside a section slot only assembles its full
1600
2137
  // include[] path in this merged set (the page sees the slot child at the
@@ -1630,135 +2167,23 @@ function generateSdk(userConfig) {
1630
2167
  sectionEntries,
1631
2168
  }, searchParams),
1632
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
+ }
1633
2181
  attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
1634
- // NEW: build per-instance scoped data sources and attach to spec.
1635
- // Convert the sectionEntries array to a Map<compositionUid, entry> for collectAllDataNeeds.
1636
- const sectionEntriesMap = new Map(sectionEntries.map((sec) => [sec.uid, sec]));
2182
+ // Build per-instance scoped data sources (pure) and attach to spec.
1637
2183
  const pageUi = typeof compositionEntry.ui === "string"
1638
2184
  ? decompressSpec(compositionEntry.ui)
1639
2185
  : compositionEntry.ui;
1640
- const { needsBySection } = collectAllDataNeeds(compositionEntry, pageUi, sectionEntriesMap);
1641
- // Build per-section-composition maps of (entryUid -> poolKey) and
1642
- // (queryUid -> stableHash) by re-parsing each section's data_sources.
1643
- // Pool key format matches what setStaticEntryInDS uses: `${ct_uid}:${entry_uid}`.
1644
- const compEntryDsToPoolKey = new Map();
1645
- const compQueryDsToPoolKey = new Map();
1646
- for (const sec of sectionEntries) {
1647
- const entryMap = new Map();
1648
- const queryMap = new Map();
1649
- try {
1650
- const parsed = JSON.parse(sec.data_sources ?? "[]");
1651
- const list = Array.isArray(parsed)
1652
- ? parsed
1653
- : Object.values(parsed);
1654
- for (const ds of list) {
1655
- if (ds?.uid === "contentstack") {
1656
- // Support both { data: { entries: [...] } } and legacy { data: [...] } formats.
1657
- const rawEntries = Array.isArray(ds.data?.entries)
1658
- ? ds.data.entries
1659
- : Array.isArray(ds.data)
1660
- ? ds.data
1661
- : [];
1662
- for (const e of rawEntries) {
1663
- const ct = e.content_type_uid ?? e._content_type_uid;
1664
- if (ct && e.uid)
1665
- entryMap.set(e.uid, `${ct}:${e.uid}`);
1666
- }
1667
- }
1668
- if (ds?.uid === "queries" ||
1669
- ds?.uid === DATA_SOURCES.QUERY ||
1670
- ds?.id === DATA_SOURCES.QUERY) {
1671
- const items = Array.isArray(ds.data)
1672
- ? ds.data
1673
- : (ds.data?.queries ?? []);
1674
- for (const q of items) {
1675
- if (q?.uid && q?.spec)
1676
- queryMap.set(q.uid, stableHashQuery(q.spec));
1677
- }
1678
- }
1679
- }
1680
- }
1681
- catch {
1682
- // malformed JSON — skip; already logged in collectAllDataNeeds
1683
- }
1684
- compEntryDsToPoolKey.set(sec.uid, entryMap);
1685
- compQueryDsToPoolKey.set(sec.uid, queryMap);
1686
- }
1687
- // Per-section-composition map of preprocessed `static_value` (key -> value),
1688
- // mirroring the page-level path at lines ~1503. Without this, static_value
1689
- // bindings inside a section subtree fall through at runtime to component
1690
- // defaults — the editor renders them only because it loads the entire
1691
- // section composition (including its static_value) into scope.
1692
- const compStaticValue = new Map();
1693
- for (const sec of sectionEntries) {
1694
- compStaticValue.set(sec.uid, preProcessStaticValues(sec.static_value || {}));
1695
- }
1696
- // Build per-instance pool-key maps from per-section-composition maps.
1697
- const instanceEntryDs = new Map();
1698
- const instanceQueryDs = new Map();
1699
- const instanceStaticValue = new Map();
1700
- walkUiForCompositionMapping(pageUi, (instanceUid, compositionUid) => {
1701
- const e = compEntryDsToPoolKey.get(compositionUid);
1702
- const q = compQueryDsToPoolKey.get(compositionUid);
1703
- const sv = compStaticValue.get(compositionUid);
1704
- if (e)
1705
- instanceEntryDs.set(instanceUid, e);
1706
- if (q)
1707
- instanceQueryDs.set(instanceUid, q);
1708
- if (sv)
1709
- instanceStaticValue.set(instanceUid, sv);
1710
- });
1711
- // data.dataSources.contentstack is already keyed by pool key (`${ct_uid}:${uid}`).
1712
- // Entries by pool key map is the contentstack data source itself.
1713
- const csEntries = data.dataSources?.contentstack ?? {};
1714
- const entriesByKey = new Map(Object.entries(csEntries));
1715
- // Build queriesByKey (hash -> result) by combining page + section query uid->hash maps.
1716
- const queriesByKey = new Map();
1717
- const csQueries = data.dataSources?.contentstack_queries ?? {};
1718
- // Helper: walk a dsUid->hash map, look up result in contentstack_queries by dsUid,
1719
- // then store in queriesByKey keyed by hash.
1720
- const recordQueryFromDsMap = (dsMap) => {
1721
- for (const [dsUid, poolKey] of dsMap.entries()) {
1722
- const q = csQueries[dsUid];
1723
- if (q !== undefined)
1724
- queriesByKey.set(poolKey, q);
1725
- }
1726
- };
1727
- // Page's own queries:
1728
- try {
1729
- const parsed = JSON.parse(compositionEntry.data_sources ?? "[]");
1730
- const list = Array.isArray(parsed)
1731
- ? parsed
1732
- : Object.values(parsed);
1733
- const pageQueryMap = new Map();
1734
- for (const ds of list) {
1735
- if (ds?.uid === "queries" ||
1736
- ds?.uid === DATA_SOURCES.QUERY ||
1737
- ds?.id === DATA_SOURCES.QUERY) {
1738
- const items = Array.isArray(ds.data)
1739
- ? ds.data
1740
- : (ds.data?.queries ?? []);
1741
- for (const q of items) {
1742
- if (q?.uid && q?.spec)
1743
- pageQueryMap.set(q.uid, stableHashQuery(q.spec));
1744
- }
1745
- }
1746
- }
1747
- recordQueryFromDsMap(pageQueryMap);
1748
- }
1749
- catch {
1750
- // ignore — page data_sources already parsed earlier
1751
- }
1752
- for (const [, dsMap] of instanceQueryDs.entries())
1753
- recordQueryFromDsMap(dsMap);
1754
- const scoped = buildScopedDataSources({
1755
- entriesByKey,
1756
- queriesByKey,
1757
- sectionEntryDsToPoolKey: instanceEntryDs,
1758
- sectionQueryDsToPoolKey: instanceQueryDs,
1759
- sectionStaticValueByInstance: instanceStaticValue,
1760
- }, needsBySection, data.dataSources);
1761
- data.section_scoped_data = scoped;
2186
+ data.section_scoped_data = buildSectionScopedData(compositionEntry, pageUi, sectionEntries, data.dataSources);
1762
2187
  return data;
1763
2188
  }
1764
2189
  async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
@@ -1871,6 +2296,51 @@ function generateSdk(userConfig) {
1871
2296
  },
1872
2297
  };
1873
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
+ }
1874
2344
  async function fetchMultipleSpecs(queries, options) {
1875
2345
  if (!config.stackSdk) {
1876
2346
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
@@ -2094,7 +2564,18 @@ function generateSdk(userConfig) {
2094
2564
  return;
2095
2565
  // Merge toggle/binding-driven include paths from resolvedReferences into the query spec.
2096
2566
  // QueryExecutor reads spec.params.include via normalizeReferenceIncludeParam → includeReference().
2097
- const togglePaths = (queriesResolvedRefs[uid] ?? [])
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
+ ]
2098
2579
  .map((p) => p
2099
2580
  .split(".")
2100
2581
  .filter((s) => !/^\d+$/.test(s) && s !== "entries")
@@ -2150,34 +2631,14 @@ function generateSdk(userConfig) {
2150
2631
  function getLightConfig() {
2151
2632
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
2152
2633
  }
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
+ */
2153
2640
  function getSeoMetadata(ui, specData) {
2154
- const seo = ui.metadata.seo;
2155
- if (!seo)
2156
- return null;
2157
- /**
2158
- * Flow:
2159
- * 1. Studio stores SEO in `ui.metadata.seo`.
2160
- * 2. Template entry data is fetched separately into `spec.data`.
2161
- * 3. We merge both here so callers of `specOptions.seo` receive resolved
2162
- * values instead of raw binding-only metadata.
2163
- *
2164
- * Each bindable field (pageTitle, pageDescription, openGraphImage, and
2165
- * every metaProp.value) is run through `resolveSeoBindingValue` so a
2166
- * bound field returns the template entry value, while an unbound field
2167
- * keeps its saved static value.
2168
- */
2169
- return {
2170
- ...seo,
2171
- pageTitle: resolveSeoBindingValue(seo.pageTitle, seo.pageTitleBinding, specData),
2172
- pageDescription: resolveSeoBindingValue(seo.pageDescription, seo.pageDescriptionBinding, specData),
2173
- openGraphImage: resolveSeoBindingValue(seo.openGraphImage, seo.openGraphImageBinding, specData),
2174
- metaProps: (seo.metaProps || []).map((prop) => {
2175
- const resolved = resolveSeoBindingValue(prop.value, prop.binding, specData);
2176
- // Both `value` and `previewValue` reflect the resolved value when the
2177
- // meta prop is bound, so canvas/SSR consumers stay in sync.
2178
- return { ...prop, value: resolved, previewValue: resolved };
2179
- }),
2180
- };
2641
+ return getSeoMetadataPure(ui, specData);
2181
2642
  }
2182
2643
  const sdkSingleton = {
2183
2644
  internal: {
@@ -2188,6 +2649,7 @@ function generateSdk(userConfig) {
2188
2649
  // Once we fetch the data, we need to perform certain operation to store the UI and data.
2189
2650
  // Hence, we moved this to the internal method.
2190
2651
  fetchSpec,
2652
+ fetchCompositionSpecOnly,
2191
2653
  fetchMultipleSpecs,
2192
2654
  fetchData,
2193
2655
  fetchTemplateEntry,
@@ -2291,6 +2753,35 @@ function generateSdk(userConfig) {
2291
2753
  seo: getSeoMetadata(spec.ui, spec.data),
2292
2754
  };
2293
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
+ },
2294
2785
  /**
2295
2786
  * This method is used to get the configuration for the client.
2296
2787
  *
@@ -2627,5 +3118,5 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
2627
3118
  };
2628
3119
  }
2629
3120
 
2630
- export { classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, isTemplateBinding, parseUI, resolveSeoBindingValue };
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 };
2631
3122
  //# sourceMappingURL=sdk.js.map