@murumets-ee/menus 0.106.0 → 0.108.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/dist/admin.d.mts +56 -1
- package/dist/admin.d.mts.map +1 -1
- package/dist/admin.mjs +1 -1
- package/dist/admin.mjs.map +1 -1
- package/dist/{columns-D9y6Mvcp.mjs → columns-DwDukx_r.mjs} +2 -2
- package/dist/columns-DwDukx_r.mjs.map +1 -0
- package/dist/en-BcniJZiB.mjs +2 -0
- package/dist/en-BcniJZiB.mjs.map +1 -0
- package/dist/{et-Bc89uj45.mjs → et-BL3ZuuFV.mjs} +2 -2
- package/dist/et-BL3ZuuFV.mjs.map +1 -0
- package/dist/i18n.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/menu-entity-types-BnKnKbif.mjs.map +1 -1
- package/dist/{menu-item-schema-Be161XVs.d.mts → menu-item-schema-_Nj03ytp.d.mts} +7 -7
- package/dist/menu-item-schema-_Nj03ytp.d.mts.map +1 -0
- package/dist/menu-resolve-context-DLIUP8RY.mjs +2 -0
- package/dist/{menu-resolve-context-2s6VJs_m.mjs.map → menu-resolve-context-DLIUP8RY.mjs.map} +1 -1
- package/dist/messages/en.json +3 -0
- package/dist/messages/et.json +3 -0
- package/dist/messages/ru.json +3 -0
- package/dist/{ru-kO0E9q-_.mjs → ru-D8QNW6XE.mjs} +2 -2
- package/dist/ru-D8QNW6XE.mjs.map +1 -0
- package/dist/schema.d.mts +1 -1
- package/package.json +7 -7
- package/dist/columns-D9y6Mvcp.mjs.map +0 -1
- package/dist/en-C92R_j7m.mjs +0 -2
- package/dist/en-C92R_j7m.mjs.map +0 -1
- package/dist/et-Bc89uj45.mjs.map +0 -1
- package/dist/menu-item-schema-Be161XVs.d.mts.map +0 -1
- package/dist/menu-resolve-context-2s6VJs_m.mjs +0 -2
- package/dist/ru-kO0E9q-_.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"columns-DwDukx_r.mjs","names":["roots","prefixIssues"],"sources":["../src/menu-item-schema.ts","../src/menu-entity-types.ts","../src/behaviors/menu-entity-types-validation.ts","../src/behaviors/menu-tree-validation.ts","../src/entity.ts","../src/internal/columns.ts"],"sourcesContent":["/**\n * `MenuItem` — the menu tree node — and its recursive Zod validation\n * (plan/routing phase 08 §3).\n *\n * A menu's `tree` column is ordered nested JSONB (D008), so the ONLY thing\n * standing between an admin PATCH and the database is this schema: it is the\n * boundary validation required by CLAUDE.md's C5. It enforces\n *\n * - the `kind`-conditional shape (`link` items carry a `LinkValue`, `header`\n * items carry a label map and no link),\n * - locale keys drawn from the app's configured locale set,\n * - `LinkValue`s that mirror `@murumets-ee/blocks`' union exactly, with `url`\n * kinds protocol-gated through the SAME `sanitizeHref` allowlist the link\n * picker uses (no `javascript:` / `data:` / protocol-relative smuggling),\n * - hard structural bounds on tree size + nesting, checked BEFORE the\n * recursive parse so a hostile payload can't turn validation itself into a\n * stack-overflow / CPU amplification vector.\n *\n * This module is deliberately **pure**: no `@murumets-ee/core`, no content\n * plugin lookup, no DB. The allowed-locale set is passed IN, so the schema can\n * be built server-side (the `menuTreeValidation()` behavior) or client-side\n * (PR10's editor, with locales handed down from the server) from the same code.\n * Cross-field depth validation against the entity's sibling `maxDepth` column\n * lives in {@link validateTreeDepth}, which the behavior calls separately.\n */\n\nimport { sanitizeHref } from '@murumets-ee/blocks/links'\nimport { z } from 'zod'\n\n/**\n * Absolute nesting cap for any menu, independent of a menu's own `maxDepth`\n * (phase 07 §2.7 — \"depth is capped per menu (default 3, max 6)\"). Also the\n * bound that keeps the recursive parse from being a DoS vector.\n */\nexport const MAX_MENU_DEPTH = 6\n\n/** `maxDepth`'s default — a 3-level menu (phase 08 §2). */\nexport const DEFAULT_MENU_DEPTH = 3\n\n/**\n * Upper bound on the number of nodes in one menu tree. Navigation menus are\n * hand-curated: a few dozen items is a big one. The cap exists so a single\n * PATCH can't hand the validator (and `extractRefs`' ref walk, and every\n * subsequent render) an unbounded amount of work — CLAUDE.md's\n * \"no unbounded fan-out\" rule applied to a single request payload.\n */\nexport const MAX_MENU_TREE_NODES = 500\n\n/**\n * Max stored length of a `url`-kind link. Pinned to `entity`'s\n * `MAX_EXTERNAL_URL_LENGTH` (the `external_link_usage.url_raw` column width)\n * at COMPILE time via `satisfies` + a type-only import — so a longer URL is\n * rejected at the boundary instead of being silently dropped from the\n * reference graph. Same drift-proofing trick as content's\n * `DEFAULT_LOCALE_SENTINEL`; `import type` has zero runtime cost, so the pure\n * schema module keeps its (client-safe) dependency-free shape.\n */\nexport const MAX_MENU_URL_LENGTH =\n 2048 satisfies typeof import('@murumets-ee/entity/refs')['MAX_EXTERNAL_URL_LENGTH']\n\n/** Max length of an item's stable id (a UUID today; generated client-side). */\nconst MAX_ITEM_ID_LENGTH = 64\n\n/**\n * Max length of a per-locale label string. Exported for the one other writer of\n * a label — the translatable source (`./translatable-source.ts`) — which tells\n * a translator the bound up front and refuses an over-long answer by item.\n */\nexport const MAX_LABEL_LENGTH = 200\n\n/**\n * Max length of an entity-link fragment/anchor.\n *\n * Exported because this module is the SINGLE OWNER of the anchor bounds: the\n * write-side schema below, the read-side anchor walk\n * (`admin/anchors.ts`) and the editor's manual-entry fallback\n * (`@murumets-ee/menus-ui`'s anchor picker, via the client-safe `./schema`\n * subpath) all validate against exactly these two constants. Two of those three\n * used to carry their own copy; a drift between them would let the picker offer\n * — or the editor accept — a value the write boundary then rejects.\n */\nexport const MAX_ANCHOR_LENGTH = 128\n\n/**\n * Max length of an entity NAME inside an entity link (`page`, `article`, …).\n *\n * Exported for the same single-owner reason as {@link MAX_ANCHOR_LENGTH}: the\n * per-menu `entityTypes` whitelist (`./menu-entity-types.ts`) stores values of\n * exactly this kind, and a second copy of the bound could drift into a\n * whitelist entry the link schema then refuses.\n */\nexport const MAX_ENTITY_NAME_LENGTH = 64\n\n/**\n * Anchors are slugified by the block editor (phase 08 §5) and rendered into an\n * `href` as `#<anchor>`; restricting them to slug characters keeps that\n * interpolation inert.\n *\n * Exported for the same single-owner reason as {@link MAX_ANCHOR_LENGTH}.\n */\nexport const ANCHOR_PATTERN = /^[A-Za-z0-9_-]+$/\n\n/**\n * A menu item's link target — the item-type union phase 07 §2.2 and phase 08 §3\n * define: `entity` (+ optional anchor) | `url` | `email`.\n *\n * **A NARROWED SUBSET of `@murumets-ee/blocks`' `LinkValue`, deliberately.**\n * Blocks additionally carries a `media` kind; menus does NOT, because no phase\n * gives a menu a media-href seam to resolve one with (phase 11 §2 specifies\n * `href` as \"canonical path from `toolkit_paths`; external URLs verbatim;\n * header items null\" and nothing else). Accepting a `media` link would let it\n * validate, persist, and register an `entity_refs` row — arming delete\n * protection for that file — while the renderer had no way to emit it: the item\n * would silently never appear. Rejecting it at the write boundary turns that\n * dead weight into a real 400. Widening later is additive (an arm here plus a\n * `resolveMediaHref` dep on `MenuResolveDeps`) and needs no shape change.\n *\n * Every `MenuLinkValue` IS a valid blocks `LinkValue` (the subset direction, and\n * the one `resolveLinkHref` needs) — pinned at compile time by an assignment in\n * `menu-item-schema.test.ts`, so a drift in blocks' union is a build error\n * rather than a silent divergence.\n *\n * The `anchor?: string | undefined` is forced by the combination of Zod and this\n * repo's `exactOptionalPropertyTypes`: `.optional()` always widens to\n * `T | undefined`, which is NOT assignable to blocks' `anchor?: string` under\n * that flag.\n */\nexport type MenuLinkValue =\n | { kind: 'entity'; entity: string; id: string; anchor?: string | undefined }\n | { kind: 'url'; url: string }\n | { kind: 'email'; email: string }\n\n/**\n * A menu tree node (phase 08 §3 / D009).\n *\n * `label: null` means \"use the LIVE title of the linked entity, per locale\";\n * a map is an explicit per-locale override. `enabled` is per-locale visibility\n * in BOTH directions — absent/`true` shows the item, `false` hides it in that\n * locale — so one tree serves every locale (no `menu_translations` table).\n *\n * Declared as a `type`, NOT an `interface`, on purpose: only type aliases get\n * TypeScript's implicit index signature, and without it `MenuItem[]` is not\n * assignable to the `Record<string, unknown>[]` arm of `AdminClient.create/\n * update`'s json-field value type — every caller storing a typed tree would\n * need a cast.\n */\nexport type MenuItem = {\n /** Stable id — DND identity + anchor for audit diffs. */\n id: string\n /** `header` = a text-only dropdown parent with no link of its own. */\n kind: 'link' | 'header'\n /**\n * Present iff `kind === 'link'`.\n *\n * The explicit `| undefined` is required by the repo's\n * `exactOptionalPropertyTypes` — Zod's `.optional()` emits\n * `LinkValue | undefined`, and without it the schema wouldn't typecheck\n * against this interface.\n */\n link?: MenuLinkValue | undefined\n /** `null` = live entity title per locale; a map = explicit override. */\n label: Record<string, string> | null\n /** Per-locale visibility. Absent/`true` = visible; `false` = hidden. */\n enabled?: Record<string, boolean> | undefined\n newTab?: boolean | undefined\n children: MenuItem[]\n}\n\n/**\n * One menu item's target, as the editor needs to render its row\n * (`@murumets-ee/menus/admin`'s `resolveMenuItemSummaries`).\n *\n * Declared here — not in `admin/summaries.ts` — for the same reason\n * {@link BlockAnchor} is: it is a pure data shape with no server dependency,\n * so the client-safe `./schema` subpath can re-export it without pulling the\n * server-only resolver along. `import type` is erased at compile time either\n * way, but a single canonical home (this leaf module) is simpler to reason\n * about than \"which of two server-only files owns the type\".\n */\nexport interface MenuItemSummary {\n /**\n * The target row's live title, or `null` when the entity declares no\n * display-able field. Unlike the public render path — which DROPS such an\n * item rather than show a raw uuid as navigation — the admin editor still\n * reports the target as present, just unlabelled.\n */\n title: string | null\n /** `false` = the target row is gone (deleted) → a BROKEN item. */\n exists: boolean\n /** `null` when the entity isn't publishable — no draft/published distinction applies. */\n published: boolean | null\n}\n\n/**\n * One addressable block anchor on a document (`@murumets-ee/menus/admin`'s\n * `collectBlockAnchors` / the anchors endpoint). See {@link MenuItemSummary}'s\n * doc for why this pure shape lives here rather than in `admin/anchors.ts`.\n */\nexport interface BlockAnchor {\n /** The stable id rendered as the block element's `id` attribute. */\n anchor: string\n /** Display text — `anchorLabel` when usable, else the anchor value itself. */\n label: string\n}\n\n/** Options for {@link buildMenuItemSchema} / {@link buildMenuTreeSchema}. */\nexport interface MenuSchemaOptions {\n /**\n * Locale codes accepted as keys in `label` / `enabled` maps. Anything else\n * is a validation error — a typo'd locale would produce a label no renderer\n * ever reads (the same failure mode content's `validateLocale` guards).\n */\n allowedLocales: readonly string[]\n}\n\n/**\n * {@link MenuLinkValue} as Zod. Blocks models its own `LinkValue` as a plain TS\n * type + structural guards (zod-free by design), so this is the first Zod\n * encoding of it — narrowed to the three kinds a menu item may carry.\n *\n * There is deliberately NO `media` arm (see {@link MenuLinkValue}): a media\n * link has no href seam at render time, so accepting one would store a\n * permanently invisible item. `z.discriminatedUnion` rejects it with an\n * `Invalid discriminator value. Expected 'entity' | 'url' | 'email'` issue —\n * which names the allowed set without echoing the caller's own value back.\n *\n * `url` kinds run through `sanitizeHref`, the single source of truth for the\n * href protocol allowlist (`http:`/`https:`/`mailto:`/`tel:` + relative\n * paths); it returns `''` for anything it rejects, including\n * protocol-relative `//evil.com` and obfuscated `java\\nscript:`.\n */\nexport const LinkValueSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('entity'),\n entity: z.string().min(1).max(MAX_ENTITY_NAME_LENGTH),\n id: z.string().uuid(),\n anchor: z.string().min(1).max(MAX_ANCHOR_LENGTH).regex(ANCHOR_PATTERN).optional(),\n }),\n z.object({\n kind: z.literal('url'),\n // Transform-then-refine, NOT refine-alone: `sanitizeHref` trims, so\n // validating its output while storing the raw input would let a value\n // that PASSED validation differ from the value that gets STORED (leading\n // /trailing whitespace). Storing the sanitizer's own return value keeps\n // stored == validated. The arrow wrapper is required — `sanitizeHref`'s\n // second parameter is the protocol allowlist, and passing Zod's ctx into\n // it would silently replace the allowlist.\n url: z\n .string()\n .min(1)\n .max(MAX_MENU_URL_LENGTH)\n .transform((value) => sanitizeHref(value))\n .refine((value) => value !== '', {\n message:\n 'link url uses a disallowed protocol (allowed: http, https, mailto, tel, or a relative path)',\n }),\n }),\n z.object({\n kind: z.literal('email'),\n email: z.string().email().max(254),\n }),\n])\n\n/**\n * A `Record<locale, T>` whose keys must all be configured locale codes.\n *\n * The key check is PIPED INTO the record parse rather than refined on top of\n * it, so it runs against the RAW value BEFORE any per-value parsing. That\n * ordering is the whole point: with `z.record(...).superRefine(...)`, zod\n * parses all N values first, so a 1,000,000-key map of wrong-typed values\n * emits 1,000,000 `invalid_type` issues before a width check on top could ever\n * fire (verified empirically against zod 3.25). Piping caps BOTH shapes —\n * unknown keys and bad values — at a single issue.\n */\nfunction localeMap<T extends z.ZodTypeAny>(\n valueSchema: T,\n allowedLocales: readonly string[],\n): z.ZodType<Record<string, z.infer<T>>, z.ZodTypeDef, unknown> {\n const allowed = new Set(allowedLocales)\n return z\n .unknown()\n .superRefine((value, ctx) => {\n // Not a plain object — let the record parse below emit the single\n // \"expected object\" issue rather than duplicating its message here.\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return\n\n const keys = Object.keys(value)\n // Width bound, checked FIRST. A legitimate map holds at most one entry\n // per configured locale, so a wider map is malformed by construction and\n // gets ONE issue for the whole map. Without this, a single node carrying\n // e.g. 1,000,000 keys sails past the tree pre-scan (which bounds node\n // COUNT and DEPTH, never map WIDTH) and turns validation itself into the\n // amplification vector it exists to prevent: a multi-hundred-MB issue\n // array plus an oversized audit-log write, from one request.\n // CLAUDE.md's \"no unbounded fan-out\" applied to a single payload.\n if (keys.length > allowed.size) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `too many locale keys — configured locales are: ${[...allowed].join(', ')}`,\n })\n return\n }\n\n // Past the width bound this loop is bounded by the CONFIGURED locale\n // count, never by the payload.\n for (const key of keys) {\n if (!allowed.has(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [key],\n // Names the allowed set (server-side data), never echoes the\n // caller-supplied key into the message — see the api-handler's\n // \"refine()/custom messages must not echo user input\" contract.\n message: `unknown locale key — configured locales are: ${[...allowed].join(', ')}`,\n })\n }\n }\n })\n .pipe(z.record(z.string(), valueSchema))\n}\n\n/**\n * The recursive per-node schema. Input is `unknown` (this parses untrusted\n * JSONB), output is a fully-narrowed {@link MenuItem}. Unknown properties are\n * STRIPPED by Zod's default object behavior, so writing the parse result back\n * onto the payload also sanitizes it — nothing a caller invents gets stored.\n */\nexport function buildMenuItemSchema(\n options: MenuSchemaOptions,\n): z.ZodType<MenuItem, z.ZodTypeDef, unknown> {\n const labelMap = localeMap(z.string().max(MAX_LABEL_LENGTH), options.allowedLocales)\n const enabledMap = localeMap(z.boolean(), options.allowedLocales)\n\n const schema: z.ZodType<MenuItem, z.ZodTypeDef, unknown> = z.lazy(() =>\n z\n .object({\n id: z.string().min(1).max(MAX_ITEM_ID_LENGTH),\n kind: z.enum(['link', 'header']),\n link: LinkValueSchema.optional(),\n label: labelMap.nullable().default(null),\n enabled: enabledMap.optional(),\n newTab: z.boolean().optional(),\n children: z.array(schema).default([]),\n })\n .superRefine((node, ctx) => {\n if (node.kind === 'link') {\n if (node.link === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['link'],\n message: 'a link item requires a link target',\n })\n }\n return\n }\n // header\n if (node.link !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['link'],\n message: 'a header item must not carry a link target',\n })\n }\n // A header has no entity to borrow a live title from, so its label\n // map is required (phase 08 §3) — otherwise it renders as nothing.\n if (node.label === null || Object.keys(node.label).length === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['label'],\n message: 'a header item requires a label for at least one locale',\n })\n }\n }),\n )\n\n return schema\n}\n\n/** The whole tree — an array of {@link buildMenuItemSchema} nodes. */\nexport function buildMenuTreeSchema(\n options: MenuSchemaOptions,\n): z.ZodType<MenuItem[], z.ZodTypeDef, unknown> {\n return z.array(buildMenuItemSchema(options))\n}\n\n/** Result of {@link measureMenuTree}. */\nexport interface MenuTreeMeasurement {\n /** Deepest nesting level; `0` for an empty tree, `1` for flat items. */\n depth: number\n /** Total node count across every level. */\n nodeCount: number\n}\n\n/**\n * Measure a (possibly untrusted) tree's depth + node count **iteratively**, so\n * measuring can never blow the stack the way a recursive walk over a hostile\n * payload would. Stops early once either hard bound is exceeded and reports\n * the over-limit value — the caller turns that into a validation error.\n *\n * Accepts `unknown` on purpose: this runs BEFORE the Zod parse (bounding the\n * work that parse will do), so it can't assume a well-formed shape.\n */\nexport function measureMenuTree(tree: unknown): MenuTreeMeasurement {\n if (!Array.isArray(tree)) return { depth: 0, nodeCount: 0 }\n\n let maxDepth = 0\n let nodeCount = 0\n // `Array.isArray` narrows an `unknown` to `any[]`; re-binding through a\n // `readonly unknown[]` annotation keeps every element typed as `unknown`\n // instead of silently leaking `any` into the walk.\n const roots: readonly unknown[] = tree\n const stack: Array<{ node: unknown; depth: number }> = roots.map((node) => ({ node, depth: 1 }))\n\n while (stack.length > 0) {\n const current = stack.pop()\n if (current === undefined) break\n const { node, depth } = current\n if (node === null || typeof node !== 'object' || Array.isArray(node)) continue\n\n nodeCount++\n if (depth > maxDepth) maxDepth = depth\n // Early abort: past either bound the exact totals no longer matter, only\n // that they're over — and continuing would be the amplification we're\n // guarding against.\n if (nodeCount > MAX_MENU_TREE_NODES || maxDepth > MAX_MENU_DEPTH) {\n return { depth: maxDepth, nodeCount }\n }\n\n const children = (node as { children?: unknown }).children\n if (Array.isArray(children)) {\n const items: readonly unknown[] = children\n for (const child of items) stack.push({ node: child, depth: depth + 1 })\n }\n }\n\n return { depth: maxDepth, nodeCount }\n}\n\n/**\n * Cross-field check: does `tree` nest no deeper than the menu's own\n * `maxDepth`? Lives outside the node schema because a per-node Zod refinement\n * has no visibility of the sibling `maxDepth` COLUMN — the behavior calls this\n * after the recursive parse.\n */\nexport function validateTreeDepth(tree: unknown, maxDepth: number): boolean {\n return measureMenuTree(tree).depth <= maxDepth\n}\n","/**\n * The per-menu `entityTypes` whitelist — \"which content types may be linked\n * from this menu\" (plan/routing phase 07 §2.8, 09 §3, 10 §4).\n *\n * Drupal's per-content-type menu offering, minus the config-entity ceremony: a\n * `page` doesn't declare \"I belong in menus\", each MENU declares which types it\n * accepts. Two surfaces consume it — the menu editor's \"Add link\" picker (which\n * content types its Content tab offers) and the Meta panel's Menus section\n * (which menus an entity's edit screen offers to join).\n *\n * ## Semantics — `null` is \"everything\", and it is the ONLY unrestricted shape\n *\n * `null` (or an absent column) = the menu accepts every entity type. That is the\n * default, and it is what every menu row written before this column existed\n * reads back as, so the whitelist is backward-compatible by construction.\n *\n * An EMPTY array means the same thing, and {@link MenuEntityTypesSchema}\n * normalises it to `null` on the way in — the editor's \"nothing selected\" state\n * naturally produces `[]`, and letting both spellings persist would mean every\n * reader had to remember to check for two. Readers still tolerate a stored `[]`\n * (a hand-edited row, an older dump) via {@link menuAcceptsEntityType}.\n *\n * A menu that accepts NOTHING is deliberately unrepresentable: it could only\n * ever be a mistake, and \"empty selection\" is far more likely to mean \"I haven't\n * narrowed this yet\" than \"refuse everything\".\n *\n * ## Not a security boundary\n *\n * This is an authoring affordance. It decides what a picker OFFERS; it does not\n * decide what a caller may write — `menu:update` on the entity PATCH does, and\n * `menuTreeValidation()` re-checks the tree's shape regardless of the whitelist.\n * So the read path fails OPEN (a malformed column means \"no restriction\"): a\n * junk value must not hide every menu from the admin who needs to fix it. The\n * WRITE path fails closed, as every boundary does.\n *\n * @module\n */\n\nimport { z } from 'zod'\nimport { MAX_ENTITY_NAME_LENGTH } from './menu-item-schema.js'\n\n/**\n * Upper bound on how many entity types one menu's whitelist may name.\n *\n * A real app registers a few dozen entities, so this is a malformed-payload\n * guard rather than a product limit — it keeps a hostile PATCH from parking an\n * unbounded array in the column (and, through it, in every editor's RSC\n * payload).\n *\n * **Not** `MAX_MENU_ENTITY_TYPES` (`./get-menu.ts`, 16). That one bounds RENDER\n * fan-out — how many distinct types one menu render may issue batched lookups\n * for — and applies to the types actually present in the stored tree. This one\n * bounds the stored AUTHORING whitelist, which costs no I/O at all.\n */\nexport const MAX_MENU_ENTITY_TYPE_WHITELIST = 64\n\n/** One entity name in the whitelist — same bound `link.entity` carries. */\nconst EntityTypeName = z.string().min(1).max(MAX_ENTITY_NAME_LENGTH)\n\n/**\n * The write-boundary schema for `menu.entityTypes`.\n *\n * Strict where {@link normalizeMenuEntityTypes} is tolerant: a junk entry is a\n * 400, not a silent drop, because silently discarding half an admin's selection\n * and reporting success is worse than refusing the write. Duplicates ARE folded\n * (an idempotent selection is not an error), and `[]` becomes `null` so the\n * column only ever holds one representation of \"unrestricted\".\n */\nexport const MenuEntityTypesSchema: z.ZodType<string[] | null, z.ZodTypeDef, unknown> = z\n .array(EntityTypeName)\n // DELIBERATE ORDER — `.max()` runs on the RAW array, BEFORE the dedup in the\n // transform below, so 65 copies of `'page'` is a 400 even though it would\n // store one entry. The bound is on the PAYLOAD, not on the result: deduping\n // first would mean accepting an unbounded array to prove it was small.\n .max(MAX_MENU_ENTITY_TYPE_WHITELIST)\n .nullable()\n .transform((value) => {\n if (value === null) return null\n const deduped = [...new Set(value)]\n return deduped.length === 0 ? null : deduped\n })\n\n/**\n * Narrow a raw `entityTypes` column value (untrusted shape) to a usable\n * whitelist, or `null` for \"no restriction\".\n *\n * The read-side counterpart of {@link MenuEntityTypesSchema}, and tolerant for\n * the same reason `normalizeMenuTree` is: rows written before this column\n * existed, hand edits and restored dumps all reach readers, and a render must\n * degrade rather than throw. Anything unusable — a non-array, a non-string\n * entry, a whitelist that reduces to nothing — reads as `null`.\n */\nexport function normalizeMenuEntityTypes(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n // `Array.isArray` narrows `unknown` to `any[]`; re-binding through a\n // `readonly unknown[]` annotation keeps every element typed as `unknown`.\n const raw: readonly unknown[] = value\n\n const out: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string' || entry.length === 0) continue\n if (entry.length > MAX_ENTITY_NAME_LENGTH) continue\n if (seen.has(entry)) continue\n seen.add(entry)\n out.push(entry)\n if (out.length === MAX_MENU_ENTITY_TYPE_WHITELIST) break\n }\n return out.length === 0 ? null : out\n}\n\n/**\n * Does this menu accept links to `entityType`?\n *\n * Takes the RAW column value so callers holding a `field.json()`-typed row can\n * ask directly, without narrowing first. Exact string match — entity names are\n * lowercase identifiers, and a case-insensitive or prefix match would silently\n * widen a whitelist the admin wrote precisely.\n *\n * Fails OPEN (see the module header): absent, empty and malformed all mean \"no\n * restriction\".\n */\nexport function menuAcceptsEntityType(value: unknown, entityType: string): boolean {\n const whitelist = normalizeMenuEntityTypes(value)\n return whitelist === null || whitelist.includes(entityType)\n}\n","/**\n * `menuEntityTypesValidation()` — boundary validation for the\n * `menu.entityTypes` JSONB column (plan/routing phase 07 §2.8, F056).\n *\n * `field.json()`'s own validation is the deliberately permissive JSON union, so\n * without this hook an admin PATCH could park any shape — including an unbounded\n * array — in the column, and every reader (editor picker, Meta panel, every RSC\n * payload that carries the row) would pay for it. CLAUDE.md's \"validate at the\n * boundary\" applied to the one column `menuTreeValidation()` doesn't cover.\n *\n * **Why a second behavior rather than a branch inside `menuTreeValidation()`.**\n * The two share nothing: the tree check is CROSS-FIELD (it reads the sibling\n * `maxDepth` column through `loadCurrent`) and CROSS-MODULE (locale keys against\n * the content plugin's registry, hence its injectable resolver option); this one\n * is self-contained and needs no context at all. Folding it in would put an\n * option-less concern behind `MenuTreeValidationOptions` and make a behavior\n * named \"tree validation\" own a non-tree column.\n *\n * Errors are `ZodError`s so the admin API maps them to **400 with structured\n * issues** rather than a 500 — same contract `menuTreeValidation()` relies on.\n * Issues are pathed at `entityTypes` so the client can point at the field.\n */\n\nimport type { Behavior, BulkUpdateInfo } from '@murumets-ee/entity'\nimport { z } from 'zod'\nimport { MenuEntityTypesSchema } from '../menu-entity-types.js'\n\n/**\n * `AdminClient.updateMany` runs NO per-row hooks, so `beforeUpdate` above never\n * fires on that path — a bulk statement could otherwise park an unbounded or\n * malformed array in the column and every reader would pay for it, which is the\n * exact hole this behavior exists to close. `assertBulkUpdate` is the sanctioned\n * cover for that gap (same mechanism `hierarchical()` uses to stop a partial\n * bulk tree write).\n *\n * This REJECTS rather than validates: `updateMany` sets one value across every\n * matched row, and \"every menu accepts exactly these types\" is not a coherent\n * intent — a whitelist is per-menu by definition. There is no legitimate bulk\n * caller to serve, so refusing is both safer and more honest than silently\n * validating a shape nobody should be writing this way.\n */\nfunction assertNoBulkEntityTypesWrite(info: BulkUpdateInfo): void {\n if (!info.keys.includes('entityTypes')) return\n throw new z.ZodError([\n {\n code: 'custom',\n path: ['entityTypes'],\n message:\n `bulk update on '${info.entityName}' cannot write 'entityTypes': updateMany runs no ` +\n 'per-row hooks, so the whitelist would bypass its schema check. A whitelist is ' +\n 'per-menu — update each row individually, or write a migration for a one-off backfill.',\n },\n ])\n}\n\n/** Prefix every issue path with `entityTypes` so the client can locate it. */\nfunction prefixIssues(error: z.ZodError): z.ZodError {\n return new z.ZodError(\n error.issues.map((issue) => ({ ...issue, path: ['entityTypes', ...issue.path] })),\n )\n}\n\n/**\n * Validate + normalize `data.entityTypes` in place, returning the payload with\n * the PARSED value (so `[]` is persisted as `null` and duplicates are folded —\n * see `../menu-entity-types.ts` for why there is exactly one unrestricted\n * shape).\n *\n * A payload without the key is a partial update that doesn't touch the column;\n * it passes through untouched rather than being defaulted, which would let a\n * `{ tree }`-only PATCH silently clear an authored whitelist.\n */\nfunction validateEntityTypes(data: Record<string, unknown>): Record<string, unknown> {\n if (!('entityTypes' in data)) return data\n\n const parsed = MenuEntityTypesSchema.safeParse(data.entityTypes)\n if (!parsed.success) throw prefixIssues(parsed.error)\n return { ...data, entityTypes: parsed.data }\n}\n\n/**\n * Recursive-free Zod validation of `menu.entityTypes` on every create/update.\n *\n * Contributes NO fields, so the field-map type param is the EMPTY map\n * `Record<never, never>` — NOT `Record<string, never>`, which would merge into\n * the entity's field map and collapse every field to `never`.\n */\nexport function menuEntityTypesValidation(): Behavior<\n Record<never, never>,\n 'menuEntityTypesValidation'\n> {\n return {\n name: 'menuEntityTypesValidation',\n hooks: {\n beforeCreate: async (data) => validateEntityTypes(data),\n beforeUpdate: async (_id, data) => validateEntityTypes(data),\n },\n assertBulkUpdate: assertNoBulkEntityTypesWrite,\n }\n}\n","/**\n * `menuTreeValidation()` — boundary validation for the `menu.tree` JSONB column\n * (plan/routing phase 08 §3, F040 pt.2).\n *\n * Why a behavior and not field-local validation: two of the four rules are\n * CROSS-FIELD or CROSS-MODULE. The tree's nesting depth is checked against the\n * sibling `maxDepth` COLUMN, and the locale keys are checked against the app's\n * configured content locales — neither is visible to `field.json()`'s\n * (deliberately permissive) JSON union. `BehaviorContext` gives a hook both:\n * the update payload and, via `loadCurrent`, the pre-update row.\n *\n * Errors are raised as `ZodError`s on purpose: the admin API handler maps\n * `ZodError` to **400 with structured issues** (a plain `Error` would surface\n * as a 500), so an editor saving a malformed tree gets a per-node message\n * pointing at the offending item instead of \"Internal server error\".\n */\n\nimport { getContentConfig } from '@murumets-ee/content/plugin'\nimport type { Behavior, BehaviorContext } from '@murumets-ee/entity'\nimport { z } from 'zod'\nimport {\n buildMenuTreeSchema,\n DEFAULT_MENU_DEPTH,\n MAX_MENU_DEPTH,\n MAX_MENU_TREE_NODES,\n measureMenuTree,\n} from '../menu-item-schema.js'\n\n/** Options for {@link menuTreeValidation}. */\nexport interface MenuTreeValidationOptions {\n /**\n * Resolve the locale codes accepted as `label` / `enabled` keys.\n *\n * Defaults to the `content()` plugin's configured locales, read LAZILY (per\n * write, never at module scope) so the behavior can be constructed before\n * the app boots. Injectable so the behavior is unit-testable without a\n * booted content plugin.\n */\n resolveAllowedLocales?: () => readonly string[]\n}\n\n/** One-issue `ZodError` at `tree`(`.path`) — the 400-mapped failure shape. */\nfunction treeError(message: string, path: Array<string | number> = []): z.ZodError {\n return new z.ZodError([{ code: z.ZodIssueCode.custom, path: ['tree', ...path], message }])\n}\n\n/** Prefix every issue path with `tree` so the client can locate the node. */\nfunction prefixIssues(error: z.ZodError): z.ZodError {\n return new z.ZodError(error.issues.map((issue) => ({ ...issue, path: ['tree', ...issue.path] })))\n}\n\n/** A `maxDepth` value from an (unvalidated, pre-field-validation) payload. */\nfunction readMaxDepth(value: unknown): number | undefined {\n if (typeof value !== 'number' || !Number.isInteger(value)) return undefined\n if (value < 1 || value > MAX_MENU_DEPTH) return undefined\n return value\n}\n\n/**\n * The effective `maxDepth` for this write.\n *\n * Hooks run BEFORE field validation, so a payload's `maxDepth` may be absent\n * or junk; junk falls through to the persisted/default value and is rejected a\n * moment later by the field's own `min`/`max`. On a partial update that\n * touches only `tree`, the persisted value comes from `loadCurrent()` (the\n * eagerly-loaded pre-update snapshot).\n */\nasync function resolveMaxDepth(\n data: Record<string, unknown>,\n ctx: BehaviorContext | undefined,\n isUpdate: boolean,\n): Promise<number> {\n const fromPayload = readMaxDepth(data.maxDepth)\n if (fromPayload !== undefined) return fromPayload\n if (!isUpdate) return DEFAULT_MENU_DEPTH\n\n if (!ctx?.loadCurrent) {\n // Fail loud rather than silently skipping the cross-field check — an\n // unvalidated depth is a correctness hole. AdminClient always wires\n // `loadCurrent` on the update codepath, so this only trips on a\n // mis-wired / direct hook invocation. (Same posture as `pathParent`.)\n throw new Error(\n 'menu: BehaviorContext.loadCurrent is unavailable — cannot validate the tree ' +\n \"against the menu's maxDepth. Writes must go through AdminClient.update.\",\n )\n }\n const current = await ctx.loadCurrent()\n // A vanished/unreadable row can't supply its own bound, so fall back to the\n // DEFAULT (3) — the same value a create would get — not the absolute cap\n // (6). Falling back to the ceiling would make an edge case the single most\n // PERMISSIVE path in the behavior; the safe fallback is the floor. The\n // absolute cap still applies separately, and the update itself fails\n // downstream when the row is genuinely gone.\n return readMaxDepth(current?.maxDepth) ?? DEFAULT_MENU_DEPTH\n}\n\n/**\n * The REVERSE cross-field check: an update that narrows `maxDepth` without\n * touching `tree`.\n *\n * `{\"maxDepth\": 1}` on a menu whose stored tree is 5 levels deep used to skip\n * validation entirely (the payload has no `tree`, so there was nothing to\n * measure) — the write succeeded and the row then PERMANENTLY violated\n * \"tree depth <= maxDepth\" until someone happened to edit the tree again.\n * Both directions of the invariant have to be enforced, so when `maxDepth`\n * moves we measure the PERSISTED tree against the new bound.\n */\nasync function validateStoredTreeAgainstNewMaxDepth(\n data: Record<string, unknown>,\n ctx: BehaviorContext | undefined,\n): Promise<void> {\n // Absent (or junk — the field's own min/max rejects that a moment later)\n // means this write doesn't move the bound, so there's nothing to re-check.\n const maxDepth = readMaxDepth(data.maxDepth)\n if (maxDepth === undefined) return\n\n if (!ctx?.loadCurrent) {\n // Same fail-loud posture as `resolveMaxDepth` — silently skipping the\n // check is precisely the hole this function closes.\n throw new Error(\n 'menu: BehaviorContext.loadCurrent is unavailable — cannot validate the stored tree ' +\n 'against the new maxDepth. Writes must go through AdminClient.update.',\n )\n }\n\n const current = await ctx.loadCurrent()\n // Measured iteratively and on a value already bounded at write time, so this\n // is cheap even for the largest legal tree.\n const { depth } = measureMenuTree(current?.tree)\n if (depth > maxDepth) {\n throw treeError(\n `the stored menu tree is nested ${depth} levels deep, deeper than this menu's ` +\n `new maxDepth (${maxDepth}) — flatten the tree first`,\n )\n }\n}\n\n/**\n * Validate + normalize `data.tree` in place. Returns the payload with `tree`\n * replaced by the PARSED value, so unknown properties a caller invented are\n * stripped before they reach the column.\n */\nasync function validateTree(\n data: Record<string, unknown>,\n ctx: BehaviorContext | undefined,\n isUpdate: boolean,\n resolveAllowedLocales: () => readonly string[],\n): Promise<Record<string, unknown>> {\n const tree = data.tree\n if (tree === undefined) {\n // No tree in the payload — but a `maxDepth`-only update still has to be\n // checked against the tree already in the column.\n if (isUpdate) await validateStoredTreeAgainstNewMaxDepth(data, ctx)\n return data\n }\n if (tree === null || !Array.isArray(tree)) {\n throw treeError('menu tree must be an array of menu items')\n }\n\n // Structural bounds FIRST — this walk is iterative, so it holds even for a\n // payload crafted to blow the recursive parse's stack.\n const { depth, nodeCount } = measureMenuTree(tree)\n if (nodeCount > MAX_MENU_TREE_NODES) {\n throw treeError(`menu tree has too many items (max ${MAX_MENU_TREE_NODES})`)\n }\n if (depth > MAX_MENU_DEPTH) {\n throw treeError(`menu tree is nested too deeply (absolute max ${MAX_MENU_DEPTH} levels)`)\n }\n\n const parsed = buildMenuTreeSchema({ allowedLocales: resolveAllowedLocales() }).safeParse(tree)\n if (!parsed.success) throw prefixIssues(parsed.error)\n\n const maxDepth = await resolveMaxDepth(data, ctx, isUpdate)\n if (depth > maxDepth) {\n throw treeError(`menu tree is nested deeper than this menu's maxDepth (${maxDepth})`)\n }\n\n return { ...data, tree: parsed.data }\n}\n\n/**\n * Recursive Zod validation of `menu.tree` on every create/update.\n *\n * Contributes NO fields, so the field-map type param is the EMPTY map\n * `Record<never, never>` — NOT `Record<string, never>`, which would merge into\n * the entity's field map and collapse every field to `never` (a break that\n * only surfaces through the built `.d.mts`).\n */\nexport function menuTreeValidation(\n options?: MenuTreeValidationOptions,\n): Behavior<Record<never, never>, 'menuTreeValidation'> {\n const resolveAllowedLocales =\n options?.resolveAllowedLocales ?? (() => getContentConfig().locales.map((l) => l.code))\n\n return {\n name: 'menuTreeValidation',\n hooks: {\n beforeCreate: async (data, ctx) => validateTree(data, ctx, false, resolveAllowedLocales),\n beforeUpdate: async (_id, data, ctx) => validateTree(data, ctx, true, resolveAllowedLocales),\n },\n }\n}\n","/**\n * The `menu` entity (plan/routing phase 08 §2, D008/D009).\n *\n * A menu is a normal entity whose item tree is ONE ordered nested JSONB column\n * — the family WordPress migrated to and Statamic uses, and the same storage\n * philosophy as our blocks layouts. Whole-tree edits save atomically in one\n * PATCH, and `publishable()` gives draft-then-publish menu editing for free.\n *\n * Locale variance lives INSIDE the tree (per-item `label` / `enabled` maps),\n * so there is deliberately no `translatable` field and no `menu_translations`\n * table — one structure serves every locale (D009).\n */\n\nimport { auditable, defineEntity, field, publishable } from '@murumets-ee/entity'\nimport { menuEntityTypesValidation } from './behaviors/menu-entity-types-validation.js'\nimport { menuTreeValidation } from './behaviors/menu-tree-validation.js'\nimport { DEFAULT_MENU_DEPTH, MAX_MENU_DEPTH } from './menu-item-schema.js'\n\nexport const Menu = defineEntity({\n name: 'menu',\n // Menus belong to one site (multisite D002); the `handle` unique is per site,\n // so every site can have its own `main` and `footer`.\n site: 'bound',\n admin: {\n label: 'Menus',\n icon: 'menu',\n },\n fields: {\n // Fetch key — 'main', 'footer' (phase 07 §2.8). `from: 'title'` is the\n // admin form's client-side auto-fill source (SlugField watches it); the\n // value itself is author-chosen and stable, so `sluggable()` (which would\n // REGENERATE the handle when the title changes) is deliberately not used.\n // `field.slug()` already sets `unique` + `indexed` — no need to repeat them.\n handle: field.slug({ from: 'title' }),\n title: field.text({ required: true }),\n // 1..6 — the renderer clamps too (phase 07 §2.7).\n maxDepth: field.number({\n default: DEFAULT_MENU_DEPTH,\n min: 1,\n max: MAX_MENU_DEPTH,\n integer: true,\n }),\n // MenuItem[] — shape validated by `menuTreeValidation()`; `refScan` makes\n // every LinkValue in the tree register in `entity_refs` /\n // `external_link_usage` on save, so a menu item pointing at a page shows\n // up in delete-protection warnings and the broken-links dashboard\n // (phase 08 §4) with no menus-side ref code at all.\n tree: field.json({ refScan: true, default: [] }),\n // Which content types may be linked FROM this menu (phase 07 §2.8) — the\n // menu editor's picker and the Meta panel's Menus section both read it.\n // `null` = accepts every type, which is what every row written before this\n // column existed reads back as, so the whitelist is backward-compatible by\n // construction. Shape validated by `menuEntityTypesValidation()`; semantics\n // and the read-side predicate live in `./menu-entity-types.ts`.\n //\n // No `refScan`: the value holds entity NAMES, not `LinkValue`s — there is\n // no row to reference, so a scan would find nothing.\n entityTypes: field.json({ default: null }),\n },\n behaviors: [auditable(), publishable(), menuTreeValidation(), menuEntityTypesValidation()],\n scope: 'global',\n // Advisory metadata (the firewall is deny-by-default + operator grants).\n // Menus are site-wide navigation: a bad edit is visible on EVERY page, and\n // the tree is a structural artifact rather than content — so writes are\n // admin-only, while `view` is public because the frontend reads menus\n // unauthenticated through the content API.\n access: {\n view: 'public',\n create: 'group.admin',\n update: 'group.admin',\n delete: 'group.admin',\n },\n})\n","/**\n * Typed column access for a dynamically-generated entity table.\n *\n * `AdminClient.getTable()` / `QueryClient.getTable()` both return\n * `PgTableWithColumns<any>` (Drizzle cannot type columns that are generated\n * from a runtime entity definition), so reading a column off one directly\n * yields `any` and silently erodes this package's type coverage. Narrowing\n * through this helper pins the ONE column being filtered on — the same idiom\n * `@murumets-ee/content`'s `buildEnumerateDeps` uses.\n *\n * Internal to `@murumets-ee/menus`; not part of any public entry.\n */\n\nimport type { PgColumn, PgTableWithColumns } from 'drizzle-orm/pg-core'\n\n/** Read one named column off a runtime-generated entity table, typed. */\nexport function column<K extends string>(\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle cannot type dynamically-generated column schemas — `PgTableWithColumns<any>` is `getTable()`'s own declared return type (CLAUDE.md's sanctioned case).\n table: PgTableWithColumns<any>,\n name: K,\n): PgColumn {\n return (table as unknown as Record<K, PgColumn>)[name]\n}\n"],"mappings":"8OAkCA,MAAa,EAAiB,EAYjB,EAAsB,IAmCtB,EAAoB,IAmBpB,EAAiB,mBAmIjB,EAAkB,EAAE,mBAAmB,OAAQ,CAC1D,EAAE,OAAO,CACP,KAAM,EAAE,QAAQ,QAAQ,EACxB,OAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,EAA0B,EACpD,GAAI,EAAE,OAAO,CAAC,CAAC,KAAK,EACpB,OAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,GAAqB,CAAC,CAAC,MAAM,CAAc,CAAC,CAAC,SAAS,CAClF,CAAC,EACD,EAAE,OAAO,CACP,KAAM,EAAE,QAAQ,KAAK,EAQrB,IAAK,EACF,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,IAAmB,CAAC,CACxB,UAAW,GAAU,EAAa,CAAK,CAAC,CAAC,CACzC,OAAQ,GAAU,IAAU,GAAI,CAC/B,QACE,6FACJ,CAAC,CACL,CAAC,EACD,EAAE,OAAO,CACP,KAAM,EAAE,QAAQ,OAAO,EACvB,MAAO,EAAE,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,GAAG,CACnC,CAAC,CACH,CAAC,EAaD,SAA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M,EAAM,KAAK,CAAE,QAAS,GAAM,QAAS,CAAC,CAAE,CAAC,EAU/C,YAAa,EAAM,KAAK,CAAE,QAAS,IAAK,CAAC,CAC3C,EACA,UAAW,CAAC,EAAU,EAAG,EAAY,EAAG,EAAmB,EAAG,EAA0B,CAAC,EACzF,MAAO,SAMP,OAAQ,CACN,KAAM,SACN,OAAQ,cACR,OAAQ,cACR,OAAQ,aACV,CACF,CAAC,ECxDD,SAAgB,EAEd,EACA,EACU,CACV,OAAQ,EAAyC,EACnD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e={PluginNav:{menu:`Menus`},Menus:{entity:{menu:`Menu`,menus:`Menus`,handle:`Handle`,title:`Title`,maxDepth:`Maximum depth`,tree:`Items`},itemKind:{link:`Link`,header:`Header`},translatableSource:{menu:`Menus`}}};export{e as default};
|
|
2
|
+
//# sourceMappingURL=en-BcniJZiB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"en-BcniJZiB.mjs","names":[],"sources":["../src/messages/en.json"],"sourcesContent":[""],"mappings":""}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={PluginNav:{menu:`Menüüd`},Menus:{entity:{menu:`Menüü`,menus:`Menüüd`,handle:`Tunnus`,title:`Pealkiri`,maxDepth:`Maksimaalne sügavus`,tree:`Elemendid`},itemKind:{link:`Link`,header:`Pealkiri`}}};export{e as default};
|
|
2
|
-
//# sourceMappingURL=et-
|
|
1
|
+
var e={PluginNav:{menu:`Menüüd`},Menus:{entity:{menu:`Menüü`,menus:`Menüüd`,handle:`Tunnus`,title:`Pealkiri`,maxDepth:`Maksimaalne sügavus`,tree:`Elemendid`},itemKind:{link:`Link`,header:`Pealkiri`},translatableSource:{menu:`Menüüd`}}};export{e as default};
|
|
2
|
+
//# sourceMappingURL=et-BL3ZuuFV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"et-BL3ZuuFV.mjs","names":[],"sources":["../src/messages/et.json"],"sourcesContent":[""],"mappings":""}
|
package/dist/i18n.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
async function e(e){switch(e){case`et`:return(await import(`./et-
|
|
1
|
+
async function e(e){switch(e){case`et`:return(await import(`./et-BL3ZuuFV.mjs`)).default;case`ru`:return(await import(`./ru-D8QNW6XE.mjs`)).default;default:return(await import(`./en-BcniJZiB.mjs`)).default}}export{e as getMenusMessages};
|
|
2
2
|
//# sourceMappingURL=i18n.mjs.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as validateTreeDepth, b as menuAcceptsEntityType, c as MAX_MENU_URL_LENGTH, d as MenuLinkValue, f as MenuSchemaOptions, g as measureMenuTree, h as buildMenuTreeSchema, i as LinkValueSchema, l as MenuItem, m as buildMenuItemSchema, o as MAX_MENU_DEPTH, p as MenuTreeMeasurement, r as DEFAULT_MENU_DEPTH, s as MAX_MENU_TREE_NODES, v as MAX_MENU_ENTITY_TYPE_WHITELIST, x as normalizeMenuEntityTypes, y as MenuEntityTypesSchema } from "./menu-item-schema-
|
|
1
|
+
import { _ as validateTreeDepth, b as menuAcceptsEntityType, c as MAX_MENU_URL_LENGTH, d as MenuLinkValue, f as MenuSchemaOptions, g as measureMenuTree, h as buildMenuTreeSchema, i as LinkValueSchema, l as MenuItem, m as buildMenuItemSchema, o as MAX_MENU_DEPTH, p as MenuTreeMeasurement, r as DEFAULT_MENU_DEPTH, s as MAX_MENU_TREE_NODES, v as MAX_MENU_ENTITY_TYPE_WHITELIST, x as normalizeMenuEntityTypes, y as MenuEntityTypesSchema } from "./menu-item-schema-_Nj03ytp.mjs";
|
|
2
2
|
import { Behavior } from "@murumets-ee/entity";
|
|
3
3
|
|
|
4
4
|
//#region src/behaviors/menu-entity-types-validation.d.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu-entity-types-BnKnKbif.mjs","names":["roots"],"sources":["../src/menu-item-schema.ts","../src/menu-entity-types.ts"],"sourcesContent":["/**\n * `MenuItem` — the menu tree node — and its recursive Zod validation\n * (plan/routing phase 08 §3).\n *\n * A menu's `tree` column is ordered nested JSONB (D008), so the ONLY thing\n * standing between an admin PATCH and the database is this schema: it is the\n * boundary validation required by CLAUDE.md's C5. It enforces\n *\n * - the `kind`-conditional shape (`link` items carry a `LinkValue`, `header`\n * items carry a label map and no link),\n * - locale keys drawn from the app's configured locale set,\n * - `LinkValue`s that mirror `@murumets-ee/blocks`' union exactly, with `url`\n * kinds protocol-gated through the SAME `sanitizeHref` allowlist the link\n * picker uses (no `javascript:` / `data:` / protocol-relative smuggling),\n * - hard structural bounds on tree size + nesting, checked BEFORE the\n * recursive parse so a hostile payload can't turn validation itself into a\n * stack-overflow / CPU amplification vector.\n *\n * This module is deliberately **pure**: no `@murumets-ee/core`, no content\n * plugin lookup, no DB. The allowed-locale set is passed IN, so the schema can\n * be built server-side (the `menuTreeValidation()` behavior) or client-side\n * (PR10's editor, with locales handed down from the server) from the same code.\n * Cross-field depth validation against the entity's sibling `maxDepth` column\n * lives in {@link validateTreeDepth}, which the behavior calls separately.\n */\n\nimport { sanitizeHref } from '@murumets-ee/blocks/links'\nimport { z } from 'zod'\n\n/**\n * Absolute nesting cap for any menu, independent of a menu's own `maxDepth`\n * (phase 07 §2.7 — \"depth is capped per menu (default 3, max 6)\"). Also the\n * bound that keeps the recursive parse from being a DoS vector.\n */\nexport const MAX_MENU_DEPTH = 6\n\n/** `maxDepth`'s default — a 3-level menu (phase 08 §2). */\nexport const DEFAULT_MENU_DEPTH = 3\n\n/**\n * Upper bound on the number of nodes in one menu tree. Navigation menus are\n * hand-curated: a few dozen items is a big one. The cap exists so a single\n * PATCH can't hand the validator (and `extractRefs`' ref walk, and every\n * subsequent render) an unbounded amount of work — CLAUDE.md's\n * \"no unbounded fan-out\" rule applied to a single request payload.\n */\nexport const MAX_MENU_TREE_NODES = 500\n\n/**\n * Max stored length of a `url`-kind link. Pinned to `entity`'s\n * `MAX_EXTERNAL_URL_LENGTH` (the `external_link_usage.url_raw` column width)\n * at COMPILE time via `satisfies` + a type-only import — so a longer URL is\n * rejected at the boundary instead of being silently dropped from the\n * reference graph. Same drift-proofing trick as content's\n * `DEFAULT_LOCALE_SENTINEL`; `import type` has zero runtime cost, so the pure\n * schema module keeps its (client-safe) dependency-free shape.\n */\nexport const MAX_MENU_URL_LENGTH =\n 2048 satisfies typeof import('@murumets-ee/entity/refs')['MAX_EXTERNAL_URL_LENGTH']\n\n/** Max length of an item's stable id (a UUID today; generated client-side). */\nconst MAX_ITEM_ID_LENGTH = 64\n\n/** Max length of a per-locale label string. */\nconst MAX_LABEL_LENGTH = 200\n\n/**\n * Max length of an entity-link fragment/anchor.\n *\n * Exported because this module is the SINGLE OWNER of the anchor bounds: the\n * write-side schema below, the read-side anchor walk\n * (`admin/anchors.ts`) and the editor's manual-entry fallback\n * (`@murumets-ee/menus-ui`'s anchor picker, via the client-safe `./schema`\n * subpath) all validate against exactly these two constants. Two of those three\n * used to carry their own copy; a drift between them would let the picker offer\n * — or the editor accept — a value the write boundary then rejects.\n */\nexport const MAX_ANCHOR_LENGTH = 128\n\n/**\n * Max length of an entity NAME inside an entity link (`page`, `article`, …).\n *\n * Exported for the same single-owner reason as {@link MAX_ANCHOR_LENGTH}: the\n * per-menu `entityTypes` whitelist (`./menu-entity-types.ts`) stores values of\n * exactly this kind, and a second copy of the bound could drift into a\n * whitelist entry the link schema then refuses.\n */\nexport const MAX_ENTITY_NAME_LENGTH = 64\n\n/**\n * Anchors are slugified by the block editor (phase 08 §5) and rendered into an\n * `href` as `#<anchor>`; restricting them to slug characters keeps that\n * interpolation inert.\n *\n * Exported for the same single-owner reason as {@link MAX_ANCHOR_LENGTH}.\n */\nexport const ANCHOR_PATTERN = /^[A-Za-z0-9_-]+$/\n\n/**\n * A menu item's link target — the item-type union phase 07 §2.2 and phase 08 §3\n * define: `entity` (+ optional anchor) | `url` | `email`.\n *\n * **A NARROWED SUBSET of `@murumets-ee/blocks`' `LinkValue`, deliberately.**\n * Blocks additionally carries a `media` kind; menus does NOT, because no phase\n * gives a menu a media-href seam to resolve one with (phase 11 §2 specifies\n * `href` as \"canonical path from `toolkit_paths`; external URLs verbatim;\n * header items null\" and nothing else). Accepting a `media` link would let it\n * validate, persist, and register an `entity_refs` row — arming delete\n * protection for that file — while the renderer had no way to emit it: the item\n * would silently never appear. Rejecting it at the write boundary turns that\n * dead weight into a real 400. Widening later is additive (an arm here plus a\n * `resolveMediaHref` dep on `MenuResolveDeps`) and needs no shape change.\n *\n * Every `MenuLinkValue` IS a valid blocks `LinkValue` (the subset direction, and\n * the one `resolveLinkHref` needs) — pinned at compile time by an assignment in\n * `menu-item-schema.test.ts`, so a drift in blocks' union is a build error\n * rather than a silent divergence.\n *\n * The `anchor?: string | undefined` is forced by the combination of Zod and this\n * repo's `exactOptionalPropertyTypes`: `.optional()` always widens to\n * `T | undefined`, which is NOT assignable to blocks' `anchor?: string` under\n * that flag.\n */\nexport type MenuLinkValue =\n | { kind: 'entity'; entity: string; id: string; anchor?: string | undefined }\n | { kind: 'url'; url: string }\n | { kind: 'email'; email: string }\n\n/**\n * A menu tree node (phase 08 §3 / D009).\n *\n * `label: null` means \"use the LIVE title of the linked entity, per locale\";\n * a map is an explicit per-locale override. `enabled` is per-locale visibility\n * in BOTH directions — absent/`true` shows the item, `false` hides it in that\n * locale — so one tree serves every locale (no `menu_translations` table).\n *\n * Declared as a `type`, NOT an `interface`, on purpose: only type aliases get\n * TypeScript's implicit index signature, and without it `MenuItem[]` is not\n * assignable to the `Record<string, unknown>[]` arm of `AdminClient.create/\n * update`'s json-field value type — every caller storing a typed tree would\n * need a cast.\n */\nexport type MenuItem = {\n /** Stable id — DND identity + anchor for audit diffs. */\n id: string\n /** `header` = a text-only dropdown parent with no link of its own. */\n kind: 'link' | 'header'\n /**\n * Present iff `kind === 'link'`.\n *\n * The explicit `| undefined` is required by the repo's\n * `exactOptionalPropertyTypes` — Zod's `.optional()` emits\n * `LinkValue | undefined`, and without it the schema wouldn't typecheck\n * against this interface.\n */\n link?: MenuLinkValue | undefined\n /** `null` = live entity title per locale; a map = explicit override. */\n label: Record<string, string> | null\n /** Per-locale visibility. Absent/`true` = visible; `false` = hidden. */\n enabled?: Record<string, boolean> | undefined\n newTab?: boolean | undefined\n children: MenuItem[]\n}\n\n/**\n * One menu item's target, as the editor needs to render its row\n * (`@murumets-ee/menus/admin`'s `resolveMenuItemSummaries`).\n *\n * Declared here — not in `admin/summaries.ts` — for the same reason\n * {@link BlockAnchor} is: it is a pure data shape with no server dependency,\n * so the client-safe `./schema` subpath can re-export it without pulling the\n * server-only resolver along. `import type` is erased at compile time either\n * way, but a single canonical home (this leaf module) is simpler to reason\n * about than \"which of two server-only files owns the type\".\n */\nexport interface MenuItemSummary {\n /**\n * The target row's live title, or `null` when the entity declares no\n * display-able field. Unlike the public render path — which DROPS such an\n * item rather than show a raw uuid as navigation — the admin editor still\n * reports the target as present, just unlabelled.\n */\n title: string | null\n /** `false` = the target row is gone (deleted) → a BROKEN item. */\n exists: boolean\n /** `null` when the entity isn't publishable — no draft/published distinction applies. */\n published: boolean | null\n}\n\n/**\n * One addressable block anchor on a document (`@murumets-ee/menus/admin`'s\n * `collectBlockAnchors` / the anchors endpoint). See {@link MenuItemSummary}'s\n * doc for why this pure shape lives here rather than in `admin/anchors.ts`.\n */\nexport interface BlockAnchor {\n /** The stable id rendered as the block element's `id` attribute. */\n anchor: string\n /** Display text — `anchorLabel` when usable, else the anchor value itself. */\n label: string\n}\n\n/** Options for {@link buildMenuItemSchema} / {@link buildMenuTreeSchema}. */\nexport interface MenuSchemaOptions {\n /**\n * Locale codes accepted as keys in `label` / `enabled` maps. Anything else\n * is a validation error — a typo'd locale would produce a label no renderer\n * ever reads (the same failure mode content's `validateLocale` guards).\n */\n allowedLocales: readonly string[]\n}\n\n/**\n * {@link MenuLinkValue} as Zod. Blocks models its own `LinkValue` as a plain TS\n * type + structural guards (zod-free by design), so this is the first Zod\n * encoding of it — narrowed to the three kinds a menu item may carry.\n *\n * There is deliberately NO `media` arm (see {@link MenuLinkValue}): a media\n * link has no href seam at render time, so accepting one would store a\n * permanently invisible item. `z.discriminatedUnion` rejects it with an\n * `Invalid discriminator value. Expected 'entity' | 'url' | 'email'` issue —\n * which names the allowed set without echoing the caller's own value back.\n *\n * `url` kinds run through `sanitizeHref`, the single source of truth for the\n * href protocol allowlist (`http:`/`https:`/`mailto:`/`tel:` + relative\n * paths); it returns `''` for anything it rejects, including\n * protocol-relative `//evil.com` and obfuscated `java\\nscript:`.\n */\nexport const LinkValueSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('entity'),\n entity: z.string().min(1).max(MAX_ENTITY_NAME_LENGTH),\n id: z.string().uuid(),\n anchor: z.string().min(1).max(MAX_ANCHOR_LENGTH).regex(ANCHOR_PATTERN).optional(),\n }),\n z.object({\n kind: z.literal('url'),\n // Transform-then-refine, NOT refine-alone: `sanitizeHref` trims, so\n // validating its output while storing the raw input would let a value\n // that PASSED validation differ from the value that gets STORED (leading\n // /trailing whitespace). Storing the sanitizer's own return value keeps\n // stored == validated. The arrow wrapper is required — `sanitizeHref`'s\n // second parameter is the protocol allowlist, and passing Zod's ctx into\n // it would silently replace the allowlist.\n url: z\n .string()\n .min(1)\n .max(MAX_MENU_URL_LENGTH)\n .transform((value) => sanitizeHref(value))\n .refine((value) => value !== '', {\n message:\n 'link url uses a disallowed protocol (allowed: http, https, mailto, tel, or a relative path)',\n }),\n }),\n z.object({\n kind: z.literal('email'),\n email: z.string().email().max(254),\n }),\n])\n\n/**\n * A `Record<locale, T>` whose keys must all be configured locale codes.\n *\n * The key check is PIPED INTO the record parse rather than refined on top of\n * it, so it runs against the RAW value BEFORE any per-value parsing. That\n * ordering is the whole point: with `z.record(...).superRefine(...)`, zod\n * parses all N values first, so a 1,000,000-key map of wrong-typed values\n * emits 1,000,000 `invalid_type` issues before a width check on top could ever\n * fire (verified empirically against zod 3.25). Piping caps BOTH shapes —\n * unknown keys and bad values — at a single issue.\n */\nfunction localeMap<T extends z.ZodTypeAny>(\n valueSchema: T,\n allowedLocales: readonly string[],\n): z.ZodType<Record<string, z.infer<T>>, z.ZodTypeDef, unknown> {\n const allowed = new Set(allowedLocales)\n return z\n .unknown()\n .superRefine((value, ctx) => {\n // Not a plain object — let the record parse below emit the single\n // \"expected object\" issue rather than duplicating its message here.\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return\n\n const keys = Object.keys(value)\n // Width bound, checked FIRST. A legitimate map holds at most one entry\n // per configured locale, so a wider map is malformed by construction and\n // gets ONE issue for the whole map. Without this, a single node carrying\n // e.g. 1,000,000 keys sails past the tree pre-scan (which bounds node\n // COUNT and DEPTH, never map WIDTH) and turns validation itself into the\n // amplification vector it exists to prevent: a multi-hundred-MB issue\n // array plus an oversized audit-log write, from one request.\n // CLAUDE.md's \"no unbounded fan-out\" applied to a single payload.\n if (keys.length > allowed.size) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `too many locale keys — configured locales are: ${[...allowed].join(', ')}`,\n })\n return\n }\n\n // Past the width bound this loop is bounded by the CONFIGURED locale\n // count, never by the payload.\n for (const key of keys) {\n if (!allowed.has(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [key],\n // Names the allowed set (server-side data), never echoes the\n // caller-supplied key into the message — see the api-handler's\n // \"refine()/custom messages must not echo user input\" contract.\n message: `unknown locale key — configured locales are: ${[...allowed].join(', ')}`,\n })\n }\n }\n })\n .pipe(z.record(z.string(), valueSchema))\n}\n\n/**\n * The recursive per-node schema. Input is `unknown` (this parses untrusted\n * JSONB), output is a fully-narrowed {@link MenuItem}. Unknown properties are\n * STRIPPED by Zod's default object behavior, so writing the parse result back\n * onto the payload also sanitizes it — nothing a caller invents gets stored.\n */\nexport function buildMenuItemSchema(\n options: MenuSchemaOptions,\n): z.ZodType<MenuItem, z.ZodTypeDef, unknown> {\n const labelMap = localeMap(z.string().max(MAX_LABEL_LENGTH), options.allowedLocales)\n const enabledMap = localeMap(z.boolean(), options.allowedLocales)\n\n const schema: z.ZodType<MenuItem, z.ZodTypeDef, unknown> = z.lazy(() =>\n z\n .object({\n id: z.string().min(1).max(MAX_ITEM_ID_LENGTH),\n kind: z.enum(['link', 'header']),\n link: LinkValueSchema.optional(),\n label: labelMap.nullable().default(null),\n enabled: enabledMap.optional(),\n newTab: z.boolean().optional(),\n children: z.array(schema).default([]),\n })\n .superRefine((node, ctx) => {\n if (node.kind === 'link') {\n if (node.link === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['link'],\n message: 'a link item requires a link target',\n })\n }\n return\n }\n // header\n if (node.link !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['link'],\n message: 'a header item must not carry a link target',\n })\n }\n // A header has no entity to borrow a live title from, so its label\n // map is required (phase 08 §3) — otherwise it renders as nothing.\n if (node.label === null || Object.keys(node.label).length === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['label'],\n message: 'a header item requires a label for at least one locale',\n })\n }\n }),\n )\n\n return schema\n}\n\n/** The whole tree — an array of {@link buildMenuItemSchema} nodes. */\nexport function buildMenuTreeSchema(\n options: MenuSchemaOptions,\n): z.ZodType<MenuItem[], z.ZodTypeDef, unknown> {\n return z.array(buildMenuItemSchema(options))\n}\n\n/** Result of {@link measureMenuTree}. */\nexport interface MenuTreeMeasurement {\n /** Deepest nesting level; `0` for an empty tree, `1` for flat items. */\n depth: number\n /** Total node count across every level. */\n nodeCount: number\n}\n\n/**\n * Measure a (possibly untrusted) tree's depth + node count **iteratively**, so\n * measuring can never blow the stack the way a recursive walk over a hostile\n * payload would. Stops early once either hard bound is exceeded and reports\n * the over-limit value — the caller turns that into a validation error.\n *\n * Accepts `unknown` on purpose: this runs BEFORE the Zod parse (bounding the\n * work that parse will do), so it can't assume a well-formed shape.\n */\nexport function measureMenuTree(tree: unknown): MenuTreeMeasurement {\n if (!Array.isArray(tree)) return { depth: 0, nodeCount: 0 }\n\n let maxDepth = 0\n let nodeCount = 0\n // `Array.isArray` narrows an `unknown` to `any[]`; re-binding through a\n // `readonly unknown[]` annotation keeps every element typed as `unknown`\n // instead of silently leaking `any` into the walk.\n const roots: readonly unknown[] = tree\n const stack: Array<{ node: unknown; depth: number }> = roots.map((node) => ({ node, depth: 1 }))\n\n while (stack.length > 0) {\n const current = stack.pop()\n if (current === undefined) break\n const { node, depth } = current\n if (node === null || typeof node !== 'object' || Array.isArray(node)) continue\n\n nodeCount++\n if (depth > maxDepth) maxDepth = depth\n // Early abort: past either bound the exact totals no longer matter, only\n // that they're over — and continuing would be the amplification we're\n // guarding against.\n if (nodeCount > MAX_MENU_TREE_NODES || maxDepth > MAX_MENU_DEPTH) {\n return { depth: maxDepth, nodeCount }\n }\n\n const children = (node as { children?: unknown }).children\n if (Array.isArray(children)) {\n const items: readonly unknown[] = children\n for (const child of items) stack.push({ node: child, depth: depth + 1 })\n }\n }\n\n return { depth: maxDepth, nodeCount }\n}\n\n/**\n * Cross-field check: does `tree` nest no deeper than the menu's own\n * `maxDepth`? Lives outside the node schema because a per-node Zod refinement\n * has no visibility of the sibling `maxDepth` COLUMN — the behavior calls this\n * after the recursive parse.\n */\nexport function validateTreeDepth(tree: unknown, maxDepth: number): boolean {\n return measureMenuTree(tree).depth <= maxDepth\n}\n","/**\n * The per-menu `entityTypes` whitelist — \"which content types may be linked\n * from this menu\" (plan/routing phase 07 §2.8, 09 §3, 10 §4).\n *\n * Drupal's per-content-type menu offering, minus the config-entity ceremony: a\n * `page` doesn't declare \"I belong in menus\", each MENU declares which types it\n * accepts. Two surfaces consume it — the menu editor's \"Add link\" picker (which\n * content types its Content tab offers) and the Meta panel's Menus section\n * (which menus an entity's edit screen offers to join).\n *\n * ## Semantics — `null` is \"everything\", and it is the ONLY unrestricted shape\n *\n * `null` (or an absent column) = the menu accepts every entity type. That is the\n * default, and it is what every menu row written before this column existed\n * reads back as, so the whitelist is backward-compatible by construction.\n *\n * An EMPTY array means the same thing, and {@link MenuEntityTypesSchema}\n * normalises it to `null` on the way in — the editor's \"nothing selected\" state\n * naturally produces `[]`, and letting both spellings persist would mean every\n * reader had to remember to check for two. Readers still tolerate a stored `[]`\n * (a hand-edited row, an older dump) via {@link menuAcceptsEntityType}.\n *\n * A menu that accepts NOTHING is deliberately unrepresentable: it could only\n * ever be a mistake, and \"empty selection\" is far more likely to mean \"I haven't\n * narrowed this yet\" than \"refuse everything\".\n *\n * ## Not a security boundary\n *\n * This is an authoring affordance. It decides what a picker OFFERS; it does not\n * decide what a caller may write — `menu:update` on the entity PATCH does, and\n * `menuTreeValidation()` re-checks the tree's shape regardless of the whitelist.\n * So the read path fails OPEN (a malformed column means \"no restriction\"): a\n * junk value must not hide every menu from the admin who needs to fix it. The\n * WRITE path fails closed, as every boundary does.\n *\n * @module\n */\n\nimport { z } from 'zod'\nimport { MAX_ENTITY_NAME_LENGTH } from './menu-item-schema.js'\n\n/**\n * Upper bound on how many entity types one menu's whitelist may name.\n *\n * A real app registers a few dozen entities, so this is a malformed-payload\n * guard rather than a product limit — it keeps a hostile PATCH from parking an\n * unbounded array in the column (and, through it, in every editor's RSC\n * payload).\n *\n * **Not** `MAX_MENU_ENTITY_TYPES` (`./get-menu.ts`, 16). That one bounds RENDER\n * fan-out — how many distinct types one menu render may issue batched lookups\n * for — and applies to the types actually present in the stored tree. This one\n * bounds the stored AUTHORING whitelist, which costs no I/O at all.\n */\nexport const MAX_MENU_ENTITY_TYPE_WHITELIST = 64\n\n/** One entity name in the whitelist — same bound `link.entity` carries. */\nconst EntityTypeName = z.string().min(1).max(MAX_ENTITY_NAME_LENGTH)\n\n/**\n * The write-boundary schema for `menu.entityTypes`.\n *\n * Strict where {@link normalizeMenuEntityTypes} is tolerant: a junk entry is a\n * 400, not a silent drop, because silently discarding half an admin's selection\n * and reporting success is worse than refusing the write. Duplicates ARE folded\n * (an idempotent selection is not an error), and `[]` becomes `null` so the\n * column only ever holds one representation of \"unrestricted\".\n */\nexport const MenuEntityTypesSchema: z.ZodType<string[] | null, z.ZodTypeDef, unknown> = z\n .array(EntityTypeName)\n // DELIBERATE ORDER — `.max()` runs on the RAW array, BEFORE the dedup in the\n // transform below, so 65 copies of `'page'` is a 400 even though it would\n // store one entry. The bound is on the PAYLOAD, not on the result: deduping\n // first would mean accepting an unbounded array to prove it was small.\n .max(MAX_MENU_ENTITY_TYPE_WHITELIST)\n .nullable()\n .transform((value) => {\n if (value === null) return null\n const deduped = [...new Set(value)]\n return deduped.length === 0 ? null : deduped\n })\n\n/**\n * Narrow a raw `entityTypes` column value (untrusted shape) to a usable\n * whitelist, or `null` for \"no restriction\".\n *\n * The read-side counterpart of {@link MenuEntityTypesSchema}, and tolerant for\n * the same reason `normalizeMenuTree` is: rows written before this column\n * existed, hand edits and restored dumps all reach readers, and a render must\n * degrade rather than throw. Anything unusable — a non-array, a non-string\n * entry, a whitelist that reduces to nothing — reads as `null`.\n */\nexport function normalizeMenuEntityTypes(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n // `Array.isArray` narrows `unknown` to `any[]`; re-binding through a\n // `readonly unknown[]` annotation keeps every element typed as `unknown`.\n const raw: readonly unknown[] = value\n\n const out: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string' || entry.length === 0) continue\n if (entry.length > MAX_ENTITY_NAME_LENGTH) continue\n if (seen.has(entry)) continue\n seen.add(entry)\n out.push(entry)\n if (out.length === MAX_MENU_ENTITY_TYPE_WHITELIST) break\n }\n return out.length === 0 ? null : out\n}\n\n/**\n * Does this menu accept links to `entityType`?\n *\n * Takes the RAW column value so callers holding a `field.json()`-typed row can\n * ask directly, without narrowing first. Exact string match — entity names are\n * lowercase identifiers, and a case-insensitive or prefix match would silently\n * widen a whitelist the admin wrote precisely.\n *\n * Fails OPEN (see the module header): absent, empty and malformed all mean \"no\n * restriction\".\n */\nexport function menuAcceptsEntityType(value: unknown, entityType: string): boolean {\n const whitelist = normalizeMenuE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AO,EAAQ,SAAW,EAAI,KAAO,CACvC,CAAC,EAYH,SAAgB,EAAyB,EAAiC,CACxE,GAAI,CAAC,MAAM,QAAQ,CAAK,EAAG,OAAO,KAGlC,IAAM,EAA0B,EAE1B,EAAgB,CAAC,EACjB,EAAO,IAAI,IACjB,IAAK,IAAM,KAAS,EACd,YAAO,GAAU,UAAY,EAAM,SAAW,IAC9C,IAAM,OAAA,KACN,GAAK,IAAI,CAAK,IAClB,EAAK,IAAI,CAAK,EACd,EAAI,KAAK,CAAK,EACV,EAAI,SAAA,IAA2C,MAErD,OAAO,EAAI,SAAW,EAAI,KAAO,CACnC,CAaA,SAAgB,EAAsB,EAAgB,EAA6B,CACjF,IAAM,EAAY,EAAyB,CAAK,EAChD,OAAO,IAAc,MAAQ,EAAU,SAAS,CAAU,CAC5D"}
|
|
1
|
+
{"version":3,"file":"menu-entity-types-BnKnKbif.mjs","names":["roots"],"sources":["../src/menu-item-schema.ts","../src/menu-entity-types.ts"],"sourcesContent":["/**\n * `MenuItem` — the menu tree node — and its recursive Zod validation\n * (plan/routing phase 08 §3).\n *\n * A menu's `tree` column is ordered nested JSONB (D008), so the ONLY thing\n * standing between an admin PATCH and the database is this schema: it is the\n * boundary validation required by CLAUDE.md's C5. It enforces\n *\n * - the `kind`-conditional shape (`link` items carry a `LinkValue`, `header`\n * items carry a label map and no link),\n * - locale keys drawn from the app's configured locale set,\n * - `LinkValue`s that mirror `@murumets-ee/blocks`' union exactly, with `url`\n * kinds protocol-gated through the SAME `sanitizeHref` allowlist the link\n * picker uses (no `javascript:` / `data:` / protocol-relative smuggling),\n * - hard structural bounds on tree size + nesting, checked BEFORE the\n * recursive parse so a hostile payload can't turn validation itself into a\n * stack-overflow / CPU amplification vector.\n *\n * This module is deliberately **pure**: no `@murumets-ee/core`, no content\n * plugin lookup, no DB. The allowed-locale set is passed IN, so the schema can\n * be built server-side (the `menuTreeValidation()` behavior) or client-side\n * (PR10's editor, with locales handed down from the server) from the same code.\n * Cross-field depth validation against the entity's sibling `maxDepth` column\n * lives in {@link validateTreeDepth}, which the behavior calls separately.\n */\n\nimport { sanitizeHref } from '@murumets-ee/blocks/links'\nimport { z } from 'zod'\n\n/**\n * Absolute nesting cap for any menu, independent of a menu's own `maxDepth`\n * (phase 07 §2.7 — \"depth is capped per menu (default 3, max 6)\"). Also the\n * bound that keeps the recursive parse from being a DoS vector.\n */\nexport const MAX_MENU_DEPTH = 6\n\n/** `maxDepth`'s default — a 3-level menu (phase 08 §2). */\nexport const DEFAULT_MENU_DEPTH = 3\n\n/**\n * Upper bound on the number of nodes in one menu tree. Navigation menus are\n * hand-curated: a few dozen items is a big one. The cap exists so a single\n * PATCH can't hand the validator (and `extractRefs`' ref walk, and every\n * subsequent render) an unbounded amount of work — CLAUDE.md's\n * \"no unbounded fan-out\" rule applied to a single request payload.\n */\nexport const MAX_MENU_TREE_NODES = 500\n\n/**\n * Max stored length of a `url`-kind link. Pinned to `entity`'s\n * `MAX_EXTERNAL_URL_LENGTH` (the `external_link_usage.url_raw` column width)\n * at COMPILE time via `satisfies` + a type-only import — so a longer URL is\n * rejected at the boundary instead of being silently dropped from the\n * reference graph. Same drift-proofing trick as content's\n * `DEFAULT_LOCALE_SENTINEL`; `import type` has zero runtime cost, so the pure\n * schema module keeps its (client-safe) dependency-free shape.\n */\nexport const MAX_MENU_URL_LENGTH =\n 2048 satisfies typeof import('@murumets-ee/entity/refs')['MAX_EXTERNAL_URL_LENGTH']\n\n/** Max length of an item's stable id (a UUID today; generated client-side). */\nconst MAX_ITEM_ID_LENGTH = 64\n\n/**\n * Max length of a per-locale label string. Exported for the one other writer of\n * a label — the translatable source (`./translatable-source.ts`) — which tells\n * a translator the bound up front and refuses an over-long answer by item.\n */\nexport const MAX_LABEL_LENGTH = 200\n\n/**\n * Max length of an entity-link fragment/anchor.\n *\n * Exported because this module is the SINGLE OWNER of the anchor bounds: the\n * write-side schema below, the read-side anchor walk\n * (`admin/anchors.ts`) and the editor's manual-entry fallback\n * (`@murumets-ee/menus-ui`'s anchor picker, via the client-safe `./schema`\n * subpath) all validate against exactly these two constants. Two of those three\n * used to carry their own copy; a drift between them would let the picker offer\n * — or the editor accept — a value the write boundary then rejects.\n */\nexport const MAX_ANCHOR_LENGTH = 128\n\n/**\n * Max length of an entity NAME inside an entity link (`page`, `article`, …).\n *\n * Exported for the same single-owner reason as {@link MAX_ANCHOR_LENGTH}: the\n * per-menu `entityTypes` whitelist (`./menu-entity-types.ts`) stores values of\n * exactly this kind, and a second copy of the bound could drift into a\n * whitelist entry the link schema then refuses.\n */\nexport const MAX_ENTITY_NAME_LENGTH = 64\n\n/**\n * Anchors are slugified by the block editor (phase 08 §5) and rendered into an\n * `href` as `#<anchor>`; restricting them to slug characters keeps that\n * interpolation inert.\n *\n * Exported for the same single-owner reason as {@link MAX_ANCHOR_LENGTH}.\n */\nexport const ANCHOR_PATTERN = /^[A-Za-z0-9_-]+$/\n\n/**\n * A menu item's link target — the item-type union phase 07 §2.2 and phase 08 §3\n * define: `entity` (+ optional anchor) | `url` | `email`.\n *\n * **A NARROWED SUBSET of `@murumets-ee/blocks`' `LinkValue`, deliberately.**\n * Blocks additionally carries a `media` kind; menus does NOT, because no phase\n * gives a menu a media-href seam to resolve one with (phase 11 §2 specifies\n * `href` as \"canonical path from `toolkit_paths`; external URLs verbatim;\n * header items null\" and nothing else). Accepting a `media` link would let it\n * validate, persist, and register an `entity_refs` row — arming delete\n * protection for that file — while the renderer had no way to emit it: the item\n * would silently never appear. Rejecting it at the write boundary turns that\n * dead weight into a real 400. Widening later is additive (an arm here plus a\n * `resolveMediaHref` dep on `MenuResolveDeps`) and needs no shape change.\n *\n * Every `MenuLinkValue` IS a valid blocks `LinkValue` (the subset direction, and\n * the one `resolveLinkHref` needs) — pinned at compile time by an assignment in\n * `menu-item-schema.test.ts`, so a drift in blocks' union is a build error\n * rather than a silent divergence.\n *\n * The `anchor?: string | undefined` is forced by the combination of Zod and this\n * repo's `exactOptionalPropertyTypes`: `.optional()` always widens to\n * `T | undefined`, which is NOT assignable to blocks' `anchor?: string` under\n * that flag.\n */\nexport type MenuLinkValue =\n | { kind: 'entity'; entity: string; id: string; anchor?: string | undefined }\n | { kind: 'url'; url: string }\n | { kind: 'email'; email: string }\n\n/**\n * A menu tree node (phase 08 §3 / D009).\n *\n * `label: null` means \"use the LIVE title of the linked entity, per locale\";\n * a map is an explicit per-locale override. `enabled` is per-locale visibility\n * in BOTH directions — absent/`true` shows the item, `false` hides it in that\n * locale — so one tree serves every locale (no `menu_translations` table).\n *\n * Declared as a `type`, NOT an `interface`, on purpose: only type aliases get\n * TypeScript's implicit index signature, and without it `MenuItem[]` is not\n * assignable to the `Record<string, unknown>[]` arm of `AdminClient.create/\n * update`'s json-field value type — every caller storing a typed tree would\n * need a cast.\n */\nexport type MenuItem = {\n /** Stable id — DND identity + anchor for audit diffs. */\n id: string\n /** `header` = a text-only dropdown parent with no link of its own. */\n kind: 'link' | 'header'\n /**\n * Present iff `kind === 'link'`.\n *\n * The explicit `| undefined` is required by the repo's\n * `exactOptionalPropertyTypes` — Zod's `.optional()` emits\n * `LinkValue | undefined`, and without it the schema wouldn't typecheck\n * against this interface.\n */\n link?: MenuLinkValue | undefined\n /** `null` = live entity title per locale; a map = explicit override. */\n label: Record<string, string> | null\n /** Per-locale visibility. Absent/`true` = visible; `false` = hidden. */\n enabled?: Record<string, boolean> | undefined\n newTab?: boolean | undefined\n children: MenuItem[]\n}\n\n/**\n * One menu item's target, as the editor needs to render its row\n * (`@murumets-ee/menus/admin`'s `resolveMenuItemSummaries`).\n *\n * Declared here — not in `admin/summaries.ts` — for the same reason\n * {@link BlockAnchor} is: it is a pure data shape with no server dependency,\n * so the client-safe `./schema` subpath can re-export it without pulling the\n * server-only resolver along. `import type` is erased at compile time either\n * way, but a single canonical home (this leaf module) is simpler to reason\n * about than \"which of two server-only files owns the type\".\n */\nexport interface MenuItemSummary {\n /**\n * The target row's live title, or `null` when the entity declares no\n * display-able field. Unlike the public render path — which DROPS such an\n * item rather than show a raw uuid as navigation — the admin editor still\n * reports the target as present, just unlabelled.\n */\n title: string | null\n /** `false` = the target row is gone (deleted) → a BROKEN item. */\n exists: boolean\n /** `null` when the entity isn't publishable — no draft/published distinction applies. */\n published: boolean | null\n}\n\n/**\n * One addressable block anchor on a document (`@murumets-ee/menus/admin`'s\n * `collectBlockAnchors` / the anchors endpoint). See {@link MenuItemSummary}'s\n * doc for why this pure shape lives here rather than in `admin/anchors.ts`.\n */\nexport interface BlockAnchor {\n /** The stable id rendered as the block element's `id` attribute. */\n anchor: string\n /** Display text — `anchorLabel` when usable, else the anchor value itself. */\n label: string\n}\n\n/** Options for {@link buildMenuItemSchema} / {@link buildMenuTreeSchema}. */\nexport interface MenuSchemaOptions {\n /**\n * Locale codes accepted as keys in `label` / `enabled` maps. Anything else\n * is a validation error — a typo'd locale would produce a label no renderer\n * ever reads (the same failure mode content's `validateLocale` guards).\n */\n allowedLocales: readonly string[]\n}\n\n/**\n * {@link MenuLinkValue} as Zod. Blocks models its own `LinkValue` as a plain TS\n * type + structural guards (zod-free by design), so this is the first Zod\n * encoding of it — narrowed to the three kinds a menu item may carry.\n *\n * There is deliberately NO `media` arm (see {@link MenuLinkValue}): a media\n * link has no href seam at render time, so accepting one would store a\n * permanently invisible item. `z.discriminatedUnion` rejects it with an\n * `Invalid discriminator value. Expected 'entity' | 'url' | 'email'` issue —\n * which names the allowed set without echoing the caller's own value back.\n *\n * `url` kinds run through `sanitizeHref`, the single source of truth for the\n * href protocol allowlist (`http:`/`https:`/`mailto:`/`tel:` + relative\n * paths); it returns `''` for anything it rejects, including\n * protocol-relative `//evil.com` and obfuscated `java\\nscript:`.\n */\nexport const LinkValueSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('entity'),\n entity: z.string().min(1).max(MAX_ENTITY_NAME_LENGTH),\n id: z.string().uuid(),\n anchor: z.string().min(1).max(MAX_ANCHOR_LENGTH).regex(ANCHOR_PATTERN).optional(),\n }),\n z.object({\n kind: z.literal('url'),\n // Transform-then-refine, NOT refine-alone: `sanitizeHref` trims, so\n // validating its output while storing the raw input would let a value\n // that PASSED validation differ from the value that gets STORED (leading\n // /trailing whitespace). Storing the sanitizer's own return value keeps\n // stored == validated. The arrow wrapper is required — `sanitizeHref`'s\n // second parameter is the protocol allowlist, and passing Zod's ctx into\n // it would silently replace the allowlist.\n url: z\n .string()\n .min(1)\n .max(MAX_MENU_URL_LENGTH)\n .transform((value) => sanitizeHref(value))\n .refine((value) => value !== '', {\n message:\n 'link url uses a disallowed protocol (allowed: http, https, mailto, tel, or a relative path)',\n }),\n }),\n z.object({\n kind: z.literal('email'),\n email: z.string().email().max(254),\n }),\n])\n\n/**\n * A `Record<locale, T>` whose keys must all be configured locale codes.\n *\n * The key check is PIPED INTO the record parse rather than refined on top of\n * it, so it runs against the RAW value BEFORE any per-value parsing. That\n * ordering is the whole point: with `z.record(...).superRefine(...)`, zod\n * parses all N values first, so a 1,000,000-key map of wrong-typed values\n * emits 1,000,000 `invalid_type` issues before a width check on top could ever\n * fire (verified empirically against zod 3.25). Piping caps BOTH shapes —\n * unknown keys and bad values — at a single issue.\n */\nfunction localeMap<T extends z.ZodTypeAny>(\n valueSchema: T,\n allowedLocales: readonly string[],\n): z.ZodType<Record<string, z.infer<T>>, z.ZodTypeDef, unknown> {\n const allowed = new Set(allowedLocales)\n return z\n .unknown()\n .superRefine((value, ctx) => {\n // Not a plain object — let the record parse below emit the single\n // \"expected object\" issue rather than duplicating its message here.\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return\n\n const keys = Object.keys(value)\n // Width bound, checked FIRST. A legitimate map holds at most one entry\n // per configured locale, so a wider map is malformed by construction and\n // gets ONE issue for the whole map. Without this, a single node carrying\n // e.g. 1,000,000 keys sails past the tree pre-scan (which bounds node\n // COUNT and DEPTH, never map WIDTH) and turns validation itself into the\n // amplification vector it exists to prevent: a multi-hundred-MB issue\n // array plus an oversized audit-log write, from one request.\n // CLAUDE.md's \"no unbounded fan-out\" applied to a single payload.\n if (keys.length > allowed.size) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `too many locale keys — configured locales are: ${[...allowed].join(', ')}`,\n })\n return\n }\n\n // Past the width bound this loop is bounded by the CONFIGURED locale\n // count, never by the payload.\n for (const key of keys) {\n if (!allowed.has(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [key],\n // Names the allowed set (server-side data), never echoes the\n // caller-supplied key into the message — see the api-handler's\n // \"refine()/custom messages must not echo user input\" contract.\n message: `unknown locale key — configured locales are: ${[...allowed].join(', ')}`,\n })\n }\n }\n })\n .pipe(z.record(z.string(), valueSchema))\n}\n\n/**\n * The recursive per-node schema. Input is `unknown` (this parses untrusted\n * JSONB), output is a fully-narrowed {@link MenuItem}. Unknown properties are\n * STRIPPED by Zod's default object behavior, so writing the parse result back\n * onto the payload also sanitizes it — nothing a caller invents gets stored.\n */\nexport function buildMenuItemSchema(\n options: MenuSchemaOptions,\n): z.ZodType<MenuItem, z.ZodTypeDef, unknown> {\n const labelMap = localeMap(z.string().max(MAX_LABEL_LENGTH), options.allowedLocales)\n const enabledMap = localeMap(z.boolean(), options.allowedLocales)\n\n const schema: z.ZodType<MenuItem, z.ZodTypeDef, unknown> = z.lazy(() =>\n z\n .object({\n id: z.string().min(1).max(MAX_ITEM_ID_LENGTH),\n kind: z.enum(['link', 'header']),\n link: LinkValueSchema.optional(),\n label: labelMap.nullable().default(null),\n enabled: enabledMap.optional(),\n newTab: z.boolean().optional(),\n children: z.array(schema).default([]),\n })\n .superRefine((node, ctx) => {\n if (node.kind === 'link') {\n if (node.link === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['link'],\n message: 'a link item requires a link target',\n })\n }\n return\n }\n // header\n if (node.link !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['link'],\n message: 'a header item must not carry a link target',\n })\n }\n // A header has no entity to borrow a live title from, so its label\n // map is required (phase 08 §3) — otherwise it renders as nothing.\n if (node.label === null || Object.keys(node.label).length === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['label'],\n message: 'a header item requires a label for at least one locale',\n })\n }\n }),\n )\n\n return schema\n}\n\n/** The whole tree — an array of {@link buildMenuItemSchema} nodes. */\nexport function buildMenuTreeSchema(\n options: MenuSchemaOptions,\n): z.ZodType<MenuItem[], z.ZodTypeDef, unknown> {\n return z.array(buildMenuItemSchema(options))\n}\n\n/** Result of {@link measureMenuTree}. */\nexport interface MenuTreeMeasurement {\n /** Deepest nesting level; `0` for an empty tree, `1` for flat items. */\n depth: number\n /** Total node count across every level. */\n nodeCount: number\n}\n\n/**\n * Measure a (possibly untrusted) tree's depth + node count **iteratively**, so\n * measuring can never blow the stack the way a recursive walk over a hostile\n * payload would. Stops early once either hard bound is exceeded and reports\n * the over-limit value — the caller turns that into a validation error.\n *\n * Accepts `unknown` on purpose: this runs BEFORE the Zod parse (bounding the\n * work that parse will do), so it can't assume a well-formed shape.\n */\nexport function measureMenuTree(tree: unknown): MenuTreeMeasurement {\n if (!Array.isArray(tree)) return { depth: 0, nodeCount: 0 }\n\n let maxDepth = 0\n let nodeCount = 0\n // `Array.isArray` narrows an `unknown` to `any[]`; re-binding through a\n // `readonly unknown[]` annotation keeps every element typed as `unknown`\n // instead of silently leaking `any` into the walk.\n const roots: readonly unknown[] = tree\n const stack: Array<{ node: unknown; depth: number }> = roots.map((node) => ({ node, depth: 1 }))\n\n while (stack.length > 0) {\n const current = stack.pop()\n if (current === undefined) break\n const { node, depth } = current\n if (node === null || typeof node !== 'object' || Array.isArray(node)) continue\n\n nodeCount++\n if (depth > maxDepth) maxDepth = depth\n // Early abort: past either bound the exact totals no longer matter, only\n // that they're over — and continuing would be the amplification we're\n // guarding against.\n if (nodeCount > MAX_MENU_TREE_NODES || maxDepth > MAX_MENU_DEPTH) {\n return { depth: maxDepth, nodeCount }\n }\n\n const children = (node as { children?: unknown }).children\n if (Array.isArray(children)) {\n const items: readonly unknown[] = children\n for (const child of items) stack.push({ node: child, depth: depth + 1 })\n }\n }\n\n return { depth: maxDepth, nodeCount }\n}\n\n/**\n * Cross-field check: does `tree` nest no deeper than the menu's own\n * `maxDepth`? Lives outside the node schema because a per-node Zod refinement\n * has no visibility of the sibling `maxDepth` COLUMN — the behavior calls this\n * after the recursive parse.\n */\nexport function validateTreeDepth(tree: unknown, maxDepth: number): boolean {\n return measureMenuTree(tree).depth <= maxDepth\n}\n","/**\n * The per-menu `entityTypes` whitelist — \"which content types may be linked\n * from this menu\" (plan/routing phase 07 §2.8, 09 §3, 10 §4).\n *\n * Drupal's per-content-type menu offering, minus the config-entity ceremony: a\n * `page` doesn't declare \"I belong in menus\", each MENU declares which types it\n * accepts. Two surfaces consume it — the menu editor's \"Add link\" picker (which\n * content types its Content tab offers) and the Meta panel's Menus section\n * (which menus an entity's edit screen offers to join).\n *\n * ## Semantics — `null` is \"everything\", and it is the ONLY unrestricted shape\n *\n * `null` (or an absent column) = the menu accepts every entity type. That is the\n * default, and it is what every menu row written before this column existed\n * reads back as, so the whitelist is backward-compatible by construction.\n *\n * An EMPTY array means the same thing, and {@link MenuEntityTypesSchema}\n * normalises it to `null` on the way in — the editor's \"nothing selected\" state\n * naturally produces `[]`, and letting both spellings persist would mean every\n * reader had to remember to check for two. Readers still tolerate a stored `[]`\n * (a hand-edited row, an older dump) via {@link menuAcceptsEntityType}.\n *\n * A menu that accepts NOTHING is deliberately unrepresentable: it could only\n * ever be a mistake, and \"empty selection\" is far more likely to mean \"I haven't\n * narrowed this yet\" than \"refuse everything\".\n *\n * ## Not a security boundary\n *\n * This is an authoring affordance. It decides what a picker OFFERS; it does not\n * decide what a caller may write — `menu:update` on the entity PATCH does, and\n * `menuTreeValidation()` re-checks the tree's shape regardless of the whitelist.\n * So the read path fails OPEN (a malformed column means \"no restriction\"): a\n * junk value must not hide every menu from the admin who needs to fix it. The\n * WRITE path fails closed, as every boundary does.\n *\n * @module\n */\n\nimport { z } from 'zod'\nimport { MAX_ENTITY_NAME_LENGTH } from './menu-item-schema.js'\n\n/**\n * Upper bound on how many entity types one menu's whitelist may name.\n *\n * A real app registers a few dozen entities, so this is a malformed-payload\n * guard rather than a product limit — it keeps a hostile PATCH from parking an\n * unbounded array in the column (and, through it, in every editor's RSC\n * payload).\n *\n * **Not** `MAX_MENU_ENTITY_TYPES` (`./get-menu.ts`, 16). That one bounds RENDER\n * fan-out — how many distinct types one menu render may issue batched lookups\n * for — and applies to the types actually present in the stored tree. This one\n * bounds the stored AUTHORING whitelist, which costs no I/O at all.\n */\nexport const MAX_MENU_ENTITY_TYPE_WHITELIST = 64\n\n/** One entity name in the whitelist — same bound `link.entity` carries. */\nconst EntityTypeName = z.string().min(1).max(MAX_ENTITY_NAME_LENGTH)\n\n/**\n * The write-boundary schema for `menu.entityTypes`.\n *\n * Strict where {@link normalizeMenuEntityTypes} is tolerant: a junk entry is a\n * 400, not a silent drop, because silently discarding half an admin's selection\n * and reporting success is worse than refusing the write. Duplicates ARE folded\n * (an idempotent selection is not an error), and `[]` becomes `null` so the\n * column only ever holds one representation of \"unrestricted\".\n */\nexport const MenuEntityTypesSchema: z.ZodType<string[] | null, z.ZodTypeDef, unknown> = z\n .array(EntityTypeName)\n // DELIBERATE ORDER — `.max()` runs on the RAW array, BEFORE the dedup in the\n // transform below, so 65 copies of `'page'` is a 400 even though it would\n // store one entry. The bound is on the PAYLOAD, not on the result: deduping\n // first would mean accepting an unbounded array to prove it was small.\n .max(MAX_MENU_ENTITY_TYPE_WHITELIST)\n .nullable()\n .transform((value) => {\n if (value === null) return null\n const deduped = [...new Set(value)]\n return deduped.length === 0 ? null : deduped\n })\n\n/**\n * Narrow a raw `entityTypes` column value (untrusted shape) to a usable\n * whitelist, or `null` for \"no restriction\".\n *\n * The read-side counterpart of {@link MenuEntityTypesSchema}, and tolerant for\n * the same reason `normalizeMenuTree` is: rows written before this column\n * existed, hand edits and restored dumps all reach readers, and a render must\n * degrade rather than throw. Anything unusable — a non-array, a non-string\n * entry, a whitelist that reduces to nothing — reads as `null`.\n */\nexport function normalizeMenuEntityTypes(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n // `Array.isArray` narrows `unknown` to `any[]`; re-binding through a\n // `readonly unknown[]` annotation keeps every element typed as `unknown`.\n const raw: readonly unknown[] = value\n\n const out: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string' || entry.length === 0) continue\n if (entry.length > MAX_ENTITY_NAME_LENGTH) continue\n if (seen.has(entry)) continue\n seen.add(entry)\n out.push(entry)\n if (out.length === MAX_MENU_ENTITY_TYPE_WHITELIST) break\n }\n return out.length === 0 ? null : out\n}\n\n/**\n * Does this menu accept links to `entityType`?\n *\n * Takes the RAW column value so callers holding a `field.json()`-typed row can\n * ask directly, without narrowing first. Exact string match — entity names are\n * lowercase identifiers, and a case-insensitive or prefix match would silently\n * widen a whitelist the admin wrote precisely.\n *\n * Fails OPEN (see the module header): absent, empty and malformed all mean \"no\n * restriction\".\n */\nexport function menuAcceptsEntityType(value: unknown, entityType: string): boolean {\n const whitelist = normalizeMenuEntityTypes(value)\n return whitelist === null || whitelist.includes(entityType)\n}\n"],"mappings":"iFAkCA,MAAa,EAAiB,EAGjB,EAAqB,EASrB,EAAsB,IAWtB,EACX,KAuBW,EAAoB,IAmBpB,EAAiB,mBAmIjB,EAAkB,EAAE,mBAAmB,OAAQ,CAC1D,EAAE,OAAO,CACP,KAAM,EAAE,QAAQ,QAAQ,EACxB,OAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,EAA0B,EACpD,GAAI,EAAE,OAAO,CAAC,CAAC,KAAK,EACpB,OAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,GAAqB,CAAC,CAAC,MAAM,CAAc,CAAC,CAAC,SAAS,CAClF,CAAC,EACD,EAAE,OAAO,CACP,KAAM,EAAE,QAAQ,KAAK,EAQrB,IAAK,EACF,OAAO,CAAC,CACR,IAAI,CA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"kind", [z.ZodObject<{
|
|
|
230
230
|
id: z.ZodString;
|
|
231
231
|
anchor: z.ZodOptional<z.ZodString>;
|
|
232
232
|
}, "strip", z.ZodTypeAny, {
|
|
233
|
-
kind: "entity";
|
|
234
233
|
entity: string;
|
|
234
|
+
kind: "entity";
|
|
235
235
|
id: string;
|
|
236
236
|
anchor?: string | undefined;
|
|
237
237
|
}, {
|
|
238
|
-
kind: "entity";
|
|
239
238
|
entity: string;
|
|
239
|
+
kind: "entity";
|
|
240
240
|
id: string;
|
|
241
241
|
anchor?: string | undefined;
|
|
242
242
|
}>, z.ZodObject<{
|
|
243
243
|
kind: z.ZodLiteral<"url">;
|
|
244
244
|
url: z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>;
|
|
245
245
|
}, "strip", z.ZodTypeAny, {
|
|
246
|
-
kind: "url";
|
|
247
246
|
url: string;
|
|
248
|
-
}, {
|
|
249
247
|
kind: "url";
|
|
248
|
+
}, {
|
|
250
249
|
url: string;
|
|
250
|
+
kind: "url";
|
|
251
251
|
}>, z.ZodObject<{
|
|
252
252
|
kind: z.ZodLiteral<"email">;
|
|
253
253
|
email: z.ZodString;
|
|
254
254
|
}, "strip", z.ZodTypeAny, {
|
|
255
|
-
kind: "email";
|
|
256
255
|
email: string;
|
|
257
|
-
}, {
|
|
258
256
|
kind: "email";
|
|
257
|
+
}, {
|
|
259
258
|
email: string;
|
|
259
|
+
kind: "email";
|
|
260
260
|
}>]>;
|
|
261
261
|
/**
|
|
262
262
|
* The recursive per-node schema. Input is `unknown` (this parses untrusted
|
|
@@ -293,4 +293,4 @@ declare function measureMenuTree(tree: unknown): MenuTreeMeasurement;
|
|
|
293
293
|
declare function validateTreeDepth(tree: unknown, maxDepth: number): boolean;
|
|
294
294
|
//#endregion
|
|
295
295
|
export { validateTreeDepth as _, MAX_ANCHOR_LENGTH as a, menuAcceptsEntityType as b, MAX_MENU_URL_LENGTH as c, MenuLinkValue as d, MenuSchemaOptions as f, measureMenuTree as g, buildMenuTreeSchema as h, LinkValueSchema as i, MenuItem as l, buildMenuItemSchema as m, BlockAnchor as n, MAX_MENU_DEPTH as o, MenuTreeMeasurement as p, DEFAULT_MENU_DEPTH as r, MAX_MENU_TREE_NODES as s, ANCHOR_PATTERN as t, MenuItemSummary as u, MAX_MENU_ENTITY_TYPE_WHITELIST as v, normalizeMenuEntityTypes as x, MenuEntityTypesSchema as y };
|
|
296
|
-
//# sourceMappingURL=menu-item-schema-
|
|
296
|
+
//# sourceMappingURL=menu-item-schema-_Nj03ytp.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"menu-item-schema-_Nj03ytp.d.mts","names":[],"sources":["../src/menu-entity-types.ts","../src/menu-item-schema.ts"],"mappings":";;;;;ACqC+B;AAS/B;;;;AAAgC;AAWhC;;;;AAAgC;cDHnB,8BAAA;;;;AC2BiB;AAmB9B;;;;AAAgD;cDhCnC,qBAAA,EAAuB,CAAA,CAAE,OAAO,kBAAkB,CAAA,CAAE,UAAA;;;;;;;;;;;iBAwBjD,wBAAA,CAAyB,KAAc;;ACsC7B;AAgB1B;;;;;;;;;iBDxBgB,qBAAA,CAAsB,KAAA,WAAgB,UAAkB;;;;AAAA;;;;cCxF3D,cAAA;;cAGA,kBAAA;;AAHc;AAG3B;;;;AAA+B;cASlB,mBAAA;;;;AAAmB;AAWhC;;;;AAAgC;cAAnB,mBAAA;;;AA2CmC;AA2BhD;;;;;;;;cA9Ca,iBAAA;;;;;;;;cAmBA,cAAA,EAAc,MAAqB;;;;;;;;;;AAiE5B;AAcpB;;;;;;;;AAWW;AAQX;;;;AAIO;AAIP;KA/EY,aAAA;EACN,IAAA;EAAgB,MAAA;EAAgB,EAAA;EAAY,MAAA;AAAA;EAC5C,IAAA;EAAa,GAAA;AAAA;EACb,IAAA;EAAe,KAAA;AAAA;;;;;;;;;;;;;;;KAgBT,QAAA;EAqFgB,yDAnF1B,EAAA,UAmF0B;EAjF1B,IAAA;;;;;;;;;EASA,IAAA,GAAO,aAAA;EAEP,KAAA,EAAO,MAAA;EAEP,OAAA,GAAU,MAAA;EACV,MAAA;EACA,QAAA,EAAU,QAAA;AAAA;;;;;;;;;;;;UAcK,eAAA;;;;;;;EAOf,KAAA;;EAEA,MAAA;;EAEA,SAAA;AAAA;;;;;;UAQe,WAAA;;EAEf,MAAA;;EAEA,KAAK;AAAA;;UAIU,iBAAA;;;;;;EAMf,cAAc;AAAA;;;;;;;;;;;;;;;;AAqHmB;cAlGtB,eAAA,EAAe,CAAA,CAAA,qBAAA,UAAA,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgGZ,mBAAA,CACd,OAAA,EAAS,iBAAA,GACR,CAAA,CAAE,OAAA,CAAQ,QAAA,EAAU,CAAA,CAAE,UAAA;;iBAkDT,mBAAA,CACd,OAAA,EAAS,iBAAA,GACR,CAAA,CAAE,OAAA,CAAQ,QAAA,IAAY,CAAA,CAAE,UAAA;;UAKV,mBAAA;;EAEf,KAAA;;EAEA,SAAS;AAAA;;;;;;;;;;iBAYK,eAAA,CAAgB,IAAA,YAAgB,mBAAmB;;;;;;;iBA0CnD,iBAAA,CAAkB,IAAA,WAAe,QAAgB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e,t}from"./columns-DwDukx_r.mjs";import{getContentConfig as n}from"@murumets-ee/content/plugin";import{createSystemReachResolver as r}from"@murumets-ee/core";import{eq as i,inArray as a}from"drizzle-orm";import{getEntityTitleField as o,isTemplateDrawn as s}from"@murumets-ee/entity";import{QueryClient as c}from"@murumets-ee/entity/query";import{createDetailTemplateProvider as l}from"@murumets-ee/content/detail-template";import{buildCanonicalPathsBatchDeps as u,buildEnumerateDeps as d,getCanonicalPaths as f}from"@murumets-ee/content/resolve";const p=r(`menu-resolver`);function m(r){let m=r.db.readOnly,h=u(r),{filterPublished:g}=d(r);return{getMenuRow:async n=>{let a=new c({entity:e,db:m,logger:r.logger.child({resolve:`menu`}),contextResolver:p}),o=(await a.findMany({where:i(t(a.getTable(),`handle`),n),limit:1}))[0];return o===void 0?null:{maxDepth:o.maxDepth,tree:o.tree}},resolveCanonicalPaths:(e,t,n)=>f(e,t,n,h),filterPublished:g,resolveTitles:async(e,i,u)=>{let d=new Map;if(i.length===0)return d;let f=r.entities.get(e);if(f===void 0)return d;let h=s(f)?l(()=>r,{defaultLocale:n().defaultLocale}):void 0,g=o(f);if(h===void 0&&g===`id`)return d;let _=new c({entity:f,db:m,logger:r.logger.child({resolve:`menu-title`,entity:e}),contextResolver:p}),v=t(_.getTable(),`id`);for(let t=0;t<i.length;t+=500){let n=i.slice(t,t+500),o=await _.findMany({where:a(v,[...n]),locale:u,limit:n.length});for(let t of o){let n=t,i=n.id,a;if(h===void 0)a=n[g];else try{a=(await h.publicRow({entity:e,row:n,locale:u})).title}catch(t){r.logger.warn({err:t,entity:e},`menus: detail-template title projection failed — the item is dropped`)}typeof i==`string`&&typeof a==`string`&&a.length>0&&d.set(i,a)}}return d},defaultLocale:n().defaultLocale,logger:r.logger.child({resolve:`menu`})}}export{m as buildMenuResolveDeps};
|
|
2
|
+
//# sourceMappingURL=menu-resolve-context-DLIUP8RY.mjs.map
|
package/dist/{menu-resolve-context-2s6VJs_m.mjs.map → menu-resolve-context-DLIUP8RY.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu-resolve-context-2s6VJs_m.mjs","names":[],"sources":["../src/menu-resolve-context.ts"],"sourcesContent":["/**\n * App-binding for {@link import('./get-menu.js').getMenu} (plan/routing PR09).\n *\n * `./get-menu.ts` is a LEAF — it takes every dependency as an injected function\n * so it imports no `@murumets-ee/core` graph. THIS module is the outer seam\n * that holds those imports and builds concrete deps from a live `ToolkitApp`,\n * mirroring `@murumets-ee/content`'s `paths/resolve-context.ts` exactly. Because\n * the real `getCanonicalPaths` / `PublishFilter` are ASSIGNED to the leaf's\n * structurally-declared dep slots here, drift between the two packages is a\n * build error at this file rather than a silent divergence.\n *\n * **Reads run under an ELEVATED system context** (same `SYSTEM_CONTEXT` shape\n * and rationale as content's `resolve-context.ts` — read that file's header).\n * Rendering a menu is a SYSTEM derivation: it must work for an anonymous public\n * request, or for a build-time SSG run with no request context at all, and must\n * not fail just because the caller holds no per-entity `view` grant. Elevation\n * bypasses ONLY the permission/scope assertion — `QueryClient`'s PUBLISH filter\n * and trashed-row exclusion still apply, because the elevated context grants\n * reach WITHOUT `view_unpublished` (D017; see {@link SYSTEM_CONTEXT}), so:\n * - an unpublished / trashed MENU still resolves to `null` (nothing renders),\n * - an unpublished / trashed TARGET is still absent from the publish gate and\n * from the title read, so its item is dropped.\n * The only data elevation exposes is a published document's title + canonical\n * path — the same facts the public sitemap already enumerates.\n */\n\nimport { createDetailTemplateProvider } from '@murumets-ee/content/detail-template'\nimport { getContentConfig } from '@murumets-ee/content/plugin'\nimport {\n buildCanonicalPathsBatchDeps,\n buildEnumerateDeps,\n getCanonicalPaths,\n} from '@murumets-ee/content/resolve'\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { createSystemReachResolver } from '@murumets-ee/core'\nimport type { SecurityContext } from '@murumets-ee/entity'\nimport { getEntityTitleField, isTemplateDrawn } from '@murumets-ee/entity'\nimport { QueryClient } from '@murumets-ee/entity/query'\nimport { eq, inArray } from 'drizzle-orm'\nimport { Menu } from './entity.js'\nimport type { MenuResolveDeps, MenuRow } from './get-menu.js'\nimport { column } from './internal/columns.js'\n\n/**\n * Elevated **reach** resolver — grants reach, never visibility of unpublished\n * rows. See the file header.\n *\n * That invariant used to rest on `QueryClient` applying the publish filter\n * unconditionally; since D017 it rests on this resolver withholding\n * `view_unpublished`, which {@link createSystemReachResolver} does centrally.\n * A `checker: () => true` here would make `_menu` render items pointing at\n * draft documents.\n */\n// Named, not defaulted: `content`'s path resolver is the other elevated reader\n// and passes `'path-resolver'`. Two of them logging the default `'system'` would\n// be indistinguishable in audit output.\nconst SYSTEM_CONTEXT: () => SecurityContext = createSystemReachResolver('menu-resolver')\n\n/** Ids per batched title lookup — mirrors content's `CANONICAL_BATCH_SIZE`. */\nconst TITLE_BATCH_SIZE = 500\n\n/**\n * Build the concrete {@link MenuResolveDeps} for an app.\n *\n * Cheap to call per request (it constructs no clients eagerly — each read\n * builds its own `QueryClient`, matching `buildEnumerateDeps`'s per-call shape,\n * so this never depends on plugin boot ORDER).\n */\nexport function buildMenuResolveDeps(app: ToolkitApp): MenuResolveDeps {\n const db = app.db.readOnly\n const canonicalBatch = buildCanonicalPathsBatchDeps(app)\n const { filterPublished } = buildEnumerateDeps(app)\n\n return {\n getMenuRow: async (handle: string): Promise<MenuRow | null> => {\n const client = new QueryClient({\n entity: Menu,\n db,\n logger: app.logger.child({ resolve: 'menu' }),\n contextResolver: SYSTEM_CONTEXT,\n })\n // `publishable()` on `Menu` means this client filters to PUBLISHED rows\n // for any principal without `view_unpublished` — and `SYSTEM_CONTEXT`\n // withholds it (D017), so the filter always applies HERE. A draft menu\n // returns nothing, which `getMenu` turns into `null`. Do not swap this\n // resolver for a blanket `checker: () => true`: that grants the action and\n // silently publishes drafts.\n //\n // No `locale` is passed: the menu entity has no translations and no\n // locale-status table (locale variance lives INSIDE the tree, per D009),\n // so a locale would only cost a pointless translation merge.\n const rows = await client.findMany({\n where: eq(column(client.getTable(), 'handle'), handle),\n limit: 1,\n })\n const row = rows[0]\n if (row === undefined) return null\n return { maxDepth: row.maxDepth, tree: row.tree }\n },\n\n resolveCanonicalPaths: (entityType, ids, locale) =>\n getCanonicalPaths(entityType, ids, locale, canonicalBatch),\n\n filterPublished,\n\n resolveTitles: async (entityType, ids, locale) => {\n const titles = new Map<string, string>()\n if (ids.length === 0) return titles\n // An unregistered entity type yields NO title, so its items are dropped\n // — fail-closed, matching `buildEnumerateDeps`'s own unknown-type branch.\n const entity = app.entities.get(entityType)\n if (entity === undefined) return titles\n\n // A row DRAWN BY A STORED TEMPLATE (block-library D009, F051) is public\n // only as far as its site's detail bindings say. Its admin title column is\n // not one of those values (a legal document's is its `type` key), so it is\n // never read for a label: the item takes the row's DECLARED title — the\n // same one its own page shows — and drops if the site declares none.\n const declaredTitles = isTemplateDrawn(entity)\n ? createDetailTemplateProvider(() => app, {\n defaultLocale: getContentConfig().defaultLocale,\n })\n : undefined\n\n const titleField = getEntityTitleField(entity)\n // `getEntityTitleField` degrades to the row's own `id` when the entity has\n // no display-able field — a raw UUID is not a menu label. Fail closed and\n // let the item drop, matching this module's own stated posture.\n if (declaredTitles === undefined && titleField === 'id') return titles\n const client = new QueryClient({\n entity,\n db,\n logger: app.logger.child({ resolve: 'menu-title', entity: entityType }),\n contextResolver: SYSTEM_CONTEXT,\n })\n const idColumn = column(client.getTable(), 'id')\n\n for (let i = 0; i < ids.length; i += TITLE_BATCH_SIZE) {\n const chunk = ids.slice(i, i + TITLE_BATCH_SIZE)\n // `locale` drives `mergeTranslations`, so a translatable title comes\n // back in the requested locale (falling back to the base row's value)\n // — the \"live entity title (locale-merged)\" phase 11 §2 asks for.\n const rows = await client.findMany({\n where: inArray(idColumn, [...chunk]),\n locale,\n limit: chunk.length,\n })\n for (const row of rows) {\n const record: Record<string, unknown> = row\n const id = record.id\n let title: unknown\n if (declaredTitles === undefined) {\n title = record[titleField]\n } else {\n // Per ITEM, like everything else here: a projection that throws\n // costs that one label (the item drops), never the whole menu.\n try {\n title = (await declaredTitles.publicRow({ entity: entityType, row: record, locale }))\n .title\n } catch (err) {\n app.logger.warn(\n { err, entity: entityType },\n 'menus: detail-template title projection failed — the item is dropped',\n )\n }\n }\n if (typeof id === 'string' && typeof title === 'string' && title.length > 0) {\n titles.set(id, title)\n }\n }\n }\n return titles\n },\n\n defaultLocale: getContentConfig().defaultLocale,\n logger: app.logger.child({ resolve: 'menu' }),\n }\n}\n"],"mappings":"8iBAwDA,MAAM,EAAwC,EAA0B,eAAe,EAYvF,SAAgB,EAAqB,EAAkC,CACrE,IAAM,EAAK,EAAI,GAAG,SACZ,EAAiB,EAA6B,CAAG,EACjD,CAAE,mBAAoB,E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EACD,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAkC,EAClC,EAAK,EAAO,GACd,EACJ,GAAI,IAAmB,IAAA,GACrB,EAAQ,EAAO,QAIf,GAAI,CACF,GAAS,MAAM,EAAe,UAAU,CAAE,OAAQ,EAAY,IAAK,EAAQ,QAAO,CAAC,EAAA,CAChF,KACL,OAAS,EAAK,CACZ,EAAI,OAAO,KACT,CAAE,MAAK,OAAQ,CAAW,EAC1B,sEACF,CACF,CAEE,OAAO,GAAO,UAAY,OAAO,GAAU,UAAY,EAAM,OAAS,GACxE,EAAO,IAAI,EAAI,CAAK,CAExB,CACF,CACA,OAAO,CACT,EAEA,cAAe,EAAiB,CAAC,CAAC,cAClC,OAAQ,EAAI,OAAO,MAAM,CAAE,QAAS,MAAO,CAAC,CAC9C,CACF"}
|
|
1
|
+
{"version":3,"file":"menu-resolve-context-DLIUP8RY.mjs","names":[],"sources":["../src/menu-resolve-context.ts"],"sourcesContent":["/**\n * App-binding for {@link import('./get-menu.js').getMenu} (plan/routing PR09).\n *\n * `./get-menu.ts` is a LEAF — it takes every dependency as an injected function\n * so it imports no `@murumets-ee/core` graph. THIS module is the outer seam\n * that holds those imports and builds concrete deps from a live `ToolkitApp`,\n * mirroring `@murumets-ee/content`'s `paths/resolve-context.ts` exactly. Because\n * the real `getCanonicalPaths` / `PublishFilter` are ASSIGNED to the leaf's\n * structurally-declared dep slots here, drift between the two packages is a\n * build error at this file rather than a silent divergence.\n *\n * **Reads run under an ELEVATED system context** (same `SYSTEM_CONTEXT` shape\n * and rationale as content's `resolve-context.ts` — read that file's header).\n * Rendering a menu is a SYSTEM derivation: it must work for an anonymous public\n * request, or for a build-time SSG run with no request context at all, and must\n * not fail just because the caller holds no per-entity `view` grant. Elevation\n * bypasses ONLY the permission/scope assertion — `QueryClient`'s PUBLISH filter\n * and trashed-row exclusion still apply, because the elevated context grants\n * reach WITHOUT `view_unpublished` (D017; see {@link SYSTEM_CONTEXT}), so:\n * - an unpublished / trashed MENU still resolves to `null` (nothing renders),\n * - an unpublished / trashed TARGET is still absent from the publish gate and\n * from the title read, so its item is dropped.\n * The only data elevation exposes is a published document's title + canonical\n * path — the same facts the public sitemap already enumerates.\n */\n\nimport { createDetailTemplateProvider } from '@murumets-ee/content/detail-template'\nimport { getContentConfig } from '@murumets-ee/content/plugin'\nimport {\n buildCanonicalPathsBatchDeps,\n buildEnumerateDeps,\n getCanonicalPaths,\n} from '@murumets-ee/content/resolve'\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { createSystemReachResolver } from '@murumets-ee/core'\nimport type { SecurityContext } from '@murumets-ee/entity'\nimport { getEntityTitleField, isTemplateDrawn } from '@murumets-ee/entity'\nimport { QueryClient } from '@murumets-ee/entity/query'\nimport { eq, inArray } from 'drizzle-orm'\nimport { Menu } from './entity.js'\nimport type { MenuResolveDeps, MenuRow } from './get-menu.js'\nimport { column } from './internal/columns.js'\n\n/**\n * Elevated **reach** resolver — grants reach, never visibility of unpublished\n * rows. See the file header.\n *\n * That invariant used to rest on `QueryClient` applying the publish filter\n * unconditionally; since D017 it rests on this resolver withholding\n * `view_unpublished`, which {@link createSystemReachResolver} does centrally.\n * A `checker: () => true` here would make `_menu` render items pointing at\n * draft documents.\n */\n// Named, not defaulted: `content`'s path resolver is the other elevated reader\n// and passes `'path-resolver'`. Two of them logging the default `'system'` would\n// be indistinguishable in audit output.\nconst SYSTEM_CONTEXT: () => SecurityContext = createSystemReachResolver('menu-resolver')\n\n/** Ids per batched title lookup — mirrors content's `CANONICAL_BATCH_SIZE`. */\nconst TITLE_BATCH_SIZE = 500\n\n/**\n * Build the concrete {@link MenuResolveDeps} for an app.\n *\n * Cheap to call per request (it constructs no clients eagerly — each read\n * builds its own `QueryClient`, matching `buildEnumerateDeps`'s per-call shape,\n * so this never depends on plugin boot ORDER).\n */\nexport function buildMenuResolveDeps(app: ToolkitApp): MenuResolveDeps {\n const db = app.db.readOnly\n const canonicalBatch = buildCanonicalPathsBatchDeps(app)\n const { filterPublished } = buildEnumerateDeps(app)\n\n return {\n getMenuRow: async (handle: string): Promise<MenuRow | null> => {\n const client = new QueryClient({\n entity: Menu,\n db,\n logger: app.logger.child({ resolve: 'menu' }),\n contextResolver: SYSTEM_CONTEXT,\n })\n // `publishable()` on `Menu` means this client filters to PUBLISHED rows\n // for any principal without `view_unpublished` — and `SYSTEM_CONTEXT`\n // withholds it (D017), so the filter always applies HERE. A draft menu\n // returns nothing, which `getMenu` turns into `null`. Do not swap this\n // resolver for a blanket `checker: () => true`: that grants the action and\n // silently publishes drafts.\n //\n // No `locale` is passed: the menu entity has no translations and no\n // locale-status table (locale variance lives INSIDE the tree, per D009),\n // so a locale would only cost a pointless translation merge.\n const rows = await client.findMany({\n where: eq(column(client.getTable(), 'handle'), handle),\n limit: 1,\n })\n const row = rows[0]\n if (row === undefined) return null\n return { maxDepth: row.maxDepth, tree: row.tree }\n },\n\n resolveCanonicalPaths: (entityType, ids, locale) =>\n getCanonicalPaths(entityType, ids, locale, canonicalBatch),\n\n filterPublished,\n\n resolveTitles: async (entityType, ids, locale) => {\n const titles = new Map<string, string>()\n if (ids.length === 0) return titles\n // An unregistered entity type yields NO title, so its items are dropped\n // — fail-closed, matching `buildEnumerateDeps`'s own unknown-type branch.\n const entity = app.entities.get(entityType)\n if (entity === undefined) return titles\n\n // A row DRAWN BY A STORED TEMPLATE (block-library D009, F051) is public\n // only as far as its site's detail bindings say. Its admin title column is\n // not one of those values (a legal document's is its `type` key), so it is\n // never read for a label: the item takes the row's DECLARED title — the\n // same one its own page shows — and drops if the site declares none.\n const declaredTitles = isTemplateDrawn(entity)\n ? createDetailTemplateProvider(() => app, {\n defaultLocale: getContentConfig().defaultLocale,\n })\n : undefined\n\n const titleField = getEntityTitleField(entity)\n // `getEntityTitleField` degrades to the row's own `id` when the entity has\n // no display-able field — a raw UUID is not a menu label. Fail closed and\n // let the item drop, matching this module's own stated posture.\n if (declaredTitles === undefined && titleField === 'id') return titles\n const client = new QueryClient({\n entity,\n db,\n logger: app.logger.child({ resolve: 'menu-title', entity: entityType }),\n contextResolver: SYSTEM_CONTEXT,\n })\n const idColumn = column(client.getTable(), 'id')\n\n for (let i = 0; i < ids.length; i += TITLE_BATCH_SIZE) {\n const chunk = ids.slice(i, i + TITLE_BATCH_SIZE)\n // `locale` drives `mergeTranslations`, so a translatable title comes\n // back in the requested locale (falling back to the base row's value)\n // — the \"live entity title (locale-merged)\" phase 11 §2 asks for.\n const rows = await client.findMany({\n where: inArray(idColumn, [...chunk]),\n locale,\n limit: chunk.length,\n })\n for (const row of rows) {\n const record: Record<string, unknown> = row\n const id = record.id\n let title: unknown\n if (declaredTitles === undefined) {\n title = record[titleField]\n } else {\n // Per ITEM, like everything else here: a projection that throws\n // costs that one label (the item drops), never the whole menu.\n try {\n title = (await declaredTitles.publicRow({ entity: entityType, row: record, locale }))\n .title\n } catch (err) {\n app.logger.warn(\n { err, entity: entityType },\n 'menus: detail-template title projection failed — the item is dropped',\n )\n }\n }\n if (typeof id === 'string' && typeof title === 'string' && title.length > 0) {\n titles.set(id, title)\n }\n }\n }\n return titles\n },\n\n defaultLocale: getContentConfig().defaultLocale,\n logger: app.logger.child({ resolve: 'menu' }),\n }\n}\n"],"mappings":"8iBAwDA,MAAM,EAAwC,EAA0B,eAAe,EAYvF,SAAgB,EAAqB,EAAkC,CACrE,IAAM,EAAK,EAAI,GAAG,SACZ,EAAiB,EAA6B,CAAG,EACjD,CAAE,mBAAoB,EAAmB,CAAG,EAElD,MAAO,CACL,WAAY,KAAO,IAA4C,CAC7D,IAAM,EAAS,IAAI,EAAY,CAC7B,OAAQ,EACR,KACA,OAAQ,EAAI,OAAO,MAAM,CAAE,QAAS,MAAO,CAAC,EAC5C,gBAAiB,CACnB,CAAC,EAeK,GAAM,MAJO,EAAO,SAAS,CACjC,MAAO,EAAG,EAAO,EAAO,SAAS,EAAG,QAAQ,EAAG,CAAM,EACrD,MAAO,CACT,CAAC,EAAA,CACgB,GAEjB,OADI,IAAQ,IAAA,G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AAY,EAAM,OAAS,GACxE,EAAO,IAAI,EAAI,CAAK,CAExB,CACF,CACA,OAAO,CACT,EAEA,cAAe,EAAiB,CAAC,CAAC,cAClC,OAAQ,EAAI,OAAO,MAAM,CAAE,QAAS,MAAO,CAAC,CAC9C,CACF"}
|
package/dist/messages/en.json
CHANGED
package/dist/messages/et.json
CHANGED
package/dist/messages/ru.json
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={PluginNav:{menu:`Меню`},Menus:{entity:{menu:`Меню`,menus:`Меню`,handle:`Идентификатор`,title:`Название`,maxDepth:`Максимальная глубина`,tree:`Элементы`},itemKind:{link:`Ссылка`,header:`Заголовок`}}};export{e as default};
|
|
2
|
-
//# sourceMappingURL=ru-
|
|
1
|
+
var e={PluginNav:{menu:`Меню`},Menus:{entity:{menu:`Меню`,menus:`Меню`,handle:`Идентификатор`,title:`Название`,maxDepth:`Максимальная глубина`,tree:`Элементы`},itemKind:{link:`Ссылка`,header:`Заголовок`},translatableSource:{menu:`Меню`}}};export{e as default};
|
|
2
|
+
//# sourceMappingURL=ru-D8QNW6XE.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ru-D8QNW6XE.mjs","names":[],"sources":["../src/messages/ru.json"],"sourcesContent":[""],"mappings":""}
|
package/dist/schema.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as validateTreeDepth, a as MAX_ANCHOR_LENGTH, b as menuAcceptsEntityType, c as MAX_MENU_URL_LENGTH, d as MenuLinkValue, f as MenuSchemaOptions, g as measureMenuTree, h as buildMenuTreeSchema, i as LinkValueSchema, l as MenuItem, m as buildMenuItemSchema, n as BlockAnchor, o as MAX_MENU_DEPTH, p as MenuTreeMeasurement, r as DEFAULT_MENU_DEPTH, s as MAX_MENU_TREE_NODES, t as ANCHOR_PATTERN, u as MenuItemSummary, v as MAX_MENU_ENTITY_TYPE_WHITELIST, x as normalizeMenuEntityTypes, y as MenuEntityTypesSchema } from "./menu-item-schema-
|
|
1
|
+
import { _ as validateTreeDepth, a as MAX_ANCHOR_LENGTH, b as menuAcceptsEntityType, c as MAX_MENU_URL_LENGTH, d as MenuLinkValue, f as MenuSchemaOptions, g as measureMenuTree, h as buildMenuTreeSchema, i as LinkValueSchema, l as MenuItem, m as buildMenuItemSchema, n as BlockAnchor, o as MAX_MENU_DEPTH, p as MenuTreeMeasurement, r as DEFAULT_MENU_DEPTH, s as MAX_MENU_TREE_NODES, t as ANCHOR_PATTERN, u as MenuItemSummary, v as MAX_MENU_ENTITY_TYPE_WHITELIST, x as normalizeMenuEntityTypes, y as MenuEntityTypesSchema } from "./menu-item-schema-_Nj03ytp.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/menu-tree-flatten.d.ts
|
|
4
4
|
/** A menu node's payload without its children — structure lives on the flat node. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@murumets-ee/menus",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.108.0",
|
|
4
4
|
"license": "Elastic-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -35,10 +35,10 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"drizzle-orm": "^0.45.2",
|
|
37
37
|
"zod": "^3.24.1",
|
|
38
|
-
"@murumets-ee/blocks": "0.
|
|
39
|
-
"@murumets-ee/content": "0.
|
|
40
|
-
"@murumets-ee/
|
|
41
|
-
"@murumets-ee/
|
|
38
|
+
"@murumets-ee/blocks": "0.108.0",
|
|
39
|
+
"@murumets-ee/content": "0.108.0",
|
|
40
|
+
"@murumets-ee/core": "0.108.0",
|
|
41
|
+
"@murumets-ee/entity": "0.108.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/node": "^20.19.42",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"tsdown": "^0.22.2",
|
|
47
47
|
"typescript": "^5.7.3",
|
|
48
48
|
"vitest": "^2.1.8",
|
|
49
|
-
"@murumets-ee/content-api": "0.
|
|
50
|
-
"@murumets-ee/db": "0.
|
|
49
|
+
"@murumets-ee/content-api": "0.108.0",
|
|
50
|
+
"@murumets-ee/db": "0.108.0"
|
|
51
51
|
},
|
|
52
52
|
"typeCoverage": {
|
|
53
53
|
"atLeast": 100
|