@aglyn/tenant-runtime 1.0.0-beta.225 → 1.0.0-beta.226

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-runtime",
3
- "version": "1.0.0-beta.225",
3
+ "version": "1.0.0-beta.226",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,11 +25,11 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.225",
29
- "@aglyn/shared-data-types": "1.0.0-beta.225",
30
- "@aglyn/shared-ui-theme": "1.0.0-beta.225",
31
- "@aglyn/shared-util-http": "1.0.0-beta.225",
32
- "@aglyn/tenant-data-admin": "1.0.0-beta.225",
28
+ "@aglyn/aglyn": "1.0.0-beta.226",
29
+ "@aglyn/shared-data-types": "1.0.0-beta.226",
30
+ "@aglyn/shared-ui-theme": "1.0.0-beta.226",
31
+ "@aglyn/shared-util-http": "1.0.0-beta.226",
32
+ "@aglyn/tenant-data-admin": "1.0.0-beta.226",
33
33
  "@swc/helpers": "0.5.23"
34
34
  },
35
35
  "peerDependencies": {
@@ -32,6 +32,8 @@ interface FallbackEntry {
32
32
  coverImage?: string;
33
33
  /** The featured video (AGL-2956); plays in the cover's place. */
34
34
  coverVideo?: string;
35
+ /** Its length in seconds (AGL-3584); the Video's `durationSeconds`. */
36
+ coverVideoDuration?: number;
35
37
  /** Meta description override (AGL-582); falls back to `excerpt`. */
36
38
  seoDescription?: string;
37
39
  /** Stable taxonomy reference (AGL-582); wins over `category`. */
@@ -179,7 +179,10 @@ const typography = (suffix, props)=>[
179
179
  * `{{entry.seoDescription}}` does, and the ISO publish instant
180
180
  * `{{entry.publishedAt}}` resolves to. An instant rather than a calendar day:
181
181
  * the builder publishes `uploadDate` as a date-time with a zone, and it keeps
182
- * an instant as given where it would publish a bare day at noon UTC.
182
+ * an instant as given where it would publish a bare day at noon UTC. The
183
+ * film's length rides along when the entry names one (AGL-3584), as
184
+ * `{{entry.coverVideoDuration}}` would bind it, and becomes the block's
185
+ * `duration`.
183
186
  *
184
187
  * `undefined` rather than a Video node in two cases, because the element's
185
188
  * answer to each is a labeled placeholder, which a published article must
@@ -214,6 +217,7 @@ const typography = (suffix, props)=>[
214
217
  if (videoEmbedOf(src) && !poster) return undefined;
215
218
  const description = entry.seoDescription || entry.excerpt || '';
216
219
  const uploadDate = Aglyn.collectionEntryPublishedAtIso(entry.publishedAt);
220
+ const durationSeconds = Aglyn.collectionEntryVideoDurationSeconds(entry.coverVideoDuration);
217
221
  return _extends({
218
222
  src
219
223
  }, poster ? {
@@ -224,6 +228,8 @@ const typography = (suffix, props)=>[
224
228
  description
225
229
  } : {}, uploadDate ? {
226
230
  uploadDate
231
+ } : {}, durationSeconds ? {
232
+ durationSeconds
227
233
  } : {}, {
228
234
  width: '100%'
229
235
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/collection-fallback-nodes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { videoEmbedOf } from '@aglyn/aglyn/plugin-manager/video-embed-provider'\nimport * as Aglyn from '@aglyn/aglyn/server'\n\n/** Namespaces the synthetic fallback node ids (never persisted). */\nconst FALLBACK_ID_PREFIX = 'cfb__'\n\nconst id = (suffix: string) => `${FALLBACK_ID_PREFIX}${suffix}`\n\ntype NodesMap = Record<string, Aglyn.AglynNodeSchema>\n\ninterface FallbackCollection {\n slug: string\n displayName: string\n /** Category taxonomy (AGL-582) for `categoryId` → name resolution. */\n categories?: Aglyn.CollectionCategory[]\n}\n\ninterface FallbackEntry {\n title?: string\n slug?: string\n excerpt?: string\n /** Per-entry byline (AGL-686); falls back to the site as author. */\n authorName?: string\n body?: string\n coverImage?: string\n /** The featured video (AGL-2956); plays in the cover's place. */\n coverVideo?: string\n /** Meta description override (AGL-582); falls back to `excerpt`. */\n seoDescription?: string\n /** Stable taxonomy reference (AGL-582); wins over `category`. */\n categoryId?: string\n /** Legacy free-typed category (AGL-582); read-only fallback. */\n category?: string\n tags?: string[]\n publishedAt?: { seconds: number } | null\n}\n\n// The one shared formatter (AGL-1926). This composes server-side, so the\n// inline `toLocaleDateString()` it replaces was not itself a hydration\n// mismatch — but it was a THIRD spelling of \"the entry's published date\",\n// free to drift from the byline and the related-post card that quote the\n// same instant. Pinned locale and zone, so all three agree by construction.\nconst formatDate = (value?: { seconds: number } | null, timeZone?: string) =>\n Aglyn.formatCollectionEntryDate(value, undefined, undefined, timeZone)\n\n/**\n * What may be interpolated into the cover block's CSS `url(\"…\")` (AGL-1407).\n *\n * The gate this replaces was `/^https?:\\/\\//i`, which answered the safety\n * question correctly and the coverage question wrongly: it admitted only the\n * OLDEST of the stored generations. A `media:` reference failed it and the\n * cover block was never emitted — a SILENT drop, no error, no placeholder,\n * just a page missing its picture — and so did the AGL-175 relative CDN path\n * that the first pass at media references wrote. Resolving before testing is\n * what closes that, and the test then has to accept a site-relative path,\n * which is what {@link Aglyn.resolveMediaSrc} returns for a reference.\n *\n * Still a scheme allowlist rather than \"anything non-empty\": this value lands\n * inside a stylesheet rather than in an `<img src>`, so `data:` and friends\n * have no business here even though {@link cssUrlValue} already makes\n * quote-breaking impossible. A bare relative `cover.png` stays rejected\n * exactly as before — there is no page for it to resolve against at compose\n * time.\n *\n * `http:` was dropped for AGL-1725. AGL-1701 found two paths accepting it;\n * markdown-lite is AGL-1713 and this was the second, separate one. It is the\n * only scheme change here, and it is not a host restriction: an author\n * hotlinking their own https cover keeps working, because on a published\n * site the author IS the site owner and the audience is their own visitors.\n * `http:` alone has no defensible use — the request is mixed passive content\n * that current browsers already block or auto-upgrade, so the author gains\n * nothing from it, while the plaintext fetch discloses which article a\n * visitor is reading to every observer on the network path.\n *\n * The consequence of the drop is the SILENT DROP this whole comment is about,\n * for `http:` covers only: no cover node is emitted. That is the correct\n * trade here and the browser was very likely refusing the image anyway, but\n * it is the reason the change is one scheme and not a host list.\n */\nconst RENDERABLE_COVER_URL = /^(?:https:\\/\\/|\\/)/i\n\n/**\n * A URL made safe to sit inside `url(\"…\")`, WITHOUT re-encoding it.\n *\n * This replaces `encodeURI`, which was the wrong tool and quietly broke the\n * commonest stored form: `encodeURI` escapes `%`, so every raw firebasestorage\n * download URL — whose object path is `orgs%2F…%2Fmedia%2F…` — came out\n * double-encoded as `%252F` and 404'd. The block rendered, the image did not,\n * which is why it survived: the page looks composed and the picture is just\n * missing.\n *\n * Only the characters that could END the CSS string are escaped, and they are\n * escaped percent-wise rather than with a backslash so the result is still a\n * valid URL if anything downstream reads it as one. `encodeURI` was never\n * needed for anything else here — a stored URL is already URL-encoded.\n */\nconst cssUrlValue = (url: string) =>\n url.replace(/[\"\\\\\\n\\r]/g, (char) => encodeURIComponent(char))\n\n/**\n * Container width for the built-in entry article: the PROSE case of the\n * Container standard (AGL-1298), not an arbitrary narrow default. A\n * collection entry is an article body, and `xl` — the section default — runs\n * a paragraph past 180 characters a line. Stock breakpoint, no bespoke\n * number.\n */\nconst ENTRY_MAX_WIDTH = 'md'\n\n/**\n * Container width for the built-in listing: the section default. A listing is\n * a card grid rather than a reading column, so the entry's prose width is the\n * wrong measure for it, and the authored list screens render at this same\n * `xl` (AGL-2567). Still a stock breakpoint, so the AGL-1298 rule holds.\n */\nconst LIST_MAX_WIDTH = 'xl'\n\n/**\n * Vertical rhythm between the built-in listing's sections, in MUI theme\n * spacing units: `theme.spacing(6)` resolves to 48px, the same rhythm the\n * authored list screens carry, so a generated listing and an authored one\n * read as one product (AGL-2567).\n *\n * A theme token rather than a pixel string: a hand-written length here\n * answers to no theme, and a length missing its unit is a valid-looking\n * value the browser drops.\n *\n * @see https://mui.com/material-ui/customization/spacing/\n */\nconst LIST_SECTION_GAP = 6\n\n/** The page shell's width and the rhythm of the stack that holds sections. */\ninterface ShellLayout {\n /** Stock Container breakpoint (AGL-1298); never a bespoke pixel cap. */\n maxWidth: typeof ENTRY_MAX_WIDTH | typeof LIST_MAX_WIDTH\n /** Props for the content stack the page's sections slot into. */\n stackProps: Record<string, unknown>\n}\n\n/** The entry article's shell: reading column, sections close together. */\nconst entryShell = (): ShellLayout => ({\n maxWidth: ENTRY_MAX_WIDTH,\n stackProps: { spacing: 2 },\n})\n\n/**\n * The listing's shell: full section width, sections on the 48px rhythm.\n *\n * The gap is declared on the stack's `sx` rather than left to the Stack's own\n * `spacing`, which is the shape the authored list screens carry: one\n * `row-gap` on the flex container, so every section is spaced by the same\n * declaration instead of by margins that a section's own styling can collapse\n * or override.\n */\nconst listShell = (): ShellLayout => ({\n maxWidth: LIST_MAX_WIDTH,\n stackProps: {\n sx: {\n display: 'flex',\n flexDirection: 'column',\n gap: LIST_SECTION_GAP,\n },\n },\n})\n\n/** Root → centered container → content stack; children slot underneath. */\nfunction shell(childIds: string[], layout: ShellLayout): NodesMap {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: [id('container')],\n },\n [id('container')]: {\n $id: id('container'),\n componentId: 'muiContainer',\n pluginId: 'mui',\n parentId: Aglyn.NODE_ROOT_ID,\n props: {\n maxWidth: layout.maxWidth,\n sx: { paddingTop: 6, paddingBottom: 6 },\n },\n nodes: [id('stack')],\n },\n [id('stack')]: {\n $id: id('stack'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('container'),\n props: layout.stackProps,\n nodes: childIds,\n },\n }\n}\n\nconst typography = (\n suffix: string,\n props: Record<string, unknown>,\n): AglynNodeEntry => [\n id(suffix),\n {\n $id: id(suffix),\n componentId: 'muiTypography',\n pluginId: 'mui',\n parentId: id('stack'),\n props,\n },\n]\n\ntype AglynNodeEntry = [string, Aglyn.AglynNodeSchema]\n\n/**\n * The Video node's props for an entry's featured video, or `undefined` when\n * the entry has none this page can play (AGL-2956).\n *\n * An entry of a video collection is an article whose film sits where a post's\n * cover would, and on the built-in page nobody is there to bind one. So the\n * props carry what a designer would bind by hand: the source, the cover as\n * the poster, and the three facts the page's `VideoObject` is built from —\n * the title, the SEO description falling back to the excerpt as\n * `{{entry.seoDescription}}` does, and the ISO publish instant\n * `{{entry.publishedAt}}` resolves to. An instant rather than a calendar day:\n * the builder publishes `uploadDate` as a date-time with a zone, and it keeps\n * an instant as given where it would publish a bare day at noon UTC.\n *\n * `undefined` rather than a Video node in two cases, because the element's\n * answer to each is a labeled placeholder, which a published article must\n * never show:\n *\n * - a source nothing resolves, such as an empty field or a malformed `media:`\n * reference;\n * - a hosted player's link (one a plugin declares, core\n * `video-embed-provider.ts`) with no poster. Its player loads only when a\n * visitor presses the poster, so without one there is nothing to press.\n *\n * The page then renders as a cover article, exactly as it does for an entry\n * with no video.\n *\n * The poster is the stored reference, not a resolved URL, so the element and\n * the structured data each resolve it against the site rendering the page. It\n * is passed only when the cover's own scheme rule would render it, so this\n * page never shows a still as a poster that it refuses as a cover.\n *\n * The film takes the cover's whole slot in the reading column, whose stock\n * `md` container bounds it; the column is the width limit rather than a pixel\n * cap (AGL-1298).\n */\nfunction featuredVideoProps(\n entry: FallbackEntry,\n options: { hostId?: string; posterRenders: boolean },\n): Record<string, unknown> | undefined {\n const src = (entry.coverVideo ?? '').trim()\n if (!src || !Aglyn.resolveMediaSrc(src, { hostId: options.hostId })) {\n return undefined\n }\n const poster = options.posterRenders ? entry.coverImage : undefined\n if (videoEmbedOf(src) && !poster) return undefined\n const description = entry.seoDescription || entry.excerpt || ''\n const uploadDate = Aglyn.collectionEntryPublishedAtIso(entry.publishedAt)\n return {\n src,\n ...(poster ? { poster } : {}),\n title: entry.title ?? '',\n ...(description ? { description } : {}),\n ...(uploadDate ? { uploadDate } : {}),\n width: '100%',\n }\n}\n\n/**\n * Built-in entry article as canvas nodes (AGL-551): when a collection has\n * no entry-template screen, `/{collection}/{entry}` renders these through\n * the normal compose pipeline — site theme, shared layout chrome, and the\n * markdown-rendering Entry body block — instead of the old unthemed HTML.\n */\nexport function buildCollectionEntryFallbackNodes(\n collection: FallbackCollection,\n entry: FallbackEntry,\n /**\n * The site being composed, so an org-scoped reference is host-qualified the\n * way every other render surface qualifies one (AGL-1043/AGL-1407). Optional\n * because a bare org reference still resolves without it; passing it is what\n * lets an asset restricted to this site resolve at all.\n */\n hostId?: string,\n /** The site's zone (AGL-3237); UTC when a site has not named one. */\n timeZone?: string,\n): NodesMap {\n const entries: AglynNodeEntry[] = [\n typography('title', {\n variant: 'h3',\n component: 'h1',\n children: entry.title ?? '',\n }),\n ]\n const date = formatDate(entry.publishedAt, timeZone)\n const tags = (entry.tags ?? []).filter(Boolean)\n // Category name resolves against the collection's taxonomy (AGL-582):\n // `categoryId` lookup first, legacy free-typed string fallback.\n const categoryName =\n Aglyn.resolveEntryCategoryName(entry, collection.categories) ?? ''\n if (date || categoryName || tags.length) {\n // Entry meta block (AGL-582): \"date · category\" line + tag chips.\n entries.push([\n id('meta'),\n {\n $id: id('meta'),\n componentId: Aglyn.COLLECTION_ENTRY_META_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n date,\n category: categoryName,\n tags: tags.join(', '),\n },\n },\n ])\n }\n // The cover, through the ONE shared resolver (AGL-1407). A `media:`\n // reference becomes the site-relative CDN path; a raw storage URL, an\n // AGL-175 CDN path and an author's own hotlinked URL all pass through\n // untouched, which is the documented precedence in `media-ref.ts`.\n const coverImage = Aglyn.resolveMediaSrc(entry.coverImage, { hostId })\n const coverRenders = Boolean(\n coverImage && RENDERABLE_COVER_URL.test(coverImage),\n )\n // A featured video takes the cover's slot, with the cover as its poster\n // (AGL-2956); see `featuredVideoProps` for when an entry has one to play.\n const video = featuredVideoProps(entry, {\n hostId,\n posterRenders: coverRenders,\n })\n if (video) {\n entries.push([\n id('video'),\n {\n $id: id('video'),\n componentId: Aglyn.VIDEO_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: video,\n },\n ])\n } else if (coverRenders) {\n // Rendered as a background image on a plain stack, NOT through the\n // first-party `image` component — that component crashes tenant SSR\n // (AGL-579); the background-image approach is proven safe.\n entries.push([\n id('cover'),\n {\n $id: id('cover'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n role: 'img',\n 'aria-label': entry.title ?? '',\n sx: {\n backgroundImage: `url(\"${cssUrlValue(coverImage)}\")`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n borderRadius: 1,\n minHeight: 320,\n },\n },\n },\n ])\n }\n entries.push([\n id('body'),\n {\n $id: id('body'),\n componentId: Aglyn.COLLECTION_ENTRY_BODY_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: { markdown: entry.body ?? '' },\n },\n ])\n // Related posts after the body, share bar at the end (AGL-582); the\n // compose pipeline stamps the related entries server-side.\n entries.push([\n id('related'),\n {\n $id: id('related'),\n componentId: Aglyn.COLLECTION_RELATED_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: { heading: 'Related articles', limit: 3, sx: { paddingTop: 2 } },\n },\n ])\n entries.push([\n id('share'),\n {\n $id: id('share'),\n componentId: Aglyn.COLLECTION_SHARE_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: {},\n },\n ])\n entries.push([\n id('back'),\n {\n $id: id('back'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n href: `/${collection.slug}`,\n children: `← ${collection.displayName}`,\n sx: { alignSelf: 'flex-start' },\n },\n },\n ])\n return {\n ...shell(\n entries.map(([entryId]) => entryId),\n entryShell(),\n ),\n ...Object.fromEntries(entries),\n }\n}\n\n/** Pagination state for the built-in list (AGL-620). */\nexport interface FallbackListPagination {\n page: number\n perPage: number\n /** @deprecated AGL-3219 — absent past one read's bound. */\n totalPages?: number\n /** The older page's cursor, or `''`/absent when there is none (AGL-3219). */\n nextCursor?: string\n /** The newer page's cursor. */\n prevCursor?: string\n}\n\n/** The routed category for a filtered listing (AGL-1321). */\nexport interface FallbackListCategory {\n slug: string\n name: string\n}\n\n/**\n * Prev/next nav over the cursor addresses (AGL-620, AGL-3219).\n *\n * The label says \"Page 4 of 9\" only where nine is a number that can be known\n * — a collection small enough to be read in one go. Past that it says \"Page\n * 4\" and stops, because the alternative is a total derived from a count the\n * listing's own reads could disagree with, which is how page 10 of a\n * seventeen-page changelog came to call itself the last one.\n */\nfunction paginationNodes(\n collection: FallbackCollection,\n pagination: FallbackListPagination,\n category?: FallbackListCategory,\n): { childId: string; nodes: NodesMap } {\n // Page 1 lives at the bare listing; deeper pages at .../page/{n}. Built\n // through the shared pager computation so this fallback and the\n // `{{pagination.*}}` tokens an authored template binds (AGL-1386) can never\n // disagree — and so the pager stays inside the category it is paging\n // (AGL-1321): a \"next\" that dropped the filter would silently return the\n // reader to the unfiltered list. An edge is the empty string, which is\n // exactly the \"no link here\" this fallback already meant.\n const { page, totalPages, prevUrl, nextUrl } = Aglyn.collectionPaginationLinks(\n {\n collectionSlug: collection.slug,\n ...(category ? { categorySlug: category.slug } : {}),\n page: pagination.page,\n ...(pagination.totalPages === undefined\n ? {}\n : { totalPages: pagination.totalPages }),\n nextCursor: pagination.nextCursor ?? '',\n prevCursor: pagination.prevCursor ?? '',\n },\n )\n const children: string[] = []\n const nodes: NodesMap = {}\n if (prevUrl) {\n nodes[id('prev')] = {\n $id: id('prev'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('pager'),\n props: { href: prevUrl, children: '← Newer' },\n }\n children.push(id('prev'))\n }\n nodes[id('pageinfo')] = {\n $id: id('pageinfo'),\n componentId: 'muiTypography',\n pluginId: 'mui',\n parentId: id('pager'),\n props: {\n variant: 'body2',\n children: totalPages > 1 ? `Page ${page} of ${totalPages}` : `Page ${page}`,\n sx: { color: 'text.secondary' },\n },\n }\n children.push(id('pageinfo'))\n if (nextUrl) {\n nodes[id('next')] = {\n $id: id('next'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('pager'),\n props: { href: nextUrl, children: 'Older →' },\n }\n children.push(id('next'))\n }\n nodes[id('pager')] = {\n $id: id('pager'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n direction: 'row',\n spacing: 3,\n sx: { alignItems: 'center', justifyContent: 'center' },\n },\n nodes: children,\n }\n return { childId: id('pager'), nodes }\n}\n\n/**\n * Built-in entry list as canvas nodes (AGL-551): a heading plus a\n * Collection entries block whose template (title, date, excerpt, Read\n * more) the compose pipeline expands over the published entries — the same\n * block designers drop onto their own list-template screens. With\n * `pagination` (AGL-620) the block renders one page and prev/next nav links\n * to `/{slug}/page/{n}`.\n */\nexport function buildCollectionListFallbackNodes(\n collection: FallbackCollection,\n hasEntries: boolean,\n pagination?: FallbackListPagination,\n category?: FallbackListCategory,\n): NodesMap {\n const [titleId, title] = typography('title', {\n variant: 'h3',\n component: 'h1',\n // A filtered listing says which slice it is (AGL-1321) — a page of\n // Guides whose only heading reads \"Blog\" tells the reader nothing about\n // why the other posts vanished.\n children: category\n ? `${collection.displayName} · ${category.name}`\n : collection.displayName,\n })\n // Category pills (AGL-1321): stamped by `expandCollectionCategories` during\n // compose, from the same taxonomy this node's collection carries. Present\n // in the EMPTY case too — a filtered listing with no entries whose pills\n // vanished would be a dead end with no way back to \"All\".\n const pills = collection.categories?.length\n ? {\n $id: id('pills'),\n componentId: Aglyn.COLLECTION_CATEGORIES_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: { allLabel: 'All' },\n }\n : null\n const lead = pills ? [titleId, id('pills')] : [titleId]\n if (!hasEntries) {\n const [emptyId, empty] = typography('empty', {\n variant: 'body1',\n children: category\n ? `Nothing published in ${category.name} yet.`\n : 'Nothing published yet.',\n sx: { color: 'text.secondary' },\n })\n return {\n ...shell([...lead, emptyId], listShell()),\n [titleId]: title,\n ...(pills ? { [id('pills')]: pills } : {}),\n [emptyId]: empty,\n }\n }\n const item = (suffix: string, props: Record<string, unknown>) => ({\n $id: id(suffix),\n componentId: 'muiTypography' as const,\n pluginId: 'mui',\n parentId: id('item'),\n props,\n })\n /*\n * A pager exists when there is somewhere to go (AGL-3219): an older page,\n * proved by the cursor probe, or a newer one, proved by being past the\n * first. `totalPages > 1` used to stand in for that and could not, once the\n * total stopped being knowable.\n */\n const pager =\n pagination &&\n (Boolean(pagination.nextCursor) ||\n pagination.page > 1 ||\n (pagination.totalPages ?? 0) > 1)\n ? paginationNodes(collection, pagination, category)\n : null\n return {\n ...shell(\n pager\n ? [...lead, id('entries'), pager.childId]\n : [...lead, id('entries')],\n listShell(),\n ),\n [titleId]: title,\n ...(pills ? { [id('pills')]: pills } : {}),\n [id('entries')]: {\n $id: id('entries'),\n componentId: Aglyn.COLLECTION_ENTRIES_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n spacing: 4,\n ...(pagination\n ? { perPage: pagination.perPage, page: pagination.page }\n : {}),\n },\n nodes: [id('item')],\n },\n ...(pager ? pager.nodes : {}),\n [id('item')]: {\n $id: id('item'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('entries'),\n props: { spacing: 0.5 },\n nodes: [\n id('item-title'),\n id('item-date'),\n id('item-excerpt'),\n id('item-link'),\n ],\n },\n [id('item-title')]: item('item-title', {\n variant: 'h5',\n component: 'h2',\n children: '{{entry.title}}',\n }),\n [id('item-date')]: item('item-date', {\n variant: 'caption',\n children: '{{entry.date}}',\n sx: { color: 'text.secondary' },\n }),\n [id('item-excerpt')]: item('item-excerpt', {\n variant: 'body1',\n children: '{{entry.excerpt}}',\n }),\n [id('item-link')]: {\n $id: id('item-link'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('item'),\n props: {\n href: '{{entry.url}}',\n children: 'Read more',\n size: 'small',\n sx: { alignSelf: 'flex-start' },\n },\n },\n }\n}\n\n/** Entry vs list fallback selection for the routed content (AGL-551). */\nexport function buildCollectionFallbackNodes(content: {\n collection: FallbackCollection\n entries: FallbackEntry[]\n entry: FallbackEntry | null\n pagination?: FallbackListPagination | null\n category?: FallbackListCategory | null\n /** The composing site, for host-qualifying a media reference (AGL-1407). */\n hostId?: string\n /** The site's zone (AGL-3237); UTC when a site has not named one. */\n timeZone?: string\n}): NodesMap {\n return content.entry\n ? buildCollectionEntryFallbackNodes(\n content.collection,\n content.entry,\n content.hostId,\n content.timeZone,\n )\n : buildCollectionListFallbackNodes(\n content.collection,\n content.entries.length > 0,\n content.pagination ?? undefined,\n content.category ?? undefined,\n )\n}\n\nexport default buildCollectionFallbackNodes\n"],"names":["videoEmbedOf","Aglyn","FALLBACK_ID_PREFIX","id","suffix","formatDate","value","timeZone","formatCollectionEntryDate","undefined","RENDERABLE_COVER_URL","cssUrlValue","url","replace","char","encodeURIComponent","ENTRY_MAX_WIDTH","LIST_MAX_WIDTH","LIST_SECTION_GAP","entryShell","maxWidth","stackProps","spacing","listShell","sx","display","flexDirection","gap","shell","childIds","layout","NODE_ROOT_ID","$id","componentId","nodes","pluginId","parentId","props","paddingTop","paddingBottom","typography","featuredVideoProps","entry","options","src","coverVideo","trim","resolveMediaSrc","hostId","poster","posterRenders","coverImage","description","seoDescription","excerpt","uploadDate","collectionEntryPublishedAtIso","publishedAt","title","width","buildCollectionEntryFallbackNodes","collection","entries","variant","component","children","date","tags","filter","Boolean","categoryName","resolveEntryCategoryName","categories","length","push","COLLECTION_ENTRY_META_COMPONENT_ID","category","join","coverRenders","test","video","VIDEO_COMPONENT_ID","role","backgroundImage","backgroundSize","backgroundPosition","borderRadius","minHeight","COLLECTION_ENTRY_BODY_COMPONENT_ID","markdown","body","COLLECTION_RELATED_COMPONENT_ID","heading","limit","COLLECTION_SHARE_COMPONENT_ID","href","slug","displayName","alignSelf","map","entryId","Object","fromEntries","paginationNodes","pagination","page","totalPages","prevUrl","nextUrl","collectionPaginationLinks","collectionSlug","categorySlug","nextCursor","prevCursor","color","direction","alignItems","justifyContent","childId","buildCollectionListFallbackNodes","hasEntries","titleId","name","pills","COLLECTION_CATEGORIES_COMPONENT_ID","allLabel","lead","emptyId","empty","item","pager","COLLECTION_ENTRIES_COMPONENT_ID","perPage","size","buildCollectionFallbackNodes","content"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAQ,mDAAkD;AAC/E,YAAYC,WAAW,sBAAqB;AAE5C,kEAAkE,GAClE,MAAMC,qBAAqB;AAE3B,MAAMC,KAAK,CAACC,SAAmB,GAAGF,qBAAqBE,QAAQ;AA+B/D,yEAAyE;AACzE,uEAAuE;AACvE,0EAA0E;AAC1E,yEAAyE;AACzE,4EAA4E;AAC5E,MAAMC,aAAa,CAACC,OAAoCC,WACtDN,MAAMO,yBAAyB,CAACF,OAAOG,WAAWA,WAAWF;AAE/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GACD,MAAMG,uBAAuB;AAE7B;;;;;;;;;;;;;;CAcC,GACD,MAAMC,cAAc,CAACC,MACnBA,IAAIC,OAAO,CAAC,cAAc,CAACC,OAASC,mBAAmBD;AAEzD;;;;;;CAMC,GACD,MAAME,kBAAkB;AAExB;;;;;CAKC,GACD,MAAMC,iBAAiB;AAEvB;;;;;;;;;;;CAWC,GACD,MAAMC,mBAAmB;AAUzB,wEAAwE,GACxE,MAAMC,aAAa,IAAoB,CAAA;QACrCC,UAAUJ;QACVK,YAAY;YAAEC,SAAS;QAAE;IAC3B,CAAA;AAEA;;;;;;;;CAQC,GACD,MAAMC,YAAY,IAAoB,CAAA;QACpCH,UAAUH;QACVI,YAAY;YACVG,IAAI;gBACFC,SAAS;gBACTC,eAAe;gBAC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YACR8B,aAAa;YACbE,UAAU;YACVC,UAAUjC,GAAG;YACbkC,OAAO;gBACL0D,MAAM;gBACN9B,UAAU;gBACVoE,MAAM;gBACN7G,IAAI;oBAAE0E,WAAW;gBAAa;YAChC;QACF;;AAEJ;AAEA,uEAAuE,GACvE,OAAO,SAASoC,6BAA6BC,OAU5C;QAWOA,qBACAA;IAXN,OAAOA,QAAQ7F,KAAK,GAChBkB,kCACE2E,QAAQ1E,UAAU,EAClB0E,QAAQ7F,KAAK,EACb6F,QAAQvF,MAAM,EACduF,QAAQhI,QAAQ,IAElBgH,iCACEgB,QAAQ1E,UAAU,EAClB0E,QAAQzE,OAAO,CAACW,MAAM,GAAG,IACzB8D,sBAAAA,QAAQ/B,UAAU,YAAlB+B,sBAAsB9H,YACtB8H,oBAAAA,QAAQ3D,QAAQ,YAAhB2D,oBAAoB9H;AAE5B;AAEA,eAAe6H,6BAA4B"}
1
+ {"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/collection-fallback-nodes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { videoEmbedOf } from '@aglyn/aglyn/plugin-manager/video-embed-provider'\nimport * as Aglyn from '@aglyn/aglyn/server'\n\n/** Namespaces the synthetic fallback node ids (never persisted). */\nconst FALLBACK_ID_PREFIX = 'cfb__'\n\nconst id = (suffix: string) => `${FALLBACK_ID_PREFIX}${suffix}`\n\ntype NodesMap = Record<string, Aglyn.AglynNodeSchema>\n\ninterface FallbackCollection {\n slug: string\n displayName: string\n /** Category taxonomy (AGL-582) for `categoryId` → name resolution. */\n categories?: Aglyn.CollectionCategory[]\n}\n\ninterface FallbackEntry {\n title?: string\n slug?: string\n excerpt?: string\n /** Per-entry byline (AGL-686); falls back to the site as author. */\n authorName?: string\n body?: string\n coverImage?: string\n /** The featured video (AGL-2956); plays in the cover's place. */\n coverVideo?: string\n /** Its length in seconds (AGL-3584); the Video's `durationSeconds`. */\n coverVideoDuration?: number\n /** Meta description override (AGL-582); falls back to `excerpt`. */\n seoDescription?: string\n /** Stable taxonomy reference (AGL-582); wins over `category`. */\n categoryId?: string\n /** Legacy free-typed category (AGL-582); read-only fallback. */\n category?: string\n tags?: string[]\n publishedAt?: { seconds: number } | null\n}\n\n// The one shared formatter (AGL-1926). This composes server-side, so the\n// inline `toLocaleDateString()` it replaces was not itself a hydration\n// mismatch — but it was a THIRD spelling of \"the entry's published date\",\n// free to drift from the byline and the related-post card that quote the\n// same instant. Pinned locale and zone, so all three agree by construction.\nconst formatDate = (value?: { seconds: number } | null, timeZone?: string) =>\n Aglyn.formatCollectionEntryDate(value, undefined, undefined, timeZone)\n\n/**\n * What may be interpolated into the cover block's CSS `url(\"…\")` (AGL-1407).\n *\n * The gate this replaces was `/^https?:\\/\\//i`, which answered the safety\n * question correctly and the coverage question wrongly: it admitted only the\n * OLDEST of the stored generations. A `media:` reference failed it and the\n * cover block was never emitted — a SILENT drop, no error, no placeholder,\n * just a page missing its picture — and so did the AGL-175 relative CDN path\n * that the first pass at media references wrote. Resolving before testing is\n * what closes that, and the test then has to accept a site-relative path,\n * which is what {@link Aglyn.resolveMediaSrc} returns for a reference.\n *\n * Still a scheme allowlist rather than \"anything non-empty\": this value lands\n * inside a stylesheet rather than in an `<img src>`, so `data:` and friends\n * have no business here even though {@link cssUrlValue} already makes\n * quote-breaking impossible. A bare relative `cover.png` stays rejected\n * exactly as before — there is no page for it to resolve against at compose\n * time.\n *\n * `http:` was dropped for AGL-1725. AGL-1701 found two paths accepting it;\n * markdown-lite is AGL-1713 and this was the second, separate one. It is the\n * only scheme change here, and it is not a host restriction: an author\n * hotlinking their own https cover keeps working, because on a published\n * site the author IS the site owner and the audience is their own visitors.\n * `http:` alone has no defensible use — the request is mixed passive content\n * that current browsers already block or auto-upgrade, so the author gains\n * nothing from it, while the plaintext fetch discloses which article a\n * visitor is reading to every observer on the network path.\n *\n * The consequence of the drop is the SILENT DROP this whole comment is about,\n * for `http:` covers only: no cover node is emitted. That is the correct\n * trade here and the browser was very likely refusing the image anyway, but\n * it is the reason the change is one scheme and not a host list.\n */\nconst RENDERABLE_COVER_URL = /^(?:https:\\/\\/|\\/)/i\n\n/**\n * A URL made safe to sit inside `url(\"…\")`, WITHOUT re-encoding it.\n *\n * This replaces `encodeURI`, which was the wrong tool and quietly broke the\n * commonest stored form: `encodeURI` escapes `%`, so every raw firebasestorage\n * download URL — whose object path is `orgs%2F…%2Fmedia%2F…` — came out\n * double-encoded as `%252F` and 404'd. The block rendered, the image did not,\n * which is why it survived: the page looks composed and the picture is just\n * missing.\n *\n * Only the characters that could END the CSS string are escaped, and they are\n * escaped percent-wise rather than with a backslash so the result is still a\n * valid URL if anything downstream reads it as one. `encodeURI` was never\n * needed for anything else here — a stored URL is already URL-encoded.\n */\nconst cssUrlValue = (url: string) =>\n url.replace(/[\"\\\\\\n\\r]/g, (char) => encodeURIComponent(char))\n\n/**\n * Container width for the built-in entry article: the PROSE case of the\n * Container standard (AGL-1298), not an arbitrary narrow default. A\n * collection entry is an article body, and `xl` — the section default — runs\n * a paragraph past 180 characters a line. Stock breakpoint, no bespoke\n * number.\n */\nconst ENTRY_MAX_WIDTH = 'md'\n\n/**\n * Container width for the built-in listing: the section default. A listing is\n * a card grid rather than a reading column, so the entry's prose width is the\n * wrong measure for it, and the authored list screens render at this same\n * `xl` (AGL-2567). Still a stock breakpoint, so the AGL-1298 rule holds.\n */\nconst LIST_MAX_WIDTH = 'xl'\n\n/**\n * Vertical rhythm between the built-in listing's sections, in MUI theme\n * spacing units: `theme.spacing(6)` resolves to 48px, the same rhythm the\n * authored list screens carry, so a generated listing and an authored one\n * read as one product (AGL-2567).\n *\n * A theme token rather than a pixel string: a hand-written length here\n * answers to no theme, and a length missing its unit is a valid-looking\n * value the browser drops.\n *\n * @see https://mui.com/material-ui/customization/spacing/\n */\nconst LIST_SECTION_GAP = 6\n\n/** The page shell's width and the rhythm of the stack that holds sections. */\ninterface ShellLayout {\n /** Stock Container breakpoint (AGL-1298); never a bespoke pixel cap. */\n maxWidth: typeof ENTRY_MAX_WIDTH | typeof LIST_MAX_WIDTH\n /** Props for the content stack the page's sections slot into. */\n stackProps: Record<string, unknown>\n}\n\n/** The entry article's shell: reading column, sections close together. */\nconst entryShell = (): ShellLayout => ({\n maxWidth: ENTRY_MAX_WIDTH,\n stackProps: { spacing: 2 },\n})\n\n/**\n * The listing's shell: full section width, sections on the 48px rhythm.\n *\n * The gap is declared on the stack's `sx` rather than left to the Stack's own\n * `spacing`, which is the shape the authored list screens carry: one\n * `row-gap` on the flex container, so every section is spaced by the same\n * declaration instead of by margins that a section's own styling can collapse\n * or override.\n */\nconst listShell = (): ShellLayout => ({\n maxWidth: LIST_MAX_WIDTH,\n stackProps: {\n sx: {\n display: 'flex',\n flexDirection: 'column',\n gap: LIST_SECTION_GAP,\n },\n },\n})\n\n/** Root → centered container → content stack; children slot underneath. */\nfunction shell(childIds: string[], layout: ShellLayout): NodesMap {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: [id('container')],\n },\n [id('container')]: {\n $id: id('container'),\n componentId: 'muiContainer',\n pluginId: 'mui',\n parentId: Aglyn.NODE_ROOT_ID,\n props: {\n maxWidth: layout.maxWidth,\n sx: { paddingTop: 6, paddingBottom: 6 },\n },\n nodes: [id('stack')],\n },\n [id('stack')]: {\n $id: id('stack'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('container'),\n props: layout.stackProps,\n nodes: childIds,\n },\n }\n}\n\nconst typography = (\n suffix: string,\n props: Record<string, unknown>,\n): AglynNodeEntry => [\n id(suffix),\n {\n $id: id(suffix),\n componentId: 'muiTypography',\n pluginId: 'mui',\n parentId: id('stack'),\n props,\n },\n]\n\ntype AglynNodeEntry = [string, Aglyn.AglynNodeSchema]\n\n/**\n * The Video node's props for an entry's featured video, or `undefined` when\n * the entry has none this page can play (AGL-2956).\n *\n * An entry of a video collection is an article whose film sits where a post's\n * cover would, and on the built-in page nobody is there to bind one. So the\n * props carry what a designer would bind by hand: the source, the cover as\n * the poster, and the three facts the page's `VideoObject` is built from —\n * the title, the SEO description falling back to the excerpt as\n * `{{entry.seoDescription}}` does, and the ISO publish instant\n * `{{entry.publishedAt}}` resolves to. An instant rather than a calendar day:\n * the builder publishes `uploadDate` as a date-time with a zone, and it keeps\n * an instant as given where it would publish a bare day at noon UTC. The\n * film's length rides along when the entry names one (AGL-3584), as\n * `{{entry.coverVideoDuration}}` would bind it, and becomes the block's\n * `duration`.\n *\n * `undefined` rather than a Video node in two cases, because the element's\n * answer to each is a labeled placeholder, which a published article must\n * never show:\n *\n * - a source nothing resolves, such as an empty field or a malformed `media:`\n * reference;\n * - a hosted player's link (one a plugin declares, core\n * `video-embed-provider.ts`) with no poster. Its player loads only when a\n * visitor presses the poster, so without one there is nothing to press.\n *\n * The page then renders as a cover article, exactly as it does for an entry\n * with no video.\n *\n * The poster is the stored reference, not a resolved URL, so the element and\n * the structured data each resolve it against the site rendering the page. It\n * is passed only when the cover's own scheme rule would render it, so this\n * page never shows a still as a poster that it refuses as a cover.\n *\n * The film takes the cover's whole slot in the reading column, whose stock\n * `md` container bounds it; the column is the width limit rather than a pixel\n * cap (AGL-1298).\n */\nfunction featuredVideoProps(\n entry: FallbackEntry,\n options: { hostId?: string; posterRenders: boolean },\n): Record<string, unknown> | undefined {\n const src = (entry.coverVideo ?? '').trim()\n if (!src || !Aglyn.resolveMediaSrc(src, { hostId: options.hostId })) {\n return undefined\n }\n const poster = options.posterRenders ? entry.coverImage : undefined\n if (videoEmbedOf(src) && !poster) return undefined\n const description = entry.seoDescription || entry.excerpt || ''\n const uploadDate = Aglyn.collectionEntryPublishedAtIso(entry.publishedAt)\n const durationSeconds = Aglyn.collectionEntryVideoDurationSeconds(\n entry.coverVideoDuration,\n )\n return {\n src,\n ...(poster ? { poster } : {}),\n title: entry.title ?? '',\n ...(description ? { description } : {}),\n ...(uploadDate ? { uploadDate } : {}),\n // The length the entry names (AGL-3584), which `{{entry.coverVideoDuration}}`\n // resolves to, so the page's `VideoObject` carries `duration`.\n ...(durationSeconds ? { durationSeconds } : {}),\n width: '100%',\n }\n}\n\n/**\n * Built-in entry article as canvas nodes (AGL-551): when a collection has\n * no entry-template screen, `/{collection}/{entry}` renders these through\n * the normal compose pipeline — site theme, shared layout chrome, and the\n * markdown-rendering Entry body block — instead of the old unthemed HTML.\n */\nexport function buildCollectionEntryFallbackNodes(\n collection: FallbackCollection,\n entry: FallbackEntry,\n /**\n * The site being composed, so an org-scoped reference is host-qualified the\n * way every other render surface qualifies one (AGL-1043/AGL-1407). Optional\n * because a bare org reference still resolves without it; passing it is what\n * lets an asset restricted to this site resolve at all.\n */\n hostId?: string,\n /** The site's zone (AGL-3237); UTC when a site has not named one. */\n timeZone?: string,\n): NodesMap {\n const entries: AglynNodeEntry[] = [\n typography('title', {\n variant: 'h3',\n component: 'h1',\n children: entry.title ?? '',\n }),\n ]\n const date = formatDate(entry.publishedAt, timeZone)\n const tags = (entry.tags ?? []).filter(Boolean)\n // Category name resolves against the collection's taxonomy (AGL-582):\n // `categoryId` lookup first, legacy free-typed string fallback.\n const categoryName =\n Aglyn.resolveEntryCategoryName(entry, collection.categories) ?? ''\n if (date || categoryName || tags.length) {\n // Entry meta block (AGL-582): \"date · category\" line + tag chips.\n entries.push([\n id('meta'),\n {\n $id: id('meta'),\n componentId: Aglyn.COLLECTION_ENTRY_META_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n date,\n category: categoryName,\n tags: tags.join(', '),\n },\n },\n ])\n }\n // The cover, through the ONE shared resolver (AGL-1407). A `media:`\n // reference becomes the site-relative CDN path; a raw storage URL, an\n // AGL-175 CDN path and an author's own hotlinked URL all pass through\n // untouched, which is the documented precedence in `media-ref.ts`.\n const coverImage = Aglyn.resolveMediaSrc(entry.coverImage, { hostId })\n const coverRenders = Boolean(\n coverImage && RENDERABLE_COVER_URL.test(coverImage),\n )\n // A featured video takes the cover's slot, with the cover as its poster\n // (AGL-2956); see `featuredVideoProps` for when an entry has one to play.\n const video = featuredVideoProps(entry, {\n hostId,\n posterRenders: coverRenders,\n })\n if (video) {\n entries.push([\n id('video'),\n {\n $id: id('video'),\n componentId: Aglyn.VIDEO_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: video,\n },\n ])\n } else if (coverRenders) {\n // Rendered as a background image on a plain stack, NOT through the\n // first-party `image` component — that component crashes tenant SSR\n // (AGL-579); the background-image approach is proven safe.\n entries.push([\n id('cover'),\n {\n $id: id('cover'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n role: 'img',\n 'aria-label': entry.title ?? '',\n sx: {\n backgroundImage: `url(\"${cssUrlValue(coverImage)}\")`,\n backgroundSize: 'cover',\n backgroundPosition: 'center',\n borderRadius: 1,\n minHeight: 320,\n },\n },\n },\n ])\n }\n entries.push([\n id('body'),\n {\n $id: id('body'),\n componentId: Aglyn.COLLECTION_ENTRY_BODY_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: { markdown: entry.body ?? '' },\n },\n ])\n // Related posts after the body, share bar at the end (AGL-582); the\n // compose pipeline stamps the related entries server-side.\n entries.push([\n id('related'),\n {\n $id: id('related'),\n componentId: Aglyn.COLLECTION_RELATED_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: { heading: 'Related articles', limit: 3, sx: { paddingTop: 2 } },\n },\n ])\n entries.push([\n id('share'),\n {\n $id: id('share'),\n componentId: Aglyn.COLLECTION_SHARE_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: {},\n },\n ])\n entries.push([\n id('back'),\n {\n $id: id('back'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n href: `/${collection.slug}`,\n children: `← ${collection.displayName}`,\n sx: { alignSelf: 'flex-start' },\n },\n },\n ])\n return {\n ...shell(\n entries.map(([entryId]) => entryId),\n entryShell(),\n ),\n ...Object.fromEntries(entries),\n }\n}\n\n/** Pagination state for the built-in list (AGL-620). */\nexport interface FallbackListPagination {\n page: number\n perPage: number\n /** @deprecated AGL-3219 — absent past one read's bound. */\n totalPages?: number\n /** The older page's cursor, or `''`/absent when there is none (AGL-3219). */\n nextCursor?: string\n /** The newer page's cursor. */\n prevCursor?: string\n}\n\n/** The routed category for a filtered listing (AGL-1321). */\nexport interface FallbackListCategory {\n slug: string\n name: string\n}\n\n/**\n * Prev/next nav over the cursor addresses (AGL-620, AGL-3219).\n *\n * The label says \"Page 4 of 9\" only where nine is a number that can be known\n * — a collection small enough to be read in one go. Past that it says \"Page\n * 4\" and stops, because the alternative is a total derived from a count the\n * listing's own reads could disagree with, which is how page 10 of a\n * seventeen-page changelog came to call itself the last one.\n */\nfunction paginationNodes(\n collection: FallbackCollection,\n pagination: FallbackListPagination,\n category?: FallbackListCategory,\n): { childId: string; nodes: NodesMap } {\n // Page 1 lives at the bare listing; deeper pages at .../page/{n}. Built\n // through the shared pager computation so this fallback and the\n // `{{pagination.*}}` tokens an authored template binds (AGL-1386) can never\n // disagree — and so the pager stays inside the category it is paging\n // (AGL-1321): a \"next\" that dropped the filter would silently return the\n // reader to the unfiltered list. An edge is the empty string, which is\n // exactly the \"no link here\" this fallback already meant.\n const { page, totalPages, prevUrl, nextUrl } = Aglyn.collectionPaginationLinks(\n {\n collectionSlug: collection.slug,\n ...(category ? { categorySlug: category.slug } : {}),\n page: pagination.page,\n ...(pagination.totalPages === undefined\n ? {}\n : { totalPages: pagination.totalPages }),\n nextCursor: pagination.nextCursor ?? '',\n prevCursor: pagination.prevCursor ?? '',\n },\n )\n const children: string[] = []\n const nodes: NodesMap = {}\n if (prevUrl) {\n nodes[id('prev')] = {\n $id: id('prev'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('pager'),\n props: { href: prevUrl, children: '← Newer' },\n }\n children.push(id('prev'))\n }\n nodes[id('pageinfo')] = {\n $id: id('pageinfo'),\n componentId: 'muiTypography',\n pluginId: 'mui',\n parentId: id('pager'),\n props: {\n variant: 'body2',\n children: totalPages > 1 ? `Page ${page} of ${totalPages}` : `Page ${page}`,\n sx: { color: 'text.secondary' },\n },\n }\n children.push(id('pageinfo'))\n if (nextUrl) {\n nodes[id('next')] = {\n $id: id('next'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('pager'),\n props: { href: nextUrl, children: 'Older →' },\n }\n children.push(id('next'))\n }\n nodes[id('pager')] = {\n $id: id('pager'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n direction: 'row',\n spacing: 3,\n sx: { alignItems: 'center', justifyContent: 'center' },\n },\n nodes: children,\n }\n return { childId: id('pager'), nodes }\n}\n\n/**\n * Built-in entry list as canvas nodes (AGL-551): a heading plus a\n * Collection entries block whose template (title, date, excerpt, Read\n * more) the compose pipeline expands over the published entries — the same\n * block designers drop onto their own list-template screens. With\n * `pagination` (AGL-620) the block renders one page and prev/next nav links\n * to `/{slug}/page/{n}`.\n */\nexport function buildCollectionListFallbackNodes(\n collection: FallbackCollection,\n hasEntries: boolean,\n pagination?: FallbackListPagination,\n category?: FallbackListCategory,\n): NodesMap {\n const [titleId, title] = typography('title', {\n variant: 'h3',\n component: 'h1',\n // A filtered listing says which slice it is (AGL-1321) — a page of\n // Guides whose only heading reads \"Blog\" tells the reader nothing about\n // why the other posts vanished.\n children: category\n ? `${collection.displayName} · ${category.name}`\n : collection.displayName,\n })\n // Category pills (AGL-1321): stamped by `expandCollectionCategories` during\n // compose, from the same taxonomy this node's collection carries. Present\n // in the EMPTY case too — a filtered listing with no entries whose pills\n // vanished would be a dead end with no way back to \"All\".\n const pills = collection.categories?.length\n ? {\n $id: id('pills'),\n componentId: Aglyn.COLLECTION_CATEGORIES_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: { allLabel: 'All' },\n }\n : null\n const lead = pills ? [titleId, id('pills')] : [titleId]\n if (!hasEntries) {\n const [emptyId, empty] = typography('empty', {\n variant: 'body1',\n children: category\n ? `Nothing published in ${category.name} yet.`\n : 'Nothing published yet.',\n sx: { color: 'text.secondary' },\n })\n return {\n ...shell([...lead, emptyId], listShell()),\n [titleId]: title,\n ...(pills ? { [id('pills')]: pills } : {}),\n [emptyId]: empty,\n }\n }\n const item = (suffix: string, props: Record<string, unknown>) => ({\n $id: id(suffix),\n componentId: 'muiTypography' as const,\n pluginId: 'mui',\n parentId: id('item'),\n props,\n })\n /*\n * A pager exists when there is somewhere to go (AGL-3219): an older page,\n * proved by the cursor probe, or a newer one, proved by being past the\n * first. `totalPages > 1` used to stand in for that and could not, once the\n * total stopped being knowable.\n */\n const pager =\n pagination &&\n (Boolean(pagination.nextCursor) ||\n pagination.page > 1 ||\n (pagination.totalPages ?? 0) > 1)\n ? paginationNodes(collection, pagination, category)\n : null\n return {\n ...shell(\n pager\n ? [...lead, id('entries'), pager.childId]\n : [...lead, id('entries')],\n listShell(),\n ),\n [titleId]: title,\n ...(pills ? { [id('pills')]: pills } : {}),\n [id('entries')]: {\n $id: id('entries'),\n componentId: Aglyn.COLLECTION_ENTRIES_COMPONENT_ID,\n pluginId: 'mui',\n parentId: id('stack'),\n props: {\n spacing: 4,\n ...(pagination\n ? { perPage: pagination.perPage, page: pagination.page }\n : {}),\n },\n nodes: [id('item')],\n },\n ...(pager ? pager.nodes : {}),\n [id('item')]: {\n $id: id('item'),\n componentId: 'muiStack',\n pluginId: 'mui',\n parentId: id('entries'),\n props: { spacing: 0.5 },\n nodes: [\n id('item-title'),\n id('item-date'),\n id('item-excerpt'),\n id('item-link'),\n ],\n },\n [id('item-title')]: item('item-title', {\n variant: 'h5',\n component: 'h2',\n children: '{{entry.title}}',\n }),\n [id('item-date')]: item('item-date', {\n variant: 'caption',\n children: '{{entry.date}}',\n sx: { color: 'text.secondary' },\n }),\n [id('item-excerpt')]: item('item-excerpt', {\n variant: 'body1',\n children: '{{entry.excerpt}}',\n }),\n [id('item-link')]: {\n $id: id('item-link'),\n componentId: 'muiScreenLink',\n pluginId: 'mui',\n parentId: id('item'),\n props: {\n href: '{{entry.url}}',\n children: 'Read more',\n size: 'small',\n sx: { alignSelf: 'flex-start' },\n },\n },\n }\n}\n\n/** Entry vs list fallback selection for the routed content (AGL-551). */\nexport function buildCollectionFallbackNodes(content: {\n collection: FallbackCollection\n entries: FallbackEntry[]\n entry: FallbackEntry | null\n pagination?: FallbackListPagination | null\n category?: FallbackListCategory | null\n /** The composing site, for host-qualifying a media reference (AGL-1407). */\n hostId?: string\n /** The site's zone (AGL-3237); UTC when a site has not named one. */\n timeZone?: string\n}): NodesMap {\n return content.entry\n ? buildCollectionEntryFallbackNodes(\n content.collection,\n content.entry,\n content.hostId,\n content.timeZone,\n )\n : buildCollectionListFallbackNodes(\n content.collection,\n content.entries.length > 0,\n content.pagination ?? undefined,\n content.category ?? undefined,\n )\n}\n\nexport default buildCollectionFallbackNodes\n"],"names":["videoEmbedOf","Aglyn","FALLBACK_ID_PREFIX","id","suffix","formatDate","value","timeZone","formatCollectionEntryDate","undefined","RENDERABLE_COVER_URL","cssUrlValue","url","replace","char","encodeURIComponent","ENTRY_MAX_WIDTH","LIST_MAX_WIDTH","LIST_SECTION_GAP","entryShell","maxWidth","stackProps","spacing","listShell","sx","display","flexDirection","gap","shell","childIds","layout","NODE_ROOT_ID","$id","componentId","nodes","pluginId","parentId","props","paddingTop","paddingBottom","typography","featuredVideoProps","entry","options","src","coverVideo","trim","resolveMediaSrc","hostId","poster","posterRenders","coverImage","description","seoDescription","excerpt","uploadDate","collectionEntryPublishedAtIso","publishedAt","durationSeconds","collectionEntryVideoDurationSeconds","coverVideoDuration","title","width","buildCollectionEntryFallbackNodes","collection","entries","variant","component","children","date","tags","filter","Boolean","categoryName","resolveEntryCategoryName","categories","length","push","COLLECTION_ENTRY_META_COMPONENT_ID","category","join","coverRenders","test","video","VIDEO_COMPONENT_ID","role","backgroundImage","backgroundSize","backgroundPosition","borderRadius","minHeight","COLLECTION_ENTRY_BODY_COMPONENT_ID","markdown","body","COLLECTION_RELATED_COMPONENT_ID","heading","limit","COLLECTION_SHARE_COMPONENT_ID","href","slug","displayName","alignSelf","map","entryId","Object","fromEntries","paginationNodes","pagination","page","totalPages","prevUrl","nextUrl","collectionPaginationLinks","collectionSlug","categorySlug","nextCursor","prevCursor","color","direction","alignItems","justifyContent","childId","buildCollectionListFallbackNodes","hasEntries","titleId","name","pills","COLLECTION_CATEGORIES_COMPONENT_ID","allLabel","lead","emptyId","empty","item","pager","COLLECTION_ENTRIES_COMPONENT_ID","perPage","size","buildCollectionFallbackNodes","content"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAQ,mDAAkD;AAC/E,YAAYC,WAAW,sBAAqB;AAE5C,kEAAkE,GAClE,MAAMC,qBAAqB;AAE3B,MAAMC,KAAK,CAACC,SAAmB,GAAGF,qBAAqBE,QAAQ;AAiC/D,yEAAyE;AACzE,uEAAuE;AACvE,0EAA0E;AAC1E,yEAAyE;AACzE,4EAA4E;AAC5E,MAAMC,aAAa,CAACC,OAAoCC,WACtDN,MAAMO,yBAAyB,CAACF,OAAOG,WAAWA,WAAWF;AAE/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GACD,MAAMG,uBAAuB;AAE7B;;;;;;;;;;;;;;CAcC,GACD,MAAMC,cAAc,CAACC,MACnBA,IAAIC,OAAO,CAAC,cAAc,CAACC,OAASC,mBAAmBD;AAEzD;;;;;;CAMC,GACD,MAAME,kBAAkB;AAExB;;;;;CAKC,GACD,MAAMC,iBAAiB;AAEvB;;;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GAAG;gBACHA,GAAG;gBACHA,GAAG;gBACHA,GAAG;aACJ;QACH;QACA,CAACA,GAAG,cAAc,EAAEiI,KAAK,cAAc;YACrClE,SAAS;YACTC,WAAW;YACXC,UAAU;QACZ;QACA,CAACjE,GAAG,aAAa,EAAEiI,KAAK,aAAa;YACnClE,SAAS;YACTE,UAAU;YACV5C,IAAI;gBAAE6F,OAAO;YAAiB;QAChC;QACA,CAAClH,GAAG,gBAAgB,EAAEiI,KAAK,gBAAgB;YACzClE,SAAS;YACTE,UAAU;QACZ;QACA,CAACjE,GAAG,aAAa,EAAE;YACjB6B,KAAK7B,GAAG;YACR8B,aAAa;YACbE,UAAU;YACVC,UAAUjC,GAAG;YACbkC,OAAO;gBACL6D,MAAM;gBACN9B,UAAU;gBACVoE,MAAM;gBACNhH,IAAI;oBAAE6E,WAAW;gBAAa;YAChC;QACF;;AAEJ;AAEA,uEAAuE,GACvE,OAAO,SAASoC,6BAA6BC,OAU5C;QAWOA,qBACAA;IAXN,OAAOA,QAAQhG,KAAK,GAChBqB,kCACE2E,QAAQ1E,UAAU,EAClB0E,QAAQhG,KAAK,EACbgG,QAAQ1F,MAAM,EACd0F,QAAQnI,QAAQ,IAElBmH,iCACEgB,QAAQ1E,UAAU,EAClB0E,QAAQzE,OAAO,CAACW,MAAM,GAAG,IACzB8D,sBAAAA,QAAQ/B,UAAU,YAAlB+B,sBAAsBjI,YACtBiI,oBAAAA,QAAQ3D,QAAQ,YAAhB2D,oBAAoBjI;AAE5B;AAEA,eAAegI,6BAA4B"}
@@ -45,6 +45,11 @@ export interface CollectionEntrySummary {
45
45
  * `CollectionEntryRecord.coverVideo`.
46
46
  */
47
47
  coverVideo?: string;
48
+ /**
49
+ * The featured video's length in whole seconds (AGL-3584), or unset when the
50
+ * entry names none. See `CollectionEntryRecord.coverVideoDuration`.
51
+ */
52
+ coverVideoDuration?: number;
48
53
  /** Search-result title override (AGL-582); falls back to `title`. */
49
54
  seoTitle?: string;
50
55
  /** Meta description override (AGL-582); falls back to `excerpt`. */
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { AUTHORS_MAX_PER_HOST, collectionCategorySlug, checkEntitlement, COLLECTION_SOURCE_MAX, collectionTotalPages, entryMatchesCategoryRoute, hostCollectionKind, normalizeContentAuthor, normalizeContentSchemaType, resolveCollectionCategoryBySlug, resolveEntryAuthor } from "@aglyn/aglyn/server";
17
+ */ import { AUTHORS_MAX_PER_HOST, collectionCategorySlug, checkEntitlement, COLLECTION_SOURCE_MAX, collectionEntryVideoDurationSeconds, collectionTotalPages, entryMatchesCategoryRoute, hostCollectionKind, normalizeContentAuthor, normalizeContentSchemaType, resolveCollectionCategoryBySlug, resolveEntryAuthor } from "@aglyn/aglyn/server";
18
18
  import { ENTRY_PUBLISH_SORT_FIELD } from "@aglyn/aglyn/app-utils/collection-entry-date";
19
19
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
20
20
  import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from "@aglyn/tenant-data-admin/render-cache";
@@ -53,7 +53,8 @@ import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from
53
53
  /** Entry-doc fields shared by the list and single-entry mappers (AGL-582). */ function mapEntryFields(value) {
54
54
  var _value_excerpt, _value_authorName, _value_authorId, _value_coverImage, _value_coverImageAlt, _value_coverVideo, _value_seoTitle, _value_seoDescription, _value_categoryId, _value_category;
55
55
  var _value_updatedAt;
56
- return {
56
+ const coverVideoDuration = collectionEntryVideoDurationSeconds(value['coverVideoDuration']);
57
+ return _extends({
57
58
  excerpt: (_value_excerpt = value['excerpt']) != null ? _value_excerpt : '',
58
59
  // The byline was DECLARED on `CollectionEntrySummary` (AGL-686) and
59
60
  // mapped by nobody, so `entry.authorName` was `undefined` on every entry
@@ -69,7 +70,10 @@ import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from
69
70
  coverImageAlt: (_value_coverImageAlt = value['coverImageAlt']) != null ? _value_coverImageAlt : '',
70
71
  // Here, where both read paths pick it up, so a list card and the routed
71
72
  // entry page can each bind the featured video (AGL-2956).
72
- coverVideo: (_value_coverVideo = value['coverVideo']) != null ? _value_coverVideo : '',
73
+ coverVideo: (_value_coverVideo = value['coverVideo']) != null ? _value_coverVideo : ''
74
+ }, coverVideoDuration ? {
75
+ coverVideoDuration
76
+ } : {}, {
73
77
  seoTitle: (_value_seoTitle = value['seoTitle']) != null ? _value_seoTitle : '',
74
78
  seoDescription: (_value_seoDescription = value['seoDescription']) != null ? _value_seoDescription : '',
75
79
  categoryId: (_value_categoryId = value['categoryId']) != null ? _value_categoryId : '',
@@ -96,7 +100,7 @@ import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from
96
100
  */ updatedAt: ((_value_updatedAt = value['updatedAt']) == null ? void 0 : _value_updatedAt.seconds) ? {
97
101
  seconds: value['updatedAt'].seconds
98
102
  } : null
99
- };
103
+ });
100
104
  }
101
105
  /**
102
106
  * The collection doc's category taxonomy (AGL-582), sanitized: only
@@ -376,6 +380,7 @@ export async function scheduledPublishingPermission(hostId) {
376
380
  'coverImage',
377
381
  'coverImageAlt',
378
382
  'coverVideo',
383
+ 'coverVideoDuration',
379
384
  'seoTitle',
380
385
  'seoDescription',
381
386
  'categoryId',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/get-collection-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AUTHORS_MAX_PER_HOST,\n type CollectionCategory,\n collectionCategorySlug,\n checkEntitlement,\n COLLECTION_SOURCE_MAX,\n collectionTotalPages,\n type ContentAuthorRecord,\n entryMatchesCategoryRoute,\n hostCollectionKind,\n normalizeContentAuthor,\n normalizeContentSchemaType,\n resolveCollectionCategoryBySlug,\n resolveEntryAuthor,\n} from '@aglyn/aglyn/server'\nimport { ENTRY_PUBLISH_SORT_FIELD } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\n\n/**\n * ONE cached read per collection, shared by every surface that lists it\n * (AGL-1302).\n *\n * It began as the compose-time source only: a Collection entries block in a\n * shared layout re-read up to ~100 entry docs on EVERY page of the site. The\n * routed listing was left out on the argument that the page's own ISR entry\n * amortized it — which is true of ONE address and false of a collection,\n * because a collection is not one address. `/blog`, `/blog/page/2…10`, a\n * `/blog/category/{slug}` per category and `/blog/rss.xml` are all the same\n * data, each paying its own `1 + entries + authors` per window, beside a\n * cache already holding exactly that.\n *\n * The other half of that argument was real and is answered rather than\n * dropped: `flipDueEntry` is a write, and a render is the backstop that\n * publishes a content entry when the `apply-entry-schedules` beat has not\n * (AGL-3340), so a cache that stored a collection with a schedule still\n * pending would suppress the render that publishes it.\n * `getPublishedCollectionSource` therefore declines to STORE exactly those\n * collections — see its `store` predicate — which keeps that backstop on the\n * render window, and puts everything else on this TTL.\n */\nconst COLLECTION_SOURCE_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/**\n * Resolve a public content-collection slug (AGL-954). Commerce's product\n * collections share `hosts/{hostId}/collections`, and a slug is only unique\n * within a kind — a bare `limit(1)` handed the URL to whichever doc Firestore\n * returned first, so a catalog collection could shadow a blog. Reads a small\n * window instead and takes the first content-kind match.\n */\nasync function findContentCollection(\n hostId: string,\n collectionSlug: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | undefined> {\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .where('slug', '==', collectionSlug)\n .limit(5)\n .get()\n return matches.docs.find(\n (docSnapshot) => hostCollectionKind(docSnapshot.data()) === 'content',\n )\n}\n\nexport interface CollectionEntrySummary {\n $id: string\n title: string\n slug: string\n excerpt?: string\n /**\n * The byline TEXT (AGL-686). Either the entry's own legacy free-typed\n * string or — since AGL-2486 — the name of the author record `authorId`\n * points at, resolved here so every downstream reader (the Entry Meta\n * block, `{{entry.author}}`, the RSS feed) keeps asking one field.\n */\n authorName?: string\n /** Reference into `hosts/{hostId}/authors` (AGL-2486). */\n authorId?: string\n /**\n * The resolved author RECORD (AGL-2486) — what `Article.author` is built\n * from. Null when the entry names no author, in which case the page falls\n * back to the site's publisher entity exactly as it always has.\n */\n author?: ContentAuthorRecord | null\n body?: string\n coverImage?: string\n /** `og:image:alt` for the cover (AGL-2417); travels WITH `coverImage`. */\n coverImageAlt?: string\n /**\n * The featured video (AGL-2956): a media reference or a URL, a hosted\n * player's link included, in the shape `coverImage` is. See\n * `CollectionEntryRecord.coverVideo`.\n */\n coverVideo?: string\n /** Search-result title override (AGL-582); falls back to `title`. */\n seoTitle?: string\n /** Meta description override (AGL-582); falls back to `excerpt`. */\n seoDescription?: string\n /**\n * Stable reference into the collection's `categories` taxonomy\n * (AGL-582); resolved to a display name at render.\n */\n categoryId?: string\n /** Legacy free-typed bucket (AGL-582); read-only fallback. */\n category?: string\n /** Free-form labels (AGL-582). */\n tags?: string[]\n publishedAt?: { seconds: number } | null\n /**\n * Last edited, which is what `Article.dateModified` publishes (AGL-2534).\n *\n * Distinct from {@link publishedAt} on purpose: re-dating a post is not\n * editing it, so the console writes `publishedAt` alone when an author\n * backdates and this stays put. Google reads `dateModified` for freshness.\n */\n updatedAt?: { seconds: number } | null\n /**\n * The collection this entry came out of (AGL-2518), stamped only by a\n * reader that MIXES collections — the author page. Unset on every routed\n * listing, where the route already answers the question. See\n * `CollectionEntryRecord.collectionSlug`.\n */\n collectionSlug?: string\n /** The display name of {@link collectionSlug}. */\n collectionName?: string\n}\n\n/** Entry-doc fields shared by the list and single-entry mappers (AGL-582). */\nfunction mapEntryFields(\n value: FirebaseFirestore.DocumentData,\n): Pick<\n CollectionEntrySummary,\n | 'excerpt'\n | 'coverImage'\n | 'coverImageAlt'\n | 'coverVideo'\n | 'seoTitle'\n | 'seoDescription'\n | 'authorName'\n | 'authorId'\n | 'categoryId'\n | 'category'\n | 'tags'\n | 'updatedAt'\n> {\n return {\n excerpt: value['excerpt'] ?? '',\n // The byline was DECLARED on `CollectionEntrySummary` (AGL-686) and\n // mapped by nobody, so `entry.authorName` was `undefined` on every entry\n // this loader returned — which is every routed entry page and every\n // Collection entries block. The console collected the field, the rules\n // stored it, the JSON-LD builder read it and the Entry Meta block printed\n // it, and all three saw nothing, because the one hop between Firestore\n // and them dropped it (AGL-2486). Written but never read, in the\n // direction that leaves no error behind.\n authorName: value['authorName'] ?? '',\n authorId: value['authorId'] ?? '',\n coverImage: value['coverImage'] ?? '',\n coverImageAlt: value['coverImageAlt'] ?? '',\n // Here, where both read paths pick it up, so a list card and the routed\n // entry page can each bind the featured video (AGL-2956).\n coverVideo: value['coverVideo'] ?? '',\n seoTitle: value['seoTitle'] ?? '',\n seoDescription: value['seoDescription'] ?? '',\n categoryId: value['categoryId'] ?? '',\n category: value['category'] ?? '',\n tags: Array.isArray(value['tags'])\n ? value['tags'].filter((tag): tag is string => typeof tag === 'string')\n : [],\n /*\n `dateModified`'s source (AGL-2534), and it was missing for the same\n reason `authorName` was — the reason this function's own comment above\n describes.\n\n The console has written `updatedAt` on every save, `page.tsx` reads\n `entry.updatedAt.seconds` to publish `Article.dateModified`, a spec\n asserts the conversion, and two console comments explain why it must not\n track `publishedAt`. Nothing mapped it, so `entry.updatedAt` was\n `undefined` on every entry the loader has ever returned and no published\n article has ever carried a `dateModified` — the freshness signal Google\n reads. The spec passed throughout because it builds its entry object by\n hand and never crosses this boundary.\n\n Mapped HERE rather than beside `publishedAt` at the two call sites: this\n is an ordinary field with no `publishAt` fallback and nothing sorts on\n it, so one place is enough — and one place is what stops the next read\n path from forgetting it.\n */\n updatedAt: value['updatedAt']?.seconds\n ? { seconds: value['updatedAt'].seconds }\n : null,\n }\n}\n\n/**\n * The collection doc's category taxonomy (AGL-582), sanitized: only\n * `{ id, name }` pairs with non-empty strings survive, order preserved.\n *\n * `description` rides along when the author wrote one and is dropped when it\n * is blank or not a string, so the head can tell \"described\" from \"not\n * described\" by truthiness alone — an empty string reaching the metadata\n * would suppress the template screen's description and leave the listing with\n * none at all.\n */\nfunction mapCollectionCategories(value: unknown): CollectionCategory[] {\n if (!Array.isArray(value)) return []\n return value\n .filter(\n (item): item is CollectionCategory =>\n typeof item?.id === 'string' &&\n item.id.trim() !== '' &&\n typeof item?.name === 'string' &&\n item.name.trim() !== '',\n )\n .map((item) => {\n const description =\n typeof item.description === 'string' ? item.description.trim() : ''\n return {\n id: item.id,\n name: item.name,\n ...(description ? { description } : {}),\n }\n })\n}\n\n/**\n * The routed view of a collection DOCUMENT (AGL-551): its name and the\n * template screens its list and entry routes render through.\n *\n * `slug` is the slug that was ASKED FOR rather than the one stored, which is\n * what every caller of this file has always returned — a listing has to build\n * its own URLs out of the segment the reader is standing on.\n */\nfunction mapCollectionDoc(\n collectionDoc: FirebaseFirestore.QueryDocumentSnapshot,\n collectionSlug: string,\n): CollectionContent['collection'] {\n return {\n $id: collectionDoc.id,\n displayName: collectionDoc.get('displayName') ?? collectionSlug,\n slug: collectionSlug,\n templateScreenId: collectionDoc.get('templateScreenId') ?? undefined,\n listScreenId: collectionDoc.get('listScreenId') ?? undefined,\n entryScreenId: collectionDoc.get('entryScreenId') ?? undefined,\n // Normalized HERE rather than at the head (AGL-2536), so an unrecognised\n // stored value can never reach the JSON-LD: an `@type` the vocabulary\n // does not define makes a consumer discard the whole node, costing the\n // page every property it publishes rather than just this one.\n schemaType: normalizeContentSchemaType(collectionDoc.get('schemaType')),\n // \"List the collection, not its entries\" (AGL-3247). Carried as the\n // STORED boolean rather than as the resolved answer: the render surface\n // composes it with the site-level switch itself, and a pre-resolved flag\n // here would be a second place that has to remember that switch exists.\n excludeEntriesFromSearch:\n collectionDoc.get('excludeEntriesFromSearch') === true,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n }\n}\n\n/**\n * Resolve the author RECORDS a set of entries reference (AGL-2486).\n *\n * Costs ZERO reads when no entry names an `authorId`, which is every site\n * that has not adopted custom authors and every entry written before them —\n * the check is on the ids already in hand, not a probe of the collection. When\n * ids are present it is one `getAll` of the DISTINCT ones, bounded by\n * {@link AUTHORS_MAX_PER_HOST} and by the ≤100-entry page above it, rather\n * than a read per entry.\n *\n * Fail-open, like every other read in this file: an authors read that throws\n * leaves the entries with their legacy `authorName` (or the site entity) and\n * the page renders. A byline is not worth a 500.\n */\nasync function attachEntryAuthors(\n hostId: string,\n entries: CollectionEntrySummary[],\n): Promise<void> {\n const ids = [\n ...new Set(\n entries\n .map((entry) => (entry.authorId ?? '').trim())\n .filter(Boolean),\n ),\n ].slice(0, AUTHORS_MAX_PER_HOST)\n let authors: ContentAuthorRecord[] = []\n if (ids.length) {\n try {\n const authorsRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('authors')\n const snapshots = await firebaseAdmin\n .app()\n .firestore()\n .getAll(...ids.map((id) => authorsRef.doc(id)))\n authors = snapshots\n .map((snapshot) =>\n snapshot.exists\n ? normalizeContentAuthor(snapshot.data(), snapshot.id)\n : null,\n )\n .filter((author): author is ContentAuthorRecord => Boolean(author))\n } catch (error) {\n console.error(error)\n }\n }\n for (const entry of entries) {\n const author = resolveEntryAuthor(entry, authors)\n entry.author = author\n // The byline TEXT is denormalized onto the field everything downstream\n // already reads, so a record-backed author needs no change in the Entry\n // Meta block, the token map, the fallback nodes or the RSS feed. A record\n // WINS over the legacy string on the same entry: picking an author is the\n // more recent statement of who wrote it.\n if (author?.name) entry.authorName = author.name\n }\n}\n\n/**\n * Terminal refusal marker for an entry schedule, the flat-status twin of\n * `publishSchedule.status: 'skipped-unentitled'` on screens (AGL-1185).\n *\n * A field rather than a new `status` value on purpose. `status` is queried\n * (`where('status', 'in', [...])`), rendered by the console, and sorted on by\n * `bundle-timestamps.ts`; adding a member would have meant auditing every one\n * of those readers. A sibling field is invisible to all of them and is read\n * only here.\n */\nconst ENTRY_SCHEDULE_SKIPPED = 'skipped-unentitled'\n\n/** A schedule this entry already had declined, and will not have reconsidered. */\nfunction scheduleAlreadyRefused(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return value['scheduleStatus'] === ENTRY_SCHEDULE_SKIPPED\n}\n\n/** A scheduled entry whose time has come — before any plan question. */\nexport function isDueScheduled(value: FirebaseFirestore.DocumentData): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n (value['publishAt']?.seconds ?? Number.POSITIVE_INFINITY) * 1000 <=\n Date.now()\n )\n}\n\n/**\n * A scheduled entry still waiting on its time: not due yet, and not refused.\n * A render is the backstop that publishes a content entry the beat has not\n * reached, so a cache that stored a read holding one would withhold the render\n * that notices it come due — see {@link LiveEntriesRead.pendingSchedule}.\n */\nexport function isPendingScheduled(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n !isDueScheduled(value)\n )\n}\n\n/**\n * When this entry's schedule comes due, in epoch ms — or null when it holds\n * no schedule to act on: not `scheduled`, already refused, or carrying no\n * `publishAt` (AGL-3340).\n *\n * The beat orders its probe by this instant. A refused schedule keeps\n * `status: 'scheduled'` forever (see {@link ENTRY_SCHEDULE_SKIPPED}), so\n * reading one as due would make every beat re-probe for work that will never\n * be done. Seconds, like {@link isDueScheduled}, so the two agree about the\n * instant an entry comes due.\n */\nexport function entryScheduleDueAtMs(\n value: FirebaseFirestore.DocumentData,\n): number | null {\n if (value['status'] !== 'scheduled' || scheduleAlreadyRefused(value)) {\n return null\n }\n const seconds = value['publishAt']?.seconds\n return typeof seconds === 'number' ? seconds * 1000 : null\n}\n\n/**\n * Is this host's plan allowed to publish on a schedule? (AGL-471 shape.)\n *\n * `React.cache`-deduped per request via `getOrgForHost`, and — this is the\n * part that keeps it off the hot path — every caller below only asks once it\n * has already found a due scheduled entry. A collection with nothing due pays\n * nothing, which is almost every render.\n *\n * THREE answers, not two, and the third is the point. `refused` means we read\n * the plan and it does not carry the entitlement. `unresolved` means we could\n * not find out. Both withhold the entry, but only `refused` may write the\n * terminal marker — burning a schedule permanently on the strength of a\n * hostIndex miss or a transient rejection would destroy a customer's post for\n * a reason that may not be true a second later.\n *\n * Withholding on `unresolved` rather than publishing is what every other\n * entitlement caller on the tenant runtime already does: `apply-publish-schedule`\n * here, and the automation engine's two runners, all pass a possibly\n * undefined org straight into `checkEntitlement`, which resolves a missing\n * plan as free and denies (AGL-247). Opening here instead would make this the\n * one gate in the lib that admits when it cannot see — the exact shape of the\n * free-tier leak `no-plan-gated-entitlement` exists to forbid.\n *\n * The blast radius of withholding is deliberately small: `isLive` answers true\n * for `status: 'published'` before it ever consults this, so an unresolved\n * read hides only the due-scheduled entry, never the published ones, and the\n * next render retries.\n */\nexport type SchedulePermission = 'allowed' | 'refused' | 'unresolved'\n\nexport async function scheduledPublishingPermission(\n hostId: string,\n): Promise<SchedulePermission> {\n try {\n const org = (await getOrgForHost(hostId))?.org\n if (!org) return 'unresolved'\n return checkEntitlement(org, 'scheduledPublishing') ? 'allowed' : 'refused'\n } catch (error) {\n // Caught rather than thrown: the only caller sits inside\n // `getCollectionContent`'s try/catch, which returns an EMPTY collection —\n // so an unhandled rejection here would blank every published entry on the\n // page, not just the scheduled one.\n console.error(error)\n return 'unresolved'\n }\n}\n\n/**\n * Scheduled entries (AGL-123) go live lazily like AGL-61: a due\n * `publishAt` counts as published for this render, and the doc is flipped\n * to `published` fail-open so the state becomes durable. The tenant's\n * `apply-entry-schedules` beat makes the same flip at the entry's time and\n * drops the pages that list it (AGL-3340); this render-time half stays as the\n * backstop for a beat that is down or has not reached the entry yet.\n *\n * PLAN GATE (AGL-471). `scheduledPublishing` is a Business entitlement, and\n * until now nothing on the entry path checked it: the console let any plan\n * write `status: 'scheduled'`, and this render path published it. Scheduling\n * worked end to end on Free. The screens path has gated this since AGL-471\n * and records its refusal since AGL-1185 — entries were simply never wired\n * to either, which is why the leak was invisible from the screens side.\n *\n * The permission is threaded in rather than resolved here so the org read\n * happens once per call site instead of once per entry.\n *\n * Exported for the one other reader that decides whether an entry is on the\n * site — whether a LINK to it resolves (AGL-3118) — so a link and the page it\n * points at can never disagree about which entries exist.\n */\nexport function isLive(\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): boolean {\n if (value['status'] === 'published') return true\n return permission === 'allowed' && isDueScheduled(value)\n}\n\n/**\n * What {@link flipDueEntry} did to one entry.\n *\n * `published` is the only outcome that changes what a visitor sees, so it is\n * the only one a caller drops pages for. `refused` changes the stored state\n * and nothing on the site — a refused entry was never live.\n */\nexport type EntryScheduleOutcome = 'published' | 'refused' | 'unchanged' | 'failed'\n\n/**\n * Make the due state durable — or record that it was refused.\n *\n * The refusal is TERMINAL, for the AGL-1185 reason: left as a bare pending\n * `scheduled`, the entry stays permanently due, so the day the org upgrades\n * to Business the next render publishes it. Content scheduled on a plan that\n * could not honour it, and forgotten, surfacing during an upgrade — exactly\n * when nobody is looking for it. Recording the refusal is what makes it stop\n * being due, and it also stops this path re-reading the org on every\n * subsequent render.\n *\n * Both writes fail open: an error leaves today's state, and the next render\n * retries. A render does not wait for them (`void`); the beat does, because\n * it drops pages only for a flip that landed.\n *\n * `precondition` is the beat's: it read the entry some milliseconds earlier,\n * and an author rescheduling it in between must win. A render passes none —\n * it writes exactly what it just rendered.\n */\nasync function flipDueEntry(\n docRef: FirebaseFirestore.DocumentReference,\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n precondition?: FirebaseFirestore.Precondition,\n): Promise<EntryScheduleOutcome> {\n if (value['status'] !== 'scheduled') return 'unchanged'\n if (scheduleAlreadyRefused(value)) return 'unchanged'\n // `unresolved` writes NOTHING. It withholds this render and leaves the\n // schedule exactly as it found it, so a later render can still publish it.\n if (permission === 'unresolved') return 'unchanged'\n if (!isDueScheduled(value)) return 'unchanged'\n const update: FirebaseFirestore.UpdateData<FirebaseFirestore.DocumentData> =\n permission === 'refused'\n ? { scheduleStatus: ENTRY_SCHEDULE_SKIPPED }\n : // The console's sort key follows the flip (AGL-3323). It already held\n // `publishAt` while the entry waited, and `publishedAt` takes that\n // same instant, so the entry keeps its place in the console's\n // Published order.\n {\n status: 'published',\n publishedAt: value['publishAt'],\n [ENTRY_PUBLISH_SORT_FIELD]: value['publishAt'],\n }\n try {\n if (precondition) await docRef.update(update, precondition)\n else await docRef.update(update)\n return permission === 'refused' ? 'refused' : 'published'\n } catch (error) {\n console.error(error)\n return 'failed'\n }\n}\n\n/**\n * Apply one due entry schedule outside a render (AGL-3340) — the executor the\n * `apply-entry-schedules` beat runs, and the same one a render runs, so the\n * two cannot come to disagree about the plan gate or the fields a flip\n * writes.\n *\n * Asks the plan only for an entry that is actually due, as every render path\n * does. Guarded on the snapshot's own `updateTime`: a schedule edited after\n * the beat read it is left for the next beat, which reads it fresh.\n */\nexport async function applyDueEntrySchedule(options: {\n hostId: string\n entry: Pick<\n FirebaseFirestore.DocumentSnapshot,\n 'ref' | 'data' | 'updateTime'\n >\n}): Promise<EntryScheduleOutcome> {\n const value = options.entry.data()\n if (!value || !isDueScheduled(value)) return 'unchanged'\n const permission = await scheduledPublishingPermission(options.hostId)\n return flipDueEntry(\n options.entry.ref,\n value,\n permission,\n options.entry.updateTime\n ? { lastUpdateTime: options.entry.updateTime }\n : undefined,\n )\n}\n\nexport interface CollectionContent {\n /**\n * The zone this site's dates read in (AGL-3237), carried on the CONTENT so\n * it reaches the client.\n *\n * `collection-fallback.tsx` renders through `next/dynamic` from\n * `catch-all-client`, so it formats dates in the browser as well as on the\n * server. A zone it read from its own runtime would be the visitor's, which\n * is precisely the hydration mismatch AGL-1926 fixed — so the server\n * decides it once and it travels here, in the props both renders read.\n */\n timeZone?: string\n collection: {\n $id: string\n displayName: string\n slug: string\n /**\n * Legacy entry-template screen (AGL-105); superseded by\n * `entryScreenId` but still honored when only it is set.\n */\n templateScreenId?: string\n /** List-template screen (AGL-551); `/{collection}` renders through it. */\n listScreenId?: string\n /**\n * Entry-template screen (AGL-551); `/{collection}/{entry}` renders\n * through it with `{{entry.*}}` tokens.\n */\n entryScreenId?: string\n /**\n * What KIND of article this collection publishes (AGL-2536) — the\n * `schema.org` type its entries serialise as. Unset publishes `Article`,\n * which is what every collection published before the setting existed.\n */\n schemaType?: string\n /**\n * Whether this collection withholds its ENTRIES from search (AGL-3247).\n * The listing and its category listings stay indexable either way.\n */\n excludeEntriesFromSearch?: boolean\n /**\n * Category taxonomy (AGL-582): entries reference these by stable\n * `id`; `name` is the renameable display label.\n */\n categories?: CollectionCategory[]\n } | null\n entries: CollectionEntrySummary[]\n entry: CollectionEntrySummary | null\n /**\n * Whether the read that produced `entries` stopped at\n * {@link COLLECTION_SOURCE_MAX} (AGL-1516). Set on LIST routes only —\n * an entry route reads one document by slug and bounds nothing.\n */\n entriesReachedBound?: boolean\n /**\n * Present ONLY when a verified preview grant revealed an entry the public\n * site withholds (AGL-3205) — never on a public render, and never for an\n * entry that is already live. Its absence is what the preview chrome reads\n * to say \"this one is actually published\", so it must not be set\n * defensively.\n */\n entryPreview?: {\n /** The stored `status` — `scheduled` or `draft`. */\n status: string\n /** The instant it is scheduled for, or null when nothing is scheduled. */\n publishAtSeconds: number | null\n }\n /** List pagination (AGL-620); null for entry pages or unpaginated lists. */\n pagination?: CollectionPagination | null\n /**\n * The category this listing is filtered to (AGL-1321); null on the\n * canonical unfiltered list and on entry pages.\n */\n category?: CollectionRouteCategory | null\n error: unknown\n}\n\n/** The category a `/{collection}/category/{slug}` route addresses (AGL-1321). */\nexport interface CollectionRouteCategory {\n /** The URL segment, normalized — what the canonical link must say. */\n slug: string\n /** Taxonomy id; absent when the segment matched no known category. */\n id?: string\n /** Display label; falls back to the raw segment for an unknown category. */\n name: string\n /**\n * The taxonomy's {@link CollectionCategory.description}, carried onto the\n * route so the head can describe the FILTERED listing rather than inherit\n * the whole collection's description. Absent for an unknown segment, which\n * names no category and therefore has nothing to describe.\n */\n description?: string\n /**\n * Whether the segment resolved against the collection's taxonomy. An\n * unknown category still renders — an empty listing, not a crash — but the\n * page must not invite indexing of a URL that names nothing.\n */\n known: boolean\n}\n\nexport interface CollectionPagination {\n /**\n * 1-based counter for display only (AGL-3219).\n *\n * It is what `{{pagination.page}}` renders and nothing reads it back: a\n * cursor page is addressed by the document it starts after, so this number\n * describes how far a reader has walked rather than where the read began.\n * Hand-edit it in a URL and the label is wrong; the entries are not.\n */\n page: number\n perPage: number\n /**\n * The document id the NEXT (older) page starts after, or `''` when this is\n * the last page (AGL-3219).\n *\n * Set from a `limit(perPage + 1)` probe: the extra row is the only evidence\n * needed that an older page exists, and it costs one document rather than\n * the `count()` aggregation a total used to need. It is also the only\n * honest answer available — see {@link CollectionPagination.totalPages}.\n */\n nextCursor: string\n /** The document id the PREVIOUS (newer) page starts before, or `''`. */\n prevCursor: string\n /**\n * How many pages there are.\n *\n * @deprecated AGL-3219. Still resolved, so a template binding\n * `{{pagination.totalPages}}` keeps rendering, but no longer a promise: a\n * total can only be stated for a collection that fits inside one read, and\n * past that it is absent rather than wrong. It used to be derived from a\n * `count()` over a set the listing's two reads disagreed about, which is\n * how the page 10/11 seam came to repeat an entry. Bind\n * {@link CollectionPagination.nextCursor} instead — `''` means there is\n * nothing older, which is the question a pager is actually asking.\n */\n totalPages?: number\n /** @deprecated AGL-3219, with {@link CollectionPagination.totalPages}. */\n totalEntries?: number\n /**\n * Where `entries` begins in the collection's own order (AGL-3213): 0 for a\n * listing served from the cached read, and the page's own offset for one\n * served by a window read past that read's bound.\n *\n * Both windowing sites subtract it — `collectionEntriesPageWindow` on the\n * way into props, and the Collection entries block on the way into compose.\n * Without it a windowed listing renders empty, because every one of them\n * slices `[(page - 1) * perPage, …)` on the premise that `entries` starts at\n * the beginning of the collection.\n */\n windowStart?: number\n}\n\n/**\n * A bounded read of a collection's live entries (AGL-1516).\n *\n * `reachedBound` is a fact about the QUERY, not about `entries`, and the two\n * genuinely differ: the query asks for `status in ['published', 'scheduled']`\n * and the filter below then drops everything not live yet, so a read that came\n * back holding all {@link COLLECTION_SOURCE_MAX} docs can hand back fewer.\n * Counting the survivors — which is all a downstream consumer can do — reads\n * that as a complete collection, and the one thing a truncated read must never\n * be allowed to claim is completeness.\n */\ninterface LiveEntriesRead {\n entries: CollectionEntrySummary[]\n /** The query came back holding its own `.limit()`. */\n reachedBound: boolean\n /**\n * The read saw a `scheduled` entry whose `publishAt` has NOT arrived and\n * which has not been terminally refused — a schedule this collection is\n * still waiting on.\n *\n * The `apply-entry-schedules` beat publishes a due entry at its time and\n * drops the pages that list it (AGL-3340), but a beat can be down, and\n * `isLive`/`flipDueEntry` running during a render is what publishes the\n * entry then. A cached source would not merely serve stale entries, it\n * would withhold that render for as long as the entry stayed cached. This\n * is what lets the cache decline to store exactly those collections, so a\n * schedule the beat missed still lands on the render window rather than on\n * the TTL.\n */\n pendingSchedule: boolean\n}\n\n/**\n * The fields a LISTING read of an entry needs — the field mask on the query\n * below (AGL-3213).\n *\n * The point of the mask is the field that is NOT in it. `body` is the whole\n * post, and `mapEntryFields` has never mapped it on this path: a list card\n * binds a title, an excerpt, a cover and a byline, and the routed entry page\n * reads its one document separately. So the markdown of up to\n * {@link COLLECTION_SOURCE_MAX} posts crossed the wire, was parsed out of the\n * response, and was dropped one function later — on every fill of a cache\n * that every listing address, every \"Latest posts\" rail, the feed and the\n * author page share. A changelog is the worst case and also the common one.\n *\n * Firestore bills the document read either way, so this buys no reads; it\n * buys egress and the JSON parse, which is the part of a collection render\n * that grows with how much people have written.\n *\n * Site search is unaffected and must stay that way: it matches on `body`\n * through its OWN query in `apps/tenant/utils/search-content.ts`, which this\n * mask does not touch.\n *\n * ⛔ A reader added to `mapEntryFields` or to the liveness/schedule helpers\n * must be added HERE in the same edit. A field left out does not error — it\n * arrives `undefined`, which is exactly how `authorName` and `updatedAt` went\n * missing for months (AGL-2486, AGL-2534). The four schedule fields are\n * listed first for that reason: `status`, `publishAt` and `scheduleStatus`\n * decide whether an entry is live at all, and `flipDueEntry` WRITES\n * `publishAt` back as `publishedAt`, so a mask that dropped it would publish\n * a due entry with no date.\n */\nconst LIVE_ENTRY_FIELDS = [\n 'status',\n 'publishAt',\n 'publishedAt',\n 'scheduleStatus',\n 'title',\n 'slug',\n 'excerpt',\n 'authorName',\n 'authorId',\n 'coverImage',\n 'coverImageAlt',\n 'coverVideo',\n 'seoTitle',\n 'seoDescription',\n 'categoryId',\n 'category',\n 'tags',\n 'updatedAt',\n] as const\n\n/**\n * Most SCHEDULED entries one live read considers (AGL-3213).\n *\n * Read by its own query rather than taken from the dated page below, because\n * a schedule is invisible to that page: scheduling writes `publishAt` and\n * never `publishedAt`, and when the beat has not reached one, `flipDueEntry`\n * during a render is the only thing that publishes it. A schedule the read\n * misses is then a post that does not go out. The set is small by nature — a hundred pending schedules on one\n * collection is already an unusual editorial calendar.\n */\nconst SCHEDULED_SOURCE_MAX = 100\n\n/** Everything a public listing may show, before any ordering. */\nfunction liveEntriesBase(\n entriesRef: FirebaseFirestore.CollectionReference,\n): FirebaseFirestore.Query {\n return (\n entriesRef\n .where('status', 'in', ['published', 'scheduled'])\n // Everything this path reads, and nothing else (AGL-3213) — see\n // {@link LIVE_ENTRY_FIELDS}.\n .select(...LIVE_ENTRY_FIELDS)\n )\n}\n\n/**\n * The documents a live read considers, in the order the site shows them\n * (AGL-3213).\n *\n * ## Why this is ordered now, and why ordering alone would have broken it\n *\n * It was `where(status).limit(100)` with NO `orderBy`, sorted in memory\n * afterwards. That is not the newest hundred — it is a hundred documents in\n * NAME order, then sorted. Under the bound the two agree, because a hundred\n * out of a hundred is everything; past it they diverge completely. This site's\n * own changelog reached 166 live entries and its listing showed an arbitrary\n * hundred of them, chosen by document id, with 66 releases reachable only at\n * their own URLs.\n *\n * The comment that used to sit here was right about `orderBy`, though:\n * Firestore returns only documents that HAVE the ordered field, so a dated\n * read does not mis-sort an entry without a date — it hides it. Two of those\n * exist and both matter:\n *\n * A SCHEDULE carries `publishAt` and no `publishedAt` until it goes out.\n * Ordering alone would have stopped scheduled posts publishing\n * at all, silently, because nothing else publishes them.\n * AN IMPORT restores whatever the bundle carried, and\n * `/api/hosts/resources` validates no field for presence\n * either — so a published entry with no `publishedAt` exists.\n *\n * So it is three queries, in the shape the console's sorted window uses\n * (AGL-2853): the DATED page, every SCHEDULE, and — only when the dated page\n * came back SHORT, which is the server's own proof that the collection fits\n * inside the bound — a scan for live entries carrying no date. Past the bound\n * an undated entry sorts after every dated one by definition, so it belongs to\n * the tail pages, which are served by their own window read.\n */\nasync function readLiveEntryDocs(\n entriesRef: FirebaseFirestore.CollectionReference,\n): Promise<{\n docs: FirebaseFirestore.QueryDocumentSnapshot[]\n reachedBound: boolean\n}> {\n try {\n const dated = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', 'desc')\n // The document name breaks ties, so two entries published in the same\n // second cannot swap places between two reads and move a page boundary\n // under a reader. Descending to match the date: a composite index ends\n // with `__name__` in the last field's direction, which makes this the\n // `(status, publishedAt DESC)` index the console's table already needs.\n .orderBy('__name__', 'desc')\n // Named rather than literal (AGL-1516): a search index has to be able to\n // say \"this read reached its bound\", and it can only do that against a\n // bound it shares with the query. `collectionSourceReachedBound` reads\n // the same constant.\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n\n const scheduled = await entriesRef\n .where('status', '==', 'scheduled')\n .select(...LIVE_ENTRY_FIELDS)\n .limit(SCHEDULED_SOURCE_MAX)\n .get()\n\n /*\n * EITHER read stopping at its own limit means entries went unseen.\n *\n * The dated page is the usual one. The schedule page is the case a dated\n * read alone cannot even detect: a collection holding nothing but pending\n * schedules returns ZERO dated documents, so a bound measured only there\n * would report a complete read of an empty collection — and \"nothing is\n * live here\" is the claim that takes a listing off the site (AGL-3101).\n */\n const reachedBound =\n dated.docs.length >= COLLECTION_SOURCE_MAX ||\n scheduled.docs.length >= SCHEDULED_SOURCE_MAX\n\n const undated = reachedBound\n ? []\n : (\n await liveEntriesBase(entriesRef)\n .orderBy('__name__')\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n ).docs.filter((entryDoc) => !entryDoc.get('publishedAt'))\n\n const seen = new Set<string>()\n const docs: FirebaseFirestore.QueryDocumentSnapshot[] = []\n for (const entryDoc of [...dated.docs, ...scheduled.docs, ...undated]) {\n if (seen.has(entryDoc.id)) continue\n seen.add(entryDoc.id)\n docs.push(entryDoc)\n }\n return { docs, reachedBound }\n } catch (error) {\n /*\n * FAIL SOFT TO THE UNORDERED READ.\n *\n * The ordered query needs the `(status, publishedAt DESC)` composite\n * index. Indexes do NOT ship with a promotion — RELEASING.md deploys them\n * by hand afterwards — so the window between the code landing and the\n * index existing has to degrade rather than break. An arbitrary hundred\n * is a bad listing; a 500 is a customer's blog down.\n */\n console.error(error)\n const unordered = await liveEntriesBase(entriesRef)\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n return {\n docs: unordered.docs,\n reachedBound: unordered.docs.length >= COLLECTION_SOURCE_MAX,\n }\n }\n}\n\n/** The live entries among `docs`, newest first, publishing any that came due. */\nfunction toLiveEntries(\n docs: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n permission: SchedulePermission,\n): CollectionEntrySummary[] {\n return (\n docs\n .filter((entryDoc) => isLive(entryDoc.data(), permission))\n .map((entryDoc) => {\n const value = entryDoc.data()\n void flipDueEntry(entryDoc.ref, value, permission)\n return {\n $id: entryDoc.id,\n title: value['title'] ?? entryDoc.id,\n slug: value['slug'] ?? entryDoc.id,\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n })\n // An entry carrying no date at all sorts last rather than to 1970 —\n // the same place the query's own order puts it.\n .sort(\n (a, b) => (b.publishedAt?.seconds ?? 0) - (a.publishedAt?.seconds ?? 0),\n )\n )\n}\n\n/**\n * Fetches a collection's live entries (newest first), shared by the route\n * loader and the compose-time Collection entries block (AGL-551).\n */\nasync function listLiveEntries(\n entriesRef: FirebaseFirestore.CollectionReference,\n hostId: string,\n): Promise<LiveEntriesRead> {\n const { docs, reachedBound } = await readLiveEntryDocs(entriesRef)\n\n // Ask the plan question ONLY if something is actually due (AGL-471). A\n // collection with no due schedule — almost every render — never reads the\n // org at all.\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n\n // Record the terminal refusal on its own pass, because a refused entry is\n // NOT live and so never reaches the `flipDueEntry` inside the map below.\n // Without this the entry stays due forever: excluded from every render, and\n // re-reading the org on each one.\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n void flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n\n // Measured on the RAW docs, before the liveness filter (AGL-1516): a\n // not-yet-due entry is filtered out one line down, so this is the last\n // place that can see one at all.\n const pendingSchedule = docs.some((entryDoc) =>\n isPendingScheduled(entryDoc.data()),\n )\n\n const entries = toLiveEntries(docs, permission)\n\n return {\n entries,\n reachedBound,\n pendingSchedule,\n }\n}\n\n/** One page of a listing, and whether anything older follows it. */\ninterface CollectionListingPage {\n entries: CollectionEntrySummary[]\n /** The `limit(perPage + 1)` probe found an extra row. */\n hasMore: boolean\n}\n\n/**\n * One page of a listing that starts PAST the cached read (AGL-3213),\n * addressed by the document it continues from rather than by a position\n * (AGL-3219).\n *\n * Uncached on purpose, and it is the only read on the collection path that is.\n * The cached source exists because `/blog`, every listing address, the feed\n * and every \"Latest posts\" rail want the same first hundred entries\n * (AGL-1302); a page past that bound wants ten entries nobody else is asking\n * for, and its own ISR entry is already the cache for them.\n *\n * ## Why a cursor, and not the offset this replaces\n *\n * `.offset(n)` asks for a POSITION, and a listing takes its inserts at the\n * head, so every publish moves every position by one. The head pages and this\n * read are cached under different policies and revalidated by different\n * triggers — the publish fan-out refreshes the head eagerly and deliberately\n * stops there — so the two sides were routinely describing the collection as\n * it stood at two different moments, and the seam between them repeated an\n * entry or hid one for as long as the slower side lagged. `v1.0.0-beta.147`\n * shipped and `/changelog` showed `v1-0-0-beta-36` as both the last entry of\n * page 10 and the first of page 11.\n *\n * `startAfter(doc)` asks a question whose answer does not move: what follows\n * THIS entry. Publish a hundred entries at the head and this page returns the\n * same ten. The seam cannot drift because there is no longer a number on\n * either side of it to disagree about.\n *\n * `offset` also billed every document it skipped; a cursor bills none of them.\n */\nasync function readCollectionListingPage(options: {\n hostId: string\n collectionSlug: string\n /** Start after this document id — the older direction. */\n after?: string\n /** Start before this document id — the newer direction. */\n before?: string\n limit: number\n}): Promise<CollectionListingPage | null> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return null\n const entriesRef = collectionDoc.ref.collection('entries')\n\n const cursorId = options.before || options.after\n if (!cursorId) return null\n // A direct get, not a `where('slug', ...)` query: the cursor IS the\n // document name, which is the second field the read orders on, so the\n // snapshot it needs is one document rather than an index lookup.\n const cursorDoc = await entriesRef.doc(cursorId).get()\n // A cursor naming a document that no longer exists — deleted, or a URL\n // someone kept — cannot be positioned against. Null sends the caller back\n // to the cached head, which is a page the reader can act on.\n if (!cursorDoc.exists) return null\n\n // Backwards is the same query read the other way up, so both directions\n // rest on an index the project already deploys: `(status, publishedAt)`\n // exists ascending and descending both.\n const backwards = Boolean(options.before)\n const snapshot = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', backwards ? 'asc' : 'desc')\n .orderBy('__name__', backwards ? 'asc' : 'desc')\n .startAfter(cursorDoc)\n // One more than the page: the extra row is the whole of \"is there\n // another page\", and it replaces a `count()` over the collection.\n .limit(options.limit + 1)\n .get()\n\n const hasMore = snapshot.docs.length > options.limit\n const pageDocs = snapshot.docs.slice(0, options.limit)\n // Read backwards, the newest of the page came back last.\n const docs = backwards ? [...pageDocs].reverse() : pageDocs\n\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(options.hostId)\n : 'allowed'\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n void flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n const entries = toLiveEntries(docs, permission)\n // The byline reads `authorName`, which a record-backed author only has\n // once resolved — the cached source does this for the entries it holds,\n // and a windowed page holds entries it never saw (AGL-2486).\n await attachEntryAuthors(options.hostId, entries)\n return { entries, hasMore }\n } catch (error) {\n // Fail open to the cached head rather than to a 500: the caller keeps\n // whatever it already had, which is a page the reader has seen before\n // rather than an error they cannot get past.\n console.error(error)\n return null\n }\n}\n\n/**\n * The cursor a retired `/{collection}/page/{n}` address redirects onto\n * (AGL-3219).\n *\n * This is the ONE place a position is still resolved, and it is deliberately\n * the only one: a 301 is served once, the reader lands on an address that\n * cannot drift afterwards, and whatever the position meant at that instant is\n * the page they would have got anyway. Everything downstream is cursors.\n *\n * Keys only — `select()` with no fields asks Firestore for document names and\n * nothing else — so the skipped documents are billed at the cheapest rate the\n * offset can be had for. Returns `''` when the position is past the end,\n * which is a 404 rather than a redirect to nowhere.\n */\nexport async function resolveCollectionPageCursor(options: {\n hostId: string\n collectionSlug: string\n /** 1-based page whose PREVIOUS entry is the cursor. */\n page: number\n perPage: number\n}): Promise<string> {\n const skip = (options.page - 1) * options.perPage - 1\n if (!Number.isFinite(skip) || skip < 0) return ''\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return ''\n const snapshot = await collectionDoc.ref\n .collection('entries')\n .where('status', 'in', ['published', 'scheduled'])\n .select()\n .orderBy('publishedAt', 'desc')\n .orderBy('__name__', 'desc')\n .offset(skip)\n .limit(1)\n .get()\n return snapshot.docs[0]?.id ?? ''\n } catch (error) {\n console.error(error)\n return ''\n }\n}\n\n/** Compose-time view of a collection: its live entries and its taxonomy. */\nexport interface PublishedCollectionSource {\n /**\n * The collection DOCUMENT this source was read from — its display name and\n * its template screen ids — or null when the slug names no content\n * collection.\n *\n * Carried so a routed listing can be served ENTIRELY from this cached\n * source. `getCollectionContent` used to resolve the same document itself\n * and then read the same entries again uncached, which meant `/blog`,\n * every `/blog/page/{n}`, every `/blog/category/{slug}` and the RSS feed\n * each paid a full collection read per regeneration while the identical\n * data already sat in this cache for every OTHER page on the site.\n */\n collection: CollectionContent['collection']\n entries: CollectionEntrySummary[]\n categories: CollectionCategory[]\n /**\n * Whether the read saw a schedule it is still waiting on — see\n * {@link LiveEntriesRead.pendingSchedule}. Never stored, only consulted by\n * the cache above, so no consumer has to know about it.\n */\n pendingSchedule?: boolean\n /**\n * Whether the entries read stopped at {@link COLLECTION_SOURCE_MAX}\n * (AGL-1516) — carried out of the loader because `entries.length` cannot\n * answer it once the liveness filter has run. Fail-open paths report\n * `false`: an empty result is not a bounded read, and describing it as one\n * would tell a reader their search covered less than it did.\n */\n reachedBound: boolean\n}\n\n/**\n * Published entries + category taxonomy for a collection resolved by slug —\n * the data source of the Collection entries block on arbitrary screens\n * (AGL-551/582). Fail-open: errors and unknown slugs resolve to an empty\n * list so a renamed collection never takes a published screen down.\n */\nexport async function getPublishedCollectionSource(options: {\n hostId: string\n collectionSlug: string\n}): Promise<PublishedCollectionSource> {\n try {\n return await withRenderCache({\n key: [\n 'tenant-collection-source',\n options.hostId,\n options.collectionSlug,\n ],\n revalidate: COLLECTION_SOURCE_TTL_SECONDS,\n tags: [tenantDataTag(options.hostId)],\n read: () => readPublishedCollectionSource(options),\n // A collection with a schedule still pending is SERVED but not STORED.\n //\n // The beat publishes a due entry and drops this tag (AGL-3340); when\n // the beat is down, `flipDueEntry` during a render is what publishes\n // it, so storing this source would suppress the very renders that would\n // have noticed the entry coming due, and the post would wait out the\n // TTL rather than land at its time. Declining to store leaves those\n // collections exactly as uncached as they were before this cache\n // existed, which is the only cost this cache is not allowed to reduce.\n //\n // Also refuses a collection that resolved to nothing, for the reason\n // `withRenderCache` states about negatives generally: a slug that\n // misses once must not miss for an hour.\n store: (value) => Boolean(value.collection) && !value.pendingSchedule,\n })\n } catch (error) {\n console.error(error)\n return readPublishedCollectionSource(options)\n }\n}\n\nasync function readPublishedCollectionSource(\n options: {\n hostId: string\n collectionSlug: string\n },\n): Promise<PublishedCollectionSource> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) {\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n const { entries, reachedBound, pendingSchedule } = await listLiveEntries(\n collectionDoc.ref.collection('entries'),\n options.hostId,\n )\n // The compose-time source feeds the Collection entries block, whose byline\n // reads `authorName` — so a record-backed author has to be resolved here\n // too, or the block prints nothing for the entries a list page shows\n // (AGL-2486). This result is the cached one, which is what keeps the extra\n // read amortized across every page of the site that carries the block.\n await attachEntryAuthors(options.hostId, entries)\n return {\n collection: mapCollectionDoc(collectionDoc, options.collectionSlug),\n entries,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n reachedBound,\n ...(pendingSchedule ? { pendingSchedule: true } : {}),\n }\n } catch (error) {\n console.error(error)\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n}\n\n/** Entries-only view of {@link getPublishedCollectionSource} (AGL-551). */\nexport async function getPublishedCollectionEntries(options: {\n hostId: string\n collectionSlug: string\n}): Promise<CollectionEntrySummary[]> {\n return (await getPublishedCollectionSource(options)).entries\n}\n\n/**\n * Narrows a listing to its routed category and stamps its pagination\n * (AGL-1321 / AGL-620).\n *\n * Category first, ALWAYS: the two have to describe the same set. Counting\n * pages over the whole collection and then filtering would advertise pages\n * that render empty and hide entries that exist.\n *\n * `entriesReachedBound` is read by the caller BEFORE this runs, because a\n * category route hands its already-narrowed entries to compose and the\n * entries block's \"measure the raw set, not the filtered one\" rule then has\n * nothing raw left to measure (AGL-1516).\n */\nfunction applyCategoryAndPagination(\n data: CollectionContent,\n options: {\n page?: number\n perPage?: number\n categorySlug?: string\n },\n listing?: {\n /** Where `data.entries` begins in that collection's order. */\n windowStart?: number\n /** The shared read came back holding its own limit. */\n reachedBound?: boolean\n /**\n * The `perPage + 1` probe of a CURSOR page found an extra row — set only\n * when this listing was served by one, because only that read can answer\n * it (AGL-3219).\n */\n cursorHasMore?: boolean\n },\n): void {\n const { page = 1, perPage } = options\n const routedCategory = (options.categorySlug ?? '').trim()\n if (routedCategory) {\n const match = resolveCollectionCategoryBySlug(\n data.collection?.categories,\n routedCategory,\n )\n data.category = {\n slug: collectionCategorySlug(routedCategory),\n ...(match ? { id: match.id } : {}),\n name: match?.name ?? routedCategory,\n ...(match?.description ? { description: match.description } : {}),\n known: Boolean(match),\n }\n data.entries = data.entries.filter((entry) =>\n entryMatchesCategoryRoute(\n entry,\n { slug: routedCategory, ...(match ? { category: match } : {}) },\n data.collection?.categories,\n ),\n )\n }\n\n if (perPage && perPage > 0) {\n /*\n * The total is the COLLECTION's, not the read's (AGL-3213).\n *\n * `entries.length` was the count, and on a collection inside the bound it\n * still is — the two are the same number there. Past the bound it is the\n * size of the window, which is how `/changelog` advertised \"Page 10 of\n * 10\" while holding 166 entries and linking to 100 of them.\n *\n * A ROUTED CATEGORY keeps counting its own entries, because that is the\n * only honest number available here: the narrowing happens in memory over\n * the cached head, so both the count and the listing describe the same\n * bounded set. Paging a category past the bound needs its own ordered\n * query and a `(categoryId, status, publishedAt DESC)` index; until then\n * a category of a very large collection is capped, and says so by\n * agreeing with what it shows.\n */\n const windowStart = Number(listing?.windowStart)\n const windowed = Number.isFinite(windowStart) && windowStart > 0\n\n /*\n * The cursors, which are the pager's real answer (AGL-3219).\n *\n * `data.entries` is either EXACTLY this page — a cursor read — or the\n * whole cached head, which every listing address shares and each slices\n * its own page out of. So the page's own last entry is at the end of the\n * array in the first case and at `page * perPage - 1` in the second, and\n * the cursor is that entry's document id.\n */\n const pageEnd = windowed ? data.entries.length : page * perPage\n const last = data.entries[pageEnd - 1]\n const first = data.entries[windowed ? 0 : (page - 1) * perPage]\n\n /*\n * Is there an older page?\n *\n * A cursor page KNOWS, because its read asked for one more entry than it\n * needed and the extra row came back. The head has to reason: either it\n * is holding more entries than this page shows, or it is holding all it\n * could read and the read stopped at its own bound, which is the one\n * thing `entries.length` can never tell you about the collection.\n */\n const hasMore =\n listing?.cursorHasMore ??\n (data.entries.length > pageEnd ||\n (Boolean(listing?.reachedBound) && !routedCategory))\n\n /*\n * The deprecated total, stated ONLY where it can be true.\n *\n * A collection that fits inside one read can be counted, and a template\n * binding `{{pagination.totalPages}}` keeps rendering the number it\n * always did. Past the bound there is no honest total — the count and\n * the listing were reading the collection at two different moments, which\n * is what made the seam repeat an entry — so it is left absent rather\n * than asserted. A routed category counts its own narrowed set, which is\n * bounded by the same head and therefore countable.\n */\n const countable = routedCategory || !listing?.reachedBound\n const totalEntries = countable ? data.entries.length : undefined\n\n data.pagination = {\n page,\n perPage,\n nextCursor: hasMore && last?.$id ? last.$id : '',\n prevCursor: page > 1 && first?.$id ? first.$id : '',\n ...(totalEntries === undefined\n ? {}\n : {\n totalEntries,\n totalPages: collectionTotalPages(totalEntries, perPage),\n }),\n ...(windowed ? { windowStart } : {}),\n }\n }\n}\n\n/**\n * Resolves a non-screen path against the host's content collections\n * (Content Collections & Blog): `/{collectionSlug}` returns the published\n * entry list, `/{collectionSlug}/{entrySlug}` one entry. Fail-open — errors\n * resolve to `collection: null` and the caller 404s.\n *\n * A listing resolves only for a collection with a live entry (AGL-3101); one\n * with nothing live answers `collection: null` as well, so its listing, feed\n * and markdown twin are not public until its first entry is.\n */\nexport async function getCollectionContent(options: {\n hostId: string\n collectionSlug: string\n entrySlug?: string\n /**\n * 1-based list page (AGL-620), now a DISPLAY counter (AGL-3219): it labels\n * the page the reader is on and no read is positioned from it. The entries\n * come from `after`/`before`, or from the head of the cached source when\n * neither is set.\n */\n page?: number\n /** Entries per page (AGL-620); when set the list is paginated. */\n perPage?: number\n /**\n * Continue AFTER this entry's document id — the older direction (AGL-3219).\n *\n * What `/{collection}?after={id}` carries. A page defined this way does not\n * move when something is published above it, which is the whole reason the\n * addresses stopped being positions.\n */\n after?: string\n /** Continue BEFORE this entry's document id — the newer direction. */\n before?: string\n /**\n * The site's zone (AGL-3237). Stamped onto the returned content so every\n * reader downstream — including the client fallback renderer — formats from\n * the same string rather than from its own runtime.\n */\n timeZone?: string\n /**\n * Category segment of `/{collection}/category/{slug}` (AGL-1321). Filters\n * the listing before pagination is computed, so page counts and the page\n * windows describe the FILTERED set rather than the whole collection.\n */\n categorySlug?: string\n /**\n * Reveal the named entry even though the public site withholds it — the\n * live-site preview of a scheduled post (AGL-3205).\n *\n * ⛔ A VERIFIED GRANT, NOT A REQUEST. The caller passes `true` only after a\n * signed preview token has been checked against the resolved hostId AND\n * this exact `collectionSlug`/`entrySlug` (`verifyCollectionPreviewToken`).\n * The token format stays in the app that receives the URL; what crosses into\n * this lib is the verdict, so nothing here can be tricked by a payload's own\n * spelling of which entry it names.\n *\n * ENTRY ROUTES ONLY, and one entry at a time. It is ignored on a list route\n * — a preview of one post must not add it to `/blog`, to the feed, or to a\n * Collection entries block on any other page, all of which read the SHARED\n * cached source. Nothing it touches is cached at all.\n *\n * The preview render also writes NOTHING: see the `flipDueEntry` guard\n * below. Publishing a schedule stays the sole business of a public render.\n */\n previewUnpublishedEntry?: boolean\n}): Promise<CollectionContent> {\n const { hostId, collectionSlug, entrySlug } = options\n // Never on a list route, whatever the caller passed: `entrySlug` is what\n // makes the grant addressable at all, and the list is the shared cached\n // read this must stay out of.\n const preview = Boolean(options.previewUnpublishedEntry) && Boolean(entrySlug)\n const data: CollectionContent = {\n // Stamped before any early return, so every shape this function can hand\n // back carries it — including the empty one a 404 renders from.\n ...(options.timeZone ? { timeZone: options.timeZone } : {}),\n collection: null,\n entries: [],\n entry: null,\n pagination: null,\n category: null,\n error: null,\n }\n try {\n // A LIST route is served entirely from the CACHED source, which every\n // other page on the site already shares. It used to resolve the\n // collection and re-read its entries here, uncached, on every\n // regeneration of every listing address — `/blog`, nine `/blog/page/{n}`,\n // one `/blog/category/{slug}` per category, and the RSS feed — so a\n // collection of N live entries cost `1 + N + authors` reads per address\n // per window, for data byte-identical to what the cache was already\n // holding for the home page's \"Latest posts\" rail.\n //\n // An ENTRY route stays where it was: it reads ONE document by slug and\n // has nothing to share.\n if (!entrySlug) {\n const source = await getPublishedCollectionSource({\n hostId,\n collectionSlug,\n })\n if (!source.collection) return data\n // A collection is not a PAGE until something in it is live (AGL-3101).\n // Without this, creating one publishes `/{slug}` at once — an empty\n // listing with a feed and a markdown twin, before a word of it is\n // written. Answering it as no collection makes every listing address\n // 404 the way an unknown slug does, until the first entry is published\n // or its schedule comes due.\n //\n // Read off the UNFILTERED live set, before the category narrows it, so\n // an empty category of a live collection still renders. A read that\n // stopped at its bound cannot prove the collection empty — the live\n // entries may be past it — so that one keeps its listing. The rule\n // lives here and not in the source above: the source also feeds the\n // Collection entries block and the author page, and to them an empty\n // collection is an empty list, not a missing one.\n if (!source.entries.length && !source.reachedBound) return data\n data.collection = source.collection\n data.entries = source.entries\n data.entriesReachedBound = source.reachedBound\n /*\n * A page that starts past the cached read is served by its own window\n * (AGL-3213). Everything before that point comes out of the shared\n * source, so the pages a reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a window read of the whole collection would hand\n * it ten entries of which any number may belong to another category.\n */\n const { page = 1, perPage } = options\n const cursor = (options.after ?? options.before ?? '').trim()\n let windowStart = 0\n let cursored: CollectionListingPage | null = null\n /*\n * A cursor address is served by its own read (AGL-3219). Everything\n * reachable without one comes out of the shared source, so the pages a\n * reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a cursor read of the whole collection would hand it\n * ten entries of which any number belong to another category.\n */\n if (perPage && perPage > 0 && cursor && !(options.categorySlug ?? '').trim()) {\n cursored = await readCollectionListingPage({\n hostId,\n collectionSlug,\n ...(options.before ? { before: options.before } : { after: cursor }),\n limit: perPage,\n })\n // Null means the cursor read failed, or named a document that is\n // gone. The cached head is the better answer than an empty page: the\n // reader sees the newest entries rather than nothing at all.\n if (cursored) {\n data.entries = cursored.entries\n /*\n * `entries` is now EXACTLY this page, and both windowing sites\n * slice `[(page - 1) * perPage, …)`. Declaring the window to start\n * at that same offset makes their subtraction come out at zero, so\n * they take the page whole.\n *\n * Both sides of the subtraction are built from the same `page`, so\n * a hand-edited counter in a URL cancels itself out: the label is\n * wrong and the entries are still this cursor's page.\n */\n windowStart = (page - 1) * perPage\n }\n }\n applyCategoryAndPagination(data, options, {\n windowStart,\n reachedBound: source.reachedBound,\n ...(cursored ? { cursorHasMore: cursored.hasMore } : {}),\n })\n return data\n }\n\n const collectionDoc = await findContentCollection(hostId, collectionSlug)\n if (!collectionDoc) return data\n data.collection = mapCollectionDoc(collectionDoc, collectionSlug)\n\n const entryQuery = await collectionDoc.ref\n .collection('entries')\n .where('slug', '==', entrySlug)\n .limit(5)\n .get()\n // Same two-step as `listLiveEntries`: only pay for the org read when\n // something is due, and record the refusal on its own pass because a\n // refused entry never becomes the `entryDoc` below (AGL-471).\n //\n // A PREVIEW RENDER SKIPS BOTH WRITES (AGL-3205). `flipDueEntry` is how a\n // content entry is published — by the beat, or by a render as its\n // backstop — and the render half belongs to the PUBLIC render: a preview\n // is one person looking at one post through a link, and it must not be\n // able to publish it, nor to burn its schedule with the terminal refusal\n // marker. Skipping the writes costs nothing — the beat or the next public\n // render asks the same questions and writes the same answers — and it is\n // what keeps a preview link from publishing anything.\n const dueHere = entryQuery.docs.filter((docSnapshot) =>\n isDueScheduled(docSnapshot.data()),\n )\n const permission: SchedulePermission = dueHere.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n if (permission !== 'allowed' && !preview) {\n for (const docSnapshot of dueHere) {\n void flipDueEntry(docSnapshot.ref, docSnapshot.data(), permission)\n }\n }\n /**\n * What a grant reveals: an entry this collection HOLDS and the site does\n * not serve.\n *\n * Deliberately not routed through `isLive`, which is the public answer and\n * has one other reader (`entry-link-routes`) whose whole job is to agree\n * with it. A second, wider answer inside it would make a LINK to a\n * previewed post resolve on the public site.\n *\n * Every status but `published` qualifies, which is `draft` as well as\n * `scheduled`: the ask is \"let me see it before it goes out\", and a post\n * is most worth looking at before its schedule is set. The blast radius is\n * the same either way — one entry, named in the signature, on one host.\n */\n const entryDoc =\n entryQuery.docs.find((docSnapshot) =>\n isLive(docSnapshot.data(), permission),\n ) ?? (preview ? entryQuery.docs[0] : undefined)\n if (entryDoc) {\n const value = entryDoc.data()\n if (!preview) void flipDueEntry(entryDoc.ref, value, permission)\n if (preview && !isLive(value, permission)) {\n // The facts the preview chrome states back to the reader, so the page\n // cannot be mistaken for the published post. Read from the stored\n // document rather than inferred from the render.\n data.entryPreview = {\n status: String(value['status'] ?? 'draft'),\n publishAtSeconds:\n typeof value['publishAt']?.seconds === 'number'\n ? value['publishAt'].seconds\n : null,\n }\n }\n data.entry = {\n $id: entryDoc.id,\n title: value['title'] ?? entrySlug,\n slug: entrySlug,\n body: value['body'] ?? '',\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n await attachEntryAuthors(hostId, [data.entry])\n }\n } catch (error) {\n console.error(error)\n data.error = error\n }\n return data\n}\n\nexport default getCollectionContent\n"],"names":["AUTHORS_MAX_PER_HOST","collectionCategorySlug","checkEntitlement","COLLECTION_SOURCE_MAX","collectionTotalPages","entryMatchesCategoryRoute","hostCollectionKind","normalizeContentAuthor","normalizeContentSchemaType","resolveCollectionCategoryBySlug","resolveEntryAuthor","ENTRY_PUBLISH_SORT_FIELD","firebaseAdmin","getOrgForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","COLLECTION_SOURCE_TTL_SECONDS","findContentCollection","hostId","collectionSlug","matches","app","firestore","collection","doc","where","limit","get","docs","find","docSnapshot","data","mapEntryFields","value","excerpt","authorName","authorId","coverImage","coverImageAlt","coverVideo","seoTitle","seoDescription","categoryId","category","tags","Array","isArray","filter","tag","updatedAt","seconds","mapCollectionCategories","item","id","trim","name","map","description","mapCollectionDoc","collectionDoc","$id","displayName","slug","templateScreenId","undefined","listScreenId","entryScreenId","schemaType","excludeEntriesFromSearch","categories","attachEntryAuthors","entries","ids","Set","entry","Boolean","slice","authors","length","authorsRef","snapshots","getAll","snapshot","exists","author","error","console","ENTRY_SCHEDULE_SKIPPED","scheduleAlreadyRefused","isDueScheduled","Number","POSITIVE_INFINITY","Date","now","isPendingScheduled","entryScheduleDueAtMs","scheduledPublishingPermission","org","isLive","permission","flipDueEntry","docRef","precondition","update","scheduleStatus","status","publishedAt","applyDueEntrySchedule","options","ref","updateTime","lastUpdateTime","LIVE_ENTRY_FIELDS","SCHEDULED_SOURCE_MAX","liveEntriesBase","entriesRef","select","readLiveEntryDocs","dated","orderBy","scheduled","reachedBound","undated","entryDoc","seen","has","add","push","unordered","toLiveEntries","title","sort","a","b","listLiveEntries","due","pendingSchedule","some","readCollectionListingPage","cursorId","before","after","cursorDoc","backwards","startAfter","hasMore","pageDocs","reverse","resolveCollectionPageCursor","skip","page","perPage","isFinite","offset","getPublishedCollectionSource","key","revalidate","read","readPublishedCollectionSource","store","getPublishedCollectionEntries","applyCategoryAndPagination","listing","routedCategory","categorySlug","match","known","windowStart","windowed","pageEnd","last","first","cursorHasMore","countable","totalEntries","pagination","nextCursor","prevCursor","totalPages","getCollectionContent","entrySlug","preview","previewUnpublishedEntry","timeZone","entryQuery","source","entriesReachedBound","cursor","cursored","dueHere","entryPreview","String","publishAtSe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KAAK,CAAC,OAAO,YAAbA,cAAiB;eACpBD,eAAeC;gBAClByE,aAAa,EAACzE,qBAAAA,KAAK,CAAC,cAAc,YAApBA,qBAAwBA,KAAK,CAAC,YAAY,IACpD;oBACEiB,SAAS,EAACjB,sBAAAA,KAAK,CAAC,cAAc,YAApBA,sBAAwBA,KAAK,CAAC,YAAY,EAAEiB,OAAO;gBAC/D,IACA;;YAEN,MAAMoB,mBAAmBpD,QAAQ;gBAACa,KAAK2C,KAAK;aAAC;QAC/C;IACF,EAAE,OAAOW,OAAO;QACdC,QAAQD,KAAK,CAACA;QACdtD,KAAKsD,KAAK,GAAGA;IACf;IACA,OAAOtD;AACT;AAEA,eAAeoJ,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/get-collection-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AUTHORS_MAX_PER_HOST,\n type CollectionCategory,\n collectionCategorySlug,\n checkEntitlement,\n COLLECTION_SOURCE_MAX,\n collectionEntryVideoDurationSeconds,\n collectionTotalPages,\n type ContentAuthorRecord,\n entryMatchesCategoryRoute,\n hostCollectionKind,\n normalizeContentAuthor,\n normalizeContentSchemaType,\n resolveCollectionCategoryBySlug,\n resolveEntryAuthor,\n} from '@aglyn/aglyn/server'\nimport { ENTRY_PUBLISH_SORT_FIELD } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\n\n/**\n * ONE cached read per collection, shared by every surface that lists it\n * (AGL-1302).\n *\n * It began as the compose-time source only: a Collection entries block in a\n * shared layout re-read up to ~100 entry docs on EVERY page of the site. The\n * routed listing was left out on the argument that the page's own ISR entry\n * amortized it — which is true of ONE address and false of a collection,\n * because a collection is not one address. `/blog`, `/blog/page/2…10`, a\n * `/blog/category/{slug}` per category and `/blog/rss.xml` are all the same\n * data, each paying its own `1 + entries + authors` per window, beside a\n * cache already holding exactly that.\n *\n * The other half of that argument was real and is answered rather than\n * dropped: `flipDueEntry` is a write, and a render is the backstop that\n * publishes a content entry when the `apply-entry-schedules` beat has not\n * (AGL-3340), so a cache that stored a collection with a schedule still\n * pending would suppress the render that publishes it.\n * `getPublishedCollectionSource` therefore declines to STORE exactly those\n * collections — see its `store` predicate — which keeps that backstop on the\n * render window, and puts everything else on this TTL.\n */\nconst COLLECTION_SOURCE_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/**\n * Resolve a public content-collection slug (AGL-954). Commerce's product\n * collections share `hosts/{hostId}/collections`, and a slug is only unique\n * within a kind — a bare `limit(1)` handed the URL to whichever doc Firestore\n * returned first, so a catalog collection could shadow a blog. Reads a small\n * window instead and takes the first content-kind match.\n */\nasync function findContentCollection(\n hostId: string,\n collectionSlug: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | undefined> {\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .where('slug', '==', collectionSlug)\n .limit(5)\n .get()\n return matches.docs.find(\n (docSnapshot) => hostCollectionKind(docSnapshot.data()) === 'content',\n )\n}\n\nexport interface CollectionEntrySummary {\n $id: string\n title: string\n slug: string\n excerpt?: string\n /**\n * The byline TEXT (AGL-686). Either the entry's own legacy free-typed\n * string or — since AGL-2486 — the name of the author record `authorId`\n * points at, resolved here so every downstream reader (the Entry Meta\n * block, `{{entry.author}}`, the RSS feed) keeps asking one field.\n */\n authorName?: string\n /** Reference into `hosts/{hostId}/authors` (AGL-2486). */\n authorId?: string\n /**\n * The resolved author RECORD (AGL-2486) — what `Article.author` is built\n * from. Null when the entry names no author, in which case the page falls\n * back to the site's publisher entity exactly as it always has.\n */\n author?: ContentAuthorRecord | null\n body?: string\n coverImage?: string\n /** `og:image:alt` for the cover (AGL-2417); travels WITH `coverImage`. */\n coverImageAlt?: string\n /**\n * The featured video (AGL-2956): a media reference or a URL, a hosted\n * player's link included, in the shape `coverImage` is. See\n * `CollectionEntryRecord.coverVideo`.\n */\n coverVideo?: string\n /**\n * The featured video's length in whole seconds (AGL-3584), or unset when the\n * entry names none. See `CollectionEntryRecord.coverVideoDuration`.\n */\n coverVideoDuration?: number\n /** Search-result title override (AGL-582); falls back to `title`. */\n seoTitle?: string\n /** Meta description override (AGL-582); falls back to `excerpt`. */\n seoDescription?: string\n /**\n * Stable reference into the collection's `categories` taxonomy\n * (AGL-582); resolved to a display name at render.\n */\n categoryId?: string\n /** Legacy free-typed bucket (AGL-582); read-only fallback. */\n category?: string\n /** Free-form labels (AGL-582). */\n tags?: string[]\n publishedAt?: { seconds: number } | null\n /**\n * Last edited, which is what `Article.dateModified` publishes (AGL-2534).\n *\n * Distinct from {@link publishedAt} on purpose: re-dating a post is not\n * editing it, so the console writes `publishedAt` alone when an author\n * backdates and this stays put. Google reads `dateModified` for freshness.\n */\n updatedAt?: { seconds: number } | null\n /**\n * The collection this entry came out of (AGL-2518), stamped only by a\n * reader that MIXES collections — the author page. Unset on every routed\n * listing, where the route already answers the question. See\n * `CollectionEntryRecord.collectionSlug`.\n */\n collectionSlug?: string\n /** The display name of {@link collectionSlug}. */\n collectionName?: string\n}\n\n/** Entry-doc fields shared by the list and single-entry mappers (AGL-582). */\nfunction mapEntryFields(\n value: FirebaseFirestore.DocumentData,\n): Pick<\n CollectionEntrySummary,\n | 'excerpt'\n | 'coverImage'\n | 'coverImageAlt'\n | 'coverVideo'\n | 'coverVideoDuration'\n | 'seoTitle'\n | 'seoDescription'\n | 'authorName'\n | 'authorId'\n | 'categoryId'\n | 'category'\n | 'tags'\n | 'updatedAt'\n> {\n const coverVideoDuration = collectionEntryVideoDurationSeconds(\n value['coverVideoDuration'],\n )\n return {\n excerpt: value['excerpt'] ?? '',\n // The byline was DECLARED on `CollectionEntrySummary` (AGL-686) and\n // mapped by nobody, so `entry.authorName` was `undefined` on every entry\n // this loader returned — which is every routed entry page and every\n // Collection entries block. The console collected the field, the rules\n // stored it, the JSON-LD builder read it and the Entry Meta block printed\n // it, and all three saw nothing, because the one hop between Firestore\n // and them dropped it (AGL-2486). Written but never read, in the\n // direction that leaves no error behind.\n authorName: value['authorName'] ?? '',\n authorId: value['authorId'] ?? '',\n coverImage: value['coverImage'] ?? '',\n coverImageAlt: value['coverImageAlt'] ?? '',\n // Here, where both read paths pick it up, so a list card and the routed\n // entry page can each bind the featured video (AGL-2956).\n coverVideo: value['coverVideo'] ?? '',\n // Its length (AGL-3584), for the Video's `durationSeconds` and so the\n // watch page's `VideoObject.duration`. Absent rather than `0` when the\n // entry names none, which every reader treats as no duration.\n ...(coverVideoDuration ? { coverVideoDuration } : {}),\n seoTitle: value['seoTitle'] ?? '',\n seoDescription: value['seoDescription'] ?? '',\n categoryId: value['categoryId'] ?? '',\n category: value['category'] ?? '',\n tags: Array.isArray(value['tags'])\n ? value['tags'].filter((tag): tag is string => typeof tag === 'string')\n : [],\n /*\n `dateModified`'s source (AGL-2534), and it was missing for the same\n reason `authorName` was — the reason this function's own comment above\n describes.\n\n The console has written `updatedAt` on every save, `page.tsx` reads\n `entry.updatedAt.seconds` to publish `Article.dateModified`, a spec\n asserts the conversion, and two console comments explain why it must not\n track `publishedAt`. Nothing mapped it, so `entry.updatedAt` was\n `undefined` on every entry the loader has ever returned and no published\n article has ever carried a `dateModified` — the freshness signal Google\n reads. The spec passed throughout because it builds its entry object by\n hand and never crosses this boundary.\n\n Mapped HERE rather than beside `publishedAt` at the two call sites: this\n is an ordinary field with no `publishAt` fallback and nothing sorts on\n it, so one place is enough — and one place is what stops the next read\n path from forgetting it.\n */\n updatedAt: value['updatedAt']?.seconds\n ? { seconds: value['updatedAt'].seconds }\n : null,\n }\n}\n\n/**\n * The collection doc's category taxonomy (AGL-582), sanitized: only\n * `{ id, name }` pairs with non-empty strings survive, order preserved.\n *\n * `description` rides along when the author wrote one and is dropped when it\n * is blank or not a string, so the head can tell \"described\" from \"not\n * described\" by truthiness alone — an empty string reaching the metadata\n * would suppress the template screen's description and leave the listing with\n * none at all.\n */\nfunction mapCollectionCategories(value: unknown): CollectionCategory[] {\n if (!Array.isArray(value)) return []\n return value\n .filter(\n (item): item is CollectionCategory =>\n typeof item?.id === 'string' &&\n item.id.trim() !== '' &&\n typeof item?.name === 'string' &&\n item.name.trim() !== '',\n )\n .map((item) => {\n const description =\n typeof item.description === 'string' ? item.description.trim() : ''\n return {\n id: item.id,\n name: item.name,\n ...(description ? { description } : {}),\n }\n })\n}\n\n/**\n * The routed view of a collection DOCUMENT (AGL-551): its name and the\n * template screens its list and entry routes render through.\n *\n * `slug` is the slug that was ASKED FOR rather than the one stored, which is\n * what every caller of this file has always returned — a listing has to build\n * its own URLs out of the segment the reader is standing on.\n */\nfunction mapCollectionDoc(\n collectionDoc: FirebaseFirestore.QueryDocumentSnapshot,\n collectionSlug: string,\n): CollectionContent['collection'] {\n return {\n $id: collectionDoc.id,\n displayName: collectionDoc.get('displayName') ?? collectionSlug,\n slug: collectionSlug,\n templateScreenId: collectionDoc.get('templateScreenId') ?? undefined,\n listScreenId: collectionDoc.get('listScreenId') ?? undefined,\n entryScreenId: collectionDoc.get('entryScreenId') ?? undefined,\n // Normalized HERE rather than at the head (AGL-2536), so an unrecognised\n // stored value can never reach the JSON-LD: an `@type` the vocabulary\n // does not define makes a consumer discard the whole node, costing the\n // page every property it publishes rather than just this one.\n schemaType: normalizeContentSchemaType(collectionDoc.get('schemaType')),\n // \"List the collection, not its entries\" (AGL-3247). Carried as the\n // STORED boolean rather than as the resolved answer: the render surface\n // composes it with the site-level switch itself, and a pre-resolved flag\n // here would be a second place that has to remember that switch exists.\n excludeEntriesFromSearch:\n collectionDoc.get('excludeEntriesFromSearch') === true,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n }\n}\n\n/**\n * Resolve the author RECORDS a set of entries reference (AGL-2486).\n *\n * Costs ZERO reads when no entry names an `authorId`, which is every site\n * that has not adopted custom authors and every entry written before them —\n * the check is on the ids already in hand, not a probe of the collection. When\n * ids are present it is one `getAll` of the DISTINCT ones, bounded by\n * {@link AUTHORS_MAX_PER_HOST} and by the ≤100-entry page above it, rather\n * than a read per entry.\n *\n * Fail-open, like every other read in this file: an authors read that throws\n * leaves the entries with their legacy `authorName` (or the site entity) and\n * the page renders. A byline is not worth a 500.\n */\nasync function attachEntryAuthors(\n hostId: string,\n entries: CollectionEntrySummary[],\n): Promise<void> {\n const ids = [\n ...new Set(\n entries\n .map((entry) => (entry.authorId ?? '').trim())\n .filter(Boolean),\n ),\n ].slice(0, AUTHORS_MAX_PER_HOST)\n let authors: ContentAuthorRecord[] = []\n if (ids.length) {\n try {\n const authorsRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('authors')\n const snapshots = await firebaseAdmin\n .app()\n .firestore()\n .getAll(...ids.map((id) => authorsRef.doc(id)))\n authors = snapshots\n .map((snapshot) =>\n snapshot.exists\n ? normalizeContentAuthor(snapshot.data(), snapshot.id)\n : null,\n )\n .filter((author): author is ContentAuthorRecord => Boolean(author))\n } catch (error) {\n console.error(error)\n }\n }\n for (const entry of entries) {\n const author = resolveEntryAuthor(entry, authors)\n entry.author = author\n // The byline TEXT is denormalized onto the field everything downstream\n // already reads, so a record-backed author needs no change in the Entry\n // Meta block, the token map, the fallback nodes or the RSS feed. A record\n // WINS over the legacy string on the same entry: picking an author is the\n // more recent statement of who wrote it.\n if (author?.name) entry.authorName = author.name\n }\n}\n\n/**\n * Terminal refusal marker for an entry schedule, the flat-status twin of\n * `publishSchedule.status: 'skipped-unentitled'` on screens (AGL-1185).\n *\n * A field rather than a new `status` value on purpose. `status` is queried\n * (`where('status', 'in', [...])`), rendered by the console, and sorted on by\n * `bundle-timestamps.ts`; adding a member would have meant auditing every one\n * of those readers. A sibling field is invisible to all of them and is read\n * only here.\n */\nconst ENTRY_SCHEDULE_SKIPPED = 'skipped-unentitled'\n\n/** A schedule this entry already had declined, and will not have reconsidered. */\nfunction scheduleAlreadyRefused(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return value['scheduleStatus'] === ENTRY_SCHEDULE_SKIPPED\n}\n\n/** A scheduled entry whose time has come — before any plan question. */\nexport function isDueScheduled(value: FirebaseFirestore.DocumentData): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n (value['publishAt']?.seconds ?? Number.POSITIVE_INFINITY) * 1000 <=\n Date.now()\n )\n}\n\n/**\n * A scheduled entry still waiting on its time: not due yet, and not refused.\n * A render is the backstop that publishes a content entry the beat has not\n * reached, so a cache that stored a read holding one would withhold the render\n * that notices it come due — see {@link LiveEntriesRead.pendingSchedule}.\n */\nexport function isPendingScheduled(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n !isDueScheduled(value)\n )\n}\n\n/**\n * When this entry's schedule comes due, in epoch ms — or null when it holds\n * no schedule to act on: not `scheduled`, already refused, or carrying no\n * `publishAt` (AGL-3340).\n *\n * The beat orders its probe by this instant. A refused schedule keeps\n * `status: 'scheduled'` forever (see {@link ENTRY_SCHEDULE_SKIPPED}), so\n * reading one as due would make every beat re-probe for work that will never\n * be done. Seconds, like {@link isDueScheduled}, so the two agree about the\n * instant an entry comes due.\n */\nexport function entryScheduleDueAtMs(\n value: FirebaseFirestore.DocumentData,\n): number | null {\n if (value['status'] !== 'scheduled' || scheduleAlreadyRefused(value)) {\n return null\n }\n const seconds = value['publishAt']?.seconds\n return typeof seconds === 'number' ? seconds * 1000 : null\n}\n\n/**\n * Is this host's plan allowed to publish on a schedule? (AGL-471 shape.)\n *\n * `React.cache`-deduped per request via `getOrgForHost`, and — this is the\n * part that keeps it off the hot path — every caller below only asks once it\n * has already found a due scheduled entry. A collection with nothing due pays\n * nothing, which is almost every render.\n *\n * THREE answers, not two, and the third is the point. `refused` means we read\n * the plan and it does not carry the entitlement. `unresolved` means we could\n * not find out. Both withhold the entry, but only `refused` may write the\n * terminal marker — burning a schedule permanently on the strength of a\n * hostIndex miss or a transient rejection would destroy a customer's post for\n * a reason that may not be true a second later.\n *\n * Withholding on `unresolved` rather than publishing is what every other\n * entitlement caller on the tenant runtime already does: `apply-publish-schedule`\n * here, and the automation engine's two runners, all pass a possibly\n * undefined org straight into `checkEntitlement`, which resolves a missing\n * plan as free and denies (AGL-247). Opening here instead would make this the\n * one gate in the lib that admits when it cannot see — the exact shape of the\n * free-tier leak `no-plan-gated-entitlement` exists to forbid.\n *\n * The blast radius of withholding is deliberately small: `isLive` answers true\n * for `status: 'published'` before it ever consults this, so an unresolved\n * read hides only the due-scheduled entry, never the published ones, and the\n * next render retries.\n */\nexport type SchedulePermission = 'allowed' | 'refused' | 'unresolved'\n\nexport async function scheduledPublishingPermission(\n hostId: string,\n): Promise<SchedulePermission> {\n try {\n const org = (await getOrgForHost(hostId))?.org\n if (!org) return 'unresolved'\n return checkEntitlement(org, 'scheduledPublishing') ? 'allowed' : 'refused'\n } catch (error) {\n // Caught rather than thrown: the only caller sits inside\n // `getCollectionContent`'s try/catch, which returns an EMPTY collection —\n // so an unhandled rejection here would blank every published entry on the\n // page, not just the scheduled one.\n console.error(error)\n return 'unresolved'\n }\n}\n\n/**\n * Scheduled entries (AGL-123) go live lazily like AGL-61: a due\n * `publishAt` counts as published for this render, and the doc is flipped\n * to `published` fail-open so the state becomes durable. The tenant's\n * `apply-entry-schedules` beat makes the same flip at the entry's time and\n * drops the pages that list it (AGL-3340); this render-time half stays as the\n * backstop for a beat that is down or has not reached the entry yet.\n *\n * PLAN GATE (AGL-471). `scheduledPublishing` is a Business entitlement, and\n * until now nothing on the entry path checked it: the console let any plan\n * write `status: 'scheduled'`, and this render path published it. Scheduling\n * worked end to end on Free. The screens path has gated this since AGL-471\n * and records its refusal since AGL-1185 — entries were simply never wired\n * to either, which is why the leak was invisible from the screens side.\n *\n * The permission is threaded in rather than resolved here so the org read\n * happens once per call site instead of once per entry.\n *\n * Exported for the one other reader that decides whether an entry is on the\n * site — whether a LINK to it resolves (AGL-3118) — so a link and the page it\n * points at can never disagree about which entries exist.\n */\nexport function isLive(\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): boolean {\n if (value['status'] === 'published') return true\n return permission === 'allowed' && isDueScheduled(value)\n}\n\n/**\n * What {@link flipDueEntry} did to one entry.\n *\n * `published` is the only outcome that changes what a visitor sees, so it is\n * the only one a caller drops pages for. `refused` changes the stored state\n * and nothing on the site — a refused entry was never live.\n */\nexport type EntryScheduleOutcome = 'published' | 'refused' | 'unchanged' | 'failed'\n\n/**\n * Make the due state durable — or record that it was refused.\n *\n * The refusal is TERMINAL, for the AGL-1185 reason: left as a bare pending\n * `scheduled`, the entry stays permanently due, so the day the org upgrades\n * to Business the next render publishes it. Content scheduled on a plan that\n * could not honour it, and forgotten, surfacing during an upgrade — exactly\n * when nobody is looking for it. Recording the refusal is what makes it stop\n * being due, and it also stops this path re-reading the org on every\n * subsequent render.\n *\n * Both writes fail open: an error leaves today's state, and the next render\n * retries. A render does not wait for them (`void`); the beat does, because\n * it drops pages only for a flip that landed.\n *\n * `precondition` is the beat's: it read the entry some milliseconds earlier,\n * and an author rescheduling it in between must win. A render passes none —\n * it writes exactly what it just rendered.\n */\nasync function flipDueEntry(\n docRef: FirebaseFirestore.DocumentReference,\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n precondition?: FirebaseFirestore.Precondition,\n): Promise<EntryScheduleOutcome> {\n if (value['status'] !== 'scheduled') return 'unchanged'\n if (scheduleAlreadyRefused(value)) return 'unchanged'\n // `unresolved` writes NOTHING. It withholds this render and leaves the\n // schedule exactly as it found it, so a later render can still publish it.\n if (permission === 'unresolved') return 'unchanged'\n if (!isDueScheduled(value)) return 'unchanged'\n const update: FirebaseFirestore.UpdateData<FirebaseFirestore.DocumentData> =\n permission === 'refused'\n ? { scheduleStatus: ENTRY_SCHEDULE_SKIPPED }\n : // The console's sort key follows the flip (AGL-3323). It already held\n // `publishAt` while the entry waited, and `publishedAt` takes that\n // same instant, so the entry keeps its place in the console's\n // Published order.\n {\n status: 'published',\n publishedAt: value['publishAt'],\n [ENTRY_PUBLISH_SORT_FIELD]: value['publishAt'],\n }\n try {\n if (precondition) await docRef.update(update, precondition)\n else await docRef.update(update)\n return permission === 'refused' ? 'refused' : 'published'\n } catch (error) {\n console.error(error)\n return 'failed'\n }\n}\n\n/**\n * Apply one due entry schedule outside a render (AGL-3340) — the executor the\n * `apply-entry-schedules` beat runs, and the same one a render runs, so the\n * two cannot come to disagree about the plan gate or the fields a flip\n * writes.\n *\n * Asks the plan only for an entry that is actually due, as every render path\n * does. Guarded on the snapshot's own `updateTime`: a schedule edited after\n * the beat read it is left for the next beat, which reads it fresh.\n */\nexport async function applyDueEntrySchedule(options: {\n hostId: string\n entry: Pick<\n FirebaseFirestore.DocumentSnapshot,\n 'ref' | 'data' | 'updateTime'\n >\n}): Promise<EntryScheduleOutcome> {\n const value = options.entry.data()\n if (!value || !isDueScheduled(value)) return 'unchanged'\n const permission = await scheduledPublishingPermission(options.hostId)\n return flipDueEntry(\n options.entry.ref,\n value,\n permission,\n options.entry.updateTime\n ? { lastUpdateTime: options.entry.updateTime }\n : undefined,\n )\n}\n\nexport interface CollectionContent {\n /**\n * The zone this site's dates read in (AGL-3237), carried on the CONTENT so\n * it reaches the client.\n *\n * `collection-fallback.tsx` renders through `next/dynamic` from\n * `catch-all-client`, so it formats dates in the browser as well as on the\n * server. A zone it read from its own runtime would be the visitor's, which\n * is precisely the hydration mismatch AGL-1926 fixed — so the server\n * decides it once and it travels here, in the props both renders read.\n */\n timeZone?: string\n collection: {\n $id: string\n displayName: string\n slug: string\n /**\n * Legacy entry-template screen (AGL-105); superseded by\n * `entryScreenId` but still honored when only it is set.\n */\n templateScreenId?: string\n /** List-template screen (AGL-551); `/{collection}` renders through it. */\n listScreenId?: string\n /**\n * Entry-template screen (AGL-551); `/{collection}/{entry}` renders\n * through it with `{{entry.*}}` tokens.\n */\n entryScreenId?: string\n /**\n * What KIND of article this collection publishes (AGL-2536) — the\n * `schema.org` type its entries serialise as. Unset publishes `Article`,\n * which is what every collection published before the setting existed.\n */\n schemaType?: string\n /**\n * Whether this collection withholds its ENTRIES from search (AGL-3247).\n * The listing and its category listings stay indexable either way.\n */\n excludeEntriesFromSearch?: boolean\n /**\n * Category taxonomy (AGL-582): entries reference these by stable\n * `id`; `name` is the renameable display label.\n */\n categories?: CollectionCategory[]\n } | null\n entries: CollectionEntrySummary[]\n entry: CollectionEntrySummary | null\n /**\n * Whether the read that produced `entries` stopped at\n * {@link COLLECTION_SOURCE_MAX} (AGL-1516). Set on LIST routes only —\n * an entry route reads one document by slug and bounds nothing.\n */\n entriesReachedBound?: boolean\n /**\n * Present ONLY when a verified preview grant revealed an entry the public\n * site withholds (AGL-3205) — never on a public render, and never for an\n * entry that is already live. Its absence is what the preview chrome reads\n * to say \"this one is actually published\", so it must not be set\n * defensively.\n */\n entryPreview?: {\n /** The stored `status` — `scheduled` or `draft`. */\n status: string\n /** The instant it is scheduled for, or null when nothing is scheduled. */\n publishAtSeconds: number | null\n }\n /** List pagination (AGL-620); null for entry pages or unpaginated lists. */\n pagination?: CollectionPagination | null\n /**\n * The category this listing is filtered to (AGL-1321); null on the\n * canonical unfiltered list and on entry pages.\n */\n category?: CollectionRouteCategory | null\n error: unknown\n}\n\n/** The category a `/{collection}/category/{slug}` route addresses (AGL-1321). */\nexport interface CollectionRouteCategory {\n /** The URL segment, normalized — what the canonical link must say. */\n slug: string\n /** Taxonomy id; absent when the segment matched no known category. */\n id?: string\n /** Display label; falls back to the raw segment for an unknown category. */\n name: string\n /**\n * The taxonomy's {@link CollectionCategory.description}, carried onto the\n * route so the head can describe the FILTERED listing rather than inherit\n * the whole collection's description. Absent for an unknown segment, which\n * names no category and therefore has nothing to describe.\n */\n description?: string\n /**\n * Whether the segment resolved against the collection's taxonomy. An\n * unknown category still renders — an empty listing, not a crash — but the\n * page must not invite indexing of a URL that names nothing.\n */\n known: boolean\n}\n\nexport interface CollectionPagination {\n /**\n * 1-based counter for display only (AGL-3219).\n *\n * It is what `{{pagination.page}}` renders and nothing reads it back: a\n * cursor page is addressed by the document it starts after, so this number\n * describes how far a reader has walked rather than where the read began.\n * Hand-edit it in a URL and the label is wrong; the entries are not.\n */\n page: number\n perPage: number\n /**\n * The document id the NEXT (older) page starts after, or `''` when this is\n * the last page (AGL-3219).\n *\n * Set from a `limit(perPage + 1)` probe: the extra row is the only evidence\n * needed that an older page exists, and it costs one document rather than\n * the `count()` aggregation a total used to need. It is also the only\n * honest answer available — see {@link CollectionPagination.totalPages}.\n */\n nextCursor: string\n /** The document id the PREVIOUS (newer) page starts before, or `''`. */\n prevCursor: string\n /**\n * How many pages there are.\n *\n * @deprecated AGL-3219. Still resolved, so a template binding\n * `{{pagination.totalPages}}` keeps rendering, but no longer a promise: a\n * total can only be stated for a collection that fits inside one read, and\n * past that it is absent rather than wrong. It used to be derived from a\n * `count()` over a set the listing's two reads disagreed about, which is\n * how the page 10/11 seam came to repeat an entry. Bind\n * {@link CollectionPagination.nextCursor} instead — `''` means there is\n * nothing older, which is the question a pager is actually asking.\n */\n totalPages?: number\n /** @deprecated AGL-3219, with {@link CollectionPagination.totalPages}. */\n totalEntries?: number\n /**\n * Where `entries` begins in the collection's own order (AGL-3213): 0 for a\n * listing served from the cached read, and the page's own offset for one\n * served by a window read past that read's bound.\n *\n * Both windowing sites subtract it — `collectionEntriesPageWindow` on the\n * way into props, and the Collection entries block on the way into compose.\n * Without it a windowed listing renders empty, because every one of them\n * slices `[(page - 1) * perPage, …)` on the premise that `entries` starts at\n * the beginning of the collection.\n */\n windowStart?: number\n}\n\n/**\n * A bounded read of a collection's live entries (AGL-1516).\n *\n * `reachedBound` is a fact about the QUERY, not about `entries`, and the two\n * genuinely differ: the query asks for `status in ['published', 'scheduled']`\n * and the filter below then drops everything not live yet, so a read that came\n * back holding all {@link COLLECTION_SOURCE_MAX} docs can hand back fewer.\n * Counting the survivors — which is all a downstream consumer can do — reads\n * that as a complete collection, and the one thing a truncated read must never\n * be allowed to claim is completeness.\n */\ninterface LiveEntriesRead {\n entries: CollectionEntrySummary[]\n /** The query came back holding its own `.limit()`. */\n reachedBound: boolean\n /**\n * The read saw a `scheduled` entry whose `publishAt` has NOT arrived and\n * which has not been terminally refused — a schedule this collection is\n * still waiting on.\n *\n * The `apply-entry-schedules` beat publishes a due entry at its time and\n * drops the pages that list it (AGL-3340), but a beat can be down, and\n * `isLive`/`flipDueEntry` running during a render is what publishes the\n * entry then. A cached source would not merely serve stale entries, it\n * would withhold that render for as long as the entry stayed cached. This\n * is what lets the cache decline to store exactly those collections, so a\n * schedule the beat missed still lands on the render window rather than on\n * the TTL.\n */\n pendingSchedule: boolean\n}\n\n/**\n * The fields a LISTING read of an entry needs — the field mask on the query\n * below (AGL-3213).\n *\n * The point of the mask is the field that is NOT in it. `body` is the whole\n * post, and `mapEntryFields` has never mapped it on this path: a list card\n * binds a title, an excerpt, a cover and a byline, and the routed entry page\n * reads its one document separately. So the markdown of up to\n * {@link COLLECTION_SOURCE_MAX} posts crossed the wire, was parsed out of the\n * response, and was dropped one function later — on every fill of a cache\n * that every listing address, every \"Latest posts\" rail, the feed and the\n * author page share. A changelog is the worst case and also the common one.\n *\n * Firestore bills the document read either way, so this buys no reads; it\n * buys egress and the JSON parse, which is the part of a collection render\n * that grows with how much people have written.\n *\n * Site search is unaffected and must stay that way: it matches on `body`\n * through its OWN query in `apps/tenant/utils/search-content.ts`, which this\n * mask does not touch.\n *\n * ⛔ A reader added to `mapEntryFields` or to the liveness/schedule helpers\n * must be added HERE in the same edit. A field left out does not error — it\n * arrives `undefined`, which is exactly how `authorName` and `updatedAt` went\n * missing for months (AGL-2486, AGL-2534). The four schedule fields are\n * listed first for that reason: `status`, `publishAt` and `scheduleStatus`\n * decide whether an entry is live at all, and `flipDueEntry` WRITES\n * `publishAt` back as `publishedAt`, so a mask that dropped it would publish\n * a due entry with no date.\n */\nconst LIVE_ENTRY_FIELDS = [\n 'status',\n 'publishAt',\n 'publishedAt',\n 'scheduleStatus',\n 'title',\n 'slug',\n 'excerpt',\n 'authorName',\n 'authorId',\n 'coverImage',\n 'coverImageAlt',\n 'coverVideo',\n 'coverVideoDuration',\n 'seoTitle',\n 'seoDescription',\n 'categoryId',\n 'category',\n 'tags',\n 'updatedAt',\n] as const\n\n/**\n * Most SCHEDULED entries one live read considers (AGL-3213).\n *\n * Read by its own query rather than taken from the dated page below, because\n * a schedule is invisible to that page: scheduling writes `publishAt` and\n * never `publishedAt`, and when the beat has not reached one, `flipDueEntry`\n * during a render is the only thing that publishes it. A schedule the read\n * misses is then a post that does not go out. The set is small by nature — a hundred pending schedules on one\n * collection is already an unusual editorial calendar.\n */\nconst SCHEDULED_SOURCE_MAX = 100\n\n/** Everything a public listing may show, before any ordering. */\nfunction liveEntriesBase(\n entriesRef: FirebaseFirestore.CollectionReference,\n): FirebaseFirestore.Query {\n return (\n entriesRef\n .where('status', 'in', ['published', 'scheduled'])\n // Everything this path reads, and nothing else (AGL-3213) — see\n // {@link LIVE_ENTRY_FIELDS}.\n .select(...LIVE_ENTRY_FIELDS)\n )\n}\n\n/**\n * The documents a live read considers, in the order the site shows them\n * (AGL-3213).\n *\n * ## Why this is ordered now, and why ordering alone would have broken it\n *\n * It was `where(status).limit(100)` with NO `orderBy`, sorted in memory\n * afterwards. That is not the newest hundred — it is a hundred documents in\n * NAME order, then sorted. Under the bound the two agree, because a hundred\n * out of a hundred is everything; past it they diverge completely. This site's\n * own changelog reached 166 live entries and its listing showed an arbitrary\n * hundred of them, chosen by document id, with 66 releases reachable only at\n * their own URLs.\n *\n * The comment that used to sit here was right about `orderBy`, though:\n * Firestore returns only documents that HAVE the ordered field, so a dated\n * read does not mis-sort an entry without a date — it hides it. Two of those\n * exist and both matter:\n *\n * A SCHEDULE carries `publishAt` and no `publishedAt` until it goes out.\n * Ordering alone would have stopped scheduled posts publishing\n * at all, silently, because nothing else publishes them.\n * AN IMPORT restores whatever the bundle carried, and\n * `/api/hosts/resources` validates no field for presence\n * either — so a published entry with no `publishedAt` exists.\n *\n * So it is three queries, in the shape the console's sorted window uses\n * (AGL-2853): the DATED page, every SCHEDULE, and — only when the dated page\n * came back SHORT, which is the server's own proof that the collection fits\n * inside the bound — a scan for live entries carrying no date. Past the bound\n * an undated entry sorts after every dated one by definition, so it belongs to\n * the tail pages, which are served by their own window read.\n */\nasync function readLiveEntryDocs(\n entriesRef: FirebaseFirestore.CollectionReference,\n): Promise<{\n docs: FirebaseFirestore.QueryDocumentSnapshot[]\n reachedBound: boolean\n}> {\n try {\n const dated = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', 'desc')\n // The document name breaks ties, so two entries published in the same\n // second cannot swap places between two reads and move a page boundary\n // under a reader. Descending to match the date: a composite index ends\n // with `__name__` in the last field's direction, which makes this the\n // `(status, publishedAt DESC)` index the console's table already needs.\n .orderBy('__name__', 'desc')\n // Named rather than literal (AGL-1516): a search index has to be able to\n // say \"this read reached its bound\", and it can only do that against a\n // bound it shares with the query. `collectionSourceReachedBound` reads\n // the same constant.\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n\n const scheduled = await entriesRef\n .where('status', '==', 'scheduled')\n .select(...LIVE_ENTRY_FIELDS)\n .limit(SCHEDULED_SOURCE_MAX)\n .get()\n\n /*\n * EITHER read stopping at its own limit means entries went unseen.\n *\n * The dated page is the usual one. The schedule page is the case a dated\n * read alone cannot even detect: a collection holding nothing but pending\n * schedules returns ZERO dated documents, so a bound measured only there\n * would report a complete read of an empty collection — and \"nothing is\n * live here\" is the claim that takes a listing off the site (AGL-3101).\n */\n const reachedBound =\n dated.docs.length >= COLLECTION_SOURCE_MAX ||\n scheduled.docs.length >= SCHEDULED_SOURCE_MAX\n\n const undated = reachedBound\n ? []\n : (\n await liveEntriesBase(entriesRef)\n .orderBy('__name__')\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n ).docs.filter((entryDoc) => !entryDoc.get('publishedAt'))\n\n const seen = new Set<string>()\n const docs: FirebaseFirestore.QueryDocumentSnapshot[] = []\n for (const entryDoc of [...dated.docs, ...scheduled.docs, ...undated]) {\n if (seen.has(entryDoc.id)) continue\n seen.add(entryDoc.id)\n docs.push(entryDoc)\n }\n return { docs, reachedBound }\n } catch (error) {\n /*\n * FAIL SOFT TO THE UNORDERED READ.\n *\n * The ordered query needs the `(status, publishedAt DESC)` composite\n * index. Indexes do NOT ship with a promotion — RELEASING.md deploys them\n * by hand afterwards — so the window between the code landing and the\n * index existing has to degrade rather than break. An arbitrary hundred\n * is a bad listing; a 500 is a customer's blog down.\n */\n console.error(error)\n const unordered = await liveEntriesBase(entriesRef)\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n return {\n docs: unordered.docs,\n reachedBound: unordered.docs.length >= COLLECTION_SOURCE_MAX,\n }\n }\n}\n\n/** The live entries among `docs`, newest first, publishing any that came due. */\nfunction toLiveEntries(\n docs: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n permission: SchedulePermission,\n): CollectionEntrySummary[] {\n return (\n docs\n .filter((entryDoc) => isLive(entryDoc.data(), permission))\n .map((entryDoc) => {\n const value = entryDoc.data()\n void flipDueEntry(entryDoc.ref, value, permission)\n return {\n $id: entryDoc.id,\n title: value['title'] ?? entryDoc.id,\n slug: value['slug'] ?? entryDoc.id,\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n })\n // An entry carrying no date at all sorts last rather than to 1970 —\n // the same place the query's own order puts it.\n .sort(\n (a, b) => (b.publishedAt?.seconds ?? 0) - (a.publishedAt?.seconds ?? 0),\n )\n )\n}\n\n/**\n * Fetches a collection's live entries (newest first), shared by the route\n * loader and the compose-time Collection entries block (AGL-551).\n */\nasync function listLiveEntries(\n entriesRef: FirebaseFirestore.CollectionReference,\n hostId: string,\n): Promise<LiveEntriesRead> {\n const { docs, reachedBound } = await readLiveEntryDocs(entriesRef)\n\n // Ask the plan question ONLY if something is actually due (AGL-471). A\n // collection with no due schedule — almost every render — never reads the\n // org at all.\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n\n // Record the terminal refusal on its own pass, because a refused entry is\n // NOT live and so never reaches the `flipDueEntry` inside the map below.\n // Without this the entry stays due forever: excluded from every render, and\n // re-reading the org on each one.\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n void flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n\n // Measured on the RAW docs, before the liveness filter (AGL-1516): a\n // not-yet-due entry is filtered out one line down, so this is the last\n // place that can see one at all.\n const pendingSchedule = docs.some((entryDoc) =>\n isPendingScheduled(entryDoc.data()),\n )\n\n const entries = toLiveEntries(docs, permission)\n\n return {\n entries,\n reachedBound,\n pendingSchedule,\n }\n}\n\n/** One page of a listing, and whether anything older follows it. */\ninterface CollectionListingPage {\n entries: CollectionEntrySummary[]\n /** The `limit(perPage + 1)` probe found an extra row. */\n hasMore: boolean\n}\n\n/**\n * One page of a listing that starts PAST the cached read (AGL-3213),\n * addressed by the document it continues from rather than by a position\n * (AGL-3219).\n *\n * Uncached on purpose, and it is the only read on the collection path that is.\n * The cached source exists because `/blog`, every listing address, the feed\n * and every \"Latest posts\" rail want the same first hundred entries\n * (AGL-1302); a page past that bound wants ten entries nobody else is asking\n * for, and its own ISR entry is already the cache for them.\n *\n * ## Why a cursor, and not the offset this replaces\n *\n * `.offset(n)` asks for a POSITION, and a listing takes its inserts at the\n * head, so every publish moves every position by one. The head pages and this\n * read are cached under different policies and revalidated by different\n * triggers — the publish fan-out refreshes the head eagerly and deliberately\n * stops there — so the two sides were routinely describing the collection as\n * it stood at two different moments, and the seam between them repeated an\n * entry or hid one for as long as the slower side lagged. `v1.0.0-beta.147`\n * shipped and `/changelog` showed `v1-0-0-beta-36` as both the last entry of\n * page 10 and the first of page 11.\n *\n * `startAfter(doc)` asks a question whose answer does not move: what follows\n * THIS entry. Publish a hundred entries at the head and this page returns the\n * same ten. The seam cannot drift because there is no longer a number on\n * either side of it to disagree about.\n *\n * `offset` also billed every document it skipped; a cursor bills none of them.\n */\nasync function readCollectionListingPage(options: {\n hostId: string\n collectionSlug: string\n /** Start after this document id — the older direction. */\n after?: string\n /** Start before this document id — the newer direction. */\n before?: string\n limit: number\n}): Promise<CollectionListingPage | null> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return null\n const entriesRef = collectionDoc.ref.collection('entries')\n\n const cursorId = options.before || options.after\n if (!cursorId) return null\n // A direct get, not a `where('slug', ...)` query: the cursor IS the\n // document name, which is the second field the read orders on, so the\n // snapshot it needs is one document rather than an index lookup.\n const cursorDoc = await entriesRef.doc(cursorId).get()\n // A cursor naming a document that no longer exists — deleted, or a URL\n // someone kept — cannot be positioned against. Null sends the caller back\n // to the cached head, which is a page the reader can act on.\n if (!cursorDoc.exists) return null\n\n // Backwards is the same query read the other way up, so both directions\n // rest on an index the project already deploys: `(status, publishedAt)`\n // exists ascending and descending both.\n const backwards = Boolean(options.before)\n const snapshot = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', backwards ? 'asc' : 'desc')\n .orderBy('__name__', backwards ? 'asc' : 'desc')\n .startAfter(cursorDoc)\n // One more than the page: the extra row is the whole of \"is there\n // another page\", and it replaces a `count()` over the collection.\n .limit(options.limit + 1)\n .get()\n\n const hasMore = snapshot.docs.length > options.limit\n const pageDocs = snapshot.docs.slice(0, options.limit)\n // Read backwards, the newest of the page came back last.\n const docs = backwards ? [...pageDocs].reverse() : pageDocs\n\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(options.hostId)\n : 'allowed'\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n void flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n const entries = toLiveEntries(docs, permission)\n // The byline reads `authorName`, which a record-backed author only has\n // once resolved — the cached source does this for the entries it holds,\n // and a windowed page holds entries it never saw (AGL-2486).\n await attachEntryAuthors(options.hostId, entries)\n return { entries, hasMore }\n } catch (error) {\n // Fail open to the cached head rather than to a 500: the caller keeps\n // whatever it already had, which is a page the reader has seen before\n // rather than an error they cannot get past.\n console.error(error)\n return null\n }\n}\n\n/**\n * The cursor a retired `/{collection}/page/{n}` address redirects onto\n * (AGL-3219).\n *\n * This is the ONE place a position is still resolved, and it is deliberately\n * the only one: a 301 is served once, the reader lands on an address that\n * cannot drift afterwards, and whatever the position meant at that instant is\n * the page they would have got anyway. Everything downstream is cursors.\n *\n * Keys only — `select()` with no fields asks Firestore for document names and\n * nothing else — so the skipped documents are billed at the cheapest rate the\n * offset can be had for. Returns `''` when the position is past the end,\n * which is a 404 rather than a redirect to nowhere.\n */\nexport async function resolveCollectionPageCursor(options: {\n hostId: string\n collectionSlug: string\n /** 1-based page whose PREVIOUS entry is the cursor. */\n page: number\n perPage: number\n}): Promise<string> {\n const skip = (options.page - 1) * options.perPage - 1\n if (!Number.isFinite(skip) || skip < 0) return ''\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return ''\n const snapshot = await collectionDoc.ref\n .collection('entries')\n .where('status', 'in', ['published', 'scheduled'])\n .select()\n .orderBy('publishedAt', 'desc')\n .orderBy('__name__', 'desc')\n .offset(skip)\n .limit(1)\n .get()\n return snapshot.docs[0]?.id ?? ''\n } catch (error) {\n console.error(error)\n return ''\n }\n}\n\n/** Compose-time view of a collection: its live entries and its taxonomy. */\nexport interface PublishedCollectionSource {\n /**\n * The collection DOCUMENT this source was read from — its display name and\n * its template screen ids — or null when the slug names no content\n * collection.\n *\n * Carried so a routed listing can be served ENTIRELY from this cached\n * source. `getCollectionContent` used to resolve the same document itself\n * and then read the same entries again uncached, which meant `/blog`,\n * every `/blog/page/{n}`, every `/blog/category/{slug}` and the RSS feed\n * each paid a full collection read per regeneration while the identical\n * data already sat in this cache for every OTHER page on the site.\n */\n collection: CollectionContent['collection']\n entries: CollectionEntrySummary[]\n categories: CollectionCategory[]\n /**\n * Whether the read saw a schedule it is still waiting on — see\n * {@link LiveEntriesRead.pendingSchedule}. Never stored, only consulted by\n * the cache above, so no consumer has to know about it.\n */\n pendingSchedule?: boolean\n /**\n * Whether the entries read stopped at {@link COLLECTION_SOURCE_MAX}\n * (AGL-1516) — carried out of the loader because `entries.length` cannot\n * answer it once the liveness filter has run. Fail-open paths report\n * `false`: an empty result is not a bounded read, and describing it as one\n * would tell a reader their search covered less than it did.\n */\n reachedBound: boolean\n}\n\n/**\n * Published entries + category taxonomy for a collection resolved by slug —\n * the data source of the Collection entries block on arbitrary screens\n * (AGL-551/582). Fail-open: errors and unknown slugs resolve to an empty\n * list so a renamed collection never takes a published screen down.\n */\nexport async function getPublishedCollectionSource(options: {\n hostId: string\n collectionSlug: string\n}): Promise<PublishedCollectionSource> {\n try {\n return await withRenderCache({\n key: [\n 'tenant-collection-source',\n options.hostId,\n options.collectionSlug,\n ],\n revalidate: COLLECTION_SOURCE_TTL_SECONDS,\n tags: [tenantDataTag(options.hostId)],\n read: () => readPublishedCollectionSource(options),\n // A collection with a schedule still pending is SERVED but not STORED.\n //\n // The beat publishes a due entry and drops this tag (AGL-3340); when\n // the beat is down, `flipDueEntry` during a render is what publishes\n // it, so storing this source would suppress the very renders that would\n // have noticed the entry coming due, and the post would wait out the\n // TTL rather than land at its time. Declining to store leaves those\n // collections exactly as uncached as they were before this cache\n // existed, which is the only cost this cache is not allowed to reduce.\n //\n // Also refuses a collection that resolved to nothing, for the reason\n // `withRenderCache` states about negatives generally: a slug that\n // misses once must not miss for an hour.\n store: (value) => Boolean(value.collection) && !value.pendingSchedule,\n })\n } catch (error) {\n console.error(error)\n return readPublishedCollectionSource(options)\n }\n}\n\nasync function readPublishedCollectionSource(\n options: {\n hostId: string\n collectionSlug: string\n },\n): Promise<PublishedCollectionSource> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) {\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n const { entries, reachedBound, pendingSchedule } = await listLiveEntries(\n collectionDoc.ref.collection('entries'),\n options.hostId,\n )\n // The compose-time source feeds the Collection entries block, whose byline\n // reads `authorName` — so a record-backed author has to be resolved here\n // too, or the block prints nothing for the entries a list page shows\n // (AGL-2486). This result is the cached one, which is what keeps the extra\n // read amortized across every page of the site that carries the block.\n await attachEntryAuthors(options.hostId, entries)\n return {\n collection: mapCollectionDoc(collectionDoc, options.collectionSlug),\n entries,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n reachedBound,\n ...(pendingSchedule ? { pendingSchedule: true } : {}),\n }\n } catch (error) {\n console.error(error)\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n}\n\n/** Entries-only view of {@link getPublishedCollectionSource} (AGL-551). */\nexport async function getPublishedCollectionEntries(options: {\n hostId: string\n collectionSlug: string\n}): Promise<CollectionEntrySummary[]> {\n return (await getPublishedCollectionSource(options)).entries\n}\n\n/**\n * Narrows a listing to its routed category and stamps its pagination\n * (AGL-1321 / AGL-620).\n *\n * Category first, ALWAYS: the two have to describe the same set. Counting\n * pages over the whole collection and then filtering would advertise pages\n * that render empty and hide entries that exist.\n *\n * `entriesReachedBound` is read by the caller BEFORE this runs, because a\n * category route hands its already-narrowed entries to compose and the\n * entries block's \"measure the raw set, not the filtered one\" rule then has\n * nothing raw left to measure (AGL-1516).\n */\nfunction applyCategoryAndPagination(\n data: CollectionContent,\n options: {\n page?: number\n perPage?: number\n categorySlug?: string\n },\n listing?: {\n /** Where `data.entries` begins in that collection's order. */\n windowStart?: number\n /** The shared read came back holding its own limit. */\n reachedBound?: boolean\n /**\n * The `perPage + 1` probe of a CURSOR page found an extra row — set only\n * when this listing was served by one, because only that read can answer\n * it (AGL-3219).\n */\n cursorHasMore?: boolean\n },\n): void {\n const { page = 1, perPage } = options\n const routedCategory = (options.categorySlug ?? '').trim()\n if (routedCategory) {\n const match = resolveCollectionCategoryBySlug(\n data.collection?.categories,\n routedCategory,\n )\n data.category = {\n slug: collectionCategorySlug(routedCategory),\n ...(match ? { id: match.id } : {}),\n name: match?.name ?? routedCategory,\n ...(match?.description ? { description: match.description } : {}),\n known: Boolean(match),\n }\n data.entries = data.entries.filter((entry) =>\n entryMatchesCategoryRoute(\n entry,\n { slug: routedCategory, ...(match ? { category: match } : {}) },\n data.collection?.categories,\n ),\n )\n }\n\n if (perPage && perPage > 0) {\n /*\n * The total is the COLLECTION's, not the read's (AGL-3213).\n *\n * `entries.length` was the count, and on a collection inside the bound it\n * still is — the two are the same number there. Past the bound it is the\n * size of the window, which is how `/changelog` advertised \"Page 10 of\n * 10\" while holding 166 entries and linking to 100 of them.\n *\n * A ROUTED CATEGORY keeps counting its own entries, because that is the\n * only honest number available here: the narrowing happens in memory over\n * the cached head, so both the count and the listing describe the same\n * bounded set. Paging a category past the bound needs its own ordered\n * query and a `(categoryId, status, publishedAt DESC)` index; until then\n * a category of a very large collection is capped, and says so by\n * agreeing with what it shows.\n */\n const windowStart = Number(listing?.windowStart)\n const windowed = Number.isFinite(windowStart) && windowStart > 0\n\n /*\n * The cursors, which are the pager's real answer (AGL-3219).\n *\n * `data.entries` is either EXACTLY this page — a cursor read — or the\n * whole cached head, which every listing address shares and each slices\n * its own page out of. So the page's own last entry is at the end of the\n * array in the first case and at `page * perPage - 1` in the second, and\n * the cursor is that entry's document id.\n */\n const pageEnd = windowed ? data.entries.length : page * perPage\n const last = data.entries[pageEnd - 1]\n const first = data.entries[windowed ? 0 : (page - 1) * perPage]\n\n /*\n * Is there an older page?\n *\n * A cursor page KNOWS, because its read asked for one more entry than it\n * needed and the extra row came back. The head has to reason: either it\n * is holding more entries than this page shows, or it is holding all it\n * could read and the read stopped at its own bound, which is the one\n * thing `entries.length` can never tell you about the collection.\n */\n const hasMore =\n listing?.cursorHasMore ??\n (data.entries.length > pageEnd ||\n (Boolean(listing?.reachedBound) && !routedCategory))\n\n /*\n * The deprecated total, stated ONLY where it can be true.\n *\n * A collection that fits inside one read can be counted, and a template\n * binding `{{pagination.totalPages}}` keeps rendering the number it\n * always did. Past the bound there is no honest total — the count and\n * the listing were reading the collection at two different moments, which\n * is what made the seam repeat an entry — so it is left absent rather\n * than asserted. A routed category counts its own narrowed set, which is\n * bounded by the same head and therefore countable.\n */\n const countable = routedCategory || !listing?.reachedBound\n const totalEntries = countable ? data.entries.length : undefined\n\n data.pagination = {\n page,\n perPage,\n nextCursor: hasMore && last?.$id ? last.$id : '',\n prevCursor: page > 1 && first?.$id ? first.$id : '',\n ...(totalEntries === undefined\n ? {}\n : {\n totalEntries,\n totalPages: collectionTotalPages(totalEntries, perPage),\n }),\n ...(windowed ? { windowStart } : {}),\n }\n }\n}\n\n/**\n * Resolves a non-screen path against the host's content collections\n * (Content Collections & Blog): `/{collectionSlug}` returns the published\n * entry list, `/{collectionSlug}/{entrySlug}` one entry. Fail-open — errors\n * resolve to `collection: null` and the caller 404s.\n *\n * A listing resolves only for a collection with a live entry (AGL-3101); one\n * with nothing live answers `collection: null` as well, so its listing, feed\n * and markdown twin are not public until its first entry is.\n */\nexport async function getCollectionContent(options: {\n hostId: string\n collectionSlug: string\n entrySlug?: string\n /**\n * 1-based list page (AGL-620), now a DISPLAY counter (AGL-3219): it labels\n * the page the reader is on and no read is positioned from it. The entries\n * come from `after`/`before`, or from the head of the cached source when\n * neither is set.\n */\n page?: number\n /** Entries per page (AGL-620); when set the list is paginated. */\n perPage?: number\n /**\n * Continue AFTER this entry's document id — the older direction (AGL-3219).\n *\n * What `/{collection}?after={id}` carries. A page defined this way does not\n * move when something is published above it, which is the whole reason the\n * addresses stopped being positions.\n */\n after?: string\n /** Continue BEFORE this entry's document id — the newer direction. */\n before?: string\n /**\n * The site's zone (AGL-3237). Stamped onto the returned content so every\n * reader downstream — including the client fallback renderer — formats from\n * the same string rather than from its own runtime.\n */\n timeZone?: string\n /**\n * Category segment of `/{collection}/category/{slug}` (AGL-1321). Filters\n * the listing before pagination is computed, so page counts and the page\n * windows describe the FILTERED set rather than the whole collection.\n */\n categorySlug?: string\n /**\n * Reveal the named entry even though the public site withholds it — the\n * live-site preview of a scheduled post (AGL-3205).\n *\n * ⛔ A VERIFIED GRANT, NOT A REQUEST. The caller passes `true` only after a\n * signed preview token has been checked against the resolved hostId AND\n * this exact `collectionSlug`/`entrySlug` (`verifyCollectionPreviewToken`).\n * The token format stays in the app that receives the URL; what crosses into\n * this lib is the verdict, so nothing here can be tricked by a payload's own\n * spelling of which entry it names.\n *\n * ENTRY ROUTES ONLY, and one entry at a time. It is ignored on a list route\n * — a preview of one post must not add it to `/blog`, to the feed, or to a\n * Collection entries block on any other page, all of which read the SHARED\n * cached source. Nothing it touches is cached at all.\n *\n * The preview render also writes NOTHING: see the `flipDueEntry` guard\n * below. Publishing a schedule stays the sole business of a public render.\n */\n previewUnpublishedEntry?: boolean\n}): Promise<CollectionContent> {\n const { hostId, collectionSlug, entrySlug } = options\n // Never on a list route, whatever the caller passed: `entrySlug` is what\n // makes the grant addressable at all, and the list is the shared cached\n // read this must stay out of.\n const preview = Boolean(options.previewUnpublishedEntry) && Boolean(entrySlug)\n const data: CollectionContent = {\n // Stamped before any early return, so every shape this function can hand\n // back carries it — including the empty one a 404 renders from.\n ...(options.timeZone ? { timeZone: options.timeZone } : {}),\n collection: null,\n entries: [],\n entry: null,\n pagination: null,\n category: null,\n error: null,\n }\n try {\n // A LIST route is served entirely from the CACHED source, which every\n // other page on the site already shares. It used to resolve the\n // collection and re-read its entries here, uncached, on every\n // regeneration of every listing address — `/blog`, nine `/blog/page/{n}`,\n // one `/blog/category/{slug}` per category, and the RSS feed — so a\n // collection of N live entries cost `1 + N + authors` reads per address\n // per window, for data byte-identical to what the cache was already\n // holding for the home page's \"Latest posts\" rail.\n //\n // An ENTRY route stays where it was: it reads ONE document by slug and\n // has nothing to share.\n if (!entrySlug) {\n const source = await getPublishedCollectionSource({\n hostId,\n collectionSlug,\n })\n if (!source.collection) return data\n // A collection is not a PAGE until something in it is live (AGL-3101).\n // Without this, creating one publishes `/{slug}` at once — an empty\n // listing with a feed and a markdown twin, before a word of it is\n // written. Answering it as no collection makes every listing address\n // 404 the way an unknown slug does, until the first entry is published\n // or its schedule comes due.\n //\n // Read off the UNFILTERED live set, before the category narrows it, so\n // an empty category of a live collection still renders. A read that\n // stopped at its bound cannot prove the collection empty — the live\n // entries may be past it — so that one keeps its listing. The rule\n // lives here and not in the source above: the source also feeds the\n // Collection entries block and the author page, and to them an empty\n // collection is an empty list, not a missing one.\n if (!source.entries.length && !source.reachedBound) return data\n data.collection = source.collection\n data.entries = source.entries\n data.entriesReachedBound = source.reachedBound\n /*\n * A page that starts past the cached read is served by its own window\n * (AGL-3213). Everything before that point comes out of the shared\n * source, so the pages a reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a window read of the whole collection would hand\n * it ten entries of which any number may belong to another category.\n */\n const { page = 1, perPage } = options\n const cursor = (options.after ?? options.before ?? '').trim()\n let windowStart = 0\n let cursored: CollectionListingPage | null = null\n /*\n * A cursor address is served by its own read (AGL-3219). Everything\n * reachable without one comes out of the shared source, so the pages a\n * reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a cursor read of the whole collection would hand it\n * ten entries of which any number belong to another category.\n */\n if (perPage && perPage > 0 && cursor && !(options.categorySlug ?? '').trim()) {\n cursored = await readCollectionListingPage({\n hostId,\n collectionSlug,\n ...(options.before ? { before: options.before } : { after: cursor }),\n limit: perPage,\n })\n // Null means the cursor read failed, or named a document that is\n // gone. The cached head is the better answer than an empty page: the\n // reader sees the newest entries rather than nothing at all.\n if (cursored) {\n data.entries = cursored.entries\n /*\n * `entries` is now EXACTLY this page, and both windowing sites\n * slice `[(page - 1) * perPage, …)`. Declaring the window to start\n * at that same offset makes their subtraction come out at zero, so\n * they take the page whole.\n *\n * Both sides of the subtraction are built from the same `page`, so\n * a hand-edited counter in a URL cancels itself out: the label is\n * wrong and the entries are still this cursor's page.\n */\n windowStart = (page - 1) * perPage\n }\n }\n applyCategoryAndPagination(data, options, {\n windowStart,\n reachedBound: source.reachedBound,\n ...(cursored ? { cursorHasMore: cursored.hasMore } : {}),\n })\n return data\n }\n\n const collectionDoc = await findContentCollection(hostId, collectionSlug)\n if (!collectionDoc) return data\n data.collection = mapCollectionDoc(collectionDoc, collectionSlug)\n\n const entryQuery = await collectionDoc.ref\n .collection('entries')\n .where('slug', '==', entrySlug)\n .limit(5)\n .get()\n // Same two-step as `listLiveEntries`: only pay for the org read when\n // something is due, and record the refusal on its own pass because a\n // refused entry never becomes the `entryDoc` below (AGL-471).\n //\n // A PREVIEW RENDER SKIPS BOTH WRITES (AGL-3205). `flipDueEntry` is how a\n // content entry is published — by the beat, or by a render as its\n // backstop — and the render half belongs to the PUBLIC render: a preview\n // is one person looking at one post through a link, and it must not be\n // able to publish it, nor to burn its schedule with the terminal refusal\n // marker. Skipping the writes costs nothing — the beat or the next public\n // render asks the same questions and writes the same answers — and it is\n // what keeps a preview link from publishing anything.\n const dueHere = entryQuery.docs.filter((docSnapshot) =>\n isDueScheduled(docSnapshot.data()),\n )\n const permission: SchedulePermission = dueHere.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n if (permission !== 'allowed' && !preview) {\n for (const docSnapshot of dueHere) {\n void flipDueEntry(docSnapshot.ref, docSnapshot.data(), permission)\n }\n }\n /**\n * What a grant reveals: an entry this collection HOLDS and the site does\n * not serve.\n *\n * Deliberately not routed through `isLive`, which is the public answer and\n * has one other reader (`entry-link-routes`) whose whole job is to agree\n * with it. A second, wider answer inside it would make a LINK to a\n * previewed post resolve on the public site.\n *\n * Every status but `published` qualifies, which is `draft` as well as\n * `scheduled`: the ask is \"let me see it before it goes out\", and a post\n * is most worth looking at before its schedule is set. The blast radius is\n * the same either way — one entry, named in the signature, on one host.\n */\n const entryDoc =\n entryQuery.docs.find((docSnapshot) =>\n isLive(docSnapshot.data(), permission),\n ) ?? (preview ? entryQuery.docs[0] : undefined)\n if (entryDoc) {\n const value = entryDoc.data()\n if (!preview) void flipDueEntry(entryDoc.ref, value, permission)\n if (preview && !isLive(value, permission)) {\n // The facts the preview chrome states back to the reader, so the page\n // cannot be mistaken for the published post. Read from the stored\n // document rather than inferred from the render.\n data.entryPreview = {\n status: String(value['status'] ?? 'draft'),\n publishAtSeconds:\n typeof value['publishAt']?.seconds === 'number'\n ? value['publishAt'].seconds\n : null,\n }\n }\n data.entry = {\n $id: entryDoc.id,\n title: value['title'] ?? entrySlug,\n slug: entrySlug,\n body: value['body'] ?? '',\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n await attachEntryAuthors(hostId, [data.entry])\n }\n } catch (error) {\n console.error(error)\n data.error = error\n }\n return data\n}\n\nexport default getCollectionContent\n"],"names":["AUTHORS_MAX_PER_HOST","collectionCategorySlug","checkEntitlement","COLLECTION_SOURCE_MAX","collectionEntryVideoDurationSeconds","collectionTotalPages","entryMatchesCategoryRoute","hostCollectionKind","normalizeContentAuthor","normalizeContentSchemaType","resolveCollectionCategoryBySlug","resolveEntryAuthor","ENTRY_PUBLISH_SORT_FIELD","firebaseAdmin","getOrgForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","COLLECTION_SOURCE_TTL_SECONDS","findContentCollection","hostId","collectionSlug","matches","app","firestore","collection","doc","where","limit","get","docs","find","docSnapshot","data","mapEntryFields","value","coverVideoDuration","excerpt","authorName","authorId","coverImage","coverImageAlt","coverVideo","seoTitle","seoDescription","categoryId","category","tags","Array","isArray","filter","tag","updatedAt","seconds","mapCollectionCategories","item","id","trim","name","map","description","mapCollectionDoc","collectionDoc","$id","displayName","slug","templateScreenId","undefined","listScreenId","entryScreenId","schemaType","excludeEntriesFromSearch","categories","attachEntryAuthors","entries","ids","Set","entry","Boolean","slice","authors","length","authorsRef","snapshots","getAll","snapshot","exists","author","error","console","ENTRY_SCHEDULE_SKIPPED","scheduleAlreadyRefused","isDueScheduled","Number","POSITIVE_INFINITY","Date","now","isPendingScheduled","entryScheduleDueAtMs","scheduledPublishingPermission","org","isLive","permission","flipDueEntry","docRef","precondition","update","scheduleStatus","status","publishedAt","applyDueEntrySchedule","options","ref","updateTime","lastUpdateTime","LIVE_ENTRY_FIELDS","SCHEDULED_SOURCE_MAX","liveEntriesBase","entriesRef","select","readLiveEntryDocs","dated","orderBy","scheduled","reachedBound","undated","entryDoc","seen","has","add","push","unordered","toLiveEntries","title","sort","a","b","listLiveEntries","due","pendingSchedule","some","readCollectionListingPage","cursorId","before","after","cursorDoc","backwards","startAfter","hasMore","pageDocs","reverse","resolveCollectionPageCursor","skip","page","perPage","isFinite","offset","getPublishedCollectionSource","key","revalidate","read","readPublishedCollectionSource","store","getPublishedCollectionEntries","applyCategoryAndPagination","listing","routedCategory","categorySlug","match","known","windowStart","windowed","pageEnd","last","first","cursorHasMore","countable","totalEntries","pagination","nextCursor","prevCursor","totalPages","getCollectionContent","entrySlug","preview","previewUnpublishedEntry","timeZone","entryQuery","source","entriesReachedBound","cursor","cursored","dueHere","entryPreview","String","publishAtSeconds","body"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EAEpBC,sBAAsB,EACtBC,gBAAgB,EAChBC,qBAAqB,EACrBC,mCAAmC,EACnCC,oBAAoB,EA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