@aglyn/tenant-runtime 1.0.0-beta.220 → 1.0.0-beta.222
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/README.md +6 -3
- package/package.json +5 -3
- package/src/index.d.ts +0 -3
- package/src/index.js +1 -4
- package/src/index.js.map +1 -1
- package/src/lib/apply-publish-schedule.js +41 -17
- package/src/lib/apply-publish-schedule.js.map +1 -1
- package/src/lib/compose-screen-nodes.d.ts +9 -0
- package/src/lib/compose-screen-nodes.js +13 -4
- package/src/lib/compose-screen-nodes.js.map +1 -1
- package/src/lib/enrich-gated-page.js +17 -2
- package/src/lib/enrich-gated-page.js.map +1 -1
- package/src/lib/get-site-icon-facts.d.ts +43 -0
- package/src/lib/get-site-icon-facts.js +105 -0
- package/src/lib/get-site-icon-facts.js.map +1 -0
- package/src/lib/self-hosted-fonts.d.ts +44 -0
- package/src/lib/self-hosted-fonts.js +149 -0
- package/src/lib/self-hosted-fonts.js.map +1 -0
- package/src/lib/assign-contact-owner.d.ts +0 -162
- package/src/lib/assign-contact-owner.js +0 -340
- package/src/lib/assign-contact-owner.js.map +0 -1
- package/src/lib/associate-company-by-domain.d.ts +0 -70
- package/src/lib/associate-company-by-domain.js +0 -153
- package/src/lib/associate-company-by-domain.js.map +0 -1
- package/src/lib/capture-host-contact.d.ts +0 -104
- package/src/lib/capture-host-contact.js +0 -151
- package/src/lib/capture-host-contact.js.map +0 -1
- package/src/lib/repeat-record-pages.d.ts +0 -48
- package/src/lib/repeat-record-pages.js +0 -64
- package/src/lib/repeat-record-pages.js.map +0 -1
- package/src/lib/resolve-dataset.d.ts +0 -40
- package/src/lib/resolve-dataset.js +0 -64
- package/src/lib/resolve-dataset.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/compose-screen-nodes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\n// By path: the overlay is server-only, and every `@aglyn/aglyn` barrel\n// re-exports `app-utils/server` into published pages.\nimport {\n applyMediaAssetFacts,\n mediaAssetRefs,\n} from '@aglyn/aglyn/app-utils/media-asset-facts'\nimport {\n recordServedPageVersion,\n reviewHostedPage,\n servedPageVersion,\n} from '@aglyn/tenant-data-admin/server/hosted-page-review'\nimport type { HostedPagePart } from '@aglyn/tenant-data-admin/server/held-page-subject'\n// By path: the contracts a repeat's rows and a form's record target are\n// asked through, both server-only.\nimport { stampFormRecordTargets } from '@aglyn/aglyn/plugin-manager/submission-record-target'\nimport { readRepeatRows } from '@aglyn/aglyn/plugin-manager/repeat-rows'\nimport { prepareComputedVariables } from '@aglyn/aglyn/plugin-manager/computed-variables'\nimport applyDuePublishSchedule from './apply-publish-schedule'\nimport getComponents from './get-components'\nimport getForms from './get-forms'\nimport getMediaAssetFacts from './get-media-asset-facts'\nimport {\n getPublishedCollectionSource,\n type PublishedCollectionSource,\n} from './get-collection-content'\nimport getPluginInstalls from './get-plugin-installs'\nimport getVariables, { getFunctions } from './get-variables'\nimport getPublishedLayoutVersion from './get-layout-version'\nimport getScreenVersion from './get-screen-version'\nimport {\n type ComposeSocialImages,\n socialImageAssetFacts,\n socialImageRefs,\n} from './social-image-facts'\n\n/**\n * Content-collection context for a compose (AGL-551): the collection the\n * route resolved (list/entry template screens). `entries` rides along when\n * the route already fetched them (list pages); blocks bound to other\n * collections — or to this one when `entries` is absent — fetch on demand.\n */\nexport interface ComposeCollectionContext {\n slug: string\n entries?: Aglyn.CollectionEntryRecord[]\n /**\n * The entry being rendered (AGL-582, entry-template screens / entry\n * fallback) — the Related posts block resolves against it.\n */\n entry?: Aglyn.CollectionEntryRecord | null\n /**\n * The routed collection's category taxonomy (AGL-582): entry\n * `categoryId`s resolve to display names against it during expansion.\n */\n categories?: Aglyn.CollectionCategory[]\n /**\n * The list page the URL asked for (AGL-1321). Fills in an entries block\n * that declares `perPage` but no `page` — design time cannot know which\n * page a visitor is on.\n */\n page?: number\n /**\n * The category segment the URL filtered on (AGL-1321); marks the current\n * pill in a Category Pills block. `entries` arrives already filtered.\n */\n categorySlug?: string\n /**\n * Whether the read behind `entries` stopped at its `.limit()` (AGL-1516).\n * Travels with the entries because the search boxes downstream have to say\n * what they actually searched, and — with the liveness gate and the route's\n * category filter both in between — `entries.length` no longer tells them.\n */\n entriesReachedBound?: boolean\n /**\n * Where `entries` begins in the collection's own order (AGL-3213).\n *\n * Zero for every listing served from the cached read. A page past that\n * read's bound carries only its own ten entries, and the block windows\n * `[(page - 1) * perPage, …)` — so without this it would slice from an\n * offset its own array never reaches and render an empty listing.\n */\n windowStart?: number\n /**\n * Whether {@link slug} is a cache KEY rather than an address (AGL-2524).\n *\n * The author page mixes collections, and the compose pipeline keys entry\n * sources by collection slug — so it hands over a synthetic one\n * (`AUTHOR_ENTRIES_SOURCE_SLUG`) with its entries already in hand. That is\n * harmless for the entries block, whose every row carries its OWN\n * `collectionSlug` and builds `entry.url` from it, and for the search box,\n * whose index is built the same way.\n *\n * It is NOT harmless for anything that builds a URL from the source's slug\n * itself. Set this and such a block resolves nothing rather than pointing\n * readers at `/{synthetic}/…`.\n */\n routeless?: boolean\n}\n\ninterface CollectionBlockScan {\n slugs: Set<string>\n hasRelated: boolean\n hasCategories: boolean\n hasSearch: boolean\n}\n\n/**\n * Which collections does this tree ask for (AGL-1152)?\n *\n * Extracted so the PREFETCH below and the expansion that consumes it read the\n * tree through one function rather than two copies of the same predicate. A\n * divergence between them is not a type error — it is a slug prefetched and\n * never awaited, or (worse) a slug the prefetch missed that then pays the full\n * serial read anyway — so there is deliberately no second implementation to\n * drift.\n */\nfunction scanCollectionBlocks(\n nodes: Record<string, any>,\n collection?: ComposeCollectionContext,\n): CollectionBlockScan {\n const slugs = new Set<string>()\n let hasRelated = false\n let hasCategories = false\n let hasSearch = false\n for (const node of Object.values(nodes)) {\n if (node?.componentId === Aglyn.COLLECTION_ENTRIES_COMPONENT_ID) {\n const slug =\n String(node?.props?.collectionSlug ?? '').trim() || collection?.slug\n if (slug) slugs.add(slug)\n }\n // Category pills (AGL-1321) need only the taxonomy, but it rides on the\n // same source, so they count as a reason to resolve one.\n if (node?.componentId === Aglyn.COLLECTION_CATEGORIES_COMPONENT_ID) {\n const slug =\n String(node?.props?.collectionSlug ?? '').trim() || collection?.slug\n if (slug) {\n hasCategories = true\n slugs.add(slug)\n }\n }\n // The standalone toolbar search box (AGL-1516, Figma 494:1220) needs the\n // collection's entries to index, and rides the same source the listing\n // beside it was built from — one read, one answer.\n if (node?.componentId === Aglyn.COLLECTION_SEARCH_COMPONENT_ID) {\n const slug =\n String(node?.props?.collectionSlug ?? '').trim() || collection?.slug\n if (slug) {\n hasSearch = true\n slugs.add(slug)\n }\n }\n // Related posts (AGL-582) always resolve against the ROUTED collection\n // — they only mean something with a current entry in context.\n if (\n node?.componentId === Aglyn.COLLECTION_RELATED_COMPONENT_ID &&\n collection?.slug &&\n collection.entry\n ) {\n hasRelated = true\n slugs.add(collection.slug)\n }\n }\n return { slugs, hasRelated, hasCategories, hasSearch }\n}\n\n/**\n * Issue the collection reads AS SOON AS THE SCREEN NODES EXIST (AGL-1152).\n *\n * `getPublishedCollectionSource` is three SEQUENTIAL round trips —\n * `findContentCollection`, then `listLiveEntries`, then `attachEntryAuthors`\n * — and until this existed it ran after the chrome bundle had already been\n * awaited, so a page carrying a Collection entries block paid the whole thing\n * as a serial tail on the compose phase. Measured on the tenant: a page with\n * no collection block composes in ~20 ms, one with a block in ~572 ms, and the\n * tree work itself accounts for under 2 ms of that at 50 entries. The gap is\n * this read, waiting for reads it shares nothing with.\n *\n * Same shape as `screenRepeatRowsPromise` directly below, and the same caveat\n * applies: the SCREEN's own nodes are a fast path, NOT the correctness gate. A\n * collection block can arrive from a layout or a grafted reusable component,\n * neither of which exists yet at this point, so the real scan still runs\n * against the composed tree and still fetches anything this missed.\n *\n * The ROUTED collection is deliberately excluded when its entries are already\n * in hand: the expansion below answers that slug from `collection.entries`\n * without reading at all, so prefetching it would buy a read nobody awaits.\n */\nfunction prefetchCollectionSources(\n hostId: string,\n screenNodes: Record<string, any>,\n collection?: ComposeCollectionContext,\n): Record<string, Promise<PublishedCollectionSource>> {\n const prefetched: Record<\n string,\n Promise<PublishedCollectionSource>\n > = {}\n for (const slug of scanCollectionBlocks(screenNodes, collection).slugs) {\n if (slug === collection?.slug && collection.entries) continue\n const pending = getPublishedCollectionSource({\n hostId,\n collectionSlug: slug,\n })\n // Marked handled the moment it exists, for the reason `composed` is in\n // `composeScreenNodes`: a tree that turns out not to need this slug never\n // awaits it, and an unawaited rejection takes the process down rather than\n // failing this one read. The real await below still sees the rejection.\n void pending.catch(() => undefined)\n prefetched[slug] = pending\n }\n return prefetched\n}\n\n/**\n * Expands Collection entries blocks (AGL-551) against their collections'\n * published entries, and Related posts blocks (AGL-582) against the routed\n * entry. Fetches lazily — screens without the blocks cost nothing — and\n * fails open on lookup errors like every other compose stage.\n */\nasync function expandCollectionEntryBlocks(\n hostId: string,\n nodes: Record<string, any>,\n collection?: ComposeCollectionContext,\n prefetched?: Record<string, Promise<PublishedCollectionSource>>,\n /** The site's zone (AGL-3237); UTC when a site has not named one. */\n timeZone?: string,\n): Promise<Record<string, any>> {\n const { slugs, hasRelated, hasCategories, hasSearch } = scanCollectionBlocks(\n nodes,\n collection,\n )\n if (!slugs.size) return nodes\n const sources: Record<string, Aglyn.CollectionEntriesSource> = {}\n await Promise.all(\n [...slugs].map(async (slug) => {\n // The routed collection rides its already-fetched entries +\n // categories (AGL-582); other collections fetch both on demand.\n if (slug === collection?.slug && collection.entries) {\n sources[slug] = {\n slug,\n entries: collection.entries,\n categories: collection.categories,\n // Only the ROUTED collection carries the URL's page (AGL-1321) — a\n // block bound to another collection must not inherit it.\n ...(collection.page ? { page: collection.page } : {}),\n // ...nor its bound (AGL-1516): this is a fact about the read the\n // route already performed, and it describes only that collection.\n ...(collection.entriesReachedBound ? { reachedBound: true } : {}),\n // ...nor where its window starts (AGL-3213), for the same reason:\n // it is a fact about the read this route performed.\n ...(collection.windowStart\n ? { windowStart: collection.windowStart }\n : {}),\n }\n return\n }\n // The prefetch when this slug was visible on the screen's own nodes;\n // a live read when it only appeared after layout/component grafting.\n const fetched = await (prefetched?.[slug] ??\n getPublishedCollectionSource({ hostId, collectionSlug: slug }))\n sources[slug] = {\n slug,\n entries: fetched.entries,\n categories:\n slug === collection?.slug && collection.categories\n ? collection.categories\n : fetched.categories,\n ...(fetched.reachedBound ? { reachedBound: true } : {}),\n }\n }),\n )\n const expanded = Aglyn.expandCollectionEntries(\n nodes,\n sources,\n collection?.slug,\n timeZone,\n )\n const withCategories = hasCategories\n ? Aglyn.expandCollectionCategories(\n expanded,\n sources,\n /*\n No DEFAULT collection for the pills on a routeless page (AGL-2524).\n\n Category pills are the one block that builds its links from the\n SOURCE's slug — `/{slug}/category/{x}` — because a category is a\n filter on one collection's own listing. On the author page that slug\n is synthetic, so an unbound pills block stamped links to a route that\n does not exist.\n\n Rendering nothing is the honest answer rather than a fallback. The\n page spans every collection, and there is no\n `/author/{slug}/category/{x}` for a pill to lead to; the only real\n destination would be some collection's listing, which drops the\n author the reader is looking at. A pills block that NAMES a\n collection is unaffected and still resolves that collection's own\n taxonomy — \"browse the blog by category\", which is a sensible thing\n to put beside an archive.\n */\n collection?.routeless ? undefined : collection?.slug,\n collection?.categorySlug,\n )\n : expanded\n const withSearch = hasSearch\n ? Aglyn.expandCollectionSearch(\n withCategories,\n sources,\n collection?.slug,\n timeZone,\n )\n : withCategories\n if (!hasRelated || !collection?.entry) return withSearch\n return Aglyn.expandCollectionRelated(\n withSearch,\n sources[collection.slug],\n collection.entry,\n timeZone,\n )\n}\n\n/**\n * Shared post-version composition (AGL-551, extracted from\n * `composeScreenNodes`): layout chrome, reusable components, repeatables,\n * collection entries, bindings, function definitions, plugin installs,\n * named tokens, denormalize, and last the current facts of each placed image\n * and film, and of the social card the page is shared as. The screen path and\n * the collection-fallback\n * path (which has no screen doc) build identical trees through this one\n * pipeline.\n */\n/**\n * The function bindings that apply to a composed tree (AGL-3393).\n *\n * First-party declarations are compiled in and cost nothing. A marketplace\n * plugin's live in its pinned version's manifest, which rides on the host's\n * realm installs — a read (render-cached, and the same one the page loader\n * issues for the bundles), so it is made only when it could change the\n * answer: the host has a function to hand out and the tree places an element\n * in a marketplace namespace. First-party declarations are listed first, so\n * no manifest can rebind a first-party element.\n *\n * A failed lookup binds first-party elements only. A marketplace element then\n * renders without its definition, which is its unconfigured placeholder —\n * the same fail-open the bundle lookup takes.\n */\nasync function functionBindingsFor(\n nodes: Record<string, { componentId?: unknown } | null | undefined>,\n hostId: string,\n functions: Record<string, unknown>,\n): Promise<Aglyn.FunctionBindings> {\n const firstParty = Aglyn.FIRST_PARTY_FUNCTION_BINDINGS\n if (!Object.keys(functions).length) return firstParty\n const placesMarketplaceElement = Object.values(nodes).some((node) =>\n Aglyn.isNamespacedComponentId(node?.componentId),\n )\n if (!placesMarketplaceElement) return firstParty\n // The dev loop's plugins have no install, so their manifests are read from\n // disk (AGL-3394). A production build never reaches the module.\n const dev =\n process.env.NODE_ENV === 'production'\n ? []\n : await (await import('./dev-plugin-manifests')).devPluginManifests()\n try {\n const { getRealmPluginInstalls } = await import('./realm-installs-seam')\n const installs = await getRealmPluginInstalls({ hostId })\n return Aglyn.mergeFunctionBindings(firstParty, ...installs, ...dev)\n } catch (error) {\n console.error('function bindings: realm install lookup failed:', error)\n return Aglyn.mergeFunctionBindings(firstParty, ...dev)\n }\n}\n\nexport async function composeNodesWithChrome(options: {\n hostId: string\n /**\n * The zone this site's dates read in (AGL-3237) — `resolveSiteTimeZone` of\n * the org and the host, resolved ONCE by the caller that holds both.\n *\n * A string rather than the two documents, because the value has to be\n * identical on the server render and the client re-render, and the surest\n * way to guarantee that is for only one place to decide it. Absent is UTC,\n * which is what every site rendered before this existed.\n */\n timeZone?: string\n /**\n * The layout binding, or a PROMISE of it.\n *\n * The unresolved form exists for the same reason `screenNodes` accepts one\n * (AGL-1428): the binding may live on the version document (key-present\n * wins over the screen's), and awaiting the version before this call would\n * put every host-scoped read back behind it. Only the layout-chain walk\n * consumes the binding, so it alone waits; the rest of the chrome bundle\n * still starts immediately.\n */\n layoutId?:\n | string\n | null\n | Promise<string | null | undefined>\n /**\n * The screen's values for the properties of the layouts it renders inside\n * (AGL-2893), keyed by layout id — or a PROMISE of them, for the reason\n * `layoutId` accepts one: they live on the version document beside the\n * binding. Absent, every layout renders its properties' defaults.\n */\n layoutPropValues?:\n | Aglyn.AglynScreenVersion['layoutPropValues']\n | null\n | Promise<Aglyn.AglynScreenVersion['layoutPropValues'] | null | undefined>\n /**\n * The screen's per-page restyling of its layouts' elements (AGL-3286),\n * keyed by layout id then layout node id — or a PROMISE of it, for the same\n * reason as `layoutPropValues`, beside which it is stored. Absent, every\n * layout renders with its own styling.\n */\n layoutStyleOverrides?:\n | Aglyn.AglynScreenVersion['layoutStyleOverrides']\n | null\n | Promise<\n Aglyn.AglynScreenVersion['layoutStyleOverrides'] | null | undefined\n >\n /**\n * The screen's own nodes, or a PROMISE of them (AGL-1428).\n *\n * Accepting the unresolved form is what lets `composeScreenNodes` hand the\n * version read over before it has finished, so the host-scoped reads below\n * — none of which look at these nodes — overlap it instead of queueing\n * behind it. Passing a resolved value behaves exactly as before, which is\n * what every other caller does.\n */\n screenNodes: Record<string, any> | Promise<Record<string, any>>\n /** Entry-template tokens (AGL-105) substituted before denormalize. */\n tokens?: Record<string, string>\n /** Routed content collection (AGL-551) for Collection entries blocks. */\n collection?: ComposeCollectionContext\n /**\n * The host document, for `host.*` tokens (AGL-1022).\n *\n * Passed in rather than read here: every caller already holds it, and\n * `composeScreenNodes` was the largest single render phase before AGL-1225\n * cut it to one round trip — adding a read back would spend that win on\n * data we already have in hand.\n */\n host?: Aglyn.HostTokenSource | null\n /**\n * The social card the head shares this page as (AGL-2850). The documents of\n * the assets it names are read in the same batch as the images and films\n * the tree places.\n */\n socialImages?: ComposeSocialImages\n}): Promise<Record<string, any>> {\n const { hostId, layoutId } = options\n\n /**\n * The layout chain, innermost first (AGL-703).\n *\n * A layout may itself render inside another layout, so this walks the\n * `layoutId` pointers rather than reading one. Fetching is sequential\n * because each step's parent is only known once the previous layout\n * document is in hand — but the walk is short by construction\n * (MAX_LAYOUT_CHAIN_DEPTH) and every layout is already a cached read.\n *\n * `seen` stops a cycle from looping forever. Stored data can hold one\n * even though both the console and `canNestLayout` refuse to create it:\n * the API, a script, or a restored backup can all write a layout\n * document directly, and a render must degrade rather than hang.\n */\n const walkLayoutChain = async () => {\n const chain: Aglyn.LayoutChainEntry[] = []\n const seen = new Set<string>()\n const boundLayoutId = await layoutId\n let currentLayoutId = boundLayoutId ? String(boundLayoutId) : undefined\n while (\n currentLayoutId &&\n !seen.has(currentLayoutId) &&\n chain.length < Aglyn.MAX_LAYOUT_CHAIN_DEPTH\n ) {\n seen.add(currentLayoutId)\n const layoutRes = await getPublishedLayoutVersion({\n hostId,\n layoutId: currentLayoutId,\n })\n // The version's declared properties travel with its nodes (AGL-2893):\n // they are applied to this layout alone, with the screen's values for\n // this layout, before the screen is grafted into its slot.\n chain.push({\n layoutId: currentLayoutId,\n nodes: layoutRes?.version?.nodes as any,\n props: (layoutRes?.version as Aglyn.AglynLayoutVersion | undefined)\n ?.props,\n })\n const parentId = (layoutRes?.layout as any)?.layoutId\n currentLayoutId = parentId ? String(parentId) : undefined\n }\n return chain\n }\n\n /**\n * ONE round-trip stage instead of three (AGL-1225).\n *\n * This used to be `await layout walk` → `await getComponents` → `await\n * Promise.all([five reads])`: three sequential waits, where only the first\n * has any reason to be sequential. Every one of the other six reads takes\n * `hostId` and nothing else — none of them consumes the layout chain — so\n * they were waiting on a walk whose result they never look at.\n *\n * The walk stays internally sequential because it genuinely is: each step's\n * parent id is only known once the previous layout document is in hand. It\n * just no longer gates anything else. The critical path becomes the walk\n * alone rather than walk + components + bulk.\n *\n * Measured budget that motivated this (production, `/product/besigner`):\n * `composeScreenNodes` was the largest single phase at 1577 ms cold and\n * consistently ~1.4-1.6 s warm too, so this is not cold-start cost. The\n * existing `AGL-1152:render` timing line reports `composeScreenNodes` as a\n * phase, so the effect of this shows up there directly — no new\n * instrumentation, and a regression would be visible in the same place.\n */\n /**\n * Does the SCREEN itself repeat (AGL-1440)?\n *\n * Asked as soon as the nodes are in hand — which since AGL-1428 is after\n * the fan-out has been ISSUED rather than before — so the overwhelmingly\n * common case still keeps the AGL-1225 shape: a page that repeats almost\n * always says so on its own document, and its rows read goes out\n * alongside the remaining chrome reads instead of after them.\n *\n * It is deliberately NOT the correctness gate — a repeatable can arrive from\n * a layout or a grafted reusable component, neither of which exists yet. The\n * gate is re-asked against the composed tree after grafting, which is the\n * exact input `expandRepeatables` reads.\n */\n /*\n * ISSUE THE HOST-SCOPED READS FIRST, THEN AWAIT THE NODES (AGL-1428).\n *\n * Every read in this bundle is keyed by `hostId` (and `layoutId`) alone —\n * none of them reads `screenNodes` — so starting them before the nodes are\n * in hand lets `composeScreenNodes`' version read overlap them rather than\n * run ahead of them. `Promise.all` is created BEFORE the `await` below on\n * purpose: that is the line that makes the two independent, and moving the\n * await above it silently gives the whole saving back.\n *\n * The repeat rows are the one read that genuinely depends on the nodes, so\n * they cannot join the bundle. It does not have to wait for the bundle either —\n * it is issued the moment the nodes resolve and awaited after, so it still\n * overlaps whatever is left of the chrome reads instead of costing the\n * extra serial round trip that dropping it from the batch would imply.\n */\n const chromeBundle = Promise.all([\n walkLayoutChain(),\n getComponents({ hostId }),\n // Host variable + function bindings (AGL-91/93): {{name}} and\n // {{fn:name(args)}} in string props resolve to values; unknown tokens\n // and failed runs stay literal. Whatever computes a variable's value\n // starts its reads here too.\n Promise.all([\n getVariables({ hostId }),\n getFunctions({ hostId }),\n prepareComputedVariables(hostId),\n getPluginInstalls({ hostId }),\n ]),\n ])\n const screenNodes = await options.screenNodes\n const screenRepeatKeys = Aglyn.repeatKeys(screenNodes)\n const screenRepeatRowsPromise = screenRepeatKeys.length\n ? readRepeatRows({ hostId, keys: screenRepeatKeys })\n : undefined\n // Does the SCREEN itself place a form entity? Gated and re-asked exactly\n // like the repeat rows read beside it (AGL-1440): most pages carry no form, and\n // the ones that do usually say so on their own document, so the read goes\n // out here alongside the chrome reads instead of as a serial tail. It is not\n // the correctness gate — a placed form can arrive from a layout or a grafted\n // component — so the composed tree is asked again below.\n const screenFormsPromise = Aglyn.placesFormEntity(screenNodes)\n ? getForms({ hostId })\n : undefined\n // Issued HERE, beside the repeat rows read and before the chrome bundle is\n // awaited, so the collection read overlaps it instead of trailing it.\n const prefetchedSources = prefetchCollectionSources(\n hostId,\n screenNodes,\n options.collection,\n )\n const [layoutChain, componentsRes, bulk] = await chromeBundle\n const [rawVariables, functions, computeVariables, pluginInstalls] = bulk\n const screenRepeatRows = await screenRepeatRowsPromise\n // Settled by now: it is read off the same version document the layout\n // binding the walk above waited on came from.\n const layoutPropValues = await options.layoutPropValues\n const layoutStyleOverrides = await options.layoutStyleOverrides\n\n const composedNodes = Aglyn.composeLayoutChainWithProps(\n layoutChain as any,\n screenNodes as any,\n layoutPropValues,\n layoutStyleOverrides,\n )\n const graftedComponents = Aglyn.composeReusableComponentNodes(\n composedNodes as any,\n componentsRes.definitions as any,\n )\n /*\n * PLACED FORMS RESOLVE AGAINST THEIR ENTITY (`docs/specs/reusable-forms.md`).\n *\n * A form node bound to `hosts/{hostId}/forms/{formId}` renders that entity's\n * published design, so a form is edited once and every page placing it\n * follows. Without this the entity's tree was written on every publish and\n * read by nothing: the fields had to be redrawn per page, and the two copies\n * diverged the moment either was touched.\n *\n * The gate is the COMPONENT-grafted tree, not the screen's own nodes, for\n * the reason the repeatables gate below states: a form placed inside a\n * layout or a shared component does not exist in `screenNodes`, and a page\n * that renders one would silently keep its stale inline copy.\n *\n * The second graft re-runs the component expansion deliberately. Instances\n * already expanded are skipped by their own prefix, so the repeat costs a\n * scan, and passing BOTH placement kinds is what expands a reusable\n * component nested inside a form's design — which the first pass could not\n * have seen, because that subtree was not in the tree yet.\n */\n const forms =\n (await screenFormsPromise)?.forms ??\n (Aglyn.placesFormEntity(graftedComponents as any)\n ? (await getForms({ hostId })).forms\n : undefined)\n const grafted = forms\n ? Aglyn.composeReusableComponentNodes(\n graftedComponents as any,\n componentsRes.definitions as any,\n [Aglyn.placedFormPlacement(forms as any)],\n )\n : graftedComponents\n // Computed variables (AGL-129): the plugin that computes a variable's\n // value fills it in once per compose; a failure keeps its stored fallback.\n const variables = computeVariables({ variables: rawVariables, functions })\n // Repeatables (AGL-103) expand after grafting (so they work inside\n // reusable components) and before bindings (so {{name}} tokens inside\n // cloned items still resolve).\n //\n // Only the rows this tree repeats over are read (AGL-1440), and the tree\n // asked is the composed one — after grafting — because that is the map the\n // expansion reads: a repeatable living in a layout or a reusable component\n // is invisible in `screenNodes`, and reading only the screen's keys would\n // silently render one template row where the author put a list. The\n // screen's own keys were issued beside the chrome reads above; a key only a\n // layout or a component adds is read here, for that key alone.\n //\n // The rows come from the plugin that keeps them, through the repeat-rows\n // contract; this composition names no collection. A declared source whose\n // reader is missing THROWS rather than answering \"no rows\", so a broken boot\n // keeps the last good render instead of replacing every list with one row.\n const composedRepeatKeys = Aglyn.repeatKeys(grafted as any)\n const unreadRepeatKeys = composedRepeatKeys.filter(\n (key) => !screenRepeatKeys.includes(key),\n )\n const repeatRows = unreadRepeatKeys.length\n ? {\n ...screenRepeatRows,\n ...(await readRepeatRows({ hostId, keys: unreadRepeatKeys })),\n }\n : screenRepeatRows\n const repeated = Aglyn.expandRepeatables(grafted as any, repeatRows)\n // Collection entries blocks (AGL-551) expand alongside repeatables:\n // per-entry {{entry.*}} tokens substitute inside the clones here, while\n // page-level tokens wait for resolveNamedTokens below.\n const withEntries = await expandCollectionEntryBlocks(\n hostId,\n repeated,\n options.collection,\n prefetchedSources,\n options.timeZone,\n )\n // Entry Meta blocks (AGL-1385): fill in the routed entry's date/category/\n // tags. Needs no source fetch — the routed entry and its taxonomy are\n // already in hand — so it sits outside `expandCollectionEntryBlocks`, which\n // returns early when no block asks for a collection read. AFTER it, so the\n // per-entry clones it just produced already carry their own resolved values\n // and are skipped.\n const withEntryMeta = Aglyn.expandCollectionEntryMeta(\n withEntries as any,\n options.collection?.entry,\n options.collection?.categories,\n options.timeZone,\n )\n // Entry Author cards (AGL-2486): the same fill, one block over. Its values\n // come off the author RECORD the routed entry resolved to, which the\n // collection read has already attached, so this costs nothing either.\n const withEntryAuthor = Aglyn.expandCollectionEntryAuthor(\n withEntryMeta as any,\n options.collection?.entry,\n )\n const bound = Aglyn.resolveNodesBindings(\n withEntryAuthor as any,\n variables,\n functions,\n )\n // Host variables (AGL-1022): `{{host.*}}` resolves from the INSTALLING\n // site, late — at render, never at install — so a rebrand propagates to\n // every artifact that names the host instead of hard-coding it. Same\n // registry the email path uses, so a token means one thing in both.\n const withHostTokens = Aglyn.resolveNodesHostTokens(\n bound as any,\n options.host,\n )\n // Function-running elements run client-side: embed their definitions\n // (AGL-93), and beside each the site variables that function reads and no\n // others (AGL-3202). Which elements those are is declared by their plugins\n // (AGL-3393), never named here.\n const withFunctions = Aglyn.attachFunctionDefinitions(\n withHostTokens,\n functions,\n variables,\n await functionBindingsFor(withHostTokens, hostId, functions),\n )\n // Marketplace plugins (AGL-45): stamp each marketplacePlugin node with its\n // pinned install (version/sha256/capabilities) + kill-switch state.\n const nodes = Aglyn.attachPluginInstalls(withFunctions, pluginInstalls)\n // Entry-template tokens (AGL-105): {{entry.*}} from the rendered entry.\n const finalNodes = Aglyn.resolveNamedTokens(nodes as any, options.tokens)\n // The document's one `main` landmark (AGL-2486). LAST, so it reads the tree\n // the page actually ships — a slot grafted from a layout chain, an element\n // an author chose — rather than the screen as stored.\n const withLandmark = Aglyn.stampDocumentLandmark(finalNodes as any)\n // Each form the record target writes for, stamped with what that target\n // trusts at submit time (AGL-2773) — a signed binding, today. Read off THIS\n // tree, the one the page ships, so a form grafted from a layout, a component\n // or a form entity is stamped as it renders; and after every stage that\n // rewrites props, so nothing changes what the stamp covers. A declared\n // target that is missing THROWS here rather than shipping forms that\n // silently write nowhere.\n const withFormBindings = await stampFormRecordTargets(\n withLandmark as Record<string, unknown>,\n hostId,\n )\n const denormalized = Aglyn.canvas.processNodesToDenormalized(\n withFormBindings as any,\n )\n /*\n * WHAT EACH PLACED IMAGE AND FILM IS NOW (AGL-2807, AGL-2833).\n *\n * An image's pixel pair and a film's length, shape and poster come from the\n * asset's DAM document as it is now, not as it was when it was picked. LAST,\n * on the tree the page ships, because an asset can arrive from any stage\n * above: a layout, a component, a form, a repeated row, a collection entry,\n * a binding.\n *\n * ONE read for all of them, issued once the tree is final rather than beside\n * the chrome reads. A read issued there could only cover the screen's own\n * placements, and nearly every layout places an image the screen does not\n * (a logo, a footer mark), so it would buy a second read on almost every\n * page. The late read costs its own round trip after the chrome reads, paid\n * each time a page is composed, which for a published page is its ISR\n * regeneration. A tree with no library asset, on a page whose social card\n * names none, issues none.\n *\n * THE SOCIAL CARD'S ASSETS JOIN THE SAME READ (AGL-2850), ahead of the\n * placements. A placement the cap leaves out keeps its pick-time pair, which\n * for an image is a reservation the decoded picture corrects. Nothing\n * corrects a card's pair, because a crawler lays the card out from it before\n * fetching the image, and a card names at most three documents.\n */\n const socialImages = options.socialImages\n const cardRefs = socialImages ? socialImageRefs(socialImages.images) : []\n const refs = mediaAssetRefs(denormalized)\n if (!refs.length && !cardRefs.length) return denormalized\n const facts = await getMediaAssetFacts({\n hostId,\n refs: [...cardRefs, ...refs],\n })\n if (socialImages) {\n const cardFacts = socialImageAssetFacts(socialImages.images, facts)\n if (cardFacts) socialImages.onFacts(cardFacts)\n }\n return applyMediaAssetFacts(denormalized, facts)\n}\n\n/**\n * What the caller knows about the page it is composing, for the page review\n * to NAME it when it holds or flags it (AGL-3374). Never read to decide\n * whether the page serves.\n */\nexport interface ComposePageContext {\n /**\n * A template composed against a routed listing or entry: the route pattern\n * it serves (`/videos`, `/videos/:slug`), the collection it renders, the\n * address being shown, and what a visitor gets when it has no clean\n * version (`built-in-design` for a content collection, whose routes fall\n * back to it; `not-found` for a store template, which has none).\n */\n template?: {\n role: 'list' | 'entry'\n route: string\n collectionName?: string | null\n entryPath?: string | null\n fallback?: 'built-in-design' | 'not-found'\n } | null\n /** An experiment variant's version of the page. */\n variant?: { experimentId: string; variantId: string; name?: string | null } | null\n}\n\n/**\n * The page's own nodes and those of every layout and reusable component\n * composed into it, for the page review to say WHICH one carries flagged\n * content (AGL-3374). Read only when a review row is filed: the layout\n * versions and the component definitions are the cached reads the compose\n * already made.\n */\nasync function composedPageParts(options: {\n hostId: string\n screenId: string\n screenNodes: Record<string, any>\n layoutId: string | null | undefined\n}): Promise<HostedPagePart[]> {\n const parts: HostedPagePart[] = [\n { type: 'screen', id: options.screenId, nodes: options.screenNodes },\n ]\n const seen = new Set<string>()\n let layoutId = options.layoutId ? String(options.layoutId) : undefined\n while (layoutId && !seen.has(layoutId) && seen.size < Aglyn.MAX_LAYOUT_CHAIN_DEPTH) {\n seen.add(layoutId)\n const layoutRes = await getPublishedLayoutVersion({ hostId: options.hostId, layoutId })\n const layout = layoutRes?.layout as { displayName?: unknown; layoutId?: unknown } | undefined\n parts.push({\n type: 'layout',\n id: layoutId,\n name: typeof layout?.displayName === 'string' ? layout.displayName : null,\n nodes: layoutRes?.version?.nodes ?? {},\n })\n layoutId = layout?.layoutId ? String(layout.layoutId) : undefined\n }\n // Only the components this page actually renders, followed through\n // components that nest others, so an unused one is never blamed.\n const { definitions } = await getComponents({ hostId: options.hostId })\n const used = new Set<string>()\n let frontier = parts.map((part) => part.nodes as Record<string, any>)\n while (frontier.length) {\n const next: Record<string, any>[] = []\n for (const [id, definition] of Object.entries(definitions)) {\n if (used.has(id)) continue\n if (frontier.some((nodes) => Aglyn.nodesReferenceComponent(nodes, id))) {\n used.add(id)\n next.push(definition.nodes as Record<string, any>)\n parts.push({ type: 'component', id, nodes: definition.nodes })\n }\n }\n frontier = next\n }\n return parts\n}\n\n/**\n * Full published-render composition for one screen (extracted for AGL-87 so\n * the SSG path and the password-unlock API build identical trees): applies\n * a due publish schedule, loads the version, composes the shared layout\n * chrome, grafts reusable components, and denormalizes.\n */\nexport async function composeScreenNodes(options: {\n hostId: string\n screenId: string\n screen: Aglyn.AglynScreen\n /** Entry-template tokens (AGL-105) substituted before denormalize. */\n tokens?: Record<string, string>\n /** Routed content collection (AGL-551) for Collection entries blocks. */\n collection?: ComposeCollectionContext\n /**\n * Compose a specific version instead of the published one (AGL-253):\n * experiment variants point at versions; schedules don't apply.\n */\n versionId?: string\n /** The host document, for `host.*` tokens (AGL-1022). */\n host?: Aglyn.HostTokenSource | null\n /**\n * The zone this site's dates read in (AGL-3237) — `resolveSiteTimeZone` of\n * the org and the host, resolved ONCE by the caller that holds both.\n *\n * A string rather than the two documents, because the value has to be\n * identical on the server render and the client re-render, and the surest\n * way to guarantee that is for only one place to decide it. Absent is UTC,\n * which is what every site rendered before this existed.\n */\n timeZone?: string\n /** The social card the head shares this page as (AGL-2850). */\n socialImages?: ComposeSocialImages\n /**\n * Internal: `false` when this compose IS the fallback to a held page's\n * last clean version, so a fallback that holds too serves nothing rather\n * than falling back again.\n */\n pageReviewFallback?: boolean\n /** What this page is, for naming it if the page review holds it (AGL-3374). */\n page?: ComposePageContext\n}): Promise<Record<string, any> | null> {\n const { hostId, screenId, screen } = options\n\n const effectiveVersionId = options.versionId\n ? null\n : await applyDuePublishSchedule({\n hostId,\n collectionName: 'screens',\n docId: screenId,\n parent: screen,\n })\n const versionId = (options.versionId ??\n effectiveVersionId ??\n screen.versionId) as string\n\n /*\n * OVERLAP THE VERSION READ WITH THE CHROME BUNDLE (AGL-1428).\n *\n * `composeNodesWithChrome`'s reads are keyed by `hostId`/`layoutId`, both\n * of which are in hand here, so the version read no longer has to finish\n * before they start. Handing the promise over instead of the resolved\n * value is the whole change: it is `composeNodesWithChrome` that decides\n * when it actually needs the nodes.\n *\n * The `versionId`-less screen still exits BEFORE anything is issued, so a\n * screen that has never been published costs no reads. What remains is the\n * narrow case of a `versionId` that points at a missing or unreadable\n * version document — a data-integrity fault rather than a routing outcome\n * — and that one now pays for a chrome bundle it discards. That is the\n * deliberate trade: one wasted bundle on a broken screen, against the\n * version read hiding under the chrome reads on every render that works.\n */\n if (!versionId) return null\n\n const versionPromise = getScreenVersion({ hostId, screenId, versionId })\n\n /*\n * NEITHER DERIVED PROMISE MAY REJECT ON ITS OWN.\n *\n * `composed` is discarded on every failure path below, and a rejected\n * promise nobody awaited is an unhandled rejection — which in Node takes\n * the whole render process down instead of letting this 404. So the nodes\n * handed to the compose absorb the failure (an empty tree it will never be\n * asked for), and `composed` gets a rejection handler attached the moment\n * it exists rather than at the point we decide to drop it. The real error\n * still propagates, from the `await versionPromise` below, exactly where it\n * did when this function awaited the version directly.\n */\n const composed = composeNodesWithChrome({\n ...(options.timeZone ? { timeZone: options.timeZone } : {}),\n hostId,\n // Version-first (key-present wins, null = explicitly no layout), screen\n // fallback — resolved as a promise so only the layout-chain walk waits on\n // the version read; the rest of the chrome bundle keeps the AGL-1428\n // overlap. A failed version read falls back to the screen binding; the\n // whole compose is discarded on that path anyway.\n layoutId: versionPromise.then(\n (res) =>\n res.version && 'layoutId' in res.version\n ? ((res.version as Aglyn.AglynScreenVersion).layoutId as\n | string\n | null)\n : (screen.layoutId as string | undefined),\n () => screen.layoutId as string | undefined,\n ),\n // The screen's values for its layouts' properties (AGL-2893), beside the\n // binding on the same document; a failed read renders the defaults.\n layoutPropValues: versionPromise.then(\n (res) =>\n (res.version as Aglyn.AglynScreenVersion | undefined)?.layoutPropValues,\n () => undefined,\n ),\n // …and its per-page restyling of their elements (AGL-3286), from the same\n // document; a failed read renders the layouts' own styling.\n layoutStyleOverrides: versionPromise.then(\n (res) =>\n (res.version as Aglyn.AglynScreenVersion | undefined)\n ?.layoutStyleOverrides,\n () => undefined,\n ),\n screenNodes: versionPromise.then(\n (res) => (res.version?.nodes ?? {}) as any,\n () => ({}) as any,\n ),\n tokens: options.tokens,\n collection: options.collection,\n host: options.host,\n socialImages: options.socialImages,\n })\n void composed.catch(() => undefined)\n\n const versionRes = await versionPromise\n if (versionRes.error || !versionRes.version) return null\n\n /*\n * THE PAGE PHISHING REVIEW (AGL-3356).\n *\n * Every way a page goes live — a toolbar publish, a versions-panel\n * publish, a scheduled publish, a component or form promoted under it, an\n * experiment variant, an edit to the live version in place — meets here,\n * with the page exactly as a visitor will receive it. So this is where a\n * page that links to a brand's lookalike, asks for a password or a card\n * in a field of its own, or (for a new workspace) dresses a brand's\n * sign-in or sends its call to action off the site beside a document or\n * account lure is held rather than served. See `hosted-page-review.ts`.\n *\n * A held version serves the last version this page served clean, screened\n * again, or nothing — and so does a flagged page whose review could not\n * finish, which is held rather than served.\n */\n const nodes = await composed\n const version = versionRes.version as Aglyn.AglynScreenVersion\n const review = await reviewHostedPage({\n hostId,\n screenId,\n versionId,\n nodes,\n // Named by what it is, not only its id (AGL-3374).\n page: {\n screen: {\n displayName: (screen as { displayName?: unknown }).displayName,\n name: (screen as { name?: unknown }).name,\n kind: (screen as { kind?: unknown }).kind,\n },\n template: options.page?.template ?? null,\n variant: options.page?.variant ?? null,\n parts: () =>\n composedPageParts({\n hostId,\n screenId,\n screenNodes: (version?.nodes ?? {}) as Record<string, any>,\n layoutId:\n version && 'layoutId' in version\n ? (version.layoutId as string | null)\n : (screen.layoutId as string | undefined),\n }),\n },\n })\n if (review.outcome === 'serve') {\n // Only the PUBLISHED version is the page's last clean one; a variant or\n // a pinned version is not what the page serves.\n if (nodes && !options.versionId) {\n await recordServedPageVersion(hostId, screenId, versionId)\n }\n return nodes\n }\n if (options.pageReviewFallback === false) return null\n const previous = await servedPageVersion(hostId, screenId)\n if (!previous || previous === versionId) return null\n return composeScreenNodes({\n ...options,\n versionId: previous,\n pageReviewFallback: false,\n })\n}\n\nexport default composeScreenNodes\n"],"names":["Aglyn","applyMediaAssetFacts","mediaAssetRefs","recordServedPageVersion","reviewHostedPage","servedPageVersion","stampFormRecordTargets","readRepeatRows","prepareComputedVariables","applyDuePublishSchedule","getComponents","getForms","getMediaAssetFacts","getPublishedCollectionSource","getPluginInstalls","getVariables","getFunctions","getPublishedLayoutVersion","getScreenVersion","socialImageAssetFacts","socialImageRefs","scanCollectionBlocks","nodes","collection","slugs","Set","hasRelated","hasCategories","hasSearch","node","Object","values","componentId","COLLECTION_ENTRIES_COMPONENT_ID","slug","String","props","collectionSlug","trim","add","COLLECTION_CATEGORIES_COMPONENT_ID","COLLECTION_SEARCH_COMPONENT_ID","COLLECTION_RELATED_COMPONENT_ID","entry","prefetchCollectionSources","hostId","screenNodes","prefetched","entries","pending","catch","undefined","expandCollectionEntryBlocks","timeZone","size","sources","Promise","all","map","categories","page","entriesReachedBound","reachedBound","windowStart","fetched","expanded","expandCollectionEntries","withCategories","expandCollectionCategories","routeless","categorySlug","withSearch","expandCollectionSearch","expandCollectionRelated","functionBindingsFor","functions","firstParty","FIRST_PARTY_FUNCTION_BINDINGS","keys","length","placesMarketplaceElement","some","isNamespacedComponentId","dev","process","env","NODE_ENV","devPluginManifests","getRealmPluginInstalls","installs","mergeFunctionBindings","error","console","composeNodesWithChrome","options","layoutId","walkLayoutChain","chain","seen","boundLayoutId","currentLayoutId","has","MAX_LAYOUT_CHAIN_DEPTH","layoutRes","push","version","parentId","layout","chromeBundle","screenRepeatKeys","repeatKeys","screenRepeatRowsPromise","screenFormsPromise","placesFormEntity","prefetchedSources","layoutChain","componentsRes","bulk","rawVariables","computeVariables","pluginInstalls","screenRepeatRows","layoutPropValues","layoutStyleOverrides","composedNodes","composeLayoutChainWithProps","graftedComponents","composeReusableComponentNodes","definitions","forms","grafted","placedFormPlacement","variables","composedRepeatKeys","unreadRepeatKeys","filter","key","includes","repeatRows","repeated","expandRepeatables","withEntries","withEntryMeta","expandCollectionEntryMeta","withEntryAuthor","expandCollectionEntryAuthor","bound","resolveNodesBindings","withHostTokens","resolveNodesHostTokens","host","withFunctions","attachFunctionDefinitions","attachPluginInstalls","finalNodes","resolveNamedTokens","tokens","withLandmark","stampDocumentLandmark","withFormBindings","denormalized","canvas","processNodesToDenormalized","socialImages","cardRefs","images","refs","facts","cardFacts","onFacts","composedPageParts","parts","type","id","screenId","name","displayName","used","frontier","part","next","definition","nodesReferenceComponent","composeScreenNodes","screen","effectiveVersionId","versionId","collectionName","docId","parent","versionPromise","composed","then","res","versionRes","review","kind","template","variant","outcome","pageReviewFallback","previous"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,uEAAuE;AACvE,sDAAsD;AACtD,SACEC,oBAAoB,EACpBC,cAAc,QACT,2CAA0C;AACjD,SACEC,uBAAuB,EACvBC,gBAAgB,EAChBC,iBAAiB,QACZ,qDAAoD;AAE3D,wEAAwE;AACxE,mCAAmC;AACnC,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,cAAc,QAAQ,0CAAyC;AACxE,SAASC,wBAAwB,QAAQ,iDAAgD;AACzF,OAAOC,6BAA6B,8BAA0B;AAC9D,OAAOC,mBAAmB,sBAAkB;AAC5C,OAAOC,cAAc,iBAAa;AAClC,OAAOC,wBAAwB,6BAAyB;AACxD,SACEC,4BAA4B,QAEvB,8BAA0B;AACjC,OAAOC,uBAAuB,2BAAuB;AACrD,OAAOC,gBAAgBC,YAAY,QAAQ,qBAAiB;AAC5D,OAAOC,+BAA+B,0BAAsB;AAC5D,OAAOC,sBAAsB,0BAAsB;AACnD,SAEEC,qBAAqB,EACrBC,eAAe,QACV,0BAAsB;AAwE7B;;;;;;;;;CASC,GACD,SAASC,qBACPC,KAA0B,EAC1BC,UAAqC;IAErC,MAAMC,QAAQ,IAAIC;IAClB,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A,aAAaf,WAAW,OAAO;IAChD,OAAOH,mBAAmB,aACrBzF;QACH4F,WAAWe;QACXD,oBAAoB;;AAExB;AAEA,eAAejB,mBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/compose-screen-nodes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\n// By path: the overlay is server-only, and every `@aglyn/aglyn` barrel\n// re-exports `app-utils/server` into published pages.\nimport {\n applyMediaAssetFacts,\n mediaAssetRefs,\n} from '@aglyn/aglyn/app-utils/media-asset-facts'\nimport {\n recordServedPageVersion,\n reviewHostedPage,\n servedPageVersion,\n} from '@aglyn/tenant-data-admin/server/hosted-page-review'\nimport type { HostedPagePart } from '@aglyn/tenant-data-admin/server/held-page-subject'\n// By path: the contracts a repeat's rows and a form's record target are\n// asked through, both server-only.\nimport { stampFormRecordTargets } from '@aglyn/aglyn/plugin-manager/submission-record-target'\nimport { readRepeatRows } from '@aglyn/aglyn/plugin-manager/repeat-rows'\nimport { prepareComputedVariables } from '@aglyn/aglyn/plugin-manager/computed-variables'\nimport applyDuePublishSchedule from './apply-publish-schedule'\nimport getComponents from './get-components'\nimport getForms from './get-forms'\nimport getMediaAssetFacts from './get-media-asset-facts'\nimport {\n getPublishedCollectionSource,\n type PublishedCollectionSource,\n} from './get-collection-content'\nimport getPluginInstalls from './get-plugin-installs'\nimport getVariables, { getFunctions } from './get-variables'\nimport getPublishedLayoutVersion from './get-layout-version'\nimport getScreenVersion from './get-screen-version'\nimport {\n type ComposeSocialImages,\n socialImageAssetFacts,\n socialImageRefs,\n} from './social-image-facts'\n\n/**\n * Content-collection context for a compose (AGL-551): the collection the\n * route resolved (list/entry template screens). `entries` rides along when\n * the route already fetched them (list pages); blocks bound to other\n * collections — or to this one when `entries` is absent — fetch on demand.\n */\nexport interface ComposeCollectionContext {\n slug: string\n entries?: Aglyn.CollectionEntryRecord[]\n /**\n * The entry being rendered (AGL-582, entry-template screens / entry\n * fallback) — the Related posts block resolves against it.\n */\n entry?: Aglyn.CollectionEntryRecord | null\n /**\n * The routed collection's category taxonomy (AGL-582): entry\n * `categoryId`s resolve to display names against it during expansion.\n */\n categories?: Aglyn.CollectionCategory[]\n /**\n * The list page the URL asked for (AGL-1321). Fills in an entries block\n * that declares `perPage` but no `page` — design time cannot know which\n * page a visitor is on.\n */\n page?: number\n /**\n * The category segment the URL filtered on (AGL-1321); marks the current\n * pill in a Category Pills block. `entries` arrives already filtered.\n */\n categorySlug?: string\n /**\n * Whether the read behind `entries` stopped at its `.limit()` (AGL-1516).\n * Travels with the entries because the search boxes downstream have to say\n * what they actually searched, and — with the liveness gate and the route's\n * category filter both in between — `entries.length` no longer tells them.\n */\n entriesReachedBound?: boolean\n /**\n * Where `entries` begins in the collection's own order (AGL-3213).\n *\n * Zero for every listing served from the cached read. A page past that\n * read's bound carries only its own ten entries, and the block windows\n * `[(page - 1) * perPage, …)` — so without this it would slice from an\n * offset its own array never reaches and render an empty listing.\n */\n windowStart?: number\n /**\n * Whether {@link slug} is a cache KEY rather than an address (AGL-2524).\n *\n * The author page mixes collections, and the compose pipeline keys entry\n * sources by collection slug — so it hands over a synthetic one\n * (`AUTHOR_ENTRIES_SOURCE_SLUG`) with its entries already in hand. That is\n * harmless for the entries block, whose every row carries its OWN\n * `collectionSlug` and builds `entry.url` from it, and for the search box,\n * whose index is built the same way.\n *\n * It is NOT harmless for anything that builds a URL from the source's slug\n * itself. Set this and such a block resolves nothing rather than pointing\n * readers at `/{synthetic}/…`.\n */\n routeless?: boolean\n}\n\ninterface CollectionBlockScan {\n slugs: Set<string>\n hasRelated: boolean\n hasCategories: boolean\n hasSearch: boolean\n}\n\n/**\n * Which collections does this tree ask for (AGL-1152)?\n *\n * Extracted so the PREFETCH below and the expansion that consumes it read the\n * tree through one function rather than two copies of the same predicate. A\n * divergence between them is not a type error — it is a slug prefetched and\n * never awaited, or (worse) a slug the prefetch missed that then pays the full\n * serial read anyway — so there is deliberately no second implementation to\n * drift.\n */\nfunction scanCollectionBlocks(\n nodes: Record<string, any>,\n collection?: ComposeCollectionContext,\n): CollectionBlockScan {\n const slugs = new Set<string>()\n let hasRelated = false\n let hasCategories = false\n let hasSearch = false\n for (const node of Object.values(nodes)) {\n if (node?.componentId === Aglyn.COLLECTION_ENTRIES_COMPONENT_ID) {\n const slug =\n String(node?.props?.collectionSlug ?? '').trim() || collection?.slug\n if (slug) slugs.add(slug)\n }\n // Category pills (AGL-1321) need only the taxonomy, but it rides on the\n // same source, so they count as a reason to resolve one.\n if (node?.componentId === Aglyn.COLLECTION_CATEGORIES_COMPONENT_ID) {\n const slug =\n String(node?.props?.collectionSlug ?? '').trim() || collection?.slug\n if (slug) {\n hasCategories = true\n slugs.add(slug)\n }\n }\n // The standalone toolbar search box (AGL-1516, Figma 494:1220) needs the\n // collection's entries to index, and rides the same source the listing\n // beside it was built from — one read, one answer.\n if (node?.componentId === Aglyn.COLLECTION_SEARCH_COMPONENT_ID) {\n const slug =\n String(node?.props?.collectionSlug ?? '').trim() || collection?.slug\n if (slug) {\n hasSearch = true\n slugs.add(slug)\n }\n }\n // Related posts (AGL-582) always resolve against the ROUTED collection\n // — they only mean something with a current entry in context.\n if (\n node?.componentId === Aglyn.COLLECTION_RELATED_COMPONENT_ID &&\n collection?.slug &&\n collection.entry\n ) {\n hasRelated = true\n slugs.add(collection.slug)\n }\n }\n return { slugs, hasRelated, hasCategories, hasSearch }\n}\n\n/**\n * Issue the collection reads AS SOON AS THE SCREEN NODES EXIST (AGL-1152).\n *\n * `getPublishedCollectionSource` is three SEQUENTIAL round trips —\n * `findContentCollection`, then `listLiveEntries`, then `attachEntryAuthors`\n * — and until this existed it ran after the chrome bundle had already been\n * awaited, so a page carrying a Collection entries block paid the whole thing\n * as a serial tail on the compose phase. Measured on the tenant: a page with\n * no collection block composes in ~20 ms, one with a block in ~572 ms, and the\n * tree work itself accounts for under 2 ms of that at 50 entries. The gap is\n * this read, waiting for reads it shares nothing with.\n *\n * Same shape as `screenRepeatRowsPromise` directly below, and the same caveat\n * applies: the SCREEN's own nodes are a fast path, NOT the correctness gate. A\n * collection block can arrive from a layout or a grafted reusable component,\n * neither of which exists yet at this point, so the real scan still runs\n * against the composed tree and still fetches anything this missed.\n *\n * The ROUTED collection is deliberately excluded when its entries are already\n * in hand: the expansion below answers that slug from `collection.entries`\n * without reading at all, so prefetching it would buy a read nobody awaits.\n */\nfunction prefetchCollectionSources(\n hostId: string,\n screenNodes: Record<string, any>,\n collection?: ComposeCollectionContext,\n): Record<string, Promise<PublishedCollectionSource>> {\n const prefetched: Record<\n string,\n Promise<PublishedCollectionSource>\n > = {}\n for (const slug of scanCollectionBlocks(screenNodes, collection).slugs) {\n if (slug === collection?.slug && collection.entries) continue\n const pending = getPublishedCollectionSource({\n hostId,\n collectionSlug: slug,\n })\n // Marked handled the moment it exists, for the reason `composed` is in\n // `composeScreenNodes`: a tree that turns out not to need this slug never\n // awaits it, and an unawaited rejection takes the process down rather than\n // failing this one read. The real await below still sees the rejection.\n void pending.catch(() => undefined)\n prefetched[slug] = pending\n }\n return prefetched\n}\n\n/**\n * Expands Collection entries blocks (AGL-551) against their collections'\n * published entries, and Related posts blocks (AGL-582) against the routed\n * entry. Fetches lazily — screens without the blocks cost nothing — and\n * fails open on lookup errors like every other compose stage.\n */\nasync function expandCollectionEntryBlocks(\n hostId: string,\n nodes: Record<string, any>,\n collection?: ComposeCollectionContext,\n prefetched?: Record<string, Promise<PublishedCollectionSource>>,\n /** The site's zone (AGL-3237); UTC when a site has not named one. */\n timeZone?: string,\n): Promise<Record<string, any>> {\n const { slugs, hasRelated, hasCategories, hasSearch } = scanCollectionBlocks(\n nodes,\n collection,\n )\n if (!slugs.size) return nodes\n const sources: Record<string, Aglyn.CollectionEntriesSource> = {}\n await Promise.all(\n [...slugs].map(async (slug) => {\n // The routed collection rides its already-fetched entries +\n // categories (AGL-582); other collections fetch both on demand.\n if (slug === collection?.slug && collection.entries) {\n sources[slug] = {\n slug,\n entries: collection.entries,\n categories: collection.categories,\n // Only the ROUTED collection carries the URL's page (AGL-1321) — a\n // block bound to another collection must not inherit it.\n ...(collection.page ? { page: collection.page } : {}),\n // ...nor its bound (AGL-1516): this is a fact about the read the\n // route already performed, and it describes only that collection.\n ...(collection.entriesReachedBound ? { reachedBound: true } : {}),\n // ...nor where its window starts (AGL-3213), for the same reason:\n // it is a fact about the read this route performed.\n ...(collection.windowStart\n ? { windowStart: collection.windowStart }\n : {}),\n }\n return\n }\n // The prefetch when this slug was visible on the screen's own nodes;\n // a live read when it only appeared after layout/component grafting.\n const fetched = await (prefetched?.[slug] ??\n getPublishedCollectionSource({ hostId, collectionSlug: slug }))\n sources[slug] = {\n slug,\n entries: fetched.entries,\n categories:\n slug === collection?.slug && collection.categories\n ? collection.categories\n : fetched.categories,\n ...(fetched.reachedBound ? { reachedBound: true } : {}),\n }\n }),\n )\n const expanded = Aglyn.expandCollectionEntries(\n nodes,\n sources,\n collection?.slug,\n timeZone,\n )\n const withCategories = hasCategories\n ? Aglyn.expandCollectionCategories(\n expanded,\n sources,\n /*\n No DEFAULT collection for the pills on a routeless page (AGL-2524).\n\n Category pills are the one block that builds its links from the\n SOURCE's slug — `/{slug}/category/{x}` — because a category is a\n filter on one collection's own listing. On the author page that slug\n is synthetic, so an unbound pills block stamped links to a route that\n does not exist.\n\n Rendering nothing is the honest answer rather than a fallback. The\n page spans every collection, and there is no\n `/author/{slug}/category/{x}` for a pill to lead to; the only real\n destination would be some collection's listing, which drops the\n author the reader is looking at. A pills block that NAMES a\n collection is unaffected and still resolves that collection's own\n taxonomy — \"browse the blog by category\", which is a sensible thing\n to put beside an archive.\n */\n collection?.routeless ? undefined : collection?.slug,\n collection?.categorySlug,\n )\n : expanded\n const withSearch = hasSearch\n ? Aglyn.expandCollectionSearch(\n withCategories,\n sources,\n collection?.slug,\n timeZone,\n )\n : withCategories\n if (!hasRelated || !collection?.entry) return withSearch\n return Aglyn.expandCollectionRelated(\n withSearch,\n sources[collection.slug],\n collection.entry,\n timeZone,\n )\n}\n\n/**\n * Shared post-version composition (AGL-551, extracted from\n * `composeScreenNodes`): layout chrome, reusable components, repeatables,\n * collection entries, bindings, function definitions, plugin installs,\n * named tokens, denormalize, and last the current facts of each placed image\n * and film, and of the social card the page is shared as. The screen path and\n * the collection-fallback\n * path (which has no screen doc) build identical trees through this one\n * pipeline.\n */\n/**\n * The function bindings that apply to a composed tree (AGL-3393).\n *\n * First-party declarations are compiled in and cost nothing. A marketplace\n * plugin's live in its pinned version's manifest, which rides on the host's\n * realm installs — a read (render-cached, and the same one the page loader\n * issues for the bundles), so it is made only when it could change the\n * answer: the host has a function to hand out and the tree places an element\n * in a marketplace namespace. First-party declarations are listed first, so\n * no manifest can rebind a first-party element.\n *\n * A failed lookup binds first-party elements only. A marketplace element then\n * renders without its definition, which is its unconfigured placeholder —\n * the same fail-open the bundle lookup takes.\n */\nasync function functionBindingsFor(\n nodes: Record<string, { componentId?: unknown } | null | undefined>,\n hostId: string,\n functions: Record<string, unknown>,\n): Promise<Aglyn.FunctionBindings> {\n const firstParty = Aglyn.FIRST_PARTY_FUNCTION_BINDINGS\n if (!Object.keys(functions).length) return firstParty\n const placesMarketplaceElement = Object.values(nodes).some((node) =>\n Aglyn.isNamespacedComponentId(node?.componentId),\n )\n if (!placesMarketplaceElement) return firstParty\n // The dev loop's plugins have no install, so their manifests are read from\n // disk (AGL-3394). A production build never reaches the module.\n const dev =\n process.env.NODE_ENV === 'production'\n ? []\n : await (await import('./dev-plugin-manifests')).devPluginManifests()\n try {\n const { getRealmPluginInstalls } = await import('./realm-installs-seam')\n const installs = await getRealmPluginInstalls({ hostId })\n return Aglyn.mergeFunctionBindings(firstParty, ...installs, ...dev)\n } catch (error) {\n console.error('function bindings: realm install lookup failed:', error)\n return Aglyn.mergeFunctionBindings(firstParty, ...dev)\n }\n}\n\nexport async function composeNodesWithChrome(options: {\n hostId: string\n /**\n * The zone this site's dates read in (AGL-3237) — `resolveSiteTimeZone` of\n * the org and the host, resolved ONCE by the caller that holds both.\n *\n * A string rather than the two documents, because the value has to be\n * identical on the server render and the client re-render, and the surest\n * way to guarantee that is for only one place to decide it. Absent is UTC,\n * which is what every site rendered before this existed.\n */\n timeZone?: string\n /**\n * The layout binding, or a PROMISE of it.\n *\n * The unresolved form exists for the same reason `screenNodes` accepts one\n * (AGL-1428): the binding may live on the version document (key-present\n * wins over the screen's), and awaiting the version before this call would\n * put every host-scoped read back behind it. Only the layout-chain walk\n * consumes the binding, so it alone waits; the rest of the chrome bundle\n * still starts immediately.\n */\n layoutId?:\n | string\n | null\n | Promise<string | null | undefined>\n /**\n * The screen's values for the properties of the layouts it renders inside\n * (AGL-2893), keyed by layout id — or a PROMISE of them, for the reason\n * `layoutId` accepts one: they live on the version document beside the\n * binding. Absent, every layout renders its properties' defaults.\n */\n layoutPropValues?:\n | Aglyn.AglynScreenVersion['layoutPropValues']\n | null\n | Promise<Aglyn.AglynScreenVersion['layoutPropValues'] | null | undefined>\n /**\n * The screen's per-page restyling of its layouts' elements (AGL-3286),\n * keyed by layout id then layout node id — or a PROMISE of it, for the same\n * reason as `layoutPropValues`, beside which it is stored. Absent, every\n * layout renders with its own styling.\n */\n layoutStyleOverrides?:\n | Aglyn.AglynScreenVersion['layoutStyleOverrides']\n | null\n | Promise<\n Aglyn.AglynScreenVersion['layoutStyleOverrides'] | null | undefined\n >\n /**\n * The screen's own nodes, or a PROMISE of them (AGL-1428).\n *\n * Accepting the unresolved form is what lets `composeScreenNodes` hand the\n * version read over before it has finished, so the host-scoped reads below\n * — none of which look at these nodes — overlap it instead of queueing\n * behind it. Passing a resolved value behaves exactly as before, which is\n * what every other caller does.\n */\n screenNodes: Record<string, any> | Promise<Record<string, any>>\n /** Entry-template tokens (AGL-105) substituted before denormalize. */\n tokens?: Record<string, string>\n /**\n * The one record this page renders (AGL-3475) — a record template's routed\n * record. Its `{{item.*}}` tokens are put into the page after the repeats\n * expand, and into each repeat's filter before, exactly as a repeat puts\n * its rows into its copies.\n */\n record?: Aglyn.PageRecordScope | null\n /** Routed content collection (AGL-551) for Collection entries blocks. */\n collection?: ComposeCollectionContext\n /**\n * The host document, for `host.*` tokens (AGL-1022).\n *\n * Passed in rather than read here: every caller already holds it, and\n * `composeScreenNodes` was the largest single render phase before AGL-1225\n * cut it to one round trip — adding a read back would spend that win on\n * data we already have in hand.\n */\n host?: Aglyn.HostTokenSource | null\n /**\n * The social card the head shares this page as (AGL-2850). The documents of\n * the assets it names are read in the same batch as the images and films\n * the tree places.\n */\n socialImages?: ComposeSocialImages\n}): Promise<Record<string, any>> {\n const { hostId, layoutId } = options\n\n /**\n * The layout chain, innermost first (AGL-703).\n *\n * A layout may itself render inside another layout, so this walks the\n * `layoutId` pointers rather than reading one. Fetching is sequential\n * because each step's parent is only known once the previous layout\n * document is in hand — but the walk is short by construction\n * (MAX_LAYOUT_CHAIN_DEPTH) and every layout is already a cached read.\n *\n * `seen` stops a cycle from looping forever. Stored data can hold one\n * even though both the console and `canNestLayout` refuse to create it:\n * the API, a script, or a restored backup can all write a layout\n * document directly, and a render must degrade rather than hang.\n */\n const walkLayoutChain = async () => {\n const chain: Aglyn.LayoutChainEntry[] = []\n const seen = new Set<string>()\n const boundLayoutId = await layoutId\n let currentLayoutId = boundLayoutId ? String(boundLayoutId) : undefined\n while (\n currentLayoutId &&\n !seen.has(currentLayoutId) &&\n chain.length < Aglyn.MAX_LAYOUT_CHAIN_DEPTH\n ) {\n seen.add(currentLayoutId)\n const layoutRes = await getPublishedLayoutVersion({\n hostId,\n layoutId: currentLayoutId,\n })\n // The version's declared properties travel with its nodes (AGL-2893):\n // they are applied to this layout alone, with the screen's values for\n // this layout, before the screen is grafted into its slot.\n chain.push({\n layoutId: currentLayoutId,\n nodes: layoutRes?.version?.nodes as any,\n props: (layoutRes?.version as Aglyn.AglynLayoutVersion | undefined)\n ?.props,\n })\n const parentId = (layoutRes?.layout as any)?.layoutId\n currentLayoutId = parentId ? String(parentId) : undefined\n }\n return chain\n }\n\n /**\n * ONE round-trip stage instead of three (AGL-1225).\n *\n * This used to be `await layout walk` → `await getComponents` → `await\n * Promise.all([five reads])`: three sequential waits, where only the first\n * has any reason to be sequential. Every one of the other six reads takes\n * `hostId` and nothing else — none of them consumes the layout chain — so\n * they were waiting on a walk whose result they never look at.\n *\n * The walk stays internally sequential because it genuinely is: each step's\n * parent id is only known once the previous layout document is in hand. It\n * just no longer gates anything else. The critical path becomes the walk\n * alone rather than walk + components + bulk.\n *\n * Measured budget that motivated this (production, `/product/besigner`):\n * `composeScreenNodes` was the largest single phase at 1577 ms cold and\n * consistently ~1.4-1.6 s warm too, so this is not cold-start cost. The\n * existing `AGL-1152:render` timing line reports `composeScreenNodes` as a\n * phase, so the effect of this shows up there directly — no new\n * instrumentation, and a regression would be visible in the same place.\n */\n /**\n * Does the SCREEN itself repeat (AGL-1440)?\n *\n * Asked as soon as the nodes are in hand — which since AGL-1428 is after\n * the fan-out has been ISSUED rather than before — so the overwhelmingly\n * common case still keeps the AGL-1225 shape: a page that repeats almost\n * always says so on its own document, and its rows read goes out\n * alongside the remaining chrome reads instead of after them.\n *\n * It is deliberately NOT the correctness gate — a repeatable can arrive from\n * a layout or a grafted reusable component, neither of which exists yet. The\n * gate is re-asked against the composed tree after grafting, which is the\n * exact input `expandRepeatables` reads.\n */\n /*\n * ISSUE THE HOST-SCOPED READS FIRST, THEN AWAIT THE NODES (AGL-1428).\n *\n * Every read in this bundle is keyed by `hostId` (and `layoutId`) alone —\n * none of them reads `screenNodes` — so starting them before the nodes are\n * in hand lets `composeScreenNodes`' version read overlap them rather than\n * run ahead of them. `Promise.all` is created BEFORE the `await` below on\n * purpose: that is the line that makes the two independent, and moving the\n * await above it silently gives the whole saving back.\n *\n * The repeat rows are the one read that genuinely depends on the nodes, so\n * they cannot join the bundle. It does not have to wait for the bundle either —\n * it is issued the moment the nodes resolve and awaited after, so it still\n * overlaps whatever is left of the chrome reads instead of costing the\n * extra serial round trip that dropping it from the batch would imply.\n */\n const chromeBundle = Promise.all([\n walkLayoutChain(),\n getComponents({ hostId }),\n // Host variable + function bindings (AGL-91/93): {{name}} and\n // {{fn:name(args)}} in string props resolve to values; unknown tokens\n // and failed runs stay literal. Whatever computes a variable's value\n // starts its reads here too.\n Promise.all([\n getVariables({ hostId }),\n getFunctions({ hostId }),\n prepareComputedVariables(hostId),\n getPluginInstalls({ hostId }),\n ]),\n ])\n const screenNodes = await options.screenNodes\n const screenRepeatKeys = Aglyn.repeatKeys(screenNodes)\n const screenRepeatRowsPromise = screenRepeatKeys.length\n ? readRepeatRows({ hostId, keys: screenRepeatKeys })\n : undefined\n // Does the SCREEN itself place a form entity? Gated and re-asked exactly\n // like the repeat rows read beside it (AGL-1440): most pages carry no form, and\n // the ones that do usually say so on their own document, so the read goes\n // out here alongside the chrome reads instead of as a serial tail. It is not\n // the correctness gate — a placed form can arrive from a layout or a grafted\n // component — so the composed tree is asked again below.\n const screenFormsPromise = Aglyn.placesFormEntity(screenNodes)\n ? getForms({ hostId })\n : undefined\n // Issued HERE, beside the repeat rows read and before the chrome bundle is\n // awaited, so the collection read overlaps it instead of trailing it.\n const prefetchedSources = prefetchCollectionSources(\n hostId,\n screenNodes,\n options.collection,\n )\n const [layoutChain, componentsRes, bulk] = await chromeBundle\n const [rawVariables, functions, computeVariables, pluginInstalls] = bulk\n const screenRepeatRows = await screenRepeatRowsPromise\n // Settled by now: it is read off the same version document the layout\n // binding the walk above waited on came from.\n const layoutPropValues = await options.layoutPropValues\n const layoutStyleOverrides = await options.layoutStyleOverrides\n\n const composedNodes = Aglyn.composeLayoutChainWithProps(\n layoutChain as any,\n screenNodes as any,\n layoutPropValues,\n layoutStyleOverrides,\n )\n const graftedComponents = Aglyn.composeReusableComponentNodes(\n composedNodes as any,\n componentsRes.definitions as any,\n )\n /*\n * PLACED FORMS RESOLVE AGAINST THEIR ENTITY (`docs/specs/reusable-forms.md`).\n *\n * A form node bound to `hosts/{hostId}/forms/{formId}` renders that entity's\n * published design, so a form is edited once and every page placing it\n * follows. Without this the entity's tree was written on every publish and\n * read by nothing: the fields had to be redrawn per page, and the two copies\n * diverged the moment either was touched.\n *\n * The gate is the COMPONENT-grafted tree, not the screen's own nodes, for\n * the reason the repeatables gate below states: a form placed inside a\n * layout or a shared component does not exist in `screenNodes`, and a page\n * that renders one would silently keep its stale inline copy.\n *\n * The second graft re-runs the component expansion deliberately. Instances\n * already expanded are skipped by their own prefix, so the repeat costs a\n * scan, and passing BOTH placement kinds is what expands a reusable\n * component nested inside a form's design — which the first pass could not\n * have seen, because that subtree was not in the tree yet.\n */\n const forms =\n (await screenFormsPromise)?.forms ??\n (Aglyn.placesFormEntity(graftedComponents as any)\n ? (await getForms({ hostId })).forms\n : undefined)\n const grafted = forms\n ? Aglyn.composeReusableComponentNodes(\n graftedComponents as any,\n componentsRes.definitions as any,\n [Aglyn.placedFormPlacement(forms as any)],\n )\n : graftedComponents\n // Computed variables (AGL-129): the plugin that computes a variable's\n // value fills it in once per compose; a failure keeps its stored fallback.\n const variables = computeVariables({ variables: rawVariables, functions })\n // Repeatables (AGL-103) expand after grafting (so they work inside\n // reusable components) and before bindings (so {{name}} tokens inside\n // cloned items still resolve).\n //\n // Only the rows this tree repeats over are read (AGL-1440), and the tree\n // asked is the composed one — after grafting — because that is the map the\n // expansion reads: a repeatable living in a layout or a reusable component\n // is invisible in `screenNodes`, and reading only the screen's keys would\n // silently render an empty list where the author put rows. The\n // screen's own keys were issued beside the chrome reads above; a key only a\n // layout or a component adds is read here, for that key alone.\n //\n // The rows come from the plugin that keeps them, through the repeat-rows\n // contract; this composition names no collection. A declared source whose\n // reader is missing THROWS rather than answering \"no rows\", so a broken boot\n // keeps the last good render instead of emptying every list. A repeat its\n // rows answer nothing for renders zero copies, never its raw template\n // (AGL-3496).\n const composedRepeatKeys = Aglyn.repeatKeys(grafted as any)\n const unreadRepeatKeys = composedRepeatKeys.filter(\n (key) => !screenRepeatKeys.includes(key),\n )\n const repeatRows = unreadRepeatKeys.length\n ? {\n ...screenRepeatRows,\n ...(await readRepeatRows({ hostId, keys: unreadRepeatKeys })),\n }\n : screenRepeatRows\n // A record template's routed record (AGL-3475): its values reach each\n // repeat's filter before the expansion, and every token the expansion left\n // — the page's own `{{item.*}}`, never a copy's — right after it.\n const filtered = Aglyn.substituteRepeatFilterRecordTokens(\n grafted as Record<string, any>,\n options.record,\n )\n const repeated = Aglyn.substituteNodesRecordTokens(\n Aglyn.expandRepeatables(filtered, repeatRows),\n options.record,\n )\n // Collection entries blocks (AGL-551) expand alongside repeatables:\n // per-entry {{entry.*}} tokens substitute inside the clones here, while\n // page-level tokens wait for resolveNamedTokens below.\n const withEntries = await expandCollectionEntryBlocks(\n hostId,\n repeated,\n options.collection,\n prefetchedSources,\n options.timeZone,\n )\n // Entry Meta blocks (AGL-1385): fill in the routed entry's date/category/\n // tags. Needs no source fetch — the routed entry and its taxonomy are\n // already in hand — so it sits outside `expandCollectionEntryBlocks`, which\n // returns early when no block asks for a collection read. AFTER it, so the\n // per-entry clones it just produced already carry their own resolved values\n // and are skipped.\n const withEntryMeta = Aglyn.expandCollectionEntryMeta(\n withEntries as any,\n options.collection?.entry,\n options.collection?.categories,\n options.timeZone,\n )\n // Entry Author cards (AGL-2486): the same fill, one block over. Its values\n // come off the author RECORD the routed entry resolved to, which the\n // collection read has already attached, so this costs nothing either.\n const withEntryAuthor = Aglyn.expandCollectionEntryAuthor(\n withEntryMeta as any,\n options.collection?.entry,\n )\n const bound = Aglyn.resolveNodesBindings(\n withEntryAuthor as any,\n variables,\n functions,\n )\n // Host variables (AGL-1022): `{{host.*}}` resolves from the INSTALLING\n // site, late — at render, never at install — so a rebrand propagates to\n // every artifact that names the host instead of hard-coding it. Same\n // registry the email path uses, so a token means one thing in both.\n const withHostTokens = Aglyn.resolveNodesHostTokens(\n bound as any,\n options.host,\n )\n // Function-running elements run client-side: embed their definitions\n // (AGL-93), and beside each the site variables that function reads and no\n // others (AGL-3202). Which elements those are is declared by their plugins\n // (AGL-3393), never named here.\n const withFunctions = Aglyn.attachFunctionDefinitions(\n withHostTokens,\n functions,\n variables,\n await functionBindingsFor(withHostTokens, hostId, functions),\n )\n // Marketplace plugins (AGL-45): stamp each marketplacePlugin node with its\n // pinned install (version/sha256/capabilities) + kill-switch state.\n const nodes = Aglyn.attachPluginInstalls(withFunctions, pluginInstalls)\n // Entry-template tokens (AGL-105): {{entry.*}} from the rendered entry.\n const finalNodes = Aglyn.resolveNamedTokens(nodes as any, options.tokens)\n // The document's one `main` landmark (AGL-2486). LAST, so it reads the tree\n // the page actually ships — a slot grafted from a layout chain, an element\n // an author chose — rather than the screen as stored.\n const withLandmark = Aglyn.stampDocumentLandmark(finalNodes as any)\n // Each form the record target writes for, stamped with what that target\n // trusts at submit time (AGL-2773) — a signed binding, today. Read off THIS\n // tree, the one the page ships, so a form grafted from a layout, a component\n // or a form entity is stamped as it renders; and after every stage that\n // rewrites props, so nothing changes what the stamp covers. A declared\n // target that is missing THROWS here rather than shipping forms that\n // silently write nowhere.\n const withFormBindings = await stampFormRecordTargets(\n withLandmark as Record<string, unknown>,\n hostId,\n )\n const denormalized = Aglyn.canvas.processNodesToDenormalized(\n withFormBindings as any,\n )\n /*\n * WHAT EACH PLACED IMAGE AND FILM IS NOW (AGL-2807, AGL-2833).\n *\n * An image's pixel pair and a film's length, shape and poster come from the\n * asset's DAM document as it is now, not as it was when it was picked. LAST,\n * on the tree the page ships, because an asset can arrive from any stage\n * above: a layout, a component, a form, a repeated row, a collection entry,\n * a binding.\n *\n * ONE read for all of them, issued once the tree is final rather than beside\n * the chrome reads. A read issued there could only cover the screen's own\n * placements, and nearly every layout places an image the screen does not\n * (a logo, a footer mark), so it would buy a second read on almost every\n * page. The late read costs its own round trip after the chrome reads, paid\n * each time a page is composed, which for a published page is its ISR\n * regeneration. A tree with no library asset, on a page whose social card\n * names none, issues none.\n *\n * THE SOCIAL CARD'S ASSETS JOIN THE SAME READ (AGL-2850), ahead of the\n * placements. A placement the cap leaves out keeps its pick-time pair, which\n * for an image is a reservation the decoded picture corrects. Nothing\n * corrects a card's pair, because a crawler lays the card out from it before\n * fetching the image, and a card names at most three documents.\n */\n const socialImages = options.socialImages\n const cardRefs = socialImages ? socialImageRefs(socialImages.images) : []\n const refs = mediaAssetRefs(denormalized)\n if (!refs.length && !cardRefs.length) return denormalized\n const facts = await getMediaAssetFacts({\n hostId,\n refs: [...cardRefs, ...refs],\n })\n if (socialImages) {\n const cardFacts = socialImageAssetFacts(socialImages.images, facts)\n if (cardFacts) socialImages.onFacts(cardFacts)\n }\n return applyMediaAssetFacts(denormalized, facts)\n}\n\n/**\n * What the caller knows about the page it is composing, for the page review\n * to NAME it when it holds or flags it (AGL-3374). Never read to decide\n * whether the page serves.\n */\nexport interface ComposePageContext {\n /**\n * A template composed against a routed listing or entry: the route pattern\n * it serves (`/videos`, `/videos/:slug`), the collection it renders, the\n * address being shown, and what a visitor gets when it has no clean\n * version (`built-in-design` for a content collection, whose routes fall\n * back to it; `not-found` for a store template, which has none).\n */\n template?: {\n role: 'list' | 'entry'\n route: string\n collectionName?: string | null\n entryPath?: string | null\n fallback?: 'built-in-design' | 'not-found'\n } | null\n /** An experiment variant's version of the page. */\n variant?: { experimentId: string; variantId: string; name?: string | null } | null\n}\n\n/**\n * The page's own nodes and those of every layout and reusable component\n * composed into it, for the page review to say WHICH one carries flagged\n * content (AGL-3374). Read only when a review row is filed: the layout\n * versions and the component definitions are the cached reads the compose\n * already made.\n */\nasync function composedPageParts(options: {\n hostId: string\n screenId: string\n screenNodes: Record<string, any>\n layoutId: string | null | undefined\n}): Promise<HostedPagePart[]> {\n const parts: HostedPagePart[] = [\n { type: 'screen', id: options.screenId, nodes: options.screenNodes },\n ]\n const seen = new Set<string>()\n let layoutId = options.layoutId ? String(options.layoutId) : undefined\n while (layoutId && !seen.has(layoutId) && seen.size < Aglyn.MAX_LAYOUT_CHAIN_DEPTH) {\n seen.add(layoutId)\n const layoutRes = await getPublishedLayoutVersion({ hostId: options.hostId, layoutId })\n const layout = layoutRes?.layout as { displayName?: unknown; layoutId?: unknown } | undefined\n parts.push({\n type: 'layout',\n id: layoutId,\n name: typeof layout?.displayName === 'string' ? layout.displayName : null,\n nodes: layoutRes?.version?.nodes ?? {},\n })\n layoutId = layout?.layoutId ? String(layout.layoutId) : undefined\n }\n // Only the components this page actually renders, followed through\n // components that nest others, so an unused one is never blamed.\n const { definitions } = await getComponents({ hostId: options.hostId })\n const used = new Set<string>()\n let frontier = parts.map((part) => part.nodes as Record<string, any>)\n while (frontier.length) {\n const next: Record<string, any>[] = []\n for (const [id, definition] of Object.entries(definitions)) {\n if (used.has(id)) continue\n if (frontier.some((nodes) => Aglyn.nodesReferenceComponent(nodes, id))) {\n used.add(id)\n next.push(definition.nodes as Record<string, any>)\n parts.push({ type: 'component', id, nodes: definition.nodes })\n }\n }\n frontier = next\n }\n return parts\n}\n\n/**\n * Full published-render composition for one screen (extracted for AGL-87 so\n * the SSG path and the password-unlock API build identical trees): applies\n * a due publish schedule, loads the version, composes the shared layout\n * chrome, grafts reusable components, and denormalizes.\n */\nexport async function composeScreenNodes(options: {\n hostId: string\n screenId: string\n screen: Aglyn.AglynScreen\n /** Entry-template tokens (AGL-105) substituted before denormalize. */\n tokens?: Record<string, string>\n /** The one record a record template renders (AGL-3475). */\n record?: Aglyn.PageRecordScope | null\n /** Routed content collection (AGL-551) for Collection entries blocks. */\n collection?: ComposeCollectionContext\n /**\n * Compose a specific version instead of the published one (AGL-253):\n * experiment variants point at versions; schedules don't apply.\n */\n versionId?: string\n /** The host document, for `host.*` tokens (AGL-1022). */\n host?: Aglyn.HostTokenSource | null\n /**\n * The zone this site's dates read in (AGL-3237) — `resolveSiteTimeZone` of\n * the org and the host, resolved ONCE by the caller that holds both.\n *\n * A string rather than the two documents, because the value has to be\n * identical on the server render and the client re-render, and the surest\n * way to guarantee that is for only one place to decide it. Absent is UTC,\n * which is what every site rendered before this existed.\n */\n timeZone?: string\n /** The social card the head shares this page as (AGL-2850). */\n socialImages?: ComposeSocialImages\n /**\n * Internal: `false` when this compose IS the fallback to a held page's\n * last clean version, so a fallback that holds too serves nothing rather\n * than falling back again.\n */\n pageReviewFallback?: boolean\n /** What this page is, for naming it if the page review holds it (AGL-3374). */\n page?: ComposePageContext\n}): Promise<Record<string, any> | null> {\n const { hostId, screenId, screen } = options\n\n const effectiveVersionId = options.versionId\n ? null\n : await applyDuePublishSchedule({\n hostId,\n collectionName: 'screens',\n docId: screenId,\n parent: screen,\n })\n const versionId = (options.versionId ??\n effectiveVersionId ??\n screen.versionId) as string\n\n /*\n * OVERLAP THE VERSION READ WITH THE CHROME BUNDLE (AGL-1428).\n *\n * `composeNodesWithChrome`'s reads are keyed by `hostId`/`layoutId`, both\n * of which are in hand here, so the version read no longer has to finish\n * before they start. Handing the promise over instead of the resolved\n * value is the whole change: it is `composeNodesWithChrome` that decides\n * when it actually needs the nodes.\n *\n * The `versionId`-less screen still exits BEFORE anything is issued, so a\n * screen that has never been published costs no reads. What remains is the\n * narrow case of a `versionId` that points at a missing or unreadable\n * version document — a data-integrity fault rather than a routing outcome\n * — and that one now pays for a chrome bundle it discards. That is the\n * deliberate trade: one wasted bundle on a broken screen, against the\n * version read hiding under the chrome reads on every render that works.\n */\n if (!versionId) return null\n\n const versionPromise = getScreenVersion({ hostId, screenId, versionId })\n\n /*\n * NEITHER DERIVED PROMISE MAY REJECT ON ITS OWN.\n *\n * `composed` is discarded on every failure path below, and a rejected\n * promise nobody awaited is an unhandled rejection — which in Node takes\n * the whole render process down instead of letting this 404. So the nodes\n * handed to the compose absorb the failure (an empty tree it will never be\n * asked for), and `composed` gets a rejection handler attached the moment\n * it exists rather than at the point we decide to drop it. The real error\n * still propagates, from the `await versionPromise` below, exactly where it\n * did when this function awaited the version directly.\n */\n const composed = composeNodesWithChrome({\n ...(options.timeZone ? { timeZone: options.timeZone } : {}),\n hostId,\n // Version-first (key-present wins, null = explicitly no layout), screen\n // fallback — resolved as a promise so only the layout-chain walk waits on\n // the version read; the rest of the chrome bundle keeps the AGL-1428\n // overlap. A failed version read falls back to the screen binding; the\n // whole compose is discarded on that path anyway.\n layoutId: versionPromise.then(\n (res) =>\n res.version && 'layoutId' in res.version\n ? ((res.version as Aglyn.AglynScreenVersion).layoutId as\n | string\n | null)\n : (screen.layoutId as string | undefined),\n () => screen.layoutId as string | undefined,\n ),\n // The screen's values for its layouts' properties (AGL-2893), beside the\n // binding on the same document; a failed read renders the defaults.\n layoutPropValues: versionPromise.then(\n (res) =>\n (res.version as Aglyn.AglynScreenVersion | undefined)?.layoutPropValues,\n () => undefined,\n ),\n // …and its per-page restyling of their elements (AGL-3286), from the same\n // document; a failed read renders the layouts' own styling.\n layoutStyleOverrides: versionPromise.then(\n (res) =>\n (res.version as Aglyn.AglynScreenVersion | undefined)\n ?.layoutStyleOverrides,\n () => undefined,\n ),\n screenNodes: versionPromise.then(\n (res) => (res.version?.nodes ?? {}) as any,\n () => ({}) as any,\n ),\n tokens: options.tokens,\n ...(options.record ? { record: options.record } : {}),\n collection: options.collection,\n host: options.host,\n socialImages: options.socialImages,\n })\n void composed.catch(() => undefined)\n\n const versionRes = await versionPromise\n if (versionRes.error || !versionRes.version) return null\n\n /*\n * THE PAGE PHISHING REVIEW (AGL-3356).\n *\n * Every way a page goes live — a toolbar publish, a versions-panel\n * publish, a scheduled publish, a component or form promoted under it, an\n * experiment variant, an edit to the live version in place — meets here,\n * with the page exactly as a visitor will receive it. So this is where a\n * page that links to a brand's lookalike, asks for a password or a card\n * in a field of its own, or (for a new workspace) dresses a brand's\n * sign-in or sends its call to action off the site beside a document or\n * account lure is held rather than served. See `hosted-page-review.ts`.\n *\n * A held version serves the last version this page served clean, screened\n * again, or nothing — and so does a flagged page whose review could not\n * finish, which is held rather than served.\n */\n const nodes = await composed\n const version = versionRes.version as Aglyn.AglynScreenVersion\n const review = await reviewHostedPage({\n hostId,\n screenId,\n versionId,\n nodes,\n // Named by what it is, not only its id (AGL-3374).\n page: {\n screen: {\n displayName: (screen as { displayName?: unknown }).displayName,\n name: (screen as { name?: unknown }).name,\n kind: (screen as { kind?: unknown }).kind,\n },\n template: options.page?.template ?? null,\n variant: options.page?.variant ?? null,\n parts: () =>\n composedPageParts({\n hostId,\n screenId,\n screenNodes: (version?.nodes ?? {}) as Record<string, any>,\n layoutId:\n version && 'layoutId' in version\n ? (version.layoutId as string | null)\n : (screen.layoutId as string | undefined),\n }),\n },\n })\n if (review.outcome === 'serve') {\n // Only the PUBLISHED version is the page's last clean one; a variant or\n // a pinned version is not what the page serves.\n if (nodes && !options.versionId) {\n await recordServedPageVersion(hostId, screenId, versionId)\n }\n return nodes\n }\n if (options.pageReviewFallback === false) return null\n const previous = await servedPageVersion(hostId, screenId)\n if (!previous || previous === versionId) return null\n return composeScreenNodes({\n ...options,\n versionId: previous,\n pageReviewFallback: false,\n })\n}\n\nexport default composeScreenNodes\n"],"names":["Aglyn","applyMediaAssetFacts","mediaAssetRefs","recordServedPageVersion","reviewHostedPage","servedPageVersion","stampFormRecordTargets","readRepeatRows","prepareComputedVariables","applyDuePublishSchedule","getComponents","getForms","getMediaAssetFacts","getPublishedCollectionSource","getPluginInstalls","getVariables","getFunctions","getPublishedLayoutVersion","getScreenVersion","socialImageAssetFacts","socialImageRefs","scanCollectionBlocks","nodes","collection","slugs","Set","hasRelated","hasCategories","hasSearch","node","Object","values","componentId","COLLECTION_ENTRIES_COMPONENT_ID","slug","String","props","collectionSlug","trim","add","COLLECTION_CATEGORIES_COMPONENT_ID","COLLECTION_SEARCH_COMPONENT_ID","COLLECTION_RELATED_COMPONENT_ID","entry","prefetchCollectionSources","hostId","screenNodes","prefetched","entries","pending","catch","undefined","expandCollectionEntryBlocks","timeZone","size","sources","Promise","all","map","categories","page","entriesReachedBound","reachedBound","windowStart","fetched","expanded","expandCollectionEntries","withCategories","expandCollectionCategories","routeless","categorySlug","withSearch","expandCollectionSearch","expandCollectionRelated","functionBindingsFor","functions","firstParty","FIRST_PARTY_FUNCTION_BINDINGS","keys","length","placesMarketplaceElement","some","isNamespacedComponentId","dev","process","env","NODE_ENV","devPluginManifests","getRealmPluginInstalls","installs","mergeFunctionBindings","error","console","composeNodesWithChrome","options","layoutId","walkLayoutChain","chain","seen","boundLayoutId","currentLayoutId","has","MAX_LAYOUT_CHAIN_DEPTH","layoutRes","push","version","parentId","layout","chromeBundle","screenRepeatKeys","repeatKeys","screenRepeatRowsPromise","screenFormsPromise","placesFormEntity","prefetchedSources","layoutChain","componentsRes","bulk","rawVariables","computeVariables","pluginInstalls","screenRepeatRows","layoutPropValues","layoutStyleOverrides","composedNodes","composeLayoutChainWithProps","graftedComponents","composeReusableComponentNodes","definitions","forms","grafted","placedFormPlacement","variables","composedRepeatKeys","unreadRepeatKeys","filter","key","includes","repeatRows","filtered","substituteRepeatFilterRecordTokens","record","repeated","substituteNodesRecordTokens","expandRepeatables","withEntries","withEntryMeta","expandCollectionEntryMeta","withEntryAuthor","expandCollectionEntryAuthor","bound","resolveNodesBindings","withHostTokens","resolveNodesHostTokens","host","withFunctions","attachFunctionDefinitions","attachPluginInstalls","finalNodes","resolveNamedTokens","tokens","withLandmark","stampDocumentLandmark","withFormBindings","denormalized","canvas","processNodesToDenormalized","socialImages","cardRefs","images","refs","facts","cardFacts","onFacts","composedPageParts","parts","type","id","screenId","name","displayName","used","frontier","part","next","definition","nodesReferenceComponent","composeScreenNodes","screen","effectiveVersionId","versionId","collectionName","docId","parent","versionPromise","composed","then","res","versionRes","review","kind","template","variant","outcome","pageReviewFallback","previous"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,W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AO,EAAE,OAAO;IAEpD;;;;;;;;;;;;;;;GAeC,GACD,MAAMnF,QAAQ,MAAM6K;IACpB,MAAM1F,UAAU6F,WAAW7F,OAAO;IAClC,MAAM8F,SAAS,MAAMnM,iBAAiB;QACpCyC;QACAqI;QACAY;QACAxK;QACA,mDAAmD;QACnDsC,MAAM;YACJgI,QAAQ;gBACNR,aAAa,AAACQ,OAAqCR,WAAW;gBAC9DD,MAAM,AAACS,OAA8BT,IAAI;gBACzCqB,MAAM,AAACZ,OAA8BY,IAAI;YAC3C;YACAC,QAAQ,YAAE3G,gBAAAA,QAAQlC,IAAI,qBAAZkC,cAAc2G,QAAQ,oBAAI;YACpCC,OAAO,YAAE5G,iBAAAA,QAAQlC,IAAI,qBAAZkC,eAAc4G,OAAO,oBAAI;YAClC3B,OAAO;;uBACLD,kBAAkB;oBAChBjI;oBACAqI;oBACApI,WAAW,UAAG2D,2BAAAA,QAASnF,KAAK,mBAAI,CAAC;oBACjCyE,UACEU,WAAW,cAAcA,UACpBA,QAAQV,QAAQ,GAChB6F,OAAO7F,QAAQ;gBACxB;;QACJ;IACF;IACA,IAAIwG,OAAOI,OAAO,KAAK,SAAS;QAC9B,wEAAwE;QACxE,gDAAgD;QAChD,IAAIrL,SAAS,CAACwE,QAAQgG,SAAS,EAAE;YAC/B,MAAM3L,wBAAwB0C,QAAQqI,UAAUY;QAClD;QACA,OAAOxK;IACT;IACA,IAAIwE,QAAQ8G,kBAAkB,KAAK,OAAO,OAAO;IACjD,MAAMC,WAAW,MAAMxM,kBAAkBwC,QAAQqI;IACjD,IAAI,CAAC2B,YAAYA,aAAaf,WAAW,OAAO;IAChD,OAAOH,mBAAmB,aACrB7F;QACHgG,WAAWe;QACXD,oBAAoB;;AAExB;AAEA,eAAejB,mBAAkB"}
|
|
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import * as Aglyn from "@aglyn/aglyn/server";
|
|
18
18
|
import { getHostDocAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
19
|
+
import { leavingNoticeSignatures } from "@aglyn/tenant-data-admin/server/leaving-notice";
|
|
19
20
|
/**
|
|
20
21
|
* Where the entries a gated tree links to are served (AGL-3118), or
|
|
21
22
|
* `undefined` when it names none that are live.
|
|
@@ -121,9 +122,23 @@ import { getHostDocAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
|
121
122
|
nodes
|
|
122
123
|
});
|
|
123
124
|
const entryRoutes = await entryRoutesPromise;
|
|
124
|
-
|
|
125
|
+
// The leaving notice's signatures for this tree (AGL-3452): the page was
|
|
126
|
+
// signed before the gate opened, from a payload that had no tree, so the
|
|
127
|
+
// outside links the visitor just unlocked are signed here.
|
|
128
|
+
const leavingSignatures = leavingNoticeSignatures({
|
|
129
|
+
hostId,
|
|
130
|
+
site: host,
|
|
131
|
+
org: orgRes == null ? void 0 : orgRes.org,
|
|
132
|
+
content: {
|
|
133
|
+
nodes,
|
|
134
|
+
enriched: enriched.props
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
return _extends({}, enriched.props, entryRoutes ? {
|
|
125
138
|
entryRoutes
|
|
126
|
-
}
|
|
139
|
+
} : {}, leavingSignatures ? {
|
|
140
|
+
leavingSignatures
|
|
141
|
+
} : {});
|
|
127
142
|
} catch (error) {
|
|
128
143
|
console.error('gated page enrichment failed', error);
|
|
129
144
|
return {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/enrich-gated-page.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 * as Aglyn from '@aglyn/aglyn/server'\nimport { getHostDocAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\n\n/**\n * Where the entries a gated tree links to are served (AGL-3118), or\n * `undefined` when it names none that are live.\n *\n * The page's routing map was built before the gate opened, from a tree it\n * did not have, so it holds no entry a gated page links to; these travel\n * with the nodes for the reason the enricher slice does. A tree that names\n * no entry costs no read.\n *\n * Never rejects, so the caller can start it early and abandon it on a\n * failure of its own.\n *\n * The two readers it needs are loaded HERE rather than imported at the top of\n * this file. Both reach `withRenderCache` and through it `next/cache`, which\n * drags Next's server runtime into the module graph of everything that\n * imports this enricher — including the commerce plugin, whose specs then\n * fail to load at all. Loading them inside the one branch that reads also\n * means a gated tree naming no entry pays for neither.\n */\nasync function gatedEntryLinkRoutes(\n hostId: string,\n nodes: unknown,\n): Promise<Record<string, string> | undefined> {\n try {\n const refs = Aglyn.collectEntryLinkRefs({\n nodes: [nodes as Record<string, unknown> | null],\n })\n if (!refs.length) return undefined\n const [{ getTemplateScreenRouting }, { resolveEntryLinkRoutes }] =\n await Promise.all([\n import('./template-screens'),\n import('./entry-link-routes'),\n ])\n const routing = await getTemplateScreenRouting({ hostId })\n const routes = await resolveEntryLinkRoutes({\n hostId,\n refs,\n collectionSlugs: routing.collectionListings,\n })\n return Object.keys(routes).length ? routes : undefined\n } catch (error) {\n console.error('gated page entry links failed', error)\n return undefined\n }\n}\n\n/**\n * The enricher slice for a screen whose nodes are withheld from the page and\n * fetched after a gate opens (AGL-2510) — a password-protected screen\n * (AGL-87) and a members-only one (AGL-109).\n *\n * ## Why these two need their own call\n *\n * Every other rendered page gets its enricher props from the loader, but\n * these two deliberately ship `nodes: null`: embedding a gated tree in static\n * HTML would publish the very content the gate exists to withhold. So the\n * page arrives with the built-in prompt and no site chrome at all, and the\n * composed tree — the site's shared layout, nav and footer included — is\n * swapped in by the client once the visitor gets past the gate. A nav menu\n * built from primitives opens through `clientAutomations`, which is enricher\n * output, so without this the unlocked page renders the site's nav and none\n * of its behavior.\n *\n * Delivering it WITH the nodes is what keeps the gate honest. The slice is\n * derived from the withheld tree and describes its structure; shipping it in\n * the public HTML alongside `nodes: null` would leak an outline of the page\n * to anyone who never answers the prompt.\n *\n * ## The path\n *\n * Taken from the host's own routing map rather than from the caller, because\n * both callers are POST endpoints a visitor controls: a supplied path would\n * let anyone pick which overlays and path-scoped automations a gated page\n * runs. A screen missing from the map (never routed) gets the site root,\n * which is what an unrouted screen's own address would be.\n *\n * ## The entry links\n *\n * `entryRoutes` rides along when the tree links to a live content entry\n * (AGL-3118), and the client adds those keys to the page's routing map — see\n * {@link gatedEntryLinkRoutes}.\n *\n * Fail-open to `{}` — an enricher slice is behavior on top of a page, and no\n * failure here may cost a visitor the content they just unlocked.\n */\nexport async function enrichGatedScreenPage(options: {\n hostId: string\n screenId: string\n screen: any\n nodes: any\n /**\n * The site document, when the caller already read it to compose `nodes`\n * (AGL-2883). Read here when absent.\n */\n host?: Record<string, unknown> | null\n}): Promise<Record<string, unknown>> {\n const { hostId, screenId, screen, nodes } = options\n try {\n // Started first: its reads share nothing with the enrichers'.\n const entryRoutesPromise = gatedEntryLinkRoutes(hostId, nodes)\n const [host, orgRes] = await Promise.all([\n options.host !== undefined ? options.host : getHostDocAdmin(hostId),\n getOrgForHost(hostId),\n ])\n const routing = ((host as { screens?: Record<string, string> })?.screens ??\n {}) as Record<string, string>\n const path = routing[screenId] || Aglyn.SCREEN_ROOT_PATH\n const enriched = await Aglyn.runSitePageEnrichers({\n hostId,\n host,\n org: orgRes?.org,\n path,\n slugSegments: path.split('/').filter(Boolean),\n screenId,\n screen,\n nodes,\n })\n const entryRoutes = await entryRoutesPromise\n
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/enrich-gated-page.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 * as Aglyn from '@aglyn/aglyn/server'\nimport { getHostDocAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { leavingNoticeSignatures } from '@aglyn/tenant-data-admin/server/leaving-notice'\n\n/**\n * Where the entries a gated tree links to are served (AGL-3118), or\n * `undefined` when it names none that are live.\n *\n * The page's routing map was built before the gate opened, from a tree it\n * did not have, so it holds no entry a gated page links to; these travel\n * with the nodes for the reason the enricher slice does. A tree that names\n * no entry costs no read.\n *\n * Never rejects, so the caller can start it early and abandon it on a\n * failure of its own.\n *\n * The two readers it needs are loaded HERE rather than imported at the top of\n * this file. Both reach `withRenderCache` and through it `next/cache`, which\n * drags Next's server runtime into the module graph of everything that\n * imports this enricher — including the commerce plugin, whose specs then\n * fail to load at all. Loading them inside the one branch that reads also\n * means a gated tree naming no entry pays for neither.\n */\nasync function gatedEntryLinkRoutes(\n hostId: string,\n nodes: unknown,\n): Promise<Record<string, string> | undefined> {\n try {\n const refs = Aglyn.collectEntryLinkRefs({\n nodes: [nodes as Record<string, unknown> | null],\n })\n if (!refs.length) return undefined\n const [{ getTemplateScreenRouting }, { resolveEntryLinkRoutes }] =\n await Promise.all([\n import('./template-screens'),\n import('./entry-link-routes'),\n ])\n const routing = await getTemplateScreenRouting({ hostId })\n const routes = await resolveEntryLinkRoutes({\n hostId,\n refs,\n collectionSlugs: routing.collectionListings,\n })\n return Object.keys(routes).length ? routes : undefined\n } catch (error) {\n console.error('gated page entry links failed', error)\n return undefined\n }\n}\n\n/**\n * The enricher slice for a screen whose nodes are withheld from the page and\n * fetched after a gate opens (AGL-2510) — a password-protected screen\n * (AGL-87) and a members-only one (AGL-109).\n *\n * ## Why these two need their own call\n *\n * Every other rendered page gets its enricher props from the loader, but\n * these two deliberately ship `nodes: null`: embedding a gated tree in static\n * HTML would publish the very content the gate exists to withhold. So the\n * page arrives with the built-in prompt and no site chrome at all, and the\n * composed tree — the site's shared layout, nav and footer included — is\n * swapped in by the client once the visitor gets past the gate. A nav menu\n * built from primitives opens through `clientAutomations`, which is enricher\n * output, so without this the unlocked page renders the site's nav and none\n * of its behavior.\n *\n * Delivering it WITH the nodes is what keeps the gate honest. The slice is\n * derived from the withheld tree and describes its structure; shipping it in\n * the public HTML alongside `nodes: null` would leak an outline of the page\n * to anyone who never answers the prompt.\n *\n * ## The path\n *\n * Taken from the host's own routing map rather than from the caller, because\n * both callers are POST endpoints a visitor controls: a supplied path would\n * let anyone pick which overlays and path-scoped automations a gated page\n * runs. A screen missing from the map (never routed) gets the site root,\n * which is what an unrouted screen's own address would be.\n *\n * ## The entry links\n *\n * `entryRoutes` rides along when the tree links to a live content entry\n * (AGL-3118), and the client adds those keys to the page's routing map — see\n * {@link gatedEntryLinkRoutes}.\n *\n * Fail-open to `{}` — an enricher slice is behavior on top of a page, and no\n * failure here may cost a visitor the content they just unlocked.\n */\nexport async function enrichGatedScreenPage(options: {\n hostId: string\n screenId: string\n screen: any\n nodes: any\n /**\n * The site document, when the caller already read it to compose `nodes`\n * (AGL-2883). Read here when absent.\n */\n host?: Record<string, unknown> | null\n}): Promise<Record<string, unknown>> {\n const { hostId, screenId, screen, nodes } = options\n try {\n // Started first: its reads share nothing with the enrichers'.\n const entryRoutesPromise = gatedEntryLinkRoutes(hostId, nodes)\n const [host, orgRes] = await Promise.all([\n options.host !== undefined ? options.host : getHostDocAdmin(hostId),\n getOrgForHost(hostId),\n ])\n const routing = ((host as { screens?: Record<string, string> })?.screens ??\n {}) as Record<string, string>\n const path = routing[screenId] || Aglyn.SCREEN_ROOT_PATH\n const enriched = await Aglyn.runSitePageEnrichers({\n hostId,\n host,\n org: orgRes?.org,\n path,\n slugSegments: path.split('/').filter(Boolean),\n screenId,\n screen,\n nodes,\n })\n const entryRoutes = await entryRoutesPromise\n // The leaving notice's signatures for this tree (AGL-3452): the page was\n // signed before the gate opened, from a payload that had no tree, so the\n // outside links the visitor just unlocked are signed here.\n const leavingSignatures = leavingNoticeSignatures({\n hostId,\n site: host as { subdomain?: string | null; cname?: string | null } | null,\n org: orgRes?.org,\n content: { nodes, enriched: enriched.props },\n })\n return {\n ...enriched.props,\n ...(entryRoutes ? { entryRoutes } : {}),\n ...(leavingSignatures ? { leavingSignatures } : {}),\n }\n } catch (error) {\n console.error('gated page enrichment failed', error)\n return {}\n }\n}\n\nexport default enrichGatedScreenPage\n"],"names":["Aglyn","getHostDocAdmin","getOrgForHost","leavingNoticeSignatures","gatedEntryLinkRoutes","hostId","nodes","refs","collectEntryLinkRefs","length","undefined","getTemplateScreenRouting","resolveEntryLinkRoutes","Promise","all","routing","routes","collectionSlugs","collectionListings","Object","keys","error","console","enrichGatedScreenPage","options","screenId","screen","entryRoutesPromise","host","orgRes","screens","path","SCREEN_ROOT_PATH","enriched","runSitePageEnrichers","org","slugSegments","split","filter","Boolean","entryRoutes","leavingSignatures","site","content","props"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,eAAe,EAAEC,aAAa,QAAQ,2BAA0B;AACzE,SAASC,uBAAuB,QAAQ,iDAAgD;AAExF;;;;;;;;;;;;;;;;;;CAkBC,GACD,eAAeC,qBACbC,MAAc,EACdC,KAAc;IAEd,IAAI;QACF,MAAMC,OAAOP,MAAMQ,oBAAoB,CAAC;YACtCF,OAAO;gBAACA;aAAwC;QAClD;QACA,IAAI,CAACC,KAAKE,MAAM,EAAE,OAAOC;QACzB,MAAM,CAAC,EAAEC,wBAAwB,EAAE,EAAE,EAAEC,sBAAsB,EAAE,CAAC,GAC9D,MAAMC,QAAQC,GAAG,CAAC;YAChB,MAAM,CAAC;YACP,MAAM,CAAC;S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QACA,OAAO,aACFX,SAASW,KAAK,EACbJ,cAAc;YAAEA;QAAY,IAAI,CAAC,GACjCC,oBAAoB;YAAEA;QAAkB,IAAI,CAAC;IAErD,EAAE,OAAOpB,OAAO;QACdC,QAAQD,KAAK,CAAC,gCAAgCA;QAC9C,OAAO,CAAC;IACV;AACF;AAEA,eAAeE,sBAAqB"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { SiteIconSourceFacts } from '@aglyn/aglyn/app-utils/site-icon-set';
|
|
18
|
+
/**
|
|
19
|
+
* The type and content hash of each site-icon source (AGL-3484), keyed by the
|
|
20
|
+
* resolved src the caller passed in.
|
|
21
|
+
*
|
|
22
|
+
* The derived icon set needs both: the type decides whether the source can be
|
|
23
|
+
* drawn from (an ICO cannot) and whether it passes through as an SVG, and the
|
|
24
|
+
* hash is the `v` that lets every derived icon be cached for a year while a
|
|
25
|
+
* DAM Replace still reaches it.
|
|
26
|
+
*
|
|
27
|
+
* Takes RESOLVED srcs — `/api/media/cdn/{scope}/{id}`, relative or absolute —
|
|
28
|
+
* because that is what the favicon chain already produces (the site's own,
|
|
29
|
+
* then the org's white-label mark). A src that is not ours gets no entry.
|
|
30
|
+
*
|
|
31
|
+
* One `getAll` for all of them, projected; at most three documents on a page
|
|
32
|
+
* (favicon, app icon, logo). Not behind the render cache, for
|
|
33
|
+
* `get-media-asset-facts`'s reason: a Replace announces nothing to the tenant,
|
|
34
|
+
* so a cached hash could outlive the page's own window by another hour. The
|
|
35
|
+
* same gates decide an entry: a deleted, private or out-of-scope asset gets
|
|
36
|
+
* none, and neither does any asset when the read fails — the icons then
|
|
37
|
+
* derive without a version, which the CDN serves under its revalidated policy.
|
|
38
|
+
*/
|
|
39
|
+
export declare function getSiteIconFacts(options: {
|
|
40
|
+
hostId: string | undefined;
|
|
41
|
+
srcs: ReadonlyArray<string | undefined | null>;
|
|
42
|
+
}): Promise<Map<string, SiteIconSourceFacts>>;
|
|
43
|
+
export default getSiteIconFacts;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ // By path rather than through a barrel, as `get-media-asset-facts` does.
|
|
18
|
+
import { MEDIA_ASSET_FACT_FIELDS, mediaAssetDocumentPath, mediaAssetFactsFromDocument } from "@aglyn/aglyn/app-utils/media-asset-facts";
|
|
19
|
+
import { mediaRefFromCdnPath, parseMediaRef } from "@aglyn/aglyn/app-utils/media-ref";
|
|
20
|
+
// The one module, not the barrel: the `[host]` layout reads this, and the
|
|
21
|
+
// barrel drags the render cache's `next/cache` into every importer.
|
|
22
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
23
|
+
/** The two fields an icon source adds to the facts projection. */ const SITE_ICON_FACT_FIELDS = [
|
|
24
|
+
...MEDIA_ASSET_FACT_FIELDS,
|
|
25
|
+
'contentType',
|
|
26
|
+
'contentHash'
|
|
27
|
+
];
|
|
28
|
+
/**
|
|
29
|
+
* The type and content hash of each site-icon source (AGL-3484), keyed by the
|
|
30
|
+
* resolved src the caller passed in.
|
|
31
|
+
*
|
|
32
|
+
* The derived icon set needs both: the type decides whether the source can be
|
|
33
|
+
* drawn from (an ICO cannot) and whether it passes through as an SVG, and the
|
|
34
|
+
* hash is the `v` that lets every derived icon be cached for a year while a
|
|
35
|
+
* DAM Replace still reaches it.
|
|
36
|
+
*
|
|
37
|
+
* Takes RESOLVED srcs — `/api/media/cdn/{scope}/{id}`, relative or absolute —
|
|
38
|
+
* because that is what the favicon chain already produces (the site's own,
|
|
39
|
+
* then the org's white-label mark). A src that is not ours gets no entry.
|
|
40
|
+
*
|
|
41
|
+
* One `getAll` for all of them, projected; at most three documents on a page
|
|
42
|
+
* (favicon, app icon, logo). Not behind the render cache, for
|
|
43
|
+
* `get-media-asset-facts`'s reason: a Replace announces nothing to the tenant,
|
|
44
|
+
* so a cached hash could outlive the page's own window by another hour. The
|
|
45
|
+
* same gates decide an entry: a deleted, private or out-of-scope asset gets
|
|
46
|
+
* none, and neither does any asset when the read fails — the icons then
|
|
47
|
+
* derive without a version, which the CDN serves under its revalidated policy.
|
|
48
|
+
*/ export async function getSiteIconFacts(options) {
|
|
49
|
+
const { hostId } = options;
|
|
50
|
+
const facts = new Map();
|
|
51
|
+
if (!hostId) return facts;
|
|
52
|
+
/** One read per document, however many srcs name it. */ const documents = new Map();
|
|
53
|
+
for (const src of options.srcs){
|
|
54
|
+
var _documents_get;
|
|
55
|
+
if (!src) continue;
|
|
56
|
+
const ref = parseMediaRef(mediaRefFromCdnPath(src));
|
|
57
|
+
const path = ref ? mediaAssetDocumentPath(ref) : null;
|
|
58
|
+
if (!ref || !path) continue;
|
|
59
|
+
const named = (_documents_get = documents.get(path)) != null ? _documents_get : [];
|
|
60
|
+
named.push({
|
|
61
|
+
src,
|
|
62
|
+
scope: ref.scope
|
|
63
|
+
});
|
|
64
|
+
documents.set(path, named);
|
|
65
|
+
}
|
|
66
|
+
if (!documents.size) return facts;
|
|
67
|
+
try {
|
|
68
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
69
|
+
const paths = [
|
|
70
|
+
...documents.keys()
|
|
71
|
+
];
|
|
72
|
+
const snapshots = await firestore.getAll(...paths.map((path)=>firestore.doc(path)), {
|
|
73
|
+
fieldMask: [
|
|
74
|
+
...SITE_ICON_FACT_FIELDS
|
|
75
|
+
]
|
|
76
|
+
});
|
|
77
|
+
snapshots.forEach((snapshot, index)=>{
|
|
78
|
+
var _documents_get;
|
|
79
|
+
if (!snapshot.exists) return;
|
|
80
|
+
const document = {};
|
|
81
|
+
for (const field of MEDIA_ASSET_FACT_FIELDS){
|
|
82
|
+
document[field] = snapshot.get(field);
|
|
83
|
+
}
|
|
84
|
+
const contentType = snapshot.get('contentType');
|
|
85
|
+
const contentHash = snapshot.get('contentHash');
|
|
86
|
+
for (const { src, scope } of (_documents_get = documents.get(paths[index])) != null ? _documents_get : []){
|
|
87
|
+
if (!mediaAssetFactsFromDocument(document, {
|
|
88
|
+
scope
|
|
89
|
+
}, hostId)) continue;
|
|
90
|
+
facts.set(src, _extends({}, typeof contentType === 'string' ? {
|
|
91
|
+
contentType
|
|
92
|
+
} : {}, typeof contentHash === 'string' && contentHash ? {
|
|
93
|
+
contentHash
|
|
94
|
+
} : {}));
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
return facts;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
console.error('[site-icon-facts] read failed; icons derive unversioned', error);
|
|
100
|
+
return new Map();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
export default getSiteIconFacts;
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=get-site-icon-facts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/get-site-icon-facts.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\n// By path rather than through a barrel, as `get-media-asset-facts` does.\nimport {\n MEDIA_ASSET_FACT_FIELDS,\n type MediaAssetDocument,\n mediaAssetDocumentPath,\n mediaAssetFactsFromDocument,\n} from '@aglyn/aglyn/app-utils/media-asset-facts'\nimport {\n mediaRefFromCdnPath,\n parseMediaRef,\n} from '@aglyn/aglyn/app-utils/media-ref'\nimport type { SiteIconSourceFacts } from '@aglyn/aglyn/app-utils/site-icon-set'\n// The one module, not the barrel: the `[host]` layout reads this, and the\n// barrel drags the render cache's `next/cache` into every importer.\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\n\n/** The two fields an icon source adds to the facts projection. */\nconst SITE_ICON_FACT_FIELDS = [\n ...MEDIA_ASSET_FACT_FIELDS,\n 'contentType',\n 'contentHash',\n] as const\n\n/**\n * The type and content hash of each site-icon source (AGL-3484), keyed by the\n * resolved src the caller passed in.\n *\n * The derived icon set needs both: the type decides whether the source can be\n * drawn from (an ICO cannot) and whether it passes through as an SVG, and the\n * hash is the `v` that lets every derived icon be cached for a year while a\n * DAM Replace still reaches it.\n *\n * Takes RESOLVED srcs — `/api/media/cdn/{scope}/{id}`, relative or absolute —\n * because that is what the favicon chain already produces (the site's own,\n * then the org's white-label mark). A src that is not ours gets no entry.\n *\n * One `getAll` for all of them, projected; at most three documents on a page\n * (favicon, app icon, logo). Not behind the render cache, for\n * `get-media-asset-facts`'s reason: a Replace announces nothing to the tenant,\n * so a cached hash could outlive the page's own window by another hour. The\n * same gates decide an entry: a deleted, private or out-of-scope asset gets\n * none, and neither does any asset when the read fails — the icons then\n * derive without a version, which the CDN serves under its revalidated policy.\n */\nexport async function getSiteIconFacts(options: {\n hostId: string | undefined\n srcs: ReadonlyArray<string | undefined | null>\n}): Promise<Map<string, SiteIconSourceFacts>> {\n const { hostId } = options\n const facts = new Map<string, SiteIconSourceFacts>()\n if (!hostId) return facts\n /** One read per document, however many srcs name it. */\n const documents = new Map<string, Array<{ src: string; scope: string }>>()\n for (const src of options.srcs) {\n if (!src) continue\n const ref = parseMediaRef(mediaRefFromCdnPath(src))\n const path = ref ? mediaAssetDocumentPath(ref) : null\n if (!ref || !path) continue\n const named = documents.get(path) ?? []\n named.push({ src, scope: ref.scope })\n documents.set(path, named)\n }\n if (!documents.size) return facts\n try {\n const firestore = firebaseAdmin.app().firestore()\n const paths = [...documents.keys()]\n const snapshots = await firestore.getAll(\n ...paths.map((path) => firestore.doc(path)),\n { fieldMask: [...SITE_ICON_FACT_FIELDS] },\n )\n snapshots.forEach((snapshot, index) => {\n if (!snapshot.exists) return\n const document: MediaAssetDocument = {}\n for (const field of MEDIA_ASSET_FACT_FIELDS) {\n document[field] = snapshot.get(field)\n }\n const contentType = snapshot.get('contentType')\n const contentHash = snapshot.get('contentHash')\n for (const { src, scope } of documents.get(paths[index]) ?? []) {\n if (!mediaAssetFactsFromDocument(document, { scope }, hostId)) continue\n facts.set(src, {\n ...(typeof contentType === 'string' ? { contentType } : {}),\n ...(typeof contentHash === 'string' && contentHash\n ? { contentHash }\n : {}),\n })\n }\n })\n return facts\n } catch (error) {\n console.error('[site-icon-facts] read failed; icons derive unversioned', error)\n return new Map()\n }\n}\n\nexport default getSiteIconFacts\n"],"names":["MEDIA_ASSET_FACT_FIELDS","mediaAssetDocumentPath","mediaAssetFactsFromDocument","mediaRefFromCdnPath","parseMediaRef","firebaseAdmin","SITE_ICON_FACT_FIELDS","getSiteIconFacts","options","hostId","facts","Map","documents","src","srcs","ref","path","named","get","push","scope","set","size","firestore","app","paths","keys","snapshots","getAll","map","doc","fieldMask","forEach","snapshot","index","exists","document","field","contentType","contentHash","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,yEAAyE;AACzE,SACEA,uBAAuB,EAEvBC,sBAAsB,EACtBC,2BAA2B,QACtB,2CAA0C;AACjD,SACEC,mBAAmB,EACnBC,aAAa,QACR,mCAAkC;AAEzC,0EAA0E;AAC1E,oEAAoE;AACpE,SAASC,aAAa,QAAQ,iDAAgD;AAE9E,gEAAgE,GAChE,MAAMC,wBAAwB;OACzBN;IACH;IACA;CACD;AAED;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,eAAeO,iBAAiBC,OAGtC;IACC,MAAM,EAAEC,MAAM,EAAE,GAAGD;IACnB,MAAME,QAAQ,IAAIC;IAClB,IAAI,CAACF,QAAQ,OAAOC;IACpB,sDAAsD,GACtD,MAAME,YAAY,IAAID;IACtB,KAAK,MAAME,OAAOL,QAAQM,IAAI,CAAE;YAKhBF;QAJd,IAAI,CAACC,KAAK;QACV,MAAME,MAAMX,cAAcD,oBAAoBU;QAC9C,MAAMG,OAAOD,MAAMd,uBAAuBc,OAAO;QACjD,IAAI,CAACA,OAAO,CAACC,MAAM;QACnB,MAAMC,SAAQL,iBAAAA,UAAUM,GAAG,CAACF,iBAAdJ,iBAAuB,EAAE;QACvCK,MAAME,IAAI,CAAC;YAAEN;YAAKO,OAAOL,IAAIK,KAAK;QAAC;QACnCR,UAAUS,GAAG,CAACL,MAAMC;IACtB;IACA,IAAI,CAACL,UAAUU,IAAI,EAAE,OAAOZ;IAC5B,IAAI;QACF,MAAMa,YAAYlB,cAAcmB,GAAG,GAAGD,SAAS;QAC/C,MAAME,QAAQ;eAAIb,UAAUc,IAAI;SAAG;QACnC,MAAMC,YAAY,MAAMJ,UAAUK,MAAM,IACnCH,MAAMI,GAAG,CAAC,CAACb,OAASO,UAAUO,GAAG,CAACd,QACrC;YAAEe,WAAW;mBAAIzB;aAAsB;QAAC;QAE1CqB,UAAUK,OAAO,CAAC,CAACC,UAAUC;gBAQEtB;YAP7B,IAAI,CAACqB,SAASE,MAAM,EAAE;YACtB,MAAMC,WAA+B,CAAC;YACtC,KAAK,MAAMC,SAASrC,wBAAyB;gBAC3CoC,QAAQ,CAACC,MAAM,GAAGJ,SAASf,GAAG,CAACmB;YACjC;YACA,MAAMC,cAAcL,SAASf,GAAG,CAAC;YACjC,MAAMqB,cAAcN,SAASf,GAAG,CAAC;YACjC,KAAK,MAAM,EAAEL,GAAG,EAAEO,KAAK,EAAE,KAAIR,iBAAAA,UAAUM,GAAG,CAACO,KAAK,CAACS,MAAM,aAA1BtB,iBAA+B,EAAE,CAAE;gBAC9D,IAAI,CAACV,4BAA4BkC,UAAU;oBAAEhB;gBAAM,GAAGX,SAAS;gBAC/DC,MAAMW,GAAG,CAACR,KAAK,aACT,OAAOyB,gBAAgB,WAAW;oBAAEA;gBAAY,IAAI,CAAC,GACrD,OAAOC,gBAAgB,YAAYA,cACnC;oBAAEA;gBAAY,IACd,CAAC;YAET;QACF;QACA,OAAO7B;IACT,EAAE,OAAO8B,OAAO;QACdC,QAAQD,KAAK,CAAC,2DAA2DA;QACzE,OAAO,IAAI7B;IACb;AACF;AAEA,eAAeJ,iBAAgB"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { HostTheme } from '@aglyn/shared-data-types';
|
|
18
|
+
/** A font file's URL never changes its bytes: the version is in the path. */
|
|
19
|
+
export declare const SELF_HOSTED_FONT_CACHE_CONTROL = "public, max-age=31536000, s-maxage=31536000, immutable";
|
|
20
|
+
/** Test seam: the process cache would otherwise leak between cases. */
|
|
21
|
+
export declare function resetSelfHostedFontsForTests(): void;
|
|
22
|
+
/** What a page inlines in its head for its theme's fonts. */
|
|
23
|
+
export interface SelfHostedThemeFonts {
|
|
24
|
+
/** The `@font-face` rules, every `src` on the site's own origin. */
|
|
25
|
+
css: string;
|
|
26
|
+
/** The one or two files the first screen paints with, to preload. */
|
|
27
|
+
preloads: string[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The theme's Google fonts as rules to inline and files to preload, or null
|
|
31
|
+
* when the theme loads none or Google could not be read — in which case the
|
|
32
|
+
* caller links the stylesheet as before.
|
|
33
|
+
*/
|
|
34
|
+
export declare function selfHostedThemeFonts(theme: Pick<HostTheme, 'fonts' | 'typography'> | undefined): Promise<SelfHostedThemeFonts | null>;
|
|
35
|
+
/**
|
|
36
|
+
* One font file, fetched from Google and answered from the site's origin with
|
|
37
|
+
* a year-long `immutable` policy. `path` is the part below `/s/` on Google's
|
|
38
|
+
* origin (`inter/v18/….woff2`); anything else is a 404, so this route cannot
|
|
39
|
+
* be pointed at any other URL.
|
|
40
|
+
*
|
|
41
|
+
* The edge keeps the answer for the year too (`s-maxage`), so Google is asked
|
|
42
|
+
* once per file per edge region rather than once per visitor.
|
|
43
|
+
*/
|
|
44
|
+
export declare function serveSelfHostedFont(path: string): Promise<Response>;
|