@adatechnology/content-module 0.2.2 → 0.4.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/README.md +40 -0
- package/dist/index.cjs +1958 -327
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +811 -40
- package/dist/index.d.ts +811 -40
- package/dist/index.js +1921 -294
- package/dist/index.js.map +1 -1
- package/dist/migrations/0002_community.sql +44 -0
- package/dist/migrations/meta/0002_snapshot.json +813 -0
- package/dist/migrations/meta/_journal.json +8 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.16.2_@swc+helpers@0.5.23__jiti@2.7.0_postcss@8.5.28_tsx@4.23.13_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/ContentModule.ts","../src/repositories/PostRepository.ts","../src/schema/schema.ts","../src/repositories/conditions.ts","../src/repositories/RecurrenceRepository.ts","../src/use-cases/Feed.use-cases.ts","../src/use-cases/Post.use-cases.ts","../src/shared/shortId.ts","../src/shared/isUniqueViolation.ts","../src/shared/notifyPostChanged.ts","../src/shared/toContract.ts","../src/use-cases/PublicPost.use-cases.ts","../src/use-cases/Recurrence.use-cases.ts","../src/use-cases/Scheduling.use-cases.ts","../src/shared/recurrence.ts","../src/use-cases/Template.use-cases.ts","../src/use-cases/UploadCoverImage.use-case.ts","../src/shared/coverImage.constant.ts","../src/http/adminRoutes.ts","../src/http/requireCompany.ts","../src/http/publicRoutes.ts","../src/http/routes.ts","../src/runMigrations.ts","../src/testing/inMemoryPostStore.ts","../src/scheduler.ts","../src/testing/inMemoryRecurrenceStore.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Composição raiz do módulo de conteúdo (blog, novidades, notícias). Recebe a conexão Drizzle do\n * host e devolve os use-cases; as rotas saem de `createContentRoutes` sobre este objeto.\n */\n\nimport { ConfigMissingError } from '@adatechnology/content-contracts'\nimport type {\n ClockPort,\n ContentHooks,\n ContentImageStoragePort,\n ContentModuleConfig,\n LoggerPort,\n} from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from './database.types'\nimport { PostRepository } from './repositories/PostRepository'\nimport { RecurrenceRepository } from './repositories/RecurrenceRepository'\nimport type { ContentDependencies, PostStorePort, RecurrenceStorePort } from './use-cases/contentModule.types'\nimport { BuildFeedUseCase, ListSitemapEntriesUseCase } from './use-cases/Feed.use-cases'\nimport {\n ArchivePostUseCase,\n CreatePostUseCase,\n GetPostUseCase,\n ListPostsUseCase,\n PublishPostUseCase,\n UnpublishPostUseCase,\n UpdatePostUseCase,\n} from './use-cases/Post.use-cases'\nimport {\n GetPublishedPostBySlugUseCase,\n ListPublishedPostsUseCase,\n ListTagsUseCase,\n} from './use-cases/PublicPost.use-cases'\nimport {\n CreateRecurrenceUseCase,\n ListRecurrencesUseCase,\n RemoveRecurrenceUseCase,\n UpdateRecurrenceUseCase,\n} from './use-cases/Recurrence.use-cases'\nimport { PublishDueUseCase, RepublishPostUseCase } from './use-cases/Scheduling.use-cases'\nimport { CountPostsUseCase, CreateFromTemplateUseCase, SaveAsTemplateUseCase } from './use-cases/Template.use-cases'\nimport { UploadCoverImageUseCase } from './use-cases/UploadCoverImage.use-case'\n\nexport type ContentModuleProviders = {\n /** Sem storage, a capa é só por URL e a rota de upload não sobe. */\n readonly imageStorage?: ContentImageStoragePort\n /** Padrão: relógio do sistema. Os testes injetam um fixo para provar o agendamento. */\n readonly clock?: ClockPort\n readonly logger?: LoggerPort\n /** Troca a persistência (ex.: dublê em memória num teste do host). Padrão: Drizzle sobre `db`. */\n readonly postStore?: PostStorePort\n readonly recurrenceStore?: RecurrenceStorePort\n}\n\nexport type CreateContentModuleParams = {\n readonly db?: ContentDatabase\n readonly config?: ContentModuleConfig\n readonly providers?: ContentModuleProviders\n readonly hooks?: ContentHooks\n}\n\nexport type ContentModule = {\n readonly useCases: {\n readonly createPost: CreatePostUseCase\n readonly updatePost: UpdatePostUseCase\n readonly archivePost: ArchivePostUseCase\n readonly publishPost: PublishPostUseCase\n readonly unpublishPost: UnpublishPostUseCase\n readonly getPost: GetPostUseCase\n readonly listPosts: ListPostsUseCase\n readonly getPublishedPostBySlug: GetPublishedPostBySlugUseCase\n readonly listPublishedPosts: ListPublishedPostsUseCase\n readonly listTags: ListTagsUseCase\n readonly countPosts: CountPostsUseCase\n readonly saveAsTemplate: SaveAsTemplateUseCase\n readonly createFromTemplate: CreateFromTemplateUseCase\n readonly republishPost: RepublishPostUseCase\n readonly createRecurrence: CreateRecurrenceUseCase\n readonly listRecurrences: ListRecurrencesUseCase\n readonly updateRecurrence: UpdateRecurrenceUseCase\n readonly removeRecurrence: RemoveRecurrenceUseCase\n /** O host chama num intervalo (ver `startContentScheduler`): publica o agendado vencido e as recorrências. */\n readonly publishDue: PublishDueUseCase\n /** Capacidade por ausência: sem `providers.imageStorage`, não existe. */\n readonly uploadCoverImage?: UploadCoverImageUseCase\n /** Sem `config.feed`, feed e sitemap não existem. */\n readonly buildFeed?: BuildFeedUseCase\n readonly listSitemapEntries?: ListSitemapEntriesUseCase\n }\n readonly config: ContentModuleConfig\n}\n\nconst SYSTEM_CLOCK: ClockPort = { now: () => new Date() }\n\nfunction assertValidConfig(config: ContentModuleConfig): void {\n // Feed com endereço relativo geraria links quebrados em todo leitor de RSS — falha no boot.\n if (config.feed && !/^https?:\\/\\/[^/]/i.test(config.feed.siteUrl)) throw new ConfigMissingError('feed.siteUrl')\n if (config.feed && !config.feed.title.trim()) throw new ConfigMissingError('feed.title')\n if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes('{slug}')) {\n throw new ConfigMissingError('feed.postPathTemplate')\n }\n if (config.wordsPerMinute !== undefined && !(config.wordsPerMinute > 0))\n throw new ConfigMissingError('wordsPerMinute')\n}\n\nexport function createContentModule(params: CreateContentModuleParams): ContentModule {\n const config = params.config ?? {}\n assertValidConfig(config)\n\n const posts = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : undefined)\n if (!posts) throw new ConfigMissingError('db')\n const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : undefined)\n if (!recurrences) throw new ConfigMissingError('db')\n\n const dependencies: ContentDependencies = {\n posts,\n recurrences,\n config,\n clock: params.providers?.clock ?? SYSTEM_CLOCK,\n ...(params.hooks ? { hooks: params.hooks } : {}),\n ...(params.providers?.imageStorage ? { imageStorage: params.providers.imageStorage } : {}),\n ...(params.providers?.logger ? { logger: params.providers.logger } : {}),\n }\n\n return {\n useCases: {\n createPost: new CreatePostUseCase(dependencies),\n updatePost: new UpdatePostUseCase(dependencies),\n archivePost: new ArchivePostUseCase(dependencies),\n publishPost: new PublishPostUseCase(dependencies),\n unpublishPost: new UnpublishPostUseCase(dependencies),\n getPost: new GetPostUseCase(dependencies),\n listPosts: new ListPostsUseCase(dependencies),\n getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),\n listPublishedPosts: new ListPublishedPostsUseCase(dependencies),\n listTags: new ListTagsUseCase(dependencies),\n countPosts: new CountPostsUseCase(dependencies),\n saveAsTemplate: new SaveAsTemplateUseCase(dependencies),\n createFromTemplate: new CreateFromTemplateUseCase(dependencies),\n republishPost: new RepublishPostUseCase(dependencies),\n createRecurrence: new CreateRecurrenceUseCase(dependencies),\n listRecurrences: new ListRecurrencesUseCase(dependencies),\n updateRecurrence: new UpdateRecurrenceUseCase(dependencies),\n removeRecurrence: new RemoveRecurrenceUseCase(dependencies),\n publishDue: new PublishDueUseCase(dependencies),\n ...(dependencies.imageStorage ? { uploadCoverImage: new UploadCoverImageUseCase(dependencies) } : {}),\n ...(config.feed\n ? {\n buildFeed: new BuildFeedUseCase(dependencies, config.feed),\n listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed),\n }\n : {}),\n },\n config,\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, desc, eq, inArray, sql } from 'drizzle-orm'\nimport { POST_STATUS, type PostCounts, type TagCount } from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from '../database.types'\nimport { postFormerSlugs, posts, type NewPostRow, type PostRow } from '../schema/schema'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\nimport {\n postAdminListCondition,\n postDueCondition,\n postOwnedByCondition,\n postPublicCondition,\n postPublicShortIdCondition,\n postShortIdCondition,\n postPublicSlugCondition,\n postSlugCondition,\n} from './conditions'\n\nconst TAG_LIST_LIMIT = 200\n\nconst SORT_COLUMNS = {\n title: posts.title,\n status: posts.status,\n publishedAt: posts.publishedAt,\n updatedAt: posts.updatedAt,\n} as const\n\n// Padrão: a última edição primeiro, que é o que o painel está mexendo agora. `id` desempata para\n// a paginação não repetir nem pular linha. Data ausente (rascunho) vai sempre para o fim.\nfunction adminOrder(query: PostAdminListQuery) {\n const column = SORT_COLUMNS[query.sort ?? 'updatedAt']\n const direction = (query.order ?? 'desc') === 'asc' ? asc : desc\n const primary =\n query.sort === 'publishedAt'\n ? sql`${column} ${sql.raw(query.order === 'asc' ? 'asc' : 'desc')} nulls last`\n : direction(column)\n return [primary, asc(posts.id)]\n}\n\nexport class PostRepository implements PostStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewPostRow): Promise<PostRow> {\n const [row] = await this.db.insert(posts).values(values).returning()\n if (!row) throw new Error('content-module: insert em posts não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1)\n return row\n }\n\n async findBySlug(params: { companyId: string; slug: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1)\n return row\n }\n\n async findPublicBySlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1)\n return row\n }\n\n async findByShortId(params: { companyId: string; shortId: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicByShortId(params: { companyId: string; shortId: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicByFormerSlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [former] = await this.db\n .select({ postId: postFormerSlugs.postId })\n .from(postFormerSlugs)\n .where(and(eq(postFormerSlugs.companyId, params.companyId), eq(postFormerSlugs.slug, params.slug)))\n .limit(1)\n if (!former) return undefined\n const [row] = await this.db\n .select()\n .from(posts)\n .where(and(postPublicCondition(params), eq(posts.id, former.postId)))\n .limit(1)\n return row\n }\n\n async recordFormerSlug(params: { companyId: string; postId: string; slug: string }): Promise<void> {\n await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing()\n }\n\n async update(params: { companyId: string; id: string; values: Partial<NewPostRow> }): Promise<PostRow | undefined> {\n const [row] = await this.db\n .update(posts)\n .set({ ...params.values, updatedAt: new Date() })\n .where(postOwnedByCondition(params))\n .returning()\n return row\n }\n\n async listForAdmin(query: PostAdminListQuery): Promise<PostPage> {\n const where = postAdminListCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(...adminOrder(query))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async listPublic(query: PostPublicListQuery): Promise<PostPage> {\n const where = postPublicCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(desc(posts.publishedAt), asc(posts.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async countByStatus(params: { companyId: string; now: Date }): Promise<PostCounts> {\n // Instante como texto com cast: o driver não serializa `Date` solto dentro de `sql` cru.\n const now = sql`${params.now.toISOString()}::timestamptz`\n const counted = (condition: ReturnType<typeof sql>) => sql<number>`count(*) filter (where ${condition})::int`\n const livePublished = sql`(${posts.status} = ${POST_STATUS.PUBLISHED} or (${posts.status} = ${POST_STATUS.SCHEDULED} and ${posts.publishedAt} <= ${now}))`\n const [row] = await this.db\n .select({\n published: counted(sql`not ${posts.isTemplate} and ${livePublished}`),\n scheduled: counted(\n sql`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.SCHEDULED} and ${posts.publishedAt} > ${now}`,\n ),\n draft: counted(sql`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.DRAFT}`),\n archived: counted(sql`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.ARCHIVED}`),\n templates: counted(sql`${posts.isTemplate} and ${posts.status} <> ${POST_STATUS.ARCHIVED}`),\n })\n .from(posts)\n .where(eq(posts.companyId, params.companyId))\n return row ?? { published: 0, scheduled: 0, draft: 0, archived: 0, templates: 0 }\n }\n\n async claimDueScheduled(params: { now: Date; limit: number }): Promise<readonly PostRow[]> {\n // Um único UPDATE com a seleção travada por dentro: quem chega depois pula as linhas já travadas\n // e não as enxerga mais como agendadas — nenhum post é marcado nem notificado duas vezes.\n const due = this.db\n .select({ id: posts.id })\n .from(posts)\n .where(postDueCondition({ now: params.now }))\n .orderBy(asc(posts.publishedAt), asc(posts.id))\n .limit(params.limit)\n .for('update', { skipLocked: true })\n return this.db.update(posts).set({ status: POST_STATUS.PUBLISHED }).where(inArray(posts.id, due)).returning()\n }\n\n async listTags(params: { companyId: string; publicAt?: Date }): Promise<readonly TagCount[]> {\n const where = params.publicAt\n ? postPublicCondition({ companyId: params.companyId, now: params.publicAt })\n : postAdminListCondition({ companyId: params.companyId, now: new Date() })\n // Subconsulta em vez de `group by unnest(...)`: o Postgres não aceita função que devolve\n // conjunto no GROUP BY.\n const postTags = this.db\n .select({ tag: sql<string>`unnest(${posts.tags})`.as('tag') })\n .from(posts)\n .where(where)\n .as('post_tags')\n const rows = await this.db\n .select({ tag: postTags.tag, count: sql<number>`count(*)::int` })\n .from(postTags)\n .groupBy(postTags.tag)\n .orderBy(sql`count(*) desc`, asc(postTags.tag))\n .limit(TAG_LIST_LIMIT)\n return rows\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { sql } from 'drizzle-orm'\nimport {\n boolean,\n index,\n integer,\n jsonb,\n primaryKey,\n pgSchema,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n varchar,\n} from 'drizzle-orm/pg-core'\n\n// Schema Postgres dedicado — o módulo nunca escreve no `public` do host.\nexport const contentSchema = pgSchema('content')\n\n// `status` em varchar e não ENUM nativo; os valores espelham `POST_STATUS` do contracts.\nexport const posts = contentSchema.table(\n 'posts',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n shortId: varchar('short_id', { length: 6 }).notNull(),\n title: varchar('title', { length: 200 }).notNull(),\n excerpt: varchar('excerpt', { length: 500 }),\n body: text('body').notNull().default(''),\n coverImageUrl: varchar('cover_image_url', { length: 2048 }),\n coverImageAlt: varchar('cover_image_alt', { length: 300 }),\n tags: text('tags').array().notNull().default([]),\n tagLabels: jsonb('tag_labels').$type<Record<string, string>>().notNull().default({}),\n status: varchar('status', { length: 12 }).notNull().default('draft'),\n isTemplate: boolean('is_template').notNull().default(false),\n publishedAt: timestamp('published_at', { withTimezone: true }),\n authorName: varchar('author_name', { length: 120 }),\n seoTitle: varchar('seo_title', { length: 200 }),\n seoDescription: varchar('seo_description', { length: 320 }),\n canonicalUrl: varchar('canonical_url', { length: 2048 }),\n readingTimeMinutes: integer('reading_time_minutes').notNull().default(1),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo\n // faria um link antigo (já compartilhado) abrir outro post.\n uniqueIndex('idx_posts_company_slug').on(table.companyId, table.slug),\n uniqueIndex('idx_posts_company_short_id').on(table.companyId, table.shortId),\n // Serve a listagem pública: empresa + status + ordem por data.\n index('idx_posts_company_status_published').on(table.companyId, table.status, table.publishedAt),\n index('idx_posts_tags').using('gin', table.tags),\n // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.\n index('idx_posts_due')\n .on(table.publishedAt)\n .where(sql`\"status\" = 'scheduled'`),\n ],\n)\n\nexport type PostRow = typeof posts.$inferSelect\nexport type NewPostRow = typeof posts.$inferInsert\n\n// `frequency` em varchar (weekly | monthly), sem ENUM nativo. Posts nunca são apagados, então a\n// chave estrangeira para o modelo não precisa de ON DELETE.\nexport const recurrenceRules = contentSchema.table(\n 'recurrence_rules',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n templateId: uuid('template_id')\n .notNull()\n .references(() => posts.id),\n frequency: varchar('frequency', { length: 10 }).notNull(),\n // Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.\n anchorDay: integer('anchor_day').notNull(),\n isActive: boolean('is_active').notNull().default(true),\n nextRunAt: timestamp('next_run_at', { withTimezone: true }).notNull(),\n lastRunAt: timestamp('last_run_at', { withTimezone: true }),\n lastPostId: uuid('last_post_id'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index('idx_recurrence_company').on(table.companyId),\n index('idx_recurrence_due')\n .on(table.nextRunAt)\n .where(sql`\"is_active\"`),\n ],\n)\n\nexport type RecurrenceRow = typeof recurrenceRules.$inferSelect\nexport type NewRecurrenceRow = typeof recurrenceRules.$inferInsert\n\n// Slugs que o post já teve: o link antigo continua abrindo o post (e o host o redireciona ao canônico).\nexport const postFormerSlugs = contentSchema.table(\n 'post_former_slugs',\n {\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n postId: uuid('post_id')\n .notNull()\n .references(() => posts.id),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [primaryKey({ columns: [table.companyId, table.slug] })],\n)\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Toda condição alcançável por uma requisição vive aqui como função pura exportada — a mesma que o\n * repositório chama e que `isolation.test.ts` renderiza em SQL. Um refactor que esqueça o filtro\n * de empresa quebra o teste na hora.\n */\n\nimport { and, arrayContains, arrayOverlaps, eq, gt, inArray, lte, ne, or, sql, type SQL } from 'drizzle-orm'\nimport { POST_STATUS, type PostStatus } from '@adatechnology/content-contracts'\n\nimport { posts } from '../schema/schema'\n\nexport function postOwnedByCondition(params: { companyId: string; id: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id)) as SQL\n}\n\nexport function postSlugCondition(params: { companyId: string; slug: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug)) as SQL\n}\n\nexport function postAdminListCondition(params: {\n companyId: string\n status?: PostStatus\n tags?: readonly string[]\n search?: string\n /** `true`: só modelos (menos os arquivados). Ausente/`false`: só posts — modelo nunca aparece misturado. */\n isTemplate?: boolean\n now: Date\n}): SQL {\n const conditions: SQL[] = [eq(posts.companyId, params.companyId), templateCondition(params.isTemplate)]\n if (params.status) conditions.push(statusCondition(params.status, params.now))\n if (params.tags?.length) conditions.push(arrayOverlaps(posts.tags, [...params.tags]))\n if (params.search) {\n const pattern = `%${params.search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n conditions.push(sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`)\n }\n return and(...conditions) as SQL\n}\n\nfunction templateCondition(isTemplate: boolean | undefined): SQL {\n if (isTemplate) return and(eq(posts.isTemplate, true), ne(posts.status, POST_STATUS.ARCHIVED)) as SQL\n return eq(posts.isTemplate, false)\n}\n\n/**\n * Filtra pelo status que o painel MOSTRA: agendado cuja hora passou aparece como publicado, então\n * o filtro \"publicados\" o inclui e o filtro \"agendados\" o exclui.\n */\nfunction statusCondition(status: PostStatus, now: Date): SQL {\n if (status === POST_STATUS.PUBLISHED) {\n return or(\n eq(posts.status, POST_STATUS.PUBLISHED),\n and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)),\n ) as SQL\n }\n if (status === POST_STATUS.SCHEDULED) {\n return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now)) as SQL\n }\n return eq(posts.status, status)\n}\n\n/**\n * Público = publicado ou agendado cuja hora chegou. `scheduled` entra na condição justamente para\n * que o agendamento valha sem cron: no instante de `published_at` o post passa a casar aqui.\n */\nexport function postPublicCondition(params: { companyId: string; now: Date; tag?: string }): SQL {\n const conditions: SQL[] = [\n eq(posts.companyId, params.companyId),\n inArray(posts.status, [POST_STATUS.PUBLISHED, POST_STATUS.SCHEDULED]),\n lte(posts.publishedAt, params.now),\n ]\n if (params.tag) conditions.push(arrayContains(posts.tags, [params.tag]))\n return and(...conditions) as SQL\n}\n\nexport function postPublicSlugCondition(params: { companyId: string; slug: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.slug, params.slug)) as SQL\n}\n\n/**\n * Agendado cuja hora chegou, de qualquer empresa: é a única condição sem `company_id`, de propósito —\n * o `publishDue` é tarefa do sistema e varre todas as empresas. Modelo nunca entra.\n */\nexport function postDueCondition(params: { now: Date }): SQL {\n return and(\n eq(posts.status, POST_STATUS.SCHEDULED),\n eq(posts.isTemplate, false),\n lte(posts.publishedAt, params.now),\n ) as SQL\n}\n\nexport function postShortIdCondition(params: { companyId: string; shortId: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.shortId, params.shortId)) as SQL\n}\n\nexport function postPublicShortIdCondition(params: { companyId: string; shortId: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.shortId, params.shortId)) as SQL\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, eq, lte } from 'drizzle-orm'\n\nimport type { ContentDatabase } from '../database.types'\nimport { recurrenceRules, type NewRecurrenceRow, type RecurrenceRow } from '../schema/schema'\nimport type { RecurrenceStorePort } from '../use-cases/contentModule.types'\n\nexport function recurrenceOwnedByCondition(params: { companyId: string; id: string }) {\n return and(eq(recurrenceRules.companyId, params.companyId), eq(recurrenceRules.id, params.id))\n}\n\nexport class RecurrenceRepository implements RecurrenceStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewRecurrenceRow): Promise<RecurrenceRow> {\n const [row] = await this.db.insert(recurrenceRules).values(values).returning()\n if (!row) throw new Error('content-module: insert em recurrence_rules não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<RecurrenceRow | undefined> {\n const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1)\n return row\n }\n\n async list(params: { companyId: string }): Promise<readonly RecurrenceRow[]> {\n return this.db\n .select()\n .from(recurrenceRules)\n .where(eq(recurrenceRules.companyId, params.companyId))\n .orderBy(asc(recurrenceRules.nextRunAt), asc(recurrenceRules.id))\n }\n\n async update(params: {\n companyId: string\n id: string\n values: Partial<NewRecurrenceRow>\n }): Promise<RecurrenceRow | undefined> {\n const [row] = await this.db\n .update(recurrenceRules)\n .set(params.values)\n .where(recurrenceOwnedByCondition(params))\n .returning()\n return row\n }\n\n async remove(params: { companyId: string; id: string }): Promise<boolean> {\n const removed = await this.db\n .delete(recurrenceRules)\n .where(recurrenceOwnedByCondition(params))\n .returning({ id: recurrenceRules.id })\n return removed.length > 0\n }\n\n async processDue(params: {\n now: Date\n limit: number\n handle: (rule: RecurrenceRow) => Promise<Partial<NewRecurrenceRow>>\n }): Promise<number> {\n return this.db.transaction(async (transaction) => {\n const due = await transaction\n .select()\n .from(recurrenceRules)\n .where(and(eq(recurrenceRules.isActive, true), lte(recurrenceRules.nextRunAt, params.now)))\n .orderBy(asc(recurrenceRules.nextRunAt), asc(recurrenceRules.id))\n .limit(params.limit)\n .for('update', { skipLocked: true })\n let processed = 0\n // Sequencial de propósito: a transação é uma conexão só, e a ordem é a da data de vencimento.\n for (const rule of due) {\n const values = await params.handle(rule)\n await transaction.update(recurrenceRules).set(values).where(eq(recurrenceRules.id, rule.id))\n processed += 1\n }\n return processed\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * RSS, Atom e entradas de sitemap do site público, a partir de `config.feed`. Sem essa config os\n * use-cases nem são construídos e as rotas não sobem.\n */\n\nimport {\n buildAtomFeed,\n buildExcerpt,\n buildPostUrl,\n buildRssFeed,\n renderMarkdownToHtml,\n type ContentFeedConfig,\n type FeedChannel,\n type FeedItem,\n type SitemapEntry,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst DEFAULT_ITEM_LIMIT = 20\n// O protocolo de sitemap aceita até 50 mil URLs por arquivo; blog real fica muito abaixo disso.\nconst SITEMAP_LIMIT = 50_000\n\nexport const FEED_FORMAT = { RSS: 'rss', ATOM: 'atom' } as const\nexport type FeedFormat = (typeof FEED_FORMAT)[keyof typeof FEED_FORMAT]\n\nexport class BuildFeedUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n async execute(params: {\n readonly companyId: string\n readonly format: FeedFormat\n readonly feedUrl?: string\n }): Promise<string> {\n const now = this.dependencies.clock.now()\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now,\n page: 1,\n pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT,\n })\n const channel: FeedChannel = {\n siteUrl: this.feed.siteUrl,\n title: this.feed.title,\n ...(this.feed.description ? { description: this.feed.description } : {}),\n ...(this.feed.language ? { language: this.feed.language } : {}),\n ...(params.feedUrl ? { feedUrl: params.feedUrl } : {}),\n }\n const items = page.rows.map((row) => this.toItem(row))\n return params.format === FEED_FORMAT.ATOM\n ? buildAtomFeed({ channel, items, now })\n : buildRssFeed({ channel, items })\n }\n\n private toItem(row: PostRow): FeedItem {\n return {\n title: row.title,\n url: buildPostUrl({\n siteUrl: this.feed.siteUrl,\n slug: row.slug,\n shortId: row.shortId,\n postPathTemplate: this.feed.postPathTemplate,\n }),\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n summary: row.excerpt ?? buildExcerpt(row.body),\n ...((this.feed.includeContent ?? true)\n ? { contentHtml: renderMarkdownToHtml(row.body, { headingIds: false }) }\n : {}),\n ...(row.authorName ? { authorName: row.authorName } : {}),\n categories: row.tags,\n ...(row.coverImageUrl ? { imageUrl: row.coverImageUrl } : {}),\n }\n }\n}\n\nexport class ListSitemapEntriesUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */\n async execute(params: { readonly companyId: string }): Promise<readonly SitemapEntry[]> {\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now: this.dependencies.clock.now(),\n page: 1,\n pageSize: SITEMAP_LIMIT,\n })\n return page.rows.map((row) => ({\n loc: buildPostUrl({\n siteUrl: this.feed.siteUrl,\n slug: row.slug,\n shortId: row.shortId,\n postPathTemplate: this.feed.postPathTemplate,\n }),\n lastmod: row.updatedAt.toISOString(),\n }))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Casos de uso do painel: criar, editar, arquivar, publicar/agendar, despublicar, ler e listar.\n * Todos validam a entrada com o schema do contracts de novo — o host pode chamar o use-case sem\n * passar pela rota, e a regra não pode depender de quem chamou.\n */\n\nimport {\n buildTagLabels,\n createPostSchema,\n DuplicateSlugError,\n estimateReadingTimeMinutes,\n listPostsQuerySchema,\n normalizeTags,\n POST_EVENT,\n POST_STATUS,\n PostNotFoundError,\n TemplateNotPublishableError,\n publishPostSchema,\n buildShortSlug,\n updatePostSchema,\n withSlugSuffix,\n type CreatePostInput,\n type ListPostsQuery,\n type Paginated,\n type Post,\n type PostEventType,\n type PostSummary,\n type PublishPostInput,\n type UpdatePostInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { generateShortId } from '../shared/shortId'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPagination, toPost, toPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst MAX_SLUG_ATTEMPTS = 50\nconst FALLBACK_SLUG = 'post'\n\nexport type PostReference = { readonly companyId: string; readonly id: string }\n\nexport abstract class PostUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected now(): Date {\n return this.dependencies.clock.now()\n }\n\n protected async findOrFail(reference: PostReference): Promise<PostRow> {\n const row = await this.dependencies.posts.findById(reference)\n if (!row) throw new PostNotFoundError(reference.id)\n return row\n }\n\n protected async save(reference: PostReference, values: Partial<NewPostRow>, event: PostEventType): Promise<Post> {\n const row = await this.dependencies.posts.update({ ...reference, values }).catch((error: unknown) => {\n if (isUniqueViolation(error) && values.slug) throw new DuplicateSlugError(values.slug)\n throw error\n })\n if (!row) throw new PostNotFoundError(reference.id)\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, event, post)\n return post\n }\n\n /** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */\n protected async generateShortId(companyId: string): Promise<string> {\n for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = generateShortId()\n if (!(await this.dependencies.posts.findByShortId({ companyId, shortId: candidate }))) return candidate\n }\n throw new Error('content-module: sem id curto livre')\n }\n\n protected readingTime(body: string): number {\n return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute)\n }\n\n protected async assertSlugAvailable(companyId: string, slug: string, ownId?: string): Promise<void> {\n const existing = await this.dependencies.posts.findBySlug({ companyId, slug })\n if (existing && existing.id !== ownId) throw new DuplicateSlugError(slug)\n }\n\n /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */\n protected async generateSlug(companyId: string, title: string): Promise<string> {\n return this.uniqueSlug(companyId, buildShortSlug(title, this.dependencies.config.slug) || FALLBACK_SLUG)\n }\n\n protected async uniqueSlug(companyId: string, base: string): Promise<string> {\n for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = withSlugSuffix(base, attempt)\n if (!(await this.dependencies.posts.findBySlug({ companyId, slug: candidate }))) return candidate\n }\n return withSlugSuffix(base, Date.now())\n }\n}\n\nfunction optionalFields(\n input: Omit<UpdatePostInput, 'slug' | 'title' | 'body' | 'tags' | 'tagLabels'>,\n): Partial<NewPostRow> {\n const values: Partial<NewPostRow> = {}\n if (input.excerpt !== undefined) values.excerpt = input.excerpt || null\n if (input.coverImageUrl !== undefined) values.coverImageUrl = input.coverImageUrl || null\n if (input.coverImageAlt !== undefined) values.coverImageAlt = input.coverImageAlt || null\n if (input.authorName !== undefined) values.authorName = input.authorName || null\n if (input.seoTitle !== undefined) values.seoTitle = input.seoTitle || null\n if (input.seoDescription !== undefined) values.seoDescription = input.seoDescription || null\n if (input.canonicalUrl !== undefined) values.canonicalUrl = input.canonicalUrl || null\n return values\n}\n\nexport class CreatePostUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string; readonly input: CreatePostInput }): Promise<Post> {\n const input = createPostSchema.parse(params.input)\n const { companyId } = params\n if (input.slug) await this.assertSlugAvailable(companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(companyId, input.title))\n\n const row = await this.dependencies.posts\n .create({\n companyId,\n slug,\n shortId: await this.generateShortId(companyId),\n title: input.title,\n body: input.body,\n tags: normalizeTags(input.tags ?? []),\n tagLabels: buildTagLabels({ typed: input.tags ?? [], explicit: input.tagLabels }),\n status: POST_STATUS.DRAFT,\n readingTimeMinutes: this.readingTime(input.body),\n ...optionalFields(input),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(slug)\n throw error\n })\n\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class UpdatePostUseCase extends PostUseCaseBase {\n /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */\n async execute(params: PostReference & { readonly input: UpdatePostInput }): Promise<Post> {\n const input = updatePostSchema.parse(params.input)\n const existing = await this.findOrFail(params)\n\n const values: Partial<NewPostRow> = optionalFields(input)\n if (input.title !== undefined) values.title = input.title\n if (input.body !== undefined) {\n values.body = input.body\n values.readingTimeMinutes = this.readingTime(input.body)\n }\n if (input.tags !== undefined || input.tagLabels !== undefined) {\n const tags = normalizeTags(input.tags ?? existing.tags)\n values.tags = tags\n values.tagLabels = buildTagLabels({\n typed: input.tags ?? tags,\n explicit: input.tagLabels,\n previous: existing.tagLabels,\n })\n }\n if (input.slug !== undefined && input.slug !== existing.slug) {\n await this.assertSlugAvailable(params.companyId, input.slug, existing.id)\n values.slug = input.slug\n // O endereço antigo continua abrindo o post: o host o redireciona ao canônico.\n await this.dependencies.posts.recordFormerSlug({\n companyId: params.companyId,\n postId: existing.id,\n slug: existing.slug,\n })\n }\n return this.save(params, values, POST_EVENT.UPDATED)\n }\n}\n\nexport class PublishPostUseCase extends PostUseCaseBase {\n /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */\n async execute(params: PostReference & { readonly input?: PublishPostInput }): Promise<Post> {\n const input = publishPostSchema.parse(params.input ?? {})\n const existing = await this.findOrFail(params)\n if (existing.isTemplate) throw new TemplateNotPublishableError(params.id)\n const now = this.now()\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n const status = publishedAt > now ? POST_STATUS.SCHEDULED : POST_STATUS.PUBLISHED\n return this.save(params, { status, publishedAt }, POST_EVENT.PUBLISHED)\n }\n}\n\nexport class UnpublishPostUseCase extends PostUseCaseBase {\n /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.DRAFT, publishedAt: null }, POST_EVENT.UNPUBLISHED)\n }\n}\n\nexport class ArchivePostUseCase extends PostUseCaseBase {\n /** \"Excluir\" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.ARCHIVED }, POST_EVENT.ARCHIVED)\n }\n}\n\nexport class GetPostUseCase extends PostUseCaseBase {\n async execute(params: PostReference): Promise<Post> {\n return toPost(await this.findOrFail(params), this.now())\n }\n}\n\nexport class ListPostsUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string } & Partial<ListPostsQuery>): Promise<Paginated<PostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPostsQuerySchema.parse(rawQuery)\n const { tag: rawTag, ...rest } = query\n const tags = rawTag ? normalizeTags(rawTag.split(',')) : []\n const now = this.now()\n const page = await this.dependencies.posts.listForAdmin({\n companyId,\n ...rest,\n isTemplate: query.isTemplate ?? false,\n now,\n ...(tags.length > 0 ? { tags } : {}),\n })\n return {\n data: page.rows.map((row) => toPostSummary(row, now)),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { randomInt } from 'node:crypto'\nimport { SHORT_ID_LENGTH } from '@adatechnology/content-contracts'\n\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\n\n/** 6 caracteres base36 (~2 bilhões): a colisão é checada contra a empresa antes de gravar. */\nexport function generateShortId(): string {\n let value = ''\n for (let index = 0; index < SHORT_ID_LENGTH; index += 1) value += ALPHABET[randomInt(ALPHABET.length)]\n return value\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nconst UNIQUE_VIOLATION = '23505'\n\n/**\n * Cada driver embrulha o erro do Postgres de um jeito (`code` direto, ou em `cause`). A checagem\n * prévia de slug não fecha a corrida entre dois saves simultâneos; o índice único fecha, e isto\n * traduz a violação para o 409 do domínio.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n let current: unknown = error\n for (let depth = 0; depth < 3 && typeof current === 'object' && current !== null; depth += 1) {\n if ((current as { code?: unknown }).code === UNIQUE_VIOLATION) return true\n current = (current as { cause?: unknown }).cause\n }\n return false\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { Post, PostEventType } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/**\n * O gancho do host roda depois da escrita, e falha nele não desfaz o que já foi gravado: o post\n * publicado continua publicado mesmo que a purga de cache do host caia. Por isso o catch local.\n */\nexport async function notifyPostChanged(\n dependencies: ContentDependencies,\n type: PostEventType,\n post: Post,\n): Promise<void> {\n const hook = dependencies.hooks?.onPostChanged\n if (!hook) return\n try {\n await hook({ type, post })\n } catch (error) {\n dependencies.logger?.error('content-module: hook onPostChanged falhou', {\n postId: post.id,\n type,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n POST_STATUS,\n type Pagination,\n type Post,\n type PostStatus,\n type PostSummary,\n type PublicPost,\n type PublicPostSummary,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\n\n/** Agendado cuja hora já passou é publicado: o painel mostra o estado que o leitor vê. */\nexport function effectiveStatus(row: PostRow, now: Date): PostStatus {\n if (row.status === POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS.PUBLISHED\n return row.status as PostStatus\n}\n\nexport function toPostSummary(row: PostRow, now: Date): PostSummary {\n return {\n id: row.id,\n companyId: row.companyId,\n slug: row.slug,\n shortId: row.shortId,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n tagLabels: row.tagLabels,\n status: effectiveStatus(row, now),\n isTemplate: row.isTemplate,\n publishedAt: row.publishedAt?.toISOString() ?? null,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n }\n}\n\nexport function toPost(row: PostRow, now: Date): Post {\n return { ...toPostSummary(row, now), body: row.body }\n}\n\n/** Só chamado sobre linha que passou pela condição pública — `publishedAt` existe. */\nexport function toPublicPostSummary(row: PostRow): PublicPostSummary {\n return {\n id: row.id,\n slug: row.slug,\n shortId: row.shortId,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n tagLabels: row.tagLabels,\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n }\n}\n\nexport function toPublicPost(row: PostRow): PublicPost {\n return { ...toPublicPostSummary(row), body: row.body }\n}\n\nexport function toPagination(params: { total: number; page: number; pageSize: number }): Pagination {\n return { ...params, totalPages: Math.max(1, Math.ceil(params.total / params.pageSize)) }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Leitura do site público. Só enxerga post publicado (ou agendado cuja hora chegou) da empresa\n * resolvida pelo host — rascunho, arquivado e agendado futuro respondem 404, igual a inexistente.\n */\n\nimport {\n listPublishedPostsQuerySchema,\n normalizeTag,\n parsePostRef,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n type Paginated,\n type PublicPost,\n type PublicPostSummary,\n type TagCount,\n} from '@adatechnology/content-contracts'\n\nimport { toPagination, toPublicPost, toPublicPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport class GetPublishedPostBySlugUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /**\n * `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto\n * manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`\n * do resultado com o pedido e redireciona (301) quando forem diferentes.\n */\n async execute(params: { readonly companyId: string; readonly slug: string }): Promise<PublicPost> {\n const { posts, clock } = this.dependencies\n const parsed = parsePostRef(params.slug)\n const query = { companyId: params.companyId, now: clock.now() }\n const row =\n (parsed.shortId ? await posts.findPublicByShortId({ ...query, shortId: parsed.shortId }) : undefined) ??\n (await posts.findPublicBySlug({ ...query, slug: parsed.slug })) ??\n (await posts.findPublicByFormerSlug({ ...query, slug: parsed.slug }))\n if (!row) throw new PostNotFoundError(parsed.slug)\n return toPublicPost(row)\n }\n}\n\nexport class ListPublishedPostsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(\n params: { readonly companyId: string } & Partial<ListPublishedPostsQuery>,\n ): Promise<Paginated<PublicPostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPublishedPostsQuerySchema.parse(rawQuery)\n const tag = query.tag ? normalizeTag(query.tag) : undefined\n const page = await this.dependencies.posts.listPublic({\n companyId,\n now: this.dependencies.clock.now(),\n page: query.page,\n pageSize: query.pageSize,\n ...(tag ? { tag } : {}),\n })\n return {\n data: page.rows.map(toPublicPostSummary),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n\nexport const TAG_SCOPE = { PUBLIC: 'public', ADMIN: 'admin' } as const\nexport type TagScope = (typeof TAG_SCOPE)[keyof typeof TAG_SCOPE]\n\nexport class ListTagsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */\n async execute(params: { readonly companyId: string; readonly scope: TagScope }): Promise<readonly TagCount[]> {\n return this.dependencies.posts.listTags({\n companyId: params.companyId,\n ...(params.scope === TAG_SCOPE.PUBLIC ? { publicAt: this.dependencies.clock.now() } : {}),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Regras de recorrência do painel: cada regra publica, na frequência escolhida, um post novo copiado\n * de um modelo. Quem executa é o `publishDue`.\n */\n\nimport {\n createRecurrenceSchema,\n NotATemplateError,\n PostNotFoundError,\n RecurrenceNotFoundError,\n updateRecurrenceSchema,\n type CreateRecurrenceInput,\n type RecurrenceFrequency,\n type RecurrenceRule,\n type UpdateRecurrenceInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewRecurrenceRow, RecurrenceRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nabstract class RecurrenceUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected async toRule(row: RecurrenceRow): Promise<RecurrenceRule> {\n const template = await this.dependencies.posts.findById({ companyId: row.companyId, id: row.templateId })\n return {\n id: row.id,\n companyId: row.companyId,\n templateId: row.templateId,\n templateTitle: template?.title ?? '',\n frequency: row.frequency as RecurrenceFrequency,\n isActive: row.isActive,\n nextRunAt: row.nextRunAt.toISOString(),\n lastRunAt: row.lastRunAt?.toISOString() ?? null,\n lastPostId: row.lastPostId,\n createdAt: row.createdAt.toISOString(),\n }\n }\n\n protected async findOrFail(params: { companyId: string; id: string }): Promise<RecurrenceRow> {\n const row = await this.dependencies.recurrences.findById(params)\n if (!row) throw new RecurrenceNotFoundError(params.id)\n return row\n }\n}\n\nexport class CreateRecurrenceUseCase extends RecurrenceUseCaseBase {\n async execute(params: {\n readonly companyId: string\n readonly input: CreateRecurrenceInput\n }): Promise<RecurrenceRule> {\n const input = createRecurrenceSchema.parse(params.input)\n const template = await this.dependencies.posts.findById({ companyId: params.companyId, id: input.templateId })\n if (!template) throw new PostNotFoundError(input.templateId)\n if (!template.isTemplate) throw new NotATemplateError(input.templateId)\n const startsAt = new Date(input.startsAt)\n const values: NewRecurrenceRow = {\n companyId: params.companyId,\n templateId: input.templateId,\n frequency: input.frequency,\n anchorDay: startsAt.getUTCDate(),\n nextRunAt: startsAt,\n }\n return this.toRule(await this.dependencies.recurrences.create(values))\n }\n}\n\nexport class ListRecurrencesUseCase extends RecurrenceUseCaseBase {\n async execute(params: { readonly companyId: string }): Promise<readonly RecurrenceRule[]> {\n const rows = await this.dependencies.recurrences.list(params)\n return Promise.all(rows.map((row) => this.toRule(row)))\n }\n}\n\nexport class UpdateRecurrenceUseCase extends RecurrenceUseCaseBase {\n /** Pausar/retomar e remarcar a próxima execução. */\n async execute(params: {\n readonly companyId: string\n readonly id: string\n readonly input: UpdateRecurrenceInput\n }): Promise<RecurrenceRule> {\n const input = updateRecurrenceSchema.parse(params.input)\n await this.findOrFail(params)\n const values: Partial<NewRecurrenceRow> = {}\n if (input.isActive !== undefined) values.isActive = input.isActive\n if (input.nextRunAt !== undefined) {\n values.nextRunAt = new Date(input.nextRunAt)\n values.anchorDay = values.nextRunAt.getUTCDate()\n }\n const row = await this.dependencies.recurrences.update({ companyId: params.companyId, id: params.id, values })\n if (!row) throw new RecurrenceNotFoundError(params.id)\n return this.toRule(row)\n }\n}\n\nexport class RemoveRecurrenceUseCase extends RecurrenceUseCaseBase {\n /** Apaga só a regra: os posts que ela já publicou continuam no ar. */\n async execute(params: { readonly companyId: string; readonly id: string }): Promise<void> {\n if (!(await this.dependencies.recurrences.remove(params))) throw new RecurrenceNotFoundError(params.id)\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Republicar e publicar no horário. `publishDue` é o que o host chama num intervalo: marca como\n * publicado o que estava agendado e já venceu, e materializa as recorrências vencidas.\n */\n\nimport {\n POST_EVENT,\n POST_STATUS,\n PostNotPublishedError,\n republishPostSchema,\n RepublishDateInFutureError,\n SLUG_MAX_LENGTH,\n slugify,\n type Post,\n type RepublishPostInput,\n} from '@adatechnology/content-contracts'\n\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { nextOccurrenceAfter, toDateStamp } from '../shared/recurrence'\nimport { effectiveStatus, toPost } from '../shared/toContract'\nimport type { RecurrenceRow } from '../schema/schema'\nimport { PostUseCaseBase, type PostReference } from './Post.use-cases'\nimport { copiableFields } from './Template.use-cases'\n\nconst DEFAULT_BATCH_LIMIT = 100\nconst DATE_SUFFIX_LENGTH = 11\nconst FALLBACK_SLUG = 'post'\n\nexport class RepublishPostUseCase extends PostUseCaseBase {\n /**\n * Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o\n * link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo\n * duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.\n */\n async execute(params: PostReference & { readonly input?: RepublishPostInput }): Promise<Post> {\n const input = republishPostSchema.parse(params.input ?? {})\n const existing = await this.findOrFail(params)\n const now = this.now()\n if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS.PUBLISHED) {\n throw new PostNotPublishedError(params.id)\n }\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n if (publishedAt > now) throw new RepublishDateInFutureError()\n return this.save(params, { status: POST_STATUS.PUBLISHED, publishedAt }, POST_EVENT.REPUBLISHED)\n }\n}\n\nexport type PublishDueResult = { readonly published: number; readonly materialized: number }\n\nexport class PublishDueUseCase extends PostUseCaseBase {\n /**\n * Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado\n * por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.\n */\n async execute(params: { readonly now?: Date; readonly limit?: number } = {}): Promise<PublishDueResult> {\n const now = params.now ?? this.now()\n const limit = params.limit ?? DEFAULT_BATCH_LIMIT\n const materialized = await this.materializeRecurrences({ now, limit })\n const rows = await this.dependencies.posts.claimDueScheduled({ now, limit })\n for (const row of rows) {\n await notifyPostChanged(this.dependencies, POST_EVENT.PUBLISHED, toPost(row, now))\n }\n if (rows.length > 0 || materialized > 0) {\n this.dependencies.logger?.info('content-module: publishDue', { published: rows.length, materialized })\n }\n return { published: rows.length, materialized }\n }\n\n private materializeRecurrences(params: { now: Date; limit: number }): Promise<number> {\n return this.dependencies.recurrences.processDue({\n ...params,\n handle: (rule) => this.materialize(rule, params.now),\n })\n }\n\n /** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */\n private async materialize(rule: RecurrenceRow, now: Date): Promise<Partial<RecurrenceRow>> {\n const advance = {\n nextRunAt: nextOccurrenceAfter({\n frequency: rule.frequency as 'weekly' | 'monthly',\n from: rule.nextRunAt,\n anchorDay: rule.anchorDay,\n now,\n }),\n }\n const template = await this.dependencies.posts.findById({ companyId: rule.companyId, id: rule.templateId })\n if (!template || !template.isTemplate || template.status === POST_STATUS.ARCHIVED) {\n // Modelo apagado: a regra para de rodar em vez de falhar a cada ciclo.\n this.dependencies.logger?.warn('content-module: modelo da recorrência indisponível', { ruleId: rule.id })\n return { isActive: false }\n }\n const base = (slugify(template.title) || FALLBACK_SLUG).slice(0, SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH)\n const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, '')}-${toDateStamp(now)}`)\n const row = await this.dependencies.posts.create({\n ...copiableFields(template),\n companyId: rule.companyId,\n slug,\n shortId: await this.generateShortId(rule.companyId),\n title: template.title,\n isTemplate: false,\n status: POST_STATUS.PUBLISHED,\n publishedAt: now,\n })\n const post = toPost(row, now)\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n await notifyPostChanged(this.dependencies, POST_EVENT.PUBLISHED, post)\n return { ...advance, lastRunAt: now, lastPostId: row.id }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Datas da recorrência, sempre em UTC: o instante de cada execução não depende do fuso do servidor.\n */\n\nimport { RECURRENCE_FREQUENCY, type RecurrenceFrequency } from '@adatechnology/content-contracts'\n\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000\n\nfunction daysInMonth(year: number, monthIndex: number): number {\n return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate()\n}\n\n/** Mensal no dia 31 cai em 28/29/30 nos meses curtos e VOLTA ao 31 depois (o âncora não deriva). */\nfunction addMonths(from: Date, anchorDay: number, months: number): Date {\n const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1))\n const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()))\n return new Date(\n Date.UTC(\n target.getUTCFullYear(),\n target.getUTCMonth(),\n day,\n from.getUTCHours(),\n from.getUTCMinutes(),\n from.getUTCSeconds(),\n from.getUTCMilliseconds(),\n ),\n )\n}\n\nexport function nextOccurrence(params: { frequency: RecurrenceFrequency; from: Date; anchorDay: number }): Date {\n if (params.frequency === RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS)\n return addMonths(params.from, params.anchorDay, 1)\n}\n\n/**\n * Primeira ocorrência estritamente depois de `now`. Servidor parado três semanas publica UM post ao\n * voltar, não três: as ocorrências perdidas são puladas, nunca emitidas em rajada.\n */\nexport function nextOccurrenceAfter(params: {\n frequency: RecurrenceFrequency\n from: Date\n anchorDay: number\n now: Date\n}): Date {\n let candidate = nextOccurrence(params)\n while (candidate <= params.now) candidate = nextOccurrence({ ...params, from: candidate })\n return candidate\n}\n\nexport function toDateStamp(date: Date): string {\n return date.toISOString().slice(0, 10)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Modelos de post: salvar um post como modelo e criar um post novo a partir de um modelo. Modelo é\n * post com `isTemplate`: nunca vai ao ar, não aparece na lista de posts e não tem endereço público.\n */\n\nimport {\n createFromTemplateSchema,\n DuplicateSlugError,\n normalizeTags,\n NotATemplateError,\n POST_EVENT,\n POST_STATUS,\n saveAsTemplateSchema,\n type CreateFromTemplateInput,\n type Post,\n type PostCounts,\n type SaveAsTemplateInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPost } from '../shared/toContract'\nimport { PostUseCaseBase, type PostReference } from './Post.use-cases'\n\nconst TEMPLATE_SLUG_PREFIX = 'modelo'\n\n/**\n * Conteúdo reaproveitável de um post. `canonicalUrl` NÃO é copiado: o canonical do original apontaria\n * o buscador para outra página e esconderia o post novo.\n */\nexport function copiableFields(row: PostRow): Partial<NewPostRow> {\n return {\n excerpt: row.excerpt,\n body: row.body,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: normalizeTags(row.tags),\n tagLabels: row.tagLabels,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n readingTimeMinutes: row.readingTimeMinutes,\n }\n}\n\nabstract class TemplateUseCaseBase extends PostUseCaseBase {\n protected async insertCopy(params: {\n readonly companyId: string\n readonly slug: string\n readonly title: string\n readonly source: PostRow\n readonly isTemplate: boolean\n readonly status?: string\n readonly publishedAt?: Date\n }): Promise<Post> {\n const row = await this.dependencies.posts\n .create({\n ...copiableFields(params.source),\n companyId: params.companyId,\n slug: params.slug,\n shortId: await this.generateShortId(params.companyId),\n title: params.title,\n isTemplate: params.isTemplate,\n status: params.status ?? POST_STATUS.DRAFT,\n ...(params.publishedAt ? { publishedAt: params.publishedAt } : {}),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(params.slug)\n throw error\n })\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class SaveAsTemplateUseCase extends TemplateUseCaseBase {\n /** Copia o post (qualquer status) para um modelo. O original não muda. */\n async execute(params: PostReference & { readonly input?: SaveAsTemplateInput }): Promise<Post> {\n const input = saveAsTemplateSchema.parse(params.input ?? {})\n const source = await this.findOrFail(params)\n const title = input.title ?? source.title\n const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`)\n return this.insertCopy({ companyId: params.companyId, slug, title, source, isTemplate: true })\n }\n}\n\nexport class CreateFromTemplateUseCase extends TemplateUseCaseBase {\n /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */\n async execute(params: PostReference & { readonly input?: CreateFromTemplateInput }): Promise<Post> {\n const input = createFromTemplateSchema.parse(params.input ?? {})\n const template = await this.findOrFail(params)\n if (!template.isTemplate) throw new NotATemplateError(params.id)\n const title = input.title ?? template.title\n if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(params.companyId, title))\n return this.insertCopy({ companyId: params.companyId, slug, title, source: template, isTemplate: false })\n }\n}\n\nexport class CountPostsUseCase extends PostUseCaseBase {\n /** Números das abas do painel, numa consulta só. */\n async execute(params: { readonly companyId: string }): Promise<PostCounts> {\n return this.dependencies.posts.countByStatus({ companyId: params.companyId, now: this.now() })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Upload da capa. O bucket é do host (`ContentImageStoragePort`); aqui ficam as decisões que não\n * variam por instalação: formatos aceitos, teto de tamanho e forma da chave.\n */\n\nimport { ImageStorageDisabledError, InvalidCoverImageError } from '@adatechnology/content-contracts'\n\nimport { COVER_IMAGE } from '../shared/coverImage.constant'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport type UploadCoverImageParams = {\n readonly companyId: string\n readonly bytes: Uint8Array\n readonly mimeType: string\n}\n\nexport type UploadCoverImageResult = { readonly url: string; readonly key: string }\n\nexport class UploadCoverImageUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(params: UploadCoverImageParams): Promise<UploadCoverImageResult> {\n const storage = this.dependencies.imageStorage\n if (!storage) throw new ImageStorageDisabledError()\n\n const mimeType = (params.mimeType.split(';')[0] ?? '').trim().toLowerCase()\n // Lista fechada, não \"começa com image/\": SVG é imagem e carrega script.\n const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType]\n if (!extension) throw new InvalidCoverImageError('unsupported_type')\n if (params.bytes.byteLength === 0) throw new InvalidCoverImageError('empty')\n if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new InvalidCoverImageError('too_large')\n\n // A chave nunca carrega nome de arquivo: é entrada de usuário e vai parar numa URL pública.\n const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`\n return storage.upload({ buffer: params.bytes, mimeType, key })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * 1 MiB é o teto de corpo do `module-http`: um limite maior aqui seria promessa que a rota não\n * cumpre. O `content-ui` avisa antes de enviar; o servidor recusa de novo porque o cliente não é\n * fonte de verdade.\n */\nexport const COVER_IMAGE = {\n MAX_BYTES: 1024 * 1024,\n KEY_PREFIX: 'content/posts',\n EXTENSION_BY_MIME: {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n } as Readonly<Record<string, string | undefined>>,\n} as const\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n createFromTemplateSchema,\n createPostSchema,\n createRecurrenceSchema,\n DEFAULT_ADMIN_SCOPES,\n listPostsQuerySchema,\n publishPostSchema,\n republishPostSchema,\n saveAsTemplateSchema,\n updatePostSchema,\n updateRecurrenceSchema,\n type CreateFromTemplateInput,\n type CreatePostInput,\n type CreateRecurrenceInput,\n type ListPostsQuery,\n type PublishPostInput,\n type RepublishPostInput,\n type SaveAsTemplateInput,\n type UpdatePostInput,\n type UpdateRecurrenceInput,\n} from '@adatechnology/content-contracts'\nimport type { ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\nimport { requireCompany } from './requireCompany'\n\nfunction reference(context: RequestContext): { companyId: string; id: string } {\n return { companyId: requireCompany(context), id: context.params.id ?? '' }\n}\n\nconst json = (status: number, data: unknown) => ({ kind: 'json' as const, status, body: { data } })\n\nexport function buildAdminRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES\n const admin = { scope: 'admin' as const, requiredScopes }\n\n const uploadRoutes: ModuleRoute[] = useCases.uploadCoverImage\n ? [\n {\n ...admin,\n method: 'POST',\n path: '/posts/cover-images',\n operationId: 'uploadPostCoverImage',\n summary: 'Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL',\n async handler(context) {\n const upload = useCases.uploadCoverImage\n if (!upload) return { kind: 'empty', status: 404 }\n const result = await upload.execute({\n companyId: requireCompany(context),\n bytes: context.rawBody ?? new Uint8Array(),\n mimeType: context.headers['content-type'] ?? '',\n })\n return json(201, result)\n },\n },\n ]\n : []\n\n return [\n {\n ...admin,\n method: 'GET',\n path: '/posts',\n querySchema: listPostsQuerySchema,\n operationId: 'listPosts',\n summary: 'Lista posts da empresa (todos os status), com filtro por status, tag e busca',\n async handler(context) {\n const result = await useCases.listPosts.execute({\n companyId: requireCompany(context),\n ...(context.query as unknown as ListPostsQuery),\n })\n return { kind: 'json', status: 200, body: result }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts',\n bodySchema: createPostSchema,\n operationId: 'createPost',\n summary: 'Cria um post como rascunho; sem slug, gera a partir do título',\n async handler(context) {\n const post = await useCases.createPost.execute({\n companyId: requireCompany(context),\n input: context.body as CreatePostInput,\n })\n return json(201, post)\n },\n },\n // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria \"tags\".\n {\n ...admin,\n method: 'GET',\n path: '/posts/tags',\n operationId: 'listPostTags',\n summary: 'Tags usadas em qualquer post da empresa, com contagem',\n async handler(context) {\n return json(\n 200,\n await useCases.listTags.execute({ companyId: requireCompany(context), scope: TAG_SCOPE.ADMIN }),\n )\n },\n },\n {\n ...admin,\n method: 'GET',\n path: '/posts/counts',\n operationId: 'countPosts',\n summary: 'Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos',\n async handler(context) {\n return json(200, await useCases.countPosts.execute({ companyId: requireCompany(context) }))\n },\n },\n ...recurrenceRoutes(module),\n ...uploadRoutes,\n {\n ...admin,\n method: 'GET',\n path: '/posts/:id',\n operationId: 'getPost',\n summary: 'Lê um post da empresa (qualquer status)',\n async handler(context) {\n return json(200, await useCases.getPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/posts/:id',\n bodySchema: updatePostSchema,\n operationId: 'updatePost',\n summary: 'Atualiza campos de um post; trocar o título não troca o slug',\n async handler(context) {\n return json(\n 200,\n await useCases.updatePost.execute({ ...reference(context), input: context.body as UpdatePostInput }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/posts/:id',\n operationId: 'archivePost',\n summary: 'Arquiva o post: sai do site, conteúdo e slug continuam guardados',\n async handler(context) {\n await useCases.archivePost.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/publish',\n // Opcional: `POST /publish` sem corpo publica agora.\n bodySchema: publishPostSchema.optional(),\n operationId: 'publishPost',\n summary: 'Publica agora, ou agenda quando `publishedAt` é futuro',\n async handler(context) {\n return json(\n 200,\n await useCases.publishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as PublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/unpublish',\n operationId: 'unpublishPost',\n summary: 'Tira do ar (ou cancela o agendamento) e volta a rascunho',\n async handler(context) {\n return json(200, await useCases.unpublishPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/republish',\n bodySchema: republishPostSchema.optional(),\n operationId: 'republishPost',\n summary: 'Republica um post no ar com nova data, mantendo o mesmo endereço (SEO); data futura é recusada',\n async handler(context) {\n return json(\n 200,\n await useCases.republishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as RepublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/save-as-template',\n bodySchema: saveAsTemplateSchema.optional(),\n operationId: 'savePostAsTemplate',\n summary: 'Copia o post para um modelo (o original não muda)',\n async handler(context) {\n return json(\n 201,\n await useCases.saveAsTemplate.execute({\n ...reference(context),\n input: (context.body ?? {}) as SaveAsTemplateInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/from-template',\n bodySchema: createFromTemplateSchema.optional(),\n operationId: 'createPostFromTemplate',\n summary: 'Cria um rascunho novo a partir do modelo `:id`',\n async handler(context) {\n return json(\n 201,\n await useCases.createFromTemplate.execute({\n ...reference(context),\n input: (context.body ?? {}) as CreateFromTemplateInput,\n }),\n )\n },\n },\n ]\n}\n\nfunction recurrenceRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const admin = { scope: 'admin' as const, requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES }\n return [\n {\n ...admin,\n method: 'GET',\n path: '/recurrences',\n operationId: 'listRecurrences',\n summary: 'Regras de recorrência da empresa',\n async handler(context) {\n return json(200, await useCases.listRecurrences.execute({ companyId: requireCompany(context) }))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/recurrences',\n bodySchema: createRecurrenceSchema,\n operationId: 'createRecurrence',\n summary: 'Cria regra: publica um post novo, copiado do modelo, toda semana ou todo mês',\n async handler(context) {\n return json(\n 201,\n await useCases.createRecurrence.execute({\n companyId: requireCompany(context),\n input: context.body as CreateRecurrenceInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/recurrences/:id',\n bodySchema: updateRecurrenceSchema,\n operationId: 'updateRecurrence',\n summary: 'Pausa, retoma ou remarca a próxima execução',\n async handler(context) {\n return json(\n 200,\n await useCases.updateRecurrence.execute({\n ...reference(context),\n input: context.body as UpdateRecurrenceInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/recurrences/:id',\n operationId: 'removeRecurrence',\n summary: 'Apaga a regra; os posts já publicados por ela continuam no ar',\n async handler(context) {\n await useCases.removeRecurrence.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { CONTENT_ERROR_CODES, ContentError } from '@adatechnology/content-contracts'\nimport type { RequestContext } from '@adatechnology/module-http'\n\n/** `dispatchRoute` já recusa rota de admin sem identidade; isto só garante o tipo para o handler. */\nexport function requireCompany(context: RequestContext): string {\n if (!context.auth?.companyId) {\n throw new ContentError('Rota exige contexto autenticado.', 401, CONTENT_ERROR_CODES.CONFIG_MISSING)\n }\n return context.auth.companyId\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas do site público. Sem identidade: a empresa vem do `PublicCompanyResolverPort` do host\n * (domínio, cabeçalho, empresa fixa…). Resolver sem resposta = 404, igual a post inexistente.\n */\n\nimport {\n DEFAULT_PUBLIC_CACHE_CONTROL,\n listPublishedPostsQuerySchema,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n} from '@adatechnology/content-contracts'\nimport type { HttpResult, ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { FEED_FORMAT } from '../use-cases/Feed.use-cases'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\n\nexport interface PublicCompanyResolverPort {\n resolve(params: {\n readonly headers: Readonly<Record<string, string>>\n readonly query: Readonly<Record<string, string>>\n }): Promise<string | undefined>\n}\n\nconst PUBLIC = { scope: 'public' as const }\n\nexport function buildPublicRoutes(params: {\n module: ContentModule\n companyResolver: PublicCompanyResolverPort\n}): ModuleRoute[] {\n const { useCases } = params.module\n const cacheControl = params.module.config.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL\n const cached = (data: unknown): HttpResult => ({\n kind: 'json',\n status: 200,\n body: data,\n headers: { 'Cache-Control': cacheControl },\n })\n\n async function resolveCompany(context: RequestContext): Promise<string> {\n const companyId = await params.companyResolver.resolve({ headers: context.headers, query: context.query })\n if (!companyId) throw new PostNotFoundError('company')\n return companyId\n }\n\n const routes: ModuleRoute[] = [\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts',\n querySchema: listPublishedPostsQuerySchema,\n operationId: 'listPublishedPosts',\n summary: 'Posts publicados, mais recentes primeiro, com filtro por tag',\n async handler(context) {\n const result = await useCases.listPublishedPosts.execute({\n companyId: await resolveCompany(context),\n ...(context.query as unknown as ListPublishedPostsQuery),\n })\n return cached(result)\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts/:slug',\n operationId: 'getPublishedPost',\n summary: 'Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404',\n async handler(context) {\n const post = await useCases.getPublishedPostBySlug.execute({\n companyId: await resolveCompany(context),\n slug: context.params.slug ?? '',\n })\n return cached({ data: post })\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/tags',\n operationId: 'listPublishedTags',\n summary: 'Tags dos posts publicados, com contagem',\n async handler(context) {\n const tags = await useCases.listTags.execute({\n companyId: await resolveCompany(context),\n scope: TAG_SCOPE.PUBLIC,\n })\n return cached({ data: tags })\n },\n },\n ]\n\n const { buildFeed, listSitemapEntries } = useCases\n if (!buildFeed || !listSitemapEntries) return routes\n\n const feedRoute = (path: string, format: 'rss' | 'atom', contentType: string, operationId: string): ModuleRoute => ({\n ...PUBLIC,\n method: 'GET',\n path,\n operationId,\n summary: `Feed ${format.toUpperCase()} dos posts publicados`,\n async handler(context) {\n const body = await buildFeed.execute({ companyId: await resolveCompany(context), format })\n return {\n kind: 'text',\n status: 200,\n body,\n headers: { 'Content-Type': contentType, 'Cache-Control': cacheControl },\n }\n },\n })\n\n return [\n ...routes,\n feedRoute('/public/feed.xml', FEED_FORMAT.RSS, 'application/rss+xml; charset=utf-8', 'getRssFeed'),\n feedRoute('/public/atom.xml', FEED_FORMAT.ATOM, 'application/atom+xml; charset=utf-8', 'getAtomFeed'),\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/sitemap-entries',\n operationId: 'listSitemapEntries',\n summary: 'Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele',\n async handler(context) {\n return cached({ data: await listSitemapEntries.execute({ companyId: await resolveCompany(context) }) })\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { ModuleRouteTable } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { buildAdminRoutes } from './adminRoutes'\nimport { buildPublicRoutes, type PublicCompanyResolverPort } from './publicRoutes'\n\nexport type CreateContentRoutesParams = {\n readonly module: ContentModule\n /**\n * Como o site público diz de qual empresa é o blog (domínio, cabeçalho, valor fixo…). Ausente,\n * as rotas `/public/*` não sobem: o host que só tem painel não expõe leitura anônima.\n */\n readonly publicCompanyResolver?: PublicCompanyResolverPort\n}\n\nexport function createContentRoutes(params: CreateContentRoutesParams): ModuleRouteTable {\n const admin = buildAdminRoutes(params.module)\n if (!params.publicCompanyResolver) return admin\n return [...admin, ...buildPublicRoutes({ module: params.module, companyResolver: params.publicCompanyResolver })]\n}\n\nexport type { PublicCompanyResolverPort }\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { join } from 'node:path'\n\nimport type { ContentDatabase, DrizzleMigrateFunction } from './database.types'\n\n// Journal próprio, fora do pgSchema `content`: a primeira migration é quem cria esse schema\n// (mesmo raciocínio de `catalog-module/runMigrations.ts`).\nexport const CONTENT_MIGRATIONS_TABLE = 'content_migrations'\n\n/** Pasta no formato clássico (`meta/_journal.json`), lida pelos migrators do drizzle 0.x e 1.x. */\nexport function contentMigrationsFolder(): string {\n return join(__dirname, 'migrations')\n}\n\nexport type RunContentMigrationsParams = {\n readonly db: ContentDatabase\n /** O `migrate` do driver do host (`drizzle-orm/node-postgres/migrator`, `.../bun-sql/migrator`…). */\n readonly migrate: DrizzleMigrateFunction\n}\n\nexport async function runContentMigrations(params: RunContentMigrationsParams): Promise<void> {\n await params.migrate(params.db as never, {\n migrationsFolder: contentMigrationsFolder(),\n migrationsTable: CONTENT_MIGRATIONS_TABLE,\n })\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `PostStorePort`, para a suíte de comportamento do módulo e para o teste do\n * host. O isolamento real (cláusula SQL) é provado em `repositories/isolation.test.ts`; aqui as\n * mesmas regras são reproduzidas em JavaScript, inclusive a violação de índice único do slug.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { POST_STATUS, type TagCount } from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { effectiveStatus } from '../shared/toContract'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\n\nfunction isPublic(row: PostRow, now: Date): boolean {\n const live = row.status === POST_STATUS.PUBLISHED || row.status === POST_STATUS.SCHEDULED\n return live && row.publishedAt !== null && row.publishedAt <= now\n}\n\nfunction adminComparator(query: PostAdminListQuery) {\n const sign = query.order === 'asc' ? 1 : -1\n const value = (row: PostRow): number | string => {\n if (query.sort === 'title') return row.title.toLowerCase()\n if (query.sort === 'status') return row.status\n if (query.sort === 'publishedAt') return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY\n return row.updatedAt.getTime()\n }\n return (left: PostRow, right: PostRow): number => {\n const a = value(left)\n const b = value(right)\n return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id)\n }\n}\n\nfunction paginate(rows: PostRow[], page: number, pageSize: number): PostPage {\n return { rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({ ...row })), total: rows.length }\n}\n\nclass UniqueViolation extends Error {\n readonly code = '23505'\n}\n\nexport function createInMemoryPostStore(seed: PostRow[] = []): PostStorePort & { readonly rows: PostRow[] } {\n const rows: PostRow[] = [...seed]\n const formerSlugs: { companyId: string; slug: string; postId: string }[] = []\n\n const assertUniqueSlug = (companyId: string, slug: string, ownId?: string): void => {\n if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {\n throw new UniqueViolation('duplicate key value violates unique constraint \"idx_posts_company_slug\"')\n }\n }\n\n return {\n rows,\n\n async findByShortId({ companyId, shortId }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId)\n return row ? { ...row } : undefined\n },\n\n async findPublicByShortId({ companyId, shortId, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async findPublicByFormerSlug({ companyId, slug, now }) {\n const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug)\n const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now))\n return row ? { ...row } : undefined\n },\n\n async recordFormerSlug(params) {\n if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {\n formerSlugs.push({ ...params })\n }\n },\n\n async create(values: NewPostRow): Promise<PostRow> {\n assertUniqueSlug(values.companyId, values.slug)\n const now = new Date()\n const row: PostRow = {\n id: randomUUID(),\n excerpt: null,\n body: '',\n coverImageUrl: null,\n coverImageAlt: null,\n tags: [],\n tagLabels: {},\n status: POST_STATUS.DRAFT,\n isTemplate: false,\n publishedAt: null,\n authorName: null,\n seoTitle: null,\n seoDescription: null,\n canonicalUrl: null,\n readingTimeMinutes: 1,\n createdAt: now,\n updatedAt: now,\n ...values,\n } as PostRow\n rows.push(row)\n return { ...row }\n },\n\n async findById({ companyId, id }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n return row ? { ...row } : undefined\n },\n\n async findBySlug({ companyId, slug }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug)\n return row ? { ...row } : undefined\n },\n\n async findPublicBySlug({ companyId, slug, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async update({ companyId, id, values }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n if (!row) return undefined\n if (values.slug !== undefined) assertUniqueSlug(companyId, values.slug, id)\n Object.assign(row, values, { updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1)) })\n return { ...row }\n },\n\n async listForAdmin(query: PostAdminListQuery) {\n const search = query.search?.toLowerCase()\n const matched = rows\n .filter((row) => row.companyId === query.companyId)\n .filter((row) => (query.isTemplate ? row.isTemplate && row.status !== POST_STATUS.ARCHIVED : !row.isTemplate))\n .filter((row) => !query.status || effectiveStatus(row, query.now) === query.status)\n .filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag)))\n .filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search))\n .sort(adminComparator(query))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async countByStatus({ companyId, now }) {\n const counts = { published: 0, scheduled: 0, draft: 0, archived: 0, templates: 0 }\n for (const row of rows) {\n if (row.companyId !== companyId) continue\n if (row.isTemplate) {\n if (row.status !== POST_STATUS.ARCHIVED) counts.templates += 1\n continue\n }\n counts[effectiveStatus(row, now) as keyof typeof counts] += 1\n }\n return counts\n },\n\n async claimDueScheduled({ now, limit }) {\n const due = rows\n .filter(\n (row) => row.status === POST_STATUS.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now,\n )\n .sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0))\n .slice(0, limit)\n for (const row of due) row.status = POST_STATUS.PUBLISHED\n return due.map((row) => ({ ...row }))\n },\n\n async listPublic(query: PostPublicListQuery) {\n const matched = rows\n .filter((row) => row.companyId === query.companyId && isPublic(row, query.now))\n .filter((row) => !query.tag || row.tags.includes(query.tag))\n .sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async listTags({ companyId, publicAt }): Promise<readonly TagCount[]> {\n const counts = new Map<string, number>()\n for (const row of rows) {\n if (row.companyId !== companyId || (publicAt && !isPublic(row, publicAt))) continue\n for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1)\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag))\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { LoggerPort } from '@adatechnology/content-contracts'\n\nimport type { ContentModule } from './ContentModule'\n\nexport const DEFAULT_SCHEDULER_INTERVAL_MS = 60_000\n\nexport type StartContentSchedulerParams = {\n readonly module: ContentModule\n /** Padrão: 1 minuto. */\n readonly intervalMs?: number\n readonly logger?: LoggerPort\n}\n\n/**\n * Chama `publishDue` num intervalo, com guarda de execução única neste processo: se um ciclo ainda\n * está rodando, o próximo tick é pulado em vez de empilhar. Entre instâncias, quem garante é o\n * `FOR UPDATE SKIP LOCKED` do store. Erro de um ciclo é logado e o seguinte tenta de novo.\n * Devolve a função que para o agendador (chame no desligamento).\n */\nexport function startContentScheduler(params: StartContentSchedulerParams): () => void {\n let isRunning = false\n const tick = async (): Promise<void> => {\n if (isRunning) return\n isRunning = true\n try {\n await params.module.useCases.publishDue.execute()\n } catch (error) {\n params.logger?.error('content-module: ciclo do agendador falhou', {\n error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n isRunning = false\n }\n }\n const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS)\n timer.unref?.()\n void tick()\n return () => clearInterval(timer)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `RecurrenceStorePort`: mesmas regras, sem transação (o teste é de um processo só).\n */\n\nimport { randomUUID } from 'node:crypto'\n\nimport type { NewRecurrenceRow, RecurrenceRow } from '../schema/schema'\nimport type { RecurrenceStorePort } from '../use-cases/contentModule.types'\n\nexport function createInMemoryRecurrenceStore(): RecurrenceStorePort & { readonly rows: RecurrenceRow[] } {\n const rows: RecurrenceRow[] = []\n const owned = (companyId: string, id: string) => rows.find((row) => row.companyId === companyId && row.id === id)\n\n return {\n rows,\n async create(values: NewRecurrenceRow) {\n const row = {\n id: randomUUID(),\n isActive: true,\n lastRunAt: null,\n lastPostId: null,\n createdAt: new Date(),\n ...values,\n } as RecurrenceRow\n rows.push(row)\n return { ...row }\n },\n async findById({ companyId, id }) {\n const row = owned(companyId, id)\n return row ? { ...row } : undefined\n },\n async list({ companyId }) {\n return rows\n .filter((row) => row.companyId === companyId)\n .sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime())\n .map((row) => ({ ...row }))\n },\n async update({ companyId, id, values }) {\n const row = owned(companyId, id)\n if (!row) return undefined\n Object.assign(row, values)\n return { ...row }\n },\n async remove({ companyId, id }) {\n const index = rows.findIndex((row) => row.companyId === companyId && row.id === id)\n if (index < 0) return false\n rows.splice(index, 1)\n return true\n },\n async processDue({ now, limit, handle }) {\n const due = rows\n .filter((row) => row.isActive && row.nextRunAt <= now)\n .sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime())\n .slice(0, limit)\n for (const row of due) Object.assign(row, await handle({ ...row }))\n return due.length\n },\n }\n}\n"],"mappings":";;;;AACA,OAAOA,UAAU;AACjB,SAASC,qBAAqB;AAE9B,IAAMC,cAAc,6BAAMC,cAAc,YAAYC,GAAG,GAAnC;AACpB,IAAMC,aAAa,6BAAMC,KAAKC,QAAQL,YAAAA,CAAAA,GAAnB;A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","getFilename","fileURLToPath","url","getDirname","path","dirname","__dirname","ConfigMissingError","and","asc","desc","eq","inArray","sql","POST_STATUS","sql","boolean","index","integer","jsonb","primaryKey","pgSchema","text","timestamp","uniqueIndex","uuid","varchar","contentSchema","posts","table","id","defaultRandom","companyId","notNull","slug","length","shortId","title","excerpt","body","default","coverImageUrl","coverImageAlt","tags","array","tagLabels","$type","status","isTemplate","publishedAt","withTimezone","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","defaultNow","updatedAt","on","using","where","recurrenceRules","templateId","references","frequency","anchorDay","isActive","nextRunAt","lastRunAt","lastPostId","postFormerSlugs","postId","columns","and","arrayContains","arrayOverlaps","eq","gt","inArray","lte","ne","or","sql","POST_STATUS","postOwnedByCondition","params","and","eq","posts","companyId","id","postSlugCondition","slug","postAdminListCondition","conditions","templateCondition","isTemplate","status","push","statusCondition","now","tags","length","arrayOverlaps","search","pattern","replace","character","sql","title","ne","POST_STATUS","ARCHIVED","PUBLISHED","or","SCHEDULED","lte","publishedAt","gt","postPublicCondition","inArray","tag","arrayContains","postPublicSlugCondition","postDueCondition","postShortIdCondition","shortId","postPublicShortIdCondition","TAG_LIST_LIMIT","SORT_COLUMNS","title","posts","status","publishedAt","updatedAt","adminOrder","query","column","sort","direction","order","asc","desc","primary","sql","raw","id","PostRepository","db","create","values","row","insert","returning","Error","findById","params","select","from","where","postOwnedByCondition","limit","findBySlug","postSlugCondition","findPublicBySlug","postPublicSlugCondition","findByShortId","postShortIdCondition","findPublicByShortId","postPublicShortIdCondition","findPublicByFormerSlug","former","postId","postFormerSlugs","and","eq","companyId","slug","undefined","postPublicCondition","recordFormerSlug","onConflictDoNothing","update","set","Date","listForAdmin","postAdminListCondition","rows","counted","Promise","all","orderBy","pageSize","offset","page","value","total","listPublic","countByStatus","now","toISOString","condition","livePublished","POST_STATUS","PUBLISHED","SCHEDULED","published","isTemplate","scheduled","draft","DRAFT","archived","ARCHIVED","templates","claimDueScheduled","due","postDueCondition","for","skipLocked","inArray","listTags","publicAt","postTags","tag","tags","as","count","groupBy","and","asc","eq","lte","recurrenceOwnedByCondition","params","and","eq","recurrenceRules","companyId","id","RecurrenceRepository","db","create","values","row","insert","returning","Error","findById","select","from","where","limit","list","orderBy","asc","nextRunAt","update","set","remove","removed","delete","length","processDue","transaction","due","isActive","lte","now","for","skipLocked","processed","rule","handle","buildAtomFeed","buildExcerpt","buildPostUrl","buildRssFeed","renderMarkdownToHtml","DEFAULT_ITEM_LIMIT","SITEMAP_LIMIT","FEED_FORMAT","RSS","ATOM","BuildFeedUseCase","dependencies","feed","execute","params","now","clock","page","posts","listPublic","companyId","pageSize","itemLimit","channel","siteUrl","title","description","language","feedUrl","items","rows","map","row","toItem","format","buildAtomFeed","buildRssFeed","url","buildPostUrl","slug","shortId","postPathTemplate","publishedAt","createdAt","toISOString","updatedAt","summary","excerpt","buildExcerpt","body","includeContent","contentHtml","renderMarkdownToHtml","headingIds","authorName","categories","tags","coverImageUrl","imageUrl","ListSitemapEntriesUseCase","loc","lastmod","buildTagLabels","createPostSchema","DuplicateSlugError","estimateReadingTimeMinutes","listPostsQuerySchema","normalizeTags","POST_EVENT","POST_STATUS","PostNotFoundError","TemplateNotPublishableError","publishPostSchema","buildShortSlug","updatePostSchema","withSlugSuffix","randomInt","SHORT_ID_LENGTH","ALPHABET","generateShortId","value","index","SHORT_ID_LENGTH","randomInt","length","UNIQUE_VIOLATION","isUniqueViolation","error","current","depth","code","cause","notifyPostChanged","dependencies","type","post","hook","hooks","onPostChanged","error","logger","postId","id","Error","message","String","POST_STATUS","effectiveStatus","row","now","status","POST_STATUS","SCHEDULED","publishedAt","PUBLISHED","toPostSummary","id","companyId","slug","shortId","title","excerpt","coverImageUrl","coverImageAlt","tags","tagLabels","isTemplate","toISOString","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","updatedAt","toPost","body","toPublicPostSummary","toPublicPost","toPagination","params","totalPages","Math","max","ceil","total","pageSize","MAX_SLUG_ATTEMPTS","FALLBACK_SLUG","PostUseCaseBase","dependencies","now","clock","findOrFail","reference","row","posts","findById","PostNotFoundError","id","save","values","event","update","catch","error","isUniqueViolation","slug","DuplicateSlugError","post","toPost","notifyPostChanged","generateShortId","companyId","attempt","candidate","findByShortId","shortId","Error","readingTime","body","estimateReadingTimeMinutes","config","wordsPerMinute","assertSlugAvailable","ownId","existing","findBySlug","generateSlug","title","uniqueSlug","buildShortSlug","base","withSlugSuffix","Date","optionalFields","input","excerpt","undefined","coverImageUrl","coverImageAlt","authorName","seoTitle","seoDescription","canonicalUrl","CreatePostUseCase","execute","params","createPostSchema","parse","create","tags","normalizeTags","tagLabels","buildTagLabels","typed","explicit","status","POST_STATUS","DRAFT","readingTimeMinutes","POST_EVENT","CREATED","UpdatePostUseCase","updatePostSchema","previous","recordFormerSlug","postId","UPDATED","PublishPostUseCase","publishPostSchema","isTemplate","TemplateNotPublishableError","publishedAt","SCHEDULED","PUBLISHED","UnpublishPostUseCase","UNPUBLISHED","ArchivePostUseCase","ARCHIVED","GetPostUseCase","ListPostsUseCase","rawQuery","query","listPostsQuerySchema","tag","rawTag","rest","split","page","listForAdmin","length","data","rows","map","toPostSummary","pagination","toPagination","total","pageSize","listPublishedPostsQuerySchema","normalizeTag","parsePostRef","PostNotFoundError","GetPublishedPostBySlugUseCase","dependencies","execute","params","posts","clock","parsed","parsePostRef","slug","query","companyId","now","row","shortId","findPublicByShortId","undefined","findPublicBySlug","findPublicByFormerSlug","PostNotFoundError","toPublicPost","ListPublishedPostsUseCase","rawQuery","listPublishedPostsQuerySchema","parse","tag","normalizeTag","page","listPublic","pageSize","data","rows","map","toPublicPostSummary","pagination","toPagination","total","TAG_SCOPE","PUBLIC","ADMIN","ListTagsUseCase","listTags","scope","publicAt","createRecurrenceSchema","NotATemplateError","PostNotFoundError","RecurrenceNotFoundError","updateRecurrenceSchema","RecurrenceUseCaseBase","dependencies","toRule","row","template","posts","findById","companyId","id","templateId","templateTitle","title","frequency","isActive","nextRunAt","toISOString","lastRunAt","lastPostId","createdAt","findOrFail","params","recurrences","RecurrenceNotFoundError","CreateRecurrenceUseCase","execute","input","createRecurrenceSchema","parse","PostNotFoundError","isTemplate","NotATemplateError","startsAt","Date","values","anchorDay","getUTCDate","create","ListRecurrencesUseCase","rows","list","Promise","all","map","UpdateRecurrenceUseCase","updateRecurrenceSchema","undefined","update","RemoveRecurrenceUseCase","remove","POST_EVENT","POST_STATUS","PostNotPublishedError","republishPostSchema","RepublishDateInFutureError","SLUG_MAX_LENGTH","slugify","RECURRENCE_FREQUENCY","WEEK_MS","daysInMonth","year","monthIndex","Date","UTC","getUTCDate","addMonths","from","anchorDay","months","target","getUTCFullYear","getUTCMonth","day","Math","min","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","nextOccurrence","params","frequency","RECURRENCE_FREQUENCY","WEEKLY","getTime","nextOccurrenceAfter","candidate","now","toDateStamp","date","toISOString","slice","createFromTemplateSchema","DuplicateSlugError","normalizeTags","NotATemplateError","POST_EVENT","POST_STATUS","saveAsTemplateSchema","TEMPLATE_SLUG_PREFIX","copiableFields","row","excerpt","body","coverImageUrl","coverImageAlt","tags","normalizeTags","tagLabels","authorName","seoTitle","seoDescription","readingTimeMinutes","TemplateUseCaseBase","PostUseCaseBase","insertCopy","params","dependencies","posts","create","source","companyId","slug","shortId","generateShortId","title","isTemplate","status","POST_STATUS","DRAFT","publishedAt","catch","error","isUniqueViolation","DuplicateSlugError","post","toPost","now","notifyPostChanged","POST_EVENT","CREATED","SaveAsTemplateUseCase","execute","input","saveAsTemplateSchema","parse","findOrFail","generateSlug","CreateFromTemplateUseCase","createFromTemplateSchema","template","NotATemplateError","id","assertSlugAvailable","CountPostsUseCase","countByStatus","DEFAULT_BATCH_LIMIT","DATE_SUFFIX_LENGTH","FALLBACK_SLUG","RepublishPostUseCase","PostUseCaseBase","execute","params","input","republishPostSchema","parse","existing","findOrFail","now","isTemplate","effectiveStatus","POST_STATUS","PUBLISHED","PostNotPublishedError","id","publishedAt","Date","RepublishDateInFutureError","save","status","POST_EVENT","REPUBLISHED","PublishDueUseCase","limit","materialized","materializeRecurrences","rows","dependencies","posts","claimDueScheduled","row","notifyPostChanged","toPost","length","logger","info","published","recurrences","processDue","handle","rule","materialize","advance","nextRunAt","nextOccurrenceAfter","frequency","from","anchorDay","template","findById","companyId","templateId","ARCHIVED","warn","ruleId","isActive","base","slugify","title","slice","SLUG_MAX_LENGTH","slug","uniqueSlug","replace","toDateStamp","create","copiableFields","shortId","generateShortId","post","CREATED","lastRunAt","lastPostId","ImageStorageDisabledError","InvalidCoverImageError","COVER_IMAGE","MAX_BYTES","KEY_PREFIX","EXTENSION_BY_MIME","UploadCoverImageUseCase","dependencies","execute","params","storage","imageStorage","ImageStorageDisabledError","mimeType","split","trim","toLowerCase","extension","COVER_IMAGE","EXTENSION_BY_MIME","InvalidCoverImageError","bytes","byteLength","MAX_BYTES","key","KEY_PREFIX","companyId","crypto","randomUUID","upload","buffer","SYSTEM_CLOCK","now","Date","assertValidConfig","config","feed","test","siteUrl","ConfigMissingError","title","trim","postPathTemplate","includes","wordsPerMinute","undefined","createContentModule","params","posts","providers","postStore","db","PostRepository","recurrences","recurrenceStore","RecurrenceRepository","dependencies","clock","hooks","imageStorage","logger","useCases","createPost","CreatePostUseCase","updatePost","UpdatePostUseCase","archivePost","ArchivePostUseCase","publishPost","PublishPostUseCase","unpublishPost","UnpublishPostUseCase","getPost","GetPostUseCase","listPosts","ListPostsUseCase","getPublishedPostBySlug","GetPublishedPostBySlugUseCase","listPublishedPosts","ListPublishedPostsUseCase","listTags","ListTagsUseCase","countPosts","CountPostsUseCase","saveAsTemplate","SaveAsTemplateUseCase","createFromTemplate","CreateFromTemplateUseCase","republishPost","RepublishPostUseCase","createRecurrence","CreateRecurrenceUseCase","listRecurrences","ListRecurrencesUseCase","updateRecurrence","UpdateRecurrenceUseCase","removeRecurrence","RemoveRecurrenceUseCase","publishDue","PublishDueUseCase","uploadCoverImage","UploadCoverImageUseCase","buildFeed","BuildFeedUseCase","listSitemapEntries","ListSitemapEntriesUseCase","createFromTemplateSchema","createPostSchema","createRecurrenceSchema","DEFAULT_ADMIN_SCOPES","listPostsQuerySchema","publishPostSchema","republishPostSchema","saveAsTemplateSchema","updatePostSchema","updateRecurrenceSchema","CONTENT_ERROR_CODES","ContentError","requireCompany","context","auth","companyId","ContentError","CONTENT_ERROR_CODES","CONFIG_MISSING","reference","context","companyId","requireCompany","id","params","json","status","data","kind","body","buildAdminRoutes","module","useCases","requiredScopes","config","adminScopes","DEFAULT_ADMIN_SCOPES","admin","scope","uploadRoutes","uploadCoverImage","method","path","operationId","summary","handler","upload","result","execute","bytes","rawBody","Uint8Array","mimeType","headers","querySchema","listPostsQuerySchema","listPosts","query","bodySchema","createPostSchema","post","createPost","input","listTags","TAG_SCOPE","ADMIN","countPosts","recurrenceRoutes","getPost","updatePostSchema","updatePost","archivePost","publishPostSchema","optional","publishPost","unpublishPost","republishPostSchema","republishPost","saveAsTemplateSchema","saveAsTemplate","createFromTemplateSchema","createFromTemplate","listRecurrences","createRecurrenceSchema","createRecurrence","updateRecurrenceSchema","updateRecurrence","removeRecurrence","DEFAULT_PUBLIC_CACHE_CONTROL","listPublishedPostsQuerySchema","PostNotFoundError","PUBLIC","scope","buildPublicRoutes","params","useCases","module","cacheControl","config","publicCacheControl","DEFAULT_PUBLIC_CACHE_CONTROL","cached","data","kind","status","body","headers","resolveCompany","context","companyId","companyResolver","resolve","query","PostNotFoundError","routes","method","path","querySchema","listPublishedPostsQuerySchema","operationId","summary","handler","result","listPublishedPosts","execute","post","getPublishedPostBySlug","slug","tags","listTags","TAG_SCOPE","buildFeed","listSitemapEntries","feedRoute","format","contentType","toUpperCase","FEED_FORMAT","RSS","ATOM","createContentRoutes","params","admin","buildAdminRoutes","module","publicCompanyResolver","buildPublicRoutes","companyResolver","join","CONTENT_MIGRATIONS_TABLE","contentMigrationsFolder","join","__dirname","runContentMigrations","params","migrate","db","migrationsFolder","migrationsTable","randomUUID","POST_STATUS","isPublic","row","now","live","status","POST_STATUS","PUBLISHED","SCHEDULED","publishedAt","adminComparator","query","sign","order","value","sort","title","toLowerCase","getTime","Number","POSITIVE_INFINITY","updatedAt","left","right","a","b","id","localeCompare","paginate","rows","page","pageSize","slice","map","total","length","UniqueViolation","Error","code","createInMemoryPostStore","seed","formerSlugs","assertUniqueSlug","companyId","slug","ownId","some","findByShortId","shortId","find","candidate","undefined","findPublicByShortId","findPublicByFormerSlug","former","entry","postId","recordFormerSlug","params","push","create","values","Date","randomUUID","excerpt","body","coverImageUrl","coverImageAlt","tags","tagLabels","DRAFT","isTemplate","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","findById","findBySlug","findPublicBySlug","update","Object","assign","Math","max","listForAdmin","search","matched","filter","ARCHIVED","effectiveStatus","tag","includes","countByStatus","counts","published","scheduled","draft","archived","templates","claimDueScheduled","limit","due","listPublic","listTags","publicAt","Map","set","get","entries","count","DEFAULT_SCHEDULER_INTERVAL_MS","startContentScheduler","params","isRunning","tick","module","useCases","publishDue","execute","error","logger","Error","message","String","timer","setInterval","intervalMs","unref","clearInterval","randomUUID","createInMemoryRecurrenceStore","rows","owned","companyId","id","find","row","create","values","randomUUID","isActive","lastRunAt","lastPostId","createdAt","Date","push","findById","undefined","list","filter","sort","left","right","nextRunAt","getTime","map","update","Object","assign","remove","index","findIndex","splice","processDue","now","limit","handle","due","slice","length"]}
|
|
1
|
+
{"version":3,"sources":["../../../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.16.2_@swc+helpers@0.5.23__jiti@2.7.0_postcss@8.5.28_tsx@4.23.13_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/ContentModule.ts","../src/repositories/CommunityRepository.ts","../src/schema/schema.ts","../src/shared/community.constant.ts","../src/repositories/PostRepository.ts","../src/repositories/conditions.ts","../src/repositories/RecurrenceRepository.ts","../src/use-cases/community/ContentSettings.use-cases.ts","../src/use-cases/Post.use-cases.ts","../src/shared/shortId.ts","../src/shared/isUniqueViolation.ts","../src/shared/notifyPostChanged.ts","../src/shared/toContract.ts","../src/use-cases/community/CreateCommunityPost.use-case.ts","../src/use-cases/community/CommunityUseCaseBase.ts","../src/use-cases/community/DeleteOwnCommunityPost.use-case.ts","../src/use-cases/community/ReadOwnCommunityPosts.use-cases.ts","../src/use-cases/community/ModerateCommunityPost.use-cases.ts","../src/use-cases/community/CommunityModerationUseCaseBase.ts","../src/shared/notifyCommunityPostReviewed.ts","../src/use-cases/community/ModerateCommunityPostsInBulk.use-case.ts","../src/use-cases/community/PostReport.use-cases.ts","../src/shared/notifyPostReported.ts","../src/use-cases/community/ResolveCommunityAuthor.use-case.ts","../src/use-cases/community/SubmitCommunityPost.use-case.ts","../src/shared/notifyCommunityPostSubmitted.ts","../src/use-cases/community/UpdateOwnCommunityPost.use-case.ts","../src/use-cases/community/UploadCommunityImage.use-case.ts","../src/use-cases/UploadImage.use-case.ts","../src/shared/coverImage.constant.ts","../src/use-cases/community/buildCommunityUseCases.ts","../src/use-cases/Feed.use-cases.ts","../src/use-cases/PublicPost.use-cases.ts","../src/use-cases/Recurrence.use-cases.ts","../src/use-cases/Scheduling.use-cases.ts","../src/shared/recurrence.ts","../src/use-cases/Template.use-cases.ts","../src/use-cases/UploadCoverImage.use-case.ts","../src/http/adminRoutes.ts","../src/http/moderationRoutes.ts","../src/http/requireCompany.ts","../src/http/communityRoutes.ts","../src/http/publicRoutes.ts","../src/http/routes.ts","../src/http/rateLimitedOperations.constant.ts","../src/runMigrations.ts","../src/testing/inMemoryPostStore.ts","../src/scheduler.ts","../src/testing/inMemoryRecurrenceStore.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Composição raiz do módulo de conteúdo (blog, novidades, notícias). Recebe a conexão Drizzle do\n * host e devolve os use-cases; as rotas saem de `createContentRoutes` sobre este objeto.\n */\n\nimport { ConfigMissingError } from '@adatechnology/content-contracts'\nimport type {\n ClockPort,\n CommunityAuthorPort,\n ContentHooks,\n ContentImageStoragePort,\n ContentModuleConfig,\n LoggerPort,\n} from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from './database.types'\nimport { CommunityRepository } from './repositories/CommunityRepository'\nimport { PostRepository } from './repositories/PostRepository'\nimport { RecurrenceRepository } from './repositories/RecurrenceRepository'\nimport type {\n CommunityStorePort,\n ContentDependencies,\n PostStorePort,\n RecurrenceStorePort,\n} from './use-cases/contentModule.types'\nimport { buildCommunityUseCases, type CommunityUseCases } from './use-cases/community/buildCommunityUseCases'\nimport { BuildFeedUseCase, ListSitemapEntriesUseCase } from './use-cases/Feed.use-cases'\nimport {\n ArchivePostUseCase,\n CreatePostUseCase,\n GetPostUseCase,\n ListPostsUseCase,\n PublishPostUseCase,\n UnpublishPostUseCase,\n UpdatePostUseCase,\n} from './use-cases/Post.use-cases'\nimport {\n GetPublishedPostBySlugUseCase,\n ListPublishedPostsUseCase,\n ListTagsUseCase,\n} from './use-cases/PublicPost.use-cases'\nimport {\n CreateRecurrenceUseCase,\n ListRecurrencesUseCase,\n RemoveRecurrenceUseCase,\n UpdateRecurrenceUseCase,\n} from './use-cases/Recurrence.use-cases'\nimport { PublishDueUseCase, RepublishPostUseCase } from './use-cases/Scheduling.use-cases'\nimport { CountPostsUseCase, CreateFromTemplateUseCase, SaveAsTemplateUseCase } from './use-cases/Template.use-cases'\nimport { UploadCoverImageUseCase } from './use-cases/UploadCoverImage.use-case'\nimport { UploadImageUseCase } from './use-cases/UploadImage.use-case'\n\nexport type ContentModuleProviders = {\n /** Sem storage, a capa é só por URL e a rota de upload não sobe. */\n readonly imageStorage?: ContentImageStoragePort\n /** Padrão: relógio do sistema. Os testes injetam um fixo para provar o agendamento. */\n readonly clock?: ClockPort\n readonly logger?: LoggerPort\n /** Troca a persistência (ex.: dublê em memória num teste do host). Padrão: Drizzle sobre `db`. */\n readonly postStore?: PostStorePort\n readonly recurrenceStore?: RecurrenceStorePort\n /** Sem a porta, nada de comunidade existe: nem use case, nem rota. */\n readonly communityAuthor?: CommunityAuthorPort\n /** Padrão: Drizzle sobre `db`. Só vale junto com `communityAuthor`. */\n readonly communityStore?: CommunityStorePort\n}\n\nexport type CreateContentModuleParams = {\n readonly db?: ContentDatabase\n readonly config?: ContentModuleConfig\n readonly providers?: ContentModuleProviders\n readonly hooks?: ContentHooks\n}\n\nexport type ContentModule = {\n readonly useCases: {\n readonly createPost: CreatePostUseCase\n readonly updatePost: UpdatePostUseCase\n readonly archivePost: ArchivePostUseCase\n readonly publishPost: PublishPostUseCase\n readonly unpublishPost: UnpublishPostUseCase\n readonly getPost: GetPostUseCase\n readonly listPosts: ListPostsUseCase\n readonly getPublishedPostBySlug: GetPublishedPostBySlugUseCase\n readonly listPublishedPosts: ListPublishedPostsUseCase\n readonly listTags: ListTagsUseCase\n readonly countPosts: CountPostsUseCase\n readonly saveAsTemplate: SaveAsTemplateUseCase\n readonly createFromTemplate: CreateFromTemplateUseCase\n readonly republishPost: RepublishPostUseCase\n readonly createRecurrence: CreateRecurrenceUseCase\n readonly listRecurrences: ListRecurrencesUseCase\n readonly updateRecurrence: UpdateRecurrenceUseCase\n readonly removeRecurrence: RemoveRecurrenceUseCase\n /** O host chama num intervalo (ver `startContentScheduler`): publica o agendado vencido e as recorrências. */\n readonly publishDue: PublishDueUseCase\n /** Capacidade por ausência: sem `providers.imageStorage`, não existe. */\n readonly uploadCoverImage?: UploadCoverImageUseCase\n /** Foto no corpo do post: mesmas regras da capa. */\n readonly uploadImage?: UploadImageUseCase\n /** Sem `config.feed`, feed e sitemap não existem. */\n readonly buildFeed?: BuildFeedUseCase\n readonly listSitemapEntries?: ListSitemapEntriesUseCase\n } & Partial<CommunityUseCases>\n readonly config: ContentModuleConfig\n}\n\nconst SYSTEM_CLOCK: ClockPort = { now: () => new Date() }\n\nfunction assertValidConfig(config: ContentModuleConfig): void {\n // Feed com endereço relativo geraria links quebrados em todo leitor de RSS — falha no boot.\n if (config.feed && !/^https?:\\/\\/[^/]/i.test(config.feed.siteUrl)) throw new ConfigMissingError('feed.siteUrl')\n if (config.feed && !config.feed.title.trim()) throw new ConfigMissingError('feed.title')\n if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes('{slug}')) {\n throw new ConfigMissingError('feed.postPathTemplate')\n }\n if (config.wordsPerMinute !== undefined && !(config.wordsPerMinute > 0))\n throw new ConfigMissingError('wordsPerMinute')\n}\n\nexport function createContentModule(params: CreateContentModuleParams): ContentModule {\n const config = params.config ?? {}\n assertValidConfig(config)\n\n const posts = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : undefined)\n if (!posts) throw new ConfigMissingError('db')\n const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : undefined)\n if (!recurrences) throw new ConfigMissingError('db')\n\n const community = params.providers?.communityStore ?? (params.db ? new CommunityRepository(params.db) : undefined)\n\n const dependencies: ContentDependencies = {\n posts,\n recurrences,\n config,\n clock: params.providers?.clock ?? SYSTEM_CLOCK,\n ...(params.hooks ? { hooks: params.hooks } : {}),\n ...(params.providers?.imageStorage ? { imageStorage: params.providers.imageStorage } : {}),\n ...(params.providers?.logger ? { logger: params.providers.logger } : {}),\n ...(params.providers?.communityAuthor ? { communityAuthor: params.providers.communityAuthor } : {}),\n ...(community ? { community } : {}),\n }\n\n return {\n useCases: {\n createPost: new CreatePostUseCase(dependencies),\n updatePost: new UpdatePostUseCase(dependencies),\n archivePost: new ArchivePostUseCase(dependencies),\n publishPost: new PublishPostUseCase(dependencies),\n unpublishPost: new UnpublishPostUseCase(dependencies),\n getPost: new GetPostUseCase(dependencies),\n listPosts: new ListPostsUseCase(dependencies),\n getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),\n listPublishedPosts: new ListPublishedPostsUseCase(dependencies),\n listTags: new ListTagsUseCase(dependencies),\n countPosts: new CountPostsUseCase(dependencies),\n saveAsTemplate: new SaveAsTemplateUseCase(dependencies),\n createFromTemplate: new CreateFromTemplateUseCase(dependencies),\n republishPost: new RepublishPostUseCase(dependencies),\n createRecurrence: new CreateRecurrenceUseCase(dependencies),\n listRecurrences: new ListRecurrencesUseCase(dependencies),\n updateRecurrence: new UpdateRecurrenceUseCase(dependencies),\n removeRecurrence: new RemoveRecurrenceUseCase(dependencies),\n publishDue: new PublishDueUseCase(dependencies),\n ...(dependencies.imageStorage\n ? {\n uploadCoverImage: new UploadCoverImageUseCase(dependencies),\n uploadImage: new UploadImageUseCase(dependencies),\n }\n : {}),\n ...buildCommunityUseCases(dependencies),\n ...(config.feed\n ? {\n buildFeed: new BuildFeedUseCase(dependencies, config.feed),\n listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed),\n }\n : {}),\n },\n config,\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, desc, eq, gt, inArray, isNotNull, isNull, ne, sql } from 'drizzle-orm'\nimport {\n COMMUNITY_MODERATIONS,\n DEFAULT_CONTENT_SETTINGS,\n POST_ORIGIN,\n POST_STATUS,\n type CommunityModeration,\n type ContentSettings,\n} from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from '../database.types'\nimport { communityImages, contentSettings, postReports, posts, type PostReportRow } from '../schema/schema'\nimport { COMMUNITY_WINDOW_MS } from '../shared/community.constant'\nimport type { CommunityCreateOutcome, CommunityStorePort, PostPage } from '../use-cases/contentModule.types'\n\nfunction toModeration(value: string): CommunityModeration {\n return (COMMUNITY_MODERATIONS as readonly string[]).includes(value)\n ? (value as CommunityModeration)\n : DEFAULT_CONTENT_SETTINGS.communityModeration\n}\n\nexport class CommunityRepository implements CommunityStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async createWithDailyLimit(\n params: Parameters<CommunityStorePort['createWithDailyLimit']>[0],\n ): Promise<CommunityCreateOutcome> {\n const { values, accountId, limit, now } = params\n const windowStart = new Date(now.getTime() - COMMUNITY_WINDOW_MS)\n const lockKey = `${values.companyId}:${accountId}`\n return this.db.transaction(async (tx) => {\n await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`)\n const recent = await tx\n .select({ createdAt: posts.createdAt })\n .from(posts)\n .where(\n and(\n eq(posts.companyId, values.companyId),\n eq(posts.origin, POST_ORIGIN.COMMUNITY),\n eq(posts.authorAccountId, accountId),\n gt(posts.createdAt, windowStart),\n ),\n )\n .orderBy(asc(posts.createdAt))\n // Com o limite reduzido depois, há mais posts na janela que o limite: libera quando o (n-limite+1)º sair.\n const blocking = recent[recent.length - limit]\n if (recent.length >= limit && blocking) {\n return { isLimited: true as const, freesUpAt: new Date(blocking.createdAt.getTime() + COMMUNITY_WINDOW_MS) }\n }\n const [row] = await tx.insert(posts).values(values).returning()\n if (!row) throw new Error('content-module: insert em posts não retornou linha')\n return { isLimited: false as const, row }\n })\n }\n\n async listByAuthor(params: Parameters<CommunityStorePort['listByAuthor']>[0]): Promise<PostPage> {\n const where = and(\n eq(posts.companyId, params.companyId),\n eq(posts.origin, POST_ORIGIN.COMMUNITY),\n eq(posts.authorAccountId, params.accountId),\n ne(posts.status, POST_STATUS.ARCHIVED),\n )\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(desc(posts.updatedAt), asc(posts.id))\n .limit(params.pageSize)\n .offset((params.page - 1) * params.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async getSettings(params: { companyId: string }): Promise<ContentSettings> {\n const [row] = await this.db\n .select()\n .from(contentSettings)\n .where(eq(contentSettings.companyId, params.companyId))\n .limit(1)\n if (!row) return DEFAULT_CONTENT_SETTINGS\n return {\n communityModeration: toModeration(row.communityModeration),\n communityDailyLimit: row.communityDailyLimit,\n maxImagesPerPost: row.maxImagesPerPost,\n }\n }\n\n async findOwnedImageUrls(\n params: Parameters<CommunityStorePort['findOwnedImageUrls']>[0],\n ): Promise<readonly string[]> {\n if (params.urls.length === 0) return []\n const rows = await this.db\n .select({ url: communityImages.url })\n .from(communityImages)\n .where(\n and(\n eq(communityImages.companyId, params.companyId),\n eq(communityImages.accountId, params.accountId),\n inArray(communityImages.url, [...params.urls]),\n ),\n )\n return rows.map((row) => row.url)\n }\n\n async recordImage(params: Parameters<CommunityStorePort['recordImage']>[0]): Promise<void> {\n await this.db.insert(communityImages).values(params)\n }\n\n async listRecentImageDates(\n params: Parameters<CommunityStorePort['listRecentImageDates']>[0],\n ): Promise<readonly Date[]> {\n const rows = await this.db\n .select({ createdAt: communityImages.createdAt })\n .from(communityImages)\n .where(\n and(\n eq(communityImages.companyId, params.companyId),\n eq(communityImages.accountId, params.accountId),\n gt(communityImages.createdAt, params.since),\n ),\n )\n .orderBy(asc(communityImages.createdAt))\n return rows.map((row) => row.createdAt)\n }\n\n async upsertSettings(params: Parameters<CommunityStorePort['upsertSettings']>[0]): Promise<ContentSettings> {\n const { companyId, settings, now } = params\n const values = { ...settings, updatedAt: now }\n await this.db\n .insert(contentSettings)\n .values({ companyId, ...values })\n .onConflictDoUpdate({ target: contentSettings.companyId, set: values })\n return settings\n }\n\n async createReport(params: Parameters<CommunityStorePort['createReport']>[0]): Promise<PostReportRow> {\n const { now, ...values } = params\n const [row] = await this.db\n .insert(postReports)\n .values({ ...values, createdAt: now })\n .returning()\n if (!row) throw new Error('content-module: insert em post_reports não retornou linha')\n return row\n }\n\n async listReports(\n params: Parameters<CommunityStorePort['listReports']>[0],\n ): ReturnType<CommunityStorePort['listReports']> {\n const where = and(\n eq(postReports.companyId, params.companyId),\n params.status === 'open' ? isNull(postReports.resolvedAt) : isNotNull(postReports.resolvedAt),\n )\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(postReports)\n .where(where)\n .orderBy(desc(postReports.createdAt), asc(postReports.id))\n .limit(params.pageSize)\n .offset((params.page - 1) * params.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(postReports)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async resolveReport(params: Parameters<CommunityStorePort['resolveReport']>[0]): Promise<PostReportRow | undefined> {\n const [row] = await this.db\n .update(postReports)\n .set({\n resolvedAt: sql`coalesce(${postReports.resolvedAt}, ${params.now.toISOString()}::timestamptz)`,\n resolvedBy: sql`coalesce(${postReports.resolvedBy}, ${params.actorUserId})`,\n })\n .where(and(eq(postReports.companyId, params.companyId), eq(postReports.id, params.id)))\n .returning()\n return row\n }\n\n async countOpenReports(\n params: Parameters<CommunityStorePort['countOpenReports']>[0],\n ): Promise<ReadonlyMap<string, number>> {\n if (params.postIds.length === 0) return new Map()\n const rows = await this.db\n .select({ postId: postReports.postId, value: sql<number>`count(*)::int` })\n .from(postReports)\n .where(\n and(\n eq(postReports.companyId, params.companyId),\n isNull(postReports.resolvedAt),\n inArray(postReports.postId, [...params.postIds]),\n ),\n )\n .groupBy(postReports.postId)\n return new Map(rows.map((row) => [row.postId, row.value]))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { sql } from 'drizzle-orm'\nimport {\n boolean,\n customType,\n index,\n integer,\n jsonb,\n primaryKey,\n pgSchema,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n varchar,\n} from 'drizzle-orm/pg-core'\nimport type { CommunityRevision } from '@adatechnology/content-contracts'\n\n// O driver bun-sql grava o `jsonb` do Drizzle como string JSON (escalar): `->>` e `@>` não enxergam as chaves.\n// Aqui o texto passa por `::text::jsonb` (o Bun recodifica string enviada a parâmetro jsonb) e a leitura aceita as duas formas (linhas antigas seguem escalar).\nconst jsonbObject = <TObject extends object>(name: string) =>\n customType<{ data: TObject; driverData: string | TObject }>({\n dataType: () => 'jsonb',\n toDriver: (value) => sql`${JSON.stringify(value)}::text::jsonb` as unknown as string,\n fromDriver: (value) => (typeof value === 'string' ? (JSON.parse(value) as TObject) : value),\n })(name)\n\n// Schema Postgres dedicado — o módulo nunca escreve no `public` do host.\nexport const contentSchema = pgSchema('content')\n\n// `status` em varchar e não ENUM nativo; os valores espelham `POST_STATUS` do contracts. Tamanho 16\n// por causa de `pending_review` (14 caracteres).\nexport const posts = contentSchema.table(\n 'posts',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n shortId: varchar('short_id', { length: 6 }).notNull(),\n title: varchar('title', { length: 200 }).notNull(),\n excerpt: varchar('excerpt', { length: 500 }),\n body: text('body').notNull().default(''),\n coverImageUrl: varchar('cover_image_url', { length: 2048 }),\n coverImageAlt: varchar('cover_image_alt', { length: 300 }),\n tags: text('tags').array().notNull().default([]),\n tagLabels: jsonb('tag_labels').$type<Record<string, string>>().notNull().default({}),\n status: varchar('status', { length: 16 }).notNull().default('draft'),\n isTemplate: boolean('is_template').notNull().default(false),\n publishedAt: timestamp('published_at', { withTimezone: true }),\n authorName: varchar('author_name', { length: 120 }),\n seoTitle: varchar('seo_title', { length: 200 }),\n seoDescription: varchar('seo_description', { length: 320 }),\n canonicalUrl: varchar('canonical_url', { length: 2048 }),\n readingTimeMinutes: integer('reading_time_minutes').notNull().default(1),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n // Comunidade: linhas antigas leem `staff`. Valores de `origin` espelham `POST_ORIGIN`.\n origin: varchar('origin', { length: 12 }).notNull().default('staff'),\n authorAccountId: varchar('author_account_id', { length: 64 }),\n authorDisplayName: varchar('author_display_name', { length: 80 }),\n // `YYYY-MM`, retrato da porta no primeiro envio.\n authorReferenceMonth: varchar('author_reference_month', { length: 7 }),\n reviewNote: varchar('review_note', { length: 500 }),\n termsAcceptedAt: timestamp('terms_accepted_at', { withTimezone: true }),\n // Ordem da fila de moderação.\n submittedAt: timestamp('submitted_at', { withTimezone: true }),\n // Edição de post publicado, à parte até a aprovação; forma validada por `communityRevisionSchema`.\n pendingRevision: jsonbObject<CommunityRevision>('pending_revision'),\n },\n (table) => [\n // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo\n // faria um link antigo (já compartilhado) abrir outro post.\n uniqueIndex('idx_posts_company_slug').on(table.companyId, table.slug),\n uniqueIndex('idx_posts_company_short_id').on(table.companyId, table.shortId),\n // Serve a listagem pública: empresa + status + ordem por data.\n index('idx_posts_company_status_published').on(table.companyId, table.status, table.publishedAt),\n index('idx_posts_company_origin_status_published').on(\n table.companyId,\n table.origin,\n table.status,\n table.publishedAt,\n ),\n // Serve o limite diário: posts do autor na janela de 24 h.\n index('idx_posts_community_author_created')\n .on(table.companyId, table.authorAccountId, table.createdAt)\n .where(sql`\"origin\" = 'community'`),\n index('idx_posts_moderation_queue')\n .on(table.companyId, table.submittedAt)\n .where(sql`\"status\" = 'pending_review' OR \"pending_revision\" IS NOT NULL`),\n index('idx_posts_tags').using('gin', table.tags),\n // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.\n index('idx_posts_due')\n .on(table.publishedAt)\n .where(sql`\"status\" = 'scheduled'`),\n ],\n)\n\nexport type PostRow = typeof posts.$inferSelect\nexport type NewPostRow = typeof posts.$inferInsert\n\n// `frequency` em varchar (weekly | monthly), sem ENUM nativo. Posts nunca são apagados, então a\n// chave estrangeira para o modelo não precisa de ON DELETE.\nexport const recurrenceRules = contentSchema.table(\n 'recurrence_rules',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n templateId: uuid('template_id')\n .notNull()\n .references(() => posts.id),\n frequency: varchar('frequency', { length: 10 }).notNull(),\n // Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.\n anchorDay: integer('anchor_day').notNull(),\n isActive: boolean('is_active').notNull().default(true),\n nextRunAt: timestamp('next_run_at', { withTimezone: true }).notNull(),\n lastRunAt: timestamp('last_run_at', { withTimezone: true }),\n lastPostId: uuid('last_post_id'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n index('idx_recurrence_company').on(table.companyId),\n index('idx_recurrence_due')\n .on(table.nextRunAt)\n .where(sql`\"is_active\"`),\n ],\n)\n\nexport type RecurrenceRow = typeof recurrenceRules.$inferSelect\nexport type NewRecurrenceRow = typeof recurrenceRules.$inferInsert\n\n// Slugs que o post já teve: o link antigo continua abrindo o post (e o host o redireciona ao canônico).\nexport const postFormerSlugs = contentSchema.table(\n 'post_former_slugs',\n {\n companyId: uuid('company_id').notNull(),\n slug: varchar('slug', { length: 120 }).notNull(),\n postId: uuid('post_id')\n .notNull()\n .references(() => posts.id),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [primaryKey({ columns: [table.companyId, table.slug] })],\n)\n\n// Sem linha = `DEFAULT_CONTENT_SETTINGS`. Os padrões aqui repetem os do contracts para o SQL puro.\nexport const contentSettings = contentSchema.table('content_settings', {\n companyId: uuid('company_id').primaryKey(),\n communityModeration: varchar('community_moderation', { length: 8 }).notNull().default('before'),\n communityDailyLimit: integer('community_daily_limit').notNull().default(3),\n maxImagesPerPost: integer('max_images_per_post').notNull().default(12),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n})\n\nexport type ContentSettingsRow = typeof contentSettings.$inferSelect\n\n// Sem IP e sem identidade de quem denunciou, de propósito.\nexport const postReports = contentSchema.table(\n 'post_reports',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n postId: uuid('post_id')\n .notNull()\n .references(() => posts.id),\n reason: varchar('reason', { length: 300 }).notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n resolvedAt: timestamp('resolved_at', { withTimezone: true }),\n resolvedBy: varchar('resolved_by', { length: 64 }),\n },\n (table) => [\n index('idx_post_reports_open')\n .on(table.companyId, table.createdAt)\n .where(sql`\"resolved_at\" IS NULL`),\n ],\n)\n\nexport type PostReportRow = typeof postReports.$inferSelect\n\n// Foto enviada pelo hóspede: só URL registrada aqui pode entrar no corpo de post da comunidade.\nexport const communityImages = contentSchema.table(\n 'community_images',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n companyId: uuid('company_id').notNull(),\n accountId: varchar('account_id', { length: 64 }).notNull(),\n storageKey: varchar('storage_key', { length: 512 }).notNull(),\n url: varchar('url', { length: 2048 }).notNull(),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => [\n uniqueIndex('idx_community_images_company_url').on(table.companyId, table.url),\n index('idx_community_images_account').on(table.companyId, table.accountId, table.createdAt),\n ],\n)\n\nexport type CommunityImageRow = typeof communityImages.$inferSelect\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/** Janela móvel do limite diário: sem fuso, não se burla na virada da meia-noite. */\nexport const COMMUNITY_WINDOW_MS = 24 * 60 * 60 * 1000\n\nexport const COMMUNITY_IMAGE_KEY_PREFIX = 'content/community'\n\n/** Título do post anonimizado ao excluir: a linha fica só para reservar slug e contar o limite. */\nexport const ANONYMIZED_TITLE = '—'\n\nexport const COMMUNITY_ACTION = {\n SUBMIT: 'submit',\n APPROVE: 'approve',\n REJECT: 'reject',\n UNPUBLISH: 'unpublish',\n} as const\n\n/** Falha de um item do lote que não é `ContentError`: a mensagem original pode ter dado interno. */\nexport const BULK_UNEXPECTED_FAILURE = {\n code: 'CONTENT_UNEXPECTED',\n message: 'Não foi possível concluir esta ação.',\n} as const\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, desc, eq, inArray, sql } from 'drizzle-orm'\nimport {\n COMMUNITY_REVISION_STATE,\n POST_ORIGIN,\n POST_STATUS,\n type PostCounts,\n type TagCount,\n} from '@adatechnology/content-contracts'\n\nimport type { ContentDatabase } from '../database.types'\nimport { postFormerSlugs, posts, type NewPostRow, type PostRow } from '../schema/schema'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\nimport {\n postAdminListCondition,\n postDueCondition,\n postOwnedByCondition,\n postPublicCondition,\n postPublicIdCondition,\n postPublicListCondition,\n postPublicShortIdCondition,\n postShortIdCondition,\n postPublicSlugCondition,\n postSlugCondition,\n revisionStateExpression,\n} from './conditions'\n\nconst TAG_LIST_LIMIT = 200\n\nconst SORT_COLUMNS = {\n title: posts.title,\n status: posts.status,\n publishedAt: posts.publishedAt,\n updatedAt: posts.updatedAt,\n} as const\n\n// Padrão: a última edição primeiro, que é o que o painel está mexendo agora. `id` desempata para\n// a paginação não repetir nem pular linha. Data ausente (rascunho) vai sempre para o fim.\nfunction adminOrder(query: PostAdminListQuery) {\n const column = SORT_COLUMNS[query.sort ?? 'updatedAt']\n const direction = (query.order ?? 'desc') === 'asc' ? asc : desc\n const primary =\n query.sort === 'publishedAt'\n ? sql`${column} ${sql.raw(query.order === 'asc' ? 'asc' : 'desc')} nulls last`\n : direction(column)\n return [primary, asc(posts.id)]\n}\n\nexport class PostRepository implements PostStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewPostRow): Promise<PostRow> {\n const [row] = await this.db.insert(posts).values(values).returning()\n if (!row) throw new Error('content-module: insert em posts não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postOwnedByCondition(params)).limit(1)\n return row\n }\n\n async findBySlug(params: { companyId: string; slug: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postSlugCondition(params)).limit(1)\n return row\n }\n\n async findPublicBySlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1)\n return row\n }\n\n async findByShortId(params: { companyId: string; shortId: string }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicByShortId(params: { companyId: string; shortId: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicById(params: { companyId: string; id: string; now: Date }): Promise<PostRow | undefined> {\n const [row] = await this.db.select().from(posts).where(postPublicIdCondition(params)).limit(1)\n return row\n }\n\n async findPublicByFormerSlug(params: { companyId: string; slug: string; now: Date }): Promise<PostRow | undefined> {\n const [former] = await this.db\n .select({ postId: postFormerSlugs.postId })\n .from(postFormerSlugs)\n .where(and(eq(postFormerSlugs.companyId, params.companyId), eq(postFormerSlugs.slug, params.slug)))\n .limit(1)\n if (!former) return undefined\n const [row] = await this.db\n .select()\n .from(posts)\n .where(and(postPublicCondition(params), eq(posts.id, former.postId)))\n .limit(1)\n return row\n }\n\n async recordFormerSlug(params: { companyId: string; postId: string; slug: string }): Promise<void> {\n await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing()\n }\n\n async update(params: { companyId: string; id: string; values: Partial<NewPostRow> }): Promise<PostRow | undefined> {\n const [row] = await this.db\n .update(posts)\n .set({ ...params.values, updatedAt: new Date() })\n .where(postOwnedByCondition(params))\n .returning()\n return row\n }\n\n async listForAdmin(query: PostAdminListQuery): Promise<PostPage> {\n const where = postAdminListCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(...adminOrder(query))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async listPublic(query: PostPublicListQuery): Promise<PostPage> {\n const where = postPublicListCondition(query)\n const [rows, [counted]] = await Promise.all([\n this.db\n .select()\n .from(posts)\n .where(where)\n .orderBy(desc(posts.publishedAt), asc(posts.id))\n .limit(query.pageSize)\n .offset((query.page - 1) * query.pageSize),\n this.db\n .select({ value: sql<number>`count(*)::int` })\n .from(posts)\n .where(where),\n ])\n return { rows, total: counted?.value ?? 0 }\n }\n\n async countByStatus(params: { companyId: string; now: Date }): Promise<PostCounts> {\n // Instante como texto com cast: o driver não serializa `Date` solto dentro de `sql` cru.\n const now = sql`${params.now.toISOString()}::timestamptz`\n const counted = (condition: ReturnType<typeof sql>) => sql<number>`count(*) filter (where ${condition})::int`\n // As abas existentes são da equipe: post da comunidade tem as suas (`pendingReview`, `rejected`).\n const staff = sql`${posts.origin} = ${POST_ORIGIN.STAFF}`\n const revisionState = revisionStateExpression()\n const livePublished = sql`(${posts.status} = ${POST_STATUS.PUBLISHED} or (${posts.status} = ${POST_STATUS.SCHEDULED} and ${posts.publishedAt} <= ${now}))`\n const [row] = await this.db\n .select({\n published: counted(sql`${staff} and not ${posts.isTemplate} and ${livePublished}`),\n scheduled: counted(\n sql`${staff} and not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.SCHEDULED} and ${posts.publishedAt} > ${now}`,\n ),\n draft: counted(sql`${staff} and not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.DRAFT}`),\n archived: counted(sql`${staff} and not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS.ARCHIVED}`),\n templates: counted(sql`${posts.isTemplate} and ${posts.status} <> ${POST_STATUS.ARCHIVED}`),\n pendingReview: counted(\n sql`${posts.status} = ${POST_STATUS.PENDING_REVIEW} or ${revisionState} = ${COMMUNITY_REVISION_STATE.PENDING}`,\n ),\n rejected: counted(sql`${posts.status} = ${POST_STATUS.REJECTED}`),\n })\n .from(posts)\n .where(eq(posts.companyId, params.companyId))\n return row ?? { published: 0, scheduled: 0, draft: 0, archived: 0, templates: 0, pendingReview: 0, rejected: 0 }\n }\n\n async claimDueScheduled(params: { now: Date; limit: number }): Promise<readonly PostRow[]> {\n // Um único UPDATE com a seleção travada por dentro: quem chega depois pula as linhas já travadas\n // e não as enxerga mais como agendadas — nenhum post é marcado nem notificado duas vezes.\n const due = this.db\n .select({ id: posts.id })\n .from(posts)\n .where(postDueCondition({ now: params.now }))\n .orderBy(asc(posts.publishedAt), asc(posts.id))\n .limit(params.limit)\n .for('update', { skipLocked: true })\n return this.db.update(posts).set({ status: POST_STATUS.PUBLISHED }).where(inArray(posts.id, due)).returning()\n }\n\n async listTags(params: { companyId: string; publicAt?: Date }): Promise<readonly TagCount[]> {\n const where = params.publicAt\n ? postPublicCondition({ companyId: params.companyId, now: params.publicAt })\n : postAdminListCondition({ companyId: params.companyId, now: new Date() })\n // Subconsulta em vez de `group by unnest(...)`: o Postgres não aceita função que devolve\n // conjunto no GROUP BY.\n const postTags = this.db\n .select({ tag: sql<string>`unnest(${posts.tags})`.as('tag') })\n .from(posts)\n .where(where)\n .as('post_tags')\n const rows = await this.db\n .select({ tag: postTags.tag, count: sql<number>`count(*)::int` })\n .from(postTags)\n .groupBy(postTags.tag)\n .orderBy(sql`count(*) desc`, asc(postTags.tag))\n .limit(TAG_LIST_LIMIT)\n return rows\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Toda condição alcançável por uma requisição vive aqui como função pura exportada — a mesma que o\n * repositório chama e que `isolation.test.ts` renderiza em SQL. Um refactor que esqueça o filtro\n * de empresa quebra o teste na hora.\n */\n\nimport { and, arrayContains, arrayOverlaps, eq, gt, inArray, lte, ne, or, sql, type SQL } from 'drizzle-orm'\nimport {\n COMMUNITY_REVISION_STATE,\n POST_ORIGIN,\n POST_STATUS,\n type PostOriginFilter,\n type PostStatus,\n} from '@adatechnology/content-contracts'\n\nimport { posts } from '../schema/schema'\n\nexport function postOwnedByCondition(params: { companyId: string; id: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id)) as SQL\n}\n\nexport function postSlugCondition(params: { companyId: string; slug: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug)) as SQL\n}\n\n/** Ausente = `staff`: quem não conhece a comunidade continua vendo só o que já via. */\nexport function postOriginCondition(origin: PostOriginFilter | undefined): SQL | undefined {\n const filter = origin ?? POST_ORIGIN.STAFF\n return filter === 'all' ? undefined : eq(posts.origin, filter)\n}\n\nexport function postAdminListCondition(params: {\n companyId: string\n origin?: PostOriginFilter\n status?: PostStatus\n tags?: readonly string[]\n search?: string\n /** `true`: só modelos (menos os arquivados). Ausente/`false`: só posts — modelo nunca aparece misturado. */\n isTemplate?: boolean\n now: Date\n}): SQL {\n const conditions: SQL[] = [eq(posts.companyId, params.companyId), templateCondition(params.isTemplate)]\n const origin = postOriginCondition(params.origin)\n if (origin) conditions.push(origin)\n if (params.status) conditions.push(statusCondition(params.status, params.now))\n if (params.tags?.length) conditions.push(arrayOverlaps(posts.tags, [...params.tags]))\n if (params.search) {\n const pattern = `%${params.search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n conditions.push(sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`)\n }\n return and(...conditions) as SQL\n}\n\n/** O driver bun-sql grava o jsonb como string JSON (escalar): `->>` direto devolveria null, então desembrulha antes. */\nexport function revisionStateExpression(): SQL {\n return sql`(case when jsonb_typeof(${posts.pendingRevision}) = 'string' then (${posts.pendingRevision} #>> '{}')::jsonb else ${posts.pendingRevision} end) ->> 'state'`\n}\n\n/** Fila de moderação: post da comunidade em análise ou com edição pendente (a mesma regra da contagem). */\nexport function pendingReviewCondition(): SQL {\n return and(\n eq(posts.origin, POST_ORIGIN.COMMUNITY),\n or(\n eq(posts.status, POST_STATUS.PENDING_REVIEW),\n sql`${revisionStateExpression()} = ${COMMUNITY_REVISION_STATE.PENDING}`,\n ),\n ) as SQL\n}\n\nfunction templateCondition(isTemplate: boolean | undefined): SQL {\n if (isTemplate) return and(eq(posts.isTemplate, true), ne(posts.status, POST_STATUS.ARCHIVED)) as SQL\n return eq(posts.isTemplate, false)\n}\n\n/**\n * Filtra pelo status que o painel MOSTRA: agendado cuja hora passou aparece como publicado, então\n * o filtro \"publicados\" o inclui e o filtro \"agendados\" o exclui.\n */\nfunction statusCondition(status: PostStatus, now: Date): SQL {\n if (status === POST_STATUS.PENDING_REVIEW) return pendingReviewCondition()\n if (status === POST_STATUS.PUBLISHED) {\n return or(\n eq(posts.status, POST_STATUS.PUBLISHED),\n and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)),\n ) as SQL\n }\n if (status === POST_STATUS.SCHEDULED) {\n return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now)) as SQL\n }\n return eq(posts.status, status)\n}\n\n/**\n * Público = publicado ou agendado cuja hora chegou. `scheduled` entra na condição justamente para\n * que o agendamento valha sem cron: no instante de `published_at` o post passa a casar aqui.\n */\nexport function postPublicCondition(params: { companyId: string; now: Date; tag?: string }): SQL {\n const conditions: SQL[] = [\n eq(posts.companyId, params.companyId),\n inArray(posts.status, [POST_STATUS.PUBLISHED, POST_STATUS.SCHEDULED]),\n lte(posts.publishedAt, params.now),\n ]\n if (params.tag) conditions.push(arrayContains(posts.tags, [params.tag]))\n return and(...conditions) as SQL\n}\n\n/** Lista pública: a condição de \"no ar\" (intocada) mais o filtro de origem. Por slug/id curto as duas origens abrem. */\nexport function postPublicListCondition(params: {\n companyId: string\n now: Date\n tag?: string\n origin?: PostOriginFilter\n}): SQL {\n return and(postPublicCondition(params), postOriginCondition(params.origin)) as SQL\n}\n\nexport function postPublicSlugCondition(params: { companyId: string; slug: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.slug, params.slug)) as SQL\n}\n\n/**\n * Agendado cuja hora chegou, de qualquer empresa: é a única condição sem `company_id`, de propósito —\n * o `publishDue` é tarefa do sistema e varre todas as empresas. Modelo nunca entra.\n */\nexport function postDueCondition(params: { now: Date }): SQL {\n return and(\n eq(posts.status, POST_STATUS.SCHEDULED),\n eq(posts.isTemplate, false),\n lte(posts.publishedAt, params.now),\n ) as SQL\n}\n\nexport function postShortIdCondition(params: { companyId: string; shortId: string }): SQL {\n return and(eq(posts.companyId, params.companyId), eq(posts.shortId, params.shortId)) as SQL\n}\n\nexport function postPublicIdCondition(params: { companyId: string; id: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.id, params.id)) as SQL\n}\n\nexport function postPublicShortIdCondition(params: { companyId: string; shortId: string; now: Date }): SQL {\n return and(postPublicCondition(params), eq(posts.shortId, params.shortId)) as SQL\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { and, asc, eq, lte } from 'drizzle-orm'\n\nimport type { ContentDatabase } from '../database.types'\nimport { recurrenceRules, type NewRecurrenceRow, type RecurrenceRow } from '../schema/schema'\nimport type { RecurrenceStorePort } from '../use-cases/contentModule.types'\n\nexport function recurrenceOwnedByCondition(params: { companyId: string; id: string }) {\n return and(eq(recurrenceRules.companyId, params.companyId), eq(recurrenceRules.id, params.id))\n}\n\nexport class RecurrenceRepository implements RecurrenceStorePort {\n constructor(private readonly db: ContentDatabase) {}\n\n async create(values: NewRecurrenceRow): Promise<RecurrenceRow> {\n const [row] = await this.db.insert(recurrenceRules).values(values).returning()\n if (!row) throw new Error('content-module: insert em recurrence_rules não retornou linha')\n return row\n }\n\n async findById(params: { companyId: string; id: string }): Promise<RecurrenceRow | undefined> {\n const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1)\n return row\n }\n\n async list(params: { companyId: string }): Promise<readonly RecurrenceRow[]> {\n return this.db\n .select()\n .from(recurrenceRules)\n .where(eq(recurrenceRules.companyId, params.companyId))\n .orderBy(asc(recurrenceRules.nextRunAt), asc(recurrenceRules.id))\n }\n\n async update(params: {\n companyId: string\n id: string\n values: Partial<NewRecurrenceRow>\n }): Promise<RecurrenceRow | undefined> {\n const [row] = await this.db\n .update(recurrenceRules)\n .set(params.values)\n .where(recurrenceOwnedByCondition(params))\n .returning()\n return row\n }\n\n async remove(params: { companyId: string; id: string }): Promise<boolean> {\n const removed = await this.db\n .delete(recurrenceRules)\n .where(recurrenceOwnedByCondition(params))\n .returning({ id: recurrenceRules.id })\n return removed.length > 0\n }\n\n async processDue(params: {\n now: Date\n limit: number\n handle: (rule: RecurrenceRow) => Promise<Partial<NewRecurrenceRow>>\n }): Promise<number> {\n return this.db.transaction(async (transaction) => {\n const due = await transaction\n .select()\n .from(recurrenceRules)\n .where(and(eq(recurrenceRules.isActive, true), lte(recurrenceRules.nextRunAt, params.now)))\n .orderBy(asc(recurrenceRules.nextRunAt), asc(recurrenceRules.id))\n .limit(params.limit)\n .for('update', { skipLocked: true })\n let processed = 0\n // Sequencial de propósito: a transação é uma conexão só, e a ordem é a da data de vencimento.\n for (const rule of due) {\n const values = await params.handle(rule)\n await transaction.update(recurrenceRules).set(values).where(eq(recurrenceRules.id, rule.id))\n processed += 1\n }\n return processed\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { contentSettingsSchema, type ContentSettings } from '@adatechnology/content-contracts'\n\nimport { PostUseCaseBase } from '../Post.use-cases'\nimport type { CommunityDependencies, UpdateContentSettingsParams } from '../types/community.types'\n\nabstract class ContentSettingsUseCaseBase extends PostUseCaseBase {\n constructor(protected override readonly dependencies: CommunityDependencies) {\n super(dependencies)\n }\n}\n\nexport class GetContentSettingsUseCase extends ContentSettingsUseCaseBase {\n /** Sem linha da empresa, o padrão do contracts. */\n execute(params: { readonly companyId: string }): Promise<ContentSettings> {\n return this.dependencies.community.getSettings(params)\n }\n}\n\nexport class UpdateContentSettingsUseCase extends ContentSettingsUseCaseBase {\n /** Vale para os próximos envios: o que já está em análise ou no ar não muda de estado. */\n async execute(params: UpdateContentSettingsParams): Promise<ContentSettings> {\n const settings = contentSettingsSchema.parse(params.input)\n return this.dependencies.community.upsertSettings({ companyId: params.companyId, settings, now: this.now() })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Casos de uso do painel: criar, editar, arquivar, publicar/agendar, despublicar, ler e listar.\n * Todos validam a entrada com o schema do contracts de novo — o host pode chamar o use-case sem\n * passar pela rota, e a regra não pode depender de quem chamou.\n */\n\nimport {\n buildTagLabels,\n CommunityPostReadOnlyError,\n createPostSchema,\n DuplicateSlugError,\n estimateReadingTimeMinutes,\n listPostsQuerySchema,\n normalizeTags,\n POST_EVENT,\n POST_ORIGIN,\n POST_STATUS,\n PostNotFoundError,\n TemplateNotPublishableError,\n publishPostSchema,\n buildShortSlug,\n updatePostSchema,\n withSlugSuffix,\n type CreatePostInput,\n type ListPostsQuery,\n type Paginated,\n type Post,\n type PostEventType,\n type PostSummary,\n type PublishPostInput,\n type UpdatePostInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { generateShortId } from '../shared/shortId'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPagination, toPost, toPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst MAX_SLUG_ATTEMPTS = 50\nconst FALLBACK_SLUG = 'post'\n\nexport type PostReference = { readonly companyId: string; readonly id: string }\n\nexport abstract class PostUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected now(): Date {\n return this.dependencies.clock.now()\n }\n\n protected async findOrFail(reference: PostReference): Promise<PostRow> {\n const row = await this.dependencies.posts.findById(reference)\n if (!row) throw new PostNotFoundError(reference.id)\n return row\n }\n\n /** Ações de edição da equipe: a equipe modera post da comunidade, não o reescreve (design §4). */\n protected async findEditableOrFail(reference: PostReference): Promise<PostRow> {\n const row = await this.findOrFail(reference)\n if (row.origin === POST_ORIGIN.COMMUNITY) throw new CommunityPostReadOnlyError(reference.id)\n return row\n }\n\n /** Denúncias abertas por post numa consulta só; sem o módulo de comunidade, ninguém tem denúncia. */\n protected async openReportCounts(params: {\n readonly companyId: string\n readonly rows: readonly PostRow[]\n }): Promise<ReadonlyMap<string, number>> {\n const { community } = this.dependencies\n const postIds = params.rows.filter((row) => row.origin === POST_ORIGIN.COMMUNITY).map((row) => row.id)\n if (!community || postIds.length === 0) return new Map()\n return community.countOpenReports({ companyId: params.companyId, postIds })\n }\n\n protected async save(reference: PostReference, values: Partial<NewPostRow>, event: PostEventType): Promise<Post> {\n const row = await this.dependencies.posts.update({ ...reference, values }).catch((error: unknown) => {\n if (isUniqueViolation(error) && values.slug) throw new DuplicateSlugError(values.slug)\n throw error\n })\n if (!row) throw new PostNotFoundError(reference.id)\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, event, post)\n return post\n }\n\n /** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */\n protected async generateShortId(companyId: string): Promise<string> {\n for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = generateShortId()\n if (!(await this.dependencies.posts.findByShortId({ companyId, shortId: candidate }))) return candidate\n }\n throw new Error('content-module: sem id curto livre')\n }\n\n protected readingTime(body: string): number {\n return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute)\n }\n\n protected async assertSlugAvailable(companyId: string, slug: string, ownId?: string): Promise<void> {\n const existing = await this.dependencies.posts.findBySlug({ companyId, slug })\n if (existing && existing.id !== ownId) throw new DuplicateSlugError(slug)\n }\n\n /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */\n protected async generateSlug(companyId: string, title: string): Promise<string> {\n return this.uniqueSlug(companyId, buildShortSlug(title, this.dependencies.config.slug) || FALLBACK_SLUG)\n }\n\n protected async uniqueSlug(companyId: string, base: string): Promise<string> {\n for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {\n const candidate = withSlugSuffix(base, attempt)\n if (!(await this.dependencies.posts.findBySlug({ companyId, slug: candidate }))) return candidate\n }\n return withSlugSuffix(base, Date.now())\n }\n}\n\nfunction optionalFields(\n input: Omit<UpdatePostInput, 'slug' | 'title' | 'body' | 'tags' | 'tagLabels'>,\n): Partial<NewPostRow> {\n const values: Partial<NewPostRow> = {}\n if (input.excerpt !== undefined) values.excerpt = input.excerpt || null\n if (input.coverImageUrl !== undefined) values.coverImageUrl = input.coverImageUrl || null\n if (input.coverImageAlt !== undefined) values.coverImageAlt = input.coverImageAlt || null\n if (input.authorName !== undefined) values.authorName = input.authorName || null\n if (input.seoTitle !== undefined) values.seoTitle = input.seoTitle || null\n if (input.seoDescription !== undefined) values.seoDescription = input.seoDescription || null\n if (input.canonicalUrl !== undefined) values.canonicalUrl = input.canonicalUrl || null\n return values\n}\n\nexport class CreatePostUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string; readonly input: CreatePostInput }): Promise<Post> {\n const input = createPostSchema.parse(params.input)\n const { companyId } = params\n if (input.slug) await this.assertSlugAvailable(companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(companyId, input.title))\n\n const row = await this.dependencies.posts\n .create({\n companyId,\n slug,\n shortId: await this.generateShortId(companyId),\n title: input.title,\n body: input.body,\n tags: normalizeTags(input.tags ?? []),\n tagLabels: buildTagLabels({ typed: input.tags ?? [], explicit: input.tagLabels }),\n status: POST_STATUS.DRAFT,\n readingTimeMinutes: this.readingTime(input.body),\n ...optionalFields(input),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(slug)\n throw error\n })\n\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class UpdatePostUseCase extends PostUseCaseBase {\n /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */\n async execute(params: PostReference & { readonly input: UpdatePostInput }): Promise<Post> {\n const input = updatePostSchema.parse(params.input)\n const existing = await this.findEditableOrFail(params)\n\n const values: Partial<NewPostRow> = optionalFields(input)\n if (input.title !== undefined) values.title = input.title\n if (input.body !== undefined) {\n values.body = input.body\n values.readingTimeMinutes = this.readingTime(input.body)\n }\n if (input.tags !== undefined || input.tagLabels !== undefined) {\n const tags = normalizeTags(input.tags ?? existing.tags)\n values.tags = tags\n values.tagLabels = buildTagLabels({\n typed: input.tags ?? tags,\n explicit: input.tagLabels,\n previous: existing.tagLabels,\n })\n }\n if (input.slug !== undefined && input.slug !== existing.slug) {\n await this.assertSlugAvailable(params.companyId, input.slug, existing.id)\n values.slug = input.slug\n // O endereço antigo continua abrindo o post: o host o redireciona ao canônico.\n await this.dependencies.posts.recordFormerSlug({\n companyId: params.companyId,\n postId: existing.id,\n slug: existing.slug,\n })\n }\n return this.save(params, values, POST_EVENT.UPDATED)\n }\n}\n\nexport class PublishPostUseCase extends PostUseCaseBase {\n /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */\n async execute(params: PostReference & { readonly input?: PublishPostInput }): Promise<Post> {\n const input = publishPostSchema.parse(params.input ?? {})\n const existing = await this.findEditableOrFail(params)\n if (existing.isTemplate) throw new TemplateNotPublishableError(params.id)\n const now = this.now()\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n const status = publishedAt > now ? POST_STATUS.SCHEDULED : POST_STATUS.PUBLISHED\n return this.save(params, { status, publishedAt }, POST_EVENT.PUBLISHED)\n }\n}\n\nexport class UnpublishPostUseCase extends PostUseCaseBase {\n /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */\n async execute(params: PostReference): Promise<Post> {\n await this.findEditableOrFail(params)\n return this.save(params, { status: POST_STATUS.DRAFT, publishedAt: null }, POST_EVENT.UNPUBLISHED)\n }\n}\n\nexport class ArchivePostUseCase extends PostUseCaseBase {\n /** \"Excluir\" no painel é arquivar: some do site, mas o conteúdo e o slug continuam guardados. */\n async execute(params: PostReference): Promise<Post> {\n await this.findOrFail(params)\n return this.save(params, { status: POST_STATUS.ARCHIVED }, POST_EVENT.ARCHIVED)\n }\n}\n\nexport class GetPostUseCase extends PostUseCaseBase {\n async execute(params: PostReference): Promise<Post> {\n const row = await this.findOrFail(params)\n const counts = await this.openReportCounts({ companyId: params.companyId, rows: [row] })\n return toPost(row, this.now(), counts.get(row.id) ?? 0)\n }\n}\n\nexport class ListPostsUseCase extends PostUseCaseBase {\n async execute(params: { readonly companyId: string } & Partial<ListPostsQuery>): Promise<Paginated<PostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPostsQuerySchema.parse(rawQuery)\n const { tag: rawTag, ...rest } = query\n const tags = rawTag ? normalizeTags(rawTag.split(',')) : []\n const now = this.now()\n const page = await this.dependencies.posts.listForAdmin({\n companyId,\n ...rest,\n isTemplate: query.isTemplate ?? false,\n now,\n ...(tags.length > 0 ? { tags } : {}),\n })\n const counts = await this.openReportCounts({ companyId, rows: page.rows })\n return {\n data: page.rows.map((row) => toPostSummary(row, now, counts.get(row.id) ?? 0)),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { randomInt } from 'node:crypto'\nimport { SHORT_ID_LENGTH } from '@adatechnology/content-contracts'\n\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\n\n/** 6 caracteres base36 (~2 bilhões): a colisão é checada contra a empresa antes de gravar. */\nexport function generateShortId(): string {\n let value = ''\n for (let index = 0; index < SHORT_ID_LENGTH; index += 1) value += ALPHABET[randomInt(ALPHABET.length)]\n return value\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nconst UNIQUE_VIOLATION = '23505'\n\n/**\n * Cada driver embrulha o erro do Postgres de um jeito (`code` direto, ou em `cause`). A checagem\n * prévia de slug não fecha a corrida entre dois saves simultâneos; o índice único fecha, e isto\n * traduz a violação para o 409 do domínio.\n */\nexport function isUniqueViolation(error: unknown): boolean {\n let current: unknown = error\n for (let depth = 0; depth < 3 && typeof current === 'object' && current !== null; depth += 1) {\n if ((current as { code?: unknown }).code === UNIQUE_VIOLATION) return true\n current = (current as { cause?: unknown }).cause\n }\n return false\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { Post, PostEventType } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/**\n * O gancho do host roda depois da escrita, e falha nele não desfaz o que já foi gravado: o post\n * publicado continua publicado mesmo que a purga de cache do host caia. Por isso o catch local.\n */\nexport async function notifyPostChanged(\n dependencies: ContentDependencies,\n type: PostEventType,\n post: Post,\n): Promise<void> {\n const hook = dependencies.hooks?.onPostChanged\n if (!hook) return\n try {\n await hook({ type, post })\n } catch (error) {\n dependencies.logger?.error('content-module: hook onPostChanged falhou', {\n postId: post.id,\n type,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n communityRevisionSchema,\n POST_ORIGIN,\n POST_STATUS,\n type CommunityPost,\n type CommunityPostStatus,\n type CommunityRevision,\n type Pagination,\n type Post,\n type PostOrigin,\n type PostReport,\n type PostStatus,\n type PostSummary,\n type PublicPost,\n type PublicPostSummary,\n} from '@adatechnology/content-contracts'\n\nimport type { PostReportRow, PostRow } from '../schema/schema'\n\n/** Agendado cuja hora já passou é publicado: o painel mostra o estado que o leitor vê. */\nexport function effectiveStatus(row: PostRow, now: Date): PostStatus {\n if (row.status === POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS.PUBLISHED\n return row.status as PostStatus\n}\n\n// A coluna é jsonb livre: forma inválida vira ausência em vez de derrubar a listagem inteira.\nexport function readPendingRevision(row: PostRow): CommunityRevision | null {\n if (row.pendingRevision === null || row.pendingRevision === undefined) return null\n const parsed = communityRevisionSchema.safeParse(row.pendingRevision)\n return parsed.success ? parsed.data : null\n}\n\nexport function toPostSummary(row: PostRow, now: Date, openReportCount = 0): PostSummary {\n return {\n id: row.id,\n companyId: row.companyId,\n slug: row.slug,\n shortId: row.shortId,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n tagLabels: row.tagLabels,\n status: effectiveStatus(row, now),\n isTemplate: row.isTemplate,\n publishedAt: row.publishedAt?.toISOString() ?? null,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n origin: row.origin as PostOrigin,\n authorAccountId: row.authorAccountId,\n authorDisplayName: row.authorDisplayName,\n authorReferenceMonth: row.authorReferenceMonth,\n reviewNote: row.reviewNote,\n termsAcceptedAt: row.termsAcceptedAt?.toISOString() ?? null,\n submittedAt: row.submittedAt?.toISOString() ?? null,\n pendingRevision: readPendingRevision(row),\n openReportCount,\n }\n}\n\nexport function toPost(row: PostRow, now: Date, openReportCount = 0): Post {\n return { ...toPostSummary(row, now, openReportCount), body: row.body }\n}\n\nfunction toCommunityAuthor(row: PostRow): PublicPostSummary['communityAuthor'] {\n if (row.origin !== POST_ORIGIN.COMMUNITY) return null\n return { displayName: row.authorDisplayName ?? '', referenceMonth: row.authorReferenceMonth }\n}\n\n/** Só chamado sobre linha que passou pela condição pública — `publishedAt` existe. */\nexport function toPublicPostSummary(row: PostRow): PublicPostSummary {\n return {\n id: row.id,\n slug: row.slug,\n shortId: row.shortId,\n title: row.title,\n excerpt: row.excerpt,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: row.tags,\n tagLabels: row.tagLabels,\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n canonicalUrl: row.canonicalUrl,\n readingTimeMinutes: row.readingTimeMinutes,\n origin: row.origin as PostOrigin,\n communityAuthor: toCommunityAuthor(row),\n }\n}\n\nexport function toPublicPost(row: PostRow): PublicPost {\n return { ...toPublicPostSummary(row), body: row.body }\n}\n\nexport function toPagination(params: { total: number; page: number; pageSize: number }): Pagination {\n return { ...params, totalPages: Math.max(1, Math.ceil(params.total / params.pageSize)) }\n}\n\n/** Visão do próprio autor: sem `archived` (nunca chega aqui) nem campos de operação. */\nexport function toCommunityPost(row: PostRow): CommunityPost {\n return {\n id: row.id,\n shortId: row.shortId,\n slug: row.slug,\n title: row.title,\n excerpt: row.excerpt,\n body: row.body,\n coverImageUrl: row.coverImageUrl,\n status: row.status as CommunityPostStatus,\n displayName: row.authorDisplayName ?? '',\n reviewNote: row.reviewNote,\n pendingRevision: readPendingRevision(row),\n publishedAt: row.publishedAt?.toISOString() ?? null,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n }\n}\n\nexport function toPostReport(row: PostReportRow): PostReport {\n return {\n id: row.id,\n postId: row.postId,\n reason: row.reason,\n createdAt: row.createdAt.toISOString(),\n resolvedAt: row.resolvedAt?.toISOString() ?? null,\n resolvedBy: row.resolvedBy,\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n CommunityDailyLimitError,\n createCommunityPostSchema,\n DuplicateSlugError,\n POST_EVENT,\n POST_ORIGIN,\n POST_STATUS,\n type CommunityPost,\n} from '@adatechnology/content-contracts'\n\nimport { isUniqueViolation } from '../../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../../shared/notifyPostChanged'\nimport { toCommunityPost, toPost } from '../../shared/toContract'\nimport type { CreateCommunityPostParams } from '../types/community.types'\nimport { CommunityUseCaseBase } from './CommunityUseCaseBase'\n\nconst MIN_RETRY_SECONDS = 1\n\nexport class CreateCommunityPostUseCase extends CommunityUseCaseBase {\n async execute(params: CreateCommunityPostParams): Promise<CommunityPost> {\n const { author } = params\n const input = createCommunityPostSchema.parse(params.input)\n const settings = await this.getSettings(author.companyId)\n const sources = await this.assertBodyImages({ author, body: input.body, settings })\n const slug = await this.generateSlug(author.companyId, input.title)\n const now = this.now()\n\n const outcome = await this.dependencies.community\n .createWithDailyLimit({\n accountId: author.accountId,\n limit: settings.communityDailyLimit,\n now,\n values: {\n companyId: author.companyId,\n slug,\n shortId: await this.generateShortId(author.companyId),\n title: input.title,\n body: input.body,\n excerpt: input.excerpt || null,\n coverImageUrl: sources[0] ?? null,\n status: POST_STATUS.DRAFT,\n origin: POST_ORIGIN.COMMUNITY,\n authorAccountId: author.accountId,\n authorDisplayName: input.displayName ?? author.defaultDisplayName,\n readingTimeMinutes: this.readingTime(input.body),\n createdAt: now,\n updatedAt: now,\n },\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(slug)\n throw error\n })\n\n if (outcome.isLimited) {\n const seconds = Math.ceil((outcome.freesUpAt.getTime() - now.getTime()) / 1000)\n throw new CommunityDailyLimitError(settings.communityDailyLimit, Math.max(MIN_RETRY_SECONDS, seconds))\n }\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, toPost(outcome.row, now))\n return toCommunityPost(outcome.row)\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Base dos casos de uso do hóspede: busca por dono (post alheio é 404, não revela existência),\n * validação das fotos do corpo e gravação com o aviso `onPostChanged`.\n */\n\nimport {\n collectImageSources,\n CommunityImageNotAllowedError,\n CommunityTooManyImagesError,\n parseMarkdown,\n POST_ORIGIN,\n POST_STATUS,\n PostNotFoundError,\n type ContentSettings,\n type PostEventType,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../../schema/schema'\nimport { notifyPostChanged } from '../../shared/notifyPostChanged'\nimport { toPost } from '../../shared/toContract'\nimport { PostUseCaseBase } from '../Post.use-cases'\nimport type { CommunityAuthorContext, CommunityDependencies } from '../types/community.types'\n\nexport abstract class CommunityUseCaseBase extends PostUseCaseBase {\n constructor(protected override readonly dependencies: CommunityDependencies) {\n super(dependencies)\n }\n\n protected getSettings(companyId: string): Promise<ContentSettings> {\n return this.dependencies.community.getSettings({ companyId })\n }\n\n protected async findOwned(author: CommunityAuthorContext, id: string): Promise<PostRow> {\n const row = await this.dependencies.posts.findById({ companyId: author.companyId, id })\n const isOwned =\n row?.origin === POST_ORIGIN.COMMUNITY &&\n row.authorAccountId === author.accountId &&\n row.status !== POST_STATUS.ARCHIVED\n if (!row || !isOwned) throw new PostNotFoundError(id)\n return row\n }\n\n protected async persist(params: {\n readonly author: CommunityAuthorContext\n readonly id: string\n readonly values: Partial<NewPostRow>\n readonly event: PostEventType\n }): Promise<PostRow> {\n const { author, id, values, event } = params\n const row = await this.dependencies.posts.update({ companyId: author.companyId, id, values })\n if (!row) throw new PostNotFoundError(id)\n await notifyPostChanged(this.dependencies, event, toPost(row, this.now()))\n return row\n }\n\n /** Só foto enviada por esta conta, nesta empresa, entra no corpo: URL externa seria rastreio sem moderação. */\n protected async assertBodyImages(params: {\n readonly author: CommunityAuthorContext\n readonly body: string\n readonly settings: ContentSettings\n }): Promise<readonly string[]> {\n const sources = collectImageSources(parseMarkdown(params.body))\n if (sources.length > params.settings.maxImagesPerPost) {\n throw new CommunityTooManyImagesError(params.settings.maxImagesPerPost)\n }\n const unique = [...new Set(sources)]\n const owned = await this.dependencies.community.findOwnedImageUrls({\n companyId: params.author.companyId,\n accountId: params.author.accountId,\n urls: unique,\n })\n if (owned.length !== unique.length) throw new CommunityImageNotAllowedError()\n return sources\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Excluir é arquivar anonimizado: o texto, o nome e a capa somem, mas a linha fica para reservar o\n * slug (link já compartilhado) e para continuar contando no limite diário (apagar e recriar não o burla).\n */\n\nimport { POST_EVENT, POST_STATUS } from '@adatechnology/content-contracts'\n\nimport type { NewPostRow } from '../../schema/schema'\nimport { ANONYMIZED_TITLE } from '../../shared/community.constant'\nimport type { DeleteOwnCommunityPostParams } from '../types/community.types'\nimport { CommunityUseCaseBase } from './CommunityUseCaseBase'\n\nconst ANONYMIZED_VALUES: Partial<NewPostRow> = {\n status: POST_STATUS.ARCHIVED,\n title: ANONYMIZED_TITLE,\n body: '',\n excerpt: null,\n coverImageUrl: null,\n coverImageAlt: null,\n authorDisplayName: null,\n pendingRevision: null,\n reviewNote: null,\n readingTimeMinutes: 1,\n}\n\nexport class DeleteOwnCommunityPostUseCase extends CommunityUseCaseBase {\n async execute(params: DeleteOwnCommunityPostParams): Promise<void> {\n await this.findOwned(params.author, params.id)\n await this.persist({\n author: params.author,\n id: params.id,\n values: ANONYMIZED_VALUES,\n event: POST_EVENT.ARCHIVED,\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { POST_LIMITS, type CommunityPost, type Paginated } from '@adatechnology/content-contracts'\n\nimport { toCommunityPost, toPagination } from '../../shared/toContract'\nimport type { GetOwnCommunityPostParams, ListOwnCommunityPostsParams } from '../types/community.types'\nimport { CommunityUseCaseBase } from './CommunityUseCaseBase'\n\nconst DEFAULT_PAGE_SIZE = 20\n\nexport class ListOwnCommunityPostsUseCase extends CommunityUseCaseBase {\n async execute(params: ListOwnCommunityPostsParams): Promise<Paginated<CommunityPost>> {\n const page = Math.max(1, Math.trunc(params.page ?? 1))\n const pageSize = Math.min(\n POST_LIMITS.PUBLIC_PAGE_SIZE,\n Math.max(1, Math.trunc(params.pageSize ?? DEFAULT_PAGE_SIZE)),\n )\n const result = await this.dependencies.community.listByAuthor({\n companyId: params.author.companyId,\n accountId: params.author.accountId,\n page,\n pageSize,\n })\n return {\n data: result.rows.map(toCommunityPost),\n pagination: toPagination({ total: result.total, page, pageSize }),\n }\n }\n}\n\nexport class GetOwnCommunityPostUseCase extends CommunityUseCaseBase {\n async execute(params: GetOwnCommunityPostParams): Promise<CommunityPost> {\n return toCommunityPost(await this.findOwned(params.author, params.id))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Decisões da equipe (máquina de estados do design, coluna \"equipe\"). Célula sem ação é\n * `InvalidPostTransitionError` (409). Aprovar uma revisão copia o texto novo para as colunas vivas\n * e só então o público passa a ler a versão nova; recusar uma revisão deixa o post no ar como está.\n */\n\nimport {\n collectImageSources,\n COMMUNITY_REVISION_STATE,\n InvalidPostTransitionError,\n parseMarkdown,\n POST_EVENT,\n POST_STATUS,\n rejectPostSchema,\n unpublishCommunityPostSchema,\n type CommunityRevision,\n type Post,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow } from '../../schema/schema'\nimport { COMMUNITY_ACTION } from '../../shared/community.constant'\nimport { toPost } from '../../shared/toContract'\nimport type {\n ModerateCommunityPostParams,\n RejectCommunityPostParams,\n UnpublishCommunityPostParams,\n} from '../types/community.types'\nimport { CommunityModerationUseCaseBase } from './CommunityModerationUseCaseBase'\n\nexport class ApproveCommunityPostUseCase extends CommunityModerationUseCaseBase {\n async execute(params: ModerateCommunityPostParams): Promise<Post> {\n const row = await this.findCommunityPost(params)\n const { actorUserId } = params\n if (row.status === POST_STATUS.PENDING_REVIEW) {\n const values = { status: POST_STATUS.PUBLISHED, publishedAt: this.now(), reviewNote: null, pendingRevision: null }\n return this.decide({\n row,\n values,\n event: POST_EVENT.PUBLISHED,\n decision: 'approved',\n target: 'post',\n actorUserId,\n })\n }\n const revision = this.openRevision(row)\n if (row.status === POST_STATUS.PUBLISHED && revision) {\n const values = this.revisionValues(revision)\n return this.decide({\n row,\n values,\n event: POST_EVENT.UPDATED,\n decision: 'approved',\n target: 'revision',\n actorUserId,\n })\n }\n throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.APPROVE)\n }\n\n private revisionValues(revision: CommunityRevision): Partial<NewPostRow> {\n return {\n title: revision.title,\n excerpt: revision.excerpt,\n body: revision.body,\n readingTimeMinutes: this.readingTime(revision.body),\n coverImageUrl: collectImageSources(parseMarkdown(revision.body))[0] ?? null,\n pendingRevision: null,\n reviewNote: null,\n }\n }\n}\n\nexport class RejectCommunityPostUseCase extends CommunityModerationUseCaseBase {\n async execute(params: RejectCommunityPostParams): Promise<Post> {\n const { note } = rejectPostSchema.parse(params.input)\n const row = await this.findCommunityPost(params)\n const { actorUserId } = params\n if (row.status === POST_STATUS.PENDING_REVIEW) {\n const values = { status: POST_STATUS.REJECTED, reviewNote: note }\n return this.decide({ row, values, event: POST_EVENT.UPDATED, decision: 'rejected', target: 'post', actorUserId })\n }\n const revision = this.openRevision(row)\n if (row.status === POST_STATUS.PUBLISHED && revision) {\n const values = { pendingRevision: { ...revision, state: COMMUNITY_REVISION_STATE.REJECTED }, reviewNote: note }\n return this.decide({\n row,\n values,\n event: POST_EVENT.UPDATED,\n decision: 'rejected',\n target: 'revision',\n actorUserId,\n })\n }\n throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.REJECT)\n }\n}\n\nexport class UnpublishCommunityPostUseCase extends CommunityModerationUseCaseBase {\n /** Tira do ar sem apagar: o autor vê a nota e pode editar e reenviar. A revisão aberta some junto. */\n async execute(params: UnpublishCommunityPostParams): Promise<Post> {\n const { note } = unpublishCommunityPostSchema.parse(params.input ?? {})\n const row = await this.findCommunityPost(params)\n if (row.status !== POST_STATUS.PUBLISHED) {\n throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.UNPUBLISH)\n }\n const values = { status: POST_STATUS.REJECTED, reviewNote: note ?? null, pendingRevision: null }\n return this.decide({\n row,\n values,\n event: POST_EVENT.UNPUBLISHED,\n decision: 'unpublished',\n target: 'post',\n actorUserId: params.actorUserId,\n })\n }\n}\n\nexport class ArchiveCommunityPostUseCase extends CommunityModerationUseCaseBase {\n /** Idempotente: já arquivado devolve o post sem gravar nem avisar de novo. */\n async execute(params: ModerateCommunityPostParams): Promise<Post> {\n const row = await this.findCommunityPost(params)\n if (row.status === POST_STATUS.ARCHIVED) return toPost(row, this.now())\n return this.decide({\n row,\n values: { status: POST_STATUS.ARCHIVED, pendingRevision: null },\n event: POST_EVENT.ARCHIVED,\n decision: 'archived',\n target: 'post',\n actorUserId: params.actorUserId,\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Base das ações da equipe sobre post da comunidade: só enxerga origem `community` (um post da equipe\n * responde 404 aqui) e toda decisão gravada avisa `onPostChanged` e `onCommunityPostReviewed`.\n */\n\nimport {\n COMMUNITY_REVISION_STATE,\n POST_ORIGIN,\n PostNotFoundError,\n type CommunityReviewDecision,\n type CommunityReviewTarget,\n type Post,\n type PostEventType,\n type PostStatus,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../../schema/schema'\nimport { notifyCommunityPostReviewed } from '../../shared/notifyCommunityPostReviewed'\nimport { notifyPostChanged } from '../../shared/notifyPostChanged'\nimport { readPendingRevision, toPost } from '../../shared/toContract'\nimport { PostUseCaseBase, type PostReference } from '../Post.use-cases'\nimport type { CommunityDependencies } from '../types/community.types'\n\nexport type ReviewDecisionParams = {\n readonly row: PostRow\n readonly values: Partial<NewPostRow>\n readonly event: PostEventType\n readonly decision: CommunityReviewDecision\n readonly target: CommunityReviewTarget\n readonly actorUserId: string\n}\n\nexport abstract class CommunityModerationUseCaseBase extends PostUseCaseBase {\n constructor(protected override readonly dependencies: CommunityDependencies) {\n super(dependencies)\n }\n\n protected async findCommunityPost(reference: PostReference): Promise<PostRow> {\n const row = await this.dependencies.posts.findById(reference)\n if (!row || row.origin !== POST_ORIGIN.COMMUNITY) throw new PostNotFoundError(reference.id)\n return row\n }\n\n /** Revisão que ainda espera decisão; uma já recusada não volta para a fila. */\n protected openRevision(row: PostRow): ReturnType<typeof readPendingRevision> {\n const revision = readPendingRevision(row)\n return revision?.state === COMMUNITY_REVISION_STATE.PENDING ? revision : null\n }\n\n protected async decide(params: ReviewDecisionParams): Promise<Post> {\n const { row, values, event, decision, target, actorUserId } = params\n const updated = await this.dependencies.posts.update({ companyId: row.companyId, id: row.id, values })\n if (!updated) throw new PostNotFoundError(row.id)\n const post = toPost(updated, this.now())\n await notifyPostChanged(this.dependencies, event, post)\n await notifyCommunityPostReviewed(this.dependencies, {\n companyId: row.companyId,\n postId: row.id,\n authorAccountId: row.authorAccountId ?? '',\n decision,\n target,\n actorUserId,\n statusBefore: row.status as PostStatus,\n statusAfter: updated.status as PostStatus,\n })\n return post\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { CommunityPostReviewedEvent } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/** Mesma regra de `notifyPostChanged`: a decisão já foi gravada, falha no aviso ao autor não a desfaz. */\nexport async function notifyCommunityPostReviewed(\n dependencies: ContentDependencies,\n event: CommunityPostReviewedEvent,\n): Promise<void> {\n const hook = dependencies.hooks?.onCommunityPostReviewed\n if (!hook) return\n try {\n await hook(event)\n } catch (error) {\n dependencies.logger?.error('content-module: hook onCommunityPostReviewed falhou', {\n postId: event.postId,\n decision: event.decision,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Lote de moderação: cada id segue sozinho (`Promise.allSettled`), então um id inválido não derruba\n * os outros e o resultado diz, por id, o que falhou e por quê.\n */\n\nimport {\n bulkModerationSchema,\n ContentError,\n rejectPostSchema,\n type BulkModerationAction,\n type BulkModerationResult,\n} from '@adatechnology/content-contracts'\n\nimport { BULK_UNEXPECTED_FAILURE } from '../../shared/community.constant'\nimport type {\n CommunityDependencies,\n ModerateCommunityPostParams,\n ModerateCommunityPostsInBulkParams,\n} from '../types/community.types'\nimport { CommunityModerationUseCaseBase } from './CommunityModerationUseCaseBase'\nimport {\n ApproveCommunityPostUseCase,\n ArchiveCommunityPostUseCase,\n RejectCommunityPostUseCase,\n UnpublishCommunityPostUseCase,\n} from './ModerateCommunityPost.use-cases'\n\ntype ItemAction = (params: ModerateCommunityPostParams, note: string | undefined) => Promise<unknown>\n\nexport class ModerateCommunityPostsInBulkUseCase extends CommunityModerationUseCaseBase {\n private readonly actions: Record<BulkModerationAction, ItemAction>\n\n constructor(dependencies: CommunityDependencies) {\n super(dependencies)\n const approve = new ApproveCommunityPostUseCase(dependencies)\n const reject = new RejectCommunityPostUseCase(dependencies)\n const unpublish = new UnpublishCommunityPostUseCase(dependencies)\n const archive = new ArchiveCommunityPostUseCase(dependencies)\n this.actions = {\n approve: (item) => approve.execute(item),\n reject: (item, note) => reject.execute({ ...item, input: { note: note ?? '' } }),\n unpublish: (item, note) => unpublish.execute({ ...item, ...(note ? { input: { note } } : {}) }),\n archive: (item) => archive.execute(item),\n }\n }\n\n async execute(params: ModerateCommunityPostsInBulkParams): Promise<BulkModerationResult> {\n const { action, ids, note } = bulkModerationSchema.parse(params.input)\n // Sem nota todos os ids falhariam igual: é erro do pedido, não de cada item.\n if (action === 'reject') rejectPostSchema.parse({ note })\n const uniqueIds = [...new Set(ids)]\n const settled = await Promise.allSettled(\n uniqueIds.map((id) =>\n this.actions[action]({ companyId: params.companyId, id, actorUserId: params.actorUserId }, note),\n ),\n )\n const succeeded: string[] = []\n const failed: { id: string; code: string; message: string }[] = []\n settled.forEach((result, index) => {\n const id = uniqueIds[index] ?? ''\n if (result.status === 'fulfilled') succeeded.push(id)\n else failed.push({ id, ...describeFailure(result.reason) })\n })\n return { succeeded, failed }\n }\n}\n\nfunction describeFailure(reason: unknown): { code: string; message: string } {\n if (reason instanceof ContentError) return { code: reason.code, message: reason.message }\n return BULK_UNEXPECTED_FAILURE\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Denúncia de leitor sobre post da comunidade no ar. Não guarda IP nem identidade de quem denunciou.\n */\n\nimport {\n createPostReportSchema,\n listPostReportsQuerySchema,\n POST_ORIGIN,\n PostNotFoundError,\n ReportNotFoundError,\n type Paginated,\n type PostReport,\n} from '@adatechnology/content-contracts'\n\nimport { notifyPostReported } from '../../shared/notifyPostReported'\nimport { toPagination, toPostReport } from '../../shared/toContract'\nimport { PostUseCaseBase } from '../Post.use-cases'\nimport type {\n CommunityDependencies,\n CreatePostReportParams,\n ListPostReportsParams,\n ResolvePostReportParams,\n} from '../types/community.types'\n\nabstract class PostReportUseCaseBase extends PostUseCaseBase {\n constructor(protected override readonly dependencies: CommunityDependencies) {\n super(dependencies)\n }\n}\n\nexport class CreatePostReportUseCase extends PostReportUseCaseBase {\n /** Só post da comunidade e público: qualquer outro caso é 404, para não revelar rascunho nem post da equipe. */\n async execute(params: CreatePostReportParams): Promise<PostReport> {\n const { reason } = createPostReportSchema.parse(params.input)\n const { companyId, postId } = params\n const now = this.now()\n const post = await this.dependencies.posts.findPublicById({ companyId, id: postId, now })\n if (!post || post.origin !== POST_ORIGIN.COMMUNITY) throw new PostNotFoundError(postId)\n const row = await this.dependencies.community.createReport({ companyId, postId, reason, now })\n await notifyPostReported(this.dependencies, { companyId, postId, reportId: row.id })\n return toPostReport(row)\n }\n}\n\nexport class ListPostReportsUseCase extends PostReportUseCaseBase {\n async execute(params: ListPostReportsParams): Promise<Paginated<PostReport>> {\n const { companyId, ...rawQuery } = params\n const query = listPostReportsQuerySchema.parse(rawQuery)\n const page = await this.dependencies.community.listReports({ companyId, ...query })\n return {\n data: page.rows.map(toPostReport),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n\nexport class ResolvePostReportUseCase extends PostReportUseCaseBase {\n /** Idempotente: resolver de novo devolve a denúncia como já estava. */\n async execute(params: ResolvePostReportParams): Promise<PostReport> {\n const row = await this.dependencies.community.resolveReport({ ...params, now: this.now() })\n if (!row) throw new ReportNotFoundError(params.id)\n return toPostReport(row)\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { PostReportedEvent } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/** Mesma regra de `notifyPostChanged`: a denúncia já foi gravada, falha no aviso da equipe não a desfaz. */\nexport async function notifyPostReported(dependencies: ContentDependencies, event: PostReportedEvent): Promise<void> {\n const hook = dependencies.hooks?.onPostReported\n if (!hook) return\n try {\n await hook(event)\n } catch (error) {\n dependencies.logger?.error('content-module: hook onPostReported falhou', {\n postId: event.postId,\n reportId: event.reportId,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Porta de entrada de toda requisição de comunidade: sem sessão é 401 e conta inelegível é 403.\n * A elegibilidade é conferida em TODA chamada, porque pode ser perdida depois da criação do post.\n */\n\nimport { CommunityAuthorNotEligibleError, CommunityUnauthenticatedError } from '@adatechnology/content-contracts'\n\nimport type {\n CommunityAuthorContext,\n CommunityDependencies,\n ResolveCommunityAuthorParams,\n} from '../types/community.types'\n\nexport class ResolveCommunityAuthorUseCase {\n constructor(private readonly dependencies: CommunityDependencies) {}\n\n async execute(params: ResolveCommunityAuthorParams): Promise<CommunityAuthorContext> {\n const port = this.dependencies.communityAuthor\n const identity = await port.resolveAuthor({ headers: params.headers })\n if (!identity) throw new CommunityUnauthenticatedError()\n const eligibility = await port.checkEligibility({ companyId: identity.companyId, accountId: identity.accountId })\n if (!eligibility.eligible) throw new CommunityAuthorNotEligibleError()\n return {\n companyId: identity.companyId,\n accountId: identity.accountId,\n defaultDisplayName: identity.defaultDisplayName,\n ...(eligibility.referenceMonth ? { referenceMonth: eligibility.referenceMonth } : {}),\n }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n COMMUNITY_MODERATION,\n CommunityTermsRequiredError,\n InvalidPostTransitionError,\n POST_EVENT,\n POST_STATUS,\n type CommunityPost,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../../schema/schema'\nimport { COMMUNITY_ACTION } from '../../shared/community.constant'\nimport { notifyCommunityPostSubmitted } from '../../shared/notifyCommunityPostSubmitted'\nimport { toCommunityPost } from '../../shared/toContract'\nimport type { SubmitCommunityPostParams } from '../types/community.types'\nimport { CommunityUseCaseBase } from './CommunityUseCaseBase'\n\nconst SUBMITTABLE_STATUSES: readonly string[] = [POST_STATUS.DRAFT, POST_STATUS.REJECTED]\n\nexport class SubmitCommunityPostUseCase extends CommunityUseCaseBase {\n async execute(params: SubmitCommunityPostParams): Promise<CommunityPost> {\n const { author, id } = params\n const row = await this.findOwned(author, id)\n if (params.termsAccepted !== true) throw new CommunityTermsRequiredError()\n if (!SUBMITTABLE_STATUSES.includes(row.status))\n throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.SUBMIT)\n\n const settings = await this.getSettings(author.companyId)\n // `after` publica só o primeiro envio: um post recusado já foi visto pela equipe e volta para a fila.\n const isPublishedNow =\n settings.communityModeration === COMMUNITY_MODERATION.AFTER && row.status === POST_STATUS.DRAFT\n const now = this.now()\n const values: Partial<NewPostRow> = {\n status: isPublishedNow ? POST_STATUS.PUBLISHED : POST_STATUS.PENDING_REVIEW,\n termsAcceptedAt: now,\n submittedAt: now,\n reviewNote: null,\n ...(isPublishedNow ? { publishedAt: now } : {}),\n ...(row.authorReferenceMonth === null && author.referenceMonth\n ? { authorReferenceMonth: author.referenceMonth }\n : {}),\n }\n const updated = await this.persist({\n author,\n id,\n values,\n event: isPublishedNow ? POST_EVENT.PUBLISHED : POST_EVENT.UPDATED,\n })\n await this.notifySubmitted(updated, settings.communityModeration)\n return toCommunityPost(updated)\n }\n\n private notifySubmitted(\n row: PostRow,\n moderation: (typeof COMMUNITY_MODERATION)[keyof typeof COMMUNITY_MODERATION],\n ): Promise<void> {\n return notifyCommunityPostSubmitted(this.dependencies, {\n companyId: row.companyId,\n postId: row.id,\n authorAccountId: row.authorAccountId ?? '',\n kind: 'new',\n moderation,\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { CommunityPostSubmittedEvent } from '@adatechnology/content-contracts'\n\nimport type { ContentDependencies } from '../use-cases/contentModule.types'\n\n/** Mesma regra de `notifyPostChanged`: o envio já foi gravado, falha no aviso da equipe não o desfaz. */\nexport async function notifyCommunityPostSubmitted(\n dependencies: ContentDependencies,\n event: CommunityPostSubmittedEvent,\n): Promise<void> {\n const hook = dependencies.hooks?.onCommunityPostSubmitted\n if (!hook) return\n try {\n await hook(event)\n } catch (error) {\n dependencies.logger?.error('content-module: hook onCommunityPostSubmitted falhou', {\n postId: event.postId,\n kind: event.kind,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Editar um post publicado no modo `before` NÃO mexe no texto no ar: a edição vira `pendingRevision`\n * até a equipe aprovar. Nos outros casos (rascunho, em análise, recusado, ou `after`) vale o texto vivo.\n */\n\nimport {\n COMMUNITY_MODERATION,\n COMMUNITY_REVISION_STATE,\n POST_EVENT,\n POST_STATUS,\n updateCommunityPostSchema,\n type CommunityPost,\n type CommunityRevision,\n type ContentSettings,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../../schema/schema'\nimport { notifyCommunityPostSubmitted } from '../../shared/notifyCommunityPostSubmitted'\nimport { readPendingRevision, toCommunityPost } from '../../shared/toContract'\nimport type { UpdateOwnCommunityPostParams } from '../types/community.types'\nimport { CommunityUseCaseBase } from './CommunityUseCaseBase'\n\ntype ParsedUpdate = ReturnType<typeof updateCommunityPostSchema.parse>\n\nexport class UpdateOwnCommunityPostUseCase extends CommunityUseCaseBase {\n async execute(params: UpdateOwnCommunityPostParams): Promise<CommunityPost> {\n const { author, id } = params\n const input = updateCommunityPostSchema.parse(params.input)\n const row = await this.findOwned(author, id)\n const settings = await this.getSettings(author.companyId)\n const sources =\n input.body === undefined ? undefined : await this.assertBodyImages({ author, body: input.body, settings })\n\n const isPublished = row.status === POST_STATUS.PUBLISHED\n const isRevision = isPublished && settings.communityModeration === COMMUNITY_MODERATION.BEFORE\n const values = isRevision ? this.revisionValues(row, input) : this.liveValues(row, input, sources)\n const updated = await this.persist({ author, id, values, event: POST_EVENT.UPDATED })\n\n if (isPublished) await this.notifyRevision({ row: updated, settings })\n return toCommunityPost(updated)\n }\n\n private liveValues(row: PostRow, input: ParsedUpdate, sources: readonly string[] | undefined): Partial<NewPostRow> {\n const values: Partial<NewPostRow> = {}\n if (input.title !== undefined) values.title = input.title\n if (input.excerpt !== undefined) values.excerpt = input.excerpt || null\n if (input.displayName !== undefined) values.authorDisplayName = input.displayName\n if (input.body !== undefined) {\n values.body = input.body\n values.readingTimeMinutes = this.readingTime(input.body)\n values.coverImageUrl = sources?.[0] ?? null\n }\n return values\n }\n\n /** O nome exibido não entra na revisão (o contrato dela não o carrega): trocar o nome de um post no ar passa pela equipe numa próxima fase. */\n private revisionValues(row: PostRow, input: ParsedUpdate): Partial<NewPostRow> {\n const open = readPendingRevision(row)\n const base: Pick<CommunityRevision, 'title' | 'excerpt' | 'body'> =\n open?.state === COMMUNITY_REVISION_STATE.PENDING ? open : row\n const now = this.now()\n const revision: CommunityRevision = {\n title: input.title ?? base.title,\n excerpt: input.excerpt === undefined ? base.excerpt : input.excerpt || null,\n body: input.body ?? base.body,\n state: COMMUNITY_REVISION_STATE.PENDING,\n submittedAt: now.toISOString(),\n }\n return { pendingRevision: revision, submittedAt: now }\n }\n\n private async notifyRevision(params: { readonly row: PostRow; readonly settings: ContentSettings }): Promise<void> {\n await notifyCommunityPostSubmitted(this.dependencies, {\n companyId: params.row.companyId,\n postId: params.row.id,\n authorAccountId: params.row.authorAccountId ?? '',\n kind: 'revision',\n moderation: params.settings.communityModeration,\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Foto do hóspede: mesmas regras de formato e tamanho do upload da equipe, chave própria e registro em\n * `community_images` (só URL registrada pode entrar no corpo). O teto em 24 h acompanha o que o limite\n * diário de posts permite escrever: posts por dia × fotos por post.\n */\n\nimport { CommunityDailyLimitError } from '@adatechnology/content-contracts'\n\nimport { COMMUNITY_IMAGE_KEY_PREFIX, COMMUNITY_WINDOW_MS } from '../../shared/community.constant'\nimport type { UploadCommunityImageParams, UploadCommunityImageResult } from '../types/community.types'\nimport { UploadImageUseCase } from '../UploadImage.use-case'\nimport { CommunityUseCaseBase } from './CommunityUseCaseBase'\n\nexport class UploadCommunityImageUseCase extends CommunityUseCaseBase {\n private readonly uploadImage = new UploadImageUseCase(this.dependencies)\n\n async execute(params: UploadCommunityImageParams): Promise<UploadCommunityImageResult> {\n const { author } = params\n const now = this.now()\n await this.assertUnderDailyCap({ author, now })\n\n const uploaded = await this.uploadImage.execute({\n companyId: author.companyId,\n bytes: params.bytes,\n mimeType: params.mimeType,\n keyPrefix: COMMUNITY_IMAGE_KEY_PREFIX,\n })\n await this.dependencies.community.recordImage({\n companyId: author.companyId,\n accountId: author.accountId,\n storageKey: uploaded.key,\n url: uploaded.url,\n createdAt: now,\n })\n return uploaded\n }\n\n private async assertUnderDailyCap(params: {\n readonly author: UploadCommunityImageParams['author']\n readonly now: Date\n }): Promise<void> {\n const { author, now } = params\n const settings = await this.getSettings(author.companyId)\n const cap = settings.communityDailyLimit * settings.maxImagesPerPost\n const recent = await this.dependencies.community.listRecentImageDates({\n companyId: author.companyId,\n accountId: author.accountId,\n since: new Date(now.getTime() - COMMUNITY_WINDOW_MS),\n })\n const blocking = recent[recent.length - cap]\n if (recent.length < cap || !blocking) return\n const seconds = Math.ceil((blocking.getTime() + COMMUNITY_WINDOW_MS - now.getTime()) / 1000)\n throw new CommunityDailyLimitError(cap, Math.max(1, seconds))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Upload de imagem do post (capa ou foto no corpo). O bucket é do host (`ContentImageStoragePort`);\n * aqui ficam as decisões que não variam por instalação: formatos aceitos, teto de tamanho e forma da chave.\n */\n\nimport { ImageStorageDisabledError, InvalidCoverImageError } from '@adatechnology/content-contracts'\n\nimport { CONTENT_IMAGE } from '../shared/coverImage.constant'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport type UploadImageParams = {\n readonly companyId: string\n readonly bytes: Uint8Array\n readonly mimeType: string\n /** Pasta no bucket antes da empresa. Padrão: a dos posts da equipe. */\n readonly keyPrefix?: string\n}\n\nexport type UploadImageResult = { readonly url: string; readonly key: string }\n\nexport class UploadImageUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(params: UploadImageParams): Promise<UploadImageResult> {\n const storage = this.dependencies.imageStorage\n if (!storage) throw new ImageStorageDisabledError()\n\n const mimeType = (params.mimeType.split(';')[0] ?? '').trim().toLowerCase()\n // Lista fechada, não \"começa com image/\": SVG é imagem e carrega script.\n const extension = CONTENT_IMAGE.EXTENSION_BY_MIME[mimeType]\n if (!extension) throw new InvalidCoverImageError('unsupported_type')\n if (params.bytes.byteLength === 0) throw new InvalidCoverImageError('empty')\n if (params.bytes.byteLength > CONTENT_IMAGE.MAX_BYTES) throw new InvalidCoverImageError('too_large')\n\n // A chave nunca carrega nome de arquivo: é entrada de usuário e vai parar numa URL pública.\n const key = `${params.keyPrefix ?? CONTENT_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`\n return storage.upload({ buffer: params.bytes, mimeType, key })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * 1 MiB é o teto de corpo do `module-http`: um limite maior aqui seria promessa que a rota não\n * cumpre. O `content-ui` avisa antes de enviar; o servidor recusa de novo porque o cliente não é\n * fonte de verdade.\n */\nexport const CONTENT_IMAGE = {\n MAX_BYTES: 1024 * 1024,\n KEY_PREFIX: 'content/posts',\n EXTENSION_BY_MIME: {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n } as Readonly<Record<string, string | undefined>>,\n} as const\n\nexport const COVER_IMAGE = CONTENT_IMAGE\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { ContentDependencies } from '../contentModule.types'\nimport type { CommunityDependencies } from '../types/community.types'\nimport { GetContentSettingsUseCase, UpdateContentSettingsUseCase } from './ContentSettings.use-cases'\nimport { CreateCommunityPostUseCase } from './CreateCommunityPost.use-case'\nimport { DeleteOwnCommunityPostUseCase } from './DeleteOwnCommunityPost.use-case'\nimport { GetOwnCommunityPostUseCase, ListOwnCommunityPostsUseCase } from './ReadOwnCommunityPosts.use-cases'\nimport {\n ApproveCommunityPostUseCase,\n ArchiveCommunityPostUseCase,\n RejectCommunityPostUseCase,\n UnpublishCommunityPostUseCase,\n} from './ModerateCommunityPost.use-cases'\nimport { ModerateCommunityPostsInBulkUseCase } from './ModerateCommunityPostsInBulk.use-case'\nimport { CreatePostReportUseCase, ListPostReportsUseCase, ResolvePostReportUseCase } from './PostReport.use-cases'\nimport { ResolveCommunityAuthorUseCase } from './ResolveCommunityAuthor.use-case'\nimport { SubmitCommunityPostUseCase } from './SubmitCommunityPost.use-case'\nimport { UpdateOwnCommunityPostUseCase } from './UpdateOwnCommunityPost.use-case'\nimport { UploadCommunityImageUseCase } from './UploadCommunityImage.use-case'\n\nexport type CommunityUseCases = {\n readonly resolveCommunityAuthor: ResolveCommunityAuthorUseCase\n readonly listOwnCommunityPosts: ListOwnCommunityPostsUseCase\n readonly getOwnCommunityPost: GetOwnCommunityPostUseCase\n readonly createCommunityPost: CreateCommunityPostUseCase\n readonly updateOwnCommunityPost: UpdateOwnCommunityPostUseCase\n readonly submitCommunityPost: SubmitCommunityPostUseCase\n readonly deleteOwnCommunityPost: DeleteOwnCommunityPostUseCase\n readonly approveCommunityPost: ApproveCommunityPostUseCase\n readonly rejectCommunityPost: RejectCommunityPostUseCase\n readonly unpublishCommunityPost: UnpublishCommunityPostUseCase\n readonly archiveCommunityPost: ArchiveCommunityPostUseCase\n readonly moderateCommunityPostsInBulk: ModerateCommunityPostsInBulkUseCase\n readonly getContentSettings: GetContentSettingsUseCase\n readonly updateContentSettings: UpdateContentSettingsUseCase\n readonly createPostReport: CreatePostReportUseCase\n readonly listPostReports: ListPostReportsUseCase\n readonly resolvePostReport: ResolvePostReportUseCase\n /** Também exige `providers.imageStorage`. */\n readonly uploadCommunityImage?: UploadCommunityImageUseCase\n}\n\nexport function isCommunityEnabled(dependencies: ContentDependencies): dependencies is CommunityDependencies {\n return dependencies.communityAuthor !== undefined && dependencies.community !== undefined\n}\n\n/** Capacidade por ausência: sem a porta do autor, nenhum use case de comunidade existe. */\nexport function buildCommunityUseCases(dependencies: ContentDependencies): Partial<CommunityUseCases> {\n if (!isCommunityEnabled(dependencies)) return {}\n return {\n resolveCommunityAuthor: new ResolveCommunityAuthorUseCase(dependencies),\n listOwnCommunityPosts: new ListOwnCommunityPostsUseCase(dependencies),\n getOwnCommunityPost: new GetOwnCommunityPostUseCase(dependencies),\n createCommunityPost: new CreateCommunityPostUseCase(dependencies),\n updateOwnCommunityPost: new UpdateOwnCommunityPostUseCase(dependencies),\n submitCommunityPost: new SubmitCommunityPostUseCase(dependencies),\n deleteOwnCommunityPost: new DeleteOwnCommunityPostUseCase(dependencies),\n approveCommunityPost: new ApproveCommunityPostUseCase(dependencies),\n rejectCommunityPost: new RejectCommunityPostUseCase(dependencies),\n unpublishCommunityPost: new UnpublishCommunityPostUseCase(dependencies),\n archiveCommunityPost: new ArchiveCommunityPostUseCase(dependencies),\n moderateCommunityPostsInBulk: new ModerateCommunityPostsInBulkUseCase(dependencies),\n getContentSettings: new GetContentSettingsUseCase(dependencies),\n updateContentSettings: new UpdateContentSettingsUseCase(dependencies),\n createPostReport: new CreatePostReportUseCase(dependencies),\n listPostReports: new ListPostReportsUseCase(dependencies),\n resolvePostReport: new ResolvePostReportUseCase(dependencies),\n ...(dependencies.imageStorage ? { uploadCommunityImage: new UploadCommunityImageUseCase(dependencies) } : {}),\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * RSS, Atom e entradas de sitemap do site público, a partir de `config.feed`. Sem essa config os\n * use-cases nem são construídos e as rotas não sobem.\n */\n\nimport {\n buildAtomFeed,\n buildExcerpt,\n buildPostUrl,\n buildRssFeed,\n renderMarkdownToHtml,\n type ContentFeedConfig,\n type FeedChannel,\n type FeedItem,\n type SitemapEntry,\n} from '@adatechnology/content-contracts'\n\nimport type { PostRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nconst DEFAULT_ITEM_LIMIT = 20\n// O protocolo de sitemap aceita até 50 mil URLs por arquivo; blog real fica muito abaixo disso.\nconst SITEMAP_LIMIT = 50_000\n\nexport const FEED_FORMAT = { RSS: 'rss', ATOM: 'atom' } as const\nexport type FeedFormat = (typeof FEED_FORMAT)[keyof typeof FEED_FORMAT]\n\nexport class BuildFeedUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n async execute(params: {\n readonly companyId: string\n readonly format: FeedFormat\n readonly feedUrl?: string\n }): Promise<string> {\n const now = this.dependencies.clock.now()\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now,\n page: 1,\n pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT,\n })\n const channel: FeedChannel = {\n siteUrl: this.feed.siteUrl,\n title: this.feed.title,\n ...(this.feed.description ? { description: this.feed.description } : {}),\n ...(this.feed.language ? { language: this.feed.language } : {}),\n ...(params.feedUrl ? { feedUrl: params.feedUrl } : {}),\n }\n const items = page.rows.map((row) => this.toItem(row))\n return params.format === FEED_FORMAT.ATOM\n ? buildAtomFeed({ channel, items, now })\n : buildRssFeed({ channel, items })\n }\n\n private toItem(row: PostRow): FeedItem {\n return {\n title: row.title,\n url: buildPostUrl({\n siteUrl: this.feed.siteUrl,\n slug: row.slug,\n shortId: row.shortId,\n postPathTemplate: this.feed.postPathTemplate,\n }),\n publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n summary: row.excerpt ?? buildExcerpt(row.body),\n ...((this.feed.includeContent ?? true)\n ? { contentHtml: renderMarkdownToHtml(row.body, { headingIds: false }) }\n : {}),\n ...(row.authorName ? { authorName: row.authorName } : {}),\n categories: row.tags,\n ...(row.coverImageUrl ? { imageUrl: row.coverImageUrl } : {}),\n }\n }\n}\n\nexport class ListSitemapEntriesUseCase {\n constructor(\n private readonly dependencies: ContentDependencies,\n private readonly feed: ContentFeedConfig,\n ) {}\n\n /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */\n async execute(params: { readonly companyId: string }): Promise<readonly SitemapEntry[]> {\n const page = await this.dependencies.posts.listPublic({\n companyId: params.companyId,\n now: this.dependencies.clock.now(),\n page: 1,\n pageSize: SITEMAP_LIMIT,\n })\n return page.rows.map((row) => ({\n loc: buildPostUrl({\n siteUrl: this.feed.siteUrl,\n slug: row.slug,\n shortId: row.shortId,\n postPathTemplate: this.feed.postPathTemplate,\n }),\n lastmod: row.updatedAt.toISOString(),\n }))\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Leitura do site público. Só enxerga post publicado (ou agendado cuja hora chegou) da empresa\n * resolvida pelo host — rascunho, arquivado e agendado futuro respondem 404, igual a inexistente.\n */\n\nimport {\n listPublishedPostsQuerySchema,\n normalizeTag,\n parsePostRef,\n PostNotFoundError,\n type ListPublishedPostsQuery,\n type Paginated,\n type PublicPost,\n type PublicPostSummary,\n type TagCount,\n} from '@adatechnology/content-contracts'\n\nimport { toPagination, toPublicPost, toPublicPostSummary } from '../shared/toContract'\nimport type { ContentDependencies } from './contentModule.types'\n\nexport class GetPublishedPostBySlugUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /**\n * `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto\n * manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`\n * do resultado com o pedido e redireciona (301) quando forem diferentes.\n */\n async execute(params: { readonly companyId: string; readonly slug: string }): Promise<PublicPost> {\n const { posts, clock } = this.dependencies\n const parsed = parsePostRef(params.slug)\n const query = { companyId: params.companyId, now: clock.now() }\n const row =\n (parsed.shortId ? await posts.findPublicByShortId({ ...query, shortId: parsed.shortId }) : undefined) ??\n (await posts.findPublicBySlug({ ...query, slug: parsed.slug })) ??\n (await posts.findPublicByFormerSlug({ ...query, slug: parsed.slug }))\n if (!row) throw new PostNotFoundError(parsed.slug)\n return toPublicPost(row)\n }\n}\n\nexport class ListPublishedPostsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n async execute(\n params: { readonly companyId: string } & Partial<ListPublishedPostsQuery>,\n ): Promise<Paginated<PublicPostSummary>> {\n const { companyId, ...rawQuery } = params\n const query = listPublishedPostsQuerySchema.parse(rawQuery)\n const tag = query.tag ? normalizeTag(query.tag) : undefined\n const page = await this.dependencies.posts.listPublic({\n companyId,\n now: this.dependencies.clock.now(),\n page: query.page,\n pageSize: query.pageSize,\n origin: query.origin,\n ...(tag ? { tag } : {}),\n })\n return {\n data: page.rows.map(toPublicPostSummary),\n pagination: toPagination({ total: page.total, page: query.page, pageSize: query.pageSize }),\n }\n }\n}\n\nexport const TAG_SCOPE = { PUBLIC: 'public', ADMIN: 'admin' } as const\nexport type TagScope = (typeof TAG_SCOPE)[keyof typeof TAG_SCOPE]\n\nexport class ListTagsUseCase {\n constructor(private readonly dependencies: ContentDependencies) {}\n\n /** `public` conta só posts no ar; `admin` conta todos, para o autor reaproveitar a tag. */\n async execute(params: { readonly companyId: string; readonly scope: TagScope }): Promise<readonly TagCount[]> {\n return this.dependencies.posts.listTags({\n companyId: params.companyId,\n ...(params.scope === TAG_SCOPE.PUBLIC ? { publicAt: this.dependencies.clock.now() } : {}),\n })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Regras de recorrência do painel: cada regra publica, na frequência escolhida, um post novo copiado\n * de um modelo. Quem executa é o `publishDue`.\n */\n\nimport {\n createRecurrenceSchema,\n NotATemplateError,\n PostNotFoundError,\n RecurrenceNotFoundError,\n updateRecurrenceSchema,\n type CreateRecurrenceInput,\n type RecurrenceFrequency,\n type RecurrenceRule,\n type UpdateRecurrenceInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewRecurrenceRow, RecurrenceRow } from '../schema/schema'\nimport type { ContentDependencies } from './contentModule.types'\n\nabstract class RecurrenceUseCaseBase {\n constructor(protected readonly dependencies: ContentDependencies) {}\n\n protected async toRule(row: RecurrenceRow): Promise<RecurrenceRule> {\n const template = await this.dependencies.posts.findById({ companyId: row.companyId, id: row.templateId })\n return {\n id: row.id,\n companyId: row.companyId,\n templateId: row.templateId,\n templateTitle: template?.title ?? '',\n frequency: row.frequency as RecurrenceFrequency,\n isActive: row.isActive,\n nextRunAt: row.nextRunAt.toISOString(),\n lastRunAt: row.lastRunAt?.toISOString() ?? null,\n lastPostId: row.lastPostId,\n createdAt: row.createdAt.toISOString(),\n }\n }\n\n protected async findOrFail(params: { companyId: string; id: string }): Promise<RecurrenceRow> {\n const row = await this.dependencies.recurrences.findById(params)\n if (!row) throw new RecurrenceNotFoundError(params.id)\n return row\n }\n}\n\nexport class CreateRecurrenceUseCase extends RecurrenceUseCaseBase {\n async execute(params: {\n readonly companyId: string\n readonly input: CreateRecurrenceInput\n }): Promise<RecurrenceRule> {\n const input = createRecurrenceSchema.parse(params.input)\n const template = await this.dependencies.posts.findById({ companyId: params.companyId, id: input.templateId })\n if (!template) throw new PostNotFoundError(input.templateId)\n if (!template.isTemplate) throw new NotATemplateError(input.templateId)\n const startsAt = new Date(input.startsAt)\n const values: NewRecurrenceRow = {\n companyId: params.companyId,\n templateId: input.templateId,\n frequency: input.frequency,\n anchorDay: startsAt.getUTCDate(),\n nextRunAt: startsAt,\n }\n return this.toRule(await this.dependencies.recurrences.create(values))\n }\n}\n\nexport class ListRecurrencesUseCase extends RecurrenceUseCaseBase {\n async execute(params: { readonly companyId: string }): Promise<readonly RecurrenceRule[]> {\n const rows = await this.dependencies.recurrences.list(params)\n return Promise.all(rows.map((row) => this.toRule(row)))\n }\n}\n\nexport class UpdateRecurrenceUseCase extends RecurrenceUseCaseBase {\n /** Pausar/retomar e remarcar a próxima execução. */\n async execute(params: {\n readonly companyId: string\n readonly id: string\n readonly input: UpdateRecurrenceInput\n }): Promise<RecurrenceRule> {\n const input = updateRecurrenceSchema.parse(params.input)\n await this.findOrFail(params)\n const values: Partial<NewRecurrenceRow> = {}\n if (input.isActive !== undefined) values.isActive = input.isActive\n if (input.nextRunAt !== undefined) {\n values.nextRunAt = new Date(input.nextRunAt)\n values.anchorDay = values.nextRunAt.getUTCDate()\n }\n const row = await this.dependencies.recurrences.update({ companyId: params.companyId, id: params.id, values })\n if (!row) throw new RecurrenceNotFoundError(params.id)\n return this.toRule(row)\n }\n}\n\nexport class RemoveRecurrenceUseCase extends RecurrenceUseCaseBase {\n /** Apaga só a regra: os posts que ela já publicou continuam no ar. */\n async execute(params: { readonly companyId: string; readonly id: string }): Promise<void> {\n if (!(await this.dependencies.recurrences.remove(params))) throw new RecurrenceNotFoundError(params.id)\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Republicar e publicar no horário. `publishDue` é o que o host chama num intervalo: marca como\n * publicado o que estava agendado e já venceu, e materializa as recorrências vencidas.\n */\n\nimport {\n POST_EVENT,\n POST_STATUS,\n PostNotPublishedError,\n republishPostSchema,\n RepublishDateInFutureError,\n SLUG_MAX_LENGTH,\n slugify,\n type Post,\n type RepublishPostInput,\n} from '@adatechnology/content-contracts'\n\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { nextOccurrenceAfter, toDateStamp } from '../shared/recurrence'\nimport { effectiveStatus, toPost } from '../shared/toContract'\nimport type { RecurrenceRow } from '../schema/schema'\nimport { PostUseCaseBase, type PostReference } from './Post.use-cases'\nimport { copiableFields } from './Template.use-cases'\n\nconst DEFAULT_BATCH_LIMIT = 100\nconst DATE_SUFFIX_LENGTH = 11\nconst FALLBACK_SLUG = 'post'\n\nexport class RepublishPostUseCase extends PostUseCaseBase {\n /**\n * Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o\n * link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo\n * duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.\n */\n async execute(params: PostReference & { readonly input?: RepublishPostInput }): Promise<Post> {\n const input = republishPostSchema.parse(params.input ?? {})\n const existing = await this.findEditableOrFail(params)\n const now = this.now()\n if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS.PUBLISHED) {\n throw new PostNotPublishedError(params.id)\n }\n const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now\n if (publishedAt > now) throw new RepublishDateInFutureError()\n return this.save(params, { status: POST_STATUS.PUBLISHED, publishedAt }, POST_EVENT.REPUBLISHED)\n }\n}\n\nexport type PublishDueResult = { readonly published: number; readonly materialized: number }\n\nexport class PublishDueUseCase extends PostUseCaseBase {\n /**\n * Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado\n * por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.\n */\n async execute(params: { readonly now?: Date; readonly limit?: number } = {}): Promise<PublishDueResult> {\n const now = params.now ?? this.now()\n const limit = params.limit ?? DEFAULT_BATCH_LIMIT\n const materialized = await this.materializeRecurrences({ now, limit })\n const rows = await this.dependencies.posts.claimDueScheduled({ now, limit })\n for (const row of rows) {\n await notifyPostChanged(this.dependencies, POST_EVENT.PUBLISHED, toPost(row, now))\n }\n if (rows.length > 0 || materialized > 0) {\n this.dependencies.logger?.info('content-module: publishDue', { published: rows.length, materialized })\n }\n return { published: rows.length, materialized }\n }\n\n private materializeRecurrences(params: { now: Date; limit: number }): Promise<number> {\n return this.dependencies.recurrences.processDue({\n ...params,\n handle: (rule) => this.materialize(rule, params.now),\n })\n }\n\n /** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */\n private async materialize(rule: RecurrenceRow, now: Date): Promise<Partial<RecurrenceRow>> {\n const advance = {\n nextRunAt: nextOccurrenceAfter({\n frequency: rule.frequency as 'weekly' | 'monthly',\n from: rule.nextRunAt,\n anchorDay: rule.anchorDay,\n now,\n }),\n }\n const template = await this.dependencies.posts.findById({ companyId: rule.companyId, id: rule.templateId })\n if (!template || !template.isTemplate || template.status === POST_STATUS.ARCHIVED) {\n // Modelo apagado: a regra para de rodar em vez de falhar a cada ciclo.\n this.dependencies.logger?.warn('content-module: modelo da recorrência indisponível', { ruleId: rule.id })\n return { isActive: false }\n }\n const base = (slugify(template.title) || FALLBACK_SLUG).slice(0, SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH)\n const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, '')}-${toDateStamp(now)}`)\n const row = await this.dependencies.posts.create({\n ...copiableFields(template),\n companyId: rule.companyId,\n slug,\n shortId: await this.generateShortId(rule.companyId),\n title: template.title,\n isTemplate: false,\n status: POST_STATUS.PUBLISHED,\n publishedAt: now,\n })\n const post = toPost(row, now)\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n await notifyPostChanged(this.dependencies, POST_EVENT.PUBLISHED, post)\n return { ...advance, lastRunAt: now, lastPostId: row.id }\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Datas da recorrência, sempre em UTC: o instante de cada execução não depende do fuso do servidor.\n */\n\nimport { RECURRENCE_FREQUENCY, type RecurrenceFrequency } from '@adatechnology/content-contracts'\n\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000\n\nfunction daysInMonth(year: number, monthIndex: number): number {\n return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate()\n}\n\n/** Mensal no dia 31 cai em 28/29/30 nos meses curtos e VOLTA ao 31 depois (o âncora não deriva). */\nfunction addMonths(from: Date, anchorDay: number, months: number): Date {\n const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1))\n const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()))\n return new Date(\n Date.UTC(\n target.getUTCFullYear(),\n target.getUTCMonth(),\n day,\n from.getUTCHours(),\n from.getUTCMinutes(),\n from.getUTCSeconds(),\n from.getUTCMilliseconds(),\n ),\n )\n}\n\nexport function nextOccurrence(params: { frequency: RecurrenceFrequency; from: Date; anchorDay: number }): Date {\n if (params.frequency === RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS)\n return addMonths(params.from, params.anchorDay, 1)\n}\n\n/**\n * Primeira ocorrência estritamente depois de `now`. Servidor parado três semanas publica UM post ao\n * voltar, não três: as ocorrências perdidas são puladas, nunca emitidas em rajada.\n */\nexport function nextOccurrenceAfter(params: {\n frequency: RecurrenceFrequency\n from: Date\n anchorDay: number\n now: Date\n}): Date {\n let candidate = nextOccurrence(params)\n while (candidate <= params.now) candidate = nextOccurrence({ ...params, from: candidate })\n return candidate\n}\n\nexport function toDateStamp(date: Date): string {\n return date.toISOString().slice(0, 10)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Modelos de post: salvar um post como modelo e criar um post novo a partir de um modelo. Modelo é\n * post com `isTemplate`: nunca vai ao ar, não aparece na lista de posts e não tem endereço público.\n */\n\nimport {\n createFromTemplateSchema,\n DuplicateSlugError,\n normalizeTags,\n NotATemplateError,\n POST_EVENT,\n POST_STATUS,\n saveAsTemplateSchema,\n type CreateFromTemplateInput,\n type Post,\n type PostCounts,\n type SaveAsTemplateInput,\n} from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { isUniqueViolation } from '../shared/isUniqueViolation'\nimport { notifyPostChanged } from '../shared/notifyPostChanged'\nimport { toPost } from '../shared/toContract'\nimport { PostUseCaseBase, type PostReference } from './Post.use-cases'\n\nconst TEMPLATE_SLUG_PREFIX = 'modelo'\n\n/**\n * Conteúdo reaproveitável de um post. `canonicalUrl` NÃO é copiado: o canonical do original apontaria\n * o buscador para outra página e esconderia o post novo.\n */\nexport function copiableFields(row: PostRow): Partial<NewPostRow> {\n return {\n excerpt: row.excerpt,\n body: row.body,\n coverImageUrl: row.coverImageUrl,\n coverImageAlt: row.coverImageAlt,\n tags: normalizeTags(row.tags),\n tagLabels: row.tagLabels,\n authorName: row.authorName,\n seoTitle: row.seoTitle,\n seoDescription: row.seoDescription,\n readingTimeMinutes: row.readingTimeMinutes,\n }\n}\n\nabstract class TemplateUseCaseBase extends PostUseCaseBase {\n protected async insertCopy(params: {\n readonly companyId: string\n readonly slug: string\n readonly title: string\n readonly source: PostRow\n readonly isTemplate: boolean\n readonly status?: string\n readonly publishedAt?: Date\n }): Promise<Post> {\n const row = await this.dependencies.posts\n .create({\n ...copiableFields(params.source),\n companyId: params.companyId,\n slug: params.slug,\n shortId: await this.generateShortId(params.companyId),\n title: params.title,\n isTemplate: params.isTemplate,\n status: params.status ?? POST_STATUS.DRAFT,\n ...(params.publishedAt ? { publishedAt: params.publishedAt } : {}),\n })\n .catch((error: unknown) => {\n if (isUniqueViolation(error)) throw new DuplicateSlugError(params.slug)\n throw error\n })\n const post = toPost(row, this.now())\n await notifyPostChanged(this.dependencies, POST_EVENT.CREATED, post)\n return post\n }\n}\n\nexport class SaveAsTemplateUseCase extends TemplateUseCaseBase {\n /** Copia o post (qualquer status) para um modelo. O original não muda. */\n async execute(params: PostReference & { readonly input?: SaveAsTemplateInput }): Promise<Post> {\n const input = saveAsTemplateSchema.parse(params.input ?? {})\n const source = await this.findEditableOrFail(params)\n const title = input.title ?? source.title\n const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`)\n return this.insertCopy({ companyId: params.companyId, slug, title, source, isTemplate: true })\n }\n}\n\nexport class CreateFromTemplateUseCase extends TemplateUseCaseBase {\n /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */\n async execute(params: PostReference & { readonly input?: CreateFromTemplateInput }): Promise<Post> {\n const input = createFromTemplateSchema.parse(params.input ?? {})\n const template = await this.findEditableOrFail(params)\n if (!template.isTemplate) throw new NotATemplateError(params.id)\n const title = input.title ?? template.title\n if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug)\n const slug = input.slug ?? (await this.generateSlug(params.companyId, title))\n return this.insertCopy({ companyId: params.companyId, slug, title, source: template, isTemplate: false })\n }\n}\n\nexport class CountPostsUseCase extends PostUseCaseBase {\n /** Números das abas do painel, numa consulta só. */\n async execute(params: { readonly companyId: string }): Promise<PostCounts> {\n return this.dependencies.posts.countByStatus({ companyId: params.companyId, now: this.now() })\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Upload da capa: mesma regra do upload de imagem do corpo (`UploadImageUseCase`).\n */\n\nimport { UploadImageUseCase, type UploadImageParams, type UploadImageResult } from './UploadImage.use-case'\n\nexport type UploadCoverImageParams = UploadImageParams\nexport type UploadCoverImageResult = UploadImageResult\n\nexport class UploadCoverImageUseCase extends UploadImageUseCase {}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport {\n createFromTemplateSchema,\n createPostSchema,\n createRecurrenceSchema,\n DEFAULT_ADMIN_SCOPES,\n listPostsQuerySchema,\n publishPostSchema,\n republishPostSchema,\n saveAsTemplateSchema,\n updatePostSchema,\n updateRecurrenceSchema,\n type CreateFromTemplateInput,\n type CreatePostInput,\n type CreateRecurrenceInput,\n type ListPostsQuery,\n type PublishPostInput,\n type RepublishPostInput,\n type SaveAsTemplateInput,\n type UpdatePostInput,\n type UpdateRecurrenceInput,\n} from '@adatechnology/content-contracts'\nimport type { ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\nimport { buildModerationRoutes } from './moderationRoutes'\nimport { requireCompany } from './requireCompany'\n\nfunction reference(context: RequestContext): { companyId: string; id: string } {\n return { companyId: requireCompany(context), id: context.params.id ?? '' }\n}\n\nconst json = (status: number, data: unknown) => ({ kind: 'json' as const, status, body: { data } })\n\nexport function buildAdminRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES\n const admin = { scope: 'admin' as const, requiredScopes }\n\n const uploadRoutes: ModuleRoute[] = useCases.uploadCoverImage\n ? [\n {\n ...admin,\n method: 'POST',\n path: '/posts/cover-images',\n operationId: 'uploadPostCoverImage',\n summary: 'Envia a imagem de capa (bytes crus, Content-Type jpeg/png/webp) e devolve a URL',\n async handler(context) {\n const upload = useCases.uploadCoverImage\n if (!upload) return { kind: 'empty', status: 404 }\n const result = await upload.execute({\n companyId: requireCompany(context),\n bytes: context.rawBody ?? new Uint8Array(),\n mimeType: context.headers['content-type'] ?? '',\n })\n return json(201, result)\n },\n },\n ]\n : []\n\n const imageRoutes: ModuleRoute[] = useCases.uploadImage\n ? [\n {\n ...admin,\n method: 'POST',\n path: '/posts/images',\n operationId: 'uploadPostImage',\n summary: 'Envia uma foto do corpo do post (bytes crus, Content-Type jpeg/png/webp) e devolve a URL',\n async handler(context) {\n const upload = useCases.uploadImage\n if (!upload) return { kind: 'empty', status: 404 }\n const result = await upload.execute({\n companyId: requireCompany(context),\n bytes: context.rawBody ?? new Uint8Array(),\n mimeType: context.headers['content-type'] ?? '',\n })\n return json(201, result)\n },\n },\n ]\n : []\n\n return [\n {\n ...admin,\n method: 'GET',\n path: '/posts',\n querySchema: listPostsQuerySchema,\n operationId: 'listPosts',\n summary: 'Lista posts da empresa (todos os status), com filtro por status, tag e busca',\n async handler(context) {\n const result = await useCases.listPosts.execute({\n companyId: requireCompany(context),\n ...(context.query as unknown as ListPostsQuery),\n })\n return { kind: 'json', status: 200, body: result }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts',\n bodySchema: createPostSchema,\n operationId: 'createPost',\n summary: 'Cria um post como rascunho; sem slug, gera a partir do título',\n async handler(context) {\n const post = await useCases.createPost.execute({\n companyId: requireCompany(context),\n input: context.body as CreatePostInput,\n })\n return json(201, post)\n },\n },\n // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria \"tags\".\n {\n ...admin,\n method: 'GET',\n path: '/posts/tags',\n operationId: 'listPostTags',\n summary: 'Tags usadas em qualquer post da empresa, com contagem',\n async handler(context) {\n return json(\n 200,\n await useCases.listTags.execute({ companyId: requireCompany(context), scope: TAG_SCOPE.ADMIN }),\n )\n },\n },\n {\n ...admin,\n method: 'GET',\n path: '/posts/counts',\n operationId: 'countPosts',\n summary: 'Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos',\n async handler(context) {\n return json(200, await useCases.countPosts.execute({ companyId: requireCompany(context) }))\n },\n },\n ...recurrenceRoutes(module),\n ...uploadRoutes,\n ...imageRoutes,\n ...buildModerationRoutes(module),\n {\n ...admin,\n method: 'GET',\n path: '/posts/:id',\n operationId: 'getPost',\n summary: 'Lê um post da empresa (qualquer status)',\n async handler(context) {\n return json(200, await useCases.getPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/posts/:id',\n bodySchema: updatePostSchema,\n operationId: 'updatePost',\n summary: 'Atualiza campos de um post; trocar o título não troca o slug',\n async handler(context) {\n return json(\n 200,\n await useCases.updatePost.execute({ ...reference(context), input: context.body as UpdatePostInput }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/posts/:id',\n operationId: 'archivePost',\n summary: 'Arquiva o post: sai do site, conteúdo e slug continuam guardados',\n async handler(context) {\n await useCases.archivePost.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/publish',\n // Opcional: `POST /publish` sem corpo publica agora.\n bodySchema: publishPostSchema.optional(),\n operationId: 'publishPost',\n summary: 'Publica agora, ou agenda quando `publishedAt` é futuro',\n async handler(context) {\n return json(\n 200,\n await useCases.publishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as PublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/unpublish',\n operationId: 'unpublishPost',\n summary: 'Tira do ar (ou cancela o agendamento) e volta a rascunho',\n async handler(context) {\n return json(200, await useCases.unpublishPost.execute(reference(context)))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/republish',\n bodySchema: republishPostSchema.optional(),\n operationId: 'republishPost',\n summary: 'Republica um post no ar com nova data, mantendo o mesmo endereço (SEO); data futura é recusada',\n async handler(context) {\n return json(\n 200,\n await useCases.republishPost.execute({\n ...reference(context),\n input: (context.body ?? {}) as RepublishPostInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/save-as-template',\n bodySchema: saveAsTemplateSchema.optional(),\n operationId: 'savePostAsTemplate',\n summary: 'Copia o post para um modelo (o original não muda)',\n async handler(context) {\n return json(\n 201,\n await useCases.saveAsTemplate.execute({\n ...reference(context),\n input: (context.body ?? {}) as SaveAsTemplateInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/from-template',\n bodySchema: createFromTemplateSchema.optional(),\n operationId: 'createPostFromTemplate',\n summary: 'Cria um rascunho novo a partir do modelo `:id`',\n async handler(context) {\n return json(\n 201,\n await useCases.createFromTemplate.execute({\n ...reference(context),\n input: (context.body ?? {}) as CreateFromTemplateInput,\n }),\n )\n },\n },\n ]\n}\n\nfunction recurrenceRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const admin = { scope: 'admin' as const, requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES }\n return [\n {\n ...admin,\n method: 'GET',\n path: '/recurrences',\n operationId: 'listRecurrences',\n summary: 'Regras de recorrência da empresa',\n async handler(context) {\n return json(200, await useCases.listRecurrences.execute({ companyId: requireCompany(context) }))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/recurrences',\n bodySchema: createRecurrenceSchema,\n operationId: 'createRecurrence',\n summary: 'Cria regra: publica um post novo, copiado do modelo, toda semana ou todo mês',\n async handler(context) {\n return json(\n 201,\n await useCases.createRecurrence.execute({\n companyId: requireCompany(context),\n input: context.body as CreateRecurrenceInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'PATCH',\n path: '/recurrences/:id',\n bodySchema: updateRecurrenceSchema,\n operationId: 'updateRecurrence',\n summary: 'Pausa, retoma ou remarca a próxima execução',\n async handler(context) {\n return json(\n 200,\n await useCases.updateRecurrence.execute({\n ...reference(context),\n input: context.body as UpdateRecurrenceInput,\n }),\n )\n },\n },\n {\n ...admin,\n method: 'DELETE',\n path: '/recurrences/:id',\n operationId: 'removeRecurrence',\n summary: 'Apaga a regra; os posts já publicados por ela continuam no ar',\n async handler(context) {\n await useCases.removeRecurrence.execute(reference(context))\n return { kind: 'empty', status: 204 }\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas da equipe sobre a comunidade: moderação, configuração e denúncias. `adminScopes` como no resto\n * do painel; `companyId` e `actorUserId` vêm sempre do `auth`, nunca do corpo.\n */\n\nimport {\n bulkModerationSchema,\n contentSettingsSchema,\n DEFAULT_ADMIN_SCOPES,\n listPostReportsQuerySchema,\n rejectPostSchema,\n unpublishCommunityPostSchema,\n type BulkModerationInput,\n type ContentSettingsInput,\n type ListPostReportsQuery,\n type RejectPostInput,\n type UnpublishCommunityPostInput,\n} from '@adatechnology/content-contracts'\nimport type { ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { requireActor, requireCompany } from './requireCompany'\n\nconst json = (status: number, data: unknown) => ({ kind: 'json' as const, status, body: { data } })\n\nfunction staffTarget(context: RequestContext) {\n return { companyId: requireCompany(context), id: context.params.id ?? '', actorUserId: requireActor(context) }\n}\n\nexport function buildModerationRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n if (!useCases.approveCommunityPost) return []\n const admin = { scope: 'admin' as const, requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES }\n\n return [\n {\n ...admin,\n method: 'POST',\n path: '/posts/moderation',\n bodySchema: bulkModerationSchema,\n operationId: 'moderateCommunityPostsInBulk',\n summary: 'Aprova, recusa, tira do ar ou arquiva vários posts da comunidade; devolve o que falhou e por quê',\n async handler(context) {\n const result = await useCases.moderateCommunityPostsInBulk?.execute({\n companyId: requireCompany(context),\n actorUserId: requireActor(context),\n input: context.body as BulkModerationInput,\n })\n return json(200, result)\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/approve',\n operationId: 'approveCommunityPost',\n summary: 'Aprova o post em análise (publica) ou a revisão pendente de um publicado',\n async handler(context) {\n return json(200, await useCases.approveCommunityPost?.execute(staffTarget(context)))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/reject',\n bodySchema: rejectPostSchema,\n operationId: 'rejectCommunityPost',\n summary: 'Recusa o post (ou a revisão pendente) com uma nota que o autor lê',\n async handler(context) {\n const input = context.body as RejectPostInput\n return json(200, await useCases.rejectCommunityPost?.execute({ ...staffTarget(context), input }))\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/posts/:id/unpublish-community',\n bodySchema: unpublishCommunityPostSchema.optional(),\n operationId: 'unpublishCommunityPost',\n summary: 'Tira do ar um post publicado da comunidade sem apagar; o autor vê a nota e pode reenviar',\n async handler(context) {\n const input = context.body as UnpublishCommunityPostInput | undefined\n return json(\n 200,\n await useCases.unpublishCommunityPost?.execute({ ...staffTarget(context), ...(input ? { input } : {}) }),\n )\n },\n },\n ...settingsRoutes(module),\n ...reportRoutes(module),\n ]\n}\n\nfunction settingsRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const admin = { scope: 'admin' as const, requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES }\n return [\n {\n ...admin,\n method: 'GET',\n path: '/settings',\n operationId: 'getContentSettings',\n summary: 'Configuração da comunidade da empresa: moderação, limite diário e fotos por post',\n async handler(context) {\n return json(200, await useCases.getContentSettings?.execute({ companyId: requireCompany(context) }))\n },\n },\n {\n ...admin,\n method: 'PUT',\n path: '/settings',\n bodySchema: contentSettingsSchema,\n operationId: 'updateContentSettings',\n summary: 'Substitui a configuração da comunidade; vale para os próximos envios',\n async handler(context) {\n const input = context.body as ContentSettingsInput\n return json(200, await useCases.updateContentSettings?.execute({ companyId: requireCompany(context), input }))\n },\n },\n ]\n}\n\nfunction reportRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const admin = { scope: 'admin' as const, requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES }\n return [\n {\n ...admin,\n method: 'GET',\n path: '/reports',\n querySchema: listPostReportsQuerySchema,\n operationId: 'listPostReports',\n summary: 'Denúncias de posts da comunidade (abertas por padrão), com paginação',\n async handler(context) {\n const query = context.query as unknown as ListPostReportsQuery\n const result = await useCases.listPostReports?.execute({ companyId: requireCompany(context), ...query })\n return { kind: 'json', status: 200, body: result }\n },\n },\n {\n ...admin,\n method: 'POST',\n path: '/reports/:id/resolve',\n operationId: 'resolvePostReport',\n summary: 'Marca a denúncia como resolvida (repetir devolve a denúncia como está)',\n async handler(context) {\n return json(200, await useCases.resolvePostReport?.execute(staffTarget(context)))\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { CONTENT_ERROR_CODES, ContentError } from '@adatechnology/content-contracts'\nimport type { RequestContext } from '@adatechnology/module-http'\n\n/** `dispatchRoute` já recusa rota de admin sem identidade; isto só garante o tipo para o handler. */\nexport function requireCompany(context: RequestContext): string {\n if (!context.auth?.companyId) {\n throw new ContentError('Rota exige contexto autenticado.', 401, CONTENT_ERROR_CODES.CONFIG_MISSING)\n }\n return context.auth.companyId\n}\n\n/** Ações de moderação gravam quem decidiu: credencial de máquina (sem `userId`) não decide. */\nexport function requireActor(context: RequestContext): string {\n if (!context.auth?.userId) {\n throw new ContentError('Rota exige um usuário da equipe.', 403, CONTENT_ERROR_CODES.CONFIG_MISSING)\n }\n return context.auth.userId\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas do hóspede autor. Escopo `public` (sem `auth` do host): quem é o autor sai da\n * `CommunityAuthorPort` a cada requisição, e o handler chama `resolveCommunityAuthor` antes de tudo.\n */\n\nimport {\n createCommunityPostSchema,\n submitCommunityPostSchema,\n updateCommunityPostSchema,\n type CreateCommunityPostInput,\n type UpdateCommunityPostInput,\n} from '@adatechnology/content-contracts'\nimport type { HttpResult, ModuleRoute, RequestContext } from '@adatechnology/module-http'\nimport { z } from 'zod'\n\nimport type { ContentModule } from '../ContentModule'\nimport type { CommunityAuthorContext } from '../use-cases/types/community.types'\n\nexport const NO_STORE_HEADERS = { 'Cache-Control': 'no-store' } as const\n\nconst SELF_SERVICE = { scope: 'public' as const }\nconst AUTHOR_NOTE = 'exige a sessão do hóspede (CommunityAuthorPort)'\n\nconst listOwnQuerySchema = z.object({\n page: z.coerce.number().int().min(1).max(10_000).optional(),\n pageSize: z.coerce.number().int().min(1).max(100).optional(),\n})\n\nexport const noStoreJson = (status: number, data: unknown): HttpResult => ({\n kind: 'json',\n status,\n body: { data },\n headers: NO_STORE_HEADERS,\n})\n\nexport function buildCommunityRoutes(module: ContentModule): ModuleRoute[] {\n const { useCases } = module\n const { resolveCommunityAuthor } = useCases\n if (!resolveCommunityAuthor) return []\n\n const authenticated =\n (handle: (context: RequestContext, author: CommunityAuthorContext) => Promise<HttpResult>) =>\n async (context: RequestContext): Promise<HttpResult> =>\n handle(context, await resolveCommunityAuthor.execute({ headers: context.headers }))\n\n const routes: ModuleRoute[] = [\n {\n ...SELF_SERVICE,\n method: 'GET',\n path: '/community/posts',\n querySchema: listOwnQuerySchema,\n operationId: 'listOwnCommunityPosts',\n summary: `Posts do próprio hóspede, mais recentes primeiro; ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) => {\n const { page, pageSize } = context.query as unknown as z.output<typeof listOwnQuerySchema>\n const result = await useCases.listOwnCommunityPosts?.execute({\n author,\n ...(page ? { page } : {}),\n ...(pageSize ? { pageSize } : {}),\n })\n return { kind: 'json', status: 200, body: result, headers: NO_STORE_HEADERS }\n }),\n },\n {\n ...SELF_SERVICE,\n method: 'POST',\n path: '/community/posts',\n bodySchema: createCommunityPostSchema,\n operationId: 'createCommunityPost',\n summary: `Cria um rascunho do hóspede (respeita o limite diário); ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) =>\n noStoreJson(\n 201,\n await useCases.createCommunityPost?.execute({ author, input: context.body as CreateCommunityPostInput }),\n ),\n ),\n },\n // Antes de `/community/posts/:id`: `images` não pode ser lido como id.\n ...imageRoutes(module, authenticated),\n {\n ...SELF_SERVICE,\n method: 'GET',\n path: '/community/posts/:id',\n operationId: 'getOwnCommunityPost',\n summary: `Lê um post do próprio hóspede (post alheio é 404); ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) =>\n noStoreJson(200, await useCases.getOwnCommunityPost?.execute({ author, id: context.params.id ?? '' })),\n ),\n },\n {\n ...SELF_SERVICE,\n method: 'PATCH',\n path: '/community/posts/:id',\n bodySchema: updateCommunityPostSchema,\n operationId: 'updateOwnCommunityPost',\n summary: `Edita o próprio post; publicado em moderação prévia vira revisão pendente; ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) =>\n noStoreJson(\n 200,\n await useCases.updateOwnCommunityPost?.execute({\n author,\n id: context.params.id ?? '',\n input: context.body as UpdateCommunityPostInput,\n }),\n ),\n ),\n },\n {\n ...SELF_SERVICE,\n method: 'DELETE',\n path: '/community/posts/:id',\n operationId: 'deleteOwnCommunityPost',\n summary: `Exclui o próprio post (anonimiza o publicado); ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) => {\n await useCases.deleteOwnCommunityPost?.execute({ author, id: context.params.id ?? '' })\n return { kind: 'empty', status: 204, headers: NO_STORE_HEADERS }\n }),\n },\n {\n ...SELF_SERVICE,\n method: 'POST',\n path: '/community/posts/:id/submit',\n // Corpo ausente chega ao use case como `undefined` e vira 422 de termos, não 400 de formato.\n bodySchema: submitCommunityPostSchema.partial().optional(),\n operationId: 'submitCommunityPost',\n summary: `Envia o post para a comunidade, com aceite dos termos; ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) =>\n noStoreJson(\n 200,\n await useCases.submitCommunityPost?.execute({\n author,\n id: context.params.id ?? '',\n termsAccepted: (context.body as { termsAccepted?: boolean } | undefined)?.termsAccepted,\n }),\n ),\n ),\n },\n ]\n return routes\n}\n\ntype Authenticated = (\n handle: (context: RequestContext, author: CommunityAuthorContext) => Promise<HttpResult>,\n) => (context: RequestContext) => Promise<HttpResult>\n\nfunction imageRoutes(module: ContentModule, authenticated: Authenticated): ModuleRoute[] {\n const upload = module.useCases.uploadCommunityImage\n if (!upload) return []\n return [\n {\n ...SELF_SERVICE,\n method: 'POST',\n path: '/community/images',\n operationId: 'uploadCommunityImage',\n summary: `Envia uma foto do hóspede (bytes crus, Content-Type jpeg/png/webp); ${AUTHOR_NOTE}`,\n handler: authenticated(async (context, author) =>\n noStoreJson(\n 201,\n await upload.execute({\n author,\n bytes: context.rawBody ?? new Uint8Array(),\n mimeType: context.headers['content-type'] ?? '',\n }),\n ),\n ),\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Rotas do site público. Sem identidade: a empresa vem do `PublicCompanyResolverPort` do host\n * (domínio, cabeçalho, empresa fixa…). Resolver sem resposta = 404, igual a post inexistente.\n */\n\nimport {\n DEFAULT_PUBLIC_CACHE_CONTROL,\n createPostReportSchema,\n listPublishedPostsQuerySchema,\n PostNotFoundError,\n type CreatePostReportInput,\n type ListPublishedPostsQuery,\n} from '@adatechnology/content-contracts'\nimport type { HttpResult, ModuleRoute, RequestContext } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { FEED_FORMAT } from '../use-cases/Feed.use-cases'\nimport { TAG_SCOPE } from '../use-cases/PublicPost.use-cases'\nimport { NO_STORE_HEADERS } from './communityRoutes'\n\nexport interface PublicCompanyResolverPort {\n resolve(params: {\n readonly headers: Readonly<Record<string, string>>\n readonly query: Readonly<Record<string, string>>\n }): Promise<string | undefined>\n}\n\nconst PUBLIC = { scope: 'public' as const }\n\nexport function buildPublicRoutes(params: {\n module: ContentModule\n companyResolver: PublicCompanyResolverPort\n}): ModuleRoute[] {\n const { useCases } = params.module\n const cacheControl = params.module.config.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL\n const cached = (data: unknown): HttpResult => ({\n kind: 'json',\n status: 200,\n body: data,\n headers: { 'Cache-Control': cacheControl },\n })\n\n async function resolveCompany(context: RequestContext): Promise<string> {\n const companyId = await params.companyResolver.resolve({ headers: context.headers, query: context.query })\n if (!companyId) throw new PostNotFoundError('company')\n return companyId\n }\n\n function reportRoutes(): ModuleRoute[] {\n const { createPostReport } = useCases\n if (!createPostReport) return []\n return [\n {\n ...PUBLIC,\n method: 'POST',\n path: '/public/posts/:id/reports',\n bodySchema: createPostReportSchema,\n operationId: 'createPostReport',\n summary: 'Denuncia um post da comunidade no ar, sem identidade; responde 202 e a equipe analisa',\n async handler(context) {\n const report = await createPostReport.execute({\n companyId: await resolveCompany(context),\n postId: context.params.id ?? '',\n input: context.body as CreatePostReportInput,\n })\n return { kind: 'json', status: 202, body: { data: report }, headers: NO_STORE_HEADERS }\n },\n },\n ]\n }\n\n const routes: ModuleRoute[] = [\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts',\n querySchema: listPublishedPostsQuerySchema,\n operationId: 'listPublishedPosts',\n summary: 'Posts publicados, mais recentes primeiro, com filtro por tag',\n async handler(context) {\n const result = await useCases.listPublishedPosts.execute({\n companyId: await resolveCompany(context),\n ...(context.query as unknown as ListPublishedPostsQuery),\n })\n return cached(result)\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/posts/:slug',\n operationId: 'getPublishedPost',\n summary: 'Post publicado pelo slug; rascunho, agendado futuro e arquivado respondem 404',\n async handler(context) {\n const post = await useCases.getPublishedPostBySlug.execute({\n companyId: await resolveCompany(context),\n slug: context.params.slug ?? '',\n })\n return cached({ data: post })\n },\n },\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/tags',\n operationId: 'listPublishedTags',\n summary: 'Tags dos posts publicados, com contagem',\n async handler(context) {\n const tags = await useCases.listTags.execute({\n companyId: await resolveCompany(context),\n scope: TAG_SCOPE.PUBLIC,\n })\n return cached({ data: tags })\n },\n },\n ...reportRoutes(),\n ]\n\n const { buildFeed, listSitemapEntries } = useCases\n if (!buildFeed || !listSitemapEntries) return routes\n\n const feedRoute = (path: string, format: 'rss' | 'atom', contentType: string, operationId: string): ModuleRoute => ({\n ...PUBLIC,\n method: 'GET',\n path,\n operationId,\n summary: `Feed ${format.toUpperCase()} dos posts publicados`,\n async handler(context) {\n const body = await buildFeed.execute({ companyId: await resolveCompany(context), format })\n return {\n kind: 'text',\n status: 200,\n body,\n headers: { 'Content-Type': contentType, 'Cache-Control': cacheControl },\n }\n },\n })\n\n return [\n ...routes,\n feedRoute('/public/feed.xml', FEED_FORMAT.RSS, 'application/rss+xml; charset=utf-8', 'getRssFeed'),\n feedRoute('/public/atom.xml', FEED_FORMAT.ATOM, 'application/atom+xml; charset=utf-8', 'getAtomFeed'),\n {\n ...PUBLIC,\n method: 'GET',\n path: '/public/sitemap-entries',\n operationId: 'listSitemapEntries',\n summary: 'Entradas de sitemap (loc, lastmod) dos posts publicados, para o host juntar ao sitemap dele',\n async handler(context) {\n return cached({ data: await listSitemapEntries.execute({ companyId: await resolveCompany(context) }) })\n },\n },\n ]\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { ModuleRouteTable } from '@adatechnology/module-http'\n\nimport type { ContentModule } from '../ContentModule'\nimport { buildAdminRoutes } from './adminRoutes'\nimport { buildCommunityRoutes } from './communityRoutes'\nimport { buildPublicRoutes, type PublicCompanyResolverPort } from './publicRoutes'\n\nexport type CreateContentRoutesParams = {\n readonly module: ContentModule\n /**\n * Como o site público diz de qual empresa é o blog (domínio, cabeçalho, valor fixo…). Ausente,\n * as rotas `/public/*` não sobem: o host que só tem painel não expõe leitura anônima.\n */\n readonly publicCompanyResolver?: PublicCompanyResolverPort\n}\n\nexport function createContentRoutes(params: CreateContentRoutesParams): ModuleRouteTable {\n const admin = buildAdminRoutes(params.module)\n const community = buildCommunityRoutes(params.module)\n if (!params.publicCompanyResolver) return [...admin, ...community]\n const site = buildPublicRoutes({ module: params.module, companyResolver: params.publicCompanyResolver })\n return [...admin, ...site, ...community]\n}\n\nexport type { PublicCompanyResolverPort }\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * `operationId` das rotas que o app deve limitar (por IP e, nas de autoria, por conta): o módulo não\n * tem contador nem relógio de janela. O app envolve o `handler` dessas rotas na tabela e responde 429\n * com `Retry-After`; o 429 do limite diário do módulo leva `retryAfterSeconds` em `publicDetails`.\n */\nexport const CONTENT_RATE_LIMITED_OPERATIONS = [\n 'createCommunityPost',\n 'updateOwnCommunityPost',\n 'submitCommunityPost',\n 'uploadCommunityImage',\n 'createPostReport',\n] as const\n\nexport type ContentRateLimitedOperation = (typeof CONTENT_RATE_LIMITED_OPERATIONS)[number]\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { join } from 'node:path'\n\nimport type { ContentDatabase, DrizzleMigrateFunction } from './database.types'\n\n// Journal próprio, fora do pgSchema `content`: a primeira migration é quem cria esse schema\n// (mesmo raciocínio de `catalog-module/runMigrations.ts`).\nexport const CONTENT_MIGRATIONS_TABLE = 'content_migrations'\n\n/** Pasta no formato clássico (`meta/_journal.json`), lida pelos migrators do drizzle 0.x e 1.x. */\nexport function contentMigrationsFolder(): string {\n return join(__dirname, 'migrations')\n}\n\nexport type RunContentMigrationsParams = {\n readonly db: ContentDatabase\n /** O `migrate` do driver do host (`drizzle-orm/node-postgres/migrator`, `.../bun-sql/migrator`…). */\n readonly migrate: DrizzleMigrateFunction\n}\n\nexport async function runContentMigrations(params: RunContentMigrationsParams): Promise<void> {\n await params.migrate(params.db as never, {\n migrationsFolder: contentMigrationsFolder(),\n migrationsTable: CONTENT_MIGRATIONS_TABLE,\n })\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `PostStorePort`, para a suíte de comportamento do módulo e para o teste do\n * host. O isolamento real (cláusula SQL) é provado em `repositories/isolation.test.ts`; aqui as\n * mesmas regras são reproduzidas em JavaScript, inclusive a violação de índice único do slug.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { COMMUNITY_REVISION_STATE, POST_ORIGIN, POST_STATUS, type TagCount } from '@adatechnology/content-contracts'\n\nimport type { NewPostRow, PostRow } from '../schema/schema'\nimport { effectiveStatus } from '../shared/toContract'\nimport type { PostAdminListQuery, PostPage, PostPublicListQuery, PostStorePort } from '../use-cases/contentModule.types'\n\nfunction isPublic(row: PostRow, now: Date): boolean {\n const live = row.status === POST_STATUS.PUBLISHED || row.status === POST_STATUS.SCHEDULED\n return live && row.publishedAt !== null && row.publishedAt <= now\n}\n\nconst originMatches = (row: PostRow, origin: string | undefined): boolean =>\n (origin ?? POST_ORIGIN.STAFF) === 'all' || row.origin === (origin ?? POST_ORIGIN.STAFF)\n\nfunction matchesStatus(row: PostRow, query: PostAdminListQuery): boolean {\n if (query.status !== POST_STATUS.PENDING_REVIEW) return effectiveStatus(row, query.now) === query.status\n const isAwaiting =\n row.status === POST_STATUS.PENDING_REVIEW || row.pendingRevision?.state === COMMUNITY_REVISION_STATE.PENDING\n return row.origin === POST_ORIGIN.COMMUNITY && isAwaiting\n}\n\nfunction adminComparator(query: PostAdminListQuery) {\n const sign = query.order === 'asc' ? 1 : -1\n const value = (row: PostRow): number | string => {\n if (query.sort === 'title') return row.title.toLowerCase()\n if (query.sort === 'status') return row.status\n if (query.sort === 'publishedAt') return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY\n return row.updatedAt.getTime()\n }\n return (left: PostRow, right: PostRow): number => {\n const a = value(left)\n const b = value(right)\n return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id)\n }\n}\n\nfunction paginate(rows: PostRow[], page: number, pageSize: number): PostPage {\n return { rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({ ...row })), total: rows.length }\n}\n\nclass UniqueViolation extends Error {\n readonly code = '23505'\n}\n\nexport function createInMemoryPostStore(seed: PostRow[] = []): PostStorePort & { readonly rows: PostRow[] } {\n const rows: PostRow[] = [...seed]\n const formerSlugs: { companyId: string; slug: string; postId: string }[] = []\n\n const assertUniqueSlug = (companyId: string, slug: string, ownId?: string): void => {\n if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {\n throw new UniqueViolation('duplicate key value violates unique constraint \"idx_posts_company_slug\"')\n }\n }\n\n return {\n rows,\n\n async findByShortId({ companyId, shortId }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId)\n return row ? { ...row } : undefined\n },\n\n async findPublicByShortId({ companyId, shortId, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async findPublicById({ companyId, id, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.id === id && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async findPublicByFormerSlug({ companyId, slug, now }) {\n const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug)\n const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now))\n return row ? { ...row } : undefined\n },\n\n async recordFormerSlug(params) {\n if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {\n formerSlugs.push({ ...params })\n }\n },\n\n async create(values: NewPostRow): Promise<PostRow> {\n assertUniqueSlug(values.companyId, values.slug)\n const now = new Date()\n const row: PostRow = {\n id: randomUUID(),\n excerpt: null,\n body: '',\n coverImageUrl: null,\n coverImageAlt: null,\n tags: [],\n tagLabels: {},\n status: POST_STATUS.DRAFT,\n isTemplate: false,\n publishedAt: null,\n authorName: null,\n seoTitle: null,\n seoDescription: null,\n canonicalUrl: null,\n readingTimeMinutes: 1,\n origin: POST_ORIGIN.STAFF,\n authorAccountId: null,\n authorDisplayName: null,\n authorReferenceMonth: null,\n reviewNote: null,\n termsAcceptedAt: null,\n submittedAt: null,\n pendingRevision: null,\n createdAt: now,\n updatedAt: now,\n ...values,\n } as PostRow\n rows.push(row)\n return { ...row }\n },\n\n async findById({ companyId, id }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n return row ? { ...row } : undefined\n },\n\n async findBySlug({ companyId, slug }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.slug === slug)\n return row ? { ...row } : undefined\n },\n\n async findPublicBySlug({ companyId, slug, now }) {\n const row = rows.find(\n (candidate) => candidate.companyId === companyId && candidate.slug === slug && isPublic(candidate, now),\n )\n return row ? { ...row } : undefined\n },\n\n async update({ companyId, id, values }) {\n const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id)\n if (!row) return undefined\n if (values.slug !== undefined) assertUniqueSlug(companyId, values.slug, id)\n Object.assign(row, values, { updatedAt: new Date(Math.max(Date.now(), row.updatedAt.getTime() + 1)) })\n return { ...row }\n },\n\n async listForAdmin(query: PostAdminListQuery) {\n const search = query.search?.toLowerCase()\n const matched = rows\n .filter((row) => row.companyId === query.companyId && originMatches(row, query.origin))\n .filter((row) => (query.isTemplate ? row.isTemplate && row.status !== POST_STATUS.ARCHIVED : !row.isTemplate))\n .filter((row) => !query.status || matchesStatus(row, query))\n .filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag)))\n .filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search))\n .sort(adminComparator(query))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async countByStatus({ companyId, now }) {\n const counts = { published: 0, scheduled: 0, draft: 0, archived: 0, templates: 0, pendingReview: 0, rejected: 0 }\n for (const row of rows) {\n if (row.companyId !== companyId) continue\n if (row.status === POST_STATUS.PENDING_REVIEW) counts.pendingReview += 1\n else if (row.pendingRevision?.state === COMMUNITY_REVISION_STATE.PENDING) counts.pendingReview += 1\n if (row.status === POST_STATUS.REJECTED) counts.rejected += 1\n if (row.origin !== POST_ORIGIN.STAFF) continue\n if (row.isTemplate) {\n if (row.status !== POST_STATUS.ARCHIVED) counts.templates += 1\n continue\n }\n counts[effectiveStatus(row, now) as keyof typeof counts] += 1\n }\n return counts\n },\n\n async claimDueScheduled({ now, limit }) {\n const due = rows\n .filter(\n (row) => row.status === POST_STATUS.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now,\n )\n .sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0))\n .slice(0, limit)\n for (const row of due) row.status = POST_STATUS.PUBLISHED\n return due.map((row) => ({ ...row }))\n },\n\n async listPublic(query: PostPublicListQuery) {\n const matched = rows\n .filter((row) => row.companyId === query.companyId && isPublic(row, query.now))\n .filter((row) => originMatches(row, query.origin))\n .filter((row) => !query.tag || row.tags.includes(query.tag))\n .sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0))\n return paginate(matched, query.page, query.pageSize)\n },\n\n async listTags({ companyId, publicAt }): Promise<readonly TagCount[]> {\n const counts = new Map<string, number>()\n for (const row of rows) {\n if (row.companyId !== companyId || (publicAt && !isPublic(row, publicAt))) continue\n for (const tag of row.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1)\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag))\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport type { LoggerPort } from '@adatechnology/content-contracts'\n\nimport type { ContentModule } from './ContentModule'\n\nexport const DEFAULT_SCHEDULER_INTERVAL_MS = 60_000\n\nexport type StartContentSchedulerParams = {\n readonly module: ContentModule\n /** Padrão: 1 minuto. */\n readonly intervalMs?: number\n readonly logger?: LoggerPort\n}\n\n/**\n * Chama `publishDue` num intervalo, com guarda de execução única neste processo: se um ciclo ainda\n * está rodando, o próximo tick é pulado em vez de empilhar. Entre instâncias, quem garante é o\n * `FOR UPDATE SKIP LOCKED` do store. Erro de um ciclo é logado e o seguinte tenta de novo.\n * Devolve a função que para o agendador (chame no desligamento).\n */\nexport function startContentScheduler(params: StartContentSchedulerParams): () => void {\n let isRunning = false\n const tick = async (): Promise<void> => {\n if (isRunning) return\n isRunning = true\n try {\n await params.module.useCases.publishDue.execute()\n } catch (error) {\n params.logger?.error('content-module: ciclo do agendador falhou', {\n error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n isRunning = false\n }\n }\n const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS)\n timer.unref?.()\n void tick()\n return () => clearInterval(timer)\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Dublê em memória do `RecurrenceStorePort`: mesmas regras, sem transação (o teste é de um processo só).\n */\n\nimport { randomUUID } from 'node:crypto'\n\nimport type { NewRecurrenceRow, RecurrenceRow } from '../schema/schema'\nimport type { RecurrenceStorePort } from '../use-cases/contentModule.types'\n\nexport function createInMemoryRecurrenceStore(): RecurrenceStorePort & { readonly rows: RecurrenceRow[] } {\n const rows: RecurrenceRow[] = []\n const owned = (companyId: string, id: string) => rows.find((row) => row.companyId === companyId && row.id === id)\n\n return {\n rows,\n async create(values: NewRecurrenceRow) {\n const row = {\n id: randomUUID(),\n isActive: true,\n lastRunAt: null,\n lastPostId: null,\n createdAt: new Date(),\n ...values,\n } as RecurrenceRow\n rows.push(row)\n return { ...row }\n },\n async findById({ companyId, id }) {\n const row = owned(companyId, id)\n return row ? { ...row } : undefined\n },\n async list({ companyId }) {\n return rows\n .filter((row) => row.companyId === companyId)\n .sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime())\n .map((row) => ({ ...row }))\n },\n async update({ companyId, id, values }) {\n const row = owned(companyId, id)\n if (!row) return undefined\n Object.assign(row, values)\n return { ...row }\n },\n async remove({ companyId, id }) {\n const index = rows.findIndex((row) => row.companyId === companyId && row.id === id)\n if (index < 0) return false\n rows.splice(index, 1)\n return true\n },\n async processDue({ now, limit, handle }) {\n const due = rows\n .filter((row) => row.isActive && row.nextRunAt <= now)\n .sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime())\n .slice(0, limit)\n for (const row of due) Object.assign(row, await handle({ ...row }))\n return due.length\n },\n }\n}\n"],"mappings":";;;;AACA,OAAOA,UAAU;AACjB,SAASC,qBAAqB;AAE9B,IAAMC,cAAc,6BAAMC,cAAc,YAAYC,GAAG,GAAnC;AACpB,IAAMC,aAAa,6BAAMC,KAAKC,QAAQL,YAAAA,CAAAA,GAAnB;AAEZ,IAAMM,YAA4BH,2BAAAA;;;ACAzC,SAASI,0BA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","getFilename","fileURLToPath","url","getDirname","path","dirname","__dirname","ConfigMissingError","and","asc","desc","eq","gt","inArray","isNotNull","isNull","ne","sql","COMMUNITY_MODERATIONS","DEFAULT_CONTENT_SETTINGS","POST_ORIGIN","POST_STATUS","sql","boolean","customType","index","integer","jsonb","primaryKey","pgSchema","text","timestamp","uniqueIndex","uuid","varchar","jsonbObject","name","customType","dataType","toDriver","value","sql","JSON","stringify","fromDriver","parse","contentSchema","pgSchema","posts","table","id","uuid","primaryKey","defaultRandom","companyId","notNull","slug","varchar","length","shortId","title","excerpt","body","text","default","coverImageUrl","coverImageAlt","tags","array","tagLabels","jsonb","$type","status","isTemplate","boolean","publishedAt","timestamp","withTimezone","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","integer","createdAt","defaultNow","updatedAt","origin","authorAccountId","authorDisplayName","authorReferenceMonth","reviewNote","termsAcceptedAt","submittedAt","pendingRevision","uniqueIndex","on","index","where","using","recurrenceRules","templateId","references","frequency","anchorDay","isActive","nextRunAt","lastRunAt","lastPostId","postFormerSlugs","postId","columns","contentSettings","communityModeration","communityDailyLimit","maxImagesPerPost","postReports","reason","resolvedAt","resolvedBy","communityImages","accountId","storageKey","url","COMMUNITY_WINDOW_MS","COMMUNITY_IMAGE_KEY_PREFIX","ANONYMIZED_TITLE","COMMUNITY_ACTION","SUBMIT","APPROVE","REJECT","UNPUBLISH","BULK_UNEXPECTED_FAILURE","code","message","toModeration","value","COMMUNITY_MODERATIONS","includes","DEFAULT_CONTENT_SETTINGS","communityModeration","CommunityRepository","db","createWithDailyLimit","params","values","accountId","limit","now","windowStart","Date","getTime","COMMUNITY_WINDOW_MS","lockKey","companyId","transaction","tx","execute","sql","recent","select","createdAt","posts","from","where","and","eq","origin","POST_ORIGIN","COMMUNITY","authorAccountId","gt","orderBy","asc","blocking","length","isLimited","freesUpAt","row","insert","returning","Error","listByAuthor","ne","status","POST_STATUS","ARCHIVED","rows","counted","Promise","all","desc","updatedAt","id","pageSize","offset","page","total","getSettings","contentSettings","communityDailyLimit","maxImagesPerPost","findOwnedImageUrls","urls","url","communityImages","inArray","map","recordImage","listRecentImageDates","since","upsertSettings","settings","onConflictDoUpdate","target","set","createReport","postReports","listReports","isNull","resolvedAt","isNotNull","resolveReport","update","toISOString","resolvedBy","actorUserId","countOpenReports","postIds","Map","postId","groupBy","and","asc","desc","eq","inArray","sql","COMMUNITY_REVISION_STATE","POST_ORIGIN","POST_STATUS","and","arrayContains","arrayOverlaps","eq","gt","inArray","lte","ne","or","sql","COMMUNITY_REVISION_STATE","POST_ORIGIN","POST_STATUS","postOwnedByCondition","params","and","eq","posts","companyId","id","postSlugCondition","slug","postOriginCondition","origin","filter","POST_ORIGIN","STAFF","undefined","postAdminListCondition","conditions","templateCondition","isTemplate","push","status","statusCondition","now","tags","length","arrayOverlaps","search","pattern","replace","character","sql","title","revisionStateExpression","pendingRevision","pendingReviewCondition","COMMUNITY","or","POST_STATUS","PENDING_REVIEW","COMMUNITY_REVISION_STATE","PENDING","ne","ARCHIVED","PUBLISHED","SCHEDULED","lte","publishedAt","gt","postPublicCondition","inArray","tag","arrayContains","postPublicListCondition","postPublicSlugCondition","postDueCondition","postShortIdCondition","shortId","postPublicIdCondition","postPublicShortIdCondition","TAG_LIST_LIMIT","SORT_COLUMNS","title","posts","status","publishedAt","updatedAt","adminOrder","query","column","sort","direction","order","asc","desc","primary","sql","raw","id","PostRepository","db","create","values","row","insert","returning","Error","findById","params","select","from","where","postOwnedByCondition","limit","findBySlug","postSlugCondition","findPublicBySlug","postPublicSlugCondition","findByShortId","postShortIdCondition","findPublicByShortId","postPublicShortIdCondition","findPublicById","postPublicIdCondition","findPublicByFormerSlug","former","postId","postFormerSlugs","and","eq","companyId","slug","undefined","postPublicCondition","recordFormerSlug","onConflictDoNothing","update","set","Date","listForAdmin","postAdminListCondition","rows","counted","Promise","all","orderBy","pageSize","offset","page","value","total","listPublic","postPublicListCondition","countByStatus","now","toISOString","condition","staff","origin","POST_ORIGIN","STAFF","revisionState","revisionStateExpression","livePublished","POST_STATUS","PUBLISHED","SCHEDULED","published","isTemplate","scheduled","draft","DRAFT","archived","ARCHIVED","templates","pendingReview","PENDING_REVIEW","COMMUNITY_REVISION_STATE","PENDING","rejected","REJECTED","claimDueScheduled","due","postDueCondition","for","skipLocked","inArray","listTags","publicAt","postTags","tag","tags","as","count","groupBy","and","asc","eq","lte","recurrenceOwnedByCondition","params","and","eq","recurrenceRules","companyId","id","RecurrenceRepository","db","create","values","row","insert","returning","Error","findById","select","from","where","limit","list","orderBy","asc","nextRunAt","update","set","remove","removed","delete","length","processDue","transaction","due","isActive","lte","now","for","skipLocked","processed","rule","handle","contentSettingsSchema","buildTagLabels","CommunityPostReadOnlyError","createPostSchema","DuplicateSlugError","estimateReadingTimeMinutes","listPostsQuerySchema","normalizeTags","POST_EVENT","POST_ORIGIN","POST_STATUS","PostNotFoundError","TemplateNotPublishableError","publishPostSchema","buildShortSlug","updatePostSchema","withSlugSuffix","randomInt","SHORT_ID_LENGTH","ALPHABET","generateShortId","value","index","SHORT_ID_LENGTH","randomInt","length","UNIQUE_VIOLATION","isUniqueViolation","error","current","depth","code","cause","notifyPostChanged","dependencies","type","post","hook","hooks","onPostChanged","error","logger","postId","id","Error","message","String","communityRevisionSchema","POST_ORIGIN","POST_STATUS","effectiveStatus","row","now","status","POST_STATUS","SCHEDULED","publishedAt","PUBLISHED","readPendingRevision","pendingRevision","undefined","parsed","communityRevisionSchema","safeParse","success","data","toPostSummary","openReportCount","id","companyId","slug","shortId","title","excerpt","coverImageUrl","coverImageAlt","tags","tagLabels","isTemplate","toISOString","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","createdAt","updatedAt","origin","authorAccountId","authorDisplayName","authorReferenceMonth","reviewNote","termsAcceptedAt","submittedAt","toPost","body","toCommunityAuthor","POST_ORIGIN","COMMUNITY","displayName","referenceMonth","toPublicPostSummary","communityAuthor","toPublicPost","toPagination","params","totalPages","Math","max","ceil","total","pageSize","toCommunityPost","toPostReport","postId","reason","resolvedAt","resolvedBy","MAX_SLUG_ATTEMPTS","FALLBACK_SLUG","PostUseCaseBase","dependencies","now","clock","findOrFail","reference","row","posts","findById","PostNotFoundError","id","findEditableOrFail","origin","POST_ORIGIN","COMMUNITY","CommunityPostReadOnlyError","openReportCounts","params","community","postIds","rows","filter","map","length","Map","countOpenReports","companyId","save","values","event","update","catch","error","isUniqueViolation","slug","DuplicateSlugError","post","toPost","notifyPostChanged","generateShortId","attempt","candidate","findByShortId","shortId","Error","readingTime","body","estimateReadingTimeMinutes","config","wordsPerMinute","assertSlugAvailable","ownId","existing","findBySlug","generateSlug","title","uniqueSlug","buildShortSlug","base","withSlugSuffix","Date","optionalFields","input","excerpt","undefined","coverImageUrl","coverImageAlt","authorName","seoTitle","seoDescription","canonicalUrl","CreatePostUseCase","execute","createPostSchema","parse","create","tags","normalizeTags","tagLabels","buildTagLabels","typed","explicit","status","POST_STATUS","DRAFT","readingTimeMinutes","POST_EVENT","CREATED","UpdatePostUseCase","updatePostSchema","previous","recordFormerSlug","postId","UPDATED","PublishPostUseCase","publishPostSchema","isTemplate","TemplateNotPublishableError","publishedAt","SCHEDULED","PUBLISHED","UnpublishPostUseCase","UNPUBLISHED","ArchivePostUseCase","ARCHIVED","GetPostUseCase","counts","get","ListPostsUseCase","rawQuery","query","listPostsQuerySchema","tag","rawTag","rest","split","page","listForAdmin","data","toPostSummary","pagination","toPagination","total","pageSize","ContentSettingsUseCaseBase","PostUseCaseBase","dependencies","GetContentSettingsUseCase","execute","params","community","getSettings","UpdateContentSettingsUseCase","settings","contentSettingsSchema","parse","input","upsertSettings","companyId","now","CommunityDailyLimitError","createCommunityPostSchema","DuplicateSlugError","POST_EVENT","POST_ORIGIN","POST_STATUS","collectImageSources","CommunityImageNotAllowedError","CommunityTooManyImagesError","parseMarkdown","POST_ORIGIN","POST_STATUS","PostNotFoundError","CommunityUseCaseBase","PostUseCaseBase","dependencies","getSettings","companyId","community","findOwned","author","id","row","posts","findById","isOwned","origin","POST_ORIGIN","COMMUNITY","authorAccountId","accountId","status","POST_STATUS","ARCHIVED","PostNotFoundError","persist","params","values","event","update","notifyPostChanged","toPost","now","assertBodyImages","sources","collectImageSources","parseMarkdown","body","length","settings","maxImagesPerPost","CommunityTooManyImagesError","unique","Set","owned","findOwnedImageUrls","urls","CommunityImageNotAllowedError","MIN_RETRY_SECONDS","CreateCommunityPostUseCase","CommunityUseCaseBase","execute","params","author","input","createCommunityPostSchema","parse","settings","getSettings","companyId","sources","assertBodyImages","body","slug","generateSlug","title","now","outcome","dependencies","community","createWithDailyLimit","accountId","limit","communityDailyLimit","values","shortId","generateShortId","excerpt","coverImageUrl","status","POST_STATUS","DRAFT","origin","POST_ORIGIN","COMMUNITY","authorAccountId","authorDisplayName","displayName","defaultDisplayName","readingTimeMinutes","readingTime","createdAt","updatedAt","catch","error","isUniqueViolation","DuplicateSlugError","isLimited","seconds","Math","ceil","freesUpAt","getTime","CommunityDailyLimitError","max","notifyPostChanged","POST_EVENT","CREATED","toPost","row","toCommunityPost","POST_EVENT","POST_STATUS","ANONYMIZED_VALUES","status","POST_STATUS","ARCHIVED","title","ANONYMIZED_TITLE","body","excerpt","coverImageUrl","coverImageAlt","authorDisplayName","pendingRevision","reviewNote","readingTimeMinutes","DeleteOwnCommunityPostUseCase","CommunityUseCaseBase","execute","params","findOwned","author","id","persist","values","event","POST_EVENT","POST_LIMITS","DEFAULT_PAGE_SIZE","ListOwnCommunityPostsUseCase","CommunityUseCaseBase","execute","params","page","Math","max","trunc","pageSize","min","POST_LIMITS","PUBLIC_PAGE_SIZE","result","dependencies","community","listByAuthor","companyId","author","accountId","data","rows","map","toCommunityPost","pagination","toPagination","total","GetOwnCommunityPostUseCase","findOwned","id","collectImageSources","COMMUNITY_REVISION_STATE","InvalidPostTransitionError","parseMarkdown","POST_EVENT","POST_STATUS","rejectPostSchema","unpublishCommunityPostSchema","COMMUNITY_REVISION_STATE","POST_ORIGIN","PostNotFoundError","notifyCommunityPostReviewed","dependencies","event","hook","hooks","onCommunityPostReviewed","error","logger","postId","decision","Error","message","String","CommunityModerationUseCaseBase","PostUseCaseBase","dependencies","findCommunityPost","reference","row","posts","findById","origin","POST_ORIGIN","COMMUNITY","PostNotFoundError","id","openRevision","revision","readPendingRevision","state","COMMUNITY_REVISION_STATE","PENDING","decide","params","values","event","decision","target","actorUserId","updated","update","companyId","post","toPost","now","notifyPostChanged","notifyCommunityPostReviewed","postId","authorAccountId","statusBefore","status","statusAfter","ApproveCommunityPostUseCase","CommunityModerationUseCaseBase","execute","params","row","findCommunityPost","actorUserId","status","POST_STATUS","PENDING_REVIEW","values","PUBLISHED","publishedAt","now","reviewNote","pendingRevision","decide","event","POST_EVENT","decision","target","revision","openRevision","revisionValues","UPDATED","InvalidPostTransitionError","COMMUNITY_ACTION","APPROVE","title","excerpt","body","readingTimeMinutes","readingTime","coverImageUrl","collectImageSources","parseMarkdown","RejectCommunityPostUseCase","note","rejectPostSchema","parse","input","REJECTED","state","COMMUNITY_REVISION_STATE","REJECT","UnpublishCommunityPostUseCase","unpublishCommunityPostSchema","UNPUBLISH","UNPUBLISHED","ArchiveCommunityPostUseCase","ARCHIVED","toPost","bulkModerationSchema","ContentError","rejectPostSchema","ModerateCommunityPostsInBulkUseCase","CommunityModerationUseCaseBase","actions","dependencies","approve","ApproveCommunityPostUseCase","reject","RejectCommunityPostUseCase","unpublish","UnpublishCommunityPostUseCase","archive","ArchiveCommunityPostUseCase","item","execute","note","input","params","action","ids","bulkModerationSchema","parse","rejectPostSchema","uniqueIds","Set","settled","Promise","allSettled","map","id","companyId","actorUserId","succeeded","failed","forEach","result","index","status","push","describeFailure","reason","ContentError","code","message","BULK_UNEXPECTED_FAILURE","createPostReportSchema","listPostReportsQuerySchema","POST_ORIGIN","PostNotFoundError","ReportNotFoundError","notifyPostReported","dependencies","event","hook","hooks","onPostReported","error","logger","postId","reportId","Error","message","String","PostReportUseCaseBase","PostUseCaseBase","dependencies","CreatePostReportUseCase","execute","params","reason","createPostReportSchema","parse","input","companyId","postId","now","post","posts","findPublicById","id","origin","POST_ORIGIN","COMMUNITY","PostNotFoundError","row","community","createReport","notifyPostReported","reportId","toPostReport","ListPostReportsUseCase","rawQuery","query","listPostReportsQuerySchema","page","listReports","data","rows","map","pagination","toPagination","total","pageSize","ResolvePostReportUseCase","resolveReport","ReportNotFoundError","CommunityAuthorNotEligibleError","CommunityUnauthenticatedError","ResolveCommunityAuthorUseCase","dependencies","execute","params","port","communityAuthor","identity","resolveAuthor","headers","CommunityUnauthenticatedError","eligibility","checkEligibility","companyId","accountId","eligible","CommunityAuthorNotEligibleError","defaultDisplayName","referenceMonth","COMMUNITY_MODERATION","CommunityTermsRequiredError","InvalidPostTransitionError","POST_EVENT","POST_STATUS","notifyCommunityPostSubmitted","dependencies","event","hook","hooks","onCommunityPostSubmitted","error","logger","postId","kind","Error","message","String","SUBMITTABLE_STATUSES","POST_STATUS","DRAFT","REJECTED","SubmitCommunityPostUseCase","CommunityUseCaseBase","execute","params","author","id","row","findOwned","termsAccepted","CommunityTermsRequiredError","includes","status","InvalidPostTransitionError","COMMUNITY_ACTION","SUBMIT","settings","getSettings","companyId","isPublishedNow","communityModeration","COMMUNITY_MODERATION","AFTER","now","values","PUBLISHED","PENDING_REVIEW","termsAcceptedAt","submittedAt","reviewNote","publishedAt","authorReferenceMonth","referenceMonth","updated","persist","event","POST_EVENT","UPDATED","notifySubmitted","toCommunityPost","moderation","notifyCommunityPostSubmitted","dependencies","postId","authorAccountId","kind","COMMUNITY_MODERATION","COMMUNITY_REVISION_STATE","POST_EVENT","POST_STATUS","updateCommunityPostSchema","UpdateOwnCommunityPostUseCase","CommunityUseCaseBase","execute","params","author","id","input","updateCommunityPostSchema","parse","row","findOwned","settings","getSettings","companyId","sources","body","undefined","assertBodyImages","isPublished","status","POST_STATUS","PUBLISHED","isRevision","communityModeration","COMMUNITY_MODERATION","BEFORE","values","revisionValues","liveValues","updated","persist","event","POST_EVENT","UPDATED","notifyRevision","toCommunityPost","title","excerpt","displayName","authorDisplayName","readingTimeMinutes","readingTime","coverImageUrl","open","readPendingRevision","base","state","COMMUNITY_REVISION_STATE","PENDING","now","revision","submittedAt","toISOString","pendingRevision","notifyCommunityPostSubmitted","dependencies","postId","authorAccountId","kind","moderation","CommunityDailyLimitError","ImageStorageDisabledError","InvalidCoverImageError","CONTENT_IMAGE","MAX_BYTES","KEY_PREFIX","EXTENSION_BY_MIME","COVER_IMAGE","UploadImageUseCase","dependencies","execute","params","storage","imageStorage","ImageStorageDisabledError","mimeType","split","trim","toLowerCase","extension","CONTENT_IMAGE","EXTENSION_BY_MIME","InvalidCoverImageError","bytes","byteLength","MAX_BYTES","key","keyPrefix","KEY_PREFIX","companyId","crypto","randomUUID","upload","buffer","UploadCommunityImageUseCase","CommunityUseCaseBase","uploadImage","UploadImageUseCase","dependencies","execute","params","author","now","assertUnderDailyCap","uploaded","companyId","bytes","mimeType","keyPrefix","COMMUNITY_IMAGE_KEY_PREFIX","community","recordImage","accountId","storageKey","key","url","createdAt","settings","getSettings","cap","communityDailyLimit","maxImagesPerPost","recent","listRecentImageDates","since","Date","getTime","COMMUNITY_WINDOW_MS","blocking","length","seconds","Math","ceil","CommunityDailyLimitError","max","isCommunityEnabled","dependencies","communityAuthor","undefined","community","buildCommunityUseCases","resolveCommunityAuthor","ResolveCommunityAuthorUseCase","listOwnCommunityPosts","ListOwnCommunityPostsUseCase","getOwnCommunityPost","GetOwnCommunityPostUseCase","createCommunityPost","CreateCommunityPostUseCase","updateOwnCommunityPost","UpdateOwnCommunityPostUseCase","submitCommunityPost","SubmitCommunityPostUseCase","deleteOwnCommunityPost","DeleteOwnCommunityPostUseCase","approveCommunityPost","ApproveCommunityPostUseCase","rejectCommunityPost","RejectCommunityPostUseCase","unpublishCommunityPost","UnpublishCommunityPostUseCase","archiveCommunityPost","ArchiveCommunityPostUseCase","moderateCommunityPostsInBulk","ModerateCommunityPostsInBulkUseCase","getContentSettings","GetContentSettingsUseCase","updateContentSettings","UpdateContentSettingsUseCase","createPostReport","CreatePostReportUseCase","listPostReports","ListPostReportsUseCase","resolvePostReport","ResolvePostReportUseCase","imageStorage","uploadCommunityImage","UploadCommunityImageUseCase","buildAtomFeed","buildExcerpt","buildPostUrl","buildRssFeed","renderMarkdownToHtml","DEFAULT_ITEM_LIMIT","SITEMAP_LIMIT","FEED_FORMAT","RSS","ATOM","BuildFeedUseCase","dependencies","feed","execute","params","now","clock","page","posts","listPublic","companyId","pageSize","itemLimit","channel","siteUrl","title","description","language","feedUrl","items","rows","map","row","toItem","format","buildAtomFeed","buildRssFeed","url","buildPostUrl","slug","shortId","postPathTemplate","publishedAt","createdAt","toISOString","updatedAt","summary","excerpt","buildExcerpt","body","includeContent","contentHtml","renderMarkdownToHtml","headingIds","authorName","categories","tags","coverImageUrl","imageUrl","ListSitemapEntriesUseCase","loc","lastmod","listPublishedPostsQuerySchema","normalizeTag","parsePostRef","PostNotFoundError","GetPublishedPostBySlugUseCase","dependencies","execute","params","posts","clock","parsed","parsePostRef","slug","query","companyId","now","row","shortId","findPublicByShortId","undefined","findPublicBySlug","findPublicByFormerSlug","PostNotFoundError","toPublicPost","ListPublishedPostsUseCase","rawQuery","listPublishedPostsQuerySchema","parse","tag","normalizeTag","page","listPublic","pageSize","origin","data","rows","map","toPublicPostSummary","pagination","toPagination","total","TAG_SCOPE","PUBLIC","ADMIN","ListTagsUseCase","listTags","scope","publicAt","createRecurrenceSchema","NotATemplateError","PostNotFoundError","RecurrenceNotFoundError","updateRecurrenceSchema","RecurrenceUseCaseBase","dependencies","toRule","row","template","posts","findById","companyId","id","templateId","templateTitle","title","frequency","isActive","nextRunAt","toISOString","lastRunAt","lastPostId","createdAt","findOrFail","params","recurrences","RecurrenceNotFoundError","CreateRecurrenceUseCase","execute","input","createRecurrenceSchema","parse","PostNotFoundError","isTemplate","NotATemplateError","startsAt","Date","values","anchorDay","getUTCDate","create","ListRecurrencesUseCase","rows","list","Promise","all","map","UpdateRecurrenceUseCase","updateRecurrenceSchema","undefined","update","RemoveRecurrenceUseCase","remove","POST_EVENT","POST_STATUS","PostNotPublishedError","republishPostSchema","RepublishDateInFutureError","SLUG_MAX_LENGTH","slugify","RECURRENCE_FREQUENCY","WEEK_MS","daysInMonth","year","monthIndex","Date","UTC","getUTCDate","addMonths","from","anchorDay","months","target","getUTCFullYear","getUTCMonth","day","Math","min","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","nextOccurrence","params","frequency","RECURRENCE_FREQUENCY","WEEKLY","getTime","nextOccurrenceAfter","candidate","now","toDateStamp","date","toISOString","slice","createFromTemplateSchema","DuplicateSlugError","normalizeTags","NotATemplateError","POST_EVENT","POST_STATUS","saveAsTemplateSchema","TEMPLATE_SLUG_PREFIX","copiableFields","row","excerpt","body","coverImageUrl","coverImageAlt","tags","normalizeTags","tagLabels","authorName","seoTitle","seoDescription","readingTimeMinutes","TemplateUseCaseBase","PostUseCaseBase","insertCopy","params","dependencies","posts","create","source","companyId","slug","shortId","generateShortId","title","isTemplate","status","POST_STATUS","DRAFT","publishedAt","catch","error","isUniqueViolation","DuplicateSlugError","post","toPost","now","notifyPostChanged","POST_EVENT","CREATED","SaveAsTemplateUseCase","execute","input","saveAsTemplateSchema","parse","findEditableOrFail","generateSlug","CreateFromTemplateUseCase","createFromTemplateSchema","template","NotATemplateError","id","assertSlugAvailable","CountPostsUseCase","countByStatus","DEFAULT_BATCH_LIMIT","DATE_SUFFIX_LENGTH","FALLBACK_SLUG","RepublishPostUseCase","PostUseCaseBase","execute","params","input","republishPostSchema","parse","existing","findEditableOrFail","now","isTemplate","effectiveStatus","POST_STATUS","PUBLISHED","PostNotPublishedError","id","publishedAt","Date","RepublishDateInFutureError","save","status","POST_EVENT","REPUBLISHED","PublishDueUseCase","limit","materialized","materializeRecurrences","rows","dependencies","posts","claimDueScheduled","row","notifyPostChanged","toPost","length","logger","info","published","recurrences","processDue","handle","rule","materialize","advance","nextRunAt","nextOccurrenceAfter","frequency","from","anchorDay","template","findById","companyId","templateId","ARCHIVED","warn","ruleId","isActive","base","slugify","title","slice","SLUG_MAX_LENGTH","slug","uniqueSlug","replace","toDateStamp","create","copiableFields","shortId","generateShortId","post","CREATED","lastRunAt","lastPostId","UploadCoverImageUseCase","UploadImageUseCase","SYSTEM_CLOCK","now","Date","assertValidConfig","config","feed","test","siteUrl","ConfigMissingError","title","trim","postPathTemplate","includes","wordsPerMinute","undefined","createContentModule","params","posts","providers","postStore","db","PostRepository","recurrences","recurrenceStore","RecurrenceRepository","community","communityStore","CommunityRepository","dependencies","clock","hooks","imageStorage","logger","communityAuthor","useCases","createPost","CreatePostUseCase","updatePost","UpdatePostUseCase","archivePost","ArchivePostUseCase","publishPost","PublishPostUseCase","unpublishPost","UnpublishPostUseCase","getPost","GetPostUseCase","listPosts","ListPostsUseCase","getPublishedPostBySlug","GetPublishedPostBySlugUseCase","listPublishedPosts","ListPublishedPostsUseCase","listTags","ListTagsUseCase","countPosts","CountPostsUseCase","saveAsTemplate","SaveAsTemplateUseCase","createFromTemplate","CreateFromTemplateUseCase","republishPost","RepublishPostUseCase","createRecurrence","CreateRecurrenceUseCase","listRecurrences","ListRecurrencesUseCase","updateRecurrence","UpdateRecurrenceUseCase","removeRecurrence","RemoveRecurrenceUseCase","publishDue","PublishDueUseCase","uploadCoverImage","UploadCoverImageUseCase","uploadImage","UploadImageUseCase","buildCommunityUseCases","buildFeed","BuildFeedUseCase","listSitemapEntries","ListSitemapEntriesUseCase","createFromTemplateSchema","createPostSchema","createRecurrenceSchema","DEFAULT_ADMIN_SCOPES","listPostsQuerySchema","publishPostSchema","republishPostSchema","saveAsTemplateSchema","updatePostSchema","updateRecurrenceSchema","bulkModerationSchema","contentSettingsSchema","DEFAULT_ADMIN_SCOPES","listPostReportsQuerySchema","rejectPostSchema","unpublishCommunityPostSchema","CONTENT_ERROR_CODES","ContentError","requireCompany","context","auth","companyId","ContentError","CONTENT_ERROR_CODES","CONFIG_MISSING","requireActor","userId","json","status","data","kind","body","staffTarget","context","companyId","requireCompany","id","params","actorUserId","requireActor","buildModerationRoutes","module","useCases","approveCommunityPost","admin","scope","requiredScopes","config","adminScopes","DEFAULT_ADMIN_SCOPES","method","path","bodySchema","bulkModerationSchema","operationId","summary","handler","result","moderateCommunityPostsInBulk","execute","input","rejectPostSchema","rejectCommunityPost","unpublishCommunityPostSchema","optional","unpublishCommunityPost","settingsRoutes","reportRoutes","getContentSettings","contentSettingsSchema","updateContentSettings","querySchema","listPostReportsQuerySchema","query","listPostReports","resolvePostReport","reference","context","companyId","requireCompany","id","params","json","status","data","kind","body","buildAdminRoutes","module","useCases","requiredScopes","config","adminScopes","DEFAULT_ADMIN_SCOPES","admin","scope","uploadRoutes","uploadCoverImage","method","path","operationId","summary","handler","upload","result","execute","bytes","rawBody","Uint8Array","mimeType","headers","imageRoutes","uploadImage","querySchema","listPostsQuerySchema","listPosts","query","bodySchema","createPostSchema","post","createPost","input","listTags","TAG_SCOPE","ADMIN","countPosts","recurrenceRoutes","buildModerationRoutes","getPost","updatePostSchema","updatePost","archivePost","publishPostSchema","optional","publishPost","unpublishPost","republishPostSchema","republishPost","saveAsTemplateSchema","saveAsTemplate","createFromTemplateSchema","createFromTemplate","listRecurrences","createRecurrenceSchema","createRecurrence","updateRecurrenceSchema","updateRecurrence","removeRecurrence","createCommunityPostSchema","submitCommunityPostSchema","updateCommunityPostSchema","z","NO_STORE_HEADERS","SELF_SERVICE","scope","AUTHOR_NOTE","listOwnQuerySchema","z","object","page","coerce","number","int","min","max","optional","pageSize","noStoreJson","status","data","kind","body","headers","buildCommunityRoutes","module","useCases","resolveCommunityAuthor","authenticated","handle","context","execute","routes","method","path","querySchema","operationId","summary","handler","author","query","result","listOwnCommunityPosts","bodySchema","createCommunityPostSchema","createCommunityPost","input","imageRoutes","getOwnCommunityPost","id","params","updateCommunityPostSchema","updateOwnCommunityPost","deleteOwnCommunityPost","submitCommunityPostSchema","partial","submitCommunityPost","termsAccepted","upload","uploadCommunityImage","bytes","rawBody","Uint8Array","mimeType","DEFAULT_PUBLIC_CACHE_CONTROL","createPostReportSchema","listPublishedPostsQuerySchema","PostNotFoundError","PUBLIC","scope","buildPublicRoutes","params","useCases","module","cacheControl","config","publicCacheControl","DEFAULT_PUBLIC_CACHE_CONTROL","cached","data","kind","status","body","headers","resolveCompany","context","companyId","companyResolver","resolve","query","PostNotFoundError","reportRoutes","createPostReport","method","path","bodySchema","createPostReportSchema","operationId","summary","handler","report","execute","postId","id","input","NO_STORE_HEADERS","routes","querySchema","listPublishedPostsQuerySchema","result","listPublishedPosts","post","getPublishedPostBySlug","slug","tags","listTags","TAG_SCOPE","buildFeed","listSitemapEntries","feedRoute","format","contentType","toUpperCase","FEED_FORMAT","RSS","ATOM","createContentRoutes","params","admin","buildAdminRoutes","module","community","buildCommunityRoutes","publicCompanyResolver","site","buildPublicRoutes","companyResolver","CONTENT_RATE_LIMITED_OPERATIONS","join","CONTENT_MIGRATIONS_TABLE","contentMigrationsFolder","join","__dirname","runContentMigrations","params","migrate","db","migrationsFolder","migrationsTable","randomUUID","COMMUNITY_REVISION_STATE","POST_ORIGIN","POST_STATUS","isPublic","row","now","live","status","POST_STATUS","PUBLISHED","SCHEDULED","publishedAt","originMatches","origin","POST_ORIGIN","STAFF","matchesStatus","query","PENDING_REVIEW","effectiveStatus","isAwaiting","pendingRevision","state","COMMUNITY_REVISION_STATE","PENDING","COMMUNITY","adminComparator","sign","order","value","sort","title","toLowerCase","getTime","Number","POSITIVE_INFINITY","updatedAt","left","right","a","b","id","localeCompare","paginate","rows","page","pageSize","slice","map","total","length","UniqueViolation","Error","code","createInMemoryPostStore","seed","formerSlugs","assertUniqueSlug","companyId","slug","ownId","some","findByShortId","shortId","find","candidate","undefined","findPublicByShortId","findPublicById","findPublicByFormerSlug","former","entry","postId","recordFormerSlug","params","push","create","values","Date","randomUUID","excerpt","body","coverImageUrl","coverImageAlt","tags","tagLabels","DRAFT","isTemplate","authorName","seoTitle","seoDescription","canonicalUrl","readingTimeMinutes","authorAccountId","authorDisplayName","authorReferenceMonth","reviewNote","termsAcceptedAt","submittedAt","createdAt","findById","findBySlug","findPublicBySlug","update","Object","assign","Math","max","listForAdmin","search","matched","filter","ARCHIVED","tag","includes","countByStatus","counts","published","scheduled","draft","archived","templates","pendingReview","rejected","REJECTED","claimDueScheduled","limit","due","listPublic","listTags","publicAt","Map","set","get","entries","count","DEFAULT_SCHEDULER_INTERVAL_MS","startContentScheduler","params","isRunning","tick","module","useCases","publishDue","execute","error","logger","Error","message","String","timer","setInterval","intervalMs","unref","clearInterval","randomUUID","createInMemoryRecurrenceStore","rows","owned","companyId","id","find","row","create","values","randomUUID","isActive","lastRunAt","lastPostId","createdAt","Date","push","findById","undefined","list","filter","sort","left","right","nextRunAt","getTime","map","update","Object","assign","remove","index","findIndex","splice","processDue","now","limit","handle","due","slice","length"]}
|