@heyo-sh/heyo-cms 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/astro.d.ts +12 -5
- package/dist/adapters/astro.d.ts.map +1 -1
- package/dist/adapters/astro.js +1 -1
- package/dist/adapters/deliver.d.ts +26 -0
- package/dist/adapters/deliver.d.ts.map +1 -0
- package/dist/adapters/next.d.ts +26 -12
- package/dist/adapters/next.d.ts.map +1 -1
- package/dist/adapters/next.js +1 -1
- package/dist/adapters/nuxt.d.ts +10 -6
- package/dist/adapters/nuxt.d.ts.map +1 -1
- package/dist/adapters/nuxt.js +1 -1
- package/dist/adapters/react-router.d.ts +12 -5
- package/dist/adapters/react-router.d.ts.map +1 -1
- package/dist/adapters/react-router.js +1 -1
- package/dist/adapters/sveltekit.d.ts +9 -5
- package/dist/adapters/sveltekit.d.ts.map +1 -1
- package/dist/adapters/sveltekit.js +1 -1
- package/dist/ai.js +1 -1
- package/dist/auth.js +1 -1
- package/dist/cli.js +2 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/types.d.ts +24 -1
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client.js +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +1 -1
- package/dist/content.js +1 -1
- package/dist/db/d1.js +1 -1
- package/dist/db/mongodb.js +2 -2
- package/dist/db/postgres.js +1 -1
- package/dist/db/sql/dialect.d.ts +2 -0
- package/dist/db/sql/dialect.d.ts.map +1 -1
- package/dist/db/sqlite.d.ts +13 -2
- package/dist/db/sqlite.d.ts.map +1 -1
- package/dist/db/sqlite.js +1 -1
- package/dist/editor/builtin.d.ts.map +1 -1
- package/dist/editor/serialize.d.ts.map +1 -1
- package/dist/editor.d.ts +1 -1
- package/dist/editor.d.ts.map +1 -1
- package/dist/editor.js +1 -1
- package/dist/engine/engine.d.ts +19 -0
- package/dist/engine/engine.d.ts.map +1 -1
- package/dist/engine/slugs.d.ts +124 -0
- package/dist/engine/slugs.d.ts.map +1 -0
- package/dist/fields/builtin.d.ts +42 -15
- package/dist/fields/builtin.d.ts.map +1 -1
- package/dist/fields.d.ts +1 -0
- package/dist/fields.d.ts.map +1 -1
- package/dist/fields.js +1 -1
- package/dist/http/handler.d.ts.map +1 -1
- package/dist/http/rich-text.d.ts +12 -1
- package/dist/http/rich-text.d.ts.map +1 -1
- package/dist/http/routes/documents.d.ts.map +1 -1
- package/dist/http/routes/media.d.ts +30 -0
- package/dist/http/routes/media.d.ts.map +1 -1
- package/dist/http.js +1 -1
- package/dist/index-2ddk43me.js +2 -0
- package/dist/index-2prbs05k.js +2 -0
- package/dist/index-385ggnge.js +2 -0
- package/dist/{index-7k091gpe.js → index-466cwb0b.js} +2 -2
- package/dist/{index-b2ecggck.js → index-4qrep5f0.js} +6 -6
- package/dist/{index-k8wbg1dw.js → index-67e458ws.js} +2 -2
- package/dist/index-6m1kjq9g.js +2 -0
- package/dist/index-6w10rch0.js +3 -0
- package/dist/index-761dec5z.js +2 -0
- package/dist/{index-2kb5nbxx.js → index-8nzmqy0f.js} +2 -2
- package/dist/{index-vq2978e7.js → index-8x2em6c8.js} +8 -8
- package/dist/index-91fa1gzf.js +2 -0
- package/dist/index-a8jcwqsf.js +2 -0
- package/dist/index-abfzb1ve.js +2 -0
- package/dist/index-cv0hpz3d.js +2 -0
- package/dist/index-g041kfa5.js +18 -0
- package/dist/index-hbx67b20.js +7 -0
- package/dist/index-hpast878.js +40 -0
- package/dist/index-kc1j3h6z.js +2 -0
- package/dist/index-p2cqsmvw.js +2 -0
- package/dist/index-rg9tpg3p.js +5 -0
- package/dist/{index-cbwwtcm4.js → index-rw0hze6x.js} +2 -2
- package/dist/index-s9x07zb3.js +2 -0
- package/dist/index-sgdnp83t.js +2 -0
- package/dist/{index-34s342fz.js → index-szaq03qq.js} +2 -2
- package/dist/{index-9x1z3b85.js → index-vkwzdfte.js} +4 -4
- package/dist/{index-gpwcmmvr.js → index-vzhxn50e.js} +2 -2
- package/dist/index-y8kzzn94.js +2 -0
- package/dist/{index-7a231xfp.js → index-ypcmns0v.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/jobs.js +1 -1
- package/dist/media/cloudflare.d.ts +58 -0
- package/dist/media/cloudflare.d.ts.map +1 -0
- package/dist/media/document.d.ts +7 -6
- package/dist/media/document.d.ts.map +1 -1
- package/dist/media/gc.d.ts.map +1 -1
- package/dist/media/pipeline.d.ts +19 -0
- package/dist/media/pipeline.d.ts.map +1 -1
- package/dist/media/service.d.ts.map +1 -1
- package/dist/media/urls.d.ts +77 -0
- package/dist/media/urls.d.ts.map +1 -0
- package/dist/media/usages.d.ts +9 -1
- package/dist/media/usages.d.ts.map +1 -1
- package/dist/media/variants.d.ts +11 -0
- package/dist/media/variants.d.ts.map +1 -1
- package/dist/migrations.js +1 -1
- package/dist/plugins/indexnow.d.ts +82 -0
- package/dist/plugins/indexnow.d.ts.map +1 -0
- package/dist/plugins.d.ts +9 -0
- package/dist/plugins.d.ts.map +1 -0
- package/dist/plugins.js +1 -0
- package/dist/query.js +1 -1
- package/dist/{run-3r72dwhs.js → run-bjge3v8e.js} +4 -4
- package/dist/schema/snapshot.d.ts +2 -0
- package/dist/schema/snapshot.d.ts.map +1 -1
- package/dist/schema/system.d.ts +9 -0
- package/dist/schema/system.d.ts.map +1 -1
- package/dist/schema.js +1 -1
- package/dist/slugify.d.ts +31 -0
- package/dist/slugify.d.ts.map +1 -0
- package/dist/telemetry.js +1 -1
- package/dist/types/api.d.ts +56 -0
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/config.d.ts +15 -0
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/editor.d.ts +26 -0
- package/dist/types/editor.d.ts.map +1 -1
- package/dist/types/media.d.ts +97 -0
- package/dist/types/media.d.ts.map +1 -1
- package/dist/types/plugin.d.ts +23 -1
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/uploads.d.ts +1 -0
- package/dist/uploads.d.ts.map +1 -1
- package/dist/uploads.js +4 -4
- package/dist/webhooks.js +1 -1
- package/package.json +9 -5
- package/dist/index-2757kej5.js +0 -2
- package/dist/index-2z1qe5mw.js +0 -2
- package/dist/index-5ngtc7gy.js +0 -2
- package/dist/index-9zqnf6gx.js +0 -23
- package/dist/index-hq05mc1n.js +0 -3
- package/dist/index-hy1x46nf.js +0 -2
- package/dist/index-kbsgt44t.js +0 -2
- package/dist/index-m82a0shw.js +0 -2
- package/dist/index-md79xr6h.js +0 -5
- package/dist/index-nvgwyykk.js +0 -40
- package/dist/index-ty698y02.js +0 -2
- package/dist/index-vxw0a03g.js +0 -2
- package/dist/index-wj8y1xcj.js +0 -2
- package/dist/index-y5mwknr9.js +0 -2
- package/dist/index-ymq6jsar.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{s,R,t,H,ae,m}from"./index-6m1kjq9g.js";import{ho,rt,jt,Et,l,u}from"./index-sgdnp83t.js";import{Pe,pn,we,re,fo}from"./index-p2cqsmvw.js";import{w}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b}from"./index-8nzmqy0f.js";import{e}from"./index-x72d1hzh.js";var Nn={github:{id:"github",endpoints:{authorization:"https://github.com/login/oauth/authorize",token:"https://github.com/login/oauth/access_token",userinfo:"https://api.github.com/user"},scope:"read:user user:email",pkce:!1,async profile(c,f){let p=await pe(f,"https://api.github.com/user",c.accessToken),g=typeof p.email==="string"?p.email:await Me(f,c.accessToken);return{id:String(p.id??""),email:g,name:M(p.name)??M(p.login),avatarUrl:M(p.avatar_url),claims:p}}},google:{id:"google",endpoints:{authorization:"https://accounts.google.com/o/oauth2/v2/auth",token:"https://oauth2.googleapis.com/token",userinfo:"https://openidconnect.googleapis.com/v1/userinfo"},scope:"openid email profile",pkce:!0,async profile(c,f){let p=c.idToken?$t(c.idToken):await pe(f,"https://openidconnect.googleapis.com/v1/userinfo",c.accessToken);return X(p)}},microsoft:{id:"microsoft",endpoints:{authorization:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",token:"https://login.microsoftonline.com/common/oauth2/v2.0/token",userinfo:"https://graph.microsoft.com/oidc/userinfo"},scope:"openid email profile",pkce:!0,async profile(c,f){let p=c.idToken?$t(c.idToken):await pe(f,"https://graph.microsoft.com/oidc/userinfo",c.accessToken);return X(p)}}};function X(c){return{id:String(c.sub??""),email:M(c.email),name:M(c.name)??M(c.preferred_username),avatarUrl:M(c.picture),claims:c}}function $t(c){let f=c.split(".")[1];if(!f)return{};let p=f.replaceAll("-","+").replaceAll("_","/");try{let g=atob(p.padEnd(Math.ceil(p.length/4)*4,"=")),k=Uint8Array.from(g,(v)=>v.charCodeAt(0));return JSON.parse(new TextDecoder().decode(k))}catch{return{}}}var fe=new Map;function Ce(c,f){let p=`${x(c)}/.well-known/openid-configuration`,g=fe.get(p);if(g)return g;let k=(async()=>{let v=await f(p,{headers:{accept:"application/json"}});if(!v.ok)throw new e(`OIDC discovery failed for ${c} (${v.status})`,{status:502,code:"oidc_discovery_failed"});let T=await v.json();return{authorization:String(T.authorization_endpoint??""),token:String(T.token_endpoint??""),...typeof T.userinfo_endpoint==="string"?{userinfo:T.userinfo_endpoint}:{}}})();return fe.set(p,k),k.catch(()=>fe.delete(p)),k}function Ue(c){let f=new URL(c.endpoints.authorization);if(f.searchParams.set("response_type","code"),f.searchParams.set("client_id",c.clientId),f.searchParams.set("redirect_uri",c.redirectUri),f.searchParams.set("scope",c.scope),f.searchParams.set("state",c.state),c.codeChallenge)f.searchParams.set("code_challenge",c.codeChallenge),f.searchParams.set("code_challenge_method","S256");for(let[p,g]of Object.entries(c.extra??{}))f.searchParams.set(p,g);return f.toString()}async function Oe(c){return{verifier:c,challenge:await fo(c)}}async function xe(c){let f=new URLSearchParams({grant_type:"authorization_code",code:c.code,redirect_uri:c.redirectUri,client_id:c.clientId,client_secret:c.clientSecret});if(c.codeVerifier)f.set("code_verifier",c.codeVerifier);let p=await c.fetchImpl(c.endpoints.token,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:f.toString()}),g=await p.json().catch(()=>({}));if(!p.ok||typeof g.access_token!=="string"){let k=M(g.error_description)??M(g.error)??`HTTP ${p.status}`;throw new e(`OAuth token exchange failed: ${k}`,{status:401,code:"oauth_exchange_failed"})}return{accessToken:g.access_token,...typeof g.id_token==="string"?{idToken:g.id_token}:{},...typeof g.token_type==="string"?{tokenType:g.token_type}:{}}}async function pe(c,f,p){let g=await c(f,{headers:{authorization:`Bearer ${p}`,accept:"application/json","user-agent":"heyo-cms"}});if(!g.ok)throw new e(`OAuth profile request failed (${g.status})`,{status:502,code:"oauth_profile_failed"});return await g.json()}async function Me(c,f){let p=await c("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${f}`,accept:"application/json","user-agent":"heyo-cms"}});if(!p.ok)return null;let g=await p.json();return(g.find((v)=>v.primary&&v.verified)??g.find((v)=>v.verified))?.email??null}function M(c){return typeof c==="string"&&c.length>0?c:null}function Un(){return qe(crypto.getRandomValues(new Uint8Array(20)))}function Jn(c){let f=`${encodeURIComponent(c.issuer)}:${encodeURIComponent(c.account)}`,p=new URLSearchParams({secret:c.secret,issuer:c.issuer,algorithm:"SHA1",digits:String(6),period:String(30)});return`otpauth://totp/${f}?${p.toString()}`}async function Qo(c,f=Date.now()){return De(c,Math.floor(f/1000/30))}async function cn(c,f,p={}){if(!c)return!1;let g=f.replaceAll(/\s/g,"");if(!/^\d{6}$/.test(g))return!1;let k=Math.floor((p.at??Date.now())/1000/30),v=p.window??1;for(let T=-v;T<=v;T+=1){let C=await De(c,k+T),U=0;for(let E=0;E<C.length;E+=1)U|=C.charCodeAt(E)^g.charCodeAt(E);if(U===0)return!0}return!1}async function De(c,f){let p=await crypto.subtle.importKey("raw",Ne(c),{name:"HMAC",hash:"SHA-1"},!1,["sign"]),g=new Uint8Array(8),k=f;for(let U=7;U>=0;U-=1)g[U]=k&255,k=Math.floor(k/256);let v=new Uint8Array(await crypto.subtle.sign("HMAC",p,g)),T=(v[v.length-1]??0)&15,C=((v[T]??0)&127)<<24|((v[T+1]??0)&255)<<16|((v[T+2]??0)&255)<<8|(v[T+3]??0)&255;return String(C%1e6).padStart(6,"0")}function qe(c){let f=0,p=0,g="";for(let k of c){p=p<<8|k,f+=8;while(f>=5)g+="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[p>>>f-5&31],f-=5}if(f>0)g+="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[p<<5-f&31];return g}function Ne(c){let f=c.replaceAll("=","").replaceAll(/\s/g,"").toUpperCase(),p=[],g=0,k=0;for(let v of f){let T="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(v);if(T===-1)continue;if(k=k<<5|T,g+=5,g>=8)p.push(k>>>g-8&255),g-=8}return new Uint8Array(p)}var A="cms_users",z="cms_sessions",q="cms_tokens",he="cms_accounts",V="cms_api_keys",N="cms_roles",be="heyo_cms_session",dn="hck_",Je={session:"7d",invite:"7d",magicLink:"15m",passwordReset:"1h",twoFactor:"10m",oauth:"10m"},Be=8,$e=5,Ke=/^[^@\s]+@[^@\s.]+\.[^@\s]+$/,He=/^[a-z][a-z0-9_-]*$/,Ve=1e4;function un(c){let{config:f}=c,p=c.fetch??((...n)=>fetch(...n)),g,k=()=>g??=Pe(we(16)),v,T=!1,C=()=>f.admin.auth,U=(n,i)=>w(i??Je[n]),E=(n)=>{let i=C();if(!i||!i.methods.includes(n))throw new e(`The "${n}" sign-in method is not enabled; add it to admin.auth.methods`,{status:400,code:"method_not_enabled"});return i};async function y(n){let i=await c.database();return i.transaction((r)=>n(r,i))}async function O(n,i,r,o){return(await i.query(n,{table:r,where:o,limit:1}))[0]??null}async function B(n,i,r,o){let d=(await i.mutate(n,{kind:"insert",table:r,values:o})).rows[0];if(!d)throw new e(`Insert into ${r} returned no row.`,{status:500,code:"insert_without_row"});return d}async function S(n,i,r,o,a){return(await i.mutate(n,{kind:"update",table:r,where:o,set:a,returning:!1})).count}async function F(n,i,r,o){return(await i.mutate(n,{kind:"delete",table:r,where:o})).count}async function j(n,i,r,o=null){let a={type:i,data:r,previous:null},d={actor:o};await c.emit(n,[a],d)}async function le(){let n=f.rbac?.roles??{};if(f.rbac?.customRoles!==!0)return n;let i=Date.now();if(v&&i-v.at<Ve)return v.map;let r=await y((d,h)=>h.query(d,{table:N})),o={};for(let d of r)o[String(d.name)]=J(d.permissions);let a={...o,...n};return v={at:i,map:a},a}async function Z(n){let i=n.roles.length>0?n.roles:f.rbac?.defaultRole?[f.rbac.defaultRole]:[];return{id:n.id,source:"session",roles:i,permissions:rt(i,await le())}}async function Y(n,i,r){let o=r.token??we(),a=new Date(Date.now()+r.ttlMs);return await B(n,i,q,{id:b("tok"),type:r.type,user_id:r.userId??null,email:r.email??null,token_hash:await re(o),data:r.data??null,expires_at:a,consumed_at:null,created_at:new Date}),{token:o,expiresAt:a}}async function _e(n,i,r,o){let a=await O(n,i,q,s(t("token_hash",await re(o)),t("type",r)));if(!a||ye(a.expires_at))throw e.unauthorized("This link is invalid or has expired");if(a.consumed_at!==null)throw e.unauthorized("This link has already been used");return a}async function ve(n,i,r){if(await S(n,i,q,s(t("id",String(r.id)),t("consumed_at",null)),{consumed_at:new Date})!==1)throw e.unauthorized("This link has already been used")}async function ee(n,i,r,o){let a=await _e(n,i,r,o);return await ve(n,i,a),a}async function te(n,i,r,o){let a=we(),d=new Date,h=new Date(d.getTime()+U("session",C()?.session?.expiresIn)),_=await B(n,i,z,{id:b("ses"),user_id:r.id,token_hash:await re(a),ip:o.ip??null,user_agent:o.userAgent??null,expires_at:h,created_at:d});return await S(n,i,A,t("id",r.id),{last_login_at:d}),{status:"signed-in",token:a,expiresAt:h.toISOString(),session:ge(_),user:{...r,lastLoginAt:d.toISOString()},actor:await Z(r)}}async function ne(n,i,r,o){if(!r.twoFactorEnabled)return te(n,i,r,o);let a=await Y(n,i,{type:"two-factor",ttlMs:U("twoFactor",void 0),userId:r.id,email:r.email});return{status:"two-factor-required",challenge:a.token,expiresAt:a.expiresAt.toISOString(),userId:r.id}}async function D(n,i,r){let o=await O(n,i,A,t("id",r));return o?W(o):null}async function K(n,i,r){let o=await O(n,i,A,t("email",ce(r)));return o?{user:W(o),row:o}:null}function se(n){if(n.status==="disabled")throw e.forbidden("This account has been disabled")}async function ke(n){let i=C();if(n==="oidc"){let a=i?.sso;if(!a)throw new e("SSO is not configured; set admin.auth.sso",{status:400,code:"method_not_enabled"});let d=await Ce(a.issuer,p),h=Ae("oidc",{...a.clientId===void 0?{}:{clientId:a.clientId},...a.clientSecret===void 0?{}:{clientSecret:a.clientSecret}});return{id:"oidc",endpoints:d,scope:a.scope??"openid email profile",pkce:!0,...h,provision:a.provision!==!1,...a.mapRoles?{mapRoles:a.mapRoles}:{},profile:async(_)=>_.idToken?X($t(_.idToken)):X(await je(d,_.accessToken))}}E(n);let r=Nn[n];if(!r)throw new e(`Unknown OAuth provider "${n}"`,{status:400,code:"unknown_provider"});let o=Ae(n);return{id:n,endpoints:r.endpoints,scope:i?.providers?.[n]?.scope??r.scope,pkce:r.pkce,...o,provision:!1,profile:r.profile}}async function je(n,i){if(!n.userinfo)return{};let r=await p(n.userinfo,{headers:{authorization:`Bearer ${i}`,accept:"application/json"}});if(!r.ok)return{};return await r.json()}function Ae(n,i={}){let r=C()?.providers?.[n],o=n.toUpperCase(),a=i.clientId??r?.clientId??ue(`HEYO_CMS_${o}_CLIENT_ID`)??ue(`${o}_CLIENT_ID`),d=i.clientSecret??r?.clientSecret??ue(`HEYO_CMS_${o}_CLIENT_SECRET`)??ue(`${o}_CLIENT_SECRET`);if(!a||!d)throw new e(`No credentials for "${n}": set admin.auth.providers.${n} or ${o}_CLIENT_ID and ${o}_CLIENT_SECRET`,{status:500,code:"provider_not_configured"});return{clientId:a,clientSecret:d}}async function ze(n,i,r,o){let a=await O(n,i,he,s(t("provider",r.id),t("provider_account_id",o.id)));if(a){let P=await D(n,i,String(a.user_id));if(!P)throw e.unauthorized("The linked account no longer exists");return Te(n,i,r,o,P)}let d=o.email?ce(o.email):null;if(!d)throw new e(`${r.id} did not return a verified email address, so the account cannot be matched`,{status:400,code:"oauth_without_email"});let _=(await K(n,i,d))?.user??null;if(!_){if(!r.provision)throw e.forbidden(`No CMS account for ${d}. An administrator has to invite this address first.`);_=await ie(n,i,{email:d,...o.name?{name:o.name}:{},roles:r.mapRoles?r.mapRoles(o.claims):f.rbac?.defaultRole?[f.rbac.defaultRole]:[],status:"active"}),await j(n,"user.joined",{userId:_.id,email:d,provider:r.id,provisioned:!0})}else if(_.status==="invited")await S(n,i,A,t("id",_.id),{status:"active",updated_at:new Date}),_={..._,status:"active"},await j(n,"user.joined",{userId:_.id,email:_.email});return await B(n,i,he,{id:b("acc"),user_id:_.id,provider:r.id,provider_account_id:o.id,email:d,created_at:new Date,updated_at:new Date}),Te(n,i,r,o,_)}async function Te(n,i,r,o,a){if(!r.mapRoles)return a;let d=r.mapRoles(o.claims);if(Fe(d,a.roles))return a;return await S(n,i,A,t("id",a.id),{roles:d,updated_at:new Date}),await j(n,"role.changed",{userId:a.id,roles:d,previous:a.roles,source:r.id}),{...a,roles:d}}async function ie(n,i,r){let o=ce(r.email);if(await O(n,i,A,t("email",o)))throw e.conflict(`A user with the email ${o} already exists`);if(r.password!==void 0)G(r.password);let d=new Date,h=await B(n,i,A,{id:b("usr"),email:o,name:r.name??null,password_hash:r.password===void 0?null:await Pe(r.password),two_factor_secret:null,two_factor_enabled:!1,status:r.status??"active",roles:r.roles??[],avatar_url:null,locale:r.locale??null,last_login_at:null,created_at:d,updated_at:d});return W(h)}function G(n){let i=C()?.password?.minLength??Be;if(n.length<i)throw e.validation(`The password must be at least ${i} characters`)}function Se(){let n=C();if(!n||!n.methods.includes("password"))return null;let i=n.firstUser??!0;if(i===!1)return null;if(i!==!0&&i.roles)return i.roles;let r=f.rbac?.roles;if(!r||"admin"in r)return["admin"];let o=Object.entries(r).find(([,a])=>a.includes(ho));return o?[o[0]]:["admin"]}async function oe(n){if(n.length===0||!f.rbac)return;let i=await le(),r=n.filter((o)=>!(o in i));if(r.length>0)throw e.validation(`Unknown role ${r.map((o)=>`"${o}"`).join(", ")}`)}let Q={async actorFromRequest(n){let i=n.headers.get("authorization"),o=(i?.toLowerCase().startsWith("bearer ")?i.slice(7).trim():null)??We(n,be);return o?Q.actorFromToken(o):null},async actorFromToken(n){if(n.startsWith(dn))return Q.apiKeys.verify(n);return(await Q.sessions.verify(n))?.actor??null},actorForUser:Z,users:{async list(n={}){let i=[];if(n.status)i.push(t("status",n.status));if(n.search){let o=`%${n.search}%`;i.push(R(ae("email",o,!0),ae("name",o,!0)))}return(await y((o,a)=>a.query(o,{table:A,...i.length>0?{where:s(...i)}:{},orderBy:[m("created_at","asc"),m("id","asc")],limit:n.limit??50,...n.offset===void 0?{}:{offset:n.offset}}))).map(W)},async get(n){return y((i,r)=>D(i,r,n))},async byEmail(n){return y(async(i,r)=>(await K(i,r,n))?.user??null)},async count(){let n=await y((i,r)=>r.query(i,{table:A,count:!0}));return Number(n[0]?.count??0)},async create(n){return await oe(n.roles??[]),y((i,r)=>ie(i,r,n))},async update(n,i){if(i.roles)await oe(i.roles);let r=await y(async(o,a)=>{let d=await D(o,a,n);if(!d)throw e.notFound(`No user with id "${n}"`);let h={updated_at:new Date};if(i.name!==void 0)h.name=i.name;if(i.status!==void 0)h.status=i.status;if(i.locale!==void 0)h.locale=i.locale;if(i.avatarUrl!==void 0)h.avatar_url=i.avatarUrl;if(i.roles!==void 0)h.roles=i.roles;if(await S(o,a,A,t("id",n),h),i.roles&&!Fe(i.roles,d.roles))await j(o,"role.changed",{userId:n,roles:i.roles,previous:d.roles},i.actor??null);if(i.status==="disabled")await F(o,a,z,t("user_id",n));return await D(o,a,n)});return c.deliver(),r},async remove(n,i={}){await y(async(r,o)=>{let a=await D(r,o,n);if(!a)throw e.notFound(`No user with id "${n}"`);for(let d of[z,q,he,V])await F(r,o,d,t("user_id",n));await F(r,o,A,t("id",n)),await j(r,"user.removed",{userId:n,email:a.email},i.actor??null)}),c.deliver()},async setPassword(n,i){G(i),await y(async(r,o)=>{let a=await Pe(i);if(await S(r,o,A,t("id",n),{password_hash:a,updated_at:new Date})===0)throw e.notFound(`No user with id "${n}"`);await F(r,o,z,t("user_id",n))})},async invite(n){await oe(n.roles??[]);let i=await y(async(r,o)=>{let a=ce(n.email),d=await K(r,o,a);if(d&&d.user.status==="active")throw e.conflict(`${a} is already an active user`);let h=d?.user??await ie(r,o,{email:a,...n.name?{name:n.name}:{},roles:n.roles??(f.rbac?.defaultRole?[f.rbac.defaultRole]:[]),status:"invited"}),_=await Y(r,o,{type:"invite",ttlMs:U("invite",C()?.invites?.expiresIn),userId:h.id,email:a});return await j(r,"user.invited",{userId:h.id,email:a,roles:h.roles},n.actor??null),{user:h,token:_.token,expiresAt:_.expiresAt.toISOString(),userId:h.id,email:a}});return c.deliver(),i},async acceptInvite(n){let i=await y(async(r,o)=>{let a=await ee(r,o,"invite",n.token),d=await D(r,o,String(a.user_id));if(!d)throw e.unauthorized("This invitation is no longer valid");let h={status:"active",updated_at:new Date};if(n.password!==void 0)G(n.password),h.password_hash=await Pe(n.password);if(n.name!==void 0)h.name=n.name;await S(r,o,A,t("id",d.id),h);let _={...d,status:"active",...n.name===void 0?{}:{name:n.name}};return await j(r,"user.joined",{userId:d.id,email:d.email}),te(r,o,_,n)});return c.deliver(),i}},setup:{async required(){if(Se()===null)return!1;if(T)return!1;let n=await Q.users.count();if(n>0)T=!0;return n===0},async claim(n){let i=Se();if(i===null)throw e.forbidden("This deployment does not accept a first account over HTTP; use heyo-cms create-admin");try{await oe(i)}catch(o){if(o instanceof e&&o.code==="validation_failed")throw e.validation(`The first account would be given the role ${i.map((a)=>`"${a}"`).join(", ")}, which rbac.roles does not define; set admin.auth.firstUser.roles`);throw o}G(n.password);let r=await y(async(o,a)=>{let d=await a.query(o,{table:A,count:!0});if(Number(d[0]?.count??0)>0)throw e.conflict("This CMS already has an account; sign in instead");let h=await ie(o,a,{email:n.email,password:n.password,roles:i,status:"active",...n.name===void 0?{}:{name:n.name}});return await j(o,"user.joined",{userId:h.id,email:h.email,first:!0}),te(o,a,h,n)});return T=!0,c.deliver(),r}},sessions:{async verify(n){return y(async(i,r)=>{let o=await O(i,r,z,t("token_hash",await re(n)));if(!o||ye(o.expires_at))return null;let a=await D(i,r,String(o.user_id));if(!a||a.status!=="active")return null;return{status:"signed-in",token:n,expiresAt:l(o.expires_at)??"",session:ge(o),user:a,actor:await Z(a)}})},async list(n){return(await y((r,o)=>o.query(r,{table:z,where:t("user_id",n),orderBy:[m("created_at","desc")]}))).map(ge)},async revoke(n){let i=await re(n);return await y((o,a)=>F(o,a,z,t("token_hash",i)))>0},async revokeById(n){return await y((r,o)=>F(r,o,z,t("id",n)))>0},async revokeAll(n){return y((i,r)=>F(i,r,z,t("user_id",n)))},async cleanup(){let n=new Date;return y(async(i,r)=>{let o=await F(i,r,z,H("expires_at",n));return await F(i,r,q,H("expires_at",n)),o})}},password:{async signIn(n){E("password");let i=await y(async(r,o)=>{let a=await K(r,o,n.email),d=a?a.row.password_hash:await k(),h=await pn(n.password,d);if(!a||!h)throw e.unauthorized("Invalid email or password");if(se(a.user),a.user.status==="invited")throw e.forbidden("This invitation has not been accepted yet");return ne(r,o,a.user,n)});return c.deliver(),i},async requestReset(n){return E("password"),y(async(i,r)=>{let o=await K(i,r,n.email);if(!o||o.user.status==="disabled")return null;let a=await Y(i,r,{type:"password-reset",ttlMs:U("passwordReset",C()?.passwordReset?.expiresIn),userId:o.user.id,email:o.user.email});return{token:a.token,expiresAt:a.expiresAt.toISOString(),userId:o.user.id,email:o.user.email}})},async reset(n){return E("password"),G(n.password),y(async(i,r)=>{let o=await ee(i,r,"password-reset",n.token),a=String(o.user_id);await S(i,r,A,t("id",a),{password_hash:await Pe(n.password),status:"active",updated_at:new Date}),await F(i,r,z,t("user_id",a));let d=await D(i,r,a);if(!d)throw e.unauthorized("This link is no longer valid");return d})}},magicLink:{async request(n){return E("magic-link"),y(async(i,r)=>{let o=await K(i,r,n.email);if(!o||o.user.status==="disabled")return null;let a=await Y(i,r,{type:"magic-link",ttlMs:U("magicLink",C()?.magicLink?.expiresIn),userId:o.user.id,email:o.user.email});return{token:a.token,expiresAt:a.expiresAt.toISOString(),userId:o.user.id,email:o.user.email}})},async verify(n){E("magic-link");let i=await y(async(r,o)=>{let a=await ee(r,o,"magic-link",n.token),d=await D(r,o,String(a.user_id));if(!d)throw e.unauthorized("This link is no longer valid");if(se(d),d.status==="invited")return await S(r,o,A,t("id",d.id),{status:"active",updated_at:new Date}),await j(r,"user.joined",{userId:d.id,email:d.email}),ne(r,o,{...d,status:"active"},n);return ne(r,o,d,n)});return c.deliver(),i}},oauth:{async authorize(n){let i=await ke(n.provider),r=we(24),o=we(),a=i.pkce?(await Oe(o)).challenge:void 0;return await y((d,h)=>Y(d,h,{type:"oauth",ttlMs:U("oauth",void 0),token:r,data:{provider:i.id,redirectUri:n.redirectUri,verifier:o,redirectTo:n.redirectTo??null}})),{url:Ue({endpoints:i.endpoints,clientId:i.clientId,redirectUri:n.redirectUri,scope:i.scope,state:r,...a===void 0?{}:{codeChallenge:a}}),state:r}},async callback(n){let i=await ke(n.provider),r=await y(async(o,a)=>{let d=await ee(o,a,"oauth",n.state),h=u(d.data);if(h.provider!==i.id)throw e.unauthorized("This sign-in request does not match");if(h.redirectUri!==n.redirectUri)throw e.unauthorized("The redirect URI does not match");let _=await xe({endpoints:i.endpoints,clientId:i.clientId,clientSecret:i.clientSecret,code:n.code,redirectUri:n.redirectUri,...i.pkce&&typeof h.verifier==="string"?{codeVerifier:h.verifier}:{},fetchImpl:p}),P=await i.profile(_,p),I=await ze(o,a,i,P);return se(I),{...await ne(o,a,I,n),redirectTo:typeof h.redirectTo==="string"?h.redirectTo:null}});return c.deliver(),r}},twoFactor:{async begin(n){let i=Un();return y(async(r,o)=>{let a=await D(r,o,n);if(!a)throw e.notFound(`No user with id "${n}"`);if(a.twoFactorEnabled)throw e.conflict("Disable the existing authenticator before enrolling another.");return await S(r,o,A,t("id",n),{two_factor_secret:i,updated_at:new Date}),{secret:i,uri:Jn({secret:i,account:a.email,issuer:f.admin.title??"Heyo CMS"})}})},async enable(n){return y(async(i,r)=>{let o=await O(i,r,A,t("id",n.userId));if(!o)throw e.notFound(`No user with id "${n.userId}"`);let a=o.two_factor_secret;if(!a)throw e.validation("Start the setup before enabling it");if(!await cn(a,n.code))throw e.unauthorized("That code is not valid");return await S(i,r,A,t("id",n.userId),{two_factor_enabled:!0,updated_at:new Date}),{...W(o),twoFactorEnabled:!0}})},async disable(n){return y(async(i,r)=>{if(await S(i,r,A,t("id",n),{two_factor_enabled:!1,two_factor_secret:null,updated_at:new Date})===0)throw e.notFound(`No user with id "${n}"`);return await D(i,r,n)})},async complete(n){let i=await y(async(r,o)=>{let a=await _e(r,o,"two-factor",n.challenge),d=await O(r,o,A,t("id",String(a.user_id)));if(!d)throw e.unauthorized("This challenge is no longer valid");if(!await cn(d.two_factor_secret,n.code)){let P=a;for(let I=0;I<$e;I+=1){let L=u(P.data).attempts,Ie=typeof L==="number"?L:null,Re=Number(Ie??0)+1;if(await S(r,o,q,s(t("id",String(P.id)),t("consumed_at",null),t("data.attempts",Ie)),{data:{...u(P.data),attempts:Re},...Re>=$e?{consumed_at:new Date}:{}})===1)break;let me=await O(r,o,q,t("id",String(P.id)));if(!me||me.consumed_at!==null)break;P=me}return null}await ve(r,o,a);let _=W(d);return se(_),te(r,o,_,n)});if(i===null)throw e.unauthorized("That code is not valid");return c.deliver(),i}},apiKeys:{async create(n){let i=C()?.apiKeys;if(!i?.enabled)throw new e("API keys are not enabled; set admin.auth.apiKeys.enabled",{status:400,code:"method_not_enabled"});let r=n.scopes??i.scopes??["read"],o=i.scopes;if(o){let P=r.filter((I)=>!o.includes(I));if(P.length>0)throw e.validation(`Scope ${P.map((I)=>`"${I}"`).join(", ")} is not in admin.auth.apiKeys.scopes`)}let a=`${dn}${we()}`,d=n.expiresIn??i.expiresIn,h=d?new Date(Date.now()+w(d)):null,_=await y(async(P,I)=>{let L=await B(P,I,V,{id:b("key"),name:n.name,user_id:n.userId??null,key_hash:await re(a),prefix:a.slice(0,dn.length+6),scopes:r,last_used_at:null,expires_at:h,revoked_at:null,created_at:new Date});return await j(P,"apikey.created",{id:String(L.id),name:n.name,scopes:r,userId:n.userId??null},n.actor??null),Ee(L)});return c.deliver(),{..._,key:a}},async list(n={}){return(await y((r,o)=>o.query(r,{table:V,...n.userId?{where:t("user_id",n.userId)}:{},orderBy:[m("created_at","desc")]}))).map(Ee)},async revoke(n,i={}){let r=await y(async(o,a)=>{let d=await S(o,a,V,s(t("id",n),t("revoked_at",null)),{revoked_at:new Date});if(d>0)await j(o,"apikey.revoked",{id:n},i.actor??null);return d>0});return c.deliver(),r},async verify(n){return y(async(i,r)=>{let o=await O(i,r,V,t("key_hash",await re(n)));if(!o)return null;if(o.revoked_at!==null)return null;if(o.expires_at!==null&&ye(o.expires_at))return null;let a=J(o.scopes),d=Et(a),h=[],_=d,P=String(o.id);if(o.user_id!==null&&o.user_id!==void 0){let I=await D(i,r,String(o.user_id));if(!I||I.status!=="active")return null;let L=await Z(I);h=L.roles,_=jt(L.permissions,d),P=I.id}return await S(i,r,V,t("id",String(o.id)),{last_used_at:new Date}),{id:P,source:"api-key",roles:h,permissions:_}})}},roles:{async list(){let n=Object.entries(f.rbac?.roles??{}).map(([a,d])=>({name:a,label:null,permissions:d,source:"config"}));if(f.rbac?.customRoles!==!0)return n;let i=await y((a,d)=>d.query(a,{table:N,orderBy:[m("name")]})),r=new Set(n.map((a)=>a.name)),o=i.filter((a)=>!r.has(String(a.name))).map((a)=>({name:String(a.name),label:a.label??null,permissions:J(a.permissions),source:"database"}));return[...n,...o].sort((a,d)=>a.name.localeCompare(d.name))},async create(n){if(de(),Le(n.name),f.rbac?.roles[n.name])throw e.conflict(`"${n.name}" is defined in the configuration; change it there`);let i=await y(async(r,o)=>{if(await O(r,o,N,t("name",n.name)))throw e.conflict(`The role "${n.name}" already exists`);return B(r,o,N,{id:b("rol"),name:n.name,label:n.label??null,permissions:n.permissions,created_at:new Date,updated_at:new Date})});return v=void 0,{name:String(i.name),label:i.label??null,permissions:J(i.permissions),source:"database"}},async update(n,i){de();let r=await y(async(o,a)=>{let d={updated_at:new Date};if(i.permissions)d.permissions=i.permissions;if(i.label!==void 0)d.label=i.label;if(await S(o,a,N,t("name",n),d)===0)throw e.notFound(`No role named "${n}"`);return O(o,a,N,t("name",n))});return v=void 0,{name:n,label:r?.label??null,permissions:J(r?.permissions),source:"database"}},async remove(n){de();let i=await y((r,o)=>F(r,o,N,t("name",n)));return v=void 0,i>0},async permissionsFor(n){return rt(n,await le())}}};function de(){if(f.rbac?.customRoles!==!0)throw new e("Roles are defined in the configuration; set rbac.customRoles to manage them in the panel",{status:400,code:"custom_roles_disabled"})}function Le(n){if(!He.test(n))throw e.validation(`"${n}" is not a role name; use lowercase letters, digits, dashes and underscores`)}return Q}function W(c){return{id:String(c.id),email:String(c.email),name:c.name??null,status:c.status??"active",roles:J(c.roles),avatarUrl:c.avatar_url??null,locale:c.locale??null,twoFactorEnabled:c.two_factor_enabled===!0,lastLoginAt:l(c.last_login_at),createdAt:l(c.created_at)??"",updatedAt:l(c.updated_at)??""}}function ge(c){return{id:String(c.id),userId:String(c.user_id),expiresAt:l(c.expires_at)??"",createdAt:l(c.created_at)??"",ip:c.ip??null,userAgent:c.user_agent??null}}function Ee(c){return{id:String(c.id),name:String(c.name),prefix:String(c.prefix),userId:c.user_id??null,scopes:J(c.scopes),lastUsedAt:l(c.last_used_at),expiresAt:l(c.expires_at),revokedAt:l(c.revoked_at),createdAt:l(c.created_at)??""}}function J(c){if(!Array.isArray(c))return[];return c.filter((f)=>typeof f==="string")}function ye(c){if(c===null||c===void 0)return!1;return(c instanceof Date?c:new Date(String(c))).getTime()<=Date.now()}function ce(c){let f=c.trim().toLowerCase();if(!Ke.test(f))throw e.validation(`"${c}" is not an email address`);return f}function Fe(c,f){if(c.length!==f.length)return!1;let p=[...f].sort();return[...c].sort().every((g,k)=>g===p[k])}function We(c,f){let p=c.headers.get("cookie");if(!p)return null;for(let g of p.split(";")){let k=g.indexOf("=");if(k===-1)continue;if(g.slice(0,k).trim()!==f)continue;return decodeURIComponent(g.slice(k+1).trim())}return null}function ue(c){return globalThis.process?.env?.[c]}
|
|
2
|
+
export{Nn,$t,Un,Jn,Qo,cn,be,dn,un};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
export{
|
|
1
|
+
var Ae="x-heyo-signature";async function ke(e,n,t=Math.floor(Date.now()/1000)){let o=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,new TextEncoder().encode(`${t}.${e}`));return`t=${t},v1=${u(new Uint8Array(a))}`}async function Cn(e){let n=new Map(e.header.split(",").map((r)=>{let[l,d]=r.split("=");return[l?.trim()??"",d?.trim()??""]})),t=Number(n.get("t")),o=n.get("v1");if(!Number.isFinite(t)||!o)return!1;let a=e.now??Math.floor(Date.now()/1000),c=e.toleranceSeconds??300;if(Math.abs(a-t)>c)return!1;let s=(await ke(e.body,e.secret,t)).split("v1=")[1]??"";if(s.length!==o.length)return!1;let i=0;for(let r=0;r<s.length;r+=1)i|=s.charCodeAt(r)^o.charCodeAt(r);return i===0}function u(e){let n="";for(let t of e)n+=t.toString(16).padStart(2,"0");return n}
|
|
2
|
+
export{Ae,ke,Cn};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ce,Oe}from"./index-vzhxn50e.js";import{z}from"./index-761dec5z.js";import{e,n}from"./index-x72d1hzh.js";class S{columns=new Map;documentColumns=new Map;constructor(t){if(t)this.use(t)}use(t){this.columns.clear(),this.documentColumns.clear();for(let r of t.tables)if(this.columns.set(r.name,new Map(r.columns.map((i)=>[i.name,i.type]))),r.documentColumn)this.documentColumns.set(r.name,r.documentColumn)}columnType(t,r){return this.columns.get(t)?.get(r)}documentColumn(t){return this.documentColumns.get(t)}tableColumns(t){return[...this.columns.get(t)?.keys()??[]]}knows(t){return this.columns.has(t)}}class E{dialect;catalog;constructor(t,r){this.dialect=t;this.catalog=r}compileQuery(t){let r=[],i=this.dialect.quote(t.table),a=`SELECT ${t.count?"COUNT(*) AS count":this.compileSelect(t)} FROM ${i}`;if(t.where)a+=` WHERE ${this.compileWhere(t.table,t.where,r)}`;if(!t.count&&t.orderBy&&t.orderBy.length>0){let o=t.orderBy.map((c)=>{let u=this.resolve(t.table,c.path),l=c.direction==="desc"?"DESC":"ASC";return`${this.expression(u)} ${l}`}).join(", ");a+=` ORDER BY ${o}`}if(!t.count&&t.limit!==void 0)a+=` LIMIT ${b(t.limit)}`;if(!t.count&&t.offset!==void 0)a+=` OFFSET ${b(t.offset)}`;return{text:a,values:r}}compileMutation(t){let r=[],i=this.dialect.quote(t.table);if(t.kind==="insert"){let o=Object.entries(t.values);if(o.length===0)throw new e("An insert needs at least one column.",{code:"empty_insert"});let c=o.map(([m])=>this.dialect.quote(m)).join(", "),u=o.map(([m,g])=>(r.push(this.encodeColumn(t.table,m,g)),this.dialect.placeholder(r.length))).join(", "),l=t.returning===!1?"":" RETURNING *";return{text:`INSERT INTO ${i} (${c}) VALUES (${u})${l}`,values:r}}if(t.kind==="update"){let o=Object.entries(t.set);if(o.length===0)throw new e("An update needs at least one column.",{code:"empty_update"});let c=o.map(([m,g])=>(r.push(this.encodeColumn(t.table,m,g)),`${this.dialect.quote(m)} = ${this.dialect.placeholder(r.length)}`)).join(", "),u=this.compileWhere(t.table,t.where,r),l=t.returning===!1?"":" RETURNING *";return{text:`UPDATE ${i} SET ${c} WHERE ${u}${l}`,values:r}}let s=this.compileWhere(t.table,t.where,r),a=t.returning===!0?" RETURNING *":"";return{text:`DELETE FROM ${i} WHERE ${s}${a}`,values:r}}decodeRow(t,r){let i={};for(let[s,a]of Object.entries(r)){let o=this.catalog.columnType(t,s);i[s]=o===void 0?a:this.dialect.decode(a,o)}return i}compileSelect(t){if(!t.select||t.select.length===0)return"*";return t.select.map((r)=>{let i=this.resolve(t.table,r);if(i.path.length===0)return this.dialect.quote(r);return`${this.expression(i)} AS "${r.replaceAll('"',"")}"`}).join(", ")}compileWhere(t,r,i){if(r.kind==="and"||r.kind==="or"){if(r.conditions.length===0)return r.kind==="and"?"1 = 1":"1 = 0";return`(${r.conditions.map((o)=>this.compileWhere(t,o,i)).join(r.kind==="and"?" AND ":" OR ")})`}if(r.kind==="not")return`NOT (${this.compileWhere(t,r.condition,i)})`;let s=this.resolve(t,r.path);return this.compileComparison(s,r.operator,r.value,i)}comparisonExpression(t,r){if(t.path.length===0)return this.dialect.quote(t.column);return this.dialect.jsonExtract(t.column,t.path,r)}compileComparison(t,r,i,s){let a=Array.isArray(i)?i[0]:i,o=O(t,a??null),c=this.comparisonExpression(t,o),u=(l)=>(s.push(this.dialect.encode(l,o)),this.dialect.placeholder(s.length));switch(r){case"eq":case"ne":{if(i===null)return`${c} IS ${r==="eq"?"":"NOT "}NULL`;return`${c} ${r==="eq"?"=":"<>"} ${u(i)}`}case"gt":case"gte":case"lt":case"lte":{let l={gt:">",gte:">=",lt:"<",lte:"<="}[r];return`${c} ${l} ${u(i)}`}case"in":case"nin":{let l=Array.isArray(i)?i:[i];if(l.length===0)return r==="in"?"1 = 0":"1 = 1";let m=l.map((g)=>u(g)).join(", ");return`${c} ${r==="in"?"IN":"NOT IN"} (${m})`}case"like":case"ilike":{let l=this.dialect.likeOperator(r==="ilike");return`${c} ${l} ${u(i)}`}case"contains":{s.push(String(i));let l=this.dialect.placeholder(s.length);return this.dialect.jsonArrayMembership(t.column,t.path,l)}case"exists":return`${c} IS ${i===!1?"":"NOT "}NULL`}}expression(t){if(t.path.length===0)return this.dialect.quote(t.column);return this.dialect.jsonExtract(t.column,t.path,t.type)}resolve(t,r){let i=r.split("."),s=i[0],a=this.catalog.columnType(t,s);if(a!==void 0&&i.length===1)return{column:s,path:[],type:a};if(a!==void 0)return{column:s,path:i.slice(1),type:"text"};let o=this.catalog.documentColumn(t);if(!o)throw new e(`Unknown column ${t}.${r}`,{status:400,code:"unknown_column"});return{column:o,path:i,type:"text"}}encodeColumn(t,r,i){let s=this.catalog.columnType(t,r);if(s===void 0)throw new e(`Unknown column ${t}.${r}`,{status:400,code:"unknown_column"});return this.dialect.encode(i,s)}}function O(t,r){if(t.path.length===0)return t.type;if(r instanceof Date)return"timestamp";if(typeof r==="number")return"real";if(typeof r==="boolean")return"boolean";return"text"}function b(t){if(!Number.isInteger(t)||t<0)throw new e(`Expected a non-negative integer, received ${t}`,{code:"invalid_pagination"});return t}class T{dialect;target;constructor(t,r){this.dialect=t;this.target=r}render(t){return`${t.flatMap((i)=>{let s=this.renderStep(i);return[`-- ${Oe(i)}`,...s]}).join(`
|
|
2
2
|
`)}
|
|
3
3
|
`}renderStep(t){switch(t.kind){case"create_table":return[this.createTable(t.table)];case"drop_table":return[`DROP TABLE IF EXISTS ${this.q(t.table)};`];case"add_column":return this.addColumn(t.table,t.column);case"drop_column":return[`ALTER TABLE ${this.q(t.table)} DROP COLUMN ${this.q(t.column)};`];case"alter_column":return this.alterColumn(t.table,t.column);case"create_index":return[this.createIndex(t.index)];case"drop_index":return[`DROP INDEX IF EXISTS ${this.q(t.index)};`];case"set_document_field":return[this.setDocumentField(t.table,t.collection,t.documentColumn,t.path,t.value)];case"unset_document_field":return[this.unsetDocumentField(t.table,t.collection,t.documentColumn,t.path)]}}createTable(t){let r=t.columns.map((i)=>this.columnClause(i));if(t.primaryKey.length>0)r.push(`PRIMARY KEY (${t.primaryKey.map((i)=>this.q(i)).join(", ")})`);for(let i of t.columns){if(!i.references)continue;r.push(`FOREIGN KEY (${this.q(i.name)}) REFERENCES ${this.q(i.references.table)} (${this.q(i.references.column)})${I(i.references.onDelete)}`)}return`CREATE TABLE IF NOT EXISTS ${this.q(t.name)} (
|
|
4
4
|
${r.join(`,
|
|
5
5
|
`)}
|
|
6
|
-
);`}columnClause(t){let r=[this.q(t.name),this.dialect.columnType(t)];if(!t.nullable)r.push("NOT NULL");if(t.default!==void 0)r.push(`DEFAULT ${this.literal(t)}`);return r.join(" ")}addColumn(t,r){if(!r.nullable&&r.default===void 0)throw new n(`${t}.${r.name}`,"a required column needs a default before it can be added to an existing table");return[`ALTER TABLE ${this.q(t)} ADD COLUMN ${this.columnClause(r)};`]}alterColumn(t,r){if(this.dialect.supportsAlterColumn){let o=this.q(r.name),c=[`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} TYPE ${this.dialect.columnType(r)} USING ${o}::${this.dialect.columnType(r)};`,`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} ${r.nullable?"DROP NOT NULL":"SET NOT NULL"};`];return c.push(r.default===void 0?`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} DROP DEFAULT;`:`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} SET DEFAULT ${this.literal(r)};`),c}let i=this.target().tables.find((o)=>o.name===t);if(!i)throw new n(t,"cannot rebuild a table that is not in the target schema");let s=`${t}__rebuild`,a=i.columns.map((o)=>this.q(o.name)).join(", ");return[this.createTable({...i,name:s}),`INSERT INTO ${this.q(s)} (${a}) SELECT ${a} FROM ${this.q(t)};`,`DROP TABLE ${this.q(t)};`,`ALTER TABLE ${this.q(s)} RENAME TO ${this.q(t)};`,...i.indexes.map((o)=>this.createIndex(o))]}createIndex(t){let r=t.targets.map((a)=>a.kind==="column"?this.q(a.column):`(${this.dialect.jsonExtract(a.column,a.path,a.type)})`).join(", "),i=t.unique?"UNIQUE ":"",s=t.where?` WHERE ${this.q(t.where.column)} = ${d(t.where.equals)}`:"";return`CREATE ${i}INDEX IF NOT EXISTS ${this.q(t.name)} ON ${this.q(t.table)} (${r})${s};`}setDocumentField(t,r,i,s,a){let o=this.q(i),c=d(JSON.stringify(a)),u=`WHERE "collection" = ${d(r)}`;if(this.dialect.id==="postgres"){let m=`'{${s.join(",")}}'`;return`UPDATE ${this.q(t)} SET ${o} = jsonb_set(${o}, ${m}, ${c}::jsonb, true) ${u} AND ${o} #> ${m} IS NULL;`}let l=d(`$.${s.join(".")}`);return`UPDATE ${this.q(t)} SET ${o} = json_set(${o}, ${l}, json(${c})) ${u} AND json_extract(${o}, ${l}) IS NULL;`}unsetDocumentField(t,r,i,s){let a=this.q(i),o=`WHERE "collection" = ${d(r)}`;if(this.dialect.id==="postgres")return`UPDATE ${this.q(t)} SET ${a} = ${a} #- '{${s.join(",")}}' ${o};`;return`UPDATE ${this.q(t)} SET ${a} = json_remove(${a}, ${d(`$.${s.join(".")}`)}) ${o};`}literal(t){let r=t.default;if(r===null||r===void 0)return"NULL";if(typeof r==="number")return String(r);if(typeof r==="boolean")return this.dialect.id==="postgres"?String(r):r?"1":"0";return d(String(r))}q(t){return this.dialect.quote(t)}}function I(t){switch(t){case"cascade":return" ON DELETE CASCADE";case"set-null":return" ON DELETE SET NULL";case"restrict":return" ON DELETE RESTRICT";default:return""}}function d(t){return`'${t.replaceAll("'","''")}'`}function
|
|
6
|
+
);`}columnClause(t){let r=[this.q(t.name),this.dialect.columnType(t)];if(!t.nullable)r.push("NOT NULL");if(t.default!==void 0)r.push(`DEFAULT ${this.literal(t)}`);return r.join(" ")}addColumn(t,r){if(!r.nullable&&r.default===void 0)throw new n(`${t}.${r.name}`,"a required column needs a default before it can be added to an existing table");return[`ALTER TABLE ${this.q(t)} ADD COLUMN ${this.columnClause(r)};`]}alterColumn(t,r){if(this.dialect.supportsAlterColumn){let o=this.q(r.name),c=[`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} TYPE ${this.dialect.columnType(r)} USING ${o}::${this.dialect.columnType(r)};`,`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} ${r.nullable?"DROP NOT NULL":"SET NOT NULL"};`];return c.push(r.default===void 0?`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} DROP DEFAULT;`:`ALTER TABLE ${this.q(t)} ALTER COLUMN ${o} SET DEFAULT ${this.literal(r)};`),c}let i=this.target().tables.find((o)=>o.name===t);if(!i)throw new n(t,"cannot rebuild a table that is not in the target schema");let s=`${t}__rebuild`,a=i.columns.map((o)=>this.q(o.name)).join(", ");return[this.createTable({...i,name:s}),`INSERT INTO ${this.q(s)} (${a}) SELECT ${a} FROM ${this.q(t)};`,`DROP TABLE ${this.q(t)};`,`ALTER TABLE ${this.q(s)} RENAME TO ${this.q(t)};`,...i.indexes.map((o)=>this.createIndex(o))]}createIndex(t){let r=t.targets.map((a)=>a.kind==="column"?this.q(a.column):`(${this.dialect.jsonExtract(a.column,a.path,a.type)})`).join(", "),i=t.unique?"UNIQUE ":"",s=t.where?` WHERE ${this.q(t.where.column)} = ${d(t.where.equals)}`:"";return`CREATE ${i}INDEX IF NOT EXISTS ${this.q(t.name)} ON ${this.q(t.table)} (${r})${s};`}setDocumentField(t,r,i,s,a){let o=this.q(i),c=d(JSON.stringify(a)),u=`WHERE "collection" = ${d(r)}`;if(this.dialect.id==="postgres"){let m=`'{${s.join(",")}}'`;return`UPDATE ${this.q(t)} SET ${o} = jsonb_set(${o}, ${m}, ${c}::jsonb, true) ${u} AND ${o} #> ${m} IS NULL;`}let l=d(`$.${s.join(".")}`);return`UPDATE ${this.q(t)} SET ${o} = json_set(${o}, ${l}, json(${c})) ${u} AND json_extract(${o}, ${l}) IS NULL;`}unsetDocumentField(t,r,i,s){let a=this.q(i),o=`WHERE "collection" = ${d(r)}`;if(this.dialect.id==="postgres")return`UPDATE ${this.q(t)} SET ${a} = ${a} #- '{${s.join(",")}}' ${o};`;return`UPDATE ${this.q(t)} SET ${a} = json_remove(${a}, ${d(`$.${s.join(".")}`)}) ${o};`}literal(t){let r=t.default;if(r===null||r===void 0)return"NULL";if(typeof r==="number")return String(r);if(typeof r==="boolean")return this.dialect.id==="postgres"?String(r):r?"1":"0";return d(String(r))}q(t){return this.dialect.quote(t)}}function I(t){switch(t){case"cascade":return" ON DELETE CASCADE";case"set-null":return" ON DELETE SET NULL";case"restrict":return" ON DELETE RESTRICT";default:return""}}function d(t){return`'${t.replaceAll("'","''")}'`}function Mt(t){let r=[],i="",s=!1;for(let a=0;a<t.length;a+=1){let o=t[a];if(o==="'"){if(s&&t[a+1]==="'"){i+="''",a+=1;continue}s=!s,i+=o;continue}if(o==="-"&&!s&&t[a+1]==="-"){let c=t.indexOf(`
|
|
7
7
|
`,a);a=c===-1?t.length:c;continue}if(o===";"&&!s){if(i.trim())r.push(i.trim());i="";continue}i+=o}if(i.trim())r.push(i.trim());return r}async function R(t){let r=await t.all(`SELECT table_name, column_name, data_type, is_nullable, column_default
|
|
8
8
|
FROM information_schema.columns
|
|
9
9
|
WHERE table_schema = current_schema()
|
|
@@ -17,10 +17,10 @@ import{Ae,xe}from"./index-gpwcmmvr.js";import{N}from"./index-y5mwknr9.js";import
|
|
|
17
17
|
AND kcu.table_schema = tc.table_schema
|
|
18
18
|
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
19
19
|
AND tc.table_schema = current_schema()
|
|
20
|
-
ORDER BY tc.table_name, kcu.ordinal_position`,[]),a=new Map;for(let o of r)A(a,String(o.table_name)).columns.push({name:String(o.column_name),type:
|
|
21
|
-
${this.renderer.render(t)}`,summary:t.map(
|
|
20
|
+
ORDER BY tc.table_name, kcu.ordinal_position`,[]),a=new Map;for(let o of r)A(a,String(o.table_name)).columns.push({name:String(o.column_name),type:j(String(o.data_type)),nullable:o.is_nullable==="YES",storage:"column"});for(let o of s){let c=a.get(String(o.table_name));if(c)c.primaryKey.push(String(o.column_name))}for(let o of i){let c=a.get(String(o.table_name));if(!c)continue;let u=String(o.definition);c.indexes.push({name:String(o.index_name),table:c.name,targets:[],unique:u.startsWith("CREATE UNIQUE")})}return N(a)}async function w(t){let r=await t.all("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",[]),i=new Map;for(let s of r){let a=String(s.name),o=A(i,a),c=await t.all(`PRAGMA table_info(${C(a)})`,[]);for(let l of c)if(o.columns.push({name:String(l.name),type:M(String(l.type)),nullable:Number(l.notnull)===0,storage:"column"}),Number(l.pk)>0)o.primaryKey.push(String(l.name));let u=await t.all(`PRAGMA index_list(${C(a)})`,[]);for(let l of u){let m=String(l.name);if(m.startsWith("sqlite_autoindex"))continue;o.indexes.push({name:m,table:a,targets:[],unique:Number(l.unique)===1})}}return N(i)}function A(t,r){let i=t.get(r);if(i)return i;let s={name:r,columns:[],primaryKey:[],indexes:[]};return t.set(r,s),s}function N(t){return{version:1,tables:[...t.values()].filter((i)=>i.name!==z).map((i)=>({...i,columns:y(i.columns),indexes:y(i.indexes)})).sort((i,s)=>i.name.localeCompare(s.name)),collections:[]}}function y(t){return[...t].sort((r,i)=>r.name.localeCompare(i.name))}function j(t){switch(t){case"integer":return"integer";case"bigint":return"bigint";case"double precision":case"numeric":case"real":return"real";case"boolean":return"boolean";case"timestamp with time zone":case"timestamp without time zone":return"timestamp";case"jsonb":case"json":return"json";case"bytea":return"blob";default:return"text"}}function M(t){let r=t.toUpperCase();if(r.includes("INT"))return"integer";if(r.includes("REAL")||r.includes("DOUB"))return"real";if(r.includes("BLOB"))return"blob";return"text"}function C(t){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Unsafe SQL identifier: ${t}`);return`"${t}"`}class h{id;real;driver;constructor(t,r,i){this.id=t;this.real=r;this.driver=i}}class ce{driver;dialect;id;capabilities;catalog=new S;compiler;renderer;schema={version:1,tables:[],collections:[]};journalReady=!1;transactionDepth=0;constructor(t,r,i={}){this.driver=t;this.dialect=r;if(this.id=t.id,this.capabilities={transactions:!0,sqlMigrations:!0,jsonQuery:!0,...i.capabilities},this.compiler=new E(r,this.catalog),this.renderer=new T(r,()=>this.schema),i.schema)this.useSchema(i.schema)}useSchema(t){this.schema=t,this.catalog.use(t)}introspect(){return this.dialect.id==="postgres"?R(this.driver):w(this.driver)}plan(t,r){return Ce(t,r)}render(t,r){return{id:r,extension:"sql",content:`-- ${r}
|
|
21
|
+
${this.renderer.render(t)}`,summary:t.map(Oe)}}async applyMigration(t){await this.ensureJournal();for(let r of Mt(t.content))await this.driver.exec(r)}async listAppliedMigrations(){return await this.ensureJournal(),(await this.driver.all(`SELECT id, checksum, applied_at FROM ${this.dialect.quote(z)} ORDER BY id`,[])).map((r)=>({id:String(r.id),checksum:String(r.checksum),appliedAt:new Date(String(r.applied_at))}))}async recordMigration(t,r){await this.ensureJournal(),await this.driver.run(`INSERT INTO ${this.dialect.quote(z)} (id, checksum, applied_at) VALUES (${this.dialect.placeholder(1)}, ${this.dialect.placeholder(2)}, ${this.dialect.placeholder(3)})`,[t,r,new Date().toISOString()])}async transaction(t){if(!this.capabilities.transactions)return t(new h(f(),!1,this.driver));if(this.transactionDepth>0)return t(new h(f(),!0,this.driver));if(this.driver.transaction)return this.driver.transaction((r)=>t(new h(f(),!0,r)));this.transactionDepth+=1,await this.driver.exec(this.dialect.beginTransaction??"BEGIN");try{let r=await t(new h(f(),!0,this.driver));return await this.driver.exec("COMMIT"),r}catch(r){throw await this.driver.exec("ROLLBACK"),r}finally{this.transactionDepth-=1}}async query(t,r){let i=this.compiler.compileQuery(r),s=await x(t,this.driver).all(i.text,i.values);if(r.count===!0)return[{count:Number(s[0]?.count??0)}];return s.map((a)=>this.compiler.decodeRow(r.table,a))}async mutate(t,r){let i=this.compiler.compileMutation(r),s=x(t,this.driver);if(i.text.includes(" RETURNING ")){let c=await s.all(i.text,i.values);return{rows:c.map((u)=>this.compiler.decodeRow(r.table,u)),count:c.length}}let o=await s.run(i.text,i.values);return{rows:[],count:o.rowsAffected}}async close(){await this.driver.close?.()}async ensureJournal(){if(this.journalReady)return;await this.driver.exec(`CREATE TABLE IF NOT EXISTS ${this.dialect.quote(z)} (
|
|
22
22
|
${this.dialect.quote("id")} TEXT NOT NULL PRIMARY KEY,
|
|
23
23
|
${this.dialect.quote("checksum")} TEXT NOT NULL,
|
|
24
24
|
${this.dialect.quote("applied_at")} TEXT NOT NULL
|
|
25
|
-
)`),this.journalReady=!0}}function
|
|
26
|
-
export{
|
|
25
|
+
)`),this.journalReady=!0}}function x(t,r){return t instanceof h?t.driver:r}var D=0;function f(){return D+=1,`tx_${D}`}var p=(t)=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Unsafe SQL identifier: ${t}`);return`"${t}"`};function L(t){return`$${t.map((r)=>`."${r.replaceAll('"',"\\\"")}"`).join("")}`}var k={text:"text",integer:"integer",bigint:"bigint",real:"double precision",boolean:"boolean",timestamp:"timestamptz",json:"jsonb",blob:"bytea"},Hn={id:"postgres",placeholder:(t)=>`$${t}`,quote:p,columnType:(t)=>t.array===!0?"jsonb":k[t.type],jsonExtract(t,r,i){let s=`${p(t)} #>> '{${r.map(q).join(",")}}'`;switch(i){case"integer":case"bigint":return`(${s})::bigint`;case"real":return`(${s})::double precision`;case"boolean":return`(${s})::boolean`;case"timestamp":return`(${s})::timestamptz`;default:return`(${s})`}},jsonArrayMembership(t,r,i){return`EXISTS (SELECT 1 FROM jsonb_array_elements_text(${r.length===0?p(t):`${p(t)} #> '{${r.map(q).join(",")}}'`}) AS membership(value) WHERE membership.value = ${i})`},likeOperator:(t)=>t?"ILIKE":"LIKE",encode(t,r){if(t===void 0||t===null)return null;if(r==="json")return JSON.stringify(t);if(r==="timestamp")return _(t);return t},decode(t,r){if(t===null||t===void 0)return null;if(r==="timestamp")return t instanceof Date?t:new Date(String(t));if(r==="json"&&typeof t==="string")return JSON.parse(t);if(r==="bigint"&&typeof t==="string")return Number(t);return t},supportsAlterColumn:!0};function q(t){return/[,{}"\s]/.test(t)?`"${t.replaceAll('"',"\\\"")}"`:t}var P={text:"TEXT",integer:"INTEGER",bigint:"INTEGER",real:"REAL",boolean:"INTEGER",timestamp:"INTEGER",json:"TEXT",blob:"BLOB"},st={id:"sqlite",beginTransaction:"BEGIN IMMEDIATE",placeholder:()=>"?",quote:p,columnType:(t)=>t.array===!0?"TEXT":P[t.type],jsonExtract(t,r,i){let s=`json_extract(${p(t)}, '${L(r)}')`;return i==="timestamp"?`CAST(ROUND((julianday(${s}) - 2440587.5) * 86400000) AS INTEGER)`:s},jsonArrayMembership(t,r,i){return`EXISTS (SELECT 1 FROM json_each(${r.length===0?p(t):`json_extract(${p(t)}, '${L(r)}')`}) WHERE json_each.value = ${i})`},likeOperator:()=>"LIKE",encode(t,r){if(t===void 0||t===null)return null;if(r==="json")return JSON.stringify(t);if(r==="timestamp")return _(t).getTime();if(r==="boolean")return t===!0?1:0;return t},decode(t,r){if(t===null||t===void 0)return null;if(r==="timestamp")return new Date(typeof t==="number"?t:Number(t));if(r==="boolean")return t===1||t===!0;if(r==="json"){if(typeof t!=="string")return t;return JSON.parse(t)}return t},supportsAlterColumn:!1};function _(t){if(t instanceof Date)return t;if(typeof t==="number")return new Date(t);return new Date(String(t))}
|
|
26
|
+
export{Mt,ce,Hn,st};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n}from"./index-x72d1hzh.js";var r=new Map;function
|
|
2
|
-
export{
|
|
1
|
+
import{n}from"./index-x72d1hzh.js";var r=new Map;function po(i){let t=r.get(i.name);if(t!==void 0&&t!==i)throw new n(`fields.${i.name}`,"a different field type with this name is already registered");r.set(i.name,i)}function Ko(i){return r.get(i)}function Yo(){return[...r.keys()].sort()}function O(i){return po(i),(t)=>{let e=t??{},o=i.optionsSchema?l(i.name,i.optionsSchema,e):e;if(e.admin!==void 0){for(let u of Object.keys(e.admin))if(u!=="hidden"&&u!=="placeholder")throw new n(`fields.${i.name}.admin.${u}`,"unsupported admin option; use only hidden or placeholder")}if(e.generate!==void 0&&typeof e.generate!=="function")throw new n(`fields.${i.name}.generate`,"must be a function");let d=e.required===!0;if(d&&e.admin?.hidden===!0)throw new n(`fields.${i.name}.admin.hidden`,"a hidden field cannot be required; remove required or show the field");let a=e.localized===!0,s=i.column(o);if(a&&(e.unique===!0||s.unique===!0))throw new n(`fields.${i.name}`,"a localized field cannot be unique in v1; enforce it in a hook instead");if(c(i.name,i.aiActions,e.ai),e.aiGenerate!==void 0){if(e.ai?.generate!==void 0)throw new n(`fields.${i.name}.aiGenerate`,"choose either aiGenerate or the legacy ai.generate, not both");if(!["text","textarea","richText","email","url"].includes(i.name))throw new n(`fields.${i.name}.aiGenerate`,"generation currently supports text, textarea, richText, email and url fields")}return{type:i.name,options:e,schema:f(i.schema(o),d),column:{...s,nullable:s.nullable??!d,...e.unique===void 0?{}:{unique:e.unique},...e.index===void 0?{}:{index:e.index},storage:s.storage??"document"},localized:a,required:d,...e.default===void 0?{}:{defaultValue:e.default},...e.generate===void 0?{}:{generate:e.generate},...e.aiGenerate===void 0?{}:{aiGenerate:e.aiGenerate},...e.ai===void 0?{}:{ai:e.ai},...e.access===void 0?{}:{access:e.access},...e.admin===void 0?{}:{admin:e.admin},...typeof e.relationTo==="string"?{relationTo:e.relationTo}:{}}}}function l(i,t,e){let o=t.safeParse(e);if(!o.success){let d=o.error.issues[0],a=d?.path.length?` (${d.path.join(".")})`:"";throw new n(`fields.${i}`,`${d?.message??"invalid options"}${a}`)}return o.data}function f(i,t){return t?i:i.nullable()}function c(i,t,e){if(!e||!t)return;for(let o of Object.keys(e)){let d=t.includes(o),a=typeof e[o]==="object";if(!d&&!a)throw new n(`fields.${i}.ai.${o}`,`unknown AI action; ${i} supports ${t.join(", ")}. Custom actions need an object with a prompt.`)}}
|
|
2
|
+
export{po,Ko,Yo,O};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function s(...e){return{kind:"and",conditions:e.filter(o)}}function R(...e){return{kind:"or",conditions:e.filter(o)}}function zn(e){return{kind:"not",condition:e}}function er(e,r,n){return{kind:"compare",path:e,operator:r,value:n}}function t(e,r){return{kind:"compare",path:e,operator:"eq",value:r}}function We(e,r){return{kind:"compare",path:e,operator:"ne",value:r}}function it(e,r){return{kind:"compare",path:e,operator:"gt",value:r}}function tr(e,r){return{kind:"compare",path:e,operator:"gte",value:r}}function H(e,r){return{kind:"compare",path:e,operator:"lt",value:r}}function M(e,r){return{kind:"compare",path:e,operator:"lte",value:r}}function S(e,r){return{kind:"compare",path:e,operator:"in",value:r}}function nr(e,r){return{kind:"compare",path:e,operator:"nin",value:r}}function ae(e,r,n=!1){return{kind:"compare",path:e,operator:n?"ilike":"like",value:r}}function rr(e,r){return{kind:"compare",path:e,operator:"contains",value:r}}function le(e,r=!0){return{kind:"compare",path:e,operator:"exists",value:r}}function m(e,r="asc"){return{path:e,direction:r}}function Xo(e,r){if(!e)return r;if(!r)return e;return s(e,r)}function ir(e,r){let n=Xo(e.where,r);return n===void 0?e:{...e,where:n}}function o(e){return e!==void 0}
|
|
2
|
+
export{s,R,zn,er,t,We,it,tr,H,M,S,nr,ae,rr,le,m,Xo,ir};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Y,Le,Ct,_,I}from"./index-8x2em6c8.js";import{l}from"./index-sgdnp83t.js";import{t}from"./index-6m1kjq9g.js";import{d}from"./index-9g2n7xa6.js";import{X}from"./index-hbx67b20.js";import{ie,mn}from"./index-p2cqsmvw.js";import{b}from"./index-8nzmqy0f.js";import{e}from"./index-x72d1hzh.js";var K="v1",Z=12;async function z(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 z(i),a=crypto.getRandomValues(new Uint8Array(Z)),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 j(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 z(i);try{let f=await crypto.subtle.decrypt({name:"AES-GCM",iv:mn(a)},s,mn(c));return new TextDecoder().decode(f)}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 L;async function R(){return L??=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"})}),L}async function kn(n){let{getModel:i}=await R(),r;try{r=i(n.provider,n.model)}catch{r=void 0}if(r)return r;throw await Sn(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=Rn(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 Zn(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 R();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 ee=new Set(["github-copilot","openai-codex"]);function Rn(n){if(n==="amazon-bedrock")return["aws"];if(ee.has(n))return["oauth"];return["api-key"]}async function Sn(n,i){let{getModel:r,getProviders:a}=await R();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 Qn(n){try{let{getModels:i}=await R();return i(n).map((r)=>r.id)}catch{return[]}}var Ke=async(n)=>{let{complete:i,stream:r}=await R(),{model:a,auth:c}=n;V(a.provider,c);let s=await kn(a),f={systemPrompt:n.system,messages:[{role:"user",content:[{type:"text",text:n.prompt},...(n.images??[]).map((u)=>({type:"image",data:te(u.data),mimeType:u.contentType}))],timestamp:Date.now()}]},m={...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}}:{}},g=await i(s,f,m);if(g.stopReason==="error"||g.errorMessage)throw new e(g.errorMessage??"The model returned an error.",{status:502,code:"ai_provider_error"});return{text:g.content.filter((u)=>u.type==="text").map((u)=>u.text).join(""),usage:Tn(g.usage)}};function Tn(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 te(n){let i="";for(let r of n)i+=String.fromCharCode(r);return btoa(i)}async function U(n){let i={input:0,output:0,total:0,cost:0},r=async(s)=>{if(!s.trim())return s;let f=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+=f.usage.input,i.output+=f.usage.output,i.total+=f.usage.total,i.cost+=f.usage.cost;let m=f.text.trim();if(!m)throw Error(`AI returned an empty translation for ${n.fieldName}.`);let g=s.slice(0,s.length-s.trimStart().length),o=s.slice(s.trimEnd().length);return`${g}${m}${o}`},a=async(s)=>{if(Array.isArray(s)){let m=[];for(let g of s)m.push(await a(g));return m}if(!s||typeof s!=="object")return s;let f={...s};if(s.type==="text"&&typeof s.text==="string")f.text=await r(s.text);if(s.type==="image"&&s.attrs&&typeof s.attrs==="object"&&!Array.isArray(s.attrs)){let m={...s.attrs};for(let g of["alt","title"])if(typeof m[g]==="string")m[g]=await r(m[g]);f.attrs=m}if(Array.isArray(s.content))f.content=await a(s.content);return f},c=await a(n.value);return{value:c,preview:X(c),usage:i}}var P="cms_ai_credentials";function Rt(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}".`)},f=async(o)=>{let u=c(),p=await ne(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"})},m=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}},g=async(o,u,p,y)=>{await(await n.database()).transaction((A)=>n.emit(A,[{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,A=p.fields[o.field];if(!A)throw e.notFound(`"${o.field}" is not a field of ${p.name}.`);let x=o.action==="generate"&&A.aiGenerate!==void 0?A.aiGenerate:A.ai?.[o.action],k=o.variantTranslation===!0&&o.action==="translate"&&A.localized&&["text","textarea","richText","email","url"].includes(A.type);if(x===void 0&&!k)throw e.notFound(`"${o.action}" is not configured on ${p.name}.${o.field}.`);let S=x===void 0||x===!0?{}:x,T=Y(o.action)??Ct(o.action,S.prompt??"");if(T.requiresLocalized&&!A.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:F,stored:D}=await B(n,p,o,h),N=T.requiresLocalized&&C!==h?(await B(n,p,o,C,o.variantTranslation===!0)).document:F;await _(p,{actor:y,operation:"update",locale:h,rbac:i.rbac,...D===void 0?{}:{record:D}}),I(p,{[o.field]:null},y,h);let G=oe(p,y,h),H=(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 G.has(w)}),v=S.model??u.defaultModel,W=await f(v.provider),J={action:o.action,value:N[o.field]??null,field:A,fieldName:o.field,collection:p,context:Object.fromEntries(H.map((w)=>[w,F[w]??null])),document:F,locale:h,sourceLocale:C,options:S,model:v,actor:y,loadImage:m,complete:(w)=>a({...w,model:v,auth:W}),...o.signal===void 0?{}:{signal:o.signal}},Q=Date.now();try{let w=k&&A.type==="richText"?await U(J):await T.run(J);return await g("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()-Q,...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 g("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-bjge3v8e.js");yield*u({args:o,config:i,cms:n.cms(),database:()=>n.database(),authFor:f,record:g})}()},approveAssistantPlan(o){return import("./run-bjge3v8e.js").then(({approvePlan:u})=>u({args:o,config:i,cms:n.cms(),database:()=>n.database(),record:g}))},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((A)=>y.query(A,{table:P}));for(let A of h)u.set(String(A.provider),{provider:String(A.provider),configured:!0,source:"database",type:"api-key",hint:A.hint===null||A.hint===void 0?null:String(A.hint),updatedAt:l(A.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(),A=new Date,x=await M(y,p),k=E(y);return await h.transaction(async(T)=>{let C=d(h,T);if(await C.findOne(P,t("provider",o.provider)))await C.update(P,t("provider",o.provider),{secret:x,hint:k,updated_at:A});else await C.insert(P,{id:b("aic"),provider:o.provider,auth_type:"api-key",secret:x,hint:k,created_at:A,updated_at:A});return{provider:o.provider,configured:!0,source:"database",type:"api-key",hint:k,updatedAt:A.toISOString()}})},async removeCredential(o){c();let u=await n.database();return u.transaction(async(p)=>await d(u,p).delete(P,t("provider",o.provider))>0)}}}async function ne(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(P,t("provider",i)));if(!c||typeof c.secret!=="string")return null;return j(c.secret,r)}async function B(n,i,r,a,c=!1){let s=n.cms(),f=r.actor??null,m;if(i.kind==="global"){let o=s.globals[i.name];if(o)m=await o.get({actor:f,locale:a,...c?{fallbackLocale:!1}:{}})}else if(r.id){let g=s.api[i.name],o=g?await g.findById(r.id,{actor:f,locale:a,...c?{fallbackLocale:!1}:{}}):null;if(!o)throw e.notFound(`No ${i.name} with id "${r.id}", or it is not readable.`);m=o}return{document:{...m??{},...r.document??{}},stored:m}}function oe(n,i,r){let a=new Set;for(let[c,s]of Object.entries(n.fields)){let f=s.access?.read;if(f&&!f({actor:i,locale:r}))continue;a.add(c)}return a}function xt(n,i,r){let a=n.i18n.defaultLocale,c=Object.values(n.collections).map((m)=>q(m,i,a)).filter((m)=>m!==null),s=Object.values(n.globals).map((m)=>q(m,i,a)).filter((m)=>m!==null),f={collections:c,globals:s,defaultLocale:a,locales:r,media:n.uploads!==void 0,trash:n.trash.enabled};return{...f,fingerprint:se(f)}}function q(n,i,r){if(!O(n,"read",i,r))return null;let a=[];for(let[c,s]of Object.entries(n.fields)){let f=s.access?.read;if(f&&!f({actor:i,locale:r}))continue;a.push(re(c,s,n,i,r))}return{name:n.name,slug:n.slug,label:n.label,kind:n.kind,titleField:kt(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 re(n,i,r,a,c){let s=i.options,f=Array.isArray(s.options)?s.options.map((m)=>typeof m==="string"?m:typeof m==="object"&&m!==null?String(m.value??""):"").filter((m)=>m.length>0):void 0;return{name:n,type:i.type,label:typeof s.label==="string"?s.label:n,required:i.required,localized:i.localized===!0,...f&&f.length>0?{options:f}:{},...i.relationTo===void 0?{}:{relationTo:i.relationTo},writable:At(r,n,a,c)}}function At(n,i,r,a){let c=n.fields[i];if(!c)return!1;if(c.options.readOnly===!0)return!1;try{return I(n,{[i]:null},r,a),!0}catch{return!1}}function Qt(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 kt(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 se(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{kn,Zn,Rn,Sn,Qn,Ke,Tn,xt,At,Qt,kt,Rt};
|
|
@@ -0,0 +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,2 +1,2 @@
|
|
|
1
|
-
function i(t){let e="";while(e.length<t){let o=crypto.getRandomValues(new Uint8Array(t*2));for(let r of o){if(r>=252)continue;if(e+="0123456789abcdefghijklmnopqrstuvwxyz"[r%36],e.length===t)break}}return e}function
|
|
2
|
-
export{
|
|
1
|
+
function i(t){let e="";while(e.length<t){let o=crypto.getRandomValues(new Uint8Array(t*2));for(let r of o){if(r>=252)continue;if(e+="0123456789abcdefghijklmnopqrstuvwxyz"[r%36],e.length===t)break}}return e}function b(t){let n=Date.now().toString(36).padStart(9,"0");return`${t}_${n}${i(8)}`}var f=0;function ve(t){f=(f+1)%60466175;let n=Date.now().toString(36).padStart(9,"0"),e=f.toString(36).padStart(5,"0");return`${t}_${n}${e}${i(3)}`}function bo(t){let n=0xcbf29ce484222325n,e=0x100000001b3n,o=0xffffffffffffffffn,r=new TextEncoder().encode(t);for(let c of r)n=(n^BigInt(c))*e&o;return n.toString(16).padStart(16,"0")}
|
|
2
|
+
export{b,ve,bo};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`))}}),
|
|
3
|
-
`);return u(t,r)}}),
|
|
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(`
|
|
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}}}),
|
|
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(`
|
|
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
|
-
${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:
|
|
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
|
|
13
|
-
`," ").replace(/\s{2,}/g," ").trim()}function v(t){return Math.max(64,Math.ceil(t/3)+32)}var
|
|
14
|
-
export{
|
|
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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{s,t,We,S}from"./index-6m1kjq9g.js";import{w}from"./index-rw0hze6x.js";import{b}from"./index-8nzmqy0f.js";var T="media",U="media_usages",g="mediaId";function en(e){return Object.values(e.fields).some((n)=>n.type==="media"||n.type==="richText"||n.relationTo==="media")}function tn(e,n){let i=new Map,o=(c,a,d)=>{if(!c)return;i.set(`${c}|${a}|${d}`,{mediaId:c,field:a,locale:d})};for(let[c,a]of Object.entries(e.fields)){let d=a.type==="media"||a.relationTo==="media",f=a.type==="richText";if(!d&&!f)continue;for(let[r,l]of h(n[c],a.localized)){if(d){for(let u of M(l))o(u,c,r);continue}for(let u of Qe(l))o(u,c,r)}}return[...i.values()]}async function nn(e){let{db:n,documentId:i}=e,o=await n.find(U,t("document_id",i)),c=new Map((e.references??[]).map((r)=>[`${r.mediaId}|${r.field}|${r.locale}`,r])),a=new Set,d=[];for(let r of o){let l=`${String(r.media_id)}|${String(r.field)}|${String(r.locale??"")}`;if(c.delete(l))continue;d.push(String(r.id)),a.add(String(r.media_id))}if(d.length>0)await n.delete(U,S("id",d));let f=new Set;for(let r of c.values())f.add(r.mediaId),await n.insert(U,{id:b("mus"),media_id:r.mediaId,collection:e.collection,document_id:i,field:r.field,locale:r.locale,created_at:e.now});if(!e.lifecycle)return{orphaned:[],reclaimed:[]};return{orphaned:await p(e,[...a]),reclaimed:await m(e,[...f])}}async function p(e,n){if(n.length===0)return[];if(e.retention?.orphanAfterUnreferenced===!1)return[];let i=[];for(let o of n){if((await e.db.find(U,t("media_id",o))).length>0)continue;if(await e.db.update(T,s(t("id",o),t("status","active")),{status:"orphaned",orphaned_at:e.now,purge_after:y(e.retention,e.now),updated_at:e.now})>0)i.push(o)}return i}async function m(e,n){if(n.length===0)return[];if(e.retention?.reclaimOnReference===!1)return[];let i=[];for(let o of n)if(await e.db.update(T,s(t("id",o),We("status","active")),{status:"active",orphaned_at:null,purge_after:null,purge_error:null,updated_at:e.now})>0)i.push(o);return i}function y(e,n){let i=e?.purgeAfter??"30d";if(i===!1)return null;return new Date(n.getTime()+w(i))}function h(e,n){if(!n)return[["",e]];if(typeof e!=="object"||e===null||Array.isArray(e))return[];return Object.entries(e)}function M(e){if(typeof e==="string")return e.length>0?[e]:[];if(Array.isArray(e))return e.filter((n)=>typeof n==="string");return[]}function Qe(e){let n=[],i=[e??null];while(i.length>0){let o=i.pop();if(Array.isArray(o)){i.push(...o);continue}if(typeof o!=="object"||o===null)continue;for(let[c,a]of Object.entries(o)){if(c===g&&typeof a==="string"){n.push(a);continue}if(a!==null&&typeof a==="object")i.push(a)}}return n}
|
|
2
|
+
export{T,U,en,tn,nn,Qe};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{w}from"./index-rw0hze6x.js";async function ct(o,r={}){let{drainEvents:t=!0,...s}=r,i=await o.jobs.run(s);if(t)await o.drainEvents();return i}function bn(o){let{cms:r,interval:t=60000,immediate:s=!0,onReport:i,onError:e,signal:f,...R}=o,b=typeof t==="number"?t:w(t),a=!1,p=null,u,c=async()=>{let n=ct(r,R);p=n;try{let m=await n;return i?.(m),m}finally{p=null}},l=()=>{if(a)return;u=setTimeout(()=>{c().catch((n)=>{if(e)e(n);else console.error("[heyo-cms] job sweep failed:",n)}).finally(l)},b),u.unref?.()},d={runNow:()=>c(),async stop(){if(a=!0,u)clearTimeout(u);await p?.catch(()=>{return})},get running(){return!a}};if(f?.addEventListener("abort",()=>void d.stop(),{once:!0}),s)c().catch((n)=>{if(e)e(n);else console.error("[heyo-cms] job sweep failed:",n)}).finally(l);else l();return d}function wn(o,r={}){return async(t,s,i)=>{let e=ct(o,r);i?.waitUntil?.(e),await e}}
|
|
2
|
+
export{ct,bn,wn};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var l={ß:"ss",æ:"ae",œ:"oe",ø:"o",ð:"d",þ:"th",đ:"d",ł:"l",ı:"i",ĸ:"k",ŋ:"n",ŧ:"t"},a={а:"a",б:"b",в:"v",г:"h",ґ:"g",д:"d",е:"e",є:"ie",ж:"zh",з:"z",и:"y",і:"i",ї:"i",й:"i",к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ў:"u",ф:"f",х:"kh",ц:"ts",ч:"ch",ш:"sh",щ:"shch",ь:"",ю:"iu",я:"ia",ъ:"",ы:"y",э:"e",ё:"e"},u={α:"a",β:"v",γ:"g",δ:"d",ε:"e",ζ:"z",η:"i",θ:"th",ι:"i",κ:"k",λ:"l",μ:"m",ν:"n",ξ:"x",ο:"o",π:"p",ρ:"r",σ:"s",ς:"s",τ:"t",υ:"y",φ:"f",χ:"ch",ψ:"ps",ω:"o"},Mn="^[a-z0-9]+(?:-[a-z0-9]+)*$",p=new RegExp("^[a-z0-9]+(?:-[a-z0-9]+)*$");function sn(e){return p.test(e)}function ye(e,n={}){let t=n.maxLength??96,c=Array.from(e.toLowerCase()).map((r)=>l[r]??a[r]??u[r.normalize("NFD").replace(/[\u0300-\u036f]/g,"")]??r).join("").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/['’`]/g,"").replace(/[^a-z0-9]+/g,"-"),s=g(c);if(s.length<=t)return s;let i=s.slice(0,t),o=i.lastIndexOf("-");return o>=t/2?i.slice(0,o):g(i)}function g(e){let n=0,t=e.length;while(n<t&&e.charCodeAt(n)===45)n++;while(t>n&&e.charCodeAt(t-1)===45)t--;return e.slice(n,t)}
|
|
2
|
+
export{Mn,sn,ye};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Y,me,_,on,fe,I}from"./index-8x2em6c8.js";import{_e,C,A,$e,Je,go,yo,Ie,hn,l,u}from"./index-sgdnp83t.js";import{s,R,t,We,H,M,S,le,m}from"./index-6m1kjq9g.js";import{sn,ye}from"./index-abfzb1ve.js";import{to,qe}from"./index-hpast878.js";import{V,J,Yt,Zt}from"./index-kc1j3h6z.js";import{Rt}from"./index-6w10rch0.js";import{Ae,ke}from"./index-466cwb0b.js";import{en,tn,nn}from"./index-91fa1gzf.js";import{d}from"./index-9g2n7xa6.js";import{Te}from"./index-hbx67b20.js";import{ge,et,tt}from"./index-y8kzzn94.js";import{p,Pt}from"./index-s9x07zb3.js";import{ot}from"./index-761dec5z.js";import{un}from"./index-2prbs05k.js";import{w,se}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b,ve}from"./index-8nzmqy0f.js";import{e,n}from"./index-x72d1hzh.js";var at="activity",rt=50,lt=200;function De(o){return{async list(i={}){let a=gt(i.limit),r=[];if(i.collection)r.push(t("collection",i.collection));if(i.documentId)r.push(t("document_id",i.documentId));if(i.actorId)r.push(t("actor_id",i.actorId));if(i.action)r.push(t("action",i.action));if(i.source)r.push(t("source",i.source));if(i.cursor)r.push(H("id",i.cursor));let c=await o.database(),f=await c.transaction((v)=>c.query(v,{table:at,...r.length===0?{}:{where:s(...r)},orderBy:[{path:"id",direction:"desc"}],limit:a+1})),h=f.length>a,g=f.slice(0,a),k=g.at(-1);return{entries:g.map(ct),limit:a,hasNextPage:h,cursor:h&&k?String(k.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:X(o.actor_id),actorSource:X(o.actor_source),source:X(o.source),collection:X(o.collection),documentId:X(o.document_id),locale:X(o.locale),changes:i,ip:X(o.ip),createdAt:l(o.created_at)}}function X(o){return o===null||o===void 0?null:String(o)}function gt(o){if(o===void 0)return rt;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 dt(o,i){let a={createBefore:[],createAfter:[],updateBefore:[],updateAfter:[],deleteBefore:[],deleteAfter:[]},r=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 r){let g={source:f,priority:h.priority??0};if(h.timing==="before"){if(h.operation==="create")a.createBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else if(h.operation==="update")a.updateBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else a.deleteBefore.push({...g,run:(v,D)=>h.handler(v,D)});continue}let k=async(v,D)=>{await h.handler(v,D)};if(h.operation==="create")a.createAfter.push({...g,run:k});else if(h.operation==="update")a.updateAfter.push({...g,run:(v,D)=>k(v.doc,D)});else a.deleteAfter.push({...g,run:k})}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(a,f.hooks,{source:f.plugin,priority:f.priority});return Ee(a,o.databaseHooks?.[i],{source:"config",priority:bt}),a}var bt=100;function Ee(o,i,a){if(i?.create?.before){let r=i.create.before;o.createBefore.push({...a,run:(c,f)=>r(c,f)})}if(i?.create?.after){let r=i.create.after;o.createAfter.push({...a,run:(c,f)=>r(c,f)})}if(i?.update?.before){let r=i.update.before;o.updateBefore.push({...a,run:async(c,f)=>await r(c,f)})}if(i?.update?.after){let r=i.update.after;o.updateAfter.push({...a,run:(c,f)=>r(c,f)})}if(i?.delete?.before){let r=i.delete.before;o.deleteBefore.push({...a,run:(c,f)=>r(c,f)})}if(i?.delete?.after){let r=i.delete.after;o.deleteAfter.push({...a,run:(c,f)=>r(c,f)})}}async function je(o,i,a,r){let c=i;for(let f of o){let h=await f.run(c,a);if(h===!1)return!1;if(h&&typeof h==="object"&&"data"in h)c=r(c,h.data)}return c}async function He(o,i,a){for(let r of o)await r.run(i,a)}function Wt(o){let i=new Set([...Object.keys(o.collections),...Object.keys(o.globals),...o.plugins.flatMap((r)=>(r.hooks??[]).map((c)=>c.collection)),...o.pluginHooks.map((r)=>r.collection)]),a=[];for(let r of[...i].sort()){let c=dt(o,r),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,k]of f)for(let v of k)a.push({collection:r,operation:h,timing:g,source:v.source,priority:v.priority})}return a}var wt="jobs",vt=100,Ct={name:"scheduled-changes",failureType:"document.schedule",failurePayload:(o)=>{let i=Ie(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,a)=>{let r=await o.database();return r.transaction((c)=>r.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:a}))},run:(o,i)=>o.applyScheduled(i)},St={name:"trash-purge",failureType:"trash.purge",failurePayload:(o)=>({collection:String(o.collection),documentId:String(o.id)}),due:async(o,i,a)=>{if(o.config.trash.purgeAfter===!1)return[];let r=await o.database();return r.transaction((c)=>r.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:a}))},run:(o,i)=>o.purgeExpired(i)};class ut{host;jobs=[Ct,St];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,a=o.limit??vt,r=o.only?this.jobs.filter((f)=>o.only?.includes(f.name)):this.jobs,c=[];for(let f of r){let h=await f.due(this.host,i,a+1),g=h.slice(0,a),k=0,v=0;for(let D of g)try{await f.run(this.host,D,i),k+=1}catch(j){v+=1,await this.host.recordFailure(f.failureType,f.failurePayload(D),j).catch(()=>{return})}c.push({job:f.name,processed:k,failed:v,more:h.length>a})}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((r)=>i.query(r,{table:wt,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((r)=>({id:String(r.id),type:String(r.type),payload:r.payload===null||r.payload===void 0?null:u(r.payload),error:r.error===null||r.error===void 0?null:String(r.error),attempts:Number(r.attempts??0),createdAt:l(r.created_at)}))}}var oe="outbox";class pt{queued=[];emit(o,i,a=null){this.queued.push({type:o,data:i,previous:a})}take(){return this.queued.splice(0,this.queued.length)}}class mt{adapter;dispatch;maxAttempts;backoff;leaseMs;now;constructor(o,i,a={}){this.adapter=o;this.dispatch=i;this.maxAttempts=a.maxAttempts??5,this.backoff=a.backoff??((r)=>1000*2**(r-1)),this.leaseMs=a.leaseMs??300000,this.now=a.now??(()=>new Date)}async append(o,i,a){let r=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:a.actor?{id:a.actor.id,source:a.actor.source}:null,collection:a.collection??null,document_id:a.documentId??null,status:"pending",attempts:0,available_at:r,processed_at:null,error:null,created_at:r}})}async drain(o=50){let i=await this.adapter.transaction((r)=>this.adapter.query(r,{table:oe,where:s(S("status",["pending","delivering"]),M("available_at",this.now())),orderBy:[m("created_at","asc"),m("id","asc")],limit:o})),a=0;for(let r of i){if(await this.hasPredecessor(r))continue;let c=await this.claim(r);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(kt(c)),await this.settle(c,!0),a+=1}catch(f){await this.settle(c,!1,f)}}return a}async hasPredecessor(o){if(!o.document_id)return!1;return(await this.adapter.transaction((a)=>this.adapter.query(a,{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((r)=>this.adapter.mutate(r,{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,a){let r=Number(o.attempts??0),c=r>=this.maxAttempts,f=i?{status:"delivered",attempts:r,processed_at:this.now(),error:null}:{status:c?"failed":"pending",attempts:r,available_at:new Date(this.now().getTime()+this.backoff(r)),error:a instanceof Error?a.message:String(a)};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",r)),set:f,returning:!1}))}}function kt(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 ft{options;cache=new Map;queries=0;constructor(o){this.options=o}get queryCount(){return this.queries}async expand(o,i,a){if(a<=0||o.length===0)return;let r=Object.entries(i.fields).map(([h,g])=>({name:h,target:vn(g)})).filter((h)=>Boolean(h.target));if(r.length===0)return;let c=new Map;for(let h of o)for(let g of r)for(let k of At(h[g.name])){if(this.cache.has(Z(g.target,k)))continue;let v=c.get(g.target)??new Set;v.add(k),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 r){let k=h[g.name];h[g.name]=this.substitute(g.target,k,f)}for(let[h,g]of f){let k=this.options.collections[h];if(k)await this.expand(g,k,a-1)}}async load(o,i){let a=this.options.collections[o];if(this.queries+=1,a){for(let g of i)this.cache.set(Z(o,g),null);let c;try{c=await _(a,{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",a.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(Z(o,g),null);for(let g of h){let k=A(g,a,this.options.locale);this.cache.set(Z(o,String(g.id)),fe(k,a,this.options.actor??null,this.options.locale.locale))}return}for(let c of i)this.cache.set(Z(o,c),null);if(o!=="media"&&o!=="cms_users")return;let r=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(Z(o,c),null);for(let c of r)this.cache.set(Z(o,String(c.id)),yo(c))}substitute(o,i,a){let r=(c)=>{let f=structuredClone(c),h=a.get(o)??[];return h.push(f),a.set(o,h),f};if(typeof i==="string"){let c=this.cache.get(Z(o,i));return c?r(c):i}if(Array.isArray(i))return i.map((c)=>{if(typeof c!=="string")return c;let f=this.cache.get(Z(o,c));return f?r(f):c});return i??null}}function vn(o){if(o.relationTo)return o.relationTo;return o.type==="media"?"media":void 0}function At(o){if(typeof o==="string")return o.length>0?[o]:[];if(Array.isArray(o))return o.filter((i)=>typeof i==="string");return[]}function Z(o,i){return`${o}:${i}`}var Q="slug_history",Fe=50;function he(o){let i=ee(o);if(typeof i.slugify==="function")return i.slugify;let a=i.maxLength;return(r)=>ye(r,a===void 0?{}:{maxLength:a})}function re(o){return Object.entries(o.fields).filter(([,i])=>i.type==="slug")}function ee(o){return o.options}async function be(o){let i=re(o.collection);if(i.length===0)return{input:o.input,moves:[]};let a={...o.input},r=[];for(let[c,f]of i){let h=ee(f),g=f.localized?o.locale:"",k=Ot(o.stored,c,f,o.locale),v=a[c],D=he(f),j;if(typeof v==="string"&&v.trim()!==""){if(j=D(v),j==="")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:j})}else if(v===null||v===""||v===void 0&&k===null){let F=h.from===void 0?null:Tt(o,h.from),B=F===null?"":D(F);if(B!=="")j=h.unique===!1?B:await xt({...o,field:c,locale:g,base:B});else if(v!==void 0)j=null}if(j===void 0)continue;if(a[c]=j,h.history===!0&&k!==null&&j!==null&&j!==k)r.push({field:c,locale:g,from:k,to:j})}return{input:a,moves:r}}async function we(o,i,a,r,c){for(let f of r){let h=s(t("collection",i.name),t("field",f.field),t("locale",f.locale));if(await o.delete(Q,s(h,t("document_id",a),t("slug",f.to))),await o.findOne(Q,s(h,t("slug",f.from))))continue;await o.insert(Q,{id:b("slg"),collection:i.name,field:f.field,locale:f.locale,slug:f.from,document_id:a,created_at:c})}}async function Le(o,i,a,r,c,f){await o.delete(Q,s(t("collection",i.name),t("document_id",a),t("field",r),t("locale",c),t("slug",f)))}async function Me(o,i,a){await o.delete(Q,s(t("collection",i.name),t("document_id",a)))}function _t(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}"`:"",a=await Be(o,o.slug);if(a!==null)throw e.conflict(`The slug "${o.slug}" is already used${i} by another document of ${o.collection.label} (${a}).`);let r=await Ne(o,o.slug);if(r!==null)throw e.conflict(`The slug "${o.slug}" is a previous slug of another document of ${o.collection.label} (${r})${i} and redirects there. Remove it from that document's previous slugs first.`)}async function xt(o){for(let i=1;i<=Fe;i+=1){let a=i===1?o.base:`${o.base}-${i}`;if(await Be(o,a)===null&&await Ne(o,a)===null)return a}throw e.conflict(`No free slug for "${o.base}" after ${Fe} tries; set one explicitly.`)}async function Be(o,i){let a=o.locale?`${o.field}.${o.locale}`:o.field,r=await o.db.query({table:p,where:s(t("collection",o.collection.slug),t(a,i),...o.documentId===null?[]:[We("id",o.documentId)]),limit:1});return r[0]?String(r[0].id):null}async function Ne(o,i){if(!_t(o))return null;let a=await o.db.findOne(Q,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 a?String(a.document_id):null}function Ot(o,i,a,r){if(!o)return null;let c=a.localized?u(o[i])[r]:o[i];return typeof c==="string"&&c!==""?c:null}function Tt(o,i){let a=o.collection.fields[i];if(!a)return null;let r=o.input[i],c=r!==void 0?r:a.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:a,field:r,slug:c}=o,f=a.fields[r];if(!f||!sn(c))return[];let h=f.localized,g=[],k=await i.query({table:p,where:s(t("collection",a.slug),t("deleted_at",null),h?R(...o.locales.map((j)=>t(`${r}.${j}`,c))):t(r,c)),limit:20});for(let j of k){let F=u(j.data)[r];if(!h){g.push({id:String(j.id),locale:null,current:!0});continue}for(let B of o.locales)if(u(F)[B]===c)g.push({id:String(j.id),locale:B,current:!0})}let v=[];if(ee(f).history===!0){let j=await i.find(Q,s(t("collection",a.name),t("field",r),t("slug",c))),F=await Dt(i,a,j.map((B)=>String(B.document_id)));for(let B of j){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=(j)=>j.locale===null||j.locale===o.locale?0:1;return[...g.sort((j,F)=>D(j)-D(F)),...v.sort((j,F)=>D(j)-D(F))]}async function Dt(o,i,a){if(a.length===0)return new Set;let r=await o.query({table:p,where:s(t("collection",i.slug),t("deleted_at",null),S("id",[...new Set(a)]))});return new Set(r.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(Q,s(...i))).map((r)=>({slug:String(r.slug),field:String(r.field),locale:r.locale?String(r.locale):null,createdAt:l(r.created_at)})).sort((r,c)=>(c.createdAt??"").localeCompare(r.createdAt??"")||r.slug.localeCompare(c.slug))}var jt=25,$t=200,Se=[m("deleted_at","desc"),m("id","desc")];async function zt(o){let{adapter:i,config:a,collections:r,args:c}=o,f=C(a,c),h=c.actor??null,g=Jt(c.limit),k=c.collection?[It(r,c.collection)]:Object.values(r),v=[],D=new Map;for(let O of k){let T;try{T=await _(O,{actor:h,operation:"read",locale:f.locale,rbac:a.rbac})}catch(L){if(c.collection)throw L;continue}D.set(O.slug,O),v.push(T?s(t("collection",O.slug),T):t("collection",O.slug))}if(v.length===0)return{entries:[],limit:g,hasNextPage:!1,cursor:null};let j=v.length===D.size&&v.every((O)=>O.kind==="compare")?S("collection",[...D.keys()]):R(...v),F=s(le("deleted_at",!0),j),B=await i.transaction((O)=>i.query(O,{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((O)=>{let T=D.get(String(O.collection));if(!T)return[];let L=A(O,T,f);if(on(T))fe(L,T,h,f.locale);return[{collection:T.name,id:String(O.id),deletedAt:l(O.deleted_at),purgeAfter:l(O.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 a=o[i];if(!a)throw e.notFound(`No collection named "${i}"`);return a}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 Et=25,Ft=500,Lt="activity",Mt="media_usages",Ue="cms_ai_mutations",Ke={create:"create",update:"update",trash:"delete",purge:"delete",restore:"update",schedule:"update",unschedule:"update"};class ht{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 zt({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 ut({config:this.options.config,database:()=>this.options.database(),applyScheduled:(o)=>this.applyScheduled(o),purgeExpired:(o)=>this.purgeExpired(o),recordFailure:(o,i,a)=>this.recordFailure(o,i,a)})}async drainEvents(o){return await this.delivery,(await this.outboxWorker()).drain(o)}async settle(){await this.delivery}async appendEvents(o,i,a){await(await this.outboxWorker()).append(o,i,a)}deliverSoon(){this.scheduleDelivery()}collectionApi(o){return{find:(i)=>this.find(o,i),findOne:(i)=>this.findOne(o,i),findById:(i,a)=>this.findById(o,i,a),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,a)=>this.resolveSlug(o,i,a),previousSlugs:(i)=>this.previousSlugs(o,i),addPreviousSlug:(i)=>this.changePreviousSlug(o,i,"add"),removePreviousSlug:(i)=>this.changePreviousSlug(o,i,"remove")}}slugField(o,i,a){let r=re(o).filter(([,f])=>!a||ee(f).history===!0),c=i===void 0?r[0]?.[0]:r.find(([f])=>f===i)?.[0];if(c===void 0)throw e.validation(i===void 0?`${o.name} has no slug field${a?" with history":""}`:`${o.name}.${i} is not a slug field${a?" with history":""}`);return c}async resolveSlug(o,i,a={}){let r=this.slugField(o,a.field,!1),c=C(this.options.config,a),f=await this.options.database(),h=await f.transaction((v)=>ze({db:d(f,v),collection:o,field:r,slug:i,locale:c.locale,locales:this.options.config.i18n.locales})),{field:g,...k}=a;for(let v of h){let D=await this.findById(o,v.id,k);if(!D)continue;return{id:v.id,field:r,locale:v.locale,current:v.current,document:D}}return null}async previousSlugs(o,i){let a=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[a],f=await this.options.database();return f.transaction((h)=>Ge({db:d(f,h),collection:o,documentId:i.id,field:a,...i.locale===void 0?{}:{locale:c?.localized?i.locale:null}}))}async changePreviousSlug(o,i,a){let r=this.slugField(o,i.field,!0),c=o.fields[r],f=C(this.options.config,i),h=i.actor??null,g=c.localized?f.locale:"",k=a==="add"?he(c)(i.slug):i.slug;if(k==="")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 j=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),I(o,{[r]:null},h,f.locale,B);let y=c.localized?u(u(F.data)[r])[f.locale]:u(F.data)[r];if(a==="add"){if(y===k)throw e.conflict(`"${k}" is this document's slug already, not a previous one.`);await Ce({db:j,collection:o,documentId:String(F.id),field:r,locale:g,slug:k}),await we(j,o,String(F.id),[{field:r,locale:g,from:k,to:String(y??"")}],new Date)}else await Le(j,o,String(F.id),r,g,k)}),this.previousSlugs(o,{id:i.id,field:r,...i.actor===void 0?{}:{actor:i.actor},...c.localized?{locale:f.locale}:{}})}async find(o,i={}){let a=await this.options.database(),r=C(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:r.locale,rbac:this.options.config.rbac}),h=this.scope(o,i.where,f,i.includeTrashed),g=Nt(i.orderBy),k=qt(i.limit);return a.transaction(async(v)=>{let D=await a.query(v,{table:p,where:i.cursor?s(h,J(i.cursor,g)):h,orderBy:g,limit:k+1,...i.offset===void 0?{}:{offset:i.offset}}),j=D.length>k,F=D.slice(0,k),B=F.map((W)=>A(W,o,r));await this.expand(a,v,B,o,r,i,c),this.redact(B,o,c,r);let y=null;if(i.count===!0){let W=await a.query(v,{table:p,where:h,count:!0});y=Number(W[0]?.count??0)}let P=F.at(-1);return{docs:B,limit:k,totalDocs:y,hasNextPage:j,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,a={}){return this.findOne(o,{...a,where:t("id",i)})}async count(o,i={}){let a=await this.options.database(),r=C(this.options.config,i),c=await _(o,{actor:i.actor??null,operation:"read",locale:r.locale,rbac:this.options.config.rbac}),f=this.scope(o,i.where,c,i.includeTrashed);return a.transaction(async(h)=>{let g=await a.query(h,{table:p,where:f,count:!0});return Number(g[0]?.count??0)})}async create(o,i){let a=C(this.options.config,i),r=i.actor??null,c={...i.data};return this.runWrite({collection:o,intent:"create",actor:r,source:i.source??"local",locale:a,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",r,a),I(o,c,r,a.locale);let k=await je(h.createBefore,{data:c},g,(P,W)=>({...P,data:W}));if(k===!1)return null;let v=i.id??b("doc"),D=await be({db:f,collection:o,input:k.data,stored:null,locale:a.locale,documentId:v}),{data:j,touched:F}=$e(o,D.input,a);Je(o,j,a,Object.keys(o.fields));let B=new Date,y=await f.insert(p,{id:v,collection:o.slug,data:j,created_at:B,updated_at:B,updated_by:r?.id??null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1});return{doc:A(y,o,a),previous:null,changed:F,stored:j}}})}async update(o,i,a){let r=C(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:r,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,...a===void 0?{}:{emit:a},step:async({adapter:h,tx:g,db:k,hooks:v,context:D})=>{let j=await this.load(h,g,o,i.id,{actor:c,operation:"update",locale:r,includeTrashed:i.includeTrashed});Re(i.expectedRevision,j);let F=A(j,o,r);await this.assertAllowed(o,"update",c,r,F),I(o,f,c,r.locale,F);let B=await je(v.updateBefore,{data:f,previous:F},D,(L,N)=>({...L,data:N}));if(B===!1)return null;let y=await be({db:k,collection:o,input:B.data,stored:u(j.data),locale:r.locale,documentId:String(j.id)}),{data:P,touched:W}=$e(o,y.input,r,u(j.data));Je(o,P,r,W);let E=new Date,O=await this.patch(h,g,j,{data:P,updated_at:E,updated_by:c?.id??null},i.expectedRevision),T=A(O,o,r);return{doc:T,previous:F,changed:go(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 r=C(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"trash",actor:c,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:f,tx:h,hooks:g,context:k})=>{let v=await this.load(f,h,o,i.id,{actor:c,operation:"delete",locale:r,includeTrashed:!1});Re(i.expectedRevision,v);let D=A(v,o,r);await this.assertAllowed(o,"delete",c,r,D);let j=await je(g.deleteBefore,D,k,(y,P)=>P);if(j===!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,r),previous:j,changed:[]}}})}async restore(o,i){let a=C(this.options.config,i),r=i.actor??null;return this.runWrite({collection:o,intent:"restore",actor:r,source:i.source??"local",locale:a,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:r,operation:"restore",locale:a,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,a);await this.assertAllowed(o,"restore",r,a,g);let k=new Date,v=await this.patch(c,f,h,{deleted_at:null,purge_after:null,updated_at:k,updated_by:r?.id??null});return{doc:A(v,o,a),previous:g,changed:[],after:!1}}})}async purge(o,i,a={}){let r=C(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"purge",actor:c,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!0,step:async({adapter:f,tx:h,db:g,hooks:k,context:v})=>{let D=await this.load(f,h,o,i.id,{actor:c,operation:"purge",locale:r,includeTrashed:!0,bypassAccess:a.retention===!0}),j=A(D,o,r),F=D.deleted_at!==null&&D.deleted_at!==void 0;if(a.retention!==!0)await this.assertAllowed(o,F?"purge":"delete",c,r,j);let B=F?j:await je(k.deleteBefore,j,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 a=C(this.options.config,i),r=i.actor??null,c=Ut(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:r,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!1,step:async({adapter:h,tx:g})=>{let k=await this.load(h,g,o,i.id,{actor:r,operation:"update",locale:a,includeTrashed:!1}),v=A(k,o,a);await this.assertAllowed(o,"update",r,a,v),I(o,f,r,a.locale,v);let D=$e(o,f,a,u(k.data));Je(o,D.data,a,D.touched);let j=new Date,F=await this.patch(h,g,k,{scheduled_at:c,scheduled_patch:{data:f,locale:a.locale,actor:r===null?null:{...r}},updated_at:j,updated_by:r?.id??null});return{doc:A(F,o,a),previous:v,changed:[],after:!1}}})}async unschedule(o,i){let a=C(this.options.config,i),r=i.actor??null;return this.runWrite({collection:o,intent:"unschedule",actor:r,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!1,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:r,operation:"update",locale:a,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,a);await this.assertAllowed(o,"update",r,a,g);let k=new Date,v=await this.patch(c,f,h,{scheduled_at:null,scheduled_patch:null,updated_at:k,updated_by:r?.id??null});return{doc:A(v,o,a),previous:g,changed:[],after:!1}}})}globalApi(o){return{get:(i)=>this.globalGet(o,i),update:async(i)=>{let a=await this.ensureGlobalRow(o,i);return this.update(o,{...i,id:a})},schedule:async(i)=>{let a=await this.ensureGlobalRow(o,i);return this.schedule(o,{...i,id:a})},unschedule:async(i={})=>this.unschedule(o,{...i,id:te(o)})}}async globalGet(o,i={}){let a=await this.options.database(),r=C(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:r.locale,rbac:this.options.config.rbac});return a.transaction(async(h)=>{let k=(await a.query(h,{table:p,where:this.scope(o,t("id",te(o)),f,!1),limit:1}))[0]??this.emptyGlobalRow(o,r,null),v=A(k,o,r);return await this.expand(a,h,[v],o,r,i,c),this.redact([v],o,c,r),v})}async ensureGlobalRow(o,i){let a=await this.options.database(),r=C(this.options.config,i),c=te(o);if(await a.transaction(async(h)=>(await a.query(h,{table:p,where:t("id",c),limit:1})).length>0))return c;try{await a.transaction((h)=>a.mutate(h,{kind:"insert",table:p,returning:!1,values:this.emptyGlobalRow(o,r,new Date)}))}catch(h){if(!await a.transaction(async(k)=>(await a.query(k,{table:p,where:t("id",c),limit:1})).length>0))throw h}return c}emptyGlobalRow(o,i,a){let{data:r}=$e(o,{},i);return{id:te(o),collection:o.slug,data:r,created_at:a,updated_at:a,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)],a=Ie(o),r=o.scheduled_at;if(!i||!a||!(r 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",r)),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))).count!==1)return;await this.update(i,{id:String(o.id),data:a.data,locale:a.locale,actor:a.actor,source:"job"},(h,g)=>{h.emit("document.schedule.applied",{collection:i.name,documentId:String(g.doc.id),locale:a.locale,scheduledFor:r.toISOString(),patch:a.data})})}async purgeExpired(o){let i=this.bySlug[String(o.collection)];if(!i){let a=await this.options.database();await a.transaction(async(r)=>{let c=d(a,r);await c.delete(Mt,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((a)=>i.mutate(a,{kind:"update",table:p,where:t("id",o),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))}async recordFailure(o,i,a){let r=a instanceof Error?a.message:String(a),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:r,created_at:f}),await this.appendEvents(h,[{type:"job.failed",data:{job:o,error:r,...i},previous:null}],{actor:null})}),this.scheduleDelivery()}async runWrite(o){let i=await this.options.database(),a=await this.outboxWorker(),r=this.pipeline(o.collection.name),c=new pt,f=await i.transaction(async(h)=>{let g=d(i,h),k=await this.replay(g,o);if(k)return k;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:r,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 a.append(h,c.take(),this.outboxMeta(o,D)),D.after!==!1)await this.runAfter(r,o,D,v);return await a.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 a=i.idempotencyKey;if(a===void 0)return null;let r=await o.findOne(Ue,t("idempotency_key",a));if(!r)return null;return{doc:u(r.result),previous:null,changed:[],replayed:!0}}async recordIdempotency(o,i,a){let r=i.idempotencyKey;if(r===void 0)return;await o.insert(Ue,{id:b("aim"),idempotency_key:r,run_id:i.runId??"",collection:i.collection.name,document_id:String(a.doc.id),result:a.doc,created_at:new Date})}async runAfter(o,i,a,r){let c=Ke[i.intent];if(c==="create"){await He(o.createAfter,a.doc,r);return}if(c==="update"){await He(o.updateAfter,{doc:a.doc,previous:a.previous},r);return}await He(o.deleteAfter,a.doc,r)}emitDocumentEvents(o,i,a){let r=(f)=>({collection:i.collection.name,documentId:String(a.doc.id),locale:i.locale.locale,document:ce(f)});switch(i.intent){case"create":{o.emit("document.created",r(a.doc),null);return}case"trash":{o.emit("document.trashed",{...r(a.doc),purgeAfter:a.doc.purgeAfter??null},null);return}case"restore":{o.emit("document.restored",r(a.doc),null);return}case"purge":{o.emit("document.purged",r(a.doc),null);return}case"schedule":{o.emit("document.scheduled",{...r(a.doc),scheduledAt:a.doc.scheduledAt??null,patch:ce(a.doc.scheduledPatch??null)},null);return}case"unschedule":{o.emit("document.schedule.cancelled",{...r(a.doc),scheduledAt:a.previous?.scheduledAt??null},null);return}case"update":break}let c=a.previous;o.emit("document.updated",r(a.doc),r(c));for(let f of a.changed)o.emit("document.field.changed",{collection:i.collection.name,documentId:String(a.doc.id),locale:i.locale.locale,field:f,value:ce(a.doc[f]??null)},{field:f,value:ce(c[f]??null)})}async syncMedia(o,i,a,r){let c=this.options.config.uploads,f=a.releaseMedia===!0;if(!f&&a.stored===void 0)return;if(!f&&!this.referencesMedia(i.collection))return;let h=await nn({db:o,collection:i.collection.name,documentId:String(a.doc.id),references:f?null:tn(i.collection,a.stored??{}),lifecycle:c!==void 0,retention:c?.retention,now:new Date}),g=(k)=>({mediaId:k,collection:i.collection.name,documentId:String(a.doc.id)});for(let k of h.orphaned)r.emit("media.orphaned",g(k));for(let k of h.reclaimed)r.emit("media.reclaimed",g(k))}async syncSlugs(o,i,a){if(!this.keepsSlugHistory(i.collection))return;let r=String(a.doc.id);if(a.releaseMedia===!0){await Me(o,i.collection,r);return}if(a.slugMoves&&a.slugMoves.length>0)await we(o,i.collection,r,a.slugMoves,new Date)}keepsSlugHistory(o){return re(o).some(([,i])=>ee(i).history===!0)}referencesMedia(o){let i=this.media.get(o.name);if(i!==void 0)return i;let a=en(o);return this.media.set(o.name,a),a}async writeActivity(o,i,a){await o.insert(Lt,{id:ve("act"),actor_id:i.actor?.id??null,actor_source:i.actor?.source??null,action:Qt(i.intent),source:i.source,collection:i.collection.name,document_id:String(a.doc.id),locale:i.locale.locale,changes:{fields:a.changed,...i.runId===void 0?{}:{runId:i.runId}},ip:null,created_at:new Date})}scope(o,i,a,r){let c=[t("collection",o.slug)];if(r!==!0)c.push(t("deleted_at",null));if(i)c.push(i);if(a)c.push(a);return s(...c)}async load(o,i,a,r,c){let f=c.bypassAccess===!0?void 0:await _(a,{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(a,t("id",r),f,c.includeTrashed),limit:1}))[0];if(!g)throw e.notFound(`No ${a.name} with id "${r}"`);return g}async patch(o,i,a,r,c){let f=hn(a.revision),h=f+1,g=String(a.id),k=await o.mutate(i,{kind:"update",table:p,where:c===void 0?t("id",g):s(t("id",g),t("revision",c)),set:{...r,revision:h}});if(c!==void 0&&k.count===0)throw Ve(c,f);return k.rows[0]??{...a,...r,revision:h}}async assertAllowed(o,i,a,r,c){if(await _(o,{actor:a,operation:i,locale:r.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,a,r,c,f,h){if(!f.depth)return;await new ft({adapter:o,tx:i,locale:c,actor:h,rbac:this.options.config.rbac,collections:this.byName,...f.includeTrashed===void 0?{}:{includeTrashed:f.includeTrashed}}).expand(a,r,f.depth)}redact(o,i,a,r){if(!on(i))return;for(let c of o)fe(c,i,a,r.locale)}pipeline(o){let i=this.pipelines.get(o);if(i)return i;let a=dt(this.options.config,o);return this.pipelines.set(o,a),a}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 mt(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 Nt(o){let i=o&&o.length>0?[...o]:[{path:"updated_at",direction:"desc"}];if(!i.some((a)=>a.path==="id"))i.push({path:"id",direction:i[i.length-1]?.direction??"desc"});return i}function qt(o){if(o===void 0)return Et;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,Ft)}function Ut(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 a=hn(i.revision);if(a!==o)throw Ve(o,a)}function Qt(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 Ht={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"},an=new Set(["ar","arc","dv","fa","he","ku","ps","sd","ug","ur","yi"]);function Bt(o){let i=Ht[o];if(i)return i;let[a,r]=o.split("-"),c=a===void 0?void 0:Ht[a.toLowerCase()];if(!c)return o;if(r===void 0)return c;let f=r.toUpperCase();return`${c} (${Xt[f]??f})`}function Vt(o){let i=o.split("-")[0];return i!==void 0&&an.has(i.toLowerCase())}function xn(o){return o.i18n.locales.map((i)=>({code:i,name:Bt(i),rtl:Vt(i),isDefault:i===o.i18n.defaultLocale}))}var q="webhooks",U="webhook_deliveries",rn=25,ln=200,cn=5,dn="10s";function Gt(o){let{config:i}=o,a=(y,P)=>(o.fetch??globalThis.fetch)(y,P),r=o.now??(()=>new Date),c=i.webhooks,f=c?.delivery?.retries??cn,h=w(c?.delivery?.timeout??dn),g=c?.delivery?.dlq!==!1,k=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)=>k?y*30000:Math.min(3600000,1000*2**y),j=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=r())=>{let O=await o.database(),T=Number(y.attempt??0)+1;if((await O.transaction((z)=>O.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 O.transaction((ae)=>d(O,ae).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),...gn(P.headers)};if(N.length>0)G[Ae]=await ke(W,N);let K=null,ue=null,ne=null;try{let z=await a(String(P.url),{method:"POST",headers:G,body:W,signal:AbortSignal.timeout(h)});if(K=z.status,ue=await pn(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=r(),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 O.transaction(async(z)=>(await d(O,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((ae)=>o.emit(ae,[{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),O=`whd_${P.id}_${String(y.id)}`,T=await W.transaction((N)=>d(W,N).findOne(U,t("id",O)));if(T)return ie(T);let L=await W.transaction(async(N)=>d(W,N).insert(U,{id:O,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:r(),delivered_at:null,created_at:r()}));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=r();return await P.transaction(async(O)=>{let L=await d(P,O).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),O=await E.findOne(q,t("id",y.id));if(!O)throw e.notFound("No such webhook.");let T={updated_at:r()};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??{...O,...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??rn)),E=[m("created_at","desc"),m("id","desc")],O=[];if(y.webhookId)O.push(t("webhook_id",y.webhookId));if(y.status)O.push(t("status",y.status));if(y.eventId)O.push(t("event_id",y.eventId));let T=O.length===0?void 0:s(...O),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,O={id:b("evt"),type:"webhook.test",createdAt:r().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,O)},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}}),O=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:r(),delivered_at:null,created_at:r()}));return F(T,E,O)},async attemptDelivery(y,P=r()){let W=await o.database(),E=await W.transaction(async(O)=>{let T=d(W,O),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 j();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??r(),O=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 O){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 j()).some((W)=>Xe(W,y))}}}async function pn(o){let i=o.body?.getReader();if(!i)return"";let a=[],r=0;try{while(r<2000){let{value:h,done:g}=await i.read();if(g)break;let k=h.slice(0,2000-r);a.push(k),r+=k.length}}finally{await i.cancel().catch(()=>{}),i.releaseLock()}let c=new Uint8Array(r),f=0;for(let h of a)c.set(h,f),f+=h.length;return new TextDecoder().decode(c)}function Xe(o,i){return Ye(o.events).some((r)=>{if(r==="*"||r===i)return!0;if(!r.endsWith("*"))return!1;return i.startsWith(r.slice(0,-1))})}function fn(o,i){if(!Xe(o,i.type))return!1;let a=o.filters??null;if(!a)return!0;let r=i.data;if(a.collections?.length){let c=typeof r.collection==="string"?r.collection:null;if(!c||!a.collections.includes(c))return!1}if(a.locales?.length){let c=mn(r);if(c.length>0&&!c.some((f)=>a.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 gn(o){if(typeof o!=="object"||o===null)return{};let i={};for(let[a,r]of Object.entries(o)){if(a.toLowerCase().startsWith("x-heyo-"))continue;if(a.toLowerCase()===Ae)continue;if(typeof r==="string")i[a]=r}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 Kt(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,a,r)=>{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",a))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:r}))},run:async(i,a,r)=>{await o.attemptDelivery(String(a.id),r)}}}var yn=new Set(["activity","admin","ai","auth","globals","jobs","locales","media","openapi.json","panel","roles","trash","users","webhooks"]),wn=/^[a-z][a-z0-9_]*$/,Cn=/^[a-z][a-zA-Z0-9_]*$/,Sn=/^[a-z][a-z0-9-]*$/,kn=/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;function Vn(o){return{...o,kind:"collection"}}function Gn(o){return{...o,kind:"global"}}function Kn(o){let i=Rn(o),a=Pt({collections:i.collections,globals:i.globals,pluginTables:i.plugins.flatMap((O)=>O.schema?.tables??[])}),r=new Map;for(let O of i.plugins)for(let[T,L]of Object.entries(O.events??{})){if(!L)continue;let N=r.get(T)??new Set;N.add(L),r.set(T,N)}let c,f,g=new ht({config:i,database:()=>E.database(),dispatch:async(O)=>{let T=[...r.get(O.type)??[],...r.get("*")??[]];for(let L of T)await L(O);await F.dispatch(O)}}),k=un({config:i,database:()=>E.database(),emit:(O,T,L)=>g.appendEvents(O,T,L),deliver:()=>g.deliverSoon()}),v=Zt({config:i,database:()=>E.database(),emit:(O,T,L)=>g.appendEvents(O,T,L),deliver:()=>g.deliverSoon()}),D=xn(i),j=De({database:()=>E.database()}),F=Gt({config:i,database:()=>E.database(),emit:(O,T,L)=>g.appendEvents(O,T,L),deliver:()=>g.deliverSoon()}),B=Rt({config:i,database:()=>E.database(),cms:()=>E,emit:(O,T,L)=>g.appendEvents(O,T,L),deliver:()=>g.deliverSoon()}),y=g.buildJobs();if(i.webhooks?.enabled)y.register(Kt(F));if(i.uploads)y.register(Yt({config:i,database:()=>E.database(),storage:()=>v.storage(),emit:(O,T,L)=>g.appendEvents(O,T,L),deliver:()=>g.deliverSoon()}));let P,W=()=>(P??=qe(E),P),E={_config:Object.freeze(i),schema:a,collections:o.collections,handler:(O)=>W().handler(O),_router:{routes:()=>W().routes()},api:g.buildApi(),globals:g.buildGlobals(),auth:k,media:v,ai:B,webhooks:F,trash:g.buildTrash(),jobs:y,locales:{list:()=>D},activity:j,inspect(){return{basePath:i.basePath,database:{id:c?.id??"unresolved",capabilities:c?.capabilities??{transactions:!1,sqlMigrations:!1,jsonQuery:!1}},storage:Un(i),collections:qn(i),schema:a,hooks:Wt(i),routes:W().routes(),admin:{path:`${i.basePath}${i.admin.path}`,panel:i.admin.assets?.id??null},plugins:Zn(i),auth:Qn(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((O)=>(O.useSchema(a),c=O,O)),f},on(O,T){let L=r.get(O)??new Set;return L.add(T),r.set(O,L),()=>{L.delete(T)}},drainEvents(O){return g.drainEvents(O)},async close(){await g.settle(),await c?.close?.(),c=void 0,f=void 0,r.clear()}};return g.bind(E),E}function Rn(o){let i=zn(o.basePath??ge),a=new Set(ot()),r=o.plugins??[];$n(r);let c=Tn(o.collections,r),f=Dn({plugins:r,collections:c,globals:o.globals??{},basePath:i}),h={};for(let[v,D]of Object.entries(c))h[v]=nt(v,D,"collection",a);let g={};for(let[v,D]of Object.entries(o.globals??{}))g[v]=nt(v,D,"global",a);An({...h,...g}),Ln({...h,...g}),_n({...h,...g}),On(o),Pn(o,h,g),jn({...h,...g}),Jn(o),Wn(o),En(o),Fn(o,i),Mn(o),Bn(o);let k=o.trash?.purgeAfter??"30d";if(typeof k==="string")w(k,"trash.purgeAfter");return{basePath:i,database:o.database,admin:{...o.admin,path:Nn(o.admin?.path??et)},...o.rbac===void 0?{}:{rbac:o.rbac},i18n:In(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:k},collections:h,globals:g,...o.hooks===void 0?{}:{hooks:o.hooks},...o.databaseHooks===void 0?{}:{databaseHooks:o.databaseHooks},plugins:r,pluginHooks:f,...o.telemetry===void 0?{}:{telemetry:o.telemetry},migrationsDirectory:o.migrations?.directory??tt}}function nt(o,i,a,r){if(!wn.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(!Sn.test(c))throw new n(`collections.${o}.slug`,`"${c}" is not a URL-safe slug`);if(r.has(o)||r.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(!Cn.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??Xn(o),kind:a,fields:f,access:i.access??{},...i.admin===void 0?{}:{admin:i.admin}}}function An(o){let i=new Map;for(let a of Object.values(o)){let r=i.get(a.slug);if(r)throw new n(`collections.${a.name}.slug`,`"${a.slug}" is already used by "${r}"; slugs are URLs and index names`);i.set(a.slug,a.name)}}function _n(o){let i=new Set([...Object.keys(o),...ot()]);for(let a of Object.values(o))for(let[r,c]of Object.entries(a.fields)){if(!c.relationTo)continue;if(!i.has(c.relationTo))throw new n(`collections.${a.name}.fields.${r}`,`relation points at "${c.relationTo}", which is not a collection`)}}function On(o){let i=o.ai;if(i&&i.chat!==void 0)throw new n("ai.chat","document chat was replaced by the panel-wide assistant. Use ai.assistant, which takes a model, instructions and limits; what the agent may read and write now comes from the configuration and the actor at runtime");let a={...o.collections,...o.globals??{}};for(let[r,c]of Object.entries(a)){if(c?.ai===void 0)continue;throw new n(`collections.${r}.ai`,"per-collection ai.chat was removed with document chat. Delete the key; the assistant reads the collection through the same access control as everything else")}}function Pn(o,i,a){for(let r of Object.keys(o.databaseHooks??{}))if(!(r in i)&&!(r in a))throw new n(`databaseHooks.${r}`,"no collection or global with this name")}function Tn(o,i){let a={...o},r=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=r.get(f);if(g)throw new n(`plugins.${c.id}.schema.collections.${f}`,`"${g}" already declares a collection called "${f}"`);r.set(f,c.id),a[f]=h}return a}function Dn(o){let i=[],a=new Map;for(let r of o.plugins){if(!r.extendCollections)continue;let c=r.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.${r.id}.extendCollections`,`patches "${f.collection}", which is not a collection or a global`);for(let[g,k]of Object.entries(f.fields??{})){let v=a.get(`${f.collection}.${g}`);if(g in h.fields)throw new n(`plugins.${r.id}.extendCollections`,v?`"${v}" already added "${g}" to ${f.collection}`:`${f.collection} already has a field called "${g}"`);a.set(`${f.collection}.${g}`,r.id),h.fields={...h.fields,[g]:k}}if(f.hooks)i.push({plugin:r.id,collection:f.collection,hooks:f.hooks,priority:0})}}return i}function jn(o){for(let i of Object.values(o))for(let[a,r]of Object.entries(i.fields)){if(r.aiGenerate!==void 0)it(i,a,r.aiGenerate,`collections.${i.name}.fields.${a}.aiGenerate`);for(let[c,f]of Object.entries(r.ai??{})){if(f!==!0)it(i,a,f,`collections.${i.name}.fields.${a}.ai.${c}`);let h=Y(c),g=`collections.${i.name}.fields.${a}.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(r.type))throw new n(g,`does not apply to a ${r.type} field; it applies to ${h.appliesTo.join(", ")}`);if(h.requiresLocalized&&!r.localized)throw new n(g,"needs a localized field; this one stores a single value for every language")}}}function it(o,i,a,r){if(a.context!==void 0&&!Array.isArray(a.context))throw new n(`${r}.context`,"must be an array of field names");let c=new Set;for(let f of a.context??[]){if(typeof f!=="string"||!o.fields[f]||f===i||c.has(f))throw new n(`${r}.context`,`"${f}" must name a different, existing field of ${o.name} (only once)`);c.add(f)}if(a.maxLength!==void 0&&(!Number.isInteger(a.maxLength)||a.maxLength<1))throw new n(`${r}.maxLength`,"must be a positive integer");if(a.model&&(!a.model.provider||!a.model.model))throw new n(`${r}.model`,"needs a provider and a model")}function $n(o){let i=new Set;for(let r of o){if(i.has(r.id))throw new n(`plugins.${r.id}`,"two plugins share this id");i.add(r.id)}let a=new Map;for(let r of o)for(let c of r.routes??[]){let f=`${c.method} ${c.root===!0?"(root) ":""}${c.path}`,h=a.get(f);if(h)throw new n(`plugins.${r.id}.routes`,`"${f}" is already registered by "${h}"`);a.set(f,r.id)}}function In(o){let i=o?.locales,a=o?.defaultLocale??i?.[0]??"en";return{defaultLocale:a,locales:i??[a]}}function Jn(o){let i=o.i18n;if(!i)return;let a=i.locales;if(a!==void 0){if(a.length===0)throw new n("i18n.locales","at least one locale; leave the section out for a single-language site");for(let c of a)if(!kn.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(a).size!==a.length)throw new n("i18n.locales","duplicate locale codes")}let r=i.defaultLocale;if(r!==void 0&&a&&!a.includes(r))throw new n("i18n.defaultLocale",`"${r}" is not in i18n.locales (${a.map((c)=>`"${c}"`).join(", ")})`)}function Wn(o){let i=o.rbac;if(!i)return;for(let[a,r]of Object.entries(i.roles)){if(!/^[a-z][a-z0-9_-]*$/.test(a))throw new n(`rbac.roles.${a}`,"a role name must be lowercase letters, digits, dashes and underscores, starting with a letter");for(let c of r){if(c==="*")continue;if(!/^[a-z0-9_*-]+:[a-z0-9_*-]+$/.test(c))throw new n(`rbac.roles.${a}`,`"${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 En(o){let i=o.admin?.auth;if(!i)return;let a=new Set;for(let r of i.methods){if(a.has(r))throw new n("admin.auth.methods",`"${r}" is listed twice`);a.add(r)}for(let r of i.apiKeys?.scopes??[])if(!_e(r))throw new n("admin.auth.apiKeys.scopes",`"${r}" 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 Fn(o,i){let a=o.uploads;if(!a)return;if(a.publicPath!==void 0)Hn(a.publicPath,i);if(a.limits?.maxFileSize)se(a.limits.maxFileSize,"uploads.limits.maxFileSize");let r=a.retention?.purgeAfter;if(typeof r==="string")w(r,"uploads.retention.purgeAfter");let c=a.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(to.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 Ln(o){for(let i of Object.values(o))for(let[a,r]of Object.entries(i.fields)){if(r.type!=="slug")continue;let c=r.options.from;if(c===void 0)continue;let f=i.fields[String(c)],h=`collections.${i.name}.fields.${a}.from`;if(!f||c===a)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 Hn(o,i){let a=x(o.trim()),r="uploads.publicPath";if(a.length===0&&o.trim().startsWith("/"))throw new n("uploads.publicPath",'cannot be "/"; use a path such as "/media"');if(!a.startsWith("/"))throw new n("uploads.publicPath",'must start with "/"');if(!a.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(a,i)||f(i,a))throw new n("uploads.publicPath",`"${a}" 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 a=new Set(Object.keys(i.auth??{})),r=i.storage?.secret!==void 0;if(a.size===0&&!r&&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(!r&&i.complete===void 0&&!a.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&&!r&&i.complete===void 0&&!a.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 k=c?.[h];if(k===void 0)continue;if(!Number.isInteger(k)||k<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 Bn(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 Nn(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 a=x(i);if(a.length===0)return"";return a}function zn(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 a=x(i);if(a.length===0)throw new n("basePath",'cannot be "/"');return a}function qn(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(([a,r])=>({name:a,type:r.type,localized:r.localized,required:r.required}))}))}function Un(o){let i=o.uploads;if(!i)return null;let a=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:a===!1?null:a}}function Zn(o){return o.plugins.map((i)=>({id:i.id,collections:Object.keys(i.schema?.collections??{}).sort(),tables:(i.schema?.tables??[]).map((a)=>a.name).sort(),routes:i.routes?.length??0,hooks:(i.hooks?.length??0)+o.pluginHooks.filter((a)=>a.plugin===i.id).length,migrations:(i.migrations??[]).map((a)=>a.id),client:i.client!==void 0,admin:i.admin!==void 0}))}function Qn(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 Xn(o){return o.replaceAll("_"," ").replace(/^./,(i)=>i.toUpperCase())}function yt(o="system"){return{id:o,source:"session",roles:["admin"],permissions:["*"]}}
|
|
2
|
+
export{dt,je,He,Wt,ut,pt,mt,ft,vn,zt,ht,te,Ht,Bt,Vt,xn,Gt,Kt,Vn,Gn,Kn,yt};
|