domma-cms 1.47.5 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/CLAUDE.md +4 -0
  3. package/admin/js/api.js +1 -1
  4. package/admin/js/lib/api-tokens-arrange.js +3 -3
  5. package/admin/js/templates/api-tokens.html +16 -0
  6. package/admin/js/views/api-tokens.js +33 -6
  7. package/admin/js/views/page-editor.js +9 -9
  8. package/docs/DommaFeatures.md +2 -0
  9. package/docs/api-reference.md +97 -2
  10. package/docs/plugin-development.md +27 -1
  11. package/package.json +1 -1
  12. package/plugins/free-tier.lock.json +13 -11
  13. package/plugins/shopping-cart/CHANGELOG.md +6 -0
  14. package/plugins/shopping-cart/CLAUDE.md +7 -1
  15. package/plugins/shopping-cart/lib/render.js +16 -3
  16. package/plugins/shopping-cart/plugin.js +15 -3
  17. package/plugins/shopping-cart/plugin.json +1 -1
  18. package/plugins/shopping-cart/public/cart.js +17 -1
  19. package/plugins/shopping-cart/public/lib/orders.js +23 -0
  20. package/plugins/shopping-cart/public/shop.css +3 -1
  21. package/plugins/shopping-cart/tests/account-scope.test.js +102 -0
  22. package/plugins/shopping-cart/tests/accounts.test.js +1 -1
  23. package/plugins/shopping-cart/tests/checkout-wording.test.js +58 -0
  24. package/public/js/site.js +1 -1
  25. package/public/js/token-handover-page.mjs +2 -0
  26. package/public/js/token-handover.mjs +13 -0
  27. package/server/routes/api/api-tokens.js +116 -4
  28. package/server/routes/api/collections.js +69 -0
  29. package/server/routes/api/content-writes.js +334 -0
  30. package/server/routes/api/pages.js +21 -1
  31. package/server/routes/public.js +15 -0
  32. package/server/routes/token-handover-public.js +59 -0
  33. package/server/server.js +6 -0
  34. package/server/services/apiTokens.js +61 -16
  35. package/server/services/content.js +4 -2
  36. package/server/services/markdown.js +10 -10
  37. package/server/services/pluginScope.js +26 -0
  38. package/server/services/plugins.js +3 -2
  39. package/server/services/siteGitignore.js +2 -0
  40. package/server/services/tokenContentPolicy.js +369 -0
  41. package/server/services/tokenHandovers.js +143 -0
  42. package/server/services/tokenRecipes.js +207 -0
  43. package/server/templates/page.html +1 -1
  44. package/server/templates/token-handover.html +3 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.48.0] - 2026-11-09
4
+
5
+ - **Making and handing over API tokens.**
6
+ - **Bot that writes drafts**, a switch in New token: tick the collections a bot (Grok, a script, another site) may write to, and it gets a token scoped to them with Drafts only on. Each collection's create (and, if chosen, update) is opened to tokens where it was off - never wider than it is: a verb already open to everyone is left alone, and the screen says so. A collection with no draft status can be given a Status field (draft / published). Built-in collections are never offered. Needs permission to change collections.
7
+ - **A one-time link** from the Token created panel, to send instead of the token. It opens once, within 24 hours, and shows the token with how to use it (where to send what, a curl example, who to credit). The token is encrypted in the admin's browser and the key is only in the link, so the site keeps nothing that could show it. Revoking the token kills the link.
8
+ - **A connection file** (JSON) to download, for a script or bot to read: the site, the token, what it may do where, and the author to credit.
9
+ - **Bots can write pages, pictures and blocks through the Content API**, with a token whose scope names it (`@pages: create, update`, `@media: create`, `@blocks: create, update`): `POST`/`PUT /api/content/v1/pages`, `POST /api/content/v1/media`, `POST`/`PUT /api/content/v1/blocks`. With Drafts only, pages arrive as drafts and only drafts can be changed; pictures are public once uploaded; only new blocks can be made. Uploads are checked by their bytes (pictures and PDFs only, never SVG or HTML) and never replace another file. Tokens made before this cannot write: writing needs the verb named, and only an admin who holds that permission can grant it. What a token writes is held to Markdown and the layout shortcodes - no HTML - and is then rendered and the RESULT checked against what those emit (no `[dconfig]`, `[collection]`, `[cta]`, `[form]`, blocks, scripts, styles or forms reach the page); drafts a token wrote are shown to their reviewer isolated (a CSP sandbox on the draft view and share link, a script-less editor preview); a drafts-only token changes only its own drafts, pages and collection entries alike; what any token writes to a collection through `/api/v1` passes the same content policy; a new block may not take a shortcode's name or one the site already uses; 30 writes a minute and 200 MB of uploads a day per token. Bot that writes drafts offers all three. Only the classes the layout shortcodes really emit reach a token's page (a parameter can no longer name a site class such as `fixed` or `modal`: every class built from a shortcode parameter keeps to letters, digits, `_` and `-`), and no token may write the roles, user profiles, tokens or other system collections, whatever their API settings say.
10
+ - The site refuses to navigate to a `javascript:`, `data:` or `vbscript:` address from a page's settings or a form's redirect (`goTo` in `public/js/site.js`).
11
+
12
+ ## [1.47.6] - 2026-11-08
13
+
14
+ - **Plugins: `options.auth.authenticateSelf`**, core's sign-in check without the plugin admin-scope rule, for plugin routes that act only on the caller's own record (a shop customer's account or reorder). A confined role such as `shop-customer` got 403 "Your account cannot use <plugin>" there. It keeps every token rule: an access token is required and a refresh token is refused. Plugin `authenticate` is unchanged. See "authenticateSelf" in docs/plugin-development.md - never use it for admin APIs or other users' data.
15
+
3
16
  ## [1.47.5] - 2026-11-08
4
17
 
5
18
  - **Security: the site's own records are never written through the public collections API.** `roles`, `user-profiles`, API tokens, projects and the other built-in collections refuse create, update and delete on `/api/v1/:slug` and `/api/collections/:slug/public` whatever their API settings say - with `roles` create set to public, an anonymous request could make a top-level role. Admins change them in the admin as before; the Tools' notes, tasks and contacts (each user's own rows) are unchanged.
package/CLAUDE.md CHANGED
@@ -175,6 +175,10 @@ Seeded on first run with: `super-admin` (0), `admin` (1), `user` (2); admins add
175
175
  browser as `adminScope` on `/api/auth/permissions`; `admin/js/lib/admin-scope.js` decides per route and
176
176
  `app.js` applies it in three places (router guard, after login, before `R.init()`). Core must not name a
177
177
  plugin's roles - the job-board `JB_ROLES` list that used to live in app.js is what this replaced.
178
+ - **Plugin API scope.** The `authenticate` a plugin gets (`pluginScope.js` `authenticateFor`) also refuses a confined
179
+ user unless one of the plugin's screens is in their scope. `auth.authenticateSelf` is core's check alone (same token
180
+ rules), for routes acting only on the caller's own record; the route must check ownership against
181
+ `request.user.id`. Never hand it to admin APIs or routes on other users' data. Both come from `pluginAuthGuards()`.
178
182
  - Role saves go through `keepRoleSystemFields()` in `routes/api/collections.js`: `plugin` and `grantedBy` are
179
183
  pinned to the stored values, because clients send whole records.
180
184
 
package/admin/js/api.js CHANGED
@@ -1 +1 @@
1
- import{claimDrafts as O}from"./lib/draft-owner.js";import{loginHashFor as $}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),folders:()=>t("/media/_folders",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"}),buy:(e,o={})=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e,...o})}),claim:e=>t("/plugins/marketplace/claim",{method:"POST",body:JSON.stringify({id:e})}),enterKey:(e,o)=>t("/plugins/marketplace/key",{method:"POST",body:JSON.stringify({slug:e,key:o})}),connect:e=>t("/plugins/marketplace/connect",{method:"POST",body:JSON.stringify({email:e})}),connectCheck:()=>t("/plugins/marketplace/connect/check",{method:"POST",body:"{}"}),disconnect:()=>t("/plugins/marketplace/connect",{method:"DELETE"}),dropPurchase:e=>t(`/plugins/marketplace/purchases/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&(O(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=$(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
1
+ import{claimDrafts as O}from"./lib/draft-owner.js";import{loginHashFor as $}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"}),recipe:e=>t(`/api-tokens/_recipe?project=${encodeURIComponent(e)}`,{method:"GET"}),handover:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}/handover`,{method:"POST",body:JSON.stringify(o)})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),folders:()=>t("/media/_folders",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"}),buy:(e,o={})=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e,...o})}),claim:e=>t("/plugins/marketplace/claim",{method:"POST",body:JSON.stringify({id:e})}),enterKey:(e,o)=>t("/plugins/marketplace/key",{method:"POST",body:JSON.stringify({slug:e,key:o})}),connect:e=>t("/plugins/marketplace/connect",{method:"POST",body:JSON.stringify({email:e})}),connectCheck:()=>t("/plugins/marketplace/connect/check",{method:"POST",body:"{}"}),disconnect:()=>t("/plugins/marketplace/connect",{method:"DELETE"}),dropPurchase:e=>t(`/plugins/marketplace/purchases/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&(O(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=$(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
@@ -1,3 +1,3 @@
1
- import{fmtDate as x}from"./dates.js";export const VERBS=["create","read","update","delete"],CONTENT_RESOURCES=["pages","menus","site","search"],FILTERS=["all","active","expiring","expired","disabled"],SOON_DAYS=14;const m=864e5,f=(e,n,r=`${n}s`)=>`${e} ${e===1?n:r}`;export function tokenState(e,n=Date.now()){const r=e?.expiresAt?Date.parse(e.expiresAt):NaN,t=Number.isFinite(r)?Math.ceil((r-n)/m):null;return Number.isFinite(r)&&r<=n?{state:"expired",days:t}:e?.enabled===!1?{state:"disabled",days:t}:t!==null&&t<=SOON_DAYS?{state:"expiring",days:t}:{state:"active",days:t}}export function expiresIn(e){return e==null?"":e<=0?"today":e===1?"tomorrow":`in ${e} days`}export function ago(e,n=Date.now()){const r=Date.parse(e);if(!Number.isFinite(r))return"";const t=Math.max(0,Math.round((n-r)/1e3));return t<60?"just now":t<3600?`${Math.round(t/60)} min ago`:t<86400?`${f(Math.round(t/3600),"hour")} ago`:t<86400*30?`${f(Math.round(t/86400),"day")} ago`:x(r)}export function scopesToText(e){return(Array.isArray(e)?e:[]).map(n=>n.content!==void 0?`@${n.content}`:Array.isArray(n.verbs)&&n.verbs.length?`${n.collection}: ${n.verbs.join(", ")}`:n.collection).join(`
2
- `)}export function parseScopes(e){const n=[],r=new Set;for(const t of String(e??"").split(`
3
- `)){const o=t.trim();if(!o)continue;if(o.startsWith("@")){if(o.includes(":"))return{error:`"${o}" - content scopes are read-only and take no verbs.`};const c=o.slice(1).trim().toLowerCase();if(!c)return{error:'"@" names no content resource.'};if(!CONTENT_RESOURCES.includes(c))return{error:`"@${c}" is not a content resource - use ${CONTENT_RESOURCES.map(u=>"@"+u).join(", ").replace(/, ([^,]*)$/," or $1")}.`};if(r.has("@"+c))return{error:`"@${c}" is listed twice.`};r.add("@"+c),n.push({content:c});continue}const s=o.indexOf(":"),a=(s<0?o:o.slice(0,s)).trim(),i=s<0?"":o.slice(s+1).trim();if(!a)return{error:`"${o}" names no collection.`};if(r.has(a))return{error:`"${a}" is listed twice.`};r.add(a);const l={collection:a};if(i){const c=i.split(",").map(p=>p.trim().toLowerCase()).filter(Boolean),u=c.find(p=>!VERBS.includes(p));if(u)return{error:`"${u}" is not a verb - use ${VERBS.join(", ")}.`};l.verbs=[...new Set(c)]}n.push(l)}return{scopes:n}}export function scopesSummary(e){if(!Array.isArray(e)||!e.length)return"everything in the project - its collections and the Content API";const n=e.filter(t=>t.content===void 0).map(t=>`${t.collection}: ${Array.isArray(t.verbs)&&t.verbs.length?t.verbs.join(", "):"all"}`),r=e.filter(t=>t.content!==void 0).map(t=>t.content);return[...n,...r.length?[`content: ${r.join(", ")}`]:[]].join(" \xB7 ")}export function arrangeTokens(e,{filter:n="all",project:r="",query:t=""}={},o=Date.now()){const s=String(t).trim().toLowerCase(),a={expired:0,expiring:1,active:2,disabled:3};return(e||[]).map(i=>({t:i,s:tokenState(i,o)})).filter(({s:i})=>n==="all"||i.state===n).filter(({t:i})=>!r||i.project===r).filter(({t:i})=>!s||[i.name,i.project,i.tokenHint,i.createdBy,scopesSummary(i.scopes)].some(l=>String(l||"").toLowerCase().includes(s))).sort((i,l)=>a[i.s.state]-a[l.s.state]||(i.s.state==="expiring"?i.s.days-l.s.days:0)||String(i.t.name||"").localeCompare(String(l.t.name||""))).map(({t:i})=>i)}export function countStates(e,n=Date.now()){const r={all:0,active:0,expiring:0,expired:0,disabled:0};for(const t of e||[])r.all++,r[tokenState(t,n).state]++;return r}const g={active:["Active","is-ok"],disabled:["Off",""],expired:["Expired","is-danger"],expiring:["","is-warn"]};export function tokenRow(e,n=Date.now()){const{state:r,days:t}=tokenState(e,n),[o,s]=g[r],a=e.expiresAt?r==="expired"?`expired ${ago(e.expiresAt,n)}`:`expires ${expiresIn(t)}`:"never expires";return{id:e.id,name:e.name||"(unnamed)",hint:`dcms_\u2026${e.tokenHint||"????"}`,project:e.project||"",meta:[scopesSummary(e.scopes),e.draftsOnly?"drafts only":"",a,e.createdBy?`by ${e.createdBy}`:""].filter(Boolean).join(" \xB7 "),used:e.lastUsedAt?`used ${ago(e.lastUsedAt,n)}`:"never used",stateLabel:r==="expiring"?`Expires ${expiresIn(t)}`:o,stateCls:s,rowCls:r==="disabled"||r==="expired"?"is-off":""}}export function toLocalInput(e){const n=Date.parse(e);if(!Number.isFinite(n))return"";const r=new Date(n),t=o=>String(o).padStart(2,"0");return`${r.getFullYear()}-${t(r.getMonth()+1)}-${t(r.getDate())}T${t(r.getHours())}:${t(r.getMinutes())}`}export function checkToken(e,{isNew:n,projects:r=[],now:t=Date.now()}={}){const o=e||{},s={},a=String(o.name??"").trim();a||(s.name="A token needs a name - who or what will use it."),n&&!String(o.project||"")?s.project="Choose the project it works in.":n&&r.length&&!r.includes(o.project)&&(s.project="Choose one of your projects.");const{scopes:i,error:l}=parseScopes(o.scopes);l&&(s.scopes=l);let c=null;if(String(o.expires||"").trim()){const d=Date.parse(o.expires);Number.isFinite(d)?(c=new Date(d).toISOString(),n&&d<=t&&(s.expires="That is already past - a new token would be dead on arrival.")):s.expires="Not a date."}const u=o.draftsOnly===!0,p=n?{name:a,project:o.project,scopes:i||[],expiresAt:c,draftsOnly:u}:{name:a,enabled:o.enabled!==!1,scopes:i||[],expiresAt:c,draftsOnly:u};return{errors:s,payload:p}}
1
+ import{fmtDate as x}from"./dates.js";export const VERBS=["create","read","update","delete"],CONTENT_RESOURCES=["pages","menus","site","search"],CONTENT_VERBS={pages:["read","create","update"],menus:["read"],site:["read"],search:["read"],media:["create"],blocks:["create","update"]};const g=Object.keys(CONTENT_VERBS);export const FILTERS=["all","active","expiring","expired","disabled"],SOON_DAYS=14;const $=864e5,m=(n,r,e=`${r}s`)=>`${n} ${n===1?r:e}`;export function tokenState(n,r=Date.now()){const e=n?.expiresAt?Date.parse(n.expiresAt):NaN,t=Number.isFinite(e)?Math.ceil((e-r)/$):null;return Number.isFinite(e)&&e<=r?{state:"expired",days:t}:n?.enabled===!1?{state:"disabled",days:t}:t!==null&&t<=SOON_DAYS?{state:"expiring",days:t}:{state:"active",days:t}}export function expiresIn(n){return n==null?"":n<=0?"today":n===1?"tomorrow":`in ${n} days`}export function ago(n,r=Date.now()){const e=Date.parse(n);if(!Number.isFinite(e))return"";const t=Math.max(0,Math.round((r-e)/1e3));return t<60?"just now":t<3600?`${Math.round(t/60)} min ago`:t<86400?`${m(Math.round(t/3600),"hour")} ago`:t<86400*30?`${m(Math.round(t/86400),"day")} ago`:x(e)}export function scopesToText(n){return(Array.isArray(n)?n:[]).map(r=>r.content!==void 0?Array.isArray(r.verbs)&&r.verbs.length?`@${r.content}: ${r.verbs.join(", ")}`:`@${r.content}`:Array.isArray(r.verbs)&&r.verbs.length?`${r.collection}: ${r.verbs.join(", ")}`:r.collection).join(`
2
+ `)}export function parseScopes(n){const r=[],e=new Set;for(const t of String(n??"").split(`
3
+ `)){const s=t.trim();if(!s)continue;if(s.startsWith("@")){const u=s.indexOf(":"),c=(u<0?s.slice(1):s.slice(1,u)).trim().toLowerCase();if(!c)return{error:'"@" names no content resource.'};if(!g.includes(c))return{error:`"@${c}" is not a content resource - use ${g.map(f=>"@"+f).join(", ").replace(/, ([^,]*)$/," or $1")}.`};if(e.has("@"+c))return{error:`"@${c}" is listed twice.`};e.add("@"+c);const d=CONTENT_VERBS[c],p=u<0?[]:[...new Set(s.slice(u+1).split(",").map(f=>f.trim().toLowerCase()).filter(Boolean))],h=p.find(f=>!d.includes(f));if(h)return{error:`"@${c}" may ${d.join(", ")} - not "${h}".`};if(!p.length&&!d.includes("read"))return{error:`"@${c}" needs what it may do: @${c}: ${d.join(", ")}.`};r.push(p.length?{content:c,verbs:p}:{content:c});continue}const o=s.indexOf(":"),a=(o<0?s:s.slice(0,o)).trim(),i=o<0?"":s.slice(o+1).trim();if(!a)return{error:`"${s}" names no collection.`};if(e.has(a))return{error:`"${a}" is listed twice.`};e.add(a);const l={collection:a};if(i){const u=i.split(",").map(d=>d.trim().toLowerCase()).filter(Boolean),c=u.find(d=>!VERBS.includes(d));if(c)return{error:`"${c}" is not a verb - use ${VERBS.join(", ")}.`};l.verbs=[...new Set(u)]}r.push(l)}return{scopes:r}}export function scopesSummary(n){if(!Array.isArray(n)||!n.length)return"everything in the project - its collections and the Content API";const r=n.filter(t=>t.content===void 0).map(t=>`${t.collection}: ${Array.isArray(t.verbs)&&t.verbs.length?t.verbs.join(", "):"all"}`),e=n.filter(t=>t.content!==void 0).map(t=>Array.isArray(t.verbs)&&t.verbs.length?`${t.content} (${t.verbs.join(", ")})`:t.content);return[...r,...e.length?[`content: ${e.join(", ")}`]:[]].join(" \xB7 ")}export function arrangeTokens(n,{filter:r="all",project:e="",query:t=""}={},s=Date.now()){const o=String(t).trim().toLowerCase(),a={expired:0,expiring:1,active:2,disabled:3};return(n||[]).map(i=>({t:i,s:tokenState(i,s)})).filter(({s:i})=>r==="all"||i.state===r).filter(({t:i})=>!e||i.project===e).filter(({t:i})=>!o||[i.name,i.project,i.tokenHint,i.createdBy,scopesSummary(i.scopes)].some(l=>String(l||"").toLowerCase().includes(o))).sort((i,l)=>a[i.s.state]-a[l.s.state]||(i.s.state==="expiring"?i.s.days-l.s.days:0)||String(i.t.name||"").localeCompare(String(l.t.name||""))).map(({t:i})=>i)}export function countStates(n,r=Date.now()){const e={all:0,active:0,expiring:0,expired:0,disabled:0};for(const t of n||[])e.all++,e[tokenState(t,r).state]++;return e}const w={active:["Active","is-ok"],disabled:["Off",""],expired:["Expired","is-danger"],expiring:["","is-warn"]};export function tokenRow(n,r=Date.now()){const{state:e,days:t}=tokenState(n,r),[s,o]=w[e],a=n.expiresAt?e==="expired"?`expired ${ago(n.expiresAt,r)}`:`expires ${expiresIn(t)}`:"never expires";return{id:n.id,name:n.name||"(unnamed)",hint:`dcms_\u2026${n.tokenHint||"????"}`,project:n.project||"",meta:[scopesSummary(n.scopes),n.draftsOnly?"drafts only":"",a,n.createdBy?`by ${n.createdBy}`:""].filter(Boolean).join(" \xB7 "),used:n.lastUsedAt?`used ${ago(n.lastUsedAt,r)}`:"never used",stateLabel:e==="expiring"?`Expires ${expiresIn(t)}`:s,stateCls:o,rowCls:e==="disabled"||e==="expired"?"is-off":""}}export function toLocalInput(n){const r=Date.parse(n);if(!Number.isFinite(r))return"";const e=new Date(r),t=s=>String(s).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}export function checkToken(n,{isNew:r,projects:e=[],now:t=Date.now()}={}){const s=n||{},o={},a=String(s.name??"").trim();a||(o.name="A token needs a name - who or what will use it."),r&&!String(s.project||"")?o.project="Choose the project it works in.":r&&e.length&&!e.includes(s.project)&&(o.project="Choose one of your projects.");const{scopes:i,error:l}=parseScopes(s.scopes);l&&(o.scopes=l);let u=null;if(String(s.expires||"").trim()){const p=Date.parse(s.expires);Number.isFinite(p)?(u=new Date(p).toISOString(),r&&p<=t&&(o.expires="That is already past - a new token would be dead on arrival.")):o.expires="Not a date."}const c=s.draftsOnly===!0,d=r?{name:a,project:s.project,scopes:i||[],expiresAt:u,draftsOnly:c}:{name:a,enabled:s.enabled!==!1,scopes:i||[],expiresAt:u,draftsOnly:c};return{errors:o,payload:d}}export function recipeRows(n=[],r=[],{edit:e=!1}={}){const t=new Set(r),s=e?["create","update"]:["create"];return n.map(o=>{if(!o.ok)return{slug:o.slug,title:o.title||o.slug,ok:!1,chosen:!1,note:o.why||"Cannot be used.",tone:"muted"};const a=[];a.push(o.drafts==="has"?"Holds drafts.":"No draft status yet - a Status field (draft / published) is added.");for(const l of s){const u=o.api?.[l];u?.enabled&&u.access!=="token"&&a.push(`${l} is already open to ${u.access==="public"?"everyone":`the ${u.access} role`} - left as it is.`)}o.hasAuthor&&a.push("Needs an author: the bot is told to credit you.");const i=o.drafts==="add"||a.some(l=>l.includes("left as it is"));return{slug:o.slug,title:o.title||o.slug,ok:!0,chosen:t.has(o.slug),note:a.join(" "),tone:i?"attention":"ok",drafts:o.drafts}}).sort((o,a)=>b(o)-b(a)||o.title.localeCompare(a.title))}const b=n=>n.ok?n.drafts==="has"?0:1:2;export function recipeUnavailable(n=[]){const r=n.filter(e=>!e.ok).map(e=>e.title||e.slug).sort((e,t)=>e.localeCompare(t));return r.length?`Not offered (a Status field without a draft option): ${r.join(", ")}.`:""}export function recipePayload(n=[],r=[],{edit:e=!1}={}){const t=new Set(r),s=n.filter(o=>o.ok&&t.has(o.slug)).map(o=>({slug:o.slug,verbs:e?["create","update"]:["create"],addStatus:o.drafts==="add"}));return s.length?{collections:s}:null}export const RECIPE_CONTENT=[{resource:"pages",label:"Pages, as drafts",note:"New pages wait as drafts; a person publishes them."},{resource:"media",label:"Pictures and PDFs",note:"Public at /media once uploaded (unlinked until a page uses it). Never over another file."},{resource:"blocks",label:"New blocks",note:"Only new ones. A block has no draft: it shows wherever a page uses it."}];export function recipeContentScopes(n=[],{edit:r=!1}={}){const e=new Set(n),t=[];return e.has("pages")&&t.push({content:"pages",verbs:r?["create","update"]:["create"]}),e.has("media")&&t.push({content:"media",verbs:["create"]}),e.has("blocks")&&t.push({content:"blocks",verbs:["create"]}),t}export function recipeReport(n=[]){const r=[];for(const e of n){const t=[];e.opened?.length&&t.push(`opened ${e.opened.join(" and ")} to tokens`),e.addsStatus&&t.push("added a Status field"),r.push(`${e.slug}: ${t.length?t.join(", "):"nothing needed changing"}.`);for(const s of e.warnings||[])r.push(` ${s}`)}return r}
@@ -83,4 +83,20 @@
83
83
  .atx-token { display: block; padding: .65rem; word-break: break-all; user-select: all; border-radius: var(--dm-radius-sm);
84
84
  background: var(--dm-surface-raised, color-mix(in srgb, var(--dm-text) 6%, transparent)); color: var(--dm-text); font-family: var(--dm-font-mono, monospace); }
85
85
  @media (max-width: 640px) { .atx-used { display: none; } }
86
+ .atx-recipe { display: flex; flex-direction: column; gap: .5rem; }
87
+ .atx-recipe-content { display: flex; flex-direction: column; gap: .35rem; }
88
+ .atx-recipe-list { display: flex; flex-direction: column; gap: .35rem; max-height: 18rem; overflow: auto; }
89
+ .atx-recipe-row { display: flex; gap: .6rem; align-items: flex-start; padding: .45rem .55rem; border: 1px solid var(--dm-border);
90
+ border-radius: var(--dm-radius-sm); cursor: pointer; }
91
+ .atx-recipe-row input { margin-top: .2rem; }
92
+ .atx-recipe-row small { color: var(--dm-text-muted); }
93
+ .atx-recipe-row.is-attention small { color: var(--dm-warning, var(--dm-text)); }
94
+ .atx-recipe-row.is-off { opacity: .6; cursor: default; }
95
+ .atx-recipe-edit { display: flex; gap: .5rem; align-items: center; font-size: .9em; }
96
+ .atx-handover { display: flex; flex-direction: column; gap: .5rem; padding-top: .6rem; border-top: 1px solid var(--dm-border); }
97
+ .atx-handover .atx-hint { margin: 0; }
98
+ .atx-link-text { display: block; padding: .5rem; word-break: break-all; user-select: all; border-radius: var(--dm-radius-sm); }
99
+ .atx-report { margin: 0; padding-left: 1.1rem; font-size: .9em; }
100
+ .atx-report .atx-report-warn { list-style: none; margin-left: -1.1rem; color: var(--dm-text-muted); }
101
+ .atx-form [hidden], .atx-recipe [hidden], .atx-handover [hidden] { display: none !important; }
86
102
  </style>
@@ -1,4 +1,4 @@
1
- import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-chrome.js";import{helpPopovers as ie}from"../lib/help-popover.js";import{onceClosed as le,openMenuAt as re,sidebarCount as Me,viewLifetime as Ae}from"../lib/tool-kit.js";import{FILTERS as Le,arrangeTokens as Oe,checkToken as Ie,countStates as $e,scopesToText as Ne,toLocalInput as Pe,tokenRow as qe,tokenState as ce}from"../lib/api-tokens-arrange.js";const de=/^#\/api-tokens\/?(\?.*)?$/,De="#/api-tokens",D="api-tokens.draft",H="api-tokens.filter",Re=`
1
+ import{api as C,getUser as Fe}from"../api.js";import{addBannerAction as _e}from"../lib/plugin-chrome.js";import{helpPopovers as ke}from"../lib/help-popover.js";import{onceClosed as xe,openMenuAt as we,sidebarCount as Ue,viewLifetime as ze}from"../lib/tool-kit.js";import{FILTERS as Ke,arrangeTokens as He,checkToken as Ge,countStates as Ye,RECIPE_CONTENT as Je,recipeContentScopes as Ve,recipePayload as We,recipeReport as Qe,recipeRows as Xe,recipeUnavailable as Ze,scopesToText as et,toLocalInput as tt,tokenRow as at,tokenState as ge}from"../lib/api-tokens-arrange.js";import{connectionFile as nt,connectionFileName as ot,handoverLink as st,sealConnection as it}from"../../../public/js/token-handover.mjs";const Ee=/^#\/api-tokens\/?(\?.*)?$/,lt="#/api-tokens",Q="api-tokens.draft",ne="api-tokens.filter",ct=`
2
2
  <div class="atx-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls">
3
3
  <span class="atx-icon" aria-hidden="true"><span data-icon="key" data-icon-size="16"></span></span>
4
4
  <span class="atx-main"><strong>{{name}}</strong><small><code>{{hint}}</code> \xB7 {{meta}}</small></span>
@@ -8,7 +8,7 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
8
8
  </span>
9
9
  <span class="atx-used" data-bind-text="used"></span>
10
10
  <button type="button" class="atx-kebab" aria-label="Actions for {{name}}" title="Actions">\u22EE</button>
11
- </div>`,L=c=>String(c??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function pe(c){const d=document.createElement("template");return d.innerHTML=c.trim(),d.content.firstElementChild}async function ue(c){try{return await navigator.clipboard.writeText(c),!0}catch{return!1}}const l=Ae(de);export const apiTokensView={templateUrl:"/admin/js/templates/api-tokens.html",async onMount(c){l.reset();const d=c.get(0).querySelector(".atx")||c.get(0),O=()=>de.test(location.hash)&&d.isConnected,x=M.observable([]),j=M.observable([]),R=M.observable(!0),F=M.observable("");let U="all";try{U=Le.includes(S.get(H))?S.get(H):"all"}catch{}const r=M.observable(U),h=M.observable(""),Y=M.observable("");l.add(M.effect(()=>{const e=r.value;try{S.set(H,e)}catch{}}));const _=M.observable([]);l.add(M.effect(()=>{const e=Date.now();_.value=Oe(x.value,{filter:r.value,project:h.value,query:Y.value},e).map(t=>qe(t,e))}));const V=M.computed(()=>$e(x.value)),fe=M.computed(()=>x.value.length?"No tokens match.":"No API tokens yet - New token in the banner makes one."),C=e=>x.peek().find(t=>t.id===e);async function J(){try{const[e,t]=await Promise.all([g.apiTokens.list(),g.projects.list().catch(()=>[])]);if(!O())return;x.value=Array.isArray(e)?e:[],j.value=Array.isArray(t)?t:[],F.value="",ke()}catch(e){F.value=`Could not load the tokens: ${e.message||e}`}finally{R.value=!1}}const $=async()=>{Me(De),O()&&await J()};async function W(e,t){if(!(!t&&!await E.confirm(`Switch off "${L(e.name)}"? Callers using it are refused until it is switched back on.`)))try{await g.apiTokens.update(e.id,{enabled:t}),E.toast(`"${e.name}" ${t?"switched on":"switched off"}.`,{type:"success"}),await $()}catch(a){E.toast(`Not changed: ${a.message||a}`,{type:"error"})}}async function me(e){if(await E.confirm(`Revoke "${L(e.name)}"? Anything using it loses access at once. This cannot be undone - a new token would have a different value.`))try{await g.apiTokens.revoke(e.id),E.toast(`Revoked "${e.name}".`,{type:"success"}),await $()}catch(t){E.toast(`Not revoked: ${t.message||t}`,{type:"error"})}}let b=null,y=null;const T=new Set;let ve=!1;function G(e,t,a){const s=e.close.bind(e);let o=!1,u=!1;return e.close=async v=>{if(!o&&v!==!0&&t()){if(u)return;u=!0;const N=await E.confirm(a);if(u=!1,!N)return}return o=!0,s()},()=>{o=!0}}function A(e=null,t=null){const a=e?C(e):null;if(e&&!a){E.toast("That token is no longer there.",{type:"warning"});return}const s=!a,o=j.peek();if(s&&!o.length){E.toast("Make a project first - a token works inside one.",{type:"warning"});return}const u={name:a?.name??"",project:a?.project??(h.peek()||o[0]?.slug||""),expires:Pe(a?.expiresAt),scopes:Ne(a?.scopes),enabled:a?a.enabled!==!1:!0,draftsOnly:a?a.draftsOnly===!0:!1,...t||{}},v=Object.fromEntries(Object.entries(u).map(([n,i])=>[n,M.observable(i)])),N=n=>JSON.stringify(Object.fromEntries(Object.entries(n).map(([i,z])=>[i,typeof z=="boolean"?z:String(z??"")]))),ee=()=>Object.fromEntries(Object.keys(v).map(n=>[n,v[n].peek()])),ge=N(u),te=()=>N(ee())!==ge||!!t,P=M.observable(!1),B=M.computed(()=>Ie(Object.fromEntries(Object.keys(v).map(n=>[n,v[n].value])),{isNew:s,projects:j.value.map(n=>n.slug)})),q=n=>M.computed(()=>B.value.errors[n]||""),Ee=a?ce(a):null,ae={...v,saving:P,isNew:s,notNew:!s,nameErr:q("name"),projectErr:q("project"),scopesErr:q("scopes"),expiresErr:q("expires"),cannot:M.computed(()=>P.value||Object.keys(B.value.errors).length>0),saveText:s?"Create token":"Save",fixedProject:a?`${a.project} - fixed for the token's life (revoke and make a new one to move it)`:"",hint:a?`dcms_\u2026${a.tokenHint||"????"}${Ee?.state==="expired"?" - expired: set a later date to bring it back":""}`:""},f=E.slideover({title:s?"New API token":`Edit ${L(a.name)}`,size:"md",position:"right"}),w=pe(`
11
+ </div>`,O=y=>String(y??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function je(y){const k=document.createElement("template");return k.innerHTML=y.trim(),k.content.firstElementChild}async function oe(y){try{return await navigator.clipboard.writeText(y),!0}catch{return!1}}const b=ze(Ee);export const apiTokensView={templateUrl:"/admin/js/templates/api-tokens.html",async onMount(y){b.reset();const k=y.get(0).querySelector(".atx")||y.get(0),Y=()=>Ee.test(location.hash)&&k.isConnected,R=M.observable([]),B=M.observable([]),X=M.observable(!0),Z=M.observable("");let se="all";try{se=Ke.includes(S.get(ne))?S.get(ne):"all"}catch{}const v=M.observable(se),L=M.observable(""),ie=M.observable("");b.add(M.effect(()=>{const e=v.value;try{S.set(ne,e)}catch{}}));const ee=M.observable([]);b.add(M.effect(()=>{const e=Date.now();ee.value=He(R.value,{filter:v.value,project:L.value,query:ie.value},e).map(t=>at(t,e))}));const le=M.computed(()=>Ye(R.value)),Ce=M.computed(()=>R.value.length?"No tokens match.":"No API tokens yet - New token in the banner makes one."),F=e=>R.peek().find(t=>t.id===e);async function ce(){try{const[e,t]=await Promise.all([C.apiTokens.list(),C.projects.list().catch(()=>[])]);if(!Y())return;R.value=Array.isArray(e)?e:[],B.value=Array.isArray(t)?t:[],Z.value="",$e()}catch(e){Z.value=`Could not load the tokens: ${e.message||e}`}finally{X.value=!1}}const J=async()=>{Ue(lt),Y()&&await ce()};async function re(e,t){if(!(!t&&!await E.confirm(`Switch off "${O(e.name)}"? Callers using it are refused until it is switched back on.`)))try{await C.apiTokens.update(e.id,{enabled:t}),E.toast(`"${e.name}" ${t?"switched on":"switched off"}.`,{type:"success"}),await J()}catch(o){E.toast(`Not changed: ${o.message||o}`,{type:"error"})}}async function Se(e){if(await E.confirm(`Revoke "${O(e.name)}"? Anything using it loses access at once. This cannot be undone - a new token would have a different value.`))try{await C.apiTokens.revoke(e.id),E.toast(`Revoked "${e.name}".`,{type:"success"}),await J()}catch(t){E.toast(`Not revoked: ${t.message||t}`,{type:"error"})}}let $=null,N=null;const _=new Set;let Te=!1;function de(e,t,o){const u=e.close.bind(e);let w=!1,h=!1;return e.close=async s=>{if(!w&&s!==!0&&t()){if(h)return;h=!0;const c=await E.confirm(o);if(h=!1,!c)return}return w=!0,u()},()=>{w=!0}}function U(e=null,t=null){const o=e?F(e):null;if(e&&!o){E.toast("That token is no longer there.",{type:"warning"});return}const u=!o,w=B.peek();if(u&&!w.length){E.toast("Make a project first - a token works inside one.",{type:"warning"});return}const h={name:o?.name??"",project:o?.project??(L.peek()||w[0]?.slug||""),expires:tt(o?.expiresAt),scopes:et(o?.scopes),enabled:o?o.enabled!==!1:!0,draftsOnly:o?o.draftsOnly===!0:!1,bot:!1,botEdit:!1,...t||{}},s=Object.fromEntries(Object.entries(h).map(([a,i])=>[a,M.observable(i)])),c=a=>JSON.stringify(Object.fromEntries(Object.entries(a).map(([i,n])=>[i,typeof n=="boolean"?n:String(n??"")]))),z=()=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a].peek()])),K=c(h),H=()=>c(z())!==K||!!t,f=M.observable(!1),d=M.computed(()=>Ge(Object.fromEntries(Object.keys(s).map(a=>[a,s[a].value])),{isNew:u,projects:B.value.map(a=>a.slug)})),p=a=>M.computed(()=>d.value.errors[a]||""),V=o?ge(o):null,l={list:[],chosen:new Set,content:new Set,mayOpen:!0,project:null},W=M.computed(()=>u&&s.bot.value===!0),he={...s,saving:f,isNew:u,notNew:!u,botOn:W,botOff:M.computed(()=>!W.value),nameErr:p("name"),projectErr:p("project"),scopesErr:p("scopes"),expiresErr:p("expires"),cannot:M.computed(()=>f.value||Object.keys(d.value.errors).length>0),saveText:u?"Create token":"Save",fixedProject:o?`${o.project} - fixed for the token's life (revoke and make a new one to move it)`:"",hint:o?`dcms_\u2026${o.tokenHint||"????"}${V?.state==="expired"?" - expired: set a later date to bring it back":""}`:""},g=E.slideover({title:u?"New API token":`Edit ${O(o.name)}`,size:"md",position:"right"}),j=je(`
12
12
  <div class="atx-form">
13
13
  <div>
14
14
  <label class="form-label" for="atx-f-name">Name <span class="text-danger">*</span></label>
@@ -25,7 +25,17 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
25
25
  <label class="form-label">Token</label>
26
26
  <div class="atx-fixed"><code data-bind-text="hint"></code><br><span data-bind-text="fixedProject"></span></div>
27
27
  </div>
28
- <div>
28
+ <div class="atx-setting" data-bind-hidden="notNew">
29
+ <label class="form-label" for="atx-f-bot">Bot that writes drafts
30
+ <span data-help-title="Bot that writes drafts" data-help="For Grok, a script or another site that writes content for you. Tick the collections it may write to: the token is scoped to them with Drafts only on, and each one is opened to tokens (never wider than it is). A collection without a draft status gets a Status field (draft / published). Everything the bot writes waits as a draft for a person to publish."></span></label>
31
+ <input id="atx-f-bot" type="checkbox" class="form-switch" data-model="bot.value">
32
+ </div>
33
+ <div class="atx-recipe" data-bind-hidden="botOff.value">
34
+ <div class="atx-recipe-content"></div>
35
+ <div class="atx-recipe-list"><small class="atx-hint">Loading the collections\u2026</small></div>
36
+ <label class="atx-recipe-edit"><input type="checkbox" data-model="botEdit.value"> It may also change its own drafts (never a published entry)</label>
37
+ </div>
38
+ <div data-bind-hidden="botOn.value">
29
39
  <label class="form-label" for="atx-f-scopes">Scopes
30
40
  <span data-help-title="Scopes" data-help="Leave empty and the token may use every collection in its project that allows token access, and the Content API where it is set to API tokens. Otherwise one line each: a collection's slug, then a colon and the verbs it may use - create, read, update, delete (no verbs means all four), for example jobs: read. For the Content API, a line of @pages, @menus, @site or @search - read-only, no verbs. A token with only collection lines gets no content."></span></label>
31
41
  <textarea id="atx-f-scopes" class="form-input font-mono" rows="4" placeholder="jobs: read&#10;enquiries: create, read&#10;@pages" data-model="scopes.value"></textarea>
@@ -37,7 +47,7 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
37
47
  <input id="atx-f-expires" type="datetime-local" class="form-input" data-model="expires.value">
38
48
  <small class="atx-err" data-bind-hidden="!expiresErr.value" data-bind-text="expiresErr.value"></small>
39
49
  </div>
40
- <div class="atx-setting">
50
+ <div class="atx-setting" data-bind-hidden="botOn.value">
41
51
  <label class="form-label" for="atx-f-drafts">Drafts only
42
52
  <span data-help-title="Drafts only" data-help="For a bot or another site writing on your behalf. Everything it creates is saved as a draft, whatever it sends, so nothing reaches the public until a person publishes it. It may change or delete its drafts but never a published entry, and it cannot write to a collection that has no draft status (a Status field with a draft option, as Blog posts have)."></span></label>
43
53
  <input id="atx-f-drafts" type="checkbox" class="form-switch" data-model="draftsOnly.value">
@@ -54,7 +64,7 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
54
64
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">
55
65
  <span data-icon="check" data-icon-size="13"></span> <span data-bind-text="saveText"></span></button>
56
66
  </div>
57
- </div>`),ne=w.querySelector("#atx-f-project");for(const n of o){const i=document.createElement("option");i.value=n.slug,i.textContent=`${n.name||n.slug} (${n.slug})`,ne.appendChild(i)}let K=()=>{};async function se(){if(ae.cannot.peek())return;P.value=!0;const{payload:n}=B.peek();try{if(s){const i=await g.apiTokens.create(n);K(),f.close(),await $(),he(i?.plaintext,n.name)}else await g.apiTokens.update(a.id,n),E.toast("Saved.",{type:"success"}),K(),f.close(),await $()}catch(i){E.toast(`Not saved: ${i.message||i}`,{type:"error"})}finally{P.value=!1}}f.element.appendChild(w);const je=ie(w),Se=M.applyBindings(ae,w,{methods:{save:se,cancel:()=>f.close()}});ne.value=v.project.peek();const Ce=n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),se())};w.addEventListener("keydown",Ce);const oe={id:a?.id??null,dirty:te,values:ee};b=oe,T.add(f),le(f,()=>{Se.dispose(),je(),T.delete(f),b===oe&&(b=null)}),K=G(f,te,"Discard the changes you have not saved?"),I.scan(w),f.open(),w.querySelector("#atx-f-name")?.focus()}function he(e,t){if(!e){E.toast("The token was made, but its value did not come back - revoke it and make another.",{type:"error"});return}let a=!1;const s=E.slideover({title:"Token created",size:"sm",position:"right"}),o=pe(`
67
+ </div>`),me=j.querySelector("#atx-f-project");for(const a of w){const i=document.createElement("option");i.value=a.slug,i.textContent=`${a.name||a.slug} (${a.slug})`,me.appendChild(i)}const qe=j.querySelector(".atx-recipe-content");for(const a of Je){const i=document.createElement("label");i.className=`atx-recipe-row is-${a.resource==="pages"?"ok":"attention"}`;const n=document.createElement("input");n.type="checkbox",n.addEventListener("change",()=>{n.checked?l.content.add(a.resource):l.content.delete(a.resource)});const m=document.createElement("span"),r=document.createElement("strong");r.textContent=a.label;const q=document.createElement("small");q.textContent=a.note,m.append(r,document.createElement("br"),q),i.append(n,m),qe.appendChild(i)}const P=j.querySelector(".atx-recipe-list");function be(){const a=Xe(l.list,l.chosen,{edit:s.botEdit.peek()}).filter(n=>n.ok);if(P.replaceChildren(),!l.mayOpen){const n=document.createElement("small");n.className="atx-err",n.textContent="A bot token opens its collections to tokens, which needs permission to change collections (collections.update).",P.appendChild(n)}if(!a.length){const n=document.createElement("small");n.className="atx-hint",n.textContent="No collection in this project can take a bot. Make one, or pick another project.",P.appendChild(n)}for(const n of a){const m=document.createElement("label");m.className=`atx-recipe-row is-${n.tone}${n.ok?"":" is-off"}`;const r=document.createElement("input");r.type="checkbox",r.checked=n.chosen,r.disabled=!n.ok||!l.mayOpen,r.addEventListener("change",()=>{r.checked?l.chosen.add(n.slug):l.chosen.delete(n.slug)});const q=document.createElement("span"),ae=document.createElement("strong");ae.textContent=n.title;const D=document.createElement("code");D.textContent=n.slug;const G=document.createElement("small");G.textContent=n.note,q.append(ae," ",D,document.createElement("br"),G),m.append(r,q),P.appendChild(m)}const i=Ze(l.list);if(i){const n=document.createElement("small");n.className="atx-hint",n.textContent=i,P.appendChild(n)}}async function Ie(){const a=s.project.peek();if(!(!u||!s.bot.peek()||!a||l.project===a)){l.project=a,l.chosen.clear();try{const i=await C.apiTokens.recipe(a);if(l.project!==a)return;l.list=i?.collections||[],l.mayOpen=i?.mayOpen!==!1}catch(i){l.list=[],P.textContent=`Could not load the collections: ${i.message||i}`;return}be()}}const Re=[M.effect(()=>{s.bot.value,s.project.value,Ie()}),M.effect(()=>{s.botEdit.value,l.list.length&&be()})];let te=()=>{};async function ve(){if(he.cannot.peek())return;const{payload:a}=d.peek();let i=a;if(W.peek()){const n=We(l.list,l.chosen,{edit:s.botEdit.peek()}),m=Ve([...l.content],{edit:s.botEdit.peek()});if(!n&&!m.length){E.toast("Tick at least one thing for the bot to write.",{type:"warning"});return}i={...a,scopes:m,draftsOnly:!0,recipe:n||{collections:[]}}}f.value=!0;try{if(u){let n;try{n=await C.apiTokens.create(i)}catch(r){if(r.status!==409||!Array.isArray(r.body?.others))throw r;const q=r.body.others.map(D=>`<li><strong>${O(D.slug)}</strong> (${O(D.verb)}): ${D.tokens.map(G=>`${O(G.name)}${G.draftsOnly?" (drafts only)":" - <em>may publish</em>"}`).join(", ")}</li>`).join("");if(!await E.confirm(`Opening these collections to tokens also lets these existing tokens write to them:<ul>${q}</ul>Narrow those tokens' scopes first if they should not. Go ahead anyway?`)){f.value=!1;return}n=await C.apiTokens.create({...i,recipe:{...i.recipe,confirmOthers:!0}})}te(),g.close(),await J();const m=W.peek()&&l.list.some(r=>l.chosen.has(r.slug)&&r.hasAuthor);Oe(n?.plaintext,a.name,{token:n?.token,report:Qe(n?.collections||[]),authorId:m&&Fe()?.id||null})}else await C.apiTokens.update(o.id,a),E.toast("Saved.",{type:"success"}),te(),g.close(),await J()}catch(n){E.toast(`Not saved: ${n.message||n}`,{type:"error"})}finally{f.value=!1}}g.element.appendChild(j);const Pe=ke(j),De=M.applyBindings(he,j,{methods:{save:ve,cancel:()=>g.close()}});me.value=s.project.peek();const Be=a=>{(a.ctrlKey||a.metaKey)&&a.key==="Enter"&&(a.preventDefault(),ve())};j.addEventListener("keydown",Be);const ye={id:o?.id??null,dirty:H,values:z};$=ye,_.add(g),xe(g,()=>{for(const a of Re)try{typeof a=="function"?a():a?.dispose?.()}catch{}De.dispose(),Pe(),_.delete(g),$===ye&&($=null)}),te=de(g,H,"Discard the changes you have not saved?"),I.scan(j),g.open(),j.querySelector("#atx-f-name")?.focus()}function Oe(e,t,{token:o=null,report:u=[],authorId:w=null}={}){if(!e){E.toast("The token was made, but its value did not come back - revoke it and make another.",{type:"error"});return}let h=!1;const s=E.slideover({title:"Token created",size:"sm",position:"right"}),c=je(`
58
68
  <div class="atx-secret">
59
69
  <p class="atx-warn"><strong>Copy it now.</strong> This is the only time it is shown - only a fingerprint is kept. If it is lost, revoke it and make another.</p>
60
70
  <code class="atx-token"></code>
@@ -64,4 +74,21 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
64
74
  <button type="button" class="btn btn-sm btn-primary atx-copy"><span data-icon="copy" data-icon-size="13"></span> Copy</button>
65
75
  <button type="button" class="btn btn-sm btn-ghost atx-done">Done</button>
66
76
  </div>
67
- </div>`);o.querySelector(".atx-token").textContent=e,o.querySelector(".atx-copy").addEventListener("click",async()=>{await ue(e)?(a=!0,o.querySelector(".copied-note").hidden=!1):E.toast("Copy failed - select the token and copy it by hand.",{type:"error"})}),o.querySelector(".atx-done").addEventListener("click",()=>s.close()),s.element.appendChild(o);const u={copied:()=>a};s.__dmSecret=!0,y=u,T.add(s),le(s,()=>{T.delete(s),y===u&&(y=null),e=null}),G(s,()=>!a,`You have not copied the token for "${L(t)}". Once this closes it can never be shown again. Close anyway?`),I.scan(o),s.open()}function be(e){const t=C(e);if(!t)return[];const{state:a}=ce(t);return[{header:t.name||"Token"},{label:"Edit\u2026",icon:"edit",action:()=>A(t.id)},t.enabled===!1?{label:"Switch on",icon:"play",action:()=>W(t,!0)}:{label:"Switch off\u2026",icon:"pause",disabled:a==="expired",action:()=>W(t,!1)},{type:"divider"},{label:"Copy its ending",icon:"copy",action:async()=>{E.toast(await ue(`dcms_\u2026${t.tokenHint||""}`)?"Copied the ending - the token itself is never shown again.":"Copy failed.",{type:"info"})}},{label:`Show only ${t.project}`,icon:"filter",disabled:h.peek()===t.project,action:()=>{h.value=t.project,ye()}},{type:"divider"},{label:"Revoke\u2026",icon:"trash",danger:!0,action:()=>me(t)}]}const m=d.querySelector(".atx-list");m.innerHTML=Re;const k=d.querySelector(".atx-project"),ye=()=>{k&&(k.value=h.peek())};function ke(){if(!k)return;const e=h.peek();for(;k.options.length>1;)k.remove(1);for(const t of j.peek()){const a=document.createElement("option");a.value=t.slug,a.textContent=t.name||t.slug,k.appendChild(a)}k.value=e}const we=M.applyBindings({tokens:x,projects:j,loading:R,loadError:F,filter:r,project:h,query:Y,rows:_,counts:V,emptyText:fe},d,{methods:{showAll:()=>{r.value="all"},showActive:()=>{r.value="active"},showExpiring:()=>{r.value="expiring"},showExpired:()=>{r.value="expired"},showDisabled:()=>{r.value="disabled"}}});l.add(()=>we.dispose()),l.add(ie(d,{position:"bottom"})),l.add(M.effect(()=>{_.value,requestAnimationFrame(()=>{m.isConnected&&I.scan(m)})})),l.add(M.effect(()=>{const e=V.value,t=r.peek();t!=="all"&&!R.value&&!e[t]&&(r.value="all")}));const xe=E.contextMenu(m,{cursor:"glyph",match:".atx-row",inherit:!1,density:"compact",items:e=>be(e.dataset.id)});l.add(()=>xe?.destroy?.());const Q=e=>{const t=e.target.closest(".atx-row");if(!t)return;const a=e.target.closest(".atx-kebab");if(a){re(a);return}A(t.dataset.id)},X=e=>{const t=e.target.closest(".atx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),re(t)):e.key==="Enter"&&e.target===t&&A(t.dataset.id))};m.addEventListener("click",Q),m.addEventListener("keydown",X),l.add(()=>{m.removeEventListener("click",Q),m.removeEventListener("keydown",X)}),Te(c,{id:"api-tokens-new",icon:"plus",title:"New token",onClick:()=>A()});const Z=e=>{(b?.dirty()||y&&!y.copied())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Z),l.add(()=>window.removeEventListener("beforeunload",Z)),l.add(()=>{if(b?.dirty())try{S.set(D,{id:b.id,values:b.values(),at:new Date().toISOString()})}catch{}ve=!0,[...T].forEach(e=>{if(!(y&&e.__dmSecret&&!y.copied()))try{e.close(!0)}catch{}})}),I.scan(d),await J(),!O())return;let p=null;try{p=S.get(D)}catch{}if(p?.values){try{S.remove?S.remove(D):S.set(D,null)}catch{}const e=p.id&&C(p.id)?`your changes to "${L(C(p.id).name)}"`:"the new token you started";await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&O()&&A(p.id&&C(p.id)?p.id:null,p.values)}}};
77
+ <div class="atx-handover">
78
+ <p class="atx-hint">Giving it to someone else, or to a bot? Send a one-time link instead of the token - it opens once, within 24 hours, and shows them how to use it. Or download the connection file a script can read.</p>
79
+ <div class="atx-actions">
80
+ <button type="button" class="btn btn-sm btn-secondary atx-link"><span data-icon="link" data-icon-size="13"></span> Make a one-time link</button>
81
+ <button type="button" class="btn btn-sm btn-ghost atx-file"><span data-icon="download" data-icon-size="13"></span> Connection file</button>
82
+ </div>
83
+ <div class="atx-link-out" hidden>
84
+ <code class="atx-link-text"></code>
85
+ <div class="atx-actions">
86
+ <small class="atx-hint atx-link-note"></small>
87
+ <span class="atx-spacer"></span>
88
+ <button type="button" class="btn btn-sm btn-primary atx-link-copy"><span data-icon="copy" data-icon-size="13"></span> Copy link</button>
89
+ </div>
90
+ </div>
91
+ </div>
92
+ <ul class="atx-report" hidden></ul>
93
+ </div>`);if(c.querySelector(".atx-token").textContent=e,u.length){const f=c.querySelector(".atx-report");for(const d of u){const p=document.createElement("li");p.textContent=d.trim(),d.startsWith(" ")&&(p.className="atx-report-warn"),f.appendChild(p)}f.hidden=!1}const z=()=>nt({origin:location.origin,token:o||{name:t},plaintext:e,authorId:w});c.querySelector(".atx-file").addEventListener("click",()=>{const f=z(),d=document.createElement("a");d.href=URL.createObjectURL(new Blob([JSON.stringify(f,null,2)+`
94
+ `],{type:"application/json"})),d.download=ot(f),document.body.appendChild(d),d.click(),setTimeout(()=>{URL.revokeObjectURL(d.href),d.remove()},1e3),h=!0});let K="";c.querySelector(".atx-link").addEventListener("click",async f=>{const d=f.currentTarget;if(!o?.id){E.toast("Make the link from a new token.",{type:"warning"});return}d.disabled=!0;try{const p=await it(z()),V=await C.apiTokens.handover(o.id,{ciphertext:p.ciphertext,iv:p.iv});K=st(location.origin,V.id,p.key),c.querySelector(".atx-link-text").textContent=K,c.querySelector(".atx-link-note").textContent=`Opens once, until ${new Date(V.expiresAt).toLocaleString("en-GB")}.`,c.querySelector(".atx-link-out").hidden=!1,h=!0}catch(p){E.toast(`No link made: ${p.message||p}`,{type:"error"}),d.disabled=!1}}),c.querySelector(".atx-link-copy").addEventListener("click",async()=>{await oe(K)?E.toast("Link copied.",{type:"success"}):E.toast("Copy failed - select the link and copy it by hand.",{type:"error"})}),c.querySelector(".atx-copy").addEventListener("click",async()=>{await oe(e)?(h=!0,c.querySelector(".copied-note").hidden=!1):E.toast("Copy failed - select the token and copy it by hand.",{type:"error"})}),c.querySelector(".atx-done").addEventListener("click",()=>s.close()),s.element.appendChild(c);const H={copied:()=>h};s.__dmSecret=!0,N=H,_.add(s),xe(s,()=>{_.delete(s),N===H&&(N=null),e=null}),de(s,()=>!h,`You have not copied the token for "${O(t)}". Once this closes it can never be shown again. Close anyway?`),I.scan(c),s.open()}function Me(e){const t=F(e);if(!t)return[];const{state:o}=ge(t);return[{header:t.name||"Token"},{label:"Edit\u2026",icon:"edit",action:()=>U(t.id)},t.enabled===!1?{label:"Switch on",icon:"play",action:()=>re(t,!0)}:{label:"Switch off\u2026",icon:"pause",disabled:o==="expired",action:()=>re(t,!1)},{type:"divider"},{label:"Copy its ending",icon:"copy",action:async()=>{E.toast(await oe(`dcms_\u2026${t.tokenHint||""}`)?"Copied the ending - the token itself is never shown again.":"Copy failed.",{type:"info"})}},{label:`Show only ${t.project}`,icon:"filter",disabled:L.peek()===t.project,action:()=>{L.value=t.project,Le()}},{type:"divider"},{label:"Revoke\u2026",icon:"trash",danger:!0,action:()=>Se(t)}]}const T=k.querySelector(".atx-list");T.innerHTML=ct;const A=k.querySelector(".atx-project"),Le=()=>{A&&(A.value=L.peek())};function $e(){if(!A)return;const e=L.peek();for(;A.options.length>1;)A.remove(1);for(const t of B.peek()){const o=document.createElement("option");o.value=t.slug,o.textContent=t.name||t.slug,A.appendChild(o)}A.value=e}const Ne=M.applyBindings({tokens:R,projects:B,loading:X,loadError:Z,filter:v,project:L,query:ie,rows:ee,counts:le,emptyText:Ce},k,{methods:{showAll:()=>{v.value="all"},showActive:()=>{v.value="active"},showExpiring:()=>{v.value="expiring"},showExpired:()=>{v.value="expired"},showDisabled:()=>{v.value="disabled"}}});b.add(()=>Ne.dispose()),b.add(ke(k,{position:"bottom"})),b.add(M.effect(()=>{ee.value,requestAnimationFrame(()=>{T.isConnected&&I.scan(T)})})),b.add(M.effect(()=>{const e=le.value,t=v.peek();t!=="all"&&!X.value&&!e[t]&&(v.value="all")}));const Ae=E.contextMenu(T,{cursor:"glyph",match:".atx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});b.add(()=>Ae?.destroy?.());const pe=e=>{const t=e.target.closest(".atx-row");if(!t)return;const o=e.target.closest(".atx-kebab");if(o){we(o);return}U(t.dataset.id)},ue=e=>{const t=e.target.closest(".atx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),we(t)):e.key==="Enter"&&e.target===t&&U(t.dataset.id))};T.addEventListener("click",pe),T.addEventListener("keydown",ue),b.add(()=>{T.removeEventListener("click",pe),T.removeEventListener("keydown",ue)}),_e(y,{id:"api-tokens-new",icon:"plus",title:"New token",onClick:()=>U()});const fe=e=>{($?.dirty()||N&&!N.copied())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",fe),b.add(()=>window.removeEventListener("beforeunload",fe)),b.add(()=>{if($?.dirty())try{S.set(Q,{id:$.id,values:$.values(),at:new Date().toISOString()})}catch{}Te=!0,[..._].forEach(e=>{if(!(N&&e.__dmSecret&&!N.copied()))try{e.close(!0)}catch{}})}),I.scan(k),await ce(),!Y())return;let x=null;try{x=S.get(Q)}catch{}if(x?.values){try{S.remove?S.remove(Q):S.set(Q,null)}catch{}const e=x.id&&F(x.id)?`your changes to "${O(F(x.id).name)}"`:"the new token you started";await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&Y()&&U(x.id&&F(x.id)?x.id:null,x.values)}}};