domma-cms 0.116.8 → 0.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CLAUDE.md +7 -4
  2. package/admin/js/app.js +2 -2
  3. package/admin/js/lib/api-tokens-arrange.js +3 -3
  4. package/admin/js/lib/content-api-arrange.js +1 -0
  5. package/admin/js/lib/menu-editor-arrange.js +1 -1
  6. package/admin/js/lib/menu-rows.js +1 -1
  7. package/admin/js/lib/sidebar-renderer.js +1 -1
  8. package/admin/js/templates/api-reference.html +2 -1
  9. package/admin/js/templates/api-tokens.html +3 -3
  10. package/admin/js/templates/content-api.html +208 -0
  11. package/admin/js/templates/docs/api-content.html +183 -0
  12. package/admin/js/templates/docs/api-external.html +2 -1
  13. package/admin/js/templates/docs/usage-editions.html +1 -1
  14. package/admin/js/templates/menu-editor.html +6 -0
  15. package/admin/js/views/api-tokens.js +6 -6
  16. package/admin/js/views/content-api.js +7 -0
  17. package/admin/js/views/doc-pages.js +1 -1
  18. package/admin/js/views/index.js +1 -1
  19. package/admin/js/views/menu-editor.js +14 -14
  20. package/package.json +1 -1
  21. package/public/js/menu-decor.mjs +1 -1
  22. package/public/js/site.js +1 -1
  23. package/server/routes/api/collections.js +10 -17
  24. package/server/routes/api/content-api.js +70 -0
  25. package/server/routes/api/content-public.js +299 -0
  26. package/server/routes/public.js +17 -68
  27. package/server/server.js +11 -4
  28. package/server/services/apiTokens.js +61 -5
  29. package/server/services/content.js +4 -4
  30. package/server/services/contentApi.js +248 -0
  31. package/server/services/menuRender.js +9 -3
  32. package/server/services/menus.js +4 -1
  33. package/server/services/pagePublishing.js +85 -0
  34. package/server/services/permissionRegistry.js +1 -1
  35. package/server/services/renderer.js +12 -2
  36. package/server/services/search.js +31 -12
  37. package/server/templates/page.html +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "0.116.8",
3
+ "version": "0.118.0",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -1 +1 @@
1
- export const PRESET_COLOUR_VARS={primary:"--dm-primary",success:"--dm-success",danger:"--dm-danger",warning:"--dm-warning",info:"--dm-info",neutral:"--dm-text-muted"},PRESET_COLOUR_FALLBACKS={primary:"#0d6efd",success:"#198754",danger:"#dc3545",warning:"#ffc107",info:"#0dcaf0",neutral:"#6c757d"};const l=/^#[0-9a-fA-F]{6}$/;export function colourToCss(t){return typeof t!="string"?"":PRESET_COLOUR_VARS[t]?`var(${PRESET_COLOUR_VARS[t]}, ${PRESET_COLOUR_FALLBACKS[t]})`:l.test(t)?t:""}export const FLOAT_ANCHORS=["TL","TR","BL","BR","L","R"],FLOAT_DEFAULTS={anchor:"TL",offsetX:16,offsetY:16,zIndex:150},FLOAT_SHADOWS={none:"none",sm:"var(--dm-shadow-sm)",md:"var(--dm-shadow-md)",lg:"var(--dm-shadow-lg)",xl:"var(--dm-shadow-xl)"};function i(t,e,o,r){const n=Number(t);return Number.isFinite(n)?Math.min(r,Math.max(o,Math.round(n))):e}function d(t){const e=[];if(t.radius!=null&&t.radius!==""&&e.push(`border-radius:${i(t.radius,8,0,48)}px`),t.shadow!=null&&t.shadow!==""&&Object.prototype.hasOwnProperty.call(FLOAT_SHADOWS,t.shadow)&&e.push(`box-shadow:${FLOAT_SHADOWS[t.shadow]}`),t.accent&&colourToCss(t.accent)){const o=colourToCss(t.accent);e.push(`--dm-menu-accent:${o}`,`border-color:${o}`)}return t.opacity!=null&&t.opacity!==""&&e.push(`--dm-menu-panel-opacity:${i(t.opacity,100,20,100)/100}`),e}export function floatToCss(t){if(!t||t.position!=="floating")return"";const e=t.float&&typeof t.float=="object"&&!Array.isArray(t.float)?t.float:{},o=FLOAT_ANCHORS.includes(e.anchor)?e.anchor:FLOAT_DEFAULTS.anchor,r=i(e.offsetX,FLOAT_DEFAULTS.offsetX,0,4e3),n=i(e.offsetY,FLOAT_DEFAULTS.offsetY,0,4e3),a=["position:fixed",`z-index:${i(e.zIndex,FLOAT_DEFAULTS.zIndex,0,2147483647)}`];return o==="L"||o==="R"?(a.push("top:50%","transform:translateY(-50%)"),a.push(o==="L"?`left:${r}px`:`right:${r}px`)):(a.push(o[0]==="T"?`top:${n}px`:`bottom:${n}px`),a.push(o[1]==="L"?`left:${r}px`:`right:${r}px`)),e.width!=null&&e.width!==""&&a.push(`width:${i(e.width,260,120,600)}px`),a.push(`max-height:calc(100vh - ${o==="L"||o==="R"?32:n*2}px)`),a.push(...d(e)),a.join(";")}export const FLOAT_FLAGS=["collapsible","collapsed","movable","resizable"];export function floatBehaviour(t){const e={collapsible:!1,collapsed:!1,movable:!1,resizable:!1,chrome:!1,title:""};if(!t||t.position!=="floating")return e;const o=t.float&&typeof t.float=="object"&&!Array.isArray(t.float)?t.float:{},r={collapsible:!!o.collapsible,collapsed:!!o.collapsible&&!!o.collapsed,movable:!!o.movable,resizable:!!o.resizable},n=r.collapsible||r.movable,s=typeof o.title=="string"&&o.title!==""?o.title:t.name||"";return{...r,chrome:n,title:n?s:""}}export function applyFloat(t,e){const o=floatToCss(e);if(!t||!o)return!1;t.style.cssText+=";"+o,t.classList.add("dm-menu-floating"),e.slug&&!t.hasAttribute("data-menu")&&t.setAttribute("data-menu",e.slug),e.float?.anchor&&t.setAttribute("data-float-anchor",e.float.anchor);const r=floatBehaviour(e);for(const n of FLOAT_FLAGS)n!=="collapsed"&&r[n]&&t.setAttribute(`data-float-${n}`,"1");return r.collapsed&&t.setAttribute("data-float-collapsed","1"),r.title&&t.setAttribute("data-float-title",r.title),!0}export function makeBadgeEl(t){if(!t||t.text==null||t.text==="")return null;const e=document.createElement("span");e.className="dm-menu-badge",e.textContent=String(t.text);const o=t.variant?colourToCss(t.variant):"";return o&&(e.style.background=o,e.style.color="var(--dm-text-inverse, #fff)"),e}export function applyColour(t,e){const o=colourToCss(e);o&&(t.style.color=o)}export function applyPill(t,e){if(!e)return;t.classList.add("dm-nav-pill");const o=e.variant?colourToCss(e.variant):"";e.style==="outline"?(t.classList.add("dm-nav-pill--outline"),o&&(t.style.borderColor=o,t.style.color=o)):o&&(t.style.background=o,t.style.color="#fff")}export const MENU_ALIGN=["left","centre","right","spread"];export function menuAlign(t){const e=t&&t.align;return MENU_ALIGN.includes(e)?e:""}export const HIGHLIGHT_HOVER=["none","colour","underline","overline","background","uppercase","grow","breathe","glow"],HIGHLIGHT_ACTIVE=["none","bold","underline","overline","background","darken","pill"],HIGHLIGHT_HOVER_LABELS={none:"None - no change on hover",colour:"Colour change",underline:"Underline",overline:"Overline",background:"Background tint",uppercase:"Uppercase",grow:"Grow",breathe:"Breathe",glow:"Glow"},HIGHLIGHT_ACTIVE_LABELS={none:"None - not marked at all",bold:"Bold",underline:"Underline",overline:"Overline",background:"Background tint",darken:"Darkened",pill:"Filled pill"},LEGACY_STYLE_HOVER={none:"none",underline:"underline",overline:"overline",transform:"uppercase","text-transform":"uppercase",breathe:"breathe"},LEGACY_STYLE_ACTIVE={none:"none",darken:"darken",background:"background","background-color":"background",underline:"underline",overline:"overline"};export function legacyStyleHighlight(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{hover:LEGACY_STYLE_HOVER[e.hover]||"",active:LEGACY_STYLE_ACTIVE[e.active]||""}}export function highlightAttrs(t){const e=t&&t.highlight&&typeof t.highlight=="object"&&!Array.isArray(t.highlight)?t.highlight:{},o=legacyStyleHighlight(t&&t.style);return{hover:HIGHLIGHT_HOVER.includes(e.hover)?e.hover:o.hover,active:HIGHLIGHT_ACTIVE.includes(e.active)?e.active:o.active,accent:e.accent?colourToCss(e.accent):""}}export function applyHighlight(t,e){if(!t)return!1;const{hover:o,active:r,accent:n}=highlightAttrs(e);return o&&t.setAttribute("data-menu-hover",o),r&&t.setAttribute("data-menu-active",r),n&&t.style.setProperty("--dm-menu-highlight",n),!!(o||r||n)}export function itemHighlightAttrs(t){const e=t&&t.highlight&&typeof t.highlight=="object"&&!Array.isArray(t.highlight)?t.highlight:{};return{hover:HIGHLIGHT_HOVER.includes(e.hover)?e.hover:"",active:HIGHLIGHT_ACTIVE.includes(e.active)?e.active:"",accent:e.accent?colourToCss(e.accent):""}}export function applyItemHighlight(t,e){if(!t)return!1;const{hover:o,active:r,accent:n}=itemHighlightAttrs(e);return o&&t.setAttribute("data-menu-item-hover",o),r&&t.setAttribute("data-menu-item-active",r),n&&t.style.setProperty("--dm-menu-highlight",n),!!(o||r||n)}function c(t){if(typeof t!="string"||!t)return"";const e=t.split("#")[0].split("?")[0];return e.startsWith("/")?e.length>1&&e.endsWith("/")?e.slice(0,-1):e:""}export function isCurrentItem(t,e){const o=c(t),r=c(e);return!!o&&!!r&&o===r}
1
+ export const PRESET_COLOUR_VARS={primary:"--dm-primary",success:"--dm-success",danger:"--dm-danger",warning:"--dm-warning",info:"--dm-info",neutral:"--dm-text-muted"},PRESET_COLOUR_FALLBACKS={primary:"#0d6efd",success:"#198754",danger:"#dc3545",warning:"#ffc107",info:"#0dcaf0",neutral:"#6c757d"};const f=/^#[0-9a-fA-F]{6}$/;export function colourToCss(t){return typeof t!="string"?"":PRESET_COLOUR_VARS[t]?`var(${PRESET_COLOUR_VARS[t]}, ${PRESET_COLOUR_FALLBACKS[t]})`:f.test(t)?t:""}export const FLOAT_ANCHORS=["TL","TR","BL","BR","L","R"],FLOAT_DEFAULTS={anchor:"TL",offsetX:16,offsetY:16,zIndex:150},FLOAT_SHADOWS={none:"none",sm:"var(--dm-shadow-sm)",md:"var(--dm-shadow-md)",lg:"var(--dm-shadow-lg)",xl:"var(--dm-shadow-xl)"};function a(t,e,o,n){const r=Number(t);return Number.isFinite(r)?Math.min(n,Math.max(o,Math.round(r))):e}function u(t){const e=[];if(t.radius!=null&&t.radius!==""&&e.push(`border-radius:${a(t.radius,8,0,48)}px`),t.shadow!=null&&t.shadow!==""&&Object.prototype.hasOwnProperty.call(FLOAT_SHADOWS,t.shadow)&&e.push(`box-shadow:${FLOAT_SHADOWS[t.shadow]}`),t.accent&&colourToCss(t.accent)){const o=colourToCss(t.accent);e.push(`--dm-menu-accent:${o}`,`border-color:${o}`)}return t.opacity!=null&&t.opacity!==""&&e.push(`--dm-menu-panel-opacity:${a(t.opacity,100,20,100)/100}`),e}export function floatToCss(t){if(!t||t.position!=="floating")return"";const e=t.float&&typeof t.float=="object"&&!Array.isArray(t.float)?t.float:{},o=FLOAT_ANCHORS.includes(e.anchor)?e.anchor:FLOAT_DEFAULTS.anchor,n=a(e.offsetX,FLOAT_DEFAULTS.offsetX,0,4e3),r=a(e.offsetY,FLOAT_DEFAULTS.offsetY,0,4e3),s=["position:fixed",`z-index:${a(e.zIndex,FLOAT_DEFAULTS.zIndex,0,2147483647)}`];return o==="L"||o==="R"?(s.push("top:50%","transform:translateY(-50%)"),s.push(o==="L"?`left:${n}px`:`right:${n}px`)):(s.push(o[0]==="T"?`top:${r}px`:`bottom:${r}px`),s.push(o[1]==="L"?`left:${n}px`:`right:${n}px`)),e.width!=null&&e.width!==""&&s.push(`width:${a(e.width,260,120,600)}px`),s.push(`max-height:calc(100vh - ${o==="L"||o==="R"?32:r*2}px)`),s.push(...u(e)),s.join(";")}export const FLOAT_FLAGS=["collapsible","collapsed","movable","resizable"];export function floatBehaviour(t){const e={collapsible:!1,collapsed:!1,movable:!1,resizable:!1,chrome:!1,title:""};if(!t||t.position!=="floating")return e;const o=t.float&&typeof t.float=="object"&&!Array.isArray(t.float)?t.float:{},n={collapsible:!!o.collapsible,collapsed:!!o.collapsible&&!!o.collapsed,movable:!!o.movable,resizable:!!o.resizable},r=n.collapsible||n.movable,i=typeof o.title=="string"&&o.title!==""?o.title:t.name||"";return{...n,chrome:r,title:r?i:""}}export function applyFloat(t,e){const o=floatToCss(e);if(!t||!o)return!1;t.style.cssText+=";"+o,t.classList.add("dm-menu-floating"),e.slug&&!t.hasAttribute("data-menu")&&t.setAttribute("data-menu",e.slug),e.float?.anchor&&t.setAttribute("data-float-anchor",e.float.anchor);const n=floatBehaviour(e);for(const r of FLOAT_FLAGS)r!=="collapsed"&&n[r]&&t.setAttribute(`data-float-${r}`,"1");return n.collapsed&&t.setAttribute("data-float-collapsed","1"),n.title&&t.setAttribute("data-float-title",n.title),!0}export function makeBadgeEl(t){if(!t||t.text==null||t.text==="")return null;const e=document.createElement("span");e.className="dm-menu-badge",e.textContent=String(t.text);const o=t.variant?colourToCss(t.variant):"";return o&&(e.style.background=o,e.style.color="var(--dm-text-inverse, #fff)"),e}export function applyColour(t,e){const o=colourToCss(e);o&&(t.style.color=o)}export function applyPill(t,e){if(!e)return;t.classList.add("dm-nav-pill");const o=e.variant?colourToCss(e.variant):"";e.style==="outline"?(t.classList.add("dm-nav-pill--outline"),o&&(t.style.borderColor=o,t.style.color=o)):o&&(t.style.background=o,t.style.color="#fff")}export const MENU_ALIGN=["left","centre","right","spread"];export function menuAlign(t){const e=t&&t.align;return MENU_ALIGN.includes(e)?e:""}export const HIGHLIGHT_HOVER=["none","colour","underline","overline","background","uppercase","grow","breathe","glow"],HIGHLIGHT_ACTIVE=["none","bold","underline","overline","background","darken","pill"],HIGHLIGHT_HOVER_LABELS={none:"None - no change on hover",colour:"Colour change",underline:"Underline",overline:"Overline",background:"Background tint",uppercase:"Uppercase",grow:"Grow",breathe:"Breathe",glow:"Glow"},HIGHLIGHT_ACTIVE_LABELS={none:"None - not marked at all",bold:"Bold",underline:"Underline",overline:"Overline",background:"Background tint",darken:"Darkened",pill:"Filled pill"},LEGACY_STYLE_HOVER={none:"none",underline:"underline",overline:"overline",transform:"uppercase","text-transform":"uppercase",breathe:"breathe"},LEGACY_STYLE_ACTIVE={none:"none",darken:"darken",background:"background","background-color":"background",underline:"underline",overline:"overline"};export function legacyStyleHighlight(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{hover:LEGACY_STYLE_HOVER[e.hover]||"",active:LEGACY_STYLE_ACTIVE[e.active]||""}}export function highlightAttrs(t){const e=t&&t.highlight&&typeof t.highlight=="object"&&!Array.isArray(t.highlight)?t.highlight:{},o=legacyStyleHighlight(t&&t.style);return{hover:HIGHLIGHT_HOVER.includes(e.hover)?e.hover:o.hover,active:HIGHLIGHT_ACTIVE.includes(e.active)?e.active:o.active,accent:e.accent?colourToCss(e.accent):""}}export function applyHighlight(t,e){if(!t)return!1;const{hover:o,active:n,accent:r}=highlightAttrs(e);return o&&t.setAttribute("data-menu-hover",o),n&&t.setAttribute("data-menu-active",n),r&&t.style.setProperty("--dm-menu-highlight",r),!!(o||n||r)}export function itemHighlightAttrs(t){const e=t&&t.highlight&&typeof t.highlight=="object"&&!Array.isArray(t.highlight)?t.highlight:{};return{hover:HIGHLIGHT_HOVER.includes(e.hover)?e.hover:"",active:HIGHLIGHT_ACTIVE.includes(e.active)?e.active:"",accent:e.accent?colourToCss(e.accent):""}}export function applyItemHighlight(t,e){if(!t)return!1;const{hover:o,active:n,accent:r}=itemHighlightAttrs(e);return o&&t.setAttribute("data-menu-item-hover",o),n&&t.setAttribute("data-menu-item-active",n),r&&t.style.setProperty("--dm-menu-highlight",r),!!(o||n||r)}function c(t){if(typeof t!="string"||!t)return"";const e=t.split("#")[0].split("?")[0];return e.startsWith("/")?e.length>1&&e.endsWith("/")?e.slice(0,-1):e:""}export function isCurrentItem(t,e){const o=c(t),n=c(e);return!!o&&!!n&&o===n}export const CSS_CLASS_RE=/^-?[_a-zA-Z][_a-zA-Z0-9-]*$/,CSS_CLASS_MAX=20,CSS_CLASS_MAX_LEN=64;function l(t){return typeof t!="string"?[]:t.split(/[\s,]+/).map(e=>e.replace(/^\./,"")).filter(Boolean)}export function cssClasses(t){const e=[];for(const o of l(t))if(o.length<=CSS_CLASS_MAX_LEN&&CSS_CLASS_RE.test(o)&&!e.includes(o)&&e.push(o),e.length>=CSS_CLASS_MAX)break;return e}export function cssClassProblems(t){if(t==null||t==="")return[];if(typeof t!="string")return["must be a string of class names"];const e=l(t),o=e.filter(r=>r.length>CSS_CLASS_MAX_LEN||!CSS_CLASS_RE.test(r)),n=[];return o.length&&n.push(`not a valid class name: ${o.join(", ")}`),e.length>CSS_CLASS_MAX&&n.push(`at most ${CSS_CLASS_MAX} classes`),n}export function normaliseCssClasses(t){return cssClasses(t).join(" ")}export function applyClasses(t,e){if(!t)return!1;const o=cssClasses(e);return o.length&&t.classList.add(...o),o.length>0}
package/public/js/site.js CHANGED
@@ -1 +1 @@
1
- import{makeBadgeEl as z,applyColour as O,applyPill as V,applyFloat as J,applyHighlight as N,applyItemHighlight as W,itemHighlightAttrs as X,isCurrentItem as B,menuAlign as G}from"/public/js/menu-decor.mjs?v=20260918-item-highlight";import{initFloatingMenus as Y}from"/public/js/menu-float.js?v=20260829-float-panel";import{enhancePickerFields as j,markInvalidFields as R,showValidationPopup as P}from"/public/js/forms.js?v=20260927-submit-btn";import{buildWizardSteps as U}from"/public/js/form-steps.mjs";import{applySubmitButtons as K,applyWizardButtons as Q}from"/public/js/form-submit.mjs";$(()=>{const C=window.__CMS_NAV__||{},y=window.__CMS_SITE__||{};if(y.autoTheme?.enabled){let t=function(e){const s=(e||"07:00").split(":");return+s[0]*60+(+s[1]||0)},i=function(){const e=new Date,s=e.getHours()*60+e.getMinutes();return s>=t(a.dayStart)&&s<t(a.nightStart)?a.dayTheme:a.nightTheme},o=function(e){const s=a.apply&&a.apply[e]||{theme:e,custom:""};Domma.theme.set(s.theme);for(const p of[...document.body.classList])p.startsWith("dm-custom-")&&document.body.classList.remove(p);s.custom&&document.body.classList.add(s.custom)};const a=y.autoTheme;o(i()),setInterval(()=>o(i()),6e4)}const _=$("#site-navbar");if(_.length&&C.brand){let i=function(c,h=0){return Array.isArray(c)?c.filter(r=>!(r&&r.type==="spacer")).filter(r=>!(r&&r.type==="separator"&&h===0)).map(r=>r&&r.type==="separator"?{divider:!0}:Array.isArray(r?.items)?{...r,items:i(r.items,h+1)}:r):c},o=function(c){return Array.isArray(c)?c.filter(h=>!(h&&(h.type==="separator"||h.type==="spacer"))):[]};const a={...C.brand},t=a.size&&a.size!=="md"?` navbar-brand-${a.size}`:"";if(a.logo||a.icon||a.tagline){let c="";a.logo?c+=`<img src="${a.logo}" class="navbar-brand-logo" alt="${a.text||""}">`:a.icon&&(c+=`<span data-icon="${a.icon}" style="width:1.1em;height:1.1em;margin-right:.35em;vertical-align:middle;"></span>`),a.text&&(c+=`<span class="navbar-brand-text${t}">${a.text}</span>`),a.tagline&&(c+=`<small class="navbar-brand-tagline">${a.tagline}</small>`),a.html=c}else t&&a.text&&(a.html=`<span class="navbar-brand-text${t}">${a.text}</span>`);const e=C.position==="floating",s=C.orientation==="vertical";Domma.elements.navbar("#site-navbar",{brand:a,items:i(C.items||[]),variant:C.variant||"dark",position:e?"static":C.position||"sticky",collapsible:!0,appearOnHover:!!C.appearOnHover}),Domma.icons.scan("#site-navbar");const p=_.get(0);p.classList.add(`dm-nav-align-${G(C)||"centre"}`),s&&_.get(0).classList.add("dm-nav-vertical",C.side==="right"?"dm-nav-vertical-right":"dm-nav-vertical-left"),N(p,C),e&&(J(_.get(0),C),Y(_.get(0).parentNode||document));const g=p.querySelector(".navbar-toggle"),u=p.querySelector(".navbar-collapse");if(g&&u){let c=null;const h=()=>{u.classList.contains("show")&&g.click()},r=()=>{c&&(c.remove(),c=null),document.body.classList.remove("dm-drawer-open")},n=()=>{c||(c=document.createElement("div"),c.className="dm-navbar-backdrop",c.addEventListener("click",h),document.body.appendChild(c),document.body.classList.add("dm-drawer-open"))};g.addEventListener("click",()=>{requestAnimationFrame(()=>{u.classList.contains("show")?n():r()})}),u.addEventListener("click",l=>{l.target.closest("a")&&requestAnimationFrame(r)}),document.addEventListener("keydown",l=>{l.key==="Escape"&&u.classList.contains("show")&&h()})}const m=p.querySelector(".navbar-nav");if(m){const c=Array.from(m.children);let h=0;for(const r of C.items||[])if(!(r&&r.type==="separator")){if(r&&r.type==="spacer"){const n=document.createElement("li"),l=["xs","sm","md","lg","xl","flex"].includes(r.size)?r.size:"md";n.className=`dm-menu-spacer dm-menu-spacer--${l}`,n.setAttribute("aria-hidden","true"),m.insertBefore(n,c[h]||null);continue}h++}}const b=o(C.items||[]);p.querySelectorAll(".navbar-link[data-index], .navbar-dropdown-item[data-index]").forEach(c=>{const h=b[parseInt(c.dataset.index,10)];if(!h)return;const r=c.dataset.subindex!=null,n=r&&Array.isArray(h.items)?h.items[parseInt(c.dataset.subindex,10)]:h;if(!n)return;n.colour&&O(c,n.colour),n.pill&&!r&&V(c,n.pill),W(c,n);const l=z(n.badge);l&&c.appendChild(l),B(n.url,location.pathname)&&(c.classList.add("active"),c.setAttribute("aria-current","page"))})}const x=$("#site-footer");if(x.length){let e=function(n){return String(n??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")},s=function(n){return e(n).replace(/'/g,"&#39;")},p=function(n){if(n&&n.type==="separator")return'<li class="footer-sep"><hr></li>';if(n&&n.type==="spacer")return`<li class="dm-menu-spacer dm-menu-spacer--${["xs","sm","md","lg","xl","flex"].includes(n.size)?n.size:"md"}" aria-hidden="true"></li>`;const l=s(n.url||"#"),d=e(n.text||""),w=Array.isArray(n.items)&&n.items.length?`<ul>${n.items.map(p).join("")}</ul>`:"",v=X(n),D=[v.hover&&` data-menu-item-hover="${s(v.hover)}"`,v.active&&` data-menu-item-active="${s(v.active)}"`].filter(Boolean).join(""),M=v.accent?` style="--dm-menu-highlight:${s(v.accent)}"`:"";return`<li><a href="${l}"${D}${M}>${d}</a>${w}</li>`},g=function(n,l){return(n||[]).forEach(d=>{d&&(d.type==="separator"||d.type==="spacer")||(l.push(d),Array.isArray(d.items)&&d.items.length&&g(d.items,l))}),l};const a=y.social||{},t={twitter:{label:"X / Twitter",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.742l7.73-8.835L1.254 2.25H8.08l4.259 5.629L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>'},facebook:{label:"Facebook",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>'},instagram:{label:"Instagram",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/></svg>'},linkedin:{label:"LinkedIn",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>'},github:{label:"GitHub",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>'},youtube:{label:"YouTube",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M23.495 6.205a3.007 3.007 0 00-2.088-2.088c-1.87-.501-9.396-.501-9.396-.501s-7.507-.01-9.396.501A3.007 3.007 0 00.527 6.205a31.247 31.247 0 00-.522 5.805 31.247 31.247 0 00.522 5.783 3.007 3.007 0 002.088 2.088c1.868.502 9.396.502 9.396.502s7.506 0 9.396-.502a3.007 3.007 0 002.088-2.088 31.247 31.247 0 00.5-5.783 31.247 31.247 0 00-.5-5.805zM9.609 15.601V8.408l6.264 3.602z"/></svg>'}};let i='<div class="footer-inner container">';const o=window.__CMS_FOOTER__||{primary:[],legal:[],copyright:""};if(o.copyright&&(i+=`<p>${e(o.copyright)}</p>`),o.primary.length&&(i+=`<nav class="footer-nav footer-nav--primary"><ul>${o.primary.map(p).join("")}</ul></nav>`),o.legal.length&&(i+=`<nav class="footer-nav footer-nav--legal"><ul>${o.legal.map(p).join("")}</ul></nav>`),y.footer){const n=Object.keys(t).filter(l=>a[l]);n.length&&(i+='<div class="footer-social">',n.forEach(l=>{const{label:d,svg:w}=t[l];i+=`<a href="${a[l]}" target="_blank" rel="noopener noreferrer" aria-label="${d}" class="footer-social-link">${w}</a>`}),i+="</div>")}i+="</div>",x.html(i);const u=[...g(o.primary,[]),...g(o.legal,[])];x.get(0).querySelectorAll(".footer-nav a").forEach((n,l)=>{const d=u[l];if(!d)return;d.colour&&O(n,d.colour);const w=z(d.badge);w&&n.appendChild(w),B(d.url,location.pathname)&&(n.classList.add("is-active"),n.setAttribute("aria-current","page"))}),N(x.get(0).querySelector(".footer-nav--primary"),{highlight:o.primaryHighlight}),N(x.get(0).querySelector(".footer-nav--legal"),{highlight:o.legalHighlight});const b=y.footer?.showMotionToggle!==!1,c=S.get("reduced_motion"),h=c!==null?!!c:!!(window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches),r=x.get(0).querySelector(".footer-inner");if(b&&r){const n=document.createElement("input");n.type="checkbox",n.className="form-switch-input",n.id="dm-motion-switch",n.checked=h,n.addEventListener("change",function(){S.set("reduced_motion",this.checked),window.location.reload()});const l=document.createElement("span");l.className="form-switch-label",l.textContent="Reduce motion";const d=document.createElement("label");d.className="form-switch footer-motion-switch",d.title="Reduce motion",d.appendChild(n),d.appendChild(l),r.appendChild(d)}}$("#site-sidebar").length&&Domma.elements.sidebar("#site-sidebar",{autoGenerate:!0,selector:"h2, h3",collapsible:!1,push:!0,contentSelector:".site-content"}),Domma.icons.scan(),Domma.syntax?.scan&&Domma.syntax.scan();const f=$(".page-body");if(f.length){f.find(".accordion").each(function(){Domma.elements.accordion(this,{allowMultiple:this.dataset.multi==="true"})}),f.find(".tabs").each(function(){Domma.elements.tabs(this)}),f.find(".carousel").each(function(){const a={autoplay:this.dataset.autoplay==="true",interval:parseInt(this.dataset.interval,10)||5e3,loop:this.dataset.loop!=="false",animation:this.dataset.animation||"slide"};if(this.dataset.animationDuration){const t=parseInt(this.dataset.animationDuration,10);Number.isFinite(t)&&(a.animationDuration=t)}this.dataset.animationEasing&&(a.animationEasing=this.dataset.animationEasing),this.dataset.ctx&&(this._dmCtxSlides=Array.from(this.querySelectorAll(".carousel-slide")).map(t=>t.cloneNode(!0)),this._dmCarouselOpts=a),this._dmCarousel=Domma.elements.carousel(this,a)}),f.find(".dm-countdown").each(function(){const a={autoStart:!0},t=String(this.dataset.format||"").trim(),i=String(this.dataset.to||"").trim(),o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(i),e=o?new Date(+o[1],+o[2]-1,+o[3]).getTime():i?new Date(i).getTime():NaN;Number.isFinite(e)?a.duration=Math.max(0,e-Date.now()):this.dataset.duration&&(a.duration=(parseInt(this.dataset.duration,10)||0)*1e3);const s=/^dd:/i.test(t);a.format=s?"hh:mm:ss":t||(a.duration>=36e5?"hh:mm:ss":"mm:ss");const p=this,g=m=>String(m).padStart(2,"0"),u=m=>{const b=Math.max(0,Math.floor(m/1e3)),c=p.querySelector(".dm-timer-time");c&&(c.textContent=`${g(Math.floor(b/86400))}:${g(Math.floor(b%86400/3600))}:${g(Math.floor(b%3600/60))}:${g(b%60)}`)};s&&(a.onTick=u),Domma.elements.timer(this,a),s&&u(a.duration||0)}),f.find("[data-tooltip]").each(function(){Domma.elements.tooltip(this,{content:$(this).data("tooltip"),position:$(this).data("tooltip-position")||"top"})}),f.find(".dm-progression").each(function(){const a=Array.from(this.querySelectorAll(".dm-progression-item")).map(o=>{const e={title:o.querySelector(".dm-progression-item-title")?.textContent?.trim()||"",description:o.querySelector(".dm-progression-item-body")?.innerHTML?.trim()||""};return o.dataset.date&&(e.date=o.dataset.date),o.dataset.status&&(e.status=o.dataset.status),o.dataset.entryId&&(e._entryId=o.dataset.entryId),e}),t=this.dataset.layout==="centred"?"centered":this.dataset.layout||"vertical",i=Domma.elements.progression(this,{layout:t,theme:this.dataset.theme||"minimal",mode:this.dataset.mode||"timeline",statusIcons:!0,allowHtml:!0,...a.length?{items:a}:{}});a.length&&(this._dmCtx={instance:i,items:a})});try{Domma.effects.reveal(".page-body .hero",{animation:"slide-up",duration:480,threshold:.06,stagger:60,once:!1})}catch{}document.querySelectorAll(".page-body .row[data-reveal]").forEach(a=>{const t=a.dataset.revealMode||"stagger",i=a.dataset.revealAnimation||"slide-up",o=parseInt(a.dataset.revealDuration,10)||400,e=parseInt(a.dataset.revealStagger,10)||60,s=parseInt(a.dataset.revealDelay,10)||0,p=a.dataset.revealDirection==="rtl",g=Array.from(a.children),u={"slide-up":"translateY(30px)","slide-down":"translateY(-30px)","slide-left":"translateX(30px)","slide-right":"translateX(-30px)",zoom:"scale(0.85)",flip:"perspective(600px) rotateX(15deg)"};g.forEach((m,b)=>{m.style.opacity="0",m.style.transform=u[i]||"",m.style.transition=`opacity ${o}ms ease, transform ${o}ms ease`;const c=p?g.length-1-b:b;m.style.transitionDelay=t==="stagger"?`${s+c*e}ms`:`${s}ms`}),requestAnimationFrame(()=>requestAnimationFrame(()=>{const m=new IntersectionObserver(b=>{b.forEach(c=>{c.isIntersecting&&(c.target.offsetWidth,c.target.style.opacity="1",c.target.style.transform="none",m.unobserve(c.target))})},{threshold:.1});g.forEach(b=>m.observe(b))}))}),f.find(".card[data-collapsible]").each(function(){const a=this.querySelector(".card-header");a&&a.addEventListener("click",()=>this.classList.toggle("is-collapsed"))}),f.find(".dm-so-trigger").each(function(){this.addEventListener("click",()=>{const a=this.dataset.soTarget,t=document.getElementById(a);if(!t)return;const i=E.slideover({title:t.dataset.soTitle||"",size:t.dataset.soSize||"md",position:t.dataset.soPosition||"right"});t.style.display="",i.setContent(t),i.open()})})}if(typeof $.setup=="function"){const a=Object.assign({},window.__CMS_DCONFIG__||{});if(document.querySelectorAll(".dm-page-config[data-config]").forEach(t=>{try{const i=atob(t.dataset.config),o=JSON.parse(i);Object.assign(a,o)}catch{}}),Object.keys(a).length>0){const t={};for(const[i,o]of Object.entries(a)){const e=o?.events?.click,{confirm:s,toast:p,alert:g,prompt:u,...m}=e||{};s||p||g||u?($(i).on("click",async function(c){if(c.preventDefault(),s&&!await E.confirm(s))return;let h=null;if(!(u&&(h=await E.prompt(u,{inputPlaceholder:m.promptPlaceholder||"",inputValue:m.promptDefault||""}),h===null))){if(m.target){const r=$(m.target);m.toggleClass&&r.toggleClass(m.toggleClass),m.addClass&&r.addClass(m.addClass),m.removeClass&&r.removeClass(m.removeClass),h!==null&&(m.setText&&r.text(h),m.setVal&&r.val(h),m.setAttr&&r.attr(m.setAttr,h))}m.href&&(window.location.href=m.href),p&&E.toast(p,{type:m.toastType||"success"}),g&&E.alert(g)}}),Object.keys(m).length&&(t[i]={...o,events:{...o.events,click:m}})):t[i]=o}$.setup(t)}}f.length&&I(f.get(0))}),window.wireCTAButtons=I;function I(C){C.querySelectorAll(".dm-cta-trigger").forEach(y=>{y.__ctaWired||(y.__ctaWired=!0,y.addEventListener("click",async()=>{const _=y.dataset.action,x=y.dataset.entry,A=y.dataset.confirm;let f=S.get("auth_token");if(!f){E.toast("Please log in to perform this action.",{type:"warning"});return}if(A&&!await E.confirm(A))return;const a=Array.from(y.childNodes).map(i=>i.cloneNode(!0));y.disabled=!0,y.textContent="Running\u2026";const t=i=>fetch(`/api/actions/${_}/public`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(y.dataset.scope?{entryId:x,scope:y.dataset.scope}:{entryId:x})});try{let i=await t(f);if(i.status===401){const e=S.get("auth_refresh_token");if(e){const s=await fetch("/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(s.ok){const{token:p}=await s.json();S.set("auth_token",p),f=p,i=await t(f)}}}const o=await i.json().catch(()=>({}));if(!i.ok)throw new Error(o.error||o.message||`Error ${i.status}`);E.toast(o.message||"Action completed.",{type:"success"})}catch(i){E.toast(i.message||"Action failed.",{type:"error"})}finally{y.disabled=!1,y.textContent="",a.forEach(i=>y.appendChild(i)),Domma.icons.scan(y)}}))})}(function(){const y=document.querySelectorAll('.dm-collection-hydrate[data-collection-scope="mine"]');if(!y.length)return;const _=S.get("auth_token");function x(f,a){const t=document.createElement("div");t.className="dm-collection-display dm-collection-empty";const i=document.createElement("p");if(a){i.appendChild(document.createTextNode("Please "));const o=document.createElement("a");o.href="/login",o.textContent="sign in",i.appendChild(o),i.appendChild(document.createTextNode(" to view your entries."))}else i.textContent=f;return t.appendChild(i),t}function A(f,a){const t=document.createElement("template");t.innerHTML=a||"",f.replaceWith(t.content)}y.forEach(async f=>{const a=f.dataset.collectionAttrs;if(!a)return;if(!_){f.replaceChildren(x("",!0));return}const t=i=>fetch("/api/collections/render-scope",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({attrs:a})});try{let i=_,o=await t(i);if(o.status===401){const s=S.get("auth_refresh_token");if(s){const p=await fetch("/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:s})});if(p.ok){const{token:g}=await p.json();S.set("auth_token",g),i=g,o=await t(i)}}}if(!o.ok){const{error:s}=await o.json().catch(()=>({}));f.replaceChildren(x(s||"Unable to load entries.",!1));return}const{html:e}=await o.json();A(f,e),window.DommaCollectionBrowser?.hydrate&&window.DommaCollectionBrowser.hydrate(document)}catch{f.replaceChildren(x("Unable to load entries.",!1))}}),setTimeout(()=>{typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(),typeof Domma<"u"&&Domma.syntax?.scan&&Domma.syntax.scan(),I(document.body)},100)})(),(function(){const y=document.querySelectorAll("[data-collection-table]");!y.length||typeof T>"u"||!T.create||y.forEach(_=>{let x;try{x=JSON.parse(atob(_.dataset.payload))}catch{return}const{columns:A,rows:f,search:a,sortable:t,exportable:i,pageSize:o,empty:e,ctaConfig:s,slug:p,exportCfg:g}=x;if(!A?.length)return;if(s){const b=A.findIndex(c=>c.key==="_cta");b!==-1&&(A[b]={key:"_cta",title:"",render:(c,h)=>{const r=document.createElement("button");if(r.className=`btn btn-${s.style||"primary"} dm-cta-trigger`,r.dataset.action=s.action||"",s.scope&&(r.dataset.scope=s.scope),r.dataset.entry=h._entryId||"",s.confirm&&(r.dataset.confirm=s.confirm),s.icon){const n=document.createElement("span");n.dataset.icon=s.icon,r.appendChild(n),r.appendChild(document.createTextNode(" "))}return r.appendChild(document.createTextNode(s.label||"Run")),r}})}const u="col-table-"+Math.random().toString(36).slice(2,7),m=document.createElement("div");m.id=u,_.replaceChildren(m),T.create("#"+u,{data:f,columns:A,search:a,sortable:t,exportable:i,pageSize:o,emptyMessage:e}),s&&I(m),_._dmTable={columns:A,rows:f,slug:p,exportCfg:g,render(b){T.create("#"+u,{data:b,columns:A,search:a,sortable:t,exportable:i,pageSize:o,emptyMessage:e}),s&&I(m)}}})})(),(function(){const y=document.querySelectorAll("[data-form-inline]");if(!y.length||typeof F>"u")return;function _(t){const i=t&&t.logic;return!!(i&&(i.visibility||i.requirement))}function x(t,i){const o={};return(t||[]).forEach(e=>{if(e.type==="page-break"||e.type==="spacer"||!e.name)return;const s=e.type==="chooser"||!!(e.variant&&["select","radio","checkbox-group"].includes(e.type)),p=e.type==="checkbox"?"boolean":e.type==="date"||e.type==="icon"||e.type==="image"?"string":s?"chooser":e.type,g={...e.formConfig||{}};g.span==="full"&&i&&(g.span=i);const u={type:p,required:_(e)?!1:e.required,label:e.label,options:e.options,formConfig:{...e.placeholder&&{placeholder:e.placeholder},...e.helper&&{hint:e.helper},...e.tooltip&&{tooltip:e.tooltip},...g}};e.minLength!==void 0&&(u.minLength=e.minLength),e.maxLength!==void 0&&(u.maxLength=e.maxLength),e.min!==void 0&&(u.min=e.min),e.max!==void 0&&(u.max=e.max),s&&(e.variant&&(u.variant=e.variant),(e.multiple||e.type==="checkbox-group")&&(u.multiple=!0),e.density&&(u.density=e.density),e.columns&&(u.columns=e.columns),e.accent&&(u.accent=e.accent),e.accentStyle&&(u.accentStyle=e.accentStyle),e.glow&&(u.glow=!0),e.glowColour&&(u.glowColour=e.glowColour),e.shadow&&(u.shadow=e.shadow),e.shadowColour&&(u.shadowColour=e.shadowColour)),o[e.name]=u}),o}function A(t){const i={};return(t||[]).forEach(o=>{if(!(!o.name||o.type==="page-break"||o.type==="spacer")&&(o.type==="select"||o.type==="multiselect")&&o.required){const e=(o.options||[])[0];e&&(i[o.name]=typeof e=="object"?e.value:e)}}),i}function f(t,i){(i||[]).forEach(o=>{if(o.type!=="date"||!o.name)return;const e=t.querySelector(`[name="${o.name}"]`);e&&e.type!=="date"&&(e.type="date")})}function a(t,i,o){let e=t.querySelector(".cms-form-message");e||(e=document.createElement("p"),e.className="cms-form-message",t.appendChild(e)),e.textContent=i,e.style.cssText=o?"color:var(--dm-danger);margin-top:.75rem;":"color:var(--dm-success);margin-top:.75rem;"}y.forEach(t=>{let i;try{i=JSON.parse(atob(t.dataset.formInline))}catch{return}const o=i.fields||[],e=i.settings||{},s=Number(e.columns)===3?3:2,p=e.layout||"grid",g=o.some(r=>r.type==="page-break"),u=async r=>{if(t.dataset.triggerBlocked==="true"){const n=t._formLogicRuntime,l=n&&n.submitBlock?n.submitBlock().reasons:[];a(t,l.join(" ")||"This form cannot be submitted yet.",!0);const d=new Error("Blocked by a form trigger");throw d.formSubmitFailed=!0,d}try{const n=t.querySelector(".fb-form-honeypot"),l=n?.querySelector('input[type="text"]')||null,d=n?.querySelector('[name="_t"]')||null,w=Object.assign({},r);delete w._t,n?.dataset.hpName&&delete w[n.dataset.hpName],l!==null&&(w._hp=l.value),d!==null&&(w._t=d.value);const v=await H.post(`/api/forms/submit/${i.slug}`,w);if(v&&v.error){a(t,v.error,!0);const D=new Error(v.error);throw D.formSubmitFailed=!0,D}if(v?.redirect){window.location.href=v.redirect;return}for(;t.firstChild;)t.removeChild(t.firstChild);a(t,v?.message||e.successMessage||"Thank you for your submission.",!1)}catch(n){throw n.formSubmitFailed||a(t,n.message||"Submission failed. Please try again.",!0),n}},m=Date.now();function b(r){const n=r.querySelector("form");if(!n||n.querySelector(".fb-form-honeypot"))return;const l=document.createElement("div");l.className="fb-form-honeypot",l.setAttribute("aria-hidden","true");const d=document.createElement("input");d.name=n.querySelector('[name="website"]')?"_website":"website",l.dataset.hpName=d.name,d.type="text",d.tabIndex=-1,d.autocomplete="url",d.placeholder="https://",l.appendChild(d);const w=document.createElement("input");w.name="_t",w.type="hidden",w.value=m,l.appendChild(w),n.appendChild(l)}function c(r){if(!window.FormLogicEngine||!o.some(l=>l.logic||Array.isArray(l.triggers)&&l.triggers.length))return null;const n=new window.FormLogicEngine.FormLogicRuntime(i,t,r?{baseValues:r}:void 0);if(n.init(),t._formLogicRuntime=n,t._formLogicObserved)return n;if(t._formLogicObserved=!0,t.parentNode&&typeof MutationObserver<"u"){const l=new MutationObserver(function(d){for(const w of d)for(const v of w.removedNodes)if(v===t||v.nodeType===1&&v.contains&&v.contains(t)){t._formLogicRuntime&&t._formLogicRuntime.destroy(),l.disconnect();return}});l.observe(t.parentNode,{childList:!0,subtree:!1}),t._formLogicObserver=l}return n}let h=!1;if(t.addEventListener("dm-form-end",r=>{const n=r.detail?.validation;if(n&&!n.valid){R(t,n.missing),P(n);return}h||(h=!0,u(r.detail?.values||{}).catch(()=>{}).finally(()=>{h=!1}))}),g&&F.wizard){const r=U(o,i.title),n=r.map(k=>({title:k.title,description:k.description,fields:x(k.fields,s)})),l=r.map(k=>k.fields);let d=0,w=null,v=null;const D=k=>{const L=window.FormLogicEngine;if(!L||!L.validateFields)return;const q=L.validateFields(t,l[d]||[]);q.valid||(k.preventDefault(),k.stopImmediatePropagation(),R(t,q.missing),P(q))},M=()=>{const k=l[d]||o;Q(t,e),f(t,k),j(t,k),e.honeypot!==!1&&b(t),w&&w.destroy(),w=c(v?.getStepData?v.getStepData():void 0),t.querySelectorAll(".wizard-next, .wizard-submit").forEach(L=>L.addEventListener("click",D,!0))};v=F.wizard(t,{schema:{steps:n},layout:p,columns:s,finishText:e.submitText||"Finish",onSubmit:u,onStepChange:k=>{d=k,setTimeout(M,0)}}),t.addEventListener("dm-form-trigger",k=>{if(k.detail?.type!=="goto-step"||!v?.goToStep)return;const L=Number(k.detail.action.step);!Number.isFinite(L)||L<0||L>=n.length||L!==d&&v.goToStep(L)}),Promise.resolve(v).then(M)}else if(F.render){const r=F.render(t,x(o,s),A(o),{submitText:e.submitText||"Submit",layout:p,columns:s,onSubmit:u});Promise.resolve(r).then(function(){K(t,e,p),f(t,o),j(t,o),e.honeypot!==!1&&b(t),c()})}}),$(document).on("click",".dm-banner__dismiss",function(){$(this).closest(".dm-banner").remove()})})();
1
+ import{makeBadgeEl as O,applyColour as B,applyPill as J,applyFloat as W,applyHighlight as z,applyItemHighlight as X,itemHighlightAttrs as G,isCurrentItem as j,menuAlign as Y,applyClasses as M,cssClasses as U}from"/public/js/menu-decor.mjs?v=20261009-menu-classes";import{initFloatingMenus as K}from"/public/js/menu-float.js?v=20260829-float-panel";import{enhancePickerFields as R,markInvalidFields as P,showValidationPopup as V}from"/public/js/forms.js?v=20260927-submit-btn";import{buildWizardSteps as Q}from"/public/js/form-steps.mjs";import{applySubmitButtons as Z,applyWizardButtons as ee}from"/public/js/form-submit.mjs";$(()=>{const x=window.__CMS_NAV__||{},y=window.__CMS_SITE__||{};if(y.autoTheme?.enabled){let t=function(e){const i=(e||"07:00").split(":");return+i[0]*60+(+i[1]||0)},s=function(){const e=new Date,i=e.getHours()*60+e.getMinutes();return i>=t(n.dayStart)&&i<t(n.nightStart)?n.dayTheme:n.nightTheme},a=function(e){const i=n.apply&&n.apply[e]||{theme:e,custom:""};Domma.theme.set(i.theme);for(const p of[...document.body.classList])p.startsWith("dm-custom-")&&document.body.classList.remove(p);i.custom&&document.body.classList.add(i.custom)};const n=y.autoTheme;a(s()),setInterval(()=>a(s()),6e4)}const _=$("#site-navbar");if(_.length&&x.brand){let s=function(c,h=0){return Array.isArray(c)?c.filter(r=>!(r&&r.type==="spacer")).filter(r=>!(r&&r.type==="separator"&&h===0)).map(r=>r&&r.type==="separator"?{divider:!0}:Array.isArray(r?.items)?{...r,items:s(r.items,h+1)}:r):c},a=function(c){return Array.isArray(c)?c.filter(h=>!(h&&(h.type==="separator"||h.type==="spacer"))):[]};const n={...x.brand},t=n.size&&n.size!=="md"?` navbar-brand-${n.size}`:"";if(n.logo||n.icon||n.tagline){let c="";n.logo?c+=`<img src="${n.logo}" class="navbar-brand-logo" alt="${n.text||""}">`:n.icon&&(c+=`<span data-icon="${n.icon}" style="width:1.1em;height:1.1em;margin-right:.35em;vertical-align:middle;"></span>`),n.text&&(c+=`<span class="navbar-brand-text${t}">${n.text}</span>`),n.tagline&&(c+=`<small class="navbar-brand-tagline">${n.tagline}</small>`),n.html=c}else t&&n.text&&(n.html=`<span class="navbar-brand-text${t}">${n.text}</span>`);const e=x.position==="floating",i=x.orientation==="vertical";Domma.elements.navbar("#site-navbar",{brand:n,items:s(x.items||[]),variant:x.variant||"dark",position:e?"static":x.position||"sticky",collapsible:!0,appearOnHover:!!x.appearOnHover}),Domma.icons.scan("#site-navbar");const p=_.get(0);p.classList.add(`dm-nav-align-${Y(x)||"centre"}`),i&&_.get(0).classList.add("dm-nav-vertical",x.side==="right"?"dm-nav-vertical-right":"dm-nav-vertical-left"),z(p,x),M(p,x.class),e&&(W(_.get(0),x),K(_.get(0).parentNode||document));const g=p.querySelector(".navbar-toggle"),u=p.querySelector(".navbar-collapse");if(g&&u){let c=null;const h=()=>{u.classList.contains("show")&&g.click()},r=()=>{c&&(c.remove(),c=null),document.body.classList.remove("dm-drawer-open")},o=()=>{c||(c=document.createElement("div"),c.className="dm-navbar-backdrop",c.addEventListener("click",h),document.body.appendChild(c),document.body.classList.add("dm-drawer-open"))};g.addEventListener("click",()=>{requestAnimationFrame(()=>{u.classList.contains("show")?o():r()})}),u.addEventListener("click",l=>{l.target.closest("a")&&requestAnimationFrame(r)}),document.addEventListener("keydown",l=>{l.key==="Escape"&&u.classList.contains("show")&&h()})}const m=p.querySelector(".navbar-nav");if(m){const c=Array.from(m.children);let h=0;for(const r of x.items||[])if(!(r&&r.type==="separator")){if(r&&r.type==="spacer"){const o=document.createElement("li"),l=["xs","sm","md","lg","xl","flex"].includes(r.size)?r.size:"md";o.className=`dm-menu-spacer dm-menu-spacer--${l}`,o.setAttribute("aria-hidden","true"),m.insertBefore(o,c[h]||null);continue}h++}}const b=a(x.items||[]);p.querySelectorAll(".navbar-link[data-index], .navbar-dropdown-item[data-index]").forEach(c=>{const h=b[parseInt(c.dataset.index,10)];if(!h)return;const r=c.dataset.subindex!=null,o=r&&Array.isArray(h.items)?h.items[parseInt(c.dataset.subindex,10)]:h;if(!o)return;o.colour&&B(c,o.colour),o.pill&&!r&&J(c,o.pill),X(c,o),M(c.closest("li"),o.class);const l=O(o.badge);l&&c.appendChild(l),j(o.url,location.pathname)&&(c.classList.add("active"),c.setAttribute("aria-current","page"))})}const C=$("#site-footer");if(C.length){let e=function(o){return String(o??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")},i=function(o){return e(o).replace(/'/g,"&#39;")},p=function(o){if(o&&o.type==="separator")return'<li class="footer-sep"><hr></li>';if(o&&o.type==="spacer")return`<li class="dm-menu-spacer dm-menu-spacer--${["xs","sm","md","lg","xl","flex"].includes(o.size)?o.size:"md"}" aria-hidden="true"></li>`;const l=i(o.url||"#"),d=e(o.text||""),w=Array.isArray(o.items)&&o.items.length?`<ul>${o.items.map(p).join("")}</ul>`:"",v=G(o),D=[v.hover&&` data-menu-item-hover="${i(v.hover)}"`,v.active&&` data-menu-item-active="${i(v.active)}"`].filter(Boolean).join(""),q=v.accent?` style="--dm-menu-highlight:${i(v.accent)}"`:"",k=U(o.class).join(" ");return`<li${k?` class="${i(k)}"`:""}><a href="${l}"${D}${q}>${d}</a>${w}</li>`},g=function(o,l){return(o||[]).forEach(d=>{d&&(d.type==="separator"||d.type==="spacer")||(l.push(d),Array.isArray(d.items)&&d.items.length&&g(d.items,l))}),l};const n=y.social||{},t={twitter:{label:"X / Twitter",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.742l7.73-8.835L1.254 2.25H8.08l4.259 5.629L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>'},facebook:{label:"Facebook",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>'},instagram:{label:"Instagram",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/></svg>'},linkedin:{label:"LinkedIn",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>'},github:{label:"GitHub",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>'},youtube:{label:"YouTube",svg:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M23.495 6.205a3.007 3.007 0 00-2.088-2.088c-1.87-.501-9.396-.501-9.396-.501s-7.507-.01-9.396.501A3.007 3.007 0 00.527 6.205a31.247 31.247 0 00-.522 5.805 31.247 31.247 0 00.522 5.783 3.007 3.007 0 002.088 2.088c1.868.502 9.396.502 9.396.502s7.506 0 9.396-.502a3.007 3.007 0 002.088-2.088 31.247 31.247 0 00.5-5.783 31.247 31.247 0 00-.5-5.805zM9.609 15.601V8.408l6.264 3.602z"/></svg>'}};let s='<div class="footer-inner container">';const a=window.__CMS_FOOTER__||{primary:[],legal:[],copyright:""};if(a.copyright&&(s+=`<p>${e(a.copyright)}</p>`),a.primary.length&&(s+=`<nav class="footer-nav footer-nav--primary"><ul>${a.primary.map(p).join("")}</ul></nav>`),a.legal.length&&(s+=`<nav class="footer-nav footer-nav--legal"><ul>${a.legal.map(p).join("")}</ul></nav>`),y.footer){const o=Object.keys(t).filter(l=>n[l]);o.length&&(s+='<div class="footer-social">',o.forEach(l=>{const{label:d,svg:w}=t[l];s+=`<a href="${n[l]}" target="_blank" rel="noopener noreferrer" aria-label="${d}" class="footer-social-link">${w}</a>`}),s+="</div>")}s+="</div>",C.html(s);const u=[...g(a.primary,[]),...g(a.legal,[])];C.get(0).querySelectorAll(".footer-nav a").forEach((o,l)=>{const d=u[l];if(!d)return;d.colour&&B(o,d.colour);const w=O(d.badge);w&&o.appendChild(w),j(d.url,location.pathname)&&(o.classList.add("is-active"),o.setAttribute("aria-current","page"))}),z(C.get(0).querySelector(".footer-nav--primary"),{highlight:a.primaryHighlight}),z(C.get(0).querySelector(".footer-nav--legal"),{highlight:a.legalHighlight}),M(C.get(0).querySelector(".footer-nav--primary"),a.primaryClass),M(C.get(0).querySelector(".footer-nav--legal"),a.legalClass);const b=y.footer?.showMotionToggle!==!1,c=S.get("reduced_motion"),h=c!==null?!!c:!!(window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches),r=C.get(0).querySelector(".footer-inner");if(b&&r){const o=document.createElement("input");o.type="checkbox",o.className="form-switch-input",o.id="dm-motion-switch",o.checked=h,o.addEventListener("change",function(){S.set("reduced_motion",this.checked),window.location.reload()});const l=document.createElement("span");l.className="form-switch-label",l.textContent="Reduce motion";const d=document.createElement("label");d.className="form-switch footer-motion-switch",d.title="Reduce motion",d.appendChild(o),d.appendChild(l),r.appendChild(d)}}$("#site-sidebar").length&&Domma.elements.sidebar("#site-sidebar",{autoGenerate:!0,selector:"h2, h3",collapsible:!1,push:!0,contentSelector:".site-content"}),Domma.icons.scan(),Domma.syntax?.scan&&Domma.syntax.scan();const f=$(".page-body");if(f.length){f.find(".accordion").each(function(){Domma.elements.accordion(this,{allowMultiple:this.dataset.multi==="true"})}),f.find(".tabs").each(function(){Domma.elements.tabs(this)}),f.find(".carousel").each(function(){const n={autoplay:this.dataset.autoplay==="true",interval:parseInt(this.dataset.interval,10)||5e3,loop:this.dataset.loop!=="false",animation:this.dataset.animation||"slide"};if(this.dataset.animationDuration){const t=parseInt(this.dataset.animationDuration,10);Number.isFinite(t)&&(n.animationDuration=t)}this.dataset.animationEasing&&(n.animationEasing=this.dataset.animationEasing),this.dataset.ctx&&(this._dmCtxSlides=Array.from(this.querySelectorAll(".carousel-slide")).map(t=>t.cloneNode(!0)),this._dmCarouselOpts=n),this._dmCarousel=Domma.elements.carousel(this,n)}),f.find(".dm-countdown").each(function(){const n={autoStart:!0},t=String(this.dataset.format||"").trim(),s=String(this.dataset.to||"").trim(),a=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s),e=a?new Date(+a[1],+a[2]-1,+a[3]).getTime():s?new Date(s).getTime():NaN;Number.isFinite(e)?n.duration=Math.max(0,e-Date.now()):this.dataset.duration&&(n.duration=(parseInt(this.dataset.duration,10)||0)*1e3);const i=/^dd:/i.test(t);n.format=i?"hh:mm:ss":t||(n.duration>=36e5?"hh:mm:ss":"mm:ss");const p=this,g=m=>String(m).padStart(2,"0"),u=m=>{const b=Math.max(0,Math.floor(m/1e3)),c=p.querySelector(".dm-timer-time");c&&(c.textContent=`${g(Math.floor(b/86400))}:${g(Math.floor(b%86400/3600))}:${g(Math.floor(b%3600/60))}:${g(b%60)}`)};i&&(n.onTick=u),Domma.elements.timer(this,n),i&&u(n.duration||0)}),f.find("[data-tooltip]").each(function(){Domma.elements.tooltip(this,{content:$(this).data("tooltip"),position:$(this).data("tooltip-position")||"top"})}),f.find(".dm-progression").each(function(){const n=Array.from(this.querySelectorAll(".dm-progression-item")).map(a=>{const e={title:a.querySelector(".dm-progression-item-title")?.textContent?.trim()||"",description:a.querySelector(".dm-progression-item-body")?.innerHTML?.trim()||""};return a.dataset.date&&(e.date=a.dataset.date),a.dataset.status&&(e.status=a.dataset.status),a.dataset.entryId&&(e._entryId=a.dataset.entryId),e}),t=this.dataset.layout==="centred"?"centered":this.dataset.layout||"vertical",s=Domma.elements.progression(this,{layout:t,theme:this.dataset.theme||"minimal",mode:this.dataset.mode||"timeline",statusIcons:!0,allowHtml:!0,...n.length?{items:n}:{}});n.length&&(this._dmCtx={instance:s,items:n})});try{Domma.effects.reveal(".page-body .hero",{animation:"slide-up",duration:480,threshold:.06,stagger:60,once:!1})}catch{}document.querySelectorAll(".page-body .row[data-reveal]").forEach(n=>{const t=n.dataset.revealMode||"stagger",s=n.dataset.revealAnimation||"slide-up",a=parseInt(n.dataset.revealDuration,10)||400,e=parseInt(n.dataset.revealStagger,10)||60,i=parseInt(n.dataset.revealDelay,10)||0,p=n.dataset.revealDirection==="rtl",g=Array.from(n.children),u={"slide-up":"translateY(30px)","slide-down":"translateY(-30px)","slide-left":"translateX(30px)","slide-right":"translateX(-30px)",zoom:"scale(0.85)",flip:"perspective(600px) rotateX(15deg)"};g.forEach((m,b)=>{m.style.opacity="0",m.style.transform=u[s]||"",m.style.transition=`opacity ${a}ms ease, transform ${a}ms ease`;const c=p?g.length-1-b:b;m.style.transitionDelay=t==="stagger"?`${i+c*e}ms`:`${i}ms`}),requestAnimationFrame(()=>requestAnimationFrame(()=>{const m=new IntersectionObserver(b=>{b.forEach(c=>{c.isIntersecting&&(c.target.offsetWidth,c.target.style.opacity="1",c.target.style.transform="none",m.unobserve(c.target))})},{threshold:.1});g.forEach(b=>m.observe(b))}))}),f.find(".card[data-collapsible]").each(function(){const n=this.querySelector(".card-header");n&&n.addEventListener("click",()=>this.classList.toggle("is-collapsed"))}),f.find(".dm-so-trigger").each(function(){this.addEventListener("click",()=>{const n=this.dataset.soTarget,t=document.getElementById(n);if(!t)return;const s=E.slideover({title:t.dataset.soTitle||"",size:t.dataset.soSize||"md",position:t.dataset.soPosition||"right"});t.style.display="",s.setContent(t),s.open()})})}if(typeof $.setup=="function"){const n=Object.assign({},window.__CMS_DCONFIG__||{});if(document.querySelectorAll(".dm-page-config[data-config]").forEach(t=>{try{const s=atob(t.dataset.config),a=JSON.parse(s);Object.assign(n,a)}catch{}}),Object.keys(n).length>0){const t={};for(const[s,a]of Object.entries(n)){const e=a?.events?.click,{confirm:i,toast:p,alert:g,prompt:u,...m}=e||{};i||p||g||u?($(s).on("click",async function(c){if(c.preventDefault(),i&&!await E.confirm(i))return;let h=null;if(!(u&&(h=await E.prompt(u,{inputPlaceholder:m.promptPlaceholder||"",inputValue:m.promptDefault||""}),h===null))){if(m.target){const r=$(m.target);m.toggleClass&&r.toggleClass(m.toggleClass),m.addClass&&r.addClass(m.addClass),m.removeClass&&r.removeClass(m.removeClass),h!==null&&(m.setText&&r.text(h),m.setVal&&r.val(h),m.setAttr&&r.attr(m.setAttr,h))}m.href&&(window.location.href=m.href),p&&E.toast(p,{type:m.toastType||"success"}),g&&E.alert(g)}}),Object.keys(m).length&&(t[s]={...a,events:{...a.events,click:m}})):t[s]=a}$.setup(t)}}f.length&&I(f.get(0))}),window.wireCTAButtons=I;function I(x){x.querySelectorAll(".dm-cta-trigger").forEach(y=>{y.__ctaWired||(y.__ctaWired=!0,y.addEventListener("click",async()=>{const _=y.dataset.action,C=y.dataset.entry,A=y.dataset.confirm;let f=S.get("auth_token");if(!f){E.toast("Please log in to perform this action.",{type:"warning"});return}if(A&&!await E.confirm(A))return;const n=Array.from(y.childNodes).map(s=>s.cloneNode(!0));y.disabled=!0,y.textContent="Running\u2026";const t=s=>fetch(`/api/actions/${_}/public`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(y.dataset.scope?{entryId:C,scope:y.dataset.scope}:{entryId:C})});try{let s=await t(f);if(s.status===401){const e=S.get("auth_refresh_token");if(e){const i=await fetch("/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(i.ok){const{token:p}=await i.json();S.set("auth_token",p),f=p,s=await t(f)}}}const a=await s.json().catch(()=>({}));if(!s.ok)throw new Error(a.error||a.message||`Error ${s.status}`);E.toast(a.message||"Action completed.",{type:"success"})}catch(s){E.toast(s.message||"Action failed.",{type:"error"})}finally{y.disabled=!1,y.textContent="",n.forEach(s=>y.appendChild(s)),Domma.icons.scan(y)}}))})}(function(){const y=document.querySelectorAll('.dm-collection-hydrate[data-collection-scope="mine"]');if(!y.length)return;const _=S.get("auth_token");function C(f,n){const t=document.createElement("div");t.className="dm-collection-display dm-collection-empty";const s=document.createElement("p");if(n){s.appendChild(document.createTextNode("Please "));const a=document.createElement("a");a.href="/login",a.textContent="sign in",s.appendChild(a),s.appendChild(document.createTextNode(" to view your entries."))}else s.textContent=f;return t.appendChild(s),t}function A(f,n){const t=document.createElement("template");t.innerHTML=n||"",f.replaceWith(t.content)}y.forEach(async f=>{const n=f.dataset.collectionAttrs;if(!n)return;if(!_){f.replaceChildren(C("",!0));return}const t=s=>fetch("/api/collections/render-scope",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({attrs:n})});try{let s=_,a=await t(s);if(a.status===401){const i=S.get("auth_refresh_token");if(i){const p=await fetch("/api/auth/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:i})});if(p.ok){const{token:g}=await p.json();S.set("auth_token",g),s=g,a=await t(s)}}}if(!a.ok){const{error:i}=await a.json().catch(()=>({}));f.replaceChildren(C(i||"Unable to load entries.",!1));return}const{html:e}=await a.json();A(f,e),window.DommaCollectionBrowser?.hydrate&&window.DommaCollectionBrowser.hydrate(document)}catch{f.replaceChildren(C("Unable to load entries.",!1))}}),setTimeout(()=>{typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(),typeof Domma<"u"&&Domma.syntax?.scan&&Domma.syntax.scan(),I(document.body)},100)})(),(function(){const y=document.querySelectorAll("[data-collection-table]");!y.length||typeof T>"u"||!T.create||y.forEach(_=>{let C;try{C=JSON.parse(atob(_.dataset.payload))}catch{return}const{columns:A,rows:f,search:n,sortable:t,exportable:s,pageSize:a,empty:e,ctaConfig:i,slug:p,exportCfg:g}=C;if(!A?.length)return;if(i){const b=A.findIndex(c=>c.key==="_cta");b!==-1&&(A[b]={key:"_cta",title:"",render:(c,h)=>{const r=document.createElement("button");if(r.className=`btn btn-${i.style||"primary"} dm-cta-trigger`,r.dataset.action=i.action||"",i.scope&&(r.dataset.scope=i.scope),r.dataset.entry=h._entryId||"",i.confirm&&(r.dataset.confirm=i.confirm),i.icon){const o=document.createElement("span");o.dataset.icon=i.icon,r.appendChild(o),r.appendChild(document.createTextNode(" "))}return r.appendChild(document.createTextNode(i.label||"Run")),r}})}const u="col-table-"+Math.random().toString(36).slice(2,7),m=document.createElement("div");m.id=u,_.replaceChildren(m),T.create("#"+u,{data:f,columns:A,search:n,sortable:t,exportable:s,pageSize:a,emptyMessage:e}),i&&I(m),_._dmTable={columns:A,rows:f,slug:p,exportCfg:g,render(b){T.create("#"+u,{data:b,columns:A,search:n,sortable:t,exportable:s,pageSize:a,emptyMessage:e}),i&&I(m)}}})})(),(function(){const y=document.querySelectorAll("[data-form-inline]");if(!y.length||typeof F>"u")return;function _(t){const s=t&&t.logic;return!!(s&&(s.visibility||s.requirement))}function C(t,s){const a={};return(t||[]).forEach(e=>{if(e.type==="page-break"||e.type==="spacer"||!e.name)return;const i=e.type==="chooser"||!!(e.variant&&["select","radio","checkbox-group"].includes(e.type)),p=e.type==="checkbox"?"boolean":e.type==="date"||e.type==="icon"||e.type==="image"?"string":i?"chooser":e.type,g={...e.formConfig||{}};g.span==="full"&&s&&(g.span=s);const u={type:p,required:_(e)?!1:e.required,label:e.label,options:e.options,formConfig:{...e.placeholder&&{placeholder:e.placeholder},...e.helper&&{hint:e.helper},...e.tooltip&&{tooltip:e.tooltip},...g}};e.minLength!==void 0&&(u.minLength=e.minLength),e.maxLength!==void 0&&(u.maxLength=e.maxLength),e.min!==void 0&&(u.min=e.min),e.max!==void 0&&(u.max=e.max),i&&(e.variant&&(u.variant=e.variant),(e.multiple||e.type==="checkbox-group")&&(u.multiple=!0),e.density&&(u.density=e.density),e.columns&&(u.columns=e.columns),e.accent&&(u.accent=e.accent),e.accentStyle&&(u.accentStyle=e.accentStyle),e.glow&&(u.glow=!0),e.glowColour&&(u.glowColour=e.glowColour),e.shadow&&(u.shadow=e.shadow),e.shadowColour&&(u.shadowColour=e.shadowColour)),a[e.name]=u}),a}function A(t){const s={};return(t||[]).forEach(a=>{if(!(!a.name||a.type==="page-break"||a.type==="spacer")&&(a.type==="select"||a.type==="multiselect")&&a.required){const e=(a.options||[])[0];e&&(s[a.name]=typeof e=="object"?e.value:e)}}),s}function f(t,s){(s||[]).forEach(a=>{if(a.type!=="date"||!a.name)return;const e=t.querySelector(`[name="${a.name}"]`);e&&e.type!=="date"&&(e.type="date")})}function n(t,s,a){let e=t.querySelector(".cms-form-message");e||(e=document.createElement("p"),e.className="cms-form-message",t.appendChild(e)),e.textContent=s,e.style.cssText=a?"color:var(--dm-danger);margin-top:.75rem;":"color:var(--dm-success);margin-top:.75rem;"}y.forEach(t=>{let s;try{s=JSON.parse(atob(t.dataset.formInline))}catch{return}const a=s.fields||[],e=s.settings||{},i=Number(e.columns)===3?3:2,p=e.layout||"grid",g=a.some(r=>r.type==="page-break"),u=async r=>{if(t.dataset.triggerBlocked==="true"){const o=t._formLogicRuntime,l=o&&o.submitBlock?o.submitBlock().reasons:[];n(t,l.join(" ")||"This form cannot be submitted yet.",!0);const d=new Error("Blocked by a form trigger");throw d.formSubmitFailed=!0,d}try{const o=t.querySelector(".fb-form-honeypot"),l=o?.querySelector('input[type="text"]')||null,d=o?.querySelector('[name="_t"]')||null,w=Object.assign({},r);delete w._t,o?.dataset.hpName&&delete w[o.dataset.hpName],l!==null&&(w._hp=l.value),d!==null&&(w._t=d.value);const v=await H.post(`/api/forms/submit/${s.slug}`,w);if(v&&v.error){n(t,v.error,!0);const D=new Error(v.error);throw D.formSubmitFailed=!0,D}if(v?.redirect){window.location.href=v.redirect;return}for(;t.firstChild;)t.removeChild(t.firstChild);n(t,v?.message||e.successMessage||"Thank you for your submission.",!1)}catch(o){throw o.formSubmitFailed||n(t,o.message||"Submission failed. Please try again.",!0),o}},m=Date.now();function b(r){const o=r.querySelector("form");if(!o||o.querySelector(".fb-form-honeypot"))return;const l=document.createElement("div");l.className="fb-form-honeypot",l.setAttribute("aria-hidden","true");const d=document.createElement("input");d.name=o.querySelector('[name="website"]')?"_website":"website",l.dataset.hpName=d.name,d.type="text",d.tabIndex=-1,d.autocomplete="url",d.placeholder="https://",l.appendChild(d);const w=document.createElement("input");w.name="_t",w.type="hidden",w.value=m,l.appendChild(w),o.appendChild(l)}function c(r){if(!window.FormLogicEngine||!a.some(l=>l.logic||Array.isArray(l.triggers)&&l.triggers.length))return null;const o=new window.FormLogicEngine.FormLogicRuntime(s,t,r?{baseValues:r}:void 0);if(o.init(),t._formLogicRuntime=o,t._formLogicObserved)return o;if(t._formLogicObserved=!0,t.parentNode&&typeof MutationObserver<"u"){const l=new MutationObserver(function(d){for(const w of d)for(const v of w.removedNodes)if(v===t||v.nodeType===1&&v.contains&&v.contains(t)){t._formLogicRuntime&&t._formLogicRuntime.destroy(),l.disconnect();return}});l.observe(t.parentNode,{childList:!0,subtree:!1}),t._formLogicObserver=l}return o}let h=!1;if(t.addEventListener("dm-form-end",r=>{const o=r.detail?.validation;if(o&&!o.valid){P(t,o.missing),V(o);return}h||(h=!0,u(r.detail?.values||{}).catch(()=>{}).finally(()=>{h=!1}))}),g&&F.wizard){const r=Q(a,s.title),o=r.map(k=>({title:k.title,description:k.description,fields:C(k.fields,i)})),l=r.map(k=>k.fields);let d=0,w=null,v=null;const D=k=>{const L=window.FormLogicEngine;if(!L||!L.validateFields)return;const N=L.validateFields(t,l[d]||[]);N.valid||(k.preventDefault(),k.stopImmediatePropagation(),P(t,N.missing),V(N))},q=()=>{const k=l[d]||a;ee(t,e),f(t,k),R(t,k),e.honeypot!==!1&&b(t),w&&w.destroy(),w=c(v?.getStepData?v.getStepData():void 0),t.querySelectorAll(".wizard-next, .wizard-submit").forEach(L=>L.addEventListener("click",D,!0))};v=F.wizard(t,{schema:{steps:o},layout:p,columns:i,finishText:e.submitText||"Finish",onSubmit:u,onStepChange:k=>{d=k,setTimeout(q,0)}}),t.addEventListener("dm-form-trigger",k=>{if(k.detail?.type!=="goto-step"||!v?.goToStep)return;const L=Number(k.detail.action.step);!Number.isFinite(L)||L<0||L>=o.length||L!==d&&v.goToStep(L)}),Promise.resolve(v).then(q)}else if(F.render){const r=F.render(t,C(a,i),A(a),{submitText:e.submitText||"Submit",layout:p,columns:i,onSubmit:u});Promise.resolve(r).then(function(){Z(t,e,p),f(t,a),R(t,a),e.honeypot!==!1&&b(t),c()})}}),$(document).on("click",".dm-banner__dismiss",function(){$(this).closest(".dm-banner").remove()})})();
@@ -61,7 +61,7 @@ import {getConfig, saveConfig} from '../../config.js';
61
61
  import {PRESET_COLLECTION_SLUGS} from '../../services/presetCollections.js';
62
62
  import {ensureFormForCollection} from '../../services/forms.js';
63
63
  import {hooks} from '../../services/hooks.js';
64
- import {scopeAllows, validateToken} from '../../services/apiTokens.js';
64
+ import {authenticateApiToken, scopeAllows} from '../../services/apiTokens.js';
65
65
  import {isProjectEnabled, resolveArtefactProject} from '../../services/projects.js';
66
66
  import {maskConnections, restoreConnections} from '../../services/connectionSecrets.js';
67
67
 
@@ -206,23 +206,16 @@ export async function checkPublicAccess(schema, operation, request, reply) {
206
206
 
207
207
  // Token mode - project-scoped API token, strict: a token is the ONLY
208
208
  // accepted credential here (a JWT never satisfies token mode, and a
209
- // token never satisfies a role mode).
209
+ // token never satisfies a role mode). The check itself is shared with the
210
+ // Content API - authenticateApiToken() in services/apiTokens.js.
210
211
  if (access.access === 'token') {
211
- const match = (request.headers.authorization || '').match(/^Bearer (dcms_[a-f0-9]{64})$/);
212
- if (!match) {
213
- return reply.status(401).send({ error: 'API token required' });
214
- }
215
- const token = await validateToken(match[1]);
216
- if (!token) {
217
- return reply.status(401).send({ error: 'Invalid, disabled or expired API token' });
218
- }
219
- if (token.project !== resolveArtefactProject(schema)) {
220
- return reply.status(403).send({ error: "Token is not valid for this collection's project" });
221
- }
222
- if (!scopeAllows(token.scopes, schema.slug, operation)) {
223
- return reply.status(403).send({ error: 'Token scope does not permit this operation' });
224
- }
225
- request.apiToken = token;
212
+ const auth = await authenticateApiToken(request, {
213
+ project: resolveArtefactProject(schema),
214
+ allows: (scopes) => scopeAllows(scopes, schema.slug, operation),
215
+ projectError: "Token is not valid for this collection's project"
216
+ });
217
+ if (!auth.ok) return reply.status(auth.status).send({error: auth.error});
218
+ request.apiToken = auth.token;
226
219
  return;
227
220
  }
228
221
 
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Content API - admin routes (System › Content API)
3
+ *
4
+ * GET /api/content-api/settings - settings.read: config/content-api.json, normalised
5
+ * PUT /api/content-api/settings - settings.update: save it (a role the site does not have is refused)
6
+ * GET /api/content-api/_count - settings.read: the sidebar badge (contentApiBadge)
7
+ * GET /api/content-api/preview?path=/about&format=html|markdown|both&as=anon
8
+ * - settings.read: the screen's Try it. Exactly what an
9
+ * anonymous caller of /api/content/v1/pages<path> would
10
+ * get - through the same buildPageResponse() - whether
11
+ * or not the API is switched on yet, so a site can look
12
+ * before it publishes. A format the site does not offer
13
+ * still renders, with `offered: false`.
14
+ *
15
+ * The permission is `settings`, the same as the screen's sidebar entry, so whoever
16
+ * sees the entry can read its badge.
17
+ */
18
+ import {authenticate, requirePermission} from '../../middleware/auth.js';
19
+ import {listPages} from '../../services/content.js';
20
+ import {searchExclusions} from '../../services/search.js';
21
+ import {contentApiBadge, getContentApiSettings, saveContentApiSettings} from '../../services/contentApi.js';
22
+ import {getRoleLevel} from '../../services/roles.js';
23
+ import {buildPageResponse} from './content-public.js';
24
+ import {getBaseUrl} from '../public.js';
25
+
26
+ const FORMAT_VALUES = ['html', 'markdown', 'both'];
27
+ const ANONYMOUS = Object.freeze({mode: 'public', viewer: null, token: null});
28
+
29
+ export async function contentApiRoutes(fastify) {
30
+ const canRead = {preHandler: [authenticate, requirePermission('settings', 'read')]};
31
+ const canUpdate = {preHandler: [authenticate, requirePermission('settings', 'update')]};
32
+
33
+ fastify.get('/content-api/settings', canRead, async () => getContentApiSettings());
34
+
35
+ fastify.put('/content-api/settings', canUpdate, async (request, reply) => {
36
+ const patch = request.body && typeof request.body === 'object' ? request.body : {};
37
+ // A role name that is not a role here would fail closed to level 0 at
38
+ // request time - safe, but a silent surprise. Say so at save instead.
39
+ const access = typeof patch.access === 'string' ? patch.access.trim() : '';
40
+ if (access && access !== 'public' && access !== 'token' && !Number.isFinite(getRoleLevel(access))) {
41
+ return reply.status(400).send({error: `"${access}" is not a role on this site`});
42
+ }
43
+ return {ok: true, settings: saveContentApiSettings(patch)};
44
+ });
45
+
46
+ fastify.get('/content-api/_count', canRead, async () => {
47
+ const pages = await listPages();
48
+ return contentApiBadge(getContentApiSettings(), pages, await searchExclusions(pages));
49
+ });
50
+
51
+ fastify.get('/content-api/preview', canRead, async (request, reply) => {
52
+ const q = request.query || {};
53
+ const path = String(q.path || '').trim();
54
+ if (!path.startsWith('/')) return reply.status(400).send({error: 'Give a page path starting with /'});
55
+ // Only the anonymous view for now: it is what public and token callers get.
56
+ if (q.as != null && q.as !== 'anon') return reply.status(400).send({error: 'Preview runs as an anonymous caller only (as=anon)'});
57
+ const format = q.format == null || q.format === '' ? 'html' : String(q.format);
58
+ if (!FORMAT_VALUES.includes(format)) return reply.status(400).send({error: `Unknown format "${format}"`});
59
+
60
+ const settings = getContentApiSettings();
61
+ const wanted = format === 'both' ? ['html', 'markdown'] : [format];
62
+ const res = await buildPageResponse(path, {access: ANONYMOUS, format});
63
+ return {
64
+ status: res.status,
65
+ body: res.body,
66
+ offered: wanted.every(f => settings.formats.includes(f)),
67
+ url: `${getBaseUrl(request)}/api/content/v1/pages${path}`
68
+ };
69
+ });
70
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Content API - /api/content/v1
3
+ *
4
+ * Read-only headless access to what the site publishes:
5
+ *
6
+ * GET /api/content/v1/pages - paged page summaries
7
+ * GET /api/content/v1/pages/* - one page (?format=html|markdown|both)
8
+ * GET /api/content/v1/menus/:location - the menu bound to a location, filtered for the caller
9
+ * GET /api/content/v1/site - the site settings public pages already show
10
+ * GET /api/content/v1/search?q= - site search
11
+ *
12
+ * Its own prefix on purpose: /api/v1/:slug matches any collection slug, and
13
+ * slugify() happily produces `pages` and `menus`, so living there would
14
+ * shadow real collections.
15
+ *
16
+ * Access is config/content-api.json `access`:
17
+ * - 'public' - anyone
18
+ * - 'token' - a project API token, strict (never a JWT), bound to the
19
+ * page's project, narrowed by `{content}` scopes
20
+ * - a role - a Bearer access JWT at that role's level or more senior; an
21
+ * unknown role admits level 0 only. Never the dm_session
22
+ * cookie: that is read only by the page renderer, so no
23
+ * API answers to ambient credentials.
24
+ * Public and token callers are served as an anonymous visitor.
25
+ *
26
+ * Every page decision is resolvePublishedPage() - the function the public
27
+ * site uses - so the two can never disagree.
28
+ */
29
+ import {getContentApiSettings, pageDetail, pageSummary, publicSiteSettings} from '../../services/contentApi.js';
30
+ import {canPreviewDrafts, resolvePublishedPage} from '../../services/pagePublishing.js';
31
+ import {getPage, getPageMtime, listPages} from '../../services/content.js';
32
+ import {getSearchSettings, isPubliclyListed, searchExclusions, searchPages} from '../../services/search.js';
33
+ import {resolveLocation} from '../../services/menus.js';
34
+ import {authenticateApiToken, contentScopeAllows} from '../../services/apiTokens.js';
35
+ import {getRoleLevel} from '../../services/roles.js';
36
+ import {getEffectiveLevel} from '../../services/userRoles.js';
37
+ import {getConfig} from '../../config.js';
38
+
39
+ const NOT_FOUND = {error: 'Not found'};
40
+ const DEFAULT_LIMIT = 50;
41
+ const FORMAT_VALUES = ['html', 'markdown', 'both'];
42
+
43
+ /** Menu slots the API never serves: the admin's own navigation, and page overlays. */
44
+ const PRIVATE_SLOTS = new Set(['admin-sidebar', 'overlay']);
45
+
46
+ /**
47
+ * Gate one request. Resolves to `{mode, viewer, token, settings}`, or sends
48
+ * the refusal and resolves to null.
49
+ *
50
+ * Token mode binds no project here: pages carry their own, so the routes
51
+ * check `inProject()` per page. Menus and site settings are site-wide and
52
+ * already shown on every public page, so any valid token may read them.
53
+ *
54
+ * @param {'pages'|'menus'|'site'|'search'} resource
55
+ * @returns {Promise<object|null>}
56
+ */
57
+ export async function checkContentAccess(resource, request, reply) {
58
+ const settings = getContentApiSettings();
59
+ if (!settings.enabled || !settings.resources[resource]?.enabled) {
60
+ reply.status(404).send(NOT_FOUND);
61
+ return null;
62
+ }
63
+
64
+ if (settings.access === 'public') return {mode: 'public', viewer: null, token: null, settings};
65
+
66
+ if (settings.access === 'token') {
67
+ const auth = await authenticateApiToken(request, {allows: (scopes) => contentScopeAllows(scopes, resource)});
68
+ if (!auth.ok) {
69
+ reply.status(auth.status).send({error: auth.error});
70
+ return null;
71
+ }
72
+ return {mode: 'token', viewer: null, token: auth.token, settings};
73
+ }
74
+
75
+ // Role mode. jwtVerify reads the Authorization header only; a refresh
76
+ // token is refused like any other non-access token.
77
+ let decoded;
78
+ try {
79
+ decoded = await request.jwtVerify();
80
+ } catch {
81
+ decoded = null;
82
+ }
83
+ if (!decoded || decoded.type !== 'access') {
84
+ reply.status(401).send({error: 'Unauthorised'});
85
+ return null;
86
+ }
87
+ // A role name that is not a role on this site fails closed to level 0,
88
+ // as checkPublicAccess() and checkVisibility() do.
89
+ const named = getRoleLevel(settings.access);
90
+ const required = Number.isFinite(named) ? named : 0;
91
+ if (getEffectiveLevel(decoded) > required) {
92
+ reply.status(403).send({error: 'Insufficient permissions'});
93
+ return null;
94
+ }
95
+ return {mode: 'role', viewer: decoded, token: null, settings};
96
+ }
97
+
98
+ /** A token sees only its own project's pages; other modes see every project. */
99
+ const inProject = (access, project) => access.mode !== 'token' || access.token.project === project;
100
+
101
+ /** Frontmatter `api: false` keeps a page off the API; it still renders on the site. */
102
+ const apiOff = (page) => page?.api === false;
103
+
104
+ function cacheHeaders(reply, access, {draft = false} = {}) {
105
+ if (draft || access.mode === 'role') reply.header('cache-control', 'no-store');
106
+ else if (access.mode === 'token') reply.header('cache-control', 'private, no-cache');
107
+ else reply.header('cache-control', 'public, max-age=60');
108
+ }
109
+
110
+ /**
111
+ * Which body formats a request asked for, or an error when the site does not
112
+ * offer one of them.
113
+ *
114
+ * @returns {{format: string} | {error: string}}
115
+ */
116
+ function pickFormat(raw, settings) {
117
+ const format = raw == null || raw === '' ? 'html' : String(raw);
118
+ if (!FORMAT_VALUES.includes(format)) return {error: `Unknown format "${format}" - use html, markdown or both`};
119
+ const wanted = format === 'both' ? ['html', 'markdown'] : [format];
120
+ if (!wanted.every(f => settings.formats.includes(f))) return {error: `Format "${format}" is not available on this site`};
121
+ return {format};
122
+ }
123
+
124
+ /**
125
+ * One page as the API serves it - the decision and the payload, without
126
+ * caching or replies. The admin's Try it console (routes/api/content-api.js)
127
+ * calls this too, so it shows exactly what a caller would get.
128
+ *
129
+ * @param {string} urlPath
130
+ * @param {{access: object, format: string, allowDrafts?: boolean}} opts
131
+ * @returns {Promise<{status: 200|403|404, body: object, page?: object, isDraft?: boolean}>}
132
+ */
133
+ export async function buildPageResponse(urlPath, {access, format, allowDrafts = false}) {
134
+ const verdict = await resolvePublishedPage(urlPath, access.viewer, {allowDrafts});
135
+ if (verdict.status === 'forbidden') return {status: 403, body: {error: 'Forbidden'}};
136
+ if (verdict.status !== 'ok' || apiOff(verdict.page) || !inProject(access, verdict.project)) {
137
+ return {status: 404, body: NOT_FOUND};
138
+ }
139
+ // The verdict's page was parsed anonymously. A signed-in caller gets the
140
+ // body rendered for them, as the site does - [menu] and row-scoped [view].
141
+ const page = access.viewer
142
+ ? (await getPage(verdict.page.urlPath, {user: access.viewer})) || verdict.page
143
+ : verdict.page;
144
+ return {status: 200, body: pageDetail(page, {format}), page, isDraft: verdict.isDraft};
145
+ }
146
+
147
+ const SORTS = {
148
+ title: (a, b) => String(a.title || '').localeCompare(String(b.title || '')),
149
+ updatedAt: (a, b) => String(a.updatedAt || '').localeCompare(String(b.updatedAt || '')),
150
+ createdAt: (a, b) => String(a.createdAt || '').localeCompare(String(b.createdAt || ''))
151
+ };
152
+
153
+ const intParam = (raw, fallback) => {
154
+ const n = parseInt(raw, 10);
155
+ return Number.isFinite(n) && n > 0 ? n : fallback;
156
+ };
157
+
158
+ /** Allowlisted menu items: what a navbar needs to draw them, nothing of their gating. */
159
+ function menuItems(items = []) {
160
+ return items.map(item => {
161
+ const out = {};
162
+ for (const k of ['type', 'text', 'url', 'icon', 'target', 'size', 'badge']) {
163
+ if (item[k] !== undefined) out[k] = item[k];
164
+ }
165
+ if (Array.isArray(item.items) && item.items.length) out.items = menuItems(item.items);
166
+ return out;
167
+ });
168
+ }
169
+
170
+ export async function contentPublicRoutes(fastify) {
171
+ // This prefix is exempt from the global /api no-store hook, so anything a
172
+ // route did not mark itself - every refusal - is no-store here. A 404 with
173
+ // no Cache-Control is heuristically cacheable, and would outlive the
174
+ // admin switching the API on. (Scoped: a hook in this plugin reaches only
175
+ // these routes.)
176
+ fastify.addHook('onSend', async (request, reply) => {
177
+ if (!reply.getHeader('cache-control')) reply.header('cache-control', 'no-store');
178
+ });
179
+
180
+ // -------------------------------------------------------------------------
181
+ // Pages
182
+ // -------------------------------------------------------------------------
183
+
184
+ fastify.get('/content/v1/pages', async (request, reply) => {
185
+ const access = await checkContentAccess('pages', request, reply);
186
+ if (!access) return;
187
+ if (!access.settings.listable) return reply.status(404).send(NOT_FOUND);
188
+
189
+ const q = request.query || {};
190
+ const limit = Math.min(access.settings.maxLimit, intParam(q.limit, DEFAULT_LIMIT));
191
+ const pageNo = intParam(q.page, 1);
192
+
193
+ const all = await listPages();
194
+ const exclusions = await searchExclusions(all);
195
+ let rows = all.filter(p => isPubliclyListed(p, access.viewer, exclusions)
196
+ && !apiOff(p)
197
+ && inProject(access, p.resolvedProject));
198
+ if (q.prefix) rows = rows.filter(p => String(p.urlPath || '').startsWith(String(q.prefix)));
199
+ if (q.tag) rows = rows.filter(p => Array.isArray(p.tags) && p.tags.includes(String(q.tag)));
200
+ if (q.category) rows = rows.filter(p => p.category === String(q.category));
201
+ if (q.project) rows = rows.filter(p => p.resolvedProject === String(q.project));
202
+ // Default order is listPages' own (sortOrder, then title).
203
+ if (SORTS[q.sort]) rows = [...rows].sort(SORTS[q.sort]);
204
+ if (q.order === 'desc') rows = [...rows].reverse();
205
+
206
+ cacheHeaders(reply, access);
207
+ const start = (pageNo - 1) * limit;
208
+ return {pages: rows.slice(start, start + limit).map(pageSummary), total: rows.length, page: pageNo, limit};
209
+ });
210
+
211
+ fastify.get('/content/v1/pages/*', async (request, reply) => {
212
+ const access = await checkContentAccess('pages', request, reply);
213
+ if (!access) return;
214
+ const picked = pickFormat(request.query?.format, access.settings);
215
+ if (picked.error) return reply.status(400).send({error: picked.error});
216
+ const {format} = picked;
217
+
218
+ const urlPath = '/' + (request.params['*'] || '');
219
+ // Drafts only for a role-mode caller who could read them in the admin.
220
+ const allowDrafts = access.mode === 'role' && request.query?.preview === '1' && canPreviewDrafts(access.viewer);
221
+
222
+ // A signed-in or draft render is that caller's alone and never cached.
223
+ if (access.viewer) {
224
+ const res = await buildPageResponse(urlPath, {access, format, allowDrafts});
225
+ cacheHeaders(reply, access, {draft: res.isDraft});
226
+ return reply.status(res.status).send(res.body);
227
+ }
228
+
229
+ // Anonymous callers (public and token). No response cache: the access
230
+ // decision has to parse the page anyway - exactly as the site's does -
231
+ // and the JSON is built straight from that parse. HTTP caching does the
232
+ // rest; the mtime ETag changes on any edit to the file, however made.
233
+ const res = await buildPageResponse(urlPath, {access, format});
234
+ if (res.status !== 200) return reply.status(res.status).send(res.body);
235
+ const mtime = await getPageMtime(res.page.urlPath || urlPath);
236
+ cacheHeaders(reply, access);
237
+ reply.header('etag', `W/"${mtime}-${format}"`);
238
+ return res.body;
239
+ });
240
+
241
+ // -------------------------------------------------------------------------
242
+ // Menus, site settings, search
243
+ // -------------------------------------------------------------------------
244
+
245
+ fastify.get('/content/v1/menus/:location', async (request, reply) => {
246
+ const access = await checkContentAccess('menus', request, reply);
247
+ if (!access) return;
248
+ const location = String(request.params.location || '');
249
+ if (PRIVATE_SLOTS.has(location) || location.startsWith('admin')) return reply.status(404).send(NOT_FOUND);
250
+
251
+ // ?page= lets page-bound menus resolve as they would on that page.
252
+ const urlPath = request.query?.page ? String(request.query.page) : undefined;
253
+ const menu = await resolveLocation(location, access.viewer, urlPath ? {urlPath} : {});
254
+ if (!menu) return reply.status(404).send(NOT_FOUND);
255
+
256
+ cacheHeaders(reply, access);
257
+ return {location, slug: menu.slug, name: menu.name, items: menuItems(menu.items)};
258
+ });
259
+
260
+ fastify.get('/content/v1/site', async (request, reply) => {
261
+ const access = await checkContentAccess('site', request, reply);
262
+ if (!access) return;
263
+ let site = {};
264
+ try { site = getConfig('site') || {}; } catch { /* no site.json - nothing to show */ }
265
+ cacheHeaders(reply, access);
266
+ return publicSiteSettings(site);
267
+ });
268
+
269
+ fastify.get('/content/v1/search', async (request, reply) => {
270
+ const access = await checkContentAccess('search', request, reply);
271
+ if (!access) return;
272
+ const settings = getSearchSettings();
273
+ // Search switched off for the site is off for the API too.
274
+ if (!settings.enabled) return reply.status(404).send(NOT_FOUND);
275
+
276
+ const q = String(request.query?.q || '').trim().slice(0, 200);
277
+ if (q.length < settings.minQueryLength) {
278
+ return reply.status(400).send({error: `Query must be at least ${settings.minQueryLength} characters`});
279
+ }
280
+ const maxResults = Math.min(settings.maxResults, intParam(request.query?.limit, settings.maxResults));
281
+
282
+ const all = await listPages();
283
+ const pages = all.filter(p => !apiOff(p) && inProject(access, p.resolvedProject));
284
+ const results = searchPages(pages, q, {
285
+ maxResults,
286
+ viewer: access.viewer,
287
+ exclusions: await searchExclusions(all),
288
+ onError: (err, page) => request.log.warn({err, page: page.urlPath}, '[content-api] search skipped an unreadable page')
289
+ });
290
+
291
+ // Search results are per viewer in role mode; never shared there.
292
+ cacheHeaders(reply, access);
293
+ return {
294
+ results: results.map(r => ({
295
+ urlPath: r.url, title: r.title, description: r.description, tags: r.tags, snippet: r.snippet, score: r.score
296
+ }))
297
+ };
298
+ });
299
+ }