@foundrykit/menu-plugin 0.6.0 → 0.6.2

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.
Files changed (53) hide show
  1. package/README.md +39 -39
  2. package/dist/cache.js.map +1 -1
  3. package/dist/collections/Menus.js +6 -0
  4. package/dist/collections/Menus.js.map +1 -1
  5. package/dist/components/ColumnLinkRowLabel.js.map +1 -1
  6. package/dist/components/MegaEntryRowLabel.js.map +1 -1
  7. package/dist/components/MenuItemRowLabel.js.map +1 -1
  8. package/dist/components/MenuPreview.d.ts +1 -1
  9. package/dist/components/MenuPreview.js +1 -1
  10. package/dist/components/MenuPreview.js.map +1 -1
  11. package/dist/components/SubMenuItemRowLabel.js.map +1 -1
  12. package/dist/components/UrlField/countryCodes.js.map +1 -1
  13. package/dist/components/UrlField/index.js +3 -4
  14. package/dist/components/UrlField/index.js.map +1 -1
  15. package/dist/endpoints/exportMenusHandler.js.map +1 -1
  16. package/dist/endpoints/getMenuHandler.js.map +1 -1
  17. package/dist/endpoints/importMenusHandler.js.map +1 -1
  18. package/dist/exports/client.d.ts +1 -1
  19. package/dist/exports/client.js +1 -1
  20. package/dist/exports/client.js.map +1 -1
  21. package/dist/exports/rsc.js.map +1 -1
  22. package/dist/fetchMenu.js.map +1 -1
  23. package/dist/fields/MenuItem.js +2 -2
  24. package/dist/fields/MenuItem.js.map +1 -1
  25. package/dist/hooks/resolveDynamicMenu.js.map +1 -1
  26. package/dist/hooks/stripDynamicMenuChildren.d.ts +28 -0
  27. package/dist/hooks/stripDynamicMenuChildren.js +50 -0
  28. package/dist/hooks/stripDynamicMenuChildren.js.map +1 -0
  29. package/dist/hooks/stripDynamicMenuChildren.test.d.ts +1 -0
  30. package/dist/hooks/stripDynamicMenuChildren.test.js +128 -0
  31. package/dist/hooks/stripDynamicMenuChildren.test.js.map +1 -0
  32. package/dist/hooks/useMenu.js.map +1 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/migrations/megaColumnsToEntries.d.ts +1 -1
  35. package/dist/migrations/megaColumnsToEntries.js.map +1 -1
  36. package/dist/types.js.map +1 -1
  37. package/dist/utilities/menuIdentity.js.map +1 -1
  38. package/dist/utilities/requireAdminUser.js.map +1 -1
  39. package/dist/utilities/sanitizeMenuDocument.js.map +1 -1
  40. package/package.json +22 -31
  41. package/dist/components/BeforeDashboardClient.d.ts +0 -1
  42. package/dist/components/BeforeDashboardClient.js +0 -40
  43. package/dist/components/BeforeDashboardClient.js.map +0 -1
  44. package/dist/components/BeforeDashboardServer.d.ts +0 -2
  45. package/dist/components/BeforeDashboardServer.js +0 -22
  46. package/dist/components/BeforeDashboardServer.js.map +0 -1
  47. package/dist/components/BeforeDashboardServer.module.css +0 -5
  48. package/dist/components/MegaColumnRowLabel.d.ts +0 -1
  49. package/dist/components/MegaColumnRowLabel.js +0 -11
  50. package/dist/components/MegaColumnRowLabel.js.map +0 -1
  51. package/dist/endpoints/customEndpointHandler.d.ts +0 -2
  52. package/dist/endpoints/customEndpointHandler.js +0 -7
  53. package/dist/endpoints/customEndpointHandler.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fields/MenuItem.ts"],"sourcesContent":["import type { CollectionSlug, Field, Validate } from 'payload'\n\nimport type { DynamicSource } from '../types.js'\n\nexport type MenuItemFieldOptions = {\n baseUrl?: string\n disabled?: boolean\n dynamicSources?: DynamicSource[]\n maxDepth?: number\n mediaCollection?: CollectionSlug\n relationTo?: CollectionSlug | CollectionSlug[]\n}\n\nconst validateUrl: Validate = (value, { siblingData }) => {\n const type = (siblingData as any)?.type\n if (!value) {\n if (['anchor', 'custom', 'external', 'internal', 'mailto', 'tel'].includes(type)) {\n return 'URL is required for this link type'\n }\n return true\n }\n\n switch (type) {\n case 'anchor': {\n if (!/^#[\\w-]+$/.test(value as string)) {\n return 'Please enter a valid anchor (e.g. #section-name)'\n }\n break\n }\n case 'external': {\n try {\n new URL(value as string)\n } catch {\n return 'Please enter a valid URL (e.g. https://example.co.uk)'\n }\n break\n }\n case 'internal': {\n const path = (value as string).replace(/^https?:\\/\\/[^/]+/, '')\n if (!path.startsWith('/')) {\n return 'Internal paths must start with /'\n }\n break\n }\n case 'mailto': {\n const email = (value as string).replace(/^mailto:/, '')\n const [local, domain] = email.split('@')\n if (!local || !domain || domain.indexOf('.') < 1 || email.split('@').length !== 2) {\n return 'Please enter a valid email address'\n }\n break\n }\n case 'tel': {\n const raw = (value as string).replace(/^tel:/, '')\n if (!/^\\+?\\d[\\d\\s\\-()]{4,}$/.test(raw)) {\n return 'Please enter a valid phone number'\n }\n break\n }\n }\n\n return true\n}\n\nconst LINK_TYPE_OPTIONS = [\n { label: 'Internal', value: 'internal' },\n { label: 'External', value: 'external' },\n { label: 'Reference', value: 'reference' },\n { label: 'Anchor', value: 'anchor' },\n { label: 'Mail To', value: 'mailto' },\n { label: 'TEL', value: 'tel' },\n { label: 'Custom', value: 'custom' },\n]\n\nconst buildFeaturedFields = (options?: MenuItemFieldOptions): Field[] => {\n const baseUrl = options?.baseUrl ?? ''\n const relationTo = options?.relationTo ?? ('pages' as CollectionSlug)\n const fields: Field[] = [\n {\n name: 'heading',\n type: 'text',\n },\n {\n name: 'description',\n type: 'textarea',\n },\n {\n name: 'ctaType',\n type: 'select',\n defaultValue: 'reference',\n label: 'CTA Link Type',\n options: LINK_TYPE_OPTIONS,\n },\n {\n name: 'ctaLabel',\n type: 'text',\n label: 'CTA Label',\n },\n {\n name: 'ctaUrl',\n type: 'text',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n Field: '@foundrykit/menu-plugin/client#UrlField',\n },\n }),\n condition: (_data, siblingData) => siblingData?.ctaType !== 'reference',\n custom: { baseUrl },\n },\n label: 'CTA URL',\n validate: validateUrl,\n },\n {\n name: 'ctaReference',\n type: 'relationship',\n admin: {\n condition: (_data, siblingData) => siblingData?.ctaType === 'reference',\n },\n ...(Array.isArray(relationTo) ? { hasMany: false, relationTo } : { relationTo }),\n } as Field,\n {\n name: 'ctaTarget',\n type: 'radio',\n defaultValue: '_self',\n label: 'CTA Open in',\n options: [\n { label: 'Same Tab', value: '_self' },\n { label: 'New Tab', value: '_blank' },\n ],\n },\n ]\n if (options?.mediaCollection) {\n fields.unshift({\n name: 'image',\n type: 'upload',\n relationTo: options.mediaCollection,\n } as Field)\n }\n return fields\n}\n\n/**\n * The simple-by-default link field set shared by every item that behaves like a\n * link: `label`, `type`, `reference`/`url`, plus the \"Options\" and \"Advanced\"\n * collapsible groups. No `itemType` and no nesting fields are included here.\n */\nconst buildLeafLinkFields = (options?: MenuItemFieldOptions): Field[] => {\n const baseUrl = options?.baseUrl ?? ''\n const relationTo = options?.relationTo ?? ('pages' as CollectionSlug)\n\n return [\n {\n name: 'type',\n type: 'select',\n admin: {\n description:\n 'Select the type of link for this menu item. On a mega menu or dropdown this is where the top-level label links to, and is optional.',\n },\n defaultValue: 'reference',\n options: LINK_TYPE_OPTIONS,\n required: true,\n },\n {\n type: 'row',\n fields: [\n {\n name: 'label',\n type: 'text',\n admin: {\n width: '50%',\n },\n required: true,\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n Field: '@foundrykit/menu-plugin/client#UrlField',\n },\n }),\n condition: (_data, siblingData) => {\n return siblingData?.type !== 'reference'\n },\n custom: { baseUrl },\n width: '50%',\n },\n label: 'URL',\n validate: validateUrl,\n },\n {\n name: 'reference',\n type: 'relationship',\n admin: {\n condition: (_data, siblingData) => {\n return siblingData?.type === 'reference'\n },\n width: '50%',\n },\n ...(Array.isArray(relationTo) ? { hasMany: false, relationTo } : { relationTo }),\n } as Field,\n ],\n },\n {\n type: 'collapsible',\n admin: {\n initCollapsed: true,\n },\n fields: [\n {\n name: 'target',\n type: 'radio',\n defaultValue: '_self',\n label: 'Open in new tab',\n options: [\n { label: 'Same Tab', value: '_self' },\n { label: 'New Tab', value: '_blank' },\n ],\n },\n {\n name: 'displaySurface',\n type: 'select',\n admin: {\n description: 'Controls which navigation surfaces render this item.',\n },\n defaultValue: 'both',\n label: 'Display Surface',\n options: [\n { label: 'Navbar + Drawer (default)', value: 'both' },\n { label: 'Navbar Only', value: 'navbar' },\n { label: 'Drawer Only', value: 'drawer' },\n ],\n },\n ],\n label: 'Options',\n },\n {\n type: 'collapsible',\n admin: {\n initCollapsed: true,\n },\n fields: [\n {\n name: 'visibility',\n type: 'radio',\n defaultValue: 'visible',\n options: [\n { label: 'Visible', value: 'visible' },\n { label: 'Invisible', value: 'invisible' },\n ],\n },\n {\n name: 'rel',\n type: 'text',\n },\n {\n name: 'roles',\n type: 'array',\n fields: [{ name: 'role', type: 'text' }],\n },\n {\n name: 'attrs',\n type: 'textarea',\n },\n ],\n label: 'Advanced',\n },\n ]\n}\n\nconst buildMegaConfigFields = (options?: MenuItemFieldOptions, currentDepth = 0): Field[] => {\n const dynamicSources = options?.dynamicSources ?? []\n const relationTo = options?.relationTo ?? ('pages' as CollectionSlug)\n\n const parentCollections = [...new Set(dynamicSources.map((source) => source.parentCollection))]\n const singleSource = dynamicSources.length === 1\n\n // Parent relationship: collapse to a single relationTo string when exactly one\n // source is configured, union when many, fall back to the link relationTo when\n // no dynamic sources are configured.\n const parentRelationTo: CollectionSlug | CollectionSlug[] =\n parentCollections.length === 1\n ? parentCollections[0]\n : parentCollections.length > 1\n ? parentCollections\n : relationTo\n\n const dynamicSourceOptions = dynamicSources.map((source) => ({\n label: source.label,\n value: source.name,\n }))\n\n const isMega = (_data: any, siblingData: any) => siblingData?.itemType === 'mega'\n\n return [\n {\n name: 'megaLayout',\n type: 'select',\n admin: {\n condition: isMega,\n description: 'How the mega menu is laid out. \"Reveal\" shows a flat list of rows that reveal their children in a second panel; \"Columns\" renders classic multi-column layout.',\n },\n defaultValue: 'reveal',\n label: 'Mega Menu Layout',\n options: [\n { label: 'Reveal (rows)', value: 'reveal' },\n { label: 'Columns', value: 'columns' },\n ],\n },\n {\n name: 'defaultFeatured',\n type: 'group',\n admin: {\n condition: isMega,\n description: 'Fallback featured panel shown when an entry does not provide its own.',\n },\n fields: buildFeaturedFields(options),\n label: 'Default Featured Panel',\n },\n {\n name: 'megaEntries',\n type: 'array',\n admin: {\n condition: isMega,\n description: 'A flat list of entries. Each entry is itself a link and can reveal children in a secondary panel.',\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel: '@foundrykit/menu-plugin/client#MegaEntryRowLabel',\n },\n }),\n },\n // Depth-aware, short dbName so the generated Postgres table/relation names\n // stay unique across nesting levels and well under the 63-char identifier\n // limit even when consumers raise `maxDepth`.\n dbName: `me${currentDepth}`,\n fields: [\n ...buildLeafLinkFields(options),\n {\n name: 'source',\n type: 'select',\n admin: {\n description: 'Where this entry\\'s children come from.',\n },\n defaultValue: 'manual',\n options: [\n { label: 'Manual', value: 'manual' },\n { label: 'Dynamic (from a related collection)', value: 'dynamic' },\n ],\n required: true,\n },\n {\n name: 'children',\n type: 'array',\n admin: {\n condition: (_data, siblingData) => siblingData?.source !== 'dynamic',\n description: 'Items revealed in the secondary panel when this entry is hovered or selected.',\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel: '@foundrykit/menu-plugin/client#SubMenuItemRowLabel',\n },\n }),\n },\n dbName: `mc${currentDepth}`,\n fields: buildLeafLinkFields(options),\n label: 'Children',\n },\n {\n name: 'dynamicSource',\n type: 'select',\n admin: {\n condition: (_data, siblingData) => siblingData?.source === 'dynamic',\n // Hidden and auto-set when exactly one source is configured.\n hidden: singleSource,\n },\n ...(singleSource ? { defaultValue: dynamicSources[0]?.name } : {}),\n label: 'Dynamic Source',\n options: dynamicSourceOptions,\n },\n {\n name: 'parent',\n type: 'relationship',\n admin: {\n condition: (_data, siblingData) => siblingData?.source === 'dynamic',\n description: 'The parent document whose related children populate this entry.',\n },\n ...(Array.isArray(parentRelationTo)\n ? { hasMany: false, relationTo: parentRelationTo }\n : { relationTo: parentRelationTo }),\n } as Field,\n {\n name: 'featured',\n type: 'group',\n admin: {\n description: 'The featured panel shown alongside this entry\\'s children.',\n },\n fields: [\n {\n name: 'mode',\n type: 'select',\n defaultValue: 'inherit',\n options: [\n { label: 'Inherit (use default featured)', value: 'inherit' },\n { label: 'Manual', value: 'manual' },\n { label: 'Dynamic (from the related source)', value: 'dynamic' },\n ],\n },\n ...buildFeaturedFields(options).map((field) => {\n if (!('name' in field)) {return field}\n const existingCondition = (field as any).admin?.condition\n return {\n ...field,\n admin: {\n ...(field as any).admin,\n condition: (_data: any, siblingData: any, extra: any) => {\n if (siblingData?.mode !== 'manual') {return false}\n return existingCondition ? existingCondition(_data, siblingData, extra) : true\n },\n },\n } as Field\n }),\n ],\n label: 'Featured Panel',\n },\n ],\n label: 'Mega Menu Entries',\n },\n ]\n}\n\nexport const createMenuItemFields = (options?: MenuItemFieldOptions, currentDepth = 0): Field[] => {\n const maxDepth = options?.maxDepth ?? 1\n const leafLinkFields = buildLeafLinkFields(options)\n\n const canNest = currentDepth < maxDepth\n\n if (!canNest) {\n return leafLinkFields\n }\n\n return [\n {\n name: 'itemType',\n type: 'select',\n defaultValue: 'link',\n options: [\n { label: 'Link', value: 'link' },\n { label: 'Dropdown', value: 'dropdown' },\n { label: 'Mega Menu', value: 'mega' },\n ],\n required: true,\n },\n ...leafLinkFields,\n {\n name: currentDepth === 0 ? 'children' : `children_${currentDepth + 1}`,\n type: 'array',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel: '@foundrykit/menu-plugin/client#SubMenuItemRowLabel',\n },\n }),\n condition: (_data, siblingData) => {\n return siblingData?.itemType === 'dropdown'\n },\n },\n fields: createMenuItemFields(options, currentDepth + 1),\n label: 'Children',\n },\n ...buildMegaConfigFields(options, currentDepth),\n ]\n}\n\nexport const menuItemFields = createMenuItemFields()\n\nexport default menuItemFields\n"],"names":["validateUrl","value","siblingData","type","includes","test","URL","path","replace","startsWith","email","local","domain","split","indexOf","length","raw","LINK_TYPE_OPTIONS","label","buildFeaturedFields","options","baseUrl","relationTo","fields","name","defaultValue","admin","disabled","components","Field","condition","_data","ctaType","custom","validate","Array","isArray","hasMany","mediaCollection","unshift","buildLeafLinkFields","description","required","width","initCollapsed","buildMegaConfigFields","currentDepth","dynamicSources","parentCollections","Set","map","source","parentCollection","singleSource","parentRelationTo","dynamicSourceOptions","isMega","itemType","RowLabel","dbName","hidden","field","existingCondition","extra","mode","createMenuItemFields","maxDepth","leafLinkFields","canNest","menuItemFields"],"mappings":"AAaA,MAAMA,cAAwB,CAACC,OAAO,EAAEC,WAAW,EAAE;IACnD,MAAMC,OAAQD,aAAqBC;IACnC,IAAI,CAACF,OAAO;QACV,IAAI;YAAC;YAAU;YAAU;YAAY;YAAY;YAAU;SAAM,CAACG,QAAQ,CAACD,OAAO;YAChF,OAAO;QACT;QACA,OAAO;IACT;IAEA,OAAQA;QACN,KAAK;YAAU;gBACb,IAAI,CAAC,YAAYE,IAAI,CAACJ,QAAkB;oBACtC,OAAO;gBACT;gBACA;YACF;QACA,KAAK;YAAY;gBACf,IAAI;oBACF,IAAIK,IAAIL;gBACV,EAAE,OAAM;oBACN,OAAO;gBACT;gBACA;YACF;QACA,KAAK;YAAY;gBACf,MAAMM,OAAO,AAACN,MAAiBO,OAAO,CAAC,qBAAqB;gBAC5D,IAAI,CAACD,KAAKE,UAAU,CAAC,MAAM;oBACzB,OAAO;gBACT;gBACA;YACF;QACA,KAAK;YAAU;gBACb,MAAMC,QAAQ,AAACT,MAAiBO,OAAO,CAAC,YAAY;gBACpD,MAAM,CAACG,OAAOC,OAAO,GAAGF,MAAMG,KAAK,CAAC;gBACpC,IAAI,CAACF,SAAS,CAACC,UAAUA,OAAOE,OAAO,CAAC,OAAO,KAAKJ,MAAMG,KAAK,CAAC,KAAKE,MAAM,KAAK,GAAG;oBACjF,OAAO;gBACT;gBACA;YACF;QACA,KAAK;YAAO;gBACV,MAAMC,MAAM,AAACf,MAAiBO,OAAO,CAAC,SAAS;gBAC/C,IAAI,CAAC,wBAAwBH,IAAI,CAACW,MAAM;oBACtC,OAAO;gBACT;gBACA;YACF;I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AAU;4CAAC,OAAO;wCAAK;wCACjD,OAAOF,oBAAoBA,kBAAkB/B,OAAO7B,aAAa6D,SAAS;oCAC5E;gCACF;4BACF;wBACF;qBACD;oBACD7C,OAAO;gBACT;aACD;YACDA,OAAO;QACT;KACD;AACH;AAEA,OAAO,MAAM+C,uBAAuB,CAAC7C,SAAgC0B,eAAe,CAAC;IACnF,MAAMoB,WAAW9C,SAAS8C,YAAY;IACtC,MAAMC,iBAAiB3B,oBAAoBpB;IAE3C,MAAMgD,UAAUtB,eAAeoB;IAE/B,IAAI,CAACE,SAAS;QACZ,OAAOD;IACT;IAEA,OAAO;QACL;YACE3C,MAAM;YACNrB,MAAM;YACNsB,cAAc;YACdL,SAAS;gBACP;oBAAEF,OAAO;oBAAQjB,OAAO;gBAAO;gBAC/B;oBAAEiB,OAAO;oBAAYjB,OAAO;gBAAW;gBACvC;oBAAEiB,OAAO;oBAAajB,OAAO;gBAAO;aACrC;YACDyC,UAAU;QACZ;WACGyB;QACH;YACE3C,MAAMsB,iBAAiB,IAAI,aAAa,CAAC,SAAS,EAAEA,eAAe,GAAG;YACtE3C,MAAM;YACNuB,OAAO;gBACL,GAAIN,SAASO,WACT,CAAC,IACD;oBACEC,YAAY;wBACV8B,UAAU;oBACZ;gBACF,CAAC;gBACL5B,WAAW,CAACC,OAAO7B;oBACjB,OAAOA,aAAauD,aAAa;gBACnC;YACF;YACAlC,QAAQ0C,qBAAqB7C,SAAS0B,eAAe;YACrD5B,OAAO;QACT;WACG2B,sBAAsBzB,SAAS0B;KACnC;AACH,EAAC;AAED,OAAO,MAAMuB,iBAAiBJ,uBAAsB;AAEpD,eAAeI,eAAc"}
1
+ {"version":3,"sources":["../../src/fields/MenuItem.ts"],"sourcesContent":["import type { CollectionSlug, Field, Validate } from 'payload';\n\nimport type { DynamicSource } from '../types.js';\n\nexport type MenuItemFieldOptions = {\n baseUrl?: string;\n disabled?: boolean;\n dynamicSources?: DynamicSource[];\n maxDepth?: number;\n mediaCollection?: CollectionSlug;\n relationTo?: CollectionSlug | CollectionSlug[];\n};\n\nconst validateUrl: Validate = (value, { siblingData }) => {\n const type = (siblingData as any)?.type;\n if (!value) {\n if (\n ['anchor', 'custom', 'external', 'internal', 'mailto', 'tel'].includes(\n type\n )\n ) {\n return 'URL is required for this link type';\n }\n return true;\n }\n\n switch (type) {\n case 'anchor': {\n if (!/^#[\\w-]+$/.test(value as string)) {\n return 'Please enter a valid anchor (e.g. #section-name)';\n }\n break;\n }\n case 'external': {\n try {\n new URL(value as string);\n } catch {\n return 'Please enter a valid URL (e.g. https://example.co.uk)';\n }\n break;\n }\n case 'internal': {\n const path = (value as string).replace(/^https?:\\/\\/[^/]+/, '');\n if (!path.startsWith('/')) {\n return 'Internal paths must start with /';\n }\n break;\n }\n case 'mailto': {\n const email = (value as string).replace(/^mailto:/, '');\n const [local, domain] = email.split('@');\n if (\n !local ||\n !domain ||\n domain.indexOf('.') < 1 ||\n email.split('@').length !== 2\n ) {\n return 'Please enter a valid email address';\n }\n break;\n }\n case 'tel': {\n const raw = (value as string).replace(/^tel:/, '');\n if (!/^\\+?\\d[\\d\\s\\-()]{4,}$/.test(raw)) {\n return 'Please enter a valid phone number';\n }\n break;\n }\n }\n\n return true;\n};\n\nconst LINK_TYPE_OPTIONS = [\n { label: 'Internal', value: 'internal' },\n { label: 'External', value: 'external' },\n { label: 'Reference', value: 'reference' },\n { label: 'Anchor', value: 'anchor' },\n { label: 'Mail To', value: 'mailto' },\n { label: 'TEL', value: 'tel' },\n { label: 'Custom', value: 'custom' },\n];\n\nconst buildFeaturedFields = (options?: MenuItemFieldOptions): Field[] => {\n const baseUrl = options?.baseUrl ?? '';\n const relationTo = options?.relationTo ?? ('pages' as CollectionSlug);\n const fields: Field[] = [\n {\n name: 'heading',\n type: 'text',\n },\n {\n name: 'description',\n type: 'textarea',\n },\n {\n name: 'ctaType',\n type: 'select',\n defaultValue: 'reference',\n label: 'CTA Link Type',\n options: LINK_TYPE_OPTIONS,\n },\n {\n name: 'ctaLabel',\n type: 'text',\n label: 'CTA Label',\n },\n {\n name: 'ctaUrl',\n type: 'text',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n Field: '@foundrykit/menu-plugin/client#UrlField',\n },\n }),\n condition: (_data, siblingData) => siblingData?.ctaType !== 'reference',\n custom: { baseUrl },\n },\n label: 'CTA URL',\n validate: validateUrl,\n },\n {\n name: 'ctaReference',\n type: 'relationship',\n admin: {\n condition: (_data, siblingData) => siblingData?.ctaType === 'reference',\n },\n ...(Array.isArray(relationTo)\n ? { hasMany: false, relationTo }\n : { relationTo }),\n } as Field,\n {\n name: 'ctaTarget',\n type: 'radio',\n defaultValue: '_self',\n label: 'CTA Open in',\n options: [\n { label: 'Same Tab', value: '_self' },\n { label: 'New Tab', value: '_blank' },\n ],\n },\n ];\n if (options?.mediaCollection) {\n fields.unshift({\n name: 'image',\n type: 'upload',\n relationTo: options.mediaCollection,\n } as Field);\n }\n return fields;\n};\n\n/**\n * The simple-by-default link field set shared by every item that behaves like a\n * link: `label`, `type`, `reference`/`url`, plus the \"Options\" and \"Advanced\"\n * collapsible groups. No `itemType` and no nesting fields are included here.\n */\nconst buildLeafLinkFields = (options?: MenuItemFieldOptions): Field[] => {\n const baseUrl = options?.baseUrl ?? '';\n const relationTo = options?.relationTo ?? ('pages' as CollectionSlug);\n\n return [\n {\n name: 'type',\n type: 'select',\n admin: {\n description:\n 'Select the type of link for this menu item. On a mega menu or dropdown this is where the top-level label links to, and is optional.',\n },\n defaultValue: 'reference',\n options: LINK_TYPE_OPTIONS,\n required: true,\n },\n {\n type: 'row',\n fields: [\n {\n name: 'label',\n type: 'text',\n admin: {\n width: '50%',\n },\n required: true,\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n Field: '@foundrykit/menu-plugin/client#UrlField',\n },\n }),\n condition: (_data, siblingData) => {\n return siblingData?.type !== 'reference';\n },\n custom: { baseUrl },\n width: '50%',\n },\n label: 'URL',\n validate: validateUrl,\n },\n {\n name: 'reference',\n type: 'relationship',\n admin: {\n condition: (_data, siblingData) => {\n return siblingData?.type === 'reference';\n },\n width: '50%',\n },\n ...(Array.isArray(relationTo)\n ? { hasMany: false, relationTo }\n : { relationTo }),\n } as Field,\n ],\n },\n {\n type: 'collapsible',\n admin: {\n initCollapsed: true,\n },\n fields: [\n {\n name: 'target',\n type: 'radio',\n defaultValue: '_self',\n label: 'Open in new tab',\n options: [\n { label: 'Same Tab', value: '_self' },\n { label: 'New Tab', value: '_blank' },\n ],\n },\n {\n name: 'displaySurface',\n type: 'select',\n admin: {\n description: 'Controls which navigation surfaces render this item.',\n },\n defaultValue: 'both',\n label: 'Display Surface',\n options: [\n { label: 'Navbar + Drawer (default)', value: 'both' },\n { label: 'Navbar Only', value: 'navbar' },\n { label: 'Drawer Only', value: 'drawer' },\n ],\n },\n ],\n label: 'Options',\n },\n {\n type: 'collapsible',\n admin: {\n initCollapsed: true,\n },\n fields: [\n {\n name: 'visibility',\n type: 'radio',\n defaultValue: 'visible',\n options: [\n { label: 'Visible', value: 'visible' },\n { label: 'Invisible', value: 'invisible' },\n ],\n },\n {\n name: 'rel',\n type: 'text',\n },\n {\n name: 'roles',\n type: 'array',\n fields: [{ name: 'role', type: 'text' }],\n },\n {\n name: 'attrs',\n type: 'textarea',\n },\n ],\n label: 'Advanced',\n },\n ];\n};\n\nconst buildMegaConfigFields = (\n options?: MenuItemFieldOptions,\n currentDepth = 0\n): Field[] => {\n const dynamicSources = options?.dynamicSources ?? [];\n const relationTo = options?.relationTo ?? ('pages' as CollectionSlug);\n\n const parentCollections = [\n ...new Set(dynamicSources.map(source => source.parentCollection)),\n ];\n const singleSource = dynamicSources.length === 1;\n\n // Parent relationship: collapse to a single relationTo string when exactly one\n // source is configured, union when many, fall back to the link relationTo when\n // no dynamic sources are configured.\n const parentRelationTo: CollectionSlug | CollectionSlug[] =\n parentCollections.length === 1\n ? parentCollections[0]\n : parentCollections.length > 1\n ? parentCollections\n : relationTo;\n\n const dynamicSourceOptions = dynamicSources.map(source => ({\n label: source.label,\n value: source.name,\n }));\n\n const isMega = (_data: any, siblingData: any) =>\n siblingData?.itemType === 'mega';\n\n return [\n {\n name: 'megaLayout',\n type: 'select',\n admin: {\n condition: isMega,\n description:\n 'How the mega menu is laid out. \"Reveal\" shows a flat list of rows that reveal their children in a second panel; \"Columns\" renders classic multi-column layout.',\n },\n defaultValue: 'reveal',\n label: 'Mega Menu Layout',\n options: [\n { label: 'Reveal (rows)', value: 'reveal' },\n { label: 'Columns', value: 'columns' },\n ],\n },\n {\n name: 'defaultFeatured',\n type: 'group',\n admin: {\n condition: isMega,\n description:\n 'Fallback featured panel shown when an entry does not provide its own.',\n },\n fields: buildFeaturedFields(options),\n label: 'Default Featured Panel',\n },\n {\n name: 'megaEntries',\n type: 'array',\n admin: {\n condition: isMega,\n description:\n 'A flat list of entries. Each entry is itself a link and can reveal children in a secondary panel.',\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel: '@foundrykit/menu-plugin/client#MegaEntryRowLabel',\n },\n }),\n },\n // Depth-aware, short dbName so the generated Postgres table/relation names\n // stay unique across nesting levels and well under the 63-char identifier\n // limit even when consumers raise `maxDepth`.\n dbName: `me${currentDepth}`,\n fields: [\n ...buildLeafLinkFields(options),\n {\n name: 'source',\n type: 'select',\n admin: {\n description: \"Where this entry's children come from.\",\n },\n defaultValue: 'manual',\n options: [\n { label: 'Manual', value: 'manual' },\n { label: 'Dynamic (from a related collection)', value: 'dynamic' },\n ],\n required: true,\n },\n {\n name: 'children',\n type: 'array',\n admin: {\n condition: (_data, siblingData) =>\n siblingData?.source !== 'dynamic',\n description:\n 'Items revealed in the secondary panel when this entry is hovered or selected.',\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel:\n '@foundrykit/menu-plugin/client#SubMenuItemRowLabel',\n },\n }),\n },\n dbName: `mc${currentDepth}`,\n fields: buildLeafLinkFields(options),\n label: 'Children',\n },\n {\n name: 'dynamicSource',\n type: 'select',\n admin: {\n condition: (_data, siblingData) =>\n siblingData?.source === 'dynamic',\n // Hidden and auto-set when exactly one source is configured.\n hidden: singleSource,\n },\n ...(singleSource ? { defaultValue: dynamicSources[0]?.name } : {}),\n label: 'Dynamic Source',\n options: dynamicSourceOptions,\n },\n {\n name: 'parent',\n type: 'relationship',\n admin: {\n condition: (_data, siblingData) =>\n siblingData?.source === 'dynamic',\n description:\n 'The parent document whose related children populate this entry.',\n },\n ...(Array.isArray(parentRelationTo)\n ? { hasMany: false, relationTo: parentRelationTo }\n : { relationTo: parentRelationTo }),\n } as Field,\n {\n name: 'featured',\n type: 'group',\n admin: {\n description:\n \"The featured panel shown alongside this entry's children.\",\n },\n fields: [\n {\n name: 'mode',\n type: 'select',\n defaultValue: 'inherit',\n options: [\n { label: 'Inherit (use default featured)', value: 'inherit' },\n { label: 'Manual', value: 'manual' },\n {\n label: 'Dynamic (from the related source)',\n value: 'dynamic',\n },\n ],\n },\n ...buildFeaturedFields(options).map(field => {\n if (!('name' in field)) {\n return field;\n }\n const existingCondition = (field as any).admin?.condition;\n return {\n ...field,\n admin: {\n ...(field as any).admin,\n condition: (_data: any, siblingData: any, extra: any) => {\n if (siblingData?.mode !== 'manual') {\n return false;\n }\n return existingCondition\n ? existingCondition(_data, siblingData, extra)\n : true;\n },\n },\n } as Field;\n }),\n ],\n label: 'Featured Panel',\n },\n ],\n label: 'Mega Menu Entries',\n },\n ];\n};\n\nexport const createMenuItemFields = (\n options?: MenuItemFieldOptions,\n currentDepth = 0\n): Field[] => {\n const maxDepth = options?.maxDepth ?? 1;\n const leafLinkFields = buildLeafLinkFields(options);\n\n const canNest = currentDepth < maxDepth;\n\n if (!canNest) {\n return leafLinkFields;\n }\n\n return [\n {\n name: 'itemType',\n type: 'select',\n defaultValue: 'link',\n options: [\n { label: 'Link', value: 'link' },\n { label: 'Dropdown', value: 'dropdown' },\n { label: 'Mega Menu', value: 'mega' },\n ],\n required: true,\n },\n ...leafLinkFields,\n {\n name: currentDepth === 0 ? 'children' : `children_${currentDepth + 1}`,\n type: 'array',\n admin: {\n ...(options?.disabled\n ? {}\n : {\n components: {\n RowLabel: '@foundrykit/menu-plugin/client#SubMenuItemRowLabel',\n },\n }),\n condition: (_data, siblingData) => {\n return siblingData?.itemType === 'dropdown';\n },\n },\n fields: createMenuItemFields(options, currentDepth + 1),\n label: 'Children',\n },\n ...buildMegaConfigFields(options, currentDepth),\n ];\n};\n\nexport const menuItemFields = createMenuItemFields();\n\nexport default menuItemFields;\n"],"names":["validateUrl","value","siblingData","type","includes","test","URL","path","replace","startsWith","email","local","domain","split","indexOf","length","raw","LINK_TYPE_OPTIONS","label","buildFeaturedFields","options","baseUrl","relationTo","fields","name","defaultValue","admin","disabled","components","Field","condition","_data","ctaType","custom","validate","Array","isArray","hasMany","mediaCollection","unshift","buildLeafLinkFields","description","required","width","initCollapsed","buildMegaConfigFields","currentDepth","dynamicSources","parentCollections","Set","map","source","parentCollection","singleSource","parentRelationTo","dynamicSourceOptions","isMega","itemType","RowLabel","dbName","hidden","field","existingCondition","extra","mode","createMenuItemFields","maxDepth","leafLinkFields","canNest","menuItemFields"],"mappings":"AAaA,MAAMA,cAAwB,CAACC,OAAO,EAAEC,WAAW,EAAE;IACnD,MAAMC,OAAQD,aAAqBC;IACnC,IAAI,CAACF,OAAO;QACV,IACE;YAAC;YAAU;YAAU;YAAY;YAAY;YAAU;SAAM,CAACG,QAAQ,CACpED,OAEF;YACA,OAAO;QACT;QACA,OAAO;IACT;IAEA,OAAQA;QACN,KAAK;YAAU;gBACb,IAAI,CAAC,YAAYE,IAAI,CAACJ,QAAkB;oBACtC,OAAO;gBACT;gBACA;YACF;QACA,KAAK;YAAY;gBACf,IAAI;oBACF,IAAIK,IAAIL;gBACV,EAAE,OAAM;oBACN,OAAO;gBACT;gBACA;YACF;QACA,KAAK;YAAY;gBACf,MAAMM,OAAO,AAACN,MAAiBO,OAAO,CAAC,qBAAqB;gBAC5D,IAAI,CAACD,KAAKE,UAAU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BACL5B,WAAW,CAACC,OAAO7B;oBACjB,OAAOA,aAAauD,aAAa;gBACnC;YACF;YACAlC,QAAQ0C,qBAAqB7C,SAAS0B,eAAe;YACrD5B,OAAO;QACT;WACG2B,sBAAsBzB,SAAS0B;KACnC;AACH,EAAE;AAEF,OAAO,MAAMuB,iBAAiBJ,uBAAuB;AAErD,eAAeI,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/resolveDynamicMenu.ts"],"sourcesContent":["import type { CollectionAfterReadHook, Payload, PayloadRequest } from 'payload'\n\nimport type { DynamicSource } from '../types.js'\n\nexport type ResolveDynamicMenuOptions = {\n /** depth used when querying children (kept low to bound relationship population) */\n childrenDepth?: number\n dynamicSources?: DynamicSource[]\n}\n\nconst getByPath = (doc: Record<string, unknown> | undefined, path?: string): unknown => {\n if (!doc || !path) {return undefined}\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc && typeof acc === 'object') {\n return (acc as Record<string, unknown>)[key]\n }\n return undefined\n }, doc)\n}\n\nconst extractParentId = (parent: unknown): string | undefined => {\n if (!parent) {return undefined}\n if (typeof parent === 'string' || typeof parent === 'number') {return String(parent)}\n if (typeof parent === 'object') {\n // Polymorphic relationship: { relationTo, value }\n if ('value' in parent) {\n const value = (parent as { value: unknown }).value\n if (value && typeof value === 'object' && 'id' in value) {\n return String((value as { id: unknown }).id)\n }\n return typeof value === 'string' || typeof value === 'number'\n ? String(value)\n : undefined\n }\n if ('id' in parent) {return String((parent as { id: unknown }).id)}\n }\n return undefined\n}\n\nconst resolveFeaturedFromDoc = (\n doc: Record<string, unknown> | undefined,\n featured?: DynamicSource['featured'],\n): Record<string, unknown> | undefined => {\n if (!doc || !featured) {return undefined}\n\n const image = getByPath(doc, featured.imageField)\n const heading = getByPath(doc, featured.headingField)\n const description = getByPath(doc, featured.descriptionField)\n\n // Omit the featured object entirely when none of the meaningful fields resolve.\n if (image === undefined && heading === undefined && description === undefined) {\n return undefined\n }\n\n const resolved: Record<string, unknown> = {}\n if (image !== undefined) {resolved.image = image}\n if (heading !== undefined) {resolved.heading = heading}\n if (description !== undefined) {resolved.description = description}\n if (featured.ctaHrefBuilder) {\n try {\n resolved.ctaUrl = featured.ctaHrefBuilder(doc)\n } catch {\n // ignore CTA build failures\n }\n }\n if (featured.ctaLabel) {resolved.ctaLabel = featured.ctaLabel}\n\n return resolved\n}\n\nconst resolveEntry = async ({\n childrenDepth,\n entry,\n locale,\n payload,\n req,\n source,\n}: {\n childrenDepth: number\n entry: Record<string, unknown>\n locale: string | undefined\n payload: Payload\n req: PayloadRequest\n source: DynamicSource\n}): Promise<void> => {\n const parentId = extractParentId(entry.parent)\n\n if (!parentId) {\n entry.children = []\n return\n }\n\n const result = await payload.find({\n collection: source.collection,\n depth: childrenDepth,\n // Default to unlimited (Payload treats `0` as \"return all\") so menus are\n // never silently truncated to Payload's default page size of 10.\n limit: source.limit ?? 0,\n locale: locale as never,\n req,\n sort: source.sort,\n where: {\n [source.parentField]: { equals: parentId },\n },\n })\n\n entry.children = result.docs.map((doc) => {\n const record = doc as Record<string, unknown>\n const child: Record<string, unknown> = {\n id: record.id,\n type: 'custom',\n label: getByPath(record, source.labelField),\n source: 'manual',\n url: source.hrefBuilder(record),\n }\n if (source.featured) {\n const childFeatured = resolveFeaturedFromDoc(record, source.featured)\n if (childFeatured) {child.featured = { ...childFeatured, mode: 'manual' }}\n }\n return child\n })\n\n // Resolve the entry-level featured panel from the parent doc (or first child)\n // when the entry is configured to derive it dynamically.\n const featuredMode = (entry.featured as Record<string, unknown> | undefined)?.mode\n if (featuredMode === 'dynamic' && source.featured) {\n let parentDoc = entry.parent as Record<string, unknown> | undefined\n if (!parentDoc || typeof parentDoc !== 'object' || !('id' in parentDoc)) {\n try {\n parentDoc = (await payload.findByID({\n id: parentId,\n collection: source.parentCollection,\n depth: childrenDepth,\n locale: locale as never,\n req,\n })) as Record<string, unknown>\n } catch {\n parentDoc = undefined\n }\n }\n const resolvedFeatured =\n resolveFeaturedFromDoc(parentDoc, source.featured) ??\n resolveFeaturedFromDoc(result.docs[0] as Record<string, unknown>, source.featured)\n if (resolvedFeatured) {\n entry.featured = { ...resolvedFeatured, mode: 'dynamic' }\n }\n }\n}\n\nconst walkItems = async ({\n childrenDepth,\n items,\n locale,\n payload,\n req,\n soleSource,\n sourcesByName,\n}: {\n childrenDepth: number\n items: unknown\n locale: string | undefined\n payload: Payload\n req: PayloadRequest\n soleSource?: DynamicSource\n sourcesByName: Map<string, DynamicSource>\n}): Promise<void> => {\n if (!Array.isArray(items)) {return}\n\n for (const rawItem of items) {\n if (!rawItem || typeof rawItem !== 'object') {continue}\n const item = rawItem as Record<string, unknown>\n\n // Recurse into dropdown children.\n if (item.itemType === 'dropdown') {\n await walkItems({\n childrenDepth,\n items: item.children,\n locale,\n payload,\n req,\n soleSource,\n sourcesByName,\n })\n }\n\n if (item.itemType !== 'mega' || !Array.isArray(item.megaEntries)) {continue}\n\n for (const rawEntry of item.megaEntries) {\n if (!rawEntry || typeof rawEntry !== 'object') {continue}\n const entry = rawEntry as Record<string, unknown>\n if (entry.source !== 'dynamic') {continue}\n\n const source =\n (typeof entry.dynamicSource === 'string'\n ? sourcesByName.get(entry.dynamicSource)\n : undefined) ?? soleSource\n\n if (!source) {\n payload.logger?.warn?.(\n `[menu-plugin] Unknown dynamic source \"${String(entry.dynamicSource)}\"; resolving to empty children.`,\n )\n entry.children = []\n continue\n }\n\n try {\n await resolveEntry({ childrenDepth, entry, locale, payload, req, source })\n } catch (error) {\n payload.logger?.error?.(\n `[menu-plugin] Failed to resolve dynamic menu entry from source \"${source.name}\": ${String(error)}`,\n )\n entry.children = []\n }\n }\n }\n}\n\n/**\n * Build an `afterRead` collection hook that expands dynamic mega entries by\n * querying their configured related collection. Read-only, idempotent, locale\n * aware, and degrades to empty children on any misconfiguration or error.\n */\nexport const createResolveDynamicMenuHook = (\n options?: ResolveDynamicMenuOptions,\n): CollectionAfterReadHook => {\n const dynamicSources = options?.dynamicSources ?? []\n const childrenDepth = options?.childrenDepth ?? 1\n const sourcesByName = new Map(dynamicSources.map((source) => [source.name, source]))\n const soleSource = dynamicSources.length === 1 ? dynamicSources[0] : undefined\n\n return async ({ doc, req }) => {\n if (!doc || typeof doc !== 'object') {return doc}\n if (dynamicSources.length === 0) {return doc}\n\n await walkItems({\n childrenDepth,\n items: (doc as Record<string, unknown>).items,\n locale: req?.locale ?? undefined,\n payload: req.payload,\n req,\n soleSource,\n sourcesByName,\n })\n\n return doc\n }\n}\n"],"names":["getByPath","doc","path","undefined","split","reduce","acc","key","extractParentId","parent","String","value","id","resolveFeaturedFromDoc","featured","image","imageField","heading","headingField","description","descriptionField","resolved","ctaHrefBuilder","ctaUrl","ctaLabel","resolveEntry","childrenDepth","entry","locale","payload","req","source","parentId","children","result","find","collection","depth","limit","sort","where","parentField","equals","docs","map","record","child","type","label","labelField","url","hrefBuilder","childFeatured","mode","featuredMode","parentDoc","findByID","parentCollection","resolvedFeatured","walkItems","items","soleSource","sourcesByName","Array","isArray","rawItem","item","itemType","megaEntries","rawEntry","dynamicSource","get","logger","warn","error","name","createResolveDynamicMenuHook","options","dynamicSources","Map","length"],"mappings":"AAUA,MAAMA,YAAY,CAACC,KAA0CC;IAC3D,IAAI,CAACD,OAAO,CAACC,MAAM;QAAC,OAAOC;IAAS;IACpC,OAAOD,KAAKE,KAAK,CAAC,KAAKC,MAAM,CAAU,CAACC,KAAKC;QAC3C,IAAID,OAAO,OAAOA,QAAQ,UAAU;YAClC,OAAO,AAACA,GAA+B,CAACC,IAAI;QAC9C;QACA,OAAOJ;IACT,GAAGF;AACL;AAEA,MAAMO,kBAAkB,CAACC;IACvB,IAAI,CAACA,QAAQ;QAAC,OAAON;IAAS;IAC9B,IAAI,OAAOM,WAAW,YAAY,OAAOA,WAAW,UAAU;QAAC,OAAOC,OAAOD;IAAO;IACpF,IAAI,OAAOA,WAAW,UAAU;QAC9B,kDAAkD;QAClD,IAAI,WAAWA,QAAQ;YACrB,MAAME,QAAQ,AAACF,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gBAEvG3C,MAAMM,QAAQ,GAAG,EAAE;gBACnB;YACF;YAEA,IAAI;gBACF,MAAMR,aAAa;oBAAEC;oBAAeC;oBAAOC;oBAAQC;oBAASC;oBAAKC;gBAAO;YAC1E,EAAE,OAAO2C,OAAO;gBACd7C,QAAQ2C,MAAM,EAAEE,QACd,CAAC,gEAAgE,EAAE3C,OAAO4C,IAAI,CAAC,GAAG,EAAEjE,OAAOgE,QAAQ;gBAErG/C,MAAMM,QAAQ,GAAG,EAAE;YACrB;QACF;IACF;AACF;AAEA;;;;CAIC,GACD,OAAO,MAAM2C,+BAA+B,CAC1CC;IAEA,MAAMC,iBAAiBD,SAASC,kBAAkB,EAAE;IACpD,MAAMpD,gBAAgBmD,SAASnD,iBAAiB;IAChD,MAAMoC,gBAAgB,IAAIiB,IAAID,eAAelC,GAAG,CAAC,CAACb,SAAW;YAACA,OAAO4C,IAAI;YAAE5C;SAAO;IAClF,MAAM8B,aAAaiB,eAAeE,MAAM,KAAK,IAAIF,cAAc,CAAC,EAAE,GAAG3E;IAErE,OAAO,OAAO,EAAEF,GAAG,EAAE6B,GAAG,EAAE;QACxB,IAAI,CAAC7B,OAAO,OAAOA,QAAQ,UAAU;YAAC,OAAOA;QAAG;QAChD,IAAI6E,eAAeE,MAAM,KAAK,GAAG;YAAC,OAAO/E;QAAG;QAE5C,MAAM0D,UAAU;YACdjC;YACAkC,OAAO,AAAC3D,IAAgC2D,KAAK;YAC7ChC,QAAQE,KAAKF,UAAUzB;YACvB0B,SAASC,IAAID,OAAO;YACpBC;YACA+B;YACAC;QACF;QAEA,OAAO7D;IACT;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/resolveDynamicMenu.ts"],"sourcesContent":["import type { CollectionAfterReadHook, Payload, PayloadRequest } from 'payload';\n\nimport type { DynamicSource } from '../types.js';\n\nexport type ResolveDynamicMenuOptions = {\n /** depth used when querying children (kept low to bound relationship population) */\n childrenDepth?: number;\n dynamicSources?: DynamicSource[];\n};\n\nconst getByPath = (\n doc: Record<string, unknown> | undefined,\n path?: string\n): unknown => {\n if (!doc || !path) {\n return undefined;\n }\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc && typeof acc === 'object') {\n return (acc as Record<string, unknown>)[key];\n }\n return undefined;\n }, doc);\n};\n\nconst extractParentId = (parent: unknown): string | undefined => {\n if (!parent) {\n return undefined;\n }\n if (typeof parent === 'string' || typeof parent === 'number') {\n return String(parent);\n }\n if (typeof parent === 'object') {\n // Polymorphic relationship: { relationTo, value }\n if ('value' in parent) {\n const value = (parent as { value: unknown }).value;\n if (value && typeof value === 'object' && 'id' in value) {\n return String((value as { id: unknown }).id);\n }\n return typeof value === 'string' || typeof value === 'number'\n ? String(value)\n : undefined;\n }\n if ('id' in parent) {\n return String((parent as { id: unknown }).id);\n }\n }\n return undefined;\n};\n\nconst resolveFeaturedFromDoc = (\n doc: Record<string, unknown> | undefined,\n featured?: DynamicSource['featured']\n): Record<string, unknown> | undefined => {\n if (!doc || !featured) {\n return undefined;\n }\n\n const image = getByPath(doc, featured.imageField);\n const heading = getByPath(doc, featured.headingField);\n const description = getByPath(doc, featured.descriptionField);\n\n // Omit the featured object entirely when none of the meaningful fields resolve.\n if (\n image === undefined &&\n heading === undefined &&\n description === undefined\n ) {\n return undefined;\n }\n\n const resolved: Record<string, unknown> = {};\n if (image !== undefined) {\n resolved.image = image;\n }\n if (heading !== undefined) {\n resolved.heading = heading;\n }\n if (description !== undefined) {\n resolved.description = description;\n }\n if (featured.ctaHrefBuilder) {\n try {\n resolved.ctaUrl = featured.ctaHrefBuilder(doc);\n } catch {\n // ignore CTA build failures\n }\n }\n if (featured.ctaLabel) {\n resolved.ctaLabel = featured.ctaLabel;\n }\n\n return resolved;\n};\n\nconst resolveEntry = async ({\n childrenDepth,\n entry,\n locale,\n payload,\n req,\n source,\n}: {\n childrenDepth: number;\n entry: Record<string, unknown>;\n locale: string | undefined;\n payload: Payload;\n req: PayloadRequest;\n source: DynamicSource;\n}): Promise<void> => {\n const parentId = extractParentId(entry.parent);\n\n if (!parentId) {\n entry.children = [];\n return;\n }\n\n const result = await payload.find({\n collection: source.collection,\n depth: childrenDepth,\n // Default to unlimited (Payload treats `0` as \"return all\") so menus are\n // never silently truncated to Payload's default page size of 10.\n limit: source.limit ?? 0,\n locale: locale as never,\n req,\n sort: source.sort,\n where: {\n [source.parentField]: { equals: parentId },\n },\n });\n\n entry.children = result.docs.map(doc => {\n const record = doc as Record<string, unknown>;\n const child: Record<string, unknown> = {\n id: record.id,\n type: 'custom',\n label: getByPath(record, source.labelField),\n source: 'manual',\n url: source.hrefBuilder(record),\n };\n if (source.featured) {\n const childFeatured = resolveFeaturedFromDoc(record, source.featured);\n if (childFeatured) {\n child.featured = { ...childFeatured, mode: 'manual' };\n }\n }\n return child;\n });\n\n // Resolve the entry-level featured panel from the parent doc (or first child)\n // when the entry is configured to derive it dynamically.\n const featuredMode = (entry.featured as Record<string, unknown> | undefined)\n ?.mode;\n if (featuredMode === 'dynamic' && source.featured) {\n let parentDoc = entry.parent as Record<string, unknown> | undefined;\n if (!parentDoc || typeof parentDoc !== 'object' || !('id' in parentDoc)) {\n try {\n parentDoc = (await payload.findByID({\n id: parentId,\n collection: source.parentCollection,\n depth: childrenDepth,\n locale: locale as never,\n req,\n })) as Record<string, unknown>;\n } catch {\n parentDoc = undefined;\n }\n }\n const resolvedFeatured =\n resolveFeaturedFromDoc(parentDoc, source.featured) ??\n resolveFeaturedFromDoc(\n result.docs[0] as Record<string, unknown>,\n source.featured\n );\n if (resolvedFeatured) {\n entry.featured = { ...resolvedFeatured, mode: 'dynamic' };\n }\n }\n};\n\nconst walkItems = async ({\n childrenDepth,\n items,\n locale,\n payload,\n req,\n soleSource,\n sourcesByName,\n}: {\n childrenDepth: number;\n items: unknown;\n locale: string | undefined;\n payload: Payload;\n req: PayloadRequest;\n soleSource?: DynamicSource;\n sourcesByName: Map<string, DynamicSource>;\n}): Promise<void> => {\n if (!Array.isArray(items)) {\n return;\n }\n\n for (const rawItem of items) {\n if (!rawItem || typeof rawItem !== 'object') {\n continue;\n }\n const item = rawItem as Record<string, unknown>;\n\n // Recurse into dropdown children.\n if (item.itemType === 'dropdown') {\n await walkItems({\n childrenDepth,\n items: item.children,\n locale,\n payload,\n req,\n soleSource,\n sourcesByName,\n });\n }\n\n if (item.itemType !== 'mega' || !Array.isArray(item.megaEntries)) {\n continue;\n }\n\n for (const rawEntry of item.megaEntries) {\n if (!rawEntry || typeof rawEntry !== 'object') {\n continue;\n }\n const entry = rawEntry as Record<string, unknown>;\n if (entry.source !== 'dynamic') {\n continue;\n }\n\n const source =\n (typeof entry.dynamicSource === 'string'\n ? sourcesByName.get(entry.dynamicSource)\n : undefined) ?? soleSource;\n\n if (!source) {\n payload.logger?.warn?.(\n `[menu-plugin] Unknown dynamic source \"${String(entry.dynamicSource)}\"; resolving to empty children.`\n );\n entry.children = [];\n continue;\n }\n\n try {\n await resolveEntry({\n childrenDepth,\n entry,\n locale,\n payload,\n req,\n source,\n });\n } catch (error) {\n payload.logger?.error?.(\n `[menu-plugin] Failed to resolve dynamic menu entry from source \"${source.name}\": ${String(error)}`\n );\n entry.children = [];\n }\n }\n }\n};\n\n/**\n * Build an `afterRead` collection hook that expands dynamic mega entries by\n * querying their configured related collection. Read-only, idempotent, locale\n * aware, and degrades to empty children on any misconfiguration or error.\n */\nexport const createResolveDynamicMenuHook = (\n options?: ResolveDynamicMenuOptions\n): CollectionAfterReadHook => {\n const dynamicSources = options?.dynamicSources ?? [];\n const childrenDepth = options?.childrenDepth ?? 1;\n const sourcesByName = new Map(\n dynamicSources.map(source => [source.name, source])\n );\n const soleSource =\n dynamicSources.length === 1 ? dynamicSources[0] : undefined;\n\n return async ({ doc, req }) => {\n if (!doc || typeof doc !== 'object') {\n return doc;\n }\n if (dynamicSources.length === 0) {\n return doc;\n }\n\n await walkItems({\n childrenDepth,\n items: (doc as Record<string, unknown>).items,\n locale: req?.locale ?? undefined,\n payload: req.payload,\n req,\n soleSource,\n sourcesByName,\n });\n\n return doc;\n };\n};\n"],"names":["getByPath","doc","path","undefined","split","reduce","acc","key","extractParentId","parent","String","value","id","resolveFeaturedFromDoc","featured","image","imageField","heading","headingField","description","descriptionField","resolved","ctaHrefBuilder","ctaUrl","ctaLabel","resolveEntry","childrenDepth","entry","locale","payload","req","source","parentId","children","result","find","collection","depth","limit","sort","where","parentField","equals","docs","map","record","child","type","label","labelField","url","hrefBuilder","childFeatured","mode","featuredMode","parentDoc","findByID","parentCollection","resolvedFeatured","walkItems","items","soleSource","sourcesByName","Array","isArray","rawItem","item","itemType","megaEntries","rawEntry","dynamicSource","get","logger","warn","error","name","createResolveDynamicMenuHook","options","dynamicSources","Map","length"],"mappings":"AAUA,MAAMA,YAAY,CAChBC,KACAC;IAEA,IAAI,CAACD,OAAO,CAACC,MAAM;QACjB,OAAOC;IACT;IACA,OAAOD,KAAKE,KAAK,CAAC,KAAKC,MAAM,CAAU,CAACC,KAAKC;QAC3C,IAAID,OAAO,OAAOA,QAAQ,UAAU;YAClC,OAAO,AAACA,GAA+B,CAACC,IAAI;QAC9C;QACA,OAAOJ;IACT,GAAGF;AACL;AAEA,MAAMO,kBAAkB,CAACC;IACvB,IAAI,CAACA,QAAQ;QACX,OAAON;IACT;IACA,IAAI,OAAOM,WAAW,YAAY,OAAOA,WAAW,UAAU;QAC5D,OAAOC,OAAOD;IAChB;IACA,IAAI,OAAOA,WAAW,UAAU;QAC9B,kDAAkD;QAClD,IAAI,WAAWA,QAAQ;YACrB,MAAME,QAAQ,AAACF,OAA8BE,KAAK;YAClD,IAAIA,SAAS,OAAOA,UAAU,YAAY,QAAQA,OAAO;gBACvD,OAAOD,OAAO,AAACC,MAA0BC,EAAE;YAC7C;YACA,OAAO,OAAOD,UAAU,YAAY,OAAOA,UAAU,WACjDD,OAAOC,SACPR;QACN;QACA,IAAI,QAAQM,QAAQ;YAClB,OAAOC,OAAO,AAACD,OAA2BG,EAAE;QAC9C;IACF;IACA,OAAOT;AACT;AAEA,MAAMU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ACF;IACF;AACF;AAEA;;;;CAIC,GACD,OAAO,MAAM2C,+BAA+B,CAC1CC;IAEA,MAAMC,iBAAiBD,SAASC,kBAAkB,EAAE;IACpD,MAAMpD,gBAAgBmD,SAASnD,iBAAiB;IAChD,MAAMoC,gBAAgB,IAAIiB,IACxBD,eAAelC,GAAG,CAACb,CAAAA,SAAU;YAACA,OAAO4C,IAAI;YAAE5C;SAAO;IAEpD,MAAM8B,aACJiB,eAAeE,MAAM,KAAK,IAAIF,cAAc,CAAC,EAAE,GAAG3E;IAEpD,OAAO,OAAO,EAAEF,GAAG,EAAE6B,GAAG,EAAE;QACxB,IAAI,CAAC7B,OAAO,OAAOA,QAAQ,UAAU;YACnC,OAAOA;QACT;QACA,IAAI6E,eAAeE,MAAM,KAAK,GAAG;YAC/B,OAAO/E;QACT;QAEA,MAAM0D,UAAU;YACdjC;YACAkC,OAAO,AAAC3D,IAAgC2D,KAAK;YAC7ChC,QAAQE,KAAKF,UAAUzB;YACvB0B,SAASC,IAAID,OAAO;YACpBC;YACA+B;YACAC;QACF;QAEA,OAAO7D;IACT;AACF,EAAE"}
@@ -0,0 +1,28 @@
1
+ import type { CollectionBeforeChangeHook } from 'payload';
2
+ /**
3
+ * Strip read-time-resolved data from dynamic mega entries before write.
4
+ *
5
+ * `createResolveDynamicMenuHook` (afterRead) fills each dynamic entry's
6
+ * `children` by querying the related collection, setting every child's `id` to
7
+ * the *related* document's id. The mega-children array is admin-hidden for
8
+ * dynamic entries (`admin.condition: source !== 'dynamic'`), but `condition`
9
+ * only hides the UI — the resolved rows remain in the admin form state and are
10
+ * sent back on save. Payload then validates each row's `id` against the array's
11
+ * own id column and rejects the foreign id with "The following field is invalid:
12
+ * id" (HTTP 400).
13
+ *
14
+ * This `beforeChange` hook drops that resolved data so it is never persisted.
15
+ * Dynamic children (and any dynamically-derived featured panel) are re-resolved
16
+ * on every read, so they must not be stored. It runs before field validation
17
+ * (`beforeChange` – Collection precedes `beforeChange` – Fields), so the offending
18
+ * rows are gone before Payload validates them.
19
+ */
20
+ type AnyDoc = Record<string, unknown>;
21
+ /** Pure helper: mutate and return `data`, stripping resolved dynamic-entry data. */
22
+ export declare const stripDynamicMenuChildren: (data: AnyDoc | null | undefined) => AnyDoc | null | undefined;
23
+ /**
24
+ * `beforeChange` collection hook that removes read-time-resolved data from
25
+ * dynamic mega entries so foreign ids never reach Payload's id validation.
26
+ */
27
+ export declare const stripDynamicMenuChildrenHook: CollectionBeforeChangeHook;
28
+ export {};
@@ -0,0 +1,50 @@
1
+ const stripEntries = (items)=>{
2
+ if (!Array.isArray(items)) {
3
+ return;
4
+ }
5
+ for (const rawItem of items){
6
+ if (!rawItem || typeof rawItem !== 'object') {
7
+ continue;
8
+ }
9
+ const item = rawItem;
10
+ // Recurse into dropdown children, same as the resolver's walker.
11
+ if (item.itemType === 'dropdown') {
12
+ stripEntries(item.children);
13
+ }
14
+ if (item.itemType !== 'mega' || !Array.isArray(item.megaEntries)) {
15
+ continue;
16
+ }
17
+ for (const rawEntry of item.megaEntries){
18
+ if (!rawEntry || typeof rawEntry !== 'object') {
19
+ continue;
20
+ }
21
+ const entry = rawEntry;
22
+ if (entry.source !== 'dynamic') {
23
+ continue;
24
+ }
25
+ // Resolved children carry the related doc's id, not a valid array-row id.
26
+ delete entry.children;
27
+ // A dynamically-derived featured panel is also resolved on read; keep only
28
+ // its mode so the stored value doesn't masquerade as manual data.
29
+ const featured = entry.featured;
30
+ if (featured && featured.mode === 'dynamic') {
31
+ entry.featured = {
32
+ mode: 'dynamic'
33
+ };
34
+ }
35
+ }
36
+ }
37
+ };
38
+ /** Pure helper: mutate and return `data`, stripping resolved dynamic-entry data. */ export const stripDynamicMenuChildren = (data)=>{
39
+ if (!data || typeof data !== 'object') {
40
+ return data;
41
+ }
42
+ stripEntries(data.items);
43
+ return data;
44
+ };
45
+ /**
46
+ * `beforeChange` collection hook that removes read-time-resolved data from
47
+ * dynamic mega entries so foreign ids never reach Payload's id validation.
48
+ */ export const stripDynamicMenuChildrenHook = ({ data })=>stripDynamicMenuChildren(data);
49
+
50
+ //# sourceMappingURL=stripDynamicMenuChildren.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hooks/stripDynamicMenuChildren.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload';\n\n/**\n * Strip read-time-resolved data from dynamic mega entries before write.\n *\n * `createResolveDynamicMenuHook` (afterRead) fills each dynamic entry's\n * `children` by querying the related collection, setting every child's `id` to\n * the *related* document's id. The mega-children array is admin-hidden for\n * dynamic entries (`admin.condition: source !== 'dynamic'`), but `condition`\n * only hides the UI — the resolved rows remain in the admin form state and are\n * sent back on save. Payload then validates each row's `id` against the array's\n * own id column and rejects the foreign id with \"The following field is invalid:\n * id\" (HTTP 400).\n *\n * This `beforeChange` hook drops that resolved data so it is never persisted.\n * Dynamic children (and any dynamically-derived featured panel) are re-resolved\n * on every read, so they must not be stored. It runs before field validation\n * (`beforeChange` – Collection precedes `beforeChange` – Fields), so the offending\n * rows are gone before Payload validates them.\n */\n\ntype AnyDoc = Record<string, unknown>;\n\nconst stripEntries = (items: unknown): void => {\n if (!Array.isArray(items)) {\n return;\n }\n\n for (const rawItem of items) {\n if (!rawItem || typeof rawItem !== 'object') {\n continue;\n }\n const item = rawItem as AnyDoc;\n\n // Recurse into dropdown children, same as the resolver's walker.\n if (item.itemType === 'dropdown') {\n stripEntries(item.children);\n }\n\n if (item.itemType !== 'mega' || !Array.isArray(item.megaEntries)) {\n continue;\n }\n\n for (const rawEntry of item.megaEntries) {\n if (!rawEntry || typeof rawEntry !== 'object') {\n continue;\n }\n const entry = rawEntry as AnyDoc;\n if (entry.source !== 'dynamic') {\n continue;\n }\n\n // Resolved children carry the related doc's id, not a valid array-row id.\n delete entry.children;\n\n // A dynamically-derived featured panel is also resolved on read; keep only\n // its mode so the stored value doesn't masquerade as manual data.\n const featured = entry.featured as AnyDoc | undefined;\n if (featured && featured.mode === 'dynamic') {\n entry.featured = { mode: 'dynamic' };\n }\n }\n }\n};\n\n/** Pure helper: mutate and return `data`, stripping resolved dynamic-entry data. */\nexport const stripDynamicMenuChildren = (\n data: AnyDoc | null | undefined\n): AnyDoc | null | undefined => {\n if (!data || typeof data !== 'object') {\n return data;\n }\n stripEntries((data as AnyDoc).items);\n return data;\n};\n\n/**\n * `beforeChange` collection hook that removes read-time-resolved data from\n * dynamic mega entries so foreign ids never reach Payload's id validation.\n */\nexport const stripDynamicMenuChildrenHook: CollectionBeforeChangeHook = ({\n data,\n}) => stripDynamicMenuChildren(data as AnyDoc) as never;\n"],"names":["stripEntries","items","Array","isArray","rawItem","item","itemType","children","megaEntries","rawEntry","entry","source","featured","mode","stripDynamicMenuChildren","data","stripDynamicMenuChildrenHook"],"mappings":"AAuBA,MAAMA,eAAe,CAACC;IACpB,IAAI,CAACC,MAAMC,OAAO,CAACF,QAAQ;QACzB;IACF;IAEA,KAAK,MAAMG,WAAWH,MAAO;QAC3B,IAAI,CAACG,WAAW,OAAOA,YAAY,UAAU;YAC3C;QACF;QACA,MAAMC,OAAOD;QAEb,iEAAiE;QACjE,IAAIC,KAAKC,QAAQ,KAAK,YAAY;YAChCN,aAAaK,KAAKE,QAAQ;QAC5B;QAEA,IAAIF,KAAKC,QAAQ,KAAK,UAAU,CAACJ,MAAMC,OAAO,CAACE,KAAKG,WAAW,GAAG;YAChE;QACF;QAEA,KAAK,MAAMC,YAAYJ,KAAKG,WAAW,CAAE;YACvC,IAAI,CAACC,YAAY,OAAOA,aAAa,UAAU;gBAC7C;YACF;YACA,MAAMC,QAAQD;YACd,IAAIC,MAAMC,MAAM,KAAK,WAAW;gBAC9B;YACF;YAEA,0EAA0E;YAC1E,OAAOD,MAAMH,QAAQ;YAErB,2EAA2E;YAC3E,kEAAkE;YAClE,MAAMK,WAAWF,MAAME,QAAQ;YAC/B,IAAIA,YAAYA,SAASC,IAAI,KAAK,WAAW;gBAC3CH,MAAME,QAAQ,GAAG;oBAAEC,MAAM;gBAAU;YACrC;QACF;IACF;AACF;AAEA,kFAAkF,GAClF,OAAO,MAAMC,2BAA2B,CACtCC;IAEA,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QACrC,OAAOA;IACT;IACAf,aAAa,AAACe,KAAgBd,KAAK;IACnC,OAAOc;AACT,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMC,+BAA2D,CAAC,EACvED,IAAI,EACL,GAAKD,yBAAyBC,MAAyB"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,128 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { stripDynamicMenuChildren } from './stripDynamicMenuChildren.js';
3
+ describe('stripDynamicMenuChildren', ()=>{
4
+ test('removes resolved children from a dynamic mega entry', ()=>{
5
+ const data = {
6
+ items: [
7
+ {
8
+ itemType: 'mega',
9
+ megaEntries: [
10
+ {
11
+ source: 'dynamic',
12
+ // Injected at read time with the related doc's id — this is what
13
+ // fails the array-row id validation on write.
14
+ children: [
15
+ {
16
+ id: 12,
17
+ label: 'Kenya',
18
+ type: 'custom',
19
+ url: '/local-regions/kenya'
20
+ },
21
+ {
22
+ id: 34,
23
+ label: 'Tanzania',
24
+ type: 'custom',
25
+ url: '/local-regions/tanzania'
26
+ }
27
+ ]
28
+ }
29
+ ]
30
+ }
31
+ ]
32
+ };
33
+ stripDynamicMenuChildren(data);
34
+ expect(data.items[0].megaEntries[0]).not.toHaveProperty('children');
35
+ });
36
+ test('leaves manual mega entries untouched', ()=>{
37
+ const children = [
38
+ {
39
+ id: 'abc',
40
+ label: 'Manual',
41
+ type: 'custom',
42
+ url: '/x'
43
+ }
44
+ ];
45
+ const data = {
46
+ items: [
47
+ {
48
+ itemType: 'mega',
49
+ megaEntries: [
50
+ {
51
+ children,
52
+ source: 'manual'
53
+ }
54
+ ]
55
+ }
56
+ ]
57
+ };
58
+ stripDynamicMenuChildren(data);
59
+ expect(data.items[0].megaEntries[0].children).toBe(children);
60
+ });
61
+ test('reduces a dynamically-derived featured panel to just its mode', ()=>{
62
+ const data = {
63
+ items: [
64
+ {
65
+ itemType: 'mega',
66
+ megaEntries: [
67
+ {
68
+ children: [
69
+ {
70
+ id: 1
71
+ }
72
+ ],
73
+ featured: {
74
+ heading: 'Resolved',
75
+ image: {
76
+ id: 9
77
+ },
78
+ mode: 'dynamic'
79
+ },
80
+ source: 'dynamic'
81
+ }
82
+ ]
83
+ }
84
+ ]
85
+ };
86
+ stripDynamicMenuChildren(data);
87
+ expect(data.items[0].megaEntries[0].featured).toEqual({
88
+ mode: 'dynamic'
89
+ });
90
+ });
91
+ test('recurses into dropdown children that contain mega items', ()=>{
92
+ const data = {
93
+ items: [
94
+ {
95
+ children: [
96
+ {
97
+ itemType: 'mega',
98
+ megaEntries: [
99
+ {
100
+ children: [
101
+ {
102
+ id: 7
103
+ }
104
+ ],
105
+ source: 'dynamic'
106
+ }
107
+ ]
108
+ }
109
+ ],
110
+ itemType: 'dropdown'
111
+ }
112
+ ]
113
+ };
114
+ stripDynamicMenuChildren(data);
115
+ expect(data.items[0].children[0].megaEntries[0]).not.toHaveProperty('children');
116
+ });
117
+ test('is a no-op for data without items', ()=>{
118
+ expect(stripDynamicMenuChildren(undefined)).toBeUndefined();
119
+ expect(stripDynamicMenuChildren(null)).toBeNull();
120
+ expect(stripDynamicMenuChildren({
121
+ title: 'x'
122
+ })).toEqual({
123
+ title: 'x'
124
+ });
125
+ });
126
+ });
127
+
128
+ //# sourceMappingURL=stripDynamicMenuChildren.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hooks/stripDynamicMenuChildren.test.ts"],"sourcesContent":["import { describe, expect, test } from 'vitest';\n\nimport { stripDynamicMenuChildren } from './stripDynamicMenuChildren.js';\n\ndescribe('stripDynamicMenuChildren', () => {\n test('removes resolved children from a dynamic mega entry', () => {\n const data = {\n items: [\n {\n itemType: 'mega',\n megaEntries: [\n {\n source: 'dynamic',\n // Injected at read time with the related doc's id — this is what\n // fails the array-row id validation on write.\n children: [\n {\n id: 12,\n label: 'Kenya',\n type: 'custom',\n url: '/local-regions/kenya',\n },\n {\n id: 34,\n label: 'Tanzania',\n type: 'custom',\n url: '/local-regions/tanzania',\n },\n ],\n },\n ],\n },\n ],\n };\n\n stripDynamicMenuChildren(data);\n\n expect(data.items[0].megaEntries[0]).not.toHaveProperty('children');\n });\n\n test('leaves manual mega entries untouched', () => {\n const children = [\n { id: 'abc', label: 'Manual', type: 'custom', url: '/x' },\n ];\n const data = {\n items: [\n { itemType: 'mega', megaEntries: [{ children, source: 'manual' }] },\n ],\n };\n\n stripDynamicMenuChildren(data);\n\n expect(data.items[0].megaEntries[0].children).toBe(children);\n });\n\n test('reduces a dynamically-derived featured panel to just its mode', () => {\n const data = {\n items: [\n {\n itemType: 'mega',\n megaEntries: [\n {\n children: [{ id: 1 }],\n featured: {\n heading: 'Resolved',\n image: { id: 9 },\n mode: 'dynamic',\n },\n source: 'dynamic',\n },\n ],\n },\n ],\n };\n\n stripDynamicMenuChildren(data);\n\n expect(data.items[0].megaEntries[0].featured).toEqual({ mode: 'dynamic' });\n });\n\n test('recurses into dropdown children that contain mega items', () => {\n const data = {\n items: [\n {\n children: [\n {\n itemType: 'mega',\n megaEntries: [{ children: [{ id: 7 }], source: 'dynamic' }],\n },\n ],\n itemType: 'dropdown',\n },\n ],\n };\n\n stripDynamicMenuChildren(data);\n\n expect(data.items[0].children[0].megaEntries[0]).not.toHaveProperty(\n 'children'\n );\n });\n\n test('is a no-op for data without items', () => {\n expect(stripDynamicMenuChildren(undefined)).toBeUndefined();\n expect(stripDynamicMenuChildren(null)).toBeNull();\n expect(stripDynamicMenuChildren({ title: 'x' })).toEqual({ title: 'x' });\n });\n});\n"],"names":["describe","expect","test","stripDynamicMenuChildren","data","items","itemType","megaEntries","source","children","id","label","type","url","not","toHaveProperty","toBe","featured","heading","image","mode","toEqual","undefined","toBeUndefined","toBeNull","title"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AAEhD,SAASC,wBAAwB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AAU;IAC1E;IAEAlB,KAAK,2DAA2D;QAC9D,MAAME,OAAO;YACXC,OAAO;gBACL;oBACEI,UAAU;wBACR;4BACEH,UAAU;4BACVC,aAAa;gCAAC;oCAAEE,UAAU;wCAAC;4CAAEC,IAAI;wCAAE;qCAAE;oCAAEF,QAAQ;gCAAU;6BAAE;wBAC7D;qBACD;oBACDF,UAAU;gBACZ;aACD;QACH;QAEAH,yBAAyBC;QAEzBH,OAAOG,KAAKC,KAAK,CAAC,EAAE,CAACI,QAAQ,CAAC,EAAE,CAACF,WAAW,CAAC,EAAE,EAAEO,GAAG,CAACC,cAAc,CACjE;IAEJ;IAEAb,KAAK,qCAAqC;QACxCD,OAAOE,yBAAyBmB,YAAYC,aAAa;QACzDtB,OAAOE,yBAAyB,OAAOqB,QAAQ;QAC/CvB,OAAOE,yBAAyB;YAAEsB,OAAO;QAAI,IAAIJ,OAAO,CAAC;YAAEI,OAAO;QAAI;IACxE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/useMenu.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { fetchMenu as requestMenu, type FetchMenuOptions, type MenuDocument } from '../fetchMenu.js'\nimport { normalizeMenuLocale } from '../utilities/menuIdentity.js'\n\ntype UseMenuOptions = Omit<FetchMenuOptions, 'fetch'> & {\n fetch?: typeof globalThis.fetch\n}\n\ntype UseMenuResult = {\n error: null | string\n isLoading: boolean\n menu: MenuDocument | null\n refetch: () => Promise<void>\n}\n\ntype ClientCacheEntry = {\n data: MenuDocument\n timestamp: number\n}\n\nconst clientCache = new Map<string, ClientCacheEntry>()\nconst CACHE_TTL = 30_000\n\nconst getDefaultBaseURL = (): string | undefined => {\n if (typeof window === 'undefined') return undefined\n return window.location.origin\n}\n\nconst getCacheKey = ({ apiRoute = '/api', baseURL, depth = 0, locale, slug }: UseMenuOptions): string => {\n return JSON.stringify({\n apiRoute,\n baseURL: baseURL || getDefaultBaseURL(),\n depth,\n locale: normalizeMenuLocale(locale),\n slug,\n })\n}\n\nexport const useMenu = ({\n apiRoute = '/api',\n baseURL,\n depth = 0,\n fetch: fetchImpl,\n locale,\n slug,\n}: UseMenuOptions): UseMenuResult => {\n const [menu, setMenu] = useState<MenuDocument | null>(null)\n const [error, setError] = useState<null | string>(null)\n const [isLoading, setIsLoading] = useState(true)\n const abortRef = useRef<AbortController | null>(null)\n\n const cacheKey = getCacheKey({ apiRoute, baseURL, depth, locale, slug })\n\n const fetchMenu = useCallback(async () => {\n const cached = clientCache.get(cacheKey)\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n setMenu(cached.data)\n setIsLoading(false)\n setError(null)\n return\n }\n\n abortRef.current?.abort()\n const controller = new AbortController()\n abortRef.current = controller\n\n setIsLoading(true)\n setError(null)\n\n try {\n const data = await requestMenu({\n apiRoute,\n baseURL: baseURL || getDefaultBaseURL(),\n depth,\n fetch: async (input, init) =>\n (fetchImpl || globalThis.fetch)(input, {\n ...init,\n signal: controller.signal,\n }),\n locale,\n slug,\n })\n\n clientCache.set(cacheKey, { data, timestamp: Date.now() })\n setMenu(data)\n } catch (err: any) {\n if (err.name !== 'AbortError') {\n setError(err.message)\n }\n } finally {\n setIsLoading(false)\n }\n }, [apiRoute, baseURL, cacheKey, depth, fetchImpl, locale, slug])\n\n useEffect(() => {\n void fetchMenu()\n return () => {\n abortRef.current?.abort()\n }\n }, [fetchMenu])\n\n return { error, isLoading, menu, refetch: fetchMenu }\n}\n"],"names":["useCallback","useEffect","useRef","useState","fetchMenu","requestMenu","normalizeMenuLocale","clientCache","Map","CACHE_TTL","getDefaultBaseURL","window","undefined","location","origin","getCacheKey","apiRoute","baseURL","depth","locale","slug","JSON","stringify","useMenu","fetch","fetchImpl","menu","setMenu","error","setError","isLoading","setIsLoading","abortRef","cacheKey","cached","get","Date","now","timestamp","data","current","abort","controller","AbortController","input","init","globalThis","signal","set","err","name","message","refetch"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAA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AMlC,YAAY;gBAC7BW;gBACAC,SAASA,WAAWP;gBACpBQ;gBACAM,OAAO,OAAOoB,OAAOC,OACnB,AAACpB,CAAAA,aAAaqB,WAAWtB,KAAK,AAAD,EAAGoB,OAAO;wBACrC,GAAGC,IAAI;wBACPE,QAAQL,WAAWK,MAAM;oBAC3B;gBACF5B;gBACAC;YACF;YAEAb,YAAYyC,GAAG,CAACf,UAAU;gBAAEM;gBAAMD,WAAWF,KAAKC,GAAG;YAAG;YACxDV,QAAQY;QACV,EAAE,OAAOU,KAAU;YACjB,IAAIA,IAAIC,IAAI,KAAK,cAAc;gBAC7BrB,SAASoB,IAAIE,OAAO;YACtB;QACF,SAAU;YACRpB,aAAa;QACf;IACF,GAAG;QAACf;QAAUC;QAASgB;QAAUf;QAAOO;QAAWN;QAAQC;KAAK;IAEhEnB,UAAU;QACR,KAAKG;QACL,OAAO;YACL4B,SAASQ,OAAO,EAAEC;QACpB;IACF,GAAG;QAACrC;KAAU;IAEd,OAAO;QAAEwB;QAAOE;QAAWJ;QAAM0B,SAAShD;IAAU;AACtD,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/useMenu.ts"],"sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n type FetchMenuOptions,\n type MenuDocument,\n fetchMenu as requestMenu,\n} from '../fetchMenu.js';\nimport { normalizeMenuLocale } from '../utilities/menuIdentity.js';\n\ntype UseMenuOptions = Omit<FetchMenuOptions, 'fetch'> & {\n fetch?: typeof globalThis.fetch;\n};\n\ntype UseMenuResult = {\n error: null | string;\n isLoading: boolean;\n menu: MenuDocument | null;\n refetch: () => Promise<void>;\n};\n\ntype ClientCacheEntry = {\n data: MenuDocument;\n timestamp: number;\n};\n\nconst clientCache = new Map<string, ClientCacheEntry>();\nconst CACHE_TTL = 30_000;\n\nconst getDefaultBaseURL = (): string | undefined => {\n if (typeof window === 'undefined') return undefined;\n return window.location.origin;\n};\n\nconst getCacheKey = ({\n apiRoute = '/api',\n baseURL,\n depth = 0,\n locale,\n slug,\n}: UseMenuOptions): string => {\n return JSON.stringify({\n apiRoute,\n baseURL: baseURL || getDefaultBaseURL(),\n depth,\n locale: normalizeMenuLocale(locale),\n slug,\n });\n};\n\nexport const useMenu = ({\n apiRoute = '/api',\n baseURL,\n depth = 0,\n fetch: fetchImpl,\n locale,\n slug,\n}: UseMenuOptions): UseMenuResult => {\n const [menu, setMenu] = useState<MenuDocument | null>(null);\n const [error, setError] = useState<null | string>(null);\n const [isLoading, setIsLoading] = useState(true);\n const abortRef = useRef<AbortController | null>(null);\n\n const cacheKey = getCacheKey({ apiRoute, baseURL, depth, locale, slug });\n\n const fetchMenu = useCallback(async () => {\n const cached = clientCache.get(cacheKey);\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n setMenu(cached.data);\n setIsLoading(false);\n setError(null);\n return;\n }\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const data = await requestMenu({\n apiRoute,\n baseURL: baseURL || getDefaultBaseURL(),\n depth,\n fetch: async (input, init) =>\n (fetchImpl || globalThis.fetch)(input, {\n ...init,\n signal: controller.signal,\n }),\n locale,\n slug,\n });\n\n clientCache.set(cacheKey, { data, timestamp: Date.now() });\n setMenu(data);\n } catch (err: any) {\n if (err.name !== 'AbortError') {\n setError(err.message);\n }\n } finally {\n setIsLoading(false);\n }\n }, [apiRoute, baseURL, cacheKey, depth, fetchImpl, locale, slug]);\n\n useEffect(() => {\n void fetchMenu();\n return () => {\n abortRef.current?.abort();\n };\n }, [fetchMenu]);\n\n return { error, isLoading, menu, refetch: fetchMenu };\n};\n"],"names":["useCallback","useEffect","useRef","useState","fetchMenu","requestMenu","normalizeMenuLocale","clientCache","Map","CACHE_TTL","getDefaultBaseURL","window","undefined","location","origin","getCacheKey","apiRoute","baseURL","depth","locale","slug","JSON","stringify","useMenu","fetch","fetchImpl","menu","setMenu","error","setError","isLoading","setIsLoading","abortRef","cacheKey","cached","get","Date","now","timestamp","data","current","abort","controller","AbortController","input","init","globalThis","signal","set","err","name","message","refetch"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAEjE,SAGEC,aAAaC,WAAW,QACnB,kBAAkB;AACzB,SAASC,mBAAmB,QAAQ,+BAA+B;AAkBnE,MAAMC,cAAc,IAAIC;AACxB,MAAMC,YAAY;AAElB,MAAMC,oBAAoB;IACxB,IAAI,OAAOC,WAAW,aAAa,OAAOC;IAC1C,OAAOD,OAAOE,QAAQ,CAACC,MAAM;AAC/B;AAEA,MAAMC,cAAc,CAAC,EACnBC,WAAW,MAAM,EACjBC,OAAO,EACPC,QAAQ,CAAC,EACTC,MAAM,EACNC,IAAI,EACW;IACf,OAAOC,KAAKC,SAAS,CAAC;QACpBN;QACAC,SAASA,WAAWP;QACpBQ;QACAC,QAAQb,oBAAoBa;QAC5BC;IACF;AACF;AAEA,OAAO,MAAMG,UAAU,CAAC,EACtBP,WAAW,MAAM,EACjBC,OAAO,EACPC,QAAQ,CAAC,EACTM,OAAOC,SAAS,EAChBN,MAAM,EACNC,IAAI,EACW;IACf,MAAM,CAACM,MAAMC,QAAQ,GAAGxB,SAA8B;IACtD,MAAM,CAACyB,OAAOC,SAAS,GAAG1B,SAAwB;IAClD,MAAM,CAAC2B,WAAWC,aAAa,GAAG5B,SAAS;IAC3C,MAAM6B,WAAW9B,OAA+B;IAEhD,MAAM+B,WAAWlB,YAAY;QAAEC;QAAUC;QAASC;QAAOC;QAAQC;IAAK;IAEtE,MAAMhB,YAAYJ,YAAY;QAC5B,MAAMkC,SAAS3B,YAAY4B,GAAG,CAACF;QAC/B,IAAIC,UAAUE,KAAKC,GAAG,KAAKH,OAAOI,SAAS,GAAG7B,WAAW;YACvDkB,QAAQO,OAAOK,IAAI;YACnBR,aAAa;YACbF,SAAS;YACT;QACF;QAEAG,SAASQ,OAAO,EAAEC;QAClB,MAAMC,aAAa,IAAIC;QACvBX,SAASQ,OAAO,GAAGE;QAEnBX,aAAa;QACbF,SAAS;QAET,IAAI;YACF,MAAMU,OAAO,MAAMlC,YAAY;gBAC7BW;gBACAC,SAASA,WAAWP;gBACpBQ;gBACAM,OAAO,OAAOoB,OAAOC,OACnB,AAACpB,CAAAA,aAAaqB,WAAWtB,KAAK,AAAD,EAAGoB,OAAO;wBACrC,GAAGC,IAAI;wBACPE,QAAQL,WAAWK,MAAM;oBAC3B;gBACF5B;gBACAC;YACF;YAEAb,YAAYyC,GAAG,CAACf,UAAU;gBAAEM;gBAAMD,WAAWF,KAAKC,GAAG;YAAG;YACxDV,QAAQY;QACV,EAAE,OAAOU,KAAU;YACjB,IAAIA,IAAIC,IAAI,KAAK,cAAc;gBAC7BrB,SAASoB,IAAIE,OAAO;YACtB;QACF,SAAU;YACRpB,aAAa;QACf;IACF,GAAG;QAACf;QAAUC;QAASgB;QAAUf;QAAOO;QAAWN;QAAQC;KAAK;IAEhEnB,UAAU;QACR,KAAKG;QACL,OAAO;YACL4B,SAASQ,OAAO,EAAEC;QACpB;IACF,GAAG;QAACrC;KAAU;IAEd,OAAO;QAAEwB;QAAOE;QAAWJ;QAAM0B,SAAShD;IAAU;AACtD,EAAE"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionSlug, Config } from 'payload'\n\nimport type { DynamicSource } from './types.js'\n\nimport { menuCache } from './cache.js'\nimport { createMenusCollection } from './collections/Menus.js'\nimport { createExportMenusHandler } from './endpoints/exportMenusHandler.js'\nimport { createGetMenuHandler } from './endpoints/getMenuHandler.js'\nimport { createImportMenusHandler } from './endpoints/importMenusHandler.js'\n\nexport { migrateMegaColumnsToEntries } from './migrations/megaColumnsToEntries.js'\nexport type { DynamicSource } from './types.js'\n\nexport type MenuPluginConfig = {\n baseUrl?: string\n cacheTTL?: number\n /** depth used when resolving dynamic mega entry children (default: 1) */\n childrenDepth?: number\n disabled?: boolean\n /** sources used to auto-populate dynamic mega entries from related collections */\n dynamicSources?: DynamicSource[]\n enableImportExport?: boolean\n maxDepth?: number\n mediaCollection?: CollectionSlug\n relationTo?: CollectionSlug | CollectionSlug[]\n requireAdminForImportExport?: boolean\n}\n\nexport const menuPlugin =\n (pluginOptions: MenuPluginConfig) =>\n (config: Config): Config => {\n const cacheTTL = pluginOptions.cacheTTL ?? 60_000\n const enableImportExport = pluginOptions.enableImportExport ?? true\n const requireAdminForImportExport = pluginOptions.requireAdminForImportExport ?? true\n\n menuCache.configure(cacheTTL)\n\n config.collections = [\n ...(config.collections || []),\n createMenusCollection({\n baseUrl: pluginOptions.baseUrl,\n childrenDepth: pluginOptions.childrenDepth,\n disabled: pluginOptions.disabled,\n dynamicSources: pluginOptions.dynamicSources,\n maxDepth: pluginOptions.maxDepth,\n mediaCollection: pluginOptions.mediaCollection,\n relationTo: pluginOptions.relationTo,\n }),\n ]\n\n if (pluginOptions.disabled) {\n return config\n }\n\n config.endpoints = [\n ...(config.endpoints || []),\n {\n handler: createGetMenuHandler(),\n method: 'get',\n path: '/api/menus/:slug',\n },\n ...(enableImportExport\n ? [\n {\n handler: createExportMenusHandler({ requireAdmin: requireAdminForImportExport }),\n method: 'get' as const,\n path: '/api/menus-export',\n },\n {\n handler: createImportMenusHandler({ requireAdmin: requireAdminForImportExport }),\n method: 'post' as const,\n path: '/api/menus-import',\n },\n ]\n : []),\n ]\n\n return config\n }\n"],"names":["menuCache","createMenusCollection","createExportMenusHandler","createGetMenuHandler","createImportMenusHandler","migrateMegaColumnsToEntries","menuPlugin","pluginOptions","config","cacheTTL","enableImportExport","requireAdminForImportExport","configure","collections","baseUrl","childrenDepth","disabled","dynamicSources","maxDepth","mediaCollection","relationTo","endpoints","handler","method","path","requireAdmin"],"mappings":"AAIA,SAASA,SAAS,QAAQ,aAAY;AACtC,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,wBAAwB,QAAQ,oCAAmC;AAC5E,SAASC,oBAAoB,QAAQ,gCAA+B;AACpE,SAASC,wBAAwB,QAAQ,oCAAmC;AAE5E,SAASC,2BAA2B,QAAQ,uCAAsC;AAkBlF,OAAO,MAAMC,aACX,CAACC,gBACD,CAACC;QACC,MAAMC,WAAWF,cAAcE,QAAQ,IAAI;QAC3C,MAAMC,qBAAqBH,cAAcG,kBAAkB,IAAI;QAC/D,MAAMC,8BAA8BJ,cAAcI,2BAA2B,IAAI;QAEjFX,UAAUY,SAAS,CAACH;QAEpBD,OAAOK,WAAW,GAAG;eACfL,OAAOK,WAAW,IAAI,EAAE;YAC5BZ,sBAAsB;gBACpBa,SAASP,cAAcO,OAAO;gBAC9BC,eAAeR,cAAcQ,aAAa;gBAC1CC,UAAUT,cAAcS,QAAQ;gBAChCC,gBAAgBV,cAAcU,cAAc;gBAC5CC,UAAUX,cAAcW,QAAQ;gBAChCC,iBAAiBZ,cAAcY,eAAe;gBAC9CC,YAAYb,cAAca,UAAU;YACtC;SACD;QAED,IAAIb,cAAcS,QAAQ,EAAE;YAC1B,OAAOR;QACT;QAEAA,OAAOa,SAAS,GAAG;eACbb,OAAOa,SAAS,IAAI,EAAE;YAC1B;gBACEC,SAASnB;gBACToB,QAAQ;gBACRC,MAAM;YACR;eACId,qBACA;gBACE;oBACEY,SAASpB,yBAAyB;wBAAEuB,cAAcd;oBAA4B;oBAC9EY,QAAQ;oBACRC,MAAM;gBACR;gBACA;oBACEF,SAASlB,yBAAyB;wBAAEqB,cAAcd;oBAA4B;oBAC9EY,QAAQ;oBACRC,MAAM;gBACR;aACD,GACD,EAAE;SACP;QAED,OAAOhB;IACT,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionSlug, Config } from 'payload';\nimport { menuCache } from './cache.js';\nimport { createMenusCollection } from './collections/Menus.js';\nimport { createExportMenusHandler } from './endpoints/exportMenusHandler.js';\nimport { createGetMenuHandler } from './endpoints/getMenuHandler.js';\nimport { createImportMenusHandler } from './endpoints/importMenusHandler.js';\nimport type { DynamicSource } from './types.js';\n\nexport { migrateMegaColumnsToEntries } from './migrations/megaColumnsToEntries.js';\nexport type { DynamicSource } from './types.js';\n\nexport type MenuPluginConfig = {\n baseUrl?: string;\n cacheTTL?: number;\n /** depth used when resolving dynamic mega entry children (default: 1) */\n childrenDepth?: number;\n disabled?: boolean;\n /** sources used to auto-populate dynamic mega entries from related collections */\n dynamicSources?: DynamicSource[];\n enableImportExport?: boolean;\n maxDepth?: number;\n mediaCollection?: CollectionSlug;\n relationTo?: CollectionSlug | CollectionSlug[];\n requireAdminForImportExport?: boolean;\n};\n\nexport const menuPlugin =\n (pluginOptions: MenuPluginConfig) =>\n (config: Config): Config => {\n const cacheTTL = pluginOptions.cacheTTL ?? 60_000;\n const enableImportExport = pluginOptions.enableImportExport ?? true;\n const requireAdminForImportExport =\n pluginOptions.requireAdminForImportExport ?? true;\n\n menuCache.configure(cacheTTL);\n\n config.collections = [\n ...(config.collections || []),\n createMenusCollection({\n baseUrl: pluginOptions.baseUrl,\n childrenDepth: pluginOptions.childrenDepth,\n disabled: pluginOptions.disabled,\n dynamicSources: pluginOptions.dynamicSources,\n maxDepth: pluginOptions.maxDepth,\n mediaCollection: pluginOptions.mediaCollection,\n relationTo: pluginOptions.relationTo,\n }),\n ];\n\n if (pluginOptions.disabled) {\n return config;\n }\n\n config.endpoints = [\n ...(config.endpoints || []),\n {\n handler: createGetMenuHandler(),\n method: 'get',\n path: '/api/menus/:slug',\n },\n ...(enableImportExport\n ? [\n {\n handler: createExportMenusHandler({\n requireAdmin: requireAdminForImportExport,\n }),\n method: 'get' as const,\n path: '/api/menus-export',\n },\n {\n handler: createImportMenusHandler({\n requireAdmin: requireAdminForImportExport,\n }),\n method: 'post' as const,\n path: '/api/menus-import',\n },\n ]\n : []),\n ];\n\n return config;\n };\n"],"names":["menuCache","createMenusCollection","createExportMenusHandler","createGetMenuHandler","createImportMenusHandler","migrateMegaColumnsToEntries","menuPlugin","pluginOptions","config","cacheTTL","enableImportExport","requireAdminForImportExport","configure","collections","baseUrl","childrenDepth","disabled","dynamicSources","maxDepth","mediaCollection","relationTo","endpoints","handler","method","path","requireAdmin"],"mappings":"AACA,SAASA,SAAS,QAAQ,aAAa;AACvC,SAASC,qBAAqB,QAAQ,yBAAyB;AAC/D,SAASC,wBAAwB,QAAQ,oCAAoC;AAC7E,SAASC,oBAAoB,QAAQ,gCAAgC;AACrE,SAASC,wBAAwB,QAAQ,oCAAoC;AAG7E,SAASC,2BAA2B,QAAQ,uCAAuC;AAkBnF,OAAO,MAAMC,aACX,CAACC,gBACD,CAACC;QACC,MAAMC,WAAWF,cAAcE,QAAQ,IAAI;QAC3C,MAAMC,qBAAqBH,cAAcG,kBAAkB,IAAI;QAC/D,MAAMC,8BACJJ,cAAcI,2BAA2B,IAAI;QAE/CX,UAAUY,SAAS,CAACH;QAEpBD,OAAOK,WAAW,GAAG;eACfL,OAAOK,WAAW,IAAI,EAAE;YAC5BZ,sBAAsB;gBACpBa,SAASP,cAAcO,OAAO;gBAC9BC,eAAeR,cAAcQ,aAAa;gBAC1CC,UAAUT,cAAcS,QAAQ;gBAChCC,gBAAgBV,cAAcU,cAAc;gBAC5CC,UAAUX,cAAcW,QAAQ;gBAChCC,iBAAiBZ,cAAcY,eAAe;gBAC9CC,YAAYb,cAAca,UAAU;YACtC;SACD;QAED,IAAIb,cAAcS,QAAQ,EAAE;YAC1B,OAAOR;QACT;QAEAA,OAAOa,SAAS,GAAG;eACbb,OAAOa,SAAS,IAAI,EAAE;YAC1B;gBACEC,SAASnB;gBACToB,QAAQ;gBACRC,MAAM;YACR;eACId,qBACA;gBACE;oBACEY,SAASpB,yBAAyB;wBAChCuB,cAAcd;oBAChB;oBACAY,QAAQ;oBACRC,MAAM;gBACR;gBACA;oBACEF,SAASlB,yBAAyB;wBAChCqB,cAAcd;oBAChB;oBACAY,QAAQ;oBACRC,MAAM;gBACR;aACD,GACD,EAAE;SACP;QAED,OAAOhB;IACT,EAAE"}
@@ -7,7 +7,7 @@ declare const migrateItems: (items: unknown, logger?: Payload["logger"]) => {
7
7
  * Determine whether a menu document still contains legacy `megaColumns` data.
8
8
  */
9
9
  declare const docNeedsMigration: (items: unknown) => boolean;
10
- export { docNeedsMigration as menuDocNeedsMegaColumnsMigration, migrateItems as migrateMenuItemsMegaColumns };
10
+ export { docNeedsMigration as menuDocNeedsMegaColumnsMigration, migrateItems as migrateMenuItemsMegaColumns, };
11
11
  /**
12
12
  * Migrate every `menus` document from the legacy `megaColumns` mega structure to
13
13
  * the new `megaEntries` shape. Safe to run multiple times — already-migrated
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/migrations/megaColumnsToEntries.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\ntype AnyRecord = Record<string, unknown>\n\nconst toLeafChild = (link: AnyRecord): AnyRecord => {\n // Drop nesting-only fields; remaining leaf link fields are preserved as-is.\n const { children: _c, megaColumns: _mc, megaEntries: _me, subLinks: _sl, ...leaf } = link\n return leaf\n}\n\nconst columnLinkToEntry = (link: AnyRecord): AnyRecord => {\n const { children: _c, megaColumns: _mc, megaEntries: _me, subLinks, ...leaf } = link\n const childSource = Array.isArray(subLinks) ? subLinks : []\n return {\n ...leaf,\n children: childSource.map((sub) => toLeafChild(sub as AnyRecord)),\n featured: { mode: 'inherit' },\n source: 'manual',\n }\n}\n\n/**\n * Transform a single mega item from the legacy `megaColumns` shape into the new\n * `megaEntries` shape. Idempotent: an item that already has `megaEntries` (or no\n * `megaColumns`) is returned unchanged.\n */\nconst migrateMegaItem = (item: AnyRecord, logger?: Payload['logger']): AnyRecord => {\n if (Array.isArray(item.megaEntries) || !Array.isArray(item.megaColumns)) {\n return item\n }\n\n const columns = item.megaColumns as AnyRecord[]\n const [primary, ...rest] = columns\n const entries: AnyRecord[] = []\n\n const pushColumnLinks = (column: AnyRecord | undefined) => {\n if (!column) {return}\n const links = Array.isArray(column.columnLinks) ? (column.columnLinks as AnyRecord[]) : []\n for (const link of links) {\n entries.push(columnLinkToEntry(link))\n }\n }\n\n pushColumnLinks(primary)\n for (const column of rest) {\n pushColumnLinks(column)\n if (column?.featured) {\n logger?.info?.(\n '[menu-plugin] Migration: dropping featured panel from a non-primary mega column (only the primary column maps to defaultFeatured).',\n )\n }\n }\n\n const { megaColumns: _mc, ...itemWithoutColumns } = item\n\n return {\n ...itemWithoutColumns,\n defaultFeatured: (primary?.featured as AnyRecord | undefined) ?? undefined,\n megaEntries: entries,\n megaLayout: 'reveal',\n }\n}\n\nconst migrateItems = (items: unknown, logger?: Payload['logger']): { changed: boolean; items: unknown } => {\n if (!Array.isArray(items)) {return { changed: false, items }}\n\n let changed = false\n const migrated = items.map((rawItem) => {\n if (!rawItem || typeof rawItem !== 'object') {return rawItem}\n const item = rawItem as AnyRecord\n\n if (item.itemType === 'dropdown') {\n const result = migrateItems(item.children, logger)\n if (result.changed) {\n changed = true\n return { ...item, children: result.items }\n }\n return item\n }\n\n if (item.itemType === 'mega' && Array.isArray(item.megaColumns) && !Array.isArray(item.megaEntries)) {\n changed = true\n return migrateMegaItem(item, logger)\n }\n\n return item\n })\n\n return { changed, items: migrated }\n}\n\n/**\n * Determine whether a menu document still contains legacy `megaColumns` data.\n */\nconst docNeedsMigration = (items: unknown): boolean => {\n if (!Array.isArray(items)) {return false}\n return items.some((rawItem) => {\n if (!rawItem || typeof rawItem !== 'object') {return false}\n const item = rawItem as AnyRecord\n if (item.itemType === 'mega' && Array.isArray(item.megaColumns) && !Array.isArray(item.megaEntries)) {\n return true\n }\n if (item.itemType === 'dropdown') {return docNeedsMigration(item.children)}\n return false\n })\n}\n\nexport { docNeedsMigration as menuDocNeedsMegaColumnsMigration, migrateItems as migrateMenuItemsMegaColumns }\n\n/**\n * Migrate every `menus` document from the legacy `megaColumns` mega structure to\n * the new `megaEntries` shape. Safe to run multiple times — already-migrated\n * documents are skipped.\n */\nexport const migrateMegaColumnsToEntries = async (payload: Payload): Promise<{\n migrated: number\n scanned: number\n}> => {\n const { docs } = await payload.find({\n collection: 'menus',\n depth: 0,\n limit: 0,\n pagination: false,\n })\n\n let migrated = 0\n\n for (const doc of docs) {\n const record = doc as AnyRecord\n if (!docNeedsMigration(record.items)) {continue}\n\n const { items } = migrateItems(record.items, payload.logger)\n\n await payload.update({\n id: record.id as string,\n collection: 'menus',\n data: { items } as never,\n })\n migrated += 1\n }\n\n return { migrated, scanned: docs.length }\n}\n"],"names":["toLeafChild","link","children","_c","megaColumns","_mc","megaEntries","_me","subLinks","_sl","leaf","columnLinkToEntry","childSource","Array","isArray","map","sub","featured","mode","source","migrateMegaItem","item","logger","columns","primary","rest","entries","pushColumnLinks","column","links","columnLinks","push","info","itemWithoutColumns","defaultFeatured","undefined","megaLayout","migrateItems","items","changed","migrated","rawItem","itemType","result","docNeedsMigration","some","menuDocNeedsMegaColumnsMigration","migrateMenuItemsMegaColumns","migrateMegaColumnsToEntries","payload","docs","find","collection","depth","limit","pagination","doc","record","update","id","data","scanned","length"],"mappings":"AAIA,MAAMA,cAAc,CAACC;IACnB,4EAA4E;IAC5E,MAAM,EAAEC,UAAUC,EAAE,EAAEC,aAAaC,GAAG,EAAEC,aAAaC,GAAG,EAAEC,UAAUC,GAAG,EAAE,GAAGC,MAAM,GAAGT;IACrF,OAAOS;AACT;AAEA,MAAMC,oBAAoB,CAACV;IACzB,MAAM,EAAEC,UAAUC,EAAE,EAAEC,aAAaC,GAAG,EAAEC,aAAaC,GAAG,EAAEC,QAAQ,EAAE,GAAGE,MAAM,GAAGT;IAChF,MAAMW,cAAcC,MAAMC,OAAO,CAACN,YAAYA,WAAW,EAAE;IAC3D,OAAO;QACL,GAAGE,IAAI;QACPR,UAAUU,YAAYG,GAAG,CAAC,CAACC,MAAQhB,YAAYgB;QAC/CC,UAAU;YAAEC,MAAM;QAAU;QAC5BC,QAAQ;IACV;AACF;AAEA;;;;CAIC,GACD,MAAMC,kBAAkB,CAACC,MAAiBC;IACxC,IAAIT,MAAMC,OAAO,CAACO,KAAKf,WAAW,KAAK,CAACO,MAAMC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,YAAY;YACZQ,MAAM;gBAAEtB;YAAM;QAChB;QACAE,YAAY;IACd;IAEA,OAAO;QAAEA;QAAUqB,SAASX,KAAKY,MAAM;IAAC;AAC1C,EAAC"}
1
+ {"version":3,"sources":["../../src/migrations/megaColumnsToEntries.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\ntype AnyRecord = Record<string, unknown>;\n\nconst toLeafChild = (link: AnyRecord): AnyRecord => {\n // Drop nesting-only fields; remaining leaf link fields are preserved as-is.\n const {\n children: _c,\n megaColumns: _mc,\n megaEntries: _me,\n subLinks: _sl,\n ...leaf\n } = link;\n return leaf;\n};\n\nconst columnLinkToEntry = (link: AnyRecord): AnyRecord => {\n const {\n children: _c,\n megaColumns: _mc,\n megaEntries: _me,\n subLinks,\n ...leaf\n } = link;\n const childSource = Array.isArray(subLinks) ? subLinks : [];\n return {\n ...leaf,\n children: childSource.map(sub => toLeafChild(sub as AnyRecord)),\n featured: { mode: 'inherit' },\n source: 'manual',\n };\n};\n\n/**\n * Transform a single mega item from the legacy `megaColumns` shape into the new\n * `megaEntries` shape. Idempotent: an item that already has `megaEntries` (or no\n * `megaColumns`) is returned unchanged.\n */\nconst migrateMegaItem = (\n item: AnyRecord,\n logger?: Payload['logger']\n): AnyRecord => {\n if (Array.isArray(item.megaEntries) || !Array.isArray(item.megaColumns)) {\n return item;\n }\n\n const columns = item.megaColumns as AnyRecord[];\n const [primary, ...rest] = columns;\n const entries: AnyRecord[] = [];\n\n const pushColumnLinks = (column: AnyRecord | undefined) => {\n if (!column) {\n return;\n }\n const links = Array.isArray(column.columnLinks)\n ? (column.columnLinks as AnyRecord[])\n : [];\n for (const link of links) {\n entries.push(columnLinkToEntry(link));\n }\n };\n\n pushColumnLinks(primary);\n for (const column of rest) {\n pushColumnLinks(column);\n if (column?.featured) {\n logger?.info?.(\n '[menu-plugin] Migration: dropping featured panel from a non-primary mega column (only the primary column maps to defaultFeatured).'\n );\n }\n }\n\n const { megaColumns: _mc, ...itemWithoutColumns } = item;\n\n return {\n ...itemWithoutColumns,\n defaultFeatured: (primary?.featured as AnyRecord | undefined) ?? undefined,\n megaEntries: entries,\n megaLayout: 'reveal',\n };\n};\n\nconst migrateItems = (\n items: unknown,\n logger?: Payload['logger']\n): { changed: boolean; items: unknown } => {\n if (!Array.isArray(items)) {\n return { changed: false, items };\n }\n\n let changed = false;\n const migrated = items.map(rawItem => {\n if (!rawItem || typeof rawItem !== 'object') {\n return rawItem;\n }\n const item = rawItem as AnyRecord;\n\n if (item.itemType === 'dropdown') {\n const result = migrateItems(item.children, logger);\n if (result.changed) {\n changed = true;\n return { ...item, children: result.items };\n }\n return item;\n }\n\n if (\n item.itemType === 'mega' &&\n Array.isArray(item.megaColumns) &&\n !Array.isArray(item.megaEntries)\n ) {\n changed = true;\n return migrateMegaItem(item, logger);\n }\n\n return item;\n });\n\n return { changed, items: migrated };\n};\n\n/**\n * Determine whether a menu document still contains legacy `megaColumns` data.\n */\nconst docNeedsMigration = (items: unknown): boolean => {\n if (!Array.isArray(items)) {\n return false;\n }\n return items.some(rawItem => {\n if (!rawItem || typeof rawItem !== 'object') {\n return false;\n }\n const item = rawItem as AnyRecord;\n if (\n item.itemType === 'mega' &&\n Array.isArray(item.megaColumns) &&\n !Array.isArray(item.megaEntries)\n ) {\n return true;\n }\n if (item.itemType === 'dropdown') {\n return docNeedsMigration(item.children);\n }\n return false;\n });\n};\n\nexport {\n docNeedsMigration as menuDocNeedsMegaColumnsMigration,\n migrateItems as migrateMenuItemsMegaColumns,\n};\n\n/**\n * Migrate every `menus` document from the legacy `megaColumns` mega structure to\n * the new `megaEntries` shape. Safe to run multiple times — already-migrated\n * documents are skipped.\n */\nexport const migrateMegaColumnsToEntries = async (\n payload: Payload\n): Promise<{\n migrated: number;\n scanned: number;\n}> => {\n const { docs } = await payload.find({\n collection: 'menus',\n depth: 0,\n limit: 0,\n pagination: false,\n });\n\n let migrated = 0;\n\n for (const doc of docs) {\n const record = doc as AnyRecord;\n if (!docNeedsMigration(record.items)) {\n continue;\n }\n\n const { items } = migrateItems(record.items, payload.logger);\n\n await payload.update({\n id: record.id as string,\n collection: 'menus',\n data: { items } as never,\n });\n migrated += 1;\n }\n\n return { migrated, scanned: docs.length };\n};\n"],"names":["toLeafChild","link","children","_c","megaColumns","_mc","megaEntries","_me","subLinks","_sl","leaf","columnLinkToEntry","childSource","Array","isArray","map","sub","featured","mode","source","migrateMegaItem","item","logger","columns","primary","rest","entries","pushColumnLinks","column","links","columnLinks","push","info","itemWithoutColumns","defaultFeatured","undefined","megaLayout","migrateItems","items","changed","migrated","rawItem","itemType","result","docNeedsMigration","some","menuDocNeedsMegaColumnsMigration","migrateMenuItemsMegaColumns","migrateMegaColumnsToEntries","payload","docs","find","collection","depth","limit","pagination","doc","record","update","id","data","scanned","length"],"mappings":"AAIA,MAAMA,cAAc,CAACC;IACnB,4EAA4E;IAC5E,MAAM,EACJC,UAAUC,EAAE,EACZC,aAAaC,GAAG,EAChBC,aAAaC,GAAG,EAChBC,UAAUC,GAAG,EACb,GAAGC,MACJ,GAAGT;IACJ,OAAOS;AACT;AAEA,MAAMC,oBAAoB,CAACV;IACzB,MAAM,EACJC,UAAUC,EAAE,EACZC,aAAaC,GAAG,EAChBC,aAAaC,GAAG,EAChBC,QAAQ,EACR,GAAGE,MACJ,GAAGT;IACJ,MAAMW,cAAcC,MAAMC,OAAO,CAACN,YAAYA,WAAW,EAAE;IAC3D,OAAO;QACL,GAAGE,IAAI;QACPR,UAAUU,YAAYG,GAAG,CAACC,CAAAA,MAAOhB,YAAYgB;QAC7CC,UAAU;YAAEC,MAAM;QAAU;QAC5BC,QAAQ;IACV;AACF;AAEA;;;;CAIC,GACD,MAAMC,kBAAkB,CACtBC,MACAC;IAEA,IAAIT,MAAMC,OAAO,CAACO,KAAKf,WAAW,KAAK,CAACO,MAAMC,OAAO,CAACO,KAAKjB,WAAW,GAAG;QACvE,OAAOiB;IACT;IAEA,MAAME,UAAUF,KAAKjB,WAAW;IAChC,MAAM,CAACo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
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug } from 'payload'\n\n/**\n * Configuration describing how a mega menu entry can auto-populate its children\n * (and optional featured content) from a related collection.\n */\nexport type DynamicSource = {\n /** collection queried for children */\n collection: CollectionSlug\n /** optional featured resolution from a child (or parent) doc */\n featured?: {\n ctaHrefBuilder?: (doc: Record<string, unknown>) => string\n ctaLabel?: string\n descriptionField?: string\n headingField?: string\n /** dot-path to an upload/media field */\n imageField?: string\n }\n /** build a child's href from its doc */\n hrefBuilder: (doc: Record<string, unknown>) => string\n /** label shown in the admin select */\n label: string\n /** field on a child doc used as its label */\n labelField: string\n /** optional limit on children */\n limit?: number\n /** stable id, stored in the `dynamicSource` field */\n name: string\n /** collection the editor picks a parent from */\n parentCollection: CollectionSlug\n /** field on `collection` relating each child to its parent */\n parentField: string\n /** sort applied to the children query (Payload sort string) */\n sort?: string\n}\n"],"names":[],"mappings":"AAEA;;;CAGC,GACD,WA4BC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug } from 'payload';\n\n/**\n * Configuration describing how a mega menu entry can auto-populate its children\n * (and optional featured content) from a related collection.\n */\nexport type DynamicSource = {\n /** collection queried for children */\n collection: CollectionSlug;\n /** optional featured resolution from a child (or parent) doc */\n featured?: {\n ctaHrefBuilder?: (doc: Record<string, unknown>) => string;\n ctaLabel?: string;\n descriptionField?: string;\n headingField?: string;\n /** dot-path to an upload/media field */\n imageField?: string;\n };\n /** build a child's href from its doc */\n hrefBuilder: (doc: Record<string, unknown>) => string;\n /** label shown in the admin select */\n label: string;\n /** field on a child doc used as its label */\n labelField: string;\n /** optional limit on children */\n limit?: number;\n /** stable id, stored in the `dynamicSource` field */\n name: string;\n /** collection the editor picks a parent from */\n parentCollection: CollectionSlug;\n /** field on `collection` relating each child to its parent */\n parentField: string;\n /** sort applied to the children query (Payload sort string) */\n sort?: string;\n};\n"],"names":[],"mappings":"AAEA;;;CAGC,GACD,WA4BE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/menuIdentity.ts"],"sourcesContent":["export const normalizeMenuLocale = (locale?: null | string): string | undefined => {\n const normalized = locale?.trim().toLowerCase()\n return normalized ? normalized : undefined\n}\n\nexport const buildMenuIdentityKey = (slug: string, locale?: null | string): string => {\n return `${slug}::${normalizeMenuLocale(locale) || '__default'}`\n}\n"],"names":["normalizeMenuLocale","locale","normalized","trim","toLowerCase","undefined","buildMenuIdentityKey","slug"],"mappings":"AAAA,OAAO,MAAMA,sBAAsB,CAACC;IAClC,MAAMC,aAAaD,QAAQE,OAAOC;IAClC,OAAOF,aAAaA,aAAaG;AACnC,EAAC;AAED,OAAO,MAAMC,uBAAuB,CAACC,MAAcN;IACjD,OAAO,GAAGM,KAAK,EAAE,EAAEP,oBAAoBC,WAAW,aAAa;AACjE,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/menuIdentity.ts"],"sourcesContent":["export const normalizeMenuLocale = (\n locale?: null | string\n): string | undefined => {\n const normalized = locale?.trim().toLowerCase();\n return normalized ? normalized : undefined;\n};\n\nexport const buildMenuIdentityKey = (\n slug: string,\n locale?: null | string\n): string => {\n return `${slug}::${normalizeMenuLocale(locale) || '__default'}`;\n};\n"],"names":["normalizeMenuLocale","locale","normalized","trim","toLowerCase","undefined","buildMenuIdentityKey","slug"],"mappings":"AAAA,OAAO,MAAMA,sBAAsB,CACjCC;IAEA,MAAMC,aAAaD,QAAQE,OAAOC;IAClC,OAAOF,aAAaA,aAAaG;AACnC,EAAE;AAEF,OAAO,MAAMC,uBAAuB,CAClCC,MACAN;IAEA,OAAO,GAAGM,KAAK,EAAE,EAAEP,oBAAoBC,WAAW,aAAa;AACjE,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/requireAdminUser.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nexport const requireAdminUser = (req: PayloadRequest): Response | undefined => {\n const adminCollection = req.payload.config.admin?.user\n\n if (!req.user) {\n return Response.json({ error: 'Authentication required' }, { status: 401 })\n }\n\n if (adminCollection && req.user.collection !== adminCollection) {\n return Response.json({ error: 'Admin access required' }, { status: 403 })\n }\n\n return undefined\n}\n"],"names":["requireAdminUser","req","adminCollection","payload","config","admin","user","Response","json","error","status","collection","undefined"],"mappings":"AAEA,OAAO,MAAMA,mBAAmB,CAACC;IAC/B,MAAMC,kBAAkBD,IAAIE,OAAO,CAACC,MAAM,CAACC,KAAK,EAAEC;IAElD,IAAI,CAACL,IAAIK,IAAI,EAAE;QACb,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAA0B,GAAG;YAAEC,QAAQ;QAAI;IAC3E;IAEA,IAAIR,mBAAmBD,IAAIK,IAAI,CAACK,UAAU,KAAKT,iBAAiB;QAC9D,OAAOK,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAwB,GAAG;YAAEC,QAAQ;QAAI;IACzE;IAEA,OAAOE;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/requireAdminUser.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload';\n\nexport const requireAdminUser = (req: PayloadRequest): Response | undefined => {\n const adminCollection = req.payload.config.admin?.user;\n\n if (!req.user) {\n return Response.json({ error: 'Authentication required' }, { status: 401 });\n }\n\n if (adminCollection && req.user.collection !== adminCollection) {\n return Response.json({ error: 'Admin access required' }, { status: 403 });\n }\n\n return undefined;\n};\n"],"names":["requireAdminUser","req","adminCollection","payload","config","admin","user","Response","json","error","status","collection","undefined"],"mappings":"AAEA,OAAO,MAAMA,mBAAmB,CAACC;IAC/B,MAAMC,kBAAkBD,IAAIE,OAAO,CAACC,MAAM,CAACC,KAAK,EAAEC;IAElD,IAAI,CAACL,IAAIK,IAAI,EAAE;QACb,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAA0B,GAAG;YAAEC,QAAQ;QAAI;IAC3E;IAEA,IAAIR,mBAAmBD,IAAIK,IAAI,CAACK,UAAU,KAAKT,iBAAiB;QAC9D,OAAOK,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAwB,GAAG;YAAEC,QAAQ;QAAI;IACzE;IAEA,OAAOE;AACT,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/sanitizeMenuDocument.ts"],"sourcesContent":["export const sanitizeMenuDocument = <T extends Record<string, unknown>>(menu: T): T => {\n const { slugLocaleKey: _slugLocaleKey, ...sanitized } = menu\n return sanitized as T\n}\n"],"names":["sanitizeMenuDocument","menu","slugLocaleKey","_slugLocaleKey","sanitized"],"mappings":"AAAA,OAAO,MAAMA,uBAAuB,CAAoCC;IACtE,MAAM,EAAEC,eAAeC,cAAc,EAAE,GAAGC,WAAW,GAAGH;IACxD,OAAOG;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/sanitizeMenuDocument.ts"],"sourcesContent":["export const sanitizeMenuDocument = <T extends Record<string, unknown>>(\n menu: T\n): T => {\n const { slugLocaleKey: _slugLocaleKey, ...sanitized } = menu;\n return sanitized as T;\n};\n"],"names":["sanitizeMenuDocument","menu","slugLocaleKey","_slugLocaleKey","sanitized"],"mappings":"AAAA,OAAO,MAAMA,uBAAuB,CAClCC;IAEA,MAAM,EAAEC,eAAeC,cAAc,EAAE,GAAGC,WAAW,GAAGH;IACxD,OAAOG;AACT,EAAE"}