@aglyn/aglyn 1.12.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- package/src/lib/app-utils/crm.js +8 -7
- package/src/lib/app-utils/crm.js.map +1 -1
- package/src/lib/app-utils/docs-help-sections.generated.js +8 -2
- package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +1 -1
- package/src/lib/app-utils/docs-help.generated.js +7 -0
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +48 -34
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/dynamic-list-rule.js +9 -5
- package/src/lib/app-utils/dynamic-list-rule.js.map +1 -1
- package/src/lib/app-utils/host-permissions.d.ts +12 -0
- package/src/lib/app-utils/host-permissions.js +26 -1
- package/src/lib/app-utils/host-permissions.js.map +1 -1
- package/src/lib/app-utils/media-asset-facts.d.ts +2 -2
- package/src/lib/app-utils/media-asset-facts.js +4 -3
- package/src/lib/app-utils/media-asset-facts.js.map +1 -1
- package/src/lib/app-utils/media-cdn-scope.d.ts +19 -4
- package/src/lib/app-utils/media-cdn-scope.js +19 -5
- package/src/lib/app-utils/media-cdn-scope.js.map +1 -1
- package/src/lib/app-utils/media-ref.d.ts +10 -6
- package/src/lib/app-utils/media-ref.js +34 -8
- package/src/lib/app-utils/media-ref.js.map +1 -1
- package/src/lib/app-utils/native-nav.d.ts +2 -2
- package/src/lib/app-utils/native-nav.js +2 -2
- package/src/lib/app-utils/native-nav.js.map +1 -1
- package/src/lib/app-utils/org-permissions.d.ts +7 -0
- package/src/lib/app-utils/org-permissions.js +2 -0
- package/src/lib/app-utils/org-permissions.js.map +1 -1
- package/src/lib/app-utils/org-role-grants.d.ts +7 -0
- package/src/lib/app-utils/org-role-grants.js +7 -5
- package/src/lib/app-utils/org-role-grants.js.map +1 -1
- package/src/lib/app-utils/scope-tokens.d.ts +132 -3
- package/src/lib/app-utils/scope-tokens.js +276 -3
- package/src/lib/app-utils/scope-tokens.js.map +1 -1
- package/src/lib/app-utils/site-placement.d.ts +74 -0
- package/src/lib/app-utils/site-placement.js +80 -0
- package/src/lib/app-utils/site-placement.js.map +1 -0
- package/src/lib/app-utils/transfer-launcher-context.d.ts +17 -1
- package/src/lib/app-utils/transfer-launcher-context.js.map +1 -1
- package/src/lib/data-transfer/access.d.ts +10 -18
- package/src/lib/data-transfer/access.js +21 -25
- package/src/lib/data-transfer/access.js.map +1 -1
- package/src/lib/data-transfer/resource.d.ts +13 -14
- package/src/lib/data-transfer/resource.js +9 -10
- package/src/lib/data-transfer/resource.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.js +3 -4
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/plugin-contact-capture.d.ts +10 -0
- package/src/lib/plugin-manager/plugin-contact-capture.js +11 -0
- package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
- package/src/lib/plugin-manager/plugin-entitlements.d.ts +12 -0
- package/src/lib/plugin-manager/plugin-entitlements.js +3 -1
- package/src/lib/plugin-manager/plugin-entitlements.js.map +1 -1
- package/src/lib/plugin-manager/plugin-scope-sharing.d.ts +52 -0
- package/src/lib/plugin-manager/plugin-scope-sharing.generated.d.ts +10 -0
- package/src/lib/plugin-manager/plugin-scope-sharing.generated.js +82 -0
- package/src/lib/plugin-manager/plugin-scope-sharing.generated.js.map +1 -0
- package/src/lib/plugin-manager/plugin-scope-sharing.js +85 -0
- package/src/lib/plugin-manager/plugin-scope-sharing.js.map +1 -0
- package/src/lib/plugin-manager/plugin-transfer-resources.d.ts +56 -1
- package/src/lib/plugin-manager/plugin-transfer-resources.js +13 -0
- package/src/lib/plugin-manager/plugin-transfer-resources.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/host-permissions.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 type {\n AglynOrgMember,\n HostAccessRole,\n HostPermissionKey,\n HostUid,\n OrgRole,\n} from '../foundation'\nimport { refinePermissionMap, type PermissionRefinement } from '../plugin-manager/plugin-permissions'\nimport { hostRoleFor, isOrgWideMember } from './organizations'\nimport { CORE_SITE_ROLE_PRESETS } from './org-role-grants'\nimport {\n permissionRefusalText,\n ORG_PERMISSION_REFINEMENTS,\n ORG_PERMISSIONS,\n resolveOrgPermissions,\n type AglynOrgCustomRole,\n type OrgPermissionDefinition,\n} from './org-permissions'\nimport { orgRoleTier } from './org-roles'\n\n/**\n * Catalog keys a site collaborator holds PER SITE (AGL-2984), resolved on one\n * of two axes.\n *\n * A plugin that declares a catalog key with `hostRoleDefaults` makes it a\n * per-site key. For the people whose membership spans the workspace, the key\n * is an ordinary catalog key: their org role's default, refined by a custom\n * role and by per-member overrides, the same on every site. A site\n * collaborator has no org standing to refine — their membership exists only\n * to carry access to named sites — so for them the key is decided PER SITE,\n * from the host role they hold there, refined by `hostPermissions[hostId]` on\n * their member document.\n *\n * Which axis applies is `isOrgWideMember`, the predicate the rules projection\n * and the scope resolver already share. A collaborator asked about a site\n * they were never granted resolves to nothing, and so does one whose request\n * names no site at all: there is no host role to read a default from, and\n * guessing one would let a request reach around the per-site toggle by\n * omitting the site.\n */\n\n/**\n * The catalog keys a collaborator can hold per site, in catalog order: every\n * key with host-role defaults, the core's site keys (AGL-4047) and the ones\n * plugins declare.\n */\nexport function hostPermissionKeys(): HostPermissionKey[] {\n return ORG_PERMISSIONS.filter((definition) => definition.hostRoleDefaults !== undefined).map(\n (definition) => definition.key,\n )\n}\n\n/**\n * What a host role grants a site collaborator for every per-site key, before\n * any toggle. A key whose site-role preset holds for members of the whole\n * workspace only (`workspaceMembersOnly`, AGL-4047) grants a collaborator\n * nothing, whatever their site role.\n */\nexport function hostRolePermissionDefaults(\n role: HostAccessRole,\n): Record<HostPermissionKey, boolean> {\n const defaults: Record<HostPermissionKey, boolean> = {}\n for (const definition of ORG_PERMISSIONS) {\n if (!definition.hostRoleDefaults) continue\n defaults[definition.key] = !definition.workspaceMembersOnly && definition.hostRoleDefaults[role] === true\n }\n return defaults\n}\n\n/** Every per-site key, refused. */\nfunction noHostPermissions(): Record<HostPermissionKey, boolean> {\n return Object.fromEntries(hostPermissionKeys().map((key) => [key, false]))\n}\n\n/**\n * The catalog's refinements whose key and broader key are both in `map`\n * (AGL-4047): the links a per-site map can settle on its own. A link to a\n * key the map does not carry would read that key as refused and add it.\n */\nfunction refinementsWithin(map: Readonly<Record<string, boolean>>): PermissionRefinement[] {\n return ORG_PERMISSION_REFINEMENTS.filter(([key, parent]) => key in map && parent in map)\n}\n\n/**\n * A collaborator's verdict on ONE site for every per-site key, or null where\n * they have no access to that site at all. An absent toggle reads as the host\n * role's default, which is what makes a member document written before\n * `hostPermissions` existed resolve exactly as it did before.\n */\nexport function resolveCollaboratorHostPermissions(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid | null | undefined,\n): Record<HostPermissionKey, boolean> | null {\n if (!member || !hostId) return null\n const role = hostRoleFor(member, hostId)\n if (!role) return null\n const merged = hostRolePermissionDefaults(role)\n const toggles = member.hostPermissions?.[hostId]\n if (toggles) {\n for (const key of Object.keys(merged)) {\n const value = toggles[key]\n if (typeof value === 'boolean') merged[key] = value\n }\n }\n // A per-site key that follows or refines another per-site key (AGL-4047)\n // takes its verdict from that key on this site where the site sets nothing\n // for it, as the org catalog's resolver does with a custom role.\n return refinePermissionMap(merged, refinementsWithin(merged), [toggles])\n}\n\n/*\n * KEYS WHOSE PRESET IS THE SITE ROLE (AGL-4047).\n *\n * Some checks were written against the member's role on a site: who may book\n * a walk-in, change a stay or edit a site's reservations asked whether their\n * `memberRoles` entry was Admin, Editor or Author. Roles are only presets of\n * permissions, so those checks became keys, and a key that replaces a gate\n * on the site role keeps that role as its preset (`presetFromSiteRole`):\n *\n * 1. the member's role ON THE SITE (`hostRoleFor`): Admin for the owner and\n * admins, a workspace-wide editor's or viewer's own role unless the site\n * gives them other access there, narrower or wider, and a collaborator's\n * site role; no access to the site holds nothing;\n * 2. that role's `hostRoleDefaults` verdict for the key;\n * 3. then, for a workspace-wide member, their custom role's verdict and\n * their own permissions' verdict, when either sets the key;\n * 4. then the site's own toggle for them (`hostPermissions[hostId][key]`).\n *\n * With nothing set at 3 or 4, the verdict is exactly what the role gate\n * answered, for every member on every site, which is how the built-in roles\n * keep the access they had. A collaborator has no custom role and no\n * workspace standing to refine, so only the site's toggle moves their\n * verdict, as for every other per-site key.\n *\n * A key declared `workspaceMembersOnly` replaces a gate that asked for an\n * admin of the whole workspace who is also this site's admin: its preset at\n * 2 is the site role's for a member of the whole workspace and refusal for a\n * collaborator, whose site role (even Admin) never carried it. The site's\n * toggle at 4 still grants it to them.\n *\n * These keys narrow nothing (`narrowsPerSite` is dropped): the site role is\n * already their preset. With no site named, the org catalog's verdict\n * (`roleDefaults`, then the layers) stands, which is the same answer for a\n * workspace-wide member on a site where their access is their workspace role.\n */\n\n/** The catalog keys whose preset is the member's role on the site, in catalog order. */\nexport function siteRolePresetPermissionKeys(): string[] {\n return ORG_PERMISSIONS.filter((definition) => definition.presetFromSiteRole).map(\n (definition) => definition.key,\n )\n}\n\n/** Is this a key whose preset is the member's role on the site? */\nexport function isSiteRolePresetPermission(permission: string): boolean {\n return ORG_PERMISSIONS.some(\n (definition) => definition.key === permission && definition.presetFromSiteRole === true,\n )\n}\n\n/**\n * A member's verdict on ONE site for every key whose preset is their role\n * there (see above). `customRole` is their custom role document when they\n * carry a `roleId` and the caller has it, and is ignored for a collaborator.\n * No site named, or no access to it, refuses every such key.\n */\nexport function resolveSiteRolePresetPermissions(\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null,\n): Record<string, boolean> {\n const definitions = ORG_PERMISSIONS.filter((definition) => definition.presetFromSiteRole)\n if (!definitions.length) return {}\n const role = member && hostId ? hostRoleFor(member, hostId) : null\n if (!member || !hostId || !role) {\n return Object.fromEntries(definitions.map((definition) => [definition.key, false]))\n }\n const toggles = member.hostPermissions?.[hostId]\n const workspaceMember = isOrgWideMember(member)\n const layers: ReadonlyArray<Readonly<Partial<Record<string, unknown>>> | null | undefined> =\n workspaceMember\n ? [member.roleId ? customRole?.permissions : undefined, member.permissions, toggles]\n : [toggles]\n const out: Record<string, boolean> = {}\n for (const definition of definitions) {\n let verdict =\n (workspaceMember || !definition.workspaceMembersOnly) && definition.hostRoleDefaults?.[role] === true\n for (const layer of layers) {\n const value = layer?.[definition.key]\n if (typeof value === 'boolean') verdict = value\n }\n out[definition.key] = verdict\n }\n return refinePermissionMap(out, refinementsWithin(out), layers)\n}\n\n/**\n * `granted` with every key whose preset is the site role decided for this\n * site. With no site named it is `granted` as given, so a resolver can call\n * it unconditionally.\n */\nexport function applySiteRolePresets<T extends Record<string, boolean>>(\n granted: T,\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null,\n): T {\n if (!hostId) return granted\n return { ...granted, ...resolveSiteRolePresetPermissions(member, hostId, customRole) }\n}\n\n/**\n * The verdict the site's own stamp gives a member for one key whose preset\n * is the site role, as the Firestore rules read it (AGL-4047): the site's\n * `memberPermissions[uid][key]` when the projection wrote one, else the\n * preset of the role the site's `memberRoles` projection holds for them.\n *\n * For a door that has the host document in hand and asks what the rules\n * ask, so the two cannot disagree: the stamp is written beside\n * `memberRoles` by the same projection, with every layer applied, and a\n * site the projection has not reached since the key existed answers exactly\n * as the role gate it replaced. `presetFor` is the declaring plugin's own\n * table, so the answer does not depend on which plugins this process loaded.\n */\nexport function hostStampedSitePermission(\n host: { memberPermissions?: unknown; memberRoles?: unknown } | null | undefined,\n uid: string,\n permission: string,\n presetFor: Readonly<Partial<Record<HostAccessRole, boolean>>>,\n): boolean {\n const stamped = (host?.memberPermissions as Record<string, Record<string, unknown> | undefined> | undefined)?.[uid]?.[\n permission\n ]\n if (typeof stamped === 'boolean') return stamped\n const role = (host?.memberRoles as Record<string, unknown> | undefined)?.[uid]\n return typeof role === 'string' && presetFor[role as HostAccessRole] === true\n}\n\n/**\n * The same for a key whose preset holds for members of the whole workspace\n * only (`workspaceMembersOnly`, AGL-4047), which `memberRoles` alone cannot\n * answer: an admin of one site and an admin of the whole workspace project\n * the same `'admin'` there. The site's stamp when the projection wrote one;\n * else the preset of the role `memberRoles` holds for them AND of the role\n * the fresh resolution gives them on the site, for a member of the whole\n * workspace only. Exactly the gate these keys replaced: the projection's\n * role, `orgWide` and the fresh site role, all three.\n */\nexport function hostStampedWorkspaceSitePermission(\n host: { memberPermissions?: unknown; memberRoles?: unknown } | null | undefined,\n uid: string,\n permission: string,\n presetFor: Readonly<Partial<Record<HostAccessRole, boolean>>>,\n membership: { orgWide: boolean; hostRole: string | null | undefined },\n): boolean {\n const stamped = (host?.memberPermissions as Record<string, Record<string, unknown> | undefined> | undefined)?.[uid]?.[\n permission\n ]\n if (typeof stamped === 'boolean') return stamped\n if (membership.orgWide !== true) return false\n const fresh = membership.hostRole\n return (\n typeof fresh === 'string' &&\n presetFor[fresh as HostAccessRole] === true &&\n hostStampedSitePermission({ memberRoles: host?.memberRoles }, uid, permission, presetFor)\n )\n}\n\n/*\n * A SITE NARROWS A WORKSPACE-WIDE MEMBER (AGL-4047).\n *\n * An editor who works across the workspace can be given Viewer or Author\n * access to one site (`hostAccess[hostId]`, which `hostRoleFor` reads ahead\n * of `allHosts`). That narrowed their content rights there and nothing else,\n * so a key the workspace grants an editor, such as working a site's\n * register, still held on the site they were narrowed on.\n *\n * A plugin marks the keys a site CAN narrow with `narrowsPerSite`, and\n * whether each one does is a control with three layers, the nearest set one\n * winning (`siteNarrowingChoices`):\n *\n * - the member's own choice (`member.siteNarrowing[key]`);\n * - else their custom role's (`customRole.siteNarrowing[key]`);\n * - else the built-in role's default the declaration names.\n *\n * `true` is \"Follow the site role\", `false` is \"Keep this permission\". On a\n * site that narrows the member, each key that follows the site role is\n * decided for that site:\n *\n * 1. the site's own verdict for the key (`hostPermissions[hostId][key]`),\n * when the site set one;\n * 2. else, for a key that refines another key that also follows the site\n * role, that key's verdict on this site, never more than the workspace\n * grants;\n * 3. else the narrower access's default for the key, never more than the\n * workspace grants;\n *\n * and a key they keep is the workspace's verdict, as everywhere else. A finer\n * key they hold on the site (one the site grants, or one they keep and the\n * workspace grants) brings the key it refines on this site with it, unless\n * the site refuses that key, because a refining key is never held without\n * it. The other finer keys do not follow that implied grant: allowing \"sell\"\n * on a site is not allowing refunds.\n *\n * A member whose access to every site matches their workspace role (the\n * owner and admins always do), one who keeps every key a site can narrow,\n * and a site collaborator, whose keys come from their site role already, all\n * resolve exactly as before.\n */\n\n/** Host roles from the widest down, for \"is this site's access narrower?\". */\nconst HOST_ROLE_RANK: Readonly<Record<HostAccessRole, number>> = {\n admin: 3,\n editor: 2,\n author: 1,\n viewer: 0,\n}\n\n/** How one site narrows a workspace-wide member: the access they hold there, the site's verdicts, and which keys follow it. */\nexport interface SiteNarrowing {\n /** Their role on the site, narrower than their workspace role. */\n role: HostAccessRole\n /** `hostPermissions[hostId]`: the verdicts the site set for them. */\n grants: Readonly<Partial<Record<string, unknown>>>\n /**\n * Every key a site can narrow, `true` where it follows the site role for\n * this member and `false` where they keep it (`siteNarrowingChoices`).\n */\n narrows: Readonly<Record<string, boolean>>\n}\n\n/** The catalog keys a site CAN narrow (`narrowsPerSite`), in catalog order. */\nexport function siteNarrowedPermissionKeys(): string[] {\n return ORG_PERMISSIONS.filter((definition) => definition.narrowsPerSite).map(\n (definition) => definition.key,\n )\n}\n\n/**\n * Could any site narrow a member of this org role? Not the owner or an\n * admin, who are admins of every site, and not a role whose site access has\n * nothing narrower below it (a viewer). The editors' control is the one that\n * changes anything; the role editor says so beside it.\n */\nexport function roleCanBeNarrowed(role: string | null | undefined): boolean {\n if (role === 'owner' || role === 'admin') return false\n return HOST_ROLE_RANK[orgRoleTier(role) as HostAccessRole] > 0\n}\n\n/**\n * Whether each key a site can narrow follows the site role for this member\n * (`true`) or is kept (`false`): their own choice, else their custom role's\n * (when they carry its id and it was supplied), else the built-in role's\n * default.\n */\nexport function siteNarrowingChoices(\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'siteNarrowing'> | null,\n): Record<string, boolean> {\n const role = (member?.role ?? 'viewer') as OrgRole\n const own = member?.siteNarrowing ?? {}\n const fromRole = member?.roleId ? (customRole?.siteNarrowing ?? {}) : {}\n const out: Record<string, boolean> = {}\n for (const definition of ORG_PERMISSIONS) {\n if (!definition.narrowsPerSite) continue\n const key = definition.key\n const mine = own[key]\n const theirRole = fromRole[key]\n out[key] =\n typeof mine === 'boolean'\n ? mine\n : typeof theirRole === 'boolean'\n ? theirRole\n : definition.narrowsPerSite[role] === true\n }\n return out\n}\n\n/**\n * Is this member's access to this site narrower than their workspace role?\n * The cheap half of `siteNarrowingFor`, which needs no custom role: a caller\n * that has to read one asks this first, and reads nothing for everyone else.\n */\nexport function siteMayNarrow(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid | null | undefined,\n): HostAccessRole | null {\n if (!member || !hostId || !isOrgWideMember(member)) return null\n const role = hostRoleFor(member, hostId)\n if (!role) return null\n const workspaceRole = orgRoleTier(member.role) as HostAccessRole\n if (HOST_ROLE_RANK[role] >= HOST_ROLE_RANK[workspaceRole]) return null\n return role\n}\n\n/**\n * How this site narrows this member, or null where it does not: a member\n * who is not workspace-wide, has no access to the site, whose access there\n * is as wide as their workspace role (owners and admins always), or who\n * keeps every key a site can narrow. `customRole` is their custom role\n * document when they carry a `roleId`; without it, only their own choices\n * and the built-in defaults decide.\n */\nexport function siteNarrowingFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'siteNarrowing'> | null,\n): SiteNarrowing | null {\n const role = siteMayNarrow(member, hostId)\n if (!role) return null\n const narrows = siteNarrowingChoices(member, customRole)\n if (!Object.values(narrows).some(Boolean)) return null\n return { role, grants: member?.hostPermissions?.[hostId as HostUid] ?? {}, narrows }\n}\n\n/** The keys that follow the site role under a narrowing, in catalog order; none without one. */\nexport function narrowedPermissionKeysOf(narrowing: SiteNarrowing | null | undefined): string[] {\n if (!narrowing) return []\n return siteNarrowedPermissionKeys().filter((key) => narrowing.narrows[key] === true)\n}\n\n/** What a site access holds by default for a key: its site default, else its tier's (Author on the Viewer tier). */\nfunction narrowedDefault(definition: OrgPermissionDefinition, role: HostAccessRole): boolean {\n const site = definition.hostRoleDefaults?.[role]\n if (typeof site === 'boolean') return site\n return definition.roleDefaults[orgRoleTier(role)] === true\n}\n\n/**\n * A workspace-wide member's resolved map with the keys that follow the site\n * role decided for that site (see above). With no narrowing it is the map\n * as given, so every resolver can call it unconditionally.\n */\nexport function narrowPermissionsToSite<T extends Record<string, boolean>>(\n granted: T,\n narrowing: SiteNarrowing | null | undefined,\n): T {\n if (!narrowing) return granted\n const definitions = ORG_PERMISSIONS.filter((definition) => definition.narrowsPerSite)\n if (!definitions.length) return granted\n const narrowable = new Set(definitions.map((definition) => definition.key))\n const follows = (key: string): boolean => narrowing.narrows[key] === true\n // A finer key's broader key, among the keys a site can narrow.\n const broader = new Map<string, string>()\n for (const [key, parent, kind] of ORG_PERMISSION_REFINEMENTS) {\n if (kind !== 'follows' && narrowable.has(key) && narrowable.has(parent)) broader.set(key, parent)\n }\n const siteVerdict = (key: string): boolean | undefined => {\n const value = narrowing.grants[key]\n return typeof value === 'boolean' ? value : undefined\n }\n const depth = (key: string): number => {\n const seen = new Set<string>()\n let steps = 0\n for (let current = key; broader.has(current) && !seen.has(current); steps += 1) {\n seen.add(current)\n current = broader.get(current) as string\n }\n return steps\n }\n const out: Record<string, boolean> = { ...granted }\n for (const definition of [...definitions].sort((a, b) => depth(a.key) - depth(b.key))) {\n const key = definition.key\n const workspace = granted[key] === true\n // Kept: the workspace's verdict, as on every other site.\n if (!follows(key)) {\n out[key] = workspace\n continue\n }\n const own = siteVerdict(key)\n const parent = broader.get(key)\n if (own !== undefined) out[key] = own\n else if (parent && follows(parent)) out[key] = out[parent] === true && workspace\n else out[key] = workspace && narrowedDefault(definition, narrowing.role)\n }\n for (const definition of definitions) {\n const key = definition.key\n const held = follows(key) ? siteVerdict(key) === true : granted[key] === true\n if (!held) continue\n const seen = new Set<string>()\n for (let parent = broader.get(key); parent && !seen.has(parent); parent = broader.get(parent)) {\n seen.add(parent)\n // A kept broader key is the workspace's verdict already.\n if (!follows(parent) || siteVerdict(parent) === false) break\n out[parent] = true\n }\n }\n return refinePermissionMap(out, ORG_PERMISSION_REFINEMENTS) as T\n}\n\n/**\n * A member's verdict for every per-site key, on whichever axis their\n * membership is on.\n *\n * `customRole` is the member's custom role document when they carry a\n * `roleId` and the caller has it in hand, and is ignored for a collaborator,\n * whose org role is a seat-accounting fact rather than a grant. `hostId` is\n * the site the request is about; an org-wide member resolves the same on\n * every site and with none named, except on a site that narrows them.\n *\n * An org-wide member's map also carries every key a site can narrow\n * (AGL-4047), decided for `hostId`, so the site's `memberPermissions`\n * projection answers the rules what the server answers. A collaborator's\n * map does not: their register and waivers keys come from their site role\n * and their own overrides, which the rules read from their member document\n * as before.\n */\nexport function resolveMemberHostPermissions(options: {\n member: Partial<AglynOrgMember> | null | undefined\n customRole?: AglynOrgCustomRole | null\n hostId?: HostUid | null\n}): Record<HostPermissionKey, boolean> {\n const { member, customRole, hostId } = options\n if (!member) return noHostPermissions()\n if (isOrgWideMember(member)) {\n // The keys whose preset is the site role (AGL-4047) are decided for this\n // site last; they narrow nothing, so the narrowing pass leaves them be.\n const granted = applySiteRolePresets(\n narrowPermissionsToSite(\n resolveOrgPermissions(member, customRole ?? null),\n siteNarrowingFor(member, hostId, customRole ?? null),\n ),\n member,\n hostId,\n customRole ?? null,\n )\n return Object.fromEntries(\n [...hostPermissionKeys(), ...siteNarrowedPermissionKeys()].map((key) => [key, granted[key] === true]),\n )\n }\n return resolveCollaboratorHostPermissions(member, hostId) ?? noHostPermissions()\n}\n\n/**\n * The `memberPermissions` projection stamped on a host document beside\n * `memberRoles`: every member who can reach the site, with the verdict for\n * every per-site key they hold ON it. Org-wide members are resolved against\n * the custom roles the caller loaded (one read per distinct role, as\n * `syncOrgAuthProjections` already does for `resolvedPermissions`);\n * collaborators against their host role. A member who cannot reach the site\n * has no entry, matching `projectHostMemberRoles`.\n */\nexport function projectHostMemberPermissions(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n customRoles: ReadonlyMap<string, AglynOrgCustomRole | null>,\n): Record<string, Record<HostPermissionKey, boolean>> {\n const projection: Record<string, Record<HostPermissionKey, boolean>> = {}\n for (const member of members) {\n if (!hostRoleFor(member, hostId)) continue\n projection[member.$id] = resolveMemberHostPermissions({\n member,\n customRole: member.roleId ? (customRoles.get(member.roleId) ?? null) : null,\n hostId,\n })\n }\n return projection\n}\n\n/** The core's site keys (AGL-4047): `CORE_SITE_ROLE_PRESETS`. */\nexport type CoreSiteKey = 'site.edit' | 'site.publish' | 'site.sensitive' | 'site.manage'\n\n/** A host document, as a snapshot (`get`) or as its data. */\nexport type HostDocumentLike =\n | { get(field: string): unknown }\n | { memberPermissions?: unknown; memberRoles?: unknown }\n | null\n | undefined\n\n/**\n * Does this member hold one of the core's site keys on this site (AGL-4047)?\n * The door's twin of the rules' `canWriteHostContent`,\n * `canPublishHostContent`, `canReadHostSensitive` and site-settings checks:\n * the site's `memberPermissions` stamp, else the preset of the member's\n * `memberRoles` entry (`hostStampedSitePermission`), so a route that asks it\n * answers what the rules answer for the same write. For the routes that read\n * the host document already; it costs no read.\n */\nexport function holdsSiteKey(hostDoc: HostDocumentLike, uid: string, key: CoreSiteKey): boolean {\n return holdsStampedSiteKey(hostDoc, uid, key, CORE_SITE_ROLE_PRESETS[key] ?? {})\n}\n\n/**\n * The same for a plugin's key whose preset is the site role (AGL-4047): the\n * site's `memberPermissions` stamp, else `presetFor` read for the member's\n * `memberRoles` entry. `presetFor` is the declaring plugin's own table, so the\n * answer does not depend on which plugins this process loaded. For the doors\n * and the cards that hold the host document already; it costs no read.\n */\nexport function holdsStampedSiteKey(\n hostDoc: HostDocumentLike,\n uid: string | null | undefined,\n key: string,\n presetFor: Readonly<Partial<Record<HostAccessRole, boolean>>>,\n): boolean {\n if (!hostDoc || !uid) return false\n // `hostDoc`, not `host`: the host-field deny guard reads every `host.…`\n // in this folder as a field of the host document, and `get` is none.\n const read = (field: string): unknown =>\n typeof (hostDoc as { get?: unknown }).get === 'function'\n ? (hostDoc as { get(field: string): unknown }).get(field)\n : (hostDoc as Record<string, unknown>)[field]\n return hostStampedSitePermission(\n { memberPermissions: read('memberPermissions'), memberRoles: read('memberRoles') },\n uid,\n key,\n presetFor,\n )\n}\n\n/**\n * The refusal a door answers when a member does not hold a site key\n * (AGL-4047): it names the permission and who can change it, never a role.\n */\nexport function siteKeyRefusal(key: string): string {\n return permissionRefusalText(key)\n}\n\n"],"names":["refinePermissionMap","hostRoleFor","isOrgWideMember","CORE_SITE_ROLE_PRESETS","permissionRefusalText","ORG_PERMISSION_REFINEMENTS","ORG_PERMISSIONS","resolveOrgPermissions","orgRoleTier","hostPermissionKeys","filter","definition","hostRoleDefaults","undefined","map","key","hostRolePermissionDefaults","role","defaults","workspaceMembersOnly","noHostPermissions","Object","fromEntries","refinementsWithin","parent","resolveCollaboratorHostPermissions","member","hostId","merged","toggles","hostPermissions","keys","value","siteRolePresetPermissionKeys","presetFromSiteRole","isSiteRolePresetPermission","permission","some","resolveSiteRolePresetPermissions","customRole","definitions","length","workspaceMember","layers","roleId","permissions","out","verdict","layer","applySiteRolePresets","granted","hostStampedSitePermission","host","uid","presetFor","stamped","memberPermissions","memberRoles","hostStampedWorkspaceSitePermission","membership","orgWide","fresh","hostRole","HOST_ROLE_RANK","admin","editor","author","viewer","siteNarrowedPermissionKeys","narrowsPerSite","roleCanBeNarrowed","siteNarrowingChoices","own","siteNarrowing","fromRole","mine","theirRole","siteMayNarrow","workspaceRole","siteNarrowingFor","narrows","values","Boolean","grants","narrowedPermissionKeysOf","narrowing","narrowedDefault","site","roleDefaults","narrowPermissionsToSite","narrowable","Set","follows","broader","Map","kind","has","set","siteVerdict","depth","seen","steps","current","add","get","sort","a","b","workspace","held","resolveMemberHostPermissions","options","projectHostMemberPermissions","members","customRoles","projection","$id","holdsSiteKey","hostDoc","holdsStampedSiteKey","read","field","siteKeyRefusal"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AASD,SAASA,mBAAmB,QAAmC,0CAAsC;AACrG,SAASC,WAAW,EAAEC,eAAe,QAAQ,qBAAiB;AAC9D,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,qBAAqB,EACrBC,0BAA0B,EAC1BC,eAAe,EACfC,qBAAqB,QAGhB,uBAAmB;AAC1B,SAASC,WAAW,QAAQ,iBAAa;AAEzC;;;;;;;;;;;;;;;;;;;CAmBC,GAED;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAOH,gBAAgBI,MAAM,CAAC,CAACC,aAAeA,WAAWC,gBAAgB,KAAKC,WAAWC,GAAG,CAC1F,CAACH,aAAeA,WAAWI,GAAG;AAElC;AAEA;;;;;CAKC,GACD,OAAO,SAASC,2BACdC,IAAoB;IAEpB,MAAMC,WAA+C,CAAC;IACtD,KAAK,MAAMP,cAAcL,gBAAiB;QACxC,IAAI,CAACK,WAAWC,gBAAgB,EAAE;QA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lib/app-utils/host-permissions.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 type {\n AglynOrgMember,\n HostAccessRole,\n HostPermissionKey,\n HostUid,\n OrgRole,\n} from '../foundation'\nimport { refinePermissionMap, type PermissionRefinement } from '../plugin-manager/plugin-permissions'\nimport { hostRoleFor, isOrgWideMember } from './organizations'\nimport { CORE_SITE_ROLE_PRESETS } from './org-role-grants'\nimport {\n permissionRefusalText,\n ORG_PERMISSION_REFINEMENTS,\n ORG_PERMISSIONS,\n resolveOrgPermissions,\n type AglynOrgCustomRole,\n type OrgPermissionDefinition,\n} from './org-permissions'\nimport { orgRoleTier } from './org-roles'\n\n/**\n * Catalog keys a site collaborator holds PER SITE (AGL-2984), resolved on one\n * of two axes.\n *\n * A plugin that declares a catalog key with `hostRoleDefaults` makes it a\n * per-site key. For the people whose membership spans the workspace, the key\n * is an ordinary catalog key: their org role's default, refined by a custom\n * role and by per-member overrides, the same on every site. A site\n * collaborator has no org standing to refine — their membership exists only\n * to carry access to named sites — so for them the key is decided PER SITE,\n * from the host role they hold there, refined by `hostPermissions[hostId]` on\n * their member document.\n *\n * Which axis applies is `isOrgWideMember`, the predicate the rules projection\n * and the scope resolver already share. A collaborator asked about a site\n * they were never granted resolves to nothing, and so does one whose request\n * names no site at all: there is no host role to read a default from, and\n * guessing one would let a request reach around the per-site toggle by\n * omitting the site.\n */\n\n/**\n * The catalog keys a collaborator can hold per site, in catalog order: every\n * key with host-role defaults, the core's site keys (AGL-4047) and the ones\n * plugins declare.\n */\nexport function hostPermissionKeys(): HostPermissionKey[] {\n return ORG_PERMISSIONS.filter((definition) => definition.hostRoleDefaults !== undefined).map(\n (definition) => definition.key,\n )\n}\n\n/**\n * What a host role grants a site collaborator for every per-site key, before\n * any toggle. A key whose site-role preset holds for members of the whole\n * workspace only (`workspaceMembersOnly`, AGL-4047) grants a collaborator\n * nothing, whatever their site role.\n */\nexport function hostRolePermissionDefaults(\n role: HostAccessRole,\n): Record<HostPermissionKey, boolean> {\n const defaults: Record<HostPermissionKey, boolean> = {}\n for (const definition of ORG_PERMISSIONS) {\n if (!definition.hostRoleDefaults) continue\n defaults[definition.key] = !definition.workspaceMembersOnly && definition.hostRoleDefaults[role] === true\n }\n return defaults\n}\n\n/** Every per-site key, refused. */\nfunction noHostPermissions(): Record<HostPermissionKey, boolean> {\n return Object.fromEntries(hostPermissionKeys().map((key) => [key, false]))\n}\n\n/**\n * The catalog's refinements whose key and broader key are both in `map`\n * (AGL-4047): the links a per-site map can settle on its own. A link to a\n * key the map does not carry would read that key as refused and add it.\n */\nfunction refinementsWithin(map: Readonly<Record<string, boolean>>): PermissionRefinement[] {\n return ORG_PERMISSION_REFINEMENTS.filter(([key, parent]) => key in map && parent in map)\n}\n\n/**\n * A collaborator's verdict on ONE site for every per-site key, or null where\n * they have no access to that site at all. An absent toggle reads as the host\n * role's default, which is what makes a member document written before\n * `hostPermissions` existed resolve exactly as it did before.\n */\nexport function resolveCollaboratorHostPermissions(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid | null | undefined,\n): Record<HostPermissionKey, boolean> | null {\n if (!member || !hostId) return null\n const role = hostRoleFor(member, hostId)\n if (!role) return null\n const merged = hostRolePermissionDefaults(role)\n const toggles = member.hostPermissions?.[hostId]\n if (toggles) {\n for (const key of Object.keys(merged)) {\n const value = toggles[key]\n if (typeof value === 'boolean') merged[key] = value\n }\n }\n // A per-site key that follows or refines another per-site key (AGL-4047)\n // takes its verdict from that key on this site where the site sets nothing\n // for it, as the org catalog's resolver does with a custom role.\n return refinePermissionMap(merged, refinementsWithin(merged), [toggles])\n}\n\n/*\n * KEYS WHOSE PRESET IS THE SITE ROLE (AGL-4047).\n *\n * Some checks were written against the member's role on a site: who may book\n * a walk-in, change a stay or edit a site's reservations asked whether their\n * `memberRoles` entry was Admin, Editor or Author. Roles are only presets of\n * permissions, so those checks became keys, and a key that replaces a gate\n * on the site role keeps that role as its preset (`presetFromSiteRole`):\n *\n * 1. the member's role ON THE SITE (`hostRoleFor`): Admin for the owner and\n * admins, a workspace-wide editor's or viewer's own role unless the site\n * gives them other access there, narrower or wider, and a collaborator's\n * site role; no access to the site holds nothing;\n * 2. that role's `hostRoleDefaults` verdict for the key;\n * 3. then, for a workspace-wide member, their custom role's verdict and\n * their own permissions' verdict, when either sets the key;\n * 4. then the site's own toggle for them (`hostPermissions[hostId][key]`).\n *\n * With nothing set at 3 or 4, the verdict is exactly what the role gate\n * answered, for every member on every site, which is how the built-in roles\n * keep the access they had. A collaborator has no custom role and no\n * workspace standing to refine, so only the site's toggle moves their\n * verdict, as for every other per-site key.\n *\n * A key declared `workspaceMembersOnly` replaces a gate that asked for an\n * admin of the whole workspace who is also this site's admin: its preset at\n * 2 is the site role's for a member of the whole workspace and refusal for a\n * collaborator, whose site role (even Admin) never carried it. The site's\n * toggle at 4 still grants it to them.\n *\n * These keys narrow nothing (`narrowsPerSite` is dropped): the site role is\n * already their preset. With no site named, the org catalog's verdict\n * (`roleDefaults`, then the layers) stands, which is the same answer for a\n * workspace-wide member on a site where their access is their workspace role.\n */\n\n/** The catalog keys whose preset is the member's role on the site, in catalog order. */\nexport function siteRolePresetPermissionKeys(): string[] {\n return ORG_PERMISSIONS.filter((definition) => definition.presetFromSiteRole).map(\n (definition) => definition.key,\n )\n}\n\n/** Is this a key whose preset is the member's role on the site? */\nexport function isSiteRolePresetPermission(permission: string): boolean {\n return ORG_PERMISSIONS.some(\n (definition) => definition.key === permission && definition.presetFromSiteRole === true,\n )\n}\n\n/**\n * A member's verdict on ONE site for every key whose preset is their role\n * there (see above). `customRole` is their custom role document when they\n * carry a `roleId` and the caller has it, and is ignored for a collaborator.\n * No site named, or no access to it, refuses every such key.\n */\nexport function resolveSiteRolePresetPermissions(\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null,\n): Record<string, boolean> {\n const definitions = ORG_PERMISSIONS.filter((definition) => definition.presetFromSiteRole)\n if (!definitions.length) return {}\n const role = member && hostId ? hostRoleFor(member, hostId) : null\n if (!member || !hostId || !role) {\n return Object.fromEntries(definitions.map((definition) => [definition.key, false]))\n }\n const toggles = member.hostPermissions?.[hostId]\n const workspaceMember = isOrgWideMember(member)\n const layers: ReadonlyArray<Readonly<Partial<Record<string, unknown>>> | null | undefined> =\n workspaceMember\n ? [member.roleId ? customRole?.permissions : undefined, member.permissions, toggles]\n : [toggles]\n const out: Record<string, boolean> = {}\n for (const definition of definitions) {\n let verdict =\n (workspaceMember || !definition.workspaceMembersOnly) && definition.hostRoleDefaults?.[role] === true\n for (const layer of layers) {\n const value = layer?.[definition.key]\n if (typeof value === 'boolean') verdict = value\n }\n out[definition.key] = verdict\n }\n return refinePermissionMap(out, refinementsWithin(out), layers)\n}\n\n/**\n * `granted` with every key whose preset is the site role decided for this\n * site. With no site named it is `granted` as given, so a resolver can call\n * it unconditionally.\n */\nexport function applySiteRolePresets<T extends Record<string, boolean>>(\n granted: T,\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null,\n): T {\n if (!hostId) return granted\n return {\n ...granted,\n ...resolveSiteRolePresetPermissions(member, hostId, customRole),\n ...resolveSiteRaisedPermissions(member, hostId, customRole),\n }\n}\n\n/**\n * The keys a site RAISES for a member of the whole workspace (AGL-4047): on a\n * site where their access is wider than their workspace role, each\n * `raisesPerSite` key they hold by that access's `hostRoleDefaults`. Only the\n * keys it raises are in the answer, so a resolver spreads it over what the\n * workspace already answered. A custom role or their own permissions deciding\n * the key, or the key it follows, stands: a raise is a default, never a way\n * round a decision someone wrote down.\n */\nexport function resolveSiteRaisedPermissions(\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null,\n): Record<string, boolean> {\n const out: Record<string, boolean> = {}\n if (!member || !hostId || !isOrgWideMember(member)) return out\n const role = hostRoleFor(member, hostId)\n if (!role || HOST_ROLE_RANK[role] <= HOST_ROLE_RANK[orgRoleTier(member.role) as HostAccessRole]) return out\n const layers = [member.roleId ? customRole?.permissions : undefined, member.permissions]\n const decided = (key: string | undefined): boolean =>\n Boolean(key) && layers.some((layer) => typeof (layer as Record<string, unknown> | undefined)?.[key as string] === 'boolean')\n for (const definition of ORG_PERMISSIONS) {\n if (!definition.raisesPerSite || decided(definition.key) || decided(definition.follows)) continue\n if (definition.hostRoleDefaults?.[role] === true) out[definition.key] = true\n }\n return out\n}\n\n/**\n * The verdict the site's own stamp gives a member for one key whose preset\n * is the site role, as the Firestore rules read it (AGL-4047): the site's\n * `memberPermissions[uid][key]` when the projection wrote one, else the\n * preset of the role the site's `memberRoles` projection holds for them.\n *\n * For a door that has the host document in hand and asks what the rules\n * ask, so the two cannot disagree: the stamp is written beside\n * `memberRoles` by the same projection, with every layer applied, and a\n * site the projection has not reached since the key existed answers exactly\n * as the role gate it replaced. `presetFor` is the declaring plugin's own\n * table, so the answer does not depend on which plugins this process loaded.\n */\nexport function hostStampedSitePermission(\n host: { memberPermissions?: unknown; memberRoles?: unknown } | null | undefined,\n uid: string,\n permission: string,\n presetFor: Readonly<Partial<Record<HostAccessRole, boolean>>>,\n): boolean {\n const stamped = (host?.memberPermissions as Record<string, Record<string, unknown> | undefined> | undefined)?.[uid]?.[\n permission\n ]\n if (typeof stamped === 'boolean') return stamped\n const role = (host?.memberRoles as Record<string, unknown> | undefined)?.[uid]\n return typeof role === 'string' && presetFor[role as HostAccessRole] === true\n}\n\n/**\n * The same for a key whose preset holds for members of the whole workspace\n * only (`workspaceMembersOnly`, AGL-4047), which `memberRoles` alone cannot\n * answer: an admin of one site and an admin of the whole workspace project\n * the same `'admin'` there. The site's stamp when the projection wrote one;\n * else the preset of the role `memberRoles` holds for them AND of the role\n * the fresh resolution gives them on the site, for a member of the whole\n * workspace only. Exactly the gate these keys replaced: the projection's\n * role, `orgWide` and the fresh site role, all three.\n */\nexport function hostStampedWorkspaceSitePermission(\n host: { memberPermissions?: unknown; memberRoles?: unknown } | null | undefined,\n uid: string,\n permission: string,\n presetFor: Readonly<Partial<Record<HostAccessRole, boolean>>>,\n membership: { orgWide: boolean; hostRole: string | null | undefined },\n): boolean {\n const stamped = (host?.memberPermissions as Record<string, Record<string, unknown> | undefined> | undefined)?.[uid]?.[\n permission\n ]\n if (typeof stamped === 'boolean') return stamped\n if (membership.orgWide !== true) return false\n const fresh = membership.hostRole\n return (\n typeof fresh === 'string' &&\n presetFor[fresh as HostAccessRole] === true &&\n hostStampedSitePermission({ memberRoles: host?.memberRoles }, uid, permission, presetFor)\n )\n}\n\n/*\n * A SITE NARROWS A WORKSPACE-WIDE MEMBER (AGL-4047).\n *\n * An editor who works across the workspace can be given Viewer or Author\n * access to one site (`hostAccess[hostId]`, which `hostRoleFor` reads ahead\n * of `allHosts`). That narrowed their content rights there and nothing else,\n * so a key the workspace grants an editor, such as working a site's\n * register, still held on the site they were narrowed on.\n *\n * A plugin marks the keys a site CAN narrow with `narrowsPerSite`, and\n * whether each one does is a control with three layers, the nearest set one\n * winning (`siteNarrowingChoices`):\n *\n * - the member's own choice (`member.siteNarrowing[key]`);\n * - else their custom role's (`customRole.siteNarrowing[key]`);\n * - else the built-in role's default the declaration names.\n *\n * `true` is \"Follow the site role\", `false` is \"Keep this permission\". On a\n * site that narrows the member, each key that follows the site role is\n * decided for that site:\n *\n * 1. the site's own verdict for the key (`hostPermissions[hostId][key]`),\n * when the site set one;\n * 2. else, for a key that refines another key that also follows the site\n * role, that key's verdict on this site, never more than the workspace\n * grants;\n * 3. else the narrower access's default for the key, never more than the\n * workspace grants;\n *\n * and a key they keep is the workspace's verdict, as everywhere else. A finer\n * key they hold on the site (one the site grants, or one they keep and the\n * workspace grants) brings the key it refines on this site with it, unless\n * the site refuses that key, because a refining key is never held without\n * it. The other finer keys do not follow that implied grant: allowing \"sell\"\n * on a site is not allowing refunds.\n *\n * A member whose access to every site matches their workspace role (the\n * owner and admins always do), one who keeps every key a site can narrow,\n * and a site collaborator, whose keys come from their site role already, all\n * resolve exactly as before.\n */\n\n/** Host roles from the widest down, for \"is this site's access narrower?\". */\nconst HOST_ROLE_RANK: Readonly<Record<HostAccessRole, number>> = {\n admin: 3,\n editor: 2,\n author: 1,\n viewer: 0,\n}\n\n/** How one site narrows a workspace-wide member: the access they hold there, the site's verdicts, and which keys follow it. */\nexport interface SiteNarrowing {\n /** Their role on the site, narrower than their workspace role. */\n role: HostAccessRole\n /** `hostPermissions[hostId]`: the verdicts the site set for them. */\n grants: Readonly<Partial<Record<string, unknown>>>\n /**\n * Every key a site can narrow, `true` where it follows the site role for\n * this member and `false` where they keep it (`siteNarrowingChoices`).\n */\n narrows: Readonly<Record<string, boolean>>\n}\n\n/** The catalog keys a site CAN narrow (`narrowsPerSite`), in catalog order. */\nexport function siteNarrowedPermissionKeys(): string[] {\n return ORG_PERMISSIONS.filter((definition) => definition.narrowsPerSite).map(\n (definition) => definition.key,\n )\n}\n\n/**\n * Could any site narrow a member of this org role? Not the owner or an\n * admin, who are admins of every site, and not a role whose site access has\n * nothing narrower below it (a viewer). The editors' control is the one that\n * changes anything; the role editor says so beside it.\n */\nexport function roleCanBeNarrowed(role: string | null | undefined): boolean {\n if (role === 'owner' || role === 'admin') return false\n return HOST_ROLE_RANK[orgRoleTier(role) as HostAccessRole] > 0\n}\n\n/**\n * Whether each key a site can narrow follows the site role for this member\n * (`true`) or is kept (`false`): their own choice, else their custom role's\n * (when they carry its id and it was supplied), else the built-in role's\n * default.\n */\nexport function siteNarrowingChoices(\n member: (Partial<AglynOrgMember> & { roleId?: string | null }) | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'siteNarrowing'> | null,\n): Record<string, boolean> {\n const role = (member?.role ?? 'viewer') as OrgRole\n const own = member?.siteNarrowing ?? {}\n const fromRole = member?.roleId ? (customRole?.siteNarrowing ?? {}) : {}\n const out: Record<string, boolean> = {}\n for (const definition of ORG_PERMISSIONS) {\n if (!definition.narrowsPerSite) continue\n const key = definition.key\n const mine = own[key]\n const theirRole = fromRole[key]\n out[key] =\n typeof mine === 'boolean'\n ? mine\n : typeof theirRole === 'boolean'\n ? theirRole\n : definition.narrowsPerSite[role] === true\n }\n return out\n}\n\n/**\n * Is this member's access to this site narrower than their workspace role?\n * The cheap half of `siteNarrowingFor`, which needs no custom role: a caller\n * that has to read one asks this first, and reads nothing for everyone else.\n */\nexport function siteMayNarrow(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid | null | undefined,\n): HostAccessRole | null {\n if (!member || !hostId || !isOrgWideMember(member)) return null\n const role = hostRoleFor(member, hostId)\n if (!role) return null\n const workspaceRole = orgRoleTier(member.role) as HostAccessRole\n if (HOST_ROLE_RANK[role] >= HOST_ROLE_RANK[workspaceRole]) return null\n return role\n}\n\n/**\n * How this site narrows this member, or null where it does not: a member\n * who is not workspace-wide, has no access to the site, whose access there\n * is as wide as their workspace role (owners and admins always), or who\n * keeps every key a site can narrow. `customRole` is their custom role\n * document when they carry a `roleId`; without it, only their own choices\n * and the built-in defaults decide.\n */\nexport function siteNarrowingFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid | null | undefined,\n customRole?: Pick<AglynOrgCustomRole, 'siteNarrowing'> | null,\n): SiteNarrowing | null {\n const role = siteMayNarrow(member, hostId)\n if (!role) return null\n const narrows = siteNarrowingChoices(member, customRole)\n if (!Object.values(narrows).some(Boolean)) return null\n return { role, grants: member?.hostPermissions?.[hostId as HostUid] ?? {}, narrows }\n}\n\n/** The keys that follow the site role under a narrowing, in catalog order; none without one. */\nexport function narrowedPermissionKeysOf(narrowing: SiteNarrowing | null | undefined): string[] {\n if (!narrowing) return []\n return siteNarrowedPermissionKeys().filter((key) => narrowing.narrows[key] === true)\n}\n\n/** What a site access holds by default for a key: its site default, else its tier's (Author on the Viewer tier). */\nfunction narrowedDefault(definition: OrgPermissionDefinition, role: HostAccessRole): boolean {\n const site = definition.hostRoleDefaults?.[role]\n if (typeof site === 'boolean') return site\n return definition.roleDefaults[orgRoleTier(role)] === true\n}\n\n/**\n * A workspace-wide member's resolved map with the keys that follow the site\n * role decided for that site (see above). With no narrowing it is the map\n * as given, so every resolver can call it unconditionally.\n */\nexport function narrowPermissionsToSite<T extends Record<string, boolean>>(\n granted: T,\n narrowing: SiteNarrowing | null | undefined,\n): T {\n if (!narrowing) return granted\n const definitions = ORG_PERMISSIONS.filter((definition) => definition.narrowsPerSite)\n if (!definitions.length) return granted\n const narrowable = new Set(definitions.map((definition) => definition.key))\n const follows = (key: string): boolean => narrowing.narrows[key] === true\n // A finer key's broader key, among the keys a site can narrow.\n const broader = new Map<string, string>()\n for (const [key, parent, kind] of ORG_PERMISSION_REFINEMENTS) {\n if (kind !== 'follows' && narrowable.has(key) && narrowable.has(parent)) broader.set(key, parent)\n }\n const siteVerdict = (key: string): boolean | undefined => {\n const value = narrowing.grants[key]\n return typeof value === 'boolean' ? value : undefined\n }\n const depth = (key: string): number => {\n const seen = new Set<string>()\n let steps = 0\n for (let current = key; broader.has(current) && !seen.has(current); steps += 1) {\n seen.add(current)\n current = broader.get(current) as string\n }\n return steps\n }\n const out: Record<string, boolean> = { ...granted }\n for (const definition of [...definitions].sort((a, b) => depth(a.key) - depth(b.key))) {\n const key = definition.key\n const workspace = granted[key] === true\n // Kept: the workspace's verdict, as on every other site.\n if (!follows(key)) {\n out[key] = workspace\n continue\n }\n const own = siteVerdict(key)\n const parent = broader.get(key)\n if (own !== undefined) out[key] = own\n else if (parent && follows(parent)) out[key] = out[parent] === true && workspace\n else out[key] = workspace && narrowedDefault(definition, narrowing.role)\n }\n for (const definition of definitions) {\n const key = definition.key\n const held = follows(key) ? siteVerdict(key) === true : granted[key] === true\n if (!held) continue\n const seen = new Set<string>()\n for (let parent = broader.get(key); parent && !seen.has(parent); parent = broader.get(parent)) {\n seen.add(parent)\n // A kept broader key is the workspace's verdict already.\n if (!follows(parent) || siteVerdict(parent) === false) break\n out[parent] = true\n }\n }\n return refinePermissionMap(out, ORG_PERMISSION_REFINEMENTS) as T\n}\n\n/**\n * A member's verdict for every per-site key, on whichever axis their\n * membership is on.\n *\n * `customRole` is the member's custom role document when they carry a\n * `roleId` and the caller has it in hand, and is ignored for a collaborator,\n * whose org role is a seat-accounting fact rather than a grant. `hostId` is\n * the site the request is about; an org-wide member resolves the same on\n * every site and with none named, except on a site that narrows them.\n *\n * An org-wide member's map also carries every key a site can narrow\n * (AGL-4047), decided for `hostId`, so the site's `memberPermissions`\n * projection answers the rules what the server answers. A collaborator's\n * map does not: their register and waivers keys come from their site role\n * and their own overrides, which the rules read from their member document\n * as before.\n */\nexport function resolveMemberHostPermissions(options: {\n member: Partial<AglynOrgMember> | null | undefined\n customRole?: AglynOrgCustomRole | null\n hostId?: HostUid | null\n}): Record<HostPermissionKey, boolean> {\n const { member, customRole, hostId } = options\n if (!member) return noHostPermissions()\n if (isOrgWideMember(member)) {\n // The keys whose preset is the site role (AGL-4047) are decided for this\n // site last; they narrow nothing, so the narrowing pass leaves them be.\n const granted = applySiteRolePresets(\n narrowPermissionsToSite(\n resolveOrgPermissions(member, customRole ?? null),\n siteNarrowingFor(member, hostId, customRole ?? null),\n ),\n member,\n hostId,\n customRole ?? null,\n )\n return Object.fromEntries(\n [...hostPermissionKeys(), ...siteNarrowedPermissionKeys()].map((key) => [key, granted[key] === true]),\n )\n }\n return resolveCollaboratorHostPermissions(member, hostId) ?? noHostPermissions()\n}\n\n/**\n * The `memberPermissions` projection stamped on a host document beside\n * `memberRoles`: every member who can reach the site, with the verdict for\n * every per-site key they hold ON it. Org-wide members are resolved against\n * the custom roles the caller loaded (one read per distinct role, as\n * `syncOrgAuthProjections` already does for `resolvedPermissions`);\n * collaborators against their host role. A member who cannot reach the site\n * has no entry, matching `projectHostMemberRoles`.\n */\nexport function projectHostMemberPermissions(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n customRoles: ReadonlyMap<string, AglynOrgCustomRole | null>,\n): Record<string, Record<HostPermissionKey, boolean>> {\n const projection: Record<string, Record<HostPermissionKey, boolean>> = {}\n for (const member of members) {\n if (!hostRoleFor(member, hostId)) continue\n projection[member.$id] = resolveMemberHostPermissions({\n member,\n customRole: member.roleId ? (customRoles.get(member.roleId) ?? null) : null,\n hostId,\n })\n }\n return projection\n}\n\n/** The core's site keys (AGL-4047): `CORE_SITE_ROLE_PRESETS`. */\nexport type CoreSiteKey = 'site.edit' | 'site.publish' | 'site.sensitive' | 'site.manage'\n\n/** A host document, as a snapshot (`get`) or as its data. */\nexport type HostDocumentLike =\n | { get(field: string): unknown }\n | { memberPermissions?: unknown; memberRoles?: unknown }\n | null\n | undefined\n\n/**\n * Does this member hold one of the core's site keys on this site (AGL-4047)?\n * The door's twin of the rules' `canWriteHostContent`,\n * `canPublishHostContent`, `canReadHostSensitive` and site-settings checks:\n * the site's `memberPermissions` stamp, else the preset of the member's\n * `memberRoles` entry (`hostStampedSitePermission`), so a route that asks it\n * answers what the rules answer for the same write. For the routes that read\n * the host document already; it costs no read.\n */\nexport function holdsSiteKey(hostDoc: HostDocumentLike, uid: string, key: CoreSiteKey): boolean {\n return holdsStampedSiteKey(hostDoc, uid, key, CORE_SITE_ROLE_PRESETS[key] ?? {})\n}\n\n/**\n * The same for a plugin's key whose preset is the site role (AGL-4047): the\n * site's `memberPermissions` stamp, else `presetFor` read for the member's\n * `memberRoles` entry. `presetFor` is the declaring plugin's own table, so the\n * answer does not depend on which plugins this process loaded. For the doors\n * and the cards that hold the host document already; it costs no read.\n */\nexport function holdsStampedSiteKey(\n hostDoc: HostDocumentLike,\n uid: string | null | undefined,\n key: string,\n presetFor: Readonly<Partial<Record<HostAccessRole, boolean>>>,\n): boolean {\n if (!hostDoc || !uid) return false\n // `hostDoc`, not `host`: the host-field deny guard reads every `host.…`\n // in this folder as a field of the host document, and `get` is none.\n const read = (field: string): unknown =>\n typeof (hostDoc as { get?: unknown }).get === 'function'\n ? (hostDoc as { get(field: string): unknown }).get(field)\n : (hostDoc as Record<string, unknown>)[field]\n return hostStampedSitePermission(\n { memberPermissions: read('memberPermissions'), memberRoles: read('memberRoles') },\n uid,\n key,\n presetFor,\n )\n}\n\n/**\n * The refusal a door answers when a member does not hold a site key\n * (AGL-4047): it names the permission and who can change it, never a role.\n */\nexport function siteKeyRefusal(key: string): string {\n return permissionRefusalText(key)\n}\n\n"],"names":["refinePermissionMap","hostRoleFor","isOrgWideMember","CORE_SITE_ROLE_PRESETS","permissionRefusalText","ORG_PERMISSION_REFINEMENTS","ORG_PERMISSIONS","resolveOrgPermissions","orgRoleTier","hostPermissionKeys","filter","definition","hostRoleDefaults","undefined","map","key","hostRolePermissionDefaults","role","defaults","workspaceMembersOnly","noHostPermissions","Object","fromEntries","refinementsWithin","parent","resolveCollaboratorHostPermissions","member","hostId","merged","toggles","hostPermissions","keys","value","siteRolePresetPermissionKeys","presetFromSiteRole","isSiteRolePresetPermission","permission","some","resolveSiteRolePresetPermissions","customRole","definitions","length","workspaceMember","layers","roleId","permissions","out","verdict","layer","applySiteRolePresets","granted","resolveSiteRaisedPermissions","HOST_ROLE_RANK","decided","Boolean","raisesPerSite","follows","hostStampedSitePermission","host","uid","presetFor","stamped","memberPermissions","memberRoles","hostStampedWorkspaceSitePermission","membership","orgWide","fresh","hostRole","admin","editor","author","viewer","siteNarrowedPermissionKeys","narrowsPerSite","roleCanBeNarrowed","siteNarrowingChoices","own","siteNarrowing","fromRole","mine","theirRole","siteMayNarrow","workspaceRole","siteNarrowingFor","narrows","values","grants","narrowedPermissionKeysOf","narrowing","narrowedDefault","site","roleDefaults","narrowPermissionsToSite","narrowable","Set","broader","Map","kind","has","set","siteVerdict","depth","seen","steps","current","add","get","sort","a","b","workspace","held","resolveMemberHostPermissions","options","projectHostMemberPermissions","members","customRoles","projection","$id","holdsSiteKey","hostDoc","holdsStampedSiteKey","read","field","siteKeyRefusal"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AASD,SAASA,mBAAmB,QAAmC,0CAAsC;AACrG,SAASC,WAAW,EAAEC,eAAe,QAAQ,qBAAiB;AAC9D,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,qBAAqB,EACrBC,0BAA0B,EAC1BC,eAAe,EACfC,qBAAqB,QAGhB,uBAAmB;AAC1B,SAASC,WAAW,QAAQ,iBAAa;AAEzC;;;;;;;;;;;;;;;;;;;CAmBC,GAED;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAOH,gBAAgBI,MAAM,CAAC,CAACC,aAAeA,WAAWC,gBAAgB,KAAKC,WAAWC,GAAG,CAC1F,CAACH,aAAeA,WAAWI,GAAG;AAElC;AAEA;;;;;CAKC,GACD,OAAO,SAASC,2BACdC,IAAoB;IAEpB,MAAMC,WAA+C,CAAC;IACtD,KAAK,MAAMP,cAAcL,gBAAiB;QACxC,IAAI,CAACK,WAAWC,gBAAgB,EAAE;QAClCM,QAAQ,CAACP,WAAWI,GAAG,CAAC,GAAG,CAACJ,WAAWQ,oBAAoB,IAAIR,WAAWC,gBAAgB,CAACK,KAAK,KAAK;IACvG;IACA,OAAOC;AACT;AAEA,iCAAiC,GACjC,SAASE;IACP,OAAOC,OAAOC,WAAW,CAACb,qBAAqBK,GAAG,CAAC,CAACC,MAAQ;YAACA;YAAK;SAAM;AAC1E;AAEA;;;;CAIC,GACD,SAASQ,kBAAkBT,GAAsC;IAC/D,OAAOT,2BAA2BK,MAAM,CAAC,CAAC,CAACK,KAAKS,OAAO,GAAKT,OAAOD,OAAOU,UAAUV;AACt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GACD,OAAO,SAASuH,oBACdD,OAAyB,EACzB9D,GAA8B,EAC9B5C,GAAW,EACX6C,SAA6D;IAE7D,IAAI,CAAC6D,WAAW,CAAC9D,KAAK,OAAO;IAC7B,wEAAwE;IACxE,qEAAqE;IACrE,MAAMgE,OAAO,CAACC,QACZ,OAAO,AAACH,QAA8Bd,GAAG,KAAK,aAC1C,AAACc,QAA4Cd,GAAG,CAACiB,SACjD,AAACH,OAAmC,CAACG,MAAM;IACjD,OAAOnE,0BACL;QAAEK,mBAAmB6D,KAAK;QAAsB5D,aAAa4D,KAAK;IAAe,GACjFhE,KACA5C,KACA6C;AAEJ;AAEA;;;CAGC,GACD,OAAO,SAASiE,eAAe9G,GAAW;IACxC,OAAOX,sBAAsBW;AAC/B"}
|
|
@@ -46,10 +46,10 @@ export interface MediaAssetFacts {
|
|
|
46
46
|
* Every field an asset's facts are decided from, and the projection a reader
|
|
47
47
|
* asks Firestore for: ONE list, whichever surface reads. `width` and `height`
|
|
48
48
|
* (an image's) and `video` and `poster` (a film's) are the facts. The other
|
|
49
|
-
*
|
|
49
|
+
* four are the gates `serveMediaCdn` applies before it will serve an asset at
|
|
50
50
|
* all, so no surface shows the shape of a file its page's URL refuses.
|
|
51
51
|
*/
|
|
52
|
-
export declare const MEDIA_ASSET_FACT_FIELDS: readonly ["width", "height", "video", "poster", "contentHash", "deletedAt", "private", "visibleTo"];
|
|
52
|
+
export declare const MEDIA_ASSET_FACT_FIELDS: readonly ["width", "height", "video", "poster", "contentHash", "deletedAt", "private", "visibleTo", "scopeMode"];
|
|
53
53
|
/** An asset's media document, as far as {@link MEDIA_ASSET_FACT_FIELDS} reach. */
|
|
54
54
|
export type MediaAssetDocument = Partial<Record<(typeof MEDIA_ASSET_FACT_FIELDS)[number], unknown>>;
|
|
55
55
|
/** The elements whose placements follow their file. */
|
|
@@ -113,7 +113,7 @@ import { VIDEO_COMPONENT_ID } from "./video-object.js";
|
|
|
113
113
|
* Every field an asset's facts are decided from, and the projection a reader
|
|
114
114
|
* asks Firestore for: ONE list, whichever surface reads. `width` and `height`
|
|
115
115
|
* (an image's) and `video` and `poster` (a film's) are the facts. The other
|
|
116
|
-
*
|
|
116
|
+
* four are the gates `serveMediaCdn` applies before it will serve an asset at
|
|
117
117
|
* all, so no surface shows the shape of a file its page's URL refuses.
|
|
118
118
|
*/ export const MEDIA_ASSET_FACT_FIELDS = [
|
|
119
119
|
'width',
|
|
@@ -123,7 +123,8 @@ import { VIDEO_COMPONENT_ID } from "./video-object.js";
|
|
|
123
123
|
'contentHash',
|
|
124
124
|
'deletedAt',
|
|
125
125
|
'private',
|
|
126
|
-
'visibleTo'
|
|
126
|
+
'visibleTo',
|
|
127
|
+
'scopeMode'
|
|
127
128
|
];
|
|
128
129
|
const owns = (map, key)=>Object.prototype.hasOwnProperty.call(map, key);
|
|
129
130
|
/**
|
|
@@ -159,7 +160,7 @@ const owns = (map, key)=>Object.prototype.hasOwnProperty.call(map, key);
|
|
|
159
160
|
if (!document) return undefined;
|
|
160
161
|
if (document.deletedAt || document.private === true) return undefined;
|
|
161
162
|
const served = parseMediaCdnScope(hostQualifiedScope(ref.scope, hostId));
|
|
162
|
-
if (!served || mediaCdnScopeRefusal(served, document.visibleTo)) {
|
|
163
|
+
if (!served || mediaCdnScopeRefusal(served, document.visibleTo, document.scopeMode)) {
|
|
163
164
|
return undefined;
|
|
164
165
|
}
|
|
165
166
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/media-asset-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/**\n * What a placed library asset is NOW, read from its DAM document when the\n * page is composed rather than copied onto the node when it was picked: a\n * film's length, shape and poster (AGL-2807), and an image's pixel pair\n * (AGL-2833).\n *\n * ## Why the pick-time copy is not enough\n *\n * Picking a library asset copies facts onto the node. An image gets its pixel\n * pair ({@link intrinsicMediaSize}), which `image.tsx` renders as the\n * `<img>`'s `width`/`height` attributes so the browser can reserve the box\n * before the bytes arrive. A film gets its running time, its frame's pair and\n * a poster flag ({@link videoMediaProps}): the pair becomes the player's CSS\n * `aspect-ratio`, the running time becomes `VideoObject.duration`, and the\n * flag decides whether a lightbox `<img>` and a `thumbnailUrl` exist at all.\n *\n * A replace (AGL-2732) keeps the asset's id and URL and rewrites its document:\n * an image's `width`/`height`, a film's `video` and `poster` records. It\n * cannot rewrite the nodes, which sit in every screen, layout, component and\n * published version that places the asset. So after a replace with a\n * different shape, every page placing the image reserved the previous\n * picture's box and shifted when the new one decoded, and every page placing\n * the film kept the previous film's length and shape, until someone re-picked\n * it.\n *\n * ## The rule\n *\n * Two surfaces read each placed asset's document and lay what it records over\n * the node here: the tenant's composition, for the page a visitor gets\n * (`libs/tenant/runtime/src/lib/get-media-asset-facts.ts`), and the console,\n * for the besigner canvas an author edits and the Preview that checks it\n * (AGL-2838, AGL-2849). Both decide what a read answers through\n * {@link mediaAssetFactsFromDocument}, so the editor cannot disagree with the\n * page about which assets answer. When the asset cannot be answered for (a\n * failed or pending read, a missing or deleted document, an asset the CDN\n * would not serve under this page's URL, one past the composition's cap), the\n * node keeps what the pick stored. That is the render every page had before\n * this, never a worse one. When the asset answers:\n *\n * - **A film's facts win, including their ABSENCE.** A film the replace left\n * with no `video` record has no known shape, so a stored pair describing\n * the previous film is dropped rather than published, and a poster flag the\n * document no longer backs is dropped with it. One stored value survives: a\n * running time the AUTHOR typed for a film the DAM has no running time for.\n * The pick only ever writes the duration together with the pixel pair\n * ({@link videoMediaProps} is all-or-nothing on the `video` record), and the\n * pair is not an author control. So a duration standing alone is an\n * author's, and a duration standing beside a pair is a copy of a film that\n * may no longer be the one in the bucket.\n * - **An image's pair wins when the document records one.** When it records\n * none (an SVG, which the upload cannot measure, or a file older than\n * AGL-173), the stored pair stays, whether an author typed it through the\n * API or it is a copy of the file the asset held before. The asymmetry with\n * a film is in the render, not the data. A film's pair is the player's\n * permanent box, but an image's is only a reservation\n * (`aspect-ratio: auto w / h`), which the decoded picture's own ratio\n * replaces. Dropping the pair guarantees a shift of the image's full height\n * on every view. A stale pair shifts by the difference between two heights,\n * and a pair typed for a file the DAM cannot measure shifts by nothing.\n *\n * Nothing an author sets for the placement is touched: an image's CSS\n * `width` and `height`, its fit and radius, and a film's own poster describe\n * the placement rather than the file.\n *\n * Imported by path and never through a barrel: every `@aglyn/aglyn` barrel\n * ships to published pages, and nothing here has a reason to reach one, so\n * the composition and the console both import this module by path.\n */\n\nimport { CANVAS_ROOT_ELEMENT_ID } from '../foundation/constants/canvas'\nimport { mediaCdnScopeRefusal, parseMediaCdnScope } from './media-cdn-scope'\nimport { intrinsicMediaSize, videoMediaProps } from './media-metadata'\nimport {\n hostQualifiedScope,\n isMediaCdnPath,\n mediaCdnVersionToken,\n type MediaRef,\n mediaRefFromCdnPath,\n parseMediaRef,\n} from './media-ref'\nimport { VIDEO_COMPONENT_ID } from './video-object'\n\n/** The Image element's persisted component id (`image.tsx`), never renamed. */\nexport const IMAGE_COMPONENT_ID = 'image'\n\n/**\n * The prop each element that holds a markdown-lite DOCUMENT keeps it in, and\n * therefore every element whose body can name a library image (AGL-3149).\n *\n * The same two elements and the same two prop names `resolveMarkdownSource`\n * walks for a table of contents (AGL-1162), which is the other reader of a\n * body's contents. They differ: the Markdown element calls it `content` and a\n * collection entry's body calls it `markdown`.\n *\n * Both ids are spelled out rather than imported. `markdown` belongs to a\n * plugin, which core may never import; `collectionEntryBody` is exported by\n * `collection-entries.ts`, but that module is 1,860 lines and drags\n * `content-authors.ts` behind it, and this one is deliberately outside the\n * barrel that ships to published pages. A persisted component id is a string\n * that cannot change — renaming one orphans every document that stores it —\n * so the copy cannot drift in the way an imported value would protect against.\n */\nconst MARKDOWN_BODY_PROPS: Readonly<Record<string, string>> = {\n markdown: 'content',\n collectionEntryBody: 'markdown',\n}\n\n/** The root of a composed map, where a walk in document order starts. */\nconst ROOT_NODE_ID: string = CANVAS_ROOT_ELEMENT_ID\n\n/**\n * What a readable asset's media document records, as the overlay consumes it.\n *\n * Raw on purpose: {@link intrinsicMediaSize} and {@link videoMediaProps} are\n * where a pair and a `video` record are bounded, and a second reading of the\n * same numbers here is how two files come to disagree about what a partial\n * record means.\n */\nexport interface MediaAssetFacts {\n /** The document's `width`: an image's, read from its bytes at upload. */\n width?: unknown\n /** The document's `height`, the other half of {@link width}. */\n height?: unknown\n /** The document's `video` record: `durationMs`, `width` and `height`. */\n video?: unknown\n /** The document's generated `poster` record, when it has one. */\n poster?: unknown\n /**\n * The document's `contentHash`, which a replace changes with the bytes. An\n * image placement carries it as `mediaVersion`, and the URL it renders is\n * then the versioned one the CDN lets every cache keep (AGL-3485).\n */\n contentHash?: unknown\n}\n\n/**\n * Every field an asset's facts are decided from, and the projection a reader\n * asks Firestore for: ONE list, whichever surface reads. `width` and `height`\n * (an image's) and `video` and `poster` (a film's) are the facts. The other\n * three are the gates `serveMediaCdn` applies before it will serve an asset at\n * all, so no surface shows the shape of a file its page's URL refuses.\n */\nexport const MEDIA_ASSET_FACT_FIELDS = [\n 'width',\n 'height',\n 'video',\n 'poster',\n 'contentHash',\n 'deletedAt',\n 'private',\n 'visibleTo',\n] as const\n\n/** An asset's media document, as far as {@link MEDIA_ASSET_FACT_FIELDS} reach. */\nexport type MediaAssetDocument = Partial<\n Record<(typeof MEDIA_ASSET_FACT_FIELDS)[number], unknown>\n>\n\n/** The elements whose placements follow their file. */\nexport type MediaAssetElement =\n | typeof IMAGE_COMPONENT_ID\n | typeof VIDEO_COMPONENT_ID\n\nexport interface MediaAssetFactsOptions {\n /**\n * One element's placements only, by persisted component id. Absent means\n * both, which is what the composition asks for.\n */\n only?: MediaAssetElement\n}\n\n/** A node as the composed map holds it: flat, children by id. */\ninterface ComposedMediaNode {\n componentId?: string\n nodes?: unknown\n props?: Record<string, unknown>\n resolvedProps?: Record<string, unknown>\n}\n\nconst owns = (map: object, key: string) =>\n Object.prototype.hasOwnProperty.call(map, key)\n\n/**\n * The key an asset's facts are filed under: the reference's own scope and id.\n *\n * Deliberately NOT the host-qualified scope a page renders. The document lives\n * under the scope's owner whichever site places it, and which site may be\n * shown it is the reader's question, answered once per page.\n */\nexport function mediaAssetFactsKey(\n ref: Pick<MediaRef, 'scope' | 'mediaId'>,\n): string {\n return `${ref.scope}/${ref.mediaId}`\n}\n\n/**\n * Where an asset's media document lives: under the scope's OWNER, `orgs/` for\n * the org library and `hosts/` for a site's own, whichever site places it.\n * `null` for a scope the CDN would not parse, which no read can answer for.\n */\nexport function mediaAssetDocumentPath(\n ref: Pick<MediaRef, 'scope' | 'mediaId'>,\n): string | null {\n const scope = parseMediaCdnScope(ref.scope)\n if (!scope) return null\n return `${scope.isOrg ? 'orgs' : 'hosts'}/${scope.scopeId}/media/${ref.mediaId}`\n}\n\n/**\n * The facts one read of an asset's document yields for a placement rendered\n * on `hostId`'s pages, or `undefined` when the placement keeps its stored\n * props.\n *\n * An answer exists only for a document that was read, is live, is not\n * private, and is visible to that site under the host-qualified scope the page\n * renders: the verdict the CDN reaches when the browser asks for the bytes.\n * The URL a page renders names the site doing the rendering\n * (`resolveMediaSrc`), so visibility is asked of THAT scope, not of the scope\n * the reference was stored with.\n */\nexport function mediaAssetFactsFromDocument(\n document: MediaAssetDocument | null | undefined,\n ref: Pick<MediaRef, 'scope'>,\n hostId: string,\n): MediaAssetFacts | undefined {\n if (!document) return undefined\n if (document.deletedAt || document.private === true) return undefined\n const served = parseMediaCdnScope(hostQualifiedScope(ref.scope, hostId))\n if (!served || mediaCdnScopeRefusal(served, document.visibleTo)) {\n return undefined\n }\n return {\n width: document.width,\n height: document.height,\n video: document.video,\n poster: document.poster,\n contentHash: document.contentHash,\n }\n}\n\n/** The library asset an Image or Video node places, or null for anything else. */\nfunction placedAsset(\n node: ComposedMediaNode | null | undefined,\n only?: MediaAssetElement,\n): MediaRef | null {\n const componentId = node?.componentId\n if (componentId !== IMAGE_COMPONENT_ID && componentId !== VIDEO_COMPONENT_ID) {\n return null\n }\n if (only && componentId !== only) return null\n // The precedence every other reader of the composed map uses: a node inside\n // a repeated collection carries its bound values in the resolved copy.\n const props = node?.resolvedProps ?? node?.props\n return placedRef(props?.['src'])\n}\n\n/**\n * The library asset a stored `src` names: a `media:` reference, or the\n * site-relative CDN path the first media picker wrote before references\n * existed (AGL-1215). Both name one asset by its id, and the path's are among\n * the oldest placements on the platform — the ones that most need their file's\n * shape read back, since nothing copied it onto the node when they were made.\n * Only the strict root-relative path: a hotlink on another host that happens\n * to contain our route names nothing of ours.\n */\nfunction placedRef(src: unknown): MediaRef | null {\n if (isMediaCdnPath(src)) return parseMediaRef(mediaRefFromCdnPath(src))\n return parseMediaRef(src)\n}\n\n/** A compose-time token the tenant has not substituted — never a document. */\nconst UNRESOLVED_TOKEN = /^\\{\\{[^}]+\\}\\}$/\n\n/**\n * The markdown-lite document a node holds, or `''` for a node holding none.\n *\n * `resolvedProps` first, for the reason {@link placedAsset} gives: an entry\n * body is the literal `{{entry.body}}` in `props` and the entry's real text in\n * the resolved copy. An unsubstituted token is not a document — it can name no\n * asset — so it is dropped here rather than walked for images that a canvas\n * surface would never find.\n */\nfunction markdownBodyOf(\n props: Record<string, unknown> | undefined,\n componentId: string | undefined,\n): string {\n const prop =\n componentId && owns(MARKDOWN_BODY_PROPS, componentId)\n ? MARKDOWN_BODY_PROPS[componentId]\n : undefined\n const text = prop ? props?.[prop] : undefined\n if (typeof text !== 'string' || UNRESOLVED_TOKEN.test(text.trim())) return ''\n return text\n}\n\n/** See {@link markdownBodyOf} — the body the page will actually render. */\nfunction markdownBody(node: ComposedMediaNode | null | undefined): string {\n return markdownBodyOf(\n node?.resolvedProps ?? node?.props,\n node?.componentId,\n )\n}\n\n/**\n * A markdown-lite image: ``, capturing only the target, and only\n * up to the first whitespace or `)`.\n *\n * That is the whole of the syntax `markdown-lite.ts` accepts — no title string\n * after the target, no angle-bracket form — so there is nowhere else in a body\n * for a reference to hide, and matching more than the parser does would name\n * assets the renderer never asks for.\n */\nconst MARKDOWN_IMAGE_TARGET = /!\\[[^\\]]*\\]\\(\\s*([^)\\s]+)/g\n\n/**\n * Every library asset a markdown body's images name, in the order the body\n * names them, each beside the target EXACTLY as the body wrote it.\n *\n * The raw target is carried because that is the key the renderer has: it holds\n * the parsed block's `src`, the same string, and looking a pair up by it costs\n * no second parse per image on every render.\n *\n * A target that is not a `media:` reference yields nothing — a hotlinked URL\n * and a legacy stored path have no DAM document to read, and the renderer\n * gives those today's markup unchanged.\n */\nfunction markdownImageRefs(\n text: string,\n): Array<{ target: string; ref: MediaRef }> {\n if (!text.includes('![')) return []\n const found: Array<{ target: string; ref: MediaRef }> = []\n for (const match of text.matchAll(MARKDOWN_IMAGE_TARGET)) {\n const target = match[1]\n const ref = parseMediaRef(target)\n if (ref) found.push({ target, ref })\n }\n return found\n}\n\n/**\n * The map's node ids in document order: depth first from the root through\n * each node's child ids, then every id the walk never reached (a map with no\n * root, an orphan) in the order the map lists it. That puts the top of the\n * page ahead of its footer, and it is the same order for the same map.\n */\nfunction documentOrder(nodes: Record<string, unknown>): string[] {\n const order: string[] = []\n const seen = new Set<string>()\n const stack = owns(nodes, ROOT_NODE_ID) ? [ROOT_NODE_ID] : []\n while (stack.length) {\n const id = stack.pop() as string\n if (seen.has(id) || !owns(nodes, id)) continue\n seen.add(id)\n order.push(id)\n const children = (nodes[id] as ComposedMediaNode | null)?.nodes\n if (!Array.isArray(children)) continue\n for (let index = children.length - 1; index >= 0; index -= 1) {\n const child = children[index]\n if (typeof child === 'string' && !seen.has(child)) stack.push(child)\n }\n }\n for (const id in nodes) if (!seen.has(id)) order.push(id)\n return order\n}\n\n/**\n * Every distinct library asset the Image and Video nodes in a map place:\n * films first, then images, each in document order.\n *\n * A read that is capped honors that order. A film goes first because its\n * stale facts are the worse render (a player of the wrong shape and a\n * thumbnail that 404s, against a reservation that corrects itself when an\n * image decodes), and document order covers the top of the page before its\n * footer.\n *\n * `[]` for a page that places none, so a caller that gates its read on the\n * length spends nothing on it. A pinned and an unpinned reference to one\n * asset are one entry: a pin names bytes, not a different asset.\n */\nexport function mediaAssetRefs(\n nodes: Record<string, unknown> | null | undefined,\n options: MediaAssetFactsOptions = {},\n): MediaRef[] {\n const refs: MediaRef[] = []\n if (!nodes) return refs\n const order = documentOrder(nodes)\n const seen = new Set<string>()\n for (const element of [VIDEO_COMPONENT_ID, IMAGE_COMPONENT_ID] as const) {\n if (options.only && options.only !== element) continue\n for (const id of order) {\n const node = nodes[id] as ComposedMediaNode | null\n if (node?.componentId !== element) continue\n const ref = placedAsset(node)\n if (!ref) continue\n const key = mediaAssetFactsKey(ref)\n if (seen.has(key)) continue\n seen.add(key)\n refs.push(ref)\n }\n }\n // A markdown body's images come LAST, and only when the caller wants every\n // element (AGL-3149). Last because of what a capped read costs each kind: a\n // placement that misses out renders at its pick-time pair, a body image that\n // misses out renders exactly as it does today, and a film that misses out\n // gets a player of the wrong shape. Only-when-unfiltered because `only` asks\n // for one ELEMENT's placements, and a body image is not a placement of the\n // Image element — the video-asset reader would otherwise read image\n // documents it has no use for.\n if (options.only) return refs\n for (const id of order) {\n const body = markdownBody(nodes[id] as ComposedMediaNode | null)\n for (const { ref } of markdownImageRefs(body)) {\n const key = mediaAssetFactsKey(ref)\n if (seen.has(key)) continue\n seen.add(key)\n refs.push(ref)\n }\n }\n return refs\n}\n\nconst usable = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value) && value > 0\n\n/** A film's props with its asset's facts laid over them. See the module note. */\nfunction withFilmFacts(\n props: Record<string, unknown>,\n facts: MediaAssetFacts,\n): Record<string, unknown> {\n const live = videoMediaProps({\n componentId: VIDEO_COMPONENT_ID,\n propName: 'src',\n assetVideo: facts.video,\n assetPoster: facts.poster,\n })\n const {\n durationSeconds,\n intrinsicWidth,\n intrinsicHeight,\n posterFromSource: _storedPosterFlag,\n ...next\n } = props\n // The pick writes a duration only beside the pixel pair, so a pair is what\n // marks the stored duration as a copy rather than an author's own.\n const typedByAuthor = !(usable(intrinsicWidth) && usable(intrinsicHeight))\n if (live.durationSeconds !== undefined) {\n next['durationSeconds'] = live.durationSeconds\n } else if (typedByAuthor && durationSeconds !== undefined) {\n next['durationSeconds'] = durationSeconds\n }\n if (live.intrinsicWidth !== undefined && live.intrinsicHeight !== undefined) {\n next['intrinsicWidth'] = live.intrinsicWidth\n next['intrinsicHeight'] = live.intrinsicHeight\n }\n if (live.posterFromSource) next['posterFromSource'] = true\n return next\n}\n\n/**\n * An image's props with its asset's pair laid over them, or the SAME object\n * when the document records no usable pair or the stored one already matches.\n * See the module note.\n */\nfunction withImageFacts(\n props: Record<string, unknown>,\n facts: MediaAssetFacts,\n): Record<string, unknown> {\n // Through the pick's own gate, so the overlay and the pick agree on what a\n // usable pair is: both halves, finite and positive.\n const live = intrinsicMediaSize({\n componentId: IMAGE_COMPONENT_ID,\n propName: 'src',\n assetWidth: facts.width,\n assetHeight: facts.height,\n })\n const version = mediaVersionOf(facts)\n const pair =\n live.intrinsicWidth !== undefined && live.intrinsicHeight !== undefined\n const pairChanged =\n pair &&\n (props['intrinsicWidth'] !== live.intrinsicWidth ||\n props['intrinsicHeight'] !== live.intrinsicHeight)\n const versionChanged =\n version !== undefined && props[IMAGE_MEDIA_VERSION_PROP] !== version\n if (!pairChanged && !versionChanged) return props\n return {\n ...props,\n ...(pairChanged\n ? {\n intrinsicWidth: live.intrinsicWidth,\n intrinsicHeight: live.intrinsicHeight,\n }\n : {}),\n ...(versionChanged ? { [IMAGE_MEDIA_VERSION_PROP]: version } : {}),\n }\n}\n\n/**\n * The prop an Image placement carries its asset's current content hash in\n * (AGL-3485). Laid on at composition like the pixel pair and never an author\n * control: it describes the file, and `image.tsx` hands it to\n * `resolveMediaSrc` so the page names the versioned URL.\n */\nexport const IMAGE_MEDIA_VERSION_PROP = 'mediaVersion'\n\n/** The document's content hash, when it is one a URL can carry. */\nfunction mediaVersionOf(facts: MediaAssetFacts): string | undefined {\n return mediaCdnVersionToken(facts.contentHash) === undefined\n ? undefined\n : (facts.contentHash as string)\n}\n\n/**\n * The prop a markdown body carries its images' pixel pairs in, keyed by the\n * target the body wrote (AGL-3149).\n *\n * A body image is not a node, so it cannot take `intrinsicWidth` and\n * `intrinsicHeight` the way a placement does; the pairs travel together on the\n * element that holds the document, and the renderer looks each one up by the\n * parsed block's `src`.\n */\nexport const BODY_IMAGE_SIZES_PROP = 'intrinsicSizes'\n\n/** One body image's pair, as {@link BODY_IMAGE_SIZES_PROP} carries it. */\nexport interface BodyImageSize {\n width: number\n height: number\n /** The asset's content hash, for the versioned URL (AGL-3485). */\n version?: string\n}\n\n/**\n * A markdown body's props with a pair for each library image it names, or the\n * SAME object when no image in it can be answered for.\n *\n * Only images whose document records a usable pair get an entry, through the\n * same {@link intrinsicMediaSize} gate a placement goes through. An image left\n * out is one the renderer must give today's markup: `srcSet` without the pair\n * makes `sizes` the image's rendered width, which upscales anything narrower\n * than the column, so a partial answer is worse here than no answer.\n */\nfunction withBodyImageFacts(\n props: Record<string, unknown>,\n componentId: string | undefined,\n facts: ReadonlyMap<string, MediaAssetFacts>,\n): Record<string, unknown> {\n // THIS object's own body, never the node's resolved one: `props` on a bound\n // entry body still holds the `{{entry.body}}` token, and pairs for images it\n // does not name are bytes in the tree that nothing can ever look up.\n let sizes: Record<string, BodyImageSize> | undefined\n for (const { target, ref } of markdownImageRefs(\n markdownBodyOf(props, componentId),\n )) {\n const found = facts.get(mediaAssetFactsKey(ref))\n if (!found) continue\n const live = intrinsicMediaSize({\n componentId: IMAGE_COMPONENT_ID,\n propName: 'src',\n assetWidth: found.width,\n assetHeight: found.height,\n })\n if (\n live.intrinsicWidth === undefined ||\n live.intrinsicHeight === undefined\n ) {\n continue\n }\n if (!sizes) sizes = {}\n const version = mediaVersionOf(found)\n sizes[target] = {\n width: live.intrinsicWidth,\n height: live.intrinsicHeight,\n ...(version ? { version } : {}),\n }\n }\n if (!sizes) return props\n return { ...props, [BODY_IMAGE_SIZES_PROP]: sizes }\n}\n\n/**\n * The composed map with each placed asset's facts laid over its node, and each\n * markdown body's images' pairs laid over the element holding the body.\n *\n * `facts` is keyed by {@link mediaAssetFactsKey}. A placement with no entry,\n * because the reader could not answer for its asset, keeps its stored props.\n * The SAME map comes back when nothing changes, so a page with no library\n * asset pays for one walk and no copy, and the input is never mutated either\n * way.\n */\nexport function applyMediaAssetFacts<T extends Record<string, unknown>>(\n nodes: T,\n facts: ReadonlyMap<string, MediaAssetFacts>,\n options: MediaAssetFactsOptions = {},\n): T {\n if (!facts.size) return nodes\n let applied: Record<string, unknown> | undefined\n const write = (id: string, node: ComposedMediaNode, next: {\n props?: Record<string, unknown>\n resolvedProps?: Record<string, unknown>\n }): void => {\n if (!applied) applied = { ...nodes }\n applied[id] = {\n ...node,\n ...(next.props ? { props: next.props } : {}),\n ...(next.resolvedProps ? { resolvedProps: next.resolvedProps } : {}),\n }\n }\n for (const id in nodes) {\n const node = nodes[id] as ComposedMediaNode\n const ref = placedAsset(node, options.only)\n const found = ref ? facts.get(mediaAssetFactsKey(ref)) : undefined\n if (found) {\n const overlay =\n node.componentId === VIDEO_COMPONENT_ID ? withFilmFacts : withImageFacts\n const props = node.props && overlay(node.props, found)\n const resolvedProps =\n node.resolvedProps && overlay(node.resolvedProps, found)\n if (props === node.props && resolvedProps === node.resolvedProps) continue\n write(id, node, { props, resolvedProps })\n continue\n }\n // A markdown body, under the same `only` rule `mediaAssetRefs` collects\n // under: a body image is not a placement of the Image element, so a reader\n // asking for one element's placements is not asking about bodies.\n if (options.only) continue\n const { componentId } = node\n if (!componentId || !owns(MARKDOWN_BODY_PROPS, componentId)) continue\n const props =\n node.props && withBodyImageFacts(node.props, componentId, facts)\n const resolvedProps =\n node.resolvedProps &&\n withBodyImageFacts(node.resolvedProps, componentId, facts)\n if (props === node.props && resolvedProps === node.resolvedProps) continue\n write(id, node, { props, resolvedProps })\n }\n return applied ? (applied as T) : nodes\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","mediaCdnScopeRefusal","parseMediaCdnScope","intrinsicMediaSize","videoMediaProps","hostQualifiedScope","isMediaCdnPath","mediaCdnVersionToken","mediaRefFromCdnPath","parseMediaRef","VIDEO_COMPONENT_ID","IMAGE_COMPONENT_ID","MARKDOWN_BODY_PROPS","markdown","collectionEntryBody","ROOT_NODE_ID","MEDIA_ASSET_FACT_FIELDS","owns","map","key","Object","prototype","hasOwnProperty","call","mediaAssetFactsKey","ref","scope","mediaId","mediaAssetDocumentPath","isOrg","scopeId","mediaAssetFactsFromDocument","document","hostId","undefined","deletedAt","private","served","visibleTo","width","height","video","poster","contentHash","placedAsset","node","only","componentId","props","resolvedProps","placedRef","src","UNRESOLVED_TOKEN","markdownBodyOf","prop","text","test","trim","markdownBody","MARKDOWN_IMAGE_TARGET","markdownImageRefs","includes","found","match","matchAll","target","push","documentOrder","nodes","order","seen","Set","stack","length","id","pop","has","add","children","Array","isArray","index","child","mediaAssetRefs","options","refs","element","body","usable","value","Number","isFinite","withFilmFacts","facts","live","propName","assetVideo","assetPoster","durationSeconds","intrinsicWidth","intrinsicHeight","posterFromSource","_storedPosterFlag","next","typedByAuthor","withImageFacts","assetWidth","assetHeight","version","mediaVersionOf","pair","pairChanged","versionChanged","IMAGE_MEDIA_VERSION_PROP","BODY_IMAGE_SIZES_PROP","withBodyImageFacts","sizes","get","applyMediaAssetFacts","size","applied","write","overlay"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GAED,SAASA,sBAAsB,QAAQ,oCAAgC;AACvE,SAASC,oBAAo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C,cAAc;QAC7D,MAAMC,QACJH,KAAKG,KAAK,IAAImE,mBAAmBtE,KAAKG,KAAK,EAAED,aAAa8C;QAC5D,MAAM5C,gBACJJ,KAAKI,aAAa,IAClBkE,mBAAmBtE,KAAKI,aAAa,EAAEF,aAAa8C;QACtD,IAAI7C,UAAUH,KAAKG,KAAK,IAAIC,kBAAkBJ,KAAKI,aAAa,EAAE;QAClEwE,MAAM/C,IAAI7B,MAAM;YAAEG;YAAOC;QAAc;IACzC;IACA,OAAOuE,UAAWA,UAAgBpD;AACpC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/media-asset-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/**\n * What a placed library asset is NOW, read from its DAM document when the\n * page is composed rather than copied onto the node when it was picked: a\n * film's length, shape and poster (AGL-2807), and an image's pixel pair\n * (AGL-2833).\n *\n * ## Why the pick-time copy is not enough\n *\n * Picking a library asset copies facts onto the node. An image gets its pixel\n * pair ({@link intrinsicMediaSize}), which `image.tsx` renders as the\n * `<img>`'s `width`/`height` attributes so the browser can reserve the box\n * before the bytes arrive. A film gets its running time, its frame's pair and\n * a poster flag ({@link videoMediaProps}): the pair becomes the player's CSS\n * `aspect-ratio`, the running time becomes `VideoObject.duration`, and the\n * flag decides whether a lightbox `<img>` and a `thumbnailUrl` exist at all.\n *\n * A replace (AGL-2732) keeps the asset's id and URL and rewrites its document:\n * an image's `width`/`height`, a film's `video` and `poster` records. It\n * cannot rewrite the nodes, which sit in every screen, layout, component and\n * published version that places the asset. So after a replace with a\n * different shape, every page placing the image reserved the previous\n * picture's box and shifted when the new one decoded, and every page placing\n * the film kept the previous film's length and shape, until someone re-picked\n * it.\n *\n * ## The rule\n *\n * Two surfaces read each placed asset's document and lay what it records over\n * the node here: the tenant's composition, for the page a visitor gets\n * (`libs/tenant/runtime/src/lib/get-media-asset-facts.ts`), and the console,\n * for the besigner canvas an author edits and the Preview that checks it\n * (AGL-2838, AGL-2849). Both decide what a read answers through\n * {@link mediaAssetFactsFromDocument}, so the editor cannot disagree with the\n * page about which assets answer. When the asset cannot be answered for (a\n * failed or pending read, a missing or deleted document, an asset the CDN\n * would not serve under this page's URL, one past the composition's cap), the\n * node keeps what the pick stored. That is the render every page had before\n * this, never a worse one. When the asset answers:\n *\n * - **A film's facts win, including their ABSENCE.** A film the replace left\n * with no `video` record has no known shape, so a stored pair describing\n * the previous film is dropped rather than published, and a poster flag the\n * document no longer backs is dropped with it. One stored value survives: a\n * running time the AUTHOR typed for a film the DAM has no running time for.\n * The pick only ever writes the duration together with the pixel pair\n * ({@link videoMediaProps} is all-or-nothing on the `video` record), and the\n * pair is not an author control. So a duration standing alone is an\n * author's, and a duration standing beside a pair is a copy of a film that\n * may no longer be the one in the bucket.\n * - **An image's pair wins when the document records one.** When it records\n * none (an SVG, which the upload cannot measure, or a file older than\n * AGL-173), the stored pair stays, whether an author typed it through the\n * API or it is a copy of the file the asset held before. The asymmetry with\n * a film is in the render, not the data. A film's pair is the player's\n * permanent box, but an image's is only a reservation\n * (`aspect-ratio: auto w / h`), which the decoded picture's own ratio\n * replaces. Dropping the pair guarantees a shift of the image's full height\n * on every view. A stale pair shifts by the difference between two heights,\n * and a pair typed for a file the DAM cannot measure shifts by nothing.\n *\n * Nothing an author sets for the placement is touched: an image's CSS\n * `width` and `height`, its fit and radius, and a film's own poster describe\n * the placement rather than the file.\n *\n * Imported by path and never through a barrel: every `@aglyn/aglyn` barrel\n * ships to published pages, and nothing here has a reason to reach one, so\n * the composition and the console both import this module by path.\n */\n\nimport { CANVAS_ROOT_ELEMENT_ID } from '../foundation/constants/canvas'\nimport { mediaCdnScopeRefusal, parseMediaCdnScope } from './media-cdn-scope'\nimport { intrinsicMediaSize, videoMediaProps } from './media-metadata'\nimport {\n hostQualifiedScope,\n isMediaCdnPath,\n mediaCdnVersionToken,\n type MediaRef,\n mediaRefFromCdnPath,\n parseMediaRef,\n} from './media-ref'\nimport { VIDEO_COMPONENT_ID } from './video-object'\n\n/** The Image element's persisted component id (`image.tsx`), never renamed. */\nexport const IMAGE_COMPONENT_ID = 'image'\n\n/**\n * The prop each element that holds a markdown-lite DOCUMENT keeps it in, and\n * therefore every element whose body can name a library image (AGL-3149).\n *\n * The same two elements and the same two prop names `resolveMarkdownSource`\n * walks for a table of contents (AGL-1162), which is the other reader of a\n * body's contents. They differ: the Markdown element calls it `content` and a\n * collection entry's body calls it `markdown`.\n *\n * Both ids are spelled out rather than imported. `markdown` belongs to a\n * plugin, which core may never import; `collectionEntryBody` is exported by\n * `collection-entries.ts`, but that module is 1,860 lines and drags\n * `content-authors.ts` behind it, and this one is deliberately outside the\n * barrel that ships to published pages. A persisted component id is a string\n * that cannot change — renaming one orphans every document that stores it —\n * so the copy cannot drift in the way an imported value would protect against.\n */\nconst MARKDOWN_BODY_PROPS: Readonly<Record<string, string>> = {\n markdown: 'content',\n collectionEntryBody: 'markdown',\n}\n\n/** The root of a composed map, where a walk in document order starts. */\nconst ROOT_NODE_ID: string = CANVAS_ROOT_ELEMENT_ID\n\n/**\n * What a readable asset's media document records, as the overlay consumes it.\n *\n * Raw on purpose: {@link intrinsicMediaSize} and {@link videoMediaProps} are\n * where a pair and a `video` record are bounded, and a second reading of the\n * same numbers here is how two files come to disagree about what a partial\n * record means.\n */\nexport interface MediaAssetFacts {\n /** The document's `width`: an image's, read from its bytes at upload. */\n width?: unknown\n /** The document's `height`, the other half of {@link width}. */\n height?: unknown\n /** The document's `video` record: `durationMs`, `width` and `height`. */\n video?: unknown\n /** The document's generated `poster` record, when it has one. */\n poster?: unknown\n /**\n * The document's `contentHash`, which a replace changes with the bytes. An\n * image placement carries it as `mediaVersion`, and the URL it renders is\n * then the versioned one the CDN lets every cache keep (AGL-3485).\n */\n contentHash?: unknown\n}\n\n/**\n * Every field an asset's facts are decided from, and the projection a reader\n * asks Firestore for: ONE list, whichever surface reads. `width` and `height`\n * (an image's) and `video` and `poster` (a film's) are the facts. The other\n * four are the gates `serveMediaCdn` applies before it will serve an asset at\n * all, so no surface shows the shape of a file its page's URL refuses.\n */\nexport const MEDIA_ASSET_FACT_FIELDS = [\n 'width',\n 'height',\n 'video',\n 'poster',\n 'contentHash',\n 'deletedAt',\n 'private',\n 'visibleTo',\n 'scopeMode',\n] as const\n\n/** An asset's media document, as far as {@link MEDIA_ASSET_FACT_FIELDS} reach. */\nexport type MediaAssetDocument = Partial<\n Record<(typeof MEDIA_ASSET_FACT_FIELDS)[number], unknown>\n>\n\n/** The elements whose placements follow their file. */\nexport type MediaAssetElement =\n | typeof IMAGE_COMPONENT_ID\n | typeof VIDEO_COMPONENT_ID\n\nexport interface MediaAssetFactsOptions {\n /**\n * One element's placements only, by persisted component id. Absent means\n * both, which is what the composition asks for.\n */\n only?: MediaAssetElement\n}\n\n/** A node as the composed map holds it: flat, children by id. */\ninterface ComposedMediaNode {\n componentId?: string\n nodes?: unknown\n props?: Record<string, unknown>\n resolvedProps?: Record<string, unknown>\n}\n\nconst owns = (map: object, key: string) =>\n Object.prototype.hasOwnProperty.call(map, key)\n\n/**\n * The key an asset's facts are filed under: the reference's own scope and id.\n *\n * Deliberately NOT the host-qualified scope a page renders. The document lives\n * under the scope's owner whichever site places it, and which site may be\n * shown it is the reader's question, answered once per page.\n */\nexport function mediaAssetFactsKey(\n ref: Pick<MediaRef, 'scope' | 'mediaId'>,\n): string {\n return `${ref.scope}/${ref.mediaId}`\n}\n\n/**\n * Where an asset's media document lives: under the scope's OWNER, `orgs/` for\n * the org library and `hosts/` for a site's own, whichever site places it.\n * `null` for a scope the CDN would not parse, which no read can answer for.\n */\nexport function mediaAssetDocumentPath(\n ref: Pick<MediaRef, 'scope' | 'mediaId'>,\n): string | null {\n const scope = parseMediaCdnScope(ref.scope)\n if (!scope) return null\n return `${scope.isOrg ? 'orgs' : 'hosts'}/${scope.scopeId}/media/${ref.mediaId}`\n}\n\n/**\n * The facts one read of an asset's document yields for a placement rendered\n * on `hostId`'s pages, or `undefined` when the placement keeps its stored\n * props.\n *\n * An answer exists only for a document that was read, is live, is not\n * private, and is visible to that site under the host-qualified scope the page\n * renders: the verdict the CDN reaches when the browser asks for the bytes.\n * The URL a page renders names the site doing the rendering\n * (`resolveMediaSrc`), so visibility is asked of THAT scope, not of the scope\n * the reference was stored with.\n */\nexport function mediaAssetFactsFromDocument(\n document: MediaAssetDocument | null | undefined,\n ref: Pick<MediaRef, 'scope'>,\n hostId: string,\n): MediaAssetFacts | undefined {\n if (!document) return undefined\n if (document.deletedAt || document.private === true) return undefined\n const served = parseMediaCdnScope(hostQualifiedScope(ref.scope, hostId))\n if (\n !served ||\n mediaCdnScopeRefusal(served, document.visibleTo, document.scopeMode)\n ) {\n return undefined\n }\n return {\n width: document.width,\n height: document.height,\n video: document.video,\n poster: document.poster,\n contentHash: document.contentHash,\n }\n}\n\n/** The library asset an Image or Video node places, or null for anything else. */\nfunction placedAsset(\n node: ComposedMediaNode | null | undefined,\n only?: MediaAssetElement,\n): MediaRef | null {\n const componentId = node?.componentId\n if (componentId !== IMAGE_COMPONENT_ID && componentId !== VIDEO_COMPONENT_ID) {\n return null\n }\n if (only && componentId !== only) return null\n // The precedence every other reader of the composed map uses: a node inside\n // a repeated collection carries its bound values in the resolved copy.\n const props = node?.resolvedProps ?? node?.props\n return placedRef(props?.['src'])\n}\n\n/**\n * The library asset a stored `src` names: a `media:` reference, or the\n * site-relative CDN path the first media picker wrote before references\n * existed (AGL-1215). Both name one asset by its id, and the path's are among\n * the oldest placements on the platform — the ones that most need their file's\n * shape read back, since nothing copied it onto the node when they were made.\n * Only the strict root-relative path: a hotlink on another host that happens\n * to contain our route names nothing of ours.\n */\nfunction placedRef(src: unknown): MediaRef | null {\n if (isMediaCdnPath(src)) return parseMediaRef(mediaRefFromCdnPath(src))\n return parseMediaRef(src)\n}\n\n/** A compose-time token the tenant has not substituted — never a document. */\nconst UNRESOLVED_TOKEN = /^\\{\\{[^}]+\\}\\}$/\n\n/**\n * The markdown-lite document a node holds, or `''` for a node holding none.\n *\n * `resolvedProps` first, for the reason {@link placedAsset} gives: an entry\n * body is the literal `{{entry.body}}` in `props` and the entry's real text in\n * the resolved copy. An unsubstituted token is not a document — it can name no\n * asset — so it is dropped here rather than walked for images that a canvas\n * surface would never find.\n */\nfunction markdownBodyOf(\n props: Record<string, unknown> | undefined,\n componentId: string | undefined,\n): string {\n const prop =\n componentId && owns(MARKDOWN_BODY_PROPS, componentId)\n ? MARKDOWN_BODY_PROPS[componentId]\n : undefined\n const text = prop ? props?.[prop] : undefined\n if (typeof text !== 'string' || UNRESOLVED_TOKEN.test(text.trim())) return ''\n return text\n}\n\n/** See {@link markdownBodyOf} — the body the page will actually render. */\nfunction markdownBody(node: ComposedMediaNode | null | undefined): string {\n return markdownBodyOf(\n node?.resolvedProps ?? node?.props,\n node?.componentId,\n )\n}\n\n/**\n * A markdown-lite image: ``, capturing only the target, and only\n * up to the first whitespace or `)`.\n *\n * That is the whole of the syntax `markdown-lite.ts` accepts — no title string\n * after the target, no angle-bracket form — so there is nowhere else in a body\n * for a reference to hide, and matching more than the parser does would name\n * assets the renderer never asks for.\n */\nconst MARKDOWN_IMAGE_TARGET = /!\\[[^\\]]*\\]\\(\\s*([^)\\s]+)/g\n\n/**\n * Every library asset a markdown body's images name, in the order the body\n * names them, each beside the target EXACTLY as the body wrote it.\n *\n * The raw target is carried because that is the key the renderer has: it holds\n * the parsed block's `src`, the same string, and looking a pair up by it costs\n * no second parse per image on every render.\n *\n * A target that is not a `media:` reference yields nothing — a hotlinked URL\n * and a legacy stored path have no DAM document to read, and the renderer\n * gives those today's markup unchanged.\n */\nfunction markdownImageRefs(\n text: string,\n): Array<{ target: string; ref: MediaRef }> {\n if (!text.includes('![')) return []\n const found: Array<{ target: string; ref: MediaRef }> = []\n for (const match of text.matchAll(MARKDOWN_IMAGE_TARGET)) {\n const target = match[1]\n const ref = parseMediaRef(target)\n if (ref) found.push({ target, ref })\n }\n return found\n}\n\n/**\n * The map's node ids in document order: depth first from the root through\n * each node's child ids, then every id the walk never reached (a map with no\n * root, an orphan) in the order the map lists it. That puts the top of the\n * page ahead of its footer, and it is the same order for the same map.\n */\nfunction documentOrder(nodes: Record<string, unknown>): string[] {\n const order: string[] = []\n const seen = new Set<string>()\n const stack = owns(nodes, ROOT_NODE_ID) ? [ROOT_NODE_ID] : []\n while (stack.length) {\n const id = stack.pop() as string\n if (seen.has(id) || !owns(nodes, id)) continue\n seen.add(id)\n order.push(id)\n const children = (nodes[id] as ComposedMediaNode | null)?.nodes\n if (!Array.isArray(children)) continue\n for (let index = children.length - 1; index >= 0; index -= 1) {\n const child = children[index]\n if (typeof child === 'string' && !seen.has(child)) stack.push(child)\n }\n }\n for (const id in nodes) if (!seen.has(id)) order.push(id)\n return order\n}\n\n/**\n * Every distinct library asset the Image and Video nodes in a map place:\n * films first, then images, each in document order.\n *\n * A read that is capped honors that order. A film goes first because its\n * stale facts are the worse render (a player of the wrong shape and a\n * thumbnail that 404s, against a reservation that corrects itself when an\n * image decodes), and document order covers the top of the page before its\n * footer.\n *\n * `[]` for a page that places none, so a caller that gates its read on the\n * length spends nothing on it. A pinned and an unpinned reference to one\n * asset are one entry: a pin names bytes, not a different asset.\n */\nexport function mediaAssetRefs(\n nodes: Record<string, unknown> | null | undefined,\n options: MediaAssetFactsOptions = {},\n): MediaRef[] {\n const refs: MediaRef[] = []\n if (!nodes) return refs\n const order = documentOrder(nodes)\n const seen = new Set<string>()\n for (const element of [VIDEO_COMPONENT_ID, IMAGE_COMPONENT_ID] as const) {\n if (options.only && options.only !== element) continue\n for (const id of order) {\n const node = nodes[id] as ComposedMediaNode | null\n if (node?.componentId !== element) continue\n const ref = placedAsset(node)\n if (!ref) continue\n const key = mediaAssetFactsKey(ref)\n if (seen.has(key)) continue\n seen.add(key)\n refs.push(ref)\n }\n }\n // A markdown body's images come LAST, and only when the caller wants every\n // element (AGL-3149). Last because of what a capped read costs each kind: a\n // placement that misses out renders at its pick-time pair, a body image that\n // misses out renders exactly as it does today, and a film that misses out\n // gets a player of the wrong shape. Only-when-unfiltered because `only` asks\n // for one ELEMENT's placements, and a body image is not a placement of the\n // Image element — the video-asset reader would otherwise read image\n // documents it has no use for.\n if (options.only) return refs\n for (const id of order) {\n const body = markdownBody(nodes[id] as ComposedMediaNode | null)\n for (const { ref } of markdownImageRefs(body)) {\n const key = mediaAssetFactsKey(ref)\n if (seen.has(key)) continue\n seen.add(key)\n refs.push(ref)\n }\n }\n return refs\n}\n\nconst usable = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value) && value > 0\n\n/** A film's props with its asset's facts laid over them. See the module note. */\nfunction withFilmFacts(\n props: Record<string, unknown>,\n facts: MediaAssetFacts,\n): Record<string, unknown> {\n const live = videoMediaProps({\n componentId: VIDEO_COMPONENT_ID,\n propName: 'src',\n assetVideo: facts.video,\n assetPoster: facts.poster,\n })\n const {\n durationSeconds,\n intrinsicWidth,\n intrinsicHeight,\n posterFromSource: _storedPosterFlag,\n ...next\n } = props\n // The pick writes a duration only beside the pixel pair, so a pair is what\n // marks the stored duration as a copy rather than an author's own.\n const typedByAuthor = !(usable(intrinsicWidth) && usable(intrinsicHeight))\n if (live.durationSeconds !== undefined) {\n next['durationSeconds'] = live.durationSeconds\n } else if (typedByAuthor && durationSeconds !== undefined) {\n next['durationSeconds'] = durationSeconds\n }\n if (live.intrinsicWidth !== undefined && live.intrinsicHeight !== undefined) {\n next['intrinsicWidth'] = live.intrinsicWidth\n next['intrinsicHeight'] = live.intrinsicHeight\n }\n if (live.posterFromSource) next['posterFromSource'] = true\n return next\n}\n\n/**\n * An image's props with its asset's pair laid over them, or the SAME object\n * when the document records no usable pair or the stored one already matches.\n * See the module note.\n */\nfunction withImageFacts(\n props: Record<string, unknown>,\n facts: MediaAssetFacts,\n): Record<string, unknown> {\n // Through the pick's own gate, so the overlay and the pick agree on what a\n // usable pair is: both halves, finite and positive.\n const live = intrinsicMediaSize({\n componentId: IMAGE_COMPONENT_ID,\n propName: 'src',\n assetWidth: facts.width,\n assetHeight: facts.height,\n })\n const version = mediaVersionOf(facts)\n const pair =\n live.intrinsicWidth !== undefined && live.intrinsicHeight !== undefined\n const pairChanged =\n pair &&\n (props['intrinsicWidth'] !== live.intrinsicWidth ||\n props['intrinsicHeight'] !== live.intrinsicHeight)\n const versionChanged =\n version !== undefined && props[IMAGE_MEDIA_VERSION_PROP] !== version\n if (!pairChanged && !versionChanged) return props\n return {\n ...props,\n ...(pairChanged\n ? {\n intrinsicWidth: live.intrinsicWidth,\n intrinsicHeight: live.intrinsicHeight,\n }\n : {}),\n ...(versionChanged ? { [IMAGE_MEDIA_VERSION_PROP]: version } : {}),\n }\n}\n\n/**\n * The prop an Image placement carries its asset's current content hash in\n * (AGL-3485). Laid on at composition like the pixel pair and never an author\n * control: it describes the file, and `image.tsx` hands it to\n * `resolveMediaSrc` so the page names the versioned URL.\n */\nexport const IMAGE_MEDIA_VERSION_PROP = 'mediaVersion'\n\n/** The document's content hash, when it is one a URL can carry. */\nfunction mediaVersionOf(facts: MediaAssetFacts): string | undefined {\n return mediaCdnVersionToken(facts.contentHash) === undefined\n ? undefined\n : (facts.contentHash as string)\n}\n\n/**\n * The prop a markdown body carries its images' pixel pairs in, keyed by the\n * target the body wrote (AGL-3149).\n *\n * A body image is not a node, so it cannot take `intrinsicWidth` and\n * `intrinsicHeight` the way a placement does; the pairs travel together on the\n * element that holds the document, and the renderer looks each one up by the\n * parsed block's `src`.\n */\nexport const BODY_IMAGE_SIZES_PROP = 'intrinsicSizes'\n\n/** One body image's pair, as {@link BODY_IMAGE_SIZES_PROP} carries it. */\nexport interface BodyImageSize {\n width: number\n height: number\n /** The asset's content hash, for the versioned URL (AGL-3485). */\n version?: string\n}\n\n/**\n * A markdown body's props with a pair for each library image it names, or the\n * SAME object when no image in it can be answered for.\n *\n * Only images whose document records a usable pair get an entry, through the\n * same {@link intrinsicMediaSize} gate a placement goes through. An image left\n * out is one the renderer must give today's markup: `srcSet` without the pair\n * makes `sizes` the image's rendered width, which upscales anything narrower\n * than the column, so a partial answer is worse here than no answer.\n */\nfunction withBodyImageFacts(\n props: Record<string, unknown>,\n componentId: string | undefined,\n facts: ReadonlyMap<string, MediaAssetFacts>,\n): Record<string, unknown> {\n // THIS object's own body, never the node's resolved one: `props` on a bound\n // entry body still holds the `{{entry.body}}` token, and pairs for images it\n // does not name are bytes in the tree that nothing can ever look up.\n let sizes: Record<string, BodyImageSize> | undefined\n for (const { target, ref } of markdownImageRefs(\n markdownBodyOf(props, componentId),\n )) {\n const found = facts.get(mediaAssetFactsKey(ref))\n if (!found) continue\n const live = intrinsicMediaSize({\n componentId: IMAGE_COMPONENT_ID,\n propName: 'src',\n assetWidth: found.width,\n assetHeight: found.height,\n })\n if (\n live.intrinsicWidth === undefined ||\n live.intrinsicHeight === undefined\n ) {\n continue\n }\n if (!sizes) sizes = {}\n const version = mediaVersionOf(found)\n sizes[target] = {\n width: live.intrinsicWidth,\n height: live.intrinsicHeight,\n ...(version ? { version } : {}),\n }\n }\n if (!sizes) return props\n return { ...props, [BODY_IMAGE_SIZES_PROP]: sizes }\n}\n\n/**\n * The composed map with each placed asset's facts laid over its node, and each\n * markdown body's images' pairs laid over the element holding the body.\n *\n * `facts` is keyed by {@link mediaAssetFactsKey}. A placement with no entry,\n * because the reader could not answer for its asset, keeps its stored props.\n * The SAME map comes back when nothing changes, so a page with no library\n * asset pays for one walk and no copy, and the input is never mutated either\n * way.\n */\nexport function applyMediaAssetFacts<T extends Record<string, unknown>>(\n nodes: T,\n facts: ReadonlyMap<string, MediaAssetFacts>,\n options: MediaAssetFactsOptions = {},\n): T {\n if (!facts.size) return nodes\n let applied: Record<string, unknown> | undefined\n const write = (id: string, node: ComposedMediaNode, next: {\n props?: Record<string, unknown>\n resolvedProps?: Record<string, unknown>\n }): void => {\n if (!applied) applied = { ...nodes }\n applied[id] = {\n ...node,\n ...(next.props ? { props: next.props } : {}),\n ...(next.resolvedProps ? { resolvedProps: next.resolvedProps } : {}),\n }\n }\n for (const id in nodes) {\n const node = nodes[id] as ComposedMediaNode\n const ref = placedAsset(node, options.only)\n const found = ref ? facts.get(mediaAssetFactsKey(ref)) : undefined\n if (found) {\n const overlay =\n node.componentId === VIDEO_COMPONENT_ID ? withFilmFacts : withImageFacts\n const props = node.props && overlay(node.props, found)\n const resolvedProps =\n node.resolvedProps && overlay(node.resolvedProps, found)\n if (props === node.props && resolvedProps === node.resolvedProps) continue\n write(id, node, { props, resolvedProps })\n continue\n }\n // A markdown body, under the same `only` rule `mediaAssetRefs` collects\n // under: a body image is not a placement of the Image element, so a reader\n // asking for one element's placements is not asking about bodies.\n if (options.only) continue\n const { componentId } = node\n if (!componentId || !owns(MARKDOWN_BODY_PROPS, componentId)) continue\n const props =\n node.props && withBodyImageFacts(node.props, componentId, facts)\n const resolvedProps =\n node.resolvedProps &&\n withBodyImageFacts(node.resolvedProps, componentId, facts)\n if (props === node.props && resolvedProps === node.resolvedProps) continue\n write(id, node, { props, resolvedProps })\n }\n return applied ? (applied as T) : nodes\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","mediaCdnScopeRefusal","parseMediaCdnScope","intrinsicMediaSize","videoMediaProps","hostQualifiedScope","isMediaCdnPath","mediaCdnVersionToken","mediaRefFromCdnPath","parseMediaRef","VIDEO_COMPONENT_ID","IMAGE_COMPONENT_ID","MARKDOWN_BODY_PROPS","markdown","collectionEntryBody","ROOT_NODE_ID","MEDIA_ASSET_FACT_FIELDS","owns","map","key","Object","prototype","hasOwnProperty","call","mediaAssetFactsKey","ref","scope","mediaId","mediaAssetDocumentPath","isOrg","scopeId","mediaAssetFactsFromDocument","document","hostId","undefined","deletedAt","private","served","visibleTo","scopeMode","width","height","video","poster","contentHash","placedAsset","node","only","componentId","props","resolvedProps","placedRef","src","UNRESOLVED_TOKEN","markdownBodyOf","prop","text","test","trim","markdownBody","MARKDOWN_IMAGE_TARGET","markdownImageRefs","includes","found","match","matchAll","target","push","documentOrder","nodes","order","seen","Set","stack","length","id","pop","has","add","children","Array","isArray","index","child","mediaAssetRefs","options","refs","element","body","usable","value","Number","isFinite","withFilmFacts","facts","live","propName","assetVideo","assetPoster","durationSeconds","intrinsicWidth","intrinsicHeight","posterFromSource","_storedPosterFlag","next","typedByAuthor","withImageFacts","assetWidth","assetHeight","version","mediaVersionOf","pair","pairChanged","versionChanged","IMAGE_MEDIA_VERSION_PROP","BODY_IMAGE_SIZES_PROP","withBodyImageFacts","sizes","get","applyMediaAssetFacts","size","applied","write","overlay"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmEC,GAED,SAASA,sBAAsB,QAAQ,oCAAgC;AACvE,SAASC,oBAAoB,EAAEC,kBAAkB,QAAQ,uBAAmB;AAC5E,SAASC,kBAAkB,EAAEC,eAAe,QAAQ,sBAAkB;AACtE,SACEC,kBAAkB,EAClBC,cAAc,EACdC,oBAAoB,EAEpBC,mBAAmB,EACnBC,aAAa,QACR,iBAAa;AACpB,SAASC,kBAAkB,QAAQ,oBAAgB;AAEnD,6EAA6E,GAC7E,OAAO,MAAMC,qBAAqB,QAAO;AAEzC;;;;;;;;;;;;;;;;CAgBC,GACD,MAAMC,sBAAwD;IAC5DC,UAAU;IACVC,qBAAqB;AACvB;AAEA,uEAAuE,GACvE,MAAMC,eAAuBf;AA2B7B;;;;;;CAMC,GACD,OAAO,MAAMgB,0BAA0B;IACrC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AA4BV,MAAMC,OAAO,CAAC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that host's own library
|
|
23
|
-
* - `org:{orgId}` — the org library,
|
|
23
|
+
* - `org:{orgId}` — the org library: assets shared with every site, and assets
|
|
24
|
+
* shared with all sites except some (`mediaCdnScopeRefusal`)
|
|
24
25
|
* - `org:{orgId}:{hostId}` — an org asset in one site's context
|
|
25
26
|
*
|
|
26
27
|
* The host is in the URL rather than sniffed from the `Host` header on
|
|
@@ -59,7 +60,21 @@ export declare function parseMediaCdnScope(scopeSegment: string): MediaCdnScope
|
|
|
59
60
|
* this one needs a person either way.
|
|
60
61
|
*/
|
|
61
62
|
export type MediaCdnScopeRefusal = 'restricted' | 'unscoped' | 'no-sites';
|
|
62
|
-
/**
|
|
63
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Why the asset is refused under this URL; `null` when it is not.
|
|
65
|
+
*
|
|
66
|
+
* `scopeMode` is the document's own, passed by every caller. An asset shared
|
|
67
|
+
* with all sites except some has no `'org'` token (`visibleTo` lists the sites
|
|
68
|
+
* it IS on), and the bare `org:{orgId}` form still serves it. Bare URLs stay in
|
|
69
|
+
* the world after the choice is made, in raw HTML and CSS strings and in sent
|
|
70
|
+
* email, and refusing them would break every one the moment a single site was
|
|
71
|
+
* excluded. It widens nothing: the CDN is unauthenticated, and any included
|
|
72
|
+
* site's URL already serves these bytes to anyone. A private asset is a later,
|
|
73
|
+
* separate gate that demands a signature whichever form was asked for.
|
|
74
|
+
*
|
|
75
|
+
* The named-site form is unchanged, so an excluded site's URL is refused. So
|
|
76
|
+
* is a marked asset with no sites left, which is `no-sites` under every form.
|
|
77
|
+
*/
|
|
78
|
+
export declare function mediaCdnScopeRefusal(scope: MediaCdnScope, visibleTo: unknown, scopeMode?: unknown): MediaCdnScopeRefusal | null;
|
|
64
79
|
/** Whether the asset may be served under this URL. */
|
|
65
|
-
export declare function mediaCdnAllows(scope: MediaCdnScope, visibleTo: unknown): boolean;
|
|
80
|
+
export declare function mediaCdnAllows(scope: MediaCdnScope, visibleTo: unknown, scopeMode?: unknown): boolean;
|
|
@@ -35,7 +35,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
35
35
|
*
|
|
36
36
|
* Out of every barrel: the handler, the composition and the editor import it
|
|
37
37
|
* by path, and nothing here has a reason to reach a published page's bundle.
|
|
38
|
-
*/ import { isOrgWideScope, visibleToHost } from "./scope-tokens.js";
|
|
38
|
+
*/ import { isOrgWideScope, SCOPE_MODE_ALL_EXCEPT, visibleToHost } from "./scope-tokens.js";
|
|
39
39
|
/** One CDN path segment: a host id, an org id, a media id or a content hash. */ export const MEDIA_CDN_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
|
|
40
40
|
export function parseMediaCdnScope(scopeSegment) {
|
|
41
41
|
if (!scopeSegment.startsWith('org:')) {
|
|
@@ -58,18 +58,32 @@ export function parseMediaCdnScope(scopeSegment) {
|
|
|
58
58
|
contextHostId
|
|
59
59
|
} : {});
|
|
60
60
|
}
|
|
61
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* Why the asset is refused under this URL; `null` when it is not.
|
|
63
|
+
*
|
|
64
|
+
* `scopeMode` is the document's own, passed by every caller. An asset shared
|
|
65
|
+
* with all sites except some has no `'org'` token (`visibleTo` lists the sites
|
|
66
|
+
* it IS on), and the bare `org:{orgId}` form still serves it. Bare URLs stay in
|
|
67
|
+
* the world after the choice is made, in raw HTML and CSS strings and in sent
|
|
68
|
+
* email, and refusing them would break every one the moment a single site was
|
|
69
|
+
* excluded. It widens nothing: the CDN is unauthenticated, and any included
|
|
70
|
+
* site's URL already serves these bytes to anyone. A private asset is a later,
|
|
71
|
+
* separate gate that demands a signature whichever form was asked for.
|
|
72
|
+
*
|
|
73
|
+
* The named-site form is unchanged, so an excluded site's URL is refused. So
|
|
74
|
+
* is a marked asset with no sites left, which is `no-sites` under every form.
|
|
75
|
+
*/ export function mediaCdnScopeRefusal(scope, visibleTo, scopeMode) {
|
|
62
76
|
// Host-library assets are private by construction and carry no
|
|
63
77
|
// `visibleTo`, so only the org branch is scoped at all.
|
|
64
78
|
if (!scope.isOrg) return null;
|
|
65
79
|
if (!Array.isArray(visibleTo)) return 'unscoped';
|
|
66
80
|
if (!visibleTo.length) return 'no-sites';
|
|
67
81
|
const scoped = visibleTo;
|
|
68
|
-
const allowed = scope.contextHostId ? visibleToHost(scoped, scope.contextHostId) : isOrgWideScope(scoped);
|
|
82
|
+
const allowed = scope.contextHostId ? visibleToHost(scoped, scope.contextHostId) : isOrgWideScope(scoped) || scopeMode === SCOPE_MODE_ALL_EXCEPT;
|
|
69
83
|
return allowed ? null : 'restricted';
|
|
70
84
|
}
|
|
71
|
-
/** Whether the asset may be served under this URL. */ export function mediaCdnAllows(scope, visibleTo) {
|
|
72
|
-
return mediaCdnScopeRefusal(scope, visibleTo) === null;
|
|
85
|
+
/** Whether the asset may be served under this URL. */ export function mediaCdnAllows(scope, visibleTo, scopeMode) {
|
|
86
|
+
return mediaCdnScopeRefusal(scope, visibleTo, scopeMode) === null;
|
|
73
87
|
}
|
|
74
88
|
|
|
75
89
|
//# sourceMappingURL=media-cdn-scope.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/media-cdn-scope.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/**\n * The media CDN's scope grammar and the verdict it reaches under it\n * (AGL-1043), as pure functions.\n *\n * `serveMediaCdn` enforces them and re-exports them, so the handler remains\n * the authority. They live here, in a module with no server dependency,\n * because two other readers have to reach the verdict the handler reaches\n * before it serves a file:\n *\n * - the tenant composition, which lays a placed asset's current facts over its\n * node only when the page's own URL would be served\n * (`libs/tenant/runtime/src/lib/get-media-asset-facts.ts`);\n * - the besigner canvas and Preview, which read the same document in the\n * browser so an author is shown what a visitor gets.\n *\n * Both reach it through `mediaAssetFactsFromDocument` in\n * `media-asset-facts.ts`. A copy in either would be a second rule, free to\n * disagree with the one that refuses the bytes.\n *\n * Out of every barrel: the handler, the composition and the editor import it\n * by path, and nothing here has a reason to reach a published page's bundle.\n */\n\nimport { isOrgWideScope, visibleToHost } from './scope-tokens'\n\n/** One CDN path segment: a host id, an org id, a media id or a content hash. */\nexport const MEDIA_CDN_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/\n\n/**\n * The parsed CDN scope segment (AGL-1043). Shapes:\n *\n * - `{hostId}` — that host's own library\n * - `org:{orgId}` — the org library,
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/media-cdn-scope.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/**\n * The media CDN's scope grammar and the verdict it reaches under it\n * (AGL-1043), as pure functions.\n *\n * `serveMediaCdn` enforces them and re-exports them, so the handler remains\n * the authority. They live here, in a module with no server dependency,\n * because two other readers have to reach the verdict the handler reaches\n * before it serves a file:\n *\n * - the tenant composition, which lays a placed asset's current facts over its\n * node only when the page's own URL would be served\n * (`libs/tenant/runtime/src/lib/get-media-asset-facts.ts`);\n * - the besigner canvas and Preview, which read the same document in the\n * browser so an author is shown what a visitor gets.\n *\n * Both reach it through `mediaAssetFactsFromDocument` in\n * `media-asset-facts.ts`. A copy in either would be a second rule, free to\n * disagree with the one that refuses the bytes.\n *\n * Out of every barrel: the handler, the composition and the editor import it\n * by path, and nothing here has a reason to reach a published page's bundle.\n */\n\nimport { isOrgWideScope, SCOPE_MODE_ALL_EXCEPT, visibleToHost } from './scope-tokens'\n\n/** One CDN path segment: a host id, an org id, a media id or a content hash. */\nexport const MEDIA_CDN_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/\n\n/**\n * The parsed CDN scope segment (AGL-1043). Shapes:\n *\n * - `{hostId}` — that host's own library\n * - `org:{orgId}` — the org library: assets shared with every site, and assets\n * shared with all sites except some (`mediaCdnScopeRefusal`)\n * - `org:{orgId}:{hostId}` — an org asset in one site's context\n *\n * The host is in the URL rather than sniffed from the `Host` header on\n * purpose. A header is the requester's CHOICE: anyone holding a restricted\n * asset's id could fetch it through a domain that IS permitted and get the\n * bytes, so header-based enforcement stops accidents while looking like a\n * boundary. Here the decision is a pure function of (URL, doc), and since\n * the cache key IS the URL, one host's answer can never reach another.\n */\nexport interface MediaCdnScope {\n isOrg: boolean\n scopeId: string\n /** Only on the `org:{orgId}:{hostId}` form. */\n contextHostId?: string\n}\n\nexport function parseMediaCdnScope(\n scopeSegment: string,\n): MediaCdnScope | null {\n if (!scopeSegment.startsWith('org:')) {\n return MEDIA_CDN_SEGMENT.test(scopeSegment)\n ? { isOrg: false, scopeId: scopeSegment }\n : null\n }\n const parts = scopeSegment.slice('org:'.length).split(':')\n if (parts.length > 2) return null\n const [scopeId, contextHostId] = parts\n if (!MEDIA_CDN_SEGMENT.test(scopeId ?? '')) return null\n if (contextHostId !== undefined && !MEDIA_CDN_SEGMENT.test(contextHostId)) {\n return null\n }\n return {\n isOrg: true,\n scopeId,\n ...(contextHostId ? { contextHostId } : {}),\n }\n}\n\n/**\n * The three ways an org asset can be refused under a CDN URL.\n *\n * They are one 404 on the wire — whether a restricted asset exists is not\n * something an anonymous caller has standing to learn — and three different\n * faults to whoever is looking at the broken page:\n *\n * - `restricted` — the asset carries a scope and this URL is not in it. The\n * URL is what is wrong: a restricted asset has to be requested through the\n * form that names the site (`hostQualifiedCdnPath`), and the same asset\n * serves normally from the site it is shared with.\n * - `unscoped` — no `visibleTo` at all, so the asset is undeliverable under\n * EVERY URL form there is. The document is what is wrong, and it means a\n * creation path wrote it without a scope: `newResourceScopeFields` is what\n * stops that at compile time, and the scope backfill is what repairs the\n * documents already written (`docs/SCOPE_DRIFT.md`).\n * - `no-sites` — a stored empty array: somebody chose nobody. Equally\n * undeliverable, and NOT repairable by the backfill, which leaves an empty\n * array alone rather than widening a resource nobody asked to widen — so\n * this one needs a person either way.\n */\nexport type MediaCdnScopeRefusal = 'restricted' | 'unscoped' | 'no-sites'\n\n/**\n * Why the asset is refused under this URL; `null` when it is not.\n *\n * `scopeMode` is the document's own, passed by every caller. An asset shared\n * with all sites except some has no `'org'` token (`visibleTo` lists the sites\n * it IS on), and the bare `org:{orgId}` form still serves it. Bare URLs stay in\n * the world after the choice is made, in raw HTML and CSS strings and in sent\n * email, and refusing them would break every one the moment a single site was\n * excluded. It widens nothing: the CDN is unauthenticated, and any included\n * site's URL already serves these bytes to anyone. A private asset is a later,\n * separate gate that demands a signature whichever form was asked for.\n *\n * The named-site form is unchanged, so an excluded site's URL is refused. So\n * is a marked asset with no sites left, which is `no-sites` under every form.\n */\nexport function mediaCdnScopeRefusal(\n scope: MediaCdnScope,\n visibleTo: unknown,\n scopeMode?: unknown,\n): MediaCdnScopeRefusal | null {\n // Host-library assets are private by construction and carry no\n // `visibleTo`, so only the org branch is scoped at all.\n if (!scope.isOrg) return null\n if (!Array.isArray(visibleTo)) return 'unscoped'\n if (!visibleTo.length) return 'no-sites'\n const scoped = visibleTo as string[]\n const allowed = scope.contextHostId\n ? visibleToHost(scoped, scope.contextHostId)\n : isOrgWideScope(scoped) || scopeMode === SCOPE_MODE_ALL_EXCEPT\n return allowed ? null : 'restricted'\n}\n\n/** Whether the asset may be served under this URL. */\nexport function mediaCdnAllows(\n scope: MediaCdnScope,\n visibleTo: unknown,\n scopeMode?: unknown,\n): boolean {\n return mediaCdnScopeRefusal(scope, visibleTo, scopeMode) === null\n}\n"],"names":["isOrgWideScope","SCOPE_MODE_ALL_EXCEPT","visibleToHost","MEDIA_CDN_SEGMENT","parseMediaCdnScope","scopeSegment","startsWith","test","isOrg","scopeId","parts","slice","length","split","contextHostId","undefined","mediaCdnScopeRefusal","scope","visibleTo","scopeMode","Array","isArray","scoped","allowed","mediaCdnAllows"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;CAqBC,GAED,SAASA,cAAc,EAAEC,qBAAqB,EAAEC,aAAa,QAAQ,oBAAgB;AAErF,8EAA8E,GAC9E,OAAO,MAAMC,oBAAoB,wBAAuB;AAwBxD,OAAO,SAASC,mBACdC,YAAoB;IAEpB,IAAI,CAACA,aAAaC,UAAU,CAAC,SAAS;QACpC,OAAOH,kBAAkBI,IAAI,CAACF,gBAC1B;YAAEG,OAAO;YAAOC,SAASJ;QAAa,IACtC;IACN;IACA,MAAMK,QAAQL,aAAaM,KAAK,CAAC,OAAOC,MAAM,EAAEC,KAAK,CAAC;IACtD,IAAIH,MAAME,MAAM,GAAG,GAAG,OAAO;IAC7B,MAAM,CAACH,SAASK,cAAc,GAAGJ;IACjC,IAAI,CAACP,kBAAkBI,IAAI,CAACE,kBAAAA,UAAW,KAAK,OAAO;IACnD,IAAIK,kBAAkBC,aAAa,CAACZ,kBAAkBI,IAAI,CAACO,gBAAgB;QACzE,OAAO;IACT;IACA,OAAO;QACLN,OAAO;QACPC;OACIK,gBAAgB;QAAEA;IAAc,IAAI,CAAC;AAE7C;AAyBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASE,qBACdC,KAAoB,EACpBC,SAAkB,EAClBC,SAAmB;IAEnB,+DAA+D;IAC/D,wDAAwD;IACxD,IAAI,CAACF,MAAMT,KAAK,EAAE,OAAO;IACzB,IAAI,CAACY,MAAMC,OAAO,CAACH,YAAY,OAAO;IACtC,IAAI,CAACA,UAAUN,MAAM,EAAE,OAAO;IAC9B,MAAMU,SAASJ;IACf,MAAMK,UAAUN,MAAMH,aAAa,GAC/BZ,cAAcoB,QAAQL,MAAMH,aAAa,IACzCd,eAAesB,WAAWH,cAAclB;IAC5C,OAAOsB,UAAU,OAAO;AAC1B;AAEA,oDAAoD,GACpD,OAAO,SAASC,eACdP,KAAoB,EACpBC,SAAkB,EAClBC,SAAmB;IAEnB,OAAOH,qBAAqBC,OAAOC,WAAWC,eAAe;AAC/D"}
|
|
@@ -232,8 +232,9 @@ export declare function isMediaCdnPath(value: unknown): value is string;
|
|
|
232
232
|
* Rewrites an org scope so it names the site doing the rendering — the
|
|
233
233
|
* scope-segment twin of `hostQualifiedCdnPath` (AGL-1043).
|
|
234
234
|
*
|
|
235
|
-
* `org:{orgId}` serves
|
|
236
|
-
*
|
|
235
|
+
* `org:{orgId}` serves org-wide assets, and assets shared with all sites
|
|
236
|
+
* except some; an asset shared with chosen sites has to be asked for through
|
|
237
|
+
* `org:{orgId}:{hostId}`,
|
|
237
238
|
* because the CDN is unauthenticated and the URL is the only thing it can
|
|
238
239
|
* decide from. The qualified form is a superset — it also serves org-wide
|
|
239
240
|
* assets, since `visibleToHost` is true for `['org']` — so qualifying
|
|
@@ -272,10 +273,13 @@ export interface ResolveMediaSrcOptions {
|
|
|
272
273
|
* 2. a **Storage download URL for a library object** → the same CDN URL,
|
|
273
274
|
* exactly as if the reference had been stored (AGL-3506). See
|
|
274
275
|
* {@link mediaRefFromStorageUrl};
|
|
275
|
-
* 3.
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
* 4. empty
|
|
276
|
+
* 3. a **legacy stored CDN path** written by the first pass → itself, naming
|
|
277
|
+
* the site doing the rendering if its org scope names none yet. See
|
|
278
|
+
* {@link hostQualifiedLegacyPath};
|
|
279
|
+
* 4. any other non-empty string → **itself, untouched**. An author-typed
|
|
280
|
+
* external URL for a hotlinked image is passed through, and so is a signed
|
|
281
|
+
* CDN URL, which {@link isMediaCdnPath} does not answer for;
|
|
282
|
+
* 5. empty/absent → undefined, so the caller shows its placeholder.
|
|
279
283
|
*
|
|
280
284
|
* Branch 2 is what routes every library byte through the CDN. A download
|
|
281
285
|
* URL goes from Google's edge straight to the visitor, so no code of ours
|