@open-commune/core 0.2.14 → 0.2.15

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/index.mjs CHANGED
@@ -1 +1 @@
1
- import{homedir as Bt}from"node:os";import{join as L}from"node:path";import{z as s}from"zod";import{Database as $t}from"bun:sqlite";import{mkdirSync as jt,existsSync as Pt}from"node:fs";import{drizzle as qt}from"drizzle-orm/bun-sqlite";import{migrate as zt}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as k,text as o,integer as be,uniqueIndex as Kt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as j,FIELD_TYPES as Ee}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as H,fieldReadSchema as Lt,buildDataSchema as ve}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as B,eq as c,and as A,isNull as P,gt as F,desc as x,notExists as Ht,or as ne,lt as _e,isNotNull as Se,inArray as se,like as Ae,asc as Ue}from"drizzle-orm";import{S3Client as Ft,PutObjectCommand as Ie,HeadObjectCommand as Wt,DeleteObjectsCommand as Qt,GetObjectCommand as Yt}from"@aws-sdk/client-s3";import{getSignedUrl as Oe}from"@aws-sdk/s3-request-presigner";import{initTRPC as Gt,TRPCError as W}from"@trpc/server";import{randomBytes as re,createHash as Jt}from"node:crypto";import{SignJWT as Vt,jwtVerify as Zt}from"jose";import{consola as Ne}from"consola";import{createInsertSchema as oe,createUpdateSchema as Q,createSelectSchema as De}from"drizzle-zod";import{nanoid as ke}from"nanoid";const $=s.string().min(1),Xt=s.object({COMMUN_DATA_DIR:s.string().default(L(Bt(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:$,COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:$,COMMUN_S3_ACCESS_KEY:$,COMMUN_S3_SECRET_KEY:$,COMMUN_EMAIL_WEBHOOK_URL:$,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:$});function xe(i=process.env){return Xt.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET})}const R=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),M=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),q=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),Y=()=>o("legacy_extra",{mode:"json"}).$type(),ei=()=>o("status",{enum:j}).notNull().default("draft"),ti=()=>o("published_at"),Me=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),O=k("organization",{id:be("id").primaryKey().default(1),name:o("name").notNull(),type:o("type",{enum:["commune","intercommunality","syndicate","other"]}).notNull().default("commune"),slug:o("slug").notNull(),description:o("description"),address:o("address",{mode:"json"}).$type(),deployment:o("deployment",{mode:"json"}).$type(),settings:o("settings",{mode:"json"}).$type(),updatedBy:o("updated_by"),legacyExtra:Y(),createdAt:M(),updatedAt:q()}),p=k("users",{id:R(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:M(),updatedAt:q()}),h=k("sessions",{id:R(),userId:o("user_id").notNull().references(()=>p.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:M()}),y=k("invitations",{id:R(),email:o("email").notNull(),tokenHash:o("token_hash").notNull().unique(),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),expiresAt:o("expires_at").notNull(),usedAt:o("used_at"),createdAt:M()}),w=k("api_tokens",{id:R(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:M()}),v=k("media",{id:R(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:be("size").notNull(),alt:o("alt"),caption:o("caption"),objects:o("objects",{mode:"json"}).$type().notNull(),metaData:o("meta_data",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:Y(),createdAt:M(),updatedAt:q()}),f=k("collection_definitions",{id:R(),name:o("name").notNull(),slug:o("slug").notNull().unique(),description:o("description"),fields:o("fields",{mode:"json"}).$type().notNull(),editor:o("editor",{mode:"json"}).$type(),display:o("display",{mode:"json"}).$type(),headings:o("headings",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),legacyExtra:Y(),createdAt:M(),updatedAt:q()}),a=k("entries",{id:R(),collectionId:o("collection_id").notNull().references(()=>f.id,{onDelete:"cascade"}),title:o("title").notNull(),slug:o("slug").notNull(),data:o("data",{mode:"json"}).$type().notNull(),related:o("related",{mode:"json"}).$type(),createdBy:o("created_by"),updatedBy:o("updated_by"),status:ei(),publishedAt:ti(),legacyExtra:Y(),createdAt:M(),updatedAt:q()},i=>[Kt("entries_slug_unique").on(i.collectionId,i.slug)]),ii={__proto__:null,FIELD_TYPES:Ee,PUBLICATION_STATUSES:j,addressSchema:Me,apiTokens:w,collectionDefinitions:f,entries:a,fieldDefinitionSchema:H,invitations:y,media:v,organization:O,sessions:h,users:p};function ni(){const i=import.meta.dir;return i?L(i,"..","..","..","drizzle"):void 0}function Te(i,e){const t=e??ni();jt(i,{recursive:!0});const n=new $t(L(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=qt({client:n,schema:ii});return t&&Pt(L(t,"meta","_journal.json"))&&zt(r,{migrationsFolder:t}),r}class te{constructor(e){this.config=e}static fromEnv(e){return new te({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class Re{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(B`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ce=168*3600,si="medias/";class Be{constructor(e){this.config=e,this.client=new Ft({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return Oe(this.client,new Ie({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Ce})}async put(e,t,n){await this.client.send(new Ie({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new Wt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Qt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(si)?Promise.resolve(this.publicUrl(e)):Oe(this.client,new Yt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ce})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),n=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${n}`}}function $e(i){return new Be({endpoint:i.COMMUN_S3_ENDPOINT,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const b={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class G extends Error{}function g(i,e){return class extends G{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ae=Gt.context().meta().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof G?{type:t.type}:{}}}}}),_=ae.router,ri=ae.procedure,je=ae.middleware,oi=je(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof G)throw new W({code:t.trpcCode,message:t.message,cause:t})}return e}),T=ri.use(oi),Pe=i=>je(({ctx:e,next:t})=>{if(!e.session)throw new W({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new W({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),u=T.use(Pe()),E=T.use(Pe("admin")),ai=_({ping:T.query(({ctx:i})=>i.services.health.check())}),qe=s.object({email:s.email(),password:s.string().min(1)}),ce=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),de=s.object({email:s.email()}),le=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),ze=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),Ke=s.strictObject({name:s.string().trim().min(1).max(120)}),N=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),Le=s.object({name:s.string().min(1)});class He{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(p).where(c(p.email,e)).get()}async findUserById(e){return this.db.select().from(p).where(c(p.id,e)).get()}async listUsers(){return this.db.select().from(p).all()}async hasAnyUser(){return this.db.select({id:p.id}).from(p).limit(1).all().length>0}async deleteUser(e){this.db.delete(p).where(c(p.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(p).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(c(p.id,t.id)).returning().get():this.db.insert(p).values(e).returning().get()}async insertSession(e){return this.db.insert(h).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:h,user:p}).from(h).innerJoin(p,c(p.id,h.userId)).where(A(c(h.id,e),P(h.revokedAt),F(h.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(h).set({revokedAt:t}).where(c(h.id,e)).run()}async findSessionById(e){return this.db.select().from(h).where(c(h.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(h).where(A(c(h.userId,e),P(h.revokedAt),F(h.expiresAt,t))).orderBy(x(h.createdAt)).all()}async updateUser(e,t){return this.db.update(p).set(t).where(c(p.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(y).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(y).where(A(c(y.tokenHash,e),P(y.usedAt),F(y.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(y).where(A(P(y.usedAt),F(y.expiresAt,e),Ht(this.db.select({one:B`1`}).from(p).where(c(p.email,y.email))))).orderBy(x(y.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(y).where(c(y.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(y).set({usedAt:t}).where(c(y.id,e)).run()}async insertApiToken(e){return this.db.insert(w).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(w).where(A(c(w.tokenHash,e),P(w.revokedAt))).get()}async touchApiToken(e,t){this.db.update(w).set({lastUsedAt:t}).where(c(w.id,e)).run()}async revokeApiToken(e,t){this.db.update(w).set({revokedAt:t}).where(c(w.id,e)).run()}async listApiTokens(){return this.db.select({id:w.id,name:w.name,lastUsedAt:w.lastUsedAt,revokedAt:w.revokedAt,createdAt:w.createdAt}).from(w).orderBy(x(w.createdAt)).all()}async purgeExpired(e){this.db.delete(h).where(ne(_e(h.expiresAt,e),Se(h.revokedAt))).run(),this.db.delete(y).where(ne(_e(y.expiresAt,e),Se(y.usedAt))).run()}}const ue=g("user-not-found-error",b.NOT_FOUND),Fe=g("session-not-found-error",b.NOT_FOUND),pe=g("invitation-invalid-error",b.BAD_REQUEST),We=g("cannot-remove-self-error",b.BAD_REQUEST),Qe=g("too-many-attempts-error",b.TOO_MANY_REQUESTS),z=i=>Jt("sha256").update(i).digest("hex"),U=()=>new Date().toISOString(),ci=720*3600*1e3,Ye=168*3600*1e3,di=Bun.password.hashSync("commun-dummy-password-for-timing"),li=5*6e4,ui=10,K=new Map,Ge=i=>{const e=Date.now(),t=(K.get(i)??[]).filter(n=>e-n<li);return t.length?K.set(i,t):K.delete(i),t},pi=i=>Ge(i).length>=ui,mi=i=>{K.set(i,[...Ge(i),Date.now()])},hi=i=>K.delete(i);class Je{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Ne.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,n){const r=e.toLowerCase();if(pi(r))throw new Qe;const d=await this.repository.findUserByEmail(r),l=await this.verifyPassword(t,d?.passwordHash??di);return!d?.passwordHash||!l?(mi(r),null):(hi(r),this.createSession(d,n))}async createSession(e,t){const n=new Date(Date.now()+ci).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Vt({session:r.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(n)).sign(this.jwtKey()),session:{sessionId:r.id,user:e,expiresAt:n}}}async verifySession(e){let t;try{const{payload:r}=await Zt(e,this.jwtKey());if(typeof r.session!="string")return null;t=r.session}catch{return null}const n=await this.repository.findActiveSessionWithUser(t,U());return n?{sessionId:n.session.id,user:n.user,expiresAt:n.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,U())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,U())).map(n=>({id:n.id,createdAt:n.createdAt,expiresAt:n.expiresAt,ua:n.ua,ip:n.ip,current:n.id===t}))}async revokeOwnSession(e,t){const n=await this.repository.findSessionById(t);if(!n||n.userId!==e)throw new Fe(`session not found: ${t}`);await this.repository.revokeSession(t,U())}async purgeExpired(){await this.repository.purgeExpired(U())}async createInvitation(e){const t=re(32).toString("base64url"),n=new Date(Date.now()+Ye).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:z(t),expiresAt:n}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:n}}async listPendingInvitations(){return(await this.repository.listPendingInvitations(U())).map(({id:e,email:t,role:n,expiresAt:r})=>({id:e,email:t,role:n,expiresAt:r}))}async revokeInvitation(e){if(!await this.repository.deleteInvitation(e))throw new pe}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const n=re(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:z(n),expiresAt:new Date(Date.now()+Ye).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${n}`}})}async acceptInvitation(e,t){const n=await this.repository.findValidInvitation(z(e),U());if(!n)throw new pe;const r=await this.repository.findUserByEmail(n.email),d=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",l=await this.repository.activateUser({email:n.email,name:d,passwordHash:await this.hashPassword(t.password),role:n.role});return await this.repository.markInvitationUsed(n.id,U()),l}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new ue(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new We;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new ue(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${re(24).toString("base64url")}`,n=await this.repository.insertApiToken({name:e,tokenHash:z(t)});return{token:t,record:n}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(z(e));return t?(await this.repository.touchApiToken(t.id,U()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,U())}async listApiTokens(){return this.repository.listApiTokens()}}const Ve=_({login:T.input(qe).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new W({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:N(t.session.user)}}),logout:u.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:u.query(({ctx:i})=>({user:N(i.session.user)})),sessions:_({list:u.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:T.input(ce).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:N(t)}}),requestPasswordReset:T.input(de).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Ze=_({list:E.query(async({ctx:i})=>(await i.services.users.listUsers()).map(N)),directory:u.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:E.input(s.object({id:s.string()})).query(async({ctx:i,input:e})=>N(await i.services.users.getUser(e.id))),invite:E.input(le).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:E.input(ze).mutation(async({ctx:i,input:e})=>N(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:u.input(Ke).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:N(t)}}),remove:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),Xe=_({list:E.query(({ctx:i})=>i.services.users.listApiTokens()),create:E.input(Le).mutation(async({ctx:i,input:e})=>{const{token:t,record:n}=await i.services.users.createApiToken(e.name);return{token:t,id:n.id,name:n.name}}),revoke:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),et=_({create:E.input(le).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:E.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeInvitation(e.id),{revoked:e.id})),accept:T.input(ce).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:N(t)}}),requestPasswordReset:T.input(de).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),tt={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},yi={createdBy:!0,updatedBy:!0},me={...tt,...yi},it={...tt,updatedBy:!0},nt=oe(O).omit(it),st=Q(O).omit(it);class rt{constructor(e){this.db=e}async get(){return this.db.select().from(O).where(c(O.id,1)).get()}async insert(e){return this.db.insert(O).values({...e,id:1}).returning().get()}async update(e){return this.db.update(O).set(e).where(c(O.id,1)).returning().get()}}const ot=g("organization-not-initialized-error",b.NOT_FOUND),at=g("organization-already-initialized-error",b.BAD_REQUEST),ct=g("deploy-hook-missing-error",b.BAD_REQUEST),he=g("deploy-failed-error",b.INTERNAL_SERVER_ERROR),fi=3e4;class dt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new at;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new ot;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new ct;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(fi)})}catch(r){throw new he(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new he(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const lt=_({get:u.query(({ctx:i})=>i.services.organization.get()),init:E.input(nt).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:E.input(st).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:u.mutation(({ctx:i})=>i.services.organization.deploy())}),ut=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),pt=s.object({key:s.string().min(1),filename:s.string().min(1),mime:s.string().min(1),alt:s.string().optional(),metaData:s.record(s.string(),s.unknown()).optional()}),mt=Q(v).pick({alt:!0,caption:!0,filename:!0});class ht{constructor(e){this.db=e}async insert(e){return this.db.insert(v).values(e).returning().get()}async findById(e){return this.db.select().from(v).where(c(v.id,e)).get()}async list(){return this.db.select().from(v).orderBy(x(v.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(v).where(B`json_extract(${v.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(v).set(t).where(c(v.id,e)).returning().get()}async delete(e){this.db.delete(v).where(c(v.id,e)).run()}}const J=g("media-not-found-error",b.NOT_FOUND),ye=g("unsupported-mime-error",b.BAD_REQUEST),yt=g("upload-incomplete-error",b.BAD_REQUEST),fe=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),gi=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],ge=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",ft="medias/";class gt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!fe.has(t))throw new ye(`unsupported mime type: ${t}`);const r=`${ft}${ke(10)}/${ge(e)}`;return{key:r,url:await this.storage.presignedPutUrl(r,t,n)}}async finalize(e,t){const n=await this.storage.head(e.key);if(!n)throw new yt(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:ge(e.filename),mime:e.mime,size:n.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Ne.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${gi.join(", ")})`),r}async uploadDirect(e,t,n,r,d){if(!fe.has(t))throw new ye(`unsupported mime type: ${t}`);const l=`${ft}${ke(10)}/${ge(e)}`;return await this.storage.put(l,n,t),this.finalize({key:l,filename:e,mime:t,metaData:r},d)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new J(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,n){const r=await this.repository.update(e,{...t,updatedBy:n??null});if(!r)throw new J(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new J(`media not found: ${e}`);const n=t.objects;await this.storage.remove([n.original,...Object.values(n.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,n={original:await this.storage.url(t.original)};for(const[r,d]of Object.entries(t.variants??{}))n[r]=await this.storage.url(d);return n}}const wt=_({requestUpload:u.input(ut).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:u.input(pt).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:u.query(({ctx:i})=>i.services.media.listResolved()),get:u.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:u.input(s.object({id:s.string(),data:mt})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),bt=oe(f).omit(me).extend({fields:s.array(H).min(1),slug:s.string().optional()}),Et=Q(f).omit(me).extend({fields:s.array(H).min(1).optional()}),vt=De(f,{fields:s.array(Lt).describe("The fields every entry of the collection is made of")}),_t={...me,related:!0,collectionId:!0},St=oe(a).omit(_t).extend({slug:s.string().optional()}),At=Q(a).omit(_t).extend({related:s.array(s.string()).optional()}),V=De(a,{collectionId:i=>i.describe("Id of the collection the entry belongs to"),slug:i=>i.describe("Route segment of the entry on the published site"),data:s.record(s.string(),s.unknown()).describe("Values of the collection\u2019s fields, keyed by field name"),related:s.array(s.string()).nullable().describe("Ids of the entries that reference this one"),status:i=>i.describe("Publication status; only `published` entries are on the public site")}),Ut=V.extend({collectionSlug:s.string().describe("Slug of the collection the entry belongs to")});class It{constructor(e){this.db=e}async list(){return this.db.select().from(f).all()}async findBySlug(e){return this.db.select().from(f).where(c(f.slug,e)).get()}async findById(e){return this.db.select().from(f).where(c(f.id,e)).get()}async findByLegacyId(e){return this.db.select().from(f).where(B`json_extract(${f.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(f).values(e).returning().get()}async update(e,t){return this.db.update(f).set(t).where(c(f.id,e)).returning().get()}async delete(e){return this.db.delete(f).where(c(f.id,e)).returning().get()}}class Ot{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(c(a.collectionId,e)).orderBy(x(a.updatedAt)).all()}narrowing(e){const t=[c(a.collectionId,e.collectionId)];return e.status?.length&&t.push(se(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),A(...t)}matching(e){const t=`%${e.trim()}%`;return ne(Ae(a.title,t),Ae(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(se(a.collectionId,e.collectionIds)),e.status?.length&&t.push(se(a.status,e.status)),this.db.select().from(a).where(A(...t)).orderBy(x(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:B`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listPaginated(e,t){const n={recent:x(a.updatedAt),oldest:Ue(a.updatedAt),title:Ue(a.title)};return this.db.select().from(a).where(this.narrowing({...t,collectionId:e})).orderBy(n[t.order??"recent"]).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(a).where(A(c(a.collectionId,e),c(a.status,"published"))).orderBy(x(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(A(c(a.collectionId,e),c(a.slug,t))).get()}async findById(e){return this.db.select().from(a).where(c(a.id,e)).get()}async findByDataField(e,t,n){return this.db.select().from(a).where(A(c(a.collectionId,e),B`json_extract(${a.data}, ${`$.${t}`}) = ${n}`)).get()}async insert(e){return this.db.insert(a).values(e).returning().get()}async update(e,t){return this.db.update(a).set(t).where(c(a.id,e)).returning().get()}async delete(e){return this.db.delete(a).where(c(a.id,e)).returning().get()}}const Z=g("collection-not-found-error",b.NOT_FOUND),X=g("entry-not-found-error",b.NOT_FOUND),Nt=g("invalid-entry-data-error",b.BAD_REQUEST),Dt=g("duplicate-slug-error",b.BAD_REQUEST);function kt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function ee(i,e){const t=[];for(const n of i){if(n.type!=="relation")continue;const r=e[n.name];typeof r=="string"&&r?t.push(r):Array.isArray(r)&&t.push(...r.filter(d=>typeof d=="string"))}return[...new Set(t)]}class xt{constructor(e,t,n){this.definitions=e,this.entries=t,this.media=n}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new Z(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(kt(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,n){const r=await this.definitions.update(e,{...t,updatedBy:n??null});if(!r)throw new Z(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new Z(`collection not found: ${e}`)}validateData(e,t){const n=ve(e.fields).safeParse(t);if(!n.success)throw new Nt(`invalid data for collection ${e.slug}: ${n.error.message}`);return n.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new X(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const n=await this.getDefinition(e);return this.entries.listPaginated(n.id,{skip:t.skip??0,limit:t.limit??20,status:t.status,search:t.search,order:t.order})}async countEntries(e,t={}){const n=await this.getDefinition(e);return this.entries.countMatching({collectionId:n.id,status:t.status,search:t.search})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(r=>this.getDefinition(r))):await this.definitions.list(),n=new Map(t.map(r=>[r.id,r.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...n.keys()]:void 0,status:e.status,limit:e.limit??20})).map(r=>({...r,collectionSlug:n.get(r.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,n){const r=await this.getDefinition(e),d=this.validateData(r,t.data),l=await this.uniqueEntrySlug(r.id,t.slug||kt(t.title)),m=await this.entries.insert({...t,slug:l,data:d,collectionId:r.id,createdBy:n??null,updatedBy:n??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(r,m.id,[],ee(r.fields,d)),m}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new X(`entry not found: ${e}`);const d=await this.getDefinition(r.collectionId),l=new Set(d.fields.map(S=>S.name)),m=Object.fromEntries(Object.entries(r.data??{}).filter(([S])=>!l.has(S))),I=t.data?{...r.data,...t.data}:r.data,D=Object.fromEntries(Object.entries(I).filter(([S])=>l.has(S)||S in(t.data??{}))),C=t.data?{...m,...this.validateData(d,D)}:void 0,ie={...t,updatedBy:n??null};C&&(ie.data=C),t.status==="published"&&!t.publishedAt&&(ie.publishedAt=new Date().toISOString());try{const S=await this.entries.update(e,ie);return C&&await this.linkRelations(d,e,ee(d.fields,r.data),ee(d.fields,C)),t.related&&await this.linkRelations(d,e,r.related??[],t.related),S}catch(S){throw this.mapSlugConflict(S,d.slug,t.slug??r.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new X(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,ee(n.fields,t.data),[]),await this.entries.delete(e)}mapSlugConflict(e,t,n){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new Dt(`le slug "${n}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let n=t;for(let r=1;await this.entries.findBySlug(e,n);r++)n=`${t}-${r}`;return n}async uniqueDefinitionSlug(e){let t=e;for(let n=1;await this.definitions.findBySlug(t);n++)t=`${e}-${n}`;return t}async linkRelations(e,t,n,r){const d=r.filter(m=>!n.includes(m)),l=n.filter(m=>!r.includes(m));for(const m of d){const I=await this.entries.findById(m);if(!I)continue;const D=new Set(I.related??[]);D.add(t),await this.entries.update(m,{related:[...D]})}for(const m of l){const I=await this.entries.findById(m);I&&await this.entries.update(m,{related:(I.related??[]).filter(D=>D!==t)})}}}const we=s.string().describe("Id or slug of the collection"),Mt=s.array(s.enum(j)).optional().describe("Keep only entries in these publication statuses"),Tt=_({list:u.query(({ctx:i})=>i.services.collections.listDefinitions()),get:u.meta({agent:{name:"collections_describe",title:"Describe a collection",description:"Returns a collection and the fields its entries are made of. Call it before reading or searching entries of a collection whose fields you do not know yet.",annotations:{readOnlyHint:!0}}}).input(s.object({idOrSlug:we})).output(vt).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:E.input(bt).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:E.input(s.object({id:s.string(),data:Et})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:E.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:_({get:u.meta({agent:{name:"entries_get",title:"Read an entry",description:"Returns one entry with all its field values, whatever its publication status.",annotations:{readOnlyHint:!0}}}).input(s.object({id:s.string().describe("Id of the entry")})).output(V).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:u.meta({agent:{name:"entries_search",title:"Search entries",description:"Finds entries whose title or field values contain the query, across every collection or within the ones named. Most recently updated first. Matches words literally: try a shorter word or a variant when nothing comes back.",annotations:{readOnlyHint:!0}}}).input(s.object({query:s.string().trim().min(1).max(200).describe("Text to look for"),collections:s.array(we).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:Mt,limit:s.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(s.array(Ut)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:u.meta({agent:{name:"entries_list",title:"List the entries of a collection",description:"Lists the entries of one collection, 20 at a time by default, optionally narrowed by status or by a text match. Use `skip` to page.",annotations:{readOnlyHint:!0}}}).input(s.object({collectionId:we,status:Mt,search:s.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),order:s.enum(["recent","oldest","title"]).optional().describe("recent (last updated first, the default), oldest, or title"),skip:s.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:s.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(s.array(V)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),count:u.input(s.object({collectionId:s.string(),status:s.array(s.enum(j)).optional(),search:s.string().max(200).optional()})).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:u.input(s.object({collectionId:s.string(),data:St})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:u.input(s.object({id:s.string(),data:At})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:u.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})}),Rt=g("agent-tool-not-found-error",b.NOT_FOUND);function Ct(i){const e=i._def.procedures;return Object.entries(e).flatMap(([t,n])=>{const r=n._def.meta?.agent;if(!r)return[];const d=n._def.inputs[0]??s.object({}),l=n._def.output;return[{...r,path:t,input:d,...l&&{output:l instanceof s.ZodArray?s.object({result:l}):l}}]})}async function wi(i,e,t,n){const r=Ct(i).find(m=>m.name===t);if(!r)throw new Rt(`unknown agent tool: ${t}`);let d=i.createCaller(e);for(const m of r.path.split("."))d=d[m];const l=await d(n??{});return Array.isArray(l)?{result:l}:l}function bi({env:i}={}){const e=i??xe(),t=Te(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=$e(e),r=te.fromEnv(e),d=new Je(new He(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),l=new ht(t),m=new gt(l,n),I=new xt(new It(t),new Ot(t),m),D=new dt(new rt(t)),C={health:new Re(t),users:d,organization:D,media:m,collections:I};return{env:e,db:t,storage:n,services:C}}const Ei=_({health:ai,auth:Ve,users:Ze,invitations:et,apiTokens:Xe,organization:lt,media:wt,collections:Tt});export{fe as ALLOWED_MIME,Rt as AgentToolNotFoundError,We as CannotRemoveSelfError,Z as CollectionNotFoundError,xt as CollectionsService,It as DefinitionRepository,he as DeployFailedError,ct as DeployHookMissingError,G as DomainError,Dt as DuplicateSlugError,te as EmailService,X as EntryNotFoundError,Ot as EntryRepository,Ee as FIELD_TYPES,Re as HealthService,Nt as InvalidEntryDataError,pe as InvitationInvalidError,J as MediaNotFoundError,ht as MediaRepository,gt as MediaService,at as OrganizationAlreadyInitializedError,ot as OrganizationNotInitializedError,rt as OrganizationRepository,dt as OrganizationService,j as PUBLICATION_STATUSES,Be as S3Storage,Fe as SessionNotFoundError,Qe as TooManyAttemptsError,ye as UnsupportedMimeError,yt as UploadIncompleteError,ue as UserNotFoundError,He as UsersRepository,Je as UsersService,ce as acceptInvitationDto,Me as addressSchema,Ct as agentTools,Le as apiTokenCreateDto,w as apiTokens,Xe as apiTokensRouter,Ei as appRouter,Ve as authRouter,ve as buildDataSchema,wi as callTool,f as collectionDefinitions,Tt as collectionsRouter,Te as connectDb,bi as createCore,$e as createStorage,g as createTypedError,bt as definitionCreateDto,vt as definitionDto,Et as definitionUpdateDto,a as entries,St as entryCreateDto,V as entryDto,Ut as entrySearchHitDto,At as entryUpdateDto,H as fieldDefinitionSchema,y as invitations,et as invitationsRouter,le as inviteDto,qe as loginDto,v as media,pt as mediaFinalizeDto,ut as mediaRequestUploadDto,wt as mediaRouter,mt as mediaUpdateDto,O as organization,nt as organizationInitDto,lt as organizationRouter,st as organizationUpdateDto,xe as parseEnv,de as requestPasswordResetDto,h as sessions,N as toPublicUser,Ke as updateOwnProfileDto,ze as userUpdateDto,p as users,Ze as usersRouter};
1
+ import{homedir as Et}from"node:os";import{join as j}from"node:path";import{z as r}from"zod";import{Database as vt}from"bun:sqlite";import{mkdirSync as _t,existsSync as Ot}from"node:fs";import{drizzle as It}from"drizzle-orm/bun-sqlite";import{migrate as bt}from"drizzle-orm/bun-sqlite/migrator";import{v as St,w as d,x as l,y as p,z as w,E as m,r as G,a as Q,t as U,l as pe,u as he,s as me,j as V,b as ye,A as x,q as we,p as fe,B as _,o as ge,m as Ee,n as ve,C as v,D as a,i as _e,f as Oe,g as J,h as Ie,e as be,d as Se,c as Ae}from"./shared/core.aw1RlSUK.mjs";export{F as addressSchema,k as isErrorType}from"./shared/core.aw1RlSUK.mjs";import{sql as R,eq as o,and as b,isNull as C,gt as P,desc as D,notExists as At,or as Z,lt as Ue,isNotNull as Ne,inArray as X,like as De,asc as Me}from"drizzle-orm";import{S3Client as Ut,PutObjectCommand as Te,HeadObjectCommand as Nt,DeleteObjectsCommand as Dt,GetObjectCommand as Mt}from"@aws-sdk/client-s3";import{getSignedUrl as xe}from"@aws-sdk/s3-request-presigner";import{initTRPC as Tt,TRPCError as L}from"@trpc/server";import{randomBytes as ee,createHash as xt}from"node:crypto";import{SignJWT as Rt,jwtVerify as kt}from"jose";import{consola as Re}from"consola";import{nanoid as ke}from"nanoid";import{buildDataSchema as Ce}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS,fieldDefinitionSchema}from"./domains/collections/utils.mjs";import{PUBLICATION_STATUSES as te}from"./domains/collections/constants.mjs";export{FIELD_TYPES}from"./domains/collections/constants.mjs";import"drizzle-zod";import"drizzle-orm/sqlite-core";const k=r.string().min(1),Ct=r.object({COMMUN_DATA_DIR:r.string().default(j(Et(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:k,COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:k,COMMUN_S3_ACCESS_KEY:k,COMMUN_S3_SECRET_KEY:k,COMMUN_EMAIL_WEBHOOK_URL:k,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:k});function Be(i=process.env){return Ct.parse({COMMUN_DATA_DIR:i.COMMUN_DATA_DIR,COMMUN_MIGRATIONS_DIR:i.COMMUN_MIGRATIONS_DIR,COMMUN_S3_ENDPOINT:i.COMMUN_S3_ENDPOINT,COMMUN_S3_REGION:i.COMMUN_S3_REGION,COMMUN_S3_BUCKET:i.COMMUN_S3_BUCKET,COMMUN_S3_ACCESS_KEY:i.COMMUN_S3_ACCESS_KEY,COMMUN_S3_SECRET_KEY:i.COMMUN_S3_SECRET_KEY,COMMUN_EMAIL_WEBHOOK_URL:i.COMMUN_EMAIL_WEBHOOK_URL,COMMUN_EMAIL_WEBHOOK_TOKEN:i.COMMUN_EMAIL_WEBHOOK_TOKEN,COMMUN_ADMIN_URL:i.COMMUN_ADMIN_URL,COMMUN_JWT_SECRET:i.COMMUN_JWT_SECRET})}function Bt(){const i=import.meta.dir;return i?j(i,"..","..","..","drizzle"):void 0}function $e(i,e){const t=e??Bt();_t(i,{recursive:!0});const s=new vt(j(i,"commun.db"));s.exec("PRAGMA journal_mode=WAL"),s.exec("PRAGMA foreign_keys=ON"),s.exec("PRAGMA busy_timeout=5000");const n=It({client:s,schema:St});return t&&Ot(j(t,"meta","_journal.json"))&&bt(n,{migrationsFolder:t}),n}class W{constructor(e){this.config=e}static fromEnv(e){return new W({url:e.COMMUN_EMAIL_WEBHOOK_URL,token:e.COMMUN_EMAIL_WEBHOOK_TOKEN})}async sendEvent(e){const t=await fetch(this.config.url,{method:"POST",headers:{"content-type":"application/json",...this.config.token?{authorization:`Bearer ${this.config.token}`}:{}},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`email webhook ${t.status}: ${(await t.text()).slice(0,200)}`)}}class je{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(R`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Pe=168*3600,$t="medias/";class Le{constructor(e){this.config=e,this.client=new Ut({region:e.region,endpoint:e.endpoint,forcePathStyle:!0,credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return xe(this.client,new Te({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Pe})}async put(e,t,s){await this.client.send(new Te({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new Nt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Dt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith($t)?Promise.resolve(this.publicUrl(e)):xe(this.client,new Mt({Bucket:this.config.bucket,Key:e}),{expiresIn:Pe})}publicUrl(e){const t=this.config.endpoint.replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function qe(i){return new Le({endpoint:i.COMMUN_S3_ENDPOINT,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const f={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class q extends Error{}function y(i,e){return class extends q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ie=(i,e)=>i instanceof Error&&i.message.includes("UNIQUE constraint failed")&&i.message.includes(e),se=Tt.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof q?{type:t.type}:{}}}}}),O=se.router,jt=se.procedure,Ke=se.middleware,Pt=Ke(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof q)throw new L({code:t.trpcCode,message:t.message,cause:t})}return e}),M=jt.use(Pt),ze=i=>Ke(({ctx:e,next:t})=>{if(!e.session)throw new L({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new L({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),u=M.use(ze()),g=M.use(ze("admin")),Lt=O({ping:M.query(({ctx:i})=>i.services.health.check())});class Fe{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(d).where(o(d.email,e)).get()}async findUserById(e){return this.db.select().from(d).where(o(d.id,e)).get()}async listUsers(){return this.db.select().from(d).all()}async hasAnyUser(){return this.db.select({id:d.id}).from(d).limit(1).all().length>0}async deleteUser(e){this.db.delete(d).where(o(d.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(d).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(o(d.id,t.id)).returning().get():this.db.insert(d).values(e).returning().get()}async insertSession(e){return this.db.insert(l).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:l,user:d}).from(l).innerJoin(d,o(d.id,l.userId)).where(b(o(l.id,e),C(l.revokedAt),P(l.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(l).set({revokedAt:t}).where(o(l.id,e)).run()}async findSessionById(e){return this.db.select().from(l).where(o(l.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(l).where(b(o(l.userId,e),C(l.revokedAt),P(l.expiresAt,t))).orderBy(D(l.createdAt)).all()}async updateUser(e,t){return this.db.update(d).set(t).where(o(d.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(p).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(p).where(b(o(p.tokenHash,e),C(p.usedAt),P(p.expiresAt,t))).get()}async listPendingInvitations(e){return this.db.select().from(p).where(b(C(p.usedAt),P(p.expiresAt,e),At(this.db.select({one:R`1`}).from(d).where(o(d.email,p.email))))).orderBy(D(p.createdAt)).all()}async deleteInvitation(e){return!!this.db.delete(p).where(o(p.id,e)).returning().get()}async markInvitationUsed(e,t){this.db.update(p).set({usedAt:t}).where(o(p.id,e)).run()}async insertApiToken(e){return this.db.insert(w).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(w).where(b(o(w.tokenHash,e),C(w.revokedAt))).get()}async touchApiToken(e,t){this.db.update(w).set({lastUsedAt:t}).where(o(w.id,e)).run()}async revokeApiToken(e,t){this.db.update(w).set({revokedAt:t}).where(o(w.id,e)).run()}async listApiTokens(){return this.db.select({id:w.id,name:w.name,lastUsedAt:w.lastUsedAt,revokedAt:w.revokedAt,createdAt:w.createdAt}).from(w).orderBy(D(w.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(Z(Ue(l.expiresAt,e),Ne(l.revokedAt))).run(),this.db.delete(p).where(Z(Ue(p.expiresAt,e),Ne(p.usedAt))).run()}}const ne=y(m.USER_NOT_FOUND,f.NOT_FOUND),He=y(m.SESSION_NOT_FOUND,f.NOT_FOUND),re=y(m.INVITATION_INVALID,f.BAD_REQUEST),We=y(m.CANNOT_REMOVE_SELF,f.BAD_REQUEST),Ye=y(m.TOO_MANY_ATTEMPTS,f.TOO_MANY_REQUESTS),B=i=>xt("sha256").update(i).digest("hex"),S=()=>new Date().toISOString(),qt=720*3600*1e3,Ge=168*3600*1e3,Kt=Bun.password.hashSync("commun-dummy-password-for-timing"),zt=5*6e4,Ft=10,$=new Map,Qe=i=>{const e=Date.now(),t=($.get(i)??[]).filter(s=>e-s<zt);return t.length?$.set(i,t):$.delete(i),t},Ht=i=>Qe(i).length>=Ft,Wt=i=>{$.set(i,[...Qe(i),Date.now()])},Yt=i=>$.delete(i);class Ve{constructor(e,t={}){this.repository=e,this.options=t}jwtKey(){if(!this.options.jwtSecret)throw new Error("COMMUN_JWT_SECRET manquant \u2014 requis pour signer les sessions (fail-fast au boot)");return new TextEncoder().encode(this.options.jwtSecret)}async sendEmailEvent(e){try{await this.options.email?.sendEvent(e)}catch(t){Re.warn(`[email] \xE9chec d'\xE9mission ${e.eventName} \u2192 ${e.email}: ${String(t)}`)}}hashPassword(e){return Bun.password.hash(e)}verifyPassword(e,t){return Bun.password.verify(e,t)}async login(e,t,s){const n=e.toLowerCase();if(Ht(n))throw new Ye;const c=await this.repository.findUserByEmail(n),E=await this.verifyPassword(t,c?.passwordHash??Kt);return!c?.passwordHash||!E?(Wt(n),null):(Yt(n),this.createSession(c,s))}async createSession(e,t){const s=new Date(Date.now()+qt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Rt({session:n.id}).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(new Date(s)).sign(this.jwtKey()),session:{sessionId:n.id,user:e,expiresAt:s}}}async verifySession(e){let t;try{const{payload:n}=await kt(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,S());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,S())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,S())).map(s=>({id:s.id,createdAt:s.createdAt,expiresAt:s.expiresAt,ua:s.ua,ip:s.ip,current:s.id===t}))}async revokeOwnSession(e,t){const s=await this.repository.findSessionById(t);if(!s||s.userId!==e)throw new He(`session not found: ${t}`);await this.repository.revokeSession(t,S())}async purgeExpired(){await this.repository.purgeExpired(S())}async createInvitation(e){const t=ee(32).toString("base64url"),s=new Date(Date.now()+Ge).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:B(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async listPendingInvitations(){return(await this.repository.listPendingInvitations(S())).map(({id:e,email:t,role:s,expiresAt:n})=>({id:e,email:t,role:s,expiresAt:n}))}async revokeInvitation(e){if(!await this.repository.deleteInvitation(e))throw new re}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=ee(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:B(s),expiresAt:new Date(Date.now()+Ge).toISOString()}),await this.sendEmailEvent({email:t.email,eventName:"passwordResetRequested",eventProperties:{url:`${this.options.adminUrl??""}/password/define/${s}`}})}async acceptInvitation(e,t){const s=await this.repository.findValidInvitation(B(e),S());if(!s)throw new re;const n=await this.repository.findUserByEmail(s.email),c=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",E=await this.repository.activateUser({email:s.email,name:c,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,S()),E}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new ne(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new We;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new ne(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${ee(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:B(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(B(e));return t?(await this.repository.touchApiToken(t.id,S()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,S())}async listApiTokens(){return this.repository.listApiTokens()}}const Je=O({login:M.input(pe).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new L({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:U(t.session.user)}}),logout:u.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:u.query(({ctx:i})=>({user:U(i.session.user)})),sessions:O({list:u.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:u.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeOwnSession(i.session.user.id,e.id),{revoked:e.id}))}),acceptInvitation:M.input(Q).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:U(t)}}),requestPasswordReset:M.input(G).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Ze=O({list:g.query(async({ctx:i})=>(await i.services.users.listUsers()).map(U)),directory:u.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:g.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>U(await i.services.users.getUser(e.id))),invite:g.input(V).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:g.input(me).mutation(async({ctx:i,input:e})=>U(await i.services.users.updateUser(e.id,e.data))),updateOwnProfile:u.input(he).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.updateUser(i.session.user.id,e);return{user:U(t)}}),remove:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.removeUser(i.session.user.id,e.id),{removed:e.id}))}),Xe=O({list:g.query(({ctx:i})=>i.services.users.listApiTokens()),create:g.input(ye).mutation(async({ctx:i,input:e})=>{const{token:t,record:s}=await i.services.users.createApiToken(e.name);return{token:t,id:s.id,name:s.name}}),revoke:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),et=O({create:g.input(V).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),list:g.query(({ctx:i})=>i.services.users.listPendingInvitations()),revoke:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeInvitation(e.id),{revoked:e.id})),accept:M.input(Q).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:U(t)}}),requestPasswordReset:M.input(G).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))});class tt{constructor(e){this.db=e}async get(){return this.db.select().from(x).where(o(x.id,1)).get()}async insert(e){return this.db.insert(x).values({...e,id:1}).returning().get()}async update(e){return this.db.update(x).set(e).where(o(x.id,1)).returning().get()}}const it=y(m.ORGANIZATION_NOT_INITIALIZED,f.NOT_FOUND),st=y(m.ORGANIZATION_ALREADY_INITIALIZED,f.BAD_REQUEST),nt=y(m.DEPLOY_HOOK_MISSING,f.BAD_REQUEST),oe=y(m.DEPLOY_FAILED,f.INTERNAL_SERVER_ERROR),Gt=3e4;class rt{constructor(e,t={}){this.repository=e,this.options=t}async get(){return await this.repository.get()??null}async init(e){if(await this.repository.get())throw new st;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new it;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new nt;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(Gt)})}catch(n){throw new oe(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new oe(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const ot=O({get:u.query(({ctx:i})=>i.services.organization.get()),init:g.input(fe).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:g.input(we).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:u.mutation(({ctx:i})=>i.services.organization.deploy())});class at{constructor(e){this.db=e}async insert(e){return this.db.insert(_).values(e).returning().get()}async findById(e){return this.db.select().from(_).where(o(_.id,e)).get()}async list(){return this.db.select().from(_).orderBy(D(_.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(_).where(R`json_extract(${_.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(_).set(t).where(o(_.id,e)).returning().get()}async delete(e){this.db.delete(_).where(o(_.id,e)).run()}}const K=y(m.MEDIA_NOT_FOUND,f.NOT_FOUND),ae=y(m.UNSUPPORTED_MIME,f.BAD_REQUEST),ct=y(m.UPLOAD_INCOMPLETE,f.BAD_REQUEST),ce=new Set(["image/jpeg","image/png","image/webp","image/gif","application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet"]),Qt=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],ue=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",ut="medias/";class dt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!ce.has(t))throw new ae(`unsupported mime type: ${t}`);const n=`${ut}${ke(10)}/${ue(e)}`;return{key:n,url:await this.storage.presignedPutUrl(n,t,s)}}async finalize(e,t){const s=await this.storage.head(e.key);if(!s)throw new ct(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:ue(e.filename),mime:e.mime,size:s.size,alt:e.alt??null,metaData:e.metaData??null,createdBy:t??null,updatedBy:t??null,objects:{original:e.key,variants:{}}});return Re.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${Qt.join(", ")})`),n}async uploadDirect(e,t,s,n,c){if(!ce.has(t))throw new ae(`unsupported mime type: ${t}`);const E=`${ut}${ke(10)}/${ue(e)}`;return await this.storage.put(E,s,t),this.finalize({key:E,filename:e,mime:t,metaData:n},c)}async list(){return this.repository.list()}async listResolved(){const e=await this.repository.list();return Promise.all(e.map(async t=>({...t,objects:await this.objectUrls(t)})))}async get(e){const t=await this.repository.findById(e);if(!t)throw new K(`media not found: ${e}`);return{...t,objects:await this.objectUrls(t)}}async updateEditorial(e,t,s){const n=await this.repository.update(e,{...t,updatedBy:s??null});if(!n)throw new K(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new K(`media not found: ${e}`);const s=t.objects;await this.storage.remove([s.original,...Object.values(s.variants??{})]),await this.repository.delete(e)}async url(e){const t=await this.repository.findById(e);return t?this.storage.url(t.objects.original):null}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,c]of Object.entries(t.variants??{}))s[n]=await this.storage.url(c);return s}}const lt=O({requestUpload:u.input(ve).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:u.input(Ee).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:u.query(({ctx:i})=>i.services.media.listResolved()),get:u.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:u.input(r.object({id:r.string(),data:ge})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:u.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))});class pt{constructor(e){this.db=e}async list(){return this.db.select().from(v).all()}async findBySlug(e){return this.db.select().from(v).where(o(v.slug,e)).get()}async findById(e){return this.db.select().from(v).where(o(v.id,e)).get()}async findByLegacyId(e){return this.db.select().from(v).where(R`json_extract(${v.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(v).values(e).returning().get()}async update(e,t){return this.db.update(v).set(t).where(o(v.id,e)).returning().get()}async delete(e){return this.db.delete(v).where(o(v.id,e)).returning().get()}}class ht{constructor(e){this.db=e}async list(e){return this.db.select().from(a).where(o(a.collectionId,e)).orderBy(D(a.updatedAt)).all()}narrowing(e){const t=[o(a.collectionId,e.collectionId)];return e.status?.length&&t.push(X(a.status,e.status)),e.search?.trim()&&t.push(this.matching(e.search)),b(...t)}matching(e){const t=`%${e.trim()}%`;return Z(De(a.title,t),De(a.data,t))}async search(e){const t=[this.matching(e.search)];return e.collectionIds?.length&&t.push(X(a.collectionId,e.collectionIds)),e.status?.length&&t.push(X(a.status,e.status)),this.db.select().from(a).where(b(...t)).orderBy(D(a.updatedAt)).limit(e.limit).all()}async countMatching(e){const[t]=this.db.select({total:R`count(*)`}).from(a).where(this.narrowing(e)).all();return t?.total??0}async listPaginated(e,t){const s={recent:D(a.updatedAt),oldest:Me(a.updatedAt),title:Me(a.title)};return this.db.select().from(a).where(this.narrowing({...t,collectionId:e})).orderBy(s[t.order??"recent"]).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(a).where(b(o(a.collectionId,e),o(a.status,"published"))).orderBy(D(a.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(a).where(b(o(a.collectionId,e),o(a.slug,t))).get()}async findById(e){return this.db.select().from(a).where(o(a.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(a).where(b(o(a.collectionId,e),R`json_extract(${a.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(a).values(e).returning().get()}async update(e,t){return this.db.update(a).set(t).where(o(a.id,e)).returning().get()}async delete(e){return this.db.delete(a).where(o(a.id,e)).returning().get()}}const z=y(m.COLLECTION_NOT_FOUND,f.NOT_FOUND),F=y(m.ENTRY_NOT_FOUND,f.NOT_FOUND),mt=y(m.INVALID_ENTRY_DATA,f.BAD_REQUEST),de=y(m.DUPLICATE_SLUG,f.BAD_REQUEST);function yt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function H(i,e){const t=[];for(const s of i){if(s.type!=="relation")continue;const n=e[s.name];typeof n=="string"&&n?t.push(n):Array.isArray(n)&&t.push(...n.filter(c=>typeof c=="string"))}return[...new Set(t)]}class wt{constructor(e,t,s){this.definitions=e,this.entries=t,this.media=s}async listDefinitions(){return this.definitions.list()}async getDefinition(e){const t=await this.definitions.findBySlug(e)??await this.definitions.findById(e);if(!t)throw new z(`collection not found: ${e}`);return t}async createDefinition(e,t){const s=e.slug||await this.uniqueDefinitionSlug(yt(e.name));try{return await this.definitions.insert({...e,slug:s,createdBy:t??null,updatedBy:t??null})}catch(n){throw this.definitionSlugConflict(n,s)}}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null}).catch(c=>{throw this.definitionSlugConflict(c,t.slug??"")});if(!n)throw new z(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new z(`collection not found: ${e}`)}validateData(e,t){const s=Ce(e.fields).safeParse(t);if(!s.success)throw new mt(`invalid data for collection ${e.slug}: ${s.error.message}`);return s.data}async listEntries(e){return this.entries.list((await this.getDefinition(e)).id)}async getEntry(e){const t=await this.entries.findById(e);if(!t)throw new F(`entry not found: ${e}`);return t}async listEntriesPaginated(e,t={}){const s=await this.getDefinition(e);return this.entries.listPaginated(s.id,{skip:t.skip??0,limit:t.limit??20,status:t.status,search:t.search,order:t.order})}async countEntries(e,t={}){const s=await this.getDefinition(e);return this.entries.countMatching({collectionId:s.id,status:t.status,search:t.search})}async searchEntries(e){const t=e.collections?.length?await Promise.all(e.collections.map(n=>this.getDefinition(n))):await this.definitions.list(),s=new Map(t.map(n=>[n.id,n.slug]));return(await this.entries.search({search:e.query,collectionIds:e.collections?.length?[...s.keys()]:void 0,status:e.status,limit:e.limit??20})).map(n=>({...n,collectionSlug:s.get(n.collectionId)??""}))}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),c=this.validateData(n,t.data),E=await this.uniqueEntrySlug(n.id,t.slug||yt(t.title)),h=await this.entries.insert({...t,slug:E,data:c,collectionId:n.id,createdBy:s??null,updatedBy:s??null,publishedAt:t.status==="published"?t.publishedAt??new Date().toISOString():t.publishedAt});return await this.linkRelations(n,h.id,[],H(n.fields,c)),h}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new F(`entry not found: ${e}`);const c=await this.getDefinition(n.collectionId),E=new Set(c.fields.map(I=>I.name)),h=Object.fromEntries(Object.entries(n.data??{}).filter(([I])=>!E.has(I))),A=t.data?{...n.data,...t.data}:n.data,N=Object.fromEntries(Object.entries(A).filter(([I])=>E.has(I)||I in(t.data??{}))),T=t.data?{...h,...this.validateData(c,N)}:void 0,Y={...t,updatedBy:s??null};T&&(Y.data=T),t.status==="published"&&!t.publishedAt&&(Y.publishedAt=new Date().toISOString());try{const I=await this.entries.update(e,Y);return T&&await this.linkRelations(c,e,H(c.fields,n.data),H(c.fields,T)),t.related&&await this.linkRelations(c,e,n.related??[],t.related),I}catch(I){throw this.entrySlugConflict(I,c.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new F(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,H(s.fields,t.data),[]),await this.entries.delete(e)}definitionSlugConflict(e,t){return ie(e,"collection_definitions.slug")?new de(`le slug "${t}" est d\xE9j\xE0 celui d'une collection`):e}entrySlugConflict(e,t,s){return ie(e,"entries.slug")?new de(`le slug "${s}" est d\xE9j\xE0 utilis\xE9 dans la collection ${t}`):e}async uniqueEntrySlug(e,t){let s=t;for(let n=1;await this.entries.findBySlug(e,s);n++)s=`${t}-${n}`;return s}async uniqueDefinitionSlug(e){let t=e;for(let s=1;await this.definitions.findBySlug(t);s++)t=`${e}-${s}`;return t}async linkRelations(e,t,s,n){const c=n.filter(h=>!s.includes(h)),E=s.filter(h=>!n.includes(h));for(const h of c){const A=await this.entries.findById(h);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(h,{related:[...N]})}for(const h of E){const A=await this.entries.findById(h);A&&await this.entries.update(h,{related:(A.related??[]).filter(N=>N!==t)})}}}const le=r.string().describe("Id or slug of the collection"),ft=r.array(r.enum(te)).optional().describe("Keep only entries in these publication statuses"),gt=O({list:u.query(({ctx:i})=>i.services.collections.listDefinitions()),get:u.input(r.object({idOrSlug:le})).output(Ae).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:g.input(Se).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:g.input(r.object({id:r.string(),data:be})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:g.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:O({get:u.input(r.object({id:r.string().describe("Id of the entry")})).output(J).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),search:u.input(r.object({query:r.string().trim().min(1).max(200).describe("Text to look for"),collections:r.array(le).optional().describe("Search only these collections (ids or slugs); all of them when omitted"),status:ft,limit:r.number().int().min(1).max(50).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(Ie)).query(({ctx:i,input:e})=>i.services.collections.searchEntries(e)),list:u.input(r.object({collectionId:le,status:ft,search:r.string().max(200).optional().describe("Keep only entries whose title or field values contain this text"),order:r.enum(["recent","oldest","title"]).optional().describe("recent (last updated first, the default), oldest, or title"),skip:r.number().int().min(0).optional().describe("Entries to skip, for paging"),limit:r.number().int().min(1).max(100).optional().describe("Maximum number of entries returned, 20 by default")})).output(r.array(J)).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),count:u.input(r.object({collectionId:r.string(),status:r.array(r.enum(te)).optional(),search:r.string().max(200).optional()})).query(({ctx:i,input:e})=>i.services.collections.countEntries(e.collectionId,e)),create:u.input(r.object({collectionId:r.string(),data:Oe})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:u.input(r.object({id:r.string(),data:_e})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:u.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function Vt({env:i}={}){const e=i??Be(),t=$e(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=qe(e),n=W.fromEnv(e),c=new Ve(new Fe(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),E=new at(t),h=new dt(E,s),A=new wt(new pt(t),new ht(t),h),N=new rt(new tt(t)),T={health:new je(t),users:c,organization:N,media:h,collections:A};return{env:e,db:t,storage:s,services:T}}const Jt=O({health:Lt,auth:Je,users:Ze,invitations:et,apiTokens:Xe,organization:ot,media:lt,collections:gt});export{ce as ALLOWED_MIME,We as CannotRemoveSelfError,z as CollectionNotFoundError,wt as CollectionsService,pt as DefinitionRepository,oe as DeployFailedError,nt as DeployHookMissingError,q as DomainError,de as DuplicateSlugError,m as ERROR_TYPES,W as EmailService,F as EntryNotFoundError,ht as EntryRepository,je as HealthService,mt as InvalidEntryDataError,re as InvitationInvalidError,K as MediaNotFoundError,at as MediaRepository,dt as MediaService,st as OrganizationAlreadyInitializedError,it as OrganizationNotInitializedError,tt as OrganizationRepository,rt as OrganizationService,te as PUBLICATION_STATUSES,Le as S3Storage,He as SessionNotFoundError,Ye as TooManyAttemptsError,ae as UnsupportedMimeError,ct as UploadIncompleteError,ne as UserNotFoundError,Fe as UsersRepository,Ve as UsersService,Q as acceptInvitationDto,ye as apiTokenCreateDto,w as apiTokens,Xe as apiTokensRouter,Jt as appRouter,Je as authRouter,Ce as buildDataSchema,v as collectionDefinitions,gt as collectionsRouter,$e as connectDb,Vt as createCore,qe as createStorage,y as createTypedError,Se as definitionCreateDto,Ae as definitionDto,be as definitionUpdateDto,a as entries,Oe as entryCreateDto,J as entryDto,Ie as entrySearchHitDto,_e as entryUpdateDto,p as invitations,et as invitationsRouter,V as inviteDto,ie as isUniqueViolation,pe as loginDto,_ as media,Ee as mediaFinalizeDto,ve as mediaRequestUploadDto,lt as mediaRouter,ge as mediaUpdateDto,x as organization,fe as organizationInitDto,ot as organizationRouter,we as organizationUpdateDto,Be as parseEnv,G as requestPasswordResetDto,l as sessions,U as toPublicUser,he as updateOwnProfileDto,me as userUpdateDto,d as users,Ze as usersRouter};