@adatechnology/content-module 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2198 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc2) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ ArchivePostUseCase: () => ArchivePostUseCase,
25
+ BuildFeedUseCase: () => BuildFeedUseCase,
26
+ CONTENT_MIGRATIONS_TABLE: () => CONTENT_MIGRATIONS_TABLE,
27
+ COVER_IMAGE: () => COVER_IMAGE,
28
+ CountPostsUseCase: () => CountPostsUseCase,
29
+ CreateFromTemplateUseCase: () => CreateFromTemplateUseCase,
30
+ CreatePostUseCase: () => CreatePostUseCase,
31
+ CreateRecurrenceUseCase: () => CreateRecurrenceUseCase,
32
+ DEFAULT_SCHEDULER_INTERVAL_MS: () => DEFAULT_SCHEDULER_INTERVAL_MS,
33
+ FEED_FORMAT: () => FEED_FORMAT,
34
+ GetPostUseCase: () => GetPostUseCase,
35
+ GetPublishedPostBySlugUseCase: () => GetPublishedPostBySlugUseCase,
36
+ ListPostsUseCase: () => ListPostsUseCase,
37
+ ListPublishedPostsUseCase: () => ListPublishedPostsUseCase,
38
+ ListRecurrencesUseCase: () => ListRecurrencesUseCase,
39
+ ListSitemapEntriesUseCase: () => ListSitemapEntriesUseCase,
40
+ ListTagsUseCase: () => ListTagsUseCase,
41
+ PostRepository: () => PostRepository,
42
+ PublishDueUseCase: () => PublishDueUseCase,
43
+ PublishPostUseCase: () => PublishPostUseCase,
44
+ RecurrenceRepository: () => RecurrenceRepository,
45
+ RemoveRecurrenceUseCase: () => RemoveRecurrenceUseCase,
46
+ RepublishPostUseCase: () => RepublishPostUseCase,
47
+ SaveAsTemplateUseCase: () => SaveAsTemplateUseCase,
48
+ TAG_SCOPE: () => TAG_SCOPE,
49
+ UnpublishPostUseCase: () => UnpublishPostUseCase,
50
+ UpdatePostUseCase: () => UpdatePostUseCase,
51
+ UpdateRecurrenceUseCase: () => UpdateRecurrenceUseCase,
52
+ UploadCoverImageUseCase: () => UploadCoverImageUseCase,
53
+ contentMigrationsFolder: () => contentMigrationsFolder,
54
+ contentSchema: () => contentSchema,
55
+ createContentModule: () => createContentModule,
56
+ createContentRoutes: () => createContentRoutes,
57
+ createInMemoryPostStore: () => createInMemoryPostStore,
58
+ createInMemoryRecurrenceStore: () => createInMemoryRecurrenceStore,
59
+ nextOccurrence: () => nextOccurrence,
60
+ nextOccurrenceAfter: () => nextOccurrenceAfter,
61
+ posts: () => posts,
62
+ recurrenceRules: () => recurrenceRules,
63
+ runContentMigrations: () => runContentMigrations,
64
+ startContentScheduler: () => startContentScheduler
65
+ });
66
+ module.exports = __toCommonJS(index_exports);
67
+
68
+ // src/ContentModule.ts
69
+ var import_content_contracts13 = require("@adatechnology/content-contracts");
70
+
71
+ // src/repositories/PostRepository.ts
72
+ var import_drizzle_orm3 = require("drizzle-orm");
73
+ var import_content_contracts2 = require("@adatechnology/content-contracts");
74
+
75
+ // src/schema/schema.ts
76
+ var import_drizzle_orm = require("drizzle-orm");
77
+ var import_pg_core = require("drizzle-orm/pg-core");
78
+ var contentSchema = (0, import_pg_core.pgSchema)("content");
79
+ var posts = contentSchema.table("posts", {
80
+ id: (0, import_pg_core.uuid)("id").primaryKey().defaultRandom(),
81
+ companyId: (0, import_pg_core.uuid)("company_id").notNull(),
82
+ slug: (0, import_pg_core.varchar)("slug", {
83
+ length: 120
84
+ }).notNull(),
85
+ shortId: (0, import_pg_core.varchar)("short_id", {
86
+ length: 6
87
+ }).notNull(),
88
+ title: (0, import_pg_core.varchar)("title", {
89
+ length: 200
90
+ }).notNull(),
91
+ excerpt: (0, import_pg_core.varchar)("excerpt", {
92
+ length: 500
93
+ }),
94
+ body: (0, import_pg_core.text)("body").notNull().default(""),
95
+ coverImageUrl: (0, import_pg_core.varchar)("cover_image_url", {
96
+ length: 2048
97
+ }),
98
+ coverImageAlt: (0, import_pg_core.varchar)("cover_image_alt", {
99
+ length: 300
100
+ }),
101
+ tags: (0, import_pg_core.text)("tags").array().notNull().default([]),
102
+ tagLabels: (0, import_pg_core.jsonb)("tag_labels").$type().notNull().default({}),
103
+ status: (0, import_pg_core.varchar)("status", {
104
+ length: 12
105
+ }).notNull().default("draft"),
106
+ isTemplate: (0, import_pg_core.boolean)("is_template").notNull().default(false),
107
+ publishedAt: (0, import_pg_core.timestamp)("published_at", {
108
+ withTimezone: true
109
+ }),
110
+ authorName: (0, import_pg_core.varchar)("author_name", {
111
+ length: 120
112
+ }),
113
+ seoTitle: (0, import_pg_core.varchar)("seo_title", {
114
+ length: 200
115
+ }),
116
+ seoDescription: (0, import_pg_core.varchar)("seo_description", {
117
+ length: 320
118
+ }),
119
+ canonicalUrl: (0, import_pg_core.varchar)("canonical_url", {
120
+ length: 2048
121
+ }),
122
+ readingTimeMinutes: (0, import_pg_core.integer)("reading_time_minutes").notNull().default(1),
123
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
124
+ withTimezone: true
125
+ }).notNull().defaultNow(),
126
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", {
127
+ withTimezone: true
128
+ }).notNull().defaultNow()
129
+ }, (table) => [
130
+ // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
131
+ // faria um link antigo (já compartilhado) abrir outro post.
132
+ (0, import_pg_core.uniqueIndex)("idx_posts_company_slug").on(table.companyId, table.slug),
133
+ (0, import_pg_core.uniqueIndex)("idx_posts_company_short_id").on(table.companyId, table.shortId),
134
+ // Serve a listagem pública: empresa + status + ordem por data.
135
+ (0, import_pg_core.index)("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
136
+ (0, import_pg_core.index)("idx_posts_tags").using("gin", table.tags),
137
+ // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.
138
+ (0, import_pg_core.index)("idx_posts_due").on(table.publishedAt).where(import_drizzle_orm.sql`"status" = 'scheduled'`)
139
+ ]);
140
+ var recurrenceRules = contentSchema.table("recurrence_rules", {
141
+ id: (0, import_pg_core.uuid)("id").primaryKey().defaultRandom(),
142
+ companyId: (0, import_pg_core.uuid)("company_id").notNull(),
143
+ templateId: (0, import_pg_core.uuid)("template_id").notNull().references(() => posts.id),
144
+ frequency: (0, import_pg_core.varchar)("frequency", {
145
+ length: 10
146
+ }).notNull(),
147
+ // Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.
148
+ anchorDay: (0, import_pg_core.integer)("anchor_day").notNull(),
149
+ isActive: (0, import_pg_core.boolean)("is_active").notNull().default(true),
150
+ nextRunAt: (0, import_pg_core.timestamp)("next_run_at", {
151
+ withTimezone: true
152
+ }).notNull(),
153
+ lastRunAt: (0, import_pg_core.timestamp)("last_run_at", {
154
+ withTimezone: true
155
+ }),
156
+ lastPostId: (0, import_pg_core.uuid)("last_post_id"),
157
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
158
+ withTimezone: true
159
+ }).notNull().defaultNow()
160
+ }, (table) => [
161
+ (0, import_pg_core.index)("idx_recurrence_company").on(table.companyId),
162
+ (0, import_pg_core.index)("idx_recurrence_due").on(table.nextRunAt).where(import_drizzle_orm.sql`"is_active"`)
163
+ ]);
164
+ var postFormerSlugs = contentSchema.table("post_former_slugs", {
165
+ companyId: (0, import_pg_core.uuid)("company_id").notNull(),
166
+ slug: (0, import_pg_core.varchar)("slug", {
167
+ length: 120
168
+ }).notNull(),
169
+ postId: (0, import_pg_core.uuid)("post_id").notNull().references(() => posts.id),
170
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
171
+ withTimezone: true
172
+ }).notNull().defaultNow()
173
+ }, (table) => [
174
+ (0, import_pg_core.primaryKey)({
175
+ columns: [
176
+ table.companyId,
177
+ table.slug
178
+ ]
179
+ })
180
+ ]);
181
+
182
+ // src/repositories/conditions.ts
183
+ var import_drizzle_orm2 = require("drizzle-orm");
184
+ var import_content_contracts = require("@adatechnology/content-contracts");
185
+ function postOwnedByCondition(params) {
186
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm2.eq)(posts.id, params.id));
187
+ }
188
+ __name(postOwnedByCondition, "postOwnedByCondition");
189
+ function postSlugCondition(params) {
190
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm2.eq)(posts.slug, params.slug));
191
+ }
192
+ __name(postSlugCondition, "postSlugCondition");
193
+ function postAdminListCondition(params) {
194
+ const conditions = [
195
+ (0, import_drizzle_orm2.eq)(posts.companyId, params.companyId),
196
+ templateCondition(params.isTemplate)
197
+ ];
198
+ if (params.status) conditions.push(statusCondition(params.status, params.now));
199
+ if (params.tags?.length) conditions.push((0, import_drizzle_orm2.arrayOverlaps)(posts.tags, [
200
+ ...params.tags
201
+ ]));
202
+ if (params.search) {
203
+ const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
204
+ conditions.push(import_drizzle_orm2.sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
205
+ }
206
+ return (0, import_drizzle_orm2.and)(...conditions);
207
+ }
208
+ __name(postAdminListCondition, "postAdminListCondition");
209
+ function templateCondition(isTemplate) {
210
+ if (isTemplate) return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.isTemplate, true), (0, import_drizzle_orm2.ne)(posts.status, import_content_contracts.POST_STATUS.ARCHIVED));
211
+ return (0, import_drizzle_orm2.eq)(posts.isTemplate, false);
212
+ }
213
+ __name(templateCondition, "templateCondition");
214
+ function statusCondition(status, now) {
215
+ if (status === import_content_contracts.POST_STATUS.PUBLISHED) {
216
+ return (0, import_drizzle_orm2.or)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.PUBLISHED), (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm2.lte)(posts.publishedAt, now)));
217
+ }
218
+ if (status === import_content_contracts.POST_STATUS.SCHEDULED) {
219
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm2.gt)(posts.publishedAt, now));
220
+ }
221
+ return (0, import_drizzle_orm2.eq)(posts.status, status);
222
+ }
223
+ __name(statusCondition, "statusCondition");
224
+ function postPublicCondition(params) {
225
+ const conditions = [
226
+ (0, import_drizzle_orm2.eq)(posts.companyId, params.companyId),
227
+ (0, import_drizzle_orm2.inArray)(posts.status, [
228
+ import_content_contracts.POST_STATUS.PUBLISHED,
229
+ import_content_contracts.POST_STATUS.SCHEDULED
230
+ ]),
231
+ (0, import_drizzle_orm2.lte)(posts.publishedAt, params.now)
232
+ ];
233
+ if (params.tag) conditions.push((0, import_drizzle_orm2.arrayContains)(posts.tags, [
234
+ params.tag
235
+ ]));
236
+ return (0, import_drizzle_orm2.and)(...conditions);
237
+ }
238
+ __name(postPublicCondition, "postPublicCondition");
239
+ function postPublicSlugCondition(params) {
240
+ return (0, import_drizzle_orm2.and)(postPublicCondition(params), (0, import_drizzle_orm2.eq)(posts.slug, params.slug));
241
+ }
242
+ __name(postPublicSlugCondition, "postPublicSlugCondition");
243
+ function postDueCondition(params) {
244
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm2.eq)(posts.isTemplate, false), (0, import_drizzle_orm2.lte)(posts.publishedAt, params.now));
245
+ }
246
+ __name(postDueCondition, "postDueCondition");
247
+ function postShortIdCondition(params) {
248
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm2.eq)(posts.shortId, params.shortId));
249
+ }
250
+ __name(postShortIdCondition, "postShortIdCondition");
251
+ function postPublicShortIdCondition(params) {
252
+ return (0, import_drizzle_orm2.and)(postPublicCondition(params), (0, import_drizzle_orm2.eq)(posts.shortId, params.shortId));
253
+ }
254
+ __name(postPublicShortIdCondition, "postPublicShortIdCondition");
255
+
256
+ // src/repositories/PostRepository.ts
257
+ var TAG_LIST_LIMIT = 200;
258
+ var SORT_COLUMNS = {
259
+ title: posts.title,
260
+ status: posts.status,
261
+ publishedAt: posts.publishedAt,
262
+ updatedAt: posts.updatedAt
263
+ };
264
+ function adminOrder(query) {
265
+ const column = SORT_COLUMNS[query.sort ?? "updatedAt"];
266
+ const direction = (query.order ?? "desc") === "asc" ? import_drizzle_orm3.asc : import_drizzle_orm3.desc;
267
+ const primary = query.sort === "publishedAt" ? import_drizzle_orm3.sql`${column} ${import_drizzle_orm3.sql.raw(query.order === "asc" ? "asc" : "desc")} nulls last` : direction(column);
268
+ return [
269
+ primary,
270
+ (0, import_drizzle_orm3.asc)(posts.id)
271
+ ];
272
+ }
273
+ __name(adminOrder, "adminOrder");
274
+ var PostRepository = class {
275
+ static {
276
+ __name(this, "PostRepository");
277
+ }
278
+ db;
279
+ constructor(db) {
280
+ this.db = db;
281
+ }
282
+ async create(values) {
283
+ const [row] = await this.db.insert(posts).values(values).returning();
284
+ if (!row) throw new Error("content-module: insert em posts n\xE3o retornou linha");
285
+ return row;
286
+ }
287
+ async findById(params) {
288
+ const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1);
289
+ return row;
290
+ }
291
+ async findBySlug(params) {
292
+ const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1);
293
+ return row;
294
+ }
295
+ async findPublicBySlug(params) {
296
+ const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1);
297
+ return row;
298
+ }
299
+ async findByShortId(params) {
300
+ const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1);
301
+ return row;
302
+ }
303
+ async findPublicByShortId(params) {
304
+ const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1);
305
+ return row;
306
+ }
307
+ async findPublicByFormerSlug(params) {
308
+ const [former] = await this.db.select({
309
+ postId: postFormerSlugs.postId
310
+ }).from(postFormerSlugs).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(postFormerSlugs.companyId, params.companyId), (0, import_drizzle_orm3.eq)(postFormerSlugs.slug, params.slug))).limit(1);
311
+ if (!former) return void 0;
312
+ const [row] = await this.db.select().from(posts).where((0, import_drizzle_orm3.and)(postPublicCondition(params), (0, import_drizzle_orm3.eq)(posts.id, former.postId))).limit(1);
313
+ return row;
314
+ }
315
+ async recordFormerSlug(params) {
316
+ await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing();
317
+ }
318
+ async update(params) {
319
+ const [row] = await this.db.update(posts).set({
320
+ ...params.values,
321
+ updatedAt: /* @__PURE__ */ new Date()
322
+ }).where(postOwnedByCondition(params)).returning();
323
+ return row;
324
+ }
325
+ async listForAdmin(query) {
326
+ const where = postAdminListCondition(query);
327
+ const [rows, [counted]] = await Promise.all([
328
+ this.db.select().from(posts).where(where).orderBy(...adminOrder(query)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
329
+ this.db.select({
330
+ value: import_drizzle_orm3.sql`count(*)::int`
331
+ }).from(posts).where(where)
332
+ ]);
333
+ return {
334
+ rows,
335
+ total: counted?.value ?? 0
336
+ };
337
+ }
338
+ async listPublic(query) {
339
+ const where = postPublicCondition(query);
340
+ const [rows, [counted]] = await Promise.all([
341
+ this.db.select().from(posts).where(where).orderBy((0, import_drizzle_orm3.desc)(posts.publishedAt), (0, import_drizzle_orm3.asc)(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
342
+ this.db.select({
343
+ value: import_drizzle_orm3.sql`count(*)::int`
344
+ }).from(posts).where(where)
345
+ ]);
346
+ return {
347
+ rows,
348
+ total: counted?.value ?? 0
349
+ };
350
+ }
351
+ async countByStatus(params) {
352
+ const now = import_drizzle_orm3.sql`${params.now.toISOString()}::timestamptz`;
353
+ const counted = /* @__PURE__ */ __name((condition) => import_drizzle_orm3.sql`count(*) filter (where ${condition})::int`, "counted");
354
+ const livePublished = import_drizzle_orm3.sql`(${posts.status} = ${import_content_contracts2.POST_STATUS.PUBLISHED} or (${posts.status} = ${import_content_contracts2.POST_STATUS.SCHEDULED} and ${posts.publishedAt} <= ${now}))`;
355
+ const [row] = await this.db.select({
356
+ published: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${livePublished}`),
357
+ scheduled: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${posts.status} = ${import_content_contracts2.POST_STATUS.SCHEDULED} and ${posts.publishedAt} > ${now}`),
358
+ draft: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${posts.status} = ${import_content_contracts2.POST_STATUS.DRAFT}`),
359
+ archived: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${posts.status} = ${import_content_contracts2.POST_STATUS.ARCHIVED}`),
360
+ templates: counted(import_drizzle_orm3.sql`${posts.isTemplate} and ${posts.status} <> ${import_content_contracts2.POST_STATUS.ARCHIVED}`)
361
+ }).from(posts).where((0, import_drizzle_orm3.eq)(posts.companyId, params.companyId));
362
+ return row ?? {
363
+ published: 0,
364
+ scheduled: 0,
365
+ draft: 0,
366
+ archived: 0,
367
+ templates: 0
368
+ };
369
+ }
370
+ async claimDueScheduled(params) {
371
+ const due = this.db.select({
372
+ id: posts.id
373
+ }).from(posts).where(postDueCondition({
374
+ now: params.now
375
+ })).orderBy((0, import_drizzle_orm3.asc)(posts.publishedAt), (0, import_drizzle_orm3.asc)(posts.id)).limit(params.limit).for("update", {
376
+ skipLocked: true
377
+ });
378
+ return this.db.update(posts).set({
379
+ status: import_content_contracts2.POST_STATUS.PUBLISHED
380
+ }).where((0, import_drizzle_orm3.inArray)(posts.id, due)).returning();
381
+ }
382
+ async listTags(params) {
383
+ const where = params.publicAt ? postPublicCondition({
384
+ companyId: params.companyId,
385
+ now: params.publicAt
386
+ }) : postAdminListCondition({
387
+ companyId: params.companyId,
388
+ now: /* @__PURE__ */ new Date()
389
+ });
390
+ const postTags = this.db.select({
391
+ tag: import_drizzle_orm3.sql`unnest(${posts.tags})`.as("tag")
392
+ }).from(posts).where(where).as("post_tags");
393
+ const rows = await this.db.select({
394
+ tag: postTags.tag,
395
+ count: import_drizzle_orm3.sql`count(*)::int`
396
+ }).from(postTags).groupBy(postTags.tag).orderBy(import_drizzle_orm3.sql`count(*) desc`, (0, import_drizzle_orm3.asc)(postTags.tag)).limit(TAG_LIST_LIMIT);
397
+ return rows;
398
+ }
399
+ };
400
+
401
+ // src/repositories/RecurrenceRepository.ts
402
+ var import_drizzle_orm4 = require("drizzle-orm");
403
+ function recurrenceOwnedByCondition(params) {
404
+ return (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(recurrenceRules.companyId, params.companyId), (0, import_drizzle_orm4.eq)(recurrenceRules.id, params.id));
405
+ }
406
+ __name(recurrenceOwnedByCondition, "recurrenceOwnedByCondition");
407
+ var RecurrenceRepository = class {
408
+ static {
409
+ __name(this, "RecurrenceRepository");
410
+ }
411
+ db;
412
+ constructor(db) {
413
+ this.db = db;
414
+ }
415
+ async create(values) {
416
+ const [row] = await this.db.insert(recurrenceRules).values(values).returning();
417
+ if (!row) throw new Error("content-module: insert em recurrence_rules n\xE3o retornou linha");
418
+ return row;
419
+ }
420
+ async findById(params) {
421
+ const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1);
422
+ return row;
423
+ }
424
+ async list(params) {
425
+ return this.db.select().from(recurrenceRules).where((0, import_drizzle_orm4.eq)(recurrenceRules.companyId, params.companyId)).orderBy((0, import_drizzle_orm4.asc)(recurrenceRules.nextRunAt), (0, import_drizzle_orm4.asc)(recurrenceRules.id));
426
+ }
427
+ async update(params) {
428
+ const [row] = await this.db.update(recurrenceRules).set(params.values).where(recurrenceOwnedByCondition(params)).returning();
429
+ return row;
430
+ }
431
+ async remove(params) {
432
+ const removed = await this.db.delete(recurrenceRules).where(recurrenceOwnedByCondition(params)).returning({
433
+ id: recurrenceRules.id
434
+ });
435
+ return removed.length > 0;
436
+ }
437
+ async processDue(params) {
438
+ return this.db.transaction(async (transaction) => {
439
+ const due = await transaction.select().from(recurrenceRules).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(recurrenceRules.isActive, true), (0, import_drizzle_orm4.lte)(recurrenceRules.nextRunAt, params.now))).orderBy((0, import_drizzle_orm4.asc)(recurrenceRules.nextRunAt), (0, import_drizzle_orm4.asc)(recurrenceRules.id)).limit(params.limit).for("update", {
440
+ skipLocked: true
441
+ });
442
+ let processed = 0;
443
+ for (const rule of due) {
444
+ const values = await params.handle(rule);
445
+ await transaction.update(recurrenceRules).set(values).where((0, import_drizzle_orm4.eq)(recurrenceRules.id, rule.id));
446
+ processed += 1;
447
+ }
448
+ return processed;
449
+ });
450
+ }
451
+ };
452
+
453
+ // src/use-cases/Feed.use-cases.ts
454
+ var import_content_contracts3 = require("@adatechnology/content-contracts");
455
+ var DEFAULT_ITEM_LIMIT = 20;
456
+ var SITEMAP_LIMIT = 5e4;
457
+ var FEED_FORMAT = {
458
+ RSS: "rss",
459
+ ATOM: "atom"
460
+ };
461
+ var BuildFeedUseCase = class {
462
+ static {
463
+ __name(this, "BuildFeedUseCase");
464
+ }
465
+ dependencies;
466
+ feed;
467
+ constructor(dependencies, feed) {
468
+ this.dependencies = dependencies;
469
+ this.feed = feed;
470
+ }
471
+ async execute(params) {
472
+ const now = this.dependencies.clock.now();
473
+ const page = await this.dependencies.posts.listPublic({
474
+ companyId: params.companyId,
475
+ now,
476
+ page: 1,
477
+ pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT
478
+ });
479
+ const channel = {
480
+ siteUrl: this.feed.siteUrl,
481
+ title: this.feed.title,
482
+ ...this.feed.description ? {
483
+ description: this.feed.description
484
+ } : {},
485
+ ...this.feed.language ? {
486
+ language: this.feed.language
487
+ } : {},
488
+ ...params.feedUrl ? {
489
+ feedUrl: params.feedUrl
490
+ } : {}
491
+ };
492
+ const items = page.rows.map((row) => this.toItem(row));
493
+ return params.format === FEED_FORMAT.ATOM ? (0, import_content_contracts3.buildAtomFeed)({
494
+ channel,
495
+ items,
496
+ now
497
+ }) : (0, import_content_contracts3.buildRssFeed)({
498
+ channel,
499
+ items
500
+ });
501
+ }
502
+ toItem(row) {
503
+ return {
504
+ title: row.title,
505
+ url: (0, import_content_contracts3.buildPostUrl)({
506
+ siteUrl: this.feed.siteUrl,
507
+ slug: row.slug,
508
+ shortId: row.shortId,
509
+ postPathTemplate: this.feed.postPathTemplate
510
+ }),
511
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
512
+ updatedAt: row.updatedAt.toISOString(),
513
+ summary: row.excerpt ?? (0, import_content_contracts3.buildExcerpt)(row.body),
514
+ ...this.feed.includeContent ?? true ? {
515
+ contentHtml: (0, import_content_contracts3.renderMarkdownToHtml)(row.body, {
516
+ headingIds: false
517
+ })
518
+ } : {},
519
+ ...row.authorName ? {
520
+ authorName: row.authorName
521
+ } : {},
522
+ categories: row.tags,
523
+ ...row.coverImageUrl ? {
524
+ imageUrl: row.coverImageUrl
525
+ } : {}
526
+ };
527
+ }
528
+ };
529
+ var ListSitemapEntriesUseCase = class {
530
+ static {
531
+ __name(this, "ListSitemapEntriesUseCase");
532
+ }
533
+ dependencies;
534
+ feed;
535
+ constructor(dependencies, feed) {
536
+ this.dependencies = dependencies;
537
+ this.feed = feed;
538
+ }
539
+ /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */
540
+ async execute(params) {
541
+ const page = await this.dependencies.posts.listPublic({
542
+ companyId: params.companyId,
543
+ now: this.dependencies.clock.now(),
544
+ page: 1,
545
+ pageSize: SITEMAP_LIMIT
546
+ });
547
+ return page.rows.map((row) => ({
548
+ loc: (0, import_content_contracts3.buildPostUrl)({
549
+ siteUrl: this.feed.siteUrl,
550
+ slug: row.slug,
551
+ shortId: row.shortId,
552
+ postPathTemplate: this.feed.postPathTemplate
553
+ }),
554
+ lastmod: row.updatedAt.toISOString()
555
+ }));
556
+ }
557
+ };
558
+
559
+ // src/use-cases/Post.use-cases.ts
560
+ var import_content_contracts6 = require("@adatechnology/content-contracts");
561
+
562
+ // src/shared/shortId.ts
563
+ var import_node_crypto = require("crypto");
564
+ var import_content_contracts4 = require("@adatechnology/content-contracts");
565
+ var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
566
+ function generateShortId() {
567
+ let value = "";
568
+ for (let index2 = 0; index2 < import_content_contracts4.SHORT_ID_LENGTH; index2 += 1) value += ALPHABET[(0, import_node_crypto.randomInt)(ALPHABET.length)];
569
+ return value;
570
+ }
571
+ __name(generateShortId, "generateShortId");
572
+
573
+ // src/shared/isUniqueViolation.ts
574
+ var UNIQUE_VIOLATION = "23505";
575
+ function isUniqueViolation(error) {
576
+ let current = error;
577
+ for (let depth = 0; depth < 3 && typeof current === "object" && current !== null; depth += 1) {
578
+ if (current.code === UNIQUE_VIOLATION) return true;
579
+ current = current.cause;
580
+ }
581
+ return false;
582
+ }
583
+ __name(isUniqueViolation, "isUniqueViolation");
584
+
585
+ // src/shared/notifyPostChanged.ts
586
+ async function notifyPostChanged(dependencies, type, post) {
587
+ const hook = dependencies.hooks?.onPostChanged;
588
+ if (!hook) return;
589
+ try {
590
+ await hook({
591
+ type,
592
+ post
593
+ });
594
+ } catch (error) {
595
+ dependencies.logger?.error("content-module: hook onPostChanged falhou", {
596
+ postId: post.id,
597
+ type,
598
+ error: error instanceof Error ? error.message : String(error)
599
+ });
600
+ }
601
+ }
602
+ __name(notifyPostChanged, "notifyPostChanged");
603
+
604
+ // src/shared/toContract.ts
605
+ var import_content_contracts5 = require("@adatechnology/content-contracts");
606
+ function effectiveStatus(row, now) {
607
+ if (row.status === import_content_contracts5.POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return import_content_contracts5.POST_STATUS.PUBLISHED;
608
+ return row.status;
609
+ }
610
+ __name(effectiveStatus, "effectiveStatus");
611
+ function toPostSummary(row, now) {
612
+ return {
613
+ id: row.id,
614
+ companyId: row.companyId,
615
+ slug: row.slug,
616
+ shortId: row.shortId,
617
+ title: row.title,
618
+ excerpt: row.excerpt,
619
+ coverImageUrl: row.coverImageUrl,
620
+ coverImageAlt: row.coverImageAlt,
621
+ tags: row.tags,
622
+ tagLabels: row.tagLabels,
623
+ status: effectiveStatus(row, now),
624
+ isTemplate: row.isTemplate,
625
+ publishedAt: row.publishedAt?.toISOString() ?? null,
626
+ authorName: row.authorName,
627
+ seoTitle: row.seoTitle,
628
+ seoDescription: row.seoDescription,
629
+ canonicalUrl: row.canonicalUrl,
630
+ readingTimeMinutes: row.readingTimeMinutes,
631
+ createdAt: row.createdAt.toISOString(),
632
+ updatedAt: row.updatedAt.toISOString()
633
+ };
634
+ }
635
+ __name(toPostSummary, "toPostSummary");
636
+ function toPost(row, now) {
637
+ return {
638
+ ...toPostSummary(row, now),
639
+ body: row.body
640
+ };
641
+ }
642
+ __name(toPost, "toPost");
643
+ function toPublicPostSummary(row) {
644
+ return {
645
+ id: row.id,
646
+ slug: row.slug,
647
+ shortId: row.shortId,
648
+ title: row.title,
649
+ excerpt: row.excerpt,
650
+ coverImageUrl: row.coverImageUrl,
651
+ coverImageAlt: row.coverImageAlt,
652
+ tags: row.tags,
653
+ tagLabels: row.tagLabels,
654
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
655
+ updatedAt: row.updatedAt.toISOString(),
656
+ authorName: row.authorName,
657
+ seoTitle: row.seoTitle,
658
+ seoDescription: row.seoDescription,
659
+ canonicalUrl: row.canonicalUrl,
660
+ readingTimeMinutes: row.readingTimeMinutes
661
+ };
662
+ }
663
+ __name(toPublicPostSummary, "toPublicPostSummary");
664
+ function toPublicPost(row) {
665
+ return {
666
+ ...toPublicPostSummary(row),
667
+ body: row.body
668
+ };
669
+ }
670
+ __name(toPublicPost, "toPublicPost");
671
+ function toPagination(params) {
672
+ return {
673
+ ...params,
674
+ totalPages: Math.max(1, Math.ceil(params.total / params.pageSize))
675
+ };
676
+ }
677
+ __name(toPagination, "toPagination");
678
+
679
+ // src/use-cases/Post.use-cases.ts
680
+ var MAX_SLUG_ATTEMPTS = 50;
681
+ var FALLBACK_SLUG = "post";
682
+ var PostUseCaseBase = class {
683
+ static {
684
+ __name(this, "PostUseCaseBase");
685
+ }
686
+ dependencies;
687
+ constructor(dependencies) {
688
+ this.dependencies = dependencies;
689
+ }
690
+ now() {
691
+ return this.dependencies.clock.now();
692
+ }
693
+ async findOrFail(reference2) {
694
+ const row = await this.dependencies.posts.findById(reference2);
695
+ if (!row) throw new import_content_contracts6.PostNotFoundError(reference2.id);
696
+ return row;
697
+ }
698
+ async save(reference2, values, event) {
699
+ const row = await this.dependencies.posts.update({
700
+ ...reference2,
701
+ values
702
+ }).catch((error) => {
703
+ if (isUniqueViolation(error) && values.slug) throw new import_content_contracts6.DuplicateSlugError(values.slug);
704
+ throw error;
705
+ });
706
+ if (!row) throw new import_content_contracts6.PostNotFoundError(reference2.id);
707
+ const post = toPost(row, this.now());
708
+ await notifyPostChanged(this.dependencies, event, post);
709
+ return post;
710
+ }
711
+ /** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */
712
+ async generateShortId(companyId) {
713
+ for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {
714
+ const candidate = generateShortId();
715
+ if (!await this.dependencies.posts.findByShortId({
716
+ companyId,
717
+ shortId: candidate
718
+ })) return candidate;
719
+ }
720
+ throw new Error("content-module: sem id curto livre");
721
+ }
722
+ readingTime(body) {
723
+ return (0, import_content_contracts6.estimateReadingTimeMinutes)(body, this.dependencies.config.wordsPerMinute);
724
+ }
725
+ async assertSlugAvailable(companyId, slug, ownId) {
726
+ const existing = await this.dependencies.posts.findBySlug({
727
+ companyId,
728
+ slug
729
+ });
730
+ if (existing && existing.id !== ownId) throw new import_content_contracts6.DuplicateSlugError(slug);
731
+ }
732
+ /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */
733
+ async generateSlug(companyId, title) {
734
+ return this.uniqueSlug(companyId, (0, import_content_contracts6.buildShortSlug)(title, this.dependencies.config.slug) || FALLBACK_SLUG);
735
+ }
736
+ async uniqueSlug(companyId, base) {
737
+ for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {
738
+ const candidate = (0, import_content_contracts6.withSlugSuffix)(base, attempt);
739
+ if (!await this.dependencies.posts.findBySlug({
740
+ companyId,
741
+ slug: candidate
742
+ })) return candidate;
743
+ }
744
+ return (0, import_content_contracts6.withSlugSuffix)(base, Date.now());
745
+ }
746
+ };
747
+ function optionalFields(input) {
748
+ const values = {};
749
+ if (input.excerpt !== void 0) values.excerpt = input.excerpt || null;
750
+ if (input.coverImageUrl !== void 0) values.coverImageUrl = input.coverImageUrl || null;
751
+ if (input.coverImageAlt !== void 0) values.coverImageAlt = input.coverImageAlt || null;
752
+ if (input.authorName !== void 0) values.authorName = input.authorName || null;
753
+ if (input.seoTitle !== void 0) values.seoTitle = input.seoTitle || null;
754
+ if (input.seoDescription !== void 0) values.seoDescription = input.seoDescription || null;
755
+ if (input.canonicalUrl !== void 0) values.canonicalUrl = input.canonicalUrl || null;
756
+ return values;
757
+ }
758
+ __name(optionalFields, "optionalFields");
759
+ var CreatePostUseCase = class extends PostUseCaseBase {
760
+ static {
761
+ __name(this, "CreatePostUseCase");
762
+ }
763
+ async execute(params) {
764
+ const input = import_content_contracts6.createPostSchema.parse(params.input);
765
+ const { companyId } = params;
766
+ if (input.slug) await this.assertSlugAvailable(companyId, input.slug);
767
+ const slug = input.slug ?? await this.generateSlug(companyId, input.title);
768
+ const row = await this.dependencies.posts.create({
769
+ companyId,
770
+ slug,
771
+ shortId: await this.generateShortId(companyId),
772
+ title: input.title,
773
+ body: input.body,
774
+ tags: (0, import_content_contracts6.normalizeTags)(input.tags ?? []),
775
+ tagLabels: (0, import_content_contracts6.buildTagLabels)({
776
+ typed: input.tags ?? [],
777
+ explicit: input.tagLabels
778
+ }),
779
+ status: import_content_contracts6.POST_STATUS.DRAFT,
780
+ readingTimeMinutes: this.readingTime(input.body),
781
+ ...optionalFields(input)
782
+ }).catch((error) => {
783
+ if (isUniqueViolation(error)) throw new import_content_contracts6.DuplicateSlugError(slug);
784
+ throw error;
785
+ });
786
+ const post = toPost(row, this.now());
787
+ await notifyPostChanged(this.dependencies, import_content_contracts6.POST_EVENT.CREATED, post);
788
+ return post;
789
+ }
790
+ };
791
+ var UpdatePostUseCase = class extends PostUseCaseBase {
792
+ static {
793
+ __name(this, "UpdatePostUseCase");
794
+ }
795
+ /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */
796
+ async execute(params) {
797
+ const input = import_content_contracts6.updatePostSchema.parse(params.input);
798
+ const existing = await this.findOrFail(params);
799
+ const values = optionalFields(input);
800
+ if (input.title !== void 0) values.title = input.title;
801
+ if (input.body !== void 0) {
802
+ values.body = input.body;
803
+ values.readingTimeMinutes = this.readingTime(input.body);
804
+ }
805
+ if (input.tags !== void 0 || input.tagLabels !== void 0) {
806
+ const tags = (0, import_content_contracts6.normalizeTags)(input.tags ?? existing.tags);
807
+ values.tags = tags;
808
+ values.tagLabels = (0, import_content_contracts6.buildTagLabels)({
809
+ typed: input.tags ?? tags,
810
+ explicit: input.tagLabels,
811
+ previous: existing.tagLabels
812
+ });
813
+ }
814
+ if (input.slug !== void 0 && input.slug !== existing.slug) {
815
+ await this.assertSlugAvailable(params.companyId, input.slug, existing.id);
816
+ values.slug = input.slug;
817
+ await this.dependencies.posts.recordFormerSlug({
818
+ companyId: params.companyId,
819
+ postId: existing.id,
820
+ slug: existing.slug
821
+ });
822
+ }
823
+ return this.save(params, values, import_content_contracts6.POST_EVENT.UPDATED);
824
+ }
825
+ };
826
+ var PublishPostUseCase = class extends PostUseCaseBase {
827
+ static {
828
+ __name(this, "PublishPostUseCase");
829
+ }
830
+ /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
831
+ async execute(params) {
832
+ const input = import_content_contracts6.publishPostSchema.parse(params.input ?? {});
833
+ const existing = await this.findOrFail(params);
834
+ if (existing.isTemplate) throw new import_content_contracts6.TemplateNotPublishableError(params.id);
835
+ const now = this.now();
836
+ const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
837
+ const status = publishedAt > now ? import_content_contracts6.POST_STATUS.SCHEDULED : import_content_contracts6.POST_STATUS.PUBLISHED;
838
+ return this.save(params, {
839
+ status,
840
+ publishedAt
841
+ }, import_content_contracts6.POST_EVENT.PUBLISHED);
842
+ }
843
+ };
844
+ var UnpublishPostUseCase = class extends PostUseCaseBase {
845
+ static {
846
+ __name(this, "UnpublishPostUseCase");
847
+ }
848
+ /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */
849
+ async execute(params) {
850
+ await this.findOrFail(params);
851
+ return this.save(params, {
852
+ status: import_content_contracts6.POST_STATUS.DRAFT,
853
+ publishedAt: null
854
+ }, import_content_contracts6.POST_EVENT.UNPUBLISHED);
855
+ }
856
+ };
857
+ var ArchivePostUseCase = class extends PostUseCaseBase {
858
+ static {
859
+ __name(this, "ArchivePostUseCase");
860
+ }
861
+ /** "Excluir" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */
862
+ async execute(params) {
863
+ await this.findOrFail(params);
864
+ return this.save(params, {
865
+ status: import_content_contracts6.POST_STATUS.ARCHIVED
866
+ }, import_content_contracts6.POST_EVENT.ARCHIVED);
867
+ }
868
+ };
869
+ var GetPostUseCase = class extends PostUseCaseBase {
870
+ static {
871
+ __name(this, "GetPostUseCase");
872
+ }
873
+ async execute(params) {
874
+ return toPost(await this.findOrFail(params), this.now());
875
+ }
876
+ };
877
+ var ListPostsUseCase = class extends PostUseCaseBase {
878
+ static {
879
+ __name(this, "ListPostsUseCase");
880
+ }
881
+ async execute(params) {
882
+ const { companyId, ...rawQuery } = params;
883
+ const query = import_content_contracts6.listPostsQuerySchema.parse(rawQuery);
884
+ const { tag: rawTag, ...rest } = query;
885
+ const tags = rawTag ? (0, import_content_contracts6.normalizeTags)(rawTag.split(",")) : [];
886
+ const now = this.now();
887
+ const page = await this.dependencies.posts.listForAdmin({
888
+ companyId,
889
+ ...rest,
890
+ isTemplate: query.isTemplate ?? false,
891
+ now,
892
+ ...tags.length > 0 ? {
893
+ tags
894
+ } : {}
895
+ });
896
+ return {
897
+ data: page.rows.map((row) => toPostSummary(row, now)),
898
+ pagination: toPagination({
899
+ total: page.total,
900
+ page: query.page,
901
+ pageSize: query.pageSize
902
+ })
903
+ };
904
+ }
905
+ };
906
+
907
+ // src/use-cases/PublicPost.use-cases.ts
908
+ var import_content_contracts7 = require("@adatechnology/content-contracts");
909
+ var GetPublishedPostBySlugUseCase = class {
910
+ static {
911
+ __name(this, "GetPublishedPostBySlugUseCase");
912
+ }
913
+ dependencies;
914
+ constructor(dependencies) {
915
+ this.dependencies = dependencies;
916
+ }
917
+ /**
918
+ * `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto
919
+ * manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`
920
+ * do resultado com o pedido e redireciona (301) quando forem diferentes.
921
+ */
922
+ async execute(params) {
923
+ const { posts: posts2, clock } = this.dependencies;
924
+ const parsed = (0, import_content_contracts7.parsePostRef)(params.slug);
925
+ const query = {
926
+ companyId: params.companyId,
927
+ now: clock.now()
928
+ };
929
+ const row = (parsed.shortId ? await posts2.findPublicByShortId({
930
+ ...query,
931
+ shortId: parsed.shortId
932
+ }) : void 0) ?? await posts2.findPublicBySlug({
933
+ ...query,
934
+ slug: parsed.slug
935
+ }) ?? await posts2.findPublicByFormerSlug({
936
+ ...query,
937
+ slug: parsed.slug
938
+ });
939
+ if (!row) throw new import_content_contracts7.PostNotFoundError(parsed.slug);
940
+ return toPublicPost(row);
941
+ }
942
+ };
943
+ var ListPublishedPostsUseCase = class {
944
+ static {
945
+ __name(this, "ListPublishedPostsUseCase");
946
+ }
947
+ dependencies;
948
+ constructor(dependencies) {
949
+ this.dependencies = dependencies;
950
+ }
951
+ async execute(params) {
952
+ const { companyId, ...rawQuery } = params;
953
+ const query = import_content_contracts7.listPublishedPostsQuerySchema.parse(rawQuery);
954
+ const tag = query.tag ? (0, import_content_contracts7.normalizeTag)(query.tag) : void 0;
955
+ const page = await this.dependencies.posts.listPublic({
956
+ companyId,
957
+ now: this.dependencies.clock.now(),
958
+ page: query.page,
959
+ pageSize: query.pageSize,
960
+ ...tag ? {
961
+ tag
962
+ } : {}
963
+ });
964
+ return {
965
+ data: page.rows.map(toPublicPostSummary),
966
+ pagination: toPagination({
967
+ total: page.total,
968
+ page: query.page,
969
+ pageSize: query.pageSize
970
+ })
971
+ };
972
+ }
973
+ };
974
+ var TAG_SCOPE = {
975
+ PUBLIC: "public",
976
+ ADMIN: "admin"
977
+ };
978
+ var ListTagsUseCase = class {
979
+ static {
980
+ __name(this, "ListTagsUseCase");
981
+ }
982
+ dependencies;
983
+ constructor(dependencies) {
984
+ this.dependencies = dependencies;
985
+ }
986
+ /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */
987
+ async execute(params) {
988
+ return this.dependencies.posts.listTags({
989
+ companyId: params.companyId,
990
+ ...params.scope === TAG_SCOPE.PUBLIC ? {
991
+ publicAt: this.dependencies.clock.now()
992
+ } : {}
993
+ });
994
+ }
995
+ };
996
+
997
+ // src/use-cases/Recurrence.use-cases.ts
998
+ var import_content_contracts8 = require("@adatechnology/content-contracts");
999
+ var RecurrenceUseCaseBase = class RecurrenceUseCaseBase2 {
1000
+ static {
1001
+ __name(this, "RecurrenceUseCaseBase");
1002
+ }
1003
+ dependencies;
1004
+ constructor(dependencies) {
1005
+ this.dependencies = dependencies;
1006
+ }
1007
+ async toRule(row) {
1008
+ const template = await this.dependencies.posts.findById({
1009
+ companyId: row.companyId,
1010
+ id: row.templateId
1011
+ });
1012
+ return {
1013
+ id: row.id,
1014
+ companyId: row.companyId,
1015
+ templateId: row.templateId,
1016
+ templateTitle: template?.title ?? "",
1017
+ frequency: row.frequency,
1018
+ isActive: row.isActive,
1019
+ nextRunAt: row.nextRunAt.toISOString(),
1020
+ lastRunAt: row.lastRunAt?.toISOString() ?? null,
1021
+ lastPostId: row.lastPostId,
1022
+ createdAt: row.createdAt.toISOString()
1023
+ };
1024
+ }
1025
+ async findOrFail(params) {
1026
+ const row = await this.dependencies.recurrences.findById(params);
1027
+ if (!row) throw new import_content_contracts8.RecurrenceNotFoundError(params.id);
1028
+ return row;
1029
+ }
1030
+ };
1031
+ var CreateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1032
+ static {
1033
+ __name(this, "CreateRecurrenceUseCase");
1034
+ }
1035
+ async execute(params) {
1036
+ const input = import_content_contracts8.createRecurrenceSchema.parse(params.input);
1037
+ const template = await this.dependencies.posts.findById({
1038
+ companyId: params.companyId,
1039
+ id: input.templateId
1040
+ });
1041
+ if (!template) throw new import_content_contracts8.PostNotFoundError(input.templateId);
1042
+ if (!template.isTemplate) throw new import_content_contracts8.NotATemplateError(input.templateId);
1043
+ const startsAt = new Date(input.startsAt);
1044
+ const values = {
1045
+ companyId: params.companyId,
1046
+ templateId: input.templateId,
1047
+ frequency: input.frequency,
1048
+ anchorDay: startsAt.getUTCDate(),
1049
+ nextRunAt: startsAt
1050
+ };
1051
+ return this.toRule(await this.dependencies.recurrences.create(values));
1052
+ }
1053
+ };
1054
+ var ListRecurrencesUseCase = class extends RecurrenceUseCaseBase {
1055
+ static {
1056
+ __name(this, "ListRecurrencesUseCase");
1057
+ }
1058
+ async execute(params) {
1059
+ const rows = await this.dependencies.recurrences.list(params);
1060
+ return Promise.all(rows.map((row) => this.toRule(row)));
1061
+ }
1062
+ };
1063
+ var UpdateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1064
+ static {
1065
+ __name(this, "UpdateRecurrenceUseCase");
1066
+ }
1067
+ /** Pausar/retomar e remarcar a próxima execução. */
1068
+ async execute(params) {
1069
+ const input = import_content_contracts8.updateRecurrenceSchema.parse(params.input);
1070
+ await this.findOrFail(params);
1071
+ const values = {};
1072
+ if (input.isActive !== void 0) values.isActive = input.isActive;
1073
+ if (input.nextRunAt !== void 0) {
1074
+ values.nextRunAt = new Date(input.nextRunAt);
1075
+ values.anchorDay = values.nextRunAt.getUTCDate();
1076
+ }
1077
+ const row = await this.dependencies.recurrences.update({
1078
+ companyId: params.companyId,
1079
+ id: params.id,
1080
+ values
1081
+ });
1082
+ if (!row) throw new import_content_contracts8.RecurrenceNotFoundError(params.id);
1083
+ return this.toRule(row);
1084
+ }
1085
+ };
1086
+ var RemoveRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1087
+ static {
1088
+ __name(this, "RemoveRecurrenceUseCase");
1089
+ }
1090
+ /** Apaga só a regra: os posts que ela já publicou continuam no ar. */
1091
+ async execute(params) {
1092
+ if (!await this.dependencies.recurrences.remove(params)) throw new import_content_contracts8.RecurrenceNotFoundError(params.id);
1093
+ }
1094
+ };
1095
+
1096
+ // src/use-cases/Scheduling.use-cases.ts
1097
+ var import_content_contracts11 = require("@adatechnology/content-contracts");
1098
+
1099
+ // src/shared/recurrence.ts
1100
+ var import_content_contracts9 = require("@adatechnology/content-contracts");
1101
+ var WEEK_MS = 7 * 24 * 60 * 60 * 1e3;
1102
+ function daysInMonth(year, monthIndex) {
1103
+ return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
1104
+ }
1105
+ __name(daysInMonth, "daysInMonth");
1106
+ function addMonths(from, anchorDay, months) {
1107
+ const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1));
1108
+ const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));
1109
+ return new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth(), day, from.getUTCHours(), from.getUTCMinutes(), from.getUTCSeconds(), from.getUTCMilliseconds()));
1110
+ }
1111
+ __name(addMonths, "addMonths");
1112
+ function nextOccurrence(params) {
1113
+ if (params.frequency === import_content_contracts9.RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS);
1114
+ return addMonths(params.from, params.anchorDay, 1);
1115
+ }
1116
+ __name(nextOccurrence, "nextOccurrence");
1117
+ function nextOccurrenceAfter(params) {
1118
+ let candidate = nextOccurrence(params);
1119
+ while (candidate <= params.now) candidate = nextOccurrence({
1120
+ ...params,
1121
+ from: candidate
1122
+ });
1123
+ return candidate;
1124
+ }
1125
+ __name(nextOccurrenceAfter, "nextOccurrenceAfter");
1126
+ function toDateStamp(date) {
1127
+ return date.toISOString().slice(0, 10);
1128
+ }
1129
+ __name(toDateStamp, "toDateStamp");
1130
+
1131
+ // src/use-cases/Template.use-cases.ts
1132
+ var import_content_contracts10 = require("@adatechnology/content-contracts");
1133
+ var TEMPLATE_SLUG_PREFIX = "modelo";
1134
+ function copiableFields(row) {
1135
+ return {
1136
+ excerpt: row.excerpt,
1137
+ body: row.body,
1138
+ coverImageUrl: row.coverImageUrl,
1139
+ coverImageAlt: row.coverImageAlt,
1140
+ tags: (0, import_content_contracts10.normalizeTags)(row.tags),
1141
+ tagLabels: row.tagLabels,
1142
+ authorName: row.authorName,
1143
+ seoTitle: row.seoTitle,
1144
+ seoDescription: row.seoDescription,
1145
+ readingTimeMinutes: row.readingTimeMinutes
1146
+ };
1147
+ }
1148
+ __name(copiableFields, "copiableFields");
1149
+ var TemplateUseCaseBase = class TemplateUseCaseBase2 extends PostUseCaseBase {
1150
+ static {
1151
+ __name(this, "TemplateUseCaseBase");
1152
+ }
1153
+ async insertCopy(params) {
1154
+ const row = await this.dependencies.posts.create({
1155
+ ...copiableFields(params.source),
1156
+ companyId: params.companyId,
1157
+ slug: params.slug,
1158
+ shortId: await this.generateShortId(params.companyId),
1159
+ title: params.title,
1160
+ isTemplate: params.isTemplate,
1161
+ status: params.status ?? import_content_contracts10.POST_STATUS.DRAFT,
1162
+ ...params.publishedAt ? {
1163
+ publishedAt: params.publishedAt
1164
+ } : {}
1165
+ }).catch((error) => {
1166
+ if (isUniqueViolation(error)) throw new import_content_contracts10.DuplicateSlugError(params.slug);
1167
+ throw error;
1168
+ });
1169
+ const post = toPost(row, this.now());
1170
+ await notifyPostChanged(this.dependencies, import_content_contracts10.POST_EVENT.CREATED, post);
1171
+ return post;
1172
+ }
1173
+ };
1174
+ var SaveAsTemplateUseCase = class extends TemplateUseCaseBase {
1175
+ static {
1176
+ __name(this, "SaveAsTemplateUseCase");
1177
+ }
1178
+ /** Copia o post (qualquer status) para um modelo. O original não muda. */
1179
+ async execute(params) {
1180
+ const input = import_content_contracts10.saveAsTemplateSchema.parse(params.input ?? {});
1181
+ const source = await this.findOrFail(params);
1182
+ const title = input.title ?? source.title;
1183
+ const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`);
1184
+ return this.insertCopy({
1185
+ companyId: params.companyId,
1186
+ slug,
1187
+ title,
1188
+ source,
1189
+ isTemplate: true
1190
+ });
1191
+ }
1192
+ };
1193
+ var CreateFromTemplateUseCase = class extends TemplateUseCaseBase {
1194
+ static {
1195
+ __name(this, "CreateFromTemplateUseCase");
1196
+ }
1197
+ /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */
1198
+ async execute(params) {
1199
+ const input = import_content_contracts10.createFromTemplateSchema.parse(params.input ?? {});
1200
+ const template = await this.findOrFail(params);
1201
+ if (!template.isTemplate) throw new import_content_contracts10.NotATemplateError(params.id);
1202
+ const title = input.title ?? template.title;
1203
+ if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug);
1204
+ const slug = input.slug ?? await this.generateSlug(params.companyId, title);
1205
+ return this.insertCopy({
1206
+ companyId: params.companyId,
1207
+ slug,
1208
+ title,
1209
+ source: template,
1210
+ isTemplate: false
1211
+ });
1212
+ }
1213
+ };
1214
+ var CountPostsUseCase = class extends PostUseCaseBase {
1215
+ static {
1216
+ __name(this, "CountPostsUseCase");
1217
+ }
1218
+ /** Números das abas do painel, numa consulta só. */
1219
+ async execute(params) {
1220
+ return this.dependencies.posts.countByStatus({
1221
+ companyId: params.companyId,
1222
+ now: this.now()
1223
+ });
1224
+ }
1225
+ };
1226
+
1227
+ // src/use-cases/Scheduling.use-cases.ts
1228
+ var DEFAULT_BATCH_LIMIT = 100;
1229
+ var DATE_SUFFIX_LENGTH = 11;
1230
+ var FALLBACK_SLUG2 = "post";
1231
+ var RepublishPostUseCase = class extends PostUseCaseBase {
1232
+ static {
1233
+ __name(this, "RepublishPostUseCase");
1234
+ }
1235
+ /**
1236
+ * Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o
1237
+ * link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo
1238
+ * duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.
1239
+ */
1240
+ async execute(params) {
1241
+ const input = import_content_contracts11.republishPostSchema.parse(params.input ?? {});
1242
+ const existing = await this.findOrFail(params);
1243
+ const now = this.now();
1244
+ if (existing.isTemplate || effectiveStatus(existing, now) !== import_content_contracts11.POST_STATUS.PUBLISHED) {
1245
+ throw new import_content_contracts11.PostNotPublishedError(params.id);
1246
+ }
1247
+ const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
1248
+ if (publishedAt > now) throw new import_content_contracts11.RepublishDateInFutureError();
1249
+ return this.save(params, {
1250
+ status: import_content_contracts11.POST_STATUS.PUBLISHED,
1251
+ publishedAt
1252
+ }, import_content_contracts11.POST_EVENT.REPUBLISHED);
1253
+ }
1254
+ };
1255
+ var PublishDueUseCase = class extends PostUseCaseBase {
1256
+ static {
1257
+ __name(this, "PublishDueUseCase");
1258
+ }
1259
+ /**
1260
+ * Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado
1261
+ * por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.
1262
+ */
1263
+ async execute(params = {}) {
1264
+ const now = params.now ?? this.now();
1265
+ const limit = params.limit ?? DEFAULT_BATCH_LIMIT;
1266
+ const materialized = await this.materializeRecurrences({
1267
+ now,
1268
+ limit
1269
+ });
1270
+ const rows = await this.dependencies.posts.claimDueScheduled({
1271
+ now,
1272
+ limit
1273
+ });
1274
+ for (const row of rows) {
1275
+ await notifyPostChanged(this.dependencies, import_content_contracts11.POST_EVENT.PUBLISHED, toPost(row, now));
1276
+ }
1277
+ if (rows.length > 0 || materialized > 0) {
1278
+ this.dependencies.logger?.info("content-module: publishDue", {
1279
+ published: rows.length,
1280
+ materialized
1281
+ });
1282
+ }
1283
+ return {
1284
+ published: rows.length,
1285
+ materialized
1286
+ };
1287
+ }
1288
+ materializeRecurrences(params) {
1289
+ return this.dependencies.recurrences.processDue({
1290
+ ...params,
1291
+ handle: /* @__PURE__ */ __name((rule) => this.materialize(rule, params.now), "handle")
1292
+ });
1293
+ }
1294
+ /** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */
1295
+ async materialize(rule, now) {
1296
+ const advance = {
1297
+ nextRunAt: nextOccurrenceAfter({
1298
+ frequency: rule.frequency,
1299
+ from: rule.nextRunAt,
1300
+ anchorDay: rule.anchorDay,
1301
+ now
1302
+ })
1303
+ };
1304
+ const template = await this.dependencies.posts.findById({
1305
+ companyId: rule.companyId,
1306
+ id: rule.templateId
1307
+ });
1308
+ if (!template || !template.isTemplate || template.status === import_content_contracts11.POST_STATUS.ARCHIVED) {
1309
+ this.dependencies.logger?.warn("content-module: modelo da recorr\xEAncia indispon\xEDvel", {
1310
+ ruleId: rule.id
1311
+ });
1312
+ return {
1313
+ isActive: false
1314
+ };
1315
+ }
1316
+ const base = ((0, import_content_contracts11.slugify)(template.title) || FALLBACK_SLUG2).slice(0, import_content_contracts11.SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH);
1317
+ const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, "")}-${toDateStamp(now)}`);
1318
+ const row = await this.dependencies.posts.create({
1319
+ ...copiableFields(template),
1320
+ companyId: rule.companyId,
1321
+ slug,
1322
+ shortId: await this.generateShortId(rule.companyId),
1323
+ title: template.title,
1324
+ isTemplate: false,
1325
+ status: import_content_contracts11.POST_STATUS.PUBLISHED,
1326
+ publishedAt: now
1327
+ });
1328
+ const post = toPost(row, now);
1329
+ await notifyPostChanged(this.dependencies, import_content_contracts11.POST_EVENT.CREATED, post);
1330
+ await notifyPostChanged(this.dependencies, import_content_contracts11.POST_EVENT.PUBLISHED, post);
1331
+ return {
1332
+ ...advance,
1333
+ lastRunAt: now,
1334
+ lastPostId: row.id
1335
+ };
1336
+ }
1337
+ };
1338
+
1339
+ // src/use-cases/UploadCoverImage.use-case.ts
1340
+ var import_content_contracts12 = require("@adatechnology/content-contracts");
1341
+
1342
+ // src/shared/coverImage.constant.ts
1343
+ var COVER_IMAGE = {
1344
+ MAX_BYTES: 1024 * 1024,
1345
+ KEY_PREFIX: "content/posts",
1346
+ EXTENSION_BY_MIME: {
1347
+ "image/jpeg": "jpg",
1348
+ "image/png": "png",
1349
+ "image/webp": "webp"
1350
+ }
1351
+ };
1352
+
1353
+ // src/use-cases/UploadCoverImage.use-case.ts
1354
+ var UploadCoverImageUseCase = class {
1355
+ static {
1356
+ __name(this, "UploadCoverImageUseCase");
1357
+ }
1358
+ dependencies;
1359
+ constructor(dependencies) {
1360
+ this.dependencies = dependencies;
1361
+ }
1362
+ async execute(params) {
1363
+ const storage = this.dependencies.imageStorage;
1364
+ if (!storage) throw new import_content_contracts12.ImageStorageDisabledError();
1365
+ const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
1366
+ const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType];
1367
+ if (!extension) throw new import_content_contracts12.InvalidCoverImageError("unsupported_type");
1368
+ if (params.bytes.byteLength === 0) throw new import_content_contracts12.InvalidCoverImageError("empty");
1369
+ if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new import_content_contracts12.InvalidCoverImageError("too_large");
1370
+ const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
1371
+ return storage.upload({
1372
+ buffer: params.bytes,
1373
+ mimeType,
1374
+ key
1375
+ });
1376
+ }
1377
+ };
1378
+
1379
+ // src/ContentModule.ts
1380
+ var SYSTEM_CLOCK = {
1381
+ now: /* @__PURE__ */ __name(() => /* @__PURE__ */ new Date(), "now")
1382
+ };
1383
+ function assertValidConfig(config) {
1384
+ if (config.feed && !/^https?:\/\/[^/]/i.test(config.feed.siteUrl)) throw new import_content_contracts13.ConfigMissingError("feed.siteUrl");
1385
+ if (config.feed && !config.feed.title.trim()) throw new import_content_contracts13.ConfigMissingError("feed.title");
1386
+ if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes("{slug}")) {
1387
+ throw new import_content_contracts13.ConfigMissingError("feed.postPathTemplate");
1388
+ }
1389
+ if (config.wordsPerMinute !== void 0 && !(config.wordsPerMinute > 0)) throw new import_content_contracts13.ConfigMissingError("wordsPerMinute");
1390
+ }
1391
+ __name(assertValidConfig, "assertValidConfig");
1392
+ function createContentModule(params) {
1393
+ const config = params.config ?? {};
1394
+ assertValidConfig(config);
1395
+ const posts2 = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : void 0);
1396
+ if (!posts2) throw new import_content_contracts13.ConfigMissingError("db");
1397
+ const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : void 0);
1398
+ if (!recurrences) throw new import_content_contracts13.ConfigMissingError("db");
1399
+ const dependencies = {
1400
+ posts: posts2,
1401
+ recurrences,
1402
+ config,
1403
+ clock: params.providers?.clock ?? SYSTEM_CLOCK,
1404
+ ...params.hooks ? {
1405
+ hooks: params.hooks
1406
+ } : {},
1407
+ ...params.providers?.imageStorage ? {
1408
+ imageStorage: params.providers.imageStorage
1409
+ } : {},
1410
+ ...params.providers?.logger ? {
1411
+ logger: params.providers.logger
1412
+ } : {}
1413
+ };
1414
+ return {
1415
+ useCases: {
1416
+ createPost: new CreatePostUseCase(dependencies),
1417
+ updatePost: new UpdatePostUseCase(dependencies),
1418
+ archivePost: new ArchivePostUseCase(dependencies),
1419
+ publishPost: new PublishPostUseCase(dependencies),
1420
+ unpublishPost: new UnpublishPostUseCase(dependencies),
1421
+ getPost: new GetPostUseCase(dependencies),
1422
+ listPosts: new ListPostsUseCase(dependencies),
1423
+ getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),
1424
+ listPublishedPosts: new ListPublishedPostsUseCase(dependencies),
1425
+ listTags: new ListTagsUseCase(dependencies),
1426
+ countPosts: new CountPostsUseCase(dependencies),
1427
+ saveAsTemplate: new SaveAsTemplateUseCase(dependencies),
1428
+ createFromTemplate: new CreateFromTemplateUseCase(dependencies),
1429
+ republishPost: new RepublishPostUseCase(dependencies),
1430
+ createRecurrence: new CreateRecurrenceUseCase(dependencies),
1431
+ listRecurrences: new ListRecurrencesUseCase(dependencies),
1432
+ updateRecurrence: new UpdateRecurrenceUseCase(dependencies),
1433
+ removeRecurrence: new RemoveRecurrenceUseCase(dependencies),
1434
+ publishDue: new PublishDueUseCase(dependencies),
1435
+ ...dependencies.imageStorage ? {
1436
+ uploadCoverImage: new UploadCoverImageUseCase(dependencies)
1437
+ } : {},
1438
+ ...config.feed ? {
1439
+ buildFeed: new BuildFeedUseCase(dependencies, config.feed),
1440
+ listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed)
1441
+ } : {}
1442
+ },
1443
+ config
1444
+ };
1445
+ }
1446
+ __name(createContentModule, "createContentModule");
1447
+
1448
+ // src/http/adminRoutes.ts
1449
+ var import_content_contracts15 = require("@adatechnology/content-contracts");
1450
+
1451
+ // src/http/requireCompany.ts
1452
+ var import_content_contracts14 = require("@adatechnology/content-contracts");
1453
+ function requireCompany(context) {
1454
+ if (!context.auth?.companyId) {
1455
+ throw new import_content_contracts14.ContentError("Rota exige contexto autenticado.", 401, import_content_contracts14.CONTENT_ERROR_CODES.CONFIG_MISSING);
1456
+ }
1457
+ return context.auth.companyId;
1458
+ }
1459
+ __name(requireCompany, "requireCompany");
1460
+
1461
+ // src/http/adminRoutes.ts
1462
+ function reference(context) {
1463
+ return {
1464
+ companyId: requireCompany(context),
1465
+ id: context.params.id ?? ""
1466
+ };
1467
+ }
1468
+ __name(reference, "reference");
1469
+ var json = /* @__PURE__ */ __name((status, data) => ({
1470
+ kind: "json",
1471
+ status,
1472
+ body: {
1473
+ data
1474
+ }
1475
+ }), "json");
1476
+ function buildAdminRoutes(module2) {
1477
+ const { useCases } = module2;
1478
+ const requiredScopes = module2.config.adminScopes ?? import_content_contracts15.DEFAULT_ADMIN_SCOPES;
1479
+ const admin = {
1480
+ scope: "admin",
1481
+ requiredScopes
1482
+ };
1483
+ const uploadRoutes = useCases.uploadCoverImage ? [
1484
+ {
1485
+ ...admin,
1486
+ method: "POST",
1487
+ path: "/posts/cover-images",
1488
+ operationId: "uploadPostCoverImage",
1489
+ summary: "Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL",
1490
+ async handler(context) {
1491
+ const upload = useCases.uploadCoverImage;
1492
+ if (!upload) return {
1493
+ kind: "empty",
1494
+ status: 404
1495
+ };
1496
+ const result = await upload.execute({
1497
+ companyId: requireCompany(context),
1498
+ bytes: context.rawBody ?? new Uint8Array(),
1499
+ mimeType: context.headers["content-type"] ?? ""
1500
+ });
1501
+ return json(201, result);
1502
+ }
1503
+ }
1504
+ ] : [];
1505
+ return [
1506
+ {
1507
+ ...admin,
1508
+ method: "GET",
1509
+ path: "/posts",
1510
+ querySchema: import_content_contracts15.listPostsQuerySchema,
1511
+ operationId: "listPosts",
1512
+ summary: "Lista posts da empresa (todos os status), com filtro por status, tag e busca",
1513
+ async handler(context) {
1514
+ const result = await useCases.listPosts.execute({
1515
+ companyId: requireCompany(context),
1516
+ ...context.query
1517
+ });
1518
+ return {
1519
+ kind: "json",
1520
+ status: 200,
1521
+ body: result
1522
+ };
1523
+ }
1524
+ },
1525
+ {
1526
+ ...admin,
1527
+ method: "POST",
1528
+ path: "/posts",
1529
+ bodySchema: import_content_contracts15.createPostSchema,
1530
+ operationId: "createPost",
1531
+ summary: "Cria um post como rascunho; sem slug, gera a partir do t\xEDtulo",
1532
+ async handler(context) {
1533
+ const post = await useCases.createPost.execute({
1534
+ companyId: requireCompany(context),
1535
+ input: context.body
1536
+ });
1537
+ return json(201, post);
1538
+ }
1539
+ },
1540
+ // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria "tags".
1541
+ {
1542
+ ...admin,
1543
+ method: "GET",
1544
+ path: "/posts/tags",
1545
+ operationId: "listPostTags",
1546
+ summary: "Tags usadas em qualquer post da empresa, com contagem",
1547
+ async handler(context) {
1548
+ return json(200, await useCases.listTags.execute({
1549
+ companyId: requireCompany(context),
1550
+ scope: TAG_SCOPE.ADMIN
1551
+ }));
1552
+ }
1553
+ },
1554
+ {
1555
+ ...admin,
1556
+ method: "GET",
1557
+ path: "/posts/counts",
1558
+ operationId: "countPosts",
1559
+ summary: "Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos",
1560
+ async handler(context) {
1561
+ return json(200, await useCases.countPosts.execute({
1562
+ companyId: requireCompany(context)
1563
+ }));
1564
+ }
1565
+ },
1566
+ ...recurrenceRoutes(module2),
1567
+ ...uploadRoutes,
1568
+ {
1569
+ ...admin,
1570
+ method: "GET",
1571
+ path: "/posts/:id",
1572
+ operationId: "getPost",
1573
+ summary: "L\xEA um post da empresa (qualquer status)",
1574
+ async handler(context) {
1575
+ return json(200, await useCases.getPost.execute(reference(context)));
1576
+ }
1577
+ },
1578
+ {
1579
+ ...admin,
1580
+ method: "PATCH",
1581
+ path: "/posts/:id",
1582
+ bodySchema: import_content_contracts15.updatePostSchema,
1583
+ operationId: "updatePost",
1584
+ summary: "Atualiza campos de um post; trocar o t\xEDtulo n\xE3o troca o slug",
1585
+ async handler(context) {
1586
+ return json(200, await useCases.updatePost.execute({
1587
+ ...reference(context),
1588
+ input: context.body
1589
+ }));
1590
+ }
1591
+ },
1592
+ {
1593
+ ...admin,
1594
+ method: "DELETE",
1595
+ path: "/posts/:id",
1596
+ operationId: "archivePost",
1597
+ summary: "Arquiva o post: sai do site, conte\xFAdo e slug continuam guardados",
1598
+ async handler(context) {
1599
+ await useCases.archivePost.execute(reference(context));
1600
+ return {
1601
+ kind: "empty",
1602
+ status: 204
1603
+ };
1604
+ }
1605
+ },
1606
+ {
1607
+ ...admin,
1608
+ method: "POST",
1609
+ path: "/posts/:id/publish",
1610
+ // Opcional: `POST /publish` sem corpo publica agora.
1611
+ bodySchema: import_content_contracts15.publishPostSchema.optional(),
1612
+ operationId: "publishPost",
1613
+ summary: "Publica agora, ou agenda quando `publishedAt` \xE9 futuro",
1614
+ async handler(context) {
1615
+ return json(200, await useCases.publishPost.execute({
1616
+ ...reference(context),
1617
+ input: context.body ?? {}
1618
+ }));
1619
+ }
1620
+ },
1621
+ {
1622
+ ...admin,
1623
+ method: "POST",
1624
+ path: "/posts/:id/unpublish",
1625
+ operationId: "unpublishPost",
1626
+ summary: "Tira do ar (ou cancela o agendamento) e volta a rascunho",
1627
+ async handler(context) {
1628
+ return json(200, await useCases.unpublishPost.execute(reference(context)));
1629
+ }
1630
+ },
1631
+ {
1632
+ ...admin,
1633
+ method: "POST",
1634
+ path: "/posts/:id/republish",
1635
+ bodySchema: import_content_contracts15.republishPostSchema.optional(),
1636
+ operationId: "republishPost",
1637
+ summary: "Republica um post no ar com nova data, mantendo o mesmo endere\xE7o (SEO); data futura \xE9 recusada",
1638
+ async handler(context) {
1639
+ return json(200, await useCases.republishPost.execute({
1640
+ ...reference(context),
1641
+ input: context.body ?? {}
1642
+ }));
1643
+ }
1644
+ },
1645
+ {
1646
+ ...admin,
1647
+ method: "POST",
1648
+ path: "/posts/:id/save-as-template",
1649
+ bodySchema: import_content_contracts15.saveAsTemplateSchema.optional(),
1650
+ operationId: "savePostAsTemplate",
1651
+ summary: "Copia o post para um modelo (o original n\xE3o muda)",
1652
+ async handler(context) {
1653
+ return json(201, await useCases.saveAsTemplate.execute({
1654
+ ...reference(context),
1655
+ input: context.body ?? {}
1656
+ }));
1657
+ }
1658
+ },
1659
+ {
1660
+ ...admin,
1661
+ method: "POST",
1662
+ path: "/posts/:id/from-template",
1663
+ bodySchema: import_content_contracts15.createFromTemplateSchema.optional(),
1664
+ operationId: "createPostFromTemplate",
1665
+ summary: "Cria um rascunho novo a partir do modelo `:id`",
1666
+ async handler(context) {
1667
+ return json(201, await useCases.createFromTemplate.execute({
1668
+ ...reference(context),
1669
+ input: context.body ?? {}
1670
+ }));
1671
+ }
1672
+ }
1673
+ ];
1674
+ }
1675
+ __name(buildAdminRoutes, "buildAdminRoutes");
1676
+ function recurrenceRoutes(module2) {
1677
+ const { useCases } = module2;
1678
+ const admin = {
1679
+ scope: "admin",
1680
+ requiredScopes: module2.config.adminScopes ?? import_content_contracts15.DEFAULT_ADMIN_SCOPES
1681
+ };
1682
+ return [
1683
+ {
1684
+ ...admin,
1685
+ method: "GET",
1686
+ path: "/recurrences",
1687
+ operationId: "listRecurrences",
1688
+ summary: "Regras de recorr\xEAncia da empresa",
1689
+ async handler(context) {
1690
+ return json(200, await useCases.listRecurrences.execute({
1691
+ companyId: requireCompany(context)
1692
+ }));
1693
+ }
1694
+ },
1695
+ {
1696
+ ...admin,
1697
+ method: "POST",
1698
+ path: "/recurrences",
1699
+ bodySchema: import_content_contracts15.createRecurrenceSchema,
1700
+ operationId: "createRecurrence",
1701
+ summary: "Cria regra: publica um post novo, copiado do modelo, toda semana ou todo m\xEAs",
1702
+ async handler(context) {
1703
+ return json(201, await useCases.createRecurrence.execute({
1704
+ companyId: requireCompany(context),
1705
+ input: context.body
1706
+ }));
1707
+ }
1708
+ },
1709
+ {
1710
+ ...admin,
1711
+ method: "PATCH",
1712
+ path: "/recurrences/:id",
1713
+ bodySchema: import_content_contracts15.updateRecurrenceSchema,
1714
+ operationId: "updateRecurrence",
1715
+ summary: "Pausa, retoma ou remarca a pr\xF3xima execu\xE7\xE3o",
1716
+ async handler(context) {
1717
+ return json(200, await useCases.updateRecurrence.execute({
1718
+ ...reference(context),
1719
+ input: context.body
1720
+ }));
1721
+ }
1722
+ },
1723
+ {
1724
+ ...admin,
1725
+ method: "DELETE",
1726
+ path: "/recurrences/:id",
1727
+ operationId: "removeRecurrence",
1728
+ summary: "Apaga a regra; os posts j\xE1 publicados por ela continuam no ar",
1729
+ async handler(context) {
1730
+ await useCases.removeRecurrence.execute(reference(context));
1731
+ return {
1732
+ kind: "empty",
1733
+ status: 204
1734
+ };
1735
+ }
1736
+ }
1737
+ ];
1738
+ }
1739
+ __name(recurrenceRoutes, "recurrenceRoutes");
1740
+
1741
+ // src/http/publicRoutes.ts
1742
+ var import_content_contracts16 = require("@adatechnology/content-contracts");
1743
+ var PUBLIC = {
1744
+ scope: "public"
1745
+ };
1746
+ function buildPublicRoutes(params) {
1747
+ const { useCases } = params.module;
1748
+ const cacheControl = params.module.config.publicCacheControl ?? import_content_contracts16.DEFAULT_PUBLIC_CACHE_CONTROL;
1749
+ const cached = /* @__PURE__ */ __name((data) => ({
1750
+ kind: "json",
1751
+ status: 200,
1752
+ body: data,
1753
+ headers: {
1754
+ "Cache-Control": cacheControl
1755
+ }
1756
+ }), "cached");
1757
+ async function resolveCompany(context) {
1758
+ const companyId = await params.companyResolver.resolve({
1759
+ headers: context.headers,
1760
+ query: context.query
1761
+ });
1762
+ if (!companyId) throw new import_content_contracts16.PostNotFoundError("company");
1763
+ return companyId;
1764
+ }
1765
+ __name(resolveCompany, "resolveCompany");
1766
+ const routes = [
1767
+ {
1768
+ ...PUBLIC,
1769
+ method: "GET",
1770
+ path: "/public/posts",
1771
+ querySchema: import_content_contracts16.listPublishedPostsQuerySchema,
1772
+ operationId: "listPublishedPosts",
1773
+ summary: "Posts publicados, mais recentes primeiro, com filtro por tag",
1774
+ async handler(context) {
1775
+ const result = await useCases.listPublishedPosts.execute({
1776
+ companyId: await resolveCompany(context),
1777
+ ...context.query
1778
+ });
1779
+ return cached(result);
1780
+ }
1781
+ },
1782
+ {
1783
+ ...PUBLIC,
1784
+ method: "GET",
1785
+ path: "/public/posts/:slug",
1786
+ operationId: "getPublishedPost",
1787
+ summary: "Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404",
1788
+ async handler(context) {
1789
+ const post = await useCases.getPublishedPostBySlug.execute({
1790
+ companyId: await resolveCompany(context),
1791
+ slug: context.params.slug ?? ""
1792
+ });
1793
+ return cached({
1794
+ data: post
1795
+ });
1796
+ }
1797
+ },
1798
+ {
1799
+ ...PUBLIC,
1800
+ method: "GET",
1801
+ path: "/public/tags",
1802
+ operationId: "listPublishedTags",
1803
+ summary: "Tags dos posts publicados, com contagem",
1804
+ async handler(context) {
1805
+ const tags = await useCases.listTags.execute({
1806
+ companyId: await resolveCompany(context),
1807
+ scope: TAG_SCOPE.PUBLIC
1808
+ });
1809
+ return cached({
1810
+ data: tags
1811
+ });
1812
+ }
1813
+ }
1814
+ ];
1815
+ const { buildFeed, listSitemapEntries } = useCases;
1816
+ if (!buildFeed || !listSitemapEntries) return routes;
1817
+ const feedRoute = /* @__PURE__ */ __name((path, format, contentType, operationId) => ({
1818
+ ...PUBLIC,
1819
+ method: "GET",
1820
+ path,
1821
+ operationId,
1822
+ summary: `Feed ${format.toUpperCase()} dos posts publicados`,
1823
+ async handler(context) {
1824
+ const body = await buildFeed.execute({
1825
+ companyId: await resolveCompany(context),
1826
+ format
1827
+ });
1828
+ return {
1829
+ kind: "text",
1830
+ status: 200,
1831
+ body,
1832
+ headers: {
1833
+ "Content-Type": contentType,
1834
+ "Cache-Control": cacheControl
1835
+ }
1836
+ };
1837
+ }
1838
+ }), "feedRoute");
1839
+ return [
1840
+ ...routes,
1841
+ feedRoute("/public/feed.xml", FEED_FORMAT.RSS, "application/rss+xml; charset=utf-8", "getRssFeed"),
1842
+ feedRoute("/public/atom.xml", FEED_FORMAT.ATOM, "application/atom+xml; charset=utf-8", "getAtomFeed"),
1843
+ {
1844
+ ...PUBLIC,
1845
+ method: "GET",
1846
+ path: "/public/sitemap-entries",
1847
+ operationId: "listSitemapEntries",
1848
+ summary: "Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele",
1849
+ async handler(context) {
1850
+ return cached({
1851
+ data: await listSitemapEntries.execute({
1852
+ companyId: await resolveCompany(context)
1853
+ })
1854
+ });
1855
+ }
1856
+ }
1857
+ ];
1858
+ }
1859
+ __name(buildPublicRoutes, "buildPublicRoutes");
1860
+
1861
+ // src/http/routes.ts
1862
+ function createContentRoutes(params) {
1863
+ const admin = buildAdminRoutes(params.module);
1864
+ if (!params.publicCompanyResolver) return admin;
1865
+ return [
1866
+ ...admin,
1867
+ ...buildPublicRoutes({
1868
+ module: params.module,
1869
+ companyResolver: params.publicCompanyResolver
1870
+ })
1871
+ ];
1872
+ }
1873
+ __name(createContentRoutes, "createContentRoutes");
1874
+
1875
+ // src/runMigrations.ts
1876
+ var import_node_path = require("path");
1877
+ var CONTENT_MIGRATIONS_TABLE = "content_migrations";
1878
+ function contentMigrationsFolder() {
1879
+ return (0, import_node_path.join)(__dirname, "migrations");
1880
+ }
1881
+ __name(contentMigrationsFolder, "contentMigrationsFolder");
1882
+ async function runContentMigrations(params) {
1883
+ await params.migrate(params.db, {
1884
+ migrationsFolder: contentMigrationsFolder(),
1885
+ migrationsTable: CONTENT_MIGRATIONS_TABLE
1886
+ });
1887
+ }
1888
+ __name(runContentMigrations, "runContentMigrations");
1889
+
1890
+ // src/testing/inMemoryPostStore.ts
1891
+ var import_node_crypto2 = require("crypto");
1892
+ var import_content_contracts17 = require("@adatechnology/content-contracts");
1893
+ function isPublic(row, now) {
1894
+ const live = row.status === import_content_contracts17.POST_STATUS.PUBLISHED || row.status === import_content_contracts17.POST_STATUS.SCHEDULED;
1895
+ return live && row.publishedAt !== null && row.publishedAt <= now;
1896
+ }
1897
+ __name(isPublic, "isPublic");
1898
+ function adminComparator(query) {
1899
+ const sign = query.order === "asc" ? 1 : -1;
1900
+ const value = /* @__PURE__ */ __name((row) => {
1901
+ if (query.sort === "title") return row.title.toLowerCase();
1902
+ if (query.sort === "status") return row.status;
1903
+ if (query.sort === "publishedAt") return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY;
1904
+ return row.updatedAt.getTime();
1905
+ }, "value");
1906
+ return (left, right) => {
1907
+ const a = value(left);
1908
+ const b = value(right);
1909
+ return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id);
1910
+ };
1911
+ }
1912
+ __name(adminComparator, "adminComparator");
1913
+ function paginate(rows, page, pageSize) {
1914
+ return {
1915
+ rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({
1916
+ ...row
1917
+ })),
1918
+ total: rows.length
1919
+ };
1920
+ }
1921
+ __name(paginate, "paginate");
1922
+ var UniqueViolation = class UniqueViolation2 extends Error {
1923
+ static {
1924
+ __name(this, "UniqueViolation");
1925
+ }
1926
+ code = "23505";
1927
+ };
1928
+ function createInMemoryPostStore(seed = []) {
1929
+ const rows = [
1930
+ ...seed
1931
+ ];
1932
+ const formerSlugs = [];
1933
+ const assertUniqueSlug = /* @__PURE__ */ __name((companyId, slug, ownId) => {
1934
+ if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {
1935
+ throw new UniqueViolation('duplicate key value violates unique constraint "idx_posts_company_slug"');
1936
+ }
1937
+ }, "assertUniqueSlug");
1938
+ return {
1939
+ rows,
1940
+ async findByShortId({ companyId, shortId }) {
1941
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId);
1942
+ return row ? {
1943
+ ...row
1944
+ } : void 0;
1945
+ },
1946
+ async findPublicByShortId({ companyId, shortId, now }) {
1947
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now));
1948
+ return row ? {
1949
+ ...row
1950
+ } : void 0;
1951
+ },
1952
+ async findPublicByFormerSlug({ companyId, slug, now }) {
1953
+ const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug);
1954
+ const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now));
1955
+ return row ? {
1956
+ ...row
1957
+ } : void 0;
1958
+ },
1959
+ async recordFormerSlug(params) {
1960
+ if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {
1961
+ formerSlugs.push({
1962
+ ...params
1963
+ });
1964
+ }
1965
+ },
1966
+ async create(values) {
1967
+ assertUniqueSlug(values.companyId, values.slug);
1968
+ const now = /* @__PURE__ */ new Date();
1969
+ const row = {
1970
+ id: (0, import_node_crypto2.randomUUID)(),
1971
+ excerpt: null,
1972
+ body: "",
1973
+ coverImageUrl: null,
1974
+ coverImageAlt: null,
1975
+ tags: [],
1976
+ tagLabels: {},
1977
+ status: import_content_contracts17.POST_STATUS.DRAFT,
1978
+ isTemplate: false,
1979
+ publishedAt: null,
1980
+ authorName: null,
1981
+ seoTitle: null,
1982
+ seoDescription: null,
1983
+ canonicalUrl: null,
1984
+ readingTimeMinutes: 1,
1985
+ createdAt: now,
1986
+ updatedAt: now,
1987
+ ...values
1988
+ };
1989
+ rows.push(row);
1990
+ return {
1991
+ ...row
1992
+ };
1993
+ },
1994
+ async findById({ companyId, id }) {
1995
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
1996
+ return row ? {
1997
+ ...row
1998
+ } : void 0;
1999
+ },
2000
+ async findBySlug({ companyId, slug }) {
2001
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug);
2002
+ return row ? {
2003
+ ...row
2004
+ } : void 0;
2005
+ },
2006
+ async findPublicBySlug({ companyId, slug, now }) {
2007
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now));
2008
+ return row ? {
2009
+ ...row
2010
+ } : void 0;
2011
+ },
2012
+ async update({ companyId, id, values }) {
2013
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
2014
+ if (!row) return void 0;
2015
+ if (values.slug !== void 0) assertUniqueSlug(companyId, values.slug, id);
2016
+ Object.assign(row, values, {
2017
+ updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1))
2018
+ });
2019
+ return {
2020
+ ...row
2021
+ };
2022
+ },
2023
+ async listForAdmin(query) {
2024
+ const search = query.search?.toLowerCase();
2025
+ const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => query.isTemplate ? row.isTemplate && row.status !== import_content_contracts17.POST_STATUS.ARCHIVED : !row.isTemplate).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag))).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort(adminComparator(query));
2026
+ return paginate(matched, query.page, query.pageSize);
2027
+ },
2028
+ async countByStatus({ companyId, now }) {
2029
+ const counts = {
2030
+ published: 0,
2031
+ scheduled: 0,
2032
+ draft: 0,
2033
+ archived: 0,
2034
+ templates: 0
2035
+ };
2036
+ for (const row of rows) {
2037
+ if (row.companyId !== companyId) continue;
2038
+ if (row.isTemplate) {
2039
+ if (row.status !== import_content_contracts17.POST_STATUS.ARCHIVED) counts.templates += 1;
2040
+ continue;
2041
+ }
2042
+ counts[effectiveStatus(row, now)] += 1;
2043
+ }
2044
+ return counts;
2045
+ },
2046
+ async claimDueScheduled({ now, limit }) {
2047
+ const due = rows.filter((row) => row.status === import_content_contracts17.POST_STATUS.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now).sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0)).slice(0, limit);
2048
+ for (const row of due) row.status = import_content_contracts17.POST_STATUS.PUBLISHED;
2049
+ return due.map((row) => ({
2050
+ ...row
2051
+ }));
2052
+ },
2053
+ async listPublic(query) {
2054
+ const matched = rows.filter((row) => row.companyId === query.companyId && isPublic(row, query.now)).filter((row) => !query.tag || row.tags.includes(query.tag)).sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0));
2055
+ return paginate(matched, query.page, query.pageSize);
2056
+ },
2057
+ async listTags({ companyId, publicAt }) {
2058
+ const counts = /* @__PURE__ */ new Map();
2059
+ for (const row of rows) {
2060
+ if (row.companyId !== companyId || publicAt && !isPublic(row, publicAt)) continue;
2061
+ for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1);
2062
+ }
2063
+ return [
2064
+ ...counts.entries()
2065
+ ].map(([tag, count]) => ({
2066
+ tag,
2067
+ count
2068
+ })).sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag));
2069
+ }
2070
+ };
2071
+ }
2072
+ __name(createInMemoryPostStore, "createInMemoryPostStore");
2073
+
2074
+ // src/scheduler.ts
2075
+ var DEFAULT_SCHEDULER_INTERVAL_MS = 6e4;
2076
+ function startContentScheduler(params) {
2077
+ let isRunning = false;
2078
+ const tick = /* @__PURE__ */ __name(async () => {
2079
+ if (isRunning) return;
2080
+ isRunning = true;
2081
+ try {
2082
+ await params.module.useCases.publishDue.execute();
2083
+ } catch (error) {
2084
+ params.logger?.error("content-module: ciclo do agendador falhou", {
2085
+ error: error instanceof Error ? error.message : String(error)
2086
+ });
2087
+ } finally {
2088
+ isRunning = false;
2089
+ }
2090
+ }, "tick");
2091
+ const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS);
2092
+ timer.unref?.();
2093
+ void tick();
2094
+ return () => clearInterval(timer);
2095
+ }
2096
+ __name(startContentScheduler, "startContentScheduler");
2097
+
2098
+ // src/testing/inMemoryRecurrenceStore.ts
2099
+ var import_node_crypto3 = require("crypto");
2100
+ function createInMemoryRecurrenceStore() {
2101
+ const rows = [];
2102
+ const owned = /* @__PURE__ */ __name((companyId, id) => rows.find((row) => row.companyId === companyId && row.id === id), "owned");
2103
+ return {
2104
+ rows,
2105
+ async create(values) {
2106
+ const row = {
2107
+ id: (0, import_node_crypto3.randomUUID)(),
2108
+ isActive: true,
2109
+ lastRunAt: null,
2110
+ lastPostId: null,
2111
+ createdAt: /* @__PURE__ */ new Date(),
2112
+ ...values
2113
+ };
2114
+ rows.push(row);
2115
+ return {
2116
+ ...row
2117
+ };
2118
+ },
2119
+ async findById({ companyId, id }) {
2120
+ const row = owned(companyId, id);
2121
+ return row ? {
2122
+ ...row
2123
+ } : void 0;
2124
+ },
2125
+ async list({ companyId }) {
2126
+ return rows.filter((row) => row.companyId === companyId).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).map((row) => ({
2127
+ ...row
2128
+ }));
2129
+ },
2130
+ async update({ companyId, id, values }) {
2131
+ const row = owned(companyId, id);
2132
+ if (!row) return void 0;
2133
+ Object.assign(row, values);
2134
+ return {
2135
+ ...row
2136
+ };
2137
+ },
2138
+ async remove({ companyId, id }) {
2139
+ const index2 = rows.findIndex((row) => row.companyId === companyId && row.id === id);
2140
+ if (index2 < 0) return false;
2141
+ rows.splice(index2, 1);
2142
+ return true;
2143
+ },
2144
+ async processDue({ now, limit, handle }) {
2145
+ const due = rows.filter((row) => row.isActive && row.nextRunAt <= now).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).slice(0, limit);
2146
+ for (const row of due) Object.assign(row, await handle({
2147
+ ...row
2148
+ }));
2149
+ return due.length;
2150
+ }
2151
+ };
2152
+ }
2153
+ __name(createInMemoryRecurrenceStore, "createInMemoryRecurrenceStore");
2154
+ // Annotate the CommonJS export names for ESM import in node:
2155
+ 0 && (module.exports = {
2156
+ ArchivePostUseCase,
2157
+ BuildFeedUseCase,
2158
+ CONTENT_MIGRATIONS_TABLE,
2159
+ COVER_IMAGE,
2160
+ CountPostsUseCase,
2161
+ CreateFromTemplateUseCase,
2162
+ CreatePostUseCase,
2163
+ CreateRecurrenceUseCase,
2164
+ DEFAULT_SCHEDULER_INTERVAL_MS,
2165
+ FEED_FORMAT,
2166
+ GetPostUseCase,
2167
+ GetPublishedPostBySlugUseCase,
2168
+ ListPostsUseCase,
2169
+ ListPublishedPostsUseCase,
2170
+ ListRecurrencesUseCase,
2171
+ ListSitemapEntriesUseCase,
2172
+ ListTagsUseCase,
2173
+ PostRepository,
2174
+ PublishDueUseCase,
2175
+ PublishPostUseCase,
2176
+ RecurrenceRepository,
2177
+ RemoveRecurrenceUseCase,
2178
+ RepublishPostUseCase,
2179
+ SaveAsTemplateUseCase,
2180
+ TAG_SCOPE,
2181
+ UnpublishPostUseCase,
2182
+ UpdatePostUseCase,
2183
+ UpdateRecurrenceUseCase,
2184
+ UploadCoverImageUseCase,
2185
+ contentMigrationsFolder,
2186
+ contentSchema,
2187
+ createContentModule,
2188
+ createContentRoutes,
2189
+ createInMemoryPostStore,
2190
+ createInMemoryRecurrenceStore,
2191
+ nextOccurrence,
2192
+ nextOccurrenceAfter,
2193
+ posts,
2194
+ recurrenceRules,
2195
+ runContentMigrations,
2196
+ startContentScheduler
2197
+ });
2198
+ //# sourceMappingURL=index.cjs.map