domma-cms 1.37.0 → 1.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/CLAUDE.md +9 -0
- package/admin/js/api.js +1 -1
- package/admin/js/lib/plugins-arrange.js +2 -2
- package/admin/js/templates/plugins.html +2 -0
- package/admin/js/views/plugins.js +24 -12
- package/bin/update.js +2 -0
- package/docs/DommaFeatures.md +3 -3
- package/docs/configuration.md +1 -0
- package/docs/plugin-development.md +11 -0
- package/package.json +1 -1
- package/plugins/_lib/games/hub.js +35 -0
- package/plugins/_lib/public/games/games.css +1 -1
- package/plugins/_lib/public/games/hub.js +79 -0
- package/server/routes/api/plugin-marketplace.js +249 -19
- package/server/services/siteGitignore.js +2 -0
- package/server/services/storeClient.js +333 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.39.0] - 2026-11-06
|
|
4
|
+
|
|
5
|
+
- **Self-hosted sites buy Tools inside their admin.** On a site with no manager, Marketplace > Browse reads the Domma store: **Buy…** opens the payment page in a new tab and the Tool installs itself once paid. Bought outright - it keeps working for good - with a term of updates; **Renew…** buys another. One licence per site address. The payment claim and licence keys stay on the server in `config/store.json` (kept out of git); `server.json` `storeUrl` (or `DOMMA_STORE_URL`) points the store elsewhere, and `false` switches it off. See `server/services/storeClient.js`.
|
|
6
|
+
- **Enter licence key…** on a store Tool takes a key bought on the public Marketplace page, and **Connect to Domma** links the site to the email it bought with, so every licence bought for its address arrives by itself.
|
|
7
|
+
- A Tool that comes free with a purchase (the MongoDB Adapter with Email and Data Transfer) installs beside it.
|
|
8
|
+
|
|
9
|
+
## [1.38.0] - 2026-11-06
|
|
10
|
+
|
|
11
|
+
- **One leaderboards hub for every Game.** `[games-leaderboards /]` now lives in the shared Games library (`plugins/_lib/games/hub.js` and `public/games/hub.js`), so any Game with a leaderboard can join it without a change here: it shows a group for every Game the site has, in the order `games="..."` names them or else by name. Its styles moved into the shared Games stylesheet. For Hangman, Anagram, Group Four, Jigsaw, Sliding Puzzle, Memory Pairs, Timeline, Higher or Lower, Picture Reveal, Treasure Hunt and Map Guess, which join the four first Games in the hub.
|
|
12
|
+
|
|
3
13
|
## [1.37.0] - 2026-11-05
|
|
4
14
|
|
|
5
15
|
- Booking is now included in the Calendar Tool, together with the former Booking Pro features, availability controls and Google Calendar connections. New CMS installations no longer ship a separate Booking plugin.
|
package/CLAUDE.md
CHANGED
|
@@ -193,6 +193,15 @@ copy is touched, carries `data/` and `.entitlement.json` across, and restores th
|
|
|
193
193
|
any failure - "neither version installed" is the one state it must never produce. Versions compare
|
|
194
194
|
numerically (1.10.0 > 1.2.0). Unsigned installs and downgrades each need their own explicit flag.
|
|
195
195
|
|
|
196
|
+
**Self-hosted sites buy from the Domma store - `server/services/storeClient.js`.** A site with no manager (no
|
|
197
|
+
`MANAGER_URL`/`FLEET_TOKEN`) and no wildcard owner entitlement reads Browse from the store (`server.json` `storeUrl`,
|
|
198
|
+
`DOMMA_STORE_URL`; default the manager's `site-manager/store`), not the fleet catalogue. `routes/api/plugin-marketplace.js`
|
|
199
|
+
`buy` starts a checkout and keeps the CLAIM secret in `config/store.json` (0600, gitignored, with the licence keys) -
|
|
200
|
+
the browser only ever gets the payment URL; `claim` swaps it for the key once paid and installs through
|
|
201
|
+
`installPlugin` with the envelope's entitlement. Bought outright (perpetual): the entitlement's `supportExpiresAt`
|
|
202
|
+
is the licence's and the store refuses a NEWER version after it (`mayDownload` on the manager); one licence per site
|
|
203
|
+
address (`self:<host>`), so localhost/IP/.local addresses are refused there.
|
|
204
|
+
|
|
196
205
|
**Signed-only sites (hosted) - `server/services/codePolicy.js`.** `signedOnly()` is true when the environment has
|
|
197
206
|
`DOMMA_SIGNED_ONLY=1` (the Manager sets it on sites it forks, after the site's .env), when server.json had
|
|
198
207
|
`requireSignedPlugins: true` at boot, or when it has it now. On such a site the hosted owner is level 0, and
|
package/admin/js/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{claimDrafts as $}from"./lib/draft-owner.js";import{loginHashFor as O}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function y(e){S.set("auth_token",e)}function f(){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 f(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return y(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"})},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&&y(e),o&&S.set("auth_refresh_token",o),n&&($(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=O(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(()=>{}),f()}export{t as apiRequest,g as refreshAccessToken,a as getToken,f 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"})},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=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e})}),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,2 +1,2 @@
|
|
|
1
|
-
export const FILTERS=["all","on","off","attention"],BROWSE_FILTERS=["all","installed","available","updates"],BLOCKING=new Set(["expired","unlicensed"]);const
|
|
2
|
-
`)||
|
|
1
|
+
export const FILTERS=["all","on","off","attention"],BROWSE_FILTERS=["all","installed","available","updates"],BLOCKING=new Set(["expired","unlicensed"]);const x={grace:{text:"Renew",tone:"warn",title:"The rental term has ended - still running during the grace period"},"support-ended":{text:"Support ended",tone:"muted",title:"Owned outright and still running, but no longer entitled to updates"},expired:{text:"Expired",tone:"danger",title:"The rental term and grace period have ended - this plugin is not running"},unlicensed:{text:"Unlicensed",tone:"danger",title:"No valid entitlement for this site - this plugin is not running"}};export function compareVersions(e,r){const t=a=>String(a??"").split(".").map(o=>parseInt(o,10)||0),n=t(e),s=t(r);for(let a=0;a<Math.max(n.length,s.length);a++){const o=(n[a]??0)-(s[a]??0);if(o)return o>0?1:-1}return 0}export function pluginStatus(e){return e.core?{key:"core",text:"Built in",tone:"info",running:!0}:e.enabled&&BLOCKING.has(e.entitlement)?{key:"blocked",text:"Not running",tone:"danger",running:!1}:e.enabled&&e.supersededBy?{key:"replaced",text:"Replaced",tone:"muted",running:!1}:e.enabled&&e.blockedBy?{key:"blocked",text:`Needs ${e.blockedBy}`,tone:"danger",running:!1}:e.enabled?{key:"on",text:"On",tone:"ok",running:!0}:{key:"off",text:"Off",tone:"muted",running:!1}}export function updateFor(e,r){const t=r?.get?.(e.name);return t&&compareVersions(t,e.version)>0?t:""}export function needsAttention(e,r){return pluginStatus(e).key==="blocked"||e.entitlement==="grace"||!!updateFor(e,r)}export function fmtReleased(e){if(!e||!/^\d{4}-\d{2}-\d{2}/.test(String(e)))return"";const r=new Date(e);if(Number.isNaN(r.getTime()))return"";const t=n=>String(n).padStart(2,"0");return`${t(r.getDate())}.${t(r.getMonth()+1)}.${r.getFullYear()}`}export function arrangePlugins(e,{filter:r="all",query:t="",latest:n=new Map}={}){const s=String(t).trim().toLowerCase(),a={all:()=>!0,on:i=>pluginStatus(i).running,off:i=>!pluginStatus(i).running,attention:i=>needsAttention(i,n)}[r]||(()=>!0),o=i=>needsAttention(i,n)?0:pluginStatus(i).running?1:2;return[...e||[]].filter(a).filter(i=>!s||[i.name,i.displayName,i.description,i.author].some(c=>String(c||"").toLowerCase().includes(s))).sort((i,c)=>o(i)-o(c)||String(i.displayName||i.name).localeCompare(String(c.displayName||c.name)))}export function pluginRow(e,r=new Map){const t=pluginStatus(e),n=x[e.entitlement]||null,s=updateFor(e,r),a=fmtReleased(e.date);return{name:e.name,displayName:e.displayName||e.name,icon:e.icon||"package",meta:[`v${e.version}`,e.author?`by ${e.author}`:"",a?`released ${a}`:"",e.supersededBy?`replaced by ${e.supersededBy}`:"",e.locked?"locked by your manager":""].filter(Boolean).join(" \xB7 "),description:e.description||"",statusText:t.text,statusCls:`is-${t.tone}`,licensed:e.closedSource===!0,entText:n?.text||"",entCls:n?`is-${n.tone}`:"",entTitle:n?.title||"",update:s,updateText:s?`Update to ${s}`:"",configurable:settingsFields(e).length>0,locked:e.locked===!0,rowCls:[t.running?"":"is-off",needsAttention(e,r)?"is-attention":""].filter(Boolean).join(" ")}}export function formatMoney(e,r="GBP"){const t={GBP:"\xA3",USD:"$",EUR:"\u20AC"}[String(r||"GBP").toUpperCase()],n=(Number(e)/100).toFixed(2);return t?`${t}${n}`:`${n} ${r}`}export function formatPrice(e){if(e?.tier!=="paid")return"Free";if(e.store)return e.owned?e.canRenew&&Number.isFinite(Number(e.renewal))&&e.renewal>0?`Renew ${formatMoney(e.renewal,e.currency)}`:"Owned":e.forSale&&Number(e.price)>0?formatMoney(e.price,e.currency):"Not on sale";const r=e.terms?.managed?.monthly;return r==null||!Number.isFinite(Number(r))?"Paid":`${e.terms?.currency==="GBP"?"\xA3":`${e.terms?.currency||""} `}${(Number(r)/100).toFixed(2)}/mo`}export function catalogueAction(e){return e.store&&e.pending?"waiting":e.installed&&e.updatable&&e.entitled?e.needsCms?"needs-cms":"update":e.store&&e.owned&&e.updatable&&e.canRenew||e.store&&e.installed&&e.tier==="paid"&&!e.owned&&!e.licensedHere&&e.forSale?"buy":e.installed?"installed":e.entitled?e.needsCms?"needs-cms":"install":e.store?(e.owned?e.canRenew:e.forSale)?"buy":"locked":e.buyUrl?"buy":"locked"}export function arrangeCatalogue(e,{filter:r="all",query:t=""}={}){const n=String(t).trim().toLowerCase(),s={all:()=>!0,installed:o=>o.installed,available:o=>catalogueAction(o)==="install",updates:o=>catalogueAction(o)==="update"}[r]||(()=>!0),a={waiting:0,update:1,install:2,buy:3,installed:4,"needs-cms":5,locked:6};return[...e||[]].filter(s).filter(o=>!n||[o.slug,o.displayName,o.description].some(i=>String(i||"").toLowerCase().includes(n))).sort((o,i)=>a[catalogueAction(o)]-a[catalogueAction(i)]||String(o.displayName||o.slug).localeCompare(String(i.displayName||i.slug)))}function h(e,r){return{update:"Update",install:"Install",installed:"Installed","needs-cms":"Needs newer CMS",waiting:"Paid? Check\u2026",buy:(e.store?e.owned:e.licenceStatus==="expired")?"Renew\u2026":"Buy\u2026",locked:e.store?e.owned?"Updates ended":"Not on sale":e.licenceStatus==="expired"?"Licence expired":"Not licensed"}[r]}function b(e){return e.tier!=="paid"?{licText:"",licCls:"is-ok"}:e.store?e.owned?e.updates?{licText:"Licensed",licCls:"is-ok"}:{licText:"Updates ended",licCls:"is-warn"}:{licText:"",licCls:"is-ok"}:e.entitled?e.licenceStatus==="grace"?{licText:"Renew",licCls:"is-warn"}:{licText:"Licensed",licCls:"is-ok"}:{licText:"",licCls:"is-ok"}}export function supportText(e,r=Date.now()){if(!e?.store||!e.owned||!e.supportEnds)return"";const t=Date.parse(e.supportEnds);if(!Number.isFinite(t))return"";const n=new Date(t).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"});return t>=r?`updates until ${n}`:`updates ended ${n}`}export function catalogueRow(e){const r=catalogueAction(e);return{slug:e.slug,displayName:e.displayName||e.slug,icon:e.icon||"package",meta:[e.installed&&e.installedVersion&&e.installedVersion!==e.version?`v${e.installedVersion} \u2192 v${e.version}`:`v${e.version}`,e.installed?"installed":"",supportText(e),e.store&&e.note?e.note:"",r==="waiting"?"waiting for payment":"",r==="needs-cms"&&e.minCmsVersion?`needs Domma CMS ${String(e.minCmsVersion).replace(/^[^\d]+/,"")} or later`:""].filter(Boolean).join(" \xB7 "),description:e.description||"",price:formatPrice(e),...b(e),action:r,actionText:h(e,r),rowCls:r==="locked"||r==="needs-cms"?"is-off":r==="update"||r==="waiting"?"is-attention":""}}export function storeBuyLines(e,{site:r="",email:t=""}={}){const n=e.displayName||e.slug;return e.owned?{title:`Renew ${n}`,lines:[`${e.renewalPeriodMonths||12} more months of updates for ${n} on ${r||"this site"}: ${formatMoney(e.renewal,e.currency)}, paid once.`,"The version you have keeps working either way.",`Payment opens in a new tab. The receipt goes to ${t||"your email address"}.`]}:{title:`Buy ${n}`,lines:[`${n} for ${r||"this site"}: ${formatMoney(e.price,e.currency)}, paid once. It is yours to keep, with ${e.supportMonths||12} months of updates - renew them later if you like.`,"One licence covers one site address.",`Payment opens in a new tab. The receipt and licence key go to ${t||"your email address"}, and ${n} installs here as soon as the payment is through.`]}}export const isSecretKey=e=>/pass(word)?|secret|token|api[-_]?key|private|credential|uri$|dsn/i.test(String(e));export function labelFor(e){const r=String(e).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().toLowerCase();return r?r[0].toUpperCase()+r.slice(1):String(e)}export function settingsFields(e){const r=e?.settings||{},t={...e?.effectiveSettings||{},...r};return Array.isArray(e?.settingsSchema)&&e.settingsSchema.length?e.settingsSchema.filter(n=>n&&n.key).map(n=>{const s=n.type==="select"?"select":n.type==="number"?"number":n.type==="boolean"||n.type==="checkbox"?"checkbox":n.type==="textarea"?"textarea":"text",a=t[n.key]??n.default??(s==="checkbox"?!1:"");return{key:n.key,label:n.label||labelFor(n.key),type:s,value:s==="checkbox"?a===!0:String(a??""),options:(n.options||[]).map(o=>typeof o=="object"?{value:String(o.value),label:String(o.label??o.value)}:{value:String(o),label:String(o)}),min:n.min,max:n.max,help:n.help||"",secret:n.secret===!0||isSecretKey(n.key)}}):Object.entries(t).map(([n,s])=>{const a=isSecretKey(n);if(typeof s=="boolean")return{key:n,label:labelFor(n),type:"checkbox",value:s,secret:a};if(typeof s=="number")return{key:n,label:labelFor(n),type:"number",value:String(s),secret:a};if(s!==null&&typeof s=="object")return{key:n,label:labelFor(n),type:"json",value:JSON.stringify(s,null,2),secret:a};const o=String(s??"");return{key:n,label:labelFor(n),type:o.includes(`
|
|
2
|
+
`)||o.length>80?"textarea":"text",value:o,secret:a}})}export function readSettings(e,r){const t={},n={};for(const s of e){const a=r[s.key];if(s.type==="checkbox"){!!a!=!!s.value&&(n[s.key]=!!a);continue}const o=String(a??"");if(o!==String(s.value))if(s.type==="number"){const i=Number(o);if(o.trim()===""||!Number.isFinite(i)){t[s.key]="A number, please.";continue}if(s.min!=null&&i<s.min){t[s.key]=`At least ${s.min}.`;continue}if(s.max!=null&&i>s.max){t[s.key]=`At most ${s.max}.`;continue}n[s.key]=i}else if(s.type==="json")try{n[s.key]=JSON.parse(o)}catch{t[s.key]="Not valid JSON."}else n[s.key]=o}return{errors:t,changed:n}}export function slugifyPlugin(e){return String(e??"").toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/g,"").slice(0,40).replace(/-+$/,"")}export function checkScaffold(e,r=[]){const t=o=>String(e?.[o]??"").trim(),n={displayName:t("displayName"),slug:t("slug"),description:t("description"),author:t("author"),icon:t("icon")||"box"},s={},a=/[<>"\\]|\*\//;n.displayName?n.displayName.length>60&&(s.displayName="60 characters at most."):s.displayName="A plugin needs a name.",/^[a-z][a-z0-9-]{1,39}$/.test(n.slug)?r.includes(n.slug)&&(s.slug=`"${n.slug}" is already installed.`):s.slug="2-40 characters: lowercase letters, digits and hyphens, starting with a letter.",n.description.length>300&&(s.description="300 characters at most."),n.author.length>80&&(s.author="80 characters at most."),/^[a-z][a-z0-9-]{0,39}$/.test(n.icon)||(s.icon="A lowercase icon name (letters, digits, hyphens).");for(const o of["displayName","description","author"])!s[o]&&a.test(n[o])&&(s[o]='No <, >, ", backslash or */.');return{errors:s,payload:n}}export function planLines(e){const r=[];for(const t of e?.cascaded||[])r.push(`${t.displayName||t.name} is switched ${t.enabled?"on":"off"} too - ${t.enabled?`${t.becauseName||t.because} needs it`:`it needs ${t.becauseName||t.because}`}.`);for(const t of e?.losses||[])r.push(`${t.displayName||t.name} stays on without ${t.toolName||t.tool}${t.reason?`, but loses: ${t.reason.replace(/\.$/,"")}`:""}.`);return r}export function dependencyRows(e,{plugins:r=[],tools:t=[],catalogue:n=[]}={}){const s={on:["On","is-ok"],off:["Off","is-muted"],missing:["Not installed","is-warn"]},a=l=>{const u=t.find(d=>d.name===l);if(u)return{displayName:u.displayName||l,state:u.enabled===!1?"off":"on"};const p=r.find(d=>d.name===l);return p?{displayName:p.displayName||l,state:pluginStatus(p).running?"on":"off"}:{displayName:n.find(d=>d.slug===l)?.displayName||l,state:"missing"}},o=(l,u="")=>{const{displayName:p,state:f}=a(l),[d,y]=s[f];return{name:l,displayName:p,reason:u,state:f,stateText:d,stateCls:y}},i=Array.isArray(e?.requires)?e.requires.filter(l=>typeof l=="string"&&l):[],c=e?.uses,g=Array.isArray(c)?c.filter(l=>typeof l=="string").map(l=>[l,""]):Object.entries(c&&typeof c=="object"?c:{}).map(([l,u])=>[l,typeof u=="string"?u:""]);return{needs:i.map(l=>o(l)),worksWith:g.map(([l,u])=>o(l,u))}}export function dependencyText(e){return(e||[]).map(r=>`${r.displayName} (${r.stateText.toLowerCase()})`).join(", ")}
|
|
@@ -113,5 +113,7 @@
|
|
|
113
113
|
.plx-actions { display: flex; align-items: center; gap: .4rem; padding-top: .6rem; border-top: 1px solid var(--dm-border); flex-wrap: wrap; }
|
|
114
114
|
.plx-actions .btn { display: inline-flex; align-items: center; gap: .3rem; }
|
|
115
115
|
.plx-spacer { flex: 1; }
|
|
116
|
+
.plx-connect { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem .6rem; padding: .5rem .7rem; border: 1px dashed var(--dm-border); border-radius: var(--dm-radius-md); }
|
|
117
|
+
.plx-connect .plx-note { flex: 1; min-width: 14rem; }
|
|
116
118
|
@media (max-width: 640px) { .plx-main small { white-space: normal; } .plx-chips { display: none; } }
|
|
117
119
|
</style>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as
|
|
1
|
+
import{api as h,getUser as Y}from"../api.js";import{addBannerAction as ke}from"../lib/plugin-chrome.js";import{SHAPES as vt,whileLoading as wt}from"../lib/loading.js";import{helpPopovers as He}from"../lib/help-popover.js";import{onceClosed as xt,openMenuAt as Ve,sidebarCount as kt,viewLifetime as $t}from"../lib/tool-kit.js";import{pluginAccent as Ye}from"../lib/plugin-accent.js";import{reportRestart as Et}from"../lib/server-restart.js";import{FILTERS as St,arrangeCatalogue as Tt,arrangePlugins as Ct,catalogueAction as re,catalogueRow as Mt,checkScaffold as Nt,dependencyRows as It,formatPrice as ce,fmtReleased as Ot,needsAttention as At,planLines as Lt,pluginRow as Dt,pluginStatus as Je,readSettings as Ut,settingsFields as Qe,slugifyPlugin as Rt,storeBuyLines as Bt,updateFor as Ge}from"../lib/plugins-arrange.js";const Ze=/^#\/plugins\/?(\?.*)?$/,et=5e3,Ft=3e4,jt=20*6e4,Wt="#/plugins",$e="plugins.filter",de="plugins.draft",Pt=`
|
|
2
2
|
<div class="plx-row" data-name="{{name}}" tabindex="0" data-bind-class="rowCls" style="--plugin-accent: {{accent}}">
|
|
3
3
|
<span class="plx-icon" aria-hidden="true"><span data-icon="{{icon}}" data-icon-size="17"></span></span>
|
|
4
4
|
<span class="plx-main"><strong>{{displayName}}</strong><small data-bind-text="meta"></small></span>
|
|
@@ -10,7 +10,7 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
10
10
|
<span class="plx-chip" data-bind-class="statusCls" data-bind-text="statusText"></span>
|
|
11
11
|
</span>
|
|
12
12
|
<button type="button" class="plx-kebab" aria-label="Actions for {{displayName}}" title="Actions">\u22EE</button>
|
|
13
|
-
</div>`,
|
|
13
|
+
</div>`,qt=`
|
|
14
14
|
<div class="plx-row" data-tool="{{name}}" tabindex="0" data-bind-class="rowCls">
|
|
15
15
|
<span class="plx-icon" aria-hidden="true"><span data-icon="{{icon}}" data-icon-size="17"></span></span>
|
|
16
16
|
<span class="plx-main"><strong>{{displayName}}</strong><small data-bind-text="meta"></small></span>
|
|
@@ -19,7 +19,7 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
19
19
|
<span class="plx-chip" data-bind-class="statusCls" data-bind-text="statusText"></span>
|
|
20
20
|
</span>
|
|
21
21
|
<button type="button" class="plx-kebab" aria-label="Actions for {{displayName}}" title="Actions">\u22EE</button>
|
|
22
|
-
</div
|
|
22
|
+
</div>`,_t=`
|
|
23
23
|
<div class="plx-row" data-slug="{{slug}}" tabindex="0" data-bind-class="rowCls" style="--plugin-accent: {{accent}}">
|
|
24
24
|
<span class="plx-icon" aria-hidden="true"><span data-icon="{{icon}}" data-icon-size="17"></span></span>
|
|
25
25
|
<span class="plx-main"><strong>{{displayName}}</strong><small>{{meta}}</small></span>
|
|
@@ -29,12 +29,12 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
29
29
|
</span>
|
|
30
30
|
<button type="button" class="btn btn-sm plx-act" data-bind-class="actCls" data-bind-disabled="actDisabled" data-bind-text="actionText"></button>
|
|
31
31
|
<button type="button" class="plx-kebab" aria-label="Actions for {{displayName}}" title="Actions">\u22EE</button>
|
|
32
|
-
</div>`,
|
|
32
|
+
</div>`,Kt=`
|
|
33
33
|
<li class="plx-dep">
|
|
34
34
|
<strong data-bind-text="displayName"></strong>
|
|
35
35
|
<span class="plx-chip" data-bind-class="stateCls" data-bind-text="stateText"></span>
|
|
36
36
|
<small class="plx-hint" data-bind-hidden="!reason" data-bind-text="reason"></small>
|
|
37
|
-
</li>`,d=T=>String(T??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function me(T){const m=document.createElement("template");return m.innerHTML=T.trim(),m.content.firstElementChild}const g=it(We);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(T){g.reset();const m=T.get(0).querySelector(".plx")||T.get(0),k=()=>We.test(location.hash)&&m.isConnected,L=M.observable([]),R=M.observable([]),he=M.computed(()=>R.value.map(e=>{const t=[...(e.requiredBy||[]).map(a=>a.displayName),...(e.usedBy||[]).map(a=>a.displayName)];return{name:e.name,displayName:e.displayName,icon:e.icon,meta:[e.description,t.length?`used by ${t.join(", ")}`:"",e.locked?"locked by your manager":"",e.staff?"your host's staff can still use it":""].filter(Boolean).join(" \xB7 "),locked:e.locked===!0,statusText:e.enabled?"On":"Off",statusCls:e.enabled?"is-ok":"is-muted",rowCls:e.enabled?"":"is-off"}})),h=M.observable({available:null,site:null,items:[]}),fe=M.observable(!0),ne=M.observable(""),b=M.observable("");let ve="all";try{ve=rt.includes(S.get(be))?S.get(be):"all"}catch{}const N=M.observable(ve),V=M.observable(""),j=M.observable("all"),ge=M.observable("");g.add(M.effect(()=>{const e=N.value;try{S.set(be,e)}catch{}}));const Y=M.computed(()=>new Map((h.value.items||[]).map(e=>[e.slug,e.version]))),W=e=>(h.peek().items||[]).find(t=>t.slug===e),se=M.observable([]);g.add(M.effect(()=>{const e=Y.value;se.value=ct(L.value,{filter:N.value,query:V.value,latest:e}).map(t=>({...vt(t,e),accent:je(t.name)}))}));const Pe=M.computed(()=>{const e=L.value,t=Y.value,a=e.filter(n=>De(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>ht(n,t)).length}}),J=M.computed(()=>(h.value.items||[]).filter(e=>te(e)==="update").length),ze=M.computed(()=>L.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),le=M.observable([]);g.add(M.effect(()=>{le.value=dt(h.value.items,{filter:j.value,query:ge.value}).map(e=>{const t=ut(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:je(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const _e=M.computed(()=>{const e=h.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>te(t)==="install").length,updates:J.value}}),Q=e=>L.peek().find(t=>t.name===e);async function ie(){try{const[e,t]=await nt(m.querySelector(".dm-loading-slot"),Promise.all([v.plugins.list(),v.tools.list().catch(()=>[])]),at.iconRows);if(!k())return;L.value=Array.isArray(e)?e:[],R.value=Array.isArray(t)?t:[],ne.value=""}catch(e){ne.value=`Could not load the plugins: ${e.message||e}`}finally{fe.value=!1}}async function ye(){try{const e=await v.marketplace.catalogue();if(!k())return;h.value={available:!!e?.available,site:e?.site||null,items:e?.catalogue||[]}}catch{h.value={available:!1,site:null,items:[],failed:!0}}}const P=async()=>{await Promise.all([ie(),ye()]),lt(wt)};async function B(e,t,a="plugin"){if(e.core)return;const n=t?"on":"off";if(e.locked){E.toast(`${e.displayName||e.name} is locked by your site's manager - ask them to switch it ${n}.`,{type:"info",duration:6e3});return}if(!await E.confirm(`Switch ${d(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||b.peek())return;const l=i=>a==="tool"?v.tools.update(e.name,{enabled:t,cascade:i}):v.plugins.update(e.name,{enabled:t,cascade:i});b.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let i;try{i=await l(!1)}catch(c){if(c.status!==409||!c.body?.needsConfirm)throw c;const u=ft(c.body.plan);if(b.value="",!await E.confirm(`<p>Switching ${d(e.displayName||e.name)} ${n} also means:</p><ul>${u.map(o=>`<li>${d(o)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;b.value=`Switching ${e.displayName||e.name} ${n}\u2026`,i=await l(!0)}await ot(i,{onStatus:c=>{b.value=c}}),E.toast(`${e.displayName||e.name} is ${n}.${t?" Reload the admin to open its screens.":""}`,{type:"success",duration:6e3});try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(i){E.toast(`Not switched ${n}: ${i.message||i}`,{type:"error"})}finally{b.value="",k()&&await P()}}async function D(e,{update:t=!1}={}){const a=d(e.displayName||e.slug),n=t?`<p>Update ${a} from ${d(e.installedVersion)} to ${d(e.version)}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`:`<p>Install ${a} v${d(e.version)}?</p> <p class="text-muted">It arrives licensed to this site and takes effect after a restart.</p>`;if(await E.confirm(n,{title:t?"Update plugin":"Install plugin",confirmText:t?"Update":"Install",cancelText:"Cancel",html:!0})){try{const l=await v.marketplace.install(e.slug,e.version,{update:t}),i=l?.action==="upgrade"?`${e.slug} updated${l.from?` from ${l.from}`:""} to ${l.version}.`:`${e.slug} ${l?.version??e.version} installed.`;E.toast(`${i} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(l){E.toast(l.message||"Install failed.",{type:"error"})}k()&&await P()}}function we(e){e?.buyUrl&&(window.open(e.buyUrl,"_blank","noopener"),E.toast(`Manage my site opened in a new tab. We email you a sign-in link; ${e.displayName||e.slug} is ticked ready once you are in. Install it here when it is paid for.`,{type:"info",duration:9e3}))}async function xe(e,t){const n=W(e)?.tier==="paid"?` <p class="text-muted">It is a paid Tool: your site's manager is told, and if you pay for it on its own it comes off your monthly bill (the rest of this month is credited).</p>`:"";if(await E.confirm(`<p>Uninstall ${d(t||e)}?</p> <p class="text-muted">Its files are removed, and its <code>data/</code> folder with them. Roles it added are removed and their users moved to <code>user</code>. Restart the server to finish.</p>${n}`,{title:"Uninstall plugin",confirmText:"Uninstall",cancelText:"Cancel",html:!0})){try{const i=(await v.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${i} Restart the server to apply.`,{type:"success",duration:6e3})}catch(l){E.toast(`Uninstall failed: ${l.message||l}`,{type:"error"})}k()&&await P()}}async function ke(e){try{await v.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const $e=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},z=m.querySelector(".plx-file");async function He(e){if(b.peek())return;b.value=`Installing ${e.name}\u2026`;const t={};try{for(let a=0;a<4;a++)try{const n=await v.plugins.installFile(e,t),l=n.action==="upgrade"?`${n.name} updated${n.from?` from ${n.from}`:""} to ${n.version}.`:`${n.name} ${n.version} installed.`;E.toast(`${l} Restart the server to activate it.`,{type:"success",duration:6e3});return}catch(n){if(b.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${d(n.name)} ${d(n.installedVersion||"the installed version")} is already installed. Update it to ${d(n.incomingVersion||"this file")}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`,{title:"Update plugin",confirmText:"Update",cancelText:"Cancel",html:!0}))return;t.confirmUpgrade=!0}else if(/refusing to downgrade/i.test(n.message)&&!t.confirmDowngrade){if(!await E.confirm(`<p>${d(n.message)} Install it anyway?</p> <p class="text-muted">An older version may not understand data written by the newer one.</p>`,{title:"Downgrade plugin",confirmText:"Downgrade",cancelText:"Cancel",html:!0}))return;t.confirmDowngrade=!0}else if(/unsigned|signature/i.test(n.message)&&!t.confirmUnsigned){if(!await E.confirm(`<p>${d(n.message)}</p> <p class="text-muted">An unsigned plugin has not been verified as coming from the marketplace. Its code runs on this server with full access. Install it anyway?</p>`,{title:"Unsigned plugin",confirmText:"Install anyway",cancelText:"Cancel",html:!0}))return;t.confirmUnsigned=!0}else{E.toast(n.message||"Install failed.",{type:"error"});return}b.value=`Installing ${e.name}\u2026`}}finally{b.value="",k()&&await P()}}const Ee=async()=>{const e=z.files?.[0];z.value="",e&&await He(e)};z.addEventListener("change",Ee),g.add(()=>z.removeEventListener("change",Ee));const G=new Set;let U=null,Se=!1;function Me({title:e,size:t="md",panel:a,model:n,methods:l,dirty:i=()=>!1,form:c=null,cleanup:u=()=>{}}){const o=E.slideover({title:d(e),size:t,position:"right"});o.element.appendChild(a);const $=Ue(a),w=M.applyBindings(n,a,{methods:l});c&&(U=c),G.add(o),st(o,()=>{u(),w.dispose(),$(),G.delete(o),U===c&&(U=null)});const x=o.close.bind(o);let f=!1,O=!1;return o.close=async F=>{if(!f&&F!==!0&&i()){if(O)return;O=!0;const q=await E.confirm("Discard the changes you have not saved?");if(O=!1,!q)return}return f=!0,x()},I.scan(a),o.open(),o}function oe(e,t=null){const a=Q(e);if(!a)return;const n=De(a),l=Fe(a),i=W(a.name),c=qe(a,Y.peek()),u=!!(c&&i?.entitled&&!i?.needsCms),$={...Object.fromEntries(l.map(s=>[s.key,s.value])),...Object.fromEntries(Object.entries(t||{}).filter(([s])=>!l.find(p=>p.key===s)?.secret))},w=Object.fromEntries(l.map(s=>[s.key,M.observable($[s.key])])),x=M.computed(()=>gt(l,Object.fromEntries(l.map(s=>[s.key,w[s.key].value])))),f=M.observable(!1),O=()=>Object.keys(x.peek().changed).length>0||Object.keys(x.peek().errors).length>0,F=[["Version",`v${a.version}${c?` (v${c} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",mt(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,s])=>s),q=(s,p)=>{const A=`plx-set-${p}`,Z=s.help?` <span data-help="${d(s.help)}"></span>`:"",H=`<label class="form-label" for="${A}">${d(s.label)}${Z}</label>`,K=`data-model="v${p}.value"`,ee=`<small class="plx-err" data-bind-hidden="!err${p}.value" data-bind-text="err${p}.value"></small>`;if(s.type==="checkbox")return`<div class="plx-setting">${H}<input id="${A}" type="checkbox" class="form-switch" ${K}></div>`;if(s.type==="select")return`<div>${H}<select id="${A}" class="form-input" ${K}>${s.options.map(Le=>`<option value="${d(Le.value)}">${d(Le.label)}</option>`).join("")}</select>${ee}</div>`;if(s.type==="json")return`<div>${H}<textarea id="${A}" class="form-input plx-json" rows="5" spellcheck="false" ${K}></textarea>${ee}</div>`;if(s.type==="textarea")return`<div>${H}<textarea id="${A}" class="form-input" rows="3" ${K}></textarea>${ee}</div>`;const Ze=s.type==="number"?"number":s.secret?"password":"text",et=`${s.min!=null?` min="${d(s.min)}"`:""}${s.max!=null?` max="${d(s.max)}"`:""}`;return`<div>${H}<input id="${A}" type="${Ze}" class="form-input" autocomplete="${s.secret?"new-password":"off"}"${et} ${K}>${ee}</div>`},r=bt(a,{plugins:L.peek(),tools:R.peek(),catalogue:h.peek().items||[]}),C={saving:f,needs:M.observable(r.needs),worksWith:M.observable(r.worksWith),hasNeeds:r.needs.length>0,hasWorksWith:r.worksWith.length>0,hasFields:l.length>0,cannot:M.computed(()=>f.value||!Object.keys(x.value.changed).length||Object.keys(x.value.errors).length>0),...Object.fromEntries(l.flatMap((s,p)=>[[`v${p}`,w[s.key]],[`err${p}`,M.computed(()=>x.value.errors[s.key]||"")]]))},_=me(`
|
|
37
|
+
</li>`,i=O=>String(O??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Ee(O){const g=document.createElement("template");return g.innerHTML=O.trim(),g.content.firstElementChild}const y=$t(Ze);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(O){y.reset();const g=O.get(0).querySelector(".plx")||O.get(0),p=()=>Ze.test(location.hash)&&g.isConnected,R=M.observable([]),j=M.observable([]),Se=M.computed(()=>j.value.map(e=>{const t=[...(e.requiredBy||[]).map(a=>a.displayName),...(e.usedBy||[]).map(a=>a.displayName)];return{name:e.name,displayName:e.displayName,icon:e.icon,meta:[e.description,t.length?`used by ${t.join(", ")}`:"",e.locked?"locked by your manager":"",e.staff?"your host's staff can still use it":""].filter(Boolean).join(" \xB7 "),locked:e.locked===!0,statusText:e.enabled?"On":"Off",statusCls:e.enabled?"is-ok":"is-muted",rowCls:e.enabled?"":"is-off"}})),u=M.observable({available:null,site:null,items:[]}),Te=M.observable(!0),ue=M.observable(""),f=M.observable("");let Ce="all";try{Ce=St.includes(S.get($e))?S.get($e):"all"}catch{}const A=M.observable(Ce),J=M.observable(""),W=M.observable("all"),Me=M.observable("");y.add(M.effect(()=>{const e=A.value;try{S.set($e,e)}catch{}}));const Q=M.computed(()=>new Map((u.value.items||[]).map(e=>[e.slug,e.version]))),L=e=>(u.peek().items||[]).find(t=>t.slug===e),pe=M.observable([]);y.add(M.effect(()=>{const e=Q.value;pe.value=Ct(R.value,{filter:A.value,query:J.value,latest:e}).map(t=>({...Dt(t,e),accent:Ye(t.name)}))}));const tt=M.computed(()=>{const e=R.value,t=Q.value,a=e.filter(n=>Je(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>At(n,t)).length}}),G=M.computed(()=>(u.value.items||[]).filter(e=>re(e)==="update").length),at=M.computed(()=>R.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),me=M.observable([]);y.add(M.effect(()=>{me.value=Tt(u.value.items,{filter:W.value,query:Me.value}).map(e=>{const t=Mt(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:Ye(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const nt=M.computed(()=>{const e=u.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>re(t)==="install").length,updates:G.value}}),Z=e=>R.peek().find(t=>t.name===e);async function he(){try{const[e,t]=await wt(g.querySelector(".dm-loading-slot"),Promise.all([h.plugins.list(),h.tools.list().catch(()=>[])]),vt.iconRows);if(!p())return;R.value=Array.isArray(e)?e:[],j.value=Array.isArray(t)?t:[],ue.value=""}catch(e){ue.value=`Could not load the plugins: ${e.message||e}`}finally{Te.value=!1}}async function Ne(){try{const e=await h.marketplace.catalogue();if(!p())return;u.value={available:!!e?.available,site:e?.site||null,items:e?.catalogue||[],mode:e?.mode||(e?.available?"managed":"none"),siteError:e?.siteError||"",storeFailed:e?.failed||"",connection:e?.connection||null},e?.connection?.status==="pending"&&be();for(const t of e?.pending||[])Ie(t.id,{fast:!1})}catch{u.value={available:!1,site:null,items:[],failed:!0}}}const v=async()=>{await Promise.all([he(),Ne()]),kt(Wt)};async function P(e,t,a="plugin"){if(e.core)return;const n=t?"on":"off";if(e.locked){E.toast(`${e.displayName||e.name} is locked by your site's manager - ask them to switch it ${n}.`,{type:"info",duration:6e3});return}if(!await E.confirm(`Switch ${i(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||f.peek())return;const s=o=>a==="tool"?h.tools.update(e.name,{enabled:t,cascade:o}):h.plugins.update(e.name,{enabled:t,cascade:o});f.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let o;try{o=await s(!1)}catch(d){if(d.status!==409||!d.body?.needsConfirm)throw d;const m=Lt(d.body.plan);if(f.value="",!await E.confirm(`<p>Switching ${i(e.displayName||e.name)} ${n} also means:</p><ul>${m.map(r=>`<li>${i(r)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;f.value=`Switching ${e.displayName||e.name} ${n}\u2026`,o=await s(!0)}await Et(o,{onStatus:d=>{f.value=d}}),E.toast(`${e.displayName||e.name} is ${n}.${t?" Reload the admin to open its screens.":""}`,{type:"success",duration:6e3});try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(o){E.toast(`Not switched ${n}: ${o.message||o}`,{type:"error"})}finally{f.value="",p()&&await v()}}async function F(e,{update:t=!1}={}){const a=i(e.displayName||e.slug),n=t?`<p>Update ${a} from ${i(e.installedVersion)} to ${i(e.version)}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`:`<p>Install ${a} v${i(e.version)}?</p> <p class="text-muted">It arrives licensed to this site and takes effect after a restart.</p>`;if(await E.confirm(n,{title:t?"Update plugin":"Install plugin",confirmText:t?"Update":"Install",cancelText:"Cancel",html:!0})){try{const s=await h.marketplace.install(e.slug,e.version,{update:t}),o=s?.action==="upgrade"?`${e.slug} updated${s.from?` from ${s.from}`:""} to ${s.version}.`:`${e.slug} ${s?.version??e.version} installed.`;E.toast(`${o} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(s){E.toast(s.message||"Install failed.",{type:"error"})}p()&&await v()}}const x=new Map;y.add(()=>{for(const e of x.values())clearTimeout(e.timer);x.clear()});function Ie(e,{fast:t=!0}={}){if(!e||x.has(e))return;const a={timer:null,until:Date.now()+(t?jt:0)};x.set(e,a);const n=()=>{clearTimeout(a.timer),!(!p()||!x.has(e))&&(a.timer=setTimeout(()=>te(e),Date.now()<a.until?et:Ft))};a.next=n,n()}const Oe=e=>{const t=x.get(e);t&&clearTimeout(t.timer),x.delete(e)},ee=new Set;async function te(e,{byHand:t=!1}={}){if(!p()||ee.has(e))return;ee.add(e),clearTimeout(x.get(e)?.timer);let a;try{a=await h.marketplace.claim(e)}catch(s){t&&E.toast(s.message||"The store could not be asked just now.",{type:"error"}),ee.delete(e),x.get(e)?.next?.();return}ee.delete(e);const n=L(a.slug)?.displayName||a.slug;if(a.status==="pending"){t&&E.toast(`Not paid yet - ${n} installs here as soon as the payment is through.`,{type:"info",duration:6e3}),x.get(e)?.next?.();return}if(Oe(e),a.status==="paid")if(a.kind==="renew")E.toast(`${n}: updates renewed.${a.installed&&!a.refreshed?" Update it on the Browse tab.":""}`,{type:"success",duration:8e3});else if(a.installed&&a.refreshed===!1&&a.installError)E.toast(`${n} is paid for, but the copy here could not be brought up to date: ${a.installError}. Use Update on the Browse tab.`,{type:"warning",duration:12e3});else if(a.installed){const s=(a.included||[]).filter(o=>o.installed).map(o=>L(o.slug)?.displayName||o.slug);E.toast(`${n} is paid for and installed${s.length?`, with ${s.join(" and ")} free`:""}. Restart the server to activate ${s.length?"them":"it"}.`+(s.some(o=>/mongo/i.test(o))?" Then open MongoDB in the sidebar to connect your database.":""),{type:"success",duration:12e3})}else E.toast(`${n} is paid for, but did not install: ${a.installError||"try Install on the Browse tab"}. The licence key is in your email.`,{type:"warning",duration:12e3});else a.status!=="unknown"&&E.toast(`${n}: the purchase ${a.status==="expired"?"was not paid for in time":`is ${a.status}`}.`,{type:"warning",duration:8e3});p()&&await v()}async function st(e){if(e?.pending&&await E.confirm(`<p>Stop waiting for the payment for ${i(e.displayName||e.slug)}?</p> <p class="text-muted">Nothing is cancelled at the store - if you did pay, the licence key is in your email and Install from file takes the file it links to.</p>`,{title:"Stop waiting",confirmText:"Stop waiting",cancelText:"Keep waiting",html:!0})){Oe(e.pending);try{await h.marketplace.dropPurchase(e.pending)}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}p()&&await v()}}async function lt(e){const t=await E.prompt(`Licence key for ${i(e.displayName||e.slug)} - it is in the email you had when you bought it.`,{title:"Enter licence key",inputPlaceholder:"DOMMA-XXXX-XXXX-XXXX",confirmText:"Use this key"});if(!(!t||!p()))try{const a=await h.marketplace.enterKey(e.slug,String(t).trim());await v();const n=L(e.slug);a.updates&&n&&!n.installed?(E.toast(`Licence accepted for ${e.displayName||e.slug}.`,{type:"success"}),await F(n)):E.toast(`Licence accepted for ${e.displayName||e.slug}.${n?.installed?" Restart the server for it to take effect.":""}`,{type:"success",duration:7e3})}catch(a){E.toast(a.message||"That key could not be used.",{type:"error",duration:8e3})}}async function ot(e){if(f.peek())return;const t=Bt(e,{site:u.peek().site,email:Y()?.email}),a=t.lines.map((s,o)=>`<p${o?' class="text-muted"':""}>${i(s)}</p>`).join(" ");if(!await E.confirm(a,{title:t.title,confirmText:e.owned?"Renew":"Buy",cancelText:"Cancel",html:!0}))return;const n=window.open("","_blank");try{const s=await h.marketplace.buy(e.slug);n&&!n.closed?(n.opener=null,n.location.href=s.checkoutUrl):window.open(s.checkoutUrl,"_blank","noopener")||E.toast("Your browser blocked the payment tab - allow pop-ups for this site and choose Buy again.",{type:"warning",duration:9e3}),Ie(s.id),E.toast(`Payment opened in a new tab. ${e.displayName||e.slug} ${e.owned?"renews":"installs here"} as soon as it is through - keep this page open, or come back to it.`,{type:"info",duration:9e3})}catch(s){try{n?.close()}catch{}E.toast(s.message||"The purchase could not be started.",{type:"error",duration:8e3})}p()&&await v()}let ae=null,q=0;y.add(()=>clearTimeout(ae));function be(){q||(q=Date.now()+60*6e4),clearTimeout(ae),!(!p()||Date.now()>q)&&(ae=setTimeout(()=>fe(!1),et))}let ne=!1;async function fe(e){if(ne||!p())return;ne=!0;let t;try{t=await h.marketplace.connectCheck()}catch(n){e&&E.toast(n.message||"Could not ask just now.",{type:"error"}),ne=!1,be();return}ne=!1;const a=t?.connection||null;if(a?.status==="pending"){e&&E.toast(`Not yet - open the link we emailed to ${a.email} and choose Connect.`,{type:"info",duration:6e3}),be();return}q=0,a?.status==="connected"?E.toast(`Connected to Domma as ${a.email}.`,{type:"success",duration:7e3}):E.toast("The link was not opened in time - choose Connect to Domma again.",{type:"warning",duration:7e3}),p()&&await v()}async function it(){const e=await E.prompt("The email address you bought your Tools with. We email it a link; open it and choose Connect.",{title:"Connect to Domma",inputPlaceholder:Y()?.email||"you@example.com",defaultValue:Y()?.email||"",confirmText:"Email me the link"});if(!(e==null||!p()))try{const t=await h.marketplace.connect(String(e).trim()||Y()?.email||"");E.toast(`Link emailed to ${t.connection?.email}. Open it and choose Connect - this page picks it up.`,{type:"info",duration:9e3}),q=0,await v()}catch(t){E.toast(t.message||"Could not connect.",{type:"error",duration:8e3})}}async function rt(){const e=u.peek().connection;if(e&&!(e.status!=="pending"&&!await E.confirm(`<p>Disconnect this site from Domma (${i(e.email)})?</p> <p class="text-muted">The licences it already has stay. New ones stop arriving by themselves - connect again, or enter a key.</p>`,{title:"Disconnect",confirmText:"Disconnect",cancelText:"Keep it",html:!0}))){clearTimeout(ae),q=0;try{await h.marketplace.disconnect()}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}p()&&await v()}}const Ae=()=>{for(const e of[...x.keys()])te(e);u.peek().connection?.status==="pending"&&fe(!1)};window.addEventListener("focus",Ae),y.add(()=>window.removeEventListener("focus",Ae));function Le(e){if(e?.store){ot(e);return}e?.buyUrl&&(window.open(e.buyUrl,"_blank","noopener"),E.toast(`Manage my site opened in a new tab. We email you a sign-in link; ${e.displayName||e.slug} is ticked ready once you are in. Install it here when it is paid for.`,{type:"info",duration:9e3}))}async function De(e,t){const n=L(e)?.tier==="paid"&&!L(e)?.store?` <p class="text-muted">It is a paid Tool: your site's manager is told, and if you pay for it on its own it comes off your monthly bill (the rest of this month is credited).</p>`:"";if(await E.confirm(`<p>Uninstall ${i(t||e)}?</p> <p class="text-muted">Its files are removed, and its <code>data/</code> folder with them. Roles it added are removed and their users moved to <code>user</code>. Restart the server to finish.</p>${n}`,{title:"Uninstall plugin",confirmText:"Uninstall",cancelText:"Cancel",html:!0})){try{const o=(await h.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${o} Restart the server to apply.`,{type:"success",duration:6e3})}catch(s){E.toast(`Uninstall failed: ${s.message||s}`,{type:"error"})}p()&&await v()}}async function Ue(e){try{await h.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const Re=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},X=g.querySelector(".plx-file");async function ct(e){if(f.peek())return;f.value=`Installing ${e.name}\u2026`;const t={};try{for(let a=0;a<4;a++)try{const n=await h.plugins.installFile(e,t),s=n.action==="upgrade"?`${n.name} updated${n.from?` from ${n.from}`:""} to ${n.version}.`:`${n.name} ${n.version} installed.`;E.toast(`${s} Restart the server to activate it.`,{type:"success",duration:6e3});return}catch(n){if(f.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${i(n.name)} ${i(n.installedVersion||"the installed version")} is already installed. Update it to ${i(n.incomingVersion||"this file")}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`,{title:"Update plugin",confirmText:"Update",cancelText:"Cancel",html:!0}))return;t.confirmUpgrade=!0}else if(/refusing to downgrade/i.test(n.message)&&!t.confirmDowngrade){if(!await E.confirm(`<p>${i(n.message)} Install it anyway?</p> <p class="text-muted">An older version may not understand data written by the newer one.</p>`,{title:"Downgrade plugin",confirmText:"Downgrade",cancelText:"Cancel",html:!0}))return;t.confirmDowngrade=!0}else if(/unsigned|signature/i.test(n.message)&&!t.confirmUnsigned){if(!await E.confirm(`<p>${i(n.message)}</p> <p class="text-muted">An unsigned plugin has not been verified as coming from the marketplace. Its code runs on this server with full access. Install it anyway?</p>`,{title:"Unsigned plugin",confirmText:"Install anyway",cancelText:"Cancel",html:!0}))return;t.confirmUnsigned=!0}else{E.toast(n.message||"Install failed.",{type:"error"});return}f.value=`Installing ${e.name}\u2026`}}finally{f.value="",p()&&await v()}}const Be=async()=>{const e=X.files?.[0];X.value="",e&&await ct(e)};X.addEventListener("change",Be),y.add(()=>X.removeEventListener("change",Be));const se=new Set;let B=null,Fe=!1;function je({title:e,size:t="md",panel:a,model:n,methods:s,dirty:o=()=>!1,form:d=null,cleanup:m=()=>{}}){const r=E.slideover({title:i(e),size:t,position:"right"});r.element.appendChild(a);const C=He(a),$=M.applyBindings(n,a,{methods:s});d&&(B=d),se.add(r),xt(r,()=>{m(),$.dispose(),C(),se.delete(r),B===d&&(B=null)});const T=r.close.bind(r);let w=!1,D=!1;return r.close=async _=>{if(!w&&_!==!0&&o()){if(D)return;D=!0;const K=await E.confirm("Discard the changes you have not saved?");if(D=!1,!K)return}return w=!0,T()},I.scan(a),r.open(),r}function ge(e,t=null){const a=Z(e);if(!a)return;const n=Je(a),s=Qe(a),o=L(a.name),d=Ge(a,Q.peek()),m=!!(d&&o?.entitled&&!o?.needsCms),C={...Object.fromEntries(s.map(l=>[l.key,l.value])),...Object.fromEntries(Object.entries(t||{}).filter(([l])=>!s.find(b=>b.key===l)?.secret))},$=Object.fromEntries(s.map(l=>[l.key,M.observable(C[l.key])])),T=M.computed(()=>Ut(s,Object.fromEntries(s.map(l=>[l.key,$[l.key].value])))),w=M.observable(!1),D=()=>Object.keys(T.peek().changed).length>0||Object.keys(T.peek().errors).length>0,_=[["Version",`v${a.version}${d?` (v${d} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",Ot(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,l])=>l),K=(l,b)=>{const U=`plx-set-${b}`,oe=l.help?` <span data-help="${i(l.help)}"></span>`:"",H=`<label class="form-label" for="${U}">${i(l.label)}${oe}</label>`,V=`data-model="v${b}.value"`,ie=`<small class="plx-err" data-bind-hidden="!err${b}.value" data-bind-text="err${b}.value"></small>`;if(l.type==="checkbox")return`<div class="plx-setting">${H}<input id="${U}" type="checkbox" class="form-switch" ${V}></div>`;if(l.type==="select")return`<div>${H}<select id="${U}" class="form-input" ${V}>${l.options.map(ze=>`<option value="${i(ze.value)}">${i(ze.label)}</option>`).join("")}</select>${ie}</div>`;if(l.type==="json")return`<div>${H}<textarea id="${U}" class="form-input plx-json" rows="5" spellcheck="false" ${V}></textarea>${ie}</div>`;if(l.type==="textarea")return`<div>${H}<textarea id="${U}" class="form-input" rows="3" ${V}></textarea>${ie}</div>`;const gt=l.type==="number"?"number":l.secret?"password":"text",yt=`${l.min!=null?` min="${i(l.min)}"`:""}${l.max!=null?` max="${i(l.max)}"`:""}`;return`<div>${H}<input id="${U}" type="${gt}" class="form-input" autocomplete="${l.secret?"new-password":"off"}"${yt} ${V}>${ie}</div>`},c=It(a,{plugins:R.peek(),tools:j.peek(),catalogue:u.peek().items||[]}),N={saving:w,needs:M.observable(c.needs),worksWith:M.observable(c.worksWith),hasNeeds:c.needs.length>0,hasWorksWith:c.worksWith.length>0,hasFields:s.length>0,cannot:M.computed(()=>w.value||!Object.keys(T.value.changed).length||Object.keys(T.value.errors).length>0),...Object.fromEntries(s.flatMap((l,b)=>[[`v${b}`,$[l.key]],[`err${b}`,M.computed(()=>T.value.errors[l.key]||"")]]))},z=Ee(`
|
|
38
38
|
<div class="plx-form">
|
|
39
39
|
<p class="plx-desc"></p>
|
|
40
40
|
<dl class="plx-facts"></dl>
|
|
@@ -51,13 +51,13 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
51
51
|
<div data-if="hasFields">
|
|
52
52
|
<p class="plx-sub">Settings
|
|
53
53
|
<span data-help-title="Settings" data-help="Saved to config/plugins.json for this site. Only what you change is stored - anything you leave keeps the plugin's own default, so a later version can improve it. Most plugins read their settings as they run; a few only at start-up."></span></p>
|
|
54
|
-
<div class="plx-form">${
|
|
54
|
+
<div class="plx-form">${s.map(K).join("")}</div>
|
|
55
55
|
</div>
|
|
56
56
|
<p class="plx-hint" data-if="!hasFields">This plugin has no settings to change here.</p>
|
|
57
57
|
<div class="plx-actions">
|
|
58
58
|
${a.core?"":`<button type="button" class="btn btn-sm btn-ghost" data-on-click="toggle"><span data-icon="${a.enabled?"pause":"play"}" data-icon-size="13"></span> ${a.enabled?"Switch off":"Switch on"}</button>`}
|
|
59
|
-
${
|
|
60
|
-
${
|
|
59
|
+
${m?`<button type="button" class="btn btn-sm btn-ghost" data-on-click="update"><span data-icon="download" data-icon-size="13"></span> Update to v${i(d)}</button>`:""}
|
|
60
|
+
${d&&o?.needsCms?`<span class="plx-hint">v${i(d)}: ${i(o.needsCms)}</span>`:""}
|
|
61
61
|
${a.sourceEditable!==!1?'<button type="button" class="btn btn-sm btn-ghost" data-on-click="source"><span data-icon="code" data-icon-size="13"></span> Source</button>':""}
|
|
62
62
|
${a.closedSource?"":'<button type="button" class="btn btn-sm btn-ghost" data-on-click="exportIt" title="Download as a .dcmsplugin file"><span data-icon="download" data-icon-size="13"></span> Export</button>'}
|
|
63
63
|
<span class="plx-spacer"></span>
|
|
@@ -65,7 +65,7 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
65
65
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-if="hasFields" data-bind-disabled="cannot.value">
|
|
66
66
|
<span data-icon="check" data-icon-size="13"></span> Save settings</button>
|
|
67
67
|
</div>
|
|
68
|
-
</div>`);
|
|
68
|
+
</div>`);z.querySelector(".plx-desc").textContent=a.description||"",z.querySelectorAll(".plx-deps").forEach(l=>{l.innerHTML=Kt});const ft=z.querySelector(".plx-facts");for(const[l,b]of _){const U=document.createElement("dt");U.textContent=l;const oe=document.createElement("dd");oe.textContent=b,ft.append(U,oe)}async function Xe(){if(N.cannot.peek())return;const{changed:l}=T.peek();w.value=!0;try{await h.plugins.update(a.name,{settings:{...a.settings||{},...l}}),E.toast(`${a.displayName||a.name}: settings saved.`,{type:"success"}),le.close(!0),p()&&await he()}catch(b){E.toast(`Not saved: ${b.message||b}`,{type:"error"})}finally{w.value=!1}}const xe=l=>async()=>{await le.close(),se.has(le)||l()},le=je({title:a.displayName||a.name,size:"md",panel:z,model:N,dirty:D,form:s.length?{kind:"settings",name:a.name,dirty:D,values:()=>{const l={};for(const b of s)b.secret||(l[b.key]=$[b.key].peek());return l}}:null,methods:{save:Xe,cancel:()=>le.close(),toggle:xe(()=>P(a,!a.enabled)),update:xe(()=>F(o,{update:!0})),source:xe(()=>Re(a)),exportIt:()=>Ue(a)}});z.addEventListener("keydown",l=>{(l.ctrlKey||l.metaKey)&&l.key==="Enter"&&(l.preventDefault(),Xe())})}function We(e=null){const t=Y(),a={displayName:M.observable(e?.displayName??""),slug:M.observable(e?.slug??""),description:M.observable(e?.description??""),author:M.observable(e?.author??(t?.name||t?.username||"")),icon:M.observable(e?.icon??"box")},n=JSON.stringify(Object.fromEntries(Object.entries(a).map(([c,N])=>[c,N.peek()]))),s=()=>Object.fromEntries(Object.entries(a).map(([c,N])=>[c,N.peek()])),o=()=>JSON.stringify(s())!==n||!!e;let d=!!e?.slug;const m=M.effect(()=>{const c=a.displayName.value;d||(a.slug.value=Rt(c))}),r=M.observable(!1),C=M.computed(()=>Nt(Object.fromEntries(Object.entries(a).map(([c,N])=>[c,N.value])),R.value.map(c=>c.name))),$=c=>M.computed(()=>C.value.errors[c]||""),T={...a,saving:r,nameErr:$("displayName"),slugErr:$("slug"),descErr:$("description"),authorErr:$("author"),iconErr:$("icon"),cannot:M.computed(()=>r.value||Object.keys(C.value.errors).length>0)},w=Ee(`
|
|
69
69
|
<div class="plx-form">
|
|
70
70
|
<div>
|
|
71
71
|
<label class="form-label" for="plx-np-name">Display name <span class="text-danger">*</span></label>
|
|
@@ -101,10 +101,16 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
101
101
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="create" data-bind-disabled="cannot.value">
|
|
102
102
|
<span data-icon="plus" data-icon-size="13"></span> Create plugin</button>
|
|
103
103
|
</div>
|
|
104
|
-
</div>`);async function
|
|
104
|
+
</div>`);async function D(){if(T.cannot.peek())return;r.value=!0;const{payload:c}=C.peek();try{await h.plugins.scaffold(c),E.toast(`"${c.displayName}" created. Restart the server to activate it.`,{type:"success",duration:6e3}),_.close(!0),p()&&await v()}catch(N){E.toast(N.message||"Could not create the plugin.",{type:"error"})}finally{r.value=!1}}const _=je({title:"New plugin",size:"sm",panel:w,model:T,dirty:o,form:{kind:"new",name:null,dirty:o,values:s},cleanup:()=>m(),methods:{create:D,cancel:()=>_.close()}}),K=w.querySelector("#plx-np-slug");K.addEventListener("input",()=>{d=!!K.value}),w.addEventListener("keydown",c=>{(c.ctrlKey||c.metaKey)&&c.key==="Enter"&&(c.preventDefault(),D())}),w.querySelector("#plx-np-name")?.focus()}function dt(e){const t=Z(e);if(!t)return[];const a=L(t.name),n=Ge(t,Q.peek()),s=!!f.peek();return[{header:t.displayName||t.name},{label:Qe(t).length?"Details and settings\u2026":"Details\u2026",icon:"settings",action:()=>ge(t.name)},...t.core?[]:[t.enabled?{label:"Switch off\u2026",icon:"pause",disabled:s,action:()=>P(t,!1)}:{label:"Switch on\u2026",icon:"play",disabled:s,action:()=>P(t,!0)}],...n?[{label:a?.needsCms?`Update to v${n} - needs a newer Domma CMS`:`Update to v${n}\u2026`,icon:"download",disabled:s||!a?.entitled||!!a?.needsCms,action:()=>F(a,{update:!0})}]:[],{type:"divider"},{label:"View source",icon:"code",disabled:t.sourceEditable===!1,action:()=>Re(t)},{label:"Export .dcmsplugin",icon:"download",disabled:t.closedSource===!0,action:()=>Ue(t)},...t.core?[]:[{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:s,action:()=>De(t.name,t.displayName)}]]}function ut(e){const t=j.peek().find(n=>n.name===e);if(!t)return[];const a=!!f.peek();return[{header:t.displayName},t.enabled?{label:t.locked?"Switch off (locked)":"Switch off\u2026",icon:"pause",disabled:a||t.locked,action:()=>P(t,!1,"tool")}:{label:t.locked?"Switch on (locked)":"Switch on\u2026",icon:"play",disabled:a||t.locked,action:()=>P(t,!0,"tool")}]}const pt=e=>{const t=j.peek().find(a=>a.name===e);t&&P(t,!t.enabled,"tool")};function mt(e){const t=L(e);if(!t)return[];const a=re(t),n=!!f.peek();return[{header:t.displayName||t.slug},...a==="install"?[{label:`Install v${t.version}\u2026`,icon:"download",disabled:n,action:()=>F(t)}]:[],...a==="update"?[{label:`Update to v${t.version}\u2026`,icon:"download",disabled:n,action:()=>F(t,{update:!0})}]:[],...t.installed?[{label:"Open in Installed",icon:"package",action:()=>{J.value=t.slug,A.value="all",_e.activate?.(0)}},{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:n,action:()=>De(t.slug,t.displayName)}]:[],...a==="buy"?[{label:t.store?`${t.owned?"Renew updates":"Buy"} - ${t.owned?ce(t).replace(/^Renew /,""):ce(t)}\u2026`:`${t.licenceStatus==="expired"?"Renew":"Buy"}${ce(t)!=="Paid"?` - ${ce(t)}`:""}\u2026`,icon:"shopping-cart",action:()=>Le(t)}]:[],...t.store&&t.tier==="paid"&&!t.owned?[{label:"Enter licence key\u2026",icon:"key",action:()=>lt(t)}]:[],...a==="waiting"?[{label:"Paid? Check now",icon:"refresh-cw",action:()=>te(t.pending,{byHand:!0})},{label:"Stop waiting\u2026",icon:"x",action:()=>st(t)}]:[],...a==="locked"?[{label:"Not licensed for this site",icon:"lock",disabled:!0,action:()=>{}}]:[],...a==="needs-cms"?[{label:t.needsCms,icon:"alert-triangle",disabled:!0,action:()=>{}}]:[]]}function ht(e){const t=L(e);if(!t)return;const a=re(t);a==="install"?F(t):a==="update"?F(t,{update:!0}):a==="buy"?Le(t):a==="waiting"?te(t.pending,{byHand:!0}):a==="needs-cms"?E.toast(t.needsCms,{type:"warning",duration:6e3}):t.installed&&(J.value=t.slug,A.value="all",_e.activate?.(0))}function ye(e,t,a,n){const s=E.contextMenu(e,{cursor:"glyph",match:".plx-row",inherit:!1,density:"compact",items:m=>a(m.dataset[t])});y.add(()=>s?.destroy?.());const o=m=>{const r=m.target.closest(".plx-row");if(!r)return;const C=m.target.closest(".plx-kebab");if(C){Ve(C);return}if(m.target.closest(".plx-act")){m.target.closest("button").disabled||n(r.dataset[t]);return}n(r.dataset[t])},d=m=>{const r=m.target.closest(".plx-row");r&&(m.key==="F10"&&m.shiftKey?(m.preventDefault(),Ve(r)):m.key==="Enter"&&m.target===r&&n(r.dataset[t]))};e.addEventListener("click",o),e.addEventListener("keydown",d),y.add(()=>{e.removeEventListener("click",o),e.removeEventListener("keydown",d)})}const ve=g.querySelector(".plx-browse");ve.appendChild(Ee(`
|
|
105
105
|
<div class="plx-card">
|
|
106
106
|
<p class="plx-note" data-bind-hidden="browseState.value !== 'loading'">Loading the catalogue\u2026</p>
|
|
107
107
|
<p class="plx-note" data-bind-hidden="browseState.value !== 'error'">The catalogue could not be loaded - it needs an administrator, and a manager that is reachable.</p>
|
|
108
|
+
<div data-bind-hidden="browseState.value !== 'owner'">
|
|
109
|
+
<p style="margin:0 0 .4rem"><strong>Every plugin is already here.</strong></p>
|
|
110
|
+
<p class="plx-note">This is an owner instance - the manager that the plugins are written on - so there is nothing to buy. Install from file in the banner still takes a <code>.dcmsplugin</code>.</p>
|
|
111
|
+
</div>
|
|
112
|
+
<p class="plx-note is-bad" data-bind-hidden="browseState.value !== 'list' || !catalogue.value.storeFailed" data-bind-text="catalogue.value.storeFailed"></p>
|
|
113
|
+
<p class="plx-note is-bad" data-bind-hidden="browseState.value !== 'list' || !catalogue.value.siteError" data-bind-text="catalogue.value.siteError"></p>
|
|
108
114
|
<div data-bind-hidden="browseState.value !== 'file'">
|
|
109
115
|
<p style="margin:0 0 .4rem"><strong>This site installs plugins from a file.</strong></p>
|
|
110
116
|
<p class="plx-note">Buy a plugin and you are sent a single <code>.dcmsplugin</code> file - Install from file in the banner installs it, and the same button takes an update later. Sites managed for you browse and install here instead, over their manager connection.</p>
|
|
@@ -118,10 +124,16 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
|
|
|
118
124
|
<button type="button" data-on-click="bUpdates" data-bind-class="browseFilter.value === 'updates' && 'is-on'" data-bind-hidden="!browseCounts.value.updates">Updates <b data-bind-text="browseCounts.value.updates"></b></button>
|
|
119
125
|
</div>
|
|
120
126
|
<input type="search" class="form-input plx-search" placeholder="Search the catalogue\u2026" aria-label="Search the catalogue" data-model="browseQuery.value">
|
|
121
|
-
<span data-help-title="Browse" data-help="What this site
|
|
127
|
+
<span data-help-title="Browse" data-help="What this site can get. Install brings a plugin in licensed to this site; Update replaces the installed version and keeps its data. On a site managed for you, Buy\u2026 (Renew\u2026 once expired) opens Manage my site in a new tab with that Tool ticked, and Not licensed means it has no online billing - ask for it to be added. On a self-hosted site, Buy\u2026 opens the Domma store's payment page in a new tab: the Tool is yours to keep, it installs here once the payment is through, and the licence key is emailed to you. Its updates last a term (shown on the row); Renew\u2026 buys more. Install and Update take effect after a server restart."></span>
|
|
122
128
|
</div>
|
|
123
129
|
<p class="plx-note" data-bind-text="siteText.value" data-bind-hidden="!siteText.value"></p>
|
|
130
|
+
<div class="plx-connect" data-bind-hidden="catalogue.value.mode !== 'store'">
|
|
131
|
+
<span class="plx-note" data-bind-text="connectText.value"></span>
|
|
132
|
+
<button type="button" class="btn btn-sm btn-outline" data-on-click="connectStart" data-bind-hidden="connStatus.value !== ''">Connect to Domma\u2026</button>
|
|
133
|
+
<button type="button" class="btn btn-sm btn-ghost" data-on-click="connectCheck" data-bind-hidden="connStatus.value !== 'pending'">Check now</button>
|
|
134
|
+
<button type="button" class="btn btn-sm btn-ghost" data-on-click="connectForget" data-bind-hidden="connStatus.value === ''" data-bind-text="connStatus.value === 'pending' ? 'Cancel' : 'Disconnect\u2026'"></button>
|
|
135
|
+
</div>
|
|
124
136
|
<p class="plx-note" data-bind-hidden="browseRows.value.length">Nothing in the catalogue matches.</p>
|
|
125
137
|
<div class="plx-list plx-catalogue" data-each="browseRows.value key=slug"></div>
|
|
126
138
|
</div>
|
|
127
|
-
</div>`)),
|
|
139
|
+
</div>`)),ve.querySelector(".plx-catalogue").innerHTML=_t;const Pe=g.querySelector(".plx-installed");Pe.innerHTML=Pt;const qe=g.querySelector(".plx-tools");qe.innerHTML=qt;const _e=E.tabs(g.querySelector(".plx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),bt=M.applyBindings({plugins:R,tools:j,toolRows:Se,catalogue:u,loading:Te,loadError:ue,restarting:f,filter:A,query:J,rows:pe,counts:tt,emptyText:at,updateCount:G,updateCountText:M.computed(()=>`${G.value} update${G.value===1?"":"s"}`),browseFilter:W,browseQuery:Me,browseRows:me,browseCounts:nt,siteText:M.computed(()=>u.value.site?u.value.mode==="store"?`From the Domma store, for ${u.value.site}. A Tool you buy is yours to keep, with a term of updates you can renew.`:`Licensed to ${u.value.site}.`:""),connStatus:M.computed(()=>u.value.connection?.status||""),connectText:M.computed(()=>{const e=u.value.connection;return e?e.status==="pending"?`Waiting for you to open the link we emailed to ${e.email} - choose Connect there.`:`Connected to Domma as ${e.email}: Tools bought for this site appear here by themselves.`:"Bought Tools on the Domma Marketplace? Connect this site and it picks up every licence bought for it."}),browseState:M.computed(()=>u.value.available===null?"loading":u.value.failed?"error":u.value.available?"list":u.value.mode==="owner"?"owner":"file")},g,{methods:{showAll:()=>{A.value="all"},showOn:()=>{A.value="on"},showOff:()=>{A.value="off"},showAttention:()=>{A.value="attention"},bAll:()=>{W.value="all"},bAvailable:()=>{W.value="available"},bInstalled:()=>{W.value="installed"},bUpdates:()=>{W.value="updates"},connectStart:()=>it(),connectCheck:()=>fe(!0),connectForget:()=>rt()}});y.add(()=>bt.dispose()),y.add(He(g,{position:"bottom"})),y.add(M.effect(()=>{pe.value,Se.value,me.value,requestAnimationFrame(()=>{g.isConnected&&I.scan(g)})})),ye(Pe,"name",dt,e=>ge(e)),ye(qe,"tool",ut,pt),ye(ve.querySelector(".plx-catalogue"),"slug",mt,ht),ke(O,{id:"plugins-guide",icon:"book",title:"Writing a Tool (guide)",onClick:()=>{location.hash="#/tutorials/plugin"}}),ke(O,{id:"plugins-install-file",icon:"upload",title:"Install from file (.dcmsplugin)",onClick:()=>X.click()});let we=!1;try{we=(await h.plugins.policy())?.signedOnly===!0}catch{}we||ke(O,{id:"plugins-new",icon:"plus",title:"New plugin",onClick:()=>We()});const Ke=e=>{(f.peek()||B?.dirty())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Ke),y.add(()=>window.removeEventListener("beforeunload",Ke)),y.add(()=>{if(B?.dirty())try{S.set(de,{kind:B.kind,name:B.name,values:B.values(),at:new Date().toISOString()})}catch{}Fe=!0,[...se].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(g),await Promise.all([he(),Ne()]),!p())return;let k=null;try{k=S.get(de)}catch{}if(k?.values&&!Fe){try{S.remove?S.remove(de):S.set(de,null)}catch{}const e=k.kind==="new"?"the new plugin you started":`your settings for ${i(Z(k.name)?.displayName||k.name)}`;(k.kind==="new"&&!we||Z(k.name))&&await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&p()&&(k.kind==="new"?We(k.values):ge(k.name,k.values))}}};
|
package/bin/update.js
CHANGED
|
@@ -560,6 +560,8 @@ export default async function update(_positional, flags) {
|
|
|
560
560
|
const requiredIgnores = [
|
|
561
561
|
'.domma-backups/',
|
|
562
562
|
'plugins/analytics/data/',
|
|
563
|
+
// The Domma store's licence keys and payment claims (services/storeClient.js).
|
|
564
|
+
'config/store.json*',
|
|
563
565
|
];
|
|
564
566
|
const current = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf8') : '';
|
|
565
567
|
const missing = requiredIgnores.filter(entry => !current.split(/\r?\n/).includes(entry));
|
package/docs/DommaFeatures.md
CHANGED
|
@@ -2527,7 +2527,7 @@ All four share the engine's games library (`plugins/_lib/games`: plays, tokens,
|
|
|
2527
2527
|
- **Giftable** - paid Tools that reach a site through the catalogue and a licence, or a gift from the Manager for good or for a number of days ([Tiers, licences and entitlements](#tiers-licences-and-entitlements)). Quiz and Crossword left the free tier at 1.3.0; the engine update (1.9.0) removes a site's old free copy unless it is licensed, keeping `data/` and `backups/`.
|
|
2528
2528
|
- **Export and import** - every game exports one or all as a file and imports a file as drafts beside what is there, with no plays; layouts and schedules are worked out afresh on the server.
|
|
2529
2529
|
- **Hints** - per game: on or off, hints a play, seconds each. Quiz takes two wrong answers away or gives a typed answer's first letter; Crossword fills one letter of the chosen word; Word Search shows where one unfound word starts; Daily Word shows one letter in its place. The server decides and records each (`POST /public/play/:id/hint`); results, the Plays screen and boards (an "H2" chip) show hints used.
|
|
2530
|
-
- **Boards** - `board="show|hide|only"` on every game shortcode; a per-game **Leaderboard shows** period (`boardPeriod`) used when no period is asked for; `[games-leaderboards games="..." period="..." limit="..."]` puts every Game's boards on one page
|
|
2530
|
+
- **Boards** - `board="show|hide|only"` on every game shortcode; a per-game **Leaderboard shows** period (`boardPeriod`) used when no period is asked for; `[games-leaderboards games="..." period="..." limit="..."]` puts every Game's boards on one page - one group per Game the site has, in the order `games` names them or else by name. Since CMS 1.38.0 the hub lives in the shared Games library (`_lib/games/hub.js` `registerHub`, `_lib/public/games/hub.js` `joinHub`, styles in `games.css`), so any Game with a leaderboard joins by serving `GET /public/boards`; Hangman, Anagram, Group Four, Jigsaw, Sliding Puzzle, Memory Pairs, Timeline, Higher or Lower, Picture Reveal, Treasure Hunt and Map Guess joined then. Games with no score (Bingo, Sweepstake, Predictions, Prize Wheel, Scratch Card, Advent Calendar, Personality Quiz) have no board in it. Board shortcodes on the page refresh when a game finishes.
|
|
2531
2531
|
- **Personal best** on every finished screen; **Share** (no answers) on Quiz, Crossword and Word Search, coloured squares on Daily Word.
|
|
2532
2532
|
- **Animations** - a per-game setting, on unless switched off: answers, letters and tiles pop or flip in, right and wrong answers pulse, found words pop along their line, finished screens and board rows pop in. Never under `prefers-reduced-motion` or `html.dm-reduced-motion`. Shared CSS and helpers: `plugins/_lib/public/games/motion.css` and `motion.js` (engine 1.9.0).
|
|
2533
2533
|
- **Rotation** (Quiz 1.5.0, Crossword 1.5.0, Word Search 1.2.0; engine 1.10.0) - **off by default**. A game can be **Queued** (never shown to the public until its turn). **Rotate** Off / Every day / Every week (a weekday), in a Rotation card above each list: at the site's midnight the next queued game opens and the last one rotation opened closes into an archive - still playable, its plays (`archive: true`) never on a board, place or goes-per-name. Idempotent: `lastRotatedDay` in the Tool's `data/rotation.json`, plus a check that no game was already opened by rotation that day, so a restart at 00:00:30 never rotates twice; a one-minute timer in the Tool, no cron. An empty queue leaves today's game up. Drag to reorder the queue; take one out. `[quiz rotate /]` (and `[crossword rotate]`, `[word-search rotate]`) shows today's game with the earlier ones below; `[<game>-leaderboard rotate /]` today's board. Notices `queue-low` (under three days queued) and `queue-empty`. Engine: `plugins/_lib/games/rotation.js` (pure rules + runner), `rotation-http.js` (`GET/PUT /rotation`, `PUT /queue`, `POST /approve`, `POST /unqueue`, `GET /content/status`, `GET /public/rotation`), `_lib/public/games/rotation.js`, `_lib/admin/games/rotation.js`; tests `tests/plugins/games-rotation.test.js`.
|
|
@@ -2535,7 +2535,7 @@ All four share the engine's games library (`plugins/_lib/games`: plays, tokens,
|
|
|
2535
2535
|
|
|
2536
2536
|
### More Games: Personality Quiz, Hangman, Anagram, Jigsaw, Memory Pairs, Treasure Hunt, Prize Wheel, Predictions
|
|
2537
2537
|
|
|
2538
|
-
Tier: paid and giftable, closed source · Version: 1.0.0 each (2026-10-29) · Needs: Domma CMS 1.10.0 (the shared games library) · Sidebar: Tools > Games · Permissions: one each in the Games group (See / Manage). Each is its own Tool in `dcms-marketplace/plugins/<slug>/` with a user guide (`docs/guide.md`, in the admin Documentation), test plays from the Tool, export and import (`domma-<slug>` version 1, arriving as drafts), animations from `_lib/public/games/motion.*` (never under reduced motion) and all UI in domma-reactive.
|
|
2538
|
+
Tier: paid and giftable, closed source · Version: 1.0.0 each (2026-10-29) · Needs: Domma CMS 1.10.0 (the shared games library) · Sidebar: Tools > Games · Permissions: one each in the Games group (See / Manage). Each is its own Tool in `dcms-marketplace/plugins/<slug>/` with a user guide (`docs/guide.md`, in the admin Documentation), test plays from the Tool, export and import (`domma-<slug>` version 1, arriving as drafts), animations from `_lib/public/games/motion.*` (never under reduced motion) and all UI in domma-reactive. The scored ones join `[games-leaderboards]` since CMS 1.38.0; none has rotation yet.
|
|
2539
2539
|
|
|
2540
2540
|
#### Personality Quiz (`personality-quiz`)
|
|
2541
2541
|
|
|
@@ -2597,7 +2597,7 @@ Tier: paid and giftable, closed source · Version: 1.0.0 each (2026-10-29) · Ne
|
|
|
2597
2597
|
|
|
2598
2598
|
### Ten more Games: Advent Calendar, Scratch Card, Timeline, Picture Reveal, Group Four, Higher or Lower, Bingo, Sliding Puzzle, Map Guess, Sweepstake
|
|
2599
2599
|
|
|
2600
|
-
Tier: paid and giftable, closed source · Version: 1.0.0 each (2026-11-01) · Needs: Domma CMS 1.10.0 · Sidebar: Tools > Games · Permissions: one each in the Games group (See / Manage; anything that holds answers needs Manage). Built the same way as the eight before them: own Tool in `dcms-marketplace/plugins/<slug>/`, user guide in the admin Documentation, test plays, export and import (`domma-<slug>` version 1, as drafts, nothing derived carried over), motion from `_lib/public/games/motion.*`, domma-reactive throughout, goes-per-name checked and started in one turn per game and name.
|
|
2600
|
+
Tier: paid and giftable, closed source · Version: 1.0.0 each (2026-11-01) · Needs: Domma CMS 1.10.0 · Sidebar: Tools > Games · Permissions: one each in the Games group (See / Manage; anything that holds answers needs Manage). Built the same way as the eight before them: own Tool in `dcms-marketplace/plugins/<slug>/`, user guide in the admin Documentation, test plays, export and import (`domma-<slug>` version 1, as drafts, nothing derived carried over), motion from `_lib/public/games/motion.*`, domma-reactive throughout, goes-per-name checked and started in one turn per game and name. The scored ones join `[games-leaderboards]` since CMS 1.38.0; none has rotation yet. The same release fixes Prize Wheel 1.0.1 (spins a day per connection, salted daily key, default 20) and Jigsaw 1.0.1 (the goes-per-name race).
|
|
2601
2601
|
|
|
2602
2602
|
#### Advent Calendar (`advent-calendar`)
|
|
2603
2603
|
|
package/docs/configuration.md
CHANGED
|
@@ -33,6 +33,7 @@ Controls the HTTP server.
|
|
|
33
33
|
| `logging.level` | string | Log verbosity: `fatal`, `error`, `warn`, `info`, `debug`, `trace`, `silent`. Defaults to `info` in development, `warn` otherwise. `warn` hides 4xx responses and plugin `log.info` output, so a failed admin action leaves no trace - raise it to `info` if you need to diagnose one. Overridden by the `LOG_LEVEL` env var. |
|
|
34
34
|
| `restartOnPluginToggle` | boolean | `true` | Restart the server automatically when an admin enables or disables a plugin. See **Plugin toggles restart the server** below |
|
|
35
35
|
| `requireSignedPlugins` | boolean | `false` | When `true`, the site runs only plugin code the Marketplace signed: an unsigned `.dcmsplugin` (e.g. one exported from another site) is refused even if the installer confirms it, New plugin is refused, a plugin's files cannot be changed in the code editor (it opens read only), licensed source cannot be read even by a Super Admin, and MongoDB connection options that start a program or read a file (`autoEncryption`, `tls…File`, …) cannot be saved. A bundle with a signature that does not verify is always refused, whatever this is set to. Read fresh on every check, and also as it was at boot, so changing the file on a running site can switch it on but not off. `DOMMA_SIGNED_ONLY=1` in the environment turns it on whatever the file says - Domma CMS Manager sets it on the sites it hosts. Nothing in the admin writes `server.json`. See `server/services/codePolicy.js` |
|
|
36
|
+
| `storeUrl` | string \| `false` | Domma's store | Where a **self-hosted** site's Marketplace buys and downloads Tools (Browse). A Tool bought there is the site's to keep, with a term of updates that is renewed with a one-off payment; the licence keys and the payment claims are kept in `config/store.json` (out of git). `false` switches the store off, leaving Install from file. Not used on a site a Domma CMS Manager runs (it buys through its manager), nor on the manager itself unless `storeUrl` is set there. `DOMMA_STORE_URL` in the environment wins. See `server/services/storeClient.js` |
|
|
36
37
|
| `outboundAllowPrivate` | boolean \| string[] | `false` | Webhooks (an Action's webhook step, a form's webhook) reach public addresses only: the name is looked up and every address must be public and not the server's own, the request is pinned to that address, redirects into private addresses are refused, and only ports 80 and 443 are used. A self-hosted site that sends webhooks inside its own network sets `true` to lift those rules for every request, or a list of host names, addresses and CIDR ranges (`["n8n.lan", "192.168.10.0/24", "fd00::/8"]`) to lift them for those only - a name passes if it is listed, or if every address it resolves to is. Ignored on a signed-only site (`requireSignedPlugins` / `DOMMA_SIGNED_ONLY=1`), so a hosted site's admin cannot open the host's network. Read fresh on every request. See `server/services/outbound.js` |
|
|
37
38
|
|
|
38
39
|
### Plugin toggles restart the server
|