The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
{
"$schema": "https://registry.mercurjs.com/registry-item.json",
"name": "messaging",
"description": "Buyer-vendor messaging with real-time SSE delivery, content filtering, admin oversight, GDPR erasure, and vendor portal UI.",
"dependencies": [
"ioredis"
],
"registryDependencies": [],
"docs": "## Configuration\n\nAdd the messaging modules to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/messaging',\n options: {\n // Optional. Defaults shown below.\n rateLimits: {\n messagesPerMinute: 20,\n conversationsPerHour: 5,\n },\n },\n },\n {\n resolve: './modules/messaging-filters',\n },\n {\n resolve: './modules/messaging-redis',\n options: {\n redisUrl: process.env.REDIS_URL,\n },\n },\n]\n```\n\n### Rate Limits\n\nThe `messaging` module accepts an optional `rateLimits` object that controls per-sender abuse protection:\n\n- `messagesPerMinute` — maximum messages any single sender (customer or vendor) can send across all conversations in a 60s window. Defaults to `20`.\n- `conversationsPerHour` — maximum new conversations a single sender can open in a 3600s window. Defaults to `5`.\n\nRate limiting is enforced via Redis. When the `messaging-redis` module is not configured (no `redisUrl`), rate limiting is skipped gracefully.\n\n## Middlewares\n\nAdd the messaging middlewares to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from \"@medusajs/medusa\";\nimport { storeMessagingMiddlewares } from \"./store/messages/middlewares\";\nimport { vendorMessagingMiddlewares } from \"./vendor/messages/middlewares\";\nimport { adminMessagingMiddlewares } from \"./admin/messages/middlewares\";\n\nexport default defineMiddlewares({\n routes: [\n ...storeMessagingMiddlewares,\n ...vendorMessagingMiddlewares,\n ...adminMessagingMiddlewares,\n ],\n});\n```\n\nIf you already have a `middlewares.ts` file, merge the messaging middleware imports and spread them into your existing `routes` array.\n\n## Environment Variables\n\nThe messaging block requires Redis for real-time delivery, rate limiting, and content filter cache invalidation:\n\n```env\nREDIS_URL=redis://localhost:6379\n```\n\n## Database Migrations\n\nAfter installing the block and adding the module configuration, generate and run the migrations:\n\n```bash\nnpx medusa db:generate messaging\nnpx medusa db:generate messagingFilters\nnpx medusa db:migrate\n```",
"categories": [
"messaging",
"api",
"vendor",
"admin"
],
"files": [
{
"path": "messaging/modules/messaging/index.ts",
"content": "import { Module } from \"@medusajs/framework/utils\"\n\nimport MessagingModuleService from \"./service\"\n\nexport const MESSAGING_MODULE = \"messaging\"\n\nexport * from \"./types/common\"\nexport * from \"./types/mutations\"\nexport { MessagingModuleService }\n\nexport default Module(MESSAGING_MODULE, {\n service: MessagingModuleService,\n})\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging/service.ts",
"content": "import { InjectManager, MedusaContext, MedusaService } from \"@medusajs/framework/utils\"\nimport { Context } from \"@medusajs/framework/types\"\nimport { EntityManager, type Knex } from \"@medusajs/framework/mikro-orm/knex\"\n\nimport { Conversation } from \"./models/conversation\"\nimport { Message } from \"./models/message\"\nimport { ChatBlock } from \"./models/chat-block\"\nimport {\n CursorPaginatedResult,\n ConversationDTO,\n MessageDTO,\n MessagingModuleOptions,\n ResolvedMessagingModuleOptions,\n MESSAGING_MODULE_OPTION_DEFAULTS,\n} from \"./types/common\"\n\nconst TABLE_CONVERSATION = \"conversation\"\nconst TABLE_MESSAGE = \"message\"\nconst TABLE_CHAT_BLOCK = \"chat_block\"\nconst MAX_PREVIEW_LENGTH = 100\n\nfunction escapeLike(value: string): string {\n return value.replace(/[\\\\%_]/g, (ch) => `\\\\${ch}`)\n}\n\nexport function encodeCursor(values: Record<string, string | number | null>): string {\n return Buffer.from(JSON.stringify(values)).toString(\"base64url\")\n}\n\nexport function decodeCursor(cursor: string): Record<string, string | number | null> | null {\n try {\n return JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf-8\"))\n } catch {\n return null\n }\n}\n\nclass MessagingModuleService extends MedusaService({\n Conversation,\n Message,\n ChatBlock,\n}) {\n protected readonly options_: ResolvedMessagingModuleOptions\n\n constructor(_deps: unknown, options?: MessagingModuleOptions) {\n // @ts-ignore — MedusaService base accepts arbitrary constructor args\n super(...arguments)\n this.options_ = {\n rateLimits: {\n ...MESSAGING_MODULE_OPTION_DEFAULTS.rateLimits,\n ...(options?.rateLimits ?? {}),\n },\n }\n }\n\n getOptions(): ResolvedMessagingModuleOptions {\n return this.options_\n }\n\n @InjectManager()\n async checkBuyersBlocked(\n buyerIds: string[],\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<Set<string>> {\n if (buyerIds.length === 0) return new Set()\n const knex = sharedContext!.manager!.getKnex()\n const rows: { customer_id: string }[] = await knex(TABLE_CHAT_BLOCK)\n .select(\"customer_id\")\n .whereIn(\"customer_id\", buyerIds)\n .whereNull(\"deleted_at\")\n return new Set(rows.map((r) => r.customer_id))\n }\n\n @InjectManager()\n async getBlockDetail(\n customerId: string,\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<{ blocked: boolean; reason: string | null }> {\n const knex = sharedContext!.manager!.getKnex()\n const row: { reason: string | null } | undefined = await knex(TABLE_CHAT_BLOCK)\n .select(\"reason\")\n .where(\"customer_id\", customerId)\n .whereNull(\"deleted_at\")\n .first()\n\n return row\n ? { blocked: true, reason: row.reason }\n : { blocked: false, reason: null }\n }\n\n @InjectManager()\n async listConversationsCursor(\n filter: { buyer_id?: string; seller_id?: string },\n pagination: { cursor?: string | null; limit?: number },\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<CursorPaginatedResult<ConversationDTO>> {\n const knex = sharedContext!.manager!.getKnex()\n const limit = Math.min(pagination.limit ?? 20, 50)\n\n let query = knex(TABLE_CONVERSATION)\n .select(\"*\")\n .where(\"deleted_at\", null)\n .orderByRaw(\"last_message_at DESC NULLS LAST, id DESC\")\n .limit(limit + 1)\n\n if (filter.buyer_id) {\n query = query.where(\"buyer_id\", filter.buyer_id)\n }\n\n if (filter.seller_id) {\n query = query.where(\"seller_id\", filter.seller_id)\n }\n\n if (pagination.cursor) {\n const decoded = decodeCursor(pagination.cursor)\n if (decoded && decoded.last_message_at && decoded.id) {\n query = query.where(function () {\n this.where(\"last_message_at\", \"<\", decoded.last_message_at!)\n .orWhere(function () {\n this.where(\"last_message_at\", \"=\", decoded.last_message_at!)\n .andWhere(\"id\", \"<\", decoded.id!)\n })\n })\n }\n }\n\n const rows: any[] = await query\n\n const hasMore = rows.length > limit\n const data = hasMore ? rows.slice(0, limit) : rows\n\n let next_cursor: string | null = null\n if (hasMore && data.length > 0) {\n const lastRow = data[data.length - 1]\n next_cursor = encodeCursor({\n last_message_at: lastRow.last_message_at?.toISOString?.() ?? lastRow.last_message_at,\n id: lastRow.id,\n })\n }\n\n return { data, next_cursor }\n }\n\n @InjectManager()\n async listMessagesCursor(\n conversationId: string,\n pagination: { cursor?: string | null; limit?: number },\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<CursorPaginatedResult<MessageDTO>> {\n const knex = sharedContext!.manager!.getKnex()\n const limit = Math.min(pagination.limit ?? 30, 100)\n\n let query = knex(TABLE_MESSAGE)\n .select(\"*\")\n .where(\"conversation_id\", conversationId)\n .where(\"deleted_at\", null)\n .orderByRaw(\"created_at DESC, id DESC\")\n .limit(limit + 1)\n\n if (pagination.cursor) {\n const decoded = decodeCursor(pagination.cursor)\n if (decoded && decoded.created_at && decoded.id) {\n query = query.where(function () {\n this.where(\"created_at\", \"<\", decoded.created_at!)\n .orWhere(function () {\n this.where(\"created_at\", \"=\", decoded.created_at!)\n .andWhere(\"id\", \"<\", decoded.id!)\n })\n })\n }\n }\n\n const rows: any[] = await query\n\n const hasMore = rows.length > limit\n const data = hasMore ? rows.slice(0, limit) : rows\n\n let next_cursor: string | null = null\n if (hasMore && data.length > 0) {\n const lastRow = data[data.length - 1]\n next_cursor = encodeCursor({\n created_at: lastRow.created_at?.toISOString?.() ?? lastRow.created_at,\n id: lastRow.id,\n })\n }\n\n return { data, next_cursor }\n }\n\n /**\n * Cross-module admin search: joins conversation with seller + customer\n * tables via raw Knex for performance (avoids N+1 queries). This is\n * intentional — admin oversight requires denormalized data in a single\n * paginated query. Module isolation is preserved at the application\n * layer; this method is only used by the admin search route.\n */\n @InjectManager()\n async searchConversationsAdmin(\n filter: {\n seller_name?: string\n buyer_name?: string\n date_from?: string\n date_to?: string\n context_type?: string\n context_id?: string\n },\n pagination: { cursor?: string | null; limit?: number },\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<CursorPaginatedResult<ConversationDTO & { seller_name?: string; buyer_name?: string; buyer_email?: string; message_count?: number }>> {\n const knex = sharedContext!.manager!.getKnex()\n const limit = Math.min(pagination.limit ?? 20, 50)\n\n let query = knex(`${TABLE_CONVERSATION} as c`)\n .select(\n \"c.*\",\n \"s.name as seller_name\",\n \"cust.first_name as buyer_first_name\",\n \"cust.last_name as buyer_last_name\",\n \"cust.email as buyer_email\"\n )\n .leftJoin(\n \"seller_seller_messaging_conversation as sc\",\n \"sc.conversation_id\",\n \"c.id\"\n )\n .leftJoin(\"seller as s\", \"s.id\", \"sc.seller_id\")\n .leftJoin(\n \"customer_customer_messaging_conversation as cc\",\n \"cc.conversation_id\",\n \"c.id\"\n )\n .leftJoin(\"customer as cust\", \"cust.id\", \"cc.customer_id\")\n .where(\"c.deleted_at\", null)\n .orderByRaw(\"c.last_message_at DESC NULLS LAST, c.id DESC\")\n .limit(limit + 1)\n\n if (filter.seller_name) {\n query = query.whereILike(\"s.name\", `%${escapeLike(filter.seller_name)}%`)\n }\n\n if (filter.buyer_name) {\n const escaped = escapeLike(filter.buyer_name)\n query = query.where(function () {\n this.whereILike(\"cust.first_name\", `%${escaped}%`)\n .orWhereILike(\"cust.last_name\", `%${escaped}%`)\n })\n }\n\n if (filter.date_from) {\n query = query.where(\"c.last_message_at\", \">=\", filter.date_from)\n }\n\n if (filter.date_to) {\n query = query.where(\"c.last_message_at\", \"<=\", filter.date_to)\n }\n\n if (filter.context_type || filter.context_id) {\n query = query.whereExists(function () {\n this.select(knex.raw(\"1\"))\n .from(`${TABLE_MESSAGE} as m`)\n .whereRaw(\"m.conversation_id = c.id\")\n\n if (filter.context_type) {\n this.where(\"m.context_type\", filter.context_type)\n }\n if (filter.context_id) {\n this.where(\"m.context_id\", filter.context_id)\n }\n })\n }\n\n if (pagination.cursor) {\n const decoded = decodeCursor(pagination.cursor)\n if (decoded && decoded.last_message_at && decoded.id) {\n query = query.where(function () {\n this.where(\"c.last_message_at\", \"<\", decoded.last_message_at!)\n .orWhere(function () {\n this.where(\"c.last_message_at\", \"=\", decoded.last_message_at!)\n .andWhere(\"c.id\", \"<\", decoded.id!)\n })\n })\n }\n }\n\n const rows: any[] = await query\n\n const hasMore = rows.length > limit\n const data = (hasMore ? rows.slice(0, limit) : rows).map((row: any) => ({\n ...row,\n buyer_name: [row.buyer_first_name, row.buyer_last_name]\n .filter(Boolean)\n .join(\" \"),\n }))\n\n let next_cursor: string | null = null\n if (hasMore && data.length > 0) {\n const lastRow = data[data.length - 1]\n next_cursor = encodeCursor({\n last_message_at: lastRow.last_message_at?.toISOString?.() ?? lastRow.last_message_at,\n id: lastRow.id,\n })\n }\n\n return { data, next_cursor }\n }\n\n @InjectManager()\n async getUnreadCountTotal(\n filter: { buyer_id?: string; seller_id?: string },\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<number> {\n const knex = sharedContext!.manager!.getKnex()\n\n const countField = filter.buyer_id\n ? \"unread_count_customer\"\n : \"unread_count_seller\"\n\n let query = knex(TABLE_CONVERSATION)\n .sum({ total: countField })\n .where(\"deleted_at\", null)\n\n if (filter.buyer_id) {\n query = query.where(\"buyer_id\", filter.buyer_id)\n }\n\n if (filter.seller_id) {\n query = query.where(\"seller_id\", filter.seller_id)\n }\n\n const [result] = await query\n\n return Number(result?.total ?? 0)\n }\n\n @InjectManager()\n async createMessageAtomic(\n data: {\n conversation_id: string\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n body: string\n context_type?: string | null\n context_id?: string | null\n context_label?: string | null\n },\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<MessageDTO> {\n const knex = sharedContext!.manager!.getKnex()\n\n const preview = data.body.substring(0, MAX_PREVIEW_LENGTH)\n const recipientCounterField =\n data.sender_type === \"customer\"\n ? \"unread_count_seller\"\n : \"unread_count_customer\"\n\n const now = new Date()\n\n return await knex.transaction(async (trx) => {\n const [message] = await trx(TABLE_MESSAGE)\n .insert({\n id: `msg_${generateId()}`,\n conversation_id: data.conversation_id,\n sender_id: data.sender_id,\n sender_type: data.sender_type,\n body: data.body,\n context_type: data.context_type ?? null,\n context_id: data.context_id ?? null,\n context_label: data.context_label ?? null,\n read_at: null,\n created_at: now,\n updated_at: now,\n deleted_at: null,\n })\n .returning(\"*\")\n\n await trx(TABLE_CONVERSATION)\n .where(\"id\", data.conversation_id)\n .update({\n last_message_preview: preview,\n last_message_sender_type: data.sender_type,\n last_message_at: now,\n [recipientCounterField]: knex.raw(`?? + 1`, [recipientCounterField]),\n updated_at: now,\n })\n\n return message\n })\n }\n\n @InjectManager()\n async markMessagesReadAtomic(\n conversationId: string,\n readerType: \"customer\" | \"seller\",\n @MedusaContext() sharedContext?: Context<EntityManager>\n ): Promise<number> {\n const knex = sharedContext!.manager!.getKnex()\n\n const senderType = readerType === \"customer\" ? \"seller\" : \"customer\"\n const counterField =\n readerType === \"customer\"\n ? \"unread_count_customer\"\n : \"unread_count_seller\"\n\n const now = new Date()\n\n return await knex.transaction(async (trx) => {\n const updated = await trx(TABLE_MESSAGE)\n .where(\"conversation_id\", conversationId)\n .where(\"sender_type\", senderType)\n .whereNull(\"read_at\")\n .whereNull(\"deleted_at\")\n .update({\n read_at: now,\n updated_at: now,\n })\n\n await trx(TABLE_CONVERSATION)\n .where(\"id\", conversationId)\n .update({\n [counterField]: 0,\n updated_at: now,\n })\n\n return updated\n })\n }\n}\n\nfunction generateId(): string {\n return crypto.randomUUID().replace(/-/g, \"\").substring(0, 16)\n}\n\nexport default MessagingModuleService\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging/models/conversation.ts",
"content": "import { model } from \"@medusajs/framework/utils\"\n\nexport const Conversation = model\n .define(\"conversation\", {\n id: model.id({ prefix: \"conv\" }).primaryKey(),\n buyer_id: model.text(),\n seller_id: model.text(),\n last_message_preview: model.text().nullable(),\n last_message_sender_type: model.enum([\"customer\", \"seller\"]).nullable(),\n last_message_at: model.dateTime().nullable(),\n unread_count_customer: model.number().default(0),\n unread_count_seller: model.number().default(0),\n messages: model.hasMany(() => Message, { mappedBy: \"conversation\" }),\n })\n .indexes([\n {\n on: [\"buyer_id\", \"seller_id\"],\n unique: true,\n },\n {\n on: [\"seller_id\", \"last_message_at\", \"id\"],\n },\n {\n on: [\"buyer_id\", \"last_message_at\", \"id\"],\n },\n ])\n\nimport { Message } from \"./message\"\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging/models/message.ts",
"content": "import { model } from \"@medusajs/framework/utils\"\nimport { Conversation } from \"./conversation\"\n\nexport const Message = model\n .define(\"message\", {\n id: model.id({ prefix: \"msg\" }).primaryKey(),\n conversation: model.belongsTo(() => Conversation, {\n mappedBy: \"messages\",\n }),\n sender_id: model.text(),\n sender_type: model.enum([\"customer\", \"seller\"]),\n body: model.text(),\n context_type: model.enum([\"product\", \"order\"]).nullable(),\n context_id: model.text().nullable(),\n context_label: model.text().nullable(),\n read_at: model.dateTime().nullable(),\n })\n .indexes([\n {\n on: [\"conversation_id\", \"created_at\", \"id\"],\n },\n {\n on: [\"context_type\", \"context_id\"],\n },\n {\n on: [\"created_at\"],\n },\n ])\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging/models/chat-block.ts",
"content": "import { model } from \"@medusajs/framework/utils\"\n\nexport const ChatBlock = model\n .define(\"chat_block\", {\n id: model.id({ prefix: \"cblk\" }).primaryKey(),\n customer_id: model.text(),\n blocked_by: model.text(),\n reason: model.text().nullable(),\n })\n .indexes([\n {\n on: [\"customer_id\"],\n unique: true,\n },\n ])\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging/types/common.ts",
"content": "export type SenderType = \"customer\" | \"seller\"\nexport type ContextType = \"product\" | \"order\"\n\nexport interface ConversationDTO {\n id: string\n buyer_id: string\n seller_id: string\n last_message_preview: string | null\n last_message_sender_type: SenderType | null\n last_message_at: Date | string | null\n unread_count_customer: number\n unread_count_seller: number\n created_at: Date | string\n updated_at: Date | string\n deleted_at: Date | string | null\n}\n\nexport interface MessageDTO {\n id: string\n conversation_id: string\n sender_id: string\n sender_type: SenderType\n body: string\n context_type: ContextType | null\n context_id: string | null\n context_label: string | null\n read_at: Date | string | null\n created_at: Date | string\n updated_at: Date | string\n deleted_at: Date | string | null\n}\n\nexport interface CursorPaginationParams {\n cursor?: string | null\n limit?: number\n}\n\nexport interface CursorPaginatedResult<T> {\n data: T[]\n next_cursor: string | null\n}\n\nexport interface StoreConversationResponse {\n conversation: ConversationDTO\n}\n\nexport type StoreConversationListResponse = {\n conversations: ConversationDTO[]\n next_cursor: string | null\n}\n\nexport interface StoreMessageResponse {\n message: MessageDTO\n}\n\nexport type StoreMessageListResponse = {\n messages: MessageDTO[]\n next_cursor: string | null\n}\n\nexport interface VendorConversationResponse {\n conversation: ConversationDTO\n}\n\nexport type VendorConversationListResponse = {\n conversations: ConversationDTO[]\n next_cursor: string | null\n}\n\nexport interface VendorMessageResponse {\n message: MessageDTO\n}\n\nexport type AdminConversationListResponse = {\n conversations: ConversationDTO[]\n next_cursor: string | null\n}\n\nexport interface AdminConversationResponse {\n conversation: ConversationDTO\n}\n\nexport interface ChatBlockDTO {\n id: string\n customer_id: string\n blocked_by: string\n reason: string | null\n created_at: Date | string\n updated_at: Date | string\n}\n\nexport interface UnreadCountResponse {\n unread_count: number\n}\n\nexport interface SseTokenResponse {\n token: string\n}\n\nexport type MessagingRateLimitOptions = {\n /** Maximum messages a single sender can send per minute. */\n messagesPerMinute?: number\n /** Maximum new conversations a single sender can open per hour. */\n conversationsPerHour?: number\n}\n\nexport type MessagingModuleOptions = {\n rateLimits?: MessagingRateLimitOptions\n}\n\nexport type ResolvedMessagingRateLimitOptions = {\n messagesPerMinute: number\n conversationsPerHour: number\n}\n\nexport type ResolvedMessagingModuleOptions = {\n rateLimits: ResolvedMessagingRateLimitOptions\n}\n\nexport const MESSAGING_MODULE_OPTION_DEFAULTS: ResolvedMessagingModuleOptions = {\n rateLimits: {\n messagesPerMinute: 20,\n conversationsPerHour: 5,\n },\n}\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging/types/mutations.ts",
"content": "import { ContextType, SenderType } from \"./common\"\n\nexport interface CreateConversationInput {\n buyer_id: string\n seller_id: string\n}\n\nexport interface SendMessageInput {\n conversation_id: string\n sender_id: string\n sender_type: SenderType\n body: string\n context_type?: ContextType | null\n context_id?: string | null\n context_label?: string | null\n}\n\nexport interface MarkMessagesReadInput {\n conversation_id: string\n reader_id: string\n reader_type: SenderType\n}\n\nexport interface BlockCustomerInput {\n customer_id: string\n blocked_by: string\n reason?: string | null\n}\n\nexport interface UnblockCustomerInput {\n customer_id: string\n}\n\nexport interface PublishMessageEventInput {\n conversation_id: string\n recipient_id: string\n sender_type: SenderType\n event_type: \"new_message\" | \"messages_read\" | \"unread_count\"\n context_type?: string | null\n context_label?: string | null\n message_id?: string\n unread_count?: number\n}\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/index.ts",
"content": "import { Module } from \"@medusajs/framework/utils\"\n\nimport MessagingFiltersModuleService from \"./service\"\nimport seedBuiltinRules from \"./loaders/seed-builtin-rules\"\nimport compileFiltersLoader from \"./loaders/compile-filters\"\n\nexport const MESSAGING_FILTERS_MODULE = \"messagingFilters\"\n\nexport * from \"./types/common\"\nexport { MessagingFiltersModuleService }\n\nexport default Module(MESSAGING_FILTERS_MODULE, {\n service: MessagingFiltersModuleService,\n loaders: [seedBuiltinRules, compileFiltersLoader],\n})\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/service.ts",
"content": "import { MedusaService } from \"@medusajs/framework/utils\"\n\nimport { FilterRule } from \"./models/filter-rule\"\nimport { BlockedMessageLog } from \"./models/blocked-message-log\"\nimport {\n CompiledRuleset,\n FilterEvaluationResult,\n} from \"./types/common\"\n\nclass MessagingFiltersModuleService extends MedusaService({\n FilterRule,\n BlockedMessageLog,\n}) {\n evaluateMessage(\n body: string,\n ruleset: CompiledRuleset\n ): FilterEvaluationResult {\n const lowercasedBody = body.toLowerCase()\n const words = lowercasedBody.split(/\\s+/)\n\n // 1. Exact word match — O(1) per word via hash set\n for (const word of words) {\n if (ruleset.exactWords.has(word)) {\n const ruleId = ruleset.exactRules.get(word)\n return {\n matched: true,\n rule_id: ruleId,\n match_type: \"exact\",\n pattern: word,\n }\n }\n }\n\n // 2. Contains/substring match — O(n) per pattern\n for (const entry of ruleset.containsPatterns) {\n if (lowercasedBody.includes(entry.pattern)) {\n return {\n matched: true,\n rule_id: entry.id,\n match_type: \"contains\",\n pattern: entry.pattern,\n }\n }\n }\n\n // 3. Regex match (built-in only) — O(n) per pattern\n for (const entry of ruleset.regexPatterns) {\n if (entry.regex.test(body)) {\n return {\n matched: true,\n rule_id: entry.id,\n match_type: \"regex\",\n pattern: entry.regex.source,\n }\n }\n }\n\n return { matched: false }\n }\n}\n\nexport default MessagingFiltersModuleService\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/models/filter-rule.ts",
"content": "import { model } from \"@medusajs/framework/utils\"\n\nexport const FilterRule = model.define(\"filter_rule\", {\n id: model.id({ prefix: \"filt\" }).primaryKey(),\n match_type: model.enum([\"exact\", \"contains\", \"regex\"]),\n pattern: model.text(),\n is_builtin: model.boolean().default(false),\n is_enabled: model.boolean().default(true),\n description: model.text().nullable(),\n})\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/models/blocked-message-log.ts",
"content": "import { model } from \"@medusajs/framework/utils\"\n\nexport const BlockedMessageLog = model.define(\"blocked_message_log\", {\n id: model.id({ prefix: \"bml\" }).primaryKey(),\n sender_id: model.text(),\n sender_type: model.enum([\"customer\", \"seller\"]),\n conversation_id: model.text(),\n matched_rule_id: model.text(),\n message_body: model.text(),\n})\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/types/common.ts",
"content": "export type MatchType = \"exact\" | \"contains\" | \"regex\"\n\nexport interface FilterRuleDTO {\n id: string\n match_type: MatchType\n pattern: string\n is_builtin: boolean\n is_enabled: boolean\n description: string | null\n created_at: Date | string\n updated_at: Date | string\n deleted_at: Date | string | null\n}\n\nexport interface BlockedMessageLogDTO {\n id: string\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n conversation_id: string\n matched_rule_id: string\n message_body: string\n created_at: Date | string\n updated_at: Date | string\n deleted_at: Date | string | null\n}\n\nexport interface CompiledRuleset {\n exactWords: Set<string>\n exactRules: Map<string, string> // lowercased word -> rule id\n containsPatterns: Array<{ id: string; pattern: string }> // lowercased\n regexPatterns: Array<{ id: string; regex: RegExp }>\n}\n\nexport interface FilterEvaluationResult {\n matched: boolean\n rule_id?: string\n match_type?: MatchType\n pattern?: string\n}\n\nexport interface AdminFilterRuleResponse {\n filter: FilterRuleDTO\n}\n\nexport type AdminFilterRuleListResponse = {\n filters: FilterRuleDTO[]\n next_cursor: string | null\n}\n\nexport interface AdminBlockedMessageLogListResponse {\n blocked_messages: BlockedMessageLogDTO[]\n next_cursor: string | null\n}\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/loaders/compile-filters.ts",
"content": "import { LoaderOptions, IMedusaInternalService } from \"@medusajs/framework/types\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\nimport { FilterRule } from \"../models/filter-rule\"\nimport { CompiledRuleset } from \"../types/common\"\n\nlet compiledRuleset: CompiledRuleset = {\n exactWords: new Set<string>(),\n exactRules: new Map<string, string>(),\n containsPatterns: [],\n regexPatterns: [],\n}\n\nexport function getCompiledRuleset(): CompiledRuleset {\n return compiledRuleset\n}\n\nexport function isRulesetEmpty(): boolean {\n return (\n compiledRuleset.exactWords.size === 0 &&\n compiledRuleset.containsPatterns.length === 0 &&\n compiledRuleset.regexPatterns.length === 0\n )\n}\n\nexport function invalidateRuleset(): void {\n compiledRuleset = {\n exactWords: new Set<string>(),\n exactRules: new Map<string, string>(),\n containsPatterns: [],\n regexPatterns: [],\n }\n}\n\nasync function compileFilters(container: any): Promise<void> {\n // Try module container first (when called from module loader), then app container\n let rules: any[]\n try {\n const service = container.resolve(\"filterRuleService\") as IMedusaInternalService<typeof FilterRule>\n const [results] = await service.listAndCount({ is_enabled: true } as any, { take: 1000 })\n rules = results\n } catch {\n // Fallback: resolve from app container via module name (used by workflow steps)\n try {\n const service = container.resolve(\"messagingFilters\")\n rules = await service.listFilterRules({ is_enabled: true }, { take: 1000 })\n } catch {\n return\n }\n }\n\n const newRuleset: CompiledRuleset = {\n exactWords: new Set<string>(),\n exactRules: new Map<string, string>(),\n containsPatterns: [],\n regexPatterns: [],\n }\n\n for (const rule of rules) {\n switch (rule.match_type) {\n case \"exact\": {\n const lowered = rule.pattern.toLowerCase()\n newRuleset.exactWords.add(lowered)\n newRuleset.exactRules.set(lowered, rule.id)\n break\n }\n case \"contains\": {\n newRuleset.containsPatterns.push({\n id: rule.id,\n pattern: rule.pattern.toLowerCase(),\n })\n break\n }\n case \"regex\": {\n try {\n const regex = new RegExp(rule.pattern, \"i\")\n // ReDoS protection: test with a probe string under a time budget\n const probeStart = Date.now()\n regex.test(\"a\".repeat(50))\n if (Date.now() - probeStart > 10) {\n // Pattern took >10ms on a short string — likely catastrophic backtracking\n try {\n const logger = container.resolve?.(ContainerRegistrationKeys.LOGGER)\n logger?.warn(`[messaging] Skipping ReDoS-prone regex rule ${rule.id}: ${rule.pattern}`)\n } catch { /* no logger available */ }\n break\n }\n newRuleset.regexPatterns.push({\n id: rule.id,\n regex,\n })\n } catch {\n // Skip invalid regex patterns\n }\n break\n }\n }\n }\n\n compiledRuleset = newRuleset\n}\n\nexport async function recompileFilters(container: any): Promise<void> {\n await compileFilters(container)\n}\n\nexport default async function compileFiltersLoader({\n container,\n}: LoaderOptions): Promise<void> {\n try {\n await compileFilters(container)\n } catch {\n // Will be compiled lazily on first message\n }\n}\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-filters/loaders/seed-builtin-rules.ts",
"content": "import { LoaderOptions, IMedusaInternalService } from \"@medusajs/framework/types\"\nimport { FilterRule } from \"../models/filter-rule\"\n\nconst BUILTIN_RULES = [\n {\n match_type: \"regex\",\n pattern: \"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}\",\n description: \"Blocks email addresses to keep communication on-platform\",\n is_builtin: true,\n is_enabled: true,\n },\n {\n match_type: \"regex\",\n pattern: \"(?:\\\\+\\\\d{1,3}[-.\\\\s]?)?(?:\\\\(?\\\\d{2,4}\\\\)?[-.\\\\s]?)?\\\\d{3,4}[-.\\\\s]?\\\\d{4,}\",\n description: \"Blocks phone numbers to keep communication on-platform\",\n is_builtin: true,\n is_enabled: true,\n },\n {\n match_type: \"regex\",\n pattern: \"https?://[^\\\\s]+|www\\\\.[^\\\\s]+\",\n description: \"Blocks URLs and links to prevent spam and phishing\",\n is_builtin: true,\n is_enabled: true,\n },\n]\n\nexport default async function seedBuiltinRules({\n container,\n}: LoaderOptions): Promise<void> {\n const service = container.resolve(\"filterRuleService\") as IMedusaInternalService<typeof FilterRule>\n\n for (const rule of BUILTIN_RULES) {\n try {\n const [existing, count] = await service.listAndCount({\n pattern: rule.pattern,\n is_builtin: true,\n } as any, { take: 1 })\n\n if (count === 0) {\n await service.create(rule as any)\n }\n } catch {\n // Skip if already seeded\n }\n }\n}\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-redis/index.ts",
"content": "import { Module } from \"@medusajs/framework/utils\"\n\nimport MessagingRedisModuleService from \"./service\"\nimport messagingRedisConnectionLoader from \"./loaders/connection\"\n\nexport const MESSAGING_REDIS_MODULE = \"messagingRedis\"\n\nexport { MessagingRedisModuleService }\n\nexport default Module(MESSAGING_REDIS_MODULE, {\n service: MessagingRedisModuleService,\n loaders: [messagingRedisConnectionLoader],\n})\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-redis/service.ts",
"content": "import Redis from \"ioredis\"\n\ntype MessagingRedisModuleOptions = {\n redisUrl?: string\n}\n\nclass MessagingRedisModuleService {\n private connection_: Redis | null\n\n static readonly identifier = \"messagingRedis\"\n\n __hooks: Record<string, () => Promise<void>>\n\n constructor(\n { messagingRedisConnection }: { messagingRedisConnection: Redis | null },\n options: MessagingRedisModuleOptions\n ) {\n this.connection_ = messagingRedisConnection\n\n this.__hooks = {\n onApplicationShutdown: async () => {\n if (this.connection_) {\n this.connection_.disconnect()\n }\n },\n }\n }\n\n get isAvailable(): boolean {\n return this.connection_ !== null\n }\n\n // --- Token operations (SSE one-time tokens) ---\n\n async setToken(token: string, value: string, ttlSeconds: number): Promise<void> {\n if (!this.connection_) return\n await this.connection_.set(`sse_token:${token}`, value, \"EX\", ttlSeconds)\n }\n\n async consumeToken(token: string): Promise<string | null> {\n if (!this.connection_) return null\n // Atomic get-and-delete to prevent TOCTOU race (token reuse)\n const value = await this.connection_.getdel(`sse_token:${token}`)\n return value\n }\n\n // --- Rate limiting ---\n\n async checkRateLimit(\n key: string,\n limit: number,\n windowSeconds: number\n ): Promise<{ allowed: boolean; count: number }> {\n if (!this.connection_) return { allowed: true, count: 0 }\n\n // Atomic INCR + conditional EXPIRE via Lua to prevent orphaned keys\n const luaScript = `\n local count = redis.call('INCR', KEYS[1])\n if count == 1 then\n redis.call('EXPIRE', KEYS[1], ARGV[1])\n end\n return count\n `\n const count = await this.connection_.eval(\n luaScript, 1, key, windowSeconds\n ) as number\n\n return { allowed: count <= limit, count }\n }\n\n // --- Pub/Sub: publish ---\n\n async publish(channel: string, data: Record<string, unknown>): Promise<void> {\n if (!this.connection_) return\n await this.connection_.publish(channel, JSON.stringify(data))\n }\n\n // --- Pub/Sub: create subscriber ---\n\n createSubscriber(): Redis | null {\n if (!this.connection_) return null\n return this.connection_.duplicate()\n }\n\n // --- Notification throttle ---\n\n async trySetThrottle(key: string, ttlSeconds: number): Promise<boolean> {\n if (!this.connection_) return true // No Redis = allow (don't block notifications)\n\n const result = await this.connection_.set(key, \"1\", \"EX\", ttlSeconds, \"NX\")\n return result === \"OK\"\n }\n}\n\nexport default MessagingRedisModuleService\n",
"type": "registry:api"
},
{
"path": "messaging/modules/messaging-redis/loaders/connection.ts",
"content": "import { LoaderOptions } from \"@medusajs/framework/types\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\nimport { asValue } from \"@medusajs/framework/awilix\"\nimport Redis from \"ioredis\"\n\nexport default async function messagingRedisConnectionLoader({\n container,\n options,\n}: LoaderOptions): Promise<void> {\n const logger = container.resolve(ContainerRegistrationKeys.LOGGER)\n\n const redisUrl = options?.redisUrl as string | undefined\n\n if (!redisUrl) {\n logger.warn(\n \"[messaging-redis] No redisUrl provided in module options — Redis features disabled\"\n )\n container.register(\"messagingRedisConnection\", asValue(null))\n return\n }\n\n try {\n const connection = new Redis(redisUrl, {\n lazyConnect: true,\n maxRetriesPerRequest: 3,\n retryStrategy(times: number) {\n if (times > 5) return null\n return Math.min(times * 200, 2000)\n },\n })\n\n await connection.connect()\n\n container.register(\"messagingRedisConnection\", asValue(connection))\n\n logger.info(\"[messaging-redis] Connected to Redis\")\n } catch (err) {\n logger.error(\n `[messaging-redis] Failed to connect to Redis: ${(err as Error).message}`\n )\n container.register(\"messagingRedisConnection\", asValue(null))\n }\n}\n",
"type": "registry:api"
},
{
"path": "messaging/links/conversation-seller.ts",
"content": "import { defineLink } from \"@medusajs/framework/utils\"\n\nimport SellerModule from \"@mercurjs/core/modules/seller\"\nimport MessagingModule from \"../modules/messaging\"\n\nexport default defineLink(SellerModule.linkable.seller, {\n linkable: MessagingModule.linkable.conversation,\n isList: true,\n})\n",
"type": "registry:api"
},
{
"path": "messaging/links/conversation-customer.ts",
"content": "import { defineLink } from \"@medusajs/framework/utils\"\nimport CustomerModule from \"@medusajs/medusa/customer\"\n\nimport MessagingModule from \"../modules/messaging\"\n\nexport default defineLink(CustomerModule.linkable.customer, {\n linkable: MessagingModule.linkable.conversation,\n isList: true,\n})\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/validate-rate-limit.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../modules/messaging-redis/service\"\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\n\ntype ValidateRateLimitInput = {\n sender_id: string\n is_new_conversation: boolean\n}\n\nexport const validateRateLimitStep = createStep(\n \"validate-rate-limit\",\n async (input: ValidateRateLimitInput, { container }) => {\n let redisService: MessagingRedisModuleService\n\n try {\n redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n } catch {\n // Module not registered — skip rate limiting gracefully\n return new StepResponse(undefined)\n }\n\n if (!redisService.isAvailable) {\n return new StepResponse(undefined)\n }\n\n const messagingService = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const rateLimits = messagingService.getOptions().rateLimits\n\n try {\n const msgResult = await redisService.checkRateLimit(\n `ratelimit:msg:${input.sender_id}`,\n rateLimits.messagesPerMinute,\n 60\n )\n\n if (!msgResult.allowed) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"You are sending messages too quickly. Please wait a moment and try again.\"\n )\n }\n\n if (input.is_new_conversation) {\n const convResult = await redisService.checkRateLimit(\n `ratelimit:conv:${input.sender_id}`,\n rateLimits.conversationsPerHour,\n 3600\n )\n\n if (!convResult.allowed) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"You are sending messages too quickly. Please wait a moment and try again.\"\n )\n }\n }\n } catch (err) {\n if (err instanceof MedusaError) {\n throw err\n }\n // Redis operation failed — skip rate limiting gracefully\n }\n\n return new StepResponse(undefined)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/validate-content-filter.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../modules/messaging-filters/service\"\nimport { getCompiledRuleset, recompileFilters, isRulesetEmpty } from \"../../../modules/messaging-filters/loaders/compile-filters\"\n\ntype ValidateContentFilterInput = {\n body: string\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n conversation_id: string\n}\n\nexport const validateContentFilterStep = createStep(\n \"validate-content-filter\",\n async (input: ValidateContentFilterInput, { container }) => {\n const filtersService = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n // Lazy-compile rules if ruleset is empty (first message or after invalidation)\n if (isRulesetEmpty()) {\n try {\n await recompileFilters(container)\n } catch {\n // Continue with empty ruleset\n }\n }\n\n const ruleset = getCompiledRuleset()\n const result = filtersService.evaluateMessage(input.body, ruleset)\n\n if (result.matched) {\n // Log the blocked message\n await filtersService.createBlockedMessageLogs({\n sender_id: input.sender_id,\n sender_type: input.sender_type,\n conversation_id: input.conversation_id,\n matched_rule_id: result.rule_id!,\n message_body: input.body,\n })\n\n throw new MedusaError(\n MedusaError.Types.INVALID_DATA,\n \"Your message could not be sent. Please revise and try again.\"\n )\n }\n\n return new StepResponse(undefined)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/create-message.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { SendMessageInput } from \"../../../modules/messaging/types/mutations\"\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\")\n}\n\nexport const createMessageStep = createStep(\n \"create-message\",\n async (input: SendMessageInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const message = await service.createMessageAtomic({\n conversation_id: input.conversation_id,\n sender_id: input.sender_id,\n sender_type: input.sender_type,\n body: escapeHtml(input.body),\n context_type: input.context_type,\n context_id: input.context_id,\n context_label: input.context_label,\n })\n\n return new StepResponse(message, message.id)\n },\n async (messageId, { container }) => {\n if (!messageId) return\n\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n await service.deleteMessages([messageId])\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/publish-message-event.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../modules/messaging-redis/service\"\nimport { PublishMessageEventInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const publishMessageEventStep = createStep(\n \"publish-message-event\",\n async (input: PublishMessageEventInput, { container }) => {\n try {\n const redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n\n await redisService.publish(\"messaging\", {\n conversation_id: input.conversation_id,\n recipient_id: input.recipient_id,\n sender_type: input.sender_type,\n event_type: input.event_type,\n context_type: input.context_type ?? null,\n context_label: input.context_label ?? null,\n message_id: input.message_id ?? null,\n unread_count: input.unread_count ?? null,\n })\n } catch {\n // Redis publish is best-effort — client catches up via Last-Event-ID\n }\n\n return new StepResponse(undefined)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/create-conversation.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { CreateConversationInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const createConversationStep = createStep(\n \"create-conversation\",\n async (input: CreateConversationInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const conversation = await service.createConversations({\n buyer_id: input.buyer_id,\n seller_id: input.seller_id,\n })\n\n return new StepResponse(conversation, conversation.id)\n },\n async (conversationId, { container }) => {\n if (!conversationId) return\n\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n await service.deleteConversations([conversationId])\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/mark-messages-read.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { MarkMessagesReadInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const markMessagesReadStep = createStep(\n \"mark-messages-read\",\n async (input: MarkMessagesReadInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const updated = await service.markMessagesReadAtomic(\n input.conversation_id,\n input.reader_type\n )\n\n return new StepResponse({ conversation_id: input.conversation_id, updated })\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/anonymize-messages-batch.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\n\ntype AnonymizeBatchInput = {\n conversation_ids: string[]\n actor_type: \"customer\" | \"seller\"\n batch_size?: number\n}\n\nexport const anonymizeMessagesBatchStep = createStep(\n \"anonymize-messages-batch\",\n async (input: AnonymizeBatchInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const batchSize = input.batch_size ?? 500\n let totalAnonymized = 0\n\n for (const conversationId of input.conversation_ids) {\n let hasMore = true\n let skip = 0\n\n while (hasMore) {\n const messages = await service.listMessages(\n {\n conversation_id: conversationId,\n sender_type: input.actor_type,\n },\n { take: batchSize, skip }\n )\n\n if (!messages || messages.length === 0) {\n hasMore = false\n break\n }\n\n const messageIds = messages.map((m: { id: string }) => m.id)\n\n for (const msgId of messageIds) {\n await service.updateMessages({\n id: msgId,\n body: \"[Message removed]\",\n })\n }\n\n totalAnonymized += messageIds.length\n skip += batchSize\n\n if (messages.length < batchSize) {\n hasMore = false\n }\n }\n }\n\n return new StepResponse(\n { anonymized_count: totalAnonymized },\n { conversation_ids: input.conversation_ids, actor_type: input.actor_type, count: totalAnonymized }\n )\n },\n async (compensationData, { container }) => {\n if (!compensationData) return\n // Message body anonymization is irreversible — original content is lost.\n // Log for auditability so operators know a partial rollback occurred.\n const logger = container.resolve(ContainerRegistrationKeys.LOGGER)\n logger.warn(\n `Messaging: anonymize-messages-batch compensation triggered for ${compensationData.count} messages ` +\n `in conversations [${compensationData.conversation_ids.join(\", \")}]. ` +\n `Message bodies cannot be restored — they were replaced with \"[Message removed]\".`\n )\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/validate-chat-block.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\n\ntype ValidateChatBlockInput = {\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n recipient_id: string\n}\n\nexport const validateChatBlockStep = createStep(\n \"validate-chat-block\",\n async (input: ValidateChatBlockInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const customerId =\n input.sender_type === \"customer\" ? input.sender_id : input.recipient_id\n const blocked = await service.checkBuyersBlocked([customerId])\n\n if (blocked.has(customerId)) {\n if (input.sender_type === \"customer\") {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Your chat access has been suspended\"\n )\n } else {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Cannot send messages to a blocked customer\"\n )\n }\n }\n\n return new StepResponse(undefined)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/block-customer.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { BlockCustomerInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const blockCustomerStep = createStep(\n \"block-customer\",\n async (input: BlockCustomerInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const existing = await service.listChatBlocks(\n { customer_id: input.customer_id },\n { take: 1 }\n )\n\n if (existing.length > 0) {\n return new StepResponse(existing[0], null)\n }\n\n const [block] = await service.createChatBlocks([\n {\n customer_id: input.customer_id,\n blocked_by: input.blocked_by,\n reason: input.reason ?? null,\n },\n ])\n\n return new StepResponse(block, block.id)\n },\n async (blockId, { container }) => {\n if (!blockId) return\n\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n await service.deleteChatBlocks([blockId])\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/steps/unblock-customer.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { UnblockCustomerInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const unblockCustomerStep = createStep(\n \"unblock-customer\",\n async (input: UnblockCustomerInput, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const existing = await service.listChatBlocks(\n { customer_id: input.customer_id },\n { take: 1 }\n )\n\n if (existing.length === 0) {\n return new StepResponse(null, null)\n }\n\n await service.deleteChatBlocks([existing[0].id])\n return new StepResponse(null, existing[0])\n },\n async (deletedBlock: any, { container }) => {\n if (!deletedBlock) return\n\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n await service.createChatBlocks([\n {\n customer_id: deletedBlock.customer_id,\n blocked_by: deletedBlock.blocked_by,\n reason: deletedBlock.reason,\n },\n ])\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/send-message.ts",
"content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\nimport { emitEventStep } from \"@medusajs/medusa/core-flows\"\n\nimport { validateChatBlockStep } from \"../steps/validate-chat-block\"\nimport { validateRateLimitStep } from \"../steps/validate-rate-limit\"\nimport { validateContentFilterStep } from \"../steps/validate-content-filter\"\nimport { createMessageStep } from \"../steps/create-message\"\nimport { publishMessageEventStep } from \"../steps/publish-message-event\"\nimport { SendMessageInput } from \"../../../modules/messaging/types/mutations\"\n\ntype SendMessageWorkflowInput = SendMessageInput & {\n recipient_id: string\n is_new_conversation: boolean\n}\n\nexport const sendMessageWorkflow = createWorkflow(\n { name: \"send-message\" },\n function (input: SendMessageWorkflowInput) {\n const blockCheckInput = transform(input, (data) => ({\n sender_id: data.sender_id,\n sender_type: data.sender_type,\n recipient_id: data.recipient_id,\n }))\n\n validateChatBlockStep(blockCheckInput)\n\n const rateLimitInput = transform(input, (data) => ({\n sender_id: data.sender_id,\n is_new_conversation: data.is_new_conversation,\n }))\n\n validateRateLimitStep(rateLimitInput)\n\n const filterInput = transform(input, (data) => ({\n body: data.body,\n sender_id: data.sender_id,\n sender_type: data.sender_type,\n conversation_id: data.conversation_id,\n }))\n\n validateContentFilterStep(filterInput)\n\n const messageInput = transform(input, (data) => ({\n conversation_id: data.conversation_id,\n sender_id: data.sender_id,\n sender_type: data.sender_type,\n body: data.body,\n context_type: data.context_type,\n context_id: data.context_id,\n context_label: data.context_label,\n }))\n\n const message = createMessageStep(messageInput)\n\n const publishInput = transform({ input, message }, ({ input, message }) => ({\n conversation_id: input.conversation_id,\n recipient_id: input.recipient_id,\n sender_type: input.sender_type,\n event_type: \"new_message\" as const,\n context_type: input.context_type,\n context_label: input.context_label,\n message_id: message.id,\n }))\n\n publishMessageEventStep(publishInput)\n\n const eventData = transform({ input, message }, ({ input, message }) => ({\n eventName: \"messaging.message.created\",\n data: {\n id: message.id,\n conversation_id: input.conversation_id,\n sender_id: input.sender_id,\n sender_type: input.sender_type,\n recipient_id: input.recipient_id,\n },\n }))\n\n emitEventStep(eventData)\n\n return new WorkflowResponse(message)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/create-conversation.ts",
"content": "import {\n createWorkflow,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\nimport { createRemoteLinkStep } from \"@medusajs/medusa/core-flows\"\nimport { Modules } from \"@medusajs/framework/utils\"\n\nimport { createConversationStep } from \"../steps/create-conversation\"\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\n\ntype CreateConversationWorkflowInput = {\n buyer_id: string\n seller_id: string\n}\n\nexport const createConversationWorkflow = createWorkflow(\n { name: \"create-conversation\" },\n function (input: CreateConversationWorkflowInput) {\n const conversation = createConversationStep(input)\n\n createRemoteLinkStep([\n {\n [Modules.CUSTOMER]: { customer_id: input.buyer_id },\n [MESSAGING_MODULE]: { conversation_id: conversation.id },\n },\n {\n \"seller\": { seller_id: input.seller_id },\n [MESSAGING_MODULE]: { conversation_id: conversation.id },\n },\n ] as any)\n\n return new WorkflowResponse(conversation)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/mark-messages-read.ts",
"content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\n\nimport { markMessagesReadStep } from \"../steps/mark-messages-read\"\nimport { publishMessageEventStep } from \"../steps/publish-message-event\"\nimport { MarkMessagesReadInput } from \"../../../modules/messaging/types/mutations\"\n\ntype MarkMessagesReadWorkflowInput = MarkMessagesReadInput & {\n sender_id: string\n}\n\nexport const markMessagesReadWorkflow = createWorkflow(\n { name: \"mark-messages-read\" },\n function (input: MarkMessagesReadWorkflowInput) {\n const result = markMessagesReadStep(input)\n\n const readEventInput = transform({ input }, ({ input }) => ({\n conversation_id: input.conversation_id,\n recipient_id: input.sender_id,\n sender_type: input.reader_type,\n event_type: \"messages_read\" as const,\n }))\n\n publishMessageEventStep(readEventInput)\n\n const unreadEventInput = transform({ input }, ({ input }) => ({\n conversation_id: input.conversation_id,\n recipient_id: input.reader_id,\n sender_type: input.reader_type,\n event_type: \"unread_count\" as const,\n unread_count: 0,\n }))\n\n ;(publishMessageEventStep(unreadEventInput) as any).config({ name: \"publish-unread-count\" })\n\n return new WorkflowResponse(result)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/anonymize-buyer-messages.ts",
"content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\nimport { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { anonymizeMessagesBatchStep } from \"../steps/anonymize-messages-batch\"\n\ntype AnonymizeBuyerInput = {\n buyer_id: string\n}\n\nconst BATCH_SIZE = 100\n\nconst findBuyerConversationsStep = createStep(\n \"find-buyer-conversations\",\n async (input: { buyer_id: string }, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n // Paginate to avoid unbounded queries\n const allIds: string[] = []\n let skip = 0\n\n while (true) {\n const conversations = await service.listConversations(\n { buyer_id: input.buyer_id },\n { take: BATCH_SIZE, skip, select: [\"id\"] }\n )\n\n if (!conversations || conversations.length === 0) break\n\n const ids = conversations.map((c: { id: string }) => c.id)\n allIds.push(...ids)\n skip += BATCH_SIZE\n\n if (conversations.length < BATCH_SIZE) break\n }\n\n // Update all conversations to reflect deleted buyer\n for (const id of allIds) {\n await service.updateConversations({\n id,\n buyer_id: `deleted_${input.buyer_id}`,\n })\n }\n\n return new StepResponse(\n { conversation_ids: allIds },\n { conversation_ids: allIds, original_buyer_id: input.buyer_id }\n )\n },\n async (compensationData, { container }) => {\n if (!compensationData) return\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n // Restore original buyer_id on rollback\n for (const id of compensationData.conversation_ids) {\n await service.updateConversations({\n id,\n buyer_id: compensationData.original_buyer_id,\n })\n }\n }\n)\n\nexport const anonymizeBuyerMessagesWorkflow = createWorkflow(\n { name: \"anonymize-buyer-messages\" },\n function (input: AnonymizeBuyerInput) {\n const findInput = transform(input, (data) => ({\n buyer_id: data.buyer_id,\n }))\n\n const result = findBuyerConversationsStep(findInput)\n\n const batchInput = transform(result, (data) => ({\n conversation_ids: data.conversation_ids,\n actor_type: \"customer\" as const,\n batch_size: 500,\n }))\n\n const anonymizeResult = anonymizeMessagesBatchStep(batchInput)\n\n return new WorkflowResponse(anonymizeResult)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/anonymize-vendor-messages.ts",
"content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\nimport { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\n\ntype AnonymizeVendorInput = {\n seller_id: string\n}\n\nconst BATCH_SIZE = 100\n\nconst anonymizeVendorConversationsStep = createStep(\n \"anonymize-vendor-conversations\",\n async (input: { seller_id: string }, { container }) => {\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n // Paginate to avoid unbounded queries\n const allIds: string[] = []\n let skip = 0\n\n while (true) {\n const conversations = await service.listConversations(\n { seller_id: input.seller_id },\n { take: BATCH_SIZE, skip, select: [\"id\"] }\n )\n\n if (!conversations || conversations.length === 0) break\n\n const ids = conversations.map((c: { id: string }) => c.id)\n allIds.push(...ids)\n skip += BATCH_SIZE\n\n if (conversations.length < BATCH_SIZE) break\n }\n\n // Mark conversations as having a deleted vendor\n // Vendor message bodies are preserved per spec (FR-006)\n for (const id of allIds) {\n await service.updateConversations({\n id,\n seller_id: `deleted_${input.seller_id}`,\n })\n }\n\n return new StepResponse(\n { conversation_ids: allIds, anonymized_count: allIds.length },\n { conversation_ids: allIds, original_seller_id: input.seller_id }\n )\n },\n async (compensationData, { container }) => {\n if (!compensationData) return\n const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)\n // Restore original seller_id on rollback\n for (const id of compensationData.conversation_ids) {\n await service.updateConversations({\n id,\n seller_id: compensationData.original_seller_id,\n })\n }\n }\n)\n\nexport const anonymizeVendorMessagesWorkflow = createWorkflow(\n { name: \"anonymize-vendor-messages\" },\n function (input: AnonymizeVendorInput) {\n const stepInput = transform(input, (data) => ({\n seller_id: data.seller_id,\n }))\n\n const result = anonymizeVendorConversationsStep(stepInput)\n\n return new WorkflowResponse(result)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/block-customer.ts",
"content": "import {\n createWorkflow,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\n\nimport { blockCustomerStep } from \"../steps/block-customer\"\nimport { BlockCustomerInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const blockCustomerWorkflow = createWorkflow(\n { name: \"block-customer\" },\n function (input: BlockCustomerInput) {\n const block = blockCustomerStep(input)\n return new WorkflowResponse(block)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging/workflows/unblock-customer.ts",
"content": "import {\n createWorkflow,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\n\nimport { unblockCustomerStep } from \"../steps/unblock-customer\"\nimport { UnblockCustomerInput } from \"../../../modules/messaging/types/mutations\"\n\nexport const unblockCustomerWorkflow = createWorkflow(\n { name: \"unblock-customer\" },\n function (input: UnblockCustomerInput) {\n const result = unblockCustomerStep(input)\n return new WorkflowResponse(result)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/steps/create-filter-rule.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../modules/messaging-filters/service\"\n\ntype CreateFilterRuleInput = {\n match_type: \"exact\" | \"contains\"\n pattern: string\n description?: string | null\n is_enabled?: boolean\n}\n\nexport const createFilterRuleStep = createStep(\n \"create-filter-rule\",\n async (input: CreateFilterRuleInput, { container }) => {\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n const rule = await service.createFilterRules({\n match_type: input.match_type,\n pattern: input.pattern,\n description: input.description ?? null,\n is_enabled: input.is_enabled ?? true,\n is_builtin: false,\n })\n\n return new StepResponse(rule, rule.id)\n },\n async (ruleId, { container }) => {\n if (!ruleId) return\n\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n await service.deleteFilterRules([ruleId])\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/steps/update-filter-rule.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../modules/messaging-filters/service\"\n\ntype UpdateFilterRuleInput = {\n id: string\n match_type?: \"exact\" | \"contains\"\n pattern?: string\n description?: string | null\n is_enabled?: boolean\n}\n\nexport const updateFilterRuleStep = createStep(\n \"update-filter-rule\",\n async (input: UpdateFilterRuleInput, { container }) => {\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n // Retrieve current state for compensation\n const existing = await service.listFilterRules({ id: input.id })\n if (!existing || existing.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n `Filter rule ${input.id} not found`\n )\n }\n\n const current = existing[0]!\n\n // Built-in rules: only allow is_enabled and description changes\n if (current.is_builtin) {\n if (input.match_type || input.pattern) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Built-in filter rules can only be enabled or disabled\"\n )\n }\n }\n\n const updateData: Record<string, any> = { id: input.id }\n if (input.is_enabled !== undefined) updateData.is_enabled = input.is_enabled\n if (input.description !== undefined) updateData.description = input.description\n if (input.pattern !== undefined && !current.is_builtin) updateData.pattern = input.pattern\n if (input.match_type !== undefined && !current.is_builtin) updateData.match_type = input.match_type\n\n const updated = await service.updateFilterRules(updateData)\n\n return new StepResponse(updated, {\n id: input.id,\n is_enabled: current.is_enabled,\n description: current.description,\n pattern: current.pattern,\n match_type: current.match_type,\n })\n },\n async (previousData: any, { container }) => {\n if (!previousData) return\n\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n await service.updateFilterRules(previousData)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/steps/delete-filter-rule.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../modules/messaging-filters/service\"\n\ntype DeleteFilterRuleInput = {\n id: string\n}\n\nexport const deleteFilterRuleStep = createStep(\n \"delete-filter-rule\",\n async (input: DeleteFilterRuleInput, { container }) => {\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n const existing = await service.listFilterRules({ id: input.id })\n if (!existing || existing.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n `Filter rule ${input.id} not found`\n )\n }\n\n const current = existing[0]!\n\n if (current.is_builtin) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Built-in filter rules cannot be deleted\"\n )\n }\n\n await service.deleteFilterRules([input.id])\n\n return new StepResponse(undefined, current)\n },\n async (previousData: any, { container }) => {\n if (!previousData) return\n\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n await service.createFilterRules(previousData)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/steps/invalidate-filter-cache.ts",
"content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../modules/messaging-redis/service\"\nimport { invalidateRuleset, recompileFilters } from \"../../../modules/messaging-filters/loaders/compile-filters\"\n\nexport const invalidateFilterCacheStep = createStep(\n \"invalidate-filter-cache\",\n async (_input: undefined, { container }) => {\n // Recompile locally\n await recompileFilters(container)\n\n // Notify other instances via Redis pub/sub\n try {\n const redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n await redisService.publish(\"filter_rules_changed\", { invalidated: true })\n } catch {\n // Best-effort cross-instance invalidation\n }\n\n return new StepResponse(undefined)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/workflows/create-filter-rule.ts",
"content": "import {\n createWorkflow,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\n\nimport { createFilterRuleStep } from \"../steps/create-filter-rule\"\nimport { invalidateFilterCacheStep } from \"../steps/invalidate-filter-cache\"\n\ntype CreateFilterRuleWorkflowInput = {\n match_type: \"exact\" | \"contains\"\n pattern: string\n description?: string | null\n is_enabled?: boolean\n}\n\nexport const createFilterRuleWorkflow = createWorkflow(\n { name: \"create-filter-rule\" },\n function (input: CreateFilterRuleWorkflowInput) {\n const rule = createFilterRuleStep(input)\n\n invalidateFilterCacheStep()\n\n return new WorkflowResponse(rule)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/workflows/update-filter-rule.ts",
"content": "import {\n createWorkflow,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\n\nimport { updateFilterRuleStep } from \"../steps/update-filter-rule\"\nimport { invalidateFilterCacheStep } from \"../steps/invalidate-filter-cache\"\n\ntype UpdateFilterRuleWorkflowInput = {\n id: string\n match_type?: \"exact\" | \"contains\"\n pattern?: string\n description?: string | null\n is_enabled?: boolean\n}\n\nexport const updateFilterRuleWorkflow = createWorkflow(\n { name: \"update-filter-rule\" },\n function (input: UpdateFilterRuleWorkflowInput) {\n const rule = updateFilterRuleStep(input)\n\n invalidateFilterCacheStep()\n\n return new WorkflowResponse(rule)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/workflows/messaging-filters/workflows/delete-filter-rule.ts",
"content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\n\nimport { deleteFilterRuleStep } from \"../steps/delete-filter-rule\"\nimport { invalidateFilterCacheStep } from \"../steps/invalidate-filter-cache\"\n\ntype DeleteFilterRuleWorkflowInput = {\n id: string\n}\n\nexport const deleteFilterRuleWorkflow = createWorkflow(\n { name: \"delete-filter-rule\" },\n function (input: DeleteFilterRuleWorkflowInput) {\n deleteFilterRuleStep(input)\n\n invalidateFilterCacheStep()\n\n const result = transform(input, (data) => ({\n id: data.id,\n deleted: true,\n }))\n\n return new WorkflowResponse(result)\n }\n)\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/validators.ts",
"content": "import { z } from \"zod\"\n\nexport type StoreListConversationsType = z.infer<typeof StoreListConversations>\nexport const StoreListConversations = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(50).optional().default(20),\n})\n\nexport type StoreCreateConversationType = z.infer<typeof StoreCreateConversation>\nexport const StoreCreateConversation = z.object({\n seller_id: z.string().min(1),\n body: z.string().min(1).max(2000).optional(),\n context_type: z.enum([\"product\", \"order\"]).optional().nullable(),\n context_id: z.string().optional().nullable(),\n}).refine(\n (data) =>\n (!data.context_type && !data.context_id) ||\n (data.context_type && data.context_id),\n { message: \"context_type and context_id must both be set or both be omitted\" }\n)\n\nexport type StoreGetMessagesType = z.infer<typeof StoreGetMessages>\nexport const StoreGetMessages = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(100).optional().default(30),\n})\n\nexport type StoreSendMessageType = z.infer<typeof StoreSendMessage>\nexport const StoreSendMessage = z.object({\n body: z.string().min(1).max(2000),\n context_type: z.enum([\"product\", \"order\"]).optional().nullable(),\n context_id: z.string().optional().nullable(),\n}).refine(\n (data) =>\n (!data.context_type && !data.context_id) ||\n (data.context_type && data.context_id),\n { message: \"context_type and context_id must both be set or both be omitted\" }\n)\n\nexport type StoreMarkReadType = z.infer<typeof StoreMarkRead>\nexport const StoreMarkRead = z.object({})\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/query-config.ts",
"content": "export const storeConversationFields = [\n \"id\",\n \"seller_id\",\n \"last_message_preview\",\n \"last_message_sender_type\",\n \"last_message_at\",\n \"unread_count_customer\",\n \"created_at\",\n]\n\nexport const storeMessageFields = [\n \"id\",\n \"sender_type\",\n \"body\",\n \"context_type\",\n \"context_id\",\n \"context_label\",\n \"read_at\",\n \"created_at\",\n]\n\nexport const storeMessagingQueryConfig = {\n listConversations: {\n defaults: storeConversationFields,\n isList: true,\n },\n retrieveConversation: {\n defaults: storeConversationFields,\n isList: false,\n },\n listMessages: {\n defaults: storeMessageFields,\n isList: true,\n },\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/helpers.ts",
"content": "import { MedusaContainer } from \"@medusajs/framework/types\"\n\n/**\n * Resolve a human-readable label for a message context attachment.\n * Returns null if the entity cannot be found or context is not provided.\n */\nexport async function resolveContextLabel(\n scope: MedusaContainer,\n context_type: string | null,\n context_id: string | null\n): Promise<string | null> {\n if (!context_type || !context_id) return null\n\n const query = scope.resolve(\"query\")\n\n if (context_type === \"product\") {\n try {\n const { data: products } = await query.graph({\n entity: \"product\",\n fields: [\"id\", \"title\"],\n filters: { id: context_id },\n })\n if (products?.length > 0) {\n return products[0].title\n }\n } catch {\n // Product may not exist\n }\n } else if (context_type === \"order\") {\n try {\n const { data: orders } = await query.graph({\n entity: \"order\",\n fields: [\"id\", \"display_id\"],\n filters: { id: context_id },\n })\n if (orders?.length > 0) {\n return `Order #${orders[0].display_id}`\n }\n } catch {\n // Order may not exist\n }\n }\n\n return null\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { ContainerRegistrationKeys, MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { createConversationWorkflow } from \"../../../workflows/messaging/workflows/create-conversation\"\nimport { sendMessageWorkflow } from \"../../../workflows/messaging/workflows/send-message\"\nimport { resolveContextLabel } from \"./helpers\"\nimport {\n StoreCreateConversationType,\n StoreListConversationsType,\n} from \"./validators\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<StoreListConversationsType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const customerId = req.auth_context.actor_id\n\n const queryParams = (req.validatedQuery ?? {}) as StoreListConversationsType\n const { data: conversations, next_cursor } =\n await service.listConversationsCursor(\n { buyer_id: customerId },\n {\n cursor: queryParams.cursor,\n limit: queryParams.limit,\n }\n )\n\n res.json({ conversations, next_cursor })\n}\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<StoreCreateConversationType>,\n res: MedusaResponse\n) => {\n const customerId = req.auth_context.actor_id\n const { seller_id, body, context_type, context_id } = req.validatedBody\n\n // Check if buyer is blocked from chat\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const blocked = await service.checkBuyersBlocked([customerId])\n if (blocked.has(customerId)) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Your chat access has been suspended\"\n )\n }\n\n // Check if seller exists and is active\n const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)\n\n const { data: sellers } = await query.graph({\n entity: \"seller\",\n fields: [\"id\", \"name\"],\n filters: { id: seller_id },\n })\n\n if (!sellers || sellers.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Seller not found\"\n )\n }\n\n // Find or create conversation\n let conversation: any\n const existing = await service.listConversations(\n { buyer_id: customerId, seller_id },\n { take: 1 }\n )\n\n if (existing && existing.length > 0) {\n conversation = existing[0]\n } else {\n const { result } = await createConversationWorkflow.run({\n container: req.scope,\n input: { buyer_id: customerId, seller_id },\n })\n conversation = result\n }\n\n let message\n if (body) {\n // Resolve context label for display\n const context_label = await resolveContextLabel(req.scope, context_type ?? null, context_id ?? null)\n\n const { result } = await sendMessageWorkflow.run({\n container: req.scope,\n input: {\n conversation_id: conversation.id,\n sender_id: customerId,\n sender_type: \"customer\",\n body,\n context_type: context_type ?? null,\n context_id: context_id ?? null,\n context_label,\n recipient_id: seller_id,\n is_new_conversation: existing.length === 0,\n },\n })\n message = result\n }\n\n const response: any = { conversation }\n if (message) {\n response.message = message\n }\n\n res.status(200).json(response)\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/middlewares.ts",
"content": "import {\n authenticate,\n validateAndTransformBody,\n validateAndTransformQuery,\n} from \"@medusajs/framework\"\nimport { MiddlewareRoute } from \"@medusajs/medusa\"\n\nimport {\n StoreCreateConversation,\n StoreGetMessages,\n StoreListConversations,\n StoreMarkRead,\n StoreSendMessage,\n} from \"./validators\"\nimport { storeMessagingQueryConfig } from \"./query-config\"\n\nexport const storeMessagingMiddlewares: MiddlewareRoute[] = [\n {\n method: [\"GET\"],\n matcher: \"/store/messages\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n validateAndTransformQuery(\n StoreListConversations,\n storeMessagingQueryConfig.listConversations\n ),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/store/messages\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n validateAndTransformBody(StoreCreateConversation),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/store/messages/:id\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n validateAndTransformQuery(\n StoreGetMessages,\n storeMessagingQueryConfig.listMessages\n ),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/store/messages/:id\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n validateAndTransformBody(StoreSendMessage),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/store/messages/:id/read\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n validateAndTransformBody(StoreMarkRead),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/store/messages/unread\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/store/messages/sse-token\",\n middlewares: [\n authenticate(\"customer\", [\"session\", \"bearer\"]),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/store/messages/events\",\n middlewares: [],\n },\n]\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/[id]/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../modules/messaging/service\"\nimport { sendMessageWorkflow } from \"../../../../workflows/messaging/workflows/send-message\"\nimport { resolveContextLabel } from \"../helpers\"\nimport { StoreGetMessagesType, StoreSendMessageType } from \"../validators\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<StoreGetMessagesType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const customerId = req.auth_context.actor_id\n const conversationId = req.params.id!\n\n // Verify ownership\n const conversations = await service.listConversations(\n { id: conversationId, buyer_id: customerId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n const conversation = conversations[0]!\n\n const queryParams = (req.validatedQuery ?? {}) as StoreGetMessagesType\n const { data: messages, next_cursor } = await service.listMessagesCursor(\n conversationId,\n {\n cursor: queryParams.cursor,\n limit: queryParams.limit,\n }\n )\n\n res.json({ conversation, messages, next_cursor })\n}\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<StoreSendMessageType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const customerId = req.auth_context.actor_id\n const conversationId = req.params.id!\n\n // Verify ownership\n const conversations = await service.listConversations(\n { id: conversationId, buyer_id: customerId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n const conversation = conversations[0]!\n\n // Check if buyer is blocked from chat\n const blocked = await service.checkBuyersBlocked([customerId])\n if (blocked.has(customerId)) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Your chat access has been suspended\"\n )\n }\n\n const { body, context_type, context_id } = req.validatedBody\n\n // Resolve context label for display\n const context_label = await resolveContextLabel(req.scope, context_type ?? null, context_id ?? null)\n\n const { result: message } = await sendMessageWorkflow.run({\n container: req.scope,\n input: {\n conversation_id: conversationId,\n sender_id: customerId,\n sender_type: \"customer\",\n body,\n context_type: context_type ?? null,\n context_id: context_id ?? null,\n context_label,\n recipient_id: conversation.seller_id,\n is_new_conversation: false,\n },\n })\n\n res.json({ message })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/[id]/read/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../../modules/messaging/service\"\nimport { markMessagesReadWorkflow } from \"../../../../../workflows/messaging/workflows/mark-messages-read\"\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const customerId = req.auth_context.actor_id\n const conversationId = req.params.id!\n\n // Verify ownership\n const conversations = await service.listConversations(\n { id: conversationId, buyer_id: customerId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n await markMessagesReadWorkflow.run({\n container: req.scope,\n input: {\n conversation_id: conversationId,\n reader_id: customerId,\n reader_type: \"customer\",\n sender_id: conversations[0]!.seller_id,\n },\n })\n\n res.json({ success: true, unread_count_customer: 0 })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/unread/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_MODULE } from \"../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../modules/messaging/service\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const customerId = req.auth_context.actor_id\n\n const unread_count = await service.getUnreadCountTotal({\n buyer_id: customerId,\n })\n\n res.json({ unread_count })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/sse-token/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { randomUUID } from \"crypto\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../../modules/messaging-redis/service\"\n\nconst SSE_TOKEN_TTL_SECONDS = 30\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const customerId = req.auth_context.actor_id\n const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n\n if (!redisService.isAvailable) {\n res.status(503).json({ message: \"Token service unavailable\" })\n return\n }\n\n const token = randomUUID()\n\n try {\n await redisService.setToken(token, customerId, SSE_TOKEN_TTL_SECONDS)\n } catch {\n res.status(503).json({ message: \"Token service unavailable\" })\n return\n }\n\n res.json({ token, expires_in: SSE_TOKEN_TTL_SECONDS })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/store/messages/events/route.ts",
"content": "import { MedusaRequest, MedusaResponse } from \"@medusajs/framework\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../../modules/messaging-redis/service\"\n\nexport const GET = async (req: MedusaRequest, res: MedusaResponse) => {\n const token = req.query.token as string | undefined\n\n if (!token) {\n res.status(401).json({ message: \"Missing token\" })\n return\n }\n\n const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n\n if (!redisService.isAvailable) {\n res.status(503).json({ message: \"Token service unavailable\" })\n return\n }\n\n let customerId: string | null = null\n\n try {\n customerId = await redisService.consumeToken(token)\n } catch {\n res.status(503).json({ message: \"Token service unavailable\" })\n return\n }\n\n if (!customerId) {\n res.status(401).json({ message: \"Invalid or expired token\" })\n return\n }\n\n // SSE headers\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"X-Accel-Buffering\": \"no\",\n })\n res.flushHeaders()\n\n // Heartbeat\n const heartbeat = setInterval(() => {\n res.write(\":heartbeat\\n\\n\")\n }, 30000)\n\n let subscriber: ReturnType<MessagingRedisModuleService[\"createSubscriber\"]> = null\n\n try {\n subscriber = redisService.createSubscriber()\n\n if (subscriber) {\n await subscriber.subscribe(\"messaging\")\n\n subscriber.on(\"message\", (_channel: string, message: string) => {\n try {\n const event = JSON.parse(message)\n\n // Only deliver events for this buyer\n if (event.recipient_id !== customerId && event.sender_id !== customerId) {\n return\n }\n\n const eventId = event.message_id || `evt_${Date.now()}`\n const eventType = event.event_type || \"message\"\n\n res.write(`id: ${eventId}\\n`)\n res.write(`event: ${eventType}\\n`)\n res.write(`data: ${JSON.stringify(event)}\\n\\n`)\n } catch {\n // Skip malformed events\n }\n })\n }\n\n res.write(`event: connected\\ndata: {\"status\":\"connected\"}\\n\\n`)\n\n // Handle Last-Event-ID (sanitize to prevent SSE frame injection)\n const lastEventId = req.query.last_event_id as string | undefined\n if (lastEventId) {\n const sanitized = lastEventId.replace(/[\\n\\r]/g, \"\")\n res.write(`event: reconnected\\ndata: ${JSON.stringify({ last_event_id: sanitized })}\\n\\n`)\n }\n } catch {\n // Redis unavailable\n }\n\n req.on(\"close\", async () => {\n clearInterval(heartbeat)\n if (subscriber) {\n try {\n subscriber.unsubscribe(\"messaging\")\n subscriber.quit()\n } catch {\n // Best effort cleanup\n }\n }\n })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/validators.ts",
"content": "import { z } from \"zod\"\n\nexport type VendorListConversationsType = z.infer<typeof VendorListConversations>\nexport const VendorListConversations = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(50).optional().default(20),\n})\n\nexport type VendorGetMessagesType = z.infer<typeof VendorGetMessages>\nexport const VendorGetMessages = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(100).optional().default(30),\n})\n\nexport type VendorSendReplyType = z.infer<typeof VendorSendReply>\nexport const VendorSendReply = z.object({\n body: z.string().min(1).max(2000),\n})\n\nexport type VendorMarkReadType = z.infer<typeof VendorMarkRead>\nexport const VendorMarkRead = z.object({})\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/query-config.ts",
"content": "export const vendorMessagingConversationFields = [\n \"id\",\n \"seller_id\",\n \"buyer_id\",\n \"last_message_preview\",\n \"last_message_sender_type\",\n \"last_message_at\",\n \"unread_count_seller\",\n \"created_at\",\n \"updated_at\",\n]\n\nexport const vendorMessagingMessageFields = [\n \"id\",\n \"sender_type\",\n \"body\",\n \"context_type\",\n \"context_id\",\n \"context_label\",\n \"read_at\",\n \"created_at\",\n]\n\nexport const vendorMessagingQueryConfig = {\n listConversations: {\n defaults: vendorMessagingConversationFields,\n isList: true,\n },\n listMessages: {\n defaults: vendorMessagingMessageFields,\n isList: true,\n },\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { ConversationDTO } from \"../../../modules/messaging/types/common\"\nimport { VendorListConversationsType } from \"./validators\"\n\ntype EnrichedConversation = ConversationDTO & {\n buyer_first_name?: string | null\n is_buyer_blocked?: boolean\n}\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<VendorListConversationsType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const sellerId = req.auth_context.actor_id\n\n const { data: conversations, next_cursor } =\n await service.listConversationsCursor(\n { seller_id: sellerId },\n {\n cursor: (req.validatedQuery as VendorListConversationsType)?.cursor,\n limit: (req.validatedQuery as VendorListConversationsType)?.limit,\n }\n )\n\n const enriched = conversations as EnrichedConversation[]\n\n // Resolve buyer first names via customer link\n if (enriched.length > 0) {\n try {\n const query = req.scope.resolve(\"query\")\n const buyerIds = [...new Set(enriched.map((c) => c.buyer_id))]\n\n const { data: customers } = await query.graph({\n entity: \"customer\",\n fields: [\"id\", \"first_name\"],\n filters: { id: buyerIds },\n })\n\n const customerMap = new Map(\n (customers ?? []).map((c: { id: string; first_name: string }) => [c.id, c.first_name])\n )\n\n for (const conv of enriched) {\n conv.buyer_first_name = customerMap.get(conv.buyer_id) ?? null\n }\n } catch {\n // Continue without buyer names\n }\n }\n\n // Annotate block status\n if (enriched.length > 0) {\n const buyerIds = [...new Set(enriched.map((c) => c.buyer_id))]\n const blockedSet = await service.checkBuyersBlocked(buyerIds)\n for (const conv of enriched) {\n conv.is_buyer_blocked = blockedSet.has(conv.buyer_id)\n }\n }\n\n res.json({ conversations: enriched, next_cursor })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/middlewares.ts",
"content": "import {\n validateAndTransformBody,\n validateAndTransformQuery,\n} from \"@medusajs/framework\"\nimport { MiddlewareRoute } from \"@medusajs/medusa\"\n\nimport {\n VendorGetMessages,\n VendorListConversations,\n VendorMarkRead,\n VendorSendReply,\n} from \"./validators\"\nimport { vendorMessagingQueryConfig } from \"./query-config\"\n\nexport const vendorMessagingMiddlewares: MiddlewareRoute[] = [\n {\n method: [\"GET\"],\n matcher: \"/vendor/messages\",\n middlewares: [\n validateAndTransformQuery(\n VendorListConversations,\n vendorMessagingQueryConfig.listConversations\n ),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/vendor/messages/:id\",\n middlewares: [\n validateAndTransformQuery(\n VendorGetMessages,\n vendorMessagingQueryConfig.listMessages\n ),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/vendor/messages/:id\",\n middlewares: [\n validateAndTransformBody(VendorSendReply),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/vendor/messages/:id/read\",\n middlewares: [\n validateAndTransformBody(VendorMarkRead),\n ],\n },\n]\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/[id]/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../modules/messaging/service\"\nimport { sendMessageWorkflow } from \"../../../../workflows/messaging/workflows/send-message\"\nimport { VendorGetMessagesType, VendorSendReplyType } from \"../validators\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<VendorGetMessagesType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const sellerId = req.auth_context.actor_id\n const conversationId = req.params.id!\n\n // Verify ownership\n const conversations = await service.listConversations(\n { id: conversationId, seller_id: sellerId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n const conversation = conversations[0]!\n\n const queryParams = (req.validatedQuery ?? {}) as VendorGetMessagesType\n const { data: messages, next_cursor } = await service.listMessagesCursor(\n conversationId,\n {\n cursor: queryParams.cursor,\n limit: queryParams.limit,\n }\n )\n\n // Resolve buyer first name + recent orders for context sidebar\n let buyer_first_name: string | null = null\n let buyer_orders: any[] = []\n\n try {\n const query = req.scope.resolve(\"query\")\n\n const { data: customers } = await query.graph({\n entity: \"customer\",\n fields: [\"id\", \"first_name\"],\n filters: { id: conversation.buyer_id },\n })\n\n if (customers?.length > 0) {\n buyer_first_name = customers[0].first_name\n }\n\n // Get recent orders for this buyer, including linked seller to filter\n const { data: orders } = await query.graph({\n entity: \"order\",\n fields: [\"id\", \"display_id\", \"status\", \"total\", \"currency_code\", \"created_at\", \"seller.id\"],\n filters: {\n customer_id: conversation.buyer_id,\n },\n })\n\n // Only include orders that belong to this seller\n buyer_orders = (orders ?? [])\n .filter((o: any) => o.seller?.id === sellerId)\n .map(({ seller, ...rest }: any) => rest)\n } catch {\n // Continue without enrichment\n }\n\n // Check block status\n const blockedSet = await service.checkBuyersBlocked([conversation.buyer_id])\n const is_buyer_blocked = blockedSet.has(conversation.buyer_id)\n\n res.json({\n conversation: { ...conversation, buyer_first_name, is_buyer_blocked },\n messages,\n next_cursor,\n buyer_orders,\n })\n}\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<VendorSendReplyType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const sellerId = req.auth_context.actor_id\n const conversationId = req.params.id!\n\n // Verify ownership\n const conversations = await service.listConversations(\n { id: conversationId, seller_id: sellerId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n const conversation = conversations[0]!\n\n // Check if buyer is blocked from chat\n const blockedSet = await service.checkBuyersBlocked([conversation.buyer_id])\n if (blockedSet.has(conversation.buyer_id)) {\n throw new MedusaError(\n MedusaError.Types.NOT_ALLOWED,\n \"Cannot send messages to a blocked customer\"\n )\n }\n\n const { body } = req.validatedBody\n\n const { result: message } = await sendMessageWorkflow.run({\n container: req.scope,\n input: {\n conversation_id: conversationId,\n sender_id: sellerId,\n sender_type: \"seller\",\n body,\n context_type: null,\n context_id: null,\n context_label: null,\n recipient_id: conversation.buyer_id,\n is_new_conversation: false,\n },\n })\n\n res.json({ message })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/[id]/read/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../../modules/messaging/service\"\nimport { markMessagesReadWorkflow } from \"../../../../../workflows/messaging/workflows/mark-messages-read\"\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const sellerId = req.auth_context.actor_id\n const conversationId = req.params.id!\n\n // Verify ownership\n const conversations = await service.listConversations(\n { id: conversationId, seller_id: sellerId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n await markMessagesReadWorkflow.run({\n container: req.scope,\n input: {\n conversation_id: conversationId,\n reader_id: sellerId,\n reader_type: \"seller\",\n sender_id: conversations[0]!.buyer_id,\n },\n })\n\n res.json({ success: true, unread_count_seller: 0 })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/unread/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_MODULE } from \"../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../modules/messaging/service\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const sellerId = req.auth_context.actor_id\n\n const unread_count = await service.getUnreadCountTotal({\n seller_id: sellerId,\n })\n\n res.json({ unread_count })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/vendor/messages/events/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../../modules/messaging-redis/service\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const sellerId = req.auth_context.actor_id\n const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n\n // SSE headers\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"X-Accel-Buffering\": \"no\",\n })\n res.flushHeaders()\n\n // Heartbeat to keep connection alive\n const heartbeat = setInterval(() => {\n res.write(\":heartbeat\\n\\n\")\n }, 30000)\n\n let subscriber: ReturnType<MessagingRedisModuleService[\"createSubscriber\"]> = null\n\n try {\n subscriber = redisService.createSubscriber()\n\n if (subscriber) {\n await subscriber.subscribe(\"messaging\")\n\n subscriber.on(\"message\", (_channel: string, message: string) => {\n try {\n const event = JSON.parse(message)\n\n // Only deliver events for this vendor\n if (event.recipient_id !== sellerId && event.sender_id !== sellerId) {\n return\n }\n\n const eventId = event.message_id || `evt_${Date.now()}`\n const eventType = event.event_type || \"message\"\n\n res.write(`id: ${eventId}\\n`)\n res.write(`event: ${eventType}\\n`)\n res.write(`data: ${JSON.stringify(event)}\\n\\n`)\n } catch {\n // Skip malformed events\n }\n })\n }\n\n // Send initial connection event\n res.write(`event: connected\\ndata: {\"status\":\"connected\"}\\n\\n`)\n\n // Handle Last-Event-ID for reconnection (sanitize to prevent SSE frame injection)\n const lastEventId = req.headers[\"last-event-id\"] as string | undefined\n if (lastEventId) {\n const sanitized = lastEventId.replace(/[\\n\\r]/g, \"\")\n res.write(`event: reconnected\\ndata: ${JSON.stringify({ last_event_id: sanitized })}\\n\\n`)\n }\n } catch {\n // Redis unavailable, connection will close\n }\n\n // Cleanup on disconnect\n req.on(\"close\", async () => {\n clearInterval(heartbeat)\n if (subscriber) {\n try {\n subscriber.unsubscribe(\"messaging\")\n subscriber.quit()\n } catch {\n // Best effort cleanup\n }\n }\n })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/validators.ts",
"content": "import { z } from \"zod\"\n\nexport type AdminSearchConversationsType = z.infer<typeof AdminSearchConversations>\nexport const AdminSearchConversations = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(50).optional().default(20),\n seller_name: z.string().optional(),\n buyer_name: z.string().optional(),\n date_from: z.string().optional(),\n date_to: z.string().optional(),\n context_type: z.enum([\"product\", \"order\"]).optional(),\n context_id: z.string().optional(),\n})\n\nexport type AdminGetMessagesType = z.infer<typeof AdminGetMessages>\nexport const AdminGetMessages = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(100).optional().default(30),\n})\n\nexport type AdminBlockCustomerType = z.infer<typeof AdminBlockCustomer>\nexport const AdminBlockCustomer = z.object({\n customer_id: z.string().min(1),\n reason: z.string().max(500).optional(),\n})\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/query-config.ts",
"content": "export const adminMessagingConversationFields = [\n \"id\",\n \"buyer_id\",\n \"seller_id\",\n \"buyer_name\",\n \"buyer_email\",\n \"seller_name\",\n \"last_message_preview\",\n \"last_message_sender_type\",\n \"last_message_at\",\n \"unread_count_customer\",\n \"unread_count_seller\",\n \"created_at\",\n \"updated_at\",\n]\n\nexport const adminMessagingMessageFields = [\n \"id\",\n \"sender_id\",\n \"sender_type\",\n \"body\",\n \"context_type\",\n \"context_id\",\n \"context_label\",\n \"read_at\",\n \"created_at\",\n]\n\nexport const adminMessagingQueryConfig = {\n listConversations: {\n defaults: adminMessagingConversationFields,\n isList: true,\n },\n listMessages: {\n defaults: adminMessagingMessageFields,\n isList: true,\n },\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_MODULE } from \"../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../modules/messaging/service\"\nimport { ConversationDTO } from \"../../../modules/messaging/types/common\"\nimport { AdminSearchConversationsType } from \"./validators\"\n\ntype AdminEnrichedConversation = ConversationDTO & {\n seller_name?: string | null\n buyer_name?: string | null\n buyer_email?: string | null\n is_buyer_blocked?: boolean\n}\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<AdminSearchConversationsType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n\n const {\n cursor,\n limit,\n seller_name,\n buyer_name,\n date_from,\n date_to,\n context_type,\n context_id,\n } = (req.validatedQuery ?? {}) as AdminSearchConversationsType\n\n const { data: conversations, next_cursor } =\n await service.searchConversationsAdmin(\n {\n seller_name,\n buyer_name,\n date_from,\n date_to,\n context_type,\n context_id,\n },\n { cursor, limit }\n )\n\n const enriched = conversations as AdminEnrichedConversation[]\n\n // Annotate block status\n if (enriched.length > 0) {\n const buyerIds = [...new Set(enriched.map((c) => c.buyer_id))]\n const blockedSet = await service.checkBuyersBlocked(buyerIds)\n for (const conv of enriched) {\n conv.is_buyer_blocked = blockedSet.has(conv.buyer_id)\n }\n }\n\n res.json({ conversations: enriched, next_cursor })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/middlewares.ts",
"content": "import {\n validateAndTransformBody,\n validateAndTransformQuery,\n} from \"@medusajs/framework\"\nimport { MiddlewareRoute } from \"@medusajs/medusa\"\n\nimport {\n AdminBlockCustomer,\n AdminGetMessages,\n AdminSearchConversations,\n} from \"./validators\"\nimport {\n AdminCreateFilter,\n AdminUpdateFilter,\n AdminListFilters,\n AdminListBlocked,\n} from \"./filters/validators\"\nimport { adminMessagingQueryConfig } from \"./query-config\"\n\nexport const adminMessagingMiddlewares: MiddlewareRoute[] = [\n {\n method: [\"GET\"],\n matcher: \"/admin/messages\",\n middlewares: [\n validateAndTransformQuery(\n AdminSearchConversations,\n adminMessagingQueryConfig.listConversations\n ),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/admin/messages/filters\",\n middlewares: [\n validateAndTransformQuery(AdminListFilters, { defaults: [\"*\"], isList: true }),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/admin/messages/filters\",\n middlewares: [\n validateAndTransformBody(AdminCreateFilter),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/admin/messages/filters/:id\",\n middlewares: [\n validateAndTransformBody(AdminUpdateFilter),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/admin/messages/blocked\",\n middlewares: [\n validateAndTransformQuery(AdminListBlocked, { defaults: [\"*\"], isList: true }),\n ],\n },\n {\n method: [\"POST\"],\n matcher: \"/admin/messages/chat-blocks\",\n middlewares: [\n validateAndTransformBody(AdminBlockCustomer),\n ],\n },\n {\n method: [\"GET\"],\n matcher: \"/admin/messages/:id\",\n middlewares: [\n validateAndTransformQuery(\n AdminGetMessages,\n adminMessagingQueryConfig.listMessages\n ),\n ],\n },\n]\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/[id]/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_MODULE } from \"../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../modules/messaging/service\"\nimport { AdminGetMessagesType } from \"../validators\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<AdminGetMessagesType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const conversationId = req.params.id!\n\n // Admin can access any conversation — no ownership check\n const conversations = await service.listConversations(\n { id: conversationId },\n { take: 1 }\n )\n\n if (!conversations || conversations.length === 0) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Conversation not found\"\n )\n }\n\n const conversation = conversations[0]!\n\n const queryParams = (req.validatedQuery ?? {}) as AdminGetMessagesType\n const { data: messages, next_cursor } = await service.listMessagesCursor(\n conversationId,\n {\n cursor: queryParams.cursor,\n limit: queryParams.limit,\n }\n )\n\n // Resolve buyer + seller names for admin view\n let buyer_name: string | null = null\n let buyer_email: string | null = null\n let seller_name: string | null = null\n\n try {\n const query = req.scope.resolve(\"query\")\n\n const { data: customers } = await query.graph({\n entity: \"customer\",\n fields: [\"id\", \"first_name\", \"last_name\", \"email\"],\n filters: { id: conversation.buyer_id },\n })\n\n if (customers?.length > 0) {\n buyer_name = [customers[0].first_name, customers[0].last_name]\n .filter(Boolean)\n .join(\" \")\n buyer_email = customers[0].email\n }\n\n const { data: sellers } = await query.graph({\n entity: \"seller\",\n fields: [\"id\", \"name\"],\n filters: { id: conversation.seller_id },\n })\n\n if (sellers?.length > 0) {\n seller_name = sellers[0].name\n }\n } catch {\n // Continue without enrichment\n }\n\n // Check block status with reason\n const blockDetail = await service.getBlockDetail(conversation.buyer_id)\n\n res.json({\n conversation: {\n ...conversation,\n buyer_name,\n buyer_email,\n seller_name,\n is_buyer_blocked: blockDetail.blocked,\n block_reason: blockDetail.reason,\n },\n messages,\n next_cursor,\n })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/events/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../../../../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../../../../modules/messaging-redis/service\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n\n // SSE headers\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"X-Accel-Buffering\": \"no\",\n })\n res.flushHeaders()\n\n const heartbeat = setInterval(() => {\n res.write(\":heartbeat\\n\\n\")\n }, 30000)\n\n let subscriber: ReturnType<MessagingRedisModuleService[\"createSubscriber\"]> = null\n\n try {\n subscriber = redisService.createSubscriber()\n\n if (subscriber) {\n await subscriber.subscribe(\"messaging\")\n\n // Admin receives ALL messaging events (no filtering)\n subscriber.on(\"message\", (_channel: string, message: string) => {\n try {\n const event = JSON.parse(message)\n const eventId = event.message_id || `evt_${Date.now()}`\n const eventType = event.event_type || \"message\"\n\n res.write(`id: ${eventId}\\n`)\n res.write(`event: ${eventType}\\n`)\n res.write(`data: ${JSON.stringify(event)}\\n\\n`)\n } catch {\n // Skip malformed events\n }\n })\n }\n\n res.write(`event: connected\\ndata: {\"status\":\"connected\"}\\n\\n`)\n\n // Sanitize Last-Event-ID to prevent SSE frame injection\n const lastEventId = req.headers[\"last-event-id\"] as string | undefined\n if (lastEventId) {\n const sanitized = lastEventId.replace(/[\\n\\r]/g, \"\")\n res.write(`event: reconnected\\ndata: ${JSON.stringify({ last_event_id: sanitized })}\\n\\n`)\n }\n } catch {\n // Redis unavailable\n }\n\n req.on(\"close\", async () => {\n clearInterval(heartbeat)\n if (subscriber) {\n try {\n subscriber.unsubscribe(\"messaging\")\n subscriber.quit()\n } catch {\n // Best effort cleanup\n }\n }\n })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/filters/validators.ts",
"content": "import { z } from \"zod\"\n\nexport type AdminCreateFilterType = z.infer<typeof AdminCreateFilter>\nexport const AdminCreateFilter = z.object({\n match_type: z.enum([\"exact\", \"contains\"]),\n pattern: z.string().min(1).max(500),\n description: z.string().max(500).optional(),\n is_enabled: z.boolean().optional().default(true),\n})\n\nexport type AdminUpdateFilterType = z.infer<typeof AdminUpdateFilter>\nexport const AdminUpdateFilter = z.object({\n match_type: z.enum([\"exact\", \"contains\"]).optional(),\n pattern: z.string().min(1).max(500).optional(),\n description: z.string().max(500).optional(),\n is_enabled: z.boolean().optional(),\n})\n\nexport type AdminListFiltersType = z.infer<typeof AdminListFilters>\nexport const AdminListFilters = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(50).optional().default(20),\n})\n\nexport type AdminListBlockedType = z.infer<typeof AdminListBlocked>\nexport const AdminListBlocked = z.object({\n cursor: z.string().optional(),\n limit: z.coerce.number().int().min(1).max(50).optional().default(20),\n sender_type: z.enum([\"customer\", \"seller\"]).optional(),\n date_from: z.string().optional(),\n date_to: z.string().optional(),\n})\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/filters/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../../modules/messaging-filters/service\"\nimport { createFilterRuleWorkflow } from \"../../../../workflows/messaging-filters/workflows/create-filter-rule\"\nimport { AdminCreateFilterType, AdminListFiltersType } from \"./validators\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<AdminListFiltersType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n const limit = req.validatedQuery?.limit ?? 20\n\n const [rules, count] = await service.listAndCountFilterRules(\n {},\n {\n take: limit,\n order: { created_at: \"ASC\" },\n }\n )\n\n res.json({ filter_rules: rules, count })\n}\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<AdminCreateFilterType>,\n res: MedusaResponse\n) => {\n const { match_type, pattern, description, is_enabled } = req.validatedBody\n\n // Custom rules cannot use regex match type\n if (match_type === \"regex\" as any) {\n throw new MedusaError(\n MedusaError.Types.INVALID_DATA,\n \"Regex match type is reserved for built-in rules only\"\n )\n }\n\n const { result: rule } = await createFilterRuleWorkflow.run({\n container: req.scope,\n input: {\n match_type,\n pattern,\n description: description ?? null,\n is_enabled: is_enabled ?? true,\n is_builtin: false,\n },\n })\n\n res.status(201).json({ filter_rule: rule })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/filters/[id]/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../../../modules/messaging-filters/service\"\nimport { updateFilterRuleWorkflow } from \"../../../../../workflows/messaging-filters/workflows/update-filter-rule\"\nimport { deleteFilterRuleWorkflow } from \"../../../../../workflows/messaging-filters/workflows/delete-filter-rule\"\nimport { AdminUpdateFilterType } from \"../validators\"\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<AdminUpdateFilterType>,\n res: MedusaResponse\n) => {\n const ruleId = req.params.id\n\n const { result: rule } = await updateFilterRuleWorkflow.run({\n container: req.scope,\n input: {\n id: ruleId,\n ...req.validatedBody,\n },\n })\n\n res.json({ filter_rule: rule })\n}\n\nexport const DELETE = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const ruleId = req.params.id\n\n await deleteFilterRuleWorkflow.run({\n container: req.scope,\n input: { id: ruleId },\n })\n\n res.json({ id: ruleId, deleted: true })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/blocked/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../../../../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../../../../modules/messaging-filters/service\"\nimport { AdminListBlockedType } from \"../filters/validators\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest<AdminListBlockedType>,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n const limit = req.validatedQuery?.limit ?? 20\n const filters: Record<string, any> = {}\n\n if (req.validatedQuery?.sender_type) {\n filters.sender_type = req.validatedQuery.sender_type\n }\n\n const [logs, count] = await service.listAndCountBlockedMessageLogs(\n filters,\n {\n take: limit,\n order: { created_at: \"DESC\" },\n }\n )\n\n res.json({ blocked_messages: logs, count })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/chat-blocks/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { blockCustomerWorkflow } from \"../../../../workflows/messaging/workflows/block-customer\"\nimport { AdminBlockCustomerType } from \"../validators\"\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<AdminBlockCustomerType>,\n res: MedusaResponse\n) => {\n const adminUserId = req.auth_context.actor_id\n\n const { result: block } = await blockCustomerWorkflow.run({\n container: req.scope,\n input: {\n customer_id: req.validatedBody.customer_id,\n blocked_by: adminUserId,\n reason: req.validatedBody.reason ?? null,\n },\n })\n\n res.status(201).json({ block })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/api/admin/messages/chat-blocks/[customer_id]/route.ts",
"content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework\"\n\nimport { MESSAGING_MODULE } from \"../../../../../modules/messaging\"\nimport type MessagingModuleService from \"../../../../../modules/messaging/service\"\nimport { unblockCustomerWorkflow } from \"../../../../../workflows/messaging/workflows/unblock-customer\"\n\nexport const GET = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)\n const blocked = await service.checkBuyersBlocked([req.params.customer_id])\n\n res.json({ is_blocked: blocked.has(req.params.customer_id) })\n}\n\nexport const DELETE = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse\n) => {\n await unblockCustomerWorkflow.run({\n container: req.scope,\n input: { customer_id: req.params.customer_id },\n })\n\n res.status(200).json({ success: true })\n}\n",
"type": "registry:api"
},
{
"path": "messaging/subscribers/message-notification.ts",
"content": "import { SubscriberArgs, SubscriberConfig } from \"@medusajs/framework\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\n\nimport { MESSAGING_REDIS_MODULE } from \"../modules/messaging-redis\"\nimport type MessagingRedisModuleService from \"../modules/messaging-redis/service\"\n\ntype MessageCreatedData = {\n id: string\n conversation_id: string\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n recipient_id: string\n}\n\nconst THROTTLE_TTL_SECONDS = 900 // 15 minutes\n\nexport default async function messageNotificationHandler({\n event,\n container,\n}: SubscriberArgs<MessageCreatedData>) {\n const logger = container.resolve(ContainerRegistrationKeys.LOGGER)\n const { conversation_id, sender_id, sender_type, recipient_id } = event.data\n\n try {\n // Check throttle — one notification per conversation per recipient per 15 min\n const redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)\n const throttleKey = `notify:${conversation_id}:${recipient_id}`\n\n const allowed = await redisService.trySetThrottle(throttleKey, THROTTLE_TTL_SECONDS)\n\n if (!allowed) {\n // Already notified recently, skip\n return\n }\n\n // Resolve sender name for the email\n const query = container.resolve(ContainerRegistrationKeys.QUERY)\n let senderName = \"Someone\"\n\n if (sender_type === \"customer\") {\n try {\n const { data: customers } = await query.graph({\n entity: \"customer\",\n fields: [\"id\", \"first_name\"],\n filters: { id: sender_id },\n })\n if (customers?.length > 0) {\n senderName = customers[0].first_name || \"A customer\"\n }\n } catch {\n // Use default name\n }\n } else {\n try {\n const { data: sellers } = await query.graph({\n entity: \"seller\",\n fields: [\"id\", \"name\"],\n filters: { id: sender_id },\n })\n if (sellers?.length > 0) {\n senderName = sellers[0].name || \"A vendor\"\n }\n } catch {\n // Use default name\n }\n }\n\n // Resolve recipient email\n let recipientEmail: string | null = null\n const recipientType = sender_type === \"customer\" ? \"seller\" : \"customer\"\n\n if (recipientType === \"customer\") {\n try {\n const { data: customers } = await query.graph({\n entity: \"customer\",\n fields: [\"id\", \"email\"],\n filters: { id: recipient_id },\n })\n if (customers?.length > 0) {\n recipientEmail = customers[0].email\n }\n } catch {\n // Cannot determine email\n }\n }\n // For sellers, email notification requires seller email which may be in auth_identity\n // This is operator-customizable — emit notification event for flexibility\n\n if (!recipientEmail) {\n logger.debug(\n `Messaging: skipping email notification for ${recipientType} ${recipient_id} — no email found`\n )\n return\n }\n\n // Send notification via Medusa notification module\n // Privacy: no message body included in email\n try {\n const notificationService: { createNotifications: (data: Record<string, unknown>) => Promise<void> } =\n container.resolve(\"notification\")\n await notificationService.createNotifications({\n to: recipientEmail,\n channel: \"email\",\n template: \"messaging-new-message\",\n data: {\n sender_name: senderName,\n conversation_id,\n },\n })\n\n logger.debug(\n `Messaging: email notification sent to ${recipientEmail} for conversation ${conversation_id}`\n )\n } catch (err) {\n logger.warn(\n `Messaging: failed to send email notification: ${(err as Error).message}`\n )\n }\n } catch (err) {\n logger.error(\n `Messaging: notification handler error: ${(err as Error).message}`\n )\n }\n}\n\nexport const config: SubscriberConfig = {\n event: \"messaging.message.created\",\n}\n",
"type": "registry:api"
},
{
"path": "messaging/subscribers/buyer-deletion.ts",
"content": "import { SubscriberArgs, SubscriberConfig } from \"@medusajs/framework\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\n\nimport { anonymizeBuyerMessagesWorkflow } from \"../workflows/messaging/workflows/anonymize-buyer-messages\"\n\nexport default async function buyerDeletionHandler({\n event,\n container,\n}: SubscriberArgs<{ id: string }>) {\n const logger = container.resolve(ContainerRegistrationKeys.LOGGER)\n\n try {\n await anonymizeBuyerMessagesWorkflow.run({\n container,\n input: { buyer_id: event.data.id },\n })\n\n logger.info(\n `Messaging: buyer ${event.data.id} messages anonymized (GDPR erasure)`\n )\n } catch (err) {\n logger.error(\n `Messaging: buyer deletion handler error: ${(err as Error).message}`\n )\n }\n}\n\nexport const config: SubscriberConfig = {\n event: \"customer.deleted\",\n}\n",
"type": "registry:api"
},
{
"path": "messaging/subscribers/vendor-removal.ts",
"content": "import { SubscriberArgs, SubscriberConfig } from \"@medusajs/framework\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\n\nimport { anonymizeVendorMessagesWorkflow } from \"../workflows/messaging/workflows/anonymize-vendor-messages\"\n\nexport default async function vendorRemovalHandler({\n event,\n container,\n}: SubscriberArgs<{ id: string }>) {\n const logger = container.resolve(ContainerRegistrationKeys.LOGGER)\n\n try {\n await anonymizeVendorMessagesWorkflow.run({\n container,\n input: { seller_id: event.data.id },\n })\n\n logger.info(\n `Messaging: vendor ${event.data.id} conversations anonymized (offboarding)`\n )\n } catch (err) {\n logger.error(\n `Messaging: vendor removal handler error: ${(err as Error).message}`\n )\n }\n}\n\nexport const config: SubscriberConfig = {\n event: \"seller.deleted\",\n}\n",
"type": "registry:api"
},
{
"path": "messaging/jobs/reconcile-unread-counts.ts",
"content": "import { MedusaContainer } from \"@medusajs/framework/types\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\n\nexport default async function reconcileUnreadCounts(\n container: MedusaContainer\n) {\n const logger = container.resolve(\"logger\")\n const pgConnection = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)\n\n try {\n // Single query: compute actual unread counts for ALL conversations at once\n const BATCH_SIZE = 500\n let totalCorrected = 0\n let offset = 0\n\n // Process in batches to avoid unbounded result sets\n while (true) {\n const { rows: actualCounts } = await pgConnection.raw(`\n SELECT\n c.id,\n c.unread_count_customer AS stored_customer,\n c.unread_count_seller AS stored_seller,\n COALESCE(SUM(CASE WHEN m.sender_type = 'seller' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)::int AS actual_customer,\n COALESCE(SUM(CASE WHEN m.sender_type = 'customer' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)::int AS actual_seller\n FROM conversation c\n LEFT JOIN message m ON m.conversation_id = c.id AND m.deleted_at IS NULL\n WHERE c.deleted_at IS NULL\n GROUP BY c.id, c.unread_count_customer, c.unread_count_seller\n HAVING\n c.unread_count_customer != COALESCE(SUM(CASE WHEN m.sender_type = 'seller' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)\n OR c.unread_count_seller != COALESCE(SUM(CASE WHEN m.sender_type = 'customer' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)\n ORDER BY c.id\n LIMIT ?\n OFFSET ?\n `, [BATCH_SIZE, offset])\n\n if (!actualCounts || actualCounts.length === 0) break\n\n for (const row of actualCounts) {\n await pgConnection.raw(`\n UPDATE conversation\n SET unread_count_customer = ?, unread_count_seller = ?, updated_at = NOW()\n WHERE id = ?\n `, [row.actual_customer, row.actual_seller, row.id])\n }\n\n totalCorrected += actualCounts.length\n offset += BATCH_SIZE\n\n if (actualCounts.length < BATCH_SIZE) break\n }\n\n if (totalCorrected === 0) {\n logger.debug(\"Messaging: reconcile-unread-counts — no drift detected\")\n return\n }\n\n logger.info(\n `Messaging: reconcile-unread-counts corrected ${totalCorrected} conversation(s)`\n )\n } catch (err) {\n logger.error(\n `Messaging: reconcile-unread-counts error: ${(err as Error).message}`\n )\n }\n}\n\nexport const config = {\n name: \"messaging-reconcile-unread-counts\",\n schedule: \"0 3 * * *\", // Daily at 3 AM\n}\n",
"type": "registry:api"
},
{
"path": "messaging/jobs/cleanup-blocked-messages.ts",
"content": "import { MedusaContainer } from \"@medusajs/framework/types\"\n\nimport { MESSAGING_FILTERS_MODULE } from \"../modules/messaging-filters\"\nimport type MessagingFiltersModuleService from \"../modules/messaging-filters/service\"\n\nconst RETENTION_DAYS = 30\n\nexport default async function cleanupBlockedMessages(\n container: MedusaContainer\n) {\n const logger = container.resolve(\"logger\")\n const service = container.resolve<MessagingFiltersModuleService>(\n MESSAGING_FILTERS_MODULE\n )\n\n try {\n const cutoffDate = new Date()\n cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS)\n\n // List old blocked message logs\n const oldLogs = await service.listBlockedMessageLogs(\n {\n created_at: { $lt: cutoffDate },\n },\n { take: 1000, select: [\"id\"] }\n )\n\n if (!oldLogs || oldLogs.length === 0) {\n logger.debug(\"Messaging: cleanup-blocked-messages — nothing to clean up\")\n return\n }\n\n const ids = oldLogs.map((log: any) => log.id)\n\n await service.deleteBlockedMessageLogs(ids)\n\n logger.info(\n `Messaging: cleanup-blocked-messages deleted ${ids.length} log(s) older than ${RETENTION_DAYS} days`\n )\n } catch (err) {\n logger.error(\n `Messaging: cleanup-blocked-messages error: ${(err as Error).message}`\n )\n }\n}\n\nexport const config = {\n name: \"messaging-cleanup-blocked-messages\",\n schedule: \"0 4 * * *\", // Daily at 4 AM\n}\n",
"type": "registry:api"
},
{
"path": "messaging/vendor/lib/client.ts",
"content": "// DO NOT ADD THIS TO registry.json its only meant for internal use\nimport { createClient, InferClient } from \"@mercurjs/client\"\nimport { Routes } from '../../../../.mercur/_generated'\n\ndeclare const __BACKEND_URL__: string\n\nexport const client: InferClient<Routes> = createClient({\n baseUrl: __BACKEND_URL__,\n fetchOptions: {\n credentials: 'include',\n },\n})\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/hooks/use-messaging-layout.ts",
"content": "import { useLayoutEffect } from \"react\"\n\n/**\n * Override the shell's scroll behavior to give the messaging\n * pages a full-height, non-scrolling layout. Restores original\n * styles on unmount.\n */\nexport function useMessagingLayout() {\n useLayoutEffect(() => {\n const main = document.querySelector(\"main\") as HTMLElement | null\n const contentCol = main?.parentElement as HTMLElement | null\n const gutter = main?.firstElementChild as HTMLElement | null\n\n const origMain = main?.style.cssText ?? \"\"\n const origCol = contentCol?.style.cssText ?? \"\"\n const origGutter = gutter?.style.cssText ?? \"\"\n\n if (contentCol) contentCol.style.overflow = \"hidden\"\n if (main) {\n main.style.overflow = \"hidden\"\n main.style.minHeight = \"0\"\n }\n if (gutter) {\n gutter.style.flex = \"1\"\n gutter.style.minHeight = \"0\"\n gutter.style.overflow = \"hidden\"\n }\n\n return () => {\n if (main) main.style.cssText = origMain\n if (contentCol) contentCol.style.cssText = origCol\n if (gutter) gutter.style.cssText = origGutter\n }\n }, [])\n}\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/hooks/api/messaging.tsx",
"content": "import {\n useQuery,\n useInfiniteQuery,\n useMutation,\n useQueryClient,\n UseQueryOptions,\n UseMutationOptions,\n} from \"@tanstack/react-query\"\nimport { queryKeysFactory } from \"@mercurjs/dashboard-shared\"\nimport { client } from \"../../lib/client\"\nimport { ClientError } from \"@mercurjs/client\"\n\nconst CONVERSATIONS_QUERY_KEY = \"vendor_conversations\" as const\nexport const conversationsQueryKeys = queryKeysFactory(CONVERSATIONS_QUERY_KEY)\n\nconst UNREAD_QUERY_KEY = \"vendor_messaging_unread\" as const\nexport const unreadQueryKeys = queryKeysFactory(UNREAD_QUERY_KEY)\n\nexport type ConversationDTO = {\n id: string\n seller_id: string\n buyer_id: string\n buyer_first_name?: string | null\n last_message_preview: string | null\n last_message_sender_type: \"customer\" | \"seller\" | null\n last_message_at: string | null\n unread_count_seller: number\n created_at: string\n updated_at: string\n is_buyer_blocked?: boolean\n}\n\nexport type MessageDTO = {\n id: string\n sender_type: \"customer\" | \"seller\"\n body: string\n context_type: \"product\" | \"order\" | null\n context_id: string | null\n context_label: string | null\n read_at: string | null\n created_at: string\n}\n\ntype ConversationListResponse = {\n conversations: ConversationDTO[]\n next_cursor: string | null\n}\n\ntype ConversationDetailResponse = {\n conversation: ConversationDTO\n messages: MessageDTO[]\n next_cursor: string | null\n buyer_orders: any[]\n}\n\ntype UnreadResponse = {\n unread_count: number\n}\n\nexport const useVendorConversations = (\n query?: { cursor?: string; limit?: number },\n options?: Omit<\n UseQueryOptions<ConversationListResponse, ClientError>,\n \"queryKey\" | \"queryFn\"\n >\n) => {\n const { data, ...rest } = useQuery({\n queryKey: conversationsQueryKeys.list(query),\n queryFn: async () =>\n (client as any).vendor.messages.query(query ?? {}) as Promise<ConversationListResponse>,\n ...options,\n })\n\n return { ...data, ...rest }\n}\n\nexport const useVendorConversation = (\n id: string,\n query?: { limit?: number },\n) => {\n const limit = query?.limit ?? 20\n\n const { data, fetchNextPage, hasNextPage, isFetchingNextPage, ...rest } =\n useInfiniteQuery<ConversationDetailResponse, ClientError>({\n queryKey: conversationsQueryKeys.detail(id, { limit }),\n queryFn: async ({ pageParam }) =>\n (client as any).vendor.messages.$id.query({\n $id: id,\n limit,\n ...(pageParam ? { cursor: pageParam } : {}),\n }) as Promise<ConversationDetailResponse>,\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage) => lastPage.next_cursor ?? undefined,\n })\n\n const conversation = data?.pages[0]?.conversation\n const buyer_orders = data?.pages[0]?.buyer_orders\n const messages = data?.pages.flatMap((p) => p.messages) ?? []\n\n return {\n conversation,\n messages,\n buyer_orders,\n fetchNextPage,\n hasNextPage,\n isFetchingNextPage,\n ...rest,\n }\n}\n\nexport const useVendorUnread = (\n options?: Omit<\n UseQueryOptions<UnreadResponse, ClientError>,\n \"queryKey\" | \"queryFn\"\n >\n) => {\n const { data, ...rest } = useQuery({\n queryKey: unreadQueryKeys.detail(\"total\"),\n queryFn: async () =>\n (client as any).vendor.messages.unread.query() as Promise<UnreadResponse>,\n ...options,\n })\n\n return { ...data, ...rest }\n}\n\nexport const useSendVendorReply = (\n conversationId: string,\n options?: UseMutationOptions<{ message: MessageDTO }, ClientError, { body: string }>\n) => {\n const queryClient = useQueryClient()\n const { onSuccess, onError, ...restOptions } = options ?? {}\n\n return useMutation({\n ...restOptions,\n mutationFn: (payload: { body: string }) =>\n (client as any).vendor.messages.$id.mutate({ $id: conversationId, ...payload }) as Promise<{ message: MessageDTO }>,\n onSuccess: (data, variables, context) => {\n queryClient.invalidateQueries({\n queryKey: conversationsQueryKeys.detail(conversationId),\n })\n queryClient.invalidateQueries({\n queryKey: conversationsQueryKeys.lists(),\n })\n queryClient.invalidateQueries({\n queryKey: unreadQueryKeys.all,\n })\n onSuccess?.(data, variables, context)\n },\n onError,\n })\n}\n\nexport const useMarkVendorRead = (\n conversationId: string,\n options?: UseMutationOptions<{ success: boolean }, ClientError, void>\n) => {\n const queryClient = useQueryClient()\n const { onSuccess, onError, ...restOptions } = options ?? {}\n\n return useMutation({\n ...restOptions,\n mutationFn: () =>\n (client as any).vendor.messages.$id.read.mutate({ $id: conversationId }) as Promise<{ success: boolean }>,\n onSuccess: (data, variables, context) => {\n queryClient.invalidateQueries({\n queryKey: conversationsQueryKeys.detail(conversationId),\n })\n queryClient.invalidateQueries({\n queryKey: conversationsQueryKeys.lists(),\n })\n queryClient.invalidateQueries({\n queryKey: unreadQueryKeys.all,\n })\n onSuccess?.(data, variables, context)\n },\n onError,\n })\n}\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/hooks/api/use-messaging-sse.tsx",
"content": "import { useEffect, useRef } from \"react\"\nimport { useQueryClient } from \"@tanstack/react-query\"\nimport { conversationsQueryKeys, unreadQueryKeys } from \"./messaging\"\n\ndeclare const __BACKEND_URL__: string\n\ntype SSEStatus = \"connecting\" | \"connected\" | \"disconnected\" | \"polling\"\n\nconst POLLING_INTERVAL_LIST = 30000\nconst POLLING_INTERVAL_UNREAD = 15000\n\nexport const useMessagingSSE = (\n activeConversationId?: string,\n onStatusChange?: (status: SSEStatus) => void\n) => {\n const queryClient = useQueryClient()\n const eventSourceRef = useRef<EventSource | null>(null)\n const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null)\n const unreadPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)\n const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)\n const reconnectDelayRef = useRef(1000)\n const statusRef = useRef<SSEStatus>(\"disconnected\")\n const mountedRef = useRef(true)\n\n // Store callbacks in refs to avoid dependency chains\n const onStatusChangeRef = useRef(onStatusChange)\n onStatusChangeRef.current = onStatusChange\n\n const activeIdRef = useRef(activeConversationId)\n activeIdRef.current = activeConversationId\n\n useEffect(() => {\n mountedRef.current = true\n\n const setStatus = (status: SSEStatus) => {\n statusRef.current = status\n onStatusChangeRef.current?.(status)\n }\n\n const invalidateQueries = () => {\n queryClient.invalidateQueries({ queryKey: conversationsQueryKeys.all })\n queryClient.invalidateQueries({ queryKey: unreadQueryKeys.all })\n }\n\n const invalidateConversation = (conversationId: string) => {\n queryClient.invalidateQueries({\n queryKey: conversationsQueryKeys.detail(conversationId),\n })\n }\n\n const stopPolling = () => {\n if (pollingRef.current) {\n clearInterval(pollingRef.current)\n pollingRef.current = null\n }\n if (unreadPollingRef.current) {\n clearInterval(unreadPollingRef.current)\n unreadPollingRef.current = null\n }\n }\n\n const startPolling = () => {\n if (pollingRef.current) return\n setStatus(\"polling\")\n\n pollingRef.current = setInterval(() => {\n invalidateQueries()\n }, POLLING_INTERVAL_LIST)\n\n unreadPollingRef.current = setInterval(() => {\n queryClient.invalidateQueries({ queryKey: unreadQueryKeys.all })\n }, POLLING_INTERVAL_UNREAD)\n }\n\n const connect = () => {\n if (!mountedRef.current) return\n\n if (eventSourceRef.current) {\n eventSourceRef.current.close()\n }\n\n setStatus(\"connecting\")\n\n const baseUrl = typeof __BACKEND_URL__ !== \"undefined\" ? __BACKEND_URL__ : \"\"\n const url = `${baseUrl}/vendor/messages/events`\n\n const es = new EventSource(url, { withCredentials: true })\n eventSourceRef.current = es\n\n es.addEventListener(\"connected\", () => {\n setStatus(\"connected\")\n stopPolling()\n reconnectDelayRef.current = 1000 // Reset backoff on success\n })\n\n es.addEventListener(\"new_message\", (event: MessageEvent) => {\n invalidateQueries()\n try {\n const data = JSON.parse(event.data)\n if (data.conversation_id) {\n invalidateConversation(data.conversation_id)\n }\n } catch {\n // Broad invalidation already handled above\n }\n })\n\n es.addEventListener(\"messages_read\", (event: MessageEvent) => {\n invalidateQueries()\n try {\n const data = JSON.parse(event.data)\n if (data.conversation_id) {\n invalidateConversation(data.conversation_id)\n }\n } catch {\n // Broad invalidation already handled above\n }\n })\n\n es.addEventListener(\"unread_count\", () => {\n queryClient.invalidateQueries({ queryKey: unreadQueryKeys.all })\n })\n\n es.onerror = () => {\n es.close()\n eventSourceRef.current = null\n startPolling()\n\n // Exponential backoff: 1s, 2s, 4s, 8s, ..., max 30s\n const delay = reconnectDelayRef.current\n reconnectDelayRef.current = Math.min(delay * 2, 30000)\n\n reconnectTimerRef.current = setTimeout(() => {\n reconnectTimerRef.current = null\n if (mountedRef.current && statusRef.current === \"polling\") {\n connect()\n }\n }, delay)\n }\n }\n\n connect()\n\n return () => {\n mountedRef.current = false\n if (eventSourceRef.current) {\n eventSourceRef.current.close()\n eventSourceRef.current = null\n }\n stopPolling()\n if (reconnectTimerRef.current) {\n clearTimeout(reconnectTimerRef.current)\n reconnectTimerRef.current = null\n }\n }\n }, [queryClient]) // queryClient is stable — no re-render loop\n\n return { status: statusRef.current }\n}\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/hooks/table/columns/use-conversation-table-columns.tsx",
"content": "import { createColumnHelper } from \"@tanstack/react-table\"\nimport { useMemo } from \"react\"\nimport { StatusBadge, Text } from \"@medusajs/ui\"\nimport { DateCell, DateHeader } from \"@mercurjs/dashboard-shared\"\nimport { ConversationDTO } from \"../../api/messaging\"\n\nconst columnHelper = createColumnHelper<ConversationDTO>()\n\nexport const useConversationTableColumns = () => {\n return useMemo(\n () => [\n columnHelper.accessor(\"buyer_first_name\", {\n header: () => (\n <div className=\"flex h-full w-full items-center\">\n <span className=\"truncate\">Customer</span>\n </div>\n ),\n cell: ({ getValue }) => {\n const name = getValue()\n return (\n <Text size=\"small\" leading=\"compact\">\n {name || \"Customer\"}\n </Text>\n )\n },\n }),\n columnHelper.accessor(\"last_message_preview\", {\n header: () => (\n <div className=\"flex h-full w-full items-center\">\n <span className=\"truncate\">Last Message</span>\n </div>\n ),\n cell: ({ getValue, row }) => {\n const preview = getValue()\n const senderType = row.original.last_message_sender_type\n const prefix = senderType === \"seller\" ? \"You: \" : \"\"\n return (\n <div className=\"flex h-full w-full items-center overflow-hidden\">\n <Text\n size=\"small\"\n leading=\"compact\"\n className=\"text-ui-fg-subtle truncate\"\n >\n {preview ? `${prefix}${preview}` : \"No messages yet\"}\n </Text>\n </div>\n )\n },\n }),\n columnHelper.accessor(\"unread_count_seller\", {\n header: () => (\n <div className=\"flex h-full w-full items-center\">\n <span className=\"truncate\">Unread</span>\n </div>\n ),\n cell: ({ getValue }) => {\n const count = getValue()\n if (!count) return null\n return (\n <StatusBadge color=\"blue\">{count}</StatusBadge>\n )\n },\n }),\n columnHelper.accessor(\"last_message_at\", {\n header: () => <DateHeader />,\n cell: ({ getValue }) => {\n const val = getValue()\n if (!val) return <Text size=\"small\" className=\"text-ui-fg-muted\">-</Text>\n const date = new Date(val)\n return <DateCell date={date} />\n },\n }),\n ],\n []\n )\n}\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/hooks/table/query/use-conversation-table-query.tsx",
"content": "import { useQueryParams } from \"@mercurjs/dashboard-shared\"\n\ntype UseConversationTableQueryProps = {\n prefix?: string\n pageSize?: number\n}\n\nexport const useConversationTableQuery = ({\n prefix,\n pageSize = 20,\n}: UseConversationTableQueryProps) => {\n const queryObject = useQueryParams(\n [\"offset\", \"order\"],\n prefix\n )\n\n const { offset, order } = queryObject\n\n const searchParams: Record<string, any> = {\n limit: pageSize,\n offset: offset ? Number(offset) : 0,\n order: order ? order : \"-last_message_at\",\n }\n\n return {\n searchParams,\n raw: queryObject,\n }\n}\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/routes/messages/page.tsx",
"content": "import { useNavigate } from \"react-router-dom\"\nimport { Badge, Container, Heading, Text, clx } from \"@medusajs/ui\"\nimport type { RouteConfig } from \"@mercurjs/dashboard-sdk\"\n\nimport { useVendorConversations, ConversationDTO } from \"../../hooks/api/messaging\"\nimport { useMessagingSSE } from \"../../hooks/api/use-messaging-sse\"\nimport { useMessagingLayout } from \"../../hooks/use-messaging-layout\"\n\nexport const config: RouteConfig = {\n label: \"Messages\",\n}\n\nexport const handle = {\n breadcrumb: () => \"Messages\",\n}\n\nconst formatRelativeTime = (dateStr: string | null): string => {\n if (!dateStr) return \"\"\n const date = new Date(dateStr)\n const now = new Date()\n const diffMs = now.getTime() - date.getTime()\n const diffMin = Math.floor(diffMs / 60000)\n if (diffMin < 1) return \"Just now\"\n if (diffMin < 60) return `${diffMin}m ago`\n const diffHours = Math.floor(diffMin / 60)\n if (diffHours < 24) return `${diffHours}h ago`\n const diffDays = Math.floor(diffHours / 24)\n if (diffDays < 7) return `${diffDays}d ago`\n return date.toLocaleDateString()\n}\n\nconst ConversationRow = ({\n conversation,\n onClick,\n}: {\n conversation: ConversationDTO\n onClick: () => void\n}) => {\n const isUnread = conversation.unread_count_seller > 0\n const senderPrefix =\n conversation.last_message_sender_type === \"seller\" ? \"You: \" : \"\"\n\n return (\n <button\n onClick={onClick}\n className={clx(\n \"flex w-full items-center gap-3 px-6 py-3 text-left transition-colors hover:bg-ui-bg-base-hover\",\n isUnread && \"bg-ui-bg-highlight\"\n )}\n >\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <div className=\"flex items-center justify-between gap-2\">\n <div className=\"flex items-center gap-x-2\">\n <Text\n size=\"small\"\n leading=\"compact\"\n weight={isUnread ? \"plus\" : \"regular\"}\n >\n {conversation.buyer_first_name || \"Customer\"}\n </Text>\n {conversation.is_buyer_blocked && (\n <Badge color=\"red\" size=\"2xsmall\">\n Blocked\n </Badge>\n )}\n </div>\n <Text size=\"xsmall\" className=\"text-ui-fg-muted shrink-0\">\n {formatRelativeTime(conversation.last_message_at)}\n </Text>\n </div>\n <div className=\"flex items-center justify-between gap-2\">\n <Text\n size=\"small\"\n leading=\"compact\"\n className={clx(\n \"truncate\",\n isUnread ? \"text-ui-fg-base\" : \"text-ui-fg-subtle\"\n )}\n >\n {conversation.last_message_preview\n ? `${senderPrefix}${conversation.last_message_preview}`\n : \"No messages yet\"}\n </Text>\n {isUnread && (\n <Badge color=\"blue\" size=\"2xsmall\">\n {conversation.unread_count_seller}\n </Badge>\n )}\n </div>\n </div>\n </button>\n )\n}\n\nconst VendorMessagesPage = () => {\n useMessagingSSE()\n const navigate = useNavigate()\n const { conversations, next_cursor, isLoading, isError, error } =\n useVendorConversations({ limit: 50 })\n\n useMessagingLayout()\n\n if (isError) throw error\n\n return (\n <div className=\"flex h-full flex-col\">\n <Container className=\"flex h-full flex-col divide-y p-0\">\n <div className=\"flex shrink-0 items-center justify-between px-6 py-4\">\n <Heading>Messages</Heading>\n </div>\n {isLoading ? (\n <div className=\"flex flex-1 items-center justify-center px-6 py-12\">\n <Text className=\"text-ui-fg-muted\">Loading conversations...</Text>\n </div>\n ) : !conversations?.length ? (\n <div className=\"flex flex-1 items-center justify-center px-6 py-12\">\n <Text className=\"text-ui-fg-muted\">No conversations yet</Text>\n </div>\n ) : (\n <div className=\"flex-1 divide-y overflow-y-auto\">\n {conversations.map((conv) => (\n <ConversationRow\n key={conv.id}\n conversation={conv}\n onClick={() => navigate(`/messages/${conv.id}`)}\n />\n ))}\n </div>\n )}\n </Container>\n </div>\n )\n}\n\nexport default VendorMessagesPage\n",
"type": "registry:vendor"
},
{
"path": "messaging/vendor/routes/messages/[id]/page.tsx",
"content": "import { useEffect, useRef, useState } from \"react\"\nimport { useParams } from \"react-router-dom\"\nimport {\n Badge,\n Button,\n Container,\n Heading,\n Text,\n Textarea,\n clx,\n} from \"@medusajs/ui\"\nimport {\n useVendorConversation,\n useMarkVendorRead,\n useSendVendorReply,\n MessageDTO,\n} from \"../../../hooks/api/messaging\"\nimport { useMessagingSSE } from \"../../../hooks/api/use-messaging-sse\"\nimport { useMessagingLayout } from \"../../../hooks/use-messaging-layout\"\n\nexport const handle = {\n breadcrumb: () => \"Conversation\",\n}\n\nconst formatTime = (dateStr: string): string => {\n const date = new Date(dateStr)\n const now = new Date()\n const isToday = date.toDateString() === now.toDateString()\n\n if (isToday) {\n return date.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })\n }\n\n const yesterday = new Date(now)\n yesterday.setDate(yesterday.getDate() - 1)\n if (date.toDateString() === yesterday.toDateString()) {\n return `Yesterday ${date.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })}`\n }\n\n return `${date.toLocaleDateString([], { month: \"short\", day: \"numeric\" })} ${date.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })}`\n}\n\nconst ContextBadge = ({ message }: { message: MessageDTO }) => {\n if (!message.context_type) return null\n return (\n <Badge color=\"grey\" size=\"2xsmall\" className=\"mb-1\">\n {message.context_label || `${message.context_type}: ${message.context_id}`}\n </Badge>\n )\n}\n\nconst MessageBubble = ({ message }: { message: MessageDTO }) => {\n const isSeller = message.sender_type === \"seller\"\n return (\n <div\n className={clx(\n \"flex flex-col gap-0.5\",\n isSeller ? \"items-end\" : \"items-start\"\n )}\n >\n <ContextBadge message={message} />\n <div\n className={clx(\n \"max-w-[70%] rounded-lg px-3 py-2\",\n isSeller\n ? \"bg-ui-bg-interactive text-ui-fg-on-color\"\n : \"bg-ui-bg-subtle text-ui-fg-base\"\n )}\n >\n <Text size=\"small\" leading=\"compact\">\n {message.body}\n </Text>\n </div>\n <Text size=\"xsmall\" className=\"text-ui-fg-muted px-1\">\n {formatTime(message.created_at)}\n {isSeller && message.read_at && \" · Read\"}\n </Text>\n </div>\n )\n}\n\nconst OrderSidebar = ({\n buyerName,\n orders,\n isBuyerBlocked,\n}: {\n buyerName: string | null\n orders: any[]\n isBuyerBlocked?: boolean\n}) => {\n return (\n <Container className=\"divide-y p-0\">\n <div className=\"px-6 py-4\">\n <Text size=\"small\" leading=\"compact\" weight=\"plus\">\n Customer\n </Text>\n <div className=\"flex items-center gap-x-2 mt-1\">\n <Text size=\"small\" leading=\"compact\" className=\"text-ui-fg-subtle\">\n {buyerName || \"Customer\"}\n </Text>\n {isBuyerBlocked && (\n <Badge color=\"red\" size=\"2xsmall\">\n Blocked\n </Badge>\n )}\n </div>\n </div>\n {orders.length > 0 && (\n <div className=\"px-6 py-4\">\n <Text size=\"small\" leading=\"compact\" weight=\"plus\" className=\"mb-2\">\n Recent Orders\n </Text>\n <div className=\"flex flex-col gap-2\">\n {orders.slice(0, 5).map((order: any) => (\n <div\n key={order.id}\n className=\"flex items-center justify-between rounded border border-ui-border-base px-3 py-2\"\n >\n <div>\n <Text size=\"small\" leading=\"compact\">\n #{order.display_id}\n </Text>\n <Text\n size=\"xsmall\"\n className=\"text-ui-fg-muted\"\n >\n {new Date(order.created_at).toLocaleDateString()}\n </Text>\n </div>\n <Badge color=\"grey\" size=\"2xsmall\">\n {order.status}\n </Badge>\n </div>\n ))}\n </div>\n </div>\n )}\n </Container>\n )\n}\n\nconst VendorConversationDetailPage = () => {\n const { id } = useParams<{ id: string }>()\n useMessagingSSE(id)\n const [replyBody, setReplyBody] = useState(\"\")\n const messagesContainerRef = useRef<HTMLDivElement>(null)\n const rootRef = useRef<HTMLDivElement>(null)\n\n const {\n conversation,\n messages,\n buyer_orders,\n fetchNextPage,\n hasNextPage,\n isFetchingNextPage,\n isLoading,\n isError,\n error,\n } = useVendorConversation(id!)\n\n const markRead = useMarkVendorRead(id!)\n const sendReply = useSendVendorReply(id!)\n\n useMessagingLayout()\n\n // Mark messages as read on mount\n useEffect(() => {\n if (conversation && conversation.unread_count_seller > 0) {\n markRead.mutate()\n }\n }, [conversation?.id, conversation?.unread_count_seller])\n\n // Scroll to bottom when messages change\n useEffect(() => {\n const el = messagesContainerRef.current\n if (el) {\n el.scrollTop = el.scrollHeight\n }\n }, [messages?.length])\n\n if (isError) throw error\n\n const handleSend = () => {\n const trimmed = replyBody.trim()\n if (!trimmed || sendReply.isPending) return\n\n sendReply.mutate(\n { body: trimmed },\n { onSuccess: () => setReplyBody(\"\") }\n )\n }\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault()\n handleSend()\n }\n }\n\n if (isLoading) {\n return (\n <div className=\"flex items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">Loading conversation...</Text>\n </div>\n )\n }\n\n // Messages come in desc order from API; reverse for display\n const displayMessages = [...(messages ?? [])].reverse()\n\n return (\n <div id=\"chat-root\" ref={rootRef} className=\"flex gap-4 h-full min-h-0\">\n {/* Main: Message Thread */}\n <div id=\"chat-card\" className=\"flex-1 flex flex-col min-h-0 bg-ui-bg-base rounded-lg shadow-elevation-card-rest overflow-hidden\">\n <div id=\"chat-header\" className=\"flex items-center justify-between px-6 py-4 border-b border-ui-border-base shrink-0\">\n <Heading level=\"h2\">\n {conversation?.buyer_first_name || \"Customer\"}\n </Heading>\n </div>\n\n {/* Messages list */}\n <div\n id=\"chat-messages\"\n ref={messagesContainerRef}\n className=\"flex-1 flex flex-col gap-3 px-6 py-4 overflow-y-auto min-h-0\"\n >\n {hasNextPage && (\n <div className=\"flex justify-center shrink-0\">\n <Button\n size=\"small\"\n variant=\"secondary\"\n onClick={() => fetchNextPage()}\n disabled={isFetchingNextPage}\n isLoading={isFetchingNextPage}\n >\n Load older messages\n </Button>\n </div>\n )}\n {displayMessages.map((msg) => (\n <MessageBubble key={msg.id} message={msg} />\n ))}\n </div>\n\n {/* Compose area */}\n {conversation?.is_buyer_blocked ? (\n <div className=\"border-t border-ui-border-base px-6 py-4 shrink-0\">\n <Text size=\"small\" className=\"text-ui-fg-muted\">\n This customer has been blocked from chat by an administrator.\n </Text>\n </div>\n ) : (\n <div id=\"chat-compose\" className=\"border-t border-ui-border-base px-6 py-4 shrink-0\">\n <div className=\"flex gap-2\">\n <Textarea\n placeholder=\"Type your reply...\"\n value={replyBody}\n onChange={(e) => setReplyBody(e.target.value)}\n onKeyDown={handleKeyDown}\n className=\"flex-1 resize-none\"\n rows={2}\n />\n <Button\n size=\"small\"\n onClick={handleSend}\n disabled={!replyBody.trim() || sendReply.isPending}\n isLoading={sendReply.isPending}\n >\n Send\n </Button>\n </div>\n </div>\n )}\n </div>\n\n {/* Sidebar: Customer + Orders */}\n <div id=\"chat-sidebar\" className=\"w-[280px] shrink-0 overflow-y-auto\">\n <OrderSidebar\n buyerName={conversation?.buyer_first_name ?? null}\n orders={buyer_orders ?? []}\n isBuyerBlocked={conversation?.is_buyer_blocked}\n />\n </div>\n </div>\n )\n}\n\nexport default VendorConversationDetailPage\n",
"type": "registry:vendor"
},
{
"path": "messaging/admin/lib/client.ts",
"content": "// DO NOT ADD THIS TO registry.json - internal use only for type checking in the mercur monorepo\nimport { createClient, InferClient } from \"@mercurjs/client\"\nimport { Routes } from '../../../../.mercur/_generated'\n\ndeclare const __BACKEND_URL__: string\n\nexport const client: InferClient<Routes> = createClient({\n baseUrl: __BACKEND_URL__,\n fetchOptions: {\n credentials: 'include',\n },\n})\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/hooks/use-messaging-layout.ts",
"content": "import { useLayoutEffect } from \"react\"\n\n/**\n * Override the shell's scroll behavior to give the messaging\n * pages a full-height, non-scrolling layout. Restores original\n * styles on unmount.\n */\nexport function useMessagingLayout() {\n useLayoutEffect(() => {\n const main = document.querySelector(\"main\") as HTMLElement | null\n const contentCol = main?.parentElement as HTMLElement | null\n const gutter = main?.firstElementChild as HTMLElement | null\n\n const origMain = main?.style.cssText ?? \"\"\n const origCol = contentCol?.style.cssText ?? \"\"\n const origGutter = gutter?.style.cssText ?? \"\"\n\n if (contentCol) contentCol.style.overflow = \"hidden\"\n if (main) {\n main.style.overflow = \"hidden\"\n main.style.minHeight = \"0\"\n }\n if (gutter) {\n gutter.style.flex = \"1\"\n gutter.style.minHeight = \"0\"\n gutter.style.overflow = \"hidden\"\n }\n\n return () => {\n if (main) main.style.cssText = origMain\n if (contentCol) contentCol.style.cssText = origCol\n if (gutter) gutter.style.cssText = origGutter\n }\n }, [])\n}\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/hooks/api/messaging.tsx",
"content": "import {\n useQuery,\n useInfiniteQuery,\n useMutation,\n useQueryClient,\n UseQueryOptions,\n} from \"@tanstack/react-query\"\nimport { client } from \"../../lib/client\"\nimport { ClientError } from \"@mercurjs/client\"\n\nconst ADMIN_CONVERSATIONS_KEY = \"admin_conversations\" as const\nconst ADMIN_CONVERSATION_KEY = \"admin_conversation\" as const\n\nexport type AdminConversationDTO = {\n id: string\n buyer_id: string\n seller_id: string\n buyer_name?: string | null\n buyer_email?: string | null\n seller_name?: string | null\n last_message_preview: string | null\n last_message_sender_type: \"customer\" | \"seller\" | null\n last_message_at: string | null\n unread_count_customer: number\n unread_count_seller: number\n created_at: string\n is_buyer_blocked?: boolean\n block_reason?: string | null\n}\n\nexport type AdminMessageDTO = {\n id: string\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n body: string\n context_type: \"product\" | \"order\" | null\n context_id: string | null\n context_label: string | null\n read_at: string | null\n created_at: string\n}\n\ntype AdminConversationListResponse = {\n conversations: AdminConversationDTO[]\n next_cursor: string | null\n}\n\ntype AdminConversationDetailResponse = {\n conversation: AdminConversationDTO\n messages: AdminMessageDTO[]\n next_cursor: string | null\n}\n\ntype SearchParams = {\n cursor?: string\n limit?: number\n seller_name?: string\n buyer_name?: string\n date_from?: string\n date_to?: string\n context_type?: string\n context_id?: string\n}\n\nexport const useAdminConversations = (\n query?: SearchParams,\n options?: Omit<UseQueryOptions<AdminConversationListResponse, ClientError>, \"queryKey\" | \"queryFn\">\n) => {\n const { data, ...rest } = useQuery({\n queryKey: [ADMIN_CONVERSATIONS_KEY, query],\n queryFn: async () =>\n (client as any).admin.messages.query(query ?? {}) as Promise<AdminConversationListResponse>,\n ...options,\n })\n\n return { ...data, ...rest }\n}\n\nexport const useAdminConversation = (\n id: string,\n query?: { limit?: number },\n) => {\n const limit = query?.limit ?? 20\n\n const { data, fetchNextPage, hasNextPage, isFetchingNextPage, ...rest } =\n useInfiniteQuery<AdminConversationDetailResponse, ClientError>({\n queryKey: [ADMIN_CONVERSATION_KEY, id, { limit }],\n queryFn: async ({ pageParam }) =>\n (client as any).admin.messages.$id.query({\n $id: id,\n limit,\n ...(pageParam ? { cursor: pageParam } : {}),\n }) as Promise<AdminConversationDetailResponse>,\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (lastPage) => lastPage.next_cursor ?? undefined,\n })\n\n const conversation = data?.pages[0]?.conversation\n const messages = data?.pages.flatMap((p) => p.messages) ?? []\n\n return {\n conversation,\n messages,\n fetchNextPage,\n hasNextPage,\n isFetchingNextPage,\n ...rest,\n }\n}\n\nexport const useBlockCustomer = () => {\n const queryClient = useQueryClient()\n\n return useMutation({\n mutationFn: async (data: { customer_id: string; reason?: string }) =>\n (client as any).admin.messages[\"chat-blocks\"].mutate(data) as Promise<{ block: any }>,\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })\n },\n })\n}\n\nexport const useUnblockCustomer = () => {\n const queryClient = useQueryClient()\n\n return useMutation({\n mutationFn: async (customerId: string) =>\n (client as any).admin.messages[\"chat-blocks\"].$customer_id.delete({ $customer_id: customerId }) as Promise<{ success: boolean }>,\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })\n },\n })\n}\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/hooks/api/filters.tsx",
"content": "import {\n useQuery,\n useMutation,\n useQueryClient,\n UseQueryOptions,\n UseMutationOptions,\n} from \"@tanstack/react-query\"\nimport { client } from \"../../lib/client\"\nimport { ClientError } from \"@mercurjs/client\"\n\nconst FILTERS_KEY = \"admin_messaging_filters\" as const\nconst BLOCKED_KEY = \"admin_messaging_blocked\" as const\n\nexport type FilterRuleDTO = {\n id: string\n match_type: \"exact\" | \"contains\" | \"regex\"\n pattern: string\n is_builtin: boolean\n is_enabled: boolean\n description: string | null\n created_at: string\n updated_at: string\n}\n\nexport type BlockedMessageDTO = {\n id: string\n sender_id: string\n sender_type: \"customer\" | \"seller\"\n conversation_id: string\n matched_rule_id: string\n message_body: string\n created_at: string\n}\n\ntype FilterListResponse = {\n filter_rules: FilterRuleDTO[]\n count: number\n}\n\ntype BlockedListResponse = {\n blocked_messages: BlockedMessageDTO[]\n count: number\n}\n\nexport const useAdminFilters = (\n options?: Omit<UseQueryOptions<FilterListResponse, ClientError>, \"queryKey\" | \"queryFn\">\n) => {\n const { data, ...rest } = useQuery({\n queryKey: [FILTERS_KEY],\n queryFn: async () =>\n (client as any).admin.messages.filters.query() as Promise<FilterListResponse>,\n ...options,\n })\n\n return { ...data, ...rest }\n}\n\nexport const useCreateFilter = (\n options?: UseMutationOptions<\n { filter_rule: FilterRuleDTO },\n ClientError,\n { match_type: string; pattern: string; description?: string; is_enabled?: boolean }\n >\n) => {\n const queryClient = useQueryClient()\n\n return useMutation({\n mutationFn: (payload) =>\n (client as any).admin.messages.filters.mutate(payload) as Promise<{ filter_rule: FilterRuleDTO }>,\n onSuccess: (data, variables, context) => {\n queryClient.invalidateQueries({ queryKey: [FILTERS_KEY] })\n options?.onSuccess?.(data, variables, context)\n },\n ...options,\n })\n}\n\nexport const useUpdateFilter = (\n id: string,\n options?: UseMutationOptions<\n { filter_rule: FilterRuleDTO },\n ClientError,\n Record<string, any>\n >\n) => {\n const queryClient = useQueryClient()\n\n return useMutation({\n mutationFn: (payload) =>\n (client as any).admin.messages.filters.$id.mutate({ $id: id, ...payload }) as Promise<{ filter_rule: FilterRuleDTO }>,\n onSuccess: (data, variables, context) => {\n queryClient.invalidateQueries({ queryKey: [FILTERS_KEY] })\n options?.onSuccess?.(data, variables, context)\n },\n ...options,\n })\n}\n\nexport const useDeleteFilter = (\n options?: UseMutationOptions<{ id: string; deleted: boolean }, ClientError, string>\n) => {\n const queryClient = useQueryClient()\n\n return useMutation({\n mutationFn: (id: string) =>\n (client as any).admin.messages.filters.$id.delete({ $id: id }) as Promise<{ id: string; deleted: boolean }>,\n onSuccess: (data, variables, context) => {\n queryClient.invalidateQueries({ queryKey: [FILTERS_KEY] })\n options?.onSuccess?.(data, variables, context)\n },\n ...options,\n })\n}\n\nexport const useAdminBlockedMessages = (\n query?: { sender_type?: string; date_from?: string; date_to?: string },\n options?: Omit<UseQueryOptions<BlockedListResponse, ClientError>, \"queryKey\" | \"queryFn\">\n) => {\n const { data, ...rest } = useQuery({\n queryKey: [BLOCKED_KEY, query],\n queryFn: async () =>\n (client as any).admin.messages.blocked.query(query ?? {}) as Promise<BlockedListResponse>,\n ...options,\n })\n\n return { ...data, ...rest }\n}\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/hooks/api/use-admin-messaging-sse.tsx",
"content": "import { useEffect, useRef } from \"react\"\nimport { useQueryClient } from \"@tanstack/react-query\"\n\ndeclare const __BACKEND_URL__: string\n\ntype SSEStatus = \"connecting\" | \"connected\" | \"disconnected\" | \"polling\"\n\nconst ADMIN_CONVERSATIONS_KEY = \"admin_conversations\"\nconst ADMIN_CONVERSATION_KEY = \"admin_conversation\"\nconst POLLING_INTERVAL = 30000\n\nexport const useAdminMessagingSSE = (\n activeConversationId?: string,\n onStatusChange?: (status: SSEStatus) => void\n) => {\n const queryClient = useQueryClient()\n const eventSourceRef = useRef<EventSource | null>(null)\n const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null)\n const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)\n const reconnectDelayRef = useRef(1000)\n const statusRef = useRef<SSEStatus>(\"disconnected\")\n const mountedRef = useRef(true)\n\n // Store callbacks in refs to avoid dependency chains\n const onStatusChangeRef = useRef(onStatusChange)\n onStatusChangeRef.current = onStatusChange\n\n useEffect(() => {\n mountedRef.current = true\n\n const setStatus = (status: SSEStatus) => {\n statusRef.current = status\n onStatusChangeRef.current?.(status)\n }\n\n const invalidateAll = () => {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })\n }\n\n const stopPolling = () => {\n if (pollingRef.current) {\n clearInterval(pollingRef.current)\n pollingRef.current = null\n }\n }\n\n const startPolling = () => {\n if (pollingRef.current) return\n setStatus(\"polling\")\n\n pollingRef.current = setInterval(() => {\n invalidateAll()\n }, POLLING_INTERVAL)\n }\n\n const connect = () => {\n if (!mountedRef.current) return\n\n if (eventSourceRef.current) {\n eventSourceRef.current.close()\n }\n\n setStatus(\"connecting\")\n\n const baseUrl = typeof __BACKEND_URL__ !== \"undefined\" ? __BACKEND_URL__ : \"\"\n const url = `${baseUrl}/admin/messages/events`\n\n const es = new EventSource(url, { withCredentials: true })\n eventSourceRef.current = es\n\n es.addEventListener(\"connected\", () => {\n setStatus(\"connected\")\n stopPolling()\n reconnectDelayRef.current = 1000 // Reset backoff on success\n })\n\n es.addEventListener(\"new_message\", (event: MessageEvent) => {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })\n try {\n const data = JSON.parse(event.data)\n if (data.conversation_id) {\n queryClient.invalidateQueries({\n queryKey: [ADMIN_CONVERSATION_KEY, data.conversation_id],\n })\n }\n } catch {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })\n }\n })\n\n es.addEventListener(\"messages_read\", (event: MessageEvent) => {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })\n try {\n const data = JSON.parse(event.data)\n if (data.conversation_id) {\n queryClient.invalidateQueries({\n queryKey: [ADMIN_CONVERSATION_KEY, data.conversation_id],\n })\n }\n } catch {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })\n }\n })\n\n es.addEventListener(\"unread_count\", () => {\n queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })\n })\n\n es.onerror = () => {\n es.close()\n eventSourceRef.current = null\n startPolling()\n\n // Exponential backoff: 1s, 2s, 4s, 8s, ..., max 30s\n const delay = reconnectDelayRef.current\n reconnectDelayRef.current = Math.min(delay * 2, 30000)\n\n reconnectTimerRef.current = setTimeout(() => {\n reconnectTimerRef.current = null\n if (mountedRef.current && statusRef.current === \"polling\") {\n connect()\n }\n }, delay)\n }\n }\n\n connect()\n\n return () => {\n mountedRef.current = false\n if (eventSourceRef.current) {\n eventSourceRef.current.close()\n eventSourceRef.current = null\n }\n stopPolling()\n if (reconnectTimerRef.current) {\n clearTimeout(reconnectTimerRef.current)\n reconnectTimerRef.current = null\n }\n }\n }, [queryClient]) // queryClient is stable — no re-render loop\n\n return { status: statusRef.current }\n}\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/routes/messages/page.tsx",
"content": "import { useState } from \"react\"\nimport { useNavigate } from \"react-router-dom\"\nimport { Badge, Button, Container, Heading, Input, Label, Text } from \"@medusajs/ui\"\nimport type { RouteConfig } from \"@mercurjs/dashboard-sdk\"\n\nimport { useAdminConversations, AdminConversationDTO } from \"../../hooks/api/messaging\"\nimport { useAdminMessagingSSE } from \"../../hooks/api/use-admin-messaging-sse\"\nimport { useMessagingLayout } from \"../../hooks/use-messaging-layout\"\n\nexport const config: RouteConfig = {\n label: \"Messages\",\n}\n\nexport const handle = {\n breadcrumb: () => \"Messages\",\n}\n\nconst formatDate = (dateStr: string | null): string => {\n if (!dateStr) return \"-\"\n return new Date(dateStr).toLocaleString()\n}\n\nconst ConversationRow = ({\n conversation,\n onClick,\n}: {\n conversation: AdminConversationDTO\n onClick: () => void\n}) => {\n return (\n <button\n onClick={onClick}\n className=\"flex w-full items-center gap-4 px-6 py-3 text-left transition-colors hover:bg-ui-bg-base-hover\"\n >\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-center gap-2\">\n <Text size=\"small\" leading=\"compact\" weight=\"plus\">\n {conversation.seller_name || conversation.seller_id}\n </Text>\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n ↔\n </Text>\n <Text size=\"small\" leading=\"compact\" weight=\"plus\">\n {conversation.buyer_name || conversation.buyer_id}\n </Text>\n {conversation.is_buyer_blocked && (\n <Badge color=\"red\" size=\"2xsmall\">\n Blocked\n </Badge>\n )}\n </div>\n <Text\n size=\"small\"\n leading=\"compact\"\n className=\"text-ui-fg-subtle truncate mt-0.5\"\n >\n {conversation.last_message_preview || \"No messages\"}\n </Text>\n </div>\n <div className=\"shrink-0 text-right\">\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n {formatDate(conversation.last_message_at)}\n </Text>\n {(conversation.buyer_email) && (\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n {conversation.buyer_email}\n </Text>\n )}\n </div>\n </button>\n )\n}\n\nconst AdminMessagesPage = () => {\n useAdminMessagingSSE()\n const navigate = useNavigate()\n const [searchParams, setSearchParams] = useState<{\n seller_name?: string\n buyer_name?: string\n date_from?: string\n date_to?: string\n }>({})\n\n const [formState, setFormState] = useState({\n seller_name: \"\",\n buyer_name: \"\",\n date_from: \"\",\n date_to: \"\",\n })\n\n const { conversations, next_cursor, isLoading, isError, error } =\n useAdminConversations({ limit: 50, ...searchParams })\n\n useMessagingLayout()\n\n if (isError) throw error\n\n const handleSearch = () => {\n setSearchParams({\n seller_name: formState.seller_name || undefined,\n buyer_name: formState.buyer_name || undefined,\n date_from: formState.date_from || undefined,\n date_to: formState.date_to || undefined,\n })\n }\n\n const handleClear = () => {\n setFormState({ seller_name: \"\", buyer_name: \"\", date_from: \"\", date_to: \"\" })\n setSearchParams({})\n }\n\n return (\n <div className=\"flex h-full flex-col gap-4\">\n {/* Search Form */}\n <Container className=\"shrink-0 p-0\">\n <div className=\"px-6 py-4\">\n <Heading>Message Oversight</Heading>\n </div>\n <div className=\"grid grid-cols-2 gap-3 px-6 pb-4\">\n <div>\n <Label size=\"xsmall\">Vendor Name</Label>\n <Input\n size=\"small\"\n placeholder=\"Search vendor...\"\n value={formState.seller_name}\n onChange={(e) =>\n setFormState((s) => ({ ...s, seller_name: e.target.value }))\n }\n />\n </div>\n <div>\n <Label size=\"xsmall\">Customer Name</Label>\n <Input\n size=\"small\"\n placeholder=\"Search customer...\"\n value={formState.buyer_name}\n onChange={(e) =>\n setFormState((s) => ({ ...s, buyer_name: e.target.value }))\n }\n />\n </div>\n <div>\n <Label size=\"xsmall\">Date From</Label>\n <Input\n size=\"small\"\n type=\"date\"\n value={formState.date_from}\n onChange={(e) =>\n setFormState((s) => ({ ...s, date_from: e.target.value }))\n }\n />\n </div>\n <div>\n <Label size=\"xsmall\">Date To</Label>\n <Input\n size=\"small\"\n type=\"date\"\n value={formState.date_to}\n onChange={(e) =>\n setFormState((s) => ({ ...s, date_to: e.target.value }))\n }\n />\n </div>\n </div>\n <div className=\"flex gap-2 px-6 pb-4\">\n <Button size=\"small\" onClick={handleSearch}>\n Search\n </Button>\n <Button size=\"small\" variant=\"secondary\" onClick={handleClear}>\n Clear\n </Button>\n </div>\n </Container>\n\n {/* Results */}\n <Container className=\"flex min-h-0 flex-1 flex-col divide-y p-0\">\n <div className=\"shrink-0 px-6 py-4\">\n <Text size=\"small\" weight=\"plus\">\n Conversations\n </Text>\n </div>\n {isLoading ? (\n <div className=\"flex flex-1 items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">Loading...</Text>\n </div>\n ) : !conversations?.length ? (\n <div className=\"flex flex-1 items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">No conversations found</Text>\n </div>\n ) : (\n <div className=\"flex-1 divide-y overflow-y-auto\">\n {conversations.map((conv) => (\n <ConversationRow\n key={conv.id}\n conversation={conv}\n onClick={() => navigate(`/messages/${conv.id}`)}\n />\n ))}\n </div>\n )}\n </Container>\n </div>\n )\n}\n\nexport default AdminMessagesPage\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/routes/messages/[id]/page.tsx",
"content": "import { useRef, useState } from \"react\"\nimport { useParams } from \"react-router-dom\"\nimport { Badge, Button, Container, Heading, Input, Label, Text, clx, toast, usePrompt } from \"@medusajs/ui\"\n\nimport {\n useAdminConversation,\n useBlockCustomer,\n useUnblockCustomer,\n AdminMessageDTO,\n} from \"../../../hooks/api/messaging\"\nimport { useAdminMessagingSSE } from \"../../../hooks/api/use-admin-messaging-sse\"\nimport { useMessagingLayout } from \"../../../hooks/use-messaging-layout\"\n\nconst formatTime = (dateStr: string): string => {\n const date = new Date(dateStr)\n return `${date.toLocaleDateString([], { month: \"short\", day: \"numeric\" })} ${date.toLocaleTimeString([], { hour: \"2-digit\", minute: \"2-digit\" })}`\n}\n\nconst MessageRow = ({ message }: { message: AdminMessageDTO }) => {\n const isCustomer = message.sender_type === \"customer\"\n\n return (\n <div\n className={clx(\n \"flex flex-col gap-0.5\",\n isCustomer ? \"items-start\" : \"items-end\"\n )}\n >\n {message.context_type && (\n <Badge color=\"grey\" size=\"2xsmall\">\n {message.context_label || `${message.context_type}: ${message.context_id}`}\n </Badge>\n )}\n <div\n className={clx(\n \"max-w-[70%] rounded-lg px-3 py-2\",\n isCustomer\n ? \"bg-ui-bg-subtle text-ui-fg-base\"\n : \"bg-ui-bg-field text-ui-fg-base\"\n )}\n >\n <Text size=\"xsmall\" className=\"text-ui-fg-muted mb-0.5\">\n {isCustomer ? \"Customer\" : \"Vendor\"}\n </Text>\n <Text size=\"small\" leading=\"compact\">\n {message.body}\n </Text>\n </div>\n <Text size=\"xsmall\" className=\"text-ui-fg-muted px-1\">\n {formatTime(message.created_at)}\n {message.read_at && \" · Read\"}\n </Text>\n </div>\n )\n}\n\nconst AdminConversationDetailPage = () => {\n const { id } = useParams<{ id: string }>()\n useAdminMessagingSSE(id)\n const prompt = usePrompt()\n\n const rootRef = useRef<HTMLDivElement>(null)\n const [showBlockDialog, setShowBlockDialog] = useState(false)\n const [blockReason, setBlockReason] = useState(\"\")\n\n const blockMutation = useBlockCustomer()\n const unblockMutation = useUnblockCustomer()\n\n const {\n conversation,\n messages,\n fetchNextPage,\n hasNextPage,\n isFetchingNextPage,\n isLoading,\n isError,\n error,\n } = useAdminConversation(id!)\n\n const handleBlock = () => {\n if (!conversation?.buyer_id) return\n blockMutation.mutate(\n {\n customer_id: conversation.buyer_id,\n reason: blockReason || undefined,\n },\n {\n onSuccess: () => {\n toast.success(\"Customer blocked from chat\")\n setShowBlockDialog(false)\n setBlockReason(\"\")\n },\n onError: () => {\n toast.error(\"Failed to block customer\")\n },\n }\n )\n }\n\n const handleUnblock = async () => {\n if (!conversation?.buyer_id) return\n const confirmed = await prompt({\n title: \"Unblock Customer\",\n description:\n \"Are you sure you want to unblock this customer? They will be able to use chat again.\",\n })\n if (!confirmed) return\n\n unblockMutation.mutate(conversation.buyer_id, {\n onSuccess: () => {\n toast.success(\"Customer unblocked\")\n },\n onError: () => {\n toast.error(\"Failed to unblock customer\")\n },\n })\n }\n\n useMessagingLayout()\n\n if (isError) throw error\n\n if (isLoading) {\n return (\n <div className=\"flex items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">Loading conversation...</Text>\n </div>\n )\n }\n\n const displayMessages = [...(messages ?? [])].reverse()\n\n return (\n <div ref={rootRef} className=\"flex gap-4 h-full min-h-0\">\n {/* Main: Read-only message thread */}\n <div className=\"flex-1 flex flex-col min-h-0 bg-ui-bg-base rounded-lg shadow-elevation-card-rest overflow-hidden\">\n <div className=\"flex items-center justify-between px-6 py-4 border-b border-ui-border-base shrink-0\">\n <Heading level=\"h2\">Conversation</Heading>\n <Badge color=\"grey\" size=\"small\">\n Read-only\n </Badge>\n </div>\n <div className=\"flex-1 flex flex-col gap-3 px-6 py-4 overflow-y-auto min-h-0\">\n {hasNextPage && (\n <div className=\"flex justify-center shrink-0\">\n <Button\n size=\"small\"\n variant=\"secondary\"\n onClick={() => fetchNextPage()}\n disabled={isFetchingNextPage}\n isLoading={isFetchingNextPage}\n >\n Load older messages\n </Button>\n </div>\n )}\n {displayMessages.map((msg) => (\n <MessageRow key={msg.id} message={msg} />\n ))}\n {!displayMessages.length && (\n <Text className=\"text-ui-fg-muted text-center py-8\">\n No messages in this conversation\n </Text>\n )}\n </div>\n </div>\n\n {/* Sidebar: Conversation metadata */}\n <div className=\"w-[300px] shrink-0 overflow-y-auto\">\n <Container className=\"divide-y p-0\">\n <div className=\"px-6 py-4\">\n <Text size=\"small\" leading=\"compact\" weight=\"plus\">\n Conversation Details\n </Text>\n </div>\n <div className=\"px-6 py-3\">\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n Vendor\n </Text>\n <Text size=\"small\" leading=\"compact\">\n {conversation?.seller_name || conversation?.seller_id}\n </Text>\n </div>\n <div className=\"px-6 py-3\">\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n Customer\n </Text>\n <div className=\"flex items-center gap-x-2\">\n <Text size=\"small\" leading=\"compact\">\n {conversation?.buyer_name || conversation?.buyer_id}\n </Text>\n {conversation?.is_buyer_blocked && (\n <Badge color=\"red\" size=\"2xsmall\">\n Blocked\n </Badge>\n )}\n </div>\n {conversation?.buyer_email && (\n <Text size=\"xsmall\" className=\"text-ui-fg-subtle\">\n {conversation.buyer_email}\n </Text>\n )}\n {conversation?.is_buyer_blocked && conversation?.block_reason && (\n <Text size=\"xsmall\" className=\"text-ui-fg-error mt-1\">\n Reason: {conversation.block_reason}\n </Text>\n )}\n </div>\n <div className=\"px-6 py-3\">\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n Created\n </Text>\n <Text size=\"small\" leading=\"compact\">\n {conversation?.created_at\n ? new Date(conversation.created_at).toLocaleString()\n : \"-\"}\n </Text>\n </div>\n <div className=\"px-6 py-3\">\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n Last Activity\n </Text>\n <Text size=\"small\" leading=\"compact\">\n {conversation?.last_message_at\n ? new Date(conversation.last_message_at).toLocaleString()\n : \"-\"}\n </Text>\n </div>\n <div className=\"px-6 py-3\">\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n Message Count\n </Text>\n <Text size=\"small\" leading=\"compact\">\n {messages?.length ?? 0}\n </Text>\n </div>\n </Container>\n\n {/* Chat Block Management */}\n <Container className=\"mt-4 p-0\">\n <div className=\"px-6 py-4\">\n <Text size=\"small\" leading=\"compact\" weight=\"plus\">\n Chat Access\n </Text>\n </div>\n <div className=\"px-6 pb-4\">\n {showBlockDialog ? (\n <div className=\"flex flex-col gap-3\">\n <div>\n <Label size=\"xsmall\">Reason (optional)</Label>\n <Input\n size=\"small\"\n placeholder=\"Why is this customer being blocked?\"\n value={blockReason}\n onChange={(e) => setBlockReason(e.target.value)}\n />\n </div>\n <div className=\"flex gap-2\">\n <Button\n size=\"small\"\n variant=\"danger\"\n onClick={handleBlock}\n disabled={blockMutation.isPending}\n isLoading={blockMutation.isPending}\n >\n Confirm Block\n </Button>\n <Button\n size=\"small\"\n variant=\"secondary\"\n onClick={() => {\n setShowBlockDialog(false)\n setBlockReason(\"\")\n }}\n disabled={blockMutation.isPending}\n >\n Cancel\n </Button>\n </div>\n </div>\n ) : conversation?.is_buyer_blocked ? (\n <Button\n size=\"small\"\n variant=\"secondary\"\n onClick={handleUnblock}\n disabled={unblockMutation.isPending}\n isLoading={unblockMutation.isPending}\n >\n Unblock Customer\n </Button>\n ) : (\n <Button\n size=\"small\"\n variant=\"danger\"\n onClick={() => setShowBlockDialog(true)}\n >\n Block Customer\n </Button>\n )}\n </div>\n </Container>\n </div>\n </div>\n )\n}\n\nexport default AdminConversationDetailPage\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/routes/messages/filters/page.tsx",
"content": "import { useState } from \"react\"\nimport {\n Badge,\n Button,\n Container,\n Heading,\n Input,\n Label,\n Select,\n Switch,\n Text,\n toast,\n} from \"@medusajs/ui\"\n\nimport {\n useAdminFilters,\n useCreateFilter,\n useUpdateFilter,\n useDeleteFilter,\n FilterRuleDTO,\n} from \"../../../hooks/api/filters\"\n\nconst FilterRow = ({\n rule,\n onDelete,\n}: {\n rule: FilterRuleDTO\n onDelete: (id: string) => void\n}) => {\n const updateFilter = useUpdateFilter(rule.id)\n\n const handleToggle = (checked: boolean) => {\n updateFilter.mutate(\n { is_enabled: checked },\n { onSuccess: () => toast.success(`Rule ${checked ? \"enabled\" : \"disabled\"}`) }\n )\n }\n\n return (\n <div className=\"flex items-center gap-4 px-6 py-3\">\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-center gap-2\">\n <Badge color={rule.is_builtin ? \"purple\" : \"grey\"} size=\"2xsmall\">\n {rule.is_builtin ? \"Built-in\" : rule.match_type}\n </Badge>\n <Text size=\"small\" leading=\"compact\" weight=\"plus\" className=\"truncate\">\n {rule.pattern}\n </Text>\n </div>\n {rule.description && (\n <Text size=\"xsmall\" className=\"text-ui-fg-subtle mt-0.5\">\n {rule.description}\n </Text>\n )}\n </div>\n <div className=\"flex items-center gap-3 shrink-0\">\n <Switch\n checked={rule.is_enabled}\n onCheckedChange={handleToggle}\n disabled={updateFilter.isPending}\n />\n {!rule.is_builtin && (\n <Button\n size=\"small\"\n variant=\"danger\"\n onClick={() => onDelete(rule.id)}\n >\n Delete\n </Button>\n )}\n </div>\n </div>\n )\n}\n\nconst AdminFiltersPage = () => {\n const { filter_rules, isLoading, isError, error } = useAdminFilters()\n const createFilter = useCreateFilter()\n const deleteFilter = useDeleteFilter()\n\n const [showForm, setShowForm] = useState(false)\n const [formState, setFormState] = useState({\n match_type: \"exact\" as \"exact\" | \"contains\",\n pattern: \"\",\n description: \"\",\n })\n\n if (isError) throw error\n\n const handleCreate = () => {\n if (!formState.pattern.trim()) return\n createFilter.mutate(\n {\n match_type: formState.match_type,\n pattern: formState.pattern.trim(),\n description: formState.description || undefined,\n },\n {\n onSuccess: () => {\n setFormState({ match_type: \"exact\", pattern: \"\", description: \"\" })\n setShowForm(false)\n toast.success(\"Filter rule created\")\n },\n }\n )\n }\n\n const handleDelete = (id: string) => {\n deleteFilter.mutate(id, {\n onSuccess: () => toast.success(\"Filter rule deleted\"),\n })\n }\n\n return (\n <div className=\"flex flex-col gap-4\">\n <Container className=\"p-0\">\n <div className=\"flex items-center justify-between px-6 py-4\">\n <Heading>Content Filters</Heading>\n <Button size=\"small\" onClick={() => setShowForm(!showForm)}>\n {showForm ? \"Cancel\" : \"Add Rule\"}\n </Button>\n </div>\n\n {showForm && (\n <div className=\"border-t border-ui-border-base px-6 py-4\">\n <div className=\"grid grid-cols-2 gap-3\">\n <div>\n <Label size=\"xsmall\">Match Type</Label>\n <Select\n value={formState.match_type}\n onValueChange={(v) =>\n setFormState((s) => ({ ...s, match_type: v as any }))\n }\n >\n <Select.Trigger>\n <Select.Value />\n </Select.Trigger>\n <Select.Content>\n <Select.Item value=\"exact\">Exact Match</Select.Item>\n <Select.Item value=\"contains\">Contains</Select.Item>\n </Select.Content>\n </Select>\n </div>\n <div>\n <Label size=\"xsmall\">Pattern</Label>\n <Input\n size=\"small\"\n placeholder=\"Word or phrase to filter...\"\n value={formState.pattern}\n onChange={(e) =>\n setFormState((s) => ({ ...s, pattern: e.target.value }))\n }\n />\n </div>\n <div className=\"col-span-2\">\n <Label size=\"xsmall\">Description (optional)</Label>\n <Input\n size=\"small\"\n placeholder=\"Why this filter exists...\"\n value={formState.description}\n onChange={(e) =>\n setFormState((s) => ({ ...s, description: e.target.value }))\n }\n />\n </div>\n </div>\n <div className=\"mt-3\">\n <Button\n size=\"small\"\n onClick={handleCreate}\n disabled={!formState.pattern.trim() || createFilter.isPending}\n isLoading={createFilter.isPending}\n >\n Create Rule\n </Button>\n </div>\n </div>\n )}\n\n <div className=\"divide-y border-t border-ui-border-base\">\n {isLoading ? (\n <div className=\"flex items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">Loading...</Text>\n </div>\n ) : !filter_rules?.length ? (\n <div className=\"flex items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">No filter rules configured</Text>\n </div>\n ) : (\n filter_rules.map((rule) => (\n <FilterRow\n key={rule.id}\n rule={rule}\n onDelete={handleDelete}\n />\n ))\n )}\n </div>\n </Container>\n </div>\n )\n}\n\nexport default AdminFiltersPage\n",
"type": "registry:admin"
},
{
"path": "messaging/admin/routes/messages/blocked/page.tsx",
"content": "import { Badge, Container, Heading, Text } from \"@medusajs/ui\"\n\nimport { useAdminBlockedMessages, BlockedMessageDTO } from \"../../../hooks/api/filters\"\n\nconst formatDate = (dateStr: string): string => {\n return new Date(dateStr).toLocaleString()\n}\n\nconst BlockedRow = ({ log }: { log: BlockedMessageDTO }) => {\n return (\n <div className=\"px-6 py-3\">\n <div className=\"flex items-center justify-between\">\n <div className=\"flex items-center gap-2\">\n <Badge\n color={log.sender_type === \"customer\" ? \"blue\" : \"green\"}\n size=\"2xsmall\"\n >\n {log.sender_type}\n </Badge>\n <Text size=\"small\" leading=\"compact\" weight=\"plus\">\n {log.sender_id}\n </Text>\n </div>\n <Text size=\"xsmall\" className=\"text-ui-fg-muted\">\n {formatDate(log.created_at)}\n </Text>\n </div>\n <Text\n size=\"small\"\n leading=\"compact\"\n className=\"text-ui-fg-subtle mt-1 line-clamp-2\"\n >\n {log.message_body}\n </Text>\n </div>\n )\n}\n\nconst AdminBlockedMessagesPage = () => {\n const { blocked_messages, count, isLoading, isError, error } =\n useAdminBlockedMessages()\n\n if (isError) throw error\n\n return (\n <Container className=\"divide-y p-0\">\n <div className=\"flex items-center justify-between px-6 py-4\">\n <Heading>Blocked Messages</Heading>\n {count != null && (\n <Text size=\"small\" className=\"text-ui-fg-muted\">\n {count} total\n </Text>\n )}\n </div>\n {isLoading ? (\n <div className=\"flex items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">Loading...</Text>\n </div>\n ) : !blocked_messages?.length ? (\n <div className=\"flex items-center justify-center py-12\">\n <Text className=\"text-ui-fg-muted\">No blocked messages</Text>\n </div>\n ) : (\n <div className=\"divide-y\">\n {blocked_messages.map((log) => (\n <BlockedRow key={log.id} log={log} />\n ))}\n </div>\n )}\n </Container>\n )\n}\n\nexport default AdminBlockedMessagesPage\n",
"type": "registry:admin"
}
]
}