@heyo-sh/heyo-cms 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/adapters/astro.js +1 -1
  2. package/dist/ai/assistant/schema.d.ts +10 -0
  3. package/dist/ai/assistant/schema.d.ts.map +1 -1
  4. package/dist/ai/service.d.ts.map +1 -1
  5. package/dist/ai.js +1 -1
  6. package/dist/auth.js +1 -1
  7. package/dist/cli.js +2 -2
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/config.js +1 -1
  10. package/dist/content/import.d.ts.map +1 -1
  11. package/dist/content.js +1 -1
  12. package/dist/db/d1.js +1 -1
  13. package/dist/db/mongodb.d.ts +2 -1
  14. package/dist/db/mongodb.d.ts.map +1 -1
  15. package/dist/db/mongodb.js +2 -2
  16. package/dist/db/postgres.js +1 -1
  17. package/dist/db/sql/adapter.d.ts.map +1 -1
  18. package/dist/db/sql/dialect.d.ts +3 -0
  19. package/dist/db/sql/dialect.d.ts.map +1 -1
  20. package/dist/db/sqlite.js +1 -1
  21. package/dist/db/unique.d.ts +46 -0
  22. package/dist/db/unique.d.ts.map +1 -0
  23. package/dist/editor.js +1 -1
  24. package/dist/engine/documents.d.ts.map +1 -1
  25. package/dist/fields/builtin.d.ts +44 -1
  26. package/dist/fields/builtin.d.ts.map +1 -1
  27. package/dist/fields/registry.d.ts.map +1 -1
  28. package/dist/fields.js +1 -1
  29. package/dist/http/routes/ai.d.ts +1 -1
  30. package/dist/http.js +1 -1
  31. package/dist/index-0fe3ngv2.js +2 -0
  32. package/dist/index-1xwmw8vb.js +3 -0
  33. package/dist/{index-vkwzdfte.js → index-2djaxtj8.js} +4 -4
  34. package/dist/{index-8x2em6c8.js → index-2j6d79fk.js} +7 -7
  35. package/dist/{index-kc1j3h6z.js → index-2zpnecrk.js} +2 -2
  36. package/dist/{index-761dec5z.js → index-344y6q4n.js} +2 -2
  37. package/dist/index-4j1kkeg2.js +2 -0
  38. package/dist/{index-2prbs05k.js → index-5j0cqm43.js} +2 -2
  39. package/dist/index-5yt6r97r.js +40 -0
  40. package/dist/{index-a8jcwqsf.js → index-78f0ghve.js} +2 -2
  41. package/dist/{index-szaq03qq.js → index-8j4p950b.js} +2 -2
  42. package/dist/{index-466cwb0b.js → index-cakys3fy.js} +2 -2
  43. package/dist/{index-p2cqsmvw.js → index-cnzt9x9x.js} +2 -2
  44. package/dist/{index-abfzb1ve.js → index-e3yknwyr.js} +2 -2
  45. package/dist/index-fy8r8e53.js +2 -0
  46. package/dist/index-gv8j76x3.js +26 -0
  47. package/dist/{index-rg9tpg3p.js → index-mzxsxzkd.js} +4 -4
  48. package/dist/{index-91fa1gzf.js → index-n09v6gx3.js} +2 -2
  49. package/dist/index-pkxgzw6e.js +2 -0
  50. package/dist/{index-vzhxn50e.js → index-q6ak9ph4.js} +2 -2
  51. package/dist/{index-6m1kjq9g.js → index-q6jkbsjp.js} +2 -2
  52. package/dist/{index-8nzmqy0f.js → index-qgtvymh2.js} +2 -2
  53. package/dist/{index-s9x07zb3.js → index-qkqtxr65.js} +2 -2
  54. package/dist/{index-ypcmns0v.js → index-rb9fxtyn.js} +2 -2
  55. package/dist/{index-g041kfa5.js → index-rpdkj3qk.js} +11 -11
  56. package/dist/{index-hbx67b20.js → index-twqpdtfh.js} +3 -3
  57. package/dist/index.js +1 -1
  58. package/dist/jobs.js +1 -1
  59. package/dist/migrations.js +1 -1
  60. package/dist/query.js +1 -1
  61. package/dist/{run-bjge3v8e.js → run-mtgvmy5x.js} +2 -2
  62. package/dist/schema.js +1 -1
  63. package/dist/telemetry.js +1 -1
  64. package/dist/types/fields.d.ts +2 -2
  65. package/dist/types/fields.d.ts.map +1 -1
  66. package/dist/types/panel.d.ts +2 -0
  67. package/dist/types/panel.d.ts.map +1 -1
  68. package/dist/uploads.js +3 -3
  69. package/dist/webhooks.js +1 -1
  70. package/package.json +1 -1
  71. package/dist/index-4qrep5f0.js +0 -26
  72. package/dist/index-67e458ws.js +0 -2
  73. package/dist/index-6w10rch0.js +0 -3
  74. package/dist/index-cv0hpz3d.js +0 -2
  75. package/dist/index-hpast878.js +0 -40
  76. package/dist/index-sgdnp83t.js +0 -2
@@ -0,0 +1,2 @@
1
+ import{Z,me,_,rn,fe,j}from"./index-2j6d79fk.js";import{_e,O,A,$e,Je,vo,xo,je,gn,l,u}from"./index-pkxgzw6e.js";import{s,R,t,We,H,M,S,le,m}from"./index-q6jkbsjp.js";import{an,ye}from"./index-e3yknwyr.js";import{io,qe}from"./index-5yt6r97r.js";import{V,J,Yt,Qt}from"./index-2zpnecrk.js";import{St}from"./index-1xwmw8vb.js";import{Ae,ke}from"./index-cakys3fy.js";import{tn,nn,on}from"./index-n09v6gx3.js";import{d}from"./index-9g2n7xa6.js";import{Te}from"./index-twqpdtfh.js";import{ge,et,tt}from"./index-y8kzzn94.js";import{p,_t}from"./index-qkqtxr65.js";import{ot}from"./index-344y6q4n.js";import{pn}from"./index-5j0cqm43.js";import{w,se}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b,ve}from"./index-qgtvymh2.js";import{e,n}from"./index-x72d1hzh.js";var rt="activity",at=50,lt=200;function De(o){return{async list(i={}){let r=dt(i.limit),a=[];if(i.collection)a.push(t("collection",i.collection));if(i.documentId)a.push(t("document_id",i.documentId));if(i.actorId)a.push(t("actor_id",i.actorId));if(i.action)a.push(t("action",i.action));if(i.source)a.push(t("source",i.source));if(i.cursor)a.push(H("id",i.cursor));let c=await o.database(),f=await c.transaction((v)=>c.query(v,{table:rt,...a.length===0?{}:{where:s(...a)},orderBy:[{path:"id",direction:"desc"}],limit:r+1})),h=f.length>r,g=f.slice(0,r),C=g.at(-1);return{entries:g.map(ct),limit:r,hasNextPage:h,cursor:h&&C?String(C.id):null}}}}function ct(o){let i=o.changes===null||o.changes===void 0?null:u(o.changes);return{id:String(o.id),action:String(o.action),actorId:Y(o.actor_id),actorSource:Y(o.actor_source),source:Y(o.source),collection:Y(o.collection),documentId:Y(o.document_id),locale:Y(o.locale),changes:i,ip:Y(o.ip),createdAt:l(o.created_at)}}function Y(o){return o===null||o===void 0?null:String(o)}function dt(o){if(o===void 0)return at;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,lt)}function ut(o,i){let r={createBefore:[],createAfter:[],updateBefore:[],updateAfter:[],deleteBefore:[],deleteAfter:[]},a=o.plugins.flatMap((f)=>(f.hooks??[]).filter((h)=>h.collection===i).map((h)=>({plugin:f.id,hook:h}))).sort((f,h)=>(f.hook.priority??0)-(h.hook.priority??0)||f.plugin.localeCompare(h.plugin));for(let{plugin:f,hook:h}of a){let g={source:f,priority:h.priority??0};if(h.timing==="before"){if(h.operation==="create")r.createBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else if(h.operation==="update")r.updateBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else r.deleteBefore.push({...g,run:(v,D)=>h.handler(v,D)});continue}let C=async(v,D)=>{await h.handler(v,D)};if(h.operation==="create")r.createAfter.push({...g,run:C});else if(h.operation==="update")r.updateAfter.push({...g,run:(v,D)=>C(v.doc,D)});else r.deleteAfter.push({...g,run:C})}let c=o.pluginHooks.filter((f)=>f.collection===i).sort((f,h)=>f.priority-h.priority||f.plugin.localeCompare(h.plugin));for(let f of c)Ee(r,f.hooks,{source:f.plugin,priority:f.priority});return Ee(r,o.databaseHooks?.[i],{source:"config",priority:gt}),r}var gt=100;function Ee(o,i,r){if(i?.create?.before){let a=i.create.before;o.createBefore.push({...r,run:(c,f)=>a(c,f)})}if(i?.create?.after){let a=i.create.after;o.createAfter.push({...r,run:(c,f)=>a(c,f)})}if(i?.update?.before){let a=i.update.before;o.updateBefore.push({...r,run:async(c,f)=>await a(c,f)})}if(i?.update?.after){let a=i.update.after;o.updateAfter.push({...r,run:(c,f)=>a(c,f)})}if(i?.delete?.before){let a=i.delete.before;o.deleteBefore.push({...r,run:(c,f)=>a(c,f)})}if(i?.delete?.after){let a=i.delete.after;o.deleteAfter.push({...r,run:(c,f)=>a(c,f)})}}async function Ie(o,i,r,a){let c=i;for(let f of o){let h=await f.run(c,r);if(h===!1)return!1;if(h&&typeof h==="object"&&"data"in h)c=a(c,h.data)}return c}async function He(o,i,r){for(let a of o)await a.run(i,r)}function zt(o){let i=new Set([...Object.keys(o.collections),...Object.keys(o.globals),...o.plugins.flatMap((a)=>(a.hooks??[]).map((c)=>c.collection)),...o.pluginHooks.map((a)=>a.collection)]),r=[];for(let a of[...i].sort()){let c=ut(o,a),f=[["create","before",c.createBefore],["create","after",c.createAfter],["delete","before",c.deleteBefore],["delete","after",c.deleteAfter],["update","before",c.updateBefore],["update","after",c.updateAfter]];for(let[h,g,C]of f)for(let v of C)r.push({collection:a,operation:h,timing:g,source:v.source,priority:v.priority})}return r}var vt="jobs",wt=100,Ct={name:"scheduled-changes",failureType:"document.schedule",failurePayload:(o)=>{let i=je(o);return{collection:String(o.collection),documentId:String(o.id),...i===null?{}:{locale:i.locale,patch:i.data},...o.scheduled_at instanceof Date?{scheduledFor:o.scheduled_at.toISOString()}:{}}},due:async(o,i,r)=>{let a=await o.database();return a.transaction((c)=>a.query(c,{table:p,where:s(le("scheduled_at",!0),M("scheduled_at",i),t("deleted_at",null)),orderBy:[m("scheduled_at","asc"),m("id","asc")],limit:r}))},run:(o,i)=>o.applyScheduled(i)},kt={name:"trash-purge",failureType:"trash.purge",failurePayload:(o)=>({collection:String(o.collection),documentId:String(o.id)}),due:async(o,i,r)=>{if(o.config.trash.purgeAfter===!1)return[];let a=await o.database();return a.transaction((c)=>a.query(c,{table:p,where:s(le("deleted_at",!0),le("purge_after",!0),M("purge_after",i)),orderBy:[m("purge_after","asc"),m("id","asc")],limit:r}))},run:(o,i)=>o.purgeExpired(i)};class pt{host;jobs=[Ct,kt];constructor(o){this.host=o}list(){return this.jobs.map((o)=>o.name)}register(o){this.jobs.push(o)}async run(o={}){let i=o.now??new Date,r=o.limit??wt,a=o.only?this.jobs.filter((f)=>o.only?.includes(f.name)):this.jobs,c=[];for(let f of a){let h=await f.due(this.host,i,r+1),g=h.slice(0,r),C=0,v=0;for(let D of g)try{await f.run(this.host,D,i),C+=1}catch(I){v+=1,await this.host.recordFailure(f.failureType,f.failurePayload(D),I).catch(()=>{return})}c.push({job:f.name,processed:C,failed:v,more:h.length>r})}return{ranAt:i.toISOString(),processed:c.reduce((f,h)=>f+h.processed,0),failed:c.reduce((f,h)=>f+h.failed,0),results:c}}async failures(o={}){let i=await this.host.database();return(await i.transaction((a)=>i.query(a,{table:vt,where:o.type===void 0?t("status","failed"):s(t("status","failed"),t("type",o.type)),orderBy:[m("created_at","desc"),m("id","desc")],limit:o.limit??50}))).map((a)=>({id:String(a.id),type:String(a.type),payload:a.payload===null||a.payload===void 0?null:u(a.payload),error:a.error===null||a.error===void 0?null:String(a.error),attempts:Number(a.attempts??0),createdAt:l(a.created_at)}))}}var oe="outbox";class mt{queued=[];emit(o,i,r=null){this.queued.push({type:o,data:i,previous:r})}take(){return this.queued.splice(0,this.queued.length)}}class ft{adapter;dispatch;maxAttempts;backoff;leaseMs;now;constructor(o,i,r={}){this.adapter=o;this.dispatch=i;this.maxAttempts=r.maxAttempts??5,this.backoff=r.backoff??((a)=>1000*2**(a-1)),this.leaseMs=r.leaseMs??300000,this.now=r.now??(()=>new Date)}async append(o,i,r){let a=this.now();for(let c of i)await this.adapter.mutate(o,{kind:"insert",table:oe,returning:!1,values:{id:ve("obx"),event_id:b("evt"),type:c.type,payload:c.data,previous:c.previous,actor:r.actor?{id:r.actor.id,source:r.actor.source}:null,collection:r.collection??null,document_id:r.documentId??null,status:"pending",attempts:0,available_at:a,processed_at:null,error:null,created_at:a}})}async drain(o=50){let i=await this.adapter.transaction((a)=>this.adapter.query(a,{table:oe,where:s(S("status",["pending","delivering"]),M("available_at",this.now())),orderBy:[m("created_at","asc"),m("id","asc")],limit:o})),r=0;for(let a of i){if(await this.hasPredecessor(a))continue;let c=await this.claim(a);if(!c)continue;if(Number(c.attempts)>this.maxAttempts){await this.settle(c,!1,Error("Delivery lease expired; attempt budget exhausted."));continue}try{await this.dispatch(At(c)),await this.settle(c,!0),r+=1}catch(f){await this.settle(c,!1,f)}}return r}async hasPredecessor(o){if(!o.document_id)return!1;return(await this.adapter.transaction((r)=>this.adapter.query(r,{table:oe,where:s(t("collection",o.collection==null?null:String(o.collection)),t("document_id",String(o.document_id)),H("id",String(o.id)),S("status",["pending","delivering"])),limit:1}))).length>0}async claim(o){let i={status:"delivering",attempts:Number(o.attempts??0)+1,available_at:new Date(this.now().getTime()+this.leaseMs)};return(await this.adapter.transaction((a)=>this.adapter.mutate(a,{kind:"update",table:oe,where:s(t("id",String(o.id)),t("status",String(o.status)),t("attempts",Number(o.attempts??0)),M("available_at",this.now())),set:i,returning:!1}))).count===1?{...o,...i}:null}async settle(o,i,r){let a=Number(o.attempts??0),c=a>=this.maxAttempts,f=i?{status:"delivered",attempts:a,processed_at:this.now(),error:null}:{status:c?"failed":"pending",attempts:a,available_at:new Date(this.now().getTime()+this.backoff(a)),error:r instanceof Error?r.message:String(r)};await this.adapter.transaction((h)=>this.adapter.mutate(h,{kind:"update",table:oe,where:s(t("id",String(o.id)),t("status","delivering"),t("attempts",a)),set:f,returning:!1}))}}function At(o){let i=u(o.actor);return{id:String(o.event_id),type:String(o.type),createdAt:l(o.created_at)??new Date().toISOString(),actor:typeof i.id==="string"?{id:i.id,source:i.source==="api-key"?"api-key":"session"}:null,data:u(o.payload),previous:o.previous===null||o.previous===void 0?null:u(o.previous)}}class ht{options;cache=new Map;queries=0;constructor(o){this.options=o}get queryCount(){return this.queries}async expand(o,i,r){if(r<=0||o.length===0)return;let a=Object.entries(i.fields).map(([h,g])=>({name:h,target:xn(g)})).filter((h)=>Boolean(h.target));if(a.length===0)return;let c=new Map;for(let h of o)for(let g of a)for(let C of Rt(h[g.name])){if(this.cache.has(Q(g.target,C)))continue;let v=c.get(g.target)??new Set;v.add(C),c.set(g.target,v)}for(let[h,g]of c)await this.load(h,[...g]);let f=new Map;for(let h of o)for(let g of a){let C=h[g.name];h[g.name]=this.substitute(g.target,C,f)}for(let[h,g]of f){let C=this.options.collections[h];if(C)await this.expand(g,C,r-1)}}async load(o,i){let r=this.options.collections[o];if(this.queries+=1,r){for(let g of i)this.cache.set(Q(o,g),null);let c;try{c=await _(r,{actor:this.options.actor??null,operation:"read",locale:this.options.locale.locale,rbac:this.options.rbac})}catch(g){if(g instanceof e&&(g.status===401||g.status===403))return;throw g}let f=[c,t("collection",r.slug),S("id",i),...this.options.includeTrashed?[]:[t("deleted_at",null)]],h=await this.options.adapter.query(this.options.tx,{table:p,where:s(...f)});for(let g of i)this.cache.set(Q(o,g),null);for(let g of h){let C=A(g,r,this.options.locale);this.cache.set(Q(o,String(g.id)),fe(C,r,this.options.actor??null,this.options.locale.locale))}return}for(let c of i)this.cache.set(Q(o,c),null);if(o!=="media"&&o!=="cms_users")return;let a=await this.options.adapter.query(this.options.tx,{table:o,where:S("id",i),...o==="cms_users"?{select:["id","name"]}:{}});for(let c of i)this.cache.set(Q(o,c),null);for(let c of a)this.cache.set(Q(o,String(c.id)),xo(c))}substitute(o,i,r){let a=(c)=>{let f=structuredClone(c),h=r.get(o)??[];return h.push(f),r.set(o,h),f};if(typeof i==="string"){let c=this.cache.get(Q(o,i));return c?a(c):i}if(Array.isArray(i))return i.map((c)=>{if(typeof c!=="string")return c;let f=this.cache.get(Q(o,c));return f?a(f):c});return i??null}}function xn(o){if(o.relationTo)return o.relationTo;return o.type==="media"?"media":void 0}function Rt(o){if(typeof o==="string")return o.length>0?[o]:[];if(Array.isArray(o))return o.filter((i)=>typeof i==="string");return[]}function Q(o,i){return`${o}:${i}`}var X="slug_history",Fe=50;function he(o){let i=ee(o);if(typeof i.slugify==="function")return i.slugify;let r=i.maxLength;return(a)=>ye(a,r===void 0?{}:{maxLength:r})}function ae(o){return Object.entries(o.fields).filter(([,i])=>i.type==="slug")}function ee(o){return o.options}async function be(o){let i=ae(o.collection);if(i.length===0)return{input:o.input,moves:[]};let r={...o.input},a=[];for(let[c,f]of i){let h=ee(f),g=f.localized?o.locale:"",C=Pt(o.stored,c,f,o.locale),v=r[c],D=he(f),I;if(typeof v==="string"&&v.trim()!==""){if(I=D(v),I==="")throw e.validation(`${o.collection.name}.${c}: "${v}" has no letters or digits to make a slug from`);if(h.unique!==!1)await Ce({...o,field:c,locale:g,slug:I})}else if(v===null||v===""||v===void 0&&C===null){let F=h.from===void 0?null:Tt(o,h.from),B=F===null?"":D(F);if(B!=="")I=h.unique===!1?B:await Ot({...o,field:c,locale:g,base:B});else if(v!==void 0)I=null}if(I===void 0)continue;if(r[c]=I,h.history===!0&&C!==null&&I!==null&&I!==C)a.push({field:c,locale:g,from:C,to:I})}return{input:r,moves:a}}async function we(o,i,r,a,c){for(let f of a){let h=s(t("collection",i.name),t("field",f.field),t("locale",f.locale));if(await o.delete(X,s(h,t("document_id",r),t("slug",f.to))),await o.findOne(X,s(h,t("slug",f.from))))continue;await o.insert(X,{id:b("slg"),collection:i.name,field:f.field,locale:f.locale,slug:f.from,document_id:r,created_at:c})}}async function Le(o,i,r,a,c,f){await o.delete(X,s(t("collection",i.name),t("document_id",r),t("field",a),t("locale",c),t("slug",f)))}async function Me(o,i,r){await o.delete(X,s(t("collection",i.name),t("document_id",r)))}function xt(o){let i=o.collection.fields[o.field];return i!==void 0&&ee(i).history===!0}async function Ce(o){let i=o.locale?` in "${o.locale}"`:"",r=await Be(o,o.slug);if(r!==null)throw e.conflict(`The slug "${o.slug}" is already used${i} by another document of ${o.collection.label} (${r}).`);let a=await Ne(o,o.slug);if(a!==null)throw e.conflict(`The slug "${o.slug}" is a previous slug of another document of ${o.collection.label} (${a})${i} and redirects there. Remove it from that document's previous slugs first.`)}async function Ot(o){for(let i=1;i<=Fe;i+=1){let r=i===1?o.base:`${o.base}-${i}`;if(await Be(o,r)===null&&await Ne(o,r)===null)return r}throw e.conflict(`No free slug for "${o.base}" after ${Fe} tries; set one explicitly.`)}async function Be(o,i){let r=o.locale?`${o.field}.${o.locale}`:o.field,a=await o.db.query({table:p,where:s(t("collection",o.collection.slug),t(r,i),...o.documentId===null?[]:[We("id",o.documentId)]),limit:1});return a[0]?String(a[0].id):null}async function Ne(o,i){if(!xt(o))return null;let r=await o.db.findOne(X,s(t("collection",o.collection.name),t("field",o.field),t("locale",o.locale),t("slug",i),...o.documentId===null?[]:[We("document_id",o.documentId)]));return r?String(r.document_id):null}function Pt(o,i,r,a){if(!o)return null;let c=r.localized?u(o[i])[a]:o[i];return typeof c==="string"&&c!==""?c:null}function Tt(o,i){let r=o.collection.fields[i];if(!r)return null;let a=o.input[i],c=a!==void 0?a:r.localized?u(o.stored?.[i])[o.locale]??null:o.stored?.[i]??null;return typeof c==="string"&&c.trim()!==""?c:null}async function ze(o){let{db:i,collection:r,field:a,slug:c}=o,f=r.fields[a];if(!f||!an(c))return[];let h=f.localized,g=[],C=await i.query({table:p,where:s(t("collection",r.slug),t("deleted_at",null),h?R(...o.locales.map((I)=>t(`${a}.${I}`,c))):t(a,c)),limit:20});for(let I of C){let F=u(I.data)[a];if(!h){g.push({id:String(I.id),locale:null,current:!0});continue}for(let B of o.locales)if(u(F)[B]===c)g.push({id:String(I.id),locale:B,current:!0})}let v=[];if(ee(f).history===!0){let I=await i.find(X,s(t("collection",r.name),t("field",a),t("slug",c))),F=await Dt(i,r,I.map((B)=>String(B.document_id)));for(let B of I){let y=String(B.document_id);if(!F.has(y))continue;let P=String(B.locale??"");v.push({id:y,locale:P===""?null:P,current:!1})}}let D=(I)=>I.locale===null||I.locale===o.locale?0:1;return[...g.sort((I,F)=>D(I)-D(F)),...v.sort((I,F)=>D(I)-D(F))]}async function Dt(o,i,r){if(r.length===0)return new Set;let a=await o.query({table:p,where:s(t("collection",i.slug),t("deleted_at",null),S("id",[...new Set(r)]))});return new Set(a.map((c)=>String(c.id)))}async function Ge(o){let i=[t("collection",o.collection.name),t("document_id",o.documentId)];if(o.field!==void 0)i.push(t("field",o.field));if(o.locale!==void 0)i.push(t("locale",o.locale??""));return(await o.db.find(X,s(...i))).map((a)=>({slug:String(a.slug),field:String(a.field),locale:a.locale?String(a.locale):null,createdAt:l(a.created_at)})).sort((a,c)=>(c.createdAt??"").localeCompare(a.createdAt??"")||a.slug.localeCompare(c.slug))}var jt=25,$t=200,Se=[m("deleted_at","desc"),m("id","desc")];async function Ht(o){let{adapter:i,config:r,collections:a,args:c}=o,f=O(r,c),h=c.actor??null,g=Jt(c.limit),C=c.collection?[It(a,c.collection)]:Object.values(a),v=[],D=new Map;for(let k of C){let T;try{T=await _(k,{actor:h,operation:"read",locale:f.locale,rbac:r.rbac})}catch(L){if(c.collection)throw L;continue}D.set(k.slug,k),v.push(T?s(t("collection",k.slug),T):t("collection",k.slug))}if(v.length===0)return{entries:[],limit:g,hasNextPage:!1,cursor:null};let I=v.length===D.size&&v.every((k)=>k.kind==="compare")?S("collection",[...D.keys()]):R(...v),F=s(le("deleted_at",!0),I),B=await i.transaction((k)=>i.query(k,{table:p,where:c.cursor?s(F,J(c.cursor,Se)):F,orderBy:Se,limit:g+1})),y=B.length>g,P=B.slice(0,g),W=P.flatMap((k)=>{let T=D.get(String(k.collection));if(!T)return[];let L=A(k,T,f);if(rn(T))fe(L,T,h,f.locale);return[{collection:T.name,id:String(k.id),deletedAt:l(k.deleted_at),purgeAfter:l(k.purge_after),document:L}]}),E=P.at(-1);return{entries:W,limit:g,hasNextPage:y,cursor:E?V(E,Se):null}}function It(o,i){let r=o[i];if(!r)throw e.notFound(`No collection named "${i}"`);return r}function Jt(o){if(o===void 0)return jt;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,$t)}var Wt=25,Et=500,Ft="activity",Lt="media_usages",Ue="cms_ai_mutations",Ke={create:"create",update:"update",trash:"delete",purge:"delete",restore:"update",schedule:"update",unschedule:"update"};class yt{options;cms;pipelines=new Map;byName;bySlug;media=new Map;outbox;delivery=Promise.resolve();constructor(o){this.options=o;this.byName={...o.config.collections,...o.config.globals},this.bySlug=Object.fromEntries(Object.values(this.byName).map((i)=>[i.slug,i]))}bind(o){this.cms=o}buildApi(){let o={};for(let i of Object.values(this.options.config.collections))o[i.name]=this.collectionApi(i);return o}buildGlobals(){let o={};for(let i of Object.values(this.options.config.globals))o[i.name]=this.globalApi(i);return o}buildTrash(){return{list:async(o={})=>{let i=await this.options.database();return Ht({adapter:i,config:this.options.config,collections:this.byName,args:o})},restore:(o)=>this.restore(this.requireCollection(o.collection),{...o,id:o.id}),purge:(o)=>this.purge(this.requireCollection(o.collection),{...o,id:o.id})}}buildJobs(){return new pt({config:this.options.config,database:()=>this.options.database(),applyScheduled:(o)=>this.applyScheduled(o),purgeExpired:(o)=>this.purgeExpired(o),recordFailure:(o,i,r)=>this.recordFailure(o,i,r)})}async drainEvents(o){return await this.delivery,(await this.outboxWorker()).drain(o)}async settle(){await this.delivery}async appendEvents(o,i,r){await(await this.outboxWorker()).append(o,i,r)}deliverSoon(){this.scheduleDelivery()}collectionApi(o){return{find:(i)=>this.find(o,i),findOne:(i)=>this.findOne(o,i),findById:(i,r)=>this.findById(o,i,r),count:(i)=>this.count(o,i),create:(i)=>this.create(o,i),update:(i)=>this.update(o,i),delete:(i)=>this.remove(o,i),restore:(i)=>this.restore(o,i),purge:(i)=>this.purge(o,i),schedule:(i)=>this.schedule(o,i),unschedule:(i)=>this.unschedule(o,i),resolveSlug:(i,r)=>this.resolveSlug(o,i,r),previousSlugs:(i)=>this.previousSlugs(o,i),addPreviousSlug:(i)=>this.changePreviousSlug(o,i,"add"),removePreviousSlug:(i)=>this.changePreviousSlug(o,i,"remove")}}slugField(o,i,r){let a=ae(o).filter(([,f])=>!r||ee(f).history===!0),c=i===void 0?a[0]?.[0]:a.find(([f])=>f===i)?.[0];if(c===void 0)throw e.validation(i===void 0?`${o.name} has no slug field${r?" with history":""}`:`${o.name}.${i} is not a slug field${r?" with history":""}`);return c}async resolveSlug(o,i,r={}){let a=this.slugField(o,r.field,!1),c=O(this.options.config,r),f=await this.options.database(),h=await f.transaction((v)=>ze({db:d(f,v),collection:o,field:a,slug:i,locale:c.locale,locales:this.options.config.i18n.locales})),{field:g,...C}=r;for(let v of h){let D=await this.findById(o,v.id,C);if(!D)continue;return{id:v.id,field:a,locale:v.locale,current:v.current,document:D}}return null}async previousSlugs(o,i){let r=this.slugField(o,i.field,!0);if(!await this.findById(o,i.id,{...i,includeTrashed:!0}))throw e.notFound(`No ${o.name} with id "${i.id}"`);let c=o.fields[r],f=await this.options.database();return f.transaction((h)=>Ge({db:d(f,h),collection:o,documentId:i.id,field:r,...i.locale===void 0?{}:{locale:c?.localized?i.locale:null}}))}async changePreviousSlug(o,i,r){let a=this.slugField(o,i.field,!0),c=o.fields[a],f=O(this.options.config,i),h=i.actor??null,g=c.localized?f.locale:"",C=r==="add"?he(c)(i.slug):i.slug;if(C==="")throw e.validation(`"${i.slug}" has no letters or digits to make a slug from`);let v=await this.options.database();return await v.transaction(async(D)=>{let I=d(v,D),F=await this.load(v,D,o,i.id,{actor:h,operation:"update",locale:f,includeTrashed:!1}),B=A(F,o,f);await this.assertAllowed(o,"update",h,f,B),j(o,{[a]:null},h,f.locale,B);let y=c.localized?u(u(F.data)[a])[f.locale]:u(F.data)[a];if(r==="add"){if(y===C)throw e.conflict(`"${C}" is this document's slug already, not a previous one.`);await Ce({db:I,collection:o,documentId:String(F.id),field:a,locale:g,slug:C}),await we(I,o,String(F.id),[{field:a,locale:g,from:C,to:String(y??"")}],new Date)}else await Le(I,o,String(F.id),a,g,C)}),this.previousSlugs(o,{id:i.id,field:a,...i.actor===void 0?{}:{actor:i.actor},...c.localized?{locale:f.locale}:{}})}async find(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:a.locale,rbac:this.options.config.rbac}),h=this.scope(o,i.where,f,i.includeTrashed),g=Mt(i.orderBy),C=Nt(i.limit);return r.transaction(async(v)=>{let D=await r.query(v,{table:p,where:i.cursor?s(h,J(i.cursor,g)):h,orderBy:g,limit:C+1,...i.offset===void 0?{}:{offset:i.offset}}),I=D.length>C,F=D.slice(0,C),B=F.map((W)=>A(W,o,a));await this.expand(r,v,B,o,a,i,c),this.redact(B,o,c,a);let y=null;if(i.count===!0){let W=await r.query(v,{table:p,where:h,count:!0});y=Number(W[0]?.count??0)}let P=F.at(-1);return{docs:B,limit:C,totalDocs:y,hasNextPage:I,cursor:P?V(P,g):null}})}async findOne(o,i={}){return(await this.find(o,{...i,limit:1})).docs[0]??null}async findById(o,i,r={}){return this.findOne(o,{...r,where:t("id",i)})}async count(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=await _(o,{actor:i.actor??null,operation:"read",locale:a.locale,rbac:this.options.config.rbac}),f=this.scope(o,i.where,c,i.includeTrashed);return r.transaction(async(h)=>{let g=await r.query(h,{table:p,where:f,count:!0});return Number(g[0]?.count??0)})}async create(o,i){let r=O(this.options.config,i),a=i.actor??null,c={...i.data};return this.runWrite({collection:o,intent:"create",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({db:f,hooks:h,context:g})=>{await this.assertAllowed(o,"create",a,r),j(o,c,a,r.locale);let C=await Ie(h.createBefore,{data:c},g,(P,W)=>({...P,data:W}));if(C===!1)return null;let v=i.id??b("doc"),D=await be({db:f,collection:o,input:C.data,stored:null,locale:r.locale,documentId:v}),{data:I,touched:F}=$e(o,D.input,r);Je(o,I,r,Object.keys(o.fields));let B=new Date,y=await f.insert(p,{id:v,collection:o.slug,data:I,created_at:B,updated_at:B,updated_by:a?.id??null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1});return{doc:A(y,o,r),previous:null,changed:F,stored:I}}})}async update(o,i,r){let a=O(this.options.config,i),c=i.actor??null,f={...i.data};return this.runWrite({collection:o,intent:"update",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,...r===void 0?{}:{emit:r},step:async({adapter:h,tx:g,db:C,hooks:v,context:D})=>{let I=await this.load(h,g,o,i.id,{actor:c,operation:"update",locale:a,includeTrashed:i.includeTrashed});Re(i.expectedRevision,I);let F=A(I,o,a);await this.assertAllowed(o,"update",c,a,F),j(o,f,c,a.locale,F);let B=await Ie(v.updateBefore,{data:f,previous:F},D,(L,N)=>({...L,data:N}));if(B===!1)return null;let y=await be({db:C,collection:o,input:B.data,stored:u(I.data),locale:a.locale,documentId:String(I.id)}),{data:P,touched:W}=$e(o,y.input,a,u(I.data));Je(o,P,a,W);let E=new Date,k=await this.patch(h,g,I,{data:P,updated_at:E,updated_by:c?.id??null},i.expectedRevision),T=A(k,o,a);return{doc:T,previous:F,changed:vo(o,F,T),stored:P,slugMoves:y.moves}}})}async remove(o,i){if(!this.options.config.trash.enabled||i.permanent===!0)return this.purge(o,i);let a=O(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"trash",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:f,tx:h,hooks:g,context:C})=>{let v=await this.load(f,h,o,i.id,{actor:c,operation:"delete",locale:a,includeTrashed:!1});Re(i.expectedRevision,v);let D=A(v,o,a);await this.assertAllowed(o,"delete",c,a,D);let I=await Ie(g.deleteBefore,D,C,(y,P)=>P);if(I===!1)return null;let F=new Date,B=await this.patch(f,h,v,{deleted_at:F,purge_after:this.purgeAt(F),scheduled_at:null,scheduled_patch:null,updated_at:F,updated_by:c?.id??null});return{doc:A(B,o,a),previous:I,changed:[]}}})}async restore(o,i){let r=O(this.options.config,i),a=i.actor??null;return this.runWrite({collection:o,intent:"restore",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:a,operation:"restore",locale:r,includeTrashed:!0});if(Re(i.expectedRevision,h),h.deleted_at===null||h.deleted_at===void 0)throw e.conflict(`${o.name} "${i.id}" is not in the trash`);let g=A(h,o,r);await this.assertAllowed(o,"restore",a,r,g);let C=new Date,v=await this.patch(c,f,h,{deleted_at:null,purge_after:null,updated_at:C,updated_by:a?.id??null});return{doc:A(v,o,r),previous:g,changed:[],after:!1}}})}async purge(o,i,r={}){let a=O(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"purge",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!0,step:async({adapter:f,tx:h,db:g,hooks:C,context:v})=>{let D=await this.load(f,h,o,i.id,{actor:c,operation:"purge",locale:a,includeTrashed:!0,bypassAccess:r.retention===!0}),I=A(D,o,a),F=D.deleted_at!==null&&D.deleted_at!==void 0;if(r.retention!==!0)await this.assertAllowed(o,F?"purge":"delete",c,a,I);let B=F?I:await Ie(C.deleteBefore,I,v,(y,P)=>P);if(B===!1)return null;return await g.delete(p,t("id",String(D.id))),{doc:B,previous:B,changed:[],after:!F,releaseMedia:!0}}})}async schedule(o,i){let r=O(this.options.config,i),a=i.actor??null,c=qt(i.at),f={...i.data};if(Object.keys(f).length===0)throw e.validation("A scheduled change needs at least one field.");return this.runWrite({collection:o,intent:"schedule",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!1,step:async({adapter:h,tx:g})=>{let C=await this.load(h,g,o,i.id,{actor:a,operation:"update",locale:r,includeTrashed:!1}),v=A(C,o,r);await this.assertAllowed(o,"update",a,r,v),j(o,f,a,r.locale,v);let D=$e(o,f,r,u(C.data));Je(o,D.data,r,D.touched);let I=new Date,F=await this.patch(h,g,C,{scheduled_at:c,scheduled_patch:{data:f,locale:r.locale,actor:a===null?null:{...a}},updated_at:I,updated_by:a?.id??null});return{doc:A(F,o,r),previous:v,changed:[],after:!1}}})}async unschedule(o,i){let r=O(this.options.config,i),a=i.actor??null;return this.runWrite({collection:o,intent:"unschedule",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!1,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:a,operation:"update",locale:r,includeTrashed:!1});if(h.scheduled_at===null||h.scheduled_at===void 0)throw e.conflict(`${o.name} "${i.id}" has nothing scheduled`);let g=A(h,o,r);await this.assertAllowed(o,"update",a,r,g);let C=new Date,v=await this.patch(c,f,h,{scheduled_at:null,scheduled_patch:null,updated_at:C,updated_by:a?.id??null});return{doc:A(v,o,r),previous:g,changed:[],after:!1}}})}globalApi(o){return{get:(i)=>this.globalGet(o,i),update:async(i)=>{let r=await this.ensureGlobalRow(o,i);return this.update(o,{...i,id:r})},schedule:async(i)=>{let r=await this.ensureGlobalRow(o,i);return this.schedule(o,{...i,id:r})},unschedule:async(i={})=>this.unschedule(o,{...i,id:te(o)})}}async globalGet(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:a.locale,rbac:this.options.config.rbac});return r.transaction(async(h)=>{let C=(await r.query(h,{table:p,where:this.scope(o,t("id",te(o)),f,!1),limit:1}))[0]??this.emptyGlobalRow(o,a,null),v=A(C,o,a);return await this.expand(r,h,[v],o,a,i,c),this.redact([v],o,c,a),v})}async ensureGlobalRow(o,i){let r=await this.options.database(),a=O(this.options.config,i),c=te(o);if(await r.transaction(async(h)=>(await r.query(h,{table:p,where:t("id",c),limit:1})).length>0))return c;try{await r.transaction((h)=>r.mutate(h,{kind:"insert",table:p,returning:!1,values:this.emptyGlobalRow(o,a,new Date)}))}catch(h){if(!await r.transaction(async(C)=>(await r.query(C,{table:p,where:t("id",c),limit:1})).length>0))throw h}return c}emptyGlobalRow(o,i,r){let{data:a}=$e(o,{},i);return{id:te(o),collection:o.slug,data:a,created_at:r,updated_at:r,updated_by:null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1}}async applyScheduled(o){let i=this.bySlug[String(o.collection)],r=je(o),a=o.scheduled_at;if(!i||!r||!(a instanceof Date)){await this.clearSchedule(String(o.id));return}let c=await this.options.database();if((await c.transaction((h)=>c.mutate(h,{kind:"update",table:p,where:s(t("id",String(o.id)),t("scheduled_at",a)),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))).count!==1)return;await this.update(i,{id:String(o.id),data:r.data,locale:r.locale,actor:r.actor,source:"job"},(h,g)=>{h.emit("document.schedule.applied",{collection:i.name,documentId:String(g.doc.id),locale:r.locale,scheduledFor:a.toISOString(),patch:r.data})})}async purgeExpired(o){let i=this.bySlug[String(o.collection)];if(!i){let r=await this.options.database();await r.transaction(async(a)=>{let c=d(r,a);await c.delete(Lt,t("document_id",String(o.id))),await c.delete(p,t("id",String(o.id)))});return}await this.purge(i,{id:String(o.id),actor:null,source:"job",includeTrashed:!0},{retention:!0})}async clearSchedule(o){let i=await this.options.database();await i.transaction((r)=>i.mutate(r,{kind:"update",table:p,where:t("id",o),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))}async recordFailure(o,i,r){let a=r instanceof Error?r.message:String(r),c=await this.options.database(),f=new Date;await c.transaction(async(h)=>{await d(c,h).insert("jobs",{id:ve("job"),type:o,payload:i,status:"failed",run_at:f,attempts:1,locked_at:null,locked_by:null,completed_at:null,error:a,created_at:f}),await this.appendEvents(h,[{type:"job.failed",data:{job:o,error:a,...i},previous:null}],{actor:null})}),this.scheduleDelivery()}async runWrite(o){let i=await this.options.database(),r=await this.outboxWorker(),a=this.pipeline(o.collection.name),c=new mt,f=await i.transaction(async(h)=>{let g=d(i,h),C=await this.replay(g,o);if(C)return C;let v={actor:o.actor,collection:o.collection.name,operation:Ke[o.intent],locale:o.locale.locale,tx:h,db:g,cms:this.instance(),events:c,source:o.source,meta:{}},D=await o.step({adapter:i,tx:h,db:g,hooks:a,context:v});if(D===null)return null;if(this.emitDocumentEvents(c,o,D),await this.syncMedia(g,o,D,c),await this.syncSlugs(g,o,D),o.emit?.(c,D),await r.append(h,c.take(),this.outboxMeta(o,D)),D.after!==!1)await this.runAfter(a,o,D,v);return await r.append(h,c.take(),this.outboxMeta(o,D)),await this.writeActivity(g,o,D),await this.recordIdempotency(g,o,D),await this.expand(i,h,[D.doc],o.collection,o.locale,o,o.actor),D});if(!f)return null;if(!("replayed"in f))this.scheduleDelivery();return this.redact([f.doc],o.collection,o.actor,o.locale),f.doc}async replay(o,i){let r=i.idempotencyKey;if(r===void 0)return null;let a=await o.findOne(Ue,t("idempotency_key",r));if(!a)return null;return{doc:u(a.result),previous:null,changed:[],replayed:!0}}async recordIdempotency(o,i,r){let a=i.idempotencyKey;if(a===void 0)return;await o.insert(Ue,{id:b("aim"),idempotency_key:a,run_id:i.runId??"",collection:i.collection.name,document_id:String(r.doc.id),result:r.doc,created_at:new Date})}async runAfter(o,i,r,a){let c=Ke[i.intent];if(c==="create"){await He(o.createAfter,r.doc,a);return}if(c==="update"){await He(o.updateAfter,{doc:r.doc,previous:r.previous},a);return}await He(o.deleteAfter,r.doc,a)}emitDocumentEvents(o,i,r){let a=(f)=>({collection:i.collection.name,documentId:String(r.doc.id),locale:i.locale.locale,document:ce(f)});switch(i.intent){case"create":{o.emit("document.created",a(r.doc),null);return}case"trash":{o.emit("document.trashed",{...a(r.doc),purgeAfter:r.doc.purgeAfter??null},null);return}case"restore":{o.emit("document.restored",a(r.doc),null);return}case"purge":{o.emit("document.purged",a(r.doc),null);return}case"schedule":{o.emit("document.scheduled",{...a(r.doc),scheduledAt:r.doc.scheduledAt??null,patch:ce(r.doc.scheduledPatch??null)},null);return}case"unschedule":{o.emit("document.schedule.cancelled",{...a(r.doc),scheduledAt:r.previous?.scheduledAt??null},null);return}case"update":break}let c=r.previous;o.emit("document.updated",a(r.doc),a(c));for(let f of r.changed)o.emit("document.field.changed",{collection:i.collection.name,documentId:String(r.doc.id),locale:i.locale.locale,field:f,value:ce(r.doc[f]??null)},{field:f,value:ce(c[f]??null)})}async syncMedia(o,i,r,a){let c=this.options.config.uploads,f=r.releaseMedia===!0;if(!f&&r.stored===void 0)return;if(!f&&!this.referencesMedia(i.collection))return;let h=await on({db:o,collection:i.collection.name,documentId:String(r.doc.id),references:f?null:nn(i.collection,r.stored??{}),lifecycle:c!==void 0,retention:c?.retention,now:new Date}),g=(C)=>({mediaId:C,collection:i.collection.name,documentId:String(r.doc.id)});for(let C of h.orphaned)a.emit("media.orphaned",g(C));for(let C of h.reclaimed)a.emit("media.reclaimed",g(C))}async syncSlugs(o,i,r){if(!this.keepsSlugHistory(i.collection))return;let a=String(r.doc.id);if(r.releaseMedia===!0){await Me(o,i.collection,a);return}if(r.slugMoves&&r.slugMoves.length>0)await we(o,i.collection,a,r.slugMoves,new Date)}keepsSlugHistory(o){return ae(o).some(([,i])=>ee(i).history===!0)}referencesMedia(o){let i=this.media.get(o.name);if(i!==void 0)return i;let r=tn(o);return this.media.set(o.name,r),r}async writeActivity(o,i,r){await o.insert(Ft,{id:ve("act"),actor_id:i.actor?.id??null,actor_source:i.actor?.source??null,action:Ut(i.intent),source:i.source,collection:i.collection.name,document_id:String(r.doc.id),locale:i.locale.locale,changes:{fields:r.changed,...i.runId===void 0?{}:{runId:i.runId}},ip:null,created_at:new Date})}scope(o,i,r,a){let c=[t("collection",o.slug)];if(a!==!0)c.push(t("deleted_at",null));if(i)c.push(i);if(r)c.push(r);return s(...c)}async load(o,i,r,a,c){let f=c.bypassAccess===!0?void 0:await _(r,{actor:c.actor,operation:c.operation,locale:c.locale.locale,rbac:this.options.config.rbac}),g=(await o.query(i,{table:p,where:this.scope(r,t("id",a),f,c.includeTrashed),limit:1}))[0];if(!g)throw e.notFound(`No ${r.name} with id "${a}"`);return g}async patch(o,i,r,a,c){let f=gn(r.revision),h=f+1,g=String(r.id),C=await o.mutate(i,{kind:"update",table:p,where:c===void 0?t("id",g):s(t("id",g),t("revision",c)),set:{...a,revision:h}});if(c!==void 0&&C.count===0)throw Ve(c,f);return C.rows[0]??{...r,...a,revision:h}}async assertAllowed(o,i,r,a,c){if(await _(o,{actor:r,operation:i,locale:a.locale,rbac:this.options.config.rbac,...c===void 0?{}:{record:c}})&&i==="create")throw new e(`access.create on "${o.name}" returned a filter; a create has no row to filter. Return true or false.`,{status:500,code:"invalid_access_rule"})}requireCollection(o){let i=this.byName[o];if(!i)throw e.notFound(`No collection named "${o}"`);return i}purgeAt(o){let i=this.options.config.trash.purgeAfter;if(i===!1)return null;return new Date(o.getTime()+w(i))}async expand(o,i,r,a,c,f,h){if(!f.depth)return;await new ht({adapter:o,tx:i,locale:c,actor:h,rbac:this.options.config.rbac,collections:this.byName,...f.includeTrashed===void 0?{}:{includeTrashed:f.includeTrashed}}).expand(r,a,f.depth)}redact(o,i,r,a){if(!rn(i))return;for(let c of o)fe(c,i,r,a.locale)}pipeline(o){let i=this.pipelines.get(o);if(i)return i;let r=ut(this.options.config,o);return this.pipelines.set(o,r),r}outboxMeta(o,i){return{actor:o.actor,collection:o.collection.name,documentId:String(i.doc.id)}}async outboxWorker(){if(this.outbox)return this.outbox;let o=await this.options.database();return this.outbox=new ft(o,this.options.dispatch),this.outbox}scheduleDelivery(){this.delivery=this.delivery.then(async()=>{await(await this.outboxWorker()).drain()}).catch(()=>{return})}instance(){if(!this.cms)throw new e("The engine was used before it was bound.",{status:500,code:"engine_unbound"});return this.cms}}function te(o){return`glb_${o.slug}`}function Mt(o){let i=o&&o.length>0?[...o]:[{path:"updated_at",direction:"desc"}];if(!i.some((r)=>r.path==="id"))i.push({path:"id",direction:i[i.length-1]?.direction??"desc"});return i}function Nt(o){if(o===void 0)return Wt;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,Et)}function qt(o){let i=o instanceof Date?o:new Date(o);if(Number.isNaN(i.getTime()))throw e.validation(`"${String(o)}" is not a date`);return i}function Ve(o,i){return new e(`This document has changed since you read it (expected revision ${o}, found ${i}). Reload it and apply your change again.`,{status:409,code:"revision_conflict",details:{expectedRevision:o,revision:i}})}function Re(o,i){if(o===void 0)return;if(!Number.isInteger(o)||o<1)throw e.validation(`expectedRevision has to be a positive integer, received ${String(o)}.`);let r=gn(i.revision);if(r!==o)throw Ve(o,r)}function Ut(o){switch(o){case"create":return"document.created";case"update":return"document.updated";case"trash":return"document.trashed";case"restore":return"document.restored";case"purge":return"document.purged";case"schedule":return"document.scheduled";case"unschedule":return"document.schedule.cancelled"}}function ce(o){return JSON.parse(JSON.stringify(o??null))}var Bt={af:"Afrikaans",am:"Amharic",ar:"Arabic",az:"Azerbaijani",be:"Belarusian",bg:"Bulgarian",bn:"Bengali",bs:"Bosnian",ca:"Catalan",cs:"Czech",cy:"Welsh",da:"Danish",de:"German",el:"Greek",en:"English",eo:"Esperanto",es:"Spanish",et:"Estonian",eu:"Basque",fa:"Persian",fi:"Finnish",fil:"Filipino",fo:"Faroese",fr:"French",ga:"Irish",gl:"Galician",gu:"Gujarati",he:"Hebrew",hi:"Hindi",hr:"Croatian",hu:"Hungarian",hy:"Armenian",id:"Indonesian",is:"Icelandic",it:"Italian",ja:"Japanese",ka:"Georgian",kk:"Kazakh",km:"Khmer",kn:"Kannada",ko:"Korean",ku:"Kurdish",ky:"Kyrgyz",lo:"Lao",lt:"Lithuanian",lv:"Latvian",mk:"Macedonian",ml:"Malayalam",mn:"Mongolian",mr:"Marathi",ms:"Malay",mt:"Maltese",my:"Burmese",nb:"Norwegian Bokmål",ne:"Nepali",nl:"Dutch",nn:"Norwegian Nynorsk",no:"Norwegian",pa:"Punjabi",pl:"Polish",ps:"Pashto",pt:"Portuguese",ro:"Romanian",ru:"Russian",si:"Sinhala",sk:"Slovak",sl:"Slovenian",sq:"Albanian",sr:"Serbian",sv:"Swedish",sw:"Swahili",ta:"Tamil",te:"Telugu",th:"Thai",tk:"Turkmen",tl:"Tagalog",tr:"Turkish",tt:"Tatar",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",vi:"Vietnamese",zh:"Chinese",zu:"Zulu"},Xt={AR:"Argentina",AT:"Austria",AU:"Australia",BE:"Belgium",BR:"Brazil",CA:"Canada",CH:"Switzerland",CL:"Chile",CN:"China",CO:"Colombia",CZ:"Czechia",DE:"Germany",DK:"Denmark",ES:"Spain",FI:"Finland",FR:"France",GB:"United Kingdom",HK:"Hong Kong",IE:"Ireland",IN:"India",IT:"Italy",JP:"Japan",KR:"South Korea",MX:"Mexico",NL:"Netherlands",NO:"Norway",NZ:"New Zealand",PL:"Poland",PT:"Portugal",RU:"Russia",SE:"Sweden",TW:"Taiwan",UA:"Ukraine",US:"United States",ZA:"South Africa"},en=new Set(["ar","arc","dv","fa","he","ku","ps","sd","ug","ur","yi"]);function Vt(o){let i=Bt[o];if(i)return i;let[r,a]=o.split("-"),c=r===void 0?void 0:Bt[r.toLowerCase()];if(!c)return o;if(a===void 0)return c;let f=a.toUpperCase();return`${c} (${Xt[f]??f})`}function Gt(o){let i=o.split("-")[0];return i!==void 0&&en.has(i.toLowerCase())}function An(o){return o.i18n.locales.map((i)=>({code:i,name:Vt(i),rtl:Gt(i),isDefault:i===o.i18n.defaultLocale}))}var q="webhooks",U="webhook_deliveries",sn=25,ln=200,cn=5,dn="10s";function Kt(o){let{config:i}=o,r=(y,P)=>(o.fetch??globalThis.fetch)(y,P),a=o.now??(()=>new Date),c=i.webhooks,f=c?.delivery?.retries??cn,h=w(c?.delivery?.timeout??dn),g=c?.delivery?.dlq!==!1,C=c?.delivery?.backoff==="linear",v=()=>{if(c?.enabled)return;throw new e("Webhooks are switched off; set webhooks.enabled to true.",{status:501,code:"webhooks_disabled"})},D=(y)=>C?y*30000:Math.min(3600000,1000*2**y),I=async()=>{let y=await o.database();return y.transaction((P)=>y.query(P,{table:q,where:t("active",!0)}))},F=async(y,P,W,E=a())=>{let k=await o.database(),T=Number(y.attempt??0)+1;if((await k.transaction((z)=>k.mutate(z,{kind:"update",table:U,where:s(t("id",String(y.id)),t("status","pending"),t("attempt",Number(y.attempt??0)),t("next_attempt_at",y.next_attempt_at==null?null:new Date(l(y.next_attempt_at))),R(t("next_attempt_at",null),M("next_attempt_at",E))),set:{attempt:T,next_attempt_at:new Date(E.getTime()+h+30000)},returning:!1}))).count!==1)return ie(y);if(T>f){let z={status:"failed",next_attempt_at:null,error:"Delivery lease expired; attempt budget exhausted."};return await k.transaction((re)=>d(k,re).update(U,s(t("id",String(y.id)),t("attempt",T)),z)),ie({...y,...z,attempt:T})}let N=typeof P.secret==="string"&&P.secret||c?.signing?.secret||"",G={"content-type":"application/json","user-agent":"heyo-cms","x-heyo-event-id":String(y.event_id),"x-heyo-event-type":String(y.event_type),"x-heyo-delivery-id":String(y.id),"x-heyo-attempt":String(T),...hn(P.headers)};if(N.length>0)G[Ae]=await ke(W,N);let K=null,ue=null,ne=null;try{let z=await r(String(P.url),{method:"POST",headers:G,body:W,signal:AbortSignal.timeout(h)});if(K=z.status,ue=await un(z),!z.ok)ne=`Responded ${z.status}.`}catch(z){ne=z instanceof Error?z.message:String(z)}let xe=ne===null,pe=T>=f,Oe=a(),Pe=xe?{status:"delivered",attempt:T,response_status:K,response_body:ue,error:null,next_attempt_at:null,delivered_at:Oe}:{status:pe?"failed":"pending",attempt:T,response_status:K,response_body:ue,error:ne,next_attempt_at:pe?null:new Date(Oe.getTime()+D(T)),delivered_at:null},st=await k.transaction(async(z)=>(await d(k,z).update(U,s(t("id",String(y.id)),t("status","pending"),t("attempt",T)),Pe),{...y,...Pe}));if(!xe&&pe&&g)await(await o.database()).transaction((re)=>o.emit(re,[{type:"job.failed",data:{job:"webhook-delivery",webhookId:String(y.webhook_id),deliveryId:String(y.id),eventId:String(y.event_id),eventType:String(y.event_type),attempts:T,error:ne??"unknown"},previous:null}],{actor:null})),o.deliver();return ie(st)},B=async(y,P)=>{let W=await o.database(),E=JSON.stringify(P),k=`whd_${P.id}_${String(y.id)}`,T=await W.transaction((N)=>d(W,N).findOne(U,t("id",k)));if(T)return ie(T);let L=await W.transaction(async(N)=>d(W,N).insert(U,{id:k,webhook_id:String(y.id),event_id:P.id,event_type:P.type,status:"pending",attempt:0,request_body:P,response_status:null,response_body:null,error:null,next_attempt_at:a(),delivered_at:null,created_at:a()}));return F(L,y,E)};return{get enabled(){return c?.enabled===!0},async list(y={}){v();let P=await o.database();return(await P.transaction((E)=>P.query(E,{table:q,...y.active===void 0?{}:{where:t("active",y.active)},orderBy:[m("created_at","desc"),m("id","desc")]}))).map(de)},async get(y){v();let P=await o.database(),W=await P.transaction(async(E)=>d(P,E).findOne(q,t("id",y)));return W?de(W):null},async create(y){v(),Ze(y.url),Qe(y.events);let P=await o.database(),W=a();return await P.transaction(async(k)=>{let L=await d(P,k).insert(q,{id:b("whk"),url:y.url,events:y.events,filters:y.filters??null,headers:y.headers??null,secret:y.secret??null,active:y.active!==!1,created_at:W,updated_at:W});return de(L)})},async update(y){if(v(),y.url!==void 0)Ze(y.url);if(y.events!==void 0)Qe(y.events);let P=await o.database();return P.transaction(async(W)=>{let E=d(P,W),k=await E.findOne(q,t("id",y.id));if(!k)throw e.notFound("No such webhook.");let T={updated_at:a()};if(y.url!==void 0)T.url=y.url;if(y.events!==void 0)T.events=y.events;if(y.filters!==void 0)T.filters=y.filters;if(y.headers!==void 0)T.headers=y.headers;if(y.secret!==void 0)T.secret=y.secret;if(y.active!==void 0)T.active=y.active;await E.update(q,t("id",y.id),T);let L=await E.findOne(q,t("id",y.id));return de(L??{...k,...T})})},async remove(y){v();let P=await o.database();return P.transaction(async(W)=>{let E=d(P,W);return await E.delete(U,t("webhook_id",y.id)),await E.delete(q,t("id",y.id))>0})},async deliveries(y={}){v();let P=await o.database(),W=Math.min(ln,Math.max(1,y.limit??sn)),E=[m("created_at","desc"),m("id","desc")],k=[];if(y.webhookId)k.push(t("webhook_id",y.webhookId));if(y.status)k.push(t("status",y.status));if(y.eventId)k.push(t("event_id",y.eventId));let T=k.length===0?void 0:s(...k),L=await P.transaction((K)=>P.query(K,{table:U,...y.cursor?{where:T===void 0?J(y.cursor,E):s(T,J(y.cursor,E))}:T===void 0?{}:{where:T},orderBy:E,limit:W+1})),N=L.slice(0,W),G=N.at(-1);return{entries:N.map((K)=>ie(K,y.includeBody===!0)),limit:W,hasNextPage:L.length>W,cursor:G?V(G,E):null}},async test(y){v();let P=await o.database(),W=await P.transaction(async(T)=>d(P,T).findOne(q,t("id",y.id)));if(!W)throw e.notFound("No such webhook.");let E=y.actor??null,k={id:b("evt"),type:"webhook.test",createdAt:a().toISOString(),actor:E?{id:E.id,source:E.source}:null,data:{message:"A test delivery from Heyo CMS. Verify the signature exactly as you would for a real event.",webhookId:String(W.id)},previous:null};return B(W,k)},async retry(y){v();let P=await o.database(),{delivery:W,subscription:E}=await P.transaction(async(L)=>{let N=d(P,L),G=await N.findOne(U,t("id",y.id));if(!G)throw e.notFound("No such delivery.");let K=await N.findOne(q,t("id",String(G.webhook_id)));if(!K)throw e.notFound("That webhook is gone.");return{delivery:G,subscription:K}}),k=JSON.stringify(W.request_body??{}),T=await P.transaction(async(L)=>d(P,L).insert(U,{id:ve("whd"),webhook_id:String(E.id),event_id:String(W.event_id),event_type:String(W.event_type),status:"pending",attempt:0,request_body:W.request_body??null,response_status:null,response_body:null,error:null,next_attempt_at:a(),delivered_at:null,created_at:a()}));return F(T,E,k)},async attemptDelivery(y,P=a()){let W=await o.database(),E=await W.transaction(async(k)=>{let T=d(W,k),L=await T.findOne(U,t("id",y));if(!L||L.status!=="pending")return null;let N=await T.findOne(q,t("id",String(L.webhook_id)));return N?{row:L,subscription:N}:null});if(!E)return null;return F(E.row,E.subscription,JSON.stringify(E.row.request_body??{}),P)},async dispatch(y){if(c?.enabled!==!0)return;let P=await I();for(let W of P){if(!fn(W,y))continue;await B(W,y)}},async drain(y={}){let P={attempted:0,delivered:0,failed:0};if(c?.enabled!==!0)return P;let W=await o.database(),E=y.now??a(),k=await W.transaction((T)=>W.query(T,{table:U,where:s(t("status","pending"),R(t("next_attempt_at",null),M("next_attempt_at",E))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:y.limit??50}));for(let T of k){let L=await W.transaction(async(G)=>d(W,G).findOne(q,t("id",String(T.webhook_id))));if(!L)continue;P.attempted+=1;let N=await F(T,L,JSON.stringify(T.request_body??{}),E);if(N.status==="delivered")P.delivered+=1;else if(N.status==="failed")P.failed+=1}return P},async wants(y){if(c?.enabled!==!0)return!1;return(await I()).some((W)=>Xe(W,y))}}}async function un(o){let i=o.body?.getReader();if(!i)return"";let r=[],a=0;try{while(a<2000){let{value:h,done:g}=await i.read();if(g)break;let C=h.slice(0,2000-a);r.push(C),a+=C.length}}finally{await i.cancel().catch(()=>{}),i.releaseLock()}let c=new Uint8Array(a),f=0;for(let h of r)c.set(h,f),f+=h.length;return new TextDecoder().decode(c)}function Xe(o,i){return Ye(o.events).some((a)=>{if(a==="*"||a===i)return!0;if(!a.endsWith("*"))return!1;return i.startsWith(a.slice(0,-1))})}function fn(o,i){if(!Xe(o,i.type))return!1;let r=o.filters??null;if(!r)return!0;let a=i.data;if(r.collections?.length){let c=typeof a.collection==="string"?a.collection:null;if(!c||!r.collections.includes(c))return!1}if(r.locales?.length){let c=mn(a);if(c.length>0&&!c.some((f)=>r.locales?.includes(f)))return!1}return!0}function mn(o){if(typeof o.locale==="string")return[o.locale];if(Array.isArray(o.locales))return o.locales.filter((i)=>typeof i==="string");return[]}function de(o){return{id:String(o.id),url:String(o.url),events:Ye(o.events),filters:o.filters?u(o.filters):null,headers:o.headers?u(o.headers):null,hasSecret:typeof o.secret==="string"&&o.secret.length>0,active:o.active===!0||o.active===1,createdAt:l(o.created_at),updatedAt:l(o.updated_at)}}function ie(o,i=!1){return{id:String(o.id),webhookId:String(o.webhook_id),eventId:String(o.event_id),eventType:String(o.event_type),status:String(o.status)??"pending",attempt:Number(o.attempt??0),responseStatus:o.response_status===null||o.response_status===void 0?null:Number(o.response_status),responseBody:o.response_body===null||o.response_body===void 0?null:String(o.response_body),error:o.error===null||o.error===void 0?null:String(o.error),nextAttemptAt:l(o.next_attempt_at),deliveredAt:l(o.delivered_at),createdAt:l(o.created_at),...i?{requestBody:o.request_body===null||o.request_body===void 0?null:u(o.request_body)}:{}}}function Ye(o){if(!Array.isArray(o))return[];return o.filter((i)=>typeof i==="string")}function hn(o){if(typeof o!=="object"||o===null)return{};let i={};for(let[r,a]of Object.entries(o)){if(r.toLowerCase().startsWith("x-heyo-"))continue;if(r.toLowerCase()===Ae)continue;if(typeof a==="string")i[r]=a}return i}function Ze(o){let i;try{i=new URL(o)}catch{throw e.validation(`"${o}" is not a URL.`)}if(i.protocol!=="https:"&&i.protocol!=="http:")throw e.validation("A webhook URL has to be http or https.")}function Qe(o){if(o.length===0)throw e.validation("A webhook has to subscribe to at least one event type.");for(let i of o)if(!/^[a-z][a-z0-9.]*\*?$|^\*$/.test(i))throw e.validation(`"${i}" is not an event type; use "document.updated", "document.*" or "*".`)}var bn="webhook_deliveries";function Zt(o){return{name:"webhook-retries",failureType:"webhook.delivery",failurePayload:(i)=>({deliveryId:String(i.id),webhookId:String(i.webhook_id),eventId:String(i.event_id),eventType:String(i.event_type),attempt:Number(i.attempt??0)}),due:async(i,r,a)=>{let c=await i.database();return c.transaction((f)=>c.query(f,{table:bn,where:s(t("status","pending"),R(t("next_attempt_at",null),M("next_attempt_at",r))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:a}))},run:async(i,r,a)=>{await o.attemptDelivery(String(r.id),a)}}}var yn=new Set(["activity","admin","ai","auth","globals","jobs","locales","media","openapi.json","panel","roles","trash","users","webhooks"]),vn=/^[a-z][a-z0-9_]*$/,wn=/^[a-z][a-zA-Z0-9_]*$/,Cn=/^[a-z][a-z0-9-]*$/,Sn=/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;function Yn(o){return{...o,kind:"collection"}}function Qn(o){return{...o,kind:"global"}}function Xn(o){let i=kn(o),r=_t({collections:i.collections,globals:i.globals,pluginTables:i.plugins.flatMap((k)=>k.schema?.tables??[])}),a=new Map;for(let k of i.plugins)for(let[T,L]of Object.entries(k.events??{})){if(!L)continue;let N=a.get(T)??new Set;N.add(L),a.set(T,N)}let c,f,g=new yt({config:i,database:()=>E.database(),dispatch:async(k)=>{let T=[...a.get(k.type)??[],...a.get("*")??[]];for(let L of T)await L(k);await F.dispatch(k)}}),C=pn({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),v=Qt({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),D=An(i),I=De({database:()=>E.database()}),F=Kt({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),B=St({config:i,database:()=>E.database(),cms:()=>E,emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),y=g.buildJobs();if(i.webhooks?.enabled)y.register(Zt(F));if(i.uploads)y.register(Yt({config:i,database:()=>E.database(),storage:()=>v.storage(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}));let P,W=()=>(P??=qe(E),P),E={_config:Object.freeze(i),schema:r,collections:o.collections,handler:(k)=>W().handler(k),_router:{routes:()=>W().routes()},api:g.buildApi(),globals:g.buildGlobals(),auth:C,media:v,ai:B,webhooks:F,trash:g.buildTrash(),jobs:y,locales:{list:()=>D},activity:I,inspect(){return{basePath:i.basePath,database:{id:c?.id??"unresolved",capabilities:c?.capabilities??{transactions:!1,sqlMigrations:!1,jsonQuery:!1}},storage:Gn(i),collections:zn(i),schema:r,hooks:zt(i),routes:W().routes(),admin:{path:`${i.basePath}${i.admin.path}`,panel:i.admin.assets?.id??null},plugins:qn(i),auth:Un(i),ai:{enabled:i.ai!==void 0,defaultModel:i.ai?.defaultModel??null,assistant:i.ai!==void 0&&i.ai.assistant?.enabled!==!1,actions:me(),providers:Object.keys(i.ai?.auth??{}).sort(),panelManagedKeys:i.ai?.storage?.secret!==void 0},webhooks:{enabled:i.webhooks?.enabled===!0,signed:i.webhooks?.signing?.secret!==void 0,retries:i.webhooks?.delivery?.retries??5},editor:Te(),jobs:E.jobs.list(),trash:{enabled:i.trash.enabled,purgeAfter:i.trash.purgeAfter===!1?null:i.trash.purgeAfter}}},async database(){if(c)return c;return f??=Promise.resolve(typeof i.database==="function"?i.database():i.database).then((k)=>(k.useSchema(r),c=k,k)),f},on(k,T){let L=a.get(k)??new Set;return L.add(T),a.set(k,L),()=>{L.delete(T)}},drainEvents(k){return g.drainEvents(k)},async close(){await g.settle(),await c?.close?.(),c=void 0,f=void 0,a.clear()}};return g.bind(E),E}function kn(o){let i=Nn(o.basePath??ge),r=new Set(ot()),a=o.plugins??[];jn(a);let c=Pn(o.collections,a),f=Tn({plugins:a,collections:c,globals:o.globals??{},basePath:i}),h={};for(let[v,D]of Object.entries(c))h[v]=nt(v,D,"collection",r);let g={};for(let[v,D]of Object.entries(o.globals??{}))g[v]=nt(v,D,"global",r);Rn({...h,...g}),Fn({...h,...g}),_n({...h,...g}),On(o,h,g),Dn({...h,...g}),In(o),Jn(o),Wn(o),En(o,i),Mn(o),Hn(o);let C=o.trash?.purgeAfter??"30d";if(typeof C==="string")w(C,"trash.purgeAfter");return{basePath:i,database:o.database,admin:{...o.admin,path:Bn(o.admin?.path??et)},...o.rbac===void 0?{}:{rbac:o.rbac},i18n:$n(o.i18n),...o.uploads===void 0?{}:{uploads:o.uploads.publicPath===void 0?o.uploads:{...o.uploads,publicPath:x(o.uploads.publicPath.trim())}},...o.ai===void 0?{}:{ai:o.ai},...o.webhooks===void 0?{}:{webhooks:o.webhooks},trash:{enabled:o.trash?.enabled??!0,purgeAfter:C},collections:h,globals:g,...o.hooks===void 0?{}:{hooks:o.hooks},...o.databaseHooks===void 0?{}:{databaseHooks:o.databaseHooks},plugins:a,pluginHooks:f,...o.telemetry===void 0?{}:{telemetry:o.telemetry},migrationsDirectory:o.migrations?.directory??tt}}function nt(o,i,r,a){if(!vn.test(o))throw new n(`collections.${o}`,"a collection name must be lowercase letters, digits and underscores, starting with a letter");let c=i.slug??o.replaceAll("_","-");if(!Cn.test(c))throw new n(`collections.${o}.slug`,`"${c}" is not a URL-safe slug`);if(a.has(o)||a.has(c))throw new n(`collections.${o}`,`"${o}" is a reserved system name; pick another`);if(yn.has(c))throw new n(`collections.${o}`,`"${c}" is a URL the CMS serves itself; give the collection another slug`);let f={};for(let[h,g]of Object.entries(i.fields)){if(!wn.test(h))throw new n(`collections.${o}.fields.${h}`,"a field name must be letters, digits and underscores, starting with a lowercase letter");if(g.required&&g.admin?.hidden===!0)throw new n(`collections.${o}.fields.${h}.admin.hidden`,"a hidden field cannot be required; remove required or show the field");f[h]=g}if(Object.keys(f).length===0)throw new n(`collections.${o}.fields`,"a collection needs at least one field");return{name:o,slug:c,label:i.label??Kn(o),kind:r,fields:f,access:i.access??{},...i.admin===void 0?{}:{admin:i.admin}}}function Rn(o){let i=new Map;for(let r of Object.values(o)){let a=i.get(r.slug);if(a)throw new n(`collections.${r.name}.slug`,`"${r.slug}" is already used by "${a}"; slugs are URLs and index names`);i.set(r.slug,r.name)}}function _n(o){let i=new Set([...Object.keys(o),...ot()]);for(let r of Object.values(o))for(let[a,c]of Object.entries(r.fields)){if(!c.relationTo)continue;if(!i.has(c.relationTo))throw new n(`collections.${r.name}.fields.${a}`,`relation points at "${c.relationTo}", which is not a collection`)}}function On(o,i,r){for(let a of Object.keys(o.databaseHooks??{}))if(!(a in i)&&!(a in r))throw new n(`databaseHooks.${a}`,"no collection or global with this name")}function Pn(o,i){let r={...o},a=new Map;for(let c of i)for(let[f,h]of Object.entries(c.schema?.collections??{})){if(f in o)throw new n(`plugins.${c.id}.schema.collections.${f}`,`the configuration already declares a collection called "${f}"`);let g=a.get(f);if(g)throw new n(`plugins.${c.id}.schema.collections.${f}`,`"${g}" already declares a collection called "${f}"`);a.set(f,c.id),r[f]=h}return r}function Tn(o){let i=[],r=new Map;for(let a of o.plugins){if(!a.extendCollections)continue;let c=a.extendCollections({collections:o.collections,basePath:o.basePath});for(let f of c){let h=o.collections[f.collection]??o.globals[f.collection];if(!h)throw new n(`plugins.${a.id}.extendCollections`,`patches "${f.collection}", which is not a collection or a global`);for(let[g,C]of Object.entries(f.fields??{})){let v=r.get(`${f.collection}.${g}`);if(g in h.fields)throw new n(`plugins.${a.id}.extendCollections`,v?`"${v}" already added "${g}" to ${f.collection}`:`${f.collection} already has a field called "${g}"`);r.set(`${f.collection}.${g}`,a.id),h.fields={...h.fields,[g]:C}}if(f.hooks)i.push({plugin:a.id,collection:f.collection,hooks:f.hooks,priority:0})}}return i}function Dn(o){for(let i of Object.values(o))for(let[r,a]of Object.entries(i.fields)){if(a.aiGenerate!==void 0)it(i,r,a.aiGenerate,`collections.${i.name}.fields.${r}.aiGenerate`);for(let[c,f]of Object.entries(a.ai??{})){if(f!==!0)it(i,r,f,`collections.${i.name}.fields.${r}.ai.${c}`);let h=Z(c),g=`collections.${i.name}.fields.${r}.ai.${c}`;if(!h){if(f===!0||f.prompt===void 0)throw new n(g,"is not a registered AI action; register it with defineAiAction() or give it a prompt");continue}if(!h.appliesTo.includes("*")&&!h.appliesTo.includes(a.type))throw new n(g,`does not apply to a ${a.type} field; it applies to ${h.appliesTo.join(", ")}`);if(h.requiresLocalized&&!a.localized)throw new n(g,"needs a localized field; this one stores a single value for every language")}}}function it(o,i,r,a){if(r.context!==void 0&&!Array.isArray(r.context))throw new n(`${a}.context`,"must be an array of field names");let c=new Set;for(let f of r.context??[]){if(typeof f!=="string"||!o.fields[f]||f===i||c.has(f))throw new n(`${a}.context`,`"${f}" must name a different, existing field of ${o.name} (only once)`);c.add(f)}if(r.maxLength!==void 0&&(!Number.isInteger(r.maxLength)||r.maxLength<1))throw new n(`${a}.maxLength`,"must be a positive integer");if(r.model&&(!r.model.provider||!r.model.model))throw new n(`${a}.model`,"needs a provider and a model")}function jn(o){let i=new Set;for(let a of o){if(i.has(a.id))throw new n(`plugins.${a.id}`,"two plugins share this id");i.add(a.id)}let r=new Map;for(let a of o)for(let c of a.routes??[]){let f=`${c.method} ${c.root===!0?"(root) ":""}${c.path}`,h=r.get(f);if(h)throw new n(`plugins.${a.id}.routes`,`"${f}" is already registered by "${h}"`);r.set(f,a.id)}}function $n(o){let i=o?.locales,r=o?.defaultLocale??i?.[0]??"en";return{defaultLocale:r,locales:i??[r]}}function In(o){let i=o.i18n;if(!i)return;let r=i.locales;if(r!==void 0){if(r.length===0)throw new n("i18n.locales","at least one locale; leave the section out for a single-language site");for(let c of r)if(!Sn.test(c))throw new n("i18n.locales",`"${c}" is not a locale code; use a BCP 47 tag such as "en" or "pt-BR"`);if(new Set(r).size!==r.length)throw new n("i18n.locales","duplicate locale codes")}let a=i.defaultLocale;if(a!==void 0&&r&&!r.includes(a))throw new n("i18n.defaultLocale",`"${a}" is not in i18n.locales (${r.map((c)=>`"${c}"`).join(", ")})`)}function Jn(o){let i=o.rbac;if(!i)return;for(let[r,a]of Object.entries(i.roles)){if(!/^[a-z][a-z0-9_-]*$/.test(r))throw new n(`rbac.roles.${r}`,"a role name must be lowercase letters, digits, dashes and underscores, starting with a letter");for(let c of a){if(c==="*")continue;if(!/^[a-z0-9_*-]+:[a-z0-9_*-]+$/.test(c))throw new n(`rbac.roles.${r}`,`"${c}" is not a permission; use "collection:action" or "*"`)}}if(i.defaultRole&&!(i.defaultRole in i.roles))throw new n("rbac.defaultRole",`"${i.defaultRole}" is not one of the configured roles`)}function Wn(o){let i=o.admin?.auth;if(!i)return;let r=new Set;for(let a of i.methods){if(r.has(a))throw new n("admin.auth.methods",`"${a}" is listed twice`);r.add(a)}for(let a of i.apiKeys?.scopes??[])if(!_e(a))throw new n("admin.auth.apiKeys.scopes",`"${a}" is not a scope; use "read", "write", "delete", "*" or "collection:action"`);if(i.sso?.mapRoles&&!o.rbac)throw new n("admin.auth.sso.mapRoles","maps claims onto roles, but no roles are configured; add rbac.roles")}function En(o,i){let r=o.uploads;if(!r)return;if(r.publicPath!==void 0)Ln(r.publicPath,i);if(r.limits?.maxFileSize)se(r.limits.maxFileSize,"uploads.limits.maxFileSize");let a=r.retention?.purgeAfter;if(typeof a==="string")w(a,"uploads.retention.purgeAfter");let c=r.images,f=c?.quality;if(f!==void 0&&(f<1||f>100))throw new n("uploads.images.quality","must be between 1 and 100");for(let[h,g]of Object.entries(c?.variants?.sizes??{})){if(!/^[a-z][a-z0-9-]*$/.test(h))throw new n(`uploads.images.variants.sizes.${h}`,"a size name ends up in a URL; use lowercase letters, digits and dashes");if(io.includes(h))throw new n(`uploads.images.variants.sizes.${h}`,`"${h}" is a media endpoint; pick another size name`);if(g.width===void 0&&g.height===void 0)throw new n(`uploads.images.variants.sizes.${h}`,"needs a width, a height, or both");if(g.fit==="cover"&&(g.width===void 0||g.height===void 0))throw new n(`uploads.images.variants.sizes.${h}`,'fit: "cover" needs both a width and a height')}if(c&&!c.processor){let h=c.convert!==void 0?"convert":c.maxDimensions!==void 0?"maxDimensions":c.variants?.mode==="pregenerate"?'variants.mode: "pregenerate"':null;if(h)throw new n("uploads.images.processor",`${h} has to render pixels, and nothing here can. Add a processor from "@heyo-sh/heyo-cms/uploads" (sharpImages() on Node, cloudflareImages() on Workers), or drop the option.`)}}function Fn(o){for(let i of Object.values(o))for(let[r,a]of Object.entries(i.fields)){if(a.type!=="slug")continue;let c=a.options.from;if(c===void 0)continue;let f=i.fields[String(c)],h=`collections.${i.name}.fields.${r}.from`;if(!f||c===r)throw new n(h,`"${String(c)}" is not another field of ${i.name}`);if(!["text","textarea","email","url","select"].includes(f.type))throw new n(h,`"${String(c)}" is a ${f.type} field; a slug is made from text`)}}function Ln(o,i){let r=x(o.trim()),a="uploads.publicPath";if(r.length===0&&o.trim().startsWith("/"))throw new n("uploads.publicPath",'cannot be "/"; use a path such as "/media"');if(!r.startsWith("/"))throw new n("uploads.publicPath",'must start with "/"');if(!r.split("/").slice(1).every((h)=>/^[A-Za-z0-9._~-]+$/.test(h)))throw new n("uploads.publicPath","may only contain letters, digits, dots, dashes, underscores and tildes between slashes");let f=(h,g)=>h===g||h.startsWith(`${g}/`);if(f(r,i)||f(i,r))throw new n("uploads.publicPath",`"${r}" overlaps basePath "${i}"; files are served from <basePath>/media already — pick a path outside it, such as "/media"`)}function Mn(o){let i=o.ai;if(!i)return;let r=new Set(Object.keys(i.auth??{})),a=i.storage?.secret!==void 0;if(r.size===0&&!a&&i.complete===void 0)throw new n("ai.auth","AI is configured without credentials. Add ai.auth, set ai.storage.secret to manage keys in the panel, or remove the section to disable AI");if(!a&&i.complete===void 0&&!r.has(i.defaultModel.provider))throw new n("ai.defaultModel.provider",`"${i.defaultModel.provider}" has no entry in ai.auth`);let c=i.assistant,f=c?.model?.provider;if(f&&!a&&i.complete===void 0&&!r.has(f))throw new n("ai.assistant.model.provider",`"${f}" has no entry in ai.auth`);for(let[h,g]of[["maxTurns",1],["maxToolCalls",1],["timeoutMs",1000]]){let C=c?.[h];if(C===void 0)continue;if(!Number.isInteger(C)||C<g)throw new n(`ai.assistant.${h}`,`must be an integer of at least ${g}; it is a budget the server enforces, not a hint to the model`)}if(i.storage&&i.storage.secret.length<16)throw new n("ai.storage.secret","must be at least 16 characters; it encrypts the provider keys in the database")}function Hn(o){let i=o.webhooks;if(!i?.enabled)return;if(!i.signing?.secret)throw new n("webhooks.signing.secret","webhooks must be signed; set a secret");if(i.delivery?.timeout)w(i.delivery.timeout,"webhooks.delivery.timeout")}function Bn(o){let i=o.trim();if(!i.startsWith("/"))throw new n("admin.path",'must start with "/"');if(/[?#]/.test(i)||i.includes("//"))throw new n("admin.path","cannot contain a query, a fragment or an empty segment");let r=x(i);if(r.length===0)return"";return r}function Nn(o){let i=o.trim();if(!i.startsWith("/"))throw new n("basePath",'must start with "/"');if(/[?#]/.test(i))throw new n("basePath","cannot contain a query or fragment");if(i.includes("//"))throw new n("basePath","cannot contain empty segments");let r=x(i);if(r.length===0)throw new n("basePath",'cannot be "/"');return r}function zn(o){return[...Object.values(o.collections),...Object.values(o.globals)].map((i)=>({name:i.name,slug:i.slug,kind:i.kind,fields:Object.entries(i.fields).map(([r,a])=>({name:r,type:a.type,localized:a.localized,required:a.required}))}))}function Gn(o){let i=o.uploads;if(!i)return null;let r=i.retention?.purgeAfter??"30d";return{id:typeof i.storage==="function"?"unresolved":i.storage.id,variants:i.images?.variants?.mode??null,processor:i.images?.processor?.id??null,purgeAfter:r===!1?null:r}}function qn(o){return o.plugins.map((i)=>({id:i.id,collections:Object.keys(i.schema?.collections??{}).sort(),tables:(i.schema?.tables??[]).map((r)=>r.name).sort(),routes:i.routes?.length??0,hooks:(i.hooks?.length??0)+o.pluginHooks.filter((r)=>r.plugin===i.id).length,migrations:(i.migrations??[]).map((r)=>r.id),client:i.client!==void 0,admin:i.admin!==void 0}))}function Un(o){let i=o.admin.auth;return{methods:i?.methods??[],twoFactor:i?.twoFactor===!0,apiKeys:i?.apiKeys?.enabled===!0,sso:i?.sso?.issuer??null,roles:Object.keys(o.rbac?.roles??{}).sort(),customRoles:o.rbac?.customRoles===!0}}function Kn(o){return o.replaceAll("_"," ").replace(/^./,(i)=>i.toUpperCase())}function bt(o="system"){return{id:o,source:"session",roles:["admin"],permissions:["*"]}}
2
+ export{ut,Ie,He,zt,pt,mt,ft,ht,xn,Ht,yt,te,Bt,Vt,Gt,An,Kt,Zt,Yn,Qn,Xn,bt};
@@ -0,0 +1,3 @@
1
+ import{Z,Le,Ot,_,j}from"./index-2j6d79fk.js";import{l}from"./index-pkxgzw6e.js";import{t}from"./index-q6jkbsjp.js";import{d}from"./index-9g2n7xa6.js";import{X}from"./index-twqpdtfh.js";import{ie,fn}from"./index-cnzt9x9x.js";import{b}from"./index-qgtvymh2.js";import{e}from"./index-x72d1hzh.js";var K="v1",ee=12;async function L(n){if(n.length<16)throw new e("ai.storage.secret must be at least 16 characters; it encrypts provider keys.",{status:500,code:"ai_secret_too_short"});let i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return crypto.subtle.importKey("raw",i,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function M(n,i){let r=await L(i),a=crypto.getRandomValues(new Uint8Array(ee)),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},r,new TextEncoder().encode(n));return[K,ie(a),ie(new Uint8Array(c))].join(".")}async function I(n,i){let[r,a,c]=n.split(".");if(r!==K||!a||!c)throw new e("A stored provider key is not in a format this version can read.",{status:500,code:"ai_credential_unreadable"});let s=await L(i);try{let m=await crypto.subtle.decrypt({name:"AES-GCM",iv:fn(a)},s,fn(c));return new TextDecoder().decode(m)}catch{throw new e("A stored provider key could not be decrypted; ai.storage.secret has probably changed. Re-enter the key in the panel.",{status:500,code:"ai_credential_unreadable"})}}function E(n){return n.length<=4?"****":`…${n.slice(-4)}`}var z;async function F(){return z??=import("@mariozechner/pi-ai").catch(()=>{throw new e('AI needs "@mariozechner/pi-ai". Install it, or set ai.complete to your own implementation.',{status:500,code:"ai_runtime_missing"})}),z}async function Rn(n){let{getModel:i}=await F(),r;try{r=i(n.provider,n.model)}catch{r=void 0}if(r)return r;throw await Tn(n.provider,n.model),new e(`pi could not resolve ${n.provider}/${n.model}.`,{status:500,code:"ai_unknown_model"})}function V(n,i){let r=Sn(n);if(r.includes(i.type))return;throw new e(`The provider "${n}" needs ${r.map((a)=>`"${a}"`).join(" or ")} credentials.`,{status:500,code:"ai_auth_mismatch"})}async function to(n,i){switch(V(n,i),i.type){case"api-key":return{getApiKey:()=>i.token};case"oauth":return{getApiKey:()=>i.getAccessToken()};case"aws":{let{streamSimple:r}=await F();return{streamFn:(a,c,s)=>r(a,c,{...s,region:i.region,...i.accessKeyId===void 0?{}:{accessKeyId:i.accessKeyId},...i.secretAccessKey===void 0?{}:{secretAccessKey:i.secretAccessKey}})}}}}var te=new Set(["github-copilot","openai-codex"]);function Sn(n){if(n==="amazon-bedrock")return["aws"];if(te.has(n))return["oauth"];return["api-key"]}async function Tn(n,i){let{getModel:r,getProviders:a}=await F();try{if(r(n,i))return}catch{}if(!a().includes(n))throw new e(`The AI provider "${n}" is not in pi's catalogue.`,{status:400,code:"ai_unknown_provider"});throw new e(`The provider "${n}" has no model called "${i}".`,{status:400,code:"ai_unknown_model"})}async function no(n){try{let{getModels:i}=await F();return i(n).map((r)=>r.id)}catch{return[]}}var Ke=async(n)=>{let{complete:i,stream:r}=await F(),{model:a,auth:c}=n;V(a.provider,c);let s=await Rn(a),m={systemPrompt:n.system,messages:[{role:"user",content:[{type:"text",text:n.prompt},...(n.images??[]).map((u)=>({type:"image",data:ne(u.data),mimeType:u.contentType}))],timestamp:Date.now()}]},f={...n.maxTokens===void 0?{}:{maxTokens:n.maxTokens},...n.signal===void 0?{}:{signal:n.signal},...c.type==="api-key"?{apiKey:c.token}:{},...c.type==="oauth"?{apiKey:await c.getAccessToken()}:{},...c.type==="aws"?{region:c.region,...c.accessKeyId===void 0?{}:{accessKeyId:c.accessKeyId},...c.secretAccessKey===void 0?{}:{secretAccessKey:c.secretAccessKey}}:{}},A=await i(s,m,f);if(A.stopReason==="error"||A.errorMessage)throw new e(A.errorMessage??"The model returned an error.",{status:502,code:"ai_provider_error"});return{text:A.content.filter((u)=>u.type==="text").map((u)=>u.text).join(""),usage:Cn(A.usage)}};function Cn(n){return{input:n.input??0,output:n.output??0,total:n.totalTokens??(n.input??0)+(n.output??0),cost:n.cost?.total??0}}function ne(n){let i="";for(let r of n)i+=String.fromCharCode(r);return btoa(i)}async function q(n){let i={input:0,output:0,total:0,cost:0},r=async(s)=>{if(!s.trim())return s;let m=await n.complete({system:"Translate CMS text. Answer with the translation only, without quotes or a preamble. Keep names, placeholders and URLs intact.",prompt:`Translate from ${n.sourceLocale} to ${n.locale}. This text belongs to the ${n.fieldName} field:
2
+
3
+ ${s}`,...n.signal===void 0?{}:{signal:n.signal}});i.input+=m.usage.input,i.output+=m.usage.output,i.total+=m.usage.total,i.cost+=m.usage.cost;let f=m.text.trim();if(!f)throw Error(`AI returned an empty translation for ${n.fieldName}.`);let A=s.slice(0,s.length-s.trimStart().length),o=s.slice(s.trimEnd().length);return`${A}${f}${o}`},a=async(s)=>{if(Array.isArray(s)){let f=[];for(let A of s)f.push(await a(A));return f}if(!s||typeof s!=="object")return s;let m={...s};if(s.type==="text"&&typeof s.text==="string")m.text=await r(s.text);if(s.type==="image"&&s.attrs&&typeof s.attrs==="object"&&!Array.isArray(s.attrs)){let f={...s.attrs};for(let A of["alt","title"])if(typeof f[A]==="string")f[A]=await r(f[A]);m.attrs=f}if(Array.isArray(s.content))m.content=await a(s.content);return m},c=await a(n.value);return{value:c,preview:X(c),usage:i}}var k="cms_ai_credentials";function St(n){let{config:i}=n,r=i.ai?.complete??Ke,a=async(o)=>{try{return await r(o)}catch(u){if(u instanceof e)throw u;if(o.signal?.aborted)throw new e("The request was cancelled.",{status:499,code:"ai_aborted",cause:u});let p=u instanceof Error?u.message:"The AI provider could not complete the request.";throw new e(p,{status:502,code:"ai_provider_error",cause:u})}},c=()=>{let o=i.ai;if(!o)throw new e("This deployment has no `ai` section, so AI is switched off.",{status:501,code:"ai_disabled"});return o},s=(o)=>{let u={...i.collections,...i.globals},p=u[o];if(p)return p;let y=Object.values(u).find((h)=>h.slug===o);if(y)return y;throw e.notFound(`No collection called "${o}".`)},m=async(o)=>{let u=c(),p=await oe(n,o);if(p)return{type:"api-key",token:p};let y=u.auth?.[o];if(y)return y;throw new e(`No credentials for the AI provider "${o}". Add them to ai.auth or store them in the panel.`,{status:500,code:"ai_credentials_missing"})},f=async(o)=>{if(!i.uploads)return null;try{let u=await n.cms().media.variant({id:o});if(!u||!u.contentType.startsWith("image/"))return null;let p=new Uint8Array(await new Response(u.body).arrayBuffer());return{contentType:u.contentType,data:p}}catch{return null}},A=async(o,u,p,y)=>{await(await n.database()).transaction((g)=>n.emit(g,[{type:o,data:y===void 0?u:{...u,error:y instanceof Error?y.message:String(y)},previous:null}],{actor:p,...typeof u.collection==="string"?{collection:u.collection}:{},...typeof u.documentId==="string"?{documentId:u.documentId}:{}})),n.deliver()};return{get enabled(){return i.ai!==void 0},get assistantEnabled(){return i.ai!==void 0&&i.ai.assistant?.enabled!==!1},actions(o){return Le(o)},async run(o){let u=c(),p=s(o.collection),y=o.actor??null,h=o.locale??i.i18n.defaultLocale,g=p.fields[o.field];if(!g)throw e.notFound(`"${o.field}" is not a field of ${p.name}.`);let x=o.action==="generate"?g.aiGenerate:g.ai?.[o.action],P=o.variantTranslation===!0&&o.action==="translate"&&g.localized&&["text","textarea","richText","email","url"].includes(g.type);if(x===void 0&&!P)throw e.notFound(`"${o.action}" is not configured on ${p.name}.${o.field}.`);let S=x===void 0||x===!0?{}:x,T=Z(o.action)??Ot(o.action,S.prompt??"");if(T.requiresLocalized&&!g.localized)throw e.validation(`"${o.action}" needs a localized field; ${p.name}.${o.field} stores one value for every language.`);let C=o.sourceLocale??(T.requiresLocalized?i.i18n.defaultLocale:h),{document:R,stored:D}=await U(n,p,o,h),G=T.requiresLocalized&&C!==h?(await U(n,p,o,C,o.variantTranslation===!0)).document:R;await _(p,{actor:y,operation:"update",locale:h,rbac:i.rbac,...D===void 0?{}:{record:D}}),j(p,{[o.field]:null},y,h);let H=re(p,y,h),W=(S.context??[]).filter((w)=>{if(!(w in p.fields))throw e.validation(`ai.context names "${w}", which is not a field of ${p.name}.`);return H.has(w)}),v=S.model??u.defaultModel,Q=await m(v.provider),J={action:o.action,value:G[o.field]??null,field:g,fieldName:o.field,collection:p,context:Object.fromEntries(W.map((w)=>[w,R[w]??null])),document:R,locale:h,sourceLocale:C,options:S,model:v,actor:y,loadImage:f,complete:(w)=>a({...w,model:v,auth:Q}),...o.signal===void 0?{}:{signal:o.signal}},Y=Date.now();try{let w=P&&g.type==="richText"?await q(J):await T.run(J);return await A("ai.task.completed",{collection:p.name,field:o.field,action:o.action,locale:h,provider:v.provider,model:v.model,usage:w.usage,durationMs:Date.now()-Y,...o.id===void 0?{}:{documentId:o.id}},y),{collection:p.name,field:o.field,action:o.action,value:w.value,preview:w.preview,model:v,usage:w.usage}}catch(w){throw await A("ai.task.failed",{collection:p.name,field:o.field,action:o.action,locale:h,provider:v.provider,model:v.model,...o.id===void 0?{}:{documentId:o.id}},y,w),w}},runAssistant(o){return async function*(){let{runAssistant:u}=await import("./run-mtgvmy5x.js");yield*u({args:o,config:i,cms:n.cms(),database:()=>n.database(),authFor:m,record:A})}()},approveAssistantPlan(o){return import("./run-mtgvmy5x.js").then(({approvePlan:u})=>u({args:o,config:i,cms:n.cms(),database:()=>n.database(),record:A}))},async providers(){let o=i.ai,u=new Map;for(let[y,h]of Object.entries(o?.auth??{}))u.set(y,{provider:y,configured:!0,source:"config",type:h.type,hint:null,updatedAt:null});if(o?.storage?.secret){let y=await n.database(),h=await y.transaction((g)=>y.query(g,{table:k}));for(let g of h)u.set(String(g.provider),{provider:String(g.provider),configured:!0,source:"database",type:"api-key",hint:g.hint===null||g.hint===void 0?null:String(g.hint),updatedAt:l(g.updated_at)})}let p=o?.defaultModel.provider;if(p&&!u.has(p))u.set(p,{provider:p,configured:!1,source:null,type:null,hint:null,updatedAt:null});return[...u.values()].sort((y,h)=>y.provider.localeCompare(h.provider))},async setCredential(o){let p=c().storage?.secret;if(!p)throw new e("Set ai.storage.secret to store provider keys in the database; without it keys can only come from ai.auth.",{status:501,code:"ai_storage_disabled"});let y=o.token.trim();if(y.length===0)throw e.validation("A provider key cannot be empty.");let h=await n.database(),g=new Date,x=await M(y,p),P=E(y);return await h.transaction(async(T)=>{let C=d(h,T);if(await C.findOne(k,t("provider",o.provider)))await C.update(k,t("provider",o.provider),{secret:x,hint:P,updated_at:g});else await C.insert(k,{id:b("aic"),provider:o.provider,auth_type:"api-key",secret:x,hint:P,created_at:g,updated_at:g});return{provider:o.provider,configured:!0,source:"database",type:"api-key",hint:P,updatedAt:g.toISOString()}})},async removeCredential(o){c();let u=await n.database();return u.transaction(async(p)=>await d(u,p).delete(k,t("provider",o.provider))>0)}}}async function oe(n,i){let r=n.config.ai?.storage?.secret;if(!r)return null;let a=await n.database(),c=await a.transaction(async(s)=>d(a,s).findOne(k,t("provider",i)));if(!c||typeof c.secret!=="string")return null;return I(c.secret,r)}async function U(n,i,r,a,c=!1){let s=n.cms(),m=r.actor??null,f;if(i.kind==="global"){let o=s.globals[i.name];if(o)f=await o.get({actor:m,locale:a,...c?{fallbackLocale:!1}:{}})}else if(r.id){let A=s.api[i.name],o=A?await A.findById(r.id,{actor:m,locale:a,...c?{fallbackLocale:!1}:{}}):null;if(!o)throw e.notFound(`No ${i.name} with id "${r.id}", or it is not readable.`);f=o}return{document:{...f??{},...r.document??{}},stored:f}}function re(n,i,r){let a=new Set;for(let[c,s]of Object.entries(n.fields)){let m=s.access?.read;if(m&&!m({actor:i,locale:r}))continue;a.add(c)}return a}function At(n,i,r){let a=n.i18n.defaultLocale,c=Object.values(n.collections).map((f)=>B(f,i,a)).filter((f)=>f!==null),s=Object.values(n.globals).map((f)=>B(f,i,a)).filter((f)=>f!==null),m={collections:c,globals:s,defaultLocale:a,locales:r,media:n.uploads!==void 0,trash:n.trash.enabled};return{...m,fingerprint:ae(m)}}function B(n,i,r){if(!O(n,"read",i,r))return null;let a=[];for(let[c,s]of Object.entries(n.fields)){let m=s.access?.read;if(m&&!m({actor:i,locale:r}))continue;a.push(se(c,s,n,i,r))}return{name:n.name,slug:n.slug,label:n.label,kind:n.kind,titleField:Rt(n),fields:a,can:{read:!0,create:n.kind==="collection"&&O(n,"create",i,r),update:O(n,"update",i,r),delete:n.kind==="collection"&&O(n,"delete",i,r)}}}function se(n,i,r,a,c){let s=i.options,m=N(s.options),f=i.type==="list"&&typeof s.fields==="object"&&s.fields!==null?Object.entries(s.fields).map(([A,o])=>{let u=N(o.options.options);return{name:A,type:o.type,required:o.required,...u&&u.length>0?{options:u}:{}}}):void 0;return{name:n,type:i.type,label:typeof s.label==="string"?s.label:n,required:i.required,localized:i.localized===!0,...m&&m.length>0?{options:m}:{},...i.relationTo===void 0?{}:{relationTo:i.relationTo},...f?{rowFields:f}:{},writable:kt(r,n,a,c)}}function N(n){if(!Array.isArray(n))return;return n.map((i)=>typeof i==="string"?i:typeof i==="object"&&i!==null?String(i.value??""):"").filter((i)=>i.length>0)}function kt(n,i,r,a){let c=n.fields[i];if(!c)return!1;if(c.options.readOnly===!0)return!1;try{return j(n,{[i]:null},r,a),!0}catch{return!1}}function Xt(n,i,r,a){let c=n.fields[i]?.access?.read;return c?c({actor:r,locale:a})===!0:!0}function O(n,i,r,a){let c=n.access[i];if(!c)return!0;try{let s=c({actor:r,operation:i,locale:a});if(s instanceof Promise)return!0;return s!==!1}catch{return!0}}function Rt(n){let i=n.admin?.useAsTitle;if(i!==void 0&&n.fields[i])return i;for(let a of["title","name","label"])if(n.fields[a])return a;return Object.entries(n.fields).find(([,a])=>a.type==="text")?.[0]??null}function ae(n){let i=JSON.stringify(n),r=2166136261;for(let a=0;a<i.length;a+=1)r^=i.charCodeAt(a),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}export{Rn,to,Sn,Tn,no,Ke,Cn,At,kt,Xt,Rt,St};
@@ -1,5 +1,5 @@
1
- import{Ue,Fn}from"./index-vzhxn50e.js";import{_t}from"./index-s9x07zb3.js";import{bo}from"./index-8nzmqy0f.js";import{n}from"./index-x72d1hzh.js";import{mkdir as m,readdir as M,readFile as f,writeFile as h}from"node:fs/promises";import{join as p}from"node:path";var y="meta/snapshot.json",w="meta/plugins.json";class an{directory;constructor(t){this.directory=t}async readSnapshot(){try{let t=await f(p(this.directory,y),"utf8");return JSON.parse(t)}catch{return _t()}}async writeSnapshot(t){await m(p(this.directory,"meta"),{recursive:!0}),await h(p(this.directory,y),`${JSON.stringify(t,null,2)}
1
+ import{Ue,Nn}from"./index-q6ak9ph4.js";import{$t}from"./index-qkqtxr65.js";import{Ao}from"./index-qgtvymh2.js";import{n}from"./index-x72d1hzh.js";import{mkdir as m,readdir as M,readFile as f,writeFile as h}from"node:fs/promises";import{join as p}from"node:path";var y="meta/snapshot.json",w="meta/plugins.json";class ln{directory;constructor(t){this.directory=t}async readSnapshot(){try{let t=await f(p(this.directory,y),"utf8");return JSON.parse(t)}catch{return $t()}}async writeSnapshot(t){await m(p(this.directory,"meta"),{recursive:!0}),await h(p(this.directory,y),`${JSON.stringify(t,null,2)}
2
2
  `,"utf8")}async readPluginLog(){try{let t=await f(p(this.directory,w),"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.filter((i)=>typeof i==="string"):[]}catch{return[]}}async writePluginLog(t){await m(p(this.directory,"meta"),{recursive:!0}),await h(p(this.directory,w),`${JSON.stringify(t,null,2)}
3
- `,"utf8")}async list(){let t;try{t=await M(this.directory)}catch{return[]}let r=[];for(let i of t.sort()){let c=/^(\d{4}_[a-z0-9_]+)\.(sql|json)$/.exec(i);if(!c)continue;let o=await f(p(this.directory,i),"utf8"),s=c[1],a=c[2];r.push({id:s,file:i,checksum:bo(o),artifact:{id:s,extension:a,content:o,summary:P(o,a)}})}return r}async write(t){await m(this.directory,{recursive:!0});let r=`${t.id}.${t.extension}`;return await h(p(this.directory,r),t.content,"utf8"),r}async nextSequence(){let r=(await this.list()).at(-1),i=r?Number(r.id.slice(0,4))+1:0;return String(i).padStart(4,"0")}}function P(t,r){if(r==="json")return JSON.parse(t).summary??[];return t.split(`
4
- `).filter((i)=>i.startsWith("-- ")&&!/^-- \d{4}_/.test(i)).map((i)=>i.slice(3))}async function Zo(t){let{adapter:r,store:i}=t;if(t.plugins.length===0)return[];let c=await i.readPluginLog(),o=[],s=new Set(c);for(let a of t.plugins){let e=`${a.plugin}:${a.id}`;if(s.has(e))continue;if(a.steps.length===0){s.add(e);continue}let u=`${await i.nextSequence()}_${S(a.plugin)}_${S(a.id)}`,d=r.render(a.steps,u),l=await i.write(d);s.add(e),o.push({id:u,file:l})}if(o.length>0)await i.writePluginLog([...s]);return o}function S(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}async function Dn(t){let{adapter:r,store:i,target:c}=t,o=await i.readSnapshot(),s=r.plan(o,c),a;if(s.length>0){let u=`${await i.nextSequence()}_${t.name??Fn(s)}`,d=r.render(s,u),l=await i.write(d);await i.writeSnapshot(c),a={id:u,file:l,summary:d.summary}}let e=await Zo({adapter:r,store:i,plugins:t.plugins??[]});if(!a)return{created:!1,summary:[],...e.length===0?{}:{plugins:e}};return{created:!0,id:a.id,file:a.file,summary:a.summary,...e.length===0?{}:{plugins:e}}}async function qn(t){let{adapter:r,store:i}=t,[c,o]=await Promise.all([i.list(),r.listAppliedMigrations()]),s=new Map(o.map((e)=>[e.id,e])),a={applied:[],alreadyApplied:0};for(let e of c){let g=s.get(e.id);if(g){x(e,g.checksum),a.alreadyApplied+=1;continue}await r.applyMigration(e.artifact),await r.recordMigration(e.id,e.checksum),a.applied.push(e.id)}return a}async function Ln(t){let{adapter:r,store:i}=t,[c,o]=await Promise.all([i.list(),r.listAppliedMigrations()]),s=new Map(o.map((e)=>[e.id,e])),a={applied:[],pending:[],modified:[],unplanned:[]};for(let e of c){let g=s.get(e.id);if(!g){a.pending.push(e.id);continue}if(a.applied.push(e.id),g.checksum!==e.checksum)a.modified.push(e.id)}if(t.target){let e=await i.readSnapshot();a.unplanned=r.plan(e,t.target).map((g)=>Ue(g))}return a}function x(t,r){if(t.checksum===r)return;throw new n(t.file,"was modified after it was applied; revert it and write a new migration instead")}
5
- export{an,Zo,Dn,qn,Ln};
3
+ `,"utf8")}async list(){let t;try{t=await M(this.directory)}catch{return[]}let r=[];for(let i of t.sort()){let c=/^(\d{4}_[a-z0-9_]+)\.(sql|json)$/.exec(i);if(!c)continue;let o=await f(p(this.directory,i),"utf8"),s=c[1],a=c[2];r.push({id:s,file:i,checksum:Ao(o),artifact:{id:s,extension:a,content:o,summary:P(o,a)}})}return r}async write(t){await m(this.directory,{recursive:!0});let r=`${t.id}.${t.extension}`;return await h(p(this.directory,r),t.content,"utf8"),r}async nextSequence(){let r=(await this.list()).at(-1),i=r?Number(r.id.slice(0,4))+1:0;return String(i).padStart(4,"0")}}function P(t,r){if(r==="json")return JSON.parse(t).summary??[];return t.split(`
4
+ `).filter((i)=>i.startsWith("-- ")&&!/^-- \d{4}_/.test(i)).map((i)=>i.slice(3))}async function tr(t){let{adapter:r,store:i}=t;if(t.plugins.length===0)return[];let c=await i.readPluginLog(),o=[],s=new Set(c);for(let a of t.plugins){let e=`${a.plugin}:${a.id}`;if(s.has(e))continue;if(a.steps.length===0){s.add(e);continue}let u=`${await i.nextSequence()}_${S(a.plugin)}_${S(a.id)}`,d=r.render(a.steps,u),l=await i.write(d);s.add(e),o.push({id:u,file:l})}if(o.length>0)await i.writePluginLog([...s]);return o}function S(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}async function qn(t){let{adapter:r,store:i,target:c}=t,o=await i.readSnapshot(),s=r.plan(o,c),a;if(s.length>0){let u=`${await i.nextSequence()}_${t.name??Nn(s)}`,d=r.render(s,u),l=await i.write(d);await i.writeSnapshot(c),a={id:u,file:l,summary:d.summary}}let e=await tr({adapter:r,store:i,plugins:t.plugins??[]});if(!a)return{created:!1,summary:[],...e.length===0?{}:{plugins:e}};return{created:!0,id:a.id,file:a.file,summary:a.summary,...e.length===0?{}:{plugins:e}}}async function Ln(t){let{adapter:r,store:i}=t,[c,o]=await Promise.all([i.list(),r.listAppliedMigrations()]),s=new Map(o.map((e)=>[e.id,e])),a={applied:[],alreadyApplied:0};for(let e of c){let g=s.get(e.id);if(g){x(e,g.checksum),a.alreadyApplied+=1;continue}await r.applyMigration(e.artifact),await r.recordMigration(e.id,e.checksum),a.applied.push(e.id)}return a}async function Fn(t){let{adapter:r,store:i}=t,[c,o]=await Promise.all([i.list(),r.listAppliedMigrations()]),s=new Map(o.map((e)=>[e.id,e])),a={applied:[],pending:[],modified:[],unplanned:[]};for(let e of c){let g=s.get(e.id);if(!g){a.pending.push(e.id);continue}if(a.applied.push(e.id),g.checksum!==e.checksum)a.modified.push(e.id)}if(t.target){let e=await i.readSnapshot();a.unplanned=r.plan(e,t.target).map((g)=>Ue(g))}return a}function x(t,r){if(t.checksum===r)return;throw new n(t.file,"was modified after it was applied; revert it and write a new migration instead")}
5
+ export{ln,tr,qn,Ln,Fn};
@@ -1,14 +1,14 @@
1
- import{he}from"./index-g041kfa5.js";import{X}from"./index-hbx67b20.js";import{It,E}from"./index-sgdnp83t.js";import{e,n}from"./index-x72d1hzh.js";var p=new Map;function pe(t){if(!/^[a-z][a-z0-9-]*$/.test(t.id))throw new n(`ai.actions.${t.id}`,"an action id becomes a URL segment; use lowercase letters, digits and dashes");let i=p.get(t.id);if(i&&i!==t)throw new n(`ai.actions.${t.id}`,"a different action with this id is already registered");return p.set(t.id,t),t}function Y(t){return p.get(t)}function Le(t){return[...p.values()].filter((i)=>i.appliesTo.includes("*")||i.appliesTo.includes(t)).map((i)=>i.id).sort()}function me(){return[...p.keys()].sort()}function Ct(t,i){return{id:t,appliesTo:["*"],label:t,prompt:i,run:(r)=>u(r,i)}}var d=["text","textarea","richText","email","url"],Ao=pe({id:"generate",appliesTo:d,label:"Generate",prompt:"Write this field from the document below.",async run(t){return u(t,h(t))}}),ko=pe({id:"improve",appliesTo:d,label:"Improve",prompt:"Improve the current value: keep its meaning, tighten the wording, remove filler.",async run(t){let i=w(t);if(i.trim().length===0)throw e.validation(`There is nothing in ${t.fieldName} to improve yet.`);return u(t,[h(t),"","Current value:",i].join(`
2
- `))}}),Ro=pe({id:"summarize",appliesTo:d,label:"Summarise",prompt:"Summarise the document below into this field.",async run(t){return u(t,h(t))}}),ro=pe({id:"translate",appliesTo:["*"],label:"Translate",prompt:"Translate the value into the target language.",requiresLocalized:!0,async run(t){let i=w(t);if(i.trim().length===0)throw e.validation(`${t.fieldName} is empty in ${t.sourceLocale??"the source language"}; there is nothing to translate.`);let r=[t.options.prompt??ro.prompt,`Source language: ${t.sourceLocale??"unknown"}.`,`Target language: ${t.locale??"unknown"}.`,"Keep formatting, links and names intact. Answer with the translation only.","",i].join(`
3
- `);return u(t,r)}}),io=pe({id:"alt",appliesTo:["media"],label:"Describe the image",prompt:"Write alternative text for this image: one sentence, describing what is shown, no 'image of' preamble.",async run(t){let i=typeof t.value==="string"?t.value:null;if(!i)throw e.validation(`${t.fieldName} has no file selected yet.`);let r=await t.loadImage(i),o=await t.complete({system:f(t),prompt:[t.options.prompt??io.prompt,r===null?"The image itself is not available; infer from the surrounding content.":"",m(t)].filter((a)=>a.length>0).join(`
1
+ import{he}from"./index-rpdkj3qk.js";import{X}from"./index-twqpdtfh.js";import{It,E}from"./index-pkxgzw6e.js";import{e,n}from"./index-x72d1hzh.js";var p=new Map;function pe(t){if(!/^[a-z][a-z0-9-]*$/.test(t.id))throw new n(`ai.actions.${t.id}`,"an action id becomes a URL segment; use lowercase letters, digits and dashes");let i=p.get(t.id);if(i&&i!==t)throw new n(`ai.actions.${t.id}`,"a different action with this id is already registered");return p.set(t.id,t),t}function Z(t){return p.get(t)}function Le(t){return[...p.values()].filter((i)=>i.appliesTo.includes("*")||i.appliesTo.includes(t)).map((i)=>i.id).sort()}function me(){return[...p.keys()].sort()}function Ot(t,i){return{id:t,appliesTo:["*"],label:t,prompt:i,run:(r)=>u(r,i)}}var d=["text","textarea","richText","email","url"],To=pe({id:"generate",appliesTo:d,label:"Generate",prompt:"Write this field from the document below.",async run(t){return u(t,h(t))}}),Co=pe({id:"improve",appliesTo:d,label:"Improve",prompt:"Improve the current value: keep its meaning, tighten the wording, remove filler.",async run(t){let i=w(t);if(i.trim().length===0)throw e.validation(`There is nothing in ${t.fieldName} to improve yet.`);return u(t,[h(t),"","Current value:",i].join(`
2
+ `))}}),Oo=pe({id:"summarize",appliesTo:d,label:"Summarise",prompt:"Summarise the document below into this field.",async run(t){return u(t,h(t))}}),lo=pe({id:"translate",appliesTo:["*"],label:"Translate",prompt:"Translate the value into the target language.",requiresLocalized:!0,async run(t){let i=w(t);if(i.trim().length===0)throw e.validation(`${t.fieldName} is empty in ${t.sourceLocale??"the source language"}; there is nothing to translate.`);let r=[t.options.prompt??lo.prompt,`Source language: ${t.sourceLocale??"unknown"}.`,`Target language: ${t.locale??"unknown"}.`,"Keep formatting, links and names intact. Answer with the translation only.","",i].join(`
3
+ `);return u(t,r)}}),co=pe({id:"alt",appliesTo:["media"],label:"Describe the image",prompt:"Write alternative text for this image: one sentence, describing what is shown, no 'image of' preamble.",async run(t){let i=typeof t.value==="string"?t.value:null;if(!i)throw e.validation(`${t.fieldName} has no file selected yet.`);let r=await t.loadImage(i),o=await t.complete({system:f(t),prompt:[t.options.prompt??co.prompt,r===null?"The image itself is not available; infer from the surrounding content.":"",m(t)].filter((a)=>a.length>0).join(`
4
4
 
5
- `),...r===null?{}:{images:[r]},...t.options.maxLength===void 0?{}:{maxTokens:v(t.options.maxLength)},...t.signal===void 0?{}:{signal:t.signal}}),s=b(o.text);return{value:s,preview:s,usage:o.usage}}}),so=pe({id:"tags",appliesTo:["multiselect","select","relation"],label:"Suggest values",prompt:"Choose the values that fit the document below.",async run(t){let i=R(t),r=await t.complete({system:f(t),prompt:[t.options.prompt??so.prompt,i.length>0?`Choose only from: ${i.join(", ")}.`:"Answer with short, lowercase values.","Answer with a comma-separated list and nothing else.",m(t)].join(`
5
+ `),...r===null?{}:{images:[r]},...t.options.maxLength===void 0?{}:{maxTokens:v(t.options.maxLength)},...t.signal===void 0?{}:{signal:t.signal}}),s=b(o.text);return{value:s,preview:s,usage:o.usage}}}),uo=pe({id:"tags",appliesTo:["multiselect","select","relation"],label:"Suggest values",prompt:"Choose the values that fit the document below.",async run(t){let i=T(t),r=await t.complete({system:f(t),prompt:[t.options.prompt??uo.prompt,i.length>0?`Choose only from: ${i.join(", ")}.`:"Answer with short, lowercase values.","Answer with a comma-separated list and nothing else.",m(t)].join(`
6
6
 
7
7
  `),...t.signal===void 0?{}:{signal:t.signal}}),o=r.text.split(/[,\n]/).map((l)=>l.trim().replace(/^[-*]\s*/,"")).filter((l)=>l.length>0),s=i.length===0?o:o.filter((l)=>i.includes(l));return{value:t.field.type==="multiselect"||t.field.options.many===!0?s:s[0]??null,preview:s.join(", "),usage:r.usage}}});async function u(t,i){let r=await t.complete({system:f(t),prompt:`${i}
8
8
 
9
9
  ${m(t)}`.trim(),...t.options.maxLength===void 0?{}:{maxTokens:v(t.options.maxLength)},...t.signal===void 0?{}:{signal:t.signal}}),o=r.text.trim();if(t.field.type==="richText")return{value:he(o),preview:o,usage:r.usage};let s=t.field.type==="textarea"?o:b(o),a=t.options.maxLength===void 0?s:s.slice(0,t.options.maxLength);return{value:a,preview:a,usage:r.usage}}function f(t){let i=[`You are an editorial assistant working inside a CMS. You are filling in the "${t.fieldName}" field of a "${t.collection.label}" document.`,`The field type is ${t.field.type}.`];if(t.field.type==="richText")i.push("Answer in Markdown. Do not wrap the answer in a code fence.");else i.push("Answer with the field value only: no preamble, no quotes, no Markdown fences.");if(t.locale)i.push(`Write in the "${t.locale}" locale.`);if(t.options.maxLength!==void 0)i.push(`Stay under ${t.options.maxLength} characters.`);return i.join(" ")}function m(t){let i=Object.entries(t.context).filter(([,r])=>r!==null&&r!==void 0&&r!=="");if(i.length===0)return"";return i.map(([r,o])=>`## ${r}
10
10
  ${g(o)}`).join(`
11
11
 
12
- `)}function g(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map(g).join(", ");if(typeof t==="object"&&t.type)return X(t);return JSON.stringify(t)}function h(t){let i=Y(t.action)?.prompt??"";return t.options.prompt??i}function w(t){return g(t.value)}function R(t){let i=t.field.options.options;if(!Array.isArray(i))return[];return i.filter((r)=>typeof r==="string")}function b(t){return t.replace(/^["'`]+|["'`]+$/g,"").replaceAll(`
13
- `," ").replace(/\s{2,}/g," ").trim()}function v(t){return Math.max(64,Math.ceil(t/3)+32)}var T={read:"read",create:"create",update:"update",delete:"delete",restore:"delete",purge:"delete"};async function _(t,i){let r=t.access[T[i.operation]];if(!r){k(t,i);return}let o=await r({actor:i.actor,operation:i.operation,locale:i.locale,...i.record===void 0?{}:{record:i.record}});if(o===!0)return;if(o===!1)throw C(t,i);return o}function k(t,i){if(!i.rbac)return;let r=It(t.name,i.operation);if(E(i.actor,r))return;throw C(t,i,r)}function C(t,i,r){let o=`${i.operation} ${t.name}`;return i.actor===null?e.unauthorized(`Not allowed to ${o}`):e.forbidden(r?`Not allowed to ${o}; the "${r}" permission is required`:`Not allowed to ${o}`)}var j=new WeakMap;function A(t){let i=j.get(t);if(i)return i;let r={read:[],update:[]};for(let[o,s]of Object.entries(t.fields)){if(s.access?.read)r.read.push(o);if(s.access?.update)r.update.push(o)}return j.set(t,r),r}function on(t){let i=A(t);return i.read.length>0||i.update.length>0}function fe(t,i,r,o){let s=A(i).read.filter((a)=>{let l=i.fields[a]?.access?.read;return l&&!l({actor:r,record:t,locale:o})});for(let a of["scheduledPatch","_fallback"]){let l=t[a];if(l&&typeof l==="object"&&!Array.isArray(l)){let c={...l};for(let y of s)delete c[y];t[a]=c}}if(Array.isArray(t._localeFields))t._localeFields=t._localeFields.filter((a)=>typeof a==="string"&&!s.includes(a));for(let a of s)delete t[a];return t}function I(t,i,r,o,s){let a=[];for(let l of A(t).update){if(!(l in i))continue;let c=t.fields[l]?.access?.update;if(!c)continue;if(!c({actor:r,locale:o,...s===void 0?{}:{record:s}}))a.push(l)}if(a.length===0)return;throw e.forbidden(`Not allowed to write ${a.map((l)=>`"${l}"`).join(", ")} on ${t.name}`)}
14
- export{pe,Y,Le,me,Ct,Ao,ko,Ro,ro,io,so,_,on,fe,I};
12
+ `)}function g(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map(g).join(", ");if(typeof t==="object"&&t.type)return X(t);return JSON.stringify(t)}function h(t){let i=Z(t.action)?.prompt??"";return t.options.prompt??i}function w(t){return g(t.value)}function T(t){let i=t.field.options.options;if(!Array.isArray(i))return[];return i.filter((r)=>typeof r==="string")}function b(t){return t.replace(/^["'`]+|["'`]+$/g,"").replaceAll(`
13
+ `," ").replace(/\s{2,}/g," ").trim()}function v(t){return Math.max(64,Math.ceil(t/3)+32)}var k={read:"read",create:"create",update:"update",delete:"delete",restore:"delete",purge:"delete"};async function _(t,i){let r=t.access[k[i.operation]];if(!r){F(t,i);return}let o=await r({actor:i.actor,operation:i.operation,locale:i.locale,...i.record===void 0?{}:{record:i.record}});if(o===!0)return;if(o===!1)throw C(t,i);return o}function F(t,i){if(!i.rbac)return;let r=It(t.name,i.operation);if(E(i.actor,r))return;throw C(t,i,r)}function C(t,i,r){let o=`${i.operation} ${t.name}`;return i.actor===null?e.unauthorized(`Not allowed to ${o}`):e.forbidden(r?`Not allowed to ${o}; the "${r}" permission is required`:`Not allowed to ${o}`)}var R=new WeakMap;function A(t){let i=R.get(t);if(i)return i;let r={read:[],update:[]};for(let[o,s]of Object.entries(t.fields)){if(s.access?.read)r.read.push(o);if(s.access?.update)r.update.push(o)}return R.set(t,r),r}function rn(t){let i=A(t);return i.read.length>0||i.update.length>0}function fe(t,i,r,o){let s=A(i).read.filter((a)=>{let l=i.fields[a]?.access?.read;return l&&!l({actor:r,record:t,locale:o})});for(let a of["scheduledPatch","_fallback"]){let l=t[a];if(l&&typeof l==="object"&&!Array.isArray(l)){let c={...l};for(let y of s)delete c[y];t[a]=c}}if(Array.isArray(t._localeFields))t._localeFields=t._localeFields.filter((a)=>typeof a==="string"&&!s.includes(a));for(let a of s)delete t[a];return t}function j(t,i,r,o,s){let a=[];for(let l of A(t).update){if(!(l in i))continue;let c=t.fields[l]?.access?.update;if(!c)continue;if(!c({actor:r,locale:o,...s===void 0?{}:{record:s}}))a.push(l)}if(a.length===0)return;throw e.forbidden(`Not allowed to write ${a.map((l)=>`"${l}"`).join(", ")} on ${t.name}`)}
14
+ export{pe,Z,Le,me,Ot,To,Co,Oo,lo,co,uo,_,rn,fe,j};
@@ -1,2 +1,2 @@
1
- import{s,R,t,it,H,M,S,ae,le,m}from"./index-6m1kjq9g.js";import{E,l,u}from"./index-sgdnp83t.js";import{ye}from"./index-abfzb1ve.js";import{T,U,Qe}from"./index-91fa1gzf.js";import{d}from"./index-9g2n7xa6.js";import{Q}from"./index-hbx67b20.js";import{se}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b}from"./index-8nzmqy0f.js";import{e}from"./index-x72d1hzh.js";function V(n,r){let i=r.map((a)=>{let o=pt(n,a.path);return{path:a.path,value:o instanceof Date?o.toISOString():gt(o),date:o instanceof Date}});return ht(JSON.stringify(i))}function J(n,r){let i=mt(n);if(i.length!==r.length)throw new e("This cursor does not match the requested sort order.",{status:400,code:"invalid_cursor"});let a=[];for(let o=0;o<r.length;o+=1){let f=[];for(let C=0;C<o;C+=1){let D=i[C];f.push(t(D.path,pe(D)))}let p=i[o],w=r[o].direction;f.push(w==="desc"?H(p.path,pe(p)):it(p.path,pe(p))),a.push(s(...f))}return R(...a)}function mt(n){try{let r=JSON.parse(yt(n));if(!Array.isArray(r))throw Error("not a cursor");return r}catch{throw new e("This cursor is not readable.",{status:400,code:"invalid_cursor"})}}function pe(n){return n.date&&typeof n.value==="string"?new Date(n.value):n.value}function pt(n,r){if(r in n)return n[r];let i=r.split("."),a=n.data??n;for(let o of i){if(typeof a!=="object"||a===null)return;a=a[o]}return a}function gt(n){if(n===void 0||n===null)return null;if(typeof n==="object")return null;return n}function ht(n){let r=new TextEncoder().encode(n),i="";for(let a of r)i+=String.fromCharCode(a);return btoa(i).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function yt(n){let r=n.replaceAll("-","+").replaceAll("_","/"),i=atob(r.padEnd(Math.ceil(r.length/4)*4,"=")),a=Uint8Array.from(i,(o)=>o.charCodeAt(0));return new TextDecoder().decode(a)}var Re={jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",tiff:"image/tiff"};function xo(n){return Re[n]}function Ee(n){return xt(n)??Mt(n)??At(n)??Ct(n)??St(n)??It(n)}function Me(n){let i={"image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/svg+xml":"svg","image/tiff":"tiff","video/mp4":"mp4","video/webm":"webm","audio/mpeg":"mp3","application/pdf":"pdf","application/json":"json","text/plain":"txt","text/csv":"csv"}[n.toLowerCase()];if(i)return i;let a=n.split("/")[1]?.split(";")[0]?.trim();return a&&/^[a-z0-9.+-]+$/i.test(a)?a:"bin"}function xt(n){let r=[137,80,78,71,13,10,26,10];if(n.length<24||!Ut(n,r))return null;return W("png",ie(n,16),ie(n,20))}function Mt(n){if(n.length<10||G(n,0,3)!=="GIF")return null;return W("gif",oe(n,6),oe(n,8))}function At(n){if(n.length<30||G(n,0,4)!=="RIFF"||G(n,8,4)!=="WEBP")return null;let r=G(n,12,4);if(r==="VP8X")return W("webp",De(n,24)+1,De(n,27)+1);if(r==="VP8 "){if(n[23]!==157||n[24]!==1||n[25]!==42)return null;return W("webp",oe(n,26)&16383,oe(n,28)&16383)}if(r==="VP8L"){if(n[20]!==47)return null;let i=B(n,21),a=B(n,22),o=B(n,23),f=B(n,24);return W("webp",((a&63)<<8|i)+1,((f&15)<<10|o<<2|(a&192)>>6)+1)}return null}function Ct(n){if(n.length<4||n[0]!==255||n[1]!==216)return null;let r=2;while(r+9<n.length){if(n[r]!==255){r+=1;continue}let i=B(n,r+1);if(i===255||i===1||i>=208&&i<=217){r+=2;continue}if(i>=192&&i<=195||i>=197&&i<=199||i>=201&&i<=203||i>=205&&i<=207)return W("jpeg",ge(n,r+7),ge(n,r+5));let o=ge(n,r+2);if(o<2)return null;r+=2+o}return null}function St(n){if(n.length<16||G(n,4,4)!=="ftyp")return null;let r=G(n,8,4),i=r==="avif"||r==="avis";if(!i&&!(r==="heic"||r==="heix"||r==="mif1"))return null;let o=Math.min(n.length-16,65536);for(let f=16;f<o;f+=1){if(G(n,f,4)!=="ispe")continue;let p=ie(n,f+8),w=ie(n,f+12);if(p>0&&w>0&&p<1e5&&w<1e5)return W(i?"avif":"avif",p,w)}return null}function It(n){let r=new TextDecoder().decode(n.subarray(0,2048));if(!/<svg[\s>]/i.test(r))return null;let i=(f)=>{let p=new RegExp(`\\b${f}\\s*=\\s*["']([\\d.]+)`,"i").exec(r);return p?Math.round(Number(p[1])):0},a=i("width"),o=i("height");if(a===0||o===0){let f=/\bviewBox\s*=\s*["']\s*[\d.-]+\s+[\d.-]+\s+([\d.]+)\s+([\d.]+)/i.exec(r);if(f)a=Math.round(Number(f[1])),o=Math.round(Number(f[2]))}return W("svg",a,o)}function W(n,r,i){return{format:n,contentType:Re[n],width:r,height:i}}function B(n,r){return n[r]??0}function ge(n,r){return B(n,r)<<8|B(n,r+1)}function ie(n,r){return B(n,r)*16777216+(B(n,r+1)<<16|B(n,r+2)<<8|B(n,r+3))}function oe(n,r){return B(n,r)|B(n,r+1)<<8}function De(n,r){return B(n,r)|B(n,r+1)<<8|B(n,r+2)<<16}function G(n,r,i){let a="";for(let o=0;o<i;o+=1)a+=String.fromCharCode(B(n,r+o));return a}function Ut(n,r){return r.every((i,a)=>n[a]===i)}function te(n){return Object.keys(n?.variants?.sizes??{})}function ne(n,r){let i=n?.variants?.sizes?.[r];if(!i){let a=te(n);throw e.notFound(a.length>0?`No image size named "${r}"; this configuration declares ${a.join(", ")}`:`No image size named "${r}"; this configuration declares none`)}return i}function bt(n,r,i){let a=ne(n,r),o={...a.width===void 0?{}:{width:a.width},...a.height===void 0?{}:{height:a.height},...a.fit===void 0?{}:{fit:a.fit}};if(n?.quality!==void 0)o.quality=n.quality;if(n?.stripMetadata!==!1)o.stripMetadata=!0;if(n?.focalPoint!==!1&&i.focalPoint)o.position=i.focalPoint;if(n?.crop!==!1&&i.crop)o.crop=i.crop;let f=n?.convert;if(f&&!(f.keep??[]).includes(i.mimeType))o.format=f.to;return o}function ce(n,r){let{width:i,height:a}=r;if(i===null||a===null||i<=0||a<=0)return!1;if(n.crop){let w=n.crop;if(!(w.x<=0&&w.y<=0&&w.width>=i&&w.height>=a))return!1}let o=n.fit??"inside",{width:f,height:p}=n;if(f===void 0&&p===void 0)return!0;if(o==="inside")return(f===void 0||f>=i)&&(p===void 0||p>=a);if(o==="outside")return Math.max(f===void 0?0:f/i,p===void 0?0:p/a)>=1;return!1}function X(n,r){let i=n?.convert;if(!i||(i.keep??[]).includes(r))return r;return`image/${i.to}`}function Be(n,r,i){let a=n.lastIndexOf("/"),o=n.lastIndexOf(".");return`${o>a?n.slice(0,o):n}/${r}.${Me(i)}`}function ue(n,r){let i=ne(n,r),a=new URLSearchParams;if(i.width!==void 0)a.set("w",String(i.width));if(i.height!==void 0)a.set("h",String(i.height));if(i.fit!==void 0)a.set("fit",i.fit);if(n?.quality!==void 0)a.set("q",String(n.quality));return a.toString()}async function Oe(n,r,i,a){if(!n||!n.supports(a.mimeType))return null;return n.transform(r,i,{format:a.mimeType.split("/")[1]??"jpeg",contentType:a.mimeType,width:a.width??0,height:a.height??0})}function je(n,r){let i=n.filename.replace(/\.[^.]*$/,"");return`${ye(i)||"file"}.${Me(r)}`}function he(n,r){if(!n)return null;return`${x(n)}/${encodeURIComponent(r.id)}/${je(r,r.mimeType)}`}function Y(n,r,i={}){let a=n.uploads?.images,o=n.uploads?.publicPath,f=i.variant,p=he(o,r)??`${ke(n)}/${encodeURIComponent(r.id)}/original`;if(f===void 0||f==="original")return p;ne(a,f);let w=a?.processor;if(!w||!w.supports(r.mimeType))return`${p}?${ue(a,f)}`;let C=X(a,r.mimeType);if(C===r.mimeType&&ce(bt(a,f,{mimeType:r.mimeType,crop:r.crop??null,focalPoint:r.focalPoint??null}),{width:r.width??null,height:r.height??null}))return p;if(o)return`${x(o)}/${encodeURIComponent(r.id)}/${encodeURIComponent(f)}/${je(r,C)}`;return`${ke(n)}/${encodeURIComponent(r.id)}/${encodeURIComponent(f)}`}function ke(n){return`${n.basePath==="/"?"":x(n.basePath)}/media`}function ze(n,r,i){let a=Ne(i);if(!a)return null;let o=ne(n,r),{width:f,height:p}=o,w=o.fit??"inside";if(f===void 0&&p===void 0)return a;if((w==="cover"||w==="contain")&&f!==void 0&&p!==void 0){if(w==="contain")return{width:f,height:p};let D=Math.max(f/a.width,p/a.height);return D>1?{width:Math.max(1,Math.round(f/D)),height:Math.max(1,Math.round(p/D))}:{width:f,height:p}}let C=w==="outside"?Math.min(1,Math.max(f===void 0?0:f/a.width,p===void 0?0:p/a.height)):Math.min(f===void 0?1/0:f/a.width,p===void 0?1/0:p/a.height,1);return{width:Math.max(1,Math.round(a.width*C)),height:Math.max(1,Math.round(a.height*C))}}function Fe(n,r,i={}){let a=Je(n,r,i);return a.length<2?null:a.map((o)=>`${o.url} ${o.width}w`).join(", ")}function Je(n,r,i){let a=n.uploads?.images,o=a?.variants?.sizes??{};if(!_t(r.mimeType)||!r.width||!r.height)return[];let f=i.sizes??Object.entries(o).filter(([,N])=>Pt(N)).map(([N])=>N),p=r.crop!==null&&r.crop!==void 0,w=[],C=new Set,D=Ne(r);if(!p&&D)w.push({url:Y(n,r),...D}),C.add(D.width);for(let N of f){let L=ze(a,N,r);if(!L||C.has(L.width))continue;C.add(L.width),w.push({url:Y(n,r,{variant:N}),...L})}return w.sort((N,L)=>N.width-L.width)}function we(n,r,i={}){let a=n.uploads?.images,o=Tt(n,r.alt,i.locale),f=i.sizes??null;if(i.variant!==void 0&&i.variant!=="original"){let D=ze(a,i.variant,r);return{src:Y(n,r,{variant:i.variant}),width:D?.width??null,height:D?.height??null,srcset:null,sizes:null,alt:o}}let p=Je(n,r,i.srcset===void 0?{}:{sizes:i.srcset}),C=r.crop!==null&&r.crop!==void 0?p.at(-1):void 0;return{src:C?.url??Y(n,r),width:C?.width??r.width??null,height:C?.height??r.height??null,srcset:p.length<2?null:p.map((D)=>`${D.url} ${D.width}w`).join(", "),sizes:p.length<2?null:f,alt:o}}function Tt(n,r,i){if(!r)return null;let a=(i===void 0?void 0:r[i])??r[n.i18n.defaultLocale];return typeof a==="string"&&a.trim()!==""?a:null}function Ne(n){if(n.crop)return{width:n.crop.width,height:n.crop.height};if(!n.width||!n.height)return null;return{width:n.width,height:n.height}}function Pt(n){let r=n.fit??"inside";if(r==="inside"||r==="outside")return!0;return n.width===void 0||n.height===void 0}function _t(n){return n.startsWith("image/")&&n!=="image/svg+xml"}var qe=["crop","variants"];function F(n,r,i){let a=u(n.metadata),{crop:o,variants:f,...p}=a,w=String(n.storage_key);return{id:String(n.id),filename:String(n.filename),mimeType:String(n.mime_type),size:Number(n.size??0),width:Le(n.width),height:Le(n.height),storageKey:w,checksum:ve(n.checksum),alt:Ot(n.alt),focalPoint:Dt(n.focal_x,n.focal_y),crop:Rt(o),status:$t(n.status),orphanedAt:l(n.orphaned_at),purgeAfter:l(n.purge_after),purgeError:ve(n.purge_error),metadata:p,variants:Array.isArray(f)?f.filter((C)=>typeof C==="string"):[],createdBy:ve(n.created_by),createdAt:l(n.created_at),updatedAt:l(n.updated_at),url:he(i,{id:String(n.id),filename:String(n.filename),mimeType:String(n.mime_type)})??r.url(w)}}function de(n){return JSON.parse(JSON.stringify(n))}function $t(n){return n==="orphaned"||n==="purging"?n:"active"}function Dt(n,r){if(n===null||n===void 0)return null;if(r===null||r===void 0)return null;return{x:Number(n),y:Number(r)}}function Rt(n){if(typeof n!=="object"||n===null||Array.isArray(n))return null;let r=n,i=["x","y","width","height"].map((a)=>Number(r[a]));if(i.some((a)=>Number.isNaN(a)))return null;return{x:i[0],y:i[1],width:i[2],height:i[3]}}function Ot(n){let r=u(n),i={};for(let[a,o]of Object.entries(r))if(typeof o==="string")i[a]=o;return i}function Le(n){return n===null||n===void 0?null:Number(n)}function ve(n){return n===null||n===void 0?null:String(n)}var kt=86400000,Et=100;async function We(n,r,i){if(n.config.uploads?.retention?.purgeAfter===!1)return[];let a=await n.database();return a.transaction((o)=>a.query(o,{table:T,where:s(t("status","orphaned"),le("purge_after",!0),M("purge_after",r)),orderBy:[m("purge_after","asc"),m("id","asc")],limit:i}))}async function Xe(n,r={}){let i={examined:0,purged:0,reclaimed:0,failed:0};if(!n.config.uploads)return i;let a=r.now??new Date,o=await We(n,a,r.limit??Et);for(let f of o){i.examined+=1;try{let p=await He(n,f,a);if(p==="purged")i.purged+=1;if(p==="reclaimed")i.reclaimed+=1}catch{i.failed+=1}}return i}async function He(n,r,i){let a=await n.storage(),o=F(r,a,n.config.uploads?.publicPath),f=await be(n,async(p,w)=>{if((await w.find(U,t("media_id",o.id))).length>0){if(await w.update(T,s(t("id",o.id),t("status","orphaned")),{status:"active",orphaned_at:null,purge_after:null,purge_error:null,updated_at:i})===0)return"taken";return await Ke(n,p,"media.reclaimed",{...o,status:"active",orphanedAt:null,purgeAfter:null}),"reclaimed"}return await w.update(T,s(t("id",o.id),t("status","orphaned")),{status:"purging",updated_at:i})===1?"claimed":"taken"});if(n.deliver(),f!=="claimed")return f;try{return await a.delete(Ae(o,n.config.uploads)),await be(n,async(p,w)=>{await w.delete(U,t("media_id",o.id)),await w.delete(T,t("id",o.id)),await Ke(n,p,"media.purged",o,{collected:!0})}),n.deliver(),"purged"}catch(p){throw await jt(n,o,p,i),p}}function Yt(n){return{name:"media-gc",failureType:"media.purge",failurePayload:(r)=>({mediaId:String(r.id),storageKey:String(r.storage_key),filename:String(r.filename)}),due:(r,i,a)=>We(n,i,a),run:async(r,i)=>{await He(n,i,new Date)}}}function Ae(n,r){let i=X(r?.images,n.mimeType),a=new Set([...n.variants,...te(r?.images)]);return[n.storageKey,...[...a].map((o)=>Be(n.storageKey,o,i))]}async function jt(n,r,i,a){let o=i instanceof Error?i.message:String(i);await be(n,async(f,p)=>{await p.update(T,t("id",r.id),{status:"orphaned",purge_after:new Date(a.getTime()+kt),purge_error:o.slice(0,1000),updated_at:a})})}async function Ke(n,r,i,a,o={}){await n.emit(r,[{type:i,data:{media:JSON.parse(JSON.stringify(a)),...o},previous:null}],{actor:null,collection:"media",documentId:a.id})}async function be(n,r){let i=await n.database();return i.transaction((a)=>r(a,d(i,a)))}async function xe(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof Blob<"u"&&n instanceof Blob)return new Uint8Array(await n.arrayBuffer());let r=[],i=n.getReader();for(;;){let{done:a,value:o}=await i.read();if(a)break;if(o)r.push(o)}return Z(r)}function Z(n){if(n.length===1)return n[0];let r=n.reduce((o,f)=>o+f.byteLength,0),i=new Uint8Array(r),a=0;for(let o of n)i.set(o,a),a+=o.byteLength;return i}function wt(n){return new ReadableStream({start(r){r.enqueue(n),r.close()}})}function Ve(n){let r="";for(let i of n)r+=i.toString(16).padStart(2,"0");return r}function Yn(n){let r="";for(let i of n)r+=String.fromCharCode(i);return btoa(r)}async function vt(n){let r=typeof n==="string"?new TextEncoder().encode(n):n,i=await crypto.subtle.digest("SHA-256",r);return new Uint8Array(i)}function Ge(n,r){switch(r.toLowerCase()){case"image/jpeg":return zt(n);case"image/png":return Jt(n);case"image/webp":return Nt(n);default:return n}}function zt(n){if(n.length<4||n[0]!==255||n[1]!==216)return n;let r=[n.subarray(0,2)],i=2;while(i+4<=n.length){if(n[i]!==255)break;let a=n[i+1]??0;if(a===216||a===1||a>=208&&a<=215){r.push(n.subarray(i,i+2)),i+=2;continue}if(a===218){r.push(n.subarray(i)),i=n.length;break}let o=(n[i+2]??0)<<8|(n[i+3]??0);if(o<2||i+2+o>n.length)break;if(!Ft(a))r.push(n.subarray(i,i+2+o));i+=2+o}if(i<n.length)r.push(n.subarray(i));return Z(r)}function Ft(n){if(n===254)return!0;if(n===224)return!1;if(n===226)return!1;if(n===238)return!1;return n>=224&&n<=239}function Jt(n){let r=[137,80,78,71,13,10,26,10];if(n.length<8||!r.every((f,p)=>n[p]===f))return n;let i=new Set(["tEXt","zTXt","iTXt","eXIf","tIME","dSIG"]),a=[n.subarray(0,8)],o=8;while(o+8<=n.length){let f=Bt(n,o),p=fe(n,o+4,4),w=12+f;if(w<12||o+w>n.length)break;if(!i.has(p))a.push(n.subarray(o,o+w));if(o+=w,p==="IEND")break}return Z(a)}function Nt(n){if(n.length<12||fe(n,0,4)!=="RIFF"||fe(n,8,4)!=="WEBP")return n;let r=new Set(["EXIF","XMP "]),i=[],a=12,o=!1;while(a+8<=n.length){let w=fe(n,a,4),C=Lt(n,a+4),D=8+C+C%2;if(a+D>n.length)break;if(r.has(w))o=!0;else i.push(n.subarray(a,a+D));a+=D}if(!o)return n;let f=Z(i),p=new Uint8Array(12);return p.set(n.subarray(0,12)),Vt(p,4,f.byteLength+4),Z([p,f])}function Bt(n,r){return(n[r]??0)*16777216+((n[r+1]??0)<<16|(n[r+2]??0)<<8|(n[r+3]??0))}function Lt(n,r){return(n[r]??0)+((n[r+1]??0)<<8)+((n[r+2]??0)<<16)+(n[r+3]??0)*16777216}function Vt(n,r,i){n[r]=i&255,n[r+1]=i>>>8&255,n[r+2]=i>>>16&255,n[r+3]=i>>>24&255}function fe(n,r,i){let a="";for(let o=0;o<i;o+=1)a+=String.fromCharCode(n[r+o]??0);return a}async function An(n){let r=n.uploads.limits,i=n.uploads.images,a=Ee(n.bytes),o=Wt(n.contentType,a);if(Kt(o,r?.accept),r?.maxFileSize){let N=se(r.maxFileSize,"uploads.limits.maxFileSize");if(n.bytes.byteLength>N)throw new e(`"${n.filename}" is ${Gt(n.bytes.byteLength)}, over the ${r.maxFileSize} limit`,{status:413,code:"file_too_large"})}let f=r?.maxImageDimensions;if(a&&f){if(a.width>f.width||a.height>f.height)throw new e(`"${n.filename}" is ${a.width}x${a.height}, over the ${f.width}x${f.height} limit`,{status:422,code:"image_too_large"})}let p=n.bytes,w=a,C=o,D=null;if(a&&i){let N=await qt(p,a,i,C);p=N.data,w=N.info,C=N.contentType,D=N.error}return{data:p,contentType:C,filename:Ue(n.filename),info:w,checksum:Ve(await vt(p)),extension:Me(C),processingError:D}}async function qt(n,r,i,a){let o=i.processor,f={},p=i.convert,w=p!==void 0&&a===`image/${p.to}`;if(p&&!(p.keep??[]).includes(a)&&r.format!=="svg"&&!w)f.format=p.to;let C=i.maxDimensions;if(C&&(r.width>C.width||r.height>C.height))f.width=C.width,f.height=C.height,f.fit="inside";if(i.quality!==void 0)f.quality=i.quality;if((f.format!==void 0||f.width!==void 0)&&o&&o.supports(a)){if(i.stripMetadata!==!1)f.stripMetadata=!0;try{let q=await o.transform(n,f,r);return{data:q.data,contentType:q.contentType,info:{format:r.format,contentType:q.contentType,width:q.width,height:q.height},error:null}}catch(q){if(Ce(q))throw q;return{data:i.stripMetadata!==!1?Ge(n,a):n,info:r,contentType:a,error:Se(q)}}}return{data:i.stripMetadata===!0||w&&o!==void 0&&i.stripMetadata!==!1?Ge(n,a):n,info:r,contentType:a,error:null}}function Ce(n){return n instanceof e&&n.code==="image_processor_missing"}function Se(n){if(n instanceof Error){let r=n.code;return typeof r==="number"||typeof r==="string"&&r!==""?`${n.message} (${String(r)})`:n.message}return String(n)}function Kt(n,r){if(!r||r.length===0)return;if(r.some((i)=>Ie(n,i)))return;throw new e(`"${n}" is not an accepted file type; uploads.limits.accept allows ${r.join(", ")}`,{status:415,code:"unsupported_media_type"})}function Ie(n,r){let i=n.toLowerCase().split(";")[0]?.trim()??"",a=r.toLowerCase().trim();if(a==="*"||a==="*/*")return!0;if(a.endsWith("/*"))return i.startsWith(a.slice(0,-1));return i===a}function Wt(n,r){if(r)return r.contentType;let i=n.split(";")[0]?.trim().toLowerCase();return i&&i.includes("/")?i:"application/octet-stream"}function Ue(n){let i=(n.split(/[/\\]/).pop()??"file").replaceAll("\x00","").replace(/[\u0000-\u001f\u007f"]/g,"").trim();return i.length>0?i.slice(0,255):"file"}function Gt(n){if(n<1024)return`${n} B`;if(n<1048576)return`${(n/1024).toFixed(1)} kB`;return`${(n/1048576).toFixed(1)} MB`}var Xt=25,Qt=3600000,Ht=200,Te=[m("created_at","desc"),m("id","desc")];function Zt(n){let{config:r}=n,i,a=new Map,o=r.uploads?.publicPath,f=()=>{if(!r.uploads)throw new e("This CMS has no uploads configured; add an `uploads` section with a storage adapter.",{status:501,code:"uploads_not_configured"});return r.uploads},p=()=>(i??=Promise.resolve(typeof f().storage==="function"?f().storage():f().storage),i);async function w(c){let g=await n.database();return g.transaction((y)=>c(y,d(g,y)))}let C={config:r,database:n.database,storage:p,emit:n.emit,deliver:n.deliver},D=(c,g)=>{if(!r.rbac)return;if(E(c,`media:${g}`))return;throw c?e.forbidden(`Not allowed to ${g} media; the "media:${g}" permission is required`):e.unauthorized(`Not allowed to ${g} media`)},N=async(c,g,y,v,h={})=>{await n.emit(c,[{type:g,data:{media:de(y),...h},previous:null}],{actor:v,collection:"media",documentId:y.id})},L=async(c,g)=>{let y=await c.findOne(T,t("id",g));if(!y)throw e.notFound(`No media with id "${g}"`);return y};async function q(c){let g=f(),y=c.actor??null;D(y,"create");let v=await xe(c.file),h=await An({bytes:v,filename:c.filename??sn(c.file)??"file",contentType:c.contentType??cn(c.file)??"application/octet-stream",uploads:g}),I=b("med"),_=await p(),k=tn(_,I,h.filename,h.extension);await _.put(k,h.data,{contentType:h.contentType,size:h.data.byteLength,cacheControl:"public, max-age=31536000, immutable"});let A=new Date,P;try{P=await w(async(j,z)=>{let O=await z.insert(T,{id:I,filename:h.filename,mime_type:h.contentType,size:h.data.byteLength,width:h.info?.width??null,height:h.info?.height??null,storage_key:k,checksum:h.checksum,alt:rn(c.alt,c.locale??r.i18n.defaultLocale),focal_x:null,focal_y:null,status:"active",orphaned_at:null,purge_after:null,purge_error:null,metadata:{...c.metadata??{}},created_by:y?.id??null,created_at:A,updated_at:A}),K=F(O,_,o);if(await N(j,"media.uploaded",K,y),h.processingError!==null)await N(j,"media.processing.failed",K,y,{variant:null,error:h.processingError});return K})}catch(j){throw await _.delete([k]).catch(()=>{return}),j}if(n.deliver(),g.images?.variants?.mode==="pregenerate")return Ze(P,y);return P}async function Ze(c,g){for(let y of te(f().images))try{let v=await $e({id:c.id,variant:y});if(v)await un(v.body)}catch(v){await w((h)=>n.emit(h,[{type:"media.processing.failed",data:{media:de(c),variant:y,error:v instanceof Error?v.message:String(v)},previous:null}],{actor:g,collection:"media",documentId:c.id})),n.deliver()}return await _e(c.id)??c}async function et(c={}){let g=nn(c.limit),y=[];if(c.status)y.push(t("status",c.status));if(c.search)y.push(ae("filename",`%${c.search}%`,!0));let v=c.mimeType?.includes("*")===!0?c.mimeType:null;if(c.mimeType&&!v)y.push(t("mime_type",c.mimeType));let h=y.length>0?s(...y):void 0,I=await n.database(),_=await I.transaction((O)=>I.query(O,{table:T,...c.cursor?{where:s(...h?[h]:[],J(c.cursor,Te))}:h===void 0?{}:{where:h},orderBy:Te,limit:g+1})),k=v?_.filter((O)=>Ie(String(O.mime_type),v)):_,A=k.length>g,P=k.slice(0,g),j=await p(),z=P.at(-1);return{docs:P.map((O)=>F(O,j,o)),limit:g,hasNextPage:A,cursor:z?V(z,Te):null}}async function _e(c){let g=await w((y,v)=>v.findOne(T,t("id",c)));return g?F(g,await p(),o):null}async function me(c){let g=[...new Set(c)].filter((h)=>h.length>0),y=new Map;if(g.length===0)return y;let v=await p();for(let h=0;h<g.length;h+=90){let I=g.slice(h,h+90),_=await w((k,A)=>A.find(T,S("id",I)));for(let k of _){let A=F(k,v,o);y.set(A.id,A)}}return y}async function tt(c,g={}){let y=[...Object.values(r.collections),...Object.values(r.globals)].find((A)=>A.name===c||A.slug===c);if(!y)throw e.notFound(`No collection or global called "${c}"`);let v=y.name,h=[];if(g.ids===void 0)h.push(...await w((A,P)=>P.find(U,t("collection",v))));else{let A=[...new Set(g.ids)];for(let P=0;P<A.length;P+=90){let j=A.slice(P,P+90);h.push(...await w((z,O)=>O.find(U,s(t("collection",v),S("document_id",j)))))}}let I=await me(h.map((A)=>String(A.media_id))),_=new Map,k=[...h].sort((A,P)=>String(A.document_id).localeCompare(String(P.document_id))||String(A.id).localeCompare(String(P.id)));for(let A of k){let P=I.get(String(A.media_id));if(!P)continue;let j=String(A.document_id),z=String(A.locale??""),O=_.get(j)??[];O.push({media:P,field:String(A.field),locale:z===""?null:z}),_.set(j,O)}return _}async function nt(c,g={}){let y=r.uploads?Qe(c??null):[],v=y.length>0?await me(y):new Map;return Q(c,{format:g.format??"html",mediaImage:(h)=>{let I=v.get(h);if(!I)return null;return we(r,I,{...g.locale===void 0?{}:{locale:g.locale},...g.sizes===void 0?{}:{sizes:g.sizes}})},mediaUrl:(h)=>`${r.basePath}/media/${encodeURIComponent(h)}/original`,images:{loading:g.loading??"lazy",decoding:"async"}})}async function rt(c){return(await w((y,v)=>v.find(U,t("media_id",c)))).map((y)=>({mediaId:String(y.media_id),collection:String(y.collection),documentId:String(y.document_id),field:String(y.field),locale:String(y.locale??""),createdAt:l(y.created_at)}))}async function at(c){let g=f(),y=c.actor??null;D(y,"update"),en(g,c);let v=await p(),{media:h,stale:I}=await w(async(_,k)=>{let A=await L(k,c.id),P=F(A,v,o),z=c.crop!==void 0&&!Ye(c.crop,P.crop)||c.focalPoint!==void 0&&!Ye(c.focalPoint,P.focalPoint)?P.variants:[],O={updated_at:new Date};if(c.filename!==void 0)O.filename=Ue(c.filename);if(c.alt!==void 0)O.alt=an(P.alt,c.alt,c.locale??r.i18n.defaultLocale);if(c.focalPoint!==void 0)O.focal_x=c.focalPoint?.x??null,O.focal_y=c.focalPoint?.y??null;let K={...u(A.metadata),...c.metadata??{}};if(c.crop===null)delete K.crop;else if(c.crop!==void 0)K.crop={...c.crop};if(z.length>0)delete K.variants;O.metadata=K,await k.update(T,t("id",c.id),O);let re=F({...A,...O},v,o);await N(_,"media.updated",re,y);let lt=X(g.images,re.mimeType);return{media:re,stale:z.map((ft)=>Be(re.storageKey,ft,lt))}});if(I.length>0)await v.delete(I).catch(()=>{return});return n.deliver(),h}async function ot(c){let g=c.actor??null;D(g,"update");let y=await w(async(v,h)=>{let I=await L(h,c.id);if(String(I.status)==="active")throw e.conflict(`"${c.id}" is in use; only an unused file has a deadline to clear`);let _={purge_after:null,purge_error:null,updated_at:new Date};await h.update(T,t("id",c.id),_);let k=F({...I,..._},await p(),o);return await N(v,"media.updated",k,g,{kept:!0}),k});return n.deliver(),y}async function st(c){let g=c.actor??null;D(g,"delete");let y=await p(),{media:v,keys:h}=await w(async(I,_)=>{let k=await L(_,c.id),A=F(k,y,o);if(c.force!==!0){let P=await _.find(U,t("media_id",c.id));if(P.length>0){let j=P.slice(0,3).map((z)=>`${String(z.collection)}/${String(z.document_id)}`).join(", ");throw e.conflict(`"${A.filename}" is used by ${P.length} document${P.length===1?"":"s"} (${j}); pass force to delete it anyway`)}}return await _.delete(U,t("media_id",c.id)),await _.delete(T,t("id",c.id)),await N(I,"media.purged",A,g),{media:A,keys:Ae(A,r.uploads)}});return await y.delete(h),n.deliver(),v}async function $e(c){let g=f(),y=await p(),v=await w((z,O)=>O.findOne(T,t("id",c.id)));if(!v)return null;let h=F(v,y,o);if(!c.variant)return ee(y,h,null);let I=g.images?.processor;if(!I||!I.supports(h.mimeType)){let z=ue(g.images,c.variant);return ee(y,h,c.variant,z)}let _=bt(g.images,c.variant,h),k=X(g.images,h.mimeType);if(k===h.mimeType&&ce(_,h))return ee(y,h,c.variant);let A=Be(h.storageKey,c.variant,k);if(c.refresh!==!0){let z=await y.get(A);if(z){let O=await y.head?.(A);return{media:h,variant:c.variant,key:A,contentType:O?.contentType??k,width:null,height:null,size:O?.size??null,body:z,url:await Pe(y,A),cached:!0,processingError:null}}}let P=await y.get(h.storageKey);if(!P)return null;let j;try{j=await Oe(I,await xe(P),_,h)}catch(z){if(Ce(z))throw z;let O=Se(z);await ct(h,c.variant,O);let K=await ee(y,h,c.variant);return K&&{...K,processingError:O}}if(!j)return ee(y,h,c.variant);return await y.put(A,j.data,{contentType:j.contentType,size:j.data.byteLength,cacheControl:"public, max-age=31536000, immutable"}),await ut(h.id,c.variant),{media:h,variant:c.variant,key:A,contentType:j.contentType,width:j.width,height:j.height,size:j.data.byteLength,body:wt(j.data),url:await Pe(y,A),cached:!1,processingError:null}}async function ct(c,g,y){let v=`${c.id}|${g}`,h=Date.now(),I=a.get(v);if(I!==void 0&&h-I<Qt)return;if(a.size>=1000)a.clear();a.set(v,h);try{await w((_)=>n.emit(_,[{type:"media.processing.failed",data:{media:de(c),variant:g,error:y},previous:null}],{actor:null,collection:"media",documentId:c.id})),n.deliver()}catch{}}async function ee(c,g,y,v=""){let h=await c.get(g.storageKey);if(!h)return null;let I=await Pe(c,g.storageKey);return{media:g,variant:y,key:g.storageKey,contentType:g.mimeType,width:g.width,height:g.height,size:g.size,body:h,url:v?`${I}?${v}`:I,cached:y===null,processingError:null}}async function ut(c,g){await w(async(y,v)=>{let h=await v.findOne(T,t("id",c));if(!h)return;let I=u(h.metadata),_=Array.isArray(I.variants)?I.variants.filter((k)=>typeof k==="string"):[];if(_.includes(g))return;await v.update(T,t("id",c),{metadata:{...I,variants:[..._,g].sort()}})})}function dt(c){return Xe(C,c)}return{upload:q,list:et,get:_e,getMany:me,update:at,delete:st,keep:ot,usages:rt,variant:$e,collect:dt,storage:p,forDocuments:tt,url:(c,g)=>Y(r,c,g),srcset:(c,g)=>Fe(r,c,g),image:(c,g)=>we(r,c,g),renderRichText:nt}}function en(n,r){for(let i of Object.keys(r.metadata??{}))if(qe.includes(i))throw e.validation(`"${i}" is reserved inside media metadata; it is maintained by the engine`);if(r.focalPoint!==void 0&&n.images?.focalPoint!==!0)throw e.validation("Focal points are off; set uploads.images.focalPoint to true");if(r.crop!==void 0&&n.images?.crop!==!0)throw e.validation("Cropping is off; set uploads.images.crop to true");if(r.focalPoint&&!on(r.focalPoint))throw e.validation("A focal point is relative: x and y are between 0 and 1")}function tn(n,r,i,a){let f=(n.prefix?.({id:r,filename:i})??String(new Date().getUTCFullYear())).replace(/^\/+|\/+$/g,"");return f?`${f}/${r}.${a}`:`${r}.${a}`}async function Pe(n,r){return n.signedUrl?n.signedUrl(r):n.url(r)}function nn(n){if(n===void 0)return Xt;if(!Number.isInteger(n)||n<1)throw new e(`limit must be a positive integer, received ${n}`,{status:400,code:"invalid_pagination"});return Math.min(n,Ht)}function rn(n,r){if(n===void 0)return{};return typeof n==="string"?{[r]:n}:{...n}}function an(n,r,i){return typeof r==="string"?{...n,[i]:r}:{...r}}function on(n){return n.x>=0&&n.x<=1&&n.y>=0&&n.y<=1}function sn(n){let r=n.name;return typeof r==="string"?r:void 0}function cn(n){let r=n.type;return typeof r==="string"&&r.length>0?r:void 0}function Ye(n,r){return JSON.stringify(n??null)===JSON.stringify(r??null)}async function un(n){let r=n.getReader();for(;;){let{done:i}=await r.read();if(i)break}}
2
- export{V,J,xo,Ee,Me,bt,Be,F,Yt,xe,wt,Ve,Yn,vt,Ge,An,Zt};
1
+ import{s,R,t,it,H,M,S,ae,le,m}from"./index-q6jkbsjp.js";import{E,l,u}from"./index-pkxgzw6e.js";import{ye}from"./index-e3yknwyr.js";import{T,U,Qe}from"./index-n09v6gx3.js";import{d}from"./index-9g2n7xa6.js";import{Q}from"./index-twqpdtfh.js";import{se}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b}from"./index-qgtvymh2.js";import{e}from"./index-x72d1hzh.js";function V(n,r){let i=r.map((a)=>{let o=pt(n,a.path);return{path:a.path,value:o instanceof Date?o.toISOString():gt(o),date:o instanceof Date}});return ht(JSON.stringify(i))}function J(n,r){let i=mt(n);if(i.length!==r.length)throw new e("This cursor does not match the requested sort order.",{status:400,code:"invalid_cursor"});let a=[];for(let o=0;o<r.length;o+=1){let f=[];for(let C=0;C<o;C+=1){let D=i[C];f.push(t(D.path,pe(D)))}let p=i[o],w=r[o].direction;f.push(w==="desc"?H(p.path,pe(p)):it(p.path,pe(p))),a.push(s(...f))}return R(...a)}function mt(n){try{let r=JSON.parse(yt(n));if(!Array.isArray(r))throw Error("not a cursor");return r}catch{throw new e("This cursor is not readable.",{status:400,code:"invalid_cursor"})}}function pe(n){return n.date&&typeof n.value==="string"?new Date(n.value):n.value}function pt(n,r){if(r in n)return n[r];let i=r.split("."),a=n.data??n;for(let o of i){if(typeof a!=="object"||a===null)return;a=a[o]}return a}function gt(n){if(n===void 0||n===null)return null;if(typeof n==="object")return null;return n}function ht(n){let r=new TextEncoder().encode(n),i="";for(let a of r)i+=String.fromCharCode(a);return btoa(i).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function yt(n){let r=n.replaceAll("-","+").replaceAll("_","/"),i=atob(r.padEnd(Math.ceil(r.length/4)*4,"=")),a=Uint8Array.from(i,(o)=>o.charCodeAt(0));return new TextDecoder().decode(a)}var Re={jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",tiff:"image/tiff"};function So(n){return Re[n]}function Ee(n){return bt(n)??Mt(n)??At(n)??Ct(n)??St(n)??It(n)}function Me(n){let i={"image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/svg+xml":"svg","image/tiff":"tiff","video/mp4":"mp4","video/webm":"webm","audio/mpeg":"mp3","application/pdf":"pdf","application/json":"json","text/plain":"txt","text/csv":"csv"}[n.toLowerCase()];if(i)return i;let a=n.split("/")[1]?.split(";")[0]?.trim();return a&&/^[a-z0-9.+-]+$/i.test(a)?a:"bin"}function bt(n){let r=[137,80,78,71,13,10,26,10];if(n.length<24||!Ut(n,r))return null;return W("png",ie(n,16),ie(n,20))}function Mt(n){if(n.length<10||G(n,0,3)!=="GIF")return null;return W("gif",oe(n,6),oe(n,8))}function At(n){if(n.length<30||G(n,0,4)!=="RIFF"||G(n,8,4)!=="WEBP")return null;let r=G(n,12,4);if(r==="VP8X")return W("webp",De(n,24)+1,De(n,27)+1);if(r==="VP8 "){if(n[23]!==157||n[24]!==1||n[25]!==42)return null;return W("webp",oe(n,26)&16383,oe(n,28)&16383)}if(r==="VP8L"){if(n[20]!==47)return null;let i=B(n,21),a=B(n,22),o=B(n,23),f=B(n,24);return W("webp",((a&63)<<8|i)+1,((f&15)<<10|o<<2|(a&192)>>6)+1)}return null}function Ct(n){if(n.length<4||n[0]!==255||n[1]!==216)return null;let r=2;while(r+9<n.length){if(n[r]!==255){r+=1;continue}let i=B(n,r+1);if(i===255||i===1||i>=208&&i<=217){r+=2;continue}if(i>=192&&i<=195||i>=197&&i<=199||i>=201&&i<=203||i>=205&&i<=207)return W("jpeg",ge(n,r+7),ge(n,r+5));let o=ge(n,r+2);if(o<2)return null;r+=2+o}return null}function St(n){if(n.length<16||G(n,4,4)!=="ftyp")return null;let r=G(n,8,4),i=r==="avif"||r==="avis";if(!i&&!(r==="heic"||r==="heix"||r==="mif1"))return null;let o=Math.min(n.length-16,65536);for(let f=16;f<o;f+=1){if(G(n,f,4)!=="ispe")continue;let p=ie(n,f+8),w=ie(n,f+12);if(p>0&&w>0&&p<1e5&&w<1e5)return W(i?"avif":"avif",p,w)}return null}function It(n){let r=new TextDecoder().decode(n.subarray(0,2048));if(!/<svg[\s>]/i.test(r))return null;let i=(f)=>{let p=new RegExp(`\\b${f}\\s*=\\s*["']([\\d.]+)`,"i").exec(r);return p?Math.round(Number(p[1])):0},a=i("width"),o=i("height");if(a===0||o===0){let f=/\bviewBox\s*=\s*["']\s*[\d.-]+\s+[\d.-]+\s+([\d.]+)\s+([\d.]+)/i.exec(r);if(f)a=Math.round(Number(f[1])),o=Math.round(Number(f[2]))}return W("svg",a,o)}function W(n,r,i){return{format:n,contentType:Re[n],width:r,height:i}}function B(n,r){return n[r]??0}function ge(n,r){return B(n,r)<<8|B(n,r+1)}function ie(n,r){return B(n,r)*16777216+(B(n,r+1)<<16|B(n,r+2)<<8|B(n,r+3))}function oe(n,r){return B(n,r)|B(n,r+1)<<8}function De(n,r){return B(n,r)|B(n,r+1)<<8|B(n,r+2)<<16}function G(n,r,i){let a="";for(let o=0;o<i;o+=1)a+=String.fromCharCode(B(n,r+o));return a}function Ut(n,r){return r.every((i,a)=>n[a]===i)}function te(n){return Object.keys(n?.variants?.sizes??{})}function ne(n,r){let i=n?.variants?.sizes?.[r];if(!i){let a=te(n);throw e.notFound(a.length>0?`No image size named "${r}"; this configuration declares ${a.join(", ")}`:`No image size named "${r}"; this configuration declares none`)}return i}function wt(n,r,i){let a=ne(n,r),o={...a.width===void 0?{}:{width:a.width},...a.height===void 0?{}:{height:a.height},...a.fit===void 0?{}:{fit:a.fit}};if(n?.quality!==void 0)o.quality=n.quality;if(n?.stripMetadata!==!1)o.stripMetadata=!0;if(n?.focalPoint!==!1&&i.focalPoint)o.position=i.focalPoint;if(n?.crop!==!1&&i.crop)o.crop=i.crop;let f=n?.convert;if(f&&!(f.keep??[]).includes(i.mimeType))o.format=f.to;return o}function ce(n,r){let{width:i,height:a}=r;if(i===null||a===null||i<=0||a<=0)return!1;if(n.crop){let w=n.crop;if(!(w.x<=0&&w.y<=0&&w.width>=i&&w.height>=a))return!1}let o=n.fit??"inside",{width:f,height:p}=n;if(f===void 0&&p===void 0)return!0;if(o==="inside")return(f===void 0||f>=i)&&(p===void 0||p>=a);if(o==="outside")return Math.max(f===void 0?0:f/i,p===void 0?0:p/a)>=1;return!1}function X(n,r){let i=n?.convert;if(!i||(i.keep??[]).includes(r))return r;return`image/${i.to}`}function Be(n,r,i){let a=n.lastIndexOf("/"),o=n.lastIndexOf(".");return`${o>a?n.slice(0,o):n}/${r}.${Me(i)}`}function ue(n,r){let i=ne(n,r),a=new URLSearchParams;if(i.width!==void 0)a.set("w",String(i.width));if(i.height!==void 0)a.set("h",String(i.height));if(i.fit!==void 0)a.set("fit",i.fit);if(n?.quality!==void 0)a.set("q",String(n.quality));return a.toString()}async function Oe(n,r,i,a){if(!n||!n.supports(a.mimeType))return null;return n.transform(r,i,{format:a.mimeType.split("/")[1]??"jpeg",contentType:a.mimeType,width:a.width??0,height:a.height??0})}function je(n,r){let i=n.filename.replace(/\.[^.]*$/,"");return`${ye(i)||"file"}.${Me(r)}`}function he(n,r){if(!n)return null;return`${x(n)}/${encodeURIComponent(r.id)}/${je(r,r.mimeType)}`}function Y(n,r,i={}){let a=n.uploads?.images,o=n.uploads?.publicPath,f=i.variant,p=he(o,r)??`${ke(n)}/${encodeURIComponent(r.id)}/original`;if(f===void 0||f==="original")return p;ne(a,f);let w=a?.processor;if(!w||!w.supports(r.mimeType))return`${p}?${ue(a,f)}`;let C=X(a,r.mimeType);if(C===r.mimeType&&ce(wt(a,f,{mimeType:r.mimeType,crop:r.crop??null,focalPoint:r.focalPoint??null}),{width:r.width??null,height:r.height??null}))return p;if(o)return`${x(o)}/${encodeURIComponent(r.id)}/${encodeURIComponent(f)}/${je(r,C)}`;return`${ke(n)}/${encodeURIComponent(r.id)}/${encodeURIComponent(f)}`}function ke(n){return`${n.basePath==="/"?"":x(n.basePath)}/media`}function ze(n,r,i){let a=Ne(i);if(!a)return null;let o=ne(n,r),{width:f,height:p}=o,w=o.fit??"inside";if(f===void 0&&p===void 0)return a;if((w==="cover"||w==="contain")&&f!==void 0&&p!==void 0){if(w==="contain")return{width:f,height:p};let D=Math.max(f/a.width,p/a.height);return D>1?{width:Math.max(1,Math.round(f/D)),height:Math.max(1,Math.round(p/D))}:{width:f,height:p}}let C=w==="outside"?Math.min(1,Math.max(f===void 0?0:f/a.width,p===void 0?0:p/a.height)):Math.min(f===void 0?1/0:f/a.width,p===void 0?1/0:p/a.height,1);return{width:Math.max(1,Math.round(a.width*C)),height:Math.max(1,Math.round(a.height*C))}}function Fe(n,r,i={}){let a=Je(n,r,i);return a.length<2?null:a.map((o)=>`${o.url} ${o.width}w`).join(", ")}function Je(n,r,i){let a=n.uploads?.images,o=a?.variants?.sizes??{};if(!_t(r.mimeType)||!r.width||!r.height)return[];let f=i.sizes??Object.entries(o).filter(([,N])=>Pt(N)).map(([N])=>N),p=r.crop!==null&&r.crop!==void 0,w=[],C=new Set,D=Ne(r);if(!p&&D)w.push({url:Y(n,r),...D}),C.add(D.width);for(let N of f){let L=ze(a,N,r);if(!L||C.has(L.width))continue;C.add(L.width),w.push({url:Y(n,r,{variant:N}),...L})}return w.sort((N,L)=>N.width-L.width)}function we(n,r,i={}){let a=n.uploads?.images,o=Tt(n,r.alt,i.locale),f=i.sizes??null;if(i.variant!==void 0&&i.variant!=="original"){let D=ze(a,i.variant,r);return{src:Y(n,r,{variant:i.variant}),width:D?.width??null,height:D?.height??null,srcset:null,sizes:null,alt:o}}let p=Je(n,r,i.srcset===void 0?{}:{sizes:i.srcset}),C=r.crop!==null&&r.crop!==void 0?p.at(-1):void 0;return{src:C?.url??Y(n,r),width:C?.width??r.width??null,height:C?.height??r.height??null,srcset:p.length<2?null:p.map((D)=>`${D.url} ${D.width}w`).join(", "),sizes:p.length<2?null:f,alt:o}}function Tt(n,r,i){if(!r)return null;let a=(i===void 0?void 0:r[i])??r[n.i18n.defaultLocale];return typeof a==="string"&&a.trim()!==""?a:null}function Ne(n){if(n.crop)return{width:n.crop.width,height:n.crop.height};if(!n.width||!n.height)return null;return{width:n.width,height:n.height}}function Pt(n){let r=n.fit??"inside";if(r==="inside"||r==="outside")return!0;return n.width===void 0||n.height===void 0}function _t(n){return n.startsWith("image/")&&n!=="image/svg+xml"}var qe=["crop","variants"];function F(n,r,i){let a=u(n.metadata),{crop:o,variants:f,...p}=a,w=String(n.storage_key);return{id:String(n.id),filename:String(n.filename),mimeType:String(n.mime_type),size:Number(n.size??0),width:Le(n.width),height:Le(n.height),storageKey:w,checksum:ve(n.checksum),alt:Ot(n.alt),focalPoint:Dt(n.focal_x,n.focal_y),crop:Rt(o),status:$t(n.status),orphanedAt:l(n.orphaned_at),purgeAfter:l(n.purge_after),purgeError:ve(n.purge_error),metadata:p,variants:Array.isArray(f)?f.filter((C)=>typeof C==="string"):[],createdBy:ve(n.created_by),createdAt:l(n.created_at),updatedAt:l(n.updated_at),url:he(i,{id:String(n.id),filename:String(n.filename),mimeType:String(n.mime_type)})??r.url(w)}}function de(n){return JSON.parse(JSON.stringify(n))}function $t(n){return n==="orphaned"||n==="purging"?n:"active"}function Dt(n,r){if(n===null||n===void 0)return null;if(r===null||r===void 0)return null;return{x:Number(n),y:Number(r)}}function Rt(n){if(typeof n!=="object"||n===null||Array.isArray(n))return null;let r=n,i=["x","y","width","height"].map((a)=>Number(r[a]));if(i.some((a)=>Number.isNaN(a)))return null;return{x:i[0],y:i[1],width:i[2],height:i[3]}}function Ot(n){let r=u(n),i={};for(let[a,o]of Object.entries(r))if(typeof o==="string")i[a]=o;return i}function Le(n){return n===null||n===void 0?null:Number(n)}function ve(n){return n===null||n===void 0?null:String(n)}var kt=86400000,Et=100;async function We(n,r,i){if(n.config.uploads?.retention?.purgeAfter===!1)return[];let a=await n.database();return a.transaction((o)=>a.query(o,{table:T,where:s(t("status","orphaned"),le("purge_after",!0),M("purge_after",r)),orderBy:[m("purge_after","asc"),m("id","asc")],limit:i}))}async function Xe(n,r={}){let i={examined:0,purged:0,reclaimed:0,failed:0};if(!n.config.uploads)return i;let a=r.now??new Date,o=await We(n,a,r.limit??Et);for(let f of o){i.examined+=1;try{let p=await He(n,f,a);if(p==="purged")i.purged+=1;if(p==="reclaimed")i.reclaimed+=1}catch{i.failed+=1}}return i}async function He(n,r,i){let a=await n.storage(),o=F(r,a,n.config.uploads?.publicPath),f=await be(n,async(p,w)=>{if((await w.find(U,t("media_id",o.id))).length>0){if(await w.update(T,s(t("id",o.id),t("status","orphaned")),{status:"active",orphaned_at:null,purge_after:null,purge_error:null,updated_at:i})===0)return"taken";return await Ke(n,p,"media.reclaimed",{...o,status:"active",orphanedAt:null,purgeAfter:null}),"reclaimed"}return await w.update(T,s(t("id",o.id),t("status","orphaned")),{status:"purging",updated_at:i})===1?"claimed":"taken"});if(n.deliver(),f!=="claimed")return f;try{return await a.delete(Ae(o,n.config.uploads)),await be(n,async(p,w)=>{await w.delete(U,t("media_id",o.id)),await w.delete(T,t("id",o.id)),await Ke(n,p,"media.purged",o,{collected:!0})}),n.deliver(),"purged"}catch(p){throw await jt(n,o,p,i),p}}function Yt(n){return{name:"media-gc",failureType:"media.purge",failurePayload:(r)=>({mediaId:String(r.id),storageKey:String(r.storage_key),filename:String(r.filename)}),due:(r,i,a)=>We(n,i,a),run:async(r,i)=>{await He(n,i,new Date)}}}function Ae(n,r){let i=X(r?.images,n.mimeType),a=new Set([...n.variants,...te(r?.images)]);return[n.storageKey,...[...a].map((o)=>Be(n.storageKey,o,i))]}async function jt(n,r,i,a){let o=i instanceof Error?i.message:String(i);await be(n,async(f,p)=>{await p.update(T,t("id",r.id),{status:"orphaned",purge_after:new Date(a.getTime()+kt),purge_error:o.slice(0,1000),updated_at:a})})}async function Ke(n,r,i,a,o={}){await n.emit(r,[{type:i,data:{media:JSON.parse(JSON.stringify(a)),...o},previous:null}],{actor:null,collection:"media",documentId:a.id})}async function be(n,r){let i=await n.database();return i.transaction((a)=>r(a,d(i,a)))}async function xe(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(typeof Blob<"u"&&n instanceof Blob)return new Uint8Array(await n.arrayBuffer());let r=[],i=n.getReader();for(;;){let{done:a,value:o}=await i.read();if(a)break;if(o)r.push(o)}return Z(r)}function Z(n){if(n.length===1)return n[0];let r=n.reduce((o,f)=>o+f.byteLength,0),i=new Uint8Array(r),a=0;for(let o of n)i.set(o,a),a+=o.byteLength;return i}function vt(n){return new ReadableStream({start(r){r.enqueue(n),r.close()}})}function Ve(n){let r="";for(let i of n)r+=i.toString(16).padStart(2,"0");return r}function eo(n){let r="";for(let i of n)r+=String.fromCharCode(i);return btoa(r)}async function xt(n){let r=typeof n==="string"?new TextEncoder().encode(n):n,i=await crypto.subtle.digest("SHA-256",r);return new Uint8Array(i)}function Ge(n,r){switch(r.toLowerCase()){case"image/jpeg":return zt(n);case"image/png":return Jt(n);case"image/webp":return Nt(n);default:return n}}function zt(n){if(n.length<4||n[0]!==255||n[1]!==216)return n;let r=[n.subarray(0,2)],i=2;while(i+4<=n.length){if(n[i]!==255)break;let a=n[i+1]??0;if(a===216||a===1||a>=208&&a<=215){r.push(n.subarray(i,i+2)),i+=2;continue}if(a===218){r.push(n.subarray(i)),i=n.length;break}let o=(n[i+2]??0)<<8|(n[i+3]??0);if(o<2||i+2+o>n.length)break;if(!Ft(a))r.push(n.subarray(i,i+2+o));i+=2+o}if(i<n.length)r.push(n.subarray(i));return Z(r)}function Ft(n){if(n===254)return!0;if(n===224)return!1;if(n===226)return!1;if(n===238)return!1;return n>=224&&n<=239}function Jt(n){let r=[137,80,78,71,13,10,26,10];if(n.length<8||!r.every((f,p)=>n[p]===f))return n;let i=new Set(["tEXt","zTXt","iTXt","eXIf","tIME","dSIG"]),a=[n.subarray(0,8)],o=8;while(o+8<=n.length){let f=Bt(n,o),p=fe(n,o+4,4),w=12+f;if(w<12||o+w>n.length)break;if(!i.has(p))a.push(n.subarray(o,o+w));if(o+=w,p==="IEND")break}return Z(a)}function Nt(n){if(n.length<12||fe(n,0,4)!=="RIFF"||fe(n,8,4)!=="WEBP")return n;let r=new Set(["EXIF","XMP "]),i=[],a=12,o=!1;while(a+8<=n.length){let w=fe(n,a,4),C=Lt(n,a+4),D=8+C+C%2;if(a+D>n.length)break;if(r.has(w))o=!0;else i.push(n.subarray(a,a+D));a+=D}if(!o)return n;let f=Z(i),p=new Uint8Array(12);return p.set(n.subarray(0,12)),Vt(p,4,f.byteLength+4),Z([p,f])}function Bt(n,r){return(n[r]??0)*16777216+((n[r+1]??0)<<16|(n[r+2]??0)<<8|(n[r+3]??0))}function Lt(n,r){return(n[r]??0)+((n[r+1]??0)<<8)+((n[r+2]??0)<<16)+(n[r+3]??0)*16777216}function Vt(n,r,i){n[r]=i&255,n[r+1]=i>>>8&255,n[r+2]=i>>>16&255,n[r+3]=i>>>24&255}function fe(n,r,i){let a="";for(let o=0;o<i;o+=1)a+=String.fromCharCode(n[r+o]??0);return a}async function kn(n){let r=n.uploads.limits,i=n.uploads.images,a=Ee(n.bytes),o=Wt(n.contentType,a);if(Kt(o,r?.accept),r?.maxFileSize){let N=se(r.maxFileSize,"uploads.limits.maxFileSize");if(n.bytes.byteLength>N)throw new e(`"${n.filename}" is ${Gt(n.bytes.byteLength)}, over the ${r.maxFileSize} limit`,{status:413,code:"file_too_large"})}let f=r?.maxImageDimensions;if(a&&f){if(a.width>f.width||a.height>f.height)throw new e(`"${n.filename}" is ${a.width}x${a.height}, over the ${f.width}x${f.height} limit`,{status:422,code:"image_too_large"})}let p=n.bytes,w=a,C=o,D=null;if(a&&i){let N=await qt(p,a,i,C);p=N.data,w=N.info,C=N.contentType,D=N.error}return{data:p,contentType:C,filename:Ue(n.filename),info:w,checksum:Ve(await xt(p)),extension:Me(C),processingError:D}}async function qt(n,r,i,a){let o=i.processor,f={},p=i.convert,w=p!==void 0&&a===`image/${p.to}`;if(p&&!(p.keep??[]).includes(a)&&r.format!=="svg"&&!w)f.format=p.to;let C=i.maxDimensions;if(C&&(r.width>C.width||r.height>C.height))f.width=C.width,f.height=C.height,f.fit="inside";if(i.quality!==void 0)f.quality=i.quality;if((f.format!==void 0||f.width!==void 0)&&o&&o.supports(a)){if(i.stripMetadata!==!1)f.stripMetadata=!0;try{let q=await o.transform(n,f,r);return{data:q.data,contentType:q.contentType,info:{format:r.format,contentType:q.contentType,width:q.width,height:q.height},error:null}}catch(q){if(Ce(q))throw q;return{data:i.stripMetadata!==!1?Ge(n,a):n,info:r,contentType:a,error:Se(q)}}}return{data:i.stripMetadata===!0||w&&o!==void 0&&i.stripMetadata!==!1?Ge(n,a):n,info:r,contentType:a,error:null}}function Ce(n){return n instanceof e&&n.code==="image_processor_missing"}function Se(n){if(n instanceof Error){let r=n.code;return typeof r==="number"||typeof r==="string"&&r!==""?`${n.message} (${String(r)})`:n.message}return String(n)}function Kt(n,r){if(!r||r.length===0)return;if(r.some((i)=>Ie(n,i)))return;throw new e(`"${n}" is not an accepted file type; uploads.limits.accept allows ${r.join(", ")}`,{status:415,code:"unsupported_media_type"})}function Ie(n,r){let i=n.toLowerCase().split(";")[0]?.trim()??"",a=r.toLowerCase().trim();if(a==="*"||a==="*/*")return!0;if(a.endsWith("/*"))return i.startsWith(a.slice(0,-1));return i===a}function Wt(n,r){if(r)return r.contentType;let i=n.split(";")[0]?.trim().toLowerCase();return i&&i.includes("/")?i:"application/octet-stream"}function Ue(n){let i=(n.split(/[/\\]/).pop()??"file").replaceAll("\x00","").replace(/[\u0000-\u001f\u007f"]/g,"").trim();return i.length>0?i.slice(0,255):"file"}function Gt(n){if(n<1024)return`${n} B`;if(n<1048576)return`${(n/1024).toFixed(1)} kB`;return`${(n/1048576).toFixed(1)} MB`}var Xt=25,Ht=3600000,Zt=200,Te=[m("created_at","desc"),m("id","desc")];function Qt(n){let{config:r}=n,i,a=new Map,o=r.uploads?.publicPath,f=()=>{if(!r.uploads)throw new e("This CMS has no uploads configured; add an `uploads` section with a storage adapter.",{status:501,code:"uploads_not_configured"});return r.uploads},p=()=>(i??=Promise.resolve(typeof f().storage==="function"?f().storage():f().storage),i);async function w(c){let g=await n.database();return g.transaction((y)=>c(y,d(g,y)))}let C={config:r,database:n.database,storage:p,emit:n.emit,deliver:n.deliver},D=(c,g)=>{if(!r.rbac)return;if(E(c,`media:${g}`))return;throw c?e.forbidden(`Not allowed to ${g} media; the "media:${g}" permission is required`):e.unauthorized(`Not allowed to ${g} media`)},N=async(c,g,y,v,h={})=>{await n.emit(c,[{type:g,data:{media:de(y),...h},previous:null}],{actor:v,collection:"media",documentId:y.id})},L=async(c,g)=>{let y=await c.findOne(T,t("id",g));if(!y)throw e.notFound(`No media with id "${g}"`);return y};async function q(c){let g=f(),y=c.actor??null;D(y,"create");let v=await xe(c.file),h=await kn({bytes:v,filename:c.filename??sn(c.file)??"file",contentType:c.contentType??cn(c.file)??"application/octet-stream",uploads:g}),I=b("med"),_=await p(),k=tn(_,I,h.filename,h.extension);await _.put(k,h.data,{contentType:h.contentType,size:h.data.byteLength,cacheControl:"public, max-age=31536000, immutable"});let A=new Date,P;try{P=await w(async(j,z)=>{let O=await z.insert(T,{id:I,filename:h.filename,mime_type:h.contentType,size:h.data.byteLength,width:h.info?.width??null,height:h.info?.height??null,storage_key:k,checksum:h.checksum,alt:rn(c.alt,c.locale??r.i18n.defaultLocale),focal_x:null,focal_y:null,status:"active",orphaned_at:null,purge_after:null,purge_error:null,metadata:{...c.metadata??{}},created_by:y?.id??null,created_at:A,updated_at:A}),K=F(O,_,o);if(await N(j,"media.uploaded",K,y),h.processingError!==null)await N(j,"media.processing.failed",K,y,{variant:null,error:h.processingError});return K})}catch(j){throw await _.delete([k]).catch(()=>{return}),j}if(n.deliver(),g.images?.variants?.mode==="pregenerate")return Ze(P,y);return P}async function Ze(c,g){for(let y of te(f().images))try{let v=await $e({id:c.id,variant:y});if(v)await un(v.body)}catch(v){await w((h)=>n.emit(h,[{type:"media.processing.failed",data:{media:de(c),variant:y,error:v instanceof Error?v.message:String(v)},previous:null}],{actor:g,collection:"media",documentId:c.id})),n.deliver()}return await _e(c.id)??c}async function et(c={}){let g=nn(c.limit),y=[];if(c.status)y.push(t("status",c.status));if(c.search)y.push(ae("filename",`%${c.search}%`,!0));let v=c.mimeType?.includes("*")===!0?c.mimeType:null;if(c.mimeType&&!v)y.push(t("mime_type",c.mimeType));let h=y.length>0?s(...y):void 0,I=await n.database(),_=await I.transaction((O)=>I.query(O,{table:T,...c.cursor?{where:s(...h?[h]:[],J(c.cursor,Te))}:h===void 0?{}:{where:h},orderBy:Te,limit:g+1})),k=v?_.filter((O)=>Ie(String(O.mime_type),v)):_,A=k.length>g,P=k.slice(0,g),j=await p(),z=P.at(-1);return{docs:P.map((O)=>F(O,j,o)),limit:g,hasNextPage:A,cursor:z?V(z,Te):null}}async function _e(c){let g=await w((y,v)=>v.findOne(T,t("id",c)));return g?F(g,await p(),o):null}async function me(c){let g=[...new Set(c)].filter((h)=>h.length>0),y=new Map;if(g.length===0)return y;let v=await p();for(let h=0;h<g.length;h+=90){let I=g.slice(h,h+90),_=await w((k,A)=>A.find(T,S("id",I)));for(let k of _){let A=F(k,v,o);y.set(A.id,A)}}return y}async function tt(c,g={}){let y=[...Object.values(r.collections),...Object.values(r.globals)].find((A)=>A.name===c||A.slug===c);if(!y)throw e.notFound(`No collection or global called "${c}"`);let v=y.name,h=[];if(g.ids===void 0)h.push(...await w((A,P)=>P.find(U,t("collection",v))));else{let A=[...new Set(g.ids)];for(let P=0;P<A.length;P+=90){let j=A.slice(P,P+90);h.push(...await w((z,O)=>O.find(U,s(t("collection",v),S("document_id",j)))))}}let I=await me(h.map((A)=>String(A.media_id))),_=new Map,k=[...h].sort((A,P)=>String(A.document_id).localeCompare(String(P.document_id))||String(A.id).localeCompare(String(P.id)));for(let A of k){let P=I.get(String(A.media_id));if(!P)continue;let j=String(A.document_id),z=String(A.locale??""),O=_.get(j)??[];O.push({media:P,field:String(A.field),locale:z===""?null:z}),_.set(j,O)}return _}async function nt(c,g={}){let y=r.uploads?Qe(c??null):[],v=y.length>0?await me(y):new Map;return Q(c,{format:g.format??"html",mediaImage:(h)=>{let I=v.get(h);if(!I)return null;return we(r,I,{...g.locale===void 0?{}:{locale:g.locale},...g.sizes===void 0?{}:{sizes:g.sizes}})},mediaUrl:(h)=>`${r.basePath}/media/${encodeURIComponent(h)}/original`,images:{loading:g.loading??"lazy",decoding:"async"}})}async function rt(c){return(await w((y,v)=>v.find(U,t("media_id",c)))).map((y)=>({mediaId:String(y.media_id),collection:String(y.collection),documentId:String(y.document_id),field:String(y.field),locale:String(y.locale??""),createdAt:l(y.created_at)}))}async function at(c){let g=f(),y=c.actor??null;D(y,"update"),en(g,c);let v=await p(),{media:h,stale:I}=await w(async(_,k)=>{let A=await L(k,c.id),P=F(A,v,o),z=c.crop!==void 0&&!Ye(c.crop,P.crop)||c.focalPoint!==void 0&&!Ye(c.focalPoint,P.focalPoint)?P.variants:[],O={updated_at:new Date};if(c.filename!==void 0)O.filename=Ue(c.filename);if(c.alt!==void 0)O.alt=an(P.alt,c.alt,c.locale??r.i18n.defaultLocale);if(c.focalPoint!==void 0)O.focal_x=c.focalPoint?.x??null,O.focal_y=c.focalPoint?.y??null;let K={...u(A.metadata),...c.metadata??{}};if(c.crop===null)delete K.crop;else if(c.crop!==void 0)K.crop={...c.crop};if(z.length>0)delete K.variants;O.metadata=K,await k.update(T,t("id",c.id),O);let re=F({...A,...O},v,o);await N(_,"media.updated",re,y);let lt=X(g.images,re.mimeType);return{media:re,stale:z.map((ft)=>Be(re.storageKey,ft,lt))}});if(I.length>0)await v.delete(I).catch(()=>{return});return n.deliver(),h}async function ot(c){let g=c.actor??null;D(g,"update");let y=await w(async(v,h)=>{let I=await L(h,c.id);if(String(I.status)==="active")throw e.conflict(`"${c.id}" is in use; only an unused file has a deadline to clear`);let _={purge_after:null,purge_error:null,updated_at:new Date};await h.update(T,t("id",c.id),_);let k=F({...I,..._},await p(),o);return await N(v,"media.updated",k,g,{kept:!0}),k});return n.deliver(),y}async function st(c){let g=c.actor??null;D(g,"delete");let y=await p(),{media:v,keys:h}=await w(async(I,_)=>{let k=await L(_,c.id),A=F(k,y,o);if(c.force!==!0){let P=await _.find(U,t("media_id",c.id));if(P.length>0){let j=P.slice(0,3).map((z)=>`${String(z.collection)}/${String(z.document_id)}`).join(", ");throw e.conflict(`"${A.filename}" is used by ${P.length} document${P.length===1?"":"s"} (${j}); pass force to delete it anyway`)}}return await _.delete(U,t("media_id",c.id)),await _.delete(T,t("id",c.id)),await N(I,"media.purged",A,g),{media:A,keys:Ae(A,r.uploads)}});return await y.delete(h),n.deliver(),v}async function $e(c){let g=f(),y=await p(),v=await w((z,O)=>O.findOne(T,t("id",c.id)));if(!v)return null;let h=F(v,y,o);if(!c.variant)return ee(y,h,null);let I=g.images?.processor;if(!I||!I.supports(h.mimeType)){let z=ue(g.images,c.variant);return ee(y,h,c.variant,z)}let _=wt(g.images,c.variant,h),k=X(g.images,h.mimeType);if(k===h.mimeType&&ce(_,h))return ee(y,h,c.variant);let A=Be(h.storageKey,c.variant,k);if(c.refresh!==!0){let z=await y.get(A);if(z){let O=await y.head?.(A);return{media:h,variant:c.variant,key:A,contentType:O?.contentType??k,width:null,height:null,size:O?.size??null,body:z,url:await Pe(y,A),cached:!0,processingError:null}}}let P=await y.get(h.storageKey);if(!P)return null;let j;try{j=await Oe(I,await xe(P),_,h)}catch(z){if(Ce(z))throw z;let O=Se(z);await ct(h,c.variant,O);let K=await ee(y,h,c.variant);return K&&{...K,processingError:O}}if(!j)return ee(y,h,c.variant);return await y.put(A,j.data,{contentType:j.contentType,size:j.data.byteLength,cacheControl:"public, max-age=31536000, immutable"}),await ut(h.id,c.variant),{media:h,variant:c.variant,key:A,contentType:j.contentType,width:j.width,height:j.height,size:j.data.byteLength,body:vt(j.data),url:await Pe(y,A),cached:!1,processingError:null}}async function ct(c,g,y){let v=`${c.id}|${g}`,h=Date.now(),I=a.get(v);if(I!==void 0&&h-I<Ht)return;if(a.size>=1000)a.clear();a.set(v,h);try{await w((_)=>n.emit(_,[{type:"media.processing.failed",data:{media:de(c),variant:g,error:y},previous:null}],{actor:null,collection:"media",documentId:c.id})),n.deliver()}catch{}}async function ee(c,g,y,v=""){let h=await c.get(g.storageKey);if(!h)return null;let I=await Pe(c,g.storageKey);return{media:g,variant:y,key:g.storageKey,contentType:g.mimeType,width:g.width,height:g.height,size:g.size,body:h,url:v?`${I}?${v}`:I,cached:y===null,processingError:null}}async function ut(c,g){await w(async(y,v)=>{let h=await v.findOne(T,t("id",c));if(!h)return;let I=u(h.metadata),_=Array.isArray(I.variants)?I.variants.filter((k)=>typeof k==="string"):[];if(_.includes(g))return;await v.update(T,t("id",c),{metadata:{...I,variants:[..._,g].sort()}})})}function dt(c){return Xe(C,c)}return{upload:q,list:et,get:_e,getMany:me,update:at,delete:st,keep:ot,usages:rt,variant:$e,collect:dt,storage:p,forDocuments:tt,url:(c,g)=>Y(r,c,g),srcset:(c,g)=>Fe(r,c,g),image:(c,g)=>we(r,c,g),renderRichText:nt}}function en(n,r){for(let i of Object.keys(r.metadata??{}))if(qe.includes(i))throw e.validation(`"${i}" is reserved inside media metadata; it is maintained by the engine`);if(r.focalPoint!==void 0&&n.images?.focalPoint!==!0)throw e.validation("Focal points are off; set uploads.images.focalPoint to true");if(r.crop!==void 0&&n.images?.crop!==!0)throw e.validation("Cropping is off; set uploads.images.crop to true");if(r.focalPoint&&!on(r.focalPoint))throw e.validation("A focal point is relative: x and y are between 0 and 1")}function tn(n,r,i,a){let f=(n.prefix?.({id:r,filename:i})??String(new Date().getUTCFullYear())).replace(/^\/+|\/+$/g,"");return f?`${f}/${r}.${a}`:`${r}.${a}`}async function Pe(n,r){return n.signedUrl?n.signedUrl(r):n.url(r)}function nn(n){if(n===void 0)return Xt;if(!Number.isInteger(n)||n<1)throw new e(`limit must be a positive integer, received ${n}`,{status:400,code:"invalid_pagination"});return Math.min(n,Zt)}function rn(n,r){if(n===void 0)return{};return typeof n==="string"?{[r]:n}:{...n}}function an(n,r,i){return typeof r==="string"?{...n,[i]:r}:{...r}}function on(n){return n.x>=0&&n.x<=1&&n.y>=0&&n.y<=1}function sn(n){let r=n.name;return typeof r==="string"?r:void 0}function cn(n){let r=n.type;return typeof r==="string"&&r.length>0?r:void 0}function Ye(n,r){return JSON.stringify(n??null)===JSON.stringify(r??null)}async function un(n){let r=n.getReader();for(;;){let{done:i}=await r.read();if(i)break}}
2
+ export{V,J,So,Ee,Me,wt,Be,F,Yt,xe,vt,Ve,eo,xt,Ge,kn,Qt};
@@ -1,2 +1,2 @@
1
- var z="cms_migrations";function e(u,i,a={}){return{name:u,type:i,nullable:a.default!==void 0?!1:a.nullable??!0,storage:"column",...a.default===void 0?{}:{default:a.default},...a.unique===void 0?{}:{unique:a.unique},...a.index===void 0?{}:{index:a.index},...a.array===void 0?{}:{array:a.array},...a.references===void 0?{}:{references:a.references}}}var l=()=>e("id","text",{nullable:!1,unique:!0}),n=()=>e("created_at","timestamp",{nullable:!1}),o=()=>e("updated_at","timestamp",{nullable:!1});function t(u,i,a={}){let d=i.map((c)=>({kind:"column",column:c})),r=a.unique===!0?"uniq":"idx";return{name:a.name??`${r}_${u}_${i.join("_")}`,table:u,targets:d,unique:a.unique===!0}}function s(u,i,a=[],d){return{name:u,columns:[...i].sort((r,c)=>r.name.localeCompare(c.name)),primaryKey:["id"],indexes:[...a].sort((r,c)=>r.name.localeCompare(c.name)),...d===void 0?{}:{documentColumn:d}}}function nt(){return[_(),b(),f(),p(),x(),h(),y(),g(),T(),v(),k(),q(),S(),j(),w(),C(),D()].sort((u,i)=>u.name.localeCompare(i.name))}function ot(){return["cms_migrations",m,...nt().map((u)=>u.name)].sort()}var m="slug_history";function mo(){return s(m,[l(),e("collection","text",{nullable:!1}),e("field","text",{nullable:!1}),e("locale","text",{nullable:!1,default:""}),e("slug","text",{nullable:!1}),e("document_id","text",{nullable:!1}),n()],[t(m,["collection","field","locale","slug"],{unique:!0,name:"uniq_slug_history_address"}),t(m,["document_id"])])}function _(){return s("documents",[l(),e("collection","text",{nullable:!1}),e("data","json",{nullable:!1}),e("revision","integer",{nullable:!1,default:1}),e("scheduled_at","timestamp"),e("scheduled_patch","json"),e("deleted_at","timestamp"),e("purge_after","timestamp"),n(),o(),e("updated_by","text")],[t("documents",["collection"]),t("documents",["collection","deleted_at"]),t("documents",["collection","updated_at"]),t("documents",["scheduled_at"]),t("documents",["purge_after"])],"data")}function b(){return s("cms_users",[l(),e("email","text",{nullable:!1,unique:!0}),e("name","text"),e("password_hash","text"),e("two_factor_secret","text"),e("two_factor_enabled","boolean",{default:!1}),e("status","text",{nullable:!1,default:"active"}),e("roles","json",{nullable:!1,array:!0}),e("avatar_url","text"),e("locale","text"),e("last_login_at","timestamp"),n(),o()],[t("cms_users",["email"],{unique:!0})])}function f(){return s("cms_sessions",[l(),e("user_id","text",{nullable:!1,references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("token_hash","text",{nullable:!1,unique:!0}),e("ip","text"),e("user_agent","text"),e("expires_at","timestamp",{nullable:!1}),n()],[t("cms_sessions",["token_hash"],{unique:!0}),t("cms_sessions",["user_id"]),t("cms_sessions",["expires_at"])])}function p(){return s("cms_accounts",[l(),e("user_id","text",{nullable:!1,references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("provider","text",{nullable:!1}),e("provider_account_id","text",{nullable:!1}),e("email","text"),n(),o()],[t("cms_accounts",["provider","provider_account_id"],{unique:!0,name:"uniq_cms_accounts_provider_account"}),t("cms_accounts",["user_id"])])}function x(){return s("cms_tokens",[l(),e("type","text",{nullable:!1}),e("user_id","text",{references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("email","text"),e("token_hash","text",{nullable:!1,unique:!0}),e("data","json"),e("expires_at","timestamp",{nullable:!1}),e("consumed_at","timestamp"),n()],[t("cms_tokens",["token_hash"],{unique:!0}),t("cms_tokens",["user_id"]),t("cms_tokens",["type","expires_at"])])}function h(){return s("cms_api_keys",[l(),e("name","text",{nullable:!1}),e("user_id","text",{references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("key_hash","text",{nullable:!1,unique:!0}),e("prefix","text",{nullable:!1}),e("scopes","json",{nullable:!1,array:!0}),e("last_used_at","timestamp"),e("expires_at","timestamp"),e("revoked_at","timestamp"),n()],[t("cms_api_keys",["key_hash"],{unique:!0}),t("cms_api_keys",["user_id"])])}function y(){return s("cms_roles",[l(),e("name","text",{nullable:!1,unique:!0}),e("label","text"),e("permissions","json",{nullable:!1,array:!0}),n(),o()],[t("cms_roles",["name"],{unique:!0})])}function g(){return s("cms_ai_credentials",[l(),e("provider","text",{nullable:!1,unique:!0}),e("auth_type","text",{nullable:!1,default:"api-key"}),e("secret","text",{nullable:!1}),e("hint","text"),n(),o()],[t("cms_ai_credentials",["provider"],{unique:!0})])}function T(){return s("cms_ai_mutations",[l(),e("idempotency_key","text",{nullable:!1,unique:!0}),e("run_id","text",{nullable:!1}),e("collection","text"),e("document_id","text"),e("result","json"),n()],[t("cms_ai_mutations",["idempotency_key"],{unique:!0}),t("cms_ai_mutations",["run_id"])])}function v(){return s("cms_ai_plans",[l(),e("run_id","text",{nullable:!1}),e("actor_id","text"),e("kind","text",{nullable:!1}),e("summary","text",{nullable:!1}),e("operations","json",{nullable:!1}),e("status","text",{nullable:!1,default:"pending"}),e("result","json"),e("expires_at","timestamp",{nullable:!1}),e("approved_at","timestamp"),n()],[t("cms_ai_plans",["run_id"]),t("cms_ai_plans",["status","expires_at"])])}function k(){return s("media",[l(),e("filename","text",{nullable:!1}),e("mime_type","text",{nullable:!1}),e("size","bigint",{nullable:!1}),e("width","integer"),e("height","integer"),e("storage_key","text",{nullable:!1,unique:!0}),e("checksum","text"),e("alt","json"),e("focal_x","real"),e("focal_y","real"),e("status","text",{nullable:!1,default:"active"}),e("orphaned_at","timestamp"),e("purge_after","timestamp"),e("purge_error","text"),e("metadata","json"),e("created_by","text"),n(),o()],[t("media",["storage_key"],{unique:!0}),t("media",["status"]),t("media",["status","purge_after"])])}function q(){return s("media_usages",[l(),e("media_id","text",{nullable:!1,references:{table:"media",column:"id",onDelete:"cascade"}}),e("collection","text",{nullable:!1}),e("document_id","text",{nullable:!1}),e("field","text",{nullable:!1}),e("locale","text",{nullable:!1,default:""}),n()],[t("media_usages",["media_id"]),t("media_usages",["document_id"]),t("media_usages",["media_id","document_id","field","locale"],{unique:!0,name:"uniq_media_usages_reference"})])}function S(){return s("webhooks",[l(),e("url","text",{nullable:!1}),e("events","json",{nullable:!1,array:!0}),e("filters","json"),e("headers","json"),e("secret","text"),e("active","boolean",{nullable:!1,default:!0}),n(),o()],[t("webhooks",["active"])])}function j(){return s("webhook_deliveries",[l(),e("webhook_id","text",{nullable:!1,references:{table:"webhooks",column:"id",onDelete:"cascade"}}),e("event_id","text",{nullable:!1}),e("event_type","text",{nullable:!1}),e("status","text",{nullable:!1,default:"pending"}),e("attempt","integer",{nullable:!1,default:0}),e("request_body","json"),e("response_status","integer"),e("response_body","text"),e("error","text"),e("next_attempt_at","timestamp"),e("delivered_at","timestamp"),n()],[t("webhook_deliveries",["webhook_id","created_at"]),t("webhook_deliveries",["status","next_attempt_at"]),t("webhook_deliveries",["event_id"])])}function w(){return s("outbox",[l(),e("event_id","text",{nullable:!1,unique:!0}),e("type","text",{nullable:!1}),e("payload","json",{nullable:!1}),e("previous","json"),e("actor","json"),e("collection","text"),e("document_id","text"),e("status","text",{nullable:!1,default:"pending"}),e("attempts","integer",{nullable:!1,default:0}),e("available_at","timestamp",{nullable:!1}),e("processed_at","timestamp"),e("error","text"),n()],[t("outbox",["event_id"],{unique:!0}),t("outbox",["status","available_at"]),t("outbox",["document_id","created_at"])])}function C(){return s("activity",[l(),e("actor_id","text"),e("actor_source","text"),e("action","text",{nullable:!1}),e("source","text"),e("collection","text"),e("document_id","text"),e("locale","text"),e("changes","json"),e("ip","text"),n()],[t("activity",["collection","document_id"]),t("activity",["actor_id"]),t("activity",["created_at"])])}function D(){return s("jobs",[l(),e("type","text",{nullable:!1}),e("payload","json"),e("status","text",{nullable:!1,default:"pending"}),e("run_at","timestamp",{nullable:!1}),e("attempts","integer",{nullable:!1,default:0}),e("locked_at","timestamp"),e("locked_by","text"),e("completed_at","timestamp"),e("error","text"),n()],[t("jobs",["status","run_at"]),t("jobs",["type"])])}
2
- export{z,nt,ot,mo};
1
+ var z="cms_migrations";function e(u,i,a={}){return{name:u,type:i,nullable:a.default!==void 0?!1:a.nullable??!0,storage:"column",...a.default===void 0?{}:{default:a.default},...a.unique===void 0?{}:{unique:a.unique},...a.index===void 0?{}:{index:a.index},...a.array===void 0?{}:{array:a.array},...a.references===void 0?{}:{references:a.references}}}var l=()=>e("id","text",{nullable:!1,unique:!0}),n=()=>e("created_at","timestamp",{nullable:!1}),o=()=>e("updated_at","timestamp",{nullable:!1});function t(u,i,a={}){let d=i.map((c)=>({kind:"column",column:c})),r=a.unique===!0?"uniq":"idx";return{name:a.name??`${r}_${u}_${i.join("_")}`,table:u,targets:d,unique:a.unique===!0}}function s(u,i,a=[],d){return{name:u,columns:[...i].sort((r,c)=>r.name.localeCompare(c.name)),primaryKey:["id"],indexes:[...a].sort((r,c)=>r.name.localeCompare(c.name)),...d===void 0?{}:{documentColumn:d}}}function nt(){return[_(),b(),f(),p(),x(),h(),y(),g(),T(),v(),k(),q(),S(),j(),w(),C(),D()].sort((u,i)=>u.name.localeCompare(i.name))}function ot(){return["cms_migrations",m,...nt().map((u)=>u.name)].sort()}var m="slug_history";function yo(){return s(m,[l(),e("collection","text",{nullable:!1}),e("field","text",{nullable:!1}),e("locale","text",{nullable:!1,default:""}),e("slug","text",{nullable:!1}),e("document_id","text",{nullable:!1}),n()],[t(m,["collection","field","locale","slug"],{unique:!0,name:"uniq_slug_history_address"}),t(m,["document_id"])])}function _(){return s("documents",[l(),e("collection","text",{nullable:!1}),e("data","json",{nullable:!1}),e("revision","integer",{nullable:!1,default:1}),e("scheduled_at","timestamp"),e("scheduled_patch","json"),e("deleted_at","timestamp"),e("purge_after","timestamp"),n(),o(),e("updated_by","text")],[t("documents",["collection"]),t("documents",["collection","deleted_at"]),t("documents",["collection","updated_at"]),t("documents",["scheduled_at"]),t("documents",["purge_after"])],"data")}function b(){return s("cms_users",[l(),e("email","text",{nullable:!1,unique:!0}),e("name","text"),e("password_hash","text"),e("two_factor_secret","text"),e("two_factor_enabled","boolean",{default:!1}),e("status","text",{nullable:!1,default:"active"}),e("roles","json",{nullable:!1,array:!0}),e("avatar_url","text"),e("locale","text"),e("last_login_at","timestamp"),n(),o()],[t("cms_users",["email"],{unique:!0})])}function f(){return s("cms_sessions",[l(),e("user_id","text",{nullable:!1,references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("token_hash","text",{nullable:!1,unique:!0}),e("ip","text"),e("user_agent","text"),e("expires_at","timestamp",{nullable:!1}),n()],[t("cms_sessions",["token_hash"],{unique:!0}),t("cms_sessions",["user_id"]),t("cms_sessions",["expires_at"])])}function p(){return s("cms_accounts",[l(),e("user_id","text",{nullable:!1,references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("provider","text",{nullable:!1}),e("provider_account_id","text",{nullable:!1}),e("email","text"),n(),o()],[t("cms_accounts",["provider","provider_account_id"],{unique:!0,name:"uniq_cms_accounts_provider_account"}),t("cms_accounts",["user_id"])])}function x(){return s("cms_tokens",[l(),e("type","text",{nullable:!1}),e("user_id","text",{references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("email","text"),e("token_hash","text",{nullable:!1,unique:!0}),e("data","json"),e("expires_at","timestamp",{nullable:!1}),e("consumed_at","timestamp"),n()],[t("cms_tokens",["token_hash"],{unique:!0}),t("cms_tokens",["user_id"]),t("cms_tokens",["type","expires_at"])])}function h(){return s("cms_api_keys",[l(),e("name","text",{nullable:!1}),e("user_id","text",{references:{table:"cms_users",column:"id",onDelete:"cascade"}}),e("key_hash","text",{nullable:!1,unique:!0}),e("prefix","text",{nullable:!1}),e("scopes","json",{nullable:!1,array:!0}),e("last_used_at","timestamp"),e("expires_at","timestamp"),e("revoked_at","timestamp"),n()],[t("cms_api_keys",["key_hash"],{unique:!0}),t("cms_api_keys",["user_id"])])}function y(){return s("cms_roles",[l(),e("name","text",{nullable:!1,unique:!0}),e("label","text"),e("permissions","json",{nullable:!1,array:!0}),n(),o()],[t("cms_roles",["name"],{unique:!0})])}function g(){return s("cms_ai_credentials",[l(),e("provider","text",{nullable:!1,unique:!0}),e("auth_type","text",{nullable:!1,default:"api-key"}),e("secret","text",{nullable:!1}),e("hint","text"),n(),o()],[t("cms_ai_credentials",["provider"],{unique:!0})])}function T(){return s("cms_ai_mutations",[l(),e("idempotency_key","text",{nullable:!1,unique:!0}),e("run_id","text",{nullable:!1}),e("collection","text"),e("document_id","text"),e("result","json"),n()],[t("cms_ai_mutations",["idempotency_key"],{unique:!0}),t("cms_ai_mutations",["run_id"])])}function v(){return s("cms_ai_plans",[l(),e("run_id","text",{nullable:!1}),e("actor_id","text"),e("kind","text",{nullable:!1}),e("summary","text",{nullable:!1}),e("operations","json",{nullable:!1}),e("status","text",{nullable:!1,default:"pending"}),e("result","json"),e("expires_at","timestamp",{nullable:!1}),e("approved_at","timestamp"),n()],[t("cms_ai_plans",["run_id"]),t("cms_ai_plans",["status","expires_at"])])}function k(){return s("media",[l(),e("filename","text",{nullable:!1}),e("mime_type","text",{nullable:!1}),e("size","bigint",{nullable:!1}),e("width","integer"),e("height","integer"),e("storage_key","text",{nullable:!1,unique:!0}),e("checksum","text"),e("alt","json"),e("focal_x","real"),e("focal_y","real"),e("status","text",{nullable:!1,default:"active"}),e("orphaned_at","timestamp"),e("purge_after","timestamp"),e("purge_error","text"),e("metadata","json"),e("created_by","text"),n(),o()],[t("media",["storage_key"],{unique:!0}),t("media",["status"]),t("media",["status","purge_after"])])}function q(){return s("media_usages",[l(),e("media_id","text",{nullable:!1,references:{table:"media",column:"id",onDelete:"cascade"}}),e("collection","text",{nullable:!1}),e("document_id","text",{nullable:!1}),e("field","text",{nullable:!1}),e("locale","text",{nullable:!1,default:""}),n()],[t("media_usages",["media_id"]),t("media_usages",["document_id"]),t("media_usages",["media_id","document_id","field","locale"],{unique:!0,name:"uniq_media_usages_reference"})])}function S(){return s("webhooks",[l(),e("url","text",{nullable:!1}),e("events","json",{nullable:!1,array:!0}),e("filters","json"),e("headers","json"),e("secret","text"),e("active","boolean",{nullable:!1,default:!0}),n(),o()],[t("webhooks",["active"])])}function j(){return s("webhook_deliveries",[l(),e("webhook_id","text",{nullable:!1,references:{table:"webhooks",column:"id",onDelete:"cascade"}}),e("event_id","text",{nullable:!1}),e("event_type","text",{nullable:!1}),e("status","text",{nullable:!1,default:"pending"}),e("attempt","integer",{nullable:!1,default:0}),e("request_body","json"),e("response_status","integer"),e("response_body","text"),e("error","text"),e("next_attempt_at","timestamp"),e("delivered_at","timestamp"),n()],[t("webhook_deliveries",["webhook_id","created_at"]),t("webhook_deliveries",["status","next_attempt_at"]),t("webhook_deliveries",["event_id"])])}function w(){return s("outbox",[l(),e("event_id","text",{nullable:!1,unique:!0}),e("type","text",{nullable:!1}),e("payload","json",{nullable:!1}),e("previous","json"),e("actor","json"),e("collection","text"),e("document_id","text"),e("status","text",{nullable:!1,default:"pending"}),e("attempts","integer",{nullable:!1,default:0}),e("available_at","timestamp",{nullable:!1}),e("processed_at","timestamp"),e("error","text"),n()],[t("outbox",["event_id"],{unique:!0}),t("outbox",["status","available_at"]),t("outbox",["document_id","created_at"])])}function C(){return s("activity",[l(),e("actor_id","text"),e("actor_source","text"),e("action","text",{nullable:!1}),e("source","text"),e("collection","text"),e("document_id","text"),e("locale","text"),e("changes","json"),e("ip","text"),n()],[t("activity",["collection","document_id"]),t("activity",["actor_id"]),t("activity",["created_at"])])}function D(){return s("jobs",[l(),e("type","text",{nullable:!1}),e("payload","json"),e("status","text",{nullable:!1,default:"pending"}),e("run_at","timestamp",{nullable:!1}),e("attempts","integer",{nullable:!1,default:0}),e("locked_at","timestamp"),e("locked_by","text"),e("completed_at","timestamp"),e("error","text"),n()],[t("jobs",["status","run_at"]),t("jobs",["type"])])}
2
+ export{z,nt,ot,yo};
@@ -0,0 +1,2 @@
1
+ import{e}from"./index-x72d1hzh.js";function Vn(n){let t=x(n),i=/UNIQUE constraint failed: (.*)/.exec(t)?.[1];if(i===void 0)return null;let s=/^index '([^']+)'/.exec(i)?.[1];if(s!==void 0)return{index:s};let r=(/^[\w.]+(?:, [\w.]+)*/.exec(i)?.[0]??"").split(", ").map((o)=>o.slice(o.lastIndexOf(".")+1)).filter(Boolean);return r.length>0?{columns:r}:{}}function Gn(n){if(typeof n!=="object"||n===null)return null;let t=n;if(t.code!=="23505")return null;let i=t.constraint??t.constraint_name,s=typeof i==="string"?i:/unique constraint "([^"]+)"/.exec(x(n))?.[1];return s===void 0?{}:{index:s}}function Kn(n){let t=x(n);if(n?.code!==11000&&!t.startsWith("E11000"))return null;let s=/index: (\S+)/.exec(t)?.[1];return s===void 0?{}:{index:s}}function at(n,t,i,s,r){let o=(u,d)=>new e(u,{status:409,code:"conflict",cause:r,...d===void 0?{}:{details:d}}),l=n.tables.find((u)=>u.name===t),c=y(n,t,i);if(c?.where?.column==="collection"){let u=n.collections.find((g)=>g.slug===c.where?.equals&&g.table===c.table),d=c.targets.length===1?c.targets[0]:void 0,p=d?.kind==="json"?d.path.join("."):void 0;if(u!==void 0&&p!==void 0)return o(`${u.name}: ${p} is already used by another document, possibly one in the trash.`,{fields:{[p]:"is already used by another document"}})}let a=c?.targets.map((u)=>u.column)??i.columns??[],f=l?.primaryKey??[],m=n.collections.some((u)=>u.table===t)?"A document":`A ${t} row`;if(i.index===`${t}_pkey`||i.index==="_id_"||a.length>0&&h(a,f)){let u=f.length===1?f[0]:void 0,d=u===void 0?void 0:s?.[u];return o(typeof d==="string"?`${m} with the id "${d}" already exists.`:`${m} with the same ${f.join(", ")||"key"} already exists.`)}return o(a.length>0?`${m} with the same ${a.join(", ")} already exists.`:`${m} with the same unique value already exists.`)}function y(n,t,i){let s=n.tables.flatMap((o)=>o.indexes);if(i.index!==void 0)return s.find((o)=>o.name===i.index);let r=i.columns;if(r===void 0)return;return s.find((o)=>o.table===t&&o.unique&&o.targets.every((l)=>l.kind==="column")&&h(o.targets.map((l)=>l.column),r))}function h(n,t){return n.length===t.length&&n.every((i)=>t.includes(i))}function x(n){return n instanceof Error?n.message:typeof n==="string"?n:""}
2
+ export{Vn,Gn,Kn,at};