@open-commune/core 0.1.5 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1178,7 +1178,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1178
1178
  data: {
1179
1179
  name: string;
1180
1180
  label: string;
1181
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
1181
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
1182
1182
  required: boolean;
1183
1183
  hidden: boolean;
1184
1184
  options?: string[] | undefined;
@@ -1198,7 +1198,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1198
1198
  $type: {
1199
1199
  name: string;
1200
1200
  label: string;
1201
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
1201
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
1202
1202
  required: boolean;
1203
1203
  hidden: boolean;
1204
1204
  options?: string[] | undefined;
@@ -2042,15 +2042,6 @@ type MediaUpdateDto = z.infer<typeof mediaUpdateDto>;
2042
2042
 
2043
2043
  /** Closed allowlist. SVG is excluded on purpose: it is an XSS surface. */
2044
2044
  declare const ALLOWED_MIME: Set<string>;
2045
- /** The media shape existing clients consume: `objects` values are public URLs. */
2046
- interface LegacyMedia {
2047
- _id: string;
2048
- id: string;
2049
- originalName: string;
2050
- mime: string;
2051
- metaData?: Record<string, unknown>;
2052
- objects: Record<string, string>;
2053
- }
2054
2045
  /**
2055
2046
  * Media library. The API hands out a pre-signed PUT URL, the client uploads
2056
2047
  * DIRECTLY to storage, then `finalize` verifies the object and records the row.
@@ -2088,10 +2079,6 @@ declare class MediaService {
2088
2079
  remove(id: string): Promise<void>;
2089
2080
  /** Public GET URL of a media's original object (null if the media is unknown). */
2090
2081
  url(id: string): Promise<string | null>;
2091
- /** The media record public payloads carry, with its URLs resolved. */
2092
- toLegacyMedia(id: string): Promise<LegacyMedia | null>;
2093
- /** Walks any JSON value, replacing `_media:<id>` strings with media records. */
2094
- resolveMediaPlaceholders(node: unknown): Promise<unknown>;
2095
2082
  private objectUrls;
2096
2083
  }
2097
2084
 
@@ -2120,10 +2107,25 @@ declare class EntryRepository {
2120
2107
  private readonly db;
2121
2108
  constructor(db: StoreDb);
2122
2109
  list(collectionId: string): Promise<Entry[]>;
2123
- /** Admin listing: most recently updated first, paginated. */
2110
+ /**
2111
+ * What an admin listing keeps. Narrowing happens in SQL: the browser is never
2112
+ * handed rows in order to discard them, and a collection of several hundred
2113
+ * entries would not fit in it anyway.
2114
+ */
2115
+ private narrowing;
2116
+ /** The total a paginated listing is a window onto. Counted in SQL. */
2117
+ countMatching(options: {
2118
+ collectionId: string;
2119
+ status?: Entry['status'][];
2120
+ search?: string;
2121
+ }): Promise<number>;
2122
+ /** Admin listing: most recently updated first by default, paginated. */
2124
2123
  listPaginated(collectionId: string, options: {
2125
2124
  skip: number;
2126
2125
  limit: number;
2126
+ status?: Entry['status'][];
2127
+ search?: string;
2128
+ order?: 'recent' | 'oldest' | 'title';
2127
2129
  }): Promise<Entry[]>;
2128
2130
  listPublished(collectionId: string): Promise<Entry[]>;
2129
2131
  findBySlug(collectionId: string, slug: string): Promise<Entry | undefined>;
@@ -2151,8 +2153,8 @@ declare const definitionCreateDto: z.ZodObject<{
2151
2153
  date: "date";
2152
2154
  text: "text";
2153
2155
  select: "select";
2154
- "rich-text": "rich-text";
2155
2156
  media: "media";
2157
+ "rich-text": "rich-text";
2156
2158
  relation: "relation";
2157
2159
  steps: "steps";
2158
2160
  }>;
@@ -2183,8 +2185,8 @@ declare const definitionUpdateDto: z.ZodObject<{
2183
2185
  date: "date";
2184
2186
  text: "text";
2185
2187
  select: "select";
2186
- "rich-text": "rich-text";
2187
2188
  media: "media";
2189
+ "rich-text": "rich-text";
2188
2190
  relation: "relation";
2189
2191
  steps: "steps";
2190
2192
  }>;
@@ -2257,27 +2259,20 @@ declare class CollectionsService {
2257
2259
  listEntriesPaginated(collectionIdOrSlug: string, options?: {
2258
2260
  skip?: number;
2259
2261
  limit?: number;
2262
+ status?: Entry['status'][];
2263
+ search?: string;
2264
+ order?: 'recent' | 'oldest' | 'title';
2260
2265
  }): Promise<Entry[]>;
2266
+ /** The total a listing is a window onto, under the same narrowing. */
2267
+ countEntries(collectionIdOrSlug: string, options?: {
2268
+ status?: Entry['status'][];
2269
+ search?: string;
2270
+ }): Promise<number>;
2261
2271
  listPublishedEntries(collectionIdOrSlug: string): Promise<Entry[]>;
2262
2272
  createEntry(collectionIdOrSlug: string, input: EntryCreateDto, actorId?: string): Promise<Entry>;
2263
2273
  /** PARTIAL update: `data` is merged field by field with what already exists. */
2264
2274
  updateEntry(id: string, input: EntryUpdateDto, actorId?: string): Promise<Entry>;
2265
2275
  removeEntry(id: string): Promise<void>;
2266
- /**
2267
- * Hidden fields excluded; rich text resolved then STRINGIFIED; media fields
2268
- * turned into arrays of media records.
2269
- */
2270
- private resolveEntryData;
2271
- /** Image and file nodes get their `mediaRecord` and a resolved `src`. */
2272
- private resolveRichTextMedia;
2273
- /** Events with no scheduled period are never published. */
2274
- private hasEmptySchedules;
2275
- /**
2276
- * ONE flat map of every published entry across all collections, keyed by id.
2277
- */
2278
- legacyRecordsPayload(): Promise<Record<string, Record<string, unknown>>>;
2279
- /** Public slugs of every published entry (`/collection/entry`), for the deployment payload. */
2280
- publishedSlugs(): Promise<string[]>;
2281
2276
  private mapSlugConflict;
2282
2277
  /** Incremental suffix -1/-2… until the slug is unique within the collection. */
2283
2278
  private uniqueEntrySlug;
@@ -2978,11 +2973,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2978
2973
  updatedAt: string;
2979
2974
  filename: string;
2980
2975
  mime: string;
2981
- size: number;
2976
+ metaData: Record<string, unknown> | null;
2982
2977
  alt: string | null;
2978
+ size: number;
2983
2979
  caption: string | null;
2984
2980
  objects: Record<string, unknown>;
2985
- metaData: Record<string, unknown> | null;
2986
2981
  createdBy: string | null;
2987
2982
  };
2988
2983
  meta: object;
@@ -2997,11 +2992,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2997
2992
  updatedAt: string;
2998
2993
  filename: string;
2999
2994
  mime: string;
3000
- size: number;
2995
+ metaData: Record<string, unknown> | null;
3001
2996
  alt: string | null;
2997
+ size: number;
3002
2998
  caption: string | null;
3003
2999
  objects: Record<string, unknown>;
3004
- metaData: Record<string, unknown> | null;
3005
3000
  createdBy: string | null;
3006
3001
  } & {
3007
3002
  objects: Record<string, string>;
@@ -3020,11 +3015,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3020
3015
  updatedAt: string;
3021
3016
  filename: string;
3022
3017
  mime: string;
3023
- size: number;
3018
+ metaData: Record<string, unknown> | null;
3024
3019
  alt: string | null;
3020
+ size: number;
3025
3021
  caption: string | null;
3026
3022
  objects: Record<string, unknown>;
3027
- metaData: Record<string, unknown> | null;
3028
3023
  createdBy: string | null;
3029
3024
  } & {
3030
3025
  objects: Record<string, string>;
@@ -3048,11 +3043,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3048
3043
  updatedAt: string;
3049
3044
  filename: string;
3050
3045
  mime: string;
3051
- size: number;
3046
+ metaData: Record<string, unknown> | null;
3052
3047
  alt: string | null;
3048
+ size: number;
3053
3049
  caption: string | null;
3054
3050
  objects: Record<string, unknown>;
3055
- metaData: Record<string, unknown> | null;
3056
3051
  createdBy: string | null;
3057
3052
  };
3058
3053
  meta: object;
@@ -3148,7 +3143,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3148
3143
  fields: {
3149
3144
  name: string;
3150
3145
  label: string;
3151
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3146
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3152
3147
  required: boolean;
3153
3148
  hidden: boolean;
3154
3149
  options?: string[] | undefined;
@@ -3177,7 +3172,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3177
3172
  fields: {
3178
3173
  name: string;
3179
3174
  label: string;
3180
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3175
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3181
3176
  required: boolean;
3182
3177
  hidden: boolean;
3183
3178
  options?: string[] | undefined;
@@ -3195,7 +3190,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3195
3190
  fields: {
3196
3191
  name: string;
3197
3192
  label: string;
3198
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3193
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3199
3194
  required?: boolean | undefined;
3200
3195
  hidden?: boolean | undefined;
3201
3196
  options?: string[] | undefined;
@@ -3220,7 +3215,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3220
3215
  fields: {
3221
3216
  name: string;
3222
3217
  label: string;
3223
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3218
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3224
3219
  required: boolean;
3225
3220
  hidden: boolean;
3226
3221
  options?: string[] | undefined;
@@ -3245,7 +3240,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3245
3240
  fields?: {
3246
3241
  name: string;
3247
3242
  label: string;
3248
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3243
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3249
3244
  required?: boolean | undefined;
3250
3245
  hidden?: boolean | undefined;
3251
3246
  options?: string[] | undefined;
@@ -3266,7 +3261,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3266
3261
  fields: {
3267
3262
  name: string;
3268
3263
  label: string;
3269
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3264
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3270
3265
  required: boolean;
3271
3266
  hidden: boolean;
3272
3267
  options?: string[] | undefined;
@@ -3324,9 +3319,13 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3324
3319
  };
3325
3320
  meta: object;
3326
3321
  }>;
3322
+ /** Narrowing is optional: a caller that ignores it keeps the old behaviour. */
3327
3323
  list: _trpc_server.TRPCQueryProcedure<{
3328
3324
  input: {
3329
3325
  collectionId: string;
3326
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3327
+ search?: string | undefined;
3328
+ order?: "title" | "recent" | "oldest" | undefined;
3330
3329
  skip?: number | undefined;
3331
3330
  limit?: number | undefined;
3332
3331
  };
@@ -3347,6 +3346,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3347
3346
  }[];
3348
3347
  meta: object;
3349
3348
  }>;
3349
+ /** The total a listing is a window onto, under the same narrowing. */
3350
+ count: _trpc_server.TRPCQueryProcedure<{
3351
+ input: {
3352
+ collectionId: string;
3353
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3354
+ search?: string | undefined;
3355
+ };
3356
+ output: number;
3357
+ meta: object;
3358
+ }>;
3350
3359
  create: _trpc_server.TRPCMutationProcedure<{
3351
3360
  input: {
3352
3361
  collectionId: string;
@@ -4218,9 +4227,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4218
4227
  legacyExtra: Record<string, unknown> | null;
4219
4228
  createdBy: string | null;
4220
4229
  collectionId: string;
4230
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4221
4231
  title: string;
4222
4232
  related: string[] | null;
4223
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4224
4233
  publishedAt: string | null;
4225
4234
  };
4226
4235
  meta: object;
@@ -4228,6 +4237,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4228
4237
  list: _trpc_server.TRPCQueryProcedure<{
4229
4238
  input: {
4230
4239
  collectionId: string;
4240
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4241
+ search?: string | undefined;
4242
+ order?: "recent" | "oldest" | "title" | undefined;
4231
4243
  skip?: number | undefined;
4232
4244
  limit?: number | undefined;
4233
4245
  };
@@ -4241,13 +4253,22 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4241
4253
  legacyExtra: Record<string, unknown> | null;
4242
4254
  createdBy: string | null;
4243
4255
  collectionId: string;
4256
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4244
4257
  title: string;
4245
4258
  related: string[] | null;
4246
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4247
4259
  publishedAt: string | null;
4248
4260
  }[];
4249
4261
  meta: object;
4250
4262
  }>;
4263
+ count: _trpc_server.TRPCQueryProcedure<{
4264
+ input: {
4265
+ collectionId: string;
4266
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4267
+ search?: string | undefined;
4268
+ };
4269
+ output: number;
4270
+ meta: object;
4271
+ }>;
4251
4272
  create: _trpc_server.TRPCMutationProcedure<{
4252
4273
  input: {
4253
4274
  collectionId: string;
@@ -4269,9 +4290,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4269
4290
  legacyExtra: Record<string, unknown> | null;
4270
4291
  createdBy: string | null;
4271
4292
  collectionId: string;
4293
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4272
4294
  title: string;
4273
4295
  related: string[] | null;
4274
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4275
4296
  publishedAt: string | null;
4276
4297
  };
4277
4298
  meta: object;
@@ -4282,8 +4303,8 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4282
4303
  data: {
4283
4304
  data?: Record<string, unknown> | undefined;
4284
4305
  slug?: string | undefined;
4285
- title?: string | undefined;
4286
4306
  status?: "draft" | "waiting" | "ready" | "scheduled" | "published" | undefined;
4307
+ title?: string | undefined;
4287
4308
  publishedAt?: string | null | undefined;
4288
4309
  related?: string[] | undefined;
4289
4310
  };
@@ -4298,9 +4319,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4298
4319
  legacyExtra: Record<string, unknown> | null;
4299
4320
  createdBy: string | null;
4300
4321
  collectionId: string;
4322
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4301
4323
  title: string;
4302
4324
  related: string[] | null;
4303
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4304
4325
  publishedAt: string | null;
4305
4326
  };
4306
4327
  meta: object;
package/dist/index.d.ts CHANGED
@@ -1178,7 +1178,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1178
1178
  data: {
1179
1179
  name: string;
1180
1180
  label: string;
1181
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
1181
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
1182
1182
  required: boolean;
1183
1183
  hidden: boolean;
1184
1184
  options?: string[] | undefined;
@@ -1198,7 +1198,7 @@ declare const collectionDefinitions: drizzle_orm_sqlite_core.SQLiteTableWithColu
1198
1198
  $type: {
1199
1199
  name: string;
1200
1200
  label: string;
1201
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
1201
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
1202
1202
  required: boolean;
1203
1203
  hidden: boolean;
1204
1204
  options?: string[] | undefined;
@@ -2042,15 +2042,6 @@ type MediaUpdateDto = z.infer<typeof mediaUpdateDto>;
2042
2042
 
2043
2043
  /** Closed allowlist. SVG is excluded on purpose: it is an XSS surface. */
2044
2044
  declare const ALLOWED_MIME: Set<string>;
2045
- /** The media shape existing clients consume: `objects` values are public URLs. */
2046
- interface LegacyMedia {
2047
- _id: string;
2048
- id: string;
2049
- originalName: string;
2050
- mime: string;
2051
- metaData?: Record<string, unknown>;
2052
- objects: Record<string, string>;
2053
- }
2054
2045
  /**
2055
2046
  * Media library. The API hands out a pre-signed PUT URL, the client uploads
2056
2047
  * DIRECTLY to storage, then `finalize` verifies the object and records the row.
@@ -2088,10 +2079,6 @@ declare class MediaService {
2088
2079
  remove(id: string): Promise<void>;
2089
2080
  /** Public GET URL of a media's original object (null if the media is unknown). */
2090
2081
  url(id: string): Promise<string | null>;
2091
- /** The media record public payloads carry, with its URLs resolved. */
2092
- toLegacyMedia(id: string): Promise<LegacyMedia | null>;
2093
- /** Walks any JSON value, replacing `_media:<id>` strings with media records. */
2094
- resolveMediaPlaceholders(node: unknown): Promise<unknown>;
2095
2082
  private objectUrls;
2096
2083
  }
2097
2084
 
@@ -2120,10 +2107,25 @@ declare class EntryRepository {
2120
2107
  private readonly db;
2121
2108
  constructor(db: StoreDb);
2122
2109
  list(collectionId: string): Promise<Entry[]>;
2123
- /** Admin listing: most recently updated first, paginated. */
2110
+ /**
2111
+ * What an admin listing keeps. Narrowing happens in SQL: the browser is never
2112
+ * handed rows in order to discard them, and a collection of several hundred
2113
+ * entries would not fit in it anyway.
2114
+ */
2115
+ private narrowing;
2116
+ /** The total a paginated listing is a window onto. Counted in SQL. */
2117
+ countMatching(options: {
2118
+ collectionId: string;
2119
+ status?: Entry['status'][];
2120
+ search?: string;
2121
+ }): Promise<number>;
2122
+ /** Admin listing: most recently updated first by default, paginated. */
2124
2123
  listPaginated(collectionId: string, options: {
2125
2124
  skip: number;
2126
2125
  limit: number;
2126
+ status?: Entry['status'][];
2127
+ search?: string;
2128
+ order?: 'recent' | 'oldest' | 'title';
2127
2129
  }): Promise<Entry[]>;
2128
2130
  listPublished(collectionId: string): Promise<Entry[]>;
2129
2131
  findBySlug(collectionId: string, slug: string): Promise<Entry | undefined>;
@@ -2151,8 +2153,8 @@ declare const definitionCreateDto: z.ZodObject<{
2151
2153
  date: "date";
2152
2154
  text: "text";
2153
2155
  select: "select";
2154
- "rich-text": "rich-text";
2155
2156
  media: "media";
2157
+ "rich-text": "rich-text";
2156
2158
  relation: "relation";
2157
2159
  steps: "steps";
2158
2160
  }>;
@@ -2183,8 +2185,8 @@ declare const definitionUpdateDto: z.ZodObject<{
2183
2185
  date: "date";
2184
2186
  text: "text";
2185
2187
  select: "select";
2186
- "rich-text": "rich-text";
2187
2188
  media: "media";
2189
+ "rich-text": "rich-text";
2188
2190
  relation: "relation";
2189
2191
  steps: "steps";
2190
2192
  }>;
@@ -2257,27 +2259,20 @@ declare class CollectionsService {
2257
2259
  listEntriesPaginated(collectionIdOrSlug: string, options?: {
2258
2260
  skip?: number;
2259
2261
  limit?: number;
2262
+ status?: Entry['status'][];
2263
+ search?: string;
2264
+ order?: 'recent' | 'oldest' | 'title';
2260
2265
  }): Promise<Entry[]>;
2266
+ /** The total a listing is a window onto, under the same narrowing. */
2267
+ countEntries(collectionIdOrSlug: string, options?: {
2268
+ status?: Entry['status'][];
2269
+ search?: string;
2270
+ }): Promise<number>;
2261
2271
  listPublishedEntries(collectionIdOrSlug: string): Promise<Entry[]>;
2262
2272
  createEntry(collectionIdOrSlug: string, input: EntryCreateDto, actorId?: string): Promise<Entry>;
2263
2273
  /** PARTIAL update: `data` is merged field by field with what already exists. */
2264
2274
  updateEntry(id: string, input: EntryUpdateDto, actorId?: string): Promise<Entry>;
2265
2275
  removeEntry(id: string): Promise<void>;
2266
- /**
2267
- * Hidden fields excluded; rich text resolved then STRINGIFIED; media fields
2268
- * turned into arrays of media records.
2269
- */
2270
- private resolveEntryData;
2271
- /** Image and file nodes get their `mediaRecord` and a resolved `src`. */
2272
- private resolveRichTextMedia;
2273
- /** Events with no scheduled period are never published. */
2274
- private hasEmptySchedules;
2275
- /**
2276
- * ONE flat map of every published entry across all collections, keyed by id.
2277
- */
2278
- legacyRecordsPayload(): Promise<Record<string, Record<string, unknown>>>;
2279
- /** Public slugs of every published entry (`/collection/entry`), for the deployment payload. */
2280
- publishedSlugs(): Promise<string[]>;
2281
2276
  private mapSlugConflict;
2282
2277
  /** Incremental suffix -1/-2… until the slug is unique within the collection. */
2283
2278
  private uniqueEntrySlug;
@@ -2978,11 +2973,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2978
2973
  updatedAt: string;
2979
2974
  filename: string;
2980
2975
  mime: string;
2981
- size: number;
2976
+ metaData: Record<string, unknown> | null;
2982
2977
  alt: string | null;
2978
+ size: number;
2983
2979
  caption: string | null;
2984
2980
  objects: Record<string, unknown>;
2985
- metaData: Record<string, unknown> | null;
2986
2981
  createdBy: string | null;
2987
2982
  };
2988
2983
  meta: object;
@@ -2997,11 +2992,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
2997
2992
  updatedAt: string;
2998
2993
  filename: string;
2999
2994
  mime: string;
3000
- size: number;
2995
+ metaData: Record<string, unknown> | null;
3001
2996
  alt: string | null;
2997
+ size: number;
3002
2998
  caption: string | null;
3003
2999
  objects: Record<string, unknown>;
3004
- metaData: Record<string, unknown> | null;
3005
3000
  createdBy: string | null;
3006
3001
  } & {
3007
3002
  objects: Record<string, string>;
@@ -3020,11 +3015,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3020
3015
  updatedAt: string;
3021
3016
  filename: string;
3022
3017
  mime: string;
3023
- size: number;
3018
+ metaData: Record<string, unknown> | null;
3024
3019
  alt: string | null;
3020
+ size: number;
3025
3021
  caption: string | null;
3026
3022
  objects: Record<string, unknown>;
3027
- metaData: Record<string, unknown> | null;
3028
3023
  createdBy: string | null;
3029
3024
  } & {
3030
3025
  objects: Record<string, string>;
@@ -3048,11 +3043,11 @@ declare const mediaRouter: _trpc_server.TRPCBuiltRouter<{
3048
3043
  updatedAt: string;
3049
3044
  filename: string;
3050
3045
  mime: string;
3051
- size: number;
3046
+ metaData: Record<string, unknown> | null;
3052
3047
  alt: string | null;
3048
+ size: number;
3053
3049
  caption: string | null;
3054
3050
  objects: Record<string, unknown>;
3055
- metaData: Record<string, unknown> | null;
3056
3051
  createdBy: string | null;
3057
3052
  };
3058
3053
  meta: object;
@@ -3148,7 +3143,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3148
3143
  fields: {
3149
3144
  name: string;
3150
3145
  label: string;
3151
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3146
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3152
3147
  required: boolean;
3153
3148
  hidden: boolean;
3154
3149
  options?: string[] | undefined;
@@ -3177,7 +3172,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3177
3172
  fields: {
3178
3173
  name: string;
3179
3174
  label: string;
3180
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3175
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3181
3176
  required: boolean;
3182
3177
  hidden: boolean;
3183
3178
  options?: string[] | undefined;
@@ -3195,7 +3190,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3195
3190
  fields: {
3196
3191
  name: string;
3197
3192
  label: string;
3198
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3193
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3199
3194
  required?: boolean | undefined;
3200
3195
  hidden?: boolean | undefined;
3201
3196
  options?: string[] | undefined;
@@ -3220,7 +3215,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3220
3215
  fields: {
3221
3216
  name: string;
3222
3217
  label: string;
3223
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3218
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3224
3219
  required: boolean;
3225
3220
  hidden: boolean;
3226
3221
  options?: string[] | undefined;
@@ -3245,7 +3240,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3245
3240
  fields?: {
3246
3241
  name: string;
3247
3242
  label: string;
3248
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3243
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3249
3244
  required?: boolean | undefined;
3250
3245
  hidden?: boolean | undefined;
3251
3246
  options?: string[] | undefined;
@@ -3266,7 +3261,7 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3266
3261
  fields: {
3267
3262
  name: string;
3268
3263
  label: string;
3269
- type: "number" | "boolean" | "json" | "date" | "text" | "select" | "rich-text" | "media" | "relation" | "steps";
3264
+ type: "number" | "boolean" | "json" | "date" | "text" | "select" | "media" | "rich-text" | "relation" | "steps";
3270
3265
  required: boolean;
3271
3266
  hidden: boolean;
3272
3267
  options?: string[] | undefined;
@@ -3324,9 +3319,13 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3324
3319
  };
3325
3320
  meta: object;
3326
3321
  }>;
3322
+ /** Narrowing is optional: a caller that ignores it keeps the old behaviour. */
3327
3323
  list: _trpc_server.TRPCQueryProcedure<{
3328
3324
  input: {
3329
3325
  collectionId: string;
3326
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3327
+ search?: string | undefined;
3328
+ order?: "title" | "recent" | "oldest" | undefined;
3330
3329
  skip?: number | undefined;
3331
3330
  limit?: number | undefined;
3332
3331
  };
@@ -3347,6 +3346,16 @@ declare const collectionsRouter: _trpc_server.TRPCBuiltRouter<{
3347
3346
  }[];
3348
3347
  meta: object;
3349
3348
  }>;
3349
+ /** The total a listing is a window onto, under the same narrowing. */
3350
+ count: _trpc_server.TRPCQueryProcedure<{
3351
+ input: {
3352
+ collectionId: string;
3353
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
3354
+ search?: string | undefined;
3355
+ };
3356
+ output: number;
3357
+ meta: object;
3358
+ }>;
3350
3359
  create: _trpc_server.TRPCMutationProcedure<{
3351
3360
  input: {
3352
3361
  collectionId: string;
@@ -4218,9 +4227,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4218
4227
  legacyExtra: Record<string, unknown> | null;
4219
4228
  createdBy: string | null;
4220
4229
  collectionId: string;
4230
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4221
4231
  title: string;
4222
4232
  related: string[] | null;
4223
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4224
4233
  publishedAt: string | null;
4225
4234
  };
4226
4235
  meta: object;
@@ -4228,6 +4237,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4228
4237
  list: _trpc_server.TRPCQueryProcedure<{
4229
4238
  input: {
4230
4239
  collectionId: string;
4240
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4241
+ search?: string | undefined;
4242
+ order?: "recent" | "oldest" | "title" | undefined;
4231
4243
  skip?: number | undefined;
4232
4244
  limit?: number | undefined;
4233
4245
  };
@@ -4241,13 +4253,22 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4241
4253
  legacyExtra: Record<string, unknown> | null;
4242
4254
  createdBy: string | null;
4243
4255
  collectionId: string;
4256
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4244
4257
  title: string;
4245
4258
  related: string[] | null;
4246
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4247
4259
  publishedAt: string | null;
4248
4260
  }[];
4249
4261
  meta: object;
4250
4262
  }>;
4263
+ count: _trpc_server.TRPCQueryProcedure<{
4264
+ input: {
4265
+ collectionId: string;
4266
+ status?: ("draft" | "waiting" | "ready" | "scheduled" | "published")[] | undefined;
4267
+ search?: string | undefined;
4268
+ };
4269
+ output: number;
4270
+ meta: object;
4271
+ }>;
4251
4272
  create: _trpc_server.TRPCMutationProcedure<{
4252
4273
  input: {
4253
4274
  collectionId: string;
@@ -4269,9 +4290,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4269
4290
  legacyExtra: Record<string, unknown> | null;
4270
4291
  createdBy: string | null;
4271
4292
  collectionId: string;
4293
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4272
4294
  title: string;
4273
4295
  related: string[] | null;
4274
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4275
4296
  publishedAt: string | null;
4276
4297
  };
4277
4298
  meta: object;
@@ -4282,8 +4303,8 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4282
4303
  data: {
4283
4304
  data?: Record<string, unknown> | undefined;
4284
4305
  slug?: string | undefined;
4285
- title?: string | undefined;
4286
4306
  status?: "draft" | "waiting" | "ready" | "scheduled" | "published" | undefined;
4307
+ title?: string | undefined;
4287
4308
  publishedAt?: string | null | undefined;
4288
4309
  related?: string[] | undefined;
4289
4310
  };
@@ -4298,9 +4319,9 @@ declare const appRouter: _trpc_server.TRPCBuiltRouter<{
4298
4319
  legacyExtra: Record<string, unknown> | null;
4299
4320
  createdBy: string | null;
4300
4321
  collectionId: string;
4322
+ status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4301
4323
  title: string;
4302
4324
  related: string[] | null;
4303
- status: "draft" | "waiting" | "ready" | "scheduled" | "published";
4304
4325
  publishedAt: string | null;
4305
4326
  };
4306
4327
  meta: object;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{homedir as St}from"node:os";import{join as z}from"node:path";import{z as r}from"zod";import{Database as Ut}from"bun:sqlite";import{mkdirSync as Ot,existsSync as Nt}from"node:fs";import{drizzle as It}from"drizzle-orm/bun-sqlite";import{migrate as Dt}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as ue,uniqueIndex as Mt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as ee,FIELD_TYPES as pe}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as L,buildDataSchema as me}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as K,eq as d,and as M,isNull as q,gt as te,desc as R,or as ye,lt as he,isNotNull as fe}from"drizzle-orm";import{S3Client as kt,PutObjectCommand as ge,HeadObjectCommand as Tt,DeleteObjectsCommand as xt,GetObjectCommand as Rt}from"@aws-sdk/client-s3";import{getSignedUrl as we}from"@aws-sdk/s3-request-presigner";import{initTRPC as Ct,TRPCError as H}from"@trpc/server";import{randomBytes as ie,createHash as $t}from"node:crypto";import{SignJWT as Bt,jwtVerify as jt}from"jose";import{consola as Ee}from"consola";import{createInsertSchema as se,createUpdateSchema as F}from"drizzle-zod";import{nanoid as _e}from"nanoid";const $=r.string().min(1),Pt=r.object({COMMUN_DATA_DIR:r.string().default(z(St(),".commun")),COMMUN_MIGRATIONS_DIR:r.string().optional(),COMMUN_S3_ENDPOINT:r.string().optional(),COMMUN_S3_REGION:r.string().default("fr-par"),COMMUN_S3_BUCKET:$,COMMUN_S3_ACCESS_KEY:$,COMMUN_S3_SECRET_KEY:$,COMMUN_EMAIL_WEBHOOK_URL:$,COMMUN_EMAIL_WEBHOOK_TOKEN:r.string().optional(),COMMUN_ADMIN_URL:r.string().optional(),COMMUN_JWT_SECRET:$});function ve(i=process.env){return Pt.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 k=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),D=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),B=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),W=()=>o("legacy_extra",{mode:"json"}).$type(),zt=()=>o("status",{enum:ee}).notNull().default("draft"),Lt=()=>o("published_at"),be=r.object({street:r.string().optional(),postalCode:r.string().optional(),city:r.string().optional()}),U=I("organization",{id:ue("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:W(),createdAt:D(),updatedAt:B()}),y=I("users",{id:k(),email:o("email").notNull().unique(),name:o("name").notNull(),passwordHash:o("password_hash"),role:o("role",{enum:["admin","redacteur"]}).notNull().default("redacteur"),createdAt:D(),updatedAt:B()}),m=I("sessions",{id:k(),userId:o("user_id").notNull().references(()=>y.id,{onDelete:"cascade"}),expiresAt:o("expires_at").notNull(),revokedAt:o("revoked_at"),ua:o("ua"),ip:o("ip"),createdAt:D()}),b=I("invitations",{id:k(),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:D()}),f=I("api_tokens",{id:k(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:D()}),_=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:ue("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:W(),createdAt:D(),updatedAt:B()}),g=I("collection_definitions",{id:k(),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:W(),createdAt:D(),updatedAt:B()}),c=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>g.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:zt(),publishedAt:Lt(),legacyExtra:W(),createdAt:D(),updatedAt:B()},i=>[Mt("entries_slug_unique").on(i.collectionId,i.slug)]),Kt={__proto__:null,FIELD_TYPES:pe,PUBLICATION_STATUSES:ee,addressSchema:be,apiTokens:f,collectionDefinitions:g,entries:c,fieldDefinitionSchema:L,invitations:b,media:_,organization:U,sessions:m,users:y};function qt(){const i=import.meta.dir;return i?z(i,"..","..","..","drizzle"):void 0}function Ae(i,e){const t=e??qt();Ot(i,{recursive:!0});const s=new Ut(z(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:Kt});return t&&Nt(z(t,"meta","_journal.json"))&&Dt(n,{migrationsFolder:t}),n}class Z{constructor(e){this.config=e}static fromEnv(e){return new Z({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 Se{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run(K`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ue=168*3600,Ht="medias/";class Oe{constructor(e){this.config=e,this.client=new kt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,s){return we(this.client,new ge({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:s}),{expiresIn:Ue})}async put(e,t,s){await this.client.send(new ge({Bucket:this.config.bucket,Key:e,Body:t,ContentType:s}))}async head(e){try{return{size:(await this.client.send(new Tt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new xt({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Ht)?Promise.resolve(this.publicUrl(e)):we(this.client,new Rt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ue})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),s=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${s}`}}function Ne(i){return new Oe({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const E={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 w(i,e){return class extends Q{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const ne=Ct.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Q?{type:t.type}:{}}}}}),S=ne.router,Ft=ne.procedure,Ie=ne.middleware,Wt=Ie(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Q)throw new H({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Ft.use(Wt),De=i=>Ie(({ctx:e,next:t})=>{if(!e.session)throw new H({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new H({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),h=C.use(De()),v=C.use(De("admin")),Qt=S({ping:C.query(({ctx:i})=>i.services.health.check())}),Me=r.object({email:r.email(),password:r.string().min(1)}),ke=r.object({token:r.string().min(1),name:r.string().min(1).optional(),password:r.string().min(10)}),Te=r.object({email:r.email()}),xe=r.object({email:r.email(),role:r.enum(["admin","redacteur"])}),Re=r.object({id:r.string(),data:r.object({name:r.string().min(1).optional(),role:r.enum(["admin","redacteur"]).optional(),email:r.email().optional()})}),T=({id:i,email:e,name:t,role:s})=>({id:i,email:e,name:t,role:s}),Ce=r.object({name:r.string().min(1)});class $e{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(y).where(d(y.email,e)).get()}async findUserById(e){return this.db.select().from(y).where(d(y.id,e)).get()}async listUsers(){return this.db.select().from(y).all()}async hasAnyUser(){return this.db.select({id:y.id}).from(y).limit(1).all().length>0}async deleteUser(e){this.db.delete(y).where(d(y.id,e)).run()}async activateUser(e){const t=await this.findUserByEmail(e.email);return t?this.db.update(y).set({name:e.name,passwordHash:e.passwordHash,role:e.role}).where(d(y.id,t.id)).returning().get():this.db.insert(y).values(e).returning().get()}async insertSession(e){return this.db.insert(m).values(e).returning().get()}async findActiveSessionWithUser(e,t){return this.db.select({session:m,user:y}).from(m).innerJoin(y,d(y.id,m.userId)).where(M(d(m.id,e),q(m.revokedAt),te(m.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(m).set({revokedAt:t}).where(d(m.id,e)).run()}async findSessionById(e){return this.db.select().from(m).where(d(m.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(m).where(M(d(m.userId,e),q(m.revokedAt),te(m.expiresAt,t))).orderBy(R(m.createdAt)).all()}async updateUser(e,t){return this.db.update(y).set(t).where(d(y.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(b).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(b).where(M(d(b.tokenHash,e),q(b.usedAt),te(b.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(b).set({usedAt:t}).where(d(b.id,e)).run()}async insertApiToken(e){return this.db.insert(f).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(f).where(M(d(f.tokenHash,e),q(f.revokedAt))).get()}async touchApiToken(e,t){this.db.update(f).set({lastUsedAt:t}).where(d(f.id,e)).run()}async revokeApiToken(e,t){this.db.update(f).set({revokedAt:t}).where(d(f.id,e)).run()}async listApiTokens(){return this.db.select({id:f.id,name:f.name,lastUsedAt:f.lastUsedAt,revokedAt:f.revokedAt,createdAt:f.createdAt}).from(f).orderBy(R(f.createdAt)).all()}async purgeExpired(e){this.db.delete(m).where(ye(he(m.expiresAt,e),fe(m.revokedAt))).run(),this.db.delete(b).where(ye(he(b.expiresAt,e),fe(b.usedAt))).run()}}const re=w("user-not-found-error",E.NOT_FOUND),Be=w("session-not-found-error",E.NOT_FOUND),je=w("invitation-invalid-error",E.BAD_REQUEST),Pe=w("cannot-remove-self-error",E.BAD_REQUEST),ze=w("too-many-attempts-error",E.TOO_MANY_REQUESTS),j=i=>$t("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Yt=720*3600*1e3,Le=168*3600*1e3,Gt=Bun.password.hashSync("commun-dummy-password-for-timing"),Jt=5*6e4,Vt=10,P=new Map,Ke=i=>{const e=Date.now(),t=(P.get(i)??[]).filter(s=>e-s<Jt);return t.length?P.set(i,t):P.delete(i),t},Zt=i=>Ke(i).length>=Vt,Xt=i=>{P.set(i,[...Ke(i),Date.now()])},ei=i=>P.delete(i);class qe{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){Ee.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(Zt(n))throw new ze;const a=await this.repository.findUserByEmail(n),l=await this.verifyPassword(t,a?.passwordHash??Gt);return!a?.passwordHash||!l?(Xt(n),null):(ei(n),this.createSession(a,s))}async createSession(e,t){const s=new Date(Date.now()+Yt).toISOString(),n=await this.repository.insertSession({userId:e.id,expiresAt:s,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Bt({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 jt(e,this.jwtKey());if(typeof n.session!="string")return null;t=n.session}catch{return null}const s=await this.repository.findActiveSessionWithUser(t,O());return s?{sessionId:s.session.id,user:s.user,expiresAt:s.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,O())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,O())).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 Be(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ie(32).toString("base64url"),s=new Date(Date.now()+Le).toISOString();return await this.repository.insertInvitation({email:e.email.toLowerCase(),role:e.role,tokenHash:j(t),expiresAt:s}),await this.sendEmailEvent({email:e.email.toLowerCase(),eventName:"userInvited",eventProperties:{url:`${this.options.adminUrl??""}/welcome/${t}`}}),{token:t,expiresAt:s}}async requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const s=ie(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:j(s),expiresAt:new Date(Date.now()+Le).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(j(e),O());if(!s)throw new je;const n=await this.repository.findUserByEmail(s.email),a=t.name?.trim()||n?.name||s.email.split("@")[0]||"Membre",l=await this.repository.activateUser({email:s.email,name:a,passwordHash:await this.hashPassword(t.password),role:s.role});return await this.repository.markInvitationUsed(s.id,O()),l}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new re(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new Pe;await this.repository.deleteUser(t)}async updateUser(e,t){const s=await this.repository.updateUser(e,t);if(!s)throw new re(`user not found: ${e}`);return s}async createApiToken(e){const t=`commun_${ie(24).toString("base64url")}`,s=await this.repository.insertApiToken({name:e,tokenHash:j(t)});return{token:t,record:s}}async verifyApiToken(e){const t=await this.repository.findActiveApiToken(j(e));return t?(await this.repository.touchApiToken(t.id,O()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,O())}async listApiTokens(){return this.repository.listApiTokens()}}const He=S({login:C.input(Me).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new H({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:T(t.session.user)}}),logout:h.mutation(async({ctx:i})=>(await i.services.users.revokeSession(i.session.sessionId),{loggedOut:!0})),me:h.query(({ctx:i})=>({user:T(i.session.user)})),sessions:S({list:h.query(({ctx:i})=>i.services.users.listSessions(i.session.user.id,i.session.sessionId)),revoke:h.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:C.input(ke).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:T(t)}}),requestPasswordReset:C.input(Te).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Fe=S({list:v.query(async({ctx:i})=>(await i.services.users.listUsers()).map(T)),directory:h.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:v.input(r.object({id:r.string()})).query(async({ctx:i,input:e})=>T(await i.services.users.getUser(e.id))),invite:v.input(xe).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:v.input(Re).mutation(async({ctx:i,input:e})=>T(await i.services.users.updateUser(e.id,e.data))),remove:v.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}))}),We=S({list:v.query(({ctx:i})=>i.services.users.listApiTokens()),create:v.input(Ce).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:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Qe={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ti={createdBy:!0,updatedBy:!0},oe={...Qe,...ti},Ye={...Qe,updatedBy:!0},Ge=se(U).omit(Ye),Je=F(U).omit(Ye);class Ve{constructor(e){this.db=e}async get(){return this.db.select().from(U).where(d(U.id,1)).get()}async insert(e){return this.db.insert(U).values({...e,id:1}).returning().get()}async update(e){return this.db.update(U).set(e).where(d(U.id,1)).returning().get()}}const Ze=w("organization-not-initialized-error",E.NOT_FOUND),Xe=w("organization-already-initialized-error",E.BAD_REQUEST),et=w("deploy-hook-missing-error",E.BAD_REQUEST),ae=w("deploy-failed-error",E.INTERNAL_SERVER_ERROR),ii=3e4;class tt{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 Xe;return this.repository.insert(e)}async update(e,t){const s=await this.repository.update({...e,updatedBy:t??null});if(!s)throw new Ze;return s}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new et;const t=this.options.fetchImpl??fetch;let s;try{s=await t(e,{signal:AbortSignal.timeout(ii)})}catch(n){throw new ae(`deploy hook unreachable: ${n instanceof Error?n.message:String(n)}`)}if(!s.ok)throw new ae(`deploy hook: ${s.status} ${s.statusText}`);return{status:s.status}}}const it=S({get:h.query(({ctx:i})=>i.services.organization.get()),init:v.input(Ge).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:v.input(Je).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:h.mutation(({ctx:i})=>i.services.organization.deploy())}),st=r.object({filename:r.string().min(1),mime:r.string().min(1),metaData:r.record(r.string(),r.string()).optional()}),nt=r.object({key:r.string().min(1),filename:r.string().min(1),mime:r.string().min(1),alt:r.string().optional(),metaData:r.record(r.string(),r.unknown()).optional()}),rt=F(_).pick({alt:!0,caption:!0,filename:!0});class ot{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(d(_.id,e)).get()}async list(){return this.db.select().from(_).orderBy(R(_.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(_).where(K`json_extract(${_.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(_).set(t).where(d(_.id,e)).returning().get()}async delete(e){this.db.delete(_).where(d(_.id,e)).run()}}const Y=w("media-not-found-error",E.NOT_FOUND),de=w("unsupported-mime-error",E.BAD_REQUEST),at=w("upload-incomplete-error",E.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"]),dt=["webp-1800","webp-1320","webp-840","webp-480","webp-1320-thumb","webp-840-thumb","webp-480-thumb"],le=i=>i.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-120)||"file",ct="medias/";class lt{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,s){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const n=`${ct}${_e(10)}/${le(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 at(`object not found in storage: ${e.key}`);const n=await this.repository.insert({filename:le(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 Ee.info(`[media] resize \xE0 impl\xE9menter pour ${n.id} (${dt.join(", ")})`),n}async uploadDirect(e,t,s,n,a){if(!ce.has(t))throw new de(`unsupported mime type: ${t}`);const l=`${ct}${_e(10)}/${le(e)}`;return await this.storage.put(l,s,t),this.finalize({key:l,filename:e,mime:t,metaData:n},a)}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 Y(`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 Y(`media not found: ${e}`);return n}async remove(e){const t=await this.repository.findById(e);if(!t)throw new Y(`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 toLegacyMedia(e){const t=await this.repository.findById(e);if(!t)return null;const s=t.objects.original,n=await this.storage.url(s),a={original:n},l=s.match(/^(.*)-original\.[^.]+$/)?.[1];for(const u of dt)a[u]=l?await this.storage.url(`${l}-${u}.webp`):n;return{_id:t.id,id:t.id,originalName:t.filename,mime:t.mime,...t.metaData?{metaData:t.metaData}:{},objects:a}}async resolveMediaPlaceholders(e){const t=n=>typeof n=="string"&&n.startsWith("_media:"),s=async n=>(await Promise.all(n.map(a=>this.toLegacyMedia(a.slice(7))))).filter(a=>a!==null);if(t(e))return s([e]);if(Array.isArray(e))return e.length>0&&e.every(t)?s(e):Promise.all(e.map(n=>this.resolveMediaPlaceholders(n)));if(e!==null&&typeof e=="object"){const n={};for(const[a,l]of Object.entries(e))n[a]=await this.resolveMediaPlaceholders(l);return n}return e}async objectUrls(e){const t=e.objects,s={original:await this.storage.url(t.original)};for(const[n,a]of Object.entries(t.variants??{}))s[n]=await this.storage.url(a);return s}}const ut=S({requestUpload:h.input(st).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:h.input(nt).mutation(({ctx:i,input:e})=>i.services.media.finalize(e,i.session.user.id)),list:h.query(({ctx:i})=>i.services.media.listResolved()),get:h.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.media.get(e.id)),update:h.input(r.object({id:r.string(),data:rt})).mutation(({ctx:i,input:e})=>i.services.media.updateEditorial(e.id,e.data,i.session.user.id)),remove:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.media.remove(e.id),{removed:e.id}))}),pt=se(g).omit(oe).extend({fields:r.array(L).min(1),slug:r.string().optional()}),mt=F(g).omit(oe).extend({fields:r.array(L).min(1).optional()}),yt={...oe,related:!0,collectionId:!0},ht=se(c).omit(yt).extend({slug:r.string().optional()}),ft=F(c).omit(yt).extend({related:r.array(r.string()).optional()});class gt{constructor(e){this.db=e}async list(){return this.db.select().from(g).all()}async findBySlug(e){return this.db.select().from(g).where(d(g.slug,e)).get()}async findById(e){return this.db.select().from(g).where(d(g.id,e)).get()}async findByLegacyId(e){return this.db.select().from(g).where(K`json_extract(${g.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(g).values(e).returning().get()}async update(e,t){return this.db.update(g).set(t).where(d(g.id,e)).returning().get()}async delete(e){return this.db.delete(g).where(d(g.id,e)).returning().get()}}class wt{constructor(e){this.db=e}async list(e){return this.db.select().from(c).where(d(c.collectionId,e)).orderBy(R(c.updatedAt)).all()}async listPaginated(e,t){return this.db.select().from(c).where(d(c.collectionId,e)).orderBy(R(c.updatedAt)).limit(t.limit).offset(t.skip).all()}async listPublished(e){return this.db.select().from(c).where(M(d(c.collectionId,e),d(c.status,"published"))).orderBy(R(c.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(c).where(M(d(c.collectionId,e),d(c.slug,t))).get()}async findById(e){return this.db.select().from(c).where(d(c.id,e)).get()}async findByDataField(e,t,s){return this.db.select().from(c).where(M(d(c.collectionId,e),K`json_extract(${c.data}, ${`$.${t}`}) = ${s}`)).get()}async insert(e){return this.db.insert(c).values(e).returning().get()}async update(e,t){return this.db.update(c).set(t).where(d(c.id,e)).returning().get()}async delete(e){return this.db.delete(c).where(d(c.id,e)).returning().get()}}const G=w("collection-not-found-error",E.NOT_FOUND),J=w("entry-not-found-error",E.NOT_FOUND),Et=w("invalid-entry-data-error",E.BAD_REQUEST),_t=w("duplicate-slug-error",E.BAD_REQUEST);function vt(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function V(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(a=>typeof a=="string"))}return[...new Set(t)]}class bt{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 G(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(vt(e.name)),createdBy:t??null,updatedBy:t??null})}async updateDefinition(e,t,s){const n=await this.definitions.update(e,{...t,updatedBy:s??null});if(!n)throw new G(`collection not found: ${e}`);return n}async removeDefinition(e){if(!await this.definitions.delete(e))throw new G(`collection not found: ${e}`)}validateData(e,t){const s=me(e.fields).safeParse(t);if(!s.success)throw new Et(`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 J(`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})}async listPublishedEntries(e){return this.entries.listPublished((await this.getDefinition(e)).id)}async createEntry(e,t,s){const n=await this.getDefinition(e),a=this.validateData(n,t.data),l=await this.uniqueEntrySlug(n.id,t.slug||vt(t.title)),u=await this.entries.insert({...t,slug:l,data:a,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,u.id,[],V(n.fields,a)),u}async updateEntry(e,t,s){const n=await this.entries.findById(e);if(!n)throw new J(`entry not found: ${e}`);const a=await this.getDefinition(n.collectionId),l=new Set(a.fields.map(A=>A.name)),u=Object.fromEntries(Object.entries(n.data??{}).filter(([A])=>!l.has(A))),p=t.data?{...n.data,...t.data}:n.data,N=Object.fromEntries(Object.entries(p).filter(([A])=>l.has(A)||A in(t.data??{}))),x=t.data?{...u,...this.validateData(a,N)}:void 0,X={...t,updatedBy:s??null};x&&(X.data=x),t.status==="published"&&!t.publishedAt&&(X.publishedAt=new Date().toISOString());try{const A=await this.entries.update(e,X);return x&&await this.linkRelations(a,e,V(a.fields,n.data),V(a.fields,x)),t.related&&await this.linkRelations(a,e,n.related??[],t.related),A}catch(A){throw this.mapSlugConflict(A,a.slug,t.slug??n.slug)}}async removeEntry(e){const t=await this.entries.findById(e);if(!t)throw new J(`entry not found: ${e}`);const s=await this.getDefinition(t.collectionId);await this.linkRelations(s,e,V(s.fields,t.data),[]),await this.entries.delete(e)}async resolveEntryData(e,t){const s={};for(const n of e.fields){if(n.hidden)continue;const a=t.data[n.name];if(a==null){s[n.name]=a;continue}switch(n.type){case"rich-text":s[n.name]=JSON.stringify(await this.resolveRichTextMedia(a));break;case"steps":{const l=Array.isArray(a)?a:[];s[n.name]=await Promise.all(l.map(async u=>{const p=u;return p.content==null?p:{...p,content:JSON.stringify(await this.resolveRichTextMedia(p.content))}}));break}case"media":{const l=Array.isArray(a)?a:[a],u=await Promise.all(l.filter(p=>typeof p=="string"&&p.length>0).sort().map(p=>this.media.toLegacyMedia(p)));s[n.name]=u.filter(p=>p!==null);break}default:s[n.name]=a}}return s}async resolveRichTextMedia(e){if(Array.isArray(e))return Promise.all(e.map(n=>this.resolveRichTextMedia(n)));if(e===null||typeof e!="object")return e;const t={...e},s=t.attrs;if((t.type==="image"||t.type==="file")&&s&&typeof s.id=="string"&&s.id){const n=await this.media.toLegacyMedia(s.id);t.attrs={...s,mediaRecord:n,src:n?.objects.original??null}}return Array.isArray(t.content)&&(t.content=await this.resolveRichTextMedia(t.content)),t}hasEmptySchedules(e){const t=e.data.schedules??e.legacyExtra?.schedules;return t!==void 0&&(t.periods?.length??0)===0}async legacyRecordsPayload(){const e={};for(const t of await this.definitions.list()){const s=await this.entries.listPublished(t.id);for(const n of s)t.slug==="events"&&this.hasEmptySchedules(n)||(e[n.id]={_id:n.id,title:n.title,slug:n.slug,relatedCollection:t.slug,...n.publishedAt!=null?{publishedAt:n.publishedAt}:{},...await this.resolveEntryData(t,n),records:n.related??[]})}return e}async publishedSlugs(){const e=[];for(const t of await this.definitions.list()){const s=await this.entries.listPublished(t.id);e.push(...s.map(n=>`/${t.slug}/${n.slug}`))}return e}mapSlugConflict(e,t,s){return e instanceof Error&&e.message.includes("UNIQUE constraint failed")&&e.message.includes("entries.slug")?new _t(`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 a=n.filter(u=>!s.includes(u)),l=s.filter(u=>!n.includes(u));for(const u of a){const p=await this.entries.findById(u);if(!p)continue;const N=new Set(p.related??[]);N.add(t),await this.entries.update(u,{related:[...N]})}for(const u of l){const p=await this.entries.findById(u);p&&await this.entries.update(u,{related:(p.related??[]).filter(N=>N!==t)})}}}const At=S({list:h.query(({ctx:i})=>i.services.collections.listDefinitions()),get:h.input(r.object({idOrSlug:r.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:v.input(pt).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:v.input(r.object({id:r.string(),data:mt})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:v.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:S({get:h.input(r.object({id:r.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:h.input(r.object({collectionId:r.string(),skip:r.number().int().min(0).optional(),limit:r.number().int().min(1).max(100).optional()})).query(({ctx:i,input:e})=>i.services.collections.listEntriesPaginated(e.collectionId,e)),create:h.input(r.object({collectionId:r.string(),data:ht})).mutation(({ctx:i,input:e})=>i.services.collections.createEntry(e.collectionId,e.data,i.session.user.id)),update:h.input(r.object({id:r.string(),data:ft})).mutation(({ctx:i,input:e})=>i.services.collections.updateEntry(e.id,e.data,i.session.user.id)),remove:h.input(r.object({id:r.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeEntry(e.id),{removed:e.id}))})});function si({env:i}={}){const e=i??ve(),t=Ae(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),s=Ne(e),n=Z.fromEnv(e),a=new qe(new $e(t),{email:n,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),l=new ot(t),u=new lt(l,s),p=new bt(new gt(t),new wt(t),u),N=new tt(new Ve(t)),x={health:new Se(t),users:a,organization:N,media:u,collections:p};return{env:e,db:t,storage:s,services:x}}const ni=S({health:Qt,auth:He,users:Fe,apiTokens:We,organization:it,media:ut,collections:At});export{ce as ALLOWED_MIME,Pe as CannotRemoveSelfError,G as CollectionNotFoundError,bt as CollectionsService,gt as DefinitionRepository,ae as DeployFailedError,et as DeployHookMissingError,Q as DomainError,_t as DuplicateSlugError,Z as EmailService,J as EntryNotFoundError,wt as EntryRepository,pe as FIELD_TYPES,Se as HealthService,Et as InvalidEntryDataError,je as InvitationInvalidError,Y as MediaNotFoundError,ot as MediaRepository,lt as MediaService,Xe as OrganizationAlreadyInitializedError,Ze as OrganizationNotInitializedError,Ve as OrganizationRepository,tt as OrganizationService,ee as PUBLICATION_STATUSES,Oe as S3Storage,Be as SessionNotFoundError,ze as TooManyAttemptsError,de as UnsupportedMimeError,at as UploadIncompleteError,re as UserNotFoundError,$e as UsersRepository,qe as UsersService,ke as acceptInvitationDto,be as addressSchema,Ce as apiTokenCreateDto,f as apiTokens,We as apiTokensRouter,ni as appRouter,He as authRouter,me as buildDataSchema,g as collectionDefinitions,At as collectionsRouter,Ae as connectDb,si as createCore,Ne as createStorage,w as createTypedError,pt as definitionCreateDto,mt as definitionUpdateDto,c as entries,ht as entryCreateDto,ft as entryUpdateDto,L as fieldDefinitionSchema,b as invitations,xe as inviteDto,Me as loginDto,_ as media,nt as mediaFinalizeDto,st as mediaRequestUploadDto,ut as mediaRouter,rt as mediaUpdateDto,U as organization,Ge as organizationInitDto,it as organizationRouter,Je as organizationUpdateDto,ve as parseEnv,Te as requestPasswordResetDto,m as sessions,T as toPublicUser,Re as userUpdateDto,y as users,Fe as usersRouter};
1
+ import{homedir as Ut}from"node:os";import{join as K}from"node:path";import{z as s}from"zod";import{Database as Ot}from"bun:sqlite";import{mkdirSync as Nt,existsSync as It}from"node:fs";import{drizzle as Dt}from"drizzle-orm/bun-sqlite";import{migrate as Mt}from"drizzle-orm/bun-sqlite/migrator";import{sqliteTable as I,text as o,integer as pe,uniqueIndex as kt}from"drizzle-orm/sqlite-core";import{PUBLICATION_STATUSES as B,FIELD_TYPES as me}from"./domains/collections/constants.mjs";import{fieldDefinitionSchema as L,buildDataSchema as he}from"./domains/collections/utils.mjs";export{FIELD_VALUE_SCHEMAS}from"./domains/collections/utils.mjs";import{sql as $,eq as a,and as D,isNull as H,gt as te,desc as R,or as ie,lt as ye,isNotNull as ge,inArray as xt,like as we,asc as fe}from"drizzle-orm";import{S3Client as Tt,PutObjectCommand as Ee,HeadObjectCommand as Rt,DeleteObjectsCommand as Ct,GetObjectCommand as Bt}from"@aws-sdk/client-s3";import{getSignedUrl as _e}from"@aws-sdk/s3-request-presigner";import{initTRPC as $t,TRPCError as F}from"@trpc/server";import{randomBytes as ne,createHash as jt}from"node:crypto";import{SignJWT as Pt,jwtVerify as zt}from"jose";import{consola as ve}from"consola";import{createInsertSchema as se,createUpdateSchema as W}from"drizzle-zod";import{nanoid as Se}from"nanoid";const j=s.string().min(1),qt=s.object({COMMUN_DATA_DIR:s.string().default(K(Ut(),".commun")),COMMUN_MIGRATIONS_DIR:s.string().optional(),COMMUN_S3_ENDPOINT:s.string().optional(),COMMUN_S3_REGION:s.string().default("fr-par"),COMMUN_S3_BUCKET:j,COMMUN_S3_ACCESS_KEY:j,COMMUN_S3_SECRET_KEY:j,COMMUN_EMAIL_WEBHOOK_URL:j,COMMUN_EMAIL_WEBHOOK_TOKEN:s.string().optional(),COMMUN_ADMIN_URL:s.string().optional(),COMMUN_JWT_SECRET:j});function be(i=process.env){return qt.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 k=()=>o("id").primaryKey().$defaultFn(()=>crypto.randomUUID()),M=()=>o("created_at").notNull().$defaultFn(()=>new Date().toISOString()),P=()=>o("updated_at").notNull().$defaultFn(()=>new Date().toISOString()).$onUpdateFn(()=>new Date().toISOString()),Q=()=>o("legacy_extra",{mode:"json"}).$type(),Kt=()=>o("status",{enum:B}).notNull().default("draft"),Lt=()=>o("published_at"),Ae=s.object({street:s.string().optional(),postalCode:s.string().optional(),city:s.string().optional()}),U=I("organization",{id:pe("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:Q(),createdAt:M(),updatedAt:P()}),p=I("users",{id:k(),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:P()}),l=I("sessions",{id:k(),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()}),v=I("invitations",{id:k(),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()}),h=I("api_tokens",{id:k(),name:o("name").notNull(),tokenHash:o("token_hash").notNull().unique(),lastUsedAt:o("last_used_at"),revokedAt:o("revoked_at"),createdAt:M()}),E=I("media",{id:k(),filename:o("filename").notNull(),mime:o("mime").notNull(),size:pe("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:Q(),createdAt:M(),updatedAt:P()}),y=I("collection_definitions",{id:k(),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:Q(),createdAt:M(),updatedAt:P()}),c=I("entries",{id:k(),collectionId:o("collection_id").notNull().references(()=>y.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:Kt(),publishedAt:Lt(),legacyExtra:Q(),createdAt:M(),updatedAt:P()},i=>[kt("entries_slug_unique").on(i.collectionId,i.slug)]),Ht={__proto__:null,FIELD_TYPES:me,PUBLICATION_STATUSES:B,addressSchema:Ae,apiTokens:h,collectionDefinitions:y,entries:c,fieldDefinitionSchema:L,invitations:v,media:E,organization:U,sessions:l,users:p};function Ft(){const i=import.meta.dir;return i?K(i,"..","..","..","drizzle"):void 0}function Ue(i,e){const t=e??Ft();Nt(i,{recursive:!0});const n=new Ot(K(i,"commun.db"));n.exec("PRAGMA journal_mode=WAL"),n.exec("PRAGMA foreign_keys=ON"),n.exec("PRAGMA busy_timeout=5000");const r=Dt({client:n,schema:Ht});return t&&It(K(t,"meta","_journal.json"))&&Mt(r,{migrationsFolder:t}),r}class X{constructor(e){this.config=e}static fromEnv(e){return new X({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 Oe{constructor(e){this.db=e}async check(){let e=!0;try{this.db.run($`select 1`)}catch{e=!1}return{status:e?"ok":"degraded",service:"@open-commune/core",time:new Date().toISOString(),db:{ok:e}}}}const Ne=168*3600,Wt="medias/";class Ie{constructor(e){this.config=e,this.client=new Tt({region:e.region,...e.endpoint?{endpoint:e.endpoint,forcePathStyle:!0}:{},credentials:{accessKeyId:e.accessKey,secretAccessKey:e.secretKey}})}client;presignedPutUrl(e,t,n){return _e(this.client,new Ee({Bucket:this.config.bucket,Key:e,ContentType:t,Metadata:n}),{expiresIn:Ne})}async put(e,t,n){await this.client.send(new Ee({Bucket:this.config.bucket,Key:e,Body:t,ContentType:n}))}async head(e){try{return{size:(await this.client.send(new Rt({Bucket:this.config.bucket,Key:e}))).ContentLength??0}}catch{return null}}async remove(e){e.length!==0&&await this.client.send(new Ct({Bucket:this.config.bucket,Delete:{Objects:e.map(t=>({Key:t}))}}))}url(e){return e.startsWith(Wt)?Promise.resolve(this.publicUrl(e)):_e(this.client,new Bt({Bucket:this.config.bucket,Key:e}),{expiresIn:Ne})}publicUrl(e){const t=(this.config.endpoint??`https://s3.${this.config.region}.scw.cloud`).replace(/\/+$/,""),n=e.split("/").map(encodeURIComponent).join("/");return`${t}/${this.config.bucket}/${n}`}}function De(i){return new Ie({endpoint:i.COMMUN_S3_ENDPOINT||void 0,region:i.COMMUN_S3_REGION,bucket:i.COMMUN_S3_BUCKET,accessKey:i.COMMUN_S3_ACCESS_KEY,secretKey:i.COMMUN_S3_SECRET_KEY})}const w={NOT_FOUND:"NOT_FOUND",BAD_REQUEST:"BAD_REQUEST",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS",INTERNAL_SERVER_ERROR:"INTERNAL_SERVER_ERROR"};class Y extends Error{}function g(i,e){return class extends Y{type=i;trpcCode=e;constructor(t){super(t??i),this.name=i}}}const re=$t.context().create({errorFormatter({shape:i,error:e}){const t=e.cause;return{...i,data:{...i.data,...t instanceof Y?{type:t.type}:{}}}}}),b=re.router,Qt=re.procedure,Me=re.middleware,Yt=Me(async({next:i})=>{const e=await i();if(!e.ok){const t=e.error.cause;if(t instanceof Y)throw new F({code:t.trpcCode,message:t.message,cause:t})}return e}),C=Qt.use(Yt),ke=i=>Me(({ctx:e,next:t})=>{if(!e.session)throw new F({code:"UNAUTHORIZED"});if(i&&e.session.user.role!==i)throw new F({code:"FORBIDDEN"});return t({ctx:{...e,session:e.session}})}),u=C.use(ke()),_=C.use(ke("admin")),Gt=b({ping:C.query(({ctx:i})=>i.services.health.check())}),xe=s.object({email:s.email(),password:s.string().min(1)}),Te=s.object({token:s.string().min(1),name:s.string().min(1).optional(),password:s.string().min(10)}),Re=s.object({email:s.email()}),Ce=s.object({email:s.email(),role:s.enum(["admin","redacteur"])}),Be=s.object({id:s.string(),data:s.object({name:s.string().min(1).optional(),role:s.enum(["admin","redacteur"]).optional(),email:s.email().optional()})}),x=({id:i,email:e,name:t,role:n})=>({id:i,email:e,name:t,role:n}),$e=s.object({name:s.string().min(1)});class je{constructor(e){this.db=e}async findUserByEmail(e){return this.db.select().from(p).where(a(p.email,e)).get()}async findUserById(e){return this.db.select().from(p).where(a(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(a(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(a(p.id,t.id)).returning().get():this.db.insert(p).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:p}).from(l).innerJoin(p,a(p.id,l.userId)).where(D(a(l.id,e),H(l.revokedAt),te(l.expiresAt,t))).get()}async revokeSession(e,t){this.db.update(l).set({revokedAt:t}).where(a(l.id,e)).run()}async findSessionById(e){return this.db.select().from(l).where(a(l.id,e)).get()}async listActiveSessionsByUser(e,t){return this.db.select().from(l).where(D(a(l.userId,e),H(l.revokedAt),te(l.expiresAt,t))).orderBy(R(l.createdAt)).all()}async updateUser(e,t){return this.db.update(p).set(t).where(a(p.id,e)).returning().get()}async insertInvitation(e){return this.db.insert(v).values(e).returning().get()}async findValidInvitation(e,t){return this.db.select().from(v).where(D(a(v.tokenHash,e),H(v.usedAt),te(v.expiresAt,t))).get()}async markInvitationUsed(e,t){this.db.update(v).set({usedAt:t}).where(a(v.id,e)).run()}async insertApiToken(e){return this.db.insert(h).values(e).returning().get()}async findActiveApiToken(e){return this.db.select().from(h).where(D(a(h.tokenHash,e),H(h.revokedAt))).get()}async touchApiToken(e,t){this.db.update(h).set({lastUsedAt:t}).where(a(h.id,e)).run()}async revokeApiToken(e,t){this.db.update(h).set({revokedAt:t}).where(a(h.id,e)).run()}async listApiTokens(){return this.db.select({id:h.id,name:h.name,lastUsedAt:h.lastUsedAt,revokedAt:h.revokedAt,createdAt:h.createdAt}).from(h).orderBy(R(h.createdAt)).all()}async purgeExpired(e){this.db.delete(l).where(ie(ye(l.expiresAt,e),ge(l.revokedAt))).run(),this.db.delete(v).where(ie(ye(v.expiresAt,e),ge(v.usedAt))).run()}}const oe=g("user-not-found-error",w.NOT_FOUND),Pe=g("session-not-found-error",w.NOT_FOUND),ze=g("invitation-invalid-error",w.BAD_REQUEST),qe=g("cannot-remove-self-error",w.BAD_REQUEST),Ke=g("too-many-attempts-error",w.TOO_MANY_REQUESTS),z=i=>jt("sha256").update(i).digest("hex"),O=()=>new Date().toISOString(),Jt=720*3600*1e3,Le=168*3600*1e3,Vt=Bun.password.hashSync("commun-dummy-password-for-timing"),Zt=5*6e4,Xt=10,q=new Map,He=i=>{const e=Date.now(),t=(q.get(i)??[]).filter(n=>e-n<Zt);return t.length?q.set(i,t):q.delete(i),t},ei=i=>He(i).length>=Xt,ti=i=>{q.set(i,[...He(i),Date.now()])},ii=i=>q.delete(i);class Fe{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){ve.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(ei(r))throw new Ke;const d=await this.repository.findUserByEmail(r),f=await this.verifyPassword(t,d?.passwordHash??Vt);return!d?.passwordHash||!f?(ti(r),null):(ii(r),this.createSession(d,n))}async createSession(e,t){const n=new Date(Date.now()+Jt).toISOString(),r=await this.repository.insertSession({userId:e.id,expiresAt:n,ua:t?.ua??null,ip:t?.ip??null});return{token:await new Pt({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,O());return n?{sessionId:n.session.id,user:n.user,expiresAt:n.session.expiresAt}:null}async revokeSession(e){await this.repository.revokeSession(e,O())}async listSessions(e,t){return(await this.repository.listActiveSessionsByUser(e,O())).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 Pe(`session not found: ${t}`);await this.repository.revokeSession(t,O())}async purgeExpired(){await this.repository.purgeExpired(O())}async createInvitation(e){const t=ne(32).toString("base64url"),n=new Date(Date.now()+Le).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 requestPasswordReset(e){const t=await this.repository.findUserByEmail(e.toLowerCase());if(!t?.passwordHash)return;const n=ne(32).toString("base64url");await this.repository.insertInvitation({email:t.email,role:t.role,tokenHash:z(n),expiresAt:new Date(Date.now()+Le).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),O());if(!n)throw new ze;const r=await this.repository.findUserByEmail(n.email),d=t.name?.trim()||r?.name||n.email.split("@")[0]||"Membre",f=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,O()),f}async listUsers(){return this.repository.listUsers()}async getUser(e){const t=await this.repository.findUserById(e);if(!t)throw new oe(`user not found: ${e}`);return t}async hasAnyUser(){return this.repository.hasAnyUser()}async removeUser(e,t){if(t===e)throw new qe;await this.repository.deleteUser(t)}async updateUser(e,t){const n=await this.repository.updateUser(e,t);if(!n)throw new oe(`user not found: ${e}`);return n}async createApiToken(e){const t=`commun_${ne(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,O()),!0):!1}async revokeApiToken(e){await this.repository.revokeApiToken(e,O())}async listApiTokens(){return this.repository.listApiTokens()}}const We=b({login:C.input(xe).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.login(e.email,e.password,i.requestMeta);if(!t)throw new F({code:"UNAUTHORIZED",message:"invalid credentials"});return{token:t.token,expiresAt:t.session.expiresAt,user:x(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:x(i.session.user)})),sessions:b({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:C.input(Te).mutation(async({ctx:i,input:e})=>{const t=await i.services.users.acceptInvitation(e.token,e);return{user:x(t)}}),requestPasswordReset:C.input(Re).mutation(async({ctx:i,input:e})=>(await i.services.users.requestPasswordReset(e.email),{ok:!0}))}),Qe=b({list:_.query(async({ctx:i})=>(await i.services.users.listUsers()).map(x)),directory:u.query(async({ctx:i})=>(await i.services.users.listUsers()).map(({id:e,name:t})=>({id:e,name:t}))),get:_.input(s.object({id:s.string()})).query(async({ctx:i,input:e})=>x(await i.services.users.getUser(e.id))),invite:_.input(Ce).mutation(({ctx:i,input:e})=>i.services.users.createInvitation(e)),update:_.input(Be).mutation(async({ctx:i,input:e})=>x(await i.services.users.updateUser(e.id,e.data))),remove:_.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}))}),Ye=b({list:_.query(({ctx:i})=>i.services.users.listApiTokens()),create:_.input($e).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:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.users.revokeApiToken(e.id),{revoked:e.id}))}),Ge={id:!0,createdAt:!0,updatedAt:!0,legacyExtra:!0},ni={createdBy:!0,updatedBy:!0},ae={...Ge,...ni},Je={...Ge,updatedBy:!0},Ve=se(U).omit(Je),Ze=W(U).omit(Je);class Xe{constructor(e){this.db=e}async get(){return this.db.select().from(U).where(a(U.id,1)).get()}async insert(e){return this.db.insert(U).values({...e,id:1}).returning().get()}async update(e){return this.db.update(U).set(e).where(a(U.id,1)).returning().get()}}const et=g("organization-not-initialized-error",w.NOT_FOUND),tt=g("organization-already-initialized-error",w.BAD_REQUEST),it=g("deploy-hook-missing-error",w.BAD_REQUEST),ce=g("deploy-failed-error",w.INTERNAL_SERVER_ERROR),si=3e4;class nt{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 tt;return this.repository.insert(e)}async update(e,t){const n=await this.repository.update({...e,updatedBy:t??null});if(!n)throw new et;return n}async deploy(){const e=(await this.get())?.deployment?.vercel?.hook;if(!e)throw new it;const t=this.options.fetchImpl??fetch;let n;try{n=await t(e,{signal:AbortSignal.timeout(si)})}catch(r){throw new ce(`deploy hook unreachable: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new ce(`deploy hook: ${n.status} ${n.statusText}`);return{status:n.status}}}const st=b({get:u.query(({ctx:i})=>i.services.organization.get()),init:_.input(Ve).mutation(({ctx:i,input:e})=>i.services.organization.init(e)),update:_.input(Ze).mutation(({ctx:i,input:e})=>i.services.organization.update(e,i.session.user.id)),deploy:u.mutation(({ctx:i})=>i.services.organization.deploy())}),rt=s.object({filename:s.string().min(1),mime:s.string().min(1),metaData:s.record(s.string(),s.string()).optional()}),ot=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()}),at=W(E).pick({alt:!0,caption:!0,filename:!0});class ct{constructor(e){this.db=e}async insert(e){return this.db.insert(E).values(e).returning().get()}async findById(e){return this.db.select().from(E).where(a(E.id,e)).get()}async list(){return this.db.select().from(E).orderBy(R(E.createdAt)).all()}async findByMetaData(e,t){return this.db.select().from(E).where($`json_extract(${E.metaData}, ${`$.${e}`}) = ${t}`).get()}async update(e,t){return this.db.update(E).set(t).where(a(E.id,e)).returning().get()}async delete(e){this.db.delete(E).where(a(E.id,e)).run()}}const G=g("media-not-found-error",w.NOT_FOUND),de=g("unsupported-mime-error",w.BAD_REQUEST),dt=g("upload-incomplete-error",w.BAD_REQUEST),le=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"]),ri=["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",lt="medias/";class ut{constructor(e,t){this.repository=e,this.storage=t}async requestUpload(e,t,n){if(!le.has(t))throw new de(`unsupported mime type: ${t}`);const r=`${lt}${Se(10)}/${ue(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 dt(`object not found in storage: ${e.key}`);const r=await this.repository.insert({filename:ue(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 ve.info(`[media] resize \xE0 impl\xE9menter pour ${r.id} (${ri.join(", ")})`),r}async uploadDirect(e,t,n,r,d){if(!le.has(t))throw new de(`unsupported mime type: ${t}`);const f=`${lt}${Se(10)}/${ue(e)}`;return await this.storage.put(f,n,t),this.finalize({key:f,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 G(`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 G(`media not found: ${e}`);return r}async remove(e){const t=await this.repository.findById(e);if(!t)throw new G(`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 pt=b({requestUpload:u.input(rt).mutation(({ctx:i,input:e})=>i.services.media.requestUpload(e.filename,e.mime,e.metaData)),finalize:u.input(ot).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:at})).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}))}),mt=se(y).omit(ae).extend({fields:s.array(L).min(1),slug:s.string().optional()}),ht=W(y).omit(ae).extend({fields:s.array(L).min(1).optional()}),yt={...ae,related:!0,collectionId:!0},gt=se(c).omit(yt).extend({slug:s.string().optional()}),wt=W(c).omit(yt).extend({related:s.array(s.string()).optional()});class ft{constructor(e){this.db=e}async list(){return this.db.select().from(y).all()}async findBySlug(e){return this.db.select().from(y).where(a(y.slug,e)).get()}async findById(e){return this.db.select().from(y).where(a(y.id,e)).get()}async findByLegacyId(e){return this.db.select().from(y).where($`json_extract(${y.legacyExtra}, '$.legacyId') = ${e}`).get()}async insert(e){return this.db.insert(y).values(e).returning().get()}async update(e,t){return this.db.update(y).set(t).where(a(y.id,e)).returning().get()}async delete(e){return this.db.delete(y).where(a(y.id,e)).returning().get()}}class Et{constructor(e){this.db=e}async list(e){return this.db.select().from(c).where(a(c.collectionId,e)).orderBy(R(c.updatedAt)).all()}narrowing(e){const t=[a(c.collectionId,e.collectionId)];if(e.status?.length&&t.push(xt(c.status,e.status)),e.search?.trim()){const n=`%${e.search.trim()}%`;t.push(ie(we(c.title,n),we(c.data,n)))}return D(...t)}async countMatching(e){const[t]=this.db.select({total:$`count(*)`}).from(c).where(this.narrowing(e)).all();return t?.total??0}async listPaginated(e,t){const n={recent:R(c.updatedAt),oldest:fe(c.updatedAt),title:fe(c.title)};return this.db.select().from(c).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(c).where(D(a(c.collectionId,e),a(c.status,"published"))).orderBy(R(c.createdAt)).all()}async findBySlug(e,t){return this.db.select().from(c).where(D(a(c.collectionId,e),a(c.slug,t))).get()}async findById(e){return this.db.select().from(c).where(a(c.id,e)).get()}async findByDataField(e,t,n){return this.db.select().from(c).where(D(a(c.collectionId,e),$`json_extract(${c.data}, ${`$.${t}`}) = ${n}`)).get()}async insert(e){return this.db.insert(c).values(e).returning().get()}async update(e,t){return this.db.update(c).set(t).where(a(c.id,e)).returning().get()}async delete(e){return this.db.delete(c).where(a(c.id,e)).returning().get()}}const J=g("collection-not-found-error",w.NOT_FOUND),V=g("entry-not-found-error",w.NOT_FOUND),_t=g("invalid-entry-data-error",w.BAD_REQUEST),vt=g("duplicate-slug-error",w.BAD_REQUEST);function St(i){return i.normalize("NFD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"sans-titre"}function Z(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 bt{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 J(`collection not found: ${e}`);return t}async createDefinition(e,t){return this.definitions.insert({...e,slug:e.slug||await this.uniqueDefinitionSlug(St(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 J(`collection not found: ${e}`);return r}async removeDefinition(e){if(!await this.definitions.delete(e))throw new J(`collection not found: ${e}`)}validateData(e,t){const n=he(e.fields).safeParse(t);if(!n.success)throw new _t(`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 V(`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 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),f=await this.uniqueEntrySlug(r.id,t.slug||St(t.title)),m=await this.entries.insert({...t,slug:f,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,[],Z(r.fields,d)),m}async updateEntry(e,t,n){const r=await this.entries.findById(e);if(!r)throw new V(`entry not found: ${e}`);const d=await this.getDefinition(r.collectionId),f=new Set(d.fields.map(S=>S.name)),m=Object.fromEntries(Object.entries(r.data??{}).filter(([S])=>!f.has(S))),A=t.data?{...r.data,...t.data}:r.data,N=Object.fromEntries(Object.entries(A).filter(([S])=>f.has(S)||S in(t.data??{}))),T=t.data?{...m,...this.validateData(d,N)}:void 0,ee={...t,updatedBy:n??null};T&&(ee.data=T),t.status==="published"&&!t.publishedAt&&(ee.publishedAt=new Date().toISOString());try{const S=await this.entries.update(e,ee);return T&&await this.linkRelations(d,e,Z(d.fields,r.data),Z(d.fields,T)),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 V(`entry not found: ${e}`);const n=await this.getDefinition(t.collectionId);await this.linkRelations(n,e,Z(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 vt(`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)),f=n.filter(m=>!r.includes(m));for(const m of d){const A=await this.entries.findById(m);if(!A)continue;const N=new Set(A.related??[]);N.add(t),await this.entries.update(m,{related:[...N]})}for(const m of f){const A=await this.entries.findById(m);A&&await this.entries.update(m,{related:(A.related??[]).filter(N=>N!==t)})}}}const At=b({list:u.query(({ctx:i})=>i.services.collections.listDefinitions()),get:u.input(s.object({idOrSlug:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getDefinition(e.idOrSlug)),create:_.input(mt).mutation(({ctx:i,input:e})=>i.services.collections.createDefinition(e,i.session.user.id)),update:_.input(s.object({id:s.string(),data:ht})).mutation(({ctx:i,input:e})=>i.services.collections.updateDefinition(e.id,e.data,i.session.user.id)),remove:_.input(s.object({id:s.string()})).mutation(async({ctx:i,input:e})=>(await i.services.collections.removeDefinition(e.id),{removed:e.id})),entries:b({get:u.input(s.object({id:s.string()})).query(({ctx:i,input:e})=>i.services.collections.getEntry(e.id)),list:u.input(s.object({collectionId:s.string(),status:s.array(s.enum(B)).optional(),search:s.string().max(200).optional(),order:s.enum(["recent","oldest","title"]).optional(),skip:s.number().int().min(0).optional(),limit:s.number().int().min(1).max(100).optional()})).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(B)).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:gt})).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:wt})).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}))})});function oi({env:i}={}){const e=i??be(),t=Ue(e.COMMUN_DATA_DIR,e.COMMUN_MIGRATIONS_DIR),n=De(e),r=X.fromEnv(e),d=new Fe(new je(t),{email:r,adminUrl:e.COMMUN_ADMIN_URL,jwtSecret:e.COMMUN_JWT_SECRET}),f=new ct(t),m=new ut(f,n),A=new bt(new ft(t),new Et(t),m),N=new nt(new Xe(t)),T={health:new Oe(t),users:d,organization:N,media:m,collections:A};return{env:e,db:t,storage:n,services:T}}const ai=b({health:Gt,auth:We,users:Qe,apiTokens:Ye,organization:st,media:pt,collections:At});export{le as ALLOWED_MIME,qe as CannotRemoveSelfError,J as CollectionNotFoundError,bt as CollectionsService,ft as DefinitionRepository,ce as DeployFailedError,it as DeployHookMissingError,Y as DomainError,vt as DuplicateSlugError,X as EmailService,V as EntryNotFoundError,Et as EntryRepository,me as FIELD_TYPES,Oe as HealthService,_t as InvalidEntryDataError,ze as InvitationInvalidError,G as MediaNotFoundError,ct as MediaRepository,ut as MediaService,tt as OrganizationAlreadyInitializedError,et as OrganizationNotInitializedError,Xe as OrganizationRepository,nt as OrganizationService,B as PUBLICATION_STATUSES,Ie as S3Storage,Pe as SessionNotFoundError,Ke as TooManyAttemptsError,de as UnsupportedMimeError,dt as UploadIncompleteError,oe as UserNotFoundError,je as UsersRepository,Fe as UsersService,Te as acceptInvitationDto,Ae as addressSchema,$e as apiTokenCreateDto,h as apiTokens,Ye as apiTokensRouter,ai as appRouter,We as authRouter,he as buildDataSchema,y as collectionDefinitions,At as collectionsRouter,Ue as connectDb,oi as createCore,De as createStorage,g as createTypedError,mt as definitionCreateDto,ht as definitionUpdateDto,c as entries,gt as entryCreateDto,wt as entryUpdateDto,L as fieldDefinitionSchema,v as invitations,Ce as inviteDto,xe as loginDto,E as media,ot as mediaFinalizeDto,rt as mediaRequestUploadDto,pt as mediaRouter,at as mediaUpdateDto,U as organization,Ve as organizationInitDto,st as organizationRouter,Ze as organizationUpdateDto,be as parseEnv,Re as requestPasswordResetDto,l as sessions,x as toPublicUser,Be as userUpdateDto,p as users,Qe as usersRouter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-commune/core",
3
- "version": "0.1.5",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "description": "Business domains, database schema and tRPC router. Holds the logic; knows nothing of transport.",
6
6
  "main": "./dist/index.mjs",