@aglyn/tenant-runtime 1.0.0-beta.146 → 1.0.0-beta.147
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 +3 -3
- package/src/lib/compose-collection-page.js +6 -2
- package/src/lib/compose-collection-page.js.map +1 -1
- package/src/lib/compose-screen-nodes.d.ts +9 -0
- package/src/lib/compose-screen-nodes.js +2 -0
- package/src/lib/compose-screen-nodes.js.map +1 -1
- package/src/lib/get-author-content.js +63 -2
- package/src/lib/get-author-content.js.map +1 -1
- package/src/lib/get-collection-content.d.ts +18 -0
- package/src/lib/get-collection-content.js +312 -43
- package/src/lib/get-collection-content.js.map +1 -1
|
@@ -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 { 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 nothing else publishes a content\n * entry, so a cache that stored a collection with a schedule still pending\n * would suppress the render that publishes it. `getPublishedCollectionSource`\n * therefore declines to STORE exactly those collections — see its `store`\n * predicate — which leaves scheduled publishing on the render window it has\n * always been on, 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 Wistia link\n * 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 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 * Nothing but a render publishes a content entry, so a cache that stored a\n * read holding one would withhold the render that notices it come due — see\n * {@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 * 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.\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 * 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.\n */\nfunction flipDueEntry(\n docRef: FirebaseFirestore.DocumentReference,\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): void {\n if (value['status'] !== 'scheduled') return\n if (scheduleAlreadyRefused(value)) return\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\n if (permission === 'refused') {\n if (!isDueScheduled(value)) return\n docRef\n .update({ scheduleStatus: ENTRY_SCHEDULE_SKIPPED })\n .catch((error) => console.error(error))\n return\n }\n docRef\n .update({ status: 'published', publishedAt: value['publishAt'] })\n .catch((error) => console.error(error))\n}\n\nexport interface CollectionContent {\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 * 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 /** 1-based current page. */\n page: number\n perPage: number\n totalPages: number\n totalEntries: 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 * Nothing promotes a content entry on a beat: `publish-schedule-job.ts` is\n * screens-only, so `isLive`/`flipDueEntry` running during a render is the\n * entire mechanism. A cached source therefore does not merely serve stale\n * entries, it withholds the render that would have published one, for as\n * long as the entry stays cached. This is what lets the cache decline to\n * store exactly those collections, so a schedule keeps landing on the\n * render window rather than on the TTL.\n */\n pendingSchedule: boolean\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 // No orderBy: entries missing publishedAt would be dropped by Firestore;\n // sort client-side like the version lists.\n const entriesQuery = await entriesRef\n .where('status', 'in', ['published', 'scheduled'])\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 // 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 = entriesQuery.docs.filter((entryDoc) =>\n isDueScheduled(entryDoc.data()),\n )\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 flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n\n // Measured on the RAW docs, before the liveness filter (AGL-1516). This is\n // the only place that can still see how many documents the query returned;\n // one line down that number is gone for good.\n const reachedBound = entriesQuery.docs.length >= COLLECTION_SOURCE_MAX\n\n // Also measured on the RAW docs, and for the same reason: a not-yet-due\n // entry is filtered out one line down, so this is the last place that can\n // see one at all.\n const pendingSchedule = entriesQuery.docs.some((entryDoc) =>\n isPendingScheduled(entryDoc.data()),\n )\n\n const entries = entriesQuery.docs\n .filter((entryDoc) => isLive(entryDoc.data(), permission))\n .map((entryDoc) => {\n const value = entryDoc.data()\n 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 .sort(\n (a, b) => (b.publishedAt?.seconds ?? 0) - (a.publishedAt?.seconds ?? 0),\n )\n\n return { entries, reachedBound, pendingSchedule }\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 // No beat publishes a content entry — `flipDueEntry` during a render is\n // the whole mechanism — so storing this source would suppress the very\n // renders that would have noticed the entry coming due, and the post\n // would wait out the TTL rather than land at its time. Declining to\n // store leaves those collections exactly as uncached as they were\n // before this cache existed, which is the only cost this cache is not\n // 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): 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 const totalEntries = data.entries.length\n data.pagination = {\n page,\n perPage,\n totalEntries,\n totalPages: collectionTotalPages(totalEntries, perPage),\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 /** 1-based list page (AGL-620); with `perPage`, drives pagination metadata. */\n page?: number\n /** Entries per page (AGL-620); when set the list is paginated. */\n perPage?: number\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 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 applyCategoryAndPagination(data, options)\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 the\n // entire publishing mechanism for a content entry, and it is a mechanism\n // that belongs to the PUBLIC render: a preview is one person looking at\n // one post through a link, and it must not be able to publish it, nor to\n // burn its schedule with the terminal refusal marker. Skipping the writes\n // costs nothing — the next public render asks the same questions and\n // writes the same answers — and it is what keeps \"nothing but a render\n // publishes a content entry\" true of renders anybody can reach.\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 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) 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","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","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","scheduledPublishingPermission","org","isLive","permission","flipDueEntry","docRef","update","scheduleStatus","catch","status","publishedAt","listLiveEntries","entriesRef","entriesQuery","due","entryDoc","ref","reachedBound","pendingSchedule","some","title","sort","a","b","getPublishedCollectionSource","options","key","revalidate","read","readPublishedCollectionSource","store","getPublishedCollectionEntries","applyCategoryAndPagination","page","perPage","routedCategory","categorySlug","match","known","totalEntries","pagination","totalPages","getCollectionContent","entrySlug","preview","previewUnpublishedEntry","entryQuery","source","entriesReachedBound","dueHere","entryPreview","String","publishAtSeconds","body"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EAEpBC,sBAAsB,EACtBC,gBAAgB,EAChBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,yBAAyB,EACzBC,kBAAkB,EAClBC,sBAAsB,EACtBC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,kBAAkB,QACb,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAE9C;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,MAAMC,gCAAgCH;AAEtC;;;;;;CAMC,GACD,eAAeI,sBACbC,MAAc,EACdC,cAAsB;IAEtB,MAAMC,UAAU,MAAMT,cACnBU,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,SACXC,GAAG,CAACN,QACJK,UAAU,CAAC,eACXE,KAAK,CAAC,QAAQ,MAAMN,gBACpBO,KAAK,CAAC,GACNC,GAAG;IACN,OAAOP,QAAQQ,IAAI,CAACC,IAAI,CACtB,CAACC,cAAgBxB,mBAAmBwB,YAAYC,IAAI,QAAQ;AAEhE;AAiEA,4EAA4E,GAC5E,SAASC,eACPC,KAAqC;QAiB1BA,gBASGA,mBACFA,iBACEA,mBACGA,sBAGHA,mBACFA,iBACMA,uBACJA,mBACFA;QAuBCA;IA3Cb,OAAO;QACLC,OAAO,GAAED,iBAAAA,KAAK,CAAC,UAAU,YAAhBA,iBAAoB;QAC7B,oEAAoE;QACpE,yEAAyE;QACzE,oEAAoE;QACpE,uEAAuE;QACvE,0EAA0E;QAC1E,uEAAuE;QACvE,iEAAiE;QACjE,yCAAyC;QACzCE,UAAU,GAAEF,oBAA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QACvC,IAAI6C,UAAU;gBAiBH5E,cAEDA,aAEQA,oBAEEA;YAtBlB,MAAMA,QAAQ4E,SAAS9E,IAAI;YAC3B,IAAI,CAAC2G,SAASxC,aAAaW,SAASC,GAAG,EAAE7E,OAAOgE;YAChD,IAAIyC,WAAW,CAAC1C,OAAO/D,OAAOgE,aAAa;oBAKxBhE;oBAENA;gBANX,sEAAsE;gBACtE,kEAAkE;gBAClE,iDAAiD;gBACjDF,KAAKiH,YAAY,GAAG;oBAClBzC,QAAQ0C,QAAOhH,gBAAAA,KAAK,CAAC,SAAS,YAAfA,gBAAmB;oBAClCiH,kBACE,SAAOjH,mBAAAA,KAAK,CAAC,YAAY,qBAAlBA,iBAAoBiB,OAAO,MAAK,WACnCjB,KAAK,CAAC,YAAY,CAACiB,OAAO,GAC1B;gBACR;YACF;YACAnB,KAAK0C,KAAK,GAAG;gBACXb,KAAKiD,SAASxD,EAAE;gBAChB6D,KAAK,GAAEjF,eAAAA,KAAK,CAAC,QAAQ,YAAdA,eAAkBwG;gBACzB3E,MAAM2E;gBACNU,IAAI,GAAElH,cAAAA,KAAK,CAAC,OAAO,YAAbA,cAAiB;eACpBD,eAAeC;gBAClBuE,aAAa,EAACvE,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,MAAMmB,mBAAmBnD,QAAQ;gBAACa,KAAK0C,KAAK;aAAC;QAC/C;IACF,EAAE,OAAOW,OAAO;QACdC,QAAQD,KAAK,CAACA;QACdrD,KAAKqD,KAAK,GAAGA;IACf;IACA,OAAOrD;AACT;AAEA,eAAeyG,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 collectionTotalPages,\n type ContentAuthorRecord,\n entryMatchesCategoryRoute,\n hostCollectionKind,\n normalizeContentAuthor,\n normalizeContentSchemaType,\n resolveCollectionCategoryBySlug,\n resolveEntryAuthor,\n} from '@aglyn/aglyn/server'\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 nothing else publishes a content\n * entry, so a cache that stored a collection with a schedule still pending\n * would suppress the render that publishes it. `getPublishedCollectionSource`\n * therefore declines to STORE exactly those collections — see its `store`\n * predicate — which leaves scheduled publishing on the render window it has\n * always been on, 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 Wistia link\n * 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 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 * Nothing but a render publishes a content entry, so a cache that stored a\n * read holding one would withhold the render that notices it come due — see\n * {@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 * 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.\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 * 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.\n */\nfunction flipDueEntry(\n docRef: FirebaseFirestore.DocumentReference,\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): void {\n if (value['status'] !== 'scheduled') return\n if (scheduleAlreadyRefused(value)) return\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\n if (permission === 'refused') {\n if (!isDueScheduled(value)) return\n docRef\n .update({ scheduleStatus: ENTRY_SCHEDULE_SKIPPED })\n .catch((error) => console.error(error))\n return\n }\n docRef\n .update({ status: 'published', publishedAt: value['publishAt'] })\n .catch((error) => console.error(error))\n}\n\nexport interface CollectionContent {\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 * 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 /** 1-based current page. */\n page: number\n perPage: number\n totalPages: number\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 * How many entries are live in the WHOLE collection (AGL-3213), which is\n * the number a pager has to state. `entries.length` is the size of the\n * READ, and on a collection past the bound the two stop being the same\n * number — which is how `/changelog` came to say \"Page 10 of 10\" while\n * holding 166 entries.\n *\n * Counted rather than listed: one `count()` aggregation over the published\n * entries, billed at a read per 1000 index entries, plus the live schedules\n * this read already holds. Only asked for when the read DID reach its\n * bound; under it the entries in hand ARE the collection.\n */\n totalLive: number\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 * Nothing promotes a content entry on a beat: `publish-schedule-job.ts` is\n * screens-only, so `isLive`/`flipDueEntry` running during a render is the\n * entire mechanism. A cached source therefore does not merely serve stale\n * entries, it withholds the render that would have published one, for as\n * long as the entry stays cached. This is what lets the cache decline to\n * store exactly those collections, so a schedule keeps landing on the\n * render window rather than on 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 `flipDueEntry` during a render is the only thing\n * that publishes one. A schedule the read misses is a post that never goes\n * 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 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 * How many entries are live in the whole collection (AGL-3213).\n *\n * The aggregation counts `published`, which `isLive` admits unconditionally,\n * and the live schedules are added from the docs already in hand — a due\n * schedule is still stored as `scheduled` while this runs, because\n * `flipDueEntry` writes behind the render, so neither half can count it twice.\n *\n * Falls back to the size of the read on failure. A pager that overstates by a\n * page is a page a reader can see is empty; a pager that throws is a listing\n * that does not render.\n */\nasync function countLiveEntries(\n entriesRef: FirebaseFirestore.CollectionReference,\n docs: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n permission: SchedulePermission,\n fallback: number,\n): Promise<number> {\n try {\n const published = await entriesRef\n .where('status', '==', 'published')\n .count()\n .get()\n const counted = Number(published.data()?.count ?? Number.NaN)\n if (!Number.isFinite(counted)) return fallback\n const liveSchedules = docs.filter((entryDoc) => {\n const value = entryDoc.data()\n return value['status'] === 'scheduled' && isLive(value, permission)\n }).length\n return counted + liveSchedules\n } catch (error) {\n console.error(error)\n return fallback\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 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 totalLive: reachedBound\n ? await countLiveEntries(entriesRef, docs, permission, entries.length)\n : entries.length,\n }\n}\n\n/**\n * One page of a listing that starts PAST the cached read (AGL-3213).\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 `/blog/page/{n}`, every\n * category listing, the feed and every \"Latest posts\" rail want the same first\n * hundred entries (AGL-1302); a page past that bound wants ten entries nobody\n * else is asking for, and its own ISR entry is already the cache for them.\n *\n * `offset` bills the documents it skips, so page 11 of a long collection costs\n * its 110 reads per regeneration. That is the price of a listing that can be\n * read to the end, it is paid only by collections past the bound, and it is\n * paid once per page per revalidate window.\n */\nasync function readCollectionListingWindow(options: {\n hostId: string\n collectionSlug: string\n offset: number\n limit: number\n}): Promise<CollectionEntrySummary[] | 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 const snapshot = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', 'desc')\n .orderBy('__name__', 'desc')\n .offset(options.offset)\n .limit(options.limit)\n .get()\n const due = snapshot.docs.filter((entryDoc) =>\n isDueScheduled(entryDoc.data()),\n )\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(options.hostId)\n : 'allowed'\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n const entries = toLiveEntries(snapshot.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\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/** 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 * How many entries are live in the whole collection (AGL-3213) — see\n * {@link LiveEntriesRead.totalLive}. Equal to `entries.length` for every\n * collection inside the bound, which is almost all of them.\n */\n totalLive: number\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 // No beat publishes a content entry — `flipDueEntry` during a render is\n // the whole mechanism — so storing this source would suppress the very\n // renders that would have noticed the entry coming due, and the post\n // would wait out the TTL rather than land at its time. Declining to\n // store leaves those collections exactly as uncached as they were\n // before this cache existed, which is the only cost this cache is not\n // 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 totalLive: 0,\n }\n }\n const { entries, reachedBound, pendingSchedule, totalLive } =\n 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 totalLive,\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 totalLive: 0,\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 /** Live entries in the whole collection — see `LiveEntriesRead.totalLive`. */\n totalLive?: number\n /** Where `data.entries` begins in that collection's order. */\n windowStart?: number\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 known = Number(listing?.totalLive)\n const totalEntries =\n !routedCategory && Number.isFinite(known) && known > data.entries.length\n ? known\n : data.entries.length\n const windowStart = Number(listing?.windowStart)\n data.pagination = {\n page,\n perPage,\n totalEntries,\n totalPages: collectionTotalPages(totalEntries, perPage),\n ...(Number.isFinite(windowStart) && windowStart > 0\n ? { windowStart }\n : {}),\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 /** 1-based list page (AGL-620); with `perPage`, drives pagination metadata. */\n page?: number\n /** Entries per page (AGL-620); when set the list is paginated. */\n perPage?: number\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 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 let windowStart = 0\n if (perPage && perPage > 0 && source.reachedBound) {\n const offset = (page - 1) * perPage\n if (!(options.categorySlug ?? '').trim() && offset >= source.entries.length) {\n const windowed = await readCollectionListingWindow({\n hostId,\n collectionSlug,\n offset,\n limit: perPage,\n })\n // Null means the window read failed, and the cached head is the\n // better answer than an empty page: the reader sees page 1's\n // entries under page N's URL rather than nothing at all.\n if (windowed) {\n data.entries = windowed\n windowStart = offset\n }\n }\n }\n applyCategoryAndPagination(data, options, {\n totalLive: source.totalLive,\n windowStart,\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 the\n // entire publishing mechanism for a content entry, and it is a mechanism\n // that belongs to the PUBLIC render: a preview is one person looking at\n // one post through a link, and it must not be able to publish it, nor to\n // burn its schedule with the terminal refusal marker. Skipping the writes\n // costs nothing — the next public render asks the same questions and\n // writes the same answers — and it is what keeps \"nothing but a render\n // publishes a content entry\" true of renders anybody can reach.\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 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) 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","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","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","scheduledPublishingPermission","org","isLive","permission","flipDueEntry","docRef","update","scheduleStatus","catch","status","publishedAt","LIVE_ENTRY_FIELDS","SCHEDULED_SOURCE_MAX","liveEntriesBase","entriesRef","select","readLiveEntryDocs","dated","orderBy","scheduled","reachedBound","undated","entryDoc","seen","has","add","push","unordered","toLiveEntries","ref","title","sort","a","b","countLiveEntries","fallback","published","count","counted","NaN","isFinite","liveSchedules","listLiveEntries","due","pendingSchedule","some","totalLive","readCollectionListingWindow","options","offset","getPublishedCollectionSource","key","revalidate","read","readPublishedCollectionSource","store","getPublishedCollectionEntries","applyCategoryAndPagination","listing","page","perPage","routedCategory","categorySlug","match","known","totalEntries","windowStart","pagination","totalPages","getCollectionContent","entrySlug","preview","previewUnpublishedEntry","entryQuery","source","entriesReachedBound","windowed","dueHere","entryPreview","String","publishAtSeconds","body"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EAEpBC,sBAAsB,EACtBC,gBAAgB,EAChBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,yBAAyB,EACzBC,kBAAkB,EAClBC,sBAAsB,EACtBC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,kBAAkB,QACb,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAE9C;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,MAAMC,gCAAgCH;AAEtC;;;;;;CAMC,GACD,eAAeI,sBACbC,MAAc,EACdC,cAAsB;IAEtB,MAAMC,UAAU,MAAMT,cACnBU,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,SACXC,GAAG,C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