@contentstack/studio-client 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,11 +21,14 @@ import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
21
21
  import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
22
22
  import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
23
23
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
24
+ import { indexModularBlocks, isModularBlockPath, dropImpliedParents } from '../utils/include-path-rules.js';
24
25
  import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
26
+ import { applyUrlBudget, referencesExceedBudget } from '../utils/query-url-budget.js';
25
27
  import { collectAllDataNeeds, stableHashQuery, parseExternalDataForComponentProps } from './collect-data-needs.js';
26
28
  import { buildScopedDataSources } from './build-scoped-data.js';
27
29
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
28
30
  import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
31
+ import { parseEntryFetchRootKey, TEMPLATE_FETCH_ROOT_KEY, resolveInstanceRootBinding, fetchRootFromBinding, resolveLegacySelectedFieldWithProvenance, isTemplateRootBinding, getRootBindingPath, resolveLegacySelectedField, isPageAbsoluteField, templateFetchRoot } from './section-data.js';
29
32
  import { decompressSpec } from '../studio-internal/dist/utils/spec-compression.js';
30
33
  import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages.default.js';
31
34
 
@@ -145,7 +148,7 @@ function walkUiForCompositionMapping(ui, visit) {
145
148
  visit(node.uid, node.metadata.compositionUID);
146
149
  }
147
150
  if (node.slots && typeof node.slots === "object") {
148
- for (const slotNodes of Object.values(node.slots)) {
151
+ for (const slotNodes of Object.values(node.slots ?? {})) {
149
152
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
150
153
  for (const c of arr)
151
154
  walkUiForCompositionMapping(c, visit);
@@ -242,9 +245,18 @@ function sanitizeFieldPath(path) {
242
245
  * other shape (wrapper chains, cross-CT ref-target binds) keeps the original
243
246
  * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
244
247
  */
245
- function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
248
+ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids, options) {
246
249
  const dropCtUids = new Set(referenceCtUids);
247
250
  const sf = sanitizeFieldPath(selectedField).filter((seg) => !dropCtUids.has(seg));
251
+ // A page-absolute field REPLACES the inherited prefix. The leading-overlap
252
+ // collapse below only catches an absolute path that happens to share a
253
+ // leading segment with its ancestor; one that does not overlap was blindly
254
+ // concatenated, producing e.g. `author.related_block` — a path the referenced
255
+ // content type does not have, which CDA silently drops so the section renders
256
+ // component defaults. Provenance answers this directly instead of guessing
257
+ // from the string. See `isPageAbsoluteField`.
258
+ if (options?.pageAbsolute && sf.length > 0)
259
+ return sf;
248
260
  // Collapse the leading overlap with `ancestorPrefix`. A section whose
249
261
  // `selected_field` is rooted at the PAGE content type re-declares the
250
262
  // ancestor's path FROM THE PAGE ROOT — e.g. nested passthrough sections each
@@ -310,7 +322,7 @@ function mapSectionRepeaterPaths(node, runningPath, map) {
310
322
  }
311
323
  }
312
324
  if (node.slots && typeof node.slots === "object") {
313
- for (const slotNodes of Object.values(node.slots)) {
325
+ for (const slotNodes of Object.values(node.slots ?? {})) {
314
326
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
315
327
  for (const c of arr)
316
328
  mapSectionRepeaterPaths(c, childPath, map);
@@ -358,7 +370,7 @@ function mapSectionSlotSegments(node, runningPath, map) {
358
370
  map.set(node.uid, childPath);
359
371
  }
360
372
  if (node.slots && typeof node.slots === "object") {
361
- for (const slotNodes of Object.values(node.slots)) {
373
+ for (const slotNodes of Object.values(node.slots ?? {})) {
362
374
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
363
375
  for (const c of arr)
364
376
  mapSectionSlotSegments(c, childPath, map);
@@ -417,7 +429,7 @@ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
417
429
  }
418
430
  }
419
431
  if (node.slots && typeof node.slots === "object") {
420
- for (const slotNodes of Object.values(node.slots)) {
432
+ for (const slotNodes of Object.values(node.slots ?? {})) {
421
433
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
422
434
  for (const c of arr)
423
435
  projectCrossBoundaryRepeaterBindings(c, map, onlyOut);
@@ -446,20 +458,23 @@ function projectCrossBoundaryRepeaterBindings(node, map, onlyOut) {
446
458
  * instead of the array → "items.map is not a function").
447
459
  */
448
460
  function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
461
+ const linkedSchemasFor = (compositionUid) => (sectionsByUid.get(compositionUid)?.linked_schemas ||
462
+ []);
463
+ // A Section data that names ANOTHER document (pinned entry / query / repeater)
464
+ // has no page-template path to project, and a cleared root (`null`) has none
465
+ // by definition — both yield "". Otherwise fall through to the legacy ladder,
466
+ // which both this and `resolveInstanceRootBinding` share, so the page-template
467
+ // projection and the Section data can never drift apart.
449
468
  const override = node.metadata?.sectionBindingOverride;
450
- let selectedField = typeof override?.selectedField === "string"
451
- ? override.selectedField
452
- : node.metadata?.selectedField;
453
- if (selectedField == null) {
454
- const linked = (sectionsByUid.get(node.metadata?.compositionUID)
455
- ?.linked_schemas || []);
456
- selectedField =
457
- linked.find((s) => s.content_type_uid === pageContentTypeUid)
458
- ?.selected_field ??
459
- linked[0]?.selected_field ??
460
- "";
461
- }
462
- return selectedField || "";
469
+ if (override && "rootBinding" in override) {
470
+ const root = resolveInstanceRootBinding(node, linkedSchemasFor, pageContentTypeUid);
471
+ if (!isTemplateRootBinding(root))
472
+ return "";
473
+ return getRootBindingPath(root).join(".");
474
+ }
475
+ // Unsanitised on purpose — callers sanitise at the point of use, and an
476
+ // indexed path (`navigation_menu_3[0].menu_subitems`) must survive to them.
477
+ return resolveLegacySelectedField(node, linkedSchemasFor, pageContentTypeUid);
463
478
  }
464
479
  /**
465
480
  * Walks the page UI tree and resolves every section-composition instance's
@@ -471,7 +486,10 @@ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
471
486
  */
472
487
  function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
473
488
  const out = [];
474
- const walk = (node, parentRepeaterUID, ancestorPrefix,
489
+ const walk = (node, parentRepeaterUID,
490
+ // The document `ancestorPrefix` counts from, threaded together with it so a
491
+ // prefix can never travel without its fetch root (ADR 0017).
492
+ inheritedFetchRoot, ancestorPrefix,
475
493
  // Binding field path of the nearest enclosing TEMPLATE-bound Repeater that
476
494
  // hasn't yet been confirmed as a reference. A Repeater's template binding
477
495
  // alone can't be told apart from a plain array; the reference condition-
@@ -493,6 +511,9 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
493
511
  // Children that descend into THIS node's slots inherit `ancestorPrefix`,
494
512
  // extended by this node's reference path when it is a wrapper section.
495
513
  let childPrefix = ancestorPrefix;
514
+ // Always assigned together with `childPrefix` — a prefix is meaningless
515
+ // without the document it counts from (ADR 0017).
516
+ let childFetchRoot = inheritedFetchRoot;
496
517
  let childRepeaterRefField = enclosingRepeaterRefField;
497
518
  let childRefCtUids = refCtUids;
498
519
  // For a wrapper section, the per-section-slot internal Repeater/CB segments
@@ -535,17 +556,53 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
535
556
  node.metadata?.compositionUID &&
536
557
  node.uid) {
537
558
  const compositionUid = node.metadata.compositionUID;
559
+ const linkedSchemasFor = (uid) => (sectionsByUid.get(uid)?.linked_schemas ||
560
+ []);
538
561
  const selectedField = resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid);
539
562
  const override = node.metadata?.sectionBindingOverride;
540
563
  const uidRemapping = override?.uidRemapping ?? node.metadata.uidRemapping ?? {};
564
+ // Resolve the Section data, then decide which document this instance's paths
565
+ // belong to. A root naming ANOTHER document (pinned entry / query)
566
+ // rebases the fetch root for this instance and for everything in its
567
+ // slots — inside such a wrapper, paths really are relative to that
568
+ // document, not to the page entry.
569
+ // Only an EXPLICIT Section data can rebase the document. A section with no
570
+ // stored `rootBinding` derives a template-typed one from its
571
+ // `linked_schemas` — that means "no opinion", so it must inherit the
572
+ // enclosing document rather than reset it to the page template entry.
573
+ // Getting this wrong sends a slot child's include paths to a template
574
+ // entry a freeform page does not have.
575
+ const hasExplicitRoot = !!override &&
576
+ Object.prototype.hasOwnProperty.call(override, "rootBinding");
577
+ const sectionData = hasExplicitRoot
578
+ ? resolveInstanceRootBinding(node, linkedSchemasFor, pageContentTypeUid)
579
+ : undefined;
580
+ const ownFetchRoot = hasExplicitRoot
581
+ ? fetchRootFromBinding(sectionData, {
582
+ key: inheritedFetchRoot.key,
583
+ prefix: ancestorPrefix,
584
+ })
585
+ : { key: inheritedFetchRoot.key, prefix: ancestorPrefix };
586
+ const rebasedDocument = ownFetchRoot.key !== inheritedFetchRoot.key;
587
+ const { provenance } = resolveLegacySelectedFieldWithProvenance(node, linkedSchemasFor, pageContentTypeUid);
588
+ // A rebased document makes the inherited prefix meaningless, so the field
589
+ // is absolute within the new document by construction.
590
+ const fieldIsPageAbsolute = rebasedDocument || isPageAbsoluteField(selectedField, provenance);
591
+ // Paths for a rebased instance count from the new document's own prefix,
592
+ // not from the page-rooted chain we walked in on.
593
+ const effectiveAncestorPrefix = rebasedDocument
594
+ ? ownFetchRoot.prefix
595
+ : ancestorPrefix;
541
596
  out.push({
542
597
  instanceUid: node.uid,
543
598
  compositionUid,
544
599
  selectedField,
545
600
  uidRemapping,
546
601
  parentRepeaterUID,
547
- ancestorPrefix,
602
+ ancestorPrefix: effectiveAncestorPrefix,
548
603
  referenceCtUids: refCtUids,
604
+ fetchRootKey: ownFetchRoot.key,
605
+ fieldIsPageAbsolute,
549
606
  });
550
607
  // A whole-CT wrapper (selectedField "") adds no segment — correct, it
551
608
  // creates no reference hop. A reference-bound wrapper extends the prefix
@@ -554,7 +611,15 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
554
611
  // re-declare an overlapping page-root-absolute selected_field (e.g.
555
612
  // `modular_blocks` → `modular_blocks.ref_block` → `modular_blocks.ref_block`)
556
613
  // does not double-count segments into an invalid include[] path.
557
- childPrefix = extendAncestorPrefix(ancestorPrefix, selectedField);
614
+ // Slot children inherit this wrapper's document. When the wrapper rebased,
615
+ // they inherit the NEW one and the page-rooted chain is dropped; when the
616
+ // wrapper's own field is page-absolute, it replaces rather than extends.
617
+ childFetchRoot = rebasedDocument ? ownFetchRoot : inheritedFetchRoot;
618
+ childPrefix = rebasedDocument
619
+ ? extendAncestorPrefix(ownFetchRoot.prefix, "")
620
+ : fieldIsPageAbsolute
621
+ ? sanitizeFieldPath(selectedField)
622
+ : extendAncestorPrefix(ancestorPrefix, selectedField);
558
623
  // Compute this wrapper's slot-internal context so a section dropped into
559
624
  // a slot buried inside the wrapper's OWN Repeater/CB chain roots at the
560
625
  // full slot path (mirrors the editor's `indexSectionSlotsContext`).
@@ -592,28 +657,28 @@ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
592
657
  metadata: { compositionUID: defaultUid },
593
658
  slots: {},
594
659
  };
595
- walk(synth, nextRepeater, slotSegments
660
+ walk(synth, nextRepeater, childFetchRoot, slotSegments
596
661
  ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
597
662
  : childPrefix, childRepeaterRefField, childRefCtUids, chain);
598
663
  }
599
664
  }
600
665
  if (node.slots && typeof node.slots === "object") {
601
- for (const [slotUid, slotNodes] of Object.entries(node.slots)) {
666
+ for (const [slotUid, slotNodes] of Object.entries(node.slots ?? {})) {
602
667
  const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
603
668
  const slotPrefix = slotSegments
604
669
  ? [...childPrefix, ...(slotSegments.get(slotUid) || [])]
605
670
  : childPrefix;
606
671
  for (const c of arr)
607
- walk(c, nextRepeater, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
672
+ walk(c, nextRepeater, childFetchRoot, slotPrefix, childRepeaterRefField, childRefCtUids, defaultAncestors);
608
673
  }
609
674
  }
610
675
  if (Array.isArray(node.children)) {
611
676
  // children (non-slot) stay in the same scope as this node.
612
677
  for (const c of node.children)
613
- walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
678
+ walk(c, nextRepeater, inheritedFetchRoot, ancestorPrefix, childRepeaterRefField, refCtUids, defaultAncestors);
614
679
  }
615
680
  };
616
- walk(ui, null, [], null, []);
681
+ walk(ui, null, templateFetchRoot(), [], null, []);
617
682
  return out;
618
683
  }
619
684
  async function fetchSectionCompositionEntries(config, sectionUids, options) {
@@ -1594,7 +1659,14 @@ function generateSdk(userConfig) {
1594
1659
  let onlyQuery = [];
1595
1660
  // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1596
1661
  if (!isInsideEditor) {
1597
- const entryProjections = entryUids.map((entry_uid) => staticBindingOnlyQueries[_content_type_uid][entry_uid] || []);
1662
+ // `?.` on the content type: an entry can reach `staticBindingQueries`
1663
+ // with no projection bucket at all (a section rooted at a whole
1664
+ // document asks for every field, so it contributes no only[] keys).
1665
+ // Indexing straight through threw a TypeError here, and because the
1666
+ // whole batch assembly sits inside a try/catch the failure surfaced
1667
+ // as NO REQUEST rather than as an error — the entry was silently
1668
+ // never fetched (E2E DR5.10).
1669
+ const entryProjections = entryUids.map((entry_uid) => staticBindingOnlyQueries[_content_type_uid]?.[entry_uid] || []);
1598
1670
  // An entry with no projection of its own (e.g. bound whole, path {})
1599
1671
  // is fetched with ALL fields; batching it with projected siblings
1600
1672
  // must not narrow it, so one unprojected entry makes the whole batch
@@ -1668,10 +1740,36 @@ function generateSdk(userConfig) {
1668
1740
  if (!config.stackSdk) {
1669
1741
  return;
1670
1742
  }
1671
- const { connected_content_type, compositionQuery, includeQueries, onlyQueries, } = fetchOptions;
1743
+ const { connected_content_type, compositionQuery, includeQueries, onlyQueries: requestedOnlyQueries, } = fetchOptions;
1672
1744
  if (!connected_content_type) {
1673
1745
  return;
1674
1746
  }
1747
+ // A page that binds many sections can push the projection past the Delivery
1748
+ // API's URL limit, which rejects the whole request and costs us the page.
1749
+ // The projection is an optimisation; the reference paths are not. Give up
1750
+ // the projection and accept a larger response rather than losing the entry.
1751
+ const urlBudget = applyUrlBudget({
1752
+ references: includeQueries,
1753
+ only: requestedOnlyQueries,
1754
+ });
1755
+ const onlyQueries = urlBudget.only;
1756
+ // Both of these are for whoever is building the site, not for its logs. The
1757
+ // first says we gave up an optimisation; the second predicts a request that
1758
+ // will fail. Neither is actionable from a production console, and a page
1759
+ // that trips one trips it on every render.
1760
+ if (process.env.NODE_ENV === "development") {
1761
+ if (urlBudget.dropped) {
1762
+ console.warn(`[Studio] Field projection dropped for "${connected_content_type}": ` +
1763
+ `${requestedOnlyQueries.length} only[] parameters would have exceeded ` +
1764
+ `the Delivery API URL limit. Fetching all fields instead — the page is ` +
1765
+ `correct but the response is larger than necessary.`);
1766
+ }
1767
+ if (referencesExceedBudget(includeQueries)) {
1768
+ console.warn(`[Studio] The reference paths for "${connected_content_type}" alone ` +
1769
+ `(${includeQueries.length} include[] parameters) exceed the Delivery ` +
1770
+ `API URL limit. This request is expected to fail with 414.`);
1771
+ }
1772
+ }
1675
1773
  const { fetchComposition: _, fetchTemplateEntry: perQueryFetchTemplateEntry, ...resolvedOptions } = compositionQueryOptions || {};
1676
1774
  // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
1677
1775
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
@@ -2100,11 +2198,35 @@ function generateSdk(userConfig) {
2100
2198
  // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
2101
2199
  // reference chain (W1 → W2 → …) fetches the full nested include depth.
2102
2200
  const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
2103
- const instanceBindings = collectSectionInstanceBindings(typeof compositionEntry.ui === "string"
2201
+ const pageUi = typeof compositionEntry.ui === "string"
2104
2202
  ? decompressSpec(compositionEntry.ui)
2105
- : compositionEntry.ui, sectionsByUid, connectedContentTypeUid);
2203
+ : compositionEntry.ui;
2204
+ const instanceBindings = collectSectionInstanceBindings(pageUi, sectionsByUid, connectedContentTypeUid);
2205
+ // The author's own modular-block choices, used below to drop the include[]
2206
+ // paths the Delivery API discards.
2207
+ const modularBlocks = indexModularBlocks(pageUi);
2106
2208
  const mergedTemplateRefs = [...templateReferencesPath];
2107
2209
  const mergedTemplateOnly = [...templateOnlyKeys];
2210
+ // Include paths for sections whose Section data names a document OTHER than the
2211
+ // page template entry (ADR 0017). Keyed by fetch root so each set flushes to
2212
+ // its own request: `mergedTemplateRefs` above is just the "template" bucket.
2213
+ // Without this the paths are computed correctly and then discarded, and the
2214
+ // section renders structure with no content — references come back as
2215
+ // `{uid, _content_type_uid}` stubs and a repeater over them yields empty rows.
2216
+ const refsByFetchRoot = new Map();
2217
+ const pushForFetchRoot = (key, path) => {
2218
+ if (!path)
2219
+ return;
2220
+ if (key === TEMPLATE_FETCH_ROOT_KEY) {
2221
+ mergedTemplateRefs.push(path);
2222
+ return;
2223
+ }
2224
+ const existing = refsByFetchRoot.get(key);
2225
+ if (existing)
2226
+ existing.push(path);
2227
+ else
2228
+ refsByFetchRoot.set(key, [path]);
2229
+ };
2108
2230
  for (const binding of instanceBindings) {
2109
2231
  const section = sectionsByUid.get(binding.compositionUid);
2110
2232
  if (!section)
@@ -2116,8 +2238,25 @@ function generateSdk(userConfig) {
2116
2238
  // Reference-ancestor placement: when the section sits inside a page
2117
2239
  // Repeater(reference)+reference-ConditionBlock (see
2118
2240
  // composeSectionTemplatePrefix).
2119
- const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
2241
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids, { pageAbsolute: binding.fieldIsPageAbsolute });
2120
2242
  const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
2243
+ const fetchRootKey = binding.fetchRootKey;
2244
+ // Register the fetch root even when the section contributes NO reference
2245
+ // include paths. `pushForFetchRoot` only records a key that carries a
2246
+ // path, and the flush below turns each key into an entry request — so a
2247
+ // section rooted at a pinned entry whose bindings are all scalar
2248
+ // (`{ heading }`) named a document nobody ever asked the CDA for. The
2249
+ // pool came back without it, `buildScopedDataSources` logged "no pooled
2250
+ // entry" and the deployed page rendered component defaults while the
2251
+ // editor — which fetches every configured data source regardless of
2252
+ // bindings — rendered it fine (E2E DR5.10). An empty path list means "all
2253
+ // fields": `resolveStaticData` drops the projection for a batch that has
2254
+ // one unprojected entry, which is what a whole-document root wants.
2255
+ if (fetchRootKey && parseEntryFetchRootKey(fetchRootKey)) {
2256
+ if (!refsByFetchRoot.has(fetchRootKey)) {
2257
+ refsByFetchRoot.set(fetchRootKey, []);
2258
+ }
2259
+ }
2121
2260
  const sectionAsCompositionEntry = {
2122
2261
  ...section,
2123
2262
  ui: typeof section.ui === "string"
@@ -2148,7 +2287,7 @@ function generateSdk(userConfig) {
2148
2287
  for (const p of sectionTemplateRefPaths) {
2149
2288
  const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
2150
2289
  if (full)
2151
- mergedTemplateRefs.push(full);
2290
+ pushForFetchRoot(fetchRootKey, full);
2152
2291
  }
2153
2292
  // Include + project EVERY cumulative hop of the composed prefix so each
2154
2293
  // reference in the chain is fetched and the next hop is reachable, e.g.
@@ -2159,9 +2298,31 @@ function generateSdk(userConfig) {
2159
2298
  const acc = [];
2160
2299
  for (const seg of prefix) {
2161
2300
  acc.push(seg);
2162
- mergedTemplateRefs.push(acc.join("."));
2163
- mergedTemplateOnly.push([parent, seg]);
2164
- parent = acc.join(".");
2301
+ const hop = acc.join(".");
2302
+ // Most hops of a section's position are the field holding the blocks,
2303
+ // or a block itself. The Delivery API ignores an include[] for those,
2304
+ // so adding one only costs URL space. The only[] row below is still
2305
+ // wanted either way — it is what keeps the block in the response.
2306
+ //
2307
+ // The block index is read off the PAGE UI, so it can only judge a hop
2308
+ // inside the page template entry. A hop inside another document — a
2309
+ // pinned entry or query the section is rooted at (ADR 0017) — is
2310
+ // routed to that document's request unconditionally.
2311
+ if (fetchRootKey !== TEMPLATE_FETCH_ROOT_KEY ||
2312
+ !isModularBlockPath(hop, modularBlocks)) {
2313
+ pushForFetchRoot(fetchRootKey, hop);
2314
+ }
2315
+ // only[] is carried for the template fetch root only in v1 —
2316
+ // `MergedEntryNeed` has no projection slot, and an only[] union is
2317
+ // SUBTRACTIVE: several sections and the page can request the same
2318
+ // entry with different projections, and a union that misses one
2319
+ // requester silently drops fields. include[] unions are additive and
2320
+ // safe. Pinned entries are already fetched unprojected, so this costs
2321
+ // payload size, not correctness (ADR 0017).
2322
+ if (fetchRootKey === TEMPLATE_FETCH_ROOT_KEY) {
2323
+ mergedTemplateOnly.push([parent, seg]);
2324
+ }
2325
+ parent = hop;
2165
2326
  }
2166
2327
  }
2167
2328
  // Re-parent the section's field projections under the selectedField
@@ -2178,7 +2339,9 @@ function generateSdk(userConfig) {
2178
2339
  ? `${prefix.join(".")}.${remappedParent}`
2179
2340
  : remappedParent;
2180
2341
  }
2181
- mergedTemplateOnly.push([newParent, remappedChild]);
2342
+ if (fetchRootKey === TEMPLATE_FETCH_ROOT_KEY) {
2343
+ mergedTemplateOnly.push([newParent, remappedChild]);
2344
+ }
2182
2345
  }
2183
2346
  }
2184
2347
  // Cross-boundary repeater bindings: a page-authored Repeater/Text bound to a
@@ -2203,10 +2366,7 @@ function generateSdk(userConfig) {
2203
2366
  mapSectionRepeaterPaths(sectionUi, prefix, repeaterPathMap);
2204
2367
  }
2205
2368
  if (repeaterPathMap.size > 0) {
2206
- const pageUiForProjection = typeof compositionEntry.ui === "string"
2207
- ? decompressSpec(compositionEntry.ui)
2208
- : compositionEntry.ui;
2209
- projectCrossBoundaryRepeaterBindings(pageUiForProjection, repeaterPathMap, mergedTemplateOnly);
2369
+ projectCrossBoundaryRepeaterBindings(pageUi, repeaterPathMap, mergedTemplateOnly);
2210
2370
  }
2211
2371
  }
2212
2372
  // ---- D7: fold the template entry into the reference union ----
@@ -2240,7 +2400,46 @@ function generateSdk(userConfig) {
2240
2400
  delete mergedOnly[templateContentTypeUid][knownTemplateUid];
2241
2401
  }
2242
2402
  }
2243
- const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
2403
+ // ---- Flush the non-template fetch roots (ADR 0017) ----
2404
+ // Each key that is not "template" names its own document, so its include
2405
+ // paths belong on THAT document's request. A `<ct>:<uid>` key routes into
2406
+ // `mergedRefs`, which `resolveStaticData` fetches and which already unions
2407
+ // include paths per (ct_uid, entry_uid) across requesters — the page asks
2408
+ // for the entry with its own includes, the section adds more, they merge.
2409
+ //
2410
+ // A `query:<dsUid>` key is not flushed here: query includes are assembled
2411
+ // from `resolvedReferences` inside `resolveQueryData`, so a query-rooted
2412
+ // section contributes through the persisted path (step 9) rather than this
2413
+ // one. Logged rather than dropped silently.
2414
+ for (const [key, paths] of refsByFetchRoot.entries()) {
2415
+ const entryRef = parseEntryFetchRootKey(key);
2416
+ if (!entryRef) {
2417
+ if (process.env.NODE_ENV === "development") {
2418
+ console.warn(`[studio] section include paths for fetch root "${key}" are not routed by the spec fetch; they must come from persisted resolvedReferences. Paths: ${paths.join(", ")}`);
2419
+ }
2420
+ continue;
2421
+ }
2422
+ const { contentTypeUid, entryUid } = entryRef;
2423
+ if (!mergedRefs[contentTypeUid])
2424
+ mergedRefs[contentTypeUid] = {};
2425
+ const existing = mergedRefs[contentTypeUid][entryUid] ?? [];
2426
+ mergedRefs[contentTypeUid][entryUid] = Array.from(new Set([...existing, ...paths]));
2427
+ // Keep the projection map in step. An empty list means "no only[] keys of
2428
+ // its own", which makes the batch unprojected — every field — and that is
2429
+ // what a document-level fetch root wants.
2430
+ if (!mergedOnly[contentTypeUid])
2431
+ mergedOnly[contentTypeUid] = {};
2432
+ if (!mergedOnly[contentTypeUid][entryUid]) {
2433
+ mergedOnly[contentTypeUid][entryUid] = [];
2434
+ }
2435
+ }
2436
+ // Sections, the page itself and the caller's own extra references have all
2437
+ // been merged by this point, so this is the first place we can tell whether
2438
+ // a path is just the start of a longer one. Drop those here, before the
2439
+ // projection patch below, so it sees the paths the request will carry.
2440
+ const dedupedTemplateRefs = dropImpliedParents([
2441
+ ...new Set(mergedTemplateRefs),
2442
+ ]);
2244
2443
  // A deep reference that lives inside a section slot only assembles its full
2245
2444
  // include[] path in this merged set (the page sees the slot child at the
2246
2445
  // wrong depth; the section sees its own reference repeater but not the
@@ -2288,10 +2487,12 @@ function generateSdk(userConfig) {
2288
2487
  }
2289
2488
  attachSectionCompositionContexts(data, compositionEntry, sectionEntries);
2290
2489
  // Build per-instance scoped data sources (pure) and attach to spec.
2291
- const pageUi = typeof compositionEntry.ui === "string"
2292
- ? decompressSpec(compositionEntry.ui)
2293
- : compositionEntry.ui;
2490
+ // `pageUi` is the spec decompressed once, above.
2294
2491
  data.section_scoped_data = buildSectionScopedData(compositionEntry, pageUi, sectionEntries, data.dataSources);
2492
+ // Store the page's dataSources ONCE for section subtrees to read back.
2493
+ // Entering a section replaces `dataSources`, so this is how a section
2494
+ // reaches the outer page's data. By reference — same object, not a copy.
2495
+ data.page_data_sources = data.dataSources;
2295
2496
  return data;
2296
2497
  }
2297
2498
  async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {