@aglyn/aglyn 1.11.0 → 1.13.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/account-preferences.d.ts +15 -13
- package/src/lib/app-utils/account-preferences.js +20 -20
- package/src/lib/app-utils/account-preferences.js.map +1 -1
- package/src/lib/app-utils/crm.d.ts +3 -1
- package/src/lib/app-utils/crm.js +6 -3
- package/src/lib/app-utils/crm.js.map +1 -1
- package/src/lib/app-utils/docs-help-sections.generated.js +10 -4
- package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +2 -2
- package/src/lib/app-utils/docs-help.generated.js +8 -0
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +117 -96
- package/src/lib/app-utils/docs-index.generated.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/markdown-lite.js +8 -1
- package/src/lib/app-utils/markdown-lite.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/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 +13 -0
- package/src/lib/app-utils/org-role-grants.js +9 -5
- package/src/lib/app-utils/org-role-grants.js.map +1 -1
- package/src/lib/app-utils/person-erasure.d.ts +8 -0
- package/src/lib/app-utils/person-erasure.js +6 -0
- package/src/lib/app-utils/person-erasure.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 +56 -0
- package/src/lib/app-utils/site-placement.js +88 -0
- package/src/lib/app-utils/site-placement.js.map +1 -0
- package/src/lib/app-utils/site-preview.d.ts +6 -2
- package/src/lib/app-utils/site-preview.js +5 -3
- package/src/lib/app-utils/site-preview.js.map +1 -1
- package/src/lib/app-utils/site-unavailable.d.ts +4 -7
- package/src/lib/app-utils/site-unavailable.js +4 -8
- package/src/lib/app-utils/site-unavailable.js.map +1 -1
- 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/foundation/definitions/org-billing.types.js +2 -2
- package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
- package/src/lib/foundation/definitions/platform.types.d.ts +1 -1
- package/src/lib/foundation/definitions/platform.types.js.map +1 -1
- package/src/lib/foundation/definitions/write-deny-coverage.util.d.ts +1 -1
- package/src/lib/foundation/definitions/write-deny-coverage.util.js +1 -1
- package/src/lib/foundation/definitions/write-deny-coverage.util.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.js +4 -5
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/plugin-contact-capture.d.ts +18 -0
- package/src/lib/plugin-manager/plugin-contact-capture.js +26 -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-person-erasure-notes.d.ts +61 -0
- package/src/lib/plugin-manager/plugin-person-erasure-notes.js +114 -0
- package/src/lib/plugin-manager/plugin-person-erasure-notes.js.map +1 -0
- 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-site-starters.d.ts +7 -0
- package/src/lib/plugin-manager/plugin-site-starters.js.map +1 -1
- 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
|
@@ -77,6 +77,18 @@ export declare function resolveSiteRolePresetPermissions(member: (Partial<AglynO
|
|
|
77
77
|
export declare function applySiteRolePresets<T extends Record<string, boolean>>(granted: T, member: (Partial<AglynOrgMember> & {
|
|
78
78
|
roleId?: string | null;
|
|
79
79
|
}) | null | undefined, hostId: HostUid | null | undefined, customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null): T;
|
|
80
|
+
/**
|
|
81
|
+
* The keys a site RAISES for a member of the whole workspace (AGL-4047): on a
|
|
82
|
+
* site where their access is wider than their workspace role, each
|
|
83
|
+
* `raisesPerSite` key they hold by that access's `hostRoleDefaults`. Only the
|
|
84
|
+
* keys it raises are in the answer, so a resolver spreads it over what the
|
|
85
|
+
* workspace already answered. A custom role or their own permissions deciding
|
|
86
|
+
* the key, or the key it follows, stands: a raise is a default, never a way
|
|
87
|
+
* round a decision someone wrote down.
|
|
88
|
+
*/
|
|
89
|
+
export declare function resolveSiteRaisedPermissions(member: (Partial<AglynOrgMember> & {
|
|
90
|
+
roleId?: string | null;
|
|
91
|
+
}) | null | undefined, hostId: HostUid | null | undefined, customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null): Record<string, boolean>;
|
|
80
92
|
/**
|
|
81
93
|
* The verdict the site's own stamp gives a member for one key whose preset
|
|
82
94
|
* is the site role, as the Firestore rules read it (AGL-4047): the site's
|
|
@@ -179,7 +179,32 @@ import { orgRoleTier } from "./org-roles.js";
|
|
|
179
179
|
* it unconditionally.
|
|
180
180
|
*/ export function applySiteRolePresets(granted, member, hostId, customRole) {
|
|
181
181
|
if (!hostId) return granted;
|
|
182
|
-
return _extends({}, granted, resolveSiteRolePresetPermissions(member, hostId, customRole));
|
|
182
|
+
return _extends({}, granted, resolveSiteRolePresetPermissions(member, hostId, customRole), resolveSiteRaisedPermissions(member, hostId, customRole));
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The keys a site RAISES for a member of the whole workspace (AGL-4047): on a
|
|
186
|
+
* site where their access is wider than their workspace role, each
|
|
187
|
+
* `raisesPerSite` key they hold by that access's `hostRoleDefaults`. Only the
|
|
188
|
+
* keys it raises are in the answer, so a resolver spreads it over what the
|
|
189
|
+
* workspace already answered. A custom role or their own permissions deciding
|
|
190
|
+
* the key, or the key it follows, stands: a raise is a default, never a way
|
|
191
|
+
* round a decision someone wrote down.
|
|
192
|
+
*/ export function resolveSiteRaisedPermissions(member, hostId, customRole) {
|
|
193
|
+
const out = {};
|
|
194
|
+
if (!member || !hostId || !isOrgWideMember(member)) return out;
|
|
195
|
+
const role = hostRoleFor(member, hostId);
|
|
196
|
+
if (!role || HOST_ROLE_RANK[role] <= HOST_ROLE_RANK[orgRoleTier(member.role)]) return out;
|
|
197
|
+
const layers = [
|
|
198
|
+
member.roleId ? customRole == null ? void 0 : customRole.permissions : undefined,
|
|
199
|
+
member.permissions
|
|
200
|
+
];
|
|
201
|
+
const decided = (key)=>Boolean(key) && layers.some((layer)=>typeof (layer == null ? void 0 : layer[key]) === 'boolean');
|
|
202
|
+
for (const definition of ORG_PERMISSIONS){
|
|
203
|
+
var _definition_hostRoleDefaults;
|
|
204
|
+
if (!definition.raisesPerSite || decided(definition.key) || decided(definition.follows)) continue;
|
|
205
|
+
if (((_definition_hostRoleDefaults = definition.hostRoleDefaults) == null ? void 0 : _definition_hostRoleDefaults[role]) === true) out[definition.key] = true;
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
183
208
|
}
|
|
184
209
|
/**
|
|
185
210
|
* The verdict the site's own stamp gives a member for one key whose preset
|
|
@@ -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,WAA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;;;;CAMC,GACD,OAAO,SAASoH,oBACdD,OAAyB,EACzBjE,GAA8B,EAC9BtC,GAAW,EACXuC,SAA6D;IAE7D,IAAI,CAACgE,WAAW,CAACjE,KAAK,OAAO;IAC7B,wEAAwE;IACxE,qEAAqE;IACrE,MAAMmE,OAAO,CAACC,QACZ,OAAO,AAACH,QAA8Bd,GAAG,KAAK,aAC1C,AAACc,QAA4Cd,GAAG,CAACiB,SACjD,AAACH,OAAmC,CAACG,MAAM;IACjD,OAAOtE,0BACL;QAAEK,mBAAmBgE,KAAK;QAAsB/D,aAAa+D,KAAK;IAAe,GACjFnE,KACAtC,KACAuC;AAEJ;AAEA;;;CAGC,GACD,OAAO,SAASoE,eAAe3G,GAAW;IACxC,OAAOX,sBAAsBW;AAC/B"}
|
|
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 {\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;;;;;CA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MC,aAAiE,CAAC;IACxE,KAAK,MAAM5F,UAAU0F,QAAS;YAIGC;QAH/B,IAAI,CAACpH,YAAYyB,QAAQC,SAAS;QAClC2F,UAAU,CAAC5F,OAAO6F,GAAG,CAAC,GAAGN,6BAA6B;YACpDvF;YACAa,YAAYb,OAAOkB,MAAM,IAAIyE,mBAAAA,YAAYV,GAAG,CAACjF,OAAOkB,MAAM,aAA7ByE,mBAAkC,OAAQ;YACvE1F;QACF;IACF;IACA,OAAO2F;AACT;AAYA;;;;;;;;CAQC,GACD,OAAO,SAASE,aAAaC,OAAyB,EAAE9D,GAAW,EAAE5C,GAAgB;QACrCZ;IAA9C,OAAOuH,oBAAoBD,SAAS9D,KAAK5C,MAAKZ,8BAAAA,sBAAsB,CAACY,IAAI,YAA3BZ,8BAA+B,CAAC;AAChF;AAEA;;;;;;CAMC,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"}
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* so there is nothing to sanitize).
|
|
22
22
|
*/ import { isMediaRef, parseMediaRef } from "./media-ref.js";
|
|
23
23
|
import { parseCollectionLinkValue, parseEntryLinkValue, parseFeedLinkValue, parseScreenLinkValue, resolveScreenHref, SCREEN_LINK_VALUE_PREFIX, screenRoutesAnswerFor } from "./screen-link-value.js";
|
|
24
|
-
const INLINE_PATTERN = /(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(\[([^\]]+)\]\(([^)\s]+)\))/g;
|
|
24
|
+
const INLINE_PATTERN = /(\*\*([^*]+)\*\*)|(\*([^*]+)\*)|(\[([^\]]+)\]\(([^)\s]+)\))|(?<![\w_])_([^_\n]+)_(?![\w_])/g;
|
|
25
25
|
/**
|
|
26
26
|
* Only absolute http(s) survives; anything else renders as text. The `http:`
|
|
27
27
|
* half reaches LINKS only — {@link safeImageUrl} refuses it before it gets
|
|
@@ -214,6 +214,13 @@ export function parseMarkdownInlines(text) {
|
|
|
214
214
|
type: 'italic',
|
|
215
215
|
text: match[4]
|
|
216
216
|
});
|
|
217
|
+
} else if (match[8] != null) {
|
|
218
|
+
// `_italic_` (AGL-4182). Only as a whole word, so `snake_case_name` and
|
|
219
|
+
// a file name stay as they were typed.
|
|
220
|
+
inlines.push({
|
|
221
|
+
type: 'italic',
|
|
222
|
+
text: match[8]
|
|
223
|
+
});
|
|
217
224
|
} else if (match[6] != null) {
|
|
218
225
|
const href = safeLinkUrl(match[7]);
|
|
219
226
|
if (href) inlines.push({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/markdown-lite.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 * Markdown-lite (AGL-123): the tiny subset blog entries use — headings,\n * bold/italic, links, images, bullet and numbered lists, paragraphs, fenced\n * code blocks, tables and blockquotes. Parsed into plain data blocks that\n * renderers turn into elements themselves (no HTML string is ever produced,\n * so there is nothing to sanitize).\n */\n\nimport { isMediaRef, parseMediaRef } from './media-ref'\nimport {\n parseCollectionLinkValue,\n parseEntryLinkValue,\n parseFeedLinkValue,\n parseScreenLinkValue,\n resolveScreenHref,\n SCREEN_LINK_VALUE_PREFIX,\n screenRoutesAnswerFor,\n} from './screen-link-value'\n\nexport type MarkdownInline =\n | { type: 'text'; text: string }\n | { type: 'bold'; text: string }\n | { type: 'italic'; text: string }\n | { type: 'link'; text: string; href: string }\n\n/** A table cell's content. Cells hold inline runs only — no nesting. */\nexport type MarkdownTableCell = MarkdownInline[]\nexport type MarkdownTableAlign = 'left' | 'center' | 'right'\n\nexport type MarkdownBlock =\n | { type: 'heading'; level: 2 | 3; inlines: MarkdownInline[] }\n | { type: 'paragraph'; inlines: MarkdownInline[] }\n /**\n * A `> ` quote (AGL-1315) — the article template's pull-quote. Like a\n * paragraph, one inline run: consecutive `> ` lines of a chunk join with\n * spaces (a bare `>` continues the group and contributes nothing). The\n * dialect has NO nesting — a second `>` is just text of the quote.\n */\n | { type: 'quote'; inlines: MarkdownInline[] }\n | { type: 'image'; src: string; alt: string }\n | { type: 'list'; items: MarkdownInline[][] }\n /**\n * A `1. ` / `1) ` numbered list (AGL-1320) — what a statute's enumerated\n * elements need, and what `/legal/dmca` was flattening into run-on prose.\n * `start` is the FIRST marker's number, so a notice continuing at `7.`\n * keeps counting from seven; the rest renumber from it, which is how the\n * serializer round-trips a `1. 1. 1.` source. A separate block rather than\n * a flag on `list`, so the six renderers have to name it and no ordered\n * list can silently render as bullets. NO nesting, like the rest of the\n * dialect: indentation is trimmed, so a ` 1. ` sub-item is a sibling.\n */\n | { type: 'orderedList'; start: number; items: MarkdownInline[][] }\n /** Fenced block. `text` is verbatim; `lang` is '' when none was given. */\n | { type: 'code'; lang: string; text: string }\n /**\n * A GFM pipe table (AGL-974). Rectangular by construction: every row and\n * `align` carry exactly `header.length` cells, so renderers never have to\n * reason about ragged input and the serializer round-trips exactly.\n */\n | {\n type: 'table'\n align: MarkdownTableAlign[]\n header: MarkdownTableCell[]\n rows: MarkdownTableCell[][]\n }\n\nconst INLINE_PATTERN =\n /(\\*\\*([^*]+)\\*\\*)|(\\*([^*]+)\\*)|(\\[([^\\]]+)\\]\\(([^)\\s]+)\\))/g\n\n/**\n * Only absolute http(s) survives; anything else renders as text. The `http:`\n * half reaches LINKS only — {@link safeImageUrl} refuses it before it gets\n * here (AGL-1713).\n */\nfunction safeUrl(url: string): string | null {\n return /^https?:\\/\\//i.test(url) ? url : null\n}\n\n/**\n * Whether a link target is one the parser will keep — the PUBLIC half of\n * {@link safeLinkUrl}, so an editor can refuse what the parser would drop\n * instead of discovering the disagreement on the published page (AGL-1686).\n */\nexport function isSupportedLinkHref(url: string): boolean {\n return safeLinkUrl(url) !== null\n}\n\n/**\n * Whether an image source is one the parser will keep. The predicate an\n * authoring surface must validate against, for the reason\n * {@link isSupportedLinkHref} exists and one the editor learned the hard way:\n * AGL-1645 widened the visual editor's image check to accept site-relative\n * paths without widening this file, so every image picked from the media\n * library serialized into the document and then vanished on the next parse.\n * One predicate, two callers, no drift.\n */\nexport function isSupportedImageSrc(url: string): boolean {\n return safeImageUrl(url) !== null\n}\n\n/**\n * Whether a link target is a stored REFERENCE rather than an address\n * (AGL-3118): a screen, a collection listing, an entry or a feed, named by id\n * so a rename cannot break it. Only the marked, well-formed forms count — a\n * bare id is indistinguishable from a relative path with no slash, so it\n * stays what the dialect has always made of it.\n *\n * Kept verbatim in the parsed link: a renderer resolves it against the same\n * routing map element links use, and the serializer writes it back as typed.\n */\nexport function isMarkdownLinkReference(url: string): boolean {\n if (url.startsWith(SCREEN_LINK_VALUE_PREFIX)) {\n return parseScreenLinkValue(url) !== undefined\n }\n return (\n parseCollectionLinkValue(url) !== undefined ||\n parseEntryLinkValue(url) !== undefined ||\n parseFeedLinkValue(url) !== undefined\n )\n}\n\n/**\n * Link targets additionally allow SITE-RELATIVE paths (AGL-582) so entry\n * markdown can link to other pages of the same site — renderers give those\n * client-side navigation — and link REFERENCES (AGL-3118), which renderers\n * resolve to wherever the target lives now. Protocol-relative `//host` is\n * rejected: it would silently leave the site.\n */\nfunction safeLinkUrl(url: string): string | null {\n if (/^\\/(?!\\/)/.test(url)) return url\n if (isMarkdownLinkReference(url)) return url\n return safeUrl(url)\n}\n\n/**\n * Image sources take everything a link takes, PLUS a media reference\n * (AGL-1686).\n *\n * Images were the one slot still on absolute-`http(s)`-only, and that was\n * silently eating two forms the product now produces:\n *\n * 1. `media:{scope}/{mediaId}` — what \"Browse media\" stores everywhere else\n * (AGL-1215). The reference names the asset and lets the renderer decide\n * how to fetch it, which is the only form that survives a folder move, a\n * replace, a route change, and a component shared across sites.\n * 2. A site-relative `/api/media/cdn/…` or `/images/hero.png`. The visual\n * editor's own `isValidImageUrl` accepts these (AGL-1645) and\n * `safeLinkUrl` always has — so the parser was the one place that\n * disagreed, and it disagreed by DROPPING the whole block. An image with\n * an unparseable src emits no block at all, so the failure was not a\n * broken-image icon or a console error; the picture simply was not there.\n *\n * A malformed reference is still refused. `parseMediaRef` is the same grammar\n * `formatMediaRef` mints against, so `media:` junk an author typed never\n * becomes a block whose src no renderer can resolve — the parse boundary\n * keeps the promise `resolveMediaSrc` makes on the other side.\n *\n * Protocol-relative stays refused here exactly as it is for links.\n *\n * It takes two things LESS than a link. A link REFERENCE (AGL-3118) names a\n * page, not a file, so no renderer has a picture to fetch for one; kept, it\n * would reach an `<img src=\"entry:…\">`.\n *\n * And `http:` (AGL-1713). An image is fetched the moment the page renders; a\n * link is followed by the reader's\n * choice, past an interstitial the browser puts up. So an `http:` image on our\n * TLS pages is mixed content that every current browser blocks outright — the\n * permissive form never rendered a picture, it only moved the failure from\n * authoring time to the viewer, and stored a src that is a CSP violation\n * waiting for AGL-1702 to enforce. Refusing it here reports at authoring time\n * through `isSupportedImageSrc`, which the editor and the besigner picker both\n * validate against. This is the same asymmetry AGL-1701 struck between\n * `SAFE_SRC` and `SAFE_HREF` on the published marketplace node, and the same\n * reason it left `homepageUrl`/`repositoryUrl` as any-https.\n */\nfunction safeImageUrl(url: string): string | null {\n if (isMediaRef(url)) return parseMediaRef(url) ? url : null\n if (/^http:\\/\\//i.test(url)) return null\n if (isMarkdownLinkReference(url)) return null\n return safeLinkUrl(url)\n}\n\n/**\n * True for hrefs the parser emitted as site-relative (start with `/`) AND that\n * a client router can actually settle on.\n *\n * `/api/…` is excluded because those paths serve FILES, not pages —\n * `/api/media/cdn/{scope}/{id}` is the download URL every media reference\n * resolves to, and it is what \"Browse media\" hands an author who links a PDF\n * or a logo kit. Routed through `AppLink` the click starts a client-side\n * navigation that can never complete: the response is an attachment, so the\n * router mounts its navigation-pending overlay and waits forever.\n *\n * The tell is a page trapped behind a spinner, NOT a failed download — the\n * browser fetches the attachment underneath the overlay, so the file lands in\n * Downloads while the site sits there looking broken. That mismatch sends you\n * hunting the media endpoint, which answers `200` with a correct\n * `Content-Disposition: attachment` every time.\n *\n * Both callers use this purely to choose `AppLink` vs a plain anchor, so\n * narrowing it here fixes markdown bodies and collection item links together.\n */\nexport function isInternalMarkdownHref(href: string): boolean {\n return /^\\/(?!\\/)/.test(href) && !/^\\/api\\//.test(href)\n}\n\n/** How a renderer draws one parsed link — see {@link resolveMarkdownLink}. */\nexport type MarkdownLinkResolution =\n /** The link's text alone, with no anchor: a reference to a missing target. */\n | { kind: 'text' }\n /** Drawn as a link with nothing to follow, on an editing surface. */\n | { kind: 'inert' }\n /** A page of this site, for client-side navigation. */\n | { kind: 'internal'; href: string }\n /** Anything else the parser kept, as a plain anchor. */\n | { kind: 'external'; href: string }\n\n/**\n * What one parsed link renders as (AGL-3118), for every markdown-lite\n * renderer on a site: the Markdown element, the entry body and the legacy\n * article surface.\n *\n * A link REFERENCE resolves against the routing map element links use, so a\n * link in a post follows its target through a rename exactly as a button\n * does, and a target the map does not have (unpublished, deleted, or never\n * asked for) renders as the link's text — never as an anchor whose href is\n * the stored reference. Every other href is the one the parser kept.\n *\n * An editing surface withholds every href, so there the only question is\n * whether a link is drawn at all: a reference the map KNOWS is gone reads as\n * the text the published page will show, and one the map cannot judge yet —\n * nothing of its kind has loaded — keeps the link look, for the reason\n * `isScreenLinkBroken` gives.\n */\nexport function resolveMarkdownLink(\n href: string,\n context: {\n screens?: Record<string, string> | null\n suppressNavigation?: boolean\n } = {},\n): MarkdownLinkResolution {\n const screens = context.screens ?? undefined\n const reference = isMarkdownLinkReference(href)\n const resolved = reference ? resolveScreenHref(screens, href) : href\n if (context.suppressNavigation) {\n const gone =\n reference &&\n resolved === undefined &&\n screenRoutesAnswerFor(screens, href)\n return gone ? { kind: 'text' } : { kind: 'inert' }\n }\n if (resolved === undefined) return { kind: 'text' }\n return isInternalMarkdownHref(resolved)\n ? { kind: 'internal', href: resolved }\n : { kind: 'external', href: resolved }\n}\n\n/**\n * Appends plain text, merging into a trailing text inline so the emitted\n * model is canonical (no adjacent text runs). Canonical inlines are what\n * makes `serializeMarkdownLite` a true inverse: a degraded link squeezed\n * between two text gaps re-parses to the same single text inline (AGL-582).\n */\nfunction pushText(inlines: MarkdownInline[], text: string): void {\n if (!text) return\n const last = inlines[inlines.length - 1]\n if (last?.type === 'text') last.text += text\n else inlines.push({ type: 'text', text })\n}\n\nexport function parseMarkdownInlines(text: string): MarkdownInline[] {\n const inlines: MarkdownInline[] = []\n let cursor = 0\n for (const match of text.matchAll(INLINE_PATTERN)) {\n const index = match.index ?? 0\n if (index > cursor) {\n pushText(inlines, text.slice(cursor, index))\n }\n if (match[2] != null) {\n inlines.push({ type: 'bold', text: match[2] })\n } else if (match[4] != null) {\n inlines.push({ type: 'italic', text: match[4] })\n } else if (match[6] != null) {\n const href = safeLinkUrl(match[7])\n if (href) inlines.push({ type: 'link', text: match[6], href })\n else pushText(inlines, match[6])\n }\n cursor = index + match[0].length\n }\n if (cursor < text.length) {\n pushText(inlines, text.slice(cursor))\n }\n return inlines\n}\n\n/**\n * An ATX heading at ANY of markdown's six levels (AGL-1082). The dialect only\n * RENDERS two, but it must not mistake the other four for prose: matching just\n * `#{2,3}` made `# Title` — how essentially every repo README opens — fall\n * through to a paragraph carrying a literal `#`, silently, in every renderer.\n */\nconst HEADING_PATTERN = /^(#{1,6})\\s+(.*)$/\n\n/**\n * Clamps an ATX level onto the two the block union carries. `#` promotes to\n * the top rendered level and `####`+ demote to the bottom one, so an out-of-\n * range heading degrades to the NEAREST heading rather than to prose — the\n * same lossy-but-visible degradation the dialect already applies to a `*`\n * inside a bold run. Deliberately NOT widening `level` to `1 | 2 | 3`: every\n * renderer reads it as `level === 2 ? h2 : h3`, so a third value would type-\n * check clean and silently render an h1 as an h3 in six places. This also\n * makes the markdown path agree with the HTML-paste path, which has always\n * mapped `<h1>` to a level-2 heading.\n */\nfunction clampHeadingLevel(hashes: number): 2 | 3 {\n return hashes <= 2 ? 2 : 3\n}\n\n/** ```` ``` ```` or longer, optionally naming a language. */\nconst FENCE_PATTERN = /^`{3,}\\s*([^\\s`]*)\\s*$/\n/** A bullet-list marker: `- ` or `* `. */\nconst BULLET_ITEM_PATTERN = /^[-*]\\s+/\n/**\n * An ordered-list marker (AGL-1320): `1. ` or `1) `, capped at nine digits\n * like CommonMark so a stray year cannot become an absurd `start`. The\n * trailing `\\s+` is load-bearing twice over: it keeps `1.no space` prose, and\n * it makes an EMPTY item impossible, which is the other half of CommonMark's\n * interrupt rule (a bare `1.` may not interrupt a paragraph either).\n */\nconst ORDERED_ITEM_PATTERN = /^(\\d{1,9})[.)]\\s+/\n/** A delimiter cell of a GFM table's second row: `---`, `:--`, `:-:`, `--:`. */\nconst DELIMITER_CELL = /^:?-+:?$/\n\n/** Splits a table row on `|`, dropping the optional outer pipes. */\nfunction splitTableRow(line: string): string[] {\n let text = line.trim()\n if (text.startsWith('|')) text = text.slice(1)\n if (text.endsWith('|')) text = text.slice(0, -1)\n return text.split('|').map((cell) => cell.trim())\n}\n\nfunction alignOfDelimiter(cell: string): MarkdownTableAlign {\n const left = cell.startsWith(':')\n const right = cell.endsWith(':')\n if (left && right) return 'center'\n return right ? 'right' : 'left'\n}\n\n/**\n * A pipe table when the chunk's SECOND line is all delimiter cells — the\n * same rule GFM uses, and the reason a paragraph mentioning `a | b` is\n * still a paragraph. Cells are squared off to the header's width: ragged\n * rows pad with empty cells and overflow is dropped, so the model the\n * serializer writes back re-parses to itself.\n */\nfunction parseTable(lines: string[]): MarkdownBlock | null {\n const [headerLine, delimiterLine] = lines\n if (!headerLine || !delimiterLine || !headerLine.includes('|')) return null\n const delimiters = splitTableRow(delimiterLine)\n if (!delimiters.every((cell) => DELIMITER_CELL.test(cell))) return null\n const header = splitTableRow(headerLine).map(parseMarkdownInlines)\n const columns = header.length\n const squared = (cells: string[]): MarkdownTableCell[] =>\n Array.from({ length: columns }, (_, index) =>\n parseMarkdownInlines(cells[index] ?? ''),\n )\n return {\n type: 'table',\n align: Array.from({ length: columns }, (_, index) =>\n alignOfDelimiter(delimiters[index] ?? '---'),\n ),\n header,\n rows: lines.slice(2).map((line) => squared(splitTableRow(line))),\n }\n}\n\n/**\n * Where a list begins, and which one (AGL-1320).\n *\n * `interrupting` is true when prose of the SAME chunk is already pending —\n * i.e. this line would break a paragraph in two. CommonMark's rule, adopted\n * verbatim: bullets may interrupt a paragraph freely, an ordered list only\n * when it starts at 1. That is what keeps prose reading `1997. A good year\n * for the web.` prose, while `…that includes:` followed by `1.`/`2.` becomes\n * the enumerated list a statute describes. At the head of a chunk nothing is\n * being interrupted, so any start number opens a list and a counter-notice\n * resuming at `7.` still counts from seven.\n */\nfunction listStartOf(\n line: string,\n interrupting: boolean,\n): { kind: 'list' | 'orderedList'; start: number } | null {\n if (BULLET_ITEM_PATTERN.test(line)) return { kind: 'list', start: 0 }\n const ordered = ORDERED_ITEM_PATTERN.exec(line)\n if (!ordered) return null\n const start = Number(ordered[1])\n if (interrupting && start !== 1) return null\n return { kind: 'orderedList', start }\n}\n\n/**\n * One blank-line-delimited chunk of non-fenced source, as blocks.\n *\n * Usually one block — but a chunk splits at a list (AGL-1320), because the\n * shape legal and instructional prose reaches for most is an introducing line\n * with its items directly beneath, no blank line between. A list runs to the\n * first line that is not an item; whatever follows starts a fresh paragraph,\n * which a later list may interrupt in turn. The serializer writes the pieces\n * back as separate blank-line-delimited chunks, so the split round-trips.\n */\nfunction parseChunk(chunk: string): MarkdownBlock[] {\n const trimmed = chunk.trim()\n if (!trimmed) return []\n const image = /^!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)$/.exec(trimmed)\n if (image) {\n const src = safeImageUrl(image[2])\n return src ? [{ type: 'image', src, alt: image[1] }] : []\n }\n const heading = HEADING_PATTERN.exec(trimmed)\n if (heading) {\n return [\n {\n type: 'heading',\n level: clampHeadingLevel(heading[1].length),\n inlines: parseMarkdownInlines(heading[2]),\n },\n ]\n }\n const lines = trimmed.split('\\n')\n const table = parseTable(lines)\n if (table) return [table]\n // A quote when EVERY line of the chunk is `>`-prefixed — a paragraph merely\n // mentioning `>` stays a paragraph, and a quote does NOT interrupt prose the\n // way a list does (`> ` is far rarer mid-paragraph than a numbered step, and\n // the all-lines rule is the cheaper guarantee). Fenced code never reaches\n // here (fences are cut out before chunking), so a `> ` inside a snippet is\n // snippet text, not a quote (AGL-1315).\n if (lines.every((line) => /^>(\\s|$)/.test(line.trim()))) {\n const text = lines\n .map((line) => line.trim().replace(/^>\\s?/, ''))\n .filter(Boolean)\n .join(' ')\n return [{ type: 'quote', inlines: parseMarkdownInlines(text) }]\n }\n const blocks: MarkdownBlock[] = []\n // Prose lines are buffered RAW and joined with spaces, the way a multi-line\n // paragraph has always read.\n let prose: string[] = []\n const flushProse = (): void => {\n if (prose.length) {\n blocks.push({\n type: 'paragraph',\n inlines: parseMarkdownInlines(prose.join(' ')),\n })\n }\n prose = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = (lines[index] ?? '').trim()\n const list = listStartOf(line, prose.length > 0)\n if (!list) {\n prose.push(lines[index] ?? '')\n continue\n }\n flushProse()\n const pattern =\n list.kind === 'list' ? BULLET_ITEM_PATTERN : ORDERED_ITEM_PATTERN\n const items: MarkdownInline[][] = []\n // The run ends at the first line that is not an item of THIS kind, so a\n // bullet closes a numbered run and vice versa. Only the FIRST ordered\n // marker is read, which is why a source numbered `1. 1. 1.` renumbers on\n // the way out.\n while (index < lines.length) {\n const item = (lines[index] ?? '').trim()\n if (!pattern.test(item)) break\n items.push(parseMarkdownInlines(item.replace(pattern, '')))\n index++\n }\n index--\n blocks.push(\n list.kind === 'list'\n ? { type: 'list', items }\n : { type: 'orderedList', start: list.start, items },\n )\n }\n flushProse()\n return blocks\n}\n\n/**\n * Blocks are blank-line separated, EXCEPT inside a ``` fence — a code\n * block owns its blank lines, so the scan is line-driven rather than a\n * split on `\\n{2,}` (AGL-974). An unterminated fence runs to the end of\n * the document, which is what a README truncated mid-snippet needs.\n */\nexport function parseMarkdownLite(body: string): MarkdownBlock[] {\n const blocks: MarkdownBlock[] = []\n const lines = body.split('\\n')\n let pending: string[] = []\n const flush = (): void => {\n // A chunk yields MORE than one block when a list interrupts its prose\n // (AGL-1320) — and none at all when it holds nothing renderable.\n if (pending.length) blocks.push(...parseChunk(pending.join('\\n')))\n pending = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] ?? ''\n const fence = FENCE_PATTERN.exec(line.trim())\n if (fence) {\n flush()\n const text: string[] = []\n while (\n ++index < lines.length &&\n !FENCE_PATTERN.test((lines[index] ?? '').trim())\n ) {\n text.push(lines[index] ?? '')\n }\n // Blank edges are the fence's own padding, not part of the snippet.\n while (text.length && !text[0]?.trim()) text.shift()\n while (text.length && !text[text.length - 1]?.trim()) text.pop()\n blocks.push({ type: 'code', lang: fence[1] ?? '', text: text.join('\\n') })\n continue\n }\n if (line.trim()) pending.push(line)\n else flush()\n }\n flush()\n return blocks\n}\n\n/** A link or an image in markdown-lite source: bang, text, target. */\nconst SOURCE_LINK_PATTERN = /(!?)\\[([^\\]]*)\\]\\(([^)\\s]+)\\)/g\n\n/**\n * Markdown-lite SOURCE with its link references resolved (AGL-3118), for a\n * reader that hands the source on instead of rendering it — the Markdown twin\n * of a page, which an agent follows links out of.\n *\n * `resolve` answers a reference with the URL to write in its place, or with\n * `undefined` for a target that is gone, and that link becomes its text\n * alone: a reference no reader can follow is worse than no link at all. An\n * image whose source is a reference becomes its alt text, because the parser\n * draws no image for one.\n *\n * Everything else stays exactly as written, and fenced code is not touched —\n * a reference quoted in a snippet is the snippet's text, as the parser has it.\n */\nexport function resolveMarkdownSourceLinks(\n source: string,\n resolve: (reference: string) => string | undefined,\n): string {\n if (!source.includes('](')) return source\n let fenced = false\n return source\n .split('\\n')\n .map((line) => {\n if (FENCE_PATTERN.test(line.trim())) {\n fenced = !fenced\n return line\n }\n if (fenced || !line.includes('](')) return line\n return line.replace(\n SOURCE_LINK_PATTERN,\n (match: string, bang: string, text: string, href: string) => {\n if (!isMarkdownLinkReference(href)) return match\n const target = bang ? undefined : resolve(href)\n // A URL cannot close the parentheses it sits in or break at a space.\n return target\n ? `[${text}](${target.replace(/\\)/g, '%29').replace(/\\s/g, '%20')})`\n : text\n },\n )\n })\n .join('\\n')\n}\n\n/**\n * The plain text an inline run reads as — the words with the emphasis and\n * link syntax removed. What a heading contributes to an anchor slug and to a\n * table-of-contents label (AGL-1162), where `## The **fine** print` has to\n * become \"The fine print\" and `the-fine-print`, not two of either.\n */\nexport function markdownInlinesToText(inlines: MarkdownInline[]): string {\n return inlines.map((inline) => inline.text).join('')\n}\n\n/** A heading a table of contents can point at (AGL-1162). */\nexport interface MarkdownHeading {\n level: 2 | 3\n /** Heading text with emphasis/link syntax stripped. */\n text: string\n /** Anchor id, deterministic and unique within the document. */\n slug: string\n /** Position in the block list, so a renderer can id the right heading. */\n index: number\n}\n\n/**\n * Anchor id for one heading's text (AGL-1162).\n *\n * Deterministic by construction — the same words always produce the same id,\n * which is the whole point: a legal page's true source is a markdown file\n * elsewhere, and re-pasting it must not silently break every link that ever\n * pointed into it. Accents fold to their base letter (NFKD then drop the\n * combining marks) so `Résumé` and `Resume` are the same anchor rather than\n * one of them being an unreadable percent-encoded id.\n *\n * A heading of nothing but punctuation or non-Latin script slugifies to\n * empty; those get `SLUG_FALLBACK` here and are told apart by the numbering\n * in {@link collectMarkdownHeadings}, because an id is required for the link\n * to work at all and no id is worse than a dull one.\n */\nexport const SLUG_FALLBACK = 'section'\n\nexport function slugifyHeading(text: string): string {\n return (\n text\n .normalize('NFKD')\n // Combining diacritics left behind by the decomposition above.\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || SLUG_FALLBACK\n )\n}\n\n/**\n * Every heading in a parsed document, with a unique anchor slug (AGL-1162).\n *\n * Duplicates take a `-2`, `-3`, … suffix in document order, and the loop\n * re-checks the suffixed candidate: a document holding two `## Notice`\n * headings AND a literal `## Notice 2` must not hand the same id to two\n * elements, which is exactly what a plain counter would do.\n *\n * Deliberately NOT a widening of the `MarkdownBlock` union. The union is\n * rendered exhaustively in six places, so a slug carried on the heading\n * block would have to be produced by every writer of that union — including\n * the visual editor's serializer, which round-trips through markdown source\n * that has nowhere to put one. Derived here instead, from the same parse the\n * renderer already has, so the markdown text stays the only source of truth.\n */\nexport function collectMarkdownHeadings(\n blocks: MarkdownBlock[],\n): MarkdownHeading[] {\n const headings: MarkdownHeading[] = []\n const used = new Set<string>()\n blocks.forEach((block, index) => {\n if (block.type !== 'heading') return\n const text = markdownInlinesToText(block.inlines).trim()\n const base = slugifyHeading(text)\n let slug = base\n let suffix = 1\n while (used.has(slug)) {\n suffix += 1\n slug = `${base}-${suffix}`\n }\n used.add(slug)\n headings.push({ level: block.level, text, slug, index })\n })\n return headings\n}\n\n/**\n * The same headings keyed by block index, which is the shape every renderer\n * actually wants (AGL-1162).\n *\n * A renderer maps over `blocks` and needs the slug for the block in hand;\n * {@link collectMarkdownHeadings} returns a list, so each of them had to\n * rebuild this map. There were six markdown renderers and one of them did —\n * five published headings a table of contents could never link to, and the\n * one that worked did it with a private `useMemo` nobody else could reach.\n * Living here means a new renderer gets the numbering, the fallback and the\n * duplicate-suffix rules for free rather than approximating them.\n */\nexport function markdownHeadingSlugs(\n blocks: MarkdownBlock[],\n): Record<number, string> {\n const map: Record<number, string> = {}\n for (const heading of collectMarkdownHeadings(blocks)) {\n map[heading.index] = heading.slug\n }\n return map\n}\n\n/**\n * How far below a heading's anchor the viewport stops (AGL-1162) — enough to\n * clear a sticky site header, so a `#slug` link does not land with the\n * heading hidden underneath the nav. Shared so the published page, the entry\n * body and the console preview all scroll to the same place.\n */\nexport const HEADING_ANCHOR_SCROLL_MARGIN = 96\n\n/** Newlines cannot exist inside an inline run — flatten them to a space. */\nconst flattenInlineText = (text: string): string =>\n text.replace(/\\s*\\n+\\s*/g, ' ')\n\n/**\n * Serializes inlines back to markdown-lite source (AGL-582). Characters an\n * inline run cannot represent (the dialect has NO escapes) are dropped:\n * `*` inside bold/italic, `]` in link text/alt, `)` or whitespace in URLs.\n * Parser-emitted inlines never contain them, so for those this is exact.\n */\nexport function serializeMarkdownInlines(inlines: MarkdownInline[]): string {\n let out = ''\n for (const inline of inlines) {\n if (inline.type === 'bold' || inline.type === 'italic') {\n const text = flattenInlineText(inline.text).replace(/\\*/g, '')\n if (!text) continue\n out += inline.type === 'bold' ? `**${text}**` : `*${text}*`\n } else if (inline.type === 'link') {\n const text = flattenInlineText(inline.text).replace(/\\]/g, '')\n const href = inline.href.replace(/[)\\s]/g, '')\n out += text && href ? `[${text}](${href})` : text\n } else {\n out += flattenInlineText(inline.text)\n }\n }\n return out\n}\n\n/**\n * Inverse of `parseMarkdownLite` — the WYSIWYG round-trip contract\n * (AGL-582): for any parser-produced model, the serialized string re-parses\n * to a deep-equal model, and serializing is stable (a second\n * parse→serialize round-trip returns the identical string). Editor-produced\n * models are additionally NORMALIZED the same way the parser would: blocks\n * and list items that would parse to nothing (empty text) are omitted, and\n * block lines are edge-trimmed. Entry bodies stay markdown-lite strings in\n * Firestore — this is the only writer the visual editor goes through.\n *\n * Every block is written as its own chunk, separated by a BLANK line, which\n * is what holds the invariant now that a list may interrupt a paragraph\n * (AGL-1320): `intro:` + `1. a` re-parses to the same paragraph + list pair\n * whether or not the author left a blank line between them. The blank line is\n * therefore load-bearing, not cosmetic: writing the two chunks adjacent would\n * re-parse correctly today only by luck of the interrupt rule.\n */\nexport function serializeMarkdownLite(blocks: MarkdownBlock[]): string {\n const chunks: string[] = []\n for (const block of blocks) {\n if (block.type === 'image') {\n const src = block.src.replace(/[)\\s]/g, '')\n const alt = flattenInlineText(block.alt).replace(/\\]/g, '')\n if (src) chunks.push(``)\n continue\n }\n if (block.type === 'list') {\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line) => `- ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'orderedList') {\n // Markers are RE-NUMBERED from `start` (AGL-1320) rather than written\n // back verbatim: the parser only reads the first one, so contiguous\n // markers are the single form that re-parses to this exact model.\n // A missing/absurd start falls back to 1, the way a hand-written list\n // reads anyway.\n const start = Number.isFinite(block.start)\n ? Math.max(0, Math.trunc(block.start))\n : 1\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line, index) => `${start + index}. ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'code') {\n // The fence is the only delimiter the dialect has, so a fence INSIDE\n // the snippet would end it early — those backticks drop, the same way\n // an unrepresentable `*` drops from a bold run.\n const text = block.text\n .replace(/^(\\s*)`{3,}/gm, '$1')\n .replace(/^(?:[ \\t]*\\n)+/, '')\n .replace(/(?:\\n[ \\t]*)+$/, '')\n const lang = block.lang.replace(/[^\\w+#.-]/g, '')\n chunks.push([`\\`\\`\\`${lang}`, ...(text ? [text] : []), '```'].join('\\n'))\n continue\n }\n if (block.type === 'table') {\n // `|` separates cells and there are no escapes, so a pipe inside a\n // cell drops. Empty cells are kept — they are meaningful in a table.\n const row = (cells: MarkdownTableCell[]): string =>\n `| ${cells\n .map((cell) => serializeMarkdownInlines(cell).replace(/\\|/g, '').trim())\n .join(' | ')} |`\n if (!block.header.length) continue\n const delimiters = block.header.map((_, index) => {\n const align = block.align[index] ?? 'left'\n return align === 'center' ? ':-:' : align === 'right' ? '--:' : '---'\n })\n chunks.push(\n [\n row(block.header),\n `| ${delimiters.join(' | ')} |`,\n // Squared off to the header: the parser reads it back that way,\n // so writing anything else would not round-trip.\n ...block.rows.map((cells) =>\n row(\n Array.from(\n { length: block.header.length },\n (_, index) => cells[index] ?? [],\n ),\n ),\n ),\n ].join('\\n'),\n )\n continue\n }\n const line = serializeMarkdownInlines(block.inlines).trim()\n if (!line) continue\n chunks.push(\n block.type === 'heading'\n ? `${'#'.repeat(block.level)} ${line}`\n : block.type === 'quote'\n ? `> ${line}`\n : line,\n )\n }\n return chunks.join('\\n\\n')\n}\n"],"names":["isMediaRef","parseMediaRef","parseCollectionLinkValue","parseEntryLinkValue","parseFeedLinkValue","parseScreenLinkValue","resolveScreenHref","SCREEN_LINK_VALUE_PREFIX","screenRoutesAnswerFor","INLINE_PATTERN","safeUrl","url","test","isSupportedLinkHref","safeLinkUrl","isSupportedImageSrc","safeImageUrl","isMarkdownLinkReference","startsWith","undefined","isInternalMarkdownHref","href","resolveMarkdownLink","context","screens","reference","resolved","suppressNavigation","gone","kind","pushText","inlines","text","last","length","type","push","parseMarkdownInlines","cursor","match","matchAll","index","slice","HEADING_PATTERN","clampHeadingLevel","hashes","FENCE_PATTERN","BULLET_ITEM_PATTERN","ORDERED_ITEM_PATTERN","DELIMITER_CELL","splitTableRow","line","trim","endsWith","split","map","cell","alignOfDelimiter","left","right","parseTable","lines","headerLine","delimiterLine","includes","delimiters","every","header","columns","squared","cells","Array","from","_","align","rows","listStartOf","interrupting","start","ordered","exec","Number","parseChunk","chunk","trimmed","image","src","alt","heading","level","table","replace","filter","Boolean","join","blocks","prose","flushProse","list","pattern","items","item","parseMarkdownLite","body","pending","flush","fence","shift","pop","lang","SOURCE_LINK_PATTERN","resolveMarkdownSourceLinks","source","resolve","fenced","bang","target","markdownInlinesToText","inline","SLUG_FALLBACK","slugifyHeading","normalize","toLowerCase","collectMarkdownHeadings","headings","used","Set","forEach","block","base","slug","suffix","has","add","markdownHeadingSlugs","HEADING_ANCHOR_SCROLL_MARGIN","flattenInlineText","serializeMarkdownInlines","out","serializeMarkdownLite","chunks","isFinite","Math","max","trunc","row","repeat"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GAED,SAASA,UAAU,EAAEC,aAAa,QAAQ,iBAAa;AACvD,SACEC,wBAAwB,EACxBC,mBAAmB,EACnBC,kBAAkB,EAClBC,oBAAoB,EACpBC,iBAAiB,EACjBC,wBAAwB,EACxBC,qBAAqB,QAChB,yBAAqB;AAiD5B,MAAMC,iBACJ;AAEF;;;;CAIC,GACD,SAASC,QAAQC,GAAW;IAC1B,OAAO,gBAAgBC,IAAI,CAACD,OAAOA,MAAM;AAC3C;AAEA;;;;CAIC,GACD,OAAO,SAASE,oBAAoBF,GAAW;IAC7C,OAAOG,YAAYH,SAAS;AAC9B;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASI,oBAAoBJ,GAAW;IAC7C,OAAOK,aAAaL,SAAS;AAC/B;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASM,wBAAwBN,GAAW;IACjD,IAAIA,IAAIO,UAAU,CAACX,2BAA2B;QAC5C,OAAOF,qBAAqBM,SAASQ;IACvC;IACA,OACEjB,yBAAyBS,SAASQ,aAClChB,oBAAoBQ,SAASQ,aAC7Bf,mBAAmBO,SAASQ;AAEhC;AAEA;;;;;;CAMC,GACD,SAASL,YAAYH,GAAW;IAC9B,IAAI,YAAYC,IAAI,CAACD,MAAM,OAAOA;IAClC,IAAIM,wBAAwBN,MAAM,OAAOA;IACzC,OAAOD,QAAQC;AACjB;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,SAAS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pE0C,IAAI,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAACkC,MAAM7D,MAAM,CAACjC,MAAM,EAAE;YAC1B,MAAM+B,aAAa+D,MAAM7D,MAAM,CAACZ,GAAG,CAAC,CAACkB,GAAGhC;oBACxBuF;gBAAd,MAAMtD,SAAQsD,qBAAAA,MAAMtD,KAAK,CAACjC,MAAM,YAAlBuF,qBAAsB;gBACpC,OAAOtD,UAAU,WAAW,QAAQA,UAAU,UAAU,QAAQ;YAClE;YACAkE,OAAOxG,IAAI,CACT;gBACE6G,IAAIjB,MAAM7D,MAAM;gBAChB,CAAC,EAAE,EAAEF,WAAW6B,IAAI,CAAC,OAAO,EAAE,CAAC;gBAC/B,gEAAgE;gBAChE,iDAAiD;mBAC9CkC,MAAMrD,IAAI,CAACpB,GAAG,CAAC,CAACe,QACjB2E,IACE1E,MAAMC,IAAI,CACR;wBAAEtC,QAAQ8F,MAAM7D,MAAM,CAACjC,MAAM;oBAAC,GAC9B,CAACuC,GAAGhC;4BAAU6B;gCAAAA,eAAAA,KAAK,CAAC7B,MAAM,YAAZ6B,eAAgB,EAAE;;aAIvC,CAACwB,IAAI,CAAC;YAET;QACF;QACA,MAAM3C,OAAOsF,yBAAyBT,MAAMjG,OAAO,EAAEqB,IAAI;QACzD,IAAI,CAACD,MAAM;QACXyF,OAAOxG,IAAI,CACT4F,MAAM7F,IAAI,KAAK,YACX,GAAG,IAAI+G,MAAM,CAAClB,MAAMvC,KAAK,EAAE,CAAC,EAAEtC,MAAM,GACpC6E,MAAM7F,IAAI,KAAK,UACb,CAAC,EAAE,EAAEgB,MAAM,GACXA;IAEV;IACA,OAAOyF,OAAO9C,IAAI,CAAC;AACrB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/markdown-lite.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 * Markdown-lite (AGL-123): the tiny subset blog entries use — headings,\n * bold/italic, links, images, bullet and numbered lists, paragraphs, fenced\n * code blocks, tables and blockquotes. Parsed into plain data blocks that\n * renderers turn into elements themselves (no HTML string is ever produced,\n * so there is nothing to sanitize).\n */\n\nimport { isMediaRef, parseMediaRef } from './media-ref'\nimport {\n parseCollectionLinkValue,\n parseEntryLinkValue,\n parseFeedLinkValue,\n parseScreenLinkValue,\n resolveScreenHref,\n SCREEN_LINK_VALUE_PREFIX,\n screenRoutesAnswerFor,\n} from './screen-link-value'\n\nexport type MarkdownInline =\n | { type: 'text'; text: string }\n | { type: 'bold'; text: string }\n | { type: 'italic'; text: string }\n | { type: 'link'; text: string; href: string }\n\n/** A table cell's content. Cells hold inline runs only — no nesting. */\nexport type MarkdownTableCell = MarkdownInline[]\nexport type MarkdownTableAlign = 'left' | 'center' | 'right'\n\nexport type MarkdownBlock =\n | { type: 'heading'; level: 2 | 3; inlines: MarkdownInline[] }\n | { type: 'paragraph'; inlines: MarkdownInline[] }\n /**\n * A `> ` quote (AGL-1315) — the article template's pull-quote. Like a\n * paragraph, one inline run: consecutive `> ` lines of a chunk join with\n * spaces (a bare `>` continues the group and contributes nothing). The\n * dialect has NO nesting — a second `>` is just text of the quote.\n */\n | { type: 'quote'; inlines: MarkdownInline[] }\n | { type: 'image'; src: string; alt: string }\n | { type: 'list'; items: MarkdownInline[][] }\n /**\n * A `1. ` / `1) ` numbered list (AGL-1320) — what a statute's enumerated\n * elements need, and what `/legal/dmca` was flattening into run-on prose.\n * `start` is the FIRST marker's number, so a notice continuing at `7.`\n * keeps counting from seven; the rest renumber from it, which is how the\n * serializer round-trips a `1. 1. 1.` source. A separate block rather than\n * a flag on `list`, so the six renderers have to name it and no ordered\n * list can silently render as bullets. NO nesting, like the rest of the\n * dialect: indentation is trimmed, so a ` 1. ` sub-item is a sibling.\n */\n | { type: 'orderedList'; start: number; items: MarkdownInline[][] }\n /** Fenced block. `text` is verbatim; `lang` is '' when none was given. */\n | { type: 'code'; lang: string; text: string }\n /**\n * A GFM pipe table (AGL-974). Rectangular by construction: every row and\n * `align` carry exactly `header.length` cells, so renderers never have to\n * reason about ragged input and the serializer round-trips exactly.\n */\n | {\n type: 'table'\n align: MarkdownTableAlign[]\n header: MarkdownTableCell[]\n rows: MarkdownTableCell[][]\n }\n\nconst INLINE_PATTERN =\n /(\\*\\*([^*]+)\\*\\*)|(\\*([^*]+)\\*)|(\\[([^\\]]+)\\]\\(([^)\\s]+)\\))|(?<![\\w_])_([^_\\n]+)_(?![\\w_])/g\n\n/**\n * Only absolute http(s) survives; anything else renders as text. The `http:`\n * half reaches LINKS only — {@link safeImageUrl} refuses it before it gets\n * here (AGL-1713).\n */\nfunction safeUrl(url: string): string | null {\n return /^https?:\\/\\//i.test(url) ? url : null\n}\n\n/**\n * Whether a link target is one the parser will keep — the PUBLIC half of\n * {@link safeLinkUrl}, so an editor can refuse what the parser would drop\n * instead of discovering the disagreement on the published page (AGL-1686).\n */\nexport function isSupportedLinkHref(url: string): boolean {\n return safeLinkUrl(url) !== null\n}\n\n/**\n * Whether an image source is one the parser will keep. The predicate an\n * authoring surface must validate against, for the reason\n * {@link isSupportedLinkHref} exists and one the editor learned the hard way:\n * AGL-1645 widened the visual editor's image check to accept site-relative\n * paths without widening this file, so every image picked from the media\n * library serialized into the document and then vanished on the next parse.\n * One predicate, two callers, no drift.\n */\nexport function isSupportedImageSrc(url: string): boolean {\n return safeImageUrl(url) !== null\n}\n\n/**\n * Whether a link target is a stored REFERENCE rather than an address\n * (AGL-3118): a screen, a collection listing, an entry or a feed, named by id\n * so a rename cannot break it. Only the marked, well-formed forms count — a\n * bare id is indistinguishable from a relative path with no slash, so it\n * stays what the dialect has always made of it.\n *\n * Kept verbatim in the parsed link: a renderer resolves it against the same\n * routing map element links use, and the serializer writes it back as typed.\n */\nexport function isMarkdownLinkReference(url: string): boolean {\n if (url.startsWith(SCREEN_LINK_VALUE_PREFIX)) {\n return parseScreenLinkValue(url) !== undefined\n }\n return (\n parseCollectionLinkValue(url) !== undefined ||\n parseEntryLinkValue(url) !== undefined ||\n parseFeedLinkValue(url) !== undefined\n )\n}\n\n/**\n * Link targets additionally allow SITE-RELATIVE paths (AGL-582) so entry\n * markdown can link to other pages of the same site — renderers give those\n * client-side navigation — and link REFERENCES (AGL-3118), which renderers\n * resolve to wherever the target lives now. Protocol-relative `//host` is\n * rejected: it would silently leave the site.\n */\nfunction safeLinkUrl(url: string): string | null {\n if (/^\\/(?!\\/)/.test(url)) return url\n if (isMarkdownLinkReference(url)) return url\n return safeUrl(url)\n}\n\n/**\n * Image sources take everything a link takes, PLUS a media reference\n * (AGL-1686).\n *\n * Images were the one slot still on absolute-`http(s)`-only, and that was\n * silently eating two forms the product now produces:\n *\n * 1. `media:{scope}/{mediaId}` — what \"Browse media\" stores everywhere else\n * (AGL-1215). The reference names the asset and lets the renderer decide\n * how to fetch it, which is the only form that survives a folder move, a\n * replace, a route change, and a component shared across sites.\n * 2. A site-relative `/api/media/cdn/…` or `/images/hero.png`. The visual\n * editor's own `isValidImageUrl` accepts these (AGL-1645) and\n * `safeLinkUrl` always has — so the parser was the one place that\n * disagreed, and it disagreed by DROPPING the whole block. An image with\n * an unparseable src emits no block at all, so the failure was not a\n * broken-image icon or a console error; the picture simply was not there.\n *\n * A malformed reference is still refused. `parseMediaRef` is the same grammar\n * `formatMediaRef` mints against, so `media:` junk an author typed never\n * becomes a block whose src no renderer can resolve — the parse boundary\n * keeps the promise `resolveMediaSrc` makes on the other side.\n *\n * Protocol-relative stays refused here exactly as it is for links.\n *\n * It takes two things LESS than a link. A link REFERENCE (AGL-3118) names a\n * page, not a file, so no renderer has a picture to fetch for one; kept, it\n * would reach an `<img src=\"entry:…\">`.\n *\n * And `http:` (AGL-1713). An image is fetched the moment the page renders; a\n * link is followed by the reader's\n * choice, past an interstitial the browser puts up. So an `http:` image on our\n * TLS pages is mixed content that every current browser blocks outright — the\n * permissive form never rendered a picture, it only moved the failure from\n * authoring time to the viewer, and stored a src that is a CSP violation\n * waiting for AGL-1702 to enforce. Refusing it here reports at authoring time\n * through `isSupportedImageSrc`, which the editor and the besigner picker both\n * validate against. This is the same asymmetry AGL-1701 struck between\n * `SAFE_SRC` and `SAFE_HREF` on the published marketplace node, and the same\n * reason it left `homepageUrl`/`repositoryUrl` as any-https.\n */\nfunction safeImageUrl(url: string): string | null {\n if (isMediaRef(url)) return parseMediaRef(url) ? url : null\n if (/^http:\\/\\//i.test(url)) return null\n if (isMarkdownLinkReference(url)) return null\n return safeLinkUrl(url)\n}\n\n/**\n * True for hrefs the parser emitted as site-relative (start with `/`) AND that\n * a client router can actually settle on.\n *\n * `/api/…` is excluded because those paths serve FILES, not pages —\n * `/api/media/cdn/{scope}/{id}` is the download URL every media reference\n * resolves to, and it is what \"Browse media\" hands an author who links a PDF\n * or a logo kit. Routed through `AppLink` the click starts a client-side\n * navigation that can never complete: the response is an attachment, so the\n * router mounts its navigation-pending overlay and waits forever.\n *\n * The tell is a page trapped behind a spinner, NOT a failed download — the\n * browser fetches the attachment underneath the overlay, so the file lands in\n * Downloads while the site sits there looking broken. That mismatch sends you\n * hunting the media endpoint, which answers `200` with a correct\n * `Content-Disposition: attachment` every time.\n *\n * Both callers use this purely to choose `AppLink` vs a plain anchor, so\n * narrowing it here fixes markdown bodies and collection item links together.\n */\nexport function isInternalMarkdownHref(href: string): boolean {\n return /^\\/(?!\\/)/.test(href) && !/^\\/api\\//.test(href)\n}\n\n/** How a renderer draws one parsed link — see {@link resolveMarkdownLink}. */\nexport type MarkdownLinkResolution =\n /** The link's text alone, with no anchor: a reference to a missing target. */\n | { kind: 'text' }\n /** Drawn as a link with nothing to follow, on an editing surface. */\n | { kind: 'inert' }\n /** A page of this site, for client-side navigation. */\n | { kind: 'internal'; href: string }\n /** Anything else the parser kept, as a plain anchor. */\n | { kind: 'external'; href: string }\n\n/**\n * What one parsed link renders as (AGL-3118), for every markdown-lite\n * renderer on a site: the Markdown element, the entry body and the legacy\n * article surface.\n *\n * A link REFERENCE resolves against the routing map element links use, so a\n * link in a post follows its target through a rename exactly as a button\n * does, and a target the map does not have (unpublished, deleted, or never\n * asked for) renders as the link's text — never as an anchor whose href is\n * the stored reference. Every other href is the one the parser kept.\n *\n * An editing surface withholds every href, so there the only question is\n * whether a link is drawn at all: a reference the map KNOWS is gone reads as\n * the text the published page will show, and one the map cannot judge yet —\n * nothing of its kind has loaded — keeps the link look, for the reason\n * `isScreenLinkBroken` gives.\n */\nexport function resolveMarkdownLink(\n href: string,\n context: {\n screens?: Record<string, string> | null\n suppressNavigation?: boolean\n } = {},\n): MarkdownLinkResolution {\n const screens = context.screens ?? undefined\n const reference = isMarkdownLinkReference(href)\n const resolved = reference ? resolveScreenHref(screens, href) : href\n if (context.suppressNavigation) {\n const gone =\n reference &&\n resolved === undefined &&\n screenRoutesAnswerFor(screens, href)\n return gone ? { kind: 'text' } : { kind: 'inert' }\n }\n if (resolved === undefined) return { kind: 'text' }\n return isInternalMarkdownHref(resolved)\n ? { kind: 'internal', href: resolved }\n : { kind: 'external', href: resolved }\n}\n\n/**\n * Appends plain text, merging into a trailing text inline so the emitted\n * model is canonical (no adjacent text runs). Canonical inlines are what\n * makes `serializeMarkdownLite` a true inverse: a degraded link squeezed\n * between two text gaps re-parses to the same single text inline (AGL-582).\n */\nfunction pushText(inlines: MarkdownInline[], text: string): void {\n if (!text) return\n const last = inlines[inlines.length - 1]\n if (last?.type === 'text') last.text += text\n else inlines.push({ type: 'text', text })\n}\n\nexport function parseMarkdownInlines(text: string): MarkdownInline[] {\n const inlines: MarkdownInline[] = []\n let cursor = 0\n for (const match of text.matchAll(INLINE_PATTERN)) {\n const index = match.index ?? 0\n if (index > cursor) {\n pushText(inlines, text.slice(cursor, index))\n }\n if (match[2] != null) {\n inlines.push({ type: 'bold', text: match[2] })\n } else if (match[4] != null) {\n inlines.push({ type: 'italic', text: match[4] })\n } else if (match[8] != null) {\n // `_italic_` (AGL-4182). Only as a whole word, so `snake_case_name` and\n // a file name stay as they were typed.\n inlines.push({ type: 'italic', text: match[8] })\n } else if (match[6] != null) {\n const href = safeLinkUrl(match[7])\n if (href) inlines.push({ type: 'link', text: match[6], href })\n else pushText(inlines, match[6])\n }\n cursor = index + match[0].length\n }\n if (cursor < text.length) {\n pushText(inlines, text.slice(cursor))\n }\n return inlines\n}\n\n/**\n * An ATX heading at ANY of markdown's six levels (AGL-1082). The dialect only\n * RENDERS two, but it must not mistake the other four for prose: matching just\n * `#{2,3}` made `# Title` — how essentially every repo README opens — fall\n * through to a paragraph carrying a literal `#`, silently, in every renderer.\n */\nconst HEADING_PATTERN = /^(#{1,6})\\s+(.*)$/\n\n/**\n * Clamps an ATX level onto the two the block union carries. `#` promotes to\n * the top rendered level and `####`+ demote to the bottom one, so an out-of-\n * range heading degrades to the NEAREST heading rather than to prose — the\n * same lossy-but-visible degradation the dialect already applies to a `*`\n * inside a bold run. Deliberately NOT widening `level` to `1 | 2 | 3`: every\n * renderer reads it as `level === 2 ? h2 : h3`, so a third value would type-\n * check clean and silently render an h1 as an h3 in six places. This also\n * makes the markdown path agree with the HTML-paste path, which has always\n * mapped `<h1>` to a level-2 heading.\n */\nfunction clampHeadingLevel(hashes: number): 2 | 3 {\n return hashes <= 2 ? 2 : 3\n}\n\n/** ```` ``` ```` or longer, optionally naming a language. */\nconst FENCE_PATTERN = /^`{3,}\\s*([^\\s`]*)\\s*$/\n/** A bullet-list marker: `- ` or `* `. */\nconst BULLET_ITEM_PATTERN = /^[-*]\\s+/\n/**\n * An ordered-list marker (AGL-1320): `1. ` or `1) `, capped at nine digits\n * like CommonMark so a stray year cannot become an absurd `start`. The\n * trailing `\\s+` is load-bearing twice over: it keeps `1.no space` prose, and\n * it makes an EMPTY item impossible, which is the other half of CommonMark's\n * interrupt rule (a bare `1.` may not interrupt a paragraph either).\n */\nconst ORDERED_ITEM_PATTERN = /^(\\d{1,9})[.)]\\s+/\n/** A delimiter cell of a GFM table's second row: `---`, `:--`, `:-:`, `--:`. */\nconst DELIMITER_CELL = /^:?-+:?$/\n\n/** Splits a table row on `|`, dropping the optional outer pipes. */\nfunction splitTableRow(line: string): string[] {\n let text = line.trim()\n if (text.startsWith('|')) text = text.slice(1)\n if (text.endsWith('|')) text = text.slice(0, -1)\n return text.split('|').map((cell) => cell.trim())\n}\n\nfunction alignOfDelimiter(cell: string): MarkdownTableAlign {\n const left = cell.startsWith(':')\n const right = cell.endsWith(':')\n if (left && right) return 'center'\n return right ? 'right' : 'left'\n}\n\n/**\n * A pipe table when the chunk's SECOND line is all delimiter cells — the\n * same rule GFM uses, and the reason a paragraph mentioning `a | b` is\n * still a paragraph. Cells are squared off to the header's width: ragged\n * rows pad with empty cells and overflow is dropped, so the model the\n * serializer writes back re-parses to itself.\n */\nfunction parseTable(lines: string[]): MarkdownBlock | null {\n const [headerLine, delimiterLine] = lines\n if (!headerLine || !delimiterLine || !headerLine.includes('|')) return null\n const delimiters = splitTableRow(delimiterLine)\n if (!delimiters.every((cell) => DELIMITER_CELL.test(cell))) return null\n const header = splitTableRow(headerLine).map(parseMarkdownInlines)\n const columns = header.length\n const squared = (cells: string[]): MarkdownTableCell[] =>\n Array.from({ length: columns }, (_, index) =>\n parseMarkdownInlines(cells[index] ?? ''),\n )\n return {\n type: 'table',\n align: Array.from({ length: columns }, (_, index) =>\n alignOfDelimiter(delimiters[index] ?? '---'),\n ),\n header,\n rows: lines.slice(2).map((line) => squared(splitTableRow(line))),\n }\n}\n\n/**\n * Where a list begins, and which one (AGL-1320).\n *\n * `interrupting` is true when prose of the SAME chunk is already pending —\n * i.e. this line would break a paragraph in two. CommonMark's rule, adopted\n * verbatim: bullets may interrupt a paragraph freely, an ordered list only\n * when it starts at 1. That is what keeps prose reading `1997. A good year\n * for the web.` prose, while `…that includes:` followed by `1.`/`2.` becomes\n * the enumerated list a statute describes. At the head of a chunk nothing is\n * being interrupted, so any start number opens a list and a counter-notice\n * resuming at `7.` still counts from seven.\n */\nfunction listStartOf(\n line: string,\n interrupting: boolean,\n): { kind: 'list' | 'orderedList'; start: number } | null {\n if (BULLET_ITEM_PATTERN.test(line)) return { kind: 'list', start: 0 }\n const ordered = ORDERED_ITEM_PATTERN.exec(line)\n if (!ordered) return null\n const start = Number(ordered[1])\n if (interrupting && start !== 1) return null\n return { kind: 'orderedList', start }\n}\n\n/**\n * One blank-line-delimited chunk of non-fenced source, as blocks.\n *\n * Usually one block — but a chunk splits at a list (AGL-1320), because the\n * shape legal and instructional prose reaches for most is an introducing line\n * with its items directly beneath, no blank line between. A list runs to the\n * first line that is not an item; whatever follows starts a fresh paragraph,\n * which a later list may interrupt in turn. The serializer writes the pieces\n * back as separate blank-line-delimited chunks, so the split round-trips.\n */\nfunction parseChunk(chunk: string): MarkdownBlock[] {\n const trimmed = chunk.trim()\n if (!trimmed) return []\n const image = /^!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)$/.exec(trimmed)\n if (image) {\n const src = safeImageUrl(image[2])\n return src ? [{ type: 'image', src, alt: image[1] }] : []\n }\n const heading = HEADING_PATTERN.exec(trimmed)\n if (heading) {\n return [\n {\n type: 'heading',\n level: clampHeadingLevel(heading[1].length),\n inlines: parseMarkdownInlines(heading[2]),\n },\n ]\n }\n const lines = trimmed.split('\\n')\n const table = parseTable(lines)\n if (table) return [table]\n // A quote when EVERY line of the chunk is `>`-prefixed — a paragraph merely\n // mentioning `>` stays a paragraph, and a quote does NOT interrupt prose the\n // way a list does (`> ` is far rarer mid-paragraph than a numbered step, and\n // the all-lines rule is the cheaper guarantee). Fenced code never reaches\n // here (fences are cut out before chunking), so a `> ` inside a snippet is\n // snippet text, not a quote (AGL-1315).\n if (lines.every((line) => /^>(\\s|$)/.test(line.trim()))) {\n const text = lines\n .map((line) => line.trim().replace(/^>\\s?/, ''))\n .filter(Boolean)\n .join(' ')\n return [{ type: 'quote', inlines: parseMarkdownInlines(text) }]\n }\n const blocks: MarkdownBlock[] = []\n // Prose lines are buffered RAW and joined with spaces, the way a multi-line\n // paragraph has always read.\n let prose: string[] = []\n const flushProse = (): void => {\n if (prose.length) {\n blocks.push({\n type: 'paragraph',\n inlines: parseMarkdownInlines(prose.join(' ')),\n })\n }\n prose = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = (lines[index] ?? '').trim()\n const list = listStartOf(line, prose.length > 0)\n if (!list) {\n prose.push(lines[index] ?? '')\n continue\n }\n flushProse()\n const pattern =\n list.kind === 'list' ? BULLET_ITEM_PATTERN : ORDERED_ITEM_PATTERN\n const items: MarkdownInline[][] = []\n // The run ends at the first line that is not an item of THIS kind, so a\n // bullet closes a numbered run and vice versa. Only the FIRST ordered\n // marker is read, which is why a source numbered `1. 1. 1.` renumbers on\n // the way out.\n while (index < lines.length) {\n const item = (lines[index] ?? '').trim()\n if (!pattern.test(item)) break\n items.push(parseMarkdownInlines(item.replace(pattern, '')))\n index++\n }\n index--\n blocks.push(\n list.kind === 'list'\n ? { type: 'list', items }\n : { type: 'orderedList', start: list.start, items },\n )\n }\n flushProse()\n return blocks\n}\n\n/**\n * Blocks are blank-line separated, EXCEPT inside a ``` fence — a code\n * block owns its blank lines, so the scan is line-driven rather than a\n * split on `\\n{2,}` (AGL-974). An unterminated fence runs to the end of\n * the document, which is what a README truncated mid-snippet needs.\n */\nexport function parseMarkdownLite(body: string): MarkdownBlock[] {\n const blocks: MarkdownBlock[] = []\n const lines = body.split('\\n')\n let pending: string[] = []\n const flush = (): void => {\n // A chunk yields MORE than one block when a list interrupts its prose\n // (AGL-1320) — and none at all when it holds nothing renderable.\n if (pending.length) blocks.push(...parseChunk(pending.join('\\n')))\n pending = []\n }\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index] ?? ''\n const fence = FENCE_PATTERN.exec(line.trim())\n if (fence) {\n flush()\n const text: string[] = []\n while (\n ++index < lines.length &&\n !FENCE_PATTERN.test((lines[index] ?? '').trim())\n ) {\n text.push(lines[index] ?? '')\n }\n // Blank edges are the fence's own padding, not part of the snippet.\n while (text.length && !text[0]?.trim()) text.shift()\n while (text.length && !text[text.length - 1]?.trim()) text.pop()\n blocks.push({ type: 'code', lang: fence[1] ?? '', text: text.join('\\n') })\n continue\n }\n if (line.trim()) pending.push(line)\n else flush()\n }\n flush()\n return blocks\n}\n\n/** A link or an image in markdown-lite source: bang, text, target. */\nconst SOURCE_LINK_PATTERN = /(!?)\\[([^\\]]*)\\]\\(([^)\\s]+)\\)/g\n\n/**\n * Markdown-lite SOURCE with its link references resolved (AGL-3118), for a\n * reader that hands the source on instead of rendering it — the Markdown twin\n * of a page, which an agent follows links out of.\n *\n * `resolve` answers a reference with the URL to write in its place, or with\n * `undefined` for a target that is gone, and that link becomes its text\n * alone: a reference no reader can follow is worse than no link at all. An\n * image whose source is a reference becomes its alt text, because the parser\n * draws no image for one.\n *\n * Everything else stays exactly as written, and fenced code is not touched —\n * a reference quoted in a snippet is the snippet's text, as the parser has it.\n */\nexport function resolveMarkdownSourceLinks(\n source: string,\n resolve: (reference: string) => string | undefined,\n): string {\n if (!source.includes('](')) return source\n let fenced = false\n return source\n .split('\\n')\n .map((line) => {\n if (FENCE_PATTERN.test(line.trim())) {\n fenced = !fenced\n return line\n }\n if (fenced || !line.includes('](')) return line\n return line.replace(\n SOURCE_LINK_PATTERN,\n (match: string, bang: string, text: string, href: string) => {\n if (!isMarkdownLinkReference(href)) return match\n const target = bang ? undefined : resolve(href)\n // A URL cannot close the parentheses it sits in or break at a space.\n return target\n ? `[${text}](${target.replace(/\\)/g, '%29').replace(/\\s/g, '%20')})`\n : text\n },\n )\n })\n .join('\\n')\n}\n\n/**\n * The plain text an inline run reads as — the words with the emphasis and\n * link syntax removed. What a heading contributes to an anchor slug and to a\n * table-of-contents label (AGL-1162), where `## The **fine** print` has to\n * become \"The fine print\" and `the-fine-print`, not two of either.\n */\nexport function markdownInlinesToText(inlines: MarkdownInline[]): string {\n return inlines.map((inline) => inline.text).join('')\n}\n\n/** A heading a table of contents can point at (AGL-1162). */\nexport interface MarkdownHeading {\n level: 2 | 3\n /** Heading text with emphasis/link syntax stripped. */\n text: string\n /** Anchor id, deterministic and unique within the document. */\n slug: string\n /** Position in the block list, so a renderer can id the right heading. */\n index: number\n}\n\n/**\n * Anchor id for one heading's text (AGL-1162).\n *\n * Deterministic by construction — the same words always produce the same id,\n * which is the whole point: a legal page's true source is a markdown file\n * elsewhere, and re-pasting it must not silently break every link that ever\n * pointed into it. Accents fold to their base letter (NFKD then drop the\n * combining marks) so `Résumé` and `Resume` are the same anchor rather than\n * one of them being an unreadable percent-encoded id.\n *\n * A heading of nothing but punctuation or non-Latin script slugifies to\n * empty; those get `SLUG_FALLBACK` here and are told apart by the numbering\n * in {@link collectMarkdownHeadings}, because an id is required for the link\n * to work at all and no id is worse than a dull one.\n */\nexport const SLUG_FALLBACK = 'section'\n\nexport function slugifyHeading(text: string): string {\n return (\n text\n .normalize('NFKD')\n // Combining diacritics left behind by the decomposition above.\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || SLUG_FALLBACK\n )\n}\n\n/**\n * Every heading in a parsed document, with a unique anchor slug (AGL-1162).\n *\n * Duplicates take a `-2`, `-3`, … suffix in document order, and the loop\n * re-checks the suffixed candidate: a document holding two `## Notice`\n * headings AND a literal `## Notice 2` must not hand the same id to two\n * elements, which is exactly what a plain counter would do.\n *\n * Deliberately NOT a widening of the `MarkdownBlock` union. The union is\n * rendered exhaustively in six places, so a slug carried on the heading\n * block would have to be produced by every writer of that union — including\n * the visual editor's serializer, which round-trips through markdown source\n * that has nowhere to put one. Derived here instead, from the same parse the\n * renderer already has, so the markdown text stays the only source of truth.\n */\nexport function collectMarkdownHeadings(\n blocks: MarkdownBlock[],\n): MarkdownHeading[] {\n const headings: MarkdownHeading[] = []\n const used = new Set<string>()\n blocks.forEach((block, index) => {\n if (block.type !== 'heading') return\n const text = markdownInlinesToText(block.inlines).trim()\n const base = slugifyHeading(text)\n let slug = base\n let suffix = 1\n while (used.has(slug)) {\n suffix += 1\n slug = `${base}-${suffix}`\n }\n used.add(slug)\n headings.push({ level: block.level, text, slug, index })\n })\n return headings\n}\n\n/**\n * The same headings keyed by block index, which is the shape every renderer\n * actually wants (AGL-1162).\n *\n * A renderer maps over `blocks` and needs the slug for the block in hand;\n * {@link collectMarkdownHeadings} returns a list, so each of them had to\n * rebuild this map. There were six markdown renderers and one of them did —\n * five published headings a table of contents could never link to, and the\n * one that worked did it with a private `useMemo` nobody else could reach.\n * Living here means a new renderer gets the numbering, the fallback and the\n * duplicate-suffix rules for free rather than approximating them.\n */\nexport function markdownHeadingSlugs(\n blocks: MarkdownBlock[],\n): Record<number, string> {\n const map: Record<number, string> = {}\n for (const heading of collectMarkdownHeadings(blocks)) {\n map[heading.index] = heading.slug\n }\n return map\n}\n\n/**\n * How far below a heading's anchor the viewport stops (AGL-1162) — enough to\n * clear a sticky site header, so a `#slug` link does not land with the\n * heading hidden underneath the nav. Shared so the published page, the entry\n * body and the console preview all scroll to the same place.\n */\nexport const HEADING_ANCHOR_SCROLL_MARGIN = 96\n\n/** Newlines cannot exist inside an inline run — flatten them to a space. */\nconst flattenInlineText = (text: string): string =>\n text.replace(/\\s*\\n+\\s*/g, ' ')\n\n/**\n * Serializes inlines back to markdown-lite source (AGL-582). Characters an\n * inline run cannot represent (the dialect has NO escapes) are dropped:\n * `*` inside bold/italic, `]` in link text/alt, `)` or whitespace in URLs.\n * Parser-emitted inlines never contain them, so for those this is exact.\n */\nexport function serializeMarkdownInlines(inlines: MarkdownInline[]): string {\n let out = ''\n for (const inline of inlines) {\n if (inline.type === 'bold' || inline.type === 'italic') {\n const text = flattenInlineText(inline.text).replace(/\\*/g, '')\n if (!text) continue\n out += inline.type === 'bold' ? `**${text}**` : `*${text}*`\n } else if (inline.type === 'link') {\n const text = flattenInlineText(inline.text).replace(/\\]/g, '')\n const href = inline.href.replace(/[)\\s]/g, '')\n out += text && href ? `[${text}](${href})` : text\n } else {\n out += flattenInlineText(inline.text)\n }\n }\n return out\n}\n\n/**\n * Inverse of `parseMarkdownLite` — the WYSIWYG round-trip contract\n * (AGL-582): for any parser-produced model, the serialized string re-parses\n * to a deep-equal model, and serializing is stable (a second\n * parse→serialize round-trip returns the identical string). Editor-produced\n * models are additionally NORMALIZED the same way the parser would: blocks\n * and list items that would parse to nothing (empty text) are omitted, and\n * block lines are edge-trimmed. Entry bodies stay markdown-lite strings in\n * Firestore — this is the only writer the visual editor goes through.\n *\n * Every block is written as its own chunk, separated by a BLANK line, which\n * is what holds the invariant now that a list may interrupt a paragraph\n * (AGL-1320): `intro:` + `1. a` re-parses to the same paragraph + list pair\n * whether or not the author left a blank line between them. The blank line is\n * therefore load-bearing, not cosmetic: writing the two chunks adjacent would\n * re-parse correctly today only by luck of the interrupt rule.\n */\nexport function serializeMarkdownLite(blocks: MarkdownBlock[]): string {\n const chunks: string[] = []\n for (const block of blocks) {\n if (block.type === 'image') {\n const src = block.src.replace(/[)\\s]/g, '')\n const alt = flattenInlineText(block.alt).replace(/\\]/g, '')\n if (src) chunks.push(``)\n continue\n }\n if (block.type === 'list') {\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line) => `- ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'orderedList') {\n // Markers are RE-NUMBERED from `start` (AGL-1320) rather than written\n // back verbatim: the parser only reads the first one, so contiguous\n // markers are the single form that re-parses to this exact model.\n // A missing/absurd start falls back to 1, the way a hand-written list\n // reads anyway.\n const start = Number.isFinite(block.start)\n ? Math.max(0, Math.trunc(block.start))\n : 1\n const lines = block.items\n .map((item) => serializeMarkdownInlines(item).trim())\n .filter(Boolean)\n .map((line, index) => `${start + index}. ${line}`)\n if (lines.length) chunks.push(lines.join('\\n'))\n continue\n }\n if (block.type === 'code') {\n // The fence is the only delimiter the dialect has, so a fence INSIDE\n // the snippet would end it early — those backticks drop, the same way\n // an unrepresentable `*` drops from a bold run.\n const text = block.text\n .replace(/^(\\s*)`{3,}/gm, '$1')\n .replace(/^(?:[ \\t]*\\n)+/, '')\n .replace(/(?:\\n[ \\t]*)+$/, '')\n const lang = block.lang.replace(/[^\\w+#.-]/g, '')\n chunks.push([`\\`\\`\\`${lang}`, ...(text ? [text] : []), '```'].join('\\n'))\n continue\n }\n if (block.type === 'table') {\n // `|` separates cells and there are no escapes, so a pipe inside a\n // cell drops. Empty cells are kept — they are meaningful in a table.\n const row = (cells: MarkdownTableCell[]): string =>\n `| ${cells\n .map((cell) => serializeMarkdownInlines(cell).replace(/\\|/g, '').trim())\n .join(' | ')} |`\n if (!block.header.length) continue\n const delimiters = block.header.map((_, index) => {\n const align = block.align[index] ?? 'left'\n return align === 'center' ? ':-:' : align === 'right' ? '--:' : '---'\n })\n chunks.push(\n [\n row(block.header),\n `| ${delimiters.join(' | ')} |`,\n // Squared off to the header: the parser reads it back that way,\n // so writing anything else would not round-trip.\n ...block.rows.map((cells) =>\n row(\n Array.from(\n { length: block.header.length },\n (_, index) => cells[index] ?? [],\n ),\n ),\n ),\n ].join('\\n'),\n )\n continue\n }\n const line = serializeMarkdownInlines(block.inlines).trim()\n if (!line) continue\n chunks.push(\n block.type === 'heading'\n ? `${'#'.repeat(block.level)} ${line}`\n : block.type === 'quote'\n ? `> ${line}`\n : line,\n )\n }\n return chunks.join('\\n\\n')\n}\n"],"names":["isMediaRef","parseMediaRef","parseCollectionLinkValue","parseEntryLinkValue","parseFeedLinkValue","parseScreenLinkValue","resolveScreenHref","SCREEN_LINK_VALUE_PREFIX","screenRoutesAnswerFor","INLINE_PATTERN","safeUrl","url","test","isSupportedLinkHref","safeLinkUrl","isSupportedImageSrc","safeImageUrl","isMarkdownLinkReference","startsWith","undefined","isInternalMarkdownHref","href","resolveMarkdownLink","context","screens","reference","resolved","suppressNavigation","gone","kind","pushText","inlines","text","last","length","type","push","parseMarkdownInlines","cursor","match","matchAll","index","slice","HEADING_PATTERN","clampHeadingLevel","hashes","FENCE_PATTERN","BULLET_ITEM_PATTERN","ORDERED_ITEM_PATTERN","DELIMITER_CELL","splitTableRow","line","trim","endsWith","split","map","cell","alignOfDelimiter","left","right","parseTable","lines","headerLine","delimiterLine","includes","delimiters","every","header","columns","squared","cells","Array","from","_","align","rows","listStartOf","interrupting","start","ordered","exec","Number","parseChunk","chunk","trimmed","image","src","alt","heading","level","table","replace","filter","Boolean","join","blocks","prose","flushProse","list","pattern","items","item","parseMarkdownLite","body","pending","flush","fence","shift","pop","lang","SOURCE_LINK_PATTERN","resolveMarkdownSourceLinks","source","resolve","fenced","bang","target","markdownInlinesToText","inline","SLUG_FALLBACK","slugifyHeading","normalize","toLowerCase","collectMarkdownHeadings","headings","used","Set","forEach","block","base","slug","suffix","has","add","markdownHeadingSlugs","HEADING_ANCHOR_SCROLL_MARGIN","flattenInlineText","serializeMarkdownInlines","out","serializeMarkdownLite","chunks","isFinite","Math","max","trunc","row","repeat"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GAED,SAASA,UAAU,EAAEC,aAAa,QAAQ,iBAAa;AACvD,SACEC,wBAAwB,EACxBC,mBAAmB,EACnBC,kBAAkB,EAClBC,oBAAoB,EACpBC,iBAAiB,EACjBC,wBAAwB,EACxBC,qBAAqB,QAChB,yBAAqB;AAiD5B,MAAMC,iBACJ;AAEF;;;;CAIC,GACD,SAASC,QAAQC,GAAW;IAC1B,OAAO,gBAAgBC,IAAI,CAACD,OAAOA,MAAM;AAC3C;AAEA;;;;CAIC,GACD,OAAO,SAASE,oBAAoBF,GAAW;IAC7C,OAAOG,YAAYH,SAAS;AAC9B;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASI,oBAAoBJ,GAAW;IAC7C,OAAOK,aAAaL,S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hC;4BAAU6B;gCAAAA,eAAAA,KAAK,CAAC7B,MAAM,YAAZ6B,eAAgB,EAAE;;aAIvC,CAACwB,IAAI,CAAC;YAET;QACF;QACA,MAAM3C,OAAOsF,yBAAyBT,MAAMjG,OAAO,EAAEqB,IAAI;QACzD,IAAI,CAACD,MAAM;QACXyF,OAAOxG,IAAI,CACT4F,MAAM7F,IAAI,KAAK,YACX,GAAG,IAAI+G,MAAM,CAAClB,MAAMvC,KAAK,EAAE,CAAC,EAAEtC,MAAM,GACpC6E,MAAM7F,IAAI,KAAK,UACb,CAAC,EAAE,EAAEgB,MAAM,GACXA;IAEV;IACA,OAAOyF,OAAO9C,IAAI,CAAC;AACrB"}
|
|
@@ -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 {
|