@adatechnology/content-module 0.0.0-stage → 0.1.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,1291 @@
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
+ CreatePostUseCase: () => CreatePostUseCase,
29
+ FEED_FORMAT: () => FEED_FORMAT,
30
+ GetPostUseCase: () => GetPostUseCase,
31
+ GetPublishedPostBySlugUseCase: () => GetPublishedPostBySlugUseCase,
32
+ ListPostsUseCase: () => ListPostsUseCase,
33
+ ListPublishedPostsUseCase: () => ListPublishedPostsUseCase,
34
+ ListSitemapEntriesUseCase: () => ListSitemapEntriesUseCase,
35
+ ListTagsUseCase: () => ListTagsUseCase,
36
+ PostRepository: () => PostRepository,
37
+ PublishPostUseCase: () => PublishPostUseCase,
38
+ TAG_SCOPE: () => TAG_SCOPE,
39
+ UnpublishPostUseCase: () => UnpublishPostUseCase,
40
+ UpdatePostUseCase: () => UpdatePostUseCase,
41
+ UploadCoverImageUseCase: () => UploadCoverImageUseCase,
42
+ contentMigrationsFolder: () => contentMigrationsFolder,
43
+ contentSchema: () => contentSchema,
44
+ createContentModule: () => createContentModule,
45
+ createContentRoutes: () => createContentRoutes,
46
+ createInMemoryPostStore: () => createInMemoryPostStore,
47
+ posts: () => posts,
48
+ runContentMigrations: () => runContentMigrations
49
+ });
50
+ module.exports = __toCommonJS(index_exports);
51
+
52
+ // src/ContentModule.ts
53
+ var import_content_contracts7 = require("@adatechnology/content-contracts");
54
+
55
+ // src/repositories/PostRepository.ts
56
+ var import_drizzle_orm2 = require("drizzle-orm");
57
+
58
+ // src/schema/schema.ts
59
+ var import_pg_core = require("drizzle-orm/pg-core");
60
+ var contentSchema = (0, import_pg_core.pgSchema)("content");
61
+ var posts = contentSchema.table("posts", {
62
+ id: (0, import_pg_core.uuid)("id").primaryKey().defaultRandom(),
63
+ companyId: (0, import_pg_core.uuid)("company_id").notNull(),
64
+ slug: (0, import_pg_core.varchar)("slug", {
65
+ length: 120
66
+ }).notNull(),
67
+ title: (0, import_pg_core.varchar)("title", {
68
+ length: 200
69
+ }).notNull(),
70
+ excerpt: (0, import_pg_core.varchar)("excerpt", {
71
+ length: 500
72
+ }),
73
+ body: (0, import_pg_core.text)("body").notNull().default(""),
74
+ coverImageUrl: (0, import_pg_core.varchar)("cover_image_url", {
75
+ length: 2048
76
+ }),
77
+ coverImageAlt: (0, import_pg_core.varchar)("cover_image_alt", {
78
+ length: 300
79
+ }),
80
+ tags: (0, import_pg_core.text)("tags").array().notNull().default([]),
81
+ status: (0, import_pg_core.varchar)("status", {
82
+ length: 12
83
+ }).notNull().default("draft"),
84
+ publishedAt: (0, import_pg_core.timestamp)("published_at", {
85
+ withTimezone: true
86
+ }),
87
+ authorName: (0, import_pg_core.varchar)("author_name", {
88
+ length: 120
89
+ }),
90
+ seoTitle: (0, import_pg_core.varchar)("seo_title", {
91
+ length: 200
92
+ }),
93
+ seoDescription: (0, import_pg_core.varchar)("seo_description", {
94
+ length: 320
95
+ }),
96
+ canonicalUrl: (0, import_pg_core.varchar)("canonical_url", {
97
+ length: 2048
98
+ }),
99
+ readingTimeMinutes: (0, import_pg_core.integer)("reading_time_minutes").notNull().default(1),
100
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
101
+ withTimezone: true
102
+ }).notNull().defaultNow(),
103
+ updatedAt: (0, import_pg_core.timestamp)("updated_at", {
104
+ withTimezone: true
105
+ }).notNull().defaultNow()
106
+ }, (table) => [
107
+ // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
108
+ // faria um link antigo (já compartilhado) abrir outro post.
109
+ (0, import_pg_core.uniqueIndex)("idx_posts_company_slug").on(table.companyId, table.slug),
110
+ // Serve a listagem pública: empresa + status + ordem por data.
111
+ (0, import_pg_core.index)("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
112
+ (0, import_pg_core.index)("idx_posts_tags").using("gin", table.tags)
113
+ ]);
114
+
115
+ // src/repositories/conditions.ts
116
+ var import_drizzle_orm = require("drizzle-orm");
117
+ var import_content_contracts = require("@adatechnology/content-contracts");
118
+ function postOwnedByCondition(params) {
119
+ return (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm.eq)(posts.id, params.id));
120
+ }
121
+ __name(postOwnedByCondition, "postOwnedByCondition");
122
+ function postSlugCondition(params) {
123
+ return (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm.eq)(posts.slug, params.slug));
124
+ }
125
+ __name(postSlugCondition, "postSlugCondition");
126
+ function postAdminListCondition(params) {
127
+ const conditions = [
128
+ (0, import_drizzle_orm.eq)(posts.companyId, params.companyId)
129
+ ];
130
+ if (params.status) conditions.push(statusCondition(params.status, params.now));
131
+ if (params.tag) conditions.push((0, import_drizzle_orm.arrayContains)(posts.tags, [
132
+ params.tag
133
+ ]));
134
+ if (params.search) {
135
+ const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
136
+ conditions.push(import_drizzle_orm.sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
137
+ }
138
+ return (0, import_drizzle_orm.and)(...conditions);
139
+ }
140
+ __name(postAdminListCondition, "postAdminListCondition");
141
+ function statusCondition(status, now) {
142
+ if (status === import_content_contracts.POST_STATUS.PUBLISHED) {
143
+ return (0, import_drizzle_orm.or)((0, import_drizzle_orm.eq)(posts.status, import_content_contracts.POST_STATUS.PUBLISHED), (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm.lte)(posts.publishedAt, now)));
144
+ }
145
+ if (status === import_content_contracts.POST_STATUS.SCHEDULED) {
146
+ return (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm.gt)(posts.publishedAt, now));
147
+ }
148
+ return (0, import_drizzle_orm.eq)(posts.status, status);
149
+ }
150
+ __name(statusCondition, "statusCondition");
151
+ function postPublicCondition(params) {
152
+ const conditions = [
153
+ (0, import_drizzle_orm.eq)(posts.companyId, params.companyId),
154
+ (0, import_drizzle_orm.inArray)(posts.status, [
155
+ import_content_contracts.POST_STATUS.PUBLISHED,
156
+ import_content_contracts.POST_STATUS.SCHEDULED
157
+ ]),
158
+ (0, import_drizzle_orm.lte)(posts.publishedAt, params.now)
159
+ ];
160
+ if (params.tag) conditions.push((0, import_drizzle_orm.arrayContains)(posts.tags, [
161
+ params.tag
162
+ ]));
163
+ return (0, import_drizzle_orm.and)(...conditions);
164
+ }
165
+ __name(postPublicCondition, "postPublicCondition");
166
+ function postPublicSlugCondition(params) {
167
+ return (0, import_drizzle_orm.and)(postPublicCondition(params), (0, import_drizzle_orm.eq)(posts.slug, params.slug));
168
+ }
169
+ __name(postPublicSlugCondition, "postPublicSlugCondition");
170
+
171
+ // src/repositories/PostRepository.ts
172
+ var TAG_LIST_LIMIT = 200;
173
+ var PostRepository = class {
174
+ static {
175
+ __name(this, "PostRepository");
176
+ }
177
+ db;
178
+ constructor(db) {
179
+ this.db = db;
180
+ }
181
+ async create(values) {
182
+ const [row] = await this.db.insert(posts).values(values).returning();
183
+ if (!row) throw new Error("content-module: insert em posts n\xE3o retornou linha");
184
+ return row;
185
+ }
186
+ async findById(params) {
187
+ const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1);
188
+ return row;
189
+ }
190
+ async findBySlug(params) {
191
+ const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1);
192
+ return row;
193
+ }
194
+ async findPublicBySlug(params) {
195
+ const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1);
196
+ return row;
197
+ }
198
+ async update(params) {
199
+ const [row] = await this.db.update(posts).set({
200
+ ...params.values,
201
+ updatedAt: /* @__PURE__ */ new Date()
202
+ }).where(postOwnedByCondition(params)).returning();
203
+ return row;
204
+ }
205
+ async listForAdmin(query) {
206
+ const where = postAdminListCondition(query);
207
+ const [rows, [counted]] = await Promise.all([
208
+ this.db.select().from(posts).where(where).orderBy((0, import_drizzle_orm2.desc)(posts.updatedAt), (0, import_drizzle_orm2.asc)(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
209
+ this.db.select({
210
+ value: import_drizzle_orm2.sql`count(*)::int`
211
+ }).from(posts).where(where)
212
+ ]);
213
+ return {
214
+ rows,
215
+ total: counted?.value ?? 0
216
+ };
217
+ }
218
+ async listPublic(query) {
219
+ const where = postPublicCondition(query);
220
+ const [rows, [counted]] = await Promise.all([
221
+ this.db.select().from(posts).where(where).orderBy((0, import_drizzle_orm2.desc)(posts.publishedAt), (0, import_drizzle_orm2.asc)(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
222
+ this.db.select({
223
+ value: import_drizzle_orm2.sql`count(*)::int`
224
+ }).from(posts).where(where)
225
+ ]);
226
+ return {
227
+ rows,
228
+ total: counted?.value ?? 0
229
+ };
230
+ }
231
+ async listTags(params) {
232
+ const where = params.publicAt ? postPublicCondition({
233
+ companyId: params.companyId,
234
+ now: params.publicAt
235
+ }) : postAdminListCondition({
236
+ companyId: params.companyId,
237
+ now: /* @__PURE__ */ new Date()
238
+ });
239
+ const postTags = this.db.select({
240
+ tag: import_drizzle_orm2.sql`unnest(${posts.tags})`.as("tag")
241
+ }).from(posts).where(where).as("post_tags");
242
+ const rows = await this.db.select({
243
+ tag: postTags.tag,
244
+ count: import_drizzle_orm2.sql`count(*)::int`
245
+ }).from(postTags).groupBy(postTags.tag).orderBy(import_drizzle_orm2.sql`count(*) desc`, (0, import_drizzle_orm2.asc)(postTags.tag)).limit(TAG_LIST_LIMIT);
246
+ return rows;
247
+ }
248
+ };
249
+
250
+ // src/use-cases/Feed.use-cases.ts
251
+ var import_content_contracts2 = require("@adatechnology/content-contracts");
252
+ var DEFAULT_ITEM_LIMIT = 20;
253
+ var SITEMAP_LIMIT = 5e4;
254
+ var FEED_FORMAT = {
255
+ RSS: "rss",
256
+ ATOM: "atom"
257
+ };
258
+ var BuildFeedUseCase = class {
259
+ static {
260
+ __name(this, "BuildFeedUseCase");
261
+ }
262
+ dependencies;
263
+ feed;
264
+ constructor(dependencies, feed) {
265
+ this.dependencies = dependencies;
266
+ this.feed = feed;
267
+ }
268
+ async execute(params) {
269
+ const now = this.dependencies.clock.now();
270
+ const page = await this.dependencies.posts.listPublic({
271
+ companyId: params.companyId,
272
+ now,
273
+ page: 1,
274
+ pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT
275
+ });
276
+ const channel = {
277
+ siteUrl: this.feed.siteUrl,
278
+ title: this.feed.title,
279
+ ...this.feed.description ? {
280
+ description: this.feed.description
281
+ } : {},
282
+ ...this.feed.language ? {
283
+ language: this.feed.language
284
+ } : {},
285
+ ...params.feedUrl ? {
286
+ feedUrl: params.feedUrl
287
+ } : {}
288
+ };
289
+ const items = page.rows.map((row) => this.toItem(row));
290
+ return params.format === FEED_FORMAT.ATOM ? (0, import_content_contracts2.buildAtomFeed)({
291
+ channel,
292
+ items,
293
+ now
294
+ }) : (0, import_content_contracts2.buildRssFeed)({
295
+ channel,
296
+ items
297
+ });
298
+ }
299
+ toItem(row) {
300
+ return {
301
+ title: row.title,
302
+ url: (0, import_content_contracts2.buildPostUrl)({
303
+ siteUrl: this.feed.siteUrl,
304
+ slug: row.slug,
305
+ postPathTemplate: this.feed.postPathTemplate
306
+ }),
307
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
308
+ updatedAt: row.updatedAt.toISOString(),
309
+ summary: row.excerpt ?? (0, import_content_contracts2.buildExcerpt)(row.body),
310
+ ...this.feed.includeContent ?? true ? {
311
+ contentHtml: (0, import_content_contracts2.renderMarkdownToHtml)(row.body, {
312
+ headingIds: false
313
+ })
314
+ } : {},
315
+ ...row.authorName ? {
316
+ authorName: row.authorName
317
+ } : {},
318
+ categories: row.tags,
319
+ ...row.coverImageUrl ? {
320
+ imageUrl: row.coverImageUrl
321
+ } : {}
322
+ };
323
+ }
324
+ };
325
+ var ListSitemapEntriesUseCase = class {
326
+ static {
327
+ __name(this, "ListSitemapEntriesUseCase");
328
+ }
329
+ dependencies;
330
+ feed;
331
+ constructor(dependencies, feed) {
332
+ this.dependencies = dependencies;
333
+ this.feed = feed;
334
+ }
335
+ /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */
336
+ async execute(params) {
337
+ const page = await this.dependencies.posts.listPublic({
338
+ companyId: params.companyId,
339
+ now: this.dependencies.clock.now(),
340
+ page: 1,
341
+ pageSize: SITEMAP_LIMIT
342
+ });
343
+ return page.rows.map((row) => ({
344
+ loc: (0, import_content_contracts2.buildPostUrl)({
345
+ siteUrl: this.feed.siteUrl,
346
+ slug: row.slug,
347
+ postPathTemplate: this.feed.postPathTemplate
348
+ }),
349
+ lastmod: row.updatedAt.toISOString()
350
+ }));
351
+ }
352
+ };
353
+
354
+ // src/use-cases/Post.use-cases.ts
355
+ var import_content_contracts4 = require("@adatechnology/content-contracts");
356
+
357
+ // src/shared/isUniqueViolation.ts
358
+ var UNIQUE_VIOLATION = "23505";
359
+ function isUniqueViolation(error) {
360
+ let current = error;
361
+ for (let depth = 0; depth < 3 && typeof current === "object" && current !== null; depth += 1) {
362
+ if (current.code === UNIQUE_VIOLATION) return true;
363
+ current = current.cause;
364
+ }
365
+ return false;
366
+ }
367
+ __name(isUniqueViolation, "isUniqueViolation");
368
+
369
+ // src/shared/notifyPostChanged.ts
370
+ async function notifyPostChanged(dependencies, type, post) {
371
+ const hook = dependencies.hooks?.onPostChanged;
372
+ if (!hook) return;
373
+ try {
374
+ await hook({
375
+ type,
376
+ post
377
+ });
378
+ } catch (error) {
379
+ dependencies.logger?.error("content-module: hook onPostChanged falhou", {
380
+ postId: post.id,
381
+ type,
382
+ error: error instanceof Error ? error.message : String(error)
383
+ });
384
+ }
385
+ }
386
+ __name(notifyPostChanged, "notifyPostChanged");
387
+
388
+ // src/shared/toContract.ts
389
+ var import_content_contracts3 = require("@adatechnology/content-contracts");
390
+ function effectiveStatus(row, now) {
391
+ if (row.status === import_content_contracts3.POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return import_content_contracts3.POST_STATUS.PUBLISHED;
392
+ return row.status;
393
+ }
394
+ __name(effectiveStatus, "effectiveStatus");
395
+ function toPostSummary(row, now) {
396
+ return {
397
+ id: row.id,
398
+ companyId: row.companyId,
399
+ slug: row.slug,
400
+ title: row.title,
401
+ excerpt: row.excerpt,
402
+ coverImageUrl: row.coverImageUrl,
403
+ coverImageAlt: row.coverImageAlt,
404
+ tags: row.tags,
405
+ status: effectiveStatus(row, now),
406
+ publishedAt: row.publishedAt?.toISOString() ?? null,
407
+ authorName: row.authorName,
408
+ seoTitle: row.seoTitle,
409
+ seoDescription: row.seoDescription,
410
+ canonicalUrl: row.canonicalUrl,
411
+ readingTimeMinutes: row.readingTimeMinutes,
412
+ createdAt: row.createdAt.toISOString(),
413
+ updatedAt: row.updatedAt.toISOString()
414
+ };
415
+ }
416
+ __name(toPostSummary, "toPostSummary");
417
+ function toPost(row, now) {
418
+ return {
419
+ ...toPostSummary(row, now),
420
+ body: row.body
421
+ };
422
+ }
423
+ __name(toPost, "toPost");
424
+ function toPublicPostSummary(row) {
425
+ return {
426
+ id: row.id,
427
+ slug: row.slug,
428
+ title: row.title,
429
+ excerpt: row.excerpt,
430
+ coverImageUrl: row.coverImageUrl,
431
+ coverImageAlt: row.coverImageAlt,
432
+ tags: row.tags,
433
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
434
+ updatedAt: row.updatedAt.toISOString(),
435
+ authorName: row.authorName,
436
+ seoTitle: row.seoTitle,
437
+ seoDescription: row.seoDescription,
438
+ canonicalUrl: row.canonicalUrl,
439
+ readingTimeMinutes: row.readingTimeMinutes
440
+ };
441
+ }
442
+ __name(toPublicPostSummary, "toPublicPostSummary");
443
+ function toPublicPost(row) {
444
+ return {
445
+ ...toPublicPostSummary(row),
446
+ body: row.body
447
+ };
448
+ }
449
+ __name(toPublicPost, "toPublicPost");
450
+ function toPagination(params) {
451
+ return {
452
+ ...params,
453
+ totalPages: Math.max(1, Math.ceil(params.total / params.pageSize))
454
+ };
455
+ }
456
+ __name(toPagination, "toPagination");
457
+
458
+ // src/use-cases/Post.use-cases.ts
459
+ var MAX_SLUG_ATTEMPTS = 50;
460
+ var FALLBACK_SLUG = "post";
461
+ var PostUseCaseBase = class PostUseCaseBase2 {
462
+ static {
463
+ __name(this, "PostUseCaseBase");
464
+ }
465
+ dependencies;
466
+ constructor(dependencies) {
467
+ this.dependencies = dependencies;
468
+ }
469
+ now() {
470
+ return this.dependencies.clock.now();
471
+ }
472
+ async findOrFail(reference2) {
473
+ const row = await this.dependencies.posts.findById(reference2);
474
+ if (!row) throw new import_content_contracts4.PostNotFoundError(reference2.id);
475
+ return row;
476
+ }
477
+ async save(reference2, values, event) {
478
+ const row = await this.dependencies.posts.update({
479
+ ...reference2,
480
+ values
481
+ }).catch((error) => {
482
+ if (isUniqueViolation(error) && values.slug) throw new import_content_contracts4.DuplicateSlugError(values.slug);
483
+ throw error;
484
+ });
485
+ if (!row) throw new import_content_contracts4.PostNotFoundError(reference2.id);
486
+ const post = toPost(row, this.now());
487
+ await notifyPostChanged(this.dependencies, event, post);
488
+ return post;
489
+ }
490
+ readingTime(body) {
491
+ return (0, import_content_contracts4.estimateReadingTimeMinutes)(body, this.dependencies.config.wordsPerMinute);
492
+ }
493
+ async assertSlugAvailable(companyId, slug, ownId) {
494
+ const existing = await this.dependencies.posts.findBySlug({
495
+ companyId,
496
+ slug
497
+ });
498
+ if (existing && existing.id !== ownId) throw new import_content_contracts4.DuplicateSlugError(slug);
499
+ }
500
+ /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */
501
+ async generateSlug(companyId, title) {
502
+ const base = (0, import_content_contracts4.slugify)(title) || FALLBACK_SLUG;
503
+ for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {
504
+ const candidate = (0, import_content_contracts4.withSlugSuffix)(base, attempt);
505
+ if (!await this.dependencies.posts.findBySlug({
506
+ companyId,
507
+ slug: candidate
508
+ })) return candidate;
509
+ }
510
+ return (0, import_content_contracts4.withSlugSuffix)(base, Date.now());
511
+ }
512
+ };
513
+ function optionalFields(input) {
514
+ const values = {};
515
+ if (input.excerpt !== void 0) values.excerpt = input.excerpt || null;
516
+ if (input.coverImageUrl !== void 0) values.coverImageUrl = input.coverImageUrl || null;
517
+ if (input.coverImageAlt !== void 0) values.coverImageAlt = input.coverImageAlt || null;
518
+ if (input.authorName !== void 0) values.authorName = input.authorName || null;
519
+ if (input.seoTitle !== void 0) values.seoTitle = input.seoTitle || null;
520
+ if (input.seoDescription !== void 0) values.seoDescription = input.seoDescription || null;
521
+ if (input.canonicalUrl !== void 0) values.canonicalUrl = input.canonicalUrl || null;
522
+ return values;
523
+ }
524
+ __name(optionalFields, "optionalFields");
525
+ var CreatePostUseCase = class extends PostUseCaseBase {
526
+ static {
527
+ __name(this, "CreatePostUseCase");
528
+ }
529
+ async execute(params) {
530
+ const input = import_content_contracts4.createPostSchema.parse(params.input);
531
+ const { companyId } = params;
532
+ if (input.slug) await this.assertSlugAvailable(companyId, input.slug);
533
+ const slug = input.slug ?? await this.generateSlug(companyId, input.title);
534
+ const row = await this.dependencies.posts.create({
535
+ companyId,
536
+ slug,
537
+ title: input.title,
538
+ body: input.body,
539
+ tags: (0, import_content_contracts4.normalizeTags)(input.tags ?? []),
540
+ status: import_content_contracts4.POST_STATUS.DRAFT,
541
+ readingTimeMinutes: this.readingTime(input.body),
542
+ ...optionalFields(input)
543
+ }).catch((error) => {
544
+ if (isUniqueViolation(error)) throw new import_content_contracts4.DuplicateSlugError(slug);
545
+ throw error;
546
+ });
547
+ const post = toPost(row, this.now());
548
+ await notifyPostChanged(this.dependencies, import_content_contracts4.POST_EVENT.CREATED, post);
549
+ return post;
550
+ }
551
+ };
552
+ var UpdatePostUseCase = class extends PostUseCaseBase {
553
+ static {
554
+ __name(this, "UpdatePostUseCase");
555
+ }
556
+ /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */
557
+ async execute(params) {
558
+ const input = import_content_contracts4.updatePostSchema.parse(params.input);
559
+ const existing = await this.findOrFail(params);
560
+ const values = optionalFields(input);
561
+ if (input.title !== void 0) values.title = input.title;
562
+ if (input.body !== void 0) {
563
+ values.body = input.body;
564
+ values.readingTimeMinutes = this.readingTime(input.body);
565
+ }
566
+ if (input.tags !== void 0) values.tags = (0, import_content_contracts4.normalizeTags)(input.tags);
567
+ if (input.slug !== void 0 && input.slug !== existing.slug) {
568
+ await this.assertSlugAvailable(params.companyId, input.slug, existing.id);
569
+ values.slug = input.slug;
570
+ }
571
+ return this.save(params, values, import_content_contracts4.POST_EVENT.UPDATED);
572
+ }
573
+ };
574
+ var PublishPostUseCase = class extends PostUseCaseBase {
575
+ static {
576
+ __name(this, "PublishPostUseCase");
577
+ }
578
+ /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
579
+ async execute(params) {
580
+ const input = import_content_contracts4.publishPostSchema.parse(params.input ?? {});
581
+ await this.findOrFail(params);
582
+ const now = this.now();
583
+ const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
584
+ const status = publishedAt > now ? import_content_contracts4.POST_STATUS.SCHEDULED : import_content_contracts4.POST_STATUS.PUBLISHED;
585
+ return this.save(params, {
586
+ status,
587
+ publishedAt
588
+ }, import_content_contracts4.POST_EVENT.PUBLISHED);
589
+ }
590
+ };
591
+ var UnpublishPostUseCase = class extends PostUseCaseBase {
592
+ static {
593
+ __name(this, "UnpublishPostUseCase");
594
+ }
595
+ /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */
596
+ async execute(params) {
597
+ await this.findOrFail(params);
598
+ return this.save(params, {
599
+ status: import_content_contracts4.POST_STATUS.DRAFT,
600
+ publishedAt: null
601
+ }, import_content_contracts4.POST_EVENT.UNPUBLISHED);
602
+ }
603
+ };
604
+ var ArchivePostUseCase = class extends PostUseCaseBase {
605
+ static {
606
+ __name(this, "ArchivePostUseCase");
607
+ }
608
+ /** "Excluir" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */
609
+ async execute(params) {
610
+ await this.findOrFail(params);
611
+ return this.save(params, {
612
+ status: import_content_contracts4.POST_STATUS.ARCHIVED
613
+ }, import_content_contracts4.POST_EVENT.ARCHIVED);
614
+ }
615
+ };
616
+ var GetPostUseCase = class extends PostUseCaseBase {
617
+ static {
618
+ __name(this, "GetPostUseCase");
619
+ }
620
+ async execute(params) {
621
+ return toPost(await this.findOrFail(params), this.now());
622
+ }
623
+ };
624
+ var ListPostsUseCase = class extends PostUseCaseBase {
625
+ static {
626
+ __name(this, "ListPostsUseCase");
627
+ }
628
+ async execute(params) {
629
+ const { companyId, ...rawQuery } = params;
630
+ const query = import_content_contracts4.listPostsQuerySchema.parse(rawQuery);
631
+ const tag = query.tag ? (0, import_content_contracts4.normalizeTags)([
632
+ query.tag
633
+ ])[0] : void 0;
634
+ const now = this.now();
635
+ const page = await this.dependencies.posts.listForAdmin({
636
+ companyId,
637
+ ...query,
638
+ now,
639
+ ...tag ? {
640
+ tag
641
+ } : {}
642
+ });
643
+ return {
644
+ data: page.rows.map((row) => toPostSummary(row, now)),
645
+ pagination: toPagination({
646
+ total: page.total,
647
+ page: query.page,
648
+ pageSize: query.pageSize
649
+ })
650
+ };
651
+ }
652
+ };
653
+
654
+ // src/use-cases/PublicPost.use-cases.ts
655
+ var import_content_contracts5 = require("@adatechnology/content-contracts");
656
+ var GetPublishedPostBySlugUseCase = class {
657
+ static {
658
+ __name(this, "GetPublishedPostBySlugUseCase");
659
+ }
660
+ dependencies;
661
+ constructor(dependencies) {
662
+ this.dependencies = dependencies;
663
+ }
664
+ async execute(params) {
665
+ const slug = params.slug.trim().toLowerCase();
666
+ const row = await this.dependencies.posts.findPublicBySlug({
667
+ companyId: params.companyId,
668
+ slug,
669
+ now: this.dependencies.clock.now()
670
+ });
671
+ if (!row) throw new import_content_contracts5.PostNotFoundError(slug);
672
+ return toPublicPost(row);
673
+ }
674
+ };
675
+ var ListPublishedPostsUseCase = class {
676
+ static {
677
+ __name(this, "ListPublishedPostsUseCase");
678
+ }
679
+ dependencies;
680
+ constructor(dependencies) {
681
+ this.dependencies = dependencies;
682
+ }
683
+ async execute(params) {
684
+ const { companyId, ...rawQuery } = params;
685
+ const query = import_content_contracts5.listPublishedPostsQuerySchema.parse(rawQuery);
686
+ const tag = query.tag ? (0, import_content_contracts5.normalizeTag)(query.tag) : void 0;
687
+ const page = await this.dependencies.posts.listPublic({
688
+ companyId,
689
+ now: this.dependencies.clock.now(),
690
+ page: query.page,
691
+ pageSize: query.pageSize,
692
+ ...tag ? {
693
+ tag
694
+ } : {}
695
+ });
696
+ return {
697
+ data: page.rows.map(toPublicPostSummary),
698
+ pagination: toPagination({
699
+ total: page.total,
700
+ page: query.page,
701
+ pageSize: query.pageSize
702
+ })
703
+ };
704
+ }
705
+ };
706
+ var TAG_SCOPE = {
707
+ PUBLIC: "public",
708
+ ADMIN: "admin"
709
+ };
710
+ var ListTagsUseCase = class {
711
+ static {
712
+ __name(this, "ListTagsUseCase");
713
+ }
714
+ dependencies;
715
+ constructor(dependencies) {
716
+ this.dependencies = dependencies;
717
+ }
718
+ /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */
719
+ async execute(params) {
720
+ return this.dependencies.posts.listTags({
721
+ companyId: params.companyId,
722
+ ...params.scope === TAG_SCOPE.PUBLIC ? {
723
+ publicAt: this.dependencies.clock.now()
724
+ } : {}
725
+ });
726
+ }
727
+ };
728
+
729
+ // src/use-cases/UploadCoverImage.use-case.ts
730
+ var import_content_contracts6 = require("@adatechnology/content-contracts");
731
+
732
+ // src/shared/coverImage.constant.ts
733
+ var COVER_IMAGE = {
734
+ MAX_BYTES: 1024 * 1024,
735
+ KEY_PREFIX: "content/posts",
736
+ EXTENSION_BY_MIME: {
737
+ "image/jpeg": "jpg",
738
+ "image/png": "png",
739
+ "image/webp": "webp"
740
+ }
741
+ };
742
+
743
+ // src/use-cases/UploadCoverImage.use-case.ts
744
+ var UploadCoverImageUseCase = class {
745
+ static {
746
+ __name(this, "UploadCoverImageUseCase");
747
+ }
748
+ dependencies;
749
+ constructor(dependencies) {
750
+ this.dependencies = dependencies;
751
+ }
752
+ async execute(params) {
753
+ const storage = this.dependencies.imageStorage;
754
+ if (!storage) throw new import_content_contracts6.ImageStorageDisabledError();
755
+ const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
756
+ const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType];
757
+ if (!extension) throw new import_content_contracts6.InvalidCoverImageError("unsupported_type");
758
+ if (params.bytes.byteLength === 0) throw new import_content_contracts6.InvalidCoverImageError("empty");
759
+ if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new import_content_contracts6.InvalidCoverImageError("too_large");
760
+ const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
761
+ return storage.upload({
762
+ buffer: params.bytes,
763
+ mimeType,
764
+ key
765
+ });
766
+ }
767
+ };
768
+
769
+ // src/ContentModule.ts
770
+ var SYSTEM_CLOCK = {
771
+ now: /* @__PURE__ */ __name(() => /* @__PURE__ */ new Date(), "now")
772
+ };
773
+ function assertValidConfig(config) {
774
+ if (config.feed && !/^https?:\/\/[^/]/i.test(config.feed.siteUrl)) throw new import_content_contracts7.ConfigMissingError("feed.siteUrl");
775
+ if (config.feed && !config.feed.title.trim()) throw new import_content_contracts7.ConfigMissingError("feed.title");
776
+ if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes("{slug}")) {
777
+ throw new import_content_contracts7.ConfigMissingError("feed.postPathTemplate");
778
+ }
779
+ if (config.wordsPerMinute !== void 0 && !(config.wordsPerMinute > 0)) throw new import_content_contracts7.ConfigMissingError("wordsPerMinute");
780
+ }
781
+ __name(assertValidConfig, "assertValidConfig");
782
+ function createContentModule(params) {
783
+ const config = params.config ?? {};
784
+ assertValidConfig(config);
785
+ const posts2 = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : void 0);
786
+ if (!posts2) throw new import_content_contracts7.ConfigMissingError("db");
787
+ const dependencies = {
788
+ posts: posts2,
789
+ config,
790
+ clock: params.providers?.clock ?? SYSTEM_CLOCK,
791
+ ...params.hooks ? {
792
+ hooks: params.hooks
793
+ } : {},
794
+ ...params.providers?.imageStorage ? {
795
+ imageStorage: params.providers.imageStorage
796
+ } : {},
797
+ ...params.providers?.logger ? {
798
+ logger: params.providers.logger
799
+ } : {}
800
+ };
801
+ return {
802
+ useCases: {
803
+ createPost: new CreatePostUseCase(dependencies),
804
+ updatePost: new UpdatePostUseCase(dependencies),
805
+ archivePost: new ArchivePostUseCase(dependencies),
806
+ publishPost: new PublishPostUseCase(dependencies),
807
+ unpublishPost: new UnpublishPostUseCase(dependencies),
808
+ getPost: new GetPostUseCase(dependencies),
809
+ listPosts: new ListPostsUseCase(dependencies),
810
+ getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),
811
+ listPublishedPosts: new ListPublishedPostsUseCase(dependencies),
812
+ listTags: new ListTagsUseCase(dependencies),
813
+ ...dependencies.imageStorage ? {
814
+ uploadCoverImage: new UploadCoverImageUseCase(dependencies)
815
+ } : {},
816
+ ...config.feed ? {
817
+ buildFeed: new BuildFeedUseCase(dependencies, config.feed),
818
+ listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed)
819
+ } : {}
820
+ },
821
+ config
822
+ };
823
+ }
824
+ __name(createContentModule, "createContentModule");
825
+
826
+ // src/http/adminRoutes.ts
827
+ var import_content_contracts9 = require("@adatechnology/content-contracts");
828
+
829
+ // src/http/requireCompany.ts
830
+ var import_content_contracts8 = require("@adatechnology/content-contracts");
831
+ function requireCompany(context) {
832
+ if (!context.auth?.companyId) {
833
+ throw new import_content_contracts8.ContentError("Rota exige contexto autenticado.", 401, import_content_contracts8.CONTENT_ERROR_CODES.CONFIG_MISSING);
834
+ }
835
+ return context.auth.companyId;
836
+ }
837
+ __name(requireCompany, "requireCompany");
838
+
839
+ // src/http/adminRoutes.ts
840
+ function reference(context) {
841
+ return {
842
+ companyId: requireCompany(context),
843
+ id: context.params.id ?? ""
844
+ };
845
+ }
846
+ __name(reference, "reference");
847
+ var json = /* @__PURE__ */ __name((status, data) => ({
848
+ kind: "json",
849
+ status,
850
+ body: {
851
+ data
852
+ }
853
+ }), "json");
854
+ function buildAdminRoutes(module2) {
855
+ const { useCases } = module2;
856
+ const requiredScopes = module2.config.adminScopes ?? import_content_contracts9.DEFAULT_ADMIN_SCOPES;
857
+ const admin = {
858
+ scope: "admin",
859
+ requiredScopes
860
+ };
861
+ const uploadRoutes = useCases.uploadCoverImage ? [
862
+ {
863
+ ...admin,
864
+ method: "POST",
865
+ path: "/posts/cover-images",
866
+ operationId: "uploadPostCoverImage",
867
+ summary: "Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL",
868
+ async handler(context) {
869
+ const upload = useCases.uploadCoverImage;
870
+ if (!upload) return {
871
+ kind: "empty",
872
+ status: 404
873
+ };
874
+ const result = await upload.execute({
875
+ companyId: requireCompany(context),
876
+ bytes: context.rawBody ?? new Uint8Array(),
877
+ mimeType: context.headers["content-type"] ?? ""
878
+ });
879
+ return json(201, result);
880
+ }
881
+ }
882
+ ] : [];
883
+ return [
884
+ {
885
+ ...admin,
886
+ method: "GET",
887
+ path: "/posts",
888
+ querySchema: import_content_contracts9.listPostsQuerySchema,
889
+ operationId: "listPosts",
890
+ summary: "Lista posts da empresa (todos os status), com filtro por status, tag e busca",
891
+ async handler(context) {
892
+ const result = await useCases.listPosts.execute({
893
+ companyId: requireCompany(context),
894
+ ...context.query
895
+ });
896
+ return {
897
+ kind: "json",
898
+ status: 200,
899
+ body: result
900
+ };
901
+ }
902
+ },
903
+ {
904
+ ...admin,
905
+ method: "POST",
906
+ path: "/posts",
907
+ bodySchema: import_content_contracts9.createPostSchema,
908
+ operationId: "createPost",
909
+ summary: "Cria um post como rascunho; sem slug, gera a partir do t\xEDtulo",
910
+ async handler(context) {
911
+ const post = await useCases.createPost.execute({
912
+ companyId: requireCompany(context),
913
+ input: context.body
914
+ });
915
+ return json(201, post);
916
+ }
917
+ },
918
+ // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria "tags".
919
+ {
920
+ ...admin,
921
+ method: "GET",
922
+ path: "/posts/tags",
923
+ operationId: "listPostTags",
924
+ summary: "Tags usadas em qualquer post da empresa, com contagem",
925
+ async handler(context) {
926
+ return json(200, await useCases.listTags.execute({
927
+ companyId: requireCompany(context),
928
+ scope: TAG_SCOPE.ADMIN
929
+ }));
930
+ }
931
+ },
932
+ ...uploadRoutes,
933
+ {
934
+ ...admin,
935
+ method: "GET",
936
+ path: "/posts/:id",
937
+ operationId: "getPost",
938
+ summary: "L\xEA um post da empresa (qualquer status)",
939
+ async handler(context) {
940
+ return json(200, await useCases.getPost.execute(reference(context)));
941
+ }
942
+ },
943
+ {
944
+ ...admin,
945
+ method: "PATCH",
946
+ path: "/posts/:id",
947
+ bodySchema: import_content_contracts9.updatePostSchema,
948
+ operationId: "updatePost",
949
+ summary: "Atualiza campos de um post; trocar o t\xEDtulo n\xE3o troca o slug",
950
+ async handler(context) {
951
+ return json(200, await useCases.updatePost.execute({
952
+ ...reference(context),
953
+ input: context.body
954
+ }));
955
+ }
956
+ },
957
+ {
958
+ ...admin,
959
+ method: "DELETE",
960
+ path: "/posts/:id",
961
+ operationId: "archivePost",
962
+ summary: "Arquiva o post: sai do site, conte\xFAdo e slug continuam guardados",
963
+ async handler(context) {
964
+ await useCases.archivePost.execute(reference(context));
965
+ return {
966
+ kind: "empty",
967
+ status: 204
968
+ };
969
+ }
970
+ },
971
+ {
972
+ ...admin,
973
+ method: "POST",
974
+ path: "/posts/:id/publish",
975
+ // Opcional: `POST /publish` sem corpo publica agora.
976
+ bodySchema: import_content_contracts9.publishPostSchema.optional(),
977
+ operationId: "publishPost",
978
+ summary: "Publica agora, ou agenda quando `publishedAt` \xE9 futuro",
979
+ async handler(context) {
980
+ return json(200, await useCases.publishPost.execute({
981
+ ...reference(context),
982
+ input: context.body ?? {}
983
+ }));
984
+ }
985
+ },
986
+ {
987
+ ...admin,
988
+ method: "POST",
989
+ path: "/posts/:id/unpublish",
990
+ operationId: "unpublishPost",
991
+ summary: "Tira do ar (ou cancela o agendamento) e volta a rascunho",
992
+ async handler(context) {
993
+ return json(200, await useCases.unpublishPost.execute(reference(context)));
994
+ }
995
+ }
996
+ ];
997
+ }
998
+ __name(buildAdminRoutes, "buildAdminRoutes");
999
+
1000
+ // src/http/publicRoutes.ts
1001
+ var import_content_contracts10 = require("@adatechnology/content-contracts");
1002
+ var PUBLIC = {
1003
+ scope: "public"
1004
+ };
1005
+ function buildPublicRoutes(params) {
1006
+ const { useCases } = params.module;
1007
+ const cacheControl = params.module.config.publicCacheControl ?? import_content_contracts10.DEFAULT_PUBLIC_CACHE_CONTROL;
1008
+ const cached = /* @__PURE__ */ __name((data) => ({
1009
+ kind: "json",
1010
+ status: 200,
1011
+ body: data,
1012
+ headers: {
1013
+ "Cache-Control": cacheControl
1014
+ }
1015
+ }), "cached");
1016
+ async function resolveCompany(context) {
1017
+ const companyId = await params.companyResolver.resolve({
1018
+ headers: context.headers,
1019
+ query: context.query
1020
+ });
1021
+ if (!companyId) throw new import_content_contracts10.PostNotFoundError("company");
1022
+ return companyId;
1023
+ }
1024
+ __name(resolveCompany, "resolveCompany");
1025
+ const routes = [
1026
+ {
1027
+ ...PUBLIC,
1028
+ method: "GET",
1029
+ path: "/public/posts",
1030
+ querySchema: import_content_contracts10.listPublishedPostsQuerySchema,
1031
+ operationId: "listPublishedPosts",
1032
+ summary: "Posts publicados, mais recentes primeiro, com filtro por tag",
1033
+ async handler(context) {
1034
+ const result = await useCases.listPublishedPosts.execute({
1035
+ companyId: await resolveCompany(context),
1036
+ ...context.query
1037
+ });
1038
+ return cached(result);
1039
+ }
1040
+ },
1041
+ {
1042
+ ...PUBLIC,
1043
+ method: "GET",
1044
+ path: "/public/posts/:slug",
1045
+ operationId: "getPublishedPost",
1046
+ summary: "Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404",
1047
+ async handler(context) {
1048
+ const post = await useCases.getPublishedPostBySlug.execute({
1049
+ companyId: await resolveCompany(context),
1050
+ slug: context.params.slug ?? ""
1051
+ });
1052
+ return cached({
1053
+ data: post
1054
+ });
1055
+ }
1056
+ },
1057
+ {
1058
+ ...PUBLIC,
1059
+ method: "GET",
1060
+ path: "/public/tags",
1061
+ operationId: "listPublishedTags",
1062
+ summary: "Tags dos posts publicados, com contagem",
1063
+ async handler(context) {
1064
+ const tags = await useCases.listTags.execute({
1065
+ companyId: await resolveCompany(context),
1066
+ scope: TAG_SCOPE.PUBLIC
1067
+ });
1068
+ return cached({
1069
+ data: tags
1070
+ });
1071
+ }
1072
+ }
1073
+ ];
1074
+ const { buildFeed, listSitemapEntries } = useCases;
1075
+ if (!buildFeed || !listSitemapEntries) return routes;
1076
+ const feedRoute = /* @__PURE__ */ __name((path, format, contentType, operationId) => ({
1077
+ ...PUBLIC,
1078
+ method: "GET",
1079
+ path,
1080
+ operationId,
1081
+ summary: `Feed ${format.toUpperCase()} dos posts publicados`,
1082
+ async handler(context) {
1083
+ const body = await buildFeed.execute({
1084
+ companyId: await resolveCompany(context),
1085
+ format
1086
+ });
1087
+ return {
1088
+ kind: "text",
1089
+ status: 200,
1090
+ body,
1091
+ headers: {
1092
+ "Content-Type": contentType,
1093
+ "Cache-Control": cacheControl
1094
+ }
1095
+ };
1096
+ }
1097
+ }), "feedRoute");
1098
+ return [
1099
+ ...routes,
1100
+ feedRoute("/public/feed.xml", FEED_FORMAT.RSS, "application/rss+xml; charset=utf-8", "getRssFeed"),
1101
+ feedRoute("/public/atom.xml", FEED_FORMAT.ATOM, "application/atom+xml; charset=utf-8", "getAtomFeed"),
1102
+ {
1103
+ ...PUBLIC,
1104
+ method: "GET",
1105
+ path: "/public/sitemap-entries",
1106
+ operationId: "listSitemapEntries",
1107
+ summary: "Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele",
1108
+ async handler(context) {
1109
+ return cached({
1110
+ data: await listSitemapEntries.execute({
1111
+ companyId: await resolveCompany(context)
1112
+ })
1113
+ });
1114
+ }
1115
+ }
1116
+ ];
1117
+ }
1118
+ __name(buildPublicRoutes, "buildPublicRoutes");
1119
+
1120
+ // src/http/routes.ts
1121
+ function createContentRoutes(params) {
1122
+ const admin = buildAdminRoutes(params.module);
1123
+ if (!params.publicCompanyResolver) return admin;
1124
+ return [
1125
+ ...admin,
1126
+ ...buildPublicRoutes({
1127
+ module: params.module,
1128
+ companyResolver: params.publicCompanyResolver
1129
+ })
1130
+ ];
1131
+ }
1132
+ __name(createContentRoutes, "createContentRoutes");
1133
+
1134
+ // src/runMigrations.ts
1135
+ var import_node_path = require("path");
1136
+ var CONTENT_MIGRATIONS_TABLE = "content_migrations";
1137
+ function contentMigrationsFolder() {
1138
+ return (0, import_node_path.join)(__dirname, "migrations");
1139
+ }
1140
+ __name(contentMigrationsFolder, "contentMigrationsFolder");
1141
+ async function runContentMigrations(params) {
1142
+ await params.migrate(params.db, {
1143
+ migrationsFolder: contentMigrationsFolder(),
1144
+ migrationsTable: CONTENT_MIGRATIONS_TABLE
1145
+ });
1146
+ }
1147
+ __name(runContentMigrations, "runContentMigrations");
1148
+
1149
+ // src/testing/inMemoryPostStore.ts
1150
+ var import_node_crypto = require("crypto");
1151
+ var import_content_contracts11 = require("@adatechnology/content-contracts");
1152
+ function isPublic(row, now) {
1153
+ const live = row.status === import_content_contracts11.POST_STATUS.PUBLISHED || row.status === import_content_contracts11.POST_STATUS.SCHEDULED;
1154
+ return live && row.publishedAt !== null && row.publishedAt <= now;
1155
+ }
1156
+ __name(isPublic, "isPublic");
1157
+ function paginate(rows, page, pageSize) {
1158
+ return {
1159
+ rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({
1160
+ ...row
1161
+ })),
1162
+ total: rows.length
1163
+ };
1164
+ }
1165
+ __name(paginate, "paginate");
1166
+ var UniqueViolation = class UniqueViolation2 extends Error {
1167
+ static {
1168
+ __name(this, "UniqueViolation");
1169
+ }
1170
+ code = "23505";
1171
+ };
1172
+ function createInMemoryPostStore(seed = []) {
1173
+ const rows = [
1174
+ ...seed
1175
+ ];
1176
+ const assertUniqueSlug = /* @__PURE__ */ __name((companyId, slug, ownId) => {
1177
+ if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {
1178
+ throw new UniqueViolation('duplicate key value violates unique constraint "idx_posts_company_slug"');
1179
+ }
1180
+ }, "assertUniqueSlug");
1181
+ return {
1182
+ rows,
1183
+ async create(values) {
1184
+ assertUniqueSlug(values.companyId, values.slug);
1185
+ const now = /* @__PURE__ */ new Date();
1186
+ const row = {
1187
+ id: (0, import_node_crypto.randomUUID)(),
1188
+ excerpt: null,
1189
+ body: "",
1190
+ coverImageUrl: null,
1191
+ coverImageAlt: null,
1192
+ tags: [],
1193
+ status: import_content_contracts11.POST_STATUS.DRAFT,
1194
+ publishedAt: null,
1195
+ authorName: null,
1196
+ seoTitle: null,
1197
+ seoDescription: null,
1198
+ canonicalUrl: null,
1199
+ readingTimeMinutes: 1,
1200
+ createdAt: now,
1201
+ updatedAt: now,
1202
+ ...values
1203
+ };
1204
+ rows.push(row);
1205
+ return {
1206
+ ...row
1207
+ };
1208
+ },
1209
+ async findById({ companyId, id }) {
1210
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
1211
+ return row ? {
1212
+ ...row
1213
+ } : void 0;
1214
+ },
1215
+ async findBySlug({ companyId, slug }) {
1216
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug);
1217
+ return row ? {
1218
+ ...row
1219
+ } : void 0;
1220
+ },
1221
+ async findPublicBySlug({ companyId, slug, now }) {
1222
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now));
1223
+ return row ? {
1224
+ ...row
1225
+ } : void 0;
1226
+ },
1227
+ async update({ companyId, id, values }) {
1228
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id);
1229
+ if (!row) return void 0;
1230
+ if (values.slug !== void 0) assertUniqueSlug(companyId, values.slug, id);
1231
+ Object.assign(row, values, {
1232
+ updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1))
1233
+ });
1234
+ return {
1235
+ ...row
1236
+ };
1237
+ },
1238
+ async listForAdmin(query) {
1239
+ const search = query.search?.toLowerCase();
1240
+ const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.tag || row.tags.includes(query.tag)).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());
1241
+ return paginate(matched, query.page, query.pageSize);
1242
+ },
1243
+ async listPublic(query) {
1244
+ 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));
1245
+ return paginate(matched, query.page, query.pageSize);
1246
+ },
1247
+ async listTags({ companyId, publicAt }) {
1248
+ const counts = /* @__PURE__ */ new Map();
1249
+ for (const row of rows) {
1250
+ if (row.companyId !== companyId || publicAt && !isPublic(row, publicAt)) continue;
1251
+ for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1);
1252
+ }
1253
+ return [
1254
+ ...counts.entries()
1255
+ ].map(([tag, count]) => ({
1256
+ tag,
1257
+ count
1258
+ })).sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag));
1259
+ }
1260
+ };
1261
+ }
1262
+ __name(createInMemoryPostStore, "createInMemoryPostStore");
1263
+ // Annotate the CommonJS export names for ESM import in node:
1264
+ 0 && (module.exports = {
1265
+ ArchivePostUseCase,
1266
+ BuildFeedUseCase,
1267
+ CONTENT_MIGRATIONS_TABLE,
1268
+ COVER_IMAGE,
1269
+ CreatePostUseCase,
1270
+ FEED_FORMAT,
1271
+ GetPostUseCase,
1272
+ GetPublishedPostBySlugUseCase,
1273
+ ListPostsUseCase,
1274
+ ListPublishedPostsUseCase,
1275
+ ListSitemapEntriesUseCase,
1276
+ ListTagsUseCase,
1277
+ PostRepository,
1278
+ PublishPostUseCase,
1279
+ TAG_SCOPE,
1280
+ UnpublishPostUseCase,
1281
+ UpdatePostUseCase,
1282
+ UploadCoverImageUseCase,
1283
+ contentMigrationsFolder,
1284
+ contentSchema,
1285
+ createContentModule,
1286
+ createContentRoutes,
1287
+ createInMemoryPostStore,
1288
+ posts,
1289
+ runContentMigrations
1290
+ });
1291
+ //# sourceMappingURL=index.cjs.map