domma-cms 1.47.6 → 1.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.48.1] - 2026-11-09
4
+
5
+ - Move "Show side admin menu" from Versions to Notifications for every signed-in user, including users without notification permissions. Keep each account's saved sidebar choice and the site default for new users.
6
+
7
+ ## [1.48.0] - 2026-11-09
8
+
9
+ - **Making and handing over API tokens.**
10
+ - **Bot that writes drafts**, a switch in New token: tick the collections a bot (Grok, a script, another site) may write to, and it gets a token scoped to them with Drafts only on. Each collection's create (and, if chosen, update) is opened to tokens where it was off - never wider than it is: a verb already open to everyone is left alone, and the screen says so. A collection with no draft status can be given a Status field (draft / published). Built-in collections are never offered. Needs permission to change collections.
11
+ - **A one-time link** from the Token created panel, to send instead of the token. It opens once, within 24 hours, and shows the token with how to use it (where to send what, a curl example, who to credit). The token is encrypted in the admin's browser and the key is only in the link, so the site keeps nothing that could show it. Revoking the token kills the link.
12
+ - **A connection file** (JSON) to download, for a script or bot to read: the site, the token, what it may do where, and the author to credit.
13
+ - **Bots can write pages, pictures and blocks through the Content API**, with a token whose scope names it (`@pages: create, update`, `@media: create`, `@blocks: create, update`): `POST`/`PUT /api/content/v1/pages`, `POST /api/content/v1/media`, `POST`/`PUT /api/content/v1/blocks`. With Drafts only, pages arrive as drafts and only drafts can be changed; pictures are public once uploaded; only new blocks can be made. Uploads are checked by their bytes (pictures and PDFs only, never SVG or HTML) and never replace another file. Tokens made before this cannot write: writing needs the verb named, and only an admin who holds that permission can grant it. What a token writes is held to Markdown and the layout shortcodes - no HTML - and is then rendered and the RESULT checked against what those emit (no `[dconfig]`, `[collection]`, `[cta]`, `[form]`, blocks, scripts, styles or forms reach the page); drafts a token wrote are shown to their reviewer isolated (a CSP sandbox on the draft view and share link, a script-less editor preview); a drafts-only token changes only its own drafts, pages and collection entries alike; what any token writes to a collection through `/api/v1` passes the same content policy; a new block may not take a shortcode's name or one the site already uses; 30 writes a minute and 200 MB of uploads a day per token. Bot that writes drafts offers all three. Only the classes the layout shortcodes really emit reach a token's page (a parameter can no longer name a site class such as `fixed` or `modal`: every class built from a shortcode parameter keeps to letters, digits, `_` and `-`), and no token may write the roles, user profiles, tokens or other system collections, whatever their API settings say.
14
+ - The site refuses to navigate to a `javascript:`, `data:` or `vbscript:` address from a page's settings or a form's redirect (`goTo` in `public/js/site.js`).
15
+
3
16
  ## [1.47.6] - 2026-11-08
4
17
 
5
18
  - **Plugins: `options.auth.authenticateSelf`**, core's sign-in check without the plugin admin-scope rule, for plugin routes that act only on the caller's own record (a shop customer's account or reorder). A confined role such as `shop-customer` got 403 "Your account cannot use <plugin>" there. It keeps every token rule: an access token is required and a refresh token is refused. Plugin `authenticate` is unchanged. See "authenticateSelf" in docs/plugin-development.md - never use it for admin APIs or other users' data.
package/admin/js/api.js CHANGED
@@ -1 +1 @@
1
- import{claimDrafts as O}from"./lib/draft-owner.js";import{loginHashFor as $}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),folders:()=>t("/media/_folders",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"}),buy:(e,o={})=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e,...o})}),claim:e=>t("/plugins/marketplace/claim",{method:"POST",body:JSON.stringify({id:e})}),enterKey:(e,o)=>t("/plugins/marketplace/key",{method:"POST",body:JSON.stringify({slug:e,key:o})}),connect:e=>t("/plugins/marketplace/connect",{method:"POST",body:JSON.stringify({email:e})}),connectCheck:()=>t("/plugins/marketplace/connect/check",{method:"POST",body:"{}"}),disconnect:()=>t("/plugins/marketplace/connect",{method:"DELETE"}),dropPurchase:e=>t(`/plugins/marketplace/purchases/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&(O(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=$(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
1
+ import{claimDrafts as O}from"./lib/draft-owner.js";import{loginHashFor as $}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"}),recipe:e=>t(`/api-tokens/_recipe?project=${encodeURIComponent(e)}`,{method:"GET"}),handover:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}/handover`,{method:"POST",body:JSON.stringify(o)})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),folders:()=>t("/media/_folders",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"}),buy:(e,o={})=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e,...o})}),claim:e=>t("/plugins/marketplace/claim",{method:"POST",body:JSON.stringify({id:e})}),enterKey:(e,o)=>t("/plugins/marketplace/key",{method:"POST",body:JSON.stringify({slug:e,key:o})}),connect:e=>t("/plugins/marketplace/connect",{method:"POST",body:JSON.stringify({email:e})}),connectCheck:()=>t("/plugins/marketplace/connect/check",{method:"POST",body:"{}"}),disconnect:()=>t("/plugins/marketplace/connect",{method:"DELETE"}),dropPurchase:e=>t(`/plugins/marketplace/purchases/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&(O(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=$(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
package/admin/js/app.js CHANGED
@@ -1,10 +1,10 @@
1
- import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{installSmoothCarets as X}from"./lib/smooth-caret.js";import{viewLoaders as Z}from"./views/index.js";import{createLazyViews as ee}from"./lib/lazy-views.js";import{withPluginChrome as _}from"./lib/plugin-chrome.js";import{api as r,getUser as x,isAuthenticated as m,logout as te,sendToLogin as ae}from"./api.js";import{claimDrafts as ie}from"./lib/draft-owner.js";import{isAuthScreen as C,loginHashFor as oe}from"./lib/login-arrange.js";import{installHttpInterceptor as se}from"./http-interceptor.js";import{installResizableSlideovers as ne}from"./lib/slideover-resizable.js";import{installActivityThrobber as re}from"./lib/activity-throbber.js";import{installUpdateNotice as le,renderCmsVersion as ce}from"./lib/update-notice.js";import{renderFrameworkVersions as W,wireAccountMenu as me}from"./lib/topbar-account.js";import{refreshTopbarProject as B}from"./lib/topbar-project.js";import{isPathAllowed as pe,redirectFor as de}from"./lib/admin-scope.js";import{deliverDesktop as ue,desktopActive as he,notificationSettings as we}from"./lib/desktop-notify.js";import{avatarUrl as ge,installAccountAvatar as fe}from"./lib/avatar.js";import{installCalculator as ve}from"./lib/calculator.js";import{takeOverviewPass as be,withDashboardStrip as H}from"./lib/dashboards-strip.js";import{installHotkeys as Se}from"./lib/hotkeys-ui.js";import{applyAdminBrand as K}from"./lib/admin-brand.js";import{installRouterCatchUp as Ce}from"./lib/router-catch-up.js";import{installSidebarDrawer as Me}from"./lib/sidebar-drawer.js";$(()=>{X(document),se(),ve(),le(),re(),ne(),Me(),(async()=>{const{applyAdminTheme:e,refreshAdminTheme:i}=await import("./lib/admin-theme.js");m()?await i(r,{init:!0}):e({dommaTheme:"charcoal-dark"},{init:!0})})();let p=null,h=null,c="/",w=!1,g=null;function D(e){if(N[e])return E.toast(`${N[e]} is switched off on this site.`,{type:"info"}),"/";const[i,t]=e.split("?"),a=new URLSearchParams(t||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(e.split("?")[0]==="/my-dashboard")return"/dashboards";const o=y[e]||de(p,e);return o||((e.split("?")[0]||"/")==="/"&&c&&c!=="/"&&!be()?y[c]||c:null)}const y={},N={};R.use(async(e,i,t)=>{if(C(e.path))return t();if(!m()){ae();return}const a=D(e.path);if(a){R.navigate(a);return}t()});async function f(){try{const e=await r.get("/auth/permissions");p=e.adminScope||null,h=e.adminBrand||null,K(h),c=e.adminHome||"/",W(e.versions);const i=e.permissions||[];return w=pe(p,"/settings")&&i.some(t=>t==="settings"||t.startsWith("settings.")),g=i.some(t=>t==="notifications"||t.startsWith("notifications.")),i}catch{return p=null,c="/",h||K(null),w=!1,g=null,[]}}document.addEventListener("dm:admin-home-changed",()=>{f()});let P=null,A=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(B(r),P){A=!0;return}P=(async()=>{do{A=!1;try{await j(await f())}catch{}}while(A)})().finally(()=>{P=null})});async function j(e){const{renderAdminSidebar:i}=await import("./lib/sidebar-renderer.js");await i({mount:"#admin-sidebar",permissions:e,adminScope:p,brand:h})}M.subscribe("router:afterChange",({to:e})=>{C(e.path)&&(u&&(clearInterval(u),u=null),p=null,c="/",w=!1,g=null)});const q=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import a site - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:e,from:i})=>{if(!C(e.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),C(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await T();const t=await f(),a=D(e.path);if(a&&R.navigate(a),j(t),we.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=d(s.data?.title||""),L=d((s.data?.body||"").slice(0,120));E.toast(`${l} - ${L}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}V()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const z=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function G(e){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(e)}M.subscribe("router:afterChange",({to:e})=>{const i=e?String(e.path).split("?")[0]:"";if(!e||!G(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const L of z){const b=document.querySelector(L);if(!b)continue;if(Array.from(b.options||[]).find(Y=>Y.value===a)){b.value=a,b.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const F="cms_card_states",k=S.get(F)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const e=$(this).find(".card-header h2, .card-header h3").first().text().trim();e&&k[e]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(e){if($(e.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const t=$(this).find("h2, h3").first().text().trim();t&&(k[t]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(F,k))}),Se(),document.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(e.preventDefault(),i.click())});const v=ee(),O=v.views,J={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import a site",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[e,i]of Object.entries(Z))v.register(e,async()=>{let t=await i();const a=J[e];return a&&(t=_(t,{plugin:e,licence:"Built in",...a})),e==="dashboard"?H(t):t});R.use(async(e,i,t)=>{try{await v.load(e.view)}catch(a){console.error("[admin] Screen failed to load",a),O[e.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}t()});const I=[...q];async function T(){if(m())try{const e=await r.plugins.adminConfig(),i=new Set(I.map(t=>t.path));for(const t of e.routes||[])i.has(t.path)||I.push(t);for(const[t,a]of Object.entries(e.views||{})){const o=(e.meta||{})[t];v.register(t,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${t}`);const l=_(s,o);return t==="dashboard"?H(l):l},JSON.stringify([a,o]))}for(const[t,{route:a}]of Object.entries(e.takeovers||{}))a&&(y[`/${t}`]=a);e.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=e.mediaPicker);for(const[t,{enabled:a,displayName:o}]of Object.entries(e.tools||{}))a===!1&&(N[`/${t}`]=o);for(const{id:t,href:a}of e.css||[])if(!document.getElementById(t)){const o=document.createElement("link");o.id=t,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function V(){const e=x();if(!e)return;if($("#topbar-user-name").length){B(r);return}const t={"super-admin":"Super Admin",admin:"Admin",user:"User"}[e.role]||e.role,a=ge(e);$("#topbar-user").get(0).innerHTML=`
1
+ import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{installSmoothCarets as X}from"./lib/smooth-caret.js";import{viewLoaders as Z}from"./views/index.js";import{createLazyViews as ee}from"./lib/lazy-views.js";import{withPluginChrome as _}from"./lib/plugin-chrome.js";import{api as r,getUser as x,isAuthenticated as m,logout as te,sendToLogin as ae}from"./api.js";import{claimDrafts as ie}from"./lib/draft-owner.js";import{isAuthScreen as C,loginHashFor as oe}from"./lib/login-arrange.js";import{installHttpInterceptor as se}from"./http-interceptor.js";import{installResizableSlideovers as ne}from"./lib/slideover-resizable.js";import{installActivityThrobber as re}from"./lib/activity-throbber.js";import{installUpdateNotice as le,renderCmsVersion as ce}from"./lib/update-notice.js";import{renderFrameworkVersions as W,wireAccountMenu as me}from"./lib/topbar-account.js";import{refreshTopbarProject as B}from"./lib/topbar-project.js";import{isPathAllowed as pe,redirectFor as de}from"./lib/admin-scope.js";import{deliverDesktop as ue,desktopActive as he,notificationSettings as we}from"./lib/desktop-notify.js";import{avatarUrl as ge,installAccountAvatar as fe}from"./lib/avatar.js";import{installCalculator as ve}from"./lib/calculator.js";import{takeOverviewPass as be,withDashboardStrip as H}from"./lib/dashboards-strip.js";import{installHotkeys as Se}from"./lib/hotkeys-ui.js";import{applyAdminBrand as K}from"./lib/admin-brand.js";import{installRouterCatchUp as Ce}from"./lib/router-catch-up.js";import{installSidebarDrawer as Me}from"./lib/sidebar-drawer.js";$(()=>{X(document),se(),ve(),le(),re(),ne(),Me(),(async()=>{const{applyAdminTheme:e,refreshAdminTheme:i}=await import("./lib/admin-theme.js");m()?await i(r,{init:!0}):e({dommaTheme:"charcoal-dark"},{init:!0})})();let p=null,w=null,c="/",g=!1,u=null;function D(e){if(N[e])return E.toast(`${N[e]} is switched off on this site.`,{type:"info"}),"/";const[i,t]=e.split("?"),a=new URLSearchParams(t||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(e.split("?")[0]==="/my-dashboard")return"/dashboards";const o=y[e]||de(p,e);return o||((e.split("?")[0]||"/")==="/"&&c&&c!=="/"&&!be()?y[c]||c:null)}const y={},N={};R.use(async(e,i,t)=>{if(C(e.path))return t();if(!m()){ae();return}const a=D(e.path);if(a){R.navigate(a);return}t()});async function f(){try{const e=await r.get("/auth/permissions");p=e.adminScope||null,w=e.adminBrand||null,K(w),c=e.adminHome||"/",W(e.versions);const i=e.permissions||[];return g=pe(p,"/settings")&&i.some(t=>t==="settings"||t.startsWith("settings.")),u=i.some(t=>t==="notifications"||t.startsWith("notifications.")),i}catch{return p=null,c="/",w||K(null),g=!1,u=null,[]}}document.addEventListener("dm:admin-home-changed",()=>{f()});let P=null,A=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(B(r),P){A=!0;return}P=(async()=>{do{A=!1;try{await j(await f())}catch{}}while(A)})().finally(()=>{P=null})});async function j(e){const{renderAdminSidebar:i}=await import("./lib/sidebar-renderer.js");await i({mount:"#admin-sidebar",permissions:e,adminScope:p,brand:w})}M.subscribe("router:afterChange",({to:e})=>{C(e.path)&&(h&&(clearInterval(h),h=null),p=null,c="/",g=!1,u=null)});const q=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import a site - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:e,from:i})=>{if(!C(e.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),C(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await T();const t=await f(),a=D(e.path);if(a&&R.navigate(a),j(t),we.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=d(s.data?.title||""),L=d((s.data?.body||"").slice(0,120));E.toast(`${l} - ${L}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}V()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const z=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function G(e){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(e)}M.subscribe("router:afterChange",({to:e})=>{const i=e?String(e.path).split("?")[0]:"";if(!e||!G(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const L of z){const b=document.querySelector(L);if(!b)continue;if(Array.from(b.options||[]).find(Y=>Y.value===a)){b.value=a,b.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const F="cms_card_states",k=S.get(F)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const e=$(this).find(".card-header h2, .card-header h3").first().text().trim();e&&k[e]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(e){if($(e.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const t=$(this).find("h2, h3").first().text().trim();t&&(k[t]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(F,k))}),Se(),document.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(e.preventDefault(),i.click())});const v=ee(),O=v.views,J={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import a site",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[e,i]of Object.entries(Z))v.register(e,async()=>{let t=await i();const a=J[e];return a&&(t=_(t,{plugin:e,licence:"Built in",...a})),e==="dashboard"?H(t):t});R.use(async(e,i,t)=>{try{await v.load(e.view)}catch(a){console.error("[admin] Screen failed to load",a),O[e.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}t()});const I=[...q];async function T(){if(m())try{const e=await r.plugins.adminConfig(),i=new Set(I.map(t=>t.path));for(const t of e.routes||[])i.has(t.path)||I.push(t);for(const[t,a]of Object.entries(e.views||{})){const o=(e.meta||{})[t];v.register(t,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${t}`);const l=_(s,o);return t==="dashboard"?H(l):l},JSON.stringify([a,o]))}for(const[t,{route:a}]of Object.entries(e.takeovers||{}))a&&(y[`/${t}`]=a);e.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=e.mediaPicker);for(const[t,{enabled:a,displayName:o}]of Object.entries(e.tools||{}))a===!1&&(N[`/${t}`]=o);for(const{id:t,href:a}of e.css||[])if(!document.getElementById(t)){const o=document.createElement("link");o.id=t,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function V(){const e=x();if(!e)return;if($("#topbar-user-name").length){B(r);return}const t={"super-admin":"Super Admin",admin:"Admin",user:"User"}[e.role]||e.role,a=ge(e);$("#topbar-user").get(0).innerHTML=`
2
2
  <a id="topbar-project" class="topbar-action-link topbar-project" hidden>
3
3
  <span data-icon="folder"></span>
4
4
  <span id="topbar-project-name" class="topbar-project-name"></span>
5
5
  </a>
6
6
  <div id="topbar-versions-menu" class="topbar-account">
7
- <button type="button" class="topbar-action-link" aria-label="Versions and layout" aria-expanded="false" aria-controls="topbar-versions-panel">
7
+ <button type="button" class="topbar-action-link" aria-label="Versions" aria-expanded="false" aria-controls="topbar-versions-panel">
8
8
  <span data-icon="layers"></span><span class="topbar-action-label">Versions</span><span data-icon="chevron-down"></span>
9
9
  </button>
10
10
  <div id="topbar-versions-panel" class="topbar-account-menu topbar-versions-panel" hidden>
@@ -13,18 +13,19 @@ import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{inst
13
13
  <span class="topbar-version-item" hidden>Domma JS <span id="topbar-js-version" class="topbar-version-badge"></span></span>
14
14
  <span class="topbar-version-item" hidden>Domma CMS <span id="topbar-cms-version" class="topbar-version-badge"></span></span>
15
15
  </div>
16
- <label class="topbar-sidebar-choice"><input type="checkbox" id="topbar-show-sidebar"> Show side admin menu</label>
17
16
  </div>
18
17
  </div>
19
18
  `,$("#topbar-actions").get(0).innerHTML=`
20
19
  <div id="topbar-notifications" class="topbar-account">
21
- <button type="button" id="topbar-bell" class="topbar-action-link" aria-label="Notifications" aria-expanded="false" aria-controls="topbar-notifications-menu" hidden>
20
+ <button type="button" id="topbar-bell" class="topbar-action-link" aria-label="Notifications" aria-expanded="false" aria-controls="topbar-notifications-menu">
22
21
  <span data-icon="bell"></span>
23
22
  <span class="topbar-action-label">Notifications</span>
24
23
  <span id="topbar-bell-badge" class="topbar-bell-badge" hidden></span>
25
24
  <span data-icon="chevron-down"></span>
26
25
  </button>
27
- <div id="topbar-notifications-menu" class="topbar-account-menu topbar-notifications-menu" aria-label="Notifications" hidden></div>
26
+ <div id="topbar-notifications-menu" class="topbar-account-menu topbar-notifications-menu" aria-label="Notifications" hidden>
27
+ <label class="topbar-sidebar-choice"><input type="checkbox" id="topbar-show-sidebar"> Show side admin menu</label>
28
+ </div>
28
29
  </div>
29
30
  <div id="topbar-account" class="topbar-account">
30
31
  <button type="button" class="topbar-action-link" aria-label="Account menu" aria-expanded="false" aria-controls="topbar-account-menu">
@@ -50,4 +51,4 @@ import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{inst
50
51
  </a>
51
52
  </div>
52
53
  </div>
53
- `;const o=$("#topbar-bell").get(0);o&&(o.hidden=!0);const n=$("#topbar-settings").get(0);n&&(n.hidden=!w),$("#topbar-logout-btn").on("click",s=>{s.preventDefault(),te()}),Domma.icons.scan("#admin-topbar"),E.tooltip("#topbar-actions [data-tooltip]",{placement:"bottom"}),me(e),Q({refreshBadge:U}),fe(e),W(),ce(),B(r),U(),u||(u=setInterval(U,6e4))}function d(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}let u=null;async function U(){if(!(!m()||g===!1))try{const{count:e}=await r.system.notifications.unreadCount();$("#topbar-bell").removeAttr("hidden");const i=$("#topbar-bell-badge");e>0?i.text(e>99?"99+":String(e)).removeAttr("hidden"):i.attr("hidden","").text(""),e>0&&he()&&ue(await r.system.notifications.list().catch(()=>[]))}catch{}}(async()=>{if(!m()&&!window.location.hash.startsWith("#/reset-password"))window.location.hash.startsWith("#/login")||(window.location.hash=oe(window.location.hash));else{ie(x()?.id);const a=x(),[o]=await Promise.all([a?f():Promise.resolve([]),T()]);if(a){const n=(window.location.hash||"#/").slice(1)||"/",s=D(n);s&&(window.location.hash=`#${s}`),j(o).catch(l=>console.error("[admin] Sidebar failed to load",l)),V()}}const e=R._extractParams.bind(R);R._extractParams=function(a,o){const n=o.indexOf("?");if(n!==-1&&(o=o.slice(0,n)),a.endsWith("/*")){const s=a.slice(0,-2);return o.startsWith(s+"/")?{}:null}return e(a,o)};const i=R._renderNotFound.bind(R);let t="";R._renderNotFound=async function(a){return m()&&t!==a&&(t=a,await T(),R._matchRoute(a).route)?(t="",R._handleRouteChange()):(t="",m()&&$("#admin-sidebar").get(0)?.style.display==="none"?(E.toast("That link goes nowhere - here is your home page.",{type:"warning"}),R.navigate("/")):i(a))},Ce(R),R.init({container:"#view-container",routes:I,views:O,default:"/",transitions:{enter:"fadeIn",leave:"fadeOut",duration:150}})})()});
54
+ `;const o=$("#topbar-settings").get(0);o&&(o.hidden=!g),$("#topbar-logout-btn").on("click",n=>{n.preventDefault(),te()}),Domma.icons.scan("#admin-topbar"),E.tooltip("#topbar-actions [data-tooltip]",{placement:"bottom"}),me(e),Q({refreshBadge:U,canRead:()=>u!==!1}),fe(e),W(),ce(),B(r),U(),h||(h=setInterval(U,6e4))}function d(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}let h=null;async function U(){if(!(!m()||u===!1))try{const{count:e}=await r.system.notifications.unreadCount(),i=$("#topbar-bell-badge");e>0?i.text(e>99?"99+":String(e)).removeAttr("hidden"):i.attr("hidden","").text(""),e>0&&he()&&ue(await r.system.notifications.list().catch(()=>[]))}catch{}}(async()=>{if(!m()&&!window.location.hash.startsWith("#/reset-password"))window.location.hash.startsWith("#/login")||(window.location.hash=oe(window.location.hash));else{ie(x()?.id);const a=x(),[o]=await Promise.all([a?f():Promise.resolve([]),T()]);if(a){const n=(window.location.hash||"#/").slice(1)||"/",s=D(n);s&&(window.location.hash=`#${s}`),j(o).catch(l=>console.error("[admin] Sidebar failed to load",l)),V()}}const e=R._extractParams.bind(R);R._extractParams=function(a,o){const n=o.indexOf("?");if(n!==-1&&(o=o.slice(0,n)),a.endsWith("/*")){const s=a.slice(0,-2);return o.startsWith(s+"/")?{}:null}return e(a,o)};const i=R._renderNotFound.bind(R);let t="";R._renderNotFound=async function(a){return m()&&t!==a&&(t=a,await T(),R._matchRoute(a).route)?(t="",R._handleRouteChange()):(t="",m()&&$("#admin-sidebar").get(0)?.style.display==="none"?(E.toast("That link goes nowhere - here is your home page.",{type:"warning"}),R.navigate("/")):i(a))},Ce(R),R.init({container:"#view-container",routes:I,views:O,default:"/",transitions:{enter:"fadeIn",leave:"fadeOut",duration:150}})})()});
@@ -1,3 +1,3 @@
1
- import{fmtDate as x}from"./dates.js";export const VERBS=["create","read","update","delete"],CONTENT_RESOURCES=["pages","menus","site","search"],FILTERS=["all","active","expiring","expired","disabled"],SOON_DAYS=14;const m=864e5,f=(e,n,r=`${n}s`)=>`${e} ${e===1?n:r}`;export function tokenState(e,n=Date.now()){const r=e?.expiresAt?Date.parse(e.expiresAt):NaN,t=Number.isFinite(r)?Math.ceil((r-n)/m):null;return Number.isFinite(r)&&r<=n?{state:"expired",days:t}:e?.enabled===!1?{state:"disabled",days:t}:t!==null&&t<=SOON_DAYS?{state:"expiring",days:t}:{state:"active",days:t}}export function expiresIn(e){return e==null?"":e<=0?"today":e===1?"tomorrow":`in ${e} days`}export function ago(e,n=Date.now()){const r=Date.parse(e);if(!Number.isFinite(r))return"";const t=Math.max(0,Math.round((n-r)/1e3));return t<60?"just now":t<3600?`${Math.round(t/60)} min ago`:t<86400?`${f(Math.round(t/3600),"hour")} ago`:t<86400*30?`${f(Math.round(t/86400),"day")} ago`:x(r)}export function scopesToText(e){return(Array.isArray(e)?e:[]).map(n=>n.content!==void 0?`@${n.content}`:Array.isArray(n.verbs)&&n.verbs.length?`${n.collection}: ${n.verbs.join(", ")}`:n.collection).join(`
2
- `)}export function parseScopes(e){const n=[],r=new Set;for(const t of String(e??"").split(`
3
- `)){const o=t.trim();if(!o)continue;if(o.startsWith("@")){if(o.includes(":"))return{error:`"${o}" - content scopes are read-only and take no verbs.`};const c=o.slice(1).trim().toLowerCase();if(!c)return{error:'"@" names no content resource.'};if(!CONTENT_RESOURCES.includes(c))return{error:`"@${c}" is not a content resource - use ${CONTENT_RESOURCES.map(u=>"@"+u).join(", ").replace(/, ([^,]*)$/," or $1")}.`};if(r.has("@"+c))return{error:`"@${c}" is listed twice.`};r.add("@"+c),n.push({content:c});continue}const s=o.indexOf(":"),a=(s<0?o:o.slice(0,s)).trim(),i=s<0?"":o.slice(s+1).trim();if(!a)return{error:`"${o}" names no collection.`};if(r.has(a))return{error:`"${a}" is listed twice.`};r.add(a);const l={collection:a};if(i){const c=i.split(",").map(p=>p.trim().toLowerCase()).filter(Boolean),u=c.find(p=>!VERBS.includes(p));if(u)return{error:`"${u}" is not a verb - use ${VERBS.join(", ")}.`};l.verbs=[...new Set(c)]}n.push(l)}return{scopes:n}}export function scopesSummary(e){if(!Array.isArray(e)||!e.length)return"everything in the project - its collections and the Content API";const n=e.filter(t=>t.content===void 0).map(t=>`${t.collection}: ${Array.isArray(t.verbs)&&t.verbs.length?t.verbs.join(", "):"all"}`),r=e.filter(t=>t.content!==void 0).map(t=>t.content);return[...n,...r.length?[`content: ${r.join(", ")}`]:[]].join(" \xB7 ")}export function arrangeTokens(e,{filter:n="all",project:r="",query:t=""}={},o=Date.now()){const s=String(t).trim().toLowerCase(),a={expired:0,expiring:1,active:2,disabled:3};return(e||[]).map(i=>({t:i,s:tokenState(i,o)})).filter(({s:i})=>n==="all"||i.state===n).filter(({t:i})=>!r||i.project===r).filter(({t:i})=>!s||[i.name,i.project,i.tokenHint,i.createdBy,scopesSummary(i.scopes)].some(l=>String(l||"").toLowerCase().includes(s))).sort((i,l)=>a[i.s.state]-a[l.s.state]||(i.s.state==="expiring"?i.s.days-l.s.days:0)||String(i.t.name||"").localeCompare(String(l.t.name||""))).map(({t:i})=>i)}export function countStates(e,n=Date.now()){const r={all:0,active:0,expiring:0,expired:0,disabled:0};for(const t of e||[])r.all++,r[tokenState(t,n).state]++;return r}const g={active:["Active","is-ok"],disabled:["Off",""],expired:["Expired","is-danger"],expiring:["","is-warn"]};export function tokenRow(e,n=Date.now()){const{state:r,days:t}=tokenState(e,n),[o,s]=g[r],a=e.expiresAt?r==="expired"?`expired ${ago(e.expiresAt,n)}`:`expires ${expiresIn(t)}`:"never expires";return{id:e.id,name:e.name||"(unnamed)",hint:`dcms_\u2026${e.tokenHint||"????"}`,project:e.project||"",meta:[scopesSummary(e.scopes),e.draftsOnly?"drafts only":"",a,e.createdBy?`by ${e.createdBy}`:""].filter(Boolean).join(" \xB7 "),used:e.lastUsedAt?`used ${ago(e.lastUsedAt,n)}`:"never used",stateLabel:r==="expiring"?`Expires ${expiresIn(t)}`:o,stateCls:s,rowCls:r==="disabled"||r==="expired"?"is-off":""}}export function toLocalInput(e){const n=Date.parse(e);if(!Number.isFinite(n))return"";const r=new Date(n),t=o=>String(o).padStart(2,"0");return`${r.getFullYear()}-${t(r.getMonth()+1)}-${t(r.getDate())}T${t(r.getHours())}:${t(r.getMinutes())}`}export function checkToken(e,{isNew:n,projects:r=[],now:t=Date.now()}={}){const o=e||{},s={},a=String(o.name??"").trim();a||(s.name="A token needs a name - who or what will use it."),n&&!String(o.project||"")?s.project="Choose the project it works in.":n&&r.length&&!r.includes(o.project)&&(s.project="Choose one of your projects.");const{scopes:i,error:l}=parseScopes(o.scopes);l&&(s.scopes=l);let c=null;if(String(o.expires||"").trim()){const d=Date.parse(o.expires);Number.isFinite(d)?(c=new Date(d).toISOString(),n&&d<=t&&(s.expires="That is already past - a new token would be dead on arrival.")):s.expires="Not a date."}const u=o.draftsOnly===!0,p=n?{name:a,project:o.project,scopes:i||[],expiresAt:c,draftsOnly:u}:{name:a,enabled:o.enabled!==!1,scopes:i||[],expiresAt:c,draftsOnly:u};return{errors:s,payload:p}}
1
+ import{fmtDate as x}from"./dates.js";export const VERBS=["create","read","update","delete"],CONTENT_RESOURCES=["pages","menus","site","search"],CONTENT_VERBS={pages:["read","create","update"],menus:["read"],site:["read"],search:["read"],media:["create"],blocks:["create","update"]};const g=Object.keys(CONTENT_VERBS);export const FILTERS=["all","active","expiring","expired","disabled"],SOON_DAYS=14;const $=864e5,m=(n,r,e=`${r}s`)=>`${n} ${n===1?r:e}`;export function tokenState(n,r=Date.now()){const e=n?.expiresAt?Date.parse(n.expiresAt):NaN,t=Number.isFinite(e)?Math.ceil((e-r)/$):null;return Number.isFinite(e)&&e<=r?{state:"expired",days:t}:n?.enabled===!1?{state:"disabled",days:t}:t!==null&&t<=SOON_DAYS?{state:"expiring",days:t}:{state:"active",days:t}}export function expiresIn(n){return n==null?"":n<=0?"today":n===1?"tomorrow":`in ${n} days`}export function ago(n,r=Date.now()){const e=Date.parse(n);if(!Number.isFinite(e))return"";const t=Math.max(0,Math.round((r-e)/1e3));return t<60?"just now":t<3600?`${Math.round(t/60)} min ago`:t<86400?`${m(Math.round(t/3600),"hour")} ago`:t<86400*30?`${m(Math.round(t/86400),"day")} ago`:x(e)}export function scopesToText(n){return(Array.isArray(n)?n:[]).map(r=>r.content!==void 0?Array.isArray(r.verbs)&&r.verbs.length?`@${r.content}: ${r.verbs.join(", ")}`:`@${r.content}`:Array.isArray(r.verbs)&&r.verbs.length?`${r.collection}: ${r.verbs.join(", ")}`:r.collection).join(`
2
+ `)}export function parseScopes(n){const r=[],e=new Set;for(const t of String(n??"").split(`
3
+ `)){const s=t.trim();if(!s)continue;if(s.startsWith("@")){const u=s.indexOf(":"),c=(u<0?s.slice(1):s.slice(1,u)).trim().toLowerCase();if(!c)return{error:'"@" names no content resource.'};if(!g.includes(c))return{error:`"@${c}" is not a content resource - use ${g.map(f=>"@"+f).join(", ").replace(/, ([^,]*)$/," or $1")}.`};if(e.has("@"+c))return{error:`"@${c}" is listed twice.`};e.add("@"+c);const d=CONTENT_VERBS[c],p=u<0?[]:[...new Set(s.slice(u+1).split(",").map(f=>f.trim().toLowerCase()).filter(Boolean))],h=p.find(f=>!d.includes(f));if(h)return{error:`"@${c}" may ${d.join(", ")} - not "${h}".`};if(!p.length&&!d.includes("read"))return{error:`"@${c}" needs what it may do: @${c}: ${d.join(", ")}.`};r.push(p.length?{content:c,verbs:p}:{content:c});continue}const o=s.indexOf(":"),a=(o<0?s:s.slice(0,o)).trim(),i=o<0?"":s.slice(o+1).trim();if(!a)return{error:`"${s}" names no collection.`};if(e.has(a))return{error:`"${a}" is listed twice.`};e.add(a);const l={collection:a};if(i){const u=i.split(",").map(d=>d.trim().toLowerCase()).filter(Boolean),c=u.find(d=>!VERBS.includes(d));if(c)return{error:`"${c}" is not a verb - use ${VERBS.join(", ")}.`};l.verbs=[...new Set(u)]}r.push(l)}return{scopes:r}}export function scopesSummary(n){if(!Array.isArray(n)||!n.length)return"everything in the project - its collections and the Content API";const r=n.filter(t=>t.content===void 0).map(t=>`${t.collection}: ${Array.isArray(t.verbs)&&t.verbs.length?t.verbs.join(", "):"all"}`),e=n.filter(t=>t.content!==void 0).map(t=>Array.isArray(t.verbs)&&t.verbs.length?`${t.content} (${t.verbs.join(", ")})`:t.content);return[...r,...e.length?[`content: ${e.join(", ")}`]:[]].join(" \xB7 ")}export function arrangeTokens(n,{filter:r="all",project:e="",query:t=""}={},s=Date.now()){const o=String(t).trim().toLowerCase(),a={expired:0,expiring:1,active:2,disabled:3};return(n||[]).map(i=>({t:i,s:tokenState(i,s)})).filter(({s:i})=>r==="all"||i.state===r).filter(({t:i})=>!e||i.project===e).filter(({t:i})=>!o||[i.name,i.project,i.tokenHint,i.createdBy,scopesSummary(i.scopes)].some(l=>String(l||"").toLowerCase().includes(o))).sort((i,l)=>a[i.s.state]-a[l.s.state]||(i.s.state==="expiring"?i.s.days-l.s.days:0)||String(i.t.name||"").localeCompare(String(l.t.name||""))).map(({t:i})=>i)}export function countStates(n,r=Date.now()){const e={all:0,active:0,expiring:0,expired:0,disabled:0};for(const t of n||[])e.all++,e[tokenState(t,r).state]++;return e}const w={active:["Active","is-ok"],disabled:["Off",""],expired:["Expired","is-danger"],expiring:["","is-warn"]};export function tokenRow(n,r=Date.now()){const{state:e,days:t}=tokenState(n,r),[s,o]=w[e],a=n.expiresAt?e==="expired"?`expired ${ago(n.expiresAt,r)}`:`expires ${expiresIn(t)}`:"never expires";return{id:n.id,name:n.name||"(unnamed)",hint:`dcms_\u2026${n.tokenHint||"????"}`,project:n.project||"",meta:[scopesSummary(n.scopes),n.draftsOnly?"drafts only":"",a,n.createdBy?`by ${n.createdBy}`:""].filter(Boolean).join(" \xB7 "),used:n.lastUsedAt?`used ${ago(n.lastUsedAt,r)}`:"never used",stateLabel:e==="expiring"?`Expires ${expiresIn(t)}`:s,stateCls:o,rowCls:e==="disabled"||e==="expired"?"is-off":""}}export function toLocalInput(n){const r=Date.parse(n);if(!Number.isFinite(r))return"";const e=new Date(r),t=s=>String(s).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}export function checkToken(n,{isNew:r,projects:e=[],now:t=Date.now()}={}){const s=n||{},o={},a=String(s.name??"").trim();a||(o.name="A token needs a name - who or what will use it."),r&&!String(s.project||"")?o.project="Choose the project it works in.":r&&e.length&&!e.includes(s.project)&&(o.project="Choose one of your projects.");const{scopes:i,error:l}=parseScopes(s.scopes);l&&(o.scopes=l);let u=null;if(String(s.expires||"").trim()){const p=Date.parse(s.expires);Number.isFinite(p)?(u=new Date(p).toISOString(),r&&p<=t&&(o.expires="That is already past - a new token would be dead on arrival.")):o.expires="Not a date."}const c=s.draftsOnly===!0,d=r?{name:a,project:s.project,scopes:i||[],expiresAt:u,draftsOnly:c}:{name:a,enabled:s.enabled!==!1,scopes:i||[],expiresAt:u,draftsOnly:c};return{errors:o,payload:d}}export function recipeRows(n=[],r=[],{edit:e=!1}={}){const t=new Set(r),s=e?["create","update"]:["create"];return n.map(o=>{if(!o.ok)return{slug:o.slug,title:o.title||o.slug,ok:!1,chosen:!1,note:o.why||"Cannot be used.",tone:"muted"};const a=[];a.push(o.drafts==="has"?"Holds drafts.":"No draft status yet - a Status field (draft / published) is added.");for(const l of s){const u=o.api?.[l];u?.enabled&&u.access!=="token"&&a.push(`${l} is already open to ${u.access==="public"?"everyone":`the ${u.access} role`} - left as it is.`)}o.hasAuthor&&a.push("Needs an author: the bot is told to credit you.");const i=o.drafts==="add"||a.some(l=>l.includes("left as it is"));return{slug:o.slug,title:o.title||o.slug,ok:!0,chosen:t.has(o.slug),note:a.join(" "),tone:i?"attention":"ok",drafts:o.drafts}}).sort((o,a)=>b(o)-b(a)||o.title.localeCompare(a.title))}const b=n=>n.ok?n.drafts==="has"?0:1:2;export function recipeUnavailable(n=[]){const r=n.filter(e=>!e.ok).map(e=>e.title||e.slug).sort((e,t)=>e.localeCompare(t));return r.length?`Not offered (a Status field without a draft option): ${r.join(", ")}.`:""}export function recipePayload(n=[],r=[],{edit:e=!1}={}){const t=new Set(r),s=n.filter(o=>o.ok&&t.has(o.slug)).map(o=>({slug:o.slug,verbs:e?["create","update"]:["create"],addStatus:o.drafts==="add"}));return s.length?{collections:s}:null}export const RECIPE_CONTENT=[{resource:"pages",label:"Pages, as drafts",note:"New pages wait as drafts; a person publishes them."},{resource:"media",label:"Pictures and PDFs",note:"Public at /media once uploaded (unlinked until a page uses it). Never over another file."},{resource:"blocks",label:"New blocks",note:"Only new ones. A block has no draft: it shows wherever a page uses it."}];export function recipeContentScopes(n=[],{edit:r=!1}={}){const e=new Set(n),t=[];return e.has("pages")&&t.push({content:"pages",verbs:r?["create","update"]:["create"]}),e.has("media")&&t.push({content:"media",verbs:["create"]}),e.has("blocks")&&t.push({content:"blocks",verbs:["create"]}),t}export function recipeReport(n=[]){const r=[];for(const e of n){const t=[];e.opened?.length&&t.push(`opened ${e.opened.join(" and ")} to tokens`),e.addsStatus&&t.push("added a Status field"),r.push(`${e.slug}: ${t.length?t.join(", "):"nothing needed changing"}.`);for(const s of e.warnings||[])r.push(` ${s}`)}return r}
@@ -1,11 +1,11 @@
1
- import{api as A,apiRequest as k}from"../api.js";import{sidebarCount as S}from"./tool-kit.js";import{severityOf as C}from"./notifications-arrange.js";import{wireNotificationCacheMenu as L}from"./topbar-cache.js";const q=[["critical","Critical","alert-circle","danger"],["warning","Warnings","alert-triangle","warn"],["info","Information","info","info"],["success","Success","check-circle","ok"]];export function notificationGroups(p=[]){return q.map(([i,c,u,e])=>{const d=p.filter(l=>C(l)===i);return{type:i,label:c,icon:u,tone:e,total:d.length,unread:d.filter(l=>l.unread).length}})}let y;export function wireNotificationMenu({refreshBadge:p}){y?.abort(),y=new AbortController;const{signal:i}=y,c=document.getElementById("topbar-notifications");if(!c)return;const u=c.querySelector("#topbar-bell"),e=c.querySelector("#topbar-notifications-menu"),d=document.createElement("div");d.dataset.notificationItems="",e.replaceChildren(d),L();let l=0,m=!1;const f=()=>{l++,e.hidden=!0,u.setAttribute("aria-expanded","false")},h=t=>{const n=document.createElement("p");n.className="nt-menu-status",n.setAttribute("role","status"),n.textContent=t,d.replaceChildren(n)},g=t=>{const n=d.contains(document.activeElement)?document.activeElement:null,o=n?.dataset.dismiss,s=n?.getAttribute("href"),r=n?.hasAttribute("data-read-all"),v=notificationGroups(t);d.innerHTML=`<div class="nt-menu-heading" aria-live="polite">Notifications <span>${v.reduce((a,$)=>a+$.unread,0)} unread</span></div>
2
- ${v.map(a=>`<div class="nt-menu-row">
1
+ import{api as S,apiRequest as C}from"../api.js";import{sidebarCount as L}from"./tool-kit.js";import{severityOf as q}from"./notifications-arrange.js";import{wireNotificationCacheMenu as D}from"./topbar-cache.js";const x=[["critical","Critical","alert-circle","danger"],["warning","Warnings","alert-triangle","warn"],["info","Information","info","info"],["success","Success","check-circle","ok"]];export function notificationGroups(y=[]){return x.map(([m,i,d,l])=>{const e=y.filter(r=>q(r)===m);return{type:m,label:i,icon:d,tone:l,total:e.length,unread:e.filter(r=>r.unread).length}})}let h;export function wireNotificationMenu({refreshBadge:y,canRead:m=()=>!0}){h?.abort(),h=new AbortController;const{signal:i}=h,d=document.getElementById("topbar-notifications");if(!d)return;const l=d.querySelector("#topbar-bell"),e=d.querySelector("#topbar-notifications-menu"),r=document.createElement("div");r.dataset.notificationItems="";const w=e.querySelector(".topbar-sidebar-choice");e.replaceChildren(r,...w?[w]:[]),D();let p=0,f=!1;const u=()=>{p++,e.hidden=!0,l.setAttribute("aria-expanded","false")},b=t=>{const n=document.createElement("p");n.className="nt-menu-status",n.setAttribute("role","status"),n.textContent=t,r.replaceChildren(n)},A=t=>{const n=r.contains(document.activeElement)?document.activeElement:null,o=n?.dataset.dismiss,s=n?.getAttribute("href"),c=n?.hasAttribute("data-read-all"),$=notificationGroups(t);r.innerHTML=`<div class="nt-menu-heading" aria-live="polite">Notifications <span>${$.reduce((a,k)=>a+k.unread,0)} unread</span></div>
2
+ ${$.map(a=>`<div class="nt-menu-row">
3
3
  <a class="nt-menu-type" href="#/system/notifications?type=${a.type}">
4
4
  <span class="nt-menu-icon is-${a.tone}"><span data-icon="${a.icon}"></span></span>
5
5
  <span>${a.label}<small>${a.unread} unread / ${a.total} total</small></span>
6
6
  </a>
7
- <button type="button" class="nt-menu-dismiss" data-dismiss="${a.type}" data-count="${a.total}" aria-label="Dismiss ${a.total} ${a.label.toLowerCase()} notifications" ${!a.total||m?"disabled":""}>Dismiss</button>
7
+ <button type="button" class="nt-menu-dismiss" data-dismiss="${a.type}" data-count="${a.total}" aria-label="Dismiss ${a.total} ${a.label.toLowerCase()} notifications" ${!a.total||f?"disabled":""}>Dismiss</button>
8
8
  </div>`).join("")}
9
9
  ${t.length?"":`<p class="nt-menu-status">No notifications - you're all caught up.</p>`}
10
10
  <div class="nt-menu-footer"><a href="#/system/notifications?type=all">View all notifications</a>
11
- <button type="button" data-read-all ${m||!t.some(a=>a.unread)?"disabled":""}>Mark all as read</button></div>`,Domma.icons.scan(e),o?(e.querySelector(`[data-dismiss="${o}"]:not(:disabled)`)||e.querySelector(`a[href$="type=${o}"]`))?.focus():s?[...e.querySelectorAll("a")].find(a=>a.getAttribute("href")===s)?.focus():r&&(e.querySelector("[data-read-all]:not(:disabled)")||e.querySelector(".nt-menu-footer a"))?.focus()},b=async()=>{const t=++l;try{const n=await A.system.notifications.list();if(i.aborted||t!==l||e.hidden)return;g(Array.isArray(n)?n:[])}catch{!i.aborted&&t===l&&!e.hidden&&h("Could not load notifications. Close and reopen to try again.")}},w=async t=>{document.dispatchEvent(new CustomEvent("dm:topbar-menu-open",{detail:{owner:c}})),e.hidden=!1,u.setAttribute("aria-expanded","true"),h("Loading notifications..."),await b(),t&&!e.hidden&&e.querySelector("a, button:not(:disabled)")?.focus()};u.addEventListener("click",()=>e.hidden?w(!1):f(),{signal:i}),u.addEventListener("keydown",t=>{t.key==="ArrowDown"&&(t.preventDefault(),w(!0))},{signal:i}),e.addEventListener("click",async t=>{const n=t.target.closest("a");if(n){const r=new URLSearchParams(n.hash.split("?")[1]||"").get("type");document.dispatchEvent(new CustomEvent("dm:notifications-filter",{detail:{type:r}})),f();return}const o=t.target.closest("button");if(!o||o.disabled||m||!o.hasAttribute("data-dismiss")&&!o.hasAttribute("data-read-all"))return;const s=o.dataset.dismiss;m=!0;try{if(s==="critical"&&!await E.confirm(`Dismiss all ${o.dataset.count} critical notifications? They are hidden for you only.`))return;d.querySelectorAll("button").forEach(r=>{r.disabled=!0}),await k(`/system/notifications/${s?"dismiss-all":"read-all"}`,{method:"POST",...s?{body:JSON.stringify({severity:s})}:{}}),document.dispatchEvent(new CustomEvent("dm:notifications-changed")),S("#/system/notifications"),await p()}catch(r){E.toast(`Could not update notifications: ${r.message||r}`,{type:"error"})}finally{m=!1,!i.aborted&&!e.hidden&&await b()}},{signal:i}),e.addEventListener("keydown",t=>{const n=[...e.querySelectorAll("a, button:not(:disabled)")].filter(r=>!r.closest("[hidden]")),o=n.indexOf(document.activeElement);if(o<0)return;let s;t.key==="ArrowDown"&&(s=(o+1)%n.length),t.key==="ArrowUp"&&(s=(o-1+n.length)%n.length),t.key==="Home"&&(s=0),t.key==="End"&&(s=n.length-1),s!==void 0&&(t.preventDefault(),n[s].focus())},{signal:i}),document.addEventListener("click",t=>{c.contains(t.target)||f()},{signal:i}),document.addEventListener("focusin",t=>{c.contains(t.target)||f()},{signal:i}),document.addEventListener("dm:topbar-menu-open",t=>{t.detail.owner!==c&&f()},{signal:i}),document.addEventListener("keydown",t=>{!t.defaultPrevented&&t.key==="Escape"&&!e.hidden&&(f(),u.focus(),t.preventDefault())},{signal:i}),window.addEventListener("hashchange",f,{signal:i})}
11
+ <button type="button" data-read-all ${f||!t.some(a=>a.unread)?"disabled":""}>Mark all as read</button></div>`,Domma.icons.scan(e),o?(e.querySelector(`[data-dismiss="${o}"]:not(:disabled)`)||e.querySelector(`a[href$="type=${o}"]`))?.focus():s?[...e.querySelectorAll("a")].find(a=>a.getAttribute("href")===s)?.focus():c&&(e.querySelector("[data-read-all]:not(:disabled)")||e.querySelector(".nt-menu-footer a"))?.focus()},v=async()=>{if(!m()){b("Notifications are unavailable for this account.");return}const t=++p;try{const n=await S.system.notifications.list();if(i.aborted||t!==p||e.hidden)return;A(Array.isArray(n)?n:[])}catch{!i.aborted&&t===p&&!e.hidden&&b("Could not load notifications. Close and reopen to try again.")}},g=async t=>{document.dispatchEvent(new CustomEvent("dm:topbar-menu-open",{detail:{owner:d}})),e.hidden=!1,l.setAttribute("aria-expanded","true"),b("Loading notifications..."),await v(),t&&!e.hidden&&e.querySelector("a, input:not(:disabled), button:not(:disabled)")?.focus()};l.addEventListener("click",()=>e.hidden?g(!1):u(),{signal:i}),l.addEventListener("keydown",t=>{t.key==="ArrowDown"&&(t.preventDefault(),g(!0))},{signal:i}),e.addEventListener("click",async t=>{const n=t.target.closest("a");if(n){const c=new URLSearchParams(n.hash.split("?")[1]||"").get("type");document.dispatchEvent(new CustomEvent("dm:notifications-filter",{detail:{type:c}})),u();return}const o=t.target.closest("button");if(!o||o.disabled||f||!o.hasAttribute("data-dismiss")&&!o.hasAttribute("data-read-all"))return;const s=o.dataset.dismiss;f=!0;try{if(s==="critical"&&!await E.confirm(`Dismiss all ${o.dataset.count} critical notifications? They are hidden for you only.`))return;r.querySelectorAll("button").forEach(c=>{c.disabled=!0}),await C(`/system/notifications/${s?"dismiss-all":"read-all"}`,{method:"POST",...s?{body:JSON.stringify({severity:s})}:{}}),document.dispatchEvent(new CustomEvent("dm:notifications-changed")),L("#/system/notifications"),await y()}catch(c){E.toast(`Could not update notifications: ${c.message||c}`,{type:"error"})}finally{f=!1,!i.aborted&&!e.hidden&&await v()}},{signal:i}),e.addEventListener("keydown",t=>{const n=[...e.querySelectorAll("a, input:not(:disabled), button:not(:disabled)")].filter(c=>!c.closest("[hidden]")),o=n.indexOf(document.activeElement);if(o<0)return;let s;t.key==="ArrowDown"&&(s=(o+1)%n.length),t.key==="ArrowUp"&&(s=(o-1+n.length)%n.length),t.key==="Home"&&(s=0),t.key==="End"&&(s=n.length-1),s!==void 0&&(t.preventDefault(),n[s].focus())},{signal:i}),document.addEventListener("click",t=>{d.contains(t.target)||u()},{signal:i}),document.addEventListener("focusin",t=>{d.contains(t.target)||u()},{signal:i}),document.addEventListener("dm:topbar-menu-open",t=>{t.detail.owner!==d&&u()},{signal:i}),document.addEventListener("keydown",t=>{!t.defaultPrevented&&t.key==="Escape"&&!e.hidden&&(u(),l.focus(),t.preventDefault())},{signal:i}),window.addEventListener("hashchange",u,{signal:i})}
@@ -83,4 +83,20 @@
83
83
  .atx-token { display: block; padding: .65rem; word-break: break-all; user-select: all; border-radius: var(--dm-radius-sm);
84
84
  background: var(--dm-surface-raised, color-mix(in srgb, var(--dm-text) 6%, transparent)); color: var(--dm-text); font-family: var(--dm-font-mono, monospace); }
85
85
  @media (max-width: 640px) { .atx-used { display: none; } }
86
+ .atx-recipe { display: flex; flex-direction: column; gap: .5rem; }
87
+ .atx-recipe-content { display: flex; flex-direction: column; gap: .35rem; }
88
+ .atx-recipe-list { display: flex; flex-direction: column; gap: .35rem; max-height: 18rem; overflow: auto; }
89
+ .atx-recipe-row { display: flex; gap: .6rem; align-items: flex-start; padding: .45rem .55rem; border: 1px solid var(--dm-border);
90
+ border-radius: var(--dm-radius-sm); cursor: pointer; }
91
+ .atx-recipe-row input { margin-top: .2rem; }
92
+ .atx-recipe-row small { color: var(--dm-text-muted); }
93
+ .atx-recipe-row.is-attention small { color: var(--dm-warning, var(--dm-text)); }
94
+ .atx-recipe-row.is-off { opacity: .6; cursor: default; }
95
+ .atx-recipe-edit { display: flex; gap: .5rem; align-items: center; font-size: .9em; }
96
+ .atx-handover { display: flex; flex-direction: column; gap: .5rem; padding-top: .6rem; border-top: 1px solid var(--dm-border); }
97
+ .atx-handover .atx-hint { margin: 0; }
98
+ .atx-link-text { display: block; padding: .5rem; word-break: break-all; user-select: all; border-radius: var(--dm-radius-sm); }
99
+ .atx-report { margin: 0; padding-left: 1.1rem; font-size: .9em; }
100
+ .atx-report .atx-report-warn { list-style: none; margin-left: -1.1rem; color: var(--dm-text-muted); }
101
+ .atx-form [hidden], .atx-recipe [hidden], .atx-handover [hidden] { display: none !important; }
86
102
  </style>