@eldrajs/theme-core 0.3.6 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -5,8 +5,50 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - **`resolveLink` resolves cards (WS-1326).** A child or section link whose `display` is `card` (its
9
+ own, else its section's) carries `card: { image, title, price? }`: the image is the link's own
10
+ `imageUrl`, else the target's (`LinkTargetInfo.image`: a product's thumbnail, a collection's
11
+ image), `price` a product's `LinkTargetInfo.price`. A card with no picture or title resolves as a
12
+ plain link (`display: 'link'`, no `card`); heading, see-all and top-level links carry neither
13
+ `display` nor `card`. `card.price` is in major units, no currency. New type `ResolvedCard`.
14
+
15
+ - **`resolveLink` resolves `sections` (WS-1321).** A link a theme that declares `tree.sections` is
16
+ served carries `sections: ResolvedSection[]` (`heading`, `headingLink`, `links`, `seeAll`, `display`),
17
+ each link resolved like a child (a section with only a heading link takes its label as the heading); `children` is `[]` then. `linkTargetKeys` walks a link's sections,
18
+ their heading links and see-all links, so their targets are read with the rest. A card's `display`
19
+ and `imageUrl` are carried through on `ResolvedLink`. New types `ResolvedSection` and
20
+ `LinkSectionValue`.
21
+
8
22
  - **`defaultCurrencyOf(commerce)` (WS-1399).** The currency pages are built in: `defaultCurrency` (contract 6.22.0), else the first of a `currencies` list without the store's own currency, else `currency`. `resolveVisitorCurrency` and `offeredCurrencies` take that default as `base`.
9
23
  - **Currencies (WS-1391).** `SELLING_CURRENCIES`, `currencyForCountry(country)` (one table, country code to selling currency), `countryFromHeader(value)`, `VISITOR_COUNTRY_PATH`, `resolveVisitorCurrency({ base, offered, remembered, country })` (the remembered choice, then the visitor's country, then the store's own currency, each only when offered) and `offeredCurrencies(base, listed)`.
24
+ - **`expandReusableLayout(layout, projection, { routeTemplate? })` (WS-1358).** A layout with
25
+ reusable placements in the shape Core's public read serves it: each placement replaced by its
26
+ component, the root taking the placement id and every node inside it the `r` + SHA-256 render id,
27
+ no projection left. Throws what the render would refuse. A draft preview session renders this.
28
+ - **`getSiteSetting(path)` reads one of the site's own settings (WS-1394)**:
29
+ `/site/v1/design-tokens` or `/site/v1/theme-messages`, parsed JSON. Outside a session an ordinary
30
+ gateway read; in a draft preview session (`enableSessionPreview`) through the router's proxy like
31
+ the CMS reads, but a setting is not a draft: no `Eldra-Preview: draft` is asked for, the answer is
32
+ not reshaped, and a failure is thrown to the caller only, never reported to `onRequestError`'s
33
+ listeners. Optional on `EldraClient`, so a hand-written client still satisfies it.
34
+
35
+ - **A draft preview session's answers arrive in the public read's shape (WS-1358).** The
36
+ session client (`enableSessionPreview`) reshapes every CMS answer with the new `asPublicRead`:
37
+ wherever a `reusableComponentProjection` appears (the answer, a list item, a resolved reference
38
+ at any depth), the placements are expanded the way Core's public read expands them, `blocks` put
39
+ in layout order and a node naming a block that does not resolve dropped, and every entry's
40
+ `status` (which the public read does not carry) is dropped. New exports:
41
+ `asPublicRead(value)` and `expandReusableLayout(layout, projection, { routeTemplate? })` (the
42
+ expansion alone, throwing what the render would refuse). A client outside a session is unchanged.
43
+
44
+ - **`enableSessionPreview({ proxyBase })` (WS-1303).** For a draft preview session on the preview
45
+ router's host: the CMS reads go same-origin to `proxyBase` (the router's `/__eldra/gateway`) with
46
+ `cache: 'no-store'`, `credentials: 'same-origin'` and no credential header, and a CMS answer without
47
+ `Eldra-Preview: draft` is refused (502, `PREVIEW_UPSTREAM_NOT_PREVIEW`). Catalog reads are
48
+ unchanged, and no request carries `X-Preview-Token` once it is on. `EldraClientError` gains
49
+ `errorId` (read from a session read's refusal) and `sessionPreview`. A client that never calls it
50
+ behaves exactly as before.
51
+
10
52
  - **`getTypeScriptDefinitions({ sdkAugmentation })` (WS-434, contract 6.1.0).** `true` sends
11
53
  `sdkAugmentation=true`, asking the gateway to append the `declare module '@eldrajs/sdk'` block that
12
54
  fills `EldraProductExtensions`, so product extensions are typed. Off by default: without it the
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { StegaMeta, decodeStega, encodeStega, stripStega } from "./stega.js";
2
- import { C as ResolveEntryListBody, S as PageMeta, _ as EldraClientOptions, a as TemplateLayoutDocument, b as EntryList, c as TemplateLayoutRenderNode, d as CatalogDoc, f as CatalogList, g as EldraClientError, h as EldraClient, i as TemplateLayoutContext, l as buildTemplateBlockRenames, m as EldraCatalogReader, n as TemplateBlockFieldDefinition, o as TemplateLayoutNode, p as CatalogQuery, r as TemplateBlockNode, s as TemplateLayoutRenderModel, t as TemplateBlockDefinition, u as createTemplateLayoutRenderModel, v as EldraRetryOptions, x as EntryQuery, y as EntryDoc } from "./templateLayout-Dp3KYV2b.js";
2
+ import { C as EntryQuery, S as EntryList, T as ResolveEntryListBody, _ as EldraClientOptions, a as TemplateLayoutDocument, b as EldraSiteReadPath, c as TemplateLayoutRenderNode, d as CatalogDoc, f as CatalogList, g as EldraClientError, h as EldraClient, i as TemplateLayoutContext, l as buildTemplateBlockRenames, m as EldraCatalogReader, n as TemplateBlockFieldDefinition, o as TemplateLayoutNode, p as CatalogQuery, r as TemplateBlockNode, s as TemplateLayoutRenderModel, t as TemplateBlockDefinition, u as createTemplateLayoutRenderModel, v as EldraRetryOptions, w as PageMeta, x as EntryDoc, y as EldraSessionPreviewOptions } from "./templateLayout-BWNs1ZYt.js";
3
3
  import { a as buildDynamicRoutePath, c as parseDynamicRoutePattern, d as resolvePagePath, i as RouteTemplateLike, l as resolveRoute, n as MAX_DYNAMIC_ROUTE_PATTERN_BYTES, o as catalogRouteTarget, r as ParsedDynamicRoutePattern, s as matchDynamicRoutePattern, t as DynamicRouteResolution, u as PageLike } from "./dynamicRoute-DzSNn4tV.js";
4
4
  import { a as RichTextRenderStateChange, c as NegotiatedEditorCapabilities, d as PreviewRouterMessageType, f as createPreviewMessageRouter, i as RichTextFieldIdentity, l as PREVIEW_ROUTER_MESSAGE_TYPES, n as OverlayRuntime, o as classifyBeforeInput, r as OverlayRuntimeOptions, s as createOverlayRuntime, t as BeforeInputClassification, u as PreviewMessageRouter } from "./overlay-mKeZLljc.js";
5
5
  import { A as generateLayoutCss, C as Responsive, D as WidthLength, E as Spacing, F as resolveLayoutBreakpoints, I as resolveLayoutDocument, L as validateLayoutDocument, M as layoutNodeClass, N as layoutRenderNodeId, O as activeLayoutBreakpoint, P as normalizeLayoutDocument, S as ResolvedLayoutStyle, T as SlotValidationContext, _ as LayoutValidationError, a as LAYOUT_BREAKPOINTS, b as ResolvedLayoutDocument, c as LayoutBreakpoints, d as LayoutNode, f as LayoutRenderBlockNode, g as LayoutValidationCode, h as LayoutStyle, i as EDIT_MODE_HIDDEN_OPACITY, j as hiddenLayoutBreakpoints, k as createLayoutRenderModel, l as LayoutContainerNode, m as LayoutRenderNode, n as CssLength, o as LayoutBlockNode, p as LayoutRenderModel, r as DEFAULT_LAYOUT_BREAKPOINTS, s as LayoutBreakpoint, t as BlockSlotDefinition, u as LayoutDocument, v as LayoutValidationIssue, w as SizingLength, x as ResolvedLayoutNode, y as NormalizedLayoutResult } from "./layout-CkPOfiOM.js";
6
- import { PageLayoutDocument, PageLayoutNode, ReusableComponentSnapshotCache, ReusableLayoutOptions, ReusableLayoutRenderModel, ReusableLayoutRenderNode, ReusablePerspective, createReusableLayoutRenderModel } from "./reusable.js";
6
+ import { PageLayoutDocument, PageLayoutNode, ReusableComponentSnapshotCache, ReusableLayoutOptions, ReusableLayoutRenderModel, ReusableLayoutRenderNode, ReusablePerspective, asPublicRead, createReusableLayoutRenderModel, expandReusableLayout } from "./reusable.js";
7
7
  import { ColorLiteral, ColorSelection, ContainerOverride, ContainerPreset, CssTokenLength, DesignTokenCatalog, DesignTokenId, DesignTokenValidationCode, DesignTokenValidationError, ResponsiveTokenValue, SiteDesignTokenOverrides, ThemeColorToken, ThemeDesignTokens, applyDesignTokenOverrides, designTokenRevisionHash, generateDesignTokenCss, generateTailwindThemeCss, normalizeColorSelection, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, resolveColorSelection, resolveDesignTokenCatalog, responsiveValue } from "./design-tokens.js";
8
8
  import { a as ReusableComponentRevision, i as ReusableComponentResolver, n as ReusableComponentPlacement, o as ReusableRenderIdentity, r as ReusableComponentProjection, s as createProjectionResolver, t as ReusableComponentBinding } from "./reusableExpansion-CqrqpK4A.js";
9
9
  import { a as ImageFraming, c as focalBand, d as imageFramingAttrs, f as imageFramingStyle, h as unscaledFrameRect, i as IMAGE_FRAMING_MIN_ZOOM, l as framingDrag, m as parseImageFramingValueAttr, n as FrameRect, o as clampFocal, p as normalizeImageFraming, r as IMAGE_FRAMING_MAX_ZOOM, s as clampImageFraming, t as DEFAULT_IMAGE_FRAMING, u as framingZoom } from "./imageFraming-BgKBJiTB.js";
@@ -860,4 +860,4 @@ export declare function offeredCurrencies(base: string, listed: readonly unknown
860
860
  export declare const VISITOR_COUNTRY_PATH = "/_eldra/visitor";
861
861
  /** A two-letter country from `CF-IPCountry`, or `null` for none, unknown (`XX`) or Tor (`T1`). */
862
862
  export declare function countryFromHeader(value: string | null | undefined): string | null;
863
- export { type BeforeInputClassification, type BlockFieldDefinition, type BlockFieldsMap, BlockSlotDefinition, type BuildRichTextTreeOptions, CatalogDoc, CatalogList, CatalogQuery, ColorLiteral, ColorSelection, ContainerOverride, ContainerPreset, CssLength, CssTokenLength, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DesignTokenCatalog, DesignTokenId, DesignTokenValidationCode, DesignTokenValidationError, DynamicRouteResolution, EDIT_MODE_HIDDEN_OPACITY, EldraCatalogReader, EldraClient, EldraClientError, EldraClientOptions, EldraRetryOptions, EntryDoc, EntryList, EntryQuery, FrameRect, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, ImageFraming, LAYOUT_BREAKPOINTS, LayoutBlockNode, LayoutBreakpoint, LayoutBreakpoints, LayoutContainerNode, LayoutDocument, LayoutNode, LayoutRenderBlockNode, LayoutRenderModel, LayoutRenderNode, LayoutStyle, LayoutValidationCode, LayoutValidationError, LayoutValidationIssue, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, type NegotiatedEditorCapabilities, NormalizedLayoutResult, type OverlayRuntime, type OverlayRuntimeOptions, PREVIEW_ROUTER_MESSAGE_TYPES, PageLayoutDocument, PageLayoutNode, type PageLike, PageMeta, ParsedDynamicRoutePattern, type PreviewMessageRouter, type PreviewRouterMessageType, ResolveEntryListBody, ResolvedLayoutDocument, ResolvedLayoutNode, ResolvedLayoutStyle, Responsive, ResponsiveTokenValue, type ReusableComponentBinding, type ReusableComponentPlacement, type ReusableComponentProjection, type ReusableComponentResolver, type ReusableComponentRevision, ReusableComponentSnapshotCache, ReusableLayoutOptions, ReusableLayoutRenderModel, ReusableLayoutRenderNode, ReusablePerspective, type ReusableRenderIdentity, type RichTextDomPoint, type RichTextFieldIdentity, type RichTextMark, type RichTextNode, type RichTextPositionNode, type RichTextPositions, type RichTextRenderChild, type RichTextRenderNode, type RichTextRenderStateChange, type RichTextSelectionContext, type RichTextToolbarControl, RouteTemplateLike, SiteDesignTokenOverrides, SizingLength, SlotValidationContext, Spacing, type StegaMeta, TemplateBlockDefinition, TemplateBlockFieldDefinition, TemplateBlockNode, TemplateLayoutContext, TemplateLayoutDocument, TemplateLayoutNode, TemplateLayoutRenderModel, TemplateLayoutRenderNode, ThemeColorToken, ThemeDesignTokens, WidthLength, activeLayoutBreakpoint, applyDesignTokenOverrides, buildDynamicRoutePath, buildTemplateBlockRenames, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, decodeStega, designTokenRevisionHash, encodeStega, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, layoutNodeClass, layoutRenderNodeId, matchDynamicRoutePattern, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, parseDynamicRoutePattern, parseImageFramingValueAttr, resolveColorSelection, resolveDesignTokenCatalog, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, responsiveValue, stripStega, unscaledFrameRect, validateLayoutDocument };
863
+ export { type BeforeInputClassification, type BlockFieldDefinition, type BlockFieldsMap, BlockSlotDefinition, type BuildRichTextTreeOptions, CatalogDoc, CatalogList, CatalogQuery, ColorLiteral, ColorSelection, ContainerOverride, ContainerPreset, CssLength, CssTokenLength, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DesignTokenCatalog, DesignTokenId, DesignTokenValidationCode, DesignTokenValidationError, DynamicRouteResolution, EDIT_MODE_HIDDEN_OPACITY, EldraCatalogReader, EldraClient, EldraClientError, EldraClientOptions, EldraRetryOptions, EldraSessionPreviewOptions, EldraSiteReadPath, EntryDoc, EntryList, EntryQuery, FrameRect, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, ImageFraming, LAYOUT_BREAKPOINTS, LayoutBlockNode, LayoutBreakpoint, LayoutBreakpoints, LayoutContainerNode, LayoutDocument, LayoutNode, LayoutRenderBlockNode, LayoutRenderModel, LayoutRenderNode, LayoutStyle, LayoutValidationCode, LayoutValidationError, LayoutValidationIssue, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, type NegotiatedEditorCapabilities, NormalizedLayoutResult, type OverlayRuntime, type OverlayRuntimeOptions, PREVIEW_ROUTER_MESSAGE_TYPES, PageLayoutDocument, PageLayoutNode, type PageLike, PageMeta, ParsedDynamicRoutePattern, type PreviewMessageRouter, type PreviewRouterMessageType, ResolveEntryListBody, ResolvedLayoutDocument, ResolvedLayoutNode, ResolvedLayoutStyle, Responsive, ResponsiveTokenValue, type ReusableComponentBinding, type ReusableComponentPlacement, type ReusableComponentProjection, type ReusableComponentResolver, type ReusableComponentRevision, ReusableComponentSnapshotCache, ReusableLayoutOptions, ReusableLayoutRenderModel, ReusableLayoutRenderNode, ReusablePerspective, type ReusableRenderIdentity, type RichTextDomPoint, type RichTextFieldIdentity, type RichTextMark, type RichTextNode, type RichTextPositionNode, type RichTextPositions, type RichTextRenderChild, type RichTextRenderNode, type RichTextRenderStateChange, type RichTextSelectionContext, type RichTextToolbarControl, RouteTemplateLike, SiteDesignTokenOverrides, SizingLength, SlotValidationContext, Spacing, type StegaMeta, TemplateBlockDefinition, TemplateBlockFieldDefinition, TemplateBlockNode, TemplateLayoutContext, TemplateLayoutDocument, TemplateLayoutNode, TemplateLayoutRenderModel, TemplateLayoutRenderNode, ThemeColorToken, ThemeDesignTokens, WidthLength, activeLayoutBreakpoint, applyDesignTokenOverrides, asPublicRead, buildDynamicRoutePath, buildTemplateBlockRenames, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, decodeStega, designTokenRevisionHash, encodeStega, expandReusableLayout, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, layoutNodeClass, layoutRenderNodeId, matchDynamicRoutePattern, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, parseDynamicRoutePattern, parseImageFramingValueAttr, resolveColorSelection, resolveDesignTokenCatalog, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, responsiveValue, stripStega, unscaledFrameRect, validateLayoutDocument };
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { decodeStega, encodeStega, stripStega } from "./stega.js";
2
2
  import { a as blockApiIdOf, c as registeredBlockApiId, i as THEME_ID_PATTERN, l as themeSchemaApiId, n as createTemplateLayoutRenderModel, o as getRegisteredThemeId, r as RESERVED_THEME_IDS, s as registerThemeId, t as buildTemplateBlockRenames } from "./templateLayout-CGMAmJBe.js";
3
+ import { ReusableComponentSnapshotCache, asPublicRead, createReusableLayoutRenderModel, expandReusableLayout } from "./reusable.js";
4
+ import { r as createProjectionResolver } from "./reusableExpansion-Cg9AE8JX.js";
3
5
  import { a as parseDynamicRoutePattern, i as matchDynamicRoutePattern, n as buildDynamicRoutePath, o as resolveRoute, r as catalogRouteTarget, s as resolvePagePath, t as MAX_DYNAMIC_ROUTE_PATTERN_BYTES } from "./dynamicRoute-k60idORj.js";
4
6
  import { a as RICH_TEXT_PAD_ATTR, c as domRangeToPositions, d as restampRichTextPositions, f as richTextMarkNameOf, h as layoutIdentityOf, i as RICH_TEXT_MARK_ELEMENTS, l as resolveDomPoint, m as richTextText, n as createOverlayRuntime, o as computeRichTextPositions, p as richTextNodeSize, r as RICH_TEXT_LEAF_TYPES, s as describeSelectionContext, t as classifyBeforeInput, u as resolveDomPosition } from "./overlay-a8pghnYy.js";
5
7
  import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
6
8
  import { DEFAULT_LAYOUT_BREAKPOINTS, EDIT_MODE_HIDDEN_OPACITY, LAYOUT_BREAKPOINTS, LayoutValidationError, activeLayoutBreakpoint, createLayoutRenderModel, generateLayoutCss, hiddenLayoutBreakpoints, layoutNodeClass, layoutRenderNodeId, normalizeLayoutDocument, resolveLayoutBreakpoints, resolveLayoutDocument, validateLayoutDocument } from "./layout.js";
7
- import { ReusableComponentSnapshotCache, createReusableLayoutRenderModel } from "./reusable.js";
8
- import { r as createProjectionResolver } from "./reusableExpansion-Cg9AE8JX.js";
9
9
  import { DesignTokenValidationError, applyDesignTokenOverrides, designTokenRevisionHash, generateDesignTokenCss, generateTailwindThemeCss, normalizeColorSelection, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, resolveColorSelection, resolveDesignTokenCatalog, responsiveValue } from "./design-tokens.js";
10
10
  import { DEFAULT_IMAGE_FRAMING, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, clampFocal, clampImageFraming, focalBand, framingDrag, framingZoom, imageFramingAttrs, imageFramingStyle, normalizeImageFraming, parseImageFramingValueAttr, unscaledFrameRect } from "./image-framing.js";
11
11
  // src/blockFields.ts
@@ -484,11 +484,22 @@ function looksLikeRichTextNode(value) {
484
484
  var EldraClientError = class extends Error {
485
485
  status;
486
486
  path;
487
- constructor(status, statusText, path) {
487
+ /**
488
+ * The refusal's `errorId`, when the answer named one. Read only from a draft preview session's
489
+ * reads (`enableSessionPreview`), where the preview router answers `application/problem+json` and
490
+ * the id says which notice to show (`SITE_PREVIEW_SESSION_EXPIRED`, `_REVOKED`, …). `null`
491
+ * everywhere else: an ordinary read's failure body is never read.
492
+ */
493
+ errorId;
494
+ /** Whether the failed request was a draft preview session read through the same-origin proxy. */
495
+ sessionPreview;
496
+ constructor(status, statusText, path, details) {
488
497
  super(`[eldra] gateway request failed: ${status} ${statusText} for ${path}`);
489
498
  this.name = "EldraClientError";
490
499
  this.status = status;
491
500
  this.path = path;
501
+ this.errorId = details?.errorId ?? null;
502
+ this.sessionPreview = details?.sessionPreview === true;
492
503
  }
493
504
  };
494
505
  // src/client.ts
@@ -511,9 +522,11 @@ function createEldraClient(opts) {
511
522
  const stegaEnabled = opts.stega === true;
512
523
  const defaultLocale = opts.defaultLocale ?? null;
513
524
  let previewToken = null;
525
+ /** The draft preview session's proxy (`enableSessionPreview`), or `null` outside one. */
526
+ let sessionProxyBase = null;
514
527
  const requestErrorListeners = /* @__PURE__ */ new Set();
515
- function buildUrl(path, query, extra) {
516
- const url = new URL(gatewayUrl + path);
528
+ function buildUrl(path, query, extra, base = gatewayUrl) {
529
+ const url = new URL(base + path);
517
530
  if (query?.locale !== void 0) url.searchParams.set("locale", query.locale);
518
531
  if (query?.depth !== void 0) url.searchParams.set("depth", String(query.depth));
519
532
  if (query?.page !== void 0) url.searchParams.set("page", String(query.page));
@@ -527,7 +540,7 @@ function createEldraClient(opts) {
527
540
  async function request(url, init) {
528
541
  const headers = new Headers(init?.headers);
529
542
  headers.set("X-Org-Id", opts.orgId);
530
- if (previewToken !== null) headers.set("X-Preview-Token", previewToken);
543
+ if (previewToken !== null && sessionProxyBase === null) headers.set("X-Preview-Token", previewToken);
531
544
  if (opts.buildToken) headers.set("X-Eldra-Build-Token", opts.buildToken);
532
545
  const merged = {
533
546
  ...init,
@@ -543,6 +556,75 @@ function createEldraClient(opts) {
543
556
  }
544
557
  return res;
545
558
  }
559
+ /**
560
+ * One CMS read: through the session's same-origin proxy when a draft preview session is on,
561
+ * otherwise exactly the read it has always been.
562
+ */
563
+ async function cmsRequest(path, query, init) {
564
+ if (sessionProxyBase === null) return request(buildUrl(path, query), init);
565
+ return sessionRequest(buildUrl(path, query, void 0, sessionProxyBase), init);
566
+ }
567
+ /**
568
+ * A draft read through the preview router's proxy. A fresh header set — the caller's own
569
+ * (`content-type` on the one POST) and `accept`, never `X-Org-Id`, `X-Preview-Token` or the build
570
+ * token: the router adds the organisation and the session itself, from the HttpOnly cookie
571
+ * `credentials: 'same-origin'` sends. `no-store`, because a draft must never be cached.
572
+ */
573
+ async function sessionRequest(url, init) {
574
+ const headers = new Headers(init?.headers);
575
+ headers.set("accept", "application/json");
576
+ const merged = {
577
+ ...init,
578
+ headers,
579
+ cache: "no-store",
580
+ credentials: "same-origin"
581
+ };
582
+ const res = await fetchWithRetry(doFetch, url.toString(), merged, retryPolicy);
583
+ if (!res.ok) {
584
+ const error = new EldraClientError(res.status, res.statusText, url.pathname, {
585
+ errorId: await readErrorId(res),
586
+ sessionPreview: true
587
+ });
588
+ notifyRequestError(error);
589
+ throw error;
590
+ }
591
+ if (res.headers.get("eldra-preview") !== "draft") {
592
+ res.body?.cancel().catch(() => void 0);
593
+ const error = new EldraClientError(502, "Bad Gateway", url.pathname, {
594
+ errorId: "PREVIEW_UPSTREAM_NOT_PREVIEW",
595
+ sessionPreview: true
596
+ });
597
+ notifyRequestError(error);
598
+ throw error;
599
+ }
600
+ const text = await res.text();
601
+ let body;
602
+ try {
603
+ body = JSON.stringify(asPublicRead(JSON.parse(text)));
604
+ } catch {
605
+ body = text;
606
+ }
607
+ return new Response(body, {
608
+ status: res.status,
609
+ statusText: res.statusText,
610
+ headers: res.headers
611
+ });
612
+ }
613
+ /** `getSiteSetting`: see its doc comment in `./clientTypes.ts`. */
614
+ async function siteSetting(path) {
615
+ if (sessionProxyBase === null) return (await request(buildUrl(path))).json();
616
+ const url = buildUrl(path, void 0, void 0, sessionProxyBase);
617
+ const res = await fetchWithRetry(doFetch, url.toString(), {
618
+ headers: { accept: "application/json" },
619
+ cache: "no-store",
620
+ credentials: "same-origin"
621
+ }, retryPolicy);
622
+ if (!res.ok) throw new EldraClientError(res.status, res.statusText, url.pathname, {
623
+ errorId: await readErrorId(res),
624
+ sessionPreview: true
625
+ });
626
+ return res.json();
627
+ }
546
628
  function notifyRequestError(error) {
547
629
  for (const listener of [...requestErrorListeners]) try {
548
630
  listener(error);
@@ -579,7 +661,7 @@ function createEldraClient(opts) {
579
661
  }
580
662
  },
581
663
  async getEntries(schemaIdentifier, query) {
582
- const list = await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry`, query))).json();
664
+ const list = await (await cmsRequest(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry`, query)).json();
583
665
  if (list.data !== void 0 && list.data !== null && !Array.isArray(list.data)) throw new TypeError("[eldra] gateway entry list data must be an array");
584
666
  return {
585
667
  ...list,
@@ -587,16 +669,16 @@ function createEldraClient(opts) {
587
669
  };
588
670
  },
589
671
  async getEntry(schemaIdentifier, entryId, query) {
590
- return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/${encodeURIComponent(entryId)}`, query))).json(), query?.locale ?? null);
672
+ return maybeStega(await (await cmsRequest(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/${encodeURIComponent(entryId)}`, query)).json(), query?.locale ?? null);
591
673
  },
592
674
  async getEntryByUniqueField(schemaIdentifier, fieldId, value, query) {
593
- return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(value)}`, query))).json(), query?.locale ?? null);
675
+ return maybeStega(await (await cmsRequest(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(value)}`, query)).json(), query?.locale ?? null);
594
676
  },
595
677
  async resolveEntryListField(entryId, fieldId, query) {
596
- return await (await request(buildUrl(`/cms/v1/entry/${encodeURIComponent(entryId)}/list/${encodeURIComponent(fieldId)}`, query))).json();
678
+ return await (await cmsRequest(`/cms/v1/entry/${encodeURIComponent(entryId)}/list/${encodeURIComponent(fieldId)}`, query)).json();
597
679
  },
598
680
  async resolveEntryList(body, query) {
599
- return await (await request(buildUrl("/cms/v1/entry-list/resolve", query), {
681
+ return await (await cmsRequest("/cms/v1/entry-list/resolve", query, {
600
682
  method: "POST",
601
683
  headers: { "content-type": "application/json" },
602
684
  body: JSON.stringify(body)
@@ -619,6 +701,13 @@ function createEldraClient(opts) {
619
701
  get previewEnabled() {
620
702
  return previewToken !== null;
621
703
  },
704
+ enableSessionPreview(options) {
705
+ sessionProxyBase = sameOriginProxyBase(options);
706
+ },
707
+ get sessionPreviewEnabled() {
708
+ return sessionProxyBase !== null;
709
+ },
710
+ getSiteSetting: siteSetting,
622
711
  onRequestError(listener) {
623
712
  requestErrorListeners.add(listener);
624
713
  return () => {
@@ -629,6 +718,33 @@ function createEldraClient(opts) {
629
718
  };
630
719
  }
631
720
  /**
721
+ * The session proxy's base, checked: absolute, on the page's own origin (when there is a page), with
722
+ * no query or fragment, trailing slashes stripped. The reads it serves carry the session cookie, so
723
+ * a base anywhere else is a mistake that must fail loudly rather than send them there.
724
+ */
725
+ function sameOriginProxyBase(options) {
726
+ let url;
727
+ try {
728
+ url = new URL(options.proxyBase);
729
+ } catch {
730
+ throw new TypeError("[eldra] enableSessionPreview: proxyBase must be an absolute URL");
731
+ }
732
+ const pageOrigin = globalThis.location?.origin;
733
+ if (typeof pageOrigin === "string" && pageOrigin !== "null" && url.origin !== pageOrigin) throw new TypeError("[eldra] enableSessionPreview: proxyBase must be on the page's own origin");
734
+ if (url.search !== "" || url.hash !== "") throw new TypeError("[eldra] enableSessionPreview: proxyBase takes no query or fragment");
735
+ return stripTrailingSlashes(`${url.origin}${url.pathname}`);
736
+ }
737
+ /** A refusal's `errorId` from its `application/problem+json` body, or `null`. Never throws. */
738
+ async function readErrorId(res) {
739
+ try {
740
+ const body = await res.json();
741
+ const errorId = typeof body === "object" && body !== null ? body.errorId : null;
742
+ return typeof errorId === "string" && errorId !== "" ? errorId : null;
743
+ } catch {
744
+ return null;
745
+ }
746
+ }
747
+ /**
632
748
  * Normalise a catalog list response. The gateway serialises an empty page as
633
749
  * `"data": null`, and a caller that pages through the list must not have to
634
750
  * guess whether a missing `meta` means "one page" or "keep asking" — an absent
@@ -1866,4 +1982,4 @@ function countryFromHeader(value) {
1866
1982
  const code = (value ?? "").trim().toUpperCase();
1867
1983
  return /^[A-Z]{2}$/.test(code) && code !== "XX" ? code : null;
1868
1984
  }
1869
- export { ANALYTICS_MAX_KEY_BYTES, ANALYTICS_MAX_NAME_BYTES, ANALYTICS_MAX_PROPS, ANALYTICS_MAX_VALUE_BYTES, ANALYTICS_QUEUE_LIMIT, DEFAULT_HOME_TITLE_PATTERN, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DEFAULT_TITLE_PATTERN, DesignTokenValidationError, EDIT_MODE_HIDDEN_OPACITY, EldraClientError, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, LAYOUT_BREAKPOINTS, LD_DESCRIPTION_MAX, LayoutValidationError, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, PREVIEW_ROUTER_MESSAGE_TYPES, RESERVED_THEME_IDS, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, SELLING_CURRENCIES, SEO_SYNTAX, SITEMAP_MAX_BYTES, SITEMAP_MAX_URLS, STRUCTURED_DATA_TYPES, THEME_ID_PATTERN, VISITOR_COUNTRY_PATH, activeLayoutBreakpoint, applyDesignTokenOverrides, applyStructuredDataPolicy, blockApiIdOf, buildAlternates, buildBreadcrumbLd, buildDynamicRoutePath, buildItemListLd, buildOrganizationLd, buildProductLd, buildRichTextTree, buildRobots, buildSitemap, buildTemplateBlockRenames, buildWebSiteLd, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, countryFromHeader, createAnalytics, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, currencyForCountry, decodeStega, defaultCurrencyOf, describeSelectionContext, designTokenRevisionHash, domRangeToPositions, encodeEntryDataStega, encodeStega, escapeXml, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, getRegisteredThemeId, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, ldPlainText, ldPrice, matchDynamicRoutePattern, normalizeAnalyticsProps, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, offeredCurrencies, parseDynamicRoutePattern, parseImageFramingValueAttr, pickSeoLocale, projectEntryDataLocale, registerBlockFields, registerThemeId, renderSeoTitle, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, resolveSeo, resolveVisitorCurrency, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, serializeLd, siteOrigin, sitemapLastmod, stripStega, substituteSeoPattern, themeSchemaApiId, tidySeoTitle, truncateUtf8, unscaledFrameRect, validGtin, validateLayoutDocument };
1985
+ export { ANALYTICS_MAX_KEY_BYTES, ANALYTICS_MAX_NAME_BYTES, ANALYTICS_MAX_PROPS, ANALYTICS_MAX_VALUE_BYTES, ANALYTICS_QUEUE_LIMIT, DEFAULT_HOME_TITLE_PATTERN, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DEFAULT_TITLE_PATTERN, DesignTokenValidationError, EDIT_MODE_HIDDEN_OPACITY, EldraClientError, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, LAYOUT_BREAKPOINTS, LD_DESCRIPTION_MAX, LayoutValidationError, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, PREVIEW_ROUTER_MESSAGE_TYPES, RESERVED_THEME_IDS, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, SELLING_CURRENCIES, SEO_SYNTAX, SITEMAP_MAX_BYTES, SITEMAP_MAX_URLS, STRUCTURED_DATA_TYPES, THEME_ID_PATTERN, VISITOR_COUNTRY_PATH, activeLayoutBreakpoint, applyDesignTokenOverrides, applyStructuredDataPolicy, asPublicRead, blockApiIdOf, buildAlternates, buildBreadcrumbLd, buildDynamicRoutePath, buildItemListLd, buildOrganizationLd, buildProductLd, buildRichTextTree, buildRobots, buildSitemap, buildTemplateBlockRenames, buildWebSiteLd, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, countryFromHeader, createAnalytics, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, currencyForCountry, decodeStega, defaultCurrencyOf, describeSelectionContext, designTokenRevisionHash, domRangeToPositions, encodeEntryDataStega, encodeStega, escapeXml, expandReusableLayout, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, getRegisteredThemeId, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, ldPlainText, ldPrice, matchDynamicRoutePattern, normalizeAnalyticsProps, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, offeredCurrencies, parseDynamicRoutePattern, parseImageFramingValueAttr, pickSeoLocale, projectEntryDataLocale, registerBlockFields, registerThemeId, renderSeoTitle, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, resolveSeo, resolveVisitorCurrency, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, serializeLd, siteOrigin, sitemapLastmod, stripStega, substituteSeoPattern, themeSchemaApiId, tidySeoTitle, truncateUtf8, unscaledFrameRect, validGtin, validateLayoutDocument };
package/dist/links.d.ts CHANGED
@@ -21,8 +21,25 @@ export interface LinkValue {
21
21
  openInNewTab?: boolean;
22
22
  /** A column heading; meaningful on a child of a mega-menu item. */
23
23
  group?: string;
24
- /** One level deep, never two. */
24
+ /** One level deep, never two. Served to a theme that declares no `sections`. */
25
25
  children?: LinkValue[];
26
+ /** The second level in columns, served to a theme that declares `sections`; never together with `children`. */
27
+ sections?: LinkSectionValue[];
28
+ /** A promotional card or a plain link; a link's own value overrides its section's. */
29
+ display?: 'card' | 'link';
30
+ /** The media URL of a card's own image. */
31
+ imageUrl?: string;
32
+ }
33
+ /** One column of a link's `sections`, as a public read serves it. */
34
+ export interface LinkSectionValue {
35
+ heading?: string;
36
+ headingLink?: LinkValue;
37
+ display?: 'card' | 'link';
38
+ links?: LinkValue[];
39
+ seeAll?: {
40
+ label?: string;
41
+ link?: LinkValue;
42
+ };
26
43
  }
27
44
  /** What a site knows about one link target, keyed by `${_type}:${id}`. The
28
45
  * slug builds the path, the title fills in a label the author left empty,
@@ -43,6 +60,10 @@ export interface LinkTargetInfo {
43
60
  * path, which on a canonical-only route is a 404 dressed as a link.
44
61
  */
45
62
  path?: string;
63
+ /** The target's own picture URL: a product's `thumbnail`, a collection's `image`. A card's fallback when its own image is absent. */
64
+ image?: string;
65
+ /** A product's lowest price as the catalog read serves it (major units, no currency: the store's own). Shown on a product card. */
66
+ price?: number;
46
67
  }
47
68
  export interface LinkRouteContext {
48
69
  pages: readonly PageLike[];
@@ -59,6 +80,32 @@ export interface ResolvedLink {
59
80
  newTab: boolean;
60
81
  group: string | null;
61
82
  children: ResolvedLink[];
83
+ /** Present only on a link the read served sections for; `children` is empty then. */
84
+ sections?: ResolvedSection[];
85
+ /** How the link is presented: its own `display`, else its section's. `link` when a card could not be resolved. */
86
+ display?: 'card' | 'link';
87
+ /** The link's own card image, as served. */
88
+ imageUrl?: string;
89
+ /** Present only when `display` is `card` and the card has a picture and a title; without it the link is a plain link. */
90
+ card?: ResolvedCard;
91
+ }
92
+ /** A resolved card: the picture (the override, else the target's own), the title and, for a product, its price. */
93
+ export interface ResolvedCard {
94
+ image: string;
95
+ title: string;
96
+ /** A product's lowest price in **major units** (the /web product list's `minPrice`, `28` for 28 kr.), with no currency: format it with the store's. */
97
+ price?: number;
98
+ }
99
+ /** One resolved column of a link's `sections`. */
100
+ export interface ResolvedSection {
101
+ /** Unstripped, like every label, so a preview can edit it inline. Falls back to the heading link's label; null when both are blank. */
102
+ heading: string | null;
103
+ /** The heading as a link, when the author made it one. */
104
+ headingLink: ResolvedLink | null;
105
+ display?: 'card' | 'link';
106
+ links: ResolvedLink[];
107
+ /** The trailing "see all" link: its own label when set, else its target's. Null when it has neither. */
108
+ seeAll: ResolvedLink | null;
62
109
  }
63
110
  /**
64
111
  * An href a theme may render, or null.
@@ -106,6 +153,8 @@ export declare function linkTargetKeys(value: unknown): string[];
106
153
  * simply is not a link until the page is published.
107
154
  *
108
155
  * Children resolve one level; a child's own `children` are ignored, matching
109
- * the depth the grammar allows.
156
+ * the depth the grammar allows. `sections` (a theme that declares them is served
157
+ * those instead of `children`) resolve the same way: each section's links, its
158
+ * heading link and its see-all link are links of that one level.
110
159
  */
111
160
  export declare function resolveLink(value: unknown, context: LinkRouteContext): ResolvedLink | null;
package/dist/links.js CHANGED
@@ -91,8 +91,16 @@ function collectTargetKeys(value, keys, seen, depth) {
91
91
  seen.add(key);
92
92
  keys.push(key);
93
93
  }
94
- if (depth > 0 || !Array.isArray(link.children)) return;
95
- for (const child of link.children) collectTargetKeys(child, keys, seen, depth + 1);
94
+ if (depth > 0) return;
95
+ if (Array.isArray(link.children)) for (const child of link.children) collectTargetKeys(child, keys, seen, depth + 1);
96
+ if (!Array.isArray(link.sections)) return;
97
+ for (const section of link.sections) {
98
+ const record = asRecord(section);
99
+ if (record === null) continue;
100
+ collectTargetKeys(record.headingLink, keys, seen, depth + 1);
101
+ if (Array.isArray(record.links)) for (const child of record.links) collectTargetKeys(child, keys, seen, depth + 1);
102
+ collectTargetKeys(asRecord(record.seeAll)?.link, keys, seen, depth + 1);
103
+ }
96
104
  }
97
105
  function targetKey(target) {
98
106
  if (typeof target !== "object" || target === null || Array.isArray(target)) return null;
@@ -114,25 +122,88 @@ function targetKey(target) {
114
122
  * simply is not a link until the page is published.
115
123
  *
116
124
  * Children resolve one level; a child's own `children` are ignored, matching
117
- * the depth the grammar allows.
125
+ * the depth the grammar allows. `sections` (a theme that declares them is served
126
+ * those instead of `children`) resolve the same way: each section's links, its
127
+ * heading link and its see-all link are links of that one level.
118
128
  */
119
129
  function resolveLink(value, context) {
120
130
  return resolveOne(value, context, 0);
121
131
  }
122
- function resolveOne(value, context, depth) {
132
+ function resolveOne(value, context, depth, card) {
123
133
  const link = asLinkValue(value);
124
134
  if (link === null) return null;
125
135
  const info = targetInfo(link.target, context);
126
136
  const ownLabel = typeof link.label === "string" ? link.label : "";
127
137
  const targetTitle = typeof info?.title === "string" ? info.title : "";
128
138
  const group = typeof link.group === "string" ? link.group : "";
129
- return {
139
+ const resolved = {
130
140
  href: resolveHref(plain(link.kind), link, info, context),
131
141
  label: plain(ownLabel) !== "" ? ownLabel : plain(targetTitle) !== "" ? targetTitle : null,
132
142
  newTab: link.openInNewTab === true,
133
143
  group: plain(group) === "" ? null : group,
134
- children: depth > 0 || !Array.isArray(link.children) ? [] : link.children.map((child) => resolveOne(child, context, depth + 1)).filter((child) => child !== null)
144
+ children: depth > 0 || !Array.isArray(link.children) ? [] : link.children.map((child) => resolveOne(child, context, depth + 1, {})).filter((child) => child !== null)
145
+ };
146
+ if (depth === 0 && Array.isArray(link.sections)) resolved.sections = link.sections.map((section) => resolveSection(section, context)).filter((section) => section !== null);
147
+ if (typeof link.imageUrl === "string" && plain(link.imageUrl) !== "") resolved.imageUrl = link.imageUrl;
148
+ if (card !== void 0) {
149
+ const display = cardDisplay(link.display) ?? card.display;
150
+ if (display !== void 0) resolved.display = display;
151
+ }
152
+ if (card !== void 0 && resolved.display === "card") {
153
+ const resolvedCard = resolveCard(plain(link.kind), link, info, resolved.label);
154
+ if (resolvedCard === null) resolved.display = "link";
155
+ else resolved.card = resolvedCard;
156
+ }
157
+ return resolved;
158
+ }
159
+ /** A card needs a picture and a title, else it is a plain link. A product or collection card falls back to the target's own picture. */
160
+ function resolveCard(kind, link, info, title) {
161
+ const own = typeof link.imageUrl === "string" && plain(link.imageUrl) !== "" ? link.imageUrl : "";
162
+ const targetImage = (kind === "product" || kind === "collection") && typeof info?.image === "string" ? info.image : "";
163
+ const image = own !== "" ? own : targetImage;
164
+ if (plain(image) === "" || title === null) return null;
165
+ const card = {
166
+ image,
167
+ title
135
168
  };
169
+ if (kind === "product" && typeof info?.price === "number" && Number.isFinite(info.price)) card.price = info.price;
170
+ return card;
171
+ }
172
+ function resolveSection(value, context) {
173
+ const section = asRecord(value);
174
+ if (section === null) return null;
175
+ const heading = typeof section.heading === "string" ? section.heading : "";
176
+ const headingLink = resolveOne(section.headingLink, context, 1);
177
+ const sectionDisplay = cardDisplay(section.display);
178
+ const resolved = {
179
+ heading: plain(heading) !== "" ? heading : headingLink?.label ?? null,
180
+ headingLink,
181
+ links: (Array.isArray(section.links) ? section.links : []).map((link) => resolveOne(link, context, 1, { display: sectionDisplay })).filter((link) => link !== null),
182
+ seeAll: resolveSeeAll(section.seeAll, context)
183
+ };
184
+ if (sectionDisplay !== void 0) resolved.display = sectionDisplay;
185
+ return resolved;
186
+ }
187
+ function resolveSeeAll(value, context) {
188
+ const seeAll = asRecord(value);
189
+ if (seeAll === null) return null;
190
+ const link = resolveOne(seeAll.link, context, 1);
191
+ const label = typeof seeAll.label === "string" ? seeAll.label : "";
192
+ if (plain(label) !== "") return link === null ? {
193
+ href: null,
194
+ label,
195
+ newTab: false,
196
+ group: null,
197
+ children: []
198
+ } : {
199
+ ...link,
200
+ label
201
+ };
202
+ return link !== null && link.label !== null ? link : null;
203
+ }
204
+ function cardDisplay(value) {
205
+ const display = plain(value);
206
+ return display === "card" || display === "link" ? display : void 0;
136
207
  }
137
208
  function resolveHref(kind, link, info, context) {
138
209
  if (kind === "none") return null;
@@ -172,6 +243,9 @@ function targetInfo(target, context) {
172
243
  const key = targetKey(target);
173
244
  return key === null ? void 0 : context.targets.get(key);
174
245
  }
246
+ function asRecord(value) {
247
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
248
+ }
175
249
  function asLinkValue(value) {
176
250
  if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
177
251
  const record = value;
package/dist/overlay.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import "./stega.js";
2
+ import "./layout.js";
2
3
  import "./image-framing.js";
3
4
  import { n as createOverlayRuntime, t as classifyBeforeInput } from "./overlay-a8pghnYy.js";
4
- import "./layout.js";
5
5
  import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
6
6
  export { PREVIEW_ROUTER_MESSAGE_TYPES, classifyBeforeInput, createOverlayRuntime, createPreviewMessageRouter };
@@ -61,4 +61,49 @@ export declare class ReusableComponentSnapshotCache {
61
61
  * output. The returned model is shared by Vue preview and SSR/static output.
62
62
  */
63
63
  export declare function createReusableLayoutRenderModel(value: unknown, options: ReusableLayoutOptions): ReusableLayoutRenderModel;
64
+ /**
65
+ * A layout document with reusable placements, in the shape Core's **public** read serves it: each
66
+ * placement replaced in place by its component's content, the component's root taking the
67
+ * placement id and every node inside it the `r` + SHA-256 render id
68
+ * (`docs/theme-reusable-components.md`), and no projection left anywhere.
69
+ *
70
+ * A preview read keeps the placements and the projection, because Studio's overlay addresses a
71
+ * node inside a component by its authored id and its placement. A draft preview session has no
72
+ * overlay, and must render exactly what the published page renders, so it renders this shape
73
+ * instead (`@eldrajs/theme-nuxt`, WS-1358). Throws a `LayoutValidationError` for what the render
74
+ * would refuse; the caller keeps the document as it was, and the render then fails closed on it.
75
+ *
76
+ * `routeTemplate` admits placements in a version-1 document, as a route template does.
77
+ */
78
+ export declare function expandReusableLayout(value: unknown, projection: unknown, options?: {
79
+ routeTemplate?: boolean;
80
+ }): {
81
+ version: 1 | 2 | 3;
82
+ root: unknown;
83
+ };
84
+ /**
85
+ * A preview read's answer, in the shape Core's public read gives the same records (WS-1358): every
86
+ * entry in it — the answer itself, every list item, every resolved reference at any depth (a page's
87
+ * `parent`, a block, a list field's entries) — that carries a `reusableComponentProjection` is
88
+ * turned into its public read (`expandReusableComponentsForPublic` in Core's cms-service):
89
+ *
90
+ * - every placement expanded in place (`expandReusableLayout`; a document with `routePattern` is a
91
+ * route template, whose version-1 layout may place a component), and the projection dropped;
92
+ * - `blocks` put in the expanded layout's depth-first order (slot children by sorted slot id);
93
+ * - every node naming a block that is not among `blocks` removed, slot children with it, and
94
+ * `blocks` rebuilt from what remains;
95
+ * - every entry's `status` dropped (an object with `id`, `schemaId` and `data`, the envelope Core
96
+ * writes around a record): the public read has none.
97
+ *
98
+ * Anything else is left as it is: a document with no projection is served the same by both reads
99
+ * (Core prunes only a document that places a component), and a projection that does not expand is
100
+ * left for the render to fail closed on, as it would have. What the two reads differ in beyond
101
+ * this — an entry's `publishedAt` and `updatedAt` (Publish sets them) and a media item's `linkId`
102
+ * (one link row per owner) — is the draft's own and stays.
103
+ *
104
+ * A draft preview session's client applies it to every CMS answer (`enableSessionPreview`): a
105
+ * session has no overlay to address a component's nodes by their authored ids, and what it must
106
+ * render is what Publish puts live.
107
+ */
108
+ export declare function asPublicRead<T>(value: T): T;
64
109
  export { type ReusableComponentBinding, type ReusableComponentPlacement, type ReusableComponentProjection, type ReusableComponentResolver, type ReusableComponentRevision, type ReusableRenderIdentity, createProjectionResolver };
package/dist/reusable.js CHANGED
@@ -88,4 +88,128 @@ function componentPerspectiveKey(perspective, siteId, componentId) {
88
88
  function snapshotKey(perspective, componentId, siteId, revision) {
89
89
  return `${componentPerspectiveKey(perspective, siteId, componentId)}\0${revision}`;
90
90
  }
91
- export { ReusableComponentSnapshotCache, createProjectionResolver, createReusableLayoutRenderModel };
91
+ /**
92
+ * A layout document with reusable placements, in the shape Core's **public** read serves it: each
93
+ * placement replaced in place by its component's content, the component's root taking the
94
+ * placement id and every node inside it the `r` + SHA-256 render id
95
+ * (`docs/theme-reusable-components.md`), and no projection left anywhere.
96
+ *
97
+ * A preview read keeps the placements and the projection, because Studio's overlay addresses a
98
+ * node inside a component by its authored id and its placement. A draft preview session has no
99
+ * overlay, and must render exactly what the published page renders, so it renders this shape
100
+ * instead (`@eldrajs/theme-nuxt`, WS-1358). Throws a `LayoutValidationError` for what the render
101
+ * would refuse; the caller keeps the document as it was, and the render then fails closed on it.
102
+ *
103
+ * `routeTemplate` admits placements in a version-1 document, as a route template does.
104
+ */
105
+ function expandReusableLayout(value, projection, options = {}) {
106
+ const envelope = asObject(value, "");
107
+ if (envelope.version !== 1 && envelope.version !== 2 && envelope.version !== 3) failLayout("/version", "INVALID_VALUE");
108
+ const expansion = expandReusablePlacements({
109
+ root: envelope.root,
110
+ path: "/root",
111
+ projection,
112
+ allowReusable: options.routeTemplate === true || envelope.version !== 1
113
+ });
114
+ return {
115
+ version: envelope.version,
116
+ root: expansion.root
117
+ };
118
+ }
119
+ function isPlainRecord(value) {
120
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
121
+ }
122
+ /**
123
+ * A preview read's answer, in the shape Core's public read gives the same records (WS-1358): every
124
+ * entry in it — the answer itself, every list item, every resolved reference at any depth (a page's
125
+ * `parent`, a block, a list field's entries) — that carries a `reusableComponentProjection` is
126
+ * turned into its public read (`expandReusableComponentsForPublic` in Core's cms-service):
127
+ *
128
+ * - every placement expanded in place (`expandReusableLayout`; a document with `routePattern` is a
129
+ * route template, whose version-1 layout may place a component), and the projection dropped;
130
+ * - `blocks` put in the expanded layout's depth-first order (slot children by sorted slot id);
131
+ * - every node naming a block that is not among `blocks` removed, slot children with it, and
132
+ * `blocks` rebuilt from what remains;
133
+ * - every entry's `status` dropped (an object with `id`, `schemaId` and `data`, the envelope Core
134
+ * writes around a record): the public read has none.
135
+ *
136
+ * Anything else is left as it is: a document with no projection is served the same by both reads
137
+ * (Core prunes only a document that places a component), and a projection that does not expand is
138
+ * left for the render to fail closed on, as it would have. What the two reads differ in beyond
139
+ * this — an entry's `publishedAt` and `updatedAt` (Publish sets them) and a media item's `linkId`
140
+ * (one link row per owner) — is the draft's own and stays.
141
+ *
142
+ * A draft preview session's client applies it to every CMS answer (`enableSessionPreview`): a
143
+ * session has no overlay to address a component's nodes by their authored ids, and what it must
144
+ * render is what Publish puts live.
145
+ */
146
+ function asPublicRead(value) {
147
+ if (Array.isArray(value)) return value.map((item) => asPublicRead(item));
148
+ if (!isPlainRecord(value)) return value;
149
+ const walked = {};
150
+ for (const [key, child] of Object.entries(value)) walked[key] = key === "reusableComponentProjection" ? child : asPublicRead(child);
151
+ return publicDocument(withoutEntryStatus(walked));
152
+ }
153
+ /** An entry's envelope without `status`: the public read drops it, a preview read keeps it. */
154
+ function withoutEntryStatus(record) {
155
+ if (!("status" in record && "id" in record && "schemaId" in record && "data" in record)) return record;
156
+ const { status: _status, ...rest } = record;
157
+ return rest;
158
+ }
159
+ function publicDocument(doc) {
160
+ if (!("reusableComponentProjection" in doc) || !isPlainRecord(doc.data)) return doc;
161
+ const { reusableComponentProjection, ...rest } = doc;
162
+ const data = doc.data;
163
+ let layout;
164
+ try {
165
+ layout = expandReusableLayout(data.layout, reusableComponentProjection, { routeTemplate: typeof data.routePattern === "string" });
166
+ } catch {
167
+ return doc;
168
+ }
169
+ if (!Array.isArray(data.blocks)) return {
170
+ ...rest,
171
+ data: {
172
+ ...data,
173
+ layout
174
+ }
175
+ };
176
+ const byId = /* @__PURE__ */ new Map();
177
+ for (const block of data.blocks) if (isPlainRecord(block) && typeof block.id === "string" && !byId.has(block.id)) byId.set(block.id, block);
178
+ const missing = new Set(layoutBlockEntryIds(layout.root).filter((id) => !byId.has(id)));
179
+ const root = missing.size === 0 ? layout.root : pruneLayoutBlocks(layout.root, missing);
180
+ const blocks = layoutBlockEntryIds(root).map((id) => byId.get(id));
181
+ return {
182
+ ...rest,
183
+ data: {
184
+ ...data,
185
+ layout: {
186
+ ...layout,
187
+ root
188
+ },
189
+ blocks
190
+ }
191
+ };
192
+ }
193
+ /** A layout's block entry ids, depth-first, slot children by sorted slot id (Core's order). */
194
+ function layoutBlockEntryIds(node, into = []) {
195
+ if (!isPlainRecord(node)) return into;
196
+ if (typeof node.entryId === "string" && node.entryId !== "") into.push(node.entryId);
197
+ if (Array.isArray(node.children)) for (const child of node.children) layoutBlockEntryIds(child, into);
198
+ if (isPlainRecord(node.slots)) {
199
+ const slots = node.slots;
200
+ for (const slot of Object.keys(slots).sort()) {
201
+ const children = slots[slot];
202
+ if (Array.isArray(children)) for (const child of children) layoutBlockEntryIds(child, into);
203
+ }
204
+ }
205
+ return into;
206
+ }
207
+ function pruneLayoutBlocks(node, missing) {
208
+ if (!isPlainRecord(node)) return node;
209
+ const keep = (children) => children.filter((child) => !(isPlainRecord(child) && typeof child.entryId === "string" && missing.has(child.entryId))).map((child) => pruneLayoutBlocks(child, missing));
210
+ const out = { ...node };
211
+ if (Array.isArray(node.children)) out.children = keep(node.children);
212
+ if (isPlainRecord(node.slots)) out.slots = Object.fromEntries(Object.entries(node.slots).map(([slot, children]) => [slot, Array.isArray(children) ? keep(children) : children]));
213
+ return out;
214
+ }
215
+ export { ReusableComponentSnapshotCache, asPublicRead, createProjectionResolver, createReusableLayoutRenderModel, expandReusableLayout };
@@ -1,3 +1,3 @@
1
- import { a as TemplateLayoutDocument, c as TemplateLayoutRenderNode, i as TemplateLayoutContext, l as buildTemplateBlockRenames, n as TemplateBlockFieldDefinition, o as TemplateLayoutNode, r as TemplateBlockNode, s as TemplateLayoutRenderModel, t as TemplateBlockDefinition, u as createTemplateLayoutRenderModel } from "./templateLayout-Dp3KYV2b.js";
1
+ import { a as TemplateLayoutDocument, c as TemplateLayoutRenderNode, i as TemplateLayoutContext, l as buildTemplateBlockRenames, n as TemplateBlockFieldDefinition, o as TemplateLayoutNode, r as TemplateBlockNode, s as TemplateLayoutRenderModel, t as TemplateBlockDefinition, u as createTemplateLayoutRenderModel } from "./templateLayout-BWNs1ZYt.js";
2
2
  import { n as ReusableComponentPlacement, o as ReusableRenderIdentity, r as ReusableComponentProjection } from "./reusableExpansion-CqrqpK4A.js";
3
3
  export { type ReusableComponentPlacement, type ReusableComponentProjection, type ReusableRenderIdentity, TemplateBlockDefinition, TemplateBlockFieldDefinition, TemplateBlockNode, TemplateLayoutContext, TemplateLayoutDocument, TemplateLayoutNode, TemplateLayoutRenderModel, TemplateLayoutRenderNode, buildTemplateBlockRenames, createTemplateLayoutRenderModel };
@@ -47,7 +47,34 @@ interface EldraClientOptions {
47
47
  declare class EldraClientError extends Error {
48
48
  readonly status: number;
49
49
  readonly path: string;
50
- constructor(status: number, statusText: string, path: string);
50
+ /**
51
+ * The refusal's `errorId`, when the answer named one. Read only from a draft preview session's
52
+ * reads (`enableSessionPreview`), where the preview router answers `application/problem+json` and
53
+ * the id says which notice to show (`SITE_PREVIEW_SESSION_EXPIRED`, `_REVOKED`, …). `null`
54
+ * everywhere else: an ordinary read's failure body is never read.
55
+ */
56
+ readonly errorId: string | null;
57
+ /** Whether the failed request was a draft preview session read through the same-origin proxy. */
58
+ readonly sessionPreview: boolean;
59
+ constructor(status: number, statusText: string, path: string, details?: {
60
+ errorId?: string | null;
61
+ sessionPreview?: boolean;
62
+ });
63
+ }
64
+ /** The site settings `getSiteSetting` reads. */
65
+ type EldraSiteReadPath = '/site/v1/design-tokens' | '/site/v1/theme-messages';
66
+ /**
67
+ * A draft preview session (`enableSessionPreview`): the page is served by Eldra's preview router on
68
+ * a host of its own, and the router holds the session's credential in an HttpOnly cookie.
69
+ */
70
+ interface EldraSessionPreviewOptions {
71
+ /**
72
+ * Where the router's draft read proxy lives: an absolute URL **on the page's own origin** (the
73
+ * router serves it at `/__eldra/gateway`), with no trailing path beyond it. A gateway path is
74
+ * appended without its `/api` prefix, exactly as `gatewayUrl` takes it. Anything that is not the
75
+ * page's own origin is refused, because the reads carry the session cookie.
76
+ */
77
+ proxyBase: string;
51
78
  }
52
79
  interface PageMeta {
53
80
  hasNext: boolean;
@@ -143,6 +170,38 @@ interface EldraClient {
143
170
  enablePreview(token: string): void;
144
171
  disablePreview(): void;
145
172
  readonly previewEnabled: boolean;
173
+ /**
174
+ * Switch the CMS reads to a draft preview session's same-origin proxy, for good: every
175
+ * `getEntries`/`getEntry`/`getEntryByUniqueField`/`resolveEntryListField`/`resolveEntryList` goes
176
+ * to `proxyBase` + the gateway path, with `cache: 'no-store'`, `credentials: 'same-origin'` and
177
+ * **no credential header** (no `X-Org-Id`, `X-Preview-Token` or build token; the router adds what
178
+ * Core needs). A CMS answer without `Eldra-Preview: draft` is refused (`502`,
179
+ * `PREVIEW_UPSTREAM_NOT_PREVIEW`) rather than shown, so a published answer never passes for a
180
+ * draft. Catalog reads stay on `gatewayUrl`, published and unchanged. From then on no request
181
+ * carries `X-Preview-Token`, whatever `enablePreview` is given.
182
+ *
183
+ * **Optional**, like `onRequestError`: a hand-written client predates it, and a caller that cannot
184
+ * find it has no session preview to offer.
185
+ */
186
+ enableSessionPreview?(options: EldraSessionPreviewOptions): void;
187
+ /** Whether `enableSessionPreview` has been called. Optional for the same reason. */
188
+ readonly sessionPreviewEnabled?: boolean;
189
+ /**
190
+ * One of the site's own settings, as the gateway serves it (`EldraSiteReadPath`): the saved design
191
+ * tokens (`{ revision, resolved }`) or the resolved theme texts (`{ defaultLocale, locales }`),
192
+ * parsed JSON, unchecked. A build reads these once and bakes them in; a draft preview session reads
193
+ * them again at runtime, so a saved change shows at once (WS-1394).
194
+ *
195
+ * Outside a session, an ordinary gateway read (`X-Org-Id`, the build token). In a session, through
196
+ * the router's proxy like the CMS reads (`no-store`, `credentials: 'same-origin'`, no credential
197
+ * header), but a site setting is not a draft: no `Eldra-Preview: draft` is asked for, the answer is
198
+ * not reshaped, and a failure is thrown to the caller only, never reported to `onRequestError`'s
199
+ * listeners — the CMS reads are what say whether the session holds, and a router that does not
200
+ * forward a site read yet must not end the session.
201
+ *
202
+ * **Optional**, like `enableSessionPreview`: a hand-written client predates it.
203
+ */
204
+ getSiteSetting?(path: EldraSiteReadPath): Promise<unknown>;
146
205
  /**
147
206
  * Subscribe to failed gateway requests; returns an unsubscribe.
148
207
  *
@@ -256,4 +315,4 @@ interface TemplateLayoutContext {
256
315
  reusableComponentProjection?: ReusableComponentProjection;
257
316
  }
258
317
  declare function createTemplateLayoutRenderModel(value: unknown, context: TemplateLayoutContext): TemplateLayoutRenderModel;
259
- export { ResolveEntryListBody as C, PageMeta as S, EldraClientOptions as _, TemplateLayoutDocument as a, EntryList as b, TemplateLayoutRenderNode as c, CatalogDoc as d, CatalogList as f, EldraClientError as g, EldraClient as h, TemplateLayoutContext as i, buildTemplateBlockRenames as l, EldraCatalogReader as m, TemplateBlockFieldDefinition as n, TemplateLayoutNode as o, CatalogQuery as p, TemplateBlockNode as r, TemplateLayoutRenderModel as s, TemplateBlockDefinition as t, createTemplateLayoutRenderModel as u, EldraRetryOptions as v, EntryQuery as x, EntryDoc as y };
318
+ export { EntryQuery as C, EntryList as S, ResolveEntryListBody as T, EldraClientOptions as _, TemplateLayoutDocument as a, EldraSiteReadPath as b, TemplateLayoutRenderNode as c, CatalogDoc as d, CatalogList as f, EldraClientError as g, EldraClient as h, TemplateLayoutContext as i, buildTemplateBlockRenames as l, EldraCatalogReader as m, TemplateBlockFieldDefinition as n, TemplateLayoutNode as o, CatalogQuery as p, TemplateBlockNode as r, TemplateLayoutRenderModel as s, TemplateBlockDefinition as t, createTemplateLayoutRenderModel as u, EldraRetryOptions as v, PageMeta as w, EntryDoc as x, EldraSessionPreviewOptions as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eldrajs/theme-core",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
4
4
  "description": "Framework-free core of the Eldra theme SDK: the Studio preview bridge, stega encoding, the overlay runtime, layout CSS, rich-text positions, design tokens and image framing.",
5
5
  "keywords": [
6
6
  "cms",