@contentstack/studio-client 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/breakpoints/BreakpointManager.js +17 -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 +270 -0
  8. package/dist/composable-studio/collect-data-needs.js.map +1 -0
  9. package/dist/composable-studio/composition-placement.types.js +7 -0
  10. package/dist/composable-studio/composition-placement.types.js.map +1 -0
  11. package/dist/composable-studio/sdk.js +1677 -191
  12. package/dist/composable-studio/sdk.js.map +1 -1
  13. package/dist/composable-studio/studio-intelligence.manager.js +1 -12
  14. package/dist/composable-studio/studio-intelligence.manager.js.map +1 -1
  15. package/dist/config/default-config.js +1 -0
  16. package/dist/config/default-config.js.map +1 -1
  17. package/dist/config/stack-sdk-wrapper.js +85 -0
  18. package/dist/config/stack-sdk-wrapper.js.map +1 -1
  19. package/dist/highlight-node/highlight-node.js +4 -1
  20. package/dist/highlight-node/highlight-node.js.map +1 -1
  21. package/dist/index.d.ts +611 -39
  22. package/dist/index.js +10 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/json-rte-registry/embedded-entry-conversion.js +186 -0
  25. package/dist/json-rte-registry/embedded-entry-conversion.js.map +1 -0
  26. package/dist/json-rte-registry/index.js +73 -33
  27. package/dist/json-rte-registry/index.js.map +1 -1
  28. package/dist/json-rte-registry/stack-sdk-store.js +10 -0
  29. package/dist/json-rte-registry/stack-sdk-store.js.map +1 -0
  30. package/dist/node_modules/fflate/esm/browser.js +1 -7
  31. package/dist/node_modules/fflate/esm/browser.js.map +1 -1
  32. package/dist/packages/studio-internal/dist/utils/section-slot-walker.js +63 -0
  33. package/dist/packages/studio-internal/dist/utils/section-slot-walker.js.map +1 -0
  34. package/dist/query/query-executor.js +182 -27
  35. package/dist/query/query-executor.js.map +1 -1
  36. package/dist/url-metadata/build-template-query.js +124 -0
  37. package/dist/url-metadata/build-template-query.js.map +1 -0
  38. package/dist/url-metadata/parse-url-metadata.js +75 -0
  39. package/dist/url-metadata/parse-url-metadata.js.map +1 -0
  40. package/dist/url-metadata/rank-url-matches.js +100 -0
  41. package/dist/url-metadata/rank-url-matches.js.map +1 -0
  42. package/dist/url-metadata/select-url-winner.js +45 -0
  43. package/dist/url-metadata/select-url-winner.js.map +1 -0
  44. package/dist/url-metadata/shouldUseUrlMetadataPath.js +22 -0
  45. package/dist/url-metadata/shouldUseUrlMetadataPath.js.map +1 -0
  46. package/dist/url-metadata/types.js +50 -0
  47. package/dist/url-metadata/types.js.map +1 -0
  48. package/dist/url-metadata/url-pattern-matcher.js +311 -0
  49. package/dist/url-metadata/url-pattern-matcher.js.map +1 -0
  50. package/dist/utils/build-composition-fetch-query.js +19 -0
  51. package/dist/utils/build-composition-fetch-query.js.map +1 -0
  52. package/dist/utils/canvas.js +14 -0
  53. package/dist/utils/canvas.js.map +1 -1
  54. package/dist/utils/constants.js +19 -2
  55. package/dist/utils/constants.js.map +1 -1
  56. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js +11 -1
  57. package/dist/utils/convertCompositionQueryInputToCompositionQuery.js.map +1 -1
  58. package/dist/utils/editor-utils.js +9 -0
  59. package/dist/utils/editor-utils.js.map +1 -1
  60. package/dist/utils/is-composition-being-edited.js.map +1 -1
  61. package/dist/utils/query-param.js +1 -1
  62. package/dist/utils/query-param.js.map +1 -1
  63. package/dist/utils/reference_fetcher.js +60 -5
  64. package/dist/utils/reference_fetcher.js.map +1 -1
  65. package/dist/utils/sdk.js +16 -1
  66. package/dist/utils/sdk.js.map +1 -1
  67. package/dist/utils/spec-analyzer.js +21 -4
  68. package/dist/utils/spec-analyzer.js.map +1 -1
  69. package/package.json +7 -10
  70. package/dist/get-composition-from-slug/get-composition-from-slug.js +0 -59
  71. package/dist/get-composition-from-slug/get-composition-from-slug.js.map +0 -1
  72. package/dist/utils/get-url-patterns.js +0 -40
  73. package/dist/utils/get-url-patterns.js.map +0 -1
@@ -1,19 +1,27 @@
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 { pick, get } 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, entriesFromResponse, setStaticEntryInDS, getBindingStringForCS } from '../utils/sdk.js';
9
9
  import { ComposableStudioError, ComposableStudioErrors } from '../utils/composable-studio-error.js';
10
10
  import { clientRendererModeUtil, RendererModeUtil } from '../utils/canvas.js';
11
11
  import { analyzeUsedComponents } from '../utils/spec-analyzer.js';
12
12
  import { convertCompositionQueryInputToCompositionQuery } from '../utils/convertCompositionQueryInputToCompositionQuery.js';
13
13
  import { getErrorMessage, getTroubleshootingInfo } from '../utils/error-messages.js';
14
- import { getUrlPatterns } from '../utils/get-url-patterns.js';
14
+ import { getPageLinkedPlacementFilter } from '../utils/build-composition-fetch-query.js';
15
+ import { resolveByUrlSource } from '../url-metadata/build-template-query.js';
16
+ import { parseUrlMetadata } from '../url-metadata/parse-url-metadata.js';
17
+ import { rankUrlMatches } from '../url-metadata/rank-url-matches.js';
18
+ import { selectUrlWinner } from '../url-metadata/select-url-winner.js';
19
+ import { COMPOSITION_PREVIEW_URL_SOURCES } from '../url-metadata/types.js';
20
+ import { matchCompositionUrl } from '../url-metadata/url-pattern-matcher.js';
15
21
  import { getStatusCode, isContentstackAuthError, hasAuthErrorShape, isAuthError, isNetworkError, HttpStatus, ContentstackErrorCode, isServerError } from '../utils/http-error.constants.js';
16
- import { getEntriesQueries } from '../utils/reference_fetcher.js';
22
+ import { getEntriesQueries, projectIncludePathsOntoOnlyKeys, getSchemaPath } from '../utils/reference_fetcher.js';
23
+ import { parseExternalDataForComponentProps, collectAllDataNeeds, stableHashQuery } from './collect-data-needs.js';
24
+ import { buildScopedDataSources } from './build-scoped-data.js';
17
25
  import { preProcessStaticValues } from './data/pre-process-static-values.js';
18
26
  import { StudioIntelligenceManager } from './studio-intelligence.manager.js';
19
27
  import { decompressSpec } from '../packages/studio-internal/dist/utils/spec-compression.js';
@@ -23,6 +31,371 @@ import { ErrorMessageKey, TroubleshootingInfoKey } from '../utils/error-messages
23
31
  // These include both built-in components AND system components (like "page")
24
32
  // All are registered synchronously during React initialization via getBasicComponents()
25
33
  const INTERNAL_COMPONENT_TYPES = Object.values(INTERNAL_COMPONENTS_NAMES);
34
+ const SECTION_COMPOSITION_NODE_TYPE = "section-composition";
35
+ function findParentRepeaterUidInTree(ui, compositionUID) {
36
+ function traverse(node, nearestRepeaterUID) {
37
+ if (node.type === "section-composition" &&
38
+ node.metadata?.compositionUID === compositionUID) {
39
+ return nearestRepeaterUID;
40
+ }
41
+ const updatedRepeaterUID = node.type === "repeater" ? node.uid : nearestRepeaterUID;
42
+ for (const slotId of Object.keys(node.slots || {})) {
43
+ for (const child of node.slots[slotId] || []) {
44
+ const result = traverse(child, updatedRepeaterUID);
45
+ if (result !== undefined)
46
+ return result;
47
+ }
48
+ }
49
+ return undefined;
50
+ }
51
+ if (!ui)
52
+ return null;
53
+ const result = traverse(ui, null);
54
+ return result !== undefined ? result : null;
55
+ }
56
+ function setSectionCompositionContext(dataSources, sectionUid, selectedField, parentRepeaterUID = null) {
57
+ if (!dataSources["section_compositions"]) {
58
+ dataSources["section_compositions"] = {};
59
+ }
60
+ dataSources["section_compositions"][sectionUid] = {
61
+ selectedField,
62
+ uidRemapping: {},
63
+ parentRepeaterUID,
64
+ };
65
+ }
66
+ function findMatchingSectionSchema(section, templateEntry) {
67
+ const linkedSchemas = section.linked_schemas || [];
68
+ if (!linkedSchemas.length)
69
+ return null;
70
+ if (!templateEntry?._content_type_uid) {
71
+ return linkedSchemas[0] || null;
72
+ }
73
+ return (linkedSchemas.find((schema) => schema.content_type_uid === templateEntry._content_type_uid) || null);
74
+ }
75
+ function resolveSectionContext(section, templateEntry) {
76
+ const matchingSchema = findMatchingSectionSchema(section, templateEntry);
77
+ if (matchingSchema) {
78
+ return { selectedField: matchingSchema.selected_field };
79
+ }
80
+ if (!(section.linked_schemas || []).length) {
81
+ return { selectedField: undefined };
82
+ }
83
+ return null;
84
+ }
85
+ function getTemplateContentTypeForComposition(compositionEntry) {
86
+ if (compositionEntry.connected_content_type) {
87
+ return compositionEntry.connected_content_type;
88
+ }
89
+ if (compositionEntry.place_composition_as === "section" &&
90
+ compositionEntry.linked_schemas?.length) {
91
+ return compositionEntry.linked_schemas[0]?.content_type_uid || "";
92
+ }
93
+ return "";
94
+ }
95
+ function attachSectionCompositionContexts(data, compositionEntry, sectionEntries) {
96
+ const templateEntry = data.dataSources?.[DATA_SOURCES.TEMPLATE];
97
+ if (!templateEntry || Array.isArray(templateEntry))
98
+ return;
99
+ if (compositionEntry.place_composition_as === "section") {
100
+ const ownContext = resolveSectionContext(compositionEntry, templateEntry);
101
+ if (ownContext) {
102
+ setSectionCompositionContext(data.dataSources, compositionEntry.uid, ownContext.selectedField, null);
103
+ }
104
+ }
105
+ const rootUI = compositionEntry.ui ?? null;
106
+ sectionEntries.forEach((sectionEntry) => {
107
+ const sectionContext = resolveSectionContext(sectionEntry, templateEntry);
108
+ if (!sectionContext)
109
+ return;
110
+ const parentRepeaterUID = findParentRepeaterUidInTree(rootUI, sectionEntry.uid);
111
+ setSectionCompositionContext(data.dataSources, sectionEntry.uid, sectionContext.selectedField, parentRepeaterUID);
112
+ });
113
+ }
114
+ /**
115
+ * Walks the UI tree and visits every section-composition node,
116
+ * yielding (instanceUid, compositionUid) pairs for building
117
+ * per-instance scoped data source maps.
118
+ */
119
+ function walkUiForCompositionMapping(ui, visit) {
120
+ if (!ui)
121
+ return;
122
+ const node = ui;
123
+ if (node.type === SECTION_COMPOSITION_NODE_TYPE &&
124
+ node.metadata?.compositionUID &&
125
+ node.uid) {
126
+ visit(node.uid, node.metadata.compositionUID);
127
+ }
128
+ if (node.slots && typeof node.slots === "object") {
129
+ for (const slotNodes of Object.values(node.slots)) {
130
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
131
+ for (const c of arr)
132
+ walkUiForCompositionMapping(c, visit);
133
+ }
134
+ }
135
+ if (Array.isArray(node.children)) {
136
+ for (const c of node.children)
137
+ walkUiForCompositionMapping(c, visit);
138
+ }
139
+ }
140
+ function collectSectionCompositionUIDs(ui, accumulator = new Set()) {
141
+ if (!ui)
142
+ return accumulator;
143
+ if (ui.type === SECTION_COMPOSITION_NODE_TYPE &&
144
+ ui.metadata?.compositionUID) {
145
+ accumulator.add(ui.metadata.compositionUID);
146
+ }
147
+ if (ui.slots && typeof ui.slots === "object") {
148
+ Object.values(ui.slots).forEach((slotNodes) => {
149
+ if (Array.isArray(slotNodes)) {
150
+ slotNodes.forEach((child) => collectSectionCompositionUIDs(child, accumulator));
151
+ }
152
+ else if (slotNodes && typeof slotNodes === "object") {
153
+ collectSectionCompositionUIDs(slotNodes, accumulator);
154
+ }
155
+ });
156
+ }
157
+ if (Array.isArray(ui.children)) {
158
+ ui.children.forEach((child) => collectSectionCompositionUIDs(child, accumulator));
159
+ }
160
+ return accumulator;
161
+ }
162
+ /**
163
+ * Strip a field path down to CDA include[]/only[]-safe segments: drop array
164
+ * indices (`x[0]` → `x`), modular-block numeric prefixes (`2_block` → `block`),
165
+ * pure-numeric segments, and the `entries` array wrapper. Shared by the
166
+ * instance walk (ancestor prefix composition) and the template-ref merge.
167
+ */
168
+ function sanitizeFieldPath(path) {
169
+ return path
170
+ .split(".")
171
+ .map((seg) => seg.replace(/\[\d+\]$/, "").replace(/^\d+_/, ""))
172
+ .filter((seg) => seg.length > 0 && !/^\d+$/.test(seg) && seg !== "entries");
173
+ }
174
+ /**
175
+ * Compose the page-template projection root for a placed section's reference
176
+ * field paths.
177
+ *
178
+ * Normally a section's references are rooted at its page-rooted prefix:
179
+ * `[...ancestorPrefix, ...selectedField]`. But when the section sits inside a
180
+ * page `Repeater(reference)+reference-ConditionBlock`, the enclosing reference
181
+ * is ALREADY in `ancestorPrefix`, and the section's own `selectedField`
182
+ * re-expresses that SAME reference with the target-CT uid tacked on as a
183
+ * discriminator (e.g. `reference.test_purpose`). That ctUid is NOT a data key,
184
+ * and re-appending the reference double-counts it — yielding an invalid CDA
185
+ * only[] key like `reference.reference.test_purpose.title` that the API
186
+ * silently ignores, so the referenced entry's fields (e.g. `title`) never come
187
+ * back and the section renders its component default on the deployed site.
188
+ *
189
+ * When `referenceCtUids` is non-empty (an enclosing reference ConditionBlock
190
+ * was seen), drop those ctUid segments and collapse the leading overlap with
191
+ * `ancestorPrefix`, so the section's fields root at the reference exactly like a
192
+ * page-DIRECT binding does (`only[reference][]=title`). When it is empty, every
193
+ * other shape (wrapper chains, cross-CT ref-target binds) keeps the original
194
+ * `[...ancestorPrefix, ...selectedField]` behavior unchanged.
195
+ */
196
+ function composeSectionTemplatePrefix(ancestorPrefix, selectedField, referenceCtUids) {
197
+ if (referenceCtUids.length === 0) {
198
+ return [...ancestorPrefix, ...sanitizeFieldPath(selectedField)];
199
+ }
200
+ const dropCtUids = new Set(referenceCtUids);
201
+ const sf = sanitizeFieldPath(selectedField).filter((seg) => !dropCtUids.has(seg));
202
+ const remainder = ancestorPrefix.length > 0 &&
203
+ sf.length >= ancestorPrefix.length &&
204
+ ancestorPrefix.every((seg, i) => seg === sf[i])
205
+ ? sf.slice(ancestorPrefix.length)
206
+ : sf;
207
+ return [...ancestorPrefix, ...remainder];
208
+ }
209
+ /**
210
+ * Resolve a section-composition node's effective `selectedField`. Resolution
211
+ * order MUST match the render side (`collect-data-needs`'s declaredField) so
212
+ * the fetch scopes the section against the SAME field the renderer reads:
213
+ * 1. per-instance override on `metadata.sectionBindingOverride`,
214
+ * 2. legacy `metadata.selectedField`,
215
+ * 3. linked_schemas default — the field declared for the page CT, else the
216
+ * first schema's `selected_field`.
217
+ *
218
+ * A repeater-nested section is NOT forced to scope-root: its declared
219
+ * `selected_field` still applies and scopes each iteration item further (e.g. a
220
+ * reference-chain section bound to ct2's `reference_to_ct3` iterates that
221
+ * referenced array per ct2 item). The render side never forced "" here, so
222
+ * forcing it on the fetch side starved exactly those sections of their nested
223
+ * reference data (the internal Repeater then received the bare iteration object
224
+ * instead of the array → "items.map is not a function").
225
+ */
226
+ function resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid) {
227
+ const override = node.metadata?.sectionBindingOverride;
228
+ let selectedField = typeof override?.selectedField === "string"
229
+ ? override.selectedField
230
+ : node.metadata?.selectedField;
231
+ if (selectedField == null) {
232
+ const linked = (sectionsByUid.get(node.metadata?.compositionUID)
233
+ ?.linked_schemas || []);
234
+ selectedField =
235
+ linked.find((s) => s.content_type_uid === pageContentTypeUid)
236
+ ?.selected_field ??
237
+ linked[0]?.selected_field ??
238
+ "";
239
+ }
240
+ return selectedField || "";
241
+ }
242
+ /**
243
+ * Walks the page UI tree and resolves every section-composition instance's
244
+ * effective binding (selectedField + uidRemapping) AND its page-rooted
245
+ * `ancestorPrefix` — the composed reference path of the wrapper sections it is
246
+ * nested inside. The template fetch roots each section's references at
247
+ * `[...ancestorPrefix, ...selectedField]` so nested wrapper chains fetch the
248
+ * full reference depth (W1.selectedField → W2.selectedField → …).
249
+ */
250
+ function collectSectionInstanceBindings(ui, sectionsByUid, pageContentTypeUid) {
251
+ const out = [];
252
+ const walk = (node, parentRepeaterUID, ancestorPrefix,
253
+ // Binding field path of the nearest enclosing TEMPLATE-bound Repeater that
254
+ // hasn't yet been confirmed as a reference. A Repeater's template binding
255
+ // alone can't be told apart from a plain array; the reference condition-
256
+ // block dropped inside it is the signal (mirrors `reference_fetcher`, which
257
+ // only records a repeater ref path at the reference condition-block). When
258
+ // we reach that block we commit this path into the prefix so a section
259
+ // nested in the repeater roots its references under the reference field.
260
+ enclosingRepeaterRefField,
261
+ // Target-CT uids from the enclosing reference ConditionBlock(s) on the path
262
+ // to this node (see SectionInstanceBinding.referenceCtUids).
263
+ refCtUids) => {
264
+ if (!node || typeof node !== "object")
265
+ return;
266
+ const nextRepeater = node.type === "repeater" && node.uid ? node.uid : parentRepeaterUID;
267
+ // Children that descend into THIS node's slots inherit `ancestorPrefix`,
268
+ // extended by this node's reference path when it is a wrapper section.
269
+ let childPrefix = ancestorPrefix;
270
+ let childRepeaterRefField = enclosingRepeaterRefField;
271
+ let childRefCtUids = refCtUids;
272
+ // Remember a Repeater's template binding path; it becomes a reference hop
273
+ // only once a reference condition-block downstream confirms the field is a
274
+ // reference (committed below). A CONTENTSTACK/REPEATER-typed binding is not
275
+ // a page-template reference path, so it never extends the prefix.
276
+ if (node.type === "repeater") {
277
+ const itemsBinding = node.props?.items?.binding;
278
+ childRepeaterRefField =
279
+ itemsBinding?.type === DATA_SOURCES.TEMPLATE
280
+ ? getBindingStringForCS(itemsBinding) || null
281
+ : null;
282
+ }
283
+ // A reference condition-block confirms the enclosing repeater iterates a
284
+ // reference field. Commit that field into the prefix so slotted sections
285
+ // (selectedField "") fetch/project their fields under e.g.
286
+ // `reference_to_ct2`, not the page root. Clear it afterwards so a deeper
287
+ // structure doesn't double-count the same hop.
288
+ if (node.type === "condition-block" &&
289
+ node.metadata?.condition?.type === "reference" &&
290
+ enclosingRepeaterRefField) {
291
+ childPrefix = [
292
+ ...ancestorPrefix,
293
+ ...getSchemaPath(enclosingRepeaterRefField),
294
+ ];
295
+ childRepeaterRefField = null;
296
+ // Record the narrowed target CT so a slotted section can drop this uid
297
+ // from its own selectedField when rooting field projections.
298
+ const cbCtUid = node.metadata?.condition?.value;
299
+ if (typeof cbCtUid === "string" && cbCtUid) {
300
+ childRefCtUids = [...refCtUids, cbCtUid];
301
+ }
302
+ }
303
+ if (node.type === SECTION_COMPOSITION_NODE_TYPE &&
304
+ node.metadata?.compositionUID &&
305
+ node.uid) {
306
+ const compositionUid = node.metadata.compositionUID;
307
+ const selectedField = resolveInstanceSelectedField(node, sectionsByUid, pageContentTypeUid);
308
+ const override = node.metadata?.sectionBindingOverride;
309
+ const uidRemapping = override?.uidRemapping ?? node.metadata.uidRemapping ?? {};
310
+ out.push({
311
+ instanceUid: node.uid,
312
+ compositionUid,
313
+ selectedField,
314
+ uidRemapping,
315
+ parentRepeaterUID,
316
+ ancestorPrefix,
317
+ referenceCtUids: refCtUids,
318
+ });
319
+ // A whole-CT wrapper (selectedField "") adds no segment — correct, it
320
+ // 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)];
323
+ }
324
+ if (node.slots && typeof node.slots === "object") {
325
+ for (const slotNodes of Object.values(node.slots)) {
326
+ const arr = Array.isArray(slotNodes) ? slotNodes : [slotNodes];
327
+ for (const c of arr)
328
+ walk(c, nextRepeater, childPrefix, childRepeaterRefField, childRefCtUids);
329
+ }
330
+ }
331
+ if (Array.isArray(node.children)) {
332
+ // children (non-slot) stay in the same scope as this node.
333
+ for (const c of node.children)
334
+ walk(c, nextRepeater, ancestorPrefix, childRepeaterRefField, refCtUids);
335
+ }
336
+ };
337
+ walk(ui, null, [], null, []);
338
+ return out;
339
+ }
340
+ async function fetchSectionCompositionEntries(config, sectionUids, options) {
341
+ if (!config.stackSdk || sectionUids.length === 0) {
342
+ return [];
343
+ }
344
+ const response = await config.stackSdk
345
+ .ctQuery(config.contentTypeUid, {
346
+ includeAll: true,
347
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
348
+ locale: options?.locale || config.locale,
349
+ })
350
+ .containedIn("uid", sectionUids)
351
+ .find();
352
+ return entriesFromResponse(response).map((entry) => ({
353
+ ...entry,
354
+ ui: typeof entry.ui === "string"
355
+ ? decompressSpec(entry.ui)
356
+ : entry.ui,
357
+ }));
358
+ }
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;
363
+ 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
+ }
373
+ }
374
+ }
375
+ // 2. Find any section-composition UIDs referenced in the UI tree that are
376
+ // missing from `map`. These need a fallback fetch.
377
+ const ui = typeof compositionEntry.ui === "string"
378
+ ? decompressSpec(compositionEntry.ui)
379
+ : 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
+ }
386
+ try {
387
+ const fetched = await fetchSectionCompositionEntries(config, missing, options);
388
+ for (const s of fetched)
389
+ map.set(s.uid, s);
390
+ }
391
+ catch (err) {
392
+ if (process.env.NODE_ENV === "development") {
393
+ console.error("getAllSectionCompositions: fallback fetch failed", err);
394
+ }
395
+ }
396
+ }
397
+ return map;
398
+ }
26
399
  function getAuthErrorMessage(err) {
27
400
  const detail = err?.error_message ||
28
401
  err?.errors?.api_key?.[0] ||
@@ -31,6 +404,106 @@ function getAuthErrorMessage(err) {
31
404
  getErrorMessage(ErrorMessageKey.INVALID_CREDENTIALS_DEFAULT);
32
405
  return getErrorMessage(ErrorMessageKey.AUTHENTICATION_ERROR, { detail });
33
406
  }
407
+ /**
408
+ * SEO bindings are stored in the UI metadata with the same nested `value.path`
409
+ * shape used by the normal data-binding system:
410
+ *
411
+ * { type: "template", value: { path: { title: {} } } }
412
+ *
413
+ * For SEO we only need the final property path as a dot-separated string
414
+ * (`title`, `seo.title`, etc.), so this helper converts the nested path object
415
+ * into a plain path string that can be used with `lodash/get`.
416
+ */
417
+ /**
418
+ * SEO bindings are stored in UI metadata with the nested `value.path` shape
419
+ * used by the rest of the data-binding system:
420
+ *
421
+ * { type: "template", value: { path: { title: {} } } }
422
+ * { type: "template", value: { path: { seo: { title: {} } } } }
423
+ *
424
+ * The path is always a SINGLE-KEY chain at each level — bindings target one
425
+ * leaf field, not multiple siblings. If a multi-key object is encountered
426
+ * (shouldn't happen given how Studio writes these), we warn in dev and pick
427
+ * the first key so SEO doesn't silently break, but the upstream caller should
428
+ * be fixed.
429
+ *
430
+ * Returns a dot-separated path (`"title"`, `"seo.title"`) usable with
431
+ * `lodash/get`, or `""` when the binding has no path.
432
+ */
433
+ function flattenBindingPathFromValue(binding) {
434
+ const path = binding.value
435
+ ?.path;
436
+ if (!path || typeof path !== "object")
437
+ return "";
438
+ const flattenPath = (value) => {
439
+ if (!value)
440
+ return "";
441
+ const keys = Object.keys(value);
442
+ if (keys.length === 0)
443
+ return "";
444
+ if (keys.length > 1 && process.env.NODE_ENV === "development") {
445
+ 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.`);
446
+ }
447
+ const key = keys[0];
448
+ const next = value[key];
449
+ const suffix = next && typeof next === "object"
450
+ ? flattenPath(next)
451
+ : "";
452
+ return suffix ? `${key}.${suffix}` : key;
453
+ };
454
+ return flattenPath(path);
455
+ }
456
+ function isTemplateBinding(binding) {
457
+ return binding.type === DATA_SOURCES.TEMPLATE || binding.type === "template";
458
+ }
459
+ /**
460
+ * Resolve a single SEO field value (`pageTitle`, `pageDescription`,
461
+ * `openGraphImage`, `metaProps[].value`) from either:
462
+ *
463
+ * 1. the static value saved on the composition, or
464
+ * 2. the currently resolved template entry data in `spec.data`
465
+ *
466
+ * Branches:
467
+ * - No binding → keep saved static value.
468
+ * - `static_value` binding → use binding literal (fall back to static).
469
+ * - `template` binding → read template entry at the flattened path.
470
+ * - Otherwise → fall back to static.
471
+ *
472
+ * Returns the resolved primitive as a string. Non-primitive resolved values
473
+ * (which shouldn't happen for SEO fields) fall back to the static value
474
+ * rather than coercing an object to "[object Object]".
475
+ */
476
+ function resolveSeoBindingValue(staticValue, binding, specData) {
477
+ const fallback = (staticValue ?? "").trim();
478
+ if (!binding || typeof binding !== "object" || binding.type == null) {
479
+ return fallback;
480
+ }
481
+ if (binding.type === "static_value" ||
482
+ binding.type === DATA_SOURCES.STATIC_VALUE) {
483
+ return typeof binding.value === "string" && binding.value.trim()
484
+ ? binding.value.trim()
485
+ : fallback;
486
+ }
487
+ if (!specData || !isTemplateBinding(binding)) {
488
+ return fallback;
489
+ }
490
+ const templateEntry = specData.dataSources?.[DATA_SOURCES.TEMPLATE];
491
+ const subPath = flattenBindingPathFromValue(binding);
492
+ if (!templateEntry || !subPath) {
493
+ return fallback;
494
+ }
495
+ const resolved = get(templateEntry, subPath);
496
+ // SEO fields are expected to resolve to a primitive. Anything else (an
497
+ // object, a missing path, an empty string) falls back to the static value
498
+ // so consumers always see a string.
499
+ if (resolved === undefined ||
500
+ resolved === null ||
501
+ resolved === "" ||
502
+ typeof resolved === "object") {
503
+ return fallback;
504
+ }
505
+ return String(resolved);
506
+ }
34
507
  /**
35
508
  * Helper function to detect and classify API errors
36
509
  * @internal - Exported for testing purposes
@@ -357,9 +830,12 @@ function sendInitStudioSignal(config) {
357
830
  sdkFramework: "react",
358
831
  timestamp: Date.now(),
359
832
  globalLocale: config.locale,
360
- globalVariantAlias: undefined, // Config doesn't have variantAlias - handled per query
833
+ globalVariantAlias: config.variantAlias,
361
834
  requestedUrl: window.location.href,
362
835
  uid: `sdk-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
836
+ configPassedToTheSdk: {
837
+ contentTypeUid: config.contentTypeUid,
838
+ },
363
839
  };
364
840
  // Send via Advanced Post Message using static imports
365
841
  composableStudioEventManager
@@ -374,22 +850,168 @@ function sendInitStudioSignal(config) {
374
850
  }
375
851
  function generateSdk(userConfig) {
376
852
  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
853
  if (clientRendererModeUtil.isInsideStudioFrame()) {
382
- const hash = new URLSearchParams(window.location.search).get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
854
+ const sp = new URLSearchParams(window.location.search);
855
+ const hash = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) || "";
383
856
  config.stackSdk.livePreviewQuery?.(hash);
857
+ // Studio is the source of truth for locale/variant when the SDK runs
858
+ // inside its iframe. Overriding the user-supplied config values here
859
+ // means every SDK-side fetch (initial spec, linked-entry references,
860
+ // section fetches) automatically uses the right locale/variant, and
861
+ // both INIT_STUDIO.globalLocale/globalVariantAlias and the per-query
862
+ // GET_COMPOSITION_SPEC payload round-trip them back to Studio.
863
+ const urlLocale = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE);
864
+ if (urlLocale) {
865
+ config.locale = urlLocale;
866
+ }
867
+ const urlVariantAlias = sp.get(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS);
868
+ if (urlVariantAlias) {
869
+ config.variantAlias = urlVariantAlias;
870
+ }
384
871
  }
872
+ if (config.stackSdk)
873
+ setStackSdkInstance(config.stackSdk);
874
+ /**
875
+ * The variant alias every SDK-side data fetch should use, in priority order:
876
+ * 1. The `cs-variant-alias` URL param when running inside Studio — Studio
877
+ * (and the Visual Builder navbar behind it) is the source of truth for the
878
+ * variant being previewed.
879
+ * 2. The per-fetch `options.variantAlias` (host-supplied, e.g. a Personalize
880
+ * alias passed to `fetchSpec`).
881
+ * 3. `config.variantAlias` — the SDK-level default. Inside Studio the init
882
+ * block above already copies `cs-variant-alias` into it, so this also acts
883
+ * as the no-search-param fallback.
884
+ *
885
+ * Centralized because the stack-sdk-wrapper applies a variant ONLY from the
886
+ * per-query option — unlike locale, it has no `config.variantAlias` fallback.
887
+ * So the resolved value must be handed to every fetch explicitly (template
888
+ * entry, bound contentstack entries, and dynamic queries); otherwise a
889
+ * Studio-selected variant renders on the page entry but silently skips all
890
+ * secondary data. Mirrors `resolveLocale`'s studio-search-param-first order.
891
+ */
892
+ /**
893
+ * The search params for the CURRENT fetch. In CSR the SDK fetches in the browser, so
894
+ * they come from `window.location.search`; in SSR the fetch runs server-side where
895
+ * `window` is blind, so the caller threads the forwarded request query string as
896
+ * `searchParams`. Request-scoped — never reads shared mutable state, so concurrent SSR
897
+ * requests cannot clobber one another.
898
+ */
899
+ const getRequestSearchParams = (searchParams) => searchParams ??
900
+ (typeof window !== "undefined"
901
+ ? new URLSearchParams(window.location.search)
902
+ : undefined);
903
+ /**
904
+ * Whether this fetch is rendering the Studio editor preview — the `cs-composable-studio`
905
+ * flag is on the iframe URL. Replaces the `window`-only `isInsideStudioFrame()` in the
906
+ * fetch path so SSR (server-side, `window`-blind) is detected via the forwarded params.
907
+ */
908
+ const isInStudio = (searchParams) => getRequestSearchParams(searchParams)?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ?? false;
909
+ /**
910
+ * Whether this fetch renders inside an editor (Studio OR Visual Builder). Editor fetches
911
+ * widen the query (all fields, no `only` projection). VB is browser-only so it still
912
+ * comes from the global mode util; Studio is searchParams-aware (so it works in SSR).
913
+ */
914
+ const isEditorFetch = (searchParams) => isInStudio(searchParams) ||
915
+ clientRendererModeUtil.isInsideVisualBuilderFrame();
916
+ /**
917
+ * Read a Studio iframe-URL param (locale, variant, template-entry) for the current
918
+ * fetch — the author's live editor choices. Returns undefined outside the editor.
919
+ */
920
+ const readStudioParam = (param, searchParams) => {
921
+ const params = getRequestSearchParams(searchParams);
922
+ if (!params?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED))
923
+ return undefined;
924
+ return params.get(param) || undefined;
925
+ };
926
+ const resolveEffectiveVariantAlias = (optionVariantAlias, searchParams) => {
927
+ const studioVariant = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.VARIANT_ALIAS, searchParams);
928
+ return studioVariant || optionVariantAlias || config.variantAlias;
929
+ };
930
+ /**
931
+ * The locale every SDK-side data fetch should use, in priority order:
932
+ * 1. The `cs-locale` URL param when running inside Studio — Studio is the
933
+ * source of truth for the previewed locale.
934
+ * 2. A URL-pattern `{{locale}}` capture (only known after URL matching, so
935
+ * callers pass it in as `patternLocale`).
936
+ * 3. The per-fetch `options.locale` (`optionLocale`).
937
+ * 4. `config.locale` — the SDK-level default (also overridden with `cs-locale`
938
+ * inside Studio by the init block above).
939
+ * 5. `config.stackSdk.locale` — the underlying delivery stack's own configured
940
+ * locale (its `_locale`/`Stack({ locale })`). Makes the stack-locale floor
941
+ * *explicit* rather than relying on the delivery SDK's implicit auto-apply
942
+ * (the TS SDK auto-applies it; the legacy JS SDK applies none) — so behavior
943
+ * is deterministic across SDK flavors. When all tiers are empty the locale is
944
+ * omitted and the CMS returns its master copy (with `include_fallback`).
945
+ *
946
+ * Mirrors resolveEffectiveVariantAlias. Centralized so the template entry, bound
947
+ * contentstack entries, and dynamic queries all resolve locale identically —
948
+ * previously only the template entry saw the URL-pattern locale; the secondary
949
+ * fetches dropped it.
950
+ */
951
+ const resolveLocale = (patternLocale, optionLocale, searchParams) => {
952
+ const studioLocale = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.LOCALE, searchParams);
953
+ return (studioLocale ||
954
+ patternLocale ||
955
+ optionLocale ||
956
+ config.locale ||
957
+ config.stackSdk?.locale);
958
+ };
959
+ /**
960
+ * Resolve the URL-pattern locale for a composition ONCE per fetch, and return
961
+ * the `matchResult` so fetchTemplateEntry can reuse it instead of re-matching.
962
+ *
963
+ * The locale is captured by matching the requested URL against the
964
+ * composition's `url_metadata` pattern (a `{{locale}}` placeholder). Hoisting
965
+ * it here lets fetchData hand the captured locale to the bound-entry and
966
+ * dynamic-query fetches too — previously only the template entry saw it. Locale
967
+ * is safe to vary per URL because Contentstack fallback always terminates at
968
+ * master, so an unpublished locale yields the master copy (never empty/stale).
969
+ *
970
+ * Environment is deliberately NOT resolved here. Unlike locale it has no
971
+ * fallback, so a per-URL environment that diverges from where the composition
972
+ * is published would serve a split/stale snapshot. Environment is the
973
+ * connection (SDK-init) environment, applied uniformly to composition AND data
974
+ * — see ADR-0002 §Environment.
975
+ *
976
+ * Returns no locale for the templateEntryUid path, the direct
977
+ * content_type_url_pattern source, and legacy compositions (no `{{...}}`
978
+ * captures there).
979
+ */
980
+ const resolveUrlPatternContext = (compositionEntry, compositionQuery, connectedContentType) => {
981
+ const empty = {
982
+ matchResult: undefined,
983
+ patternLocale: undefined,
984
+ };
985
+ const parsedMetadata = compositionEntry.url_metadata
986
+ ? parseUrlMetadata(compositionEntry.url_metadata)
987
+ : null;
988
+ const url = "url" in compositionQuery ? compositionQuery.url : undefined;
989
+ if (!parsedMetadata ||
990
+ !url ||
991
+ !compositionEntry.url ||
992
+ parsedMetadata.url_source ===
993
+ COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
994
+ return empty;
995
+ }
996
+ const matchResult = matchCompositionUrl(url, compositionEntry.url, compositionEntry.composable_uid, {
997
+ includeReferences: parsedMetadata.url_queries?.include,
998
+ connected_content_type: connectedContentType,
999
+ });
1000
+ return {
1001
+ matchResult,
1002
+ patternLocale: matchResult.matched
1003
+ ? matchResult.variables?.metadata?.locale
1004
+ : undefined,
1005
+ };
1006
+ };
385
1007
  isSdkInitDebugEnabled();
386
1008
  // REMOVED: sendSDKInitializedSignal - replaced by INIT_STUDIO via Advanced Post Message
387
1009
  // The raw postMessage approach has been consolidated into the proven INIT_STUDIO system
388
1010
  // REMOVED: initiateStudioHandshake - no longer needed with Advanced Post Message
389
1011
  // The INIT_STUDIO system via composableStudioEventManager handles reliable delivery
390
- async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}) {
1012
+ async function resolveStaticData(staticBindingQueries, staticBindingOnlyQueries, data, options = {}, searchParams) {
391
1013
  const { variantAlias, locale } = options;
392
- const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
1014
+ const isInsideEditor = isEditorFetch(searchParams);
393
1015
  try {
394
1016
  const promises = [];
395
1017
  for (const _content_type_uid in staticBindingQueries) {
@@ -397,8 +1019,8 @@ function generateSdk(userConfig) {
397
1019
  for (const entry_uid in staticBindingQueries[_content_type_uid]) {
398
1020
  const references = staticBindingQueries[_content_type_uid][entry_uid];
399
1021
  let onlyQuery = [];
400
- // When inside Visual Builder, fetch all fields (don't use onlyQueries)
401
- if (!isInsideVB) {
1022
+ // When inside Studio or Visual Builder, fetch all fields (don't use onlyQueries)
1023
+ if (!isInsideEditor) {
402
1024
  onlyQuery =
403
1025
  staticBindingOnlyQueries[_content_type_uid][entry_uid] || [];
404
1026
  // We need locale for redirect to the correct locale.
@@ -456,7 +1078,7 @@ function generateSdk(userConfig) {
456
1078
  * When composition is binded to a content type, we need to fetch the entry for that content type. Called template entry.
457
1079
  * Supports custom fetcher overrides (per-query > global > SDK default).
458
1080
  */
459
- async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions) {
1081
+ async function fetchTemplateEntry(fetchOptions, data, compositionEntry, compositionQueryOptions, urlPatternContext, searchParams) {
460
1082
  if (!config.stackSdk) {
461
1083
  return;
462
1084
  }
@@ -468,11 +1090,147 @@ function generateSdk(userConfig) {
468
1090
  // Safe access to enhanced options (available only when SDK provides Studio Intelligence)
469
1091
  const enhancedOptions = compositionQueryOptions; // Type assertion for internal properties
470
1092
  const _studioIntelligence = enhancedOptions?._studioIntelligence;
471
- const _enhancementMode = enhancedOptions?._enhancementMode;
472
1093
  const isInsideVB = clientRendererModeUtil.isInsideVisualBuilderFrame();
473
- const isInsideStudio = clientRendererModeUtil.isInsideStudioFrame();
474
- const isStudioAware = _enhancementMode === "studio-aware";
1094
+ // searchParams-aware so the all-fields projection (the `only`-suppression gates below)
1095
+ // fires for an SSR editor fetch, where the window-based util would report false.
1096
+ const isInsideStudio = isInStudio(searchParams);
1097
+ // Studio override: when running inside Studio and the iframe URL carries
1098
+ // `cs-template-entry-uid`, prefer it over any host-passed `templateEntryUid`.
1099
+ // This lets the user pick a preview entry from Studio's navbar that
1100
+ // overrides a host-hardcoded UID, while leaving the host's behaviour intact
1101
+ // in production (the param is only honored when isInsideStudio).
1102
+ //
1103
+ const studioOverride = readStudioParam(COMPOSABLE_STUDIO_QUERY_PARAM.TEMPLATE_ENTRY_UID, searchParams);
1104
+ if (studioOverride) {
1105
+ resolvedOptions.templateEntryUid = studioOverride;
1106
+ }
1107
+ // Locale/variant resolution is shared across all SDK fetches — see
1108
+ // resolveEffectiveVariantAlias (studio `cs-variant-alias` > per-fetch option > config).
1109
+ const resolveVariant = () => resolveEffectiveVariantAlias(resolvedOptions.variantAlias, searchParams);
475
1110
  const defaultImpl = async () => {
1111
+ // Resolution priority: templateEntryUid > url_metadata path > legacy path
1112
+ if (resolvedOptions.templateEntryUid) {
1113
+ // Enhanced include queries with Studio Intelligence
1114
+ const allIncludeQueries = [
1115
+ ...includeQueries,
1116
+ ...(_studioIntelligence?.includeReferences || []),
1117
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
1118
+ const queryOptions = {
1119
+ references: allIncludeQueries,
1120
+ variantAlias: resolveVariant(),
1121
+ // No URL pattern in this branch — pattern locale is N/A.
1122
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
1123
+ };
1124
+ // Smart 'only' parameter handling - only apply in production
1125
+ if (!isInsideVB && !isInsideStudio) {
1126
+ queryOptions.only = onlyQueries;
1127
+ }
1128
+ let dataQuery = config.stackSdk
1129
+ .ctQuery(connected_content_type, queryOptions)
1130
+ .limit(1);
1131
+ dataQuery = config.stackSdk.where(dataQuery, "uid", resolvedOptions.templateEntryUid);
1132
+ const response = await dataQuery.find().catch((err) => {
1133
+ const { errorType, message } = classifyApiError(err);
1134
+ const finalErrorType = errorType === ComposableStudioErrors.COMPOSITION_NOT_FOUND
1135
+ ? ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1136
+ : errorType;
1137
+ throw new ComposableStudioError(finalErrorType, finalErrorType ===
1138
+ ComposableStudioErrors.FETCHING_CONNECTED_DATA_FAILED
1139
+ ? getErrorMessage(ErrorMessageKey.FETCHING_CONNECTED_DATA_FAILED)
1140
+ : message, {
1141
+ options: fetchOptions,
1142
+ response: err,
1143
+ statusCode: err?.status || err?.statusCode,
1144
+ errorCode: err?.error_code,
1145
+ });
1146
+ });
1147
+ const entries = entriesFromResponse(response);
1148
+ if (!entries?.[0]) {
1149
+ throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
1150
+ contentType: connected_content_type,
1151
+ }), {
1152
+ contentType: connected_content_type,
1153
+ hasStackSdk: !!config.stackSdk,
1154
+ compositionQuery,
1155
+ options: fetchOptions,
1156
+ troubleshootingInfo: getTroubleshootingInfo(TroubleshootingInfoKey.PREVIEW_ENTRY_NOT_FOUND),
1157
+ });
1158
+ }
1159
+ return entries[0];
1160
+ }
1161
+ // Check if we should use url_metadata path
1162
+ const parsedMetadata = compositionEntry.url_metadata
1163
+ ? parseUrlMetadata(compositionEntry.url_metadata)
1164
+ : null;
1165
+ if (parsedMetadata && "url" in compositionQuery && compositionQuery.url) {
1166
+ // Metadata path: resolve using url_queries + extracted variables
1167
+ try {
1168
+ // Enhanced include queries with Studio Intelligence
1169
+ const allIncludeQueries = [
1170
+ ...includeQueries,
1171
+ ...(_studioIntelligence?.includeReferences || []),
1172
+ ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
1173
+ // Smart 'only' parameter handling for onlyQueries
1174
+ const finalOnlyQueries = !isInsideVB && !isInsideStudio ? onlyQueries : undefined;
1175
+ if (parsedMetadata.url_source ===
1176
+ COMPOSITION_PREVIEW_URL_SOURCES.CONTENT_TYPE_URL_PATTERN) {
1177
+ // content_type_url_pattern: Direct URL match (no pattern variables).
1178
+ let directQuery = config.stackSdk
1179
+ .ctQuery(connected_content_type, {
1180
+ references: allIncludeQueries,
1181
+ variantAlias: resolveVariant(),
1182
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
1183
+ only: finalOnlyQueries,
1184
+ })
1185
+ .limit(1);
1186
+ directQuery = config.stackSdk.where(directQuery, "url", compositionQuery.url);
1187
+ const response = await directQuery.find();
1188
+ const entries = entriesFromResponse(response);
1189
+ if (entries?.[0]) {
1190
+ return entries[0];
1191
+ }
1192
+ }
1193
+ else {
1194
+ // Other sources: Use template matching + extracted variables
1195
+ if (!compositionEntry.url) {
1196
+ throw new Error("Composition entry missing URL pattern for template matching");
1197
+ }
1198
+ // Match the composition URL pattern to extract variables. Reuse the
1199
+ // match fetchData already computed for the whole page
1200
+ // (resolveUrlPatternContext) when provided — same inputs, so this is
1201
+ // a true resolve-once rather than a second identical match.
1202
+ const matchResult = urlPatternContext?.matchResult ??
1203
+ matchCompositionUrl(compositionQuery.url, compositionEntry.url, compositionEntry.composable_uid, {
1204
+ includeReferences: parsedMetadata.url_queries?.include,
1205
+ connected_content_type,
1206
+ });
1207
+ if (matchResult.matched && matchResult.variables) {
1208
+ const patternMetadata = matchResult.variables.metadata;
1209
+ // Build query using extracted variables and metadata
1210
+ const templateQuery = resolveByUrlSource(config.stackSdk, parsedMetadata.url_source, compositionQuery, matchResult.variables, parsedMetadata.url_queries, connected_content_type, {
1211
+ references: allIncludeQueries,
1212
+ variantAlias: resolveVariant(),
1213
+ locale: resolveLocale(patternMetadata.locale, resolvedOptions.locale, searchParams),
1214
+ branch: patternMetadata.branch,
1215
+ // environment intentionally omitted: it is the connection
1216
+ // (SDK-init) env, uniform across composition + data. Per-URL
1217
+ // {{environment}} has no fallback and would split the snapshot
1218
+ // (see ADR-0002 §Environment).
1219
+ only: finalOnlyQueries,
1220
+ });
1221
+ const response = await templateQuery.find();
1222
+ const entries = entriesFromResponse(response);
1223
+ if (entries?.[0]) {
1224
+ return entries[0];
1225
+ }
1226
+ }
1227
+ }
1228
+ }
1229
+ catch (metadataError) {
1230
+ console.warn("Metadata template resolution failed, falling back to legacy:", metadataError);
1231
+ }
1232
+ }
1233
+ // Legacy path: Original implementation
476
1234
  // Enhanced include queries with Studio Intelligence
477
1235
  const allIncludeQueries = [
478
1236
  ...includeQueries,
@@ -480,23 +1238,21 @@ function generateSdk(userConfig) {
480
1238
  ].filter((v, i, arr) => arr.indexOf(v) === i); // Remove duplicates
481
1239
  const queryOptions = {
482
1240
  references: allIncludeQueries,
483
- variantAlias: resolvedOptions.variantAlias,
484
- locale: resolvedOptions.locale || config.locale,
1241
+ variantAlias: resolveVariant(),
1242
+ // No URL pattern in this branch — pattern locale is N/A. Forward
1243
+ // searchParams so the SSR editor's cs-locale is honored here too
1244
+ // (window is blind on the server); matches every sibling branch.
1245
+ locale: resolveLocale(undefined, resolvedOptions.locale, searchParams),
485
1246
  };
486
- // Smart 'only' parameter handling - ignore in Visual Builder OR Studio-aware mode
487
- if (!isInsideVB && !(isInsideStudio && isStudioAware)) {
1247
+ // Smart 'only' parameter handling - only apply in production
1248
+ if (!isInsideVB && !isInsideStudio) {
488
1249
  queryOptions.only = onlyQueries;
489
1250
  }
490
- // When Studio-aware: Skip 'only' to fetch all fields for data binding
491
1251
  let dataQuery = config.stackSdk
492
1252
  .ctQuery(connected_content_type, queryOptions)
493
1253
  .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) {
1254
+ // Legacy URL matching (note: this is likely incorrect for patterned URLs as mentioned in plan)
1255
+ if ("url" in compositionQuery && compositionQuery.url) {
500
1256
  dataQuery = config.stackSdk.where(dataQuery, "url", compositionQuery.url);
501
1257
  }
502
1258
  const response = await dataQuery.find().catch((err) => {
@@ -515,19 +1271,6 @@ function generateSdk(userConfig) {
515
1271
  });
516
1272
  });
517
1273
  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
1274
  if (!entries?.[0]) {
532
1275
  throw new ComposableStudioError(ComposableStudioErrors.PREVIEW_ENTRY_NOT_FOUND, getErrorMessage(ErrorMessageKey.PREVIEW_ENTRY_NOT_FOUND, {
533
1276
  contentType: connected_content_type,
@@ -550,7 +1293,7 @@ function generateSdk(userConfig) {
550
1293
  connectedContentType: connected_content_type,
551
1294
  options: resolvedOptions,
552
1295
  includeReferences: includeQueries,
553
- only: isInsideVB ? [] : onlyQueries,
1296
+ only: isInsideStudio || isInsideVB ? [] : onlyQueries,
554
1297
  stackSdk: config.stackSdk.sdk,
555
1298
  defaultFetch: defaultImpl,
556
1299
  });
@@ -576,33 +1319,449 @@ function generateSdk(userConfig) {
576
1319
  if (!isCompositionBeingEdited(fetchOptions?.composableUid || ""))
577
1320
  return;
578
1321
  }
579
- async function fetchData(compositionEntry, queryOptions, options) {
1322
+ async function fetchData(compositionEntry, queryOptions, options, sectionEntries = [], searchParams) {
580
1323
  const { variantAlias, locale } = options || {};
581
- const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, compositionEntry.connected_content_type || "", options);
1324
+ // Read all saved reference include paths from compositionEntry.data_sources.resolvedReferences.
1325
+ // Covers toggle ON paths, directly-bound field paths, and condition block binding paths.
1326
+ // Works in both embedded and standalone modes — compositionEntry is always present.
1327
+ // Restores what the April 9 refactor removed (generateQueryDetails referencePaths) but safely:
1328
+ // resolvedReferences contains only validated reference paths, never inferred tree paths.
1329
+ const rawDataSources = (() => {
1330
+ try {
1331
+ const raw = compositionEntry.data_sources;
1332
+ return Array.isArray(raw)
1333
+ ? raw
1334
+ : Object.values(typeof raw === "string" ? JSON.parse(raw) : (raw ?? {}));
1335
+ }
1336
+ catch {
1337
+ return [];
1338
+ }
1339
+ })();
1340
+ const extendQuery = {
1341
+ ...(options?.extendQuery ?? {}),
1342
+ };
1343
+ // Sanitize resolvedReferences paths before injecting into CDA include[].
1344
+ // Filters: pure numeric segments (picker-tree array indexes like "entries.0.cross_links")
1345
+ // and modular-block numeric prefixes ("2_block_1" → "block_1").
1346
+ // Applied uniformly to contentstack, template, and query DS paths.
1347
+ const sanitizeResolvedPaths = (paths) => [
1348
+ ...new Set(paths
1349
+ .filter((p) => typeof p === "string" && p.trim().length > 0)
1350
+ .map((p) => {
1351
+ const segments = p.split(".").filter(Boolean);
1352
+ const result = [];
1353
+ for (let i = 0; i < segments.length; i++) {
1354
+ const stripped = segments[i].replace(/^\d+_/, ""); // strip modular-block prefix
1355
+ // Skip pure numeric array indexes and "entries" array-wrapper segments —
1356
+ // neither is a valid Contentstack include[] field name.
1357
+ if (/^\d+$/.test(stripped) || stripped === "entries") {
1358
+ continue;
1359
+ }
1360
+ result.push(stripped);
1361
+ }
1362
+ return result.join(".");
1363
+ })
1364
+ .filter((p) => p.length > 0)),
1365
+ ];
1366
+ // Static entries (contentstack DS) → extendQuery[ctUid].includeReferences
1367
+ const csDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.CONTENTSTACK);
1368
+ if (csDS?.resolvedReferences && Array.isArray(csDS.data)) {
1369
+ for (const entry of csDS.data) {
1370
+ const raw = csDS.resolvedReferences[entry.uid] ?? [];
1371
+ const paths = sanitizeResolvedPaths(raw);
1372
+ if (!paths.length)
1373
+ continue;
1374
+ const ct = entry._content_type_uid;
1375
+ if (!extendQuery[ct])
1376
+ extendQuery[ct] = { includeReferences: [] };
1377
+ extendQuery[ct].includeReferences = [
1378
+ ...new Set([...(extendQuery[ct].includeReferences ?? []), ...paths]),
1379
+ ];
1380
+ }
1381
+ }
1382
+ // Template entry (contentstackPreview DS) → extendQuery[connectedContentTypeUid].includeReferences
1383
+ // Now safe to inject because sanitizeResolvedPaths filters out picker-tree
1384
+ // tracking paths (pure numeric indexes) before they reach the CDA query.
1385
+ const connectedContentTypeUid = compositionEntry.connected_content_type || "";
1386
+ const previewDS = rawDataSources.find((ds) => ds.uid === DATA_SOURCES.TEMPLATE);
1387
+ if (previewDS?.resolvedReferences && connectedContentTypeUid) {
1388
+ const previewPaths = sanitizeResolvedPaths(Object.values(previewDS.resolvedReferences).flat());
1389
+ if (previewPaths.length) {
1390
+ if (!extendQuery[connectedContentTypeUid])
1391
+ extendQuery[connectedContentTypeUid] = { includeReferences: [] };
1392
+ extendQuery[connectedContentTypeUid].includeReferences = [
1393
+ ...new Set([
1394
+ ...(extendQuery[connectedContentTypeUid].includeReferences ?? []),
1395
+ ...previewPaths,
1396
+ ]),
1397
+ ];
1398
+ }
1399
+ }
1400
+ const resolvedOptions = { ...options, extendQuery };
1401
+ const { templateReferencesPath, templateOnlyKeys, contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, } = getEntriesQueries(compositionEntry, connectedContentTypeUid, resolvedOptions);
1402
+ // When inside Studio, ensure ALL configured contentstack DS entries are in
1403
+ // contentstackEntriesReferencesPath — not just those with active bindings.
1404
+ // Entries without bindings are still shown in Studio's data picker and must
1405
+ // be fetched with their saved resolvedReferences include paths so that
1406
+ // isResolutionFresh() returns true and Studio skips its own CMA call.
1407
+ if (clientRendererModeUtil.isInsideStudioFrame() &&
1408
+ csDS?.data &&
1409
+ Array.isArray(csDS.data)) {
1410
+ for (const entry of csDS.data) {
1411
+ const { uid, _content_type_uid } = entry;
1412
+ if (!uid || !_content_type_uid)
1413
+ continue;
1414
+ if (contentstackEntriesReferencesPath[_content_type_uid]?.[uid] !==
1415
+ undefined)
1416
+ continue;
1417
+ const paths = sanitizeResolvedPaths(csDS.resolvedReferences?.[uid] ?? []);
1418
+ if (!contentstackEntriesReferencesPath[_content_type_uid]) {
1419
+ contentstackEntriesReferencesPath[_content_type_uid] = {};
1420
+ }
1421
+ contentstackEntriesReferencesPath[_content_type_uid][uid] = paths;
1422
+ // Also ensure the onlyKeys slot exists (empty = fetch all fields, correct for Studio)
1423
+ if (!contentstackEntriesOnlyKeys[_content_type_uid]) {
1424
+ contentstackEntriesOnlyKeys[_content_type_uid] = {};
1425
+ }
1426
+ if (!contentstackEntriesOnlyKeys[_content_type_uid][uid]) {
1427
+ contentstackEntriesOnlyKeys[_content_type_uid][uid] = [];
1428
+ }
1429
+ }
1430
+ }
1431
+ // The page composition's `static_value` lives at the top level; each
1432
+ // section composition's own `static_value` is carried per-instance via
1433
+ // `section_scoped_data[instanceUid].static_value` (built below) and
1434
+ // overlaid by SectionCompositionProvider inside the section subtree. This
1435
+ // keeps section keys scoped to their own subtree — siblings and the page
1436
+ // can't read each other's keys through `data.static_value`.
1437
+ // Surface the page composition's own `external_data` JSON as
1438
+ // `spec.data.component_props`. useDataWithSpec uses this as the fallback
1439
+ // when the consumer's `<StudioComponent componentProps={...} />`
1440
+ // doesn't supply state — and SectionCompositionProvider merges it under
1441
+ // each section's `componentPropsFallback` (page wins per top-level
1442
+ // key). The Studio editor's `useFetchCurrentUI` does the same injection
1443
+ // for the editor canvas; this branch keeps the SDK runtime in sync.
1444
+ const pageExternalProps = parseExternalDataForComponentProps(compositionEntry.data_sources);
582
1445
  const data = {
583
1446
  [DATA_SOURCES_PREFIX]: {},
584
1447
  [DATA_SOURCES.STATIC_VALUE]: preProcessStaticValues(compositionEntry.static_value || {}),
1448
+ ...(pageExternalProps ? { component_props: pageExternalProps } : {}),
585
1449
  };
1450
+ const templateContentTypeUid = getTemplateContentTypeForComposition(compositionEntry);
1451
+ // Resolve the URL-pattern locale ONCE for the whole page, so the bound-entry
1452
+ // and dynamic-query fetches honor a captured {{locale}} — not just the
1453
+ // template entry. (Environment is the connection env, not threaded per-URL —
1454
+ // see resolveUrlPatternContext / ADR-0002 §Environment.)
1455
+ const urlPatternContext = resolveUrlPatternContext(compositionEntry, queryOptions, templateContentTypeUid);
1456
+ const pageLocale = resolveLocale(urlPatternContext.patternLocale, locale, searchParams);
1457
+ // Resolve the effective variant once for the whole page (mirrors pageLocale); the
1458
+ // bound-entry and dynamic-query fetches below share it.
1459
+ const pageVariantAlias = resolveEffectiveVariantAlias(variantAlias, searchParams);
1460
+ // Build merged entry-reference paths covering page + all section data
1461
+ // sources, with unioned include[] per (ct_uid, entry_uid).
1462
+ const mergedRefs = JSON.parse(JSON.stringify(contentstackEntriesReferencesPath));
1463
+ const mergedOnly = JSON.parse(JSON.stringify(contentstackEntriesOnlyKeys));
1464
+ for (const section of sectionEntries) {
1465
+ // SectionCompositionEntry has ui: Node (already parsed). getEntriesQueries
1466
+ // expects ui as a string so decompressSpec can parse it — re-serialize here.
1467
+ const sectionAsCompositionEntry = {
1468
+ ...section,
1469
+ ui: typeof section.ui === "string"
1470
+ ? section.ui
1471
+ : JSON.stringify(section.ui),
1472
+ };
1473
+ const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
1474
+ // Union refs per ct_uid:entry_uid
1475
+ for (const ctUid of Object.keys(sectionRefs.contentstackEntriesReferencesPath)) {
1476
+ if (!mergedRefs[ctUid])
1477
+ mergedRefs[ctUid] = {};
1478
+ for (const entryUid of Object.keys(sectionRefs.contentstackEntriesReferencesPath[ctUid])) {
1479
+ const existing = mergedRefs[ctUid][entryUid] ?? [];
1480
+ const incoming = sectionRefs.contentstackEntriesReferencesPath[ctUid][entryUid];
1481
+ mergedRefs[ctUid][entryUid] = Array.from(new Set([...existing, ...incoming]));
1482
+ }
1483
+ }
1484
+ // Union onlyKeys
1485
+ for (const ctUid of Object.keys(sectionRefs.contentstackEntriesOnlyKeys)) {
1486
+ if (!mergedOnly[ctUid])
1487
+ mergedOnly[ctUid] = {};
1488
+ for (const entryUid of Object.keys(sectionRefs.contentstackEntriesOnlyKeys[ctUid])) {
1489
+ const existing = mergedOnly[ctUid][entryUid] ?? [];
1490
+ const incoming = sectionRefs.contentstackEntriesOnlyKeys[ctUid][entryUid];
1491
+ const seen = new Set(existing.map((p) => p.join("|")));
1492
+ for (const p of incoming) {
1493
+ const sig = p.join("|");
1494
+ if (!seen.has(sig)) {
1495
+ existing.push(p);
1496
+ seen.add(sig);
1497
+ }
1498
+ }
1499
+ mergedOnly[ctUid][entryUid] = existing;
1500
+ }
1501
+ }
1502
+ }
1503
+ // ---- Section template references → page template include/only ----
1504
+ // Each section renders against a scoped slice of the PAGE template entry
1505
+ // (data.dataSources.template, narrowed by selectedField). For a section's
1506
+ // reference fields to resolve at render, the CDA template fetch must pull
1507
+ // them in — remapped from the section's own schema namespace into the page
1508
+ // template namespace via the instance's selectedField (path prefix) and
1509
+ // uidRemapping (per-segment rename). getEntriesQueries(section) above only
1510
+ // contributed the section's *contentstack-entry* refs; its template refs
1511
+ // and field projections were dropped, so section-bound references came back
1512
+ // as bare stubs (or were never requested) and rendered blank standalone.
1513
+ // For nested wrapper chains, each section's references are rooted at its
1514
+ // page-rooted `ancestorPrefix` + its own `selectedField`, so a multi-level
1515
+ // reference chain (W1 → W2 → …) fetches the full nested include depth.
1516
+ const sectionsByUid = new Map(sectionEntries.map((s) => [s.uid, s]));
1517
+ const instanceBindings = collectSectionInstanceBindings(typeof compositionEntry.ui === "string"
1518
+ ? decompressSpec(compositionEntry.ui)
1519
+ : compositionEntry.ui, sectionsByUid, connectedContentTypeUid);
1520
+ const mergedTemplateRefs = [...templateReferencesPath];
1521
+ const mergedTemplateOnly = [...templateOnlyKeys];
1522
+ for (const binding of instanceBindings) {
1523
+ const section = sectionsByUid.get(binding.compositionUid);
1524
+ if (!section)
1525
+ continue;
1526
+ // Page-rooted prefix: enclosing wrapper reference path (ancestorPrefix)
1527
+ // composed with this instance's own selectedField. ancestorPrefix is
1528
+ // already sanitized + page-namespaced (ancestor selectedFields are real
1529
+ // field names), so only the instance's own selectedField is sanitized here.
1530
+ // Reference-ancestor placement: when the section sits inside a page
1531
+ // Repeater(reference)+reference-ConditionBlock (see
1532
+ // composeSectionTemplatePrefix).
1533
+ const prefix = composeSectionTemplatePrefix(binding.ancestorPrefix, binding.selectedField, binding.referenceCtUids);
1534
+ const remapSeg = (seg) => binding.uidRemapping?.[seg] ?? seg;
1535
+ const sectionAsCompositionEntry = {
1536
+ ...section,
1537
+ ui: typeof section.ui === "string"
1538
+ ? section.ui
1539
+ : JSON.stringify(section.ui),
1540
+ };
1541
+ const sectionRefs = getEntriesQueries(sectionAsCompositionEntry, config.contentTypeUid, resolvedOptions);
1542
+ // Section reference include paths: UI-derived (reference conditions) plus
1543
+ // saved toggle paths from the SECTION's own data_sources[template].
1544
+ const sectionTemplateRefPaths = new Set(sectionRefs.templateReferencesPath);
1545
+ try {
1546
+ const sds = Array.isArray(section.data_sources)
1547
+ ? section.data_sources
1548
+ : typeof section.data_sources === "string"
1549
+ ? JSON.parse(section.data_sources)
1550
+ : [];
1551
+ const tmplDS = sds.find((ds) => ds?.uid === DATA_SOURCES.TEMPLATE);
1552
+ if (tmplDS?.resolvedReferences) {
1553
+ for (const p of Object.values(tmplDS.resolvedReferences).flat()) {
1554
+ if (typeof p === "string" && p.trim())
1555
+ sectionTemplateRefPaths.add(p);
1556
+ }
1557
+ }
1558
+ }
1559
+ catch {
1560
+ // malformed section data_sources — fall back to UI-derived refs only
1561
+ }
1562
+ for (const p of sectionTemplateRefPaths) {
1563
+ const full = [...prefix, ...sanitizeFieldPath(p).map(remapSeg)].join(".");
1564
+ if (full)
1565
+ mergedTemplateRefs.push(full);
1566
+ }
1567
+ // Include + project EVERY cumulative hop of the composed prefix so each
1568
+ // reference in the chain is fetched and the next hop is reachable, e.g.
1569
+ // include[]=related_articles, include[]=related_articles.author
1570
+ // only[BASE][]=related_articles, only[related_articles][]=author
1571
+ {
1572
+ let parent = "BASE";
1573
+ const acc = [];
1574
+ for (const seg of prefix) {
1575
+ acc.push(seg);
1576
+ mergedTemplateRefs.push(acc.join("."));
1577
+ mergedTemplateOnly.push([parent, seg]);
1578
+ parent = acc.join(".");
1579
+ }
1580
+ }
1581
+ // Re-parent the section's field projections under the selectedField
1582
+ // subtree so the right fields come back on the referenced entries.
1583
+ for (const [parentKey, child] of sectionRefs.templateOnlyKeys) {
1584
+ const remappedChild = child.split(".").map(remapSeg).join(".");
1585
+ let newParent;
1586
+ if (parentKey === "BASE") {
1587
+ newParent = prefix.length ? prefix.join(".") : "BASE";
1588
+ }
1589
+ else {
1590
+ const remappedParent = parentKey.split(".").map(remapSeg).join(".");
1591
+ newParent = prefix.length
1592
+ ? `${prefix.join(".")}.${remappedParent}`
1593
+ : remappedParent;
1594
+ }
1595
+ mergedTemplateOnly.push([newParent, remappedChild]);
1596
+ }
1597
+ }
1598
+ const dedupedTemplateRefs = [...new Set(mergedTemplateRefs)];
1599
+ // A deep reference that lives inside a section slot only assembles its full
1600
+ // include[] path in this merged set (the page sees the slot child at the
1601
+ // wrong depth; the section sees its own reference repeater but not the
1602
+ // page-authored slot binding). Reconcile here so every merged include[]
1603
+ // segment is projected in only[] at its parent — otherwise the section's
1604
+ // restrictive projection (e.g. only[a.b][]=_content_type_uid) silently
1605
+ // strips the leaf reference and it renders blank.
1606
+ mergedTemplateOnly.push(...projectIncludePathsOntoOnlyKeys(dedupedTemplateRefs, mergedTemplateOnly));
1607
+ const seenOnly = new Set();
1608
+ const dedupedTemplateOnly = mergedTemplateOnly.filter(([p, c]) => {
1609
+ const sig = `${p}|${c}`;
1610
+ if (seenOnly.has(sig))
1611
+ return false;
1612
+ seenOnly.add(sig);
1613
+ return true;
1614
+ });
586
1615
  await Promise.all([
587
1616
  fetchTemplateEntry({
588
- connected_content_type: compositionEntry.connected_content_type || "",
1617
+ connected_content_type: templateContentTypeUid,
589
1618
  compositionQuery: queryOptions,
590
- includeQueries: templateReferencesPath,
591
- onlyQueries: templateOnlyKeys,
1619
+ includeQueries: dedupedTemplateRefs,
1620
+ onlyQueries: dedupedTemplateOnly,
592
1621
  composableUid: compositionEntry.composable_uid,
593
- }, data, compositionEntry, options),
594
- resolveStaticData(contentstackEntriesReferencesPath, contentstackEntriesOnlyKeys, data, {
595
- variantAlias: variantAlias,
596
- locale: locale,
597
- }),
1622
+ }, data, compositionEntry, resolvedOptions, urlPatternContext, searchParams),
1623
+ resolveStaticData(mergedRefs, mergedOnly, data, {
1624
+ variantAlias: pageVariantAlias,
1625
+ locale: pageLocale,
1626
+ }, searchParams),
598
1627
  resolveQueryData(compositionEntry, data, {
599
- variantAlias,
600
- locale: locale || config.locale,
601
- }),
1628
+ variantAlias: pageVariantAlias,
1629
+ locale: pageLocale,
1630
+ sectionEntries,
1631
+ }, searchParams),
602
1632
  ]);
1633
+ 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]));
1637
+ const pageUi = typeof compositionEntry.ui === "string"
1638
+ ? decompressSpec(compositionEntry.ui)
1639
+ : 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;
603
1762
  return data;
604
1763
  }
605
- async function fetchSpec(queryOptions, options, skipComponentLoading = false) {
1764
+ async function fetchSpec(queryOptions, options, skipComponentLoading = false, searchParams) {
606
1765
  if (!config.stackSdk) {
607
1766
  throw new ComposableStudioError(ComposableStudioErrors.STACK_SDK_NOT_AVAILABLE, getErrorMessage(ErrorMessageKey.STACK_SDK_NOT_AVAILABLE));
608
1767
  }
@@ -611,22 +1770,44 @@ function generateSdk(userConfig) {
611
1770
  // Phase 2: Enhance options with Studio Intelligence (preserves user preferences)
612
1771
  const enhancedOptions = StudioIntelligenceManager.enhanceOptionsWithStudioIntelligence(options, studioIntelligence);
613
1772
  // 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);
1773
+ const { compositionEntry, symbolEntries, urlResolution } = await fetchComposition(config, queryOptions, enhancedOptions);
616
1774
  const ui = typeof compositionEntry.ui === "string"
617
1775
  ? decompressSpec(compositionEntry.ui)
618
1776
  : compositionEntry.ui;
1777
+ const sectionEntries = await getAllSectionCompositions(config, compositionEntry, enhancedOptions);
1778
+ const allSymbolEntries = [...symbolEntries];
1779
+ const seenSymbolUids = new Set(symbolEntries.map((symbol) => symbol.uid));
1780
+ for (const sectionEntry of sectionEntries.values()) {
1781
+ getAllSymbols(sectionEntry).forEach((symbol) => {
1782
+ if (seenSymbolUids.has(symbol.uid))
1783
+ return;
1784
+ seenSymbolUids.add(symbol.uid);
1785
+ allSymbolEntries.push(symbol);
1786
+ });
1787
+ }
1788
+ const data = await fetchData(compositionEntry, queryOptions, enhancedOptions, Array.from(sectionEntries.values()), searchParams);
619
1789
  // Lazy loading and SSR validation for production mode
620
1790
  // Skip if called from fetchMultipleSpecs (which handles loading in batch)
621
1791
  const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
622
- if (isProductionMode && ui && !skipComponentLoading) {
1792
+ // 1.3.0 rendering contract: server returns the spec as data only. The
1793
+ // renderer is `"use client"` and runs entirely on the client — that's
1794
+ // where registry-vs-spec validation belongs. Running it server-side
1795
+ // forces consumers to make their registration module server-evaluable,
1796
+ // which means dragging `"use client"` components into the server module
1797
+ // graph — exactly the failure mode the RFC asks us to avoid.
1798
+ const isServer = typeof window === "undefined";
1799
+ if (!isServer && isProductionMode && ui && !skipComponentLoading) {
623
1800
  const componentRegistry = getComponentRegistryInstance();
624
1801
  // SSR VALIDATION: Check if all required components are registered
625
1802
  // Built-in components should be registered automatically when @contentstack/studio-react is imported
626
1803
  const usedComponents = analyzeUsedComponents(ui);
1804
+ const sectionComponentTypes = new Set(sectionEntries.keys());
627
1805
  const missingBuiltInComponents = [];
628
1806
  const missingCustomComponents = [];
629
1807
  usedComponents.forEach((type) => {
1808
+ if (sectionComponentTypes.has(type)) {
1809
+ return;
1810
+ }
630
1811
  if (!componentRegistry.hasComponentLoader(type)) {
631
1812
  if (INTERNAL_COMPONENT_TYPES.includes(type)) {
632
1813
  missingBuiltInComponents.push(type);
@@ -641,21 +1822,12 @@ function generateSdk(userConfig) {
641
1822
  const errorMessage = [
642
1823
  `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
643
1824
  "",
644
- "❌ Built-in components should be automatically available when importing the SDK.",
645
- "This indicates a build, import, or packaging issue.",
646
- "",
647
- "Ensure you're importing from @contentstack/studio-react:",
648
- ' import { useCompositionData } from "@contentstack/studio-react";',
649
- "",
650
- "If using a bundler, verify the package is properly resolved and built.",
651
- "Check for console errors during module import.",
1825
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
1826
+ "If you're seeing this, the package root was either not imported on this code path",
1827
+ "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
652
1828
  "",
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);",
1829
+ "Fix: make sure the package root is imported at least once before fetchSpec runs:",
1830
+ ' import "@contentstack/studio-react";',
659
1831
  ].join("\n");
660
1832
  throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
661
1833
  }
@@ -687,7 +1859,10 @@ function generateSdk(userConfig) {
687
1859
  data,
688
1860
  ui,
689
1861
  compositionEntry,
690
- symbols: symbolEntries,
1862
+ symbols: allSymbolEntries,
1863
+ sectionCompositions: Array.from(sectionEntries.values()),
1864
+ // Studio-only resolution diagnostics (URL metadata path); undefined otherwise.
1865
+ urlResolution,
691
1866
  config: {
692
1867
  ...getLightConfig(),
693
1868
  // Debug information for compatibility checking (type assertion for internal properties)
@@ -702,23 +1877,32 @@ function generateSdk(userConfig) {
702
1877
  }
703
1878
  // Fetch all specs in parallel (skip individual component loading)
704
1879
  const specs = await Promise.all(queries.map((query) => fetchSpec(query, options, true)));
705
- // In production mode, perform union analysis and load components once
1880
+ // In production mode, perform union analysis and load components once.
1881
+ // Gated to client-only — see the equivalent block in `fetchSpec` for the
1882
+ // 1.3.0-contract reasoning (server returns spec as data; validation belongs
1883
+ // on the client where the renderer actually runs).
706
1884
  const isProductionMode = !clientRendererModeUtil.isInsideStudioFrame();
707
- if (isProductionMode) {
1885
+ const isServer = typeof window === "undefined";
1886
+ if (!isServer && isProductionMode) {
708
1887
  const componentRegistry = getComponentRegistryInstance();
709
1888
  // Collect all unique component types from all specs
710
1889
  // Built-in components should be registered automatically when @contentstack/studio-react is imported
711
1890
  const allComponents = new Set();
1891
+ const allSectionComponents = new Set();
712
1892
  specs.forEach((spec) => {
713
1893
  if (spec.ui) {
714
1894
  const components = analyzeUsedComponents(spec.ui);
715
1895
  components.forEach((c) => allComponents.add(c));
716
1896
  }
1897
+ spec.sectionCompositions?.forEach((section) => allSectionComponents.add(section.uid));
717
1898
  });
718
1899
  // SSR VALIDATION: Check if all required components are registered
719
1900
  const missingBuiltInComponents = [];
720
1901
  const missingCustomComponents = [];
721
1902
  allComponents.forEach((type) => {
1903
+ if (allSectionComponents.has(type)) {
1904
+ return;
1905
+ }
722
1906
  if (!componentRegistry.hasComponentLoader(type)) {
723
1907
  if (INTERNAL_COMPONENT_TYPES.includes(type)) {
724
1908
  missingBuiltInComponents.push(type);
@@ -733,21 +1917,12 @@ function generateSdk(userConfig) {
733
1917
  const errorMessage = [
734
1918
  `[Composable Studio SDK] Internal components missing: ${missingBuiltInComponents.join(", ")}`,
735
1919
  "",
736
- "❌ Built-in components should be automatically available when importing the SDK.",
737
- "This indicates a build, import, or packaging issue.",
1920
+ "Built-in components are auto-registered on first import of @contentstack/studio-react.",
1921
+ "If you're seeing this, the package root was either not imported on this code path",
1922
+ "(e.g. a server-only bundle that pulls a subpath but not the root) or was tree-shaken away.",
738
1923
  "",
739
- "Ensure you're importing from @contentstack/studio-react:",
740
- ' import { useCompositionData } from "@contentstack/studio-react";',
741
- "",
742
- "If using a bundler, verify the package is properly resolved and built.",
743
- "Check for console errors during module import.",
744
- "",
745
- "Manual registration workaround:",
746
- ' import { registerComponents, getDefaultDesignTokens } from "@contentstack/studio-react";',
747
- ' import { getBasicComponents } from "@contentstack/studio-react-components";',
748
- "",
749
- " const components = getBasicComponents({ csDesignTokens: getDefaultDesignTokens() });",
750
- " registerComponents(components);",
1924
+ "Fix: make sure the package root is imported at least once before fetchSpec runs:",
1925
+ ' import "@contentstack/studio-react";',
751
1926
  ].join("\n");
752
1927
  throw new ComposableStudioError(ComposableStudioErrors.COMPONENT_NOT_FOUND, errorMessage);
753
1928
  }
@@ -818,38 +1993,93 @@ function generateSdk(userConfig) {
818
1993
  return { entries: [], count: 0 };
819
1994
  }
820
1995
  }
821
- async function resolveQueryData(compositionEntry, data, options) {
822
- if (!compositionEntry.data_sources) {
823
- return;
1996
+ async function resolveQueryData(compositionEntry, data, options, searchParams) {
1997
+ // Parse page data_sources (may be absent — sections may still declare queries).
1998
+ let pageDataSources = [];
1999
+ if (compositionEntry.data_sources) {
2000
+ try {
2001
+ const parsed = JSON.parse(compositionEntry.data_sources);
2002
+ pageDataSources = Array.isArray(parsed)
2003
+ ? parsed
2004
+ : Object.values(parsed);
2005
+ }
2006
+ catch (error) {
2007
+ if (process.env.NODE_ENV === "development") {
2008
+ console.error("Error parsing data sources JSON:", error);
2009
+ }
2010
+ }
824
2011
  }
825
- let dataSources = [];
826
- try {
827
- const parsed = JSON.parse(compositionEntry.data_sources);
828
- dataSources = Array.isArray(parsed) ? parsed : Object.values(parsed);
2012
+ const queriesDS = pageDataSources.find((ds) => ds.uid === DATA_SOURCES.QUERY || ds.id === DATA_SOURCES.QUERY);
2013
+ // Page-side queries (may be empty if page declares no queries).
2014
+ let queries = [];
2015
+ if (queriesDS) {
2016
+ const raw = queriesDS.data || queriesDS.queries || [];
2017
+ if (Array.isArray(raw))
2018
+ queries = raw;
829
2019
  }
830
- catch (error) {
831
- if (process.env.NODE_ENV === "development") {
832
- console.error("Error parsing data sources JSON:", error);
2020
+ // Stable-hash dedup across page queries + section queries.
2021
+ // We also track every uid (alias) that maps to a given hash so the
2022
+ // single resolved result can be fanned out to all of them — section
2023
+ // instances bind by their own data_source uid, which differs from
2024
+ // the page's, and section_scoped_data lookups go via uid.
2025
+ const queryDeduper = new Map();
2026
+ const aliasesByHash = new Map();
2027
+ const seedFromQueries = (items) => {
2028
+ for (const item of items) {
2029
+ if (!item?.spec || !item?.uid)
2030
+ continue;
2031
+ const hash = stableHashQuery(item.spec);
2032
+ if (!queryDeduper.has(hash))
2033
+ queryDeduper.set(hash, item);
2034
+ const aliases = aliasesByHash.get(hash) ?? [];
2035
+ if (!aliases.includes(item.uid))
2036
+ aliases.push(item.uid);
2037
+ aliasesByHash.set(hash, aliases);
2038
+ }
2039
+ };
2040
+ seedFromQueries(queries);
2041
+ // Aggregate resolvedReferences across page + section query data sources.
2042
+ const queriesResolvedRefs = {
2043
+ ...((queriesDS && queriesDS.resolvedReferences) || {}),
2044
+ };
2045
+ for (const sec of options?.sectionEntries ?? []) {
2046
+ try {
2047
+ const parsed = JSON.parse(sec.data_sources);
2048
+ const list = Array.isArray(parsed) ? parsed : Object.values(parsed);
2049
+ const qDs = list.find((d) => d?.uid === DATA_SOURCES.QUERY ||
2050
+ d?.uid === "queries" ||
2051
+ d?.id === DATA_SOURCES.QUERY);
2052
+ if (qDs) {
2053
+ const items = Array.isArray(qDs.data)
2054
+ ? qDs.data
2055
+ : (qDs.data?.queries ?? []);
2056
+ seedFromQueries(items);
2057
+ // Merge section's per-query resolvedReferences as well.
2058
+ if (qDs.resolvedReferences) {
2059
+ Object.assign(queriesResolvedRefs, qDs.resolvedReferences);
2060
+ }
2061
+ }
2062
+ }
2063
+ catch {
2064
+ /* per-section JSON failure already logged in collect-data-needs */
833
2065
  }
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
2066
  }
840
- const queries = queriesDS.data || queriesDS.queries || [];
841
- if (!Array.isArray(queries))
2067
+ const dedupedQueries = Array.from(queryDeduper.values());
2068
+ // Nothing to resolve (neither page nor any section declared a query).
2069
+ if (dedupedQueries.length === 0)
842
2070
  return;
843
2071
  const queryResults = {};
844
- // Build RuntimeContext for expression resolution
845
- // In SDK, use window.location.href for URL params
2072
+ // The request's search params (forwarded `searchParams` in SSR, `window.location.search`
2073
+ // in CSR), resolved once and reused for url.params and the in-Studio check below.
2074
+ const requestParams = getRequestSearchParams(searchParams);
2075
+ const isInsideStudio = requestParams?.has(COMPOSABLE_STUDIO_QUERY_PARAM.ENABLED) ?? false;
2076
+ // Build RuntimeContext for expression resolution. URL params come from the request.
2077
+ // `url.hash` stays window-only — the fragment is never sent to a server, so SSR
2078
+ // (preview and production alike) cannot see it.
846
2079
  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
- }
2080
+ requestParams?.forEach((value, key) => {
2081
+ urlParams[key] = value;
2082
+ });
853
2083
  const context = {
854
2084
  url: {
855
2085
  params: urlParams,
@@ -858,14 +2088,59 @@ function generateSdk(userConfig) {
858
2088
  },
859
2089
  // NO componentProps or user context - expressions only support URL params and time
860
2090
  };
861
- await Promise.all(queries.map(async (queryConfig) => {
2091
+ await Promise.all(dedupedQueries.map(async (queryConfig) => {
862
2092
  const { uid, spec } = queryConfig;
863
2093
  if (!uid || !spec?.contentType)
864
2094
  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;
2095
+ // Merge toggle/binding-driven include paths from resolvedReferences into the query spec.
2096
+ // QueryExecutor reads spec.params.include via normalizeReferenceIncludeParam → includeReference().
2097
+ const togglePaths = (queriesResolvedRefs[uid] ?? [])
2098
+ .map((p) => p
2099
+ .split(".")
2100
+ .filter((s) => !/^\d+$/.test(s) && s !== "entries")
2101
+ .join("."))
2102
+ .filter(Boolean);
2103
+ // When inside Studio, add editor params so the delivery SDK (preview API)
2104
+ // returns unpublished entries and full field metadata — matching CMA richness.
2105
+ // Studio's isResolutionFresh then sees non-empty entries and skips its CMA call.
2106
+ // (isInsideStudio is resolved once for the whole resolveQueryData call above.)
2107
+ const studioParams = isInsideStudio
2108
+ ? {
2109
+ include_publish_details: true,
2110
+ include_unpublished: true,
2111
+ include_fields: true,
2112
+ }
2113
+ : {};
2114
+ const needsMerge = togglePaths.length > 0 || Object.keys(studioParams).length > 0;
2115
+ const mergedSpec = needsMerge
2116
+ ? {
2117
+ ...spec,
2118
+ params: {
2119
+ ...studioParams,
2120
+ ...(spec.params ?? {}),
2121
+ ...(togglePaths.length
2122
+ ? {
2123
+ include: [
2124
+ ...new Set([
2125
+ ...(Array.isArray(spec.params?.include)
2126
+ ? spec.params.include
2127
+ : []),
2128
+ ...togglePaths,
2129
+ ]),
2130
+ ],
2131
+ }
2132
+ : {}),
2133
+ },
2134
+ }
2135
+ : spec;
2136
+ const result = await fetchContentstackData(mergedSpec, context, options);
2137
+ // Fan out result to every uid that resolved to this query spec
2138
+ // (page's data_source uid + each section instance's data_source uid).
2139
+ const hash = stableHashQuery(spec);
2140
+ const aliases = aliasesByHash.get(hash) ?? [uid];
2141
+ for (const alias of aliases) {
2142
+ queryResults[alias] = result;
2143
+ }
869
2144
  }));
870
2145
  if (!data.dataSources[DATA_SOURCES.QUERY]) {
871
2146
  data.dataSources[DATA_SOURCES.QUERY] = {};
@@ -875,8 +2150,34 @@ function generateSdk(userConfig) {
875
2150
  function getLightConfig() {
876
2151
  return pick(config, ["openInStudioButton", "contentTypeUid", "cslp"]);
877
2152
  }
878
- function getSeoMetadata(ui) {
879
- return ui.metadata.seo || null;
2153
+ 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
+ };
880
2181
  }
881
2182
  const sdkSingleton = {
882
2183
  internal: {
@@ -895,11 +2196,36 @@ function generateSdk(userConfig) {
895
2196
  public: {
896
2197
  // Exposing this method for the user to fetch the data.
897
2198
  /**
898
- * This method is used to fetch the composition data for the SSR.
2199
+ * Server-side composition fetcher. Resolves a composition + its bound
2200
+ * data into a `StudioComponentSpecOptions` object you can hand to
2201
+ * `<StudioComponent specOptions={...} />`.
2202
+ *
2203
+ * Pair with `useCompositionData` for CSR; the two cover the same use
2204
+ * cases on different render paths.
2205
+ *
2206
+ * IMPORTANT — this returns the spec options object **directly**, NOT
2207
+ * wrapped in `{ specOptions }`. Destructure accordingly:
899
2208
  *
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.
2209
+ * ```ts
2210
+ * // ✅ Correct
2211
+ * const specOptions = await sdk.fetchCompositionData({ url: "/about", searchQuery: "" });
2212
+ *
2213
+ * // ❌ Wrong — `specOptions` will be undefined
2214
+ * const { specOptions } = await sdk.fetchCompositionData(...);
2215
+ * ```
2216
+ *
2217
+ * There is **no `.public` namespace** on the SDK returned from
2218
+ * `studioSdk.init(...)` — call `sdk.fetchCompositionData(...)`,
2219
+ * not `sdk.public.fetchCompositionData(...)`.
2220
+ *
2221
+ * @param queryOptions - Identifies the composition (`compositionUid`,
2222
+ * `url`, `templateContentTypeUid`, or a combination) PLUS the
2223
+ * server-only `searchQuery` string for forwarding Studio iframe
2224
+ * overrides (locale, variant, preview entry, edit mode).
2225
+ * @param options - Optional modifiers: `variantAlias`, `locale`,
2226
+ * `templateEntryUid`, `extendQuery`, custom fetchers.
2227
+ * @returns `Promise<StudioComponentSpecOptions>` — the resolved spec
2228
+ * options object.
903
2229
  */
904
2230
  fetchCompositionData: async (queryOptions, options) => {
905
2231
  if (!config.stackSdk) {
@@ -910,43 +2236,46 @@ function generateSdk(userConfig) {
910
2236
  const urlSearchParam = new URLSearchParams(searchQuery);
911
2237
  // NOTE: Always keep this before fetching the spec. In SSR, we use the urlSearchParams
912
2238
  // 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
- };
2239
+ //
2240
+ // Only invoke `livePreviewQuery` when the request URL actually carries
2241
+ // a preview hash. Passing an empty string explicitly disables live
2242
+ // preview on the delivery SDK for subsequent requests, which forces
2243
+ // SSR's `fetchSpec` to hit the delivery API even when the stack was
2244
+ // initialised with `live_preview.enable=true`. Skipping the reset
2245
+ // when there's no hash preserves the stack's initialised live-preview
2246
+ // state and matches CSR's `useCompositionData` behaviour, which never
2247
+ // resets the hash between fetches.
2248
+ const previewHash = urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.PREVIEW_HASH) ||
2249
+ urlSearchParam.get(COMPOSABLE_STUDIO_QUERY_PARAM.LIVE_PREVIEW_HASH);
2250
+ if (previewHash) {
2251
+ config.stackSdk.livePreviewQuery(previewHash);
949
2252
  }
2253
+ const rendererModeUtil = new RendererModeUtil(urlSearchParam);
2254
+ // P4.2 (ADR-0005): always fetch and return the spec — uniformly for the
2255
+ // composition-uid and URL cases, whether or not it is being edited. The two
2256
+ // being-edited `null` returns are removed: returning `null` is what put SSR on
2257
+ // the served path (the iframe falls back to `getSpecFromParent` and asks Studio).
2258
+ // With the spec returned, SSR-being-edited now renders through the spec-provided
2259
+ // boundary and hands the spec to Studio via the push path (SDK_SPEC_RESOLVED,
2260
+ // emitted from EditableRendererHelper) — the same way CSR and production fetch.
2261
+ // The credential-less playground is unaffected: it never calls fetchCompositionData
2262
+ // (it uses `getSpecFromParent` directly) and stays on the served path.
2263
+ // Thread the forwarded request query (`searchQuery`) into the fetch so the
2264
+ // server-side resolvers see the author's live editor context (cs-locale,
2265
+ // cs-variant-alias, cs-template-entry-uid) — SSR resolves identically to CSR.
2266
+ // On the client this is the same window-derived context, so CSR is unchanged.
2267
+ const spec = await fetchSpec(compositionQuery, options, false, urlSearchParam);
2268
+ // Echo the resolved editor locale/variant back to Studio so the pushed
2269
+ // `sdkContext` reports the copy the SSR data was actually fetched in (e.g.
2270
+ // fr-fr) rather than the host's empty default — otherwise Studio's
2271
+ // diagnostics warn "rendered en-us" and Stage-2 entry/query adds would use
2272
+ // the wrong copy. Same precedence as the fetch (cs-locale > option >
2273
+ // config), read from the request query.
2274
+ const echoedOptions = {
2275
+ ...options,
2276
+ locale: resolveLocale(undefined, options?.locale, urlSearchParam),
2277
+ variantAlias: resolveEffectiveVariantAlias(options?.variantAlias, urlSearchParam),
2278
+ };
950
2279
  return {
951
2280
  spec,
952
2281
  hasSpec: !!spec.compositionEntry,
@@ -955,11 +2284,11 @@ function generateSdk(userConfig) {
955
2284
  // TODO: @Nilesh - see if we can remove this as this config is already available in the spec.
956
2285
  config: getLightConfig(),
957
2286
  compositionQuery,
958
- options,
2287
+ options: echoedOptions,
959
2288
  searchQuery: urlSearchParam.toString(),
960
2289
  mode: rendererModeUtil.getMode(spec.compositionEntry.composable_uid),
961
2290
  },
962
- seo: getSeoMetadata(spec.ui),
2291
+ seo: getSeoMetadata(spec.ui, spec.data),
963
2292
  };
964
2293
  },
965
2294
  /**
@@ -993,7 +2322,9 @@ const parseUI = (ui) => {
993
2322
  };
994
2323
  function getAllSymbols(compositionEntry) {
995
2324
  const res = [];
996
- const Q = [compositionEntry];
2325
+ const Q = [
2326
+ compositionEntry,
2327
+ ];
997
2328
  while (Q.length > 0) {
998
2329
  const curr = Q.shift();
999
2330
  const symbols = (curr?.symbols || []);
@@ -1005,6 +2336,99 @@ function getAllSymbols(compositionEntry) {
1005
2336
  }
1006
2337
  return res;
1007
2338
  }
2339
+ /** CDA entries page size for the lightweight candidate fetch. */
2340
+ const CANDIDATE_PAGE_SIZE = 100;
2341
+ /** Safety cap on candidate pages (server-side resolution will own this later). */
2342
+ const MAX_CANDIDATE_PAGES = 20;
2343
+ /**
2344
+ * Fetch every page-linked composition (lightweight: url + url_metadata +
2345
+ * composable_uid + connected_content_type) for URL resolution — legacy and
2346
+ * variable, linked and freeform. Section compositions are excluded by the page
2347
+ * placement filter. Paginates with skip/limit; `truncated` is true if the safety
2348
+ * cap is hit.
2349
+ */
2350
+ async function fetchAllPageCompositions(config, locale) {
2351
+ const all = [];
2352
+ for (let page = 0; page < MAX_CANDIDATE_PAGES; page++) {
2353
+ const res = await config.stackSdk
2354
+ .ctQuery(config.contentTypeUid, {
2355
+ locale: locale || config.locale,
2356
+ query: { ...getPageLinkedPlacementFilter() },
2357
+ only: [
2358
+ ["BASE", "url"],
2359
+ ["BASE", "url_metadata"],
2360
+ ["BASE", "composable_uid"],
2361
+ ["BASE", "connected_content_type"],
2362
+ ],
2363
+ })
2364
+ .limit(CANDIDATE_PAGE_SIZE)
2365
+ .skip(page * CANDIDATE_PAGE_SIZE)
2366
+ .find();
2367
+ const batch = entriesFromResponse(res);
2368
+ all.push(...batch);
2369
+ if (batch.length < CANDIDATE_PAGE_SIZE) {
2370
+ return { entries: all, truncated: false };
2371
+ }
2372
+ }
2373
+ return { entries: all, truncated: true };
2374
+ }
2375
+ /**
2376
+ * Decide which composition wins among the ranking's top-tier candidates.
2377
+ *
2378
+ * - Single top-tier candidate → it wins, no probe.
2379
+ * - Multiple → probe each tied *linked* candidate's connected content type (in
2380
+ * parallel) for an entry matching the URL. A freeform candidate (no content
2381
+ * type) is unconditionally valid. The first valid candidate in fetch order
2382
+ * wins; a residual multi-owner case is a content mistake surfaced by Studio
2383
+ * diagnostics, never an error.
2384
+ *
2385
+ * Returns the winner's composable_uid (or undefined if nothing owns the URL) and
2386
+ * the per-candidate ownership outcome for diagnostics.
2387
+ */
2388
+ async function resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale) {
2389
+ const topTier = ranking.matches;
2390
+ // Happy path — a single (or no) top-tier candidate needs no probe.
2391
+ if (topTier.length <= 1) {
2392
+ return selectUrlWinner(topTier, new Map());
2393
+ }
2394
+ // Tie — probe each tied linked candidate's content type in parallel.
2395
+ const linkedMatches = topTier.filter((m) => m.connected_content_type);
2396
+ const probeOutcomes = await Promise.all(linkedMatches.map(async (m) => {
2397
+ const lightweight = candidatesByUid.get(m.composable_uid);
2398
+ // Legacy compositions persist no `url_metadata`. parseUrlMetadata maps an
2399
+ // absent/unknown source to the canonical LEGACY_URL metadata (url-non-empty
2400
+ // / url-equals query), so a tie of metadata-less legacy compositions still
2401
+ // gets probed by URL instead of bailing to "no winner" → COMPOSITION_NOT_
2402
+ // FOUND_BY_URL. Only an unmatched candidate (no captured variables / no
2403
+ // content type) is unprobeable.
2404
+ const meta = parseUrlMetadata(lightweight?.url_metadata);
2405
+ if (!m.variables || !m.connected_content_type) {
2406
+ return { uid: m.composable_uid, owns: false };
2407
+ }
2408
+ try {
2409
+ const probeQuery = resolveByUrlSource(config.stackSdk, meta.url_source, { url: requestUrl }, m.variables, meta.url_queries, m.connected_content_type, {
2410
+ references: [],
2411
+ only: [["BASE", "uid"]],
2412
+ locale: m.variables.metadata.locale || locale || config.locale,
2413
+ branch: m.variables.metadata.branch,
2414
+ // environment intentionally omitted — the ownership probe uses the
2415
+ // connection (SDK-init) env, consistent with how the page is served
2416
+ // (see ADR-0002 §Environment).
2417
+ });
2418
+ const res = await probeQuery.find();
2419
+ return {
2420
+ uid: m.composable_uid,
2421
+ owns: entriesFromResponse(res).length > 0,
2422
+ };
2423
+ }
2424
+ catch {
2425
+ // A failed probe counts as non-owning; another candidate may still own it.
2426
+ return { uid: m.composable_uid, owns: false };
2427
+ }
2428
+ }));
2429
+ const ownsByUid = new Map(probeOutcomes.map((r) => [r.uid, r.owns]));
2430
+ return selectUrlWinner(topTier, ownsByUid);
2431
+ }
1008
2432
  /**
1009
2433
  * This function fetches UI Composition from defined options.
1010
2434
  * Supports custom fetcher overrides (per-query > global > SDK default).
@@ -1012,6 +2436,9 @@ function getAllSymbols(compositionEntry) {
1012
2436
  async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1013
2437
  const { fetchComposition: perQueryFetchComposition, fetchTemplateEntry: _, ...resolvedOptions } = compositionQueryOptions || {};
1014
2438
  const locale = resolvedOptions.locale;
2439
+ // Captured by the URL metadata (Phase A) path for Studio resolution
2440
+ // diagnostics — every candidate considered, with specificity.
2441
+ let urlResolution;
1015
2442
  const defaultImpl = async () => {
1016
2443
  if ("composableUid" in queryOptions) {
1017
2444
  const uiQuery = config.stackSdk.where(config.stackSdk.ctQuery(config.contentTypeUid, {
@@ -1051,41 +2478,30 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1051
2478
  });
1052
2479
  });
1053
2480
  }
1054
- else if ("url" in queryOptions) {
1055
- const possibleEntryUrlPatterns = getUrlPatterns(queryOptions.url);
2481
+ else if ("templateContentTypeUid" in queryOptions) {
2482
+ // Fetch by connected content type - takes priority over url when both are present
2483
+ const placementFilter = getPageLinkedPlacementFilter();
1056
2484
  return await config.stackSdk
1057
2485
  .ctQuery(config.contentTypeUid, {
1058
2486
  includeAll: true,
1059
2487
  includeAllDepth: INCLUDE_DEPTH_COUNT,
1060
2488
  locale: locale || config.locale,
1061
2489
  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
- ],
2490
+ connected_content_type: queryOptions.templateContentTypeUid,
2491
+ ...placementFilter,
1073
2492
  },
1074
2493
  })
2494
+ .limit(1) // First match as per plan
1075
2495
  .find()
1076
2496
  .then((res) => {
1077
2497
  const entries = entriesFromResponse(res);
1078
- const entry = getCompositionFromSlug(queryOptions.url, entries);
2498
+ const entry = entries[0];
1079
2499
  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,
2500
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_404), {
2501
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
1084
2502
  hasStackSdk: !!config.stackSdk,
1085
- searchedPatterns: possibleEntryUrlPatterns,
1086
- entriesFound: entries.length,
1087
2503
  options: queryOptions,
1088
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
2504
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND, false),
1089
2505
  });
1090
2506
  }
1091
2507
  return entry;
@@ -1095,15 +2511,81 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1095
2511
  throw err;
1096
2512
  const { errorType, message } = classifyApiError(err);
1097
2513
  throw new ComposableStudioError(errorType, message, {
1098
- url: queryOptions.url,
2514
+ templateContentTypeUid: queryOptions.templateContentTypeUid,
1099
2515
  hasStackSdk: !!config.stackSdk,
1100
2516
  statusCode: err?.status || err?.statusCode || "none",
1101
2517
  errorCode: err?.error_code || "none",
1102
2518
  errorMessage: err?.error_message || err?.message || "none",
1103
- troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
2519
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, false),
1104
2520
  });
1105
2521
  });
1106
2522
  }
2523
+ else if ("url" in queryOptions) {
2524
+ // Unified resolution: rank ALL page-linked compositions (legacy +
2525
+ // variable, linked + freeform) in one pool, then disambiguate any
2526
+ // top-tier tie by probing each tied linked candidate's content type for an
2527
+ // entry matching the URL. The most-specific match is authoritative — no
2528
+ // descent to lower tiers, no legacy fallback.
2529
+ const requestUrl = queryOptions.url;
2530
+ try {
2531
+ // 1. Fetch every page-linked candidate (lightweight, paginated).
2532
+ const { entries: candidates, truncated } = await fetchAllPageCompositions(config, locale);
2533
+ if (truncated) {
2534
+ console.warn(`[Composable Studio SDK] Composition candidate list hit the pagination cap while resolving "${requestUrl}"; some compositions may not have been considered.`);
2535
+ }
2536
+ // 2. Rank the whole pool by literal-character specificity.
2537
+ const ranking = rankUrlMatches(requestUrl, candidates);
2538
+ if (ranking.composableUids.length > 0) {
2539
+ const candidatesByUid = new Map(candidates.map((c) => [c.composable_uid, c]));
2540
+ // 3. Disambiguate top-tier ties by entry existence.
2541
+ const { winnerUid, ownershipByUid } = await resolveUrlWinner(config, requestUrl, ranking, candidatesByUid, locale);
2542
+ // 4. Record every considered candidate (all tiers) + ownership for
2543
+ // Studio diagnostics, before committing to a winner.
2544
+ urlResolution = {
2545
+ shortlisted: ranking.allMatches.map((d) => ({
2546
+ ...d,
2547
+ connectedEntryResult: ownershipByUid.get(d.composable_uid) ?? "not-checked",
2548
+ })),
2549
+ };
2550
+ if (winnerUid) {
2551
+ // 5. Full-fetch the winning composition only.
2552
+ const fullQuery = config.stackSdk.ctQuery(config.contentTypeUid, {
2553
+ includeAll: true,
2554
+ includeAllDepth: INCLUDE_DEPTH_COUNT,
2555
+ locale: locale || config.locale,
2556
+ query: { composable_uid: winnerUid },
2557
+ });
2558
+ const fullRes = await fullQuery.find();
2559
+ const fullEntries = entriesFromResponse(fullRes);
2560
+ if (fullEntries[0]) {
2561
+ return fullEntries[0];
2562
+ }
2563
+ }
2564
+ }
2565
+ // Nothing matched, or no tied candidate owns the URL.
2566
+ throw new ComposableStudioError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, getErrorMessage(ErrorMessageKey.COMPOSITION_NOT_FOUND_BY_URL, {
2567
+ url: requestUrl,
2568
+ }), {
2569
+ url: requestUrl,
2570
+ hasStackSdk: !!config.stackSdk,
2571
+ options: queryOptions,
2572
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(ComposableStudioErrors.COMPOSITION_NOT_FOUND_BY_URL, true),
2573
+ });
2574
+ }
2575
+ catch (err) {
2576
+ if (err instanceof ComposableStudioError)
2577
+ throw err;
2578
+ const { errorType, message } = classifyApiError(err);
2579
+ throw new ComposableStudioError(errorType, message, {
2580
+ url: requestUrl,
2581
+ hasStackSdk: !!config.stackSdk,
2582
+ statusCode: err?.status || err?.statusCode || "none",
2583
+ errorCode: err?.error_code || "none",
2584
+ errorMessage: err?.error_message || err?.message || "none",
2585
+ troubleshootingInfo: getTroubleshootingInfoForCompositionFetchError(errorType, true),
2586
+ });
2587
+ }
2588
+ }
1107
2589
  else {
1108
2590
  throw new ComposableStudioError(ComposableStudioErrors.MISSING_COMPOSITION_IDENTIFIER, getErrorMessage(ErrorMessageKey.MISSING_COMPOSITION_IDENTIFIER), {
1109
2591
  options: queryOptions,
@@ -1132,14 +2614,18 @@ async function fetchComposition(config, queryOptions, compositionQueryOptions) {
1132
2614
  return {
1133
2615
  compositionEntry: entry,
1134
2616
  symbolEntries: getAllSymbols(entry),
2617
+ // Populated if the custom fetcher delegated to `defaultFetch` and it
2618
+ // resolved via the URL metadata path; otherwise undefined.
2619
+ urlResolution,
1135
2620
  };
1136
2621
  }
1137
2622
  const entry = await defaultImpl();
1138
2623
  return {
1139
2624
  compositionEntry: entry,
1140
2625
  symbolEntries: getAllSymbols(entry),
2626
+ urlResolution,
1141
2627
  };
1142
2628
  }
1143
2629
 
1144
- export { classifyApiError, generateSdk, parseUI };
2630
+ export { classifyApiError, collectSectionInstanceBindings as collectSectionInstanceBindingsForTest, composeSectionTemplatePrefix, fetchComposition as fetchCompositionForTest, flattenBindingPathFromValue, generateSdk, getAllSectionCompositions as getAllSectionCompositionsForTest, isTemplateBinding, parseUI, resolveSeoBindingValue };
1145
2631
  //# sourceMappingURL=sdk.js.map