@bernierllc/content-management-suite 0.10.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +68 -51
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +68 -51
- package/dist/index.mjs.map +1 -1
- package/dist/prisma.d.mts +1 -1
- package/dist/prisma.d.ts +1 -1
- package/dist/{types-DQpwJ5e3.d.ts → types-DQNP3lLP.d.ts} +31 -13
- package/dist/utils.js +6 -6
- package/dist/utils.js.map +1 -1
- package/dist/utils.mjs +6 -6
- package/dist/utils.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/content-management-suite.ts","../src/config.ts","../src/errors.ts","../src/in-memory-adapter.ts","../src/namespaces/content.ts","../src/namespaces/content-types.ts","../src/namespaces/workflows.ts","../src/namespaces/users.ts","../src/namespaces/config.ts","../src/namespaces/plugins.ts","../src/namespaces/publishers.ts","../src/namespaces/sources.ts","../src/namespaces/ai.ts","../src/namespaces/social.ts"],"sourcesContent":["/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\n\nimport { ContentManagementConfigSchema } from './config';\nimport type { ContentManagementConfig } from './config';\nimport { InternalError } from './errors';\nimport type {\n ContentManagementSuite,\n ContentManagementSuiteOptions,\n ContentManagementLogger,\n ContentNamespace,\n ContentTypesNamespace,\n WorkflowsNamespace,\n UsersNamespace,\n PermissionsNamespace,\n ConfigNamespace,\n PluginsNamespace,\n PublishersNamespace,\n SourcesNamespace,\n AINamespace,\n SocialNamespace,\n SuiteEventMap,\n} from './types';\nimport type { ContentStorageAdapter } from './storage';\nimport { createInMemoryAdapter } from './in-memory-adapter';\n\nimport { ContentNamespaceImpl } from './namespaces/content';\nimport { ContentTypesNamespaceImpl } from './namespaces/content-types';\nimport { WorkflowsNamespaceImpl } from './namespaces/workflows';\nimport { UsersNamespaceImpl, PermissionsNamespaceImpl } from './namespaces/users';\nimport { ConfigNamespaceImpl } from './namespaces/config';\nimport { PluginsNamespaceImpl } from './namespaces/plugins';\nimport { PublishersNamespaceImpl } from './namespaces/publishers';\nimport { SourcesNamespaceImpl } from './namespaces/sources';\nimport { AINamespaceImpl } from './namespaces/ai';\nimport { SocialNamespaceImpl } from './namespaces/social';\n\nexport class ContentManagementSuiteImpl extends EventEmitter implements ContentManagementSuite {\n readonly content: ContentNamespace;\n readonly contentTypes: ContentTypesNamespace;\n readonly workflows: WorkflowsNamespace;\n readonly users: UsersNamespace;\n readonly permissions: PermissionsNamespace;\n readonly config: ConfigNamespace;\n readonly plugins: PluginsNamespace;\n readonly publishers: PublishersNamespace;\n readonly sources: SourcesNamespace;\n readonly ai: AINamespace;\n readonly social: SocialNamespace;\n\n private readonly _logger: ContentManagementLogger | undefined;\n private readonly _options: ContentManagementSuiteOptions;\n private readonly _storage: ContentStorageAdapter;\n private _initialized = false;\n\n constructor(options?: ContentManagementSuiteOptions) {\n super();\n\n this._options = options ?? {};\n this._logger = this._options.logger;\n this._storage = this._options.storage ?? createInMemoryAdapter();\n\n const parsedConfig: ContentManagementConfig = ContentManagementConfigSchema.parse(\n this._options.config ?? {}\n );\n\n const workflowDefaults = this._options.workflows?.defaults ?? {};\n\n // Create namespace instances\n this.contentTypes = new ContentTypesNamespaceImpl();\n this.publishers = new PublishersNamespaceImpl(this);\n this.content = new ContentNamespaceImpl(\n this,\n this._storage,\n () => this.contentTypes,\n () => this.publishers,\n );\n this.workflows = new WorkflowsNamespaceImpl(this._storage);\n this.users = new UsersNamespaceImpl(this);\n this.permissions = new PermissionsNamespaceImpl();\n this.config = new ConfigNamespaceImpl(parsedConfig, this);\n this.plugins = new PluginsNamespaceImpl(this);\n this.sources = new SourcesNamespaceImpl(this, this._storage, workflowDefaults);\n const aiOpts: {\n reviewService?: import('./interfaces').AIReviewService;\n socialGeneratorService?: import('./interfaces').AISocialGeneratorService;\n enhanceService?: import('./interfaces').AIEnhanceService;\n workflowDefaults?: Record<string, string>;\n } = {};\n if (this._options.ai?.reviewService) {\n aiOpts.reviewService = this._options.ai.reviewService;\n }\n if (this._options.ai?.socialGeneratorService) {\n aiOpts.socialGeneratorService = this._options.ai.socialGeneratorService;\n }\n if (this._options.ai?.enhanceService) {\n aiOpts.enhanceService = this._options.ai.enhanceService;\n }\n if (Object.keys(workflowDefaults).length > 0) {\n aiOpts.workflowDefaults = workflowDefaults;\n }\n this.ai = new AINamespaceImpl(this, this._storage, aiOpts);\n this.social = new SocialNamespaceImpl(this, this._storage);\n }\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n throw new InternalError('Suite is already initialized');\n }\n\n // Register default content types\n this.contentTypes.register({ id: 'text', name: 'text' });\n this.contentTypes.register({ id: 'image', name: 'image' });\n this.contentTypes.register({ id: 'audio', name: 'audio' });\n this.contentTypes.register({ id: 'video', name: 'video' });\n\n // Load workflows from storage\n const workflowsImpl = this.workflows as WorkflowsNamespaceImpl;\n if (typeof workflowsImpl.loadFromStorage === 'function') {\n await workflowsImpl.loadFromStorage();\n }\n\n // Register plugins from options\n if (this._options.plugins) {\n for (const plugin of this._options.plugins) {\n await this.plugins.register(plugin);\n }\n }\n\n // Wire auto-advance on ai:review:completed\n this.on('ai:review:completed', async ({ contentId, review }) => {\n try {\n const content = await this._storage.content.get(contentId);\n if (!content || !content.workflowId || !content.workflowStage) {\n return;\n }\n\n const workflow = await this._storage.workflows.get(content.workflowId);\n if (!workflow || !workflow.stages) {\n return;\n }\n\n const currentStage = workflow.stages.find((s) => s.id === content.workflowStage);\n if (!currentStage || !currentStage.conditions) {\n return;\n }\n\n const { autoAdvance, minScore, requiresHumanReview } = currentStage.conditions;\n\n // If human review required, skip auto-advance\n if (requiresHumanReview) {\n return;\n }\n\n // Check auto-advance conditions\n if (autoAdvance && review.passesThreshold && (minScore === undefined || review.score >= minScore)) {\n // Find next stage\n const sortedStages = [...workflow.stages].sort((a, b) => a.order - b.order);\n const currentIndex = sortedStages.findIndex((s) => s.id === currentStage.id);\n const nextStage = sortedStages[currentIndex + 1];\n\n if (nextStage) {\n const fromStage = content.workflowStage;\n await this._storage.content.update(contentId, {\n workflowStage: nextStage.id,\n });\n this.emit('workflow:stage:changed', {\n contentId,\n workflowId: content.workflowId,\n from: fromStage,\n to: nextStage.id,\n });\n }\n }\n } catch {\n // Silently handle errors in auto-advance to avoid breaking the event chain\n }\n });\n\n this._initialized = true;\n this.emit('initialized', undefined as unknown as void);\n }\n\n async dispose(): Promise<void> {\n if (!this._initialized) {\n throw new InternalError('Suite is not initialized');\n }\n\n this._initialized = false;\n this.emit('disposed', undefined as unknown as void);\n }\n\n // Typed event overrides to satisfy the ContentManagementSuite interface\n on<K extends keyof SuiteEventMap>(event: K, listener: (payload: SuiteEventMap[K]) => void): this;\n on(event: string | symbol, listener: (...args: unknown[]) => void): this;\n on(event: string | symbol, listener: (...args: unknown[]) => void): this {\n return super.on(event, listener);\n }\n\n emit<K extends keyof SuiteEventMap>(event: K, payload: SuiteEventMap[K]): boolean;\n emit(event: string | symbol, ...args: unknown[]): boolean;\n emit(event: string | symbol, ...args: unknown[]): boolean {\n return super.emit(event, ...args);\n }\n}\n\n/**\n * Factory function to create a new ContentManagementSuite instance.\n */\nexport function createContentManagementSuite(options?: ContentManagementSuiteOptions): ContentManagementSuite {\n return new ContentManagementSuiteImpl(options);\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { z } from 'zod';\n\nexport const ContentManagementConfigSchema = z.object({\n content: z.object({\n defaultWorkflow: z.object({\n id: z.string().default('standard'),\n name: z.string().default('Standard Workflow'),\n description: z.string().default('Standard editorial workflow'),\n stages: z.array(z.object({\n id: z.string(),\n name: z.string(),\n order: z.number(),\n isPublishStage: z.boolean().default(false),\n allowsScheduling: z.boolean().default(false),\n description: z.string().optional(),\n permissions: z.array(z.string()).default([]),\n })).default([\n { id: 'write', name: 'Write', order: 1, isPublishStage: false, allowsScheduling: false, description: 'Write content', permissions: ['content.edit'] },\n { id: 'publish', name: 'Publish', order: 2, isPublishStage: true, allowsScheduling: true, description: 'Publish content', permissions: ['content.publish'] },\n ]),\n transitions: z.array(z.object({\n id: z.string(),\n from: z.string(),\n to: z.string(),\n description: z.string().optional(),\n permissions: z.array(z.string()).default([]),\n })).default([\n { id: 'write-to-publish', from: 'write', to: 'publish', description: 'Move from write to publish', permissions: ['content.publish'] },\n ]),\n }).default({}),\n contentTypes: z.array(z.string()).default(['text', 'image', 'audio', 'video']),\n autoSave: z.object({\n enabled: z.boolean().default(true),\n debounceMs: z.number().default(1000),\n maxRetries: z.number().default(3),\n backoffMs: z.number().default(1000),\n }).default({}),\n softDelete: z.object({\n enabled: z.boolean().default(true),\n showDeletedToUsers: z.boolean().default(false),\n retentionDays: z.number().default(30),\n }).default({}),\n upload: z.object({\n maxFileSize: z.number().default(104857600),\n allowedTypes: z.array(z.string()).default([\n 'image/jpeg', 'image/png', 'image/webp', 'image/gif',\n 'audio/mpeg', 'audio/wav', 'audio/ogg',\n 'video/mp4', 'video/webm', 'video/ogg',\n ]),\n storage: z.object({\n type: z.enum(['local', 's3']).default('local'),\n path: z.string().default('./uploads'),\n bucket: z.string().optional(),\n region: z.string().optional(),\n }).default({}).optional(),\n }).default({}),\n }).default({}),\n\n database: z.object({\n type: z.enum(['sqlite', 'postgresql', 'mysql', 'mongodb']).default('sqlite'),\n url: z.string().optional(),\n host: z.string().default('localhost'),\n port: z.number().optional(),\n name: z.string().default('content_management'),\n username: z.string().optional(),\n password: z.string().optional(),\n ssl: z.boolean().default(false),\n pool: z.object({\n min: z.number().default(2),\n max: z.number().default(10),\n idleTimeoutMs: z.number().optional(),\n }).default({}),\n }).default({}),\n\n integrations: z.object({\n neverAdmin: z.object({\n enabled: z.boolean().default(false),\n endpoint: z.string().optional(),\n }).default({}),\n neverHub: z.object({\n enabled: z.boolean().default(false),\n endpoint: z.string().optional(),\n }).default({}),\n analytics: z.object({\n enabled: z.boolean().default(false),\n provider: z.string().optional(),\n }).default({}),\n }).default({}),\n\n security: z.object({\n permissions: z.object({\n enabled: z.boolean().default(true),\n defaultRole: z.string().default('user'),\n }).default({}),\n roles: z.array(z.object({\n name: z.string(),\n permissions: z.array(z.string()),\n description: z.string().optional(),\n })).default([\n { name: 'admin', permissions: ['*'], description: 'Full administrative access' },\n { name: 'editor', permissions: ['content.edit', 'content.publish', 'content.schedule'], description: 'Content editing and publishing' },\n { name: 'author', permissions: ['content.edit'], description: 'Content creation and editing' },\n { name: 'user', permissions: ['content.view'], description: 'Content viewing only' },\n ]),\n }).default({}),\n\n workflows: z.object({\n defaults: z.record(z.string(), z.string()).default({}),\n }).default({}),\n\n logging: z.object({\n level: z.enum(['error', 'warn', 'info', 'debug']).default('info'),\n }).default({}),\n\n performance: z.object({\n cache: z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().default(300),\n maxSize: z.number().default(1000),\n }).default({}),\n }).default({}),\n});\n\nexport type ContentManagementConfig = z.infer<typeof ContentManagementConfigSchema>;\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nexport class ContentManagementError extends Error {\n readonly code: string;\n readonly details?: Record<string, unknown>;\n\n constructor(message: string, options?: {\n cause?: Error;\n code?: string;\n details?: Record<string, unknown>;\n }) {\n super(message);\n // Attach cause manually (ES2022 feature; tsconfig targets ES2020 so we set it post-construction)\n if (options?.cause !== undefined) {\n (this as unknown as { cause: Error }).cause = options.cause;\n }\n this.name = this.constructor.name;\n this.code = options?.code ?? 'CONTENT_MANAGEMENT_ERROR';\n if (options?.details !== undefined) {\n this.details = options.details;\n }\n }\n}\n\nexport class ValidationError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; details?: Record<string, unknown> }) {\n super(message, { ...options, code: 'VALIDATION_ERROR' });\n }\n}\n\nexport class NotFoundError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; details?: Record<string, unknown> }) {\n super(message, { ...options, code: 'NOT_FOUND' });\n }\n}\n\nexport class UnauthorizedError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; details?: Record<string, unknown> }) {\n super(message, { ...options, code: 'UNAUTHORIZED' });\n }\n}\n\nexport class ForbiddenError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; details?: Record<string, unknown> }) {\n super(message, { ...options, code: 'FORBIDDEN' });\n }\n}\n\nexport class ConflictError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; details?: Record<string, unknown> }) {\n super(message, { ...options, code: 'CONFLICT' });\n }\n}\n\nexport class InternalError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; details?: Record<string, unknown> }) {\n super(message, { ...options, code: 'INTERNAL_ERROR' });\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport type {\n ContentItem,\n ContentFilters,\n SearchOptions,\n PaginatedResult,\n Workflow,\n SocialPost,\n AIReview,\n} from './types';\n\nimport type {\n ContentStorageAdapter,\n ContentStorageNamespace,\n WorkflowStorageNamespace,\n ContentTypeStorageNamespace,\n SocialPostStorageNamespace,\n AIReviewStorageNamespace,\n StoredContentTypeDefinition,\n} from './storage';\n\n// --- In-Memory Content Storage ---\n\nclass InMemoryContentStorage implements ContentStorageNamespace {\n private readonly store = new Map<string, ContentItem>();\n\n async list(filters?: ContentFilters): Promise<PaginatedResult<ContentItem>> {\n let items = Array.from(this.store.values());\n\n if (filters?.type) {\n items = items.filter((item) => item.type === filters.type);\n }\n if (filters?.status) {\n items = items.filter((item) => item.status === filters.status);\n }\n\n const total = items.length;\n const page = filters?.page ?? 1;\n const limit = filters?.limit ?? items.length;\n const start = (page - 1) * limit;\n const paged = items.slice(start, start + limit);\n\n return { items: paged, total, page, limit };\n }\n\n async get(id: string): Promise<ContentItem | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(item: ContentItem): Promise<ContentItem> {\n this.store.set(item.id, item);\n return item;\n }\n\n async update(id: string, partial: Partial<ContentItem>): Promise<ContentItem> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Content item not found: ${id}`);\n }\n const updated: ContentItem = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n\n async findBySource(sourceType: string, sourceId: string): Promise<ContentItem | null> {\n for (const item of this.store.values()) {\n if (item.sourceType === sourceType && item.sourceId === sourceId) {\n return item;\n }\n }\n return null;\n }\n\n async search(query: string, options?: SearchOptions): Promise<PaginatedResult<ContentItem>> {\n const lowerQuery = query.toLowerCase();\n let items = Array.from(this.store.values()).filter((item) => {\n const titleMatch = item.title && item.title.toLowerCase().includes(lowerQuery);\n const bodyMatch = item.body && item.body.toLowerCase().includes(lowerQuery);\n const dataMatch = item.data && Object.values(item.data).some(\n (value) => typeof value === 'string' && value.toLowerCase().includes(lowerQuery)\n );\n return titleMatch || bodyMatch || dataMatch;\n });\n\n if (options?.type) {\n items = items.filter((item) => item.type === options.type);\n }\n if (options?.status) {\n items = items.filter((item) => item.status === options.status);\n }\n\n const total = items.length;\n const page = options?.page ?? 1;\n const limit = options?.limit ?? items.length;\n const start = (page - 1) * limit;\n const paged = items.slice(start, start + limit);\n\n return { items: paged, total, page, limit };\n }\n}\n\n// --- In-Memory Workflow Storage ---\n\nclass InMemoryWorkflowStorage implements WorkflowStorageNamespace {\n private readonly store = new Map<string, Workflow>();\n private readonly contentTypeMap = new Map<string, string>(); // contentType -> workflowId\n\n async list(): Promise<Workflow[]> {\n return Array.from(this.store.values());\n }\n\n async get(id: string): Promise<Workflow | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(workflow: Workflow): Promise<Workflow> {\n this.store.set(workflow.id, workflow);\n return workflow;\n }\n\n async update(id: string, partial: Partial<Workflow>): Promise<Workflow> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Workflow not found: ${id}`);\n }\n const updated: Workflow = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n // Remove content type mappings pointing to this workflow\n for (const [ct, wId] of this.contentTypeMap.entries()) {\n if (wId === id) {\n this.contentTypeMap.delete(ct);\n }\n }\n }\n\n async findByContentType(contentType: string): Promise<Workflow | null> {\n const workflowId = this.contentTypeMap.get(contentType);\n if (!workflowId) {\n return null;\n }\n return this.store.get(workflowId) ?? null;\n }\n\n setContentTypeMapping(contentType: string, workflowId: string): void {\n this.contentTypeMap.set(contentType, workflowId);\n }\n}\n\n// --- In-Memory Content Type Storage ---\n\nclass InMemoryContentTypeStorage implements ContentTypeStorageNamespace {\n private readonly store = new Map<string, StoredContentTypeDefinition>();\n\n async list(): Promise<StoredContentTypeDefinition[]> {\n return Array.from(this.store.values());\n }\n\n async get(id: string): Promise<StoredContentTypeDefinition | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(def: StoredContentTypeDefinition): Promise<StoredContentTypeDefinition> {\n this.store.set(def.id, def);\n return def;\n }\n\n async update(id: string, partial: Partial<StoredContentTypeDefinition>): Promise<StoredContentTypeDefinition> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Content type not found: ${id}`);\n }\n const updated: StoredContentTypeDefinition = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n}\n\n// --- In-Memory Social Post Storage ---\n\nclass InMemorySocialPostStorage implements SocialPostStorageNamespace {\n private readonly store = new Map<string, SocialPost>();\n\n async list(filters?: { contentId?: string; platform?: string; status?: string }): Promise<SocialPost[]> {\n let items = Array.from(this.store.values());\n\n if (filters?.contentId) {\n items = items.filter((p) => p.contentId === filters.contentId);\n }\n if (filters?.platform) {\n items = items.filter((p) => p.platform === filters.platform);\n }\n if (filters?.status) {\n items = items.filter((p) => p.status === filters.status);\n }\n\n return items;\n }\n\n async get(id: string): Promise<SocialPost | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(post: SocialPost): Promise<SocialPost> {\n this.store.set(post.id, post);\n return post;\n }\n\n async update(id: string, partial: Partial<SocialPost>): Promise<SocialPost> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Social post not found: ${id}`);\n }\n const updated: SocialPost = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n\n async findByContent(contentId: string): Promise<SocialPost[]> {\n return Array.from(this.store.values()).filter((p) => p.contentId === contentId);\n }\n}\n\n// --- In-Memory AI Review Storage ---\n\nclass InMemoryAIReviewStorage implements AIReviewStorageNamespace {\n private readonly store = new Map<string, AIReview>();\n\n async list(filters?: { contentId?: string }): Promise<AIReview[]> {\n let items = Array.from(this.store.values());\n\n if (filters?.contentId) {\n items = items.filter((r) => r.contentId === filters.contentId);\n }\n\n return items;\n }\n\n async get(id: string): Promise<AIReview | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(review: AIReview): Promise<AIReview> {\n this.store.set(review.id, review);\n return review;\n }\n\n async findByContent(contentId: string): Promise<AIReview[]> {\n return Array.from(this.store.values()).filter((r) => r.contentId === contentId);\n }\n\n async getLatestForContent(contentId: string): Promise<AIReview | null> {\n const reviews = await this.findByContent(contentId);\n if (reviews.length === 0) {\n return null;\n }\n // Sort by createdAt descending and return the first\n reviews.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n return reviews[0] ?? null;\n }\n}\n\n// --- Factory Function ---\n\nexport function createInMemoryAdapter(): ContentStorageAdapter {\n return {\n content: new InMemoryContentStorage(),\n workflows: new InMemoryWorkflowStorage(),\n contentTypes: new InMemoryContentTypeStorage(),\n socialPosts: new InMemorySocialPostStorage(),\n aiReviews: new InMemoryAIReviewStorage(),\n };\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type {\n ContentNamespace,\n ContentItem,\n CreateContentInput,\n UpdateContentInput,\n ContentFilters,\n SearchOptions,\n PaginatedResult,\n ContentTypesNamespace,\n PublishersNamespace,\n} from '../types';\nimport type { ContentPublishResult, PublishResult } from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ValidationError } from '../errors';\n\nexport class ContentNamespaceImpl implements ContentNamespace {\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n private readonly getContentTypes: () => ContentTypesNamespace;\n private readonly getPublishers: () => PublishersNamespace;\n\n constructor(\n emitter: EventEmitter,\n storage: ContentStorageAdapter,\n getContentTypes: () => ContentTypesNamespace,\n getPublishers: () => PublishersNamespace,\n ) {\n this.emitter = emitter;\n this.storage = storage;\n this.getContentTypes = getContentTypes;\n this.getPublishers = getPublishers;\n }\n\n async create(input: CreateContentInput): Promise<ContentItem> {\n // Validate against content type schema if registered\n const contentTypes = this.getContentTypes();\n const typeDef = contentTypes.get(input.type);\n if (typeDef && typeDef.schema) {\n const dataToValidate: Record<string, unknown> = {\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.data ?? {}),\n };\n const result = contentTypes.validate(input.type, dataToValidate);\n if (!result.valid) {\n throw new ValidationError('Content type schema validation failed', {\n details: { errors: result.errors },\n });\n }\n }\n\n const item: ContentItem = {\n id: crypto.randomUUID(),\n type: input.type,\n createdAt: new Date().toISOString(),\n status: 'draft',\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.data !== undefined ? { data: { ...input.data } } : {}),\n ...(input.channels !== undefined ? { channels: input.channels } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n\n const created = await this.storage.content.create(item);\n this.emitter.emit('content:created', created);\n return created;\n }\n\n async get(id: string): Promise<ContentItem> {\n const item = await this.storage.content.get(id);\n if (!item) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n return item;\n }\n\n async list(filters?: ContentFilters): Promise<PaginatedResult<ContentItem>> {\n return this.storage.content.list(filters);\n }\n\n async update(id: string, input: UpdateContentInput): Promise<ContentItem> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n\n const partial: Partial<ContentItem> = {\n updatedAt: new Date().toISOString(),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.status !== undefined ? { status: input.status } : {}),\n ...(input.channels !== undefined ? { channels: input.channels } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n\n if (input.data !== undefined) {\n partial.data = { ...(existing.data ?? {}), ...input.data };\n }\n\n const updated = await this.storage.content.update(id, partial);\n this.emitter.emit('content:updated', updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n await this.storage.content.delete(id);\n this.emitter.emit('content:deleted', { id });\n }\n\n async publish(id: string, options?: { channels?: string[] }): Promise<ContentPublishResult> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n\n // Check publish-stage gating\n if (existing.workflowId) {\n const workflow = await this.storage.workflows.get(existing.workflowId);\n if (workflow && workflow.stages && workflow.stages.length > 0) {\n const currentStage = workflow.stages.find((s) => s.id === existing.workflowStage);\n const publishStage = workflow.stages.find((s) => s.isPublishStage);\n if (publishStage && (!currentStage || !currentStage.isPublishStage)) {\n throw new ValidationError(\n `Content is not at a publish-eligible stage. Current stage: \"${existing.workflowStage ?? 'none'}\", ` +\n `required publish stage: \"${publishStage.id}\"`,\n {\n details: {\n currentStage: existing.workflowStage ?? null,\n requiredStage: publishStage.id,\n },\n },\n );\n }\n }\n }\n\n const publishers = this.getPublishers();\n const allPublishers = publishers.list();\n\n // Determine which channels to publish to\n const channelIds = options?.channels ?? existing.channels;\n\n let targetPublishers;\n if (channelIds && channelIds.length > 0) {\n targetPublishers = allPublishers.filter((p) => channelIds.includes(p.id));\n } else {\n // Publish to all publishers that accept this content type\n targetPublishers = allPublishers.filter((p) => p.acceptedTypes.includes(existing.type));\n }\n\n const results: PublishResult[] = [];\n\n for (const publisher of targetPublishers) {\n // Type check\n if (!publisher.acceptedTypes.includes(existing.type)) {\n results.push({\n channelId: publisher.id,\n success: false,\n error: `Content type \"${existing.type}\" not accepted by publisher \"${publisher.id}\". Accepted: ${publisher.acceptedTypes.join(', ')}`,\n });\n continue;\n }\n\n // Validate if publisher provides validate method\n if (publisher.validate) {\n const validationErrors = await publisher.validate(existing);\n if (validationErrors.length > 0) {\n results.push({\n channelId: publisher.id,\n success: false,\n error: `Validation failed: ${validationErrors.map((e) => e.message).join(', ')}`,\n });\n continue;\n }\n }\n\n try {\n const result = await publisher.publish(existing);\n results.push(result);\n } catch (error) {\n results.push({\n channelId: publisher.id,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Update content status\n const now = new Date().toISOString();\n const updated = await this.storage.content.update(id, {\n status: 'published',\n publishedAt: now,\n updatedAt: now,\n });\n\n const publishResult: ContentPublishResult = { item: updated, results };\n this.emitter.emit('content:published', publishResult);\n return publishResult;\n }\n\n async unpublish(id: string): Promise<ContentItem> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n const updated = await this.storage.content.update(id, {\n status: 'draft',\n updatedAt: new Date().toISOString(),\n });\n this.emitter.emit('content:unpublished', updated);\n return updated;\n }\n\n async schedule(id: string, date: Date): Promise<ContentItem> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n const updated = await this.storage.content.update(id, {\n scheduledFor: date,\n updatedAt: new Date().toISOString(),\n });\n this.emitter.emit('content:scheduled', { item: updated, date });\n return updated;\n }\n\n async search(query: string, options?: SearchOptions): Promise<PaginatedResult<ContentItem>> {\n return this.storage.content.search(query, options);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { z } from 'zod';\nimport type { ContentTypesNamespace } from '../types';\nimport type { ContentTypeDefinition, SchemaValidationResult } from '../interfaces';\nimport { NotFoundError } from '../errors';\n\nexport class ContentTypesNamespaceImpl implements ContentTypesNamespace {\n private readonly store = new Map<string, ContentTypeDefinition>();\n\n register(definition: ContentTypeDefinition | { id?: string; name?: string }): void {\n // Support both legacy { id, name } and new ContentTypeDefinition\n if ('schema' in definition && definition.schema) {\n const def = definition as ContentTypeDefinition;\n this.store.set(def.id, def);\n } else {\n const id = definition.id ?? definition.name;\n if (!id) {\n throw new Error('Content type must have an id or name');\n }\n const name = definition.name ?? definition.id ?? id;\n // Legacy registration without schema - store with no schema\n this.store.set(id, {\n id,\n name,\n schema: null as unknown,\n });\n }\n }\n\n unregister(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Content type not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n get(id: string): ContentTypeDefinition | undefined {\n return this.store.get(id);\n }\n\n list(): ContentTypeDefinition[] {\n return Array.from(this.store.values());\n }\n\n validate(type: string, data: Record<string, unknown>): SchemaValidationResult {\n const def = this.store.get(type);\n if (!def || !def.schema) {\n // No schema registered - pass through\n return { valid: true };\n }\n\n try {\n // Assume schema is a Zod schema\n const schema = def.schema as z.ZodType;\n schema.parse(data);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((issue) => ({\n message: issue.message,\n path: issue.path.map(String),\n })),\n };\n }\n return {\n valid: false,\n errors: [{ message: error instanceof Error ? error.message : String(error) }],\n };\n }\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport * as crypto from 'crypto';\nimport type {\n WorkflowsNamespace,\n Workflow,\n CreateWorkflowInput,\n UpdateWorkflowInput,\n} from '../types';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ConflictError } from '../errors';\n\nexport class WorkflowsNamespaceImpl implements WorkflowsNamespace {\n private readonly cache = new Map<string, Workflow>();\n private readonly storage: ContentStorageAdapter | undefined;\n\n constructor(storage?: ContentStorageAdapter) {\n this.storage = storage;\n }\n\n /** Load workflows from storage into cache. Called during suite initialization. */\n async loadFromStorage(): Promise<void> {\n if (!this.storage) {\n return;\n }\n const workflows = await this.storage.workflows.list();\n for (const w of workflows) {\n this.cache.set(w.id, w);\n }\n }\n\n async create(input: CreateWorkflowInput): Promise<Workflow> {\n const workflow: Workflow = {\n id: crypto.randomUUID(),\n name: input.name,\n ...(input.description !== undefined ? { description: input.description } : {}),\n ...(input.stages !== undefined ? { stages: input.stages } : {}),\n ...(input.transitions !== undefined ? { transitions: input.transitions } : {}),\n };\n\n // Persist to storage\n if (this.storage) {\n await this.storage.workflows.create(workflow);\n }\n\n this.cache.set(workflow.id, workflow);\n return workflow;\n }\n\n async get(id: string): Promise<Workflow> {\n const workflow = this.cache.get(id);\n if (!workflow) {\n throw new NotFoundError(`Workflow not found: ${id}`);\n }\n return workflow;\n }\n\n async list(): Promise<Workflow[]> {\n return Array.from(this.cache.values());\n }\n\n async update(id: string, input: UpdateWorkflowInput): Promise<Workflow> {\n const existing = this.cache.get(id);\n if (!existing) {\n throw new NotFoundError(`Workflow not found: ${id}`);\n }\n\n const updated: Workflow = {\n ...existing,\n ...(input.name !== undefined ? { name: input.name } : {}),\n ...(input.description !== undefined ? { description: input.description } : {}),\n ...(input.stages !== undefined ? { stages: input.stages } : {}),\n ...(input.transitions !== undefined ? { transitions: input.transitions } : {}),\n };\n\n // Persist to storage\n if (this.storage) {\n await this.storage.workflows.update(id, updated);\n }\n\n this.cache.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n if (!this.cache.has(id)) {\n throw new NotFoundError(`Workflow not found: ${id}`);\n }\n\n // Check if any content references this workflow\n if (this.storage) {\n const contentResult = await this.storage.content.list();\n const assignedContent = contentResult.items.filter((item) => item.workflowId === id);\n if (assignedContent.length > 0) {\n throw new ConflictError(\n `Cannot delete workflow \"${id}\": ${assignedContent.length} content item(s) are assigned to it. Reassign or archive them first.`,\n { details: { assignedCount: assignedContent.length } },\n );\n }\n await this.storage.workflows.delete(id);\n }\n\n this.cache.delete(id);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type {\n UsersNamespace,\n PermissionsNamespace,\n User,\n CreateUserInput,\n UpdateUserInput,\n PaginatedResult,\n} from '../types';\nimport { NotFoundError } from '../errors';\n\nexport class UsersNamespaceImpl implements UsersNamespace {\n private readonly store = new Map<string, User>();\n private readonly emitter: EventEmitter;\n\n constructor(emitter: EventEmitter) {\n this.emitter = emitter;\n }\n\n async create(input: CreateUserInput): Promise<User> {\n const user: User = {\n id: crypto.randomUUID(),\n name: input.name,\n ...(input.email !== undefined ? { email: input.email } : {}),\n ...(input.role !== undefined ? { role: input.role } : {}),\n createdAt: new Date().toISOString(),\n };\n this.store.set(user.id, user);\n this.emitter.emit('user:created', user);\n return user;\n }\n\n async get(id: string): Promise<User> {\n const user = this.store.get(id);\n if (!user) {\n throw new NotFoundError(`User not found: ${id}`);\n }\n return user;\n }\n\n async list(): Promise<PaginatedResult<User>> {\n const items = Array.from(this.store.values());\n return { items, total: items.length };\n }\n\n async update(id: string, input: UpdateUserInput): Promise<User> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new NotFoundError(`User not found: ${id}`);\n }\n const updated: User = {\n ...existing,\n ...input,\n updatedAt: new Date().toISOString(),\n };\n this.store.set(id, updated);\n this.emitter.emit('user:updated', updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n if (!this.store.has(id)) {\n throw new NotFoundError(`User not found: ${id}`);\n }\n this.store.delete(id);\n this.emitter.emit('user:deleted', { id });\n }\n}\n\nexport class PermissionsNamespaceImpl implements PermissionsNamespace {\n private readonly store = new Map<string, Set<string>>();\n\n async check(userId: string, permission: string): Promise<boolean> {\n const perms = this.store.get(userId);\n return perms?.has(permission) ?? false;\n }\n\n async grant(userId: string, permission: string): Promise<void> {\n let perms = this.store.get(userId);\n if (!perms) {\n perms = new Set();\n this.store.set(userId, perms);\n }\n perms.add(permission);\n }\n\n async revoke(userId: string, permission: string): Promise<void> {\n const perms = this.store.get(userId);\n if (perms) {\n perms.delete(permission);\n }\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport type { ConfigNamespace } from '../types';\nimport type { ContentManagementConfig } from '../config';\nimport { ContentManagementConfigSchema } from '../config';\nimport { ValidationError } from '../errors';\n\nfunction deepMerge<T extends Record<string, unknown>>(target: T, source: Partial<T>): T {\n const result = { ...target } as Record<string, unknown>;\n for (const key of Object.keys(source)) {\n const sourceVal = (source as Record<string, unknown>)[key];\n const targetVal = result[key];\n if (\n sourceVal !== null &&\n sourceVal !== undefined &&\n typeof sourceVal === 'object' &&\n !Array.isArray(sourceVal) &&\n targetVal !== null &&\n targetVal !== undefined &&\n typeof targetVal === 'object' &&\n !Array.isArray(targetVal)\n ) {\n result[key] = deepMerge(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>\n );\n } else {\n result[key] = sourceVal;\n }\n }\n return result as T;\n}\n\nexport class ConfigNamespaceImpl implements ConfigNamespace {\n private config: ContentManagementConfig;\n private readonly emitter: EventEmitter;\n\n constructor(initialConfig: ContentManagementConfig, emitter: EventEmitter) {\n this.config = initialConfig;\n this.emitter = emitter;\n }\n\n get(): ContentManagementConfig {\n return this.config;\n }\n\n update(partial: Partial<ContentManagementConfig>): ContentManagementConfig {\n const merged = deepMerge(this.config, partial);\n try {\n this.config = ContentManagementConfigSchema.parse(merged);\n } catch (err) {\n throw new ValidationError('Invalid configuration',\n err instanceof Error ? { cause: err } : undefined,\n );\n }\n this.emitter.emit('config:updated', this.config);\n return this.config;\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport type { PluginsNamespace, SuitePlugin, ContentManagementSuite } from '../types';\nimport { ConflictError, NotFoundError } from '../errors';\n\nexport class PluginsNamespaceImpl implements PluginsNamespace {\n private readonly store = new Map<string, SuitePlugin>();\n private readonly suite: ContentManagementSuite;\n\n constructor(suite: ContentManagementSuite) {\n this.suite = suite;\n }\n\n async register(plugin: SuitePlugin): Promise<void> {\n if (this.store.has(plugin.name)) {\n throw new ConflictError(`Plugin already registered: ${plugin.name}`);\n }\n await plugin.setup(this.suite);\n this.store.set(plugin.name, plugin);\n }\n\n async unregister(name: string): Promise<void> {\n const plugin = this.store.get(name);\n if (!plugin) {\n throw new NotFoundError(`Plugin not found: ${name}`);\n }\n if (plugin.teardown) {\n await plugin.teardown(this.suite);\n }\n this.store.delete(name);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport type { PublishersNamespace, ContentItem } from '../types';\nimport type { ContentPublisher, PublishResult } from '../interfaces';\nimport { NotFoundError } from '../errors';\n\n// --- Built-in Website Publisher ---\n\nclass WebsitePublisher implements ContentPublisher {\n readonly id = 'website';\n readonly name = 'Website';\n readonly acceptedTypes = ['blog-post', 'article', 'page', 'generic', 'text'];\n\n async publish(content: ContentItem): Promise<PublishResult> {\n const slug = content.title\n ? content.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n : content.id;\n return {\n channelId: this.id,\n success: true,\n url: `/content/${slug}`,\n };\n }\n}\n\n// --- Built-in RSS Publisher ---\n\nclass RSSPublisher implements ContentPublisher {\n readonly id = 'rss';\n readonly name = 'RSS Feed';\n readonly acceptedTypes = ['blog-post', 'article', 'rss-article', 'generic', 'text'];\n\n async publish(content: ContentItem): Promise<PublishResult> {\n return {\n channelId: this.id,\n success: true,\n url: `/feed/rss/${content.id}`,\n };\n }\n}\n\n// --- Publishers Namespace Implementation ---\n\nexport class PublishersNamespaceImpl implements PublishersNamespace {\n private readonly store = new Map<string, ContentPublisher>();\n private readonly emitter: EventEmitter;\n\n constructor(emitter: EventEmitter) {\n this.emitter = emitter;\n\n // Register built-in publishers\n this.store.set('website', new WebsitePublisher());\n this.store.set('rss', new RSSPublisher());\n }\n\n register(publisher: ContentPublisher): void {\n this.store.set(publisher.id, publisher);\n this.emitter.emit('publisher:registered', { publisher });\n }\n\n unregister(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Publisher not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n list(): ContentPublisher[] {\n return Array.from(this.store.values());\n }\n\n get(id: string): ContentPublisher | undefined {\n return this.store.get(id);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type { SourcesNamespace, ContentItem } from '../types';\nimport type { ContentSource, IngestResult } from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ValidationError } from '../errors';\n\nexport class SourcesNamespaceImpl implements SourcesNamespace {\n private readonly store = new Map<string, ContentSource>();\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n private readonly workflowDefaults: Record<string, string>;\n\n constructor(\n emitter: EventEmitter,\n storage: ContentStorageAdapter,\n workflowDefaults: Record<string, string>,\n ) {\n this.emitter = emitter;\n this.storage = storage;\n this.workflowDefaults = workflowDefaults;\n }\n\n register(source: ContentSource): void {\n this.store.set(source.id, source);\n this.emitter.emit('source:registered', { source });\n }\n\n unregister(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Source not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n list(): ContentSource[] {\n return Array.from(this.store.values());\n }\n\n get(id: string): ContentSource | undefined {\n return this.store.get(id);\n }\n\n async ingest(sourceId: string, rawPayload: unknown): Promise<IngestResult> {\n const source = this.store.get(sourceId);\n if (!source) {\n throw new NotFoundError(`Source not found: ${sourceId}`);\n }\n\n // Validate if the source provides a validate method\n if (source.validate) {\n const validationErrors = await source.validate(rawPayload);\n if (validationErrors.length > 0) {\n throw new ValidationError('Source validation failed', {\n details: { errors: validationErrors },\n });\n }\n }\n\n // Ingest the payload\n const rawItem = await source.ingest(rawPayload);\n\n // Dedup check: if sourceId is set on the item, check for existing\n if (rawItem.sourceId) {\n const existing = await this.storage.content.findBySource(source.id, rawItem.sourceId);\n if (existing) {\n return { created: false, content: existing };\n }\n }\n\n // Build the content item\n const now = new Date().toISOString();\n const workflowId = this.workflowDefaults[rawItem.type] ?? this.workflowDefaults['generic'];\n\n const item: ContentItem = {\n id: crypto.randomUUID(),\n type: rawItem.type,\n createdAt: now,\n status: 'review',\n sourceType: source.id,\n sourceId: rawItem.sourceId ?? null,\n ...(rawItem.title !== undefined ? { title: rawItem.title } : {}),\n ...(rawItem.body !== undefined ? { body: rawItem.body } : {}),\n ...(rawItem.data !== undefined ? { data: rawItem.data } : {}),\n ...(rawItem.metadata !== undefined ? { metadata: rawItem.metadata } : {}),\n ...(workflowId !== undefined ? { workflowId } : {}),\n };\n\n // Persist\n const created = await this.storage.content.create(item);\n\n // Emit events\n this.emitter.emit('content:ingested', { item: created, sourceType: source.id });\n this.emitter.emit('content:created', created);\n\n return { created: true, content: created };\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type { AINamespace, AIReview, SocialPost } from '../types';\nimport type {\n AIReviewService,\n AISocialGeneratorService,\n AIEnhanceService,\n EnhancedContent,\n EnhanceOptions,\n Suggestion,\n AIReviewSuggestion,\n} from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, InternalError } from '../errors';\n\nexport class AINamespaceImpl implements AINamespace {\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n private readonly reviewService: AIReviewService | undefined;\n private readonly socialGeneratorService: AISocialGeneratorService | undefined;\n private readonly enhanceService: AIEnhanceService | undefined;\n private readonly workflowDefaults: Record<string, string>;\n\n constructor(\n emitter: EventEmitter,\n storage: ContentStorageAdapter,\n options: {\n reviewService?: AIReviewService;\n socialGeneratorService?: AISocialGeneratorService;\n enhanceService?: AIEnhanceService;\n workflowDefaults?: Record<string, string>;\n },\n ) {\n this.emitter = emitter;\n this.storage = storage;\n this.reviewService = options.reviewService;\n this.socialGeneratorService = options.socialGeneratorService;\n this.enhanceService = options.enhanceService;\n this.workflowDefaults = options.workflowDefaults ?? {};\n }\n\n async review(contentId: string): Promise<AIReview> {\n if (!this.reviewService) {\n throw new InternalError('AI review service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n // Build text to review from available content fields\n const textToReview = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n const result = await this.reviewService.review(textToReview);\n\n // Map result to AIReview\n const suggestions: AIReviewSuggestion[] = result.issues.map((issue) => ({\n category: issue.category,\n severity: (issue.severity === 'info' || issue.severity === 'warning' || issue.severity === 'error')\n ? issue.severity\n : 'info' as const,\n message: issue.message,\n ...(issue.originalText !== undefined ? { originalText: issue.originalText } : {}),\n ...(issue.suggestedFix !== undefined ? { suggestedFix: issue.suggestedFix } : {}),\n }));\n\n const review: AIReview = {\n id: crypto.randomUUID(),\n contentId,\n score: result.overallScore,\n suggestions,\n passesThreshold: result.passesThreshold,\n rawResult: result.raw,\n createdAt: new Date().toISOString(),\n };\n\n // Persist\n await this.storage.aiReviews.create(review);\n\n // Emit event\n this.emitter.emit('ai:review:completed', { contentId, review });\n\n return review;\n }\n\n async generateSocialPosts(contentId: string, platforms: string[]): Promise<SocialPost[]> {\n if (!this.socialGeneratorService) {\n throw new InternalError('AI social generator service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n const textContent = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n const generated = await this.socialGeneratorService.generate(textContent, platforms);\n\n const now = new Date().toISOString();\n const workflowId = this.workflowDefaults['social-post'] ?? this.workflowDefaults['generic'];\n\n const posts: SocialPost[] = generated.map((g) => ({\n id: crypto.randomUUID(),\n contentId,\n platform: g.platform,\n body: g.body,\n status: 'draft' as const,\n platformPostId: null,\n publishedAt: null,\n createdAt: now,\n ...(workflowId !== undefined ? { workflowId } : {}),\n }));\n\n // Persist all posts\n for (const post of posts) {\n await this.storage.socialPosts.create(post);\n }\n\n // Emit event\n this.emitter.emit('ai:social:generated', { contentId, posts });\n\n return posts;\n }\n\n async enhance(contentId: string, opts?: EnhanceOptions): Promise<EnhancedContent> {\n if (!this.enhanceService) {\n throw new InternalError('AI enhance service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n const textContent = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n return this.enhanceService.enhance(textContent, opts);\n }\n\n async suggest(contentId: string): Promise<Suggestion[]> {\n if (!this.enhanceService) {\n throw new InternalError('AI enhance service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n const textContent = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n return this.enhanceService.suggest(textContent);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport type { SocialNamespace } from '../types';\nimport type {\n SocialPlatformAdapter,\n PlatformPublishResult,\n PlatformInfo,\n PreviewResult,\n SocialMetrics,\n} from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ValidationError, InternalError } from '../errors';\n\nexport class SocialNamespaceImpl implements SocialNamespace {\n private readonly store = new Map<string, SocialPlatformAdapter>();\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n\n constructor(emitter: EventEmitter, storage: ContentStorageAdapter) {\n this.emitter = emitter;\n this.storage = storage;\n }\n\n registerPlatform(adapter: SocialPlatformAdapter): void {\n this.store.set(adapter.id, adapter);\n }\n\n unregisterPlatform(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Social platform not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n listPlatforms(): PlatformInfo[] {\n return Array.from(this.store.values()).map((adapter) => ({\n id: adapter.id,\n name: adapter.name,\n acceptedTypes: adapter.acceptedTypes,\n hasPreview: typeof adapter.preview === 'function',\n hasMetrics: typeof adapter.getMetrics === 'function',\n }));\n }\n\n async publish(contentId: string, platforms: string[]): Promise<PlatformPublishResult[]> {\n // Check all platforms are registered\n const missing = platforms.filter((p) => !this.store.has(p));\n if (missing.length > 0) {\n throw new ValidationError(\n `Unregistered social platform(s): ${missing.join(', ')}`,\n { details: { missingPlatforms: missing } },\n );\n }\n\n // Get content\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n // Check publish-stage gating: content must be at a publish-eligible workflow stage\n if (content.workflowId) {\n const workflow = await this.storage.workflows.get(content.workflowId);\n if (workflow && workflow.stages && workflow.stages.length > 0) {\n const currentStage = workflow.stages.find((s) => s.id === content.workflowStage);\n const publishStage = workflow.stages.find((s) => s.isPublishStage);\n if (publishStage && (!currentStage || !currentStage.isPublishStage)) {\n throw new ValidationError(\n `Content is not at a publish-eligible stage. Current stage: \"${content.workflowStage ?? 'none'}\", ` +\n `required publish stage: \"${publishStage.id}\"`,\n {\n details: {\n currentStage: content.workflowStage ?? null,\n requiredStage: publishStage.id,\n },\n },\n );\n }\n }\n }\n\n // Get social posts for this content\n const socialPosts = await this.storage.socialPosts.findByContent(contentId);\n\n const results: PlatformPublishResult[] = [];\n\n for (const platformId of platforms) {\n const adapter = this.store.get(platformId);\n if (!adapter) {\n continue;\n }\n\n // Type validation\n if (!adapter.acceptedTypes.includes(content.type)) {\n results.push({\n platform: platformId,\n success: false,\n error: `Content type \"${content.type}\" not accepted by platform \"${platformId}\". Accepted: ${adapter.acceptedTypes.join(', ')}`,\n });\n continue;\n }\n\n // Find a social post for this platform\n const post = socialPosts.find((p) => p.platform === platformId && p.status === 'draft');\n if (!post) {\n results.push({\n platform: platformId,\n success: false,\n error: `No draft social post found for platform \"${platformId}\"`,\n });\n continue;\n }\n\n try {\n const result = await adapter.publish(post);\n results.push(result);\n\n // Update social post status\n if (result.success) {\n await this.storage.socialPosts.update(post.id, {\n status: 'published',\n publishedAt: new Date().toISOString(),\n ...(result.platformPostId !== undefined ? { platformPostId: result.platformPostId } : {}),\n });\n this.emitter.emit('social:published', { contentId, platform: platformId, result });\n } else {\n await this.storage.socialPosts.update(post.id, { status: 'failed' });\n }\n } catch (error) {\n await this.storage.socialPosts.update(post.id, { status: 'failed' });\n results.push({\n platform: platformId,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return results;\n }\n\n async preview(contentId: string, platform: string): Promise<PreviewResult> {\n const adapter = this.store.get(platform);\n if (!adapter) {\n throw new NotFoundError(`Social platform not found: ${platform}`);\n }\n\n if (!adapter.preview) {\n throw new InternalError(`Platform \"${platform}\" does not support preview`);\n }\n\n const posts = await this.storage.socialPosts.findByContent(contentId);\n const post = posts.find((p) => p.platform === platform);\n if (!post) {\n throw new NotFoundError(`No social post found for content \"${contentId}\" on platform \"${platform}\"`);\n }\n\n return adapter.preview(post);\n }\n\n async getMetrics(contentId: string, platform: string): Promise<SocialMetrics> {\n const adapter = this.store.get(platform);\n if (!adapter) {\n throw new NotFoundError(`Social platform not found: ${platform}`);\n }\n\n if (!adapter.getMetrics) {\n throw new InternalError(`Platform \"${platform}\" does not support metrics`);\n }\n\n const posts = await this.storage.socialPosts.findByContent(contentId);\n const post = posts.find((p) => p.platform === platform && p.platformPostId);\n if (!post || !post.platformPostId) {\n throw new NotFoundError(`No published social post found for content \"${contentId}\" on platform \"${platform}\"`);\n }\n\n return adapter.getMetrics(post.platformPostId);\n }\n}\n"],"mappings":";AAQA,SAAS,oBAAoB;;;ACA7B,SAAS,SAAS;AAEX,IAAM,gCAAgC,EAAE,OAAO;AAAA,EACpD,SAAS,EAAE,OAAO;AAAA,IAChB,iBAAiB,EAAE,OAAO;AAAA,MACxB,IAAI,EAAE,OAAO,EAAE,QAAQ,UAAU;AAAA,MACjC,MAAM,EAAE,OAAO,EAAE,QAAQ,mBAAmB;AAAA,MAC5C,aAAa,EAAE,OAAO,EAAE,QAAQ,6BAA6B;AAAA,MAC7D,QAAQ,EAAE,MAAM,EAAE,OAAO;AAAA,QACvB,IAAI,EAAE,OAAO;AAAA,QACb,MAAM,EAAE,OAAO;AAAA,QACf,OAAO,EAAE,OAAO;AAAA,QAChB,gBAAgB,EAAE,QAAQ,EAAE,QAAQ,KAAK;AAAA,QACzC,kBAAkB,EAAE,QAAQ,EAAE,QAAQ,KAAK;AAAA,QAC3C,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,QACjC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,MAC7C,CAAC,CAAC,EAAE,QAAQ;AAAA,QACV,EAAE,IAAI,SAAS,MAAM,SAAS,OAAO,GAAG,gBAAgB,OAAO,kBAAkB,OAAO,aAAa,iBAAiB,aAAa,CAAC,cAAc,EAAE;AAAA,QACpJ,EAAE,IAAI,WAAW,MAAM,WAAW,OAAO,GAAG,gBAAgB,MAAM,kBAAkB,MAAM,aAAa,mBAAmB,aAAa,CAAC,iBAAiB,EAAE;AAAA,MAC7J,CAAC;AAAA,MACD,aAAa,EAAE,MAAM,EAAE,OAAO;AAAA,QAC5B,IAAI,EAAE,OAAO;AAAA,QACb,MAAM,EAAE,OAAO;AAAA,QACf,IAAI,EAAE,OAAO;AAAA,QACb,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,QACjC,aAAa,EAAE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AAe,OAAO,oBAAoB,aAAa,UAAa,OAAO,SAAS,WAAW;AAEjG,gBAAM,eAAe,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC1E,gBAAM,eAAe,aAAa,UAAU,CAAC,MAAM,EAAE,OAAO,aAAa,EAAE;AAC3E,gBAAM,YAAY,aAAa,eAAe,CAAC;AAE/C,cAAI,WAAW;AACb,kBAAM,YAAY,QAAQ;AAC1B,kBAAM,KAAK,SAAS,QAAQ,OAAO,WAAW;AAAA,cAC5C,eAAe,UAAU;AAAA,YAC3B,CAAC;AACD,iBAAK,KAAK,0BAA0B;AAAA,cAClC;AAAA,cACA,YAAY,QAAQ;AAAA,cACpB,MAAM;AAAA,cACN,IAAI,UAAU;AAAA,YAChB,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF,CAAC;AAED,SAAK,eAAe;AACpB,SAAK,KAAK,eAAe,MAA4B;AAAA,EACvD;AAAA,EAEA,MAAM,UAAyB;AAC7B,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,cAAc,0BAA0B;AAAA,IACpD;AAEA,SAAK,eAAe;AACpB,SAAK,KAAK,YAAY,MAA4B;AAAA,EACpD;AAAA,EAKA,GAAG,OAAwB,UAA8C;AACvE,WAAO,MAAM,GAAG,OAAO,QAAQ;AAAA,EACjC;AAAA,EAIA,KAAK,UAA2B,MAA0B;AACxD,WAAO,MAAM,KAAK,OAAO,GAAG,IAAI;AAAA,EAClC;AACF;AAKO,SAAS,6BAA6B,SAAiE;AAC5G,SAAO,IAAI,2BAA2B,OAAO;AAC/C;","names":["z","z","crypto","crypto","crypto","crypto"]}
|
|
1
|
+
{"version":3,"sources":["../src/content-management-suite.ts","../src/config.ts","../src/errors.ts","../src/in-memory-adapter.ts","../src/namespaces/content.ts","../src/namespaces/content-types.ts","../src/namespaces/workflows.ts","../src/namespaces/users.ts","../src/namespaces/config.ts","../src/namespaces/plugins.ts","../src/namespaces/publishers.ts","../src/namespaces/sources.ts","../src/namespaces/ai.ts","../src/namespaces/social.ts"],"sourcesContent":["/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\n\nimport { ContentManagementConfigSchema } from './config';\nimport type { ContentManagementConfig } from './config';\nimport { InternalError } from './errors';\nimport type {\n ContentManagementSuite,\n ContentManagementSuiteOptions,\n ContentManagementLogger,\n ContentNamespace,\n ContentTypesNamespace,\n WorkflowsNamespace,\n UsersNamespace,\n PermissionsNamespace,\n ConfigNamespace,\n PluginsNamespace,\n PublishersNamespace,\n SourcesNamespace,\n AINamespace,\n SocialNamespace,\n SuiteEventMap,\n} from './types';\nimport type { ContentStorageAdapter } from './storage';\nimport { createInMemoryAdapter } from './in-memory-adapter';\n\nimport { ContentNamespaceImpl } from './namespaces/content';\nimport { ContentTypesNamespaceImpl } from './namespaces/content-types';\nimport { WorkflowsNamespaceImpl } from './namespaces/workflows';\nimport { UsersNamespaceImpl, PermissionsNamespaceImpl } from './namespaces/users';\nimport { ConfigNamespaceImpl } from './namespaces/config';\nimport { PluginsNamespaceImpl } from './namespaces/plugins';\nimport { PublishersNamespaceImpl } from './namespaces/publishers';\nimport { SourcesNamespaceImpl } from './namespaces/sources';\nimport { AINamespaceImpl } from './namespaces/ai';\nimport { SocialNamespaceImpl } from './namespaces/social';\n\nexport class ContentManagementSuiteImpl extends EventEmitter implements ContentManagementSuite {\n readonly content: ContentNamespace;\n readonly contentTypes: ContentTypesNamespace;\n readonly workflows: WorkflowsNamespace;\n readonly users: UsersNamespace;\n readonly permissions: PermissionsNamespace;\n readonly config: ConfigNamespace;\n readonly plugins: PluginsNamespace;\n readonly publishers: PublishersNamespace;\n readonly sources: SourcesNamespace;\n readonly ai: AINamespace;\n readonly social: SocialNamespace;\n\n private readonly _logger: ContentManagementLogger | undefined;\n private readonly _options: ContentManagementSuiteOptions;\n private readonly _storage: ContentStorageAdapter;\n private _initialized = false;\n\n constructor(options?: ContentManagementSuiteOptions) {\n super();\n\n this._options = options ?? {};\n this._logger = this._options.logger;\n this._storage = this._options.storage ?? createInMemoryAdapter();\n\n const parsedConfig: ContentManagementConfig = ContentManagementConfigSchema.parse(\n this._options.config ?? {}\n );\n\n const workflowDefaults = this._options.workflows?.defaults ?? {};\n\n // Create namespace instances\n this.contentTypes = new ContentTypesNamespaceImpl();\n this.publishers = new PublishersNamespaceImpl(this);\n this.content = new ContentNamespaceImpl(\n this,\n this._storage,\n () => this.contentTypes,\n () => this.publishers,\n );\n this.workflows = new WorkflowsNamespaceImpl(this._storage);\n this.users = new UsersNamespaceImpl(this);\n this.permissions = new PermissionsNamespaceImpl();\n this.config = new ConfigNamespaceImpl(parsedConfig, this);\n this.plugins = new PluginsNamespaceImpl(this);\n this.sources = new SourcesNamespaceImpl(this, this._storage, workflowDefaults);\n const aiOpts: {\n reviewService?: import('./interfaces').AIReviewService;\n socialGeneratorService?: import('./interfaces').AISocialGeneratorService;\n enhanceService?: import('./interfaces').AIEnhanceService;\n workflowDefaults?: Record<string, string>;\n } = {};\n if (this._options.ai?.reviewService) {\n aiOpts.reviewService = this._options.ai.reviewService;\n }\n if (this._options.ai?.socialGeneratorService) {\n aiOpts.socialGeneratorService = this._options.ai.socialGeneratorService;\n }\n if (this._options.ai?.enhanceService) {\n aiOpts.enhanceService = this._options.ai.enhanceService;\n }\n if (Object.keys(workflowDefaults).length > 0) {\n aiOpts.workflowDefaults = workflowDefaults;\n }\n this.ai = new AINamespaceImpl(this, this._storage, aiOpts);\n this.social = new SocialNamespaceImpl(this, this._storage);\n }\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n throw new InternalError('Suite is already initialized');\n }\n\n // Register default content types\n this.contentTypes.register({ id: 'text', name: 'text' });\n this.contentTypes.register({ id: 'image', name: 'image' });\n this.contentTypes.register({ id: 'audio', name: 'audio' });\n this.contentTypes.register({ id: 'video', name: 'video' });\n\n // Load workflows from storage\n const workflowsImpl = this.workflows as WorkflowsNamespaceImpl;\n if (typeof workflowsImpl.loadFromStorage === 'function') {\n await workflowsImpl.loadFromStorage();\n }\n\n // Register plugins from options\n if (this._options.plugins) {\n for (const plugin of this._options.plugins) {\n await this.plugins.register(plugin);\n }\n }\n\n // Wire auto-advance on ai:review:completed\n this.on('ai:review:completed', async ({ contentId, review }) => {\n try {\n const content = await this._storage.content.get(contentId);\n if (!content || !content.workflowId || !content.workflowStage) {\n return;\n }\n\n const workflow = await this._storage.workflows.get(content.workflowId);\n if (!workflow || !workflow.stages) {\n return;\n }\n\n const currentStage = workflow.stages.find((s) => s.id === content.workflowStage);\n if (!currentStage || !currentStage.conditions) {\n return;\n }\n\n const { autoAdvance, minScore, requiresHumanReview } = currentStage.conditions;\n\n // If human review required, skip auto-advance\n if (requiresHumanReview) {\n return;\n }\n\n // Check auto-advance conditions\n if (autoAdvance && review.passesThreshold && (minScore === undefined || review.score >= minScore)) {\n // Find next stage\n const sortedStages = [...workflow.stages].sort((a, b) => a.order - b.order);\n const currentIndex = sortedStages.findIndex((s) => s.id === currentStage.id);\n const nextStage = sortedStages[currentIndex + 1];\n\n if (nextStage) {\n const fromStage = content.workflowStage;\n await this._storage.content.update(contentId, {\n workflowStage: nextStage.id,\n });\n this.emit('workflow:stage:changed', {\n contentId,\n workflowId: content.workflowId,\n from: fromStage,\n to: nextStage.id,\n });\n }\n }\n } catch {\n // Silently handle errors in auto-advance to avoid breaking the event chain\n }\n });\n\n this._initialized = true;\n this.emit('initialized', undefined as unknown as void);\n }\n\n async dispose(): Promise<void> {\n if (!this._initialized) {\n throw new InternalError('Suite is not initialized');\n }\n\n this._initialized = false;\n this.emit('disposed', undefined as unknown as void);\n }\n\n // Typed event overrides to satisfy the ContentManagementSuite interface\n on<K extends keyof SuiteEventMap>(event: K, listener: (payload: SuiteEventMap[K]) => void): this;\n on(event: string | symbol, listener: (...args: unknown[]) => void): this;\n on(event: string | symbol, listener: (...args: unknown[]) => void): this {\n return super.on(event, listener);\n }\n\n emit<K extends keyof SuiteEventMap>(event: K, payload: SuiteEventMap[K]): boolean;\n emit(event: string | symbol, ...args: unknown[]): boolean;\n emit(event: string | symbol, ...args: unknown[]): boolean {\n return super.emit(event, ...args);\n }\n}\n\n/**\n * Factory function to create a new ContentManagementSuite instance.\n */\nexport function createContentManagementSuite(options?: ContentManagementSuiteOptions): ContentManagementSuite {\n return new ContentManagementSuiteImpl(options);\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { z } from 'zod';\n\nexport const ContentManagementConfigSchema = z.object({\n content: z.object({\n defaultWorkflow: z.object({\n id: z.string().default('standard'),\n name: z.string().default('Standard Workflow'),\n description: z.string().default('Standard editorial workflow'),\n stages: z.array(z.object({\n id: z.string(),\n name: z.string(),\n order: z.number(),\n isPublishStage: z.boolean().default(false),\n allowsScheduling: z.boolean().default(false),\n description: z.string().optional(),\n permissions: z.array(z.string()).default([]),\n })).default([\n { id: 'write', name: 'Write', order: 1, isPublishStage: false, allowsScheduling: false, description: 'Write content', permissions: ['content.edit'] },\n { id: 'publish', name: 'Publish', order: 2, isPublishStage: true, allowsScheduling: true, description: 'Publish content', permissions: ['content.publish'] },\n ]),\n transitions: z.array(z.object({\n id: z.string(),\n from: z.string(),\n to: z.string(),\n description: z.string().optional(),\n permissions: z.array(z.string()).default([]),\n })).default([\n { id: 'write-to-publish', from: 'write', to: 'publish', description: 'Move from write to publish', permissions: ['content.publish'] },\n ]),\n }).default({}),\n contentTypes: z.array(z.string()).default(['text', 'image', 'audio', 'video']),\n autoSave: z.object({\n enabled: z.boolean().default(true),\n debounceMs: z.number().default(1000),\n maxRetries: z.number().default(3),\n backoffMs: z.number().default(1000),\n }).default({}),\n softDelete: z.object({\n enabled: z.boolean().default(true),\n showDeletedToUsers: z.boolean().default(false),\n retentionDays: z.number().default(30),\n }).default({}),\n upload: z.object({\n maxFileSize: z.number().default(104857600),\n allowedTypes: z.array(z.string()).default([\n 'image/jpeg', 'image/png', 'image/webp', 'image/gif',\n 'audio/mpeg', 'audio/wav', 'audio/ogg',\n 'video/mp4', 'video/webm', 'video/ogg',\n ]),\n storage: z.object({\n type: z.enum(['local', 's3']).default('local'),\n path: z.string().default('./uploads'),\n bucket: z.string().optional(),\n region: z.string().optional(),\n }).default({}).optional(),\n }).default({}),\n }).default({}),\n\n database: z.object({\n type: z.enum(['sqlite', 'postgresql', 'mysql', 'mongodb']).default('sqlite'),\n url: z.string().optional(),\n host: z.string().default('localhost'),\n port: z.number().optional(),\n name: z.string().default('content_management'),\n username: z.string().optional(),\n password: z.string().optional(),\n ssl: z.boolean().default(false),\n pool: z.object({\n min: z.number().default(2),\n max: z.number().default(10),\n idleTimeoutMs: z.number().optional(),\n }).default({}),\n }).default({}),\n\n integrations: z.object({\n neverAdmin: z.object({\n enabled: z.boolean().default(false),\n endpoint: z.string().optional(),\n }).default({}),\n neverHub: z.object({\n enabled: z.boolean().default(false),\n endpoint: z.string().optional(),\n }).default({}),\n analytics: z.object({\n enabled: z.boolean().default(false),\n provider: z.string().optional(),\n }).default({}),\n }).default({}),\n\n security: z.object({\n permissions: z.object({\n enabled: z.boolean().default(true),\n defaultRole: z.string().default('user'),\n }).default({}),\n roles: z.array(z.object({\n name: z.string(),\n permissions: z.array(z.string()),\n description: z.string().optional(),\n })).default([\n { name: 'admin', permissions: ['*'], description: 'Full administrative access' },\n { name: 'editor', permissions: ['content.edit', 'content.publish', 'content.schedule'], description: 'Content editing and publishing' },\n { name: 'author', permissions: ['content.edit'], description: 'Content creation and editing' },\n { name: 'user', permissions: ['content.view'], description: 'Content viewing only' },\n ]),\n }).default({}),\n\n workflows: z.object({\n defaults: z.record(z.string(), z.string()).default({}),\n }).default({}),\n\n logging: z.object({\n level: z.enum(['error', 'warn', 'info', 'debug']).default('info'),\n }).default({}),\n\n performance: z.object({\n cache: z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().default(300),\n maxSize: z.number().default(1000),\n }).default({}),\n }).default({}),\n});\n\nexport type ContentManagementConfig = z.infer<typeof ContentManagementConfigSchema>;\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\n/**\n * Typed error code union for content-management-suite errors.\n */\nexport type ContentManagementErrorCode =\n | 'CONTENT_MANAGEMENT_ERROR'\n | 'VALIDATION_ERROR'\n | 'NOT_FOUND'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'CONFLICT'\n | 'INTERNAL_ERROR';\n\n/**\n * Options bag accepted by `ContentManagementError`.\n *\n * - `cause`: chained underlying error (ES2022 Error.cause).\n * - `code`: a typed error code from {@link ContentManagementErrorCode}.\n * - `context`: arbitrary structured context.\n */\nexport interface ContentManagementErrorOptions {\n cause?: Error;\n code?: ContentManagementErrorCode;\n context?: Record<string, unknown>;\n}\n\n/**\n * Custom error class for content-management-suite errors.\n *\n * Uses native ES2022 `Error.cause` for error chaining — read the underlying\n * error via `error.cause`. Structured context lives on `error.context`.\n */\nexport class ContentManagementError extends Error {\n public readonly code: ContentManagementErrorCode;\n public readonly context?: Record<string, unknown>;\n\n constructor(message: string, options?: ContentManagementErrorOptions) {\n super(message, options?.cause ? { cause: options.cause } : undefined);\n this.name = this.constructor.name;\n this.code = options?.code ?? 'CONTENT_MANAGEMENT_ERROR';\n if (options?.context !== undefined) {\n this.context = options.context;\n }\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\n\nexport class ValidationError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { ...options, code: 'VALIDATION_ERROR' });\n }\n}\n\nexport class NotFoundError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { ...options, code: 'NOT_FOUND' });\n }\n}\n\nexport class UnauthorizedError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { ...options, code: 'UNAUTHORIZED' });\n }\n}\n\nexport class ForbiddenError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { ...options, code: 'FORBIDDEN' });\n }\n}\n\nexport class ConflictError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { ...options, code: 'CONFLICT' });\n }\n}\n\nexport class InternalError extends ContentManagementError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { ...options, code: 'INTERNAL_ERROR' });\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport type {\n ContentItem,\n ContentFilters,\n SearchOptions,\n PaginatedResult,\n Workflow,\n SocialPost,\n AIReview,\n} from './types';\n\nimport type {\n ContentStorageAdapter,\n ContentStorageNamespace,\n WorkflowStorageNamespace,\n ContentTypeStorageNamespace,\n SocialPostStorageNamespace,\n AIReviewStorageNamespace,\n StoredContentTypeDefinition,\n} from './storage';\n\n// --- In-Memory Content Storage ---\n\nclass InMemoryContentStorage implements ContentStorageNamespace {\n private readonly store = new Map<string, ContentItem>();\n\n async list(filters?: ContentFilters): Promise<PaginatedResult<ContentItem>> {\n let items = Array.from(this.store.values());\n\n if (filters?.type) {\n items = items.filter((item) => item.type === filters.type);\n }\n if (filters?.status) {\n items = items.filter((item) => item.status === filters.status);\n }\n\n const total = items.length;\n const page = filters?.page ?? 1;\n const limit = filters?.limit ?? items.length;\n const start = (page - 1) * limit;\n const paged = items.slice(start, start + limit);\n\n return { items: paged, total, page, limit };\n }\n\n async get(id: string): Promise<ContentItem | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(item: ContentItem): Promise<ContentItem> {\n this.store.set(item.id, item);\n return item;\n }\n\n async update(id: string, partial: Partial<ContentItem>): Promise<ContentItem> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Content item not found: ${id}`);\n }\n const updated: ContentItem = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n\n async findBySource(sourceType: string, sourceId: string): Promise<ContentItem | null> {\n for (const item of this.store.values()) {\n if (item.sourceType === sourceType && item.sourceId === sourceId) {\n return item;\n }\n }\n return null;\n }\n\n async search(query: string, options?: SearchOptions): Promise<PaginatedResult<ContentItem>> {\n const lowerQuery = query.toLowerCase();\n let items = Array.from(this.store.values()).filter((item) => {\n const titleMatch = item.title && item.title.toLowerCase().includes(lowerQuery);\n const bodyMatch = item.body && item.body.toLowerCase().includes(lowerQuery);\n const dataMatch = item.data && Object.values(item.data).some(\n (value) => typeof value === 'string' && value.toLowerCase().includes(lowerQuery)\n );\n return titleMatch || bodyMatch || dataMatch;\n });\n\n if (options?.type) {\n items = items.filter((item) => item.type === options.type);\n }\n if (options?.status) {\n items = items.filter((item) => item.status === options.status);\n }\n\n const total = items.length;\n const page = options?.page ?? 1;\n const limit = options?.limit ?? items.length;\n const start = (page - 1) * limit;\n const paged = items.slice(start, start + limit);\n\n return { items: paged, total, page, limit };\n }\n}\n\n// --- In-Memory Workflow Storage ---\n\nclass InMemoryWorkflowStorage implements WorkflowStorageNamespace {\n private readonly store = new Map<string, Workflow>();\n private readonly contentTypeMap = new Map<string, string>(); // contentType -> workflowId\n\n async list(): Promise<Workflow[]> {\n return Array.from(this.store.values());\n }\n\n async get(id: string): Promise<Workflow | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(workflow: Workflow): Promise<Workflow> {\n this.store.set(workflow.id, workflow);\n return workflow;\n }\n\n async update(id: string, partial: Partial<Workflow>): Promise<Workflow> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Workflow not found: ${id}`);\n }\n const updated: Workflow = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n // Remove content type mappings pointing to this workflow\n for (const [ct, wId] of this.contentTypeMap.entries()) {\n if (wId === id) {\n this.contentTypeMap.delete(ct);\n }\n }\n }\n\n async findByContentType(contentType: string): Promise<Workflow | null> {\n const workflowId = this.contentTypeMap.get(contentType);\n if (!workflowId) {\n return null;\n }\n return this.store.get(workflowId) ?? null;\n }\n\n setContentTypeMapping(contentType: string, workflowId: string): void {\n this.contentTypeMap.set(contentType, workflowId);\n }\n}\n\n// --- In-Memory Content Type Storage ---\n\nclass InMemoryContentTypeStorage implements ContentTypeStorageNamespace {\n private readonly store = new Map<string, StoredContentTypeDefinition>();\n\n async list(): Promise<StoredContentTypeDefinition[]> {\n return Array.from(this.store.values());\n }\n\n async get(id: string): Promise<StoredContentTypeDefinition | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(def: StoredContentTypeDefinition): Promise<StoredContentTypeDefinition> {\n this.store.set(def.id, def);\n return def;\n }\n\n async update(id: string, partial: Partial<StoredContentTypeDefinition>): Promise<StoredContentTypeDefinition> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Content type not found: ${id}`);\n }\n const updated: StoredContentTypeDefinition = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n}\n\n// --- In-Memory Social Post Storage ---\n\nclass InMemorySocialPostStorage implements SocialPostStorageNamespace {\n private readonly store = new Map<string, SocialPost>();\n\n async list(filters?: { contentId?: string; platform?: string; status?: string }): Promise<SocialPost[]> {\n let items = Array.from(this.store.values());\n\n if (filters?.contentId) {\n items = items.filter((p) => p.contentId === filters.contentId);\n }\n if (filters?.platform) {\n items = items.filter((p) => p.platform === filters.platform);\n }\n if (filters?.status) {\n items = items.filter((p) => p.status === filters.status);\n }\n\n return items;\n }\n\n async get(id: string): Promise<SocialPost | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(post: SocialPost): Promise<SocialPost> {\n this.store.set(post.id, post);\n return post;\n }\n\n async update(id: string, partial: Partial<SocialPost>): Promise<SocialPost> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new Error(`Social post not found: ${id}`);\n }\n const updated: SocialPost = { ...existing, ...partial };\n this.store.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n this.store.delete(id);\n }\n\n async findByContent(contentId: string): Promise<SocialPost[]> {\n return Array.from(this.store.values()).filter((p) => p.contentId === contentId);\n }\n}\n\n// --- In-Memory AI Review Storage ---\n\nclass InMemoryAIReviewStorage implements AIReviewStorageNamespace {\n private readonly store = new Map<string, AIReview>();\n\n async list(filters?: { contentId?: string }): Promise<AIReview[]> {\n let items = Array.from(this.store.values());\n\n if (filters?.contentId) {\n items = items.filter((r) => r.contentId === filters.contentId);\n }\n\n return items;\n }\n\n async get(id: string): Promise<AIReview | null> {\n return this.store.get(id) ?? null;\n }\n\n async create(review: AIReview): Promise<AIReview> {\n this.store.set(review.id, review);\n return review;\n }\n\n async findByContent(contentId: string): Promise<AIReview[]> {\n return Array.from(this.store.values()).filter((r) => r.contentId === contentId);\n }\n\n async getLatestForContent(contentId: string): Promise<AIReview | null> {\n const reviews = await this.findByContent(contentId);\n if (reviews.length === 0) {\n return null;\n }\n // Sort by createdAt descending and return the first\n reviews.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n return reviews[0] ?? null;\n }\n}\n\n// --- Factory Function ---\n\nexport function createInMemoryAdapter(): ContentStorageAdapter {\n return {\n content: new InMemoryContentStorage(),\n workflows: new InMemoryWorkflowStorage(),\n contentTypes: new InMemoryContentTypeStorage(),\n socialPosts: new InMemorySocialPostStorage(),\n aiReviews: new InMemoryAIReviewStorage(),\n };\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type {\n ContentNamespace,\n ContentItem,\n CreateContentInput,\n UpdateContentInput,\n ContentFilters,\n SearchOptions,\n PaginatedResult,\n ContentTypesNamespace,\n PublishersNamespace,\n} from '../types';\nimport type { ContentPublishResult, PublishResult } from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ValidationError } from '../errors';\n\nexport class ContentNamespaceImpl implements ContentNamespace {\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n private readonly getContentTypes: () => ContentTypesNamespace;\n private readonly getPublishers: () => PublishersNamespace;\n\n constructor(\n emitter: EventEmitter,\n storage: ContentStorageAdapter,\n getContentTypes: () => ContentTypesNamespace,\n getPublishers: () => PublishersNamespace,\n ) {\n this.emitter = emitter;\n this.storage = storage;\n this.getContentTypes = getContentTypes;\n this.getPublishers = getPublishers;\n }\n\n async create(input: CreateContentInput): Promise<ContentItem> {\n // Validate against content type schema if registered\n const contentTypes = this.getContentTypes();\n const typeDef = contentTypes.get(input.type);\n if (typeDef && typeDef.schema) {\n const dataToValidate: Record<string, unknown> = {\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.data ?? {}),\n };\n const result = contentTypes.validate(input.type, dataToValidate);\n if (!result.valid) {\n throw new ValidationError('Content type schema validation failed', {\n context: { errors: result.errors },\n });\n }\n }\n\n const item: ContentItem = {\n id: crypto.randomUUID(),\n type: input.type,\n createdAt: new Date().toISOString(),\n status: 'draft',\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.data !== undefined ? { data: { ...input.data } } : {}),\n ...(input.channels !== undefined ? { channels: input.channels } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n\n const created = await this.storage.content.create(item);\n this.emitter.emit('content:created', created);\n return created;\n }\n\n async get(id: string): Promise<ContentItem> {\n const item = await this.storage.content.get(id);\n if (!item) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n return item;\n }\n\n async list(filters?: ContentFilters): Promise<PaginatedResult<ContentItem>> {\n return this.storage.content.list(filters);\n }\n\n async update(id: string, input: UpdateContentInput): Promise<ContentItem> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n\n const partial: Partial<ContentItem> = {\n updatedAt: new Date().toISOString(),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.status !== undefined ? { status: input.status } : {}),\n ...(input.channels !== undefined ? { channels: input.channels } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n\n if (input.data !== undefined) {\n partial.data = { ...(existing.data ?? {}), ...input.data };\n }\n\n const updated = await this.storage.content.update(id, partial);\n this.emitter.emit('content:updated', updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n await this.storage.content.delete(id);\n this.emitter.emit('content:deleted', { id });\n }\n\n async publish(id: string, options?: { channels?: string[] }): Promise<ContentPublishResult> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n\n // Check publish-stage gating\n if (existing.workflowId) {\n const workflow = await this.storage.workflows.get(existing.workflowId);\n if (workflow && workflow.stages && workflow.stages.length > 0) {\n const currentStage = workflow.stages.find((s) => s.id === existing.workflowStage);\n const publishStage = workflow.stages.find((s) => s.isPublishStage);\n if (publishStage && (!currentStage || !currentStage.isPublishStage)) {\n throw new ValidationError(\n `Content is not at a publish-eligible stage. Current stage: \"${existing.workflowStage ?? 'none'}\", ` +\n `required publish stage: \"${publishStage.id}\"`,\n {\n context: {\n currentStage: existing.workflowStage ?? null,\n requiredStage: publishStage.id,\n },\n },\n );\n }\n }\n }\n\n const publishers = this.getPublishers();\n const allPublishers = publishers.list();\n\n // Determine which channels to publish to\n const channelIds = options?.channels ?? existing.channels;\n\n let targetPublishers;\n if (channelIds && channelIds.length > 0) {\n targetPublishers = allPublishers.filter((p) => channelIds.includes(p.id));\n } else {\n // Publish to all publishers that accept this content type\n targetPublishers = allPublishers.filter((p) => p.acceptedTypes.includes(existing.type));\n }\n\n const results: PublishResult[] = [];\n\n for (const publisher of targetPublishers) {\n // Type check\n if (!publisher.acceptedTypes.includes(existing.type)) {\n results.push({\n channelId: publisher.id,\n success: false,\n error: `Content type \"${existing.type}\" not accepted by publisher \"${publisher.id}\". Accepted: ${publisher.acceptedTypes.join(', ')}`,\n });\n continue;\n }\n\n // Validate if publisher provides validate method\n if (publisher.validate) {\n const validationErrors = await publisher.validate(existing);\n if (validationErrors.length > 0) {\n results.push({\n channelId: publisher.id,\n success: false,\n error: `Validation failed: ${validationErrors.map((e) => e.message).join(', ')}`,\n });\n continue;\n }\n }\n\n try {\n const result = await publisher.publish(existing);\n results.push(result);\n } catch (error) {\n results.push({\n channelId: publisher.id,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Update content status\n const now = new Date().toISOString();\n const updated = await this.storage.content.update(id, {\n status: 'published',\n publishedAt: now,\n updatedAt: now,\n });\n\n const publishResult: ContentPublishResult = { item: updated, results };\n this.emitter.emit('content:published', publishResult);\n return publishResult;\n }\n\n async unpublish(id: string): Promise<ContentItem> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n const updated = await this.storage.content.update(id, {\n status: 'draft',\n updatedAt: new Date().toISOString(),\n });\n this.emitter.emit('content:unpublished', updated);\n return updated;\n }\n\n async schedule(id: string, date: Date): Promise<ContentItem> {\n const existing = await this.storage.content.get(id);\n if (!existing) {\n throw new NotFoundError(`Content item not found: ${id}`);\n }\n const updated = await this.storage.content.update(id, {\n scheduledFor: date,\n updatedAt: new Date().toISOString(),\n });\n this.emitter.emit('content:scheduled', { item: updated, date });\n return updated;\n }\n\n async search(query: string, options?: SearchOptions): Promise<PaginatedResult<ContentItem>> {\n return this.storage.content.search(query, options);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { z } from 'zod';\nimport type { ContentTypesNamespace } from '../types';\nimport type { ContentTypeDefinition, SchemaValidationResult } from '../interfaces';\nimport { NotFoundError } from '../errors';\n\nexport class ContentTypesNamespaceImpl implements ContentTypesNamespace {\n private readonly store = new Map<string, ContentTypeDefinition>();\n\n register(definition: ContentTypeDefinition | { id?: string; name?: string }): void {\n // Support both legacy { id, name } and new ContentTypeDefinition\n if ('schema' in definition && definition.schema) {\n const def = definition as ContentTypeDefinition;\n this.store.set(def.id, def);\n } else {\n const id = definition.id ?? definition.name;\n if (!id) {\n throw new Error('Content type must have an id or name');\n }\n const name = definition.name ?? definition.id ?? id;\n // Legacy registration without schema - store with no schema\n this.store.set(id, {\n id,\n name,\n schema: null as unknown,\n });\n }\n }\n\n unregister(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Content type not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n get(id: string): ContentTypeDefinition | undefined {\n return this.store.get(id);\n }\n\n list(): ContentTypeDefinition[] {\n return Array.from(this.store.values());\n }\n\n validate(type: string, data: Record<string, unknown>): SchemaValidationResult {\n const def = this.store.get(type);\n if (!def || !def.schema) {\n // No schema registered - pass through\n return { valid: true };\n }\n\n try {\n // Assume schema is a Zod schema\n const schema = def.schema as z.ZodType;\n schema.parse(data);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((issue) => ({\n message: issue.message,\n path: issue.path.map(String),\n })),\n };\n }\n return {\n valid: false,\n errors: [{ message: error instanceof Error ? error.message : String(error) }],\n };\n }\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport * as crypto from 'crypto';\nimport type {\n WorkflowsNamespace,\n Workflow,\n CreateWorkflowInput,\n UpdateWorkflowInput,\n} from '../types';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ConflictError } from '../errors';\n\nexport class WorkflowsNamespaceImpl implements WorkflowsNamespace {\n private readonly cache = new Map<string, Workflow>();\n private readonly storage: ContentStorageAdapter | undefined;\n\n constructor(storage?: ContentStorageAdapter) {\n this.storage = storage;\n }\n\n /** Load workflows from storage into cache. Called during suite initialization. */\n async loadFromStorage(): Promise<void> {\n if (!this.storage) {\n return;\n }\n const workflows = await this.storage.workflows.list();\n for (const w of workflows) {\n this.cache.set(w.id, w);\n }\n }\n\n async create(input: CreateWorkflowInput): Promise<Workflow> {\n const workflow: Workflow = {\n id: crypto.randomUUID(),\n name: input.name,\n ...(input.description !== undefined ? { description: input.description } : {}),\n ...(input.stages !== undefined ? { stages: input.stages } : {}),\n ...(input.transitions !== undefined ? { transitions: input.transitions } : {}),\n };\n\n // Persist to storage\n if (this.storage) {\n await this.storage.workflows.create(workflow);\n }\n\n this.cache.set(workflow.id, workflow);\n return workflow;\n }\n\n async get(id: string): Promise<Workflow> {\n const workflow = this.cache.get(id);\n if (!workflow) {\n throw new NotFoundError(`Workflow not found: ${id}`);\n }\n return workflow;\n }\n\n async list(): Promise<Workflow[]> {\n return Array.from(this.cache.values());\n }\n\n async update(id: string, input: UpdateWorkflowInput): Promise<Workflow> {\n const existing = this.cache.get(id);\n if (!existing) {\n throw new NotFoundError(`Workflow not found: ${id}`);\n }\n\n const updated: Workflow = {\n ...existing,\n ...(input.name !== undefined ? { name: input.name } : {}),\n ...(input.description !== undefined ? { description: input.description } : {}),\n ...(input.stages !== undefined ? { stages: input.stages } : {}),\n ...(input.transitions !== undefined ? { transitions: input.transitions } : {}),\n };\n\n // Persist to storage\n if (this.storage) {\n await this.storage.workflows.update(id, updated);\n }\n\n this.cache.set(id, updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n if (!this.cache.has(id)) {\n throw new NotFoundError(`Workflow not found: ${id}`);\n }\n\n // Check if any content references this workflow\n if (this.storage) {\n const contentResult = await this.storage.content.list();\n const assignedContent = contentResult.items.filter((item) => item.workflowId === id);\n if (assignedContent.length > 0) {\n throw new ConflictError(\n `Cannot delete workflow \"${id}\": ${assignedContent.length} content item(s) are assigned to it. Reassign or archive them first.`,\n { context: { assignedCount: assignedContent.length } },\n );\n }\n await this.storage.workflows.delete(id);\n }\n\n this.cache.delete(id);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type {\n UsersNamespace,\n PermissionsNamespace,\n User,\n CreateUserInput,\n UpdateUserInput,\n PaginatedResult,\n} from '../types';\nimport { NotFoundError } from '../errors';\n\nexport class UsersNamespaceImpl implements UsersNamespace {\n private readonly store = new Map<string, User>();\n private readonly emitter: EventEmitter;\n\n constructor(emitter: EventEmitter) {\n this.emitter = emitter;\n }\n\n async create(input: CreateUserInput): Promise<User> {\n const user: User = {\n id: crypto.randomUUID(),\n name: input.name,\n ...(input.email !== undefined ? { email: input.email } : {}),\n ...(input.role !== undefined ? { role: input.role } : {}),\n createdAt: new Date().toISOString(),\n };\n this.store.set(user.id, user);\n this.emitter.emit('user:created', user);\n return user;\n }\n\n async get(id: string): Promise<User> {\n const user = this.store.get(id);\n if (!user) {\n throw new NotFoundError(`User not found: ${id}`);\n }\n return user;\n }\n\n async list(): Promise<PaginatedResult<User>> {\n const items = Array.from(this.store.values());\n return { items, total: items.length };\n }\n\n async update(id: string, input: UpdateUserInput): Promise<User> {\n const existing = this.store.get(id);\n if (!existing) {\n throw new NotFoundError(`User not found: ${id}`);\n }\n const updated: User = {\n ...existing,\n ...input,\n updatedAt: new Date().toISOString(),\n };\n this.store.set(id, updated);\n this.emitter.emit('user:updated', updated);\n return updated;\n }\n\n async delete(id: string): Promise<void> {\n if (!this.store.has(id)) {\n throw new NotFoundError(`User not found: ${id}`);\n }\n this.store.delete(id);\n this.emitter.emit('user:deleted', { id });\n }\n}\n\nexport class PermissionsNamespaceImpl implements PermissionsNamespace {\n private readonly store = new Map<string, Set<string>>();\n\n async check(userId: string, permission: string): Promise<boolean> {\n const perms = this.store.get(userId);\n return perms?.has(permission) ?? false;\n }\n\n async grant(userId: string, permission: string): Promise<void> {\n let perms = this.store.get(userId);\n if (!perms) {\n perms = new Set();\n this.store.set(userId, perms);\n }\n perms.add(permission);\n }\n\n async revoke(userId: string, permission: string): Promise<void> {\n const perms = this.store.get(userId);\n if (perms) {\n perms.delete(permission);\n }\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport type { ConfigNamespace } from '../types';\nimport type { ContentManagementConfig } from '../config';\nimport { ContentManagementConfigSchema } from '../config';\nimport { ValidationError } from '../errors';\n\nfunction deepMerge<T extends Record<string, unknown>>(target: T, source: Partial<T>): T {\n const result = { ...target } as Record<string, unknown>;\n for (const key of Object.keys(source)) {\n const sourceVal = (source as Record<string, unknown>)[key];\n const targetVal = result[key];\n if (\n sourceVal !== null &&\n sourceVal !== undefined &&\n typeof sourceVal === 'object' &&\n !Array.isArray(sourceVal) &&\n targetVal !== null &&\n targetVal !== undefined &&\n typeof targetVal === 'object' &&\n !Array.isArray(targetVal)\n ) {\n result[key] = deepMerge(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>\n );\n } else {\n result[key] = sourceVal;\n }\n }\n return result as T;\n}\n\nexport class ConfigNamespaceImpl implements ConfigNamespace {\n private config: ContentManagementConfig;\n private readonly emitter: EventEmitter;\n\n constructor(initialConfig: ContentManagementConfig, emitter: EventEmitter) {\n this.config = initialConfig;\n this.emitter = emitter;\n }\n\n get(): ContentManagementConfig {\n return this.config;\n }\n\n update(partial: Partial<ContentManagementConfig>): ContentManagementConfig {\n const merged = deepMerge(this.config, partial);\n try {\n this.config = ContentManagementConfigSchema.parse(merged);\n } catch (err) {\n throw new ValidationError('Invalid configuration',\n err instanceof Error ? { cause: err } : undefined,\n );\n }\n this.emitter.emit('config:updated', this.config);\n return this.config;\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport type { PluginsNamespace, SuitePlugin, ContentManagementSuite } from '../types';\nimport { ConflictError, NotFoundError } from '../errors';\n\nexport class PluginsNamespaceImpl implements PluginsNamespace {\n private readonly store = new Map<string, SuitePlugin>();\n private readonly suite: ContentManagementSuite;\n\n constructor(suite: ContentManagementSuite) {\n this.suite = suite;\n }\n\n async register(plugin: SuitePlugin): Promise<void> {\n if (this.store.has(plugin.name)) {\n throw new ConflictError(`Plugin already registered: ${plugin.name}`);\n }\n await plugin.setup(this.suite);\n this.store.set(plugin.name, plugin);\n }\n\n async unregister(name: string): Promise<void> {\n const plugin = this.store.get(name);\n if (!plugin) {\n throw new NotFoundError(`Plugin not found: ${name}`);\n }\n if (plugin.teardown) {\n await plugin.teardown(this.suite);\n }\n this.store.delete(name);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport type { PublishersNamespace, ContentItem } from '../types';\nimport type { ContentPublisher, PublishResult } from '../interfaces';\nimport { NotFoundError } from '../errors';\n\n// --- Built-in Website Publisher ---\n\nclass WebsitePublisher implements ContentPublisher {\n readonly id = 'website';\n readonly name = 'Website';\n readonly acceptedTypes = ['blog-post', 'article', 'page', 'generic', 'text'];\n\n async publish(content: ContentItem): Promise<PublishResult> {\n const slug = content.title\n ? content.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n : content.id;\n return {\n channelId: this.id,\n success: true,\n url: `/content/${slug}`,\n };\n }\n}\n\n// --- Built-in RSS Publisher ---\n\nclass RSSPublisher implements ContentPublisher {\n readonly id = 'rss';\n readonly name = 'RSS Feed';\n readonly acceptedTypes = ['blog-post', 'article', 'rss-article', 'generic', 'text'];\n\n async publish(content: ContentItem): Promise<PublishResult> {\n return {\n channelId: this.id,\n success: true,\n url: `/feed/rss/${content.id}`,\n };\n }\n}\n\n// --- Publishers Namespace Implementation ---\n\nexport class PublishersNamespaceImpl implements PublishersNamespace {\n private readonly store = new Map<string, ContentPublisher>();\n private readonly emitter: EventEmitter;\n\n constructor(emitter: EventEmitter) {\n this.emitter = emitter;\n\n // Register built-in publishers\n this.store.set('website', new WebsitePublisher());\n this.store.set('rss', new RSSPublisher());\n }\n\n register(publisher: ContentPublisher): void {\n this.store.set(publisher.id, publisher);\n this.emitter.emit('publisher:registered', { publisher });\n }\n\n unregister(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Publisher not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n list(): ContentPublisher[] {\n return Array.from(this.store.values());\n }\n\n get(id: string): ContentPublisher | undefined {\n return this.store.get(id);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type { SourcesNamespace, ContentItem } from '../types';\nimport type { ContentSource, IngestResult } from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ValidationError } from '../errors';\n\nexport class SourcesNamespaceImpl implements SourcesNamespace {\n private readonly store = new Map<string, ContentSource>();\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n private readonly workflowDefaults: Record<string, string>;\n\n constructor(\n emitter: EventEmitter,\n storage: ContentStorageAdapter,\n workflowDefaults: Record<string, string>,\n ) {\n this.emitter = emitter;\n this.storage = storage;\n this.workflowDefaults = workflowDefaults;\n }\n\n register(source: ContentSource): void {\n this.store.set(source.id, source);\n this.emitter.emit('source:registered', { source });\n }\n\n unregister(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Source not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n list(): ContentSource[] {\n return Array.from(this.store.values());\n }\n\n get(id: string): ContentSource | undefined {\n return this.store.get(id);\n }\n\n async ingest(sourceId: string, rawPayload: unknown): Promise<IngestResult> {\n const source = this.store.get(sourceId);\n if (!source) {\n throw new NotFoundError(`Source not found: ${sourceId}`);\n }\n\n // Validate if the source provides a validate method\n if (source.validate) {\n const validationErrors = await source.validate(rawPayload);\n if (validationErrors.length > 0) {\n throw new ValidationError('Source validation failed', {\n context: { errors: validationErrors },\n });\n }\n }\n\n // Ingest the payload\n const rawItem = await source.ingest(rawPayload);\n\n // Dedup check: if sourceId is set on the item, check for existing\n if (rawItem.sourceId) {\n const existing = await this.storage.content.findBySource(source.id, rawItem.sourceId);\n if (existing) {\n return { created: false, content: existing };\n }\n }\n\n // Build the content item\n const now = new Date().toISOString();\n const workflowId = this.workflowDefaults[rawItem.type] ?? this.workflowDefaults['generic'];\n\n const item: ContentItem = {\n id: crypto.randomUUID(),\n type: rawItem.type,\n createdAt: now,\n status: 'review',\n sourceType: source.id,\n sourceId: rawItem.sourceId ?? null,\n ...(rawItem.title !== undefined ? { title: rawItem.title } : {}),\n ...(rawItem.body !== undefined ? { body: rawItem.body } : {}),\n ...(rawItem.data !== undefined ? { data: rawItem.data } : {}),\n ...(rawItem.metadata !== undefined ? { metadata: rawItem.metadata } : {}),\n ...(workflowId !== undefined ? { workflowId } : {}),\n };\n\n // Persist\n const created = await this.storage.content.create(item);\n\n // Emit events\n this.emitter.emit('content:ingested', { item: created, sourceType: source.id });\n this.emitter.emit('content:created', created);\n\n return { created: true, content: created };\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport * as crypto from 'crypto';\nimport type { AINamespace, AIReview, SocialPost } from '../types';\nimport type {\n AIReviewService,\n AISocialGeneratorService,\n AIEnhanceService,\n EnhancedContent,\n EnhanceOptions,\n Suggestion,\n AIReviewSuggestion,\n} from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, InternalError } from '../errors';\n\nexport class AINamespaceImpl implements AINamespace {\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n private readonly reviewService: AIReviewService | undefined;\n private readonly socialGeneratorService: AISocialGeneratorService | undefined;\n private readonly enhanceService: AIEnhanceService | undefined;\n private readonly workflowDefaults: Record<string, string>;\n\n constructor(\n emitter: EventEmitter,\n storage: ContentStorageAdapter,\n options: {\n reviewService?: AIReviewService;\n socialGeneratorService?: AISocialGeneratorService;\n enhanceService?: AIEnhanceService;\n workflowDefaults?: Record<string, string>;\n },\n ) {\n this.emitter = emitter;\n this.storage = storage;\n this.reviewService = options.reviewService;\n this.socialGeneratorService = options.socialGeneratorService;\n this.enhanceService = options.enhanceService;\n this.workflowDefaults = options.workflowDefaults ?? {};\n }\n\n async review(contentId: string): Promise<AIReview> {\n if (!this.reviewService) {\n throw new InternalError('AI review service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n // Build text to review from available content fields\n const textToReview = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n const result = await this.reviewService.review(textToReview);\n\n // Map result to AIReview\n const suggestions: AIReviewSuggestion[] = result.issues.map((issue) => ({\n category: issue.category,\n severity: (issue.severity === 'info' || issue.severity === 'warning' || issue.severity === 'error')\n ? issue.severity\n : 'info' as const,\n message: issue.message,\n ...(issue.originalText !== undefined ? { originalText: issue.originalText } : {}),\n ...(issue.suggestedFix !== undefined ? { suggestedFix: issue.suggestedFix } : {}),\n }));\n\n const review: AIReview = {\n id: crypto.randomUUID(),\n contentId,\n score: result.overallScore,\n suggestions,\n passesThreshold: result.passesThreshold,\n rawResult: result.raw,\n createdAt: new Date().toISOString(),\n };\n\n // Persist\n await this.storage.aiReviews.create(review);\n\n // Emit event\n this.emitter.emit('ai:review:completed', { contentId, review });\n\n return review;\n }\n\n async generateSocialPosts(contentId: string, platforms: string[]): Promise<SocialPost[]> {\n if (!this.socialGeneratorService) {\n throw new InternalError('AI social generator service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n const textContent = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n const generated = await this.socialGeneratorService.generate(textContent, platforms);\n\n const now = new Date().toISOString();\n const workflowId = this.workflowDefaults['social-post'] ?? this.workflowDefaults['generic'];\n\n const posts: SocialPost[] = generated.map((g) => ({\n id: crypto.randomUUID(),\n contentId,\n platform: g.platform,\n body: g.body,\n status: 'draft' as const,\n platformPostId: null,\n publishedAt: null,\n createdAt: now,\n ...(workflowId !== undefined ? { workflowId } : {}),\n }));\n\n // Persist all posts\n for (const post of posts) {\n await this.storage.socialPosts.create(post);\n }\n\n // Emit event\n this.emitter.emit('ai:social:generated', { contentId, posts });\n\n return posts;\n }\n\n async enhance(contentId: string, opts?: EnhanceOptions): Promise<EnhancedContent> {\n if (!this.enhanceService) {\n throw new InternalError('AI enhance service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n const textContent = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n return this.enhanceService.enhance(textContent, opts);\n }\n\n async suggest(contentId: string): Promise<Suggestion[]> {\n if (!this.enhanceService) {\n throw new InternalError('AI enhance service not configured');\n }\n\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n const textContent = [content.title, content.body].filter(Boolean).join('\\n\\n')\n || JSON.stringify(content.data ?? {});\n\n return this.enhanceService.suggest(textContent);\n }\n}\n","/*\nCopyright (c) 2025 Bernier LLC\n\nThis file is licensed to the client under a limited-use license.\nThe client may use and modify this code *only within the scope of the project it was delivered for*.\nRedistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.\n*/\n\nimport { EventEmitter } from 'events';\nimport type { SocialNamespace } from '../types';\nimport type {\n SocialPlatformAdapter,\n PlatformPublishResult,\n PlatformInfo,\n PreviewResult,\n SocialMetrics,\n} from '../interfaces';\nimport type { ContentStorageAdapter } from '../storage';\nimport { NotFoundError, ValidationError, InternalError } from '../errors';\n\nexport class SocialNamespaceImpl implements SocialNamespace {\n private readonly store = new Map<string, SocialPlatformAdapter>();\n private readonly emitter: EventEmitter;\n private readonly storage: ContentStorageAdapter;\n\n constructor(emitter: EventEmitter, storage: ContentStorageAdapter) {\n this.emitter = emitter;\n this.storage = storage;\n }\n\n registerPlatform(adapter: SocialPlatformAdapter): void {\n this.store.set(adapter.id, adapter);\n }\n\n unregisterPlatform(id: string): void {\n if (!this.store.has(id)) {\n throw new NotFoundError(`Social platform not found: ${id}`);\n }\n this.store.delete(id);\n }\n\n listPlatforms(): PlatformInfo[] {\n return Array.from(this.store.values()).map((adapter) => ({\n id: adapter.id,\n name: adapter.name,\n acceptedTypes: adapter.acceptedTypes,\n hasPreview: typeof adapter.preview === 'function',\n hasMetrics: typeof adapter.getMetrics === 'function',\n }));\n }\n\n async publish(contentId: string, platforms: string[]): Promise<PlatformPublishResult[]> {\n // Check all platforms are registered\n const missing = platforms.filter((p) => !this.store.has(p));\n if (missing.length > 0) {\n throw new ValidationError(\n `Unregistered social platform(s): ${missing.join(', ')}`,\n { context: { missingPlatforms: missing } },\n );\n }\n\n // Get content\n const content = await this.storage.content.get(contentId);\n if (!content) {\n throw new NotFoundError(`Content item not found: ${contentId}`);\n }\n\n // Check publish-stage gating: content must be at a publish-eligible workflow stage\n if (content.workflowId) {\n const workflow = await this.storage.workflows.get(content.workflowId);\n if (workflow && workflow.stages && workflow.stages.length > 0) {\n const currentStage = workflow.stages.find((s) => s.id === content.workflowStage);\n const publishStage = workflow.stages.find((s) => s.isPublishStage);\n if (publishStage && (!currentStage || !currentStage.isPublishStage)) {\n throw new ValidationError(\n `Content is not at a publish-eligible stage. Current stage: \"${content.workflowStage ?? 'none'}\", ` +\n `required publish stage: \"${publishStage.id}\"`,\n {\n context: {\n currentStage: content.workflowStage ?? null,\n requiredStage: publishStage.id,\n },\n },\n );\n }\n }\n }\n\n // Get social posts for this content\n const socialPosts = await this.storage.socialPosts.findByContent(contentId);\n\n const results: PlatformPublishResult[] = [];\n\n for (const platformId of platforms) {\n const adapter = this.store.get(platformId);\n if (!adapter) {\n continue;\n }\n\n // Type validation\n if (!adapter.acceptedTypes.includes(content.type)) {\n results.push({\n platform: platformId,\n success: false,\n error: `Content type \"${content.type}\" not accepted by platform \"${platformId}\". Accepted: ${adapter.acceptedTypes.join(', ')}`,\n });\n continue;\n }\n\n // Find a social post for this platform\n const post = socialPosts.find((p) => p.platform === platformId && p.status === 'draft');\n if (!post) {\n results.push({\n platform: platformId,\n success: false,\n error: `No draft social post found for platform \"${platformId}\"`,\n });\n continue;\n }\n\n try {\n const result = await adapter.publish(post);\n results.push(result);\n\n // Update social post status\n if (result.success) {\n await this.storage.socialPosts.update(post.id, {\n status: 'published',\n publishedAt: new Date().toISOString(),\n ...(result.platformPostId !== undefined ? { platformPostId: result.platformPostId } : {}),\n });\n this.emitter.emit('social:published', { contentId, platform: platformId, result });\n } else {\n await this.storage.socialPosts.update(post.id, { status: 'failed' });\n }\n } catch (error) {\n await this.storage.socialPosts.update(post.id, { status: 'failed' });\n results.push({\n platform: platformId,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return results;\n }\n\n async preview(contentId: string, platform: string): Promise<PreviewResult> {\n const adapter = this.store.get(platform);\n if (!adapter) {\n throw new NotFoundError(`Social platform not found: ${platform}`);\n }\n\n if (!adapter.preview) {\n throw new InternalError(`Platform \"${platform}\" does not support preview`);\n }\n\n const posts = await this.storage.socialPosts.findByContent(contentId);\n const post = posts.find((p) => p.platform === platform);\n if (!post) {\n throw new NotFoundError(`No social post found for content \"${contentId}\" on platform \"${platform}\"`);\n }\n\n return adapter.preview(post);\n }\n\n async getMetrics(contentId: string, platform: string): Promise<SocialMetrics> {\n const adapter = this.store.get(platform);\n if (!adapter) {\n throw new NotFoundError(`Social platform not found: ${platform}`);\n }\n\n if (!adapter.getMetrics) {\n throw new InternalError(`Platform \"${platform}\" does not support metrics`);\n }\n\n const posts = await this.storage.socialPosts.findByContent(contentId);\n const post = posts.find((p) => p.platform === platform && p.platformPostId);\n if (!post || !post.platformPostId) {\n throw new NotFoundError(`No published social post found for content \"${contentId}\" on platform \"${platform}\"`);\n }\n\n return adapter.getMetrics(post.platformPostId);\n }\n}\n"],"mappings":";AAQA,SAAS,oBAAoB;;;ACA7B,SAAS,SAAS;AAEX,IAAM,gCAAgC,EAAE,OAAO;AAAA,EACpD,SAAS,EAAE,OAAO;AAAA,IAChB,iB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qBAAqB;AACvB;AAAA,QACF;AAGA,YAAI,eAAe,OAAO,oBAAoB,aAAa,UAAa,OAAO,SAAS,WAAW;AAEjG,gBAAM,eAAe,CAAC,GAAG,SAAS,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC1E,gBAAM,eAAe,aAAa,UAAU,CAAC,MAAM,EAAE,OAAO,aAAa,EAAE;AAC3E,gBAAM,YAAY,aAAa,eAAe,CAAC;AAE/C,cAAI,WAAW;AACb,kBAAM,YAAY,QAAQ;AAC1B,kBAAM,KAAK,SAAS,QAAQ,OAAO,WAAW;AAAA,cAC5C,eAAe,UAAU;AAAA,YAC3B,CAAC;AACD,iBAAK,KAAK,0BAA0B;AAAA,cAClC;AAAA,cACA,YAAY,QAAQ;AAAA,cACpB,MAAM;AAAA,cACN,IAAI,UAAU;AAAA,YAChB,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF,CAAC;AAED,SAAK,eAAe;AACpB,SAAK,KAAK,eAAe,MAA4B;AAAA,EACvD;AAAA,EAEA,MAAM,UAAyB;AAC7B,QAAI,CAAC,KAAK,cAAc;AACtB,YAAM,IAAI,cAAc,0BAA0B;AAAA,IACpD;AAEA,SAAK,eAAe;AACpB,SAAK,KAAK,YAAY,MAA4B;AAAA,EACpD;AAAA,EAKA,GAAG,OAAwB,UAA8C;AACvE,WAAO,MAAM,GAAG,OAAO,QAAQ;AAAA,EACjC;AAAA,EAIA,KAAK,UAA2B,MAA0B;AACxD,WAAO,MAAM,KAAK,OAAO,GAAG,IAAI;AAAA,EAClC;AACF;AAKO,SAAS,6BAA6B,SAAiE;AAC5G,SAAO,IAAI,2BAA2B,OAAO;AAC/C;","names":["z","z","crypto","crypto","crypto","crypto"]}
|
package/dist/prisma.d.mts
CHANGED
package/dist/prisma.d.ts
CHANGED
|
@@ -644,49 +644,67 @@ declare const ContentManagementConfigSchema: z.ZodObject<{
|
|
|
644
644
|
}>;
|
|
645
645
|
type ContentManagementConfig = z.infer<typeof ContentManagementConfigSchema>;
|
|
646
646
|
|
|
647
|
+
/**
|
|
648
|
+
* Typed error code union for content-management-suite errors.
|
|
649
|
+
*/
|
|
650
|
+
type ContentManagementErrorCode = 'CONTENT_MANAGEMENT_ERROR' | 'VALIDATION_ERROR' | 'NOT_FOUND' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'CONFLICT' | 'INTERNAL_ERROR';
|
|
651
|
+
/**
|
|
652
|
+
* Options bag accepted by `ContentManagementError`.
|
|
653
|
+
*
|
|
654
|
+
* - `cause`: chained underlying error (ES2022 Error.cause).
|
|
655
|
+
* - `code`: a typed error code from {@link ContentManagementErrorCode}.
|
|
656
|
+
* - `context`: arbitrary structured context.
|
|
657
|
+
*/
|
|
658
|
+
interface ContentManagementErrorOptions {
|
|
659
|
+
cause?: Error;
|
|
660
|
+
code?: ContentManagementErrorCode;
|
|
661
|
+
context?: Record<string, unknown>;
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Custom error class for content-management-suite errors.
|
|
665
|
+
*
|
|
666
|
+
* Uses native ES2022 `Error.cause` for error chaining — read the underlying
|
|
667
|
+
* error via `error.cause`. Structured context lives on `error.context`.
|
|
668
|
+
*/
|
|
647
669
|
declare class ContentManagementError extends Error {
|
|
648
|
-
readonly code:
|
|
649
|
-
readonly
|
|
650
|
-
constructor(message: string, options?:
|
|
651
|
-
cause?: Error;
|
|
652
|
-
code?: string;
|
|
653
|
-
details?: Record<string, unknown>;
|
|
654
|
-
});
|
|
670
|
+
readonly code: ContentManagementErrorCode;
|
|
671
|
+
readonly context?: Record<string, unknown>;
|
|
672
|
+
constructor(message: string, options?: ContentManagementErrorOptions);
|
|
655
673
|
}
|
|
656
674
|
declare class ValidationError extends ContentManagementError {
|
|
657
675
|
constructor(message: string, options?: {
|
|
658
676
|
cause?: Error;
|
|
659
|
-
|
|
677
|
+
context?: Record<string, unknown>;
|
|
660
678
|
});
|
|
661
679
|
}
|
|
662
680
|
declare class NotFoundError extends ContentManagementError {
|
|
663
681
|
constructor(message: string, options?: {
|
|
664
682
|
cause?: Error;
|
|
665
|
-
|
|
683
|
+
context?: Record<string, unknown>;
|
|
666
684
|
});
|
|
667
685
|
}
|
|
668
686
|
declare class UnauthorizedError extends ContentManagementError {
|
|
669
687
|
constructor(message: string, options?: {
|
|
670
688
|
cause?: Error;
|
|
671
|
-
|
|
689
|
+
context?: Record<string, unknown>;
|
|
672
690
|
});
|
|
673
691
|
}
|
|
674
692
|
declare class ForbiddenError extends ContentManagementError {
|
|
675
693
|
constructor(message: string, options?: {
|
|
676
694
|
cause?: Error;
|
|
677
|
-
|
|
695
|
+
context?: Record<string, unknown>;
|
|
678
696
|
});
|
|
679
697
|
}
|
|
680
698
|
declare class ConflictError extends ContentManagementError {
|
|
681
699
|
constructor(message: string, options?: {
|
|
682
700
|
cause?: Error;
|
|
683
|
-
|
|
701
|
+
context?: Record<string, unknown>;
|
|
684
702
|
});
|
|
685
703
|
}
|
|
686
704
|
declare class InternalError extends ContentManagementError {
|
|
687
705
|
constructor(message: string, options?: {
|
|
688
706
|
cause?: Error;
|
|
689
|
-
|
|
707
|
+
context?: Record<string, unknown>;
|
|
690
708
|
});
|
|
691
709
|
}
|
|
692
710
|
|
package/dist/utils.js
CHANGED
|
@@ -28,16 +28,16 @@ module.exports = __toCommonJS(utils_exports);
|
|
|
28
28
|
|
|
29
29
|
// src/errors.ts
|
|
30
30
|
var ContentManagementError = class extends Error {
|
|
31
|
+
code;
|
|
32
|
+
context;
|
|
31
33
|
constructor(message, options) {
|
|
32
|
-
super(message);
|
|
33
|
-
if (options?.cause !== void 0) {
|
|
34
|
-
this.cause = options.cause;
|
|
35
|
-
}
|
|
34
|
+
super(message, options?.cause ? { cause: options.cause } : void 0);
|
|
36
35
|
this.name = this.constructor.name;
|
|
37
36
|
this.code = options?.code ?? "CONTENT_MANAGEMENT_ERROR";
|
|
38
|
-
if (options?.
|
|
39
|
-
this.
|
|
37
|
+
if (options?.context !== void 0) {
|
|
38
|
+
this.context = options.context;
|
|
40
39
|
}
|
|
40
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
41
41
|
}
|
|
42
42
|
};
|
|
43
43
|
var ValidationError = class extends ContentManagementError {
|