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
feat: add buyer-vendor messaging plugin (#829)
Kamil Jędrasd48ecced93e1
diff --git a/apps/docs/blocks.mdx b/apps/docs/blocks.mdxindex 31dd638d7..4db4f7707 100644--- a/apps/docs/blocks.mdx+++ b/apps/docs/blocks.mdx@@ -139,6 +139,21 @@ mode: "custom"</div></div>+ <div className="p-5 rounded-xl border border-gray-200 dark:border-gray-800">+ <div className="flex items-center gap-3 mb-1">+ <span className="text-base">✉️</span>+ <h3 className="font-semibold text-base m-0">messaging</h3>+ </div>+ <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">Buyer-vendor messaging with real-time SSE, content filtering, chat blocking, rate limiting, and admin oversight.</p>+ <div className="flex flex-wrap gap-1.5">+ <span className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 rounded px-2 py-0.5">module</span>+ <span className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 rounded px-2 py-0.5">workflow</span>+ <span className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 rounded px-2 py-0.5">api</span>+ <span className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 rounded px-2 py-0.5">admin</span>+ <span className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 rounded px-2 py-0.5">vendor</span>+ </div>+ </div>+</div><div className="mt-10 p-5 rounded-xl border border-gray-200 dark:border-gray-800">diff --git a/bun.lock b/bun.lockindex a2e81a763..0ee007378 100644--- a/bun.lock+++ b/bun.lock@@ -155,7 +155,7 @@},"packages/admin": {"name": "@mercurjs/admin",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@ariakit/react": "^0.4.15","@babel/runtime": "^7.26.10",@@ -215,7 +215,7 @@},"packages/cli": {"name": "@mercurjs/cli",- "version": "2.1.3",+ "version": "2.1.5","bin": {"mercurjs": "./dist/index.js",},@@ -226,7 +226,7 @@"@medusajs/admin-vite-plugin": "2.13.4","@medusajs/dashboard": "2.13.4","@medusajs/framework": "2.13.4",- "@mercurjs/dashboard-sdk": "2.1.3",+ "@mercurjs/dashboard-sdk": "2.1.5","@types/cross-spawn": "^6.0.6","@vitejs/plugin-react": "^4.2.1","autoprefixer": "^10.4.19",@@ -274,7 +274,7 @@},"packages/client": {"name": "@mercurjs/client",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@tanstack/react-query": "^5.64.2","qs": "^6.12.1",@@ -291,7 +291,7 @@},"packages/core": {"name": "@mercurjs/core",- "version": "2.1.3",+ "version": "2.1.5","devDependencies": {"@medusajs/cli": "^2.13.4","@medusajs/core-flows": "^2.13.4",@@ -335,7 +335,7 @@},"packages/dashboard-sdk": {"name": "@mercurjs/dashboard-sdk",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@babel/parser": "7.25.6","@babel/traverse": "7.25.6",@@ -352,7 +352,7 @@},"packages/dashboard-shared": {"name": "@mercurjs/dashboard-shared",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@ariakit/react": "^0.4.15","@babel/runtime": "^7.26.10",@@ -365,7 +365,7 @@"@medusajs/dashboard": "^2.13.4","@medusajs/icons": "2.13.4","@medusajs/ui": "4.1.1",- "@mercurjs/client": "2.1.3",+ "@mercurjs/client": "2.1.5","@radix-ui/react-dialog": "1.1.4","@radix-ui/react-dismissable-layer": "1.1.4","@tanstack/react-query": "5.64.2",@@ -406,7 +406,7 @@},"packages/providers/payout-stripe-connect": {"name": "@mercurjs/payout-stripe-connect",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"stripe": "^15.5.0",},@@ -421,7 +421,7 @@},"packages/registry": {"name": "@mercurjs/registry",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@hookform/resolvers": "3.4.2","@medusajs/core-flows": "^2.13.4",@@ -438,6 +438,7 @@"@tanstack/react-query": "5.64.2","@tanstack/react-table": "8.20.5","algoliasearch": "^5.40.0",+ "ioredis": "^5.10.1","jsonwebtoken": "9.0.2","meilisearch": "^0.47.0","react-hook-form": "7.49.1",@@ -460,11 +461,12 @@"@types/react-dom": "^18.2.22","@types/unzipper": "^0.10.10","jest": "^30.2.0",+ "vitest": "^4.1.2",},},"packages/types": {"name": "@mercurjs/types",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@medusajs/types": "2.13.4",},@@ -474,7 +476,7 @@},"packages/vendor": {"name": "@mercurjs/vendor",- "version": "2.1.3",+ "version": "2.1.5","dependencies": {"@ariakit/react": "^0.4.15","@babel/runtime": "^7.26.10",@@ -487,8 +489,8 @@"@medusajs/dashboard": "^2.13.4","@medusajs/icons": "2.13.4","@medusajs/ui": "4.1.1",- "@mercurjs/client": "2.1.3",- "@mercurjs/dashboard-shared": "2.1.3",+ "@mercurjs/client": "2.1.5",+ "@mercurjs/dashboard-shared": "2.1.5","@radix-ui/react-dialog": "1.1.4","@radix-ui/react-dismissable-layer": "1.1.4","@tanstack/react-query": "5.64.2",@@ -767,11 +769,11 @@"@dnd-kit/utilities": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="],- "@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.0", "tslib": "^2.4.0" } }, "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w=="],+ "@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],- "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw=="],+ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],- "@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg=="],+ "@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],"@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="],@@ -931,7 +933,7 @@"@internationalized/string": ["@internationalized/[email protected]", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-D4OHBjrinH+PFZPvfCXvG28n2LSykWcJ7GIioQL+ok0LON15SdfoUssoHzzOUmVZLbRoREsQXVzA6r8JKsbP6A=="],- "@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],+ "@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q=="],"@isaacs/cliui": ["@isaacs/[email protected]", "", {}, "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg=="],@@ -1177,7 +1179,7 @@"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],- "@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.4.3", "@emnapi/runtime": "^1.4.3", "@tybys/wasm-util": "^0.10.0" } }, "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ=="],+ "@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow=="],"@nodelib/fs.scandir": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],@@ -1261,6 +1263,8 @@"@opentelemetry/sql-common": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "^2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0" } }, "sha512-4mhWm3Z8z+i508zQJ7r6Xi7y4mmoJpdvH0fZPFRkWrdp5fq7hhZ2HhYokEOLkfqSMgPR4Z9EyB3DBkbKGOqZiQ=="],+ "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA=="],+"@oxlint/binding-android-arm-eabi": ["@oxlint/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-2r6Nq3XXGLHEXKkSj8JtmJ6N4gDw431DPFOg0ZoJHlNjnG6HVMm/ksQ10m0HJ8WBvwgMe1L50UHPaYZutCRPCw=="],"@oxlint/binding-android-arm64": ["@oxlint/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-ePJMpePgg7fBv+L/hVx1xXRU5/5gd5m0obLA6hPEfLXF3GjpR8idIDbY1dhQYhyz1ms2wdTccSboo6KEd2Oxtg=="],@@ -1639,6 +1643,36 @@"@remix-run/router": ["@remix-run/[email protected]", "", {}, "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w=="],+ "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw=="],++ "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA=="],++ "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg=="],++ "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g=="],++ "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw=="],++ "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw=="],++ "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q=="],++ "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg=="],++ "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg=="],++ "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg=="],++ "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow=="],++ "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg=="],++ "@rolldown/binding-wasm32-wasi": ["@rolldown/[email protected]", "", { "dependencies": { "@emnapi/core": "1.10.0", "@emnapi/runtime": "1.10.0", "@napi-rs/wasm-runtime": "^1.1.4" }, "cpu": "none" }, "sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg=="],++ "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g=="],++ "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA=="],+"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="],"@rollup/rollup-android-arm-eabi": ["@rollup/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg=="],@@ -1889,12 +1923,16 @@"@types/body-parser": ["@types/[email protected]", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="],+ "@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],+"@types/connect": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="],"@types/cors": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg=="],"@types/cross-spawn": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA=="],+ "@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],+"@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],"@types/express": ["@types/[email protected]", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^4.17.33", "@types/qs": "*", "@types/serve-static": "^1" } }, "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw=="],@@ -2045,6 +2083,20 @@"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="],+ "@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.8", "@vitest/utils": "4.1.8", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ=="],++ "@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "4.1.8", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw=="],++ "@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA=="],++ "@vitest/runner": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/utils": "4.1.8", "pathe": "^2.0.3" } }, "sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg=="],++ "@vitest/snapshot": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.1.8", "@vitest/utils": "4.1.8", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ=="],++ "@vitest/spy": ["@vitest/[email protected]", "", {}, "sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA=="],++ "@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.1.8", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg=="],+"@whatwg-node/promise-helpers": ["@whatwg-node/[email protected]", "", { "dependencies": { "tslib": "^2.6.3" } }, "sha512-Nst5JdK47VIl9UcGwtv2Rcgyn5lWtZ0/mhRQ4G8NN2isxpq2TO30iqHzmwoJycjWuyUfg3GFXqP/gFHXeV57IA=="],"accepts": ["[email protected]", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="],@@ -2093,6 +2145,8 @@"array-union": ["[email protected]", "", {}, "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw=="],+ "assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],+"async": ["[email protected]", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="],"asynckit": ["[email protected]", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="],@@ -2181,6 +2235,8 @@"cardinal": ["[email protected]", "", { "dependencies": { "ansicolors": "~0.3.2", "redeyed": "~2.1.0" }, "bin": { "cdl": "./bin/cdl.js" } }, "sha512-JSr5eOgoEymtYHBjNWyjrMqet9Am2miJhlfKNdqLp6zoeAh0KN5dRAcxlecj5mAJrmQomgiOBj35xHLrFjqBpw=="],+ "chai": ["[email protected]", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],+"chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],"change-case": ["[email protected]", "", { "dependencies": { "camel-case": "^4.1.2", "capital-case": "^1.0.4", "constant-case": "^3.0.4", "dot-case": "^3.0.4", "header-case": "^2.0.4", "no-case": "^3.0.4", "param-case": "^3.0.4", "pascal-case": "^3.1.2", "path-case": "^3.0.4", "sentence-case": "^3.0.4", "snake-case": "^3.0.4", "tslib": "^2.0.3" } }, "sha512-bSxY2ws9OtviILG1EiY5K7NNxkqg/JnRnFxLtKQ96JaviiIxi7djMrSd0ECT9AC+lttClmYwKw53BWpOMblo7A=="],@@ -2219,7 +2275,7 @@"clsx": ["[email protected]", "", {}, "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg=="],- "cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],+ "cluster-key-slot": ["[email protected]", "", {}, "sha512-rwHwUfXL40Chm1r08yrhU3qpUvdVlgkKNeyeGPOxnW8/SyVDvgRaed/Uz54AqWNaTCAThlj6QAs3TZcKI0xDEw=="],"cmdk": ["[email protected]", "", { "dependencies": { "@radix-ui/react-dialog": "1.0.0" }, "peerDependencies": { "react": "^18.0.0", "react-dom": "^18.0.0" } }, "sha512-U6//9lQ6JvT47+6OF6Gi8BvkxYQ8SCRRSKIJkthIMsFsLZRG0cKvTtuTaefyIKMQb8rvvXy0wGdpTNq/jPtm+g=="],@@ -2395,6 +2451,8 @@"es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],+ "es-module-lexer": ["[email protected]", "", {}, "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ=="],+"es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],"es-set-tostringtag": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="],@@ -2431,6 +2489,8 @@"estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],+ "estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],+"esutils": ["[email protected]", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],"etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],@@ -2447,6 +2507,8 @@"expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],+ "expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],+"express": ["[email protected]", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "~1.20.3", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.3.1", "fresh": "~0.5.2", "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", "qs": "~6.14.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", "serve-static": "~1.16.2", "setprototypeof": "1.2.0", "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g=="],"express-session": ["[email protected]", "", { "dependencies": { "cookie": "~0.7.2", "cookie-signature": "~1.0.7", "debug": "~2.6.9", "depd": "~2.0.0", "on-headers": "~1.1.0", "parseurl": "~1.3.3", "safe-buffer": "~5.2.1", "uid-safe": "~2.1.5" } }, "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA=="],@@ -2635,7 +2697,7 @@"invariant": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="],- "ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],+ "ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.10.0", "cluster-key-slot": "1.1.1", "debug": "4.4.3", "denque": "2.1.0", "redis-errors": "1.2.0", "redis-parser": "3.0.0", "standard-as-callback": "2.1.0" } }, "sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A=="],"ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],@@ -2809,6 +2871,30 @@"levn": ["[email protected]", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],+ "lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],++ "lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],++ "lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],++ "lightningcss-darwin-x64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="],++ "lightningcss-freebsd-x64": ["[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="],++ "lightningcss-linux-arm-gnueabihf": ["[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="],++ "lightningcss-linux-arm64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="],++ "lightningcss-linux-arm64-musl": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="],++ "lightningcss-linux-x64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="],++ "lightningcss-linux-x64-musl": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="],++ "lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="],++ "lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],+"lilconfig": ["[email protected]", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="],"lines-and-columns": ["[email protected]", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="],@@ -2989,6 +3075,8 @@"obliterator": ["[email protected]", "", {}, "sha512-9WXswnqINnnhOG/5SLimUlzuU1hFJUc8zkwyD59Sd+dPOMf05PmnYG/d6Q7HZ+KmgkZJa1PxRso6QdM3sTNHig=="],+ "obug": ["[email protected]", "", {}, "sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg=="],+"on-finished": ["[email protected]", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],"on-headers": ["[email protected]", "", {}, "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A=="],@@ -3083,7 +3171,7 @@"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],- "picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],+ "picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],"pify": ["[email protected]", "", {}, "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog=="],@@ -3241,6 +3329,8 @@"reusify": ["[email protected]", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],+ "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.133.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.0.3", "@rolldown/binding-darwin-arm64": "1.0.3", "@rolldown/binding-darwin-x64": "1.0.3", "@rolldown/binding-freebsd-x64": "1.0.3", "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", "@rolldown/binding-linux-arm64-gnu": "1.0.3", "@rolldown/binding-linux-arm64-musl": "1.0.3", "@rolldown/binding-linux-ppc64-gnu": "1.0.3", "@rolldown/binding-linux-s390x-gnu": "1.0.3", "@rolldown/binding-linux-x64-gnu": "1.0.3", "@rolldown/binding-linux-x64-musl": "1.0.3", "@rolldown/binding-openharmony-arm64": "1.0.3", "@rolldown/binding-wasm32-wasi": "1.0.3", "@rolldown/binding-win32-arm64-msvc": "1.0.3", "@rolldown/binding-win32-x64-msvc": "1.0.3" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g=="],+"rollup": ["[email protected]", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.59.0", "@rollup/rollup-android-arm64": "4.59.0", "@rollup/rollup-darwin-arm64": "4.59.0", "@rollup/rollup-darwin-x64": "4.59.0", "@rollup/rollup-freebsd-arm64": "4.59.0", "@rollup/rollup-freebsd-x64": "4.59.0", "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", "@rollup/rollup-linux-arm-musleabihf": "4.59.0", "@rollup/rollup-linux-arm64-gnu": "4.59.0", "@rollup/rollup-linux-arm64-musl": "4.59.0", "@rollup/rollup-linux-loong64-gnu": "4.59.0", "@rollup/rollup-linux-loong64-musl": "4.59.0", "@rollup/rollup-linux-ppc64-gnu": "4.59.0", "@rollup/rollup-linux-ppc64-musl": "4.59.0", "@rollup/rollup-linux-riscv64-gnu": "4.59.0", "@rollup/rollup-linux-riscv64-musl": "4.59.0", "@rollup/rollup-linux-s390x-gnu": "4.59.0", "@rollup/rollup-linux-x64-gnu": "4.59.0", "@rollup/rollup-linux-x64-musl": "4.59.0", "@rollup/rollup-openbsd-x64": "4.59.0", "@rollup/rollup-openharmony-arm64": "4.59.0", "@rollup/rollup-win32-arm64-msvc": "4.59.0", "@rollup/rollup-win32-ia32-msvc": "4.59.0", "@rollup/rollup-win32-x64-gnu": "4.59.0", "@rollup/rollup-win32-x64-msvc": "4.59.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg=="],"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],@@ -3287,6 +3377,8 @@"side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],+ "siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],+"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],"sisteransi": ["[email protected]", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="],@@ -3319,10 +3411,14 @@"stack-utils": ["[email protected]", "", { "dependencies": { "escape-string-regexp": "^2.0.0" } }, "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ=="],+ "stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],+"standard-as-callback": ["[email protected]", "", {}, "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="],"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],+ "std-env": ["[email protected]", "", {}, "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ=="],+"stdin-discarder": ["[email protected]", "", {}, "sha512-reExS1kSGoElkextOcPkel4NE99S0BWxjUHQeDFnR8S993JxpPX7KU4MNmO19NXhlJp+8dmdCbKQVNgLJh2teA=="],"stream-browserify": ["[email protected]", "", { "dependencies": { "inherits": "~2.0.4", "readable-stream": "^3.5.0" } }, "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA=="],@@ -3391,10 +3487,14 @@"tildify": ["[email protected]", "", {}, "sha512-Cc+OraorugtXNfs50hU9KS369rFXCfgGLpfCfvlc+Ud5u6VWmUQsOAa9HbTvheQdYnrdJqqv1e5oIqXppMYnSw=="],+ "tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],+"tinyexec": ["[email protected]", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="],"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],+ "tinyrainbow": ["[email protected]", "", {}, "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw=="],+"title-case": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.3" } }, "sha512-e1zGYRvbffpcHIrnuqT0Dh+gEJtDaxDSoG4JAIpq4oDFyooziLBIiYQv0GBT4FUAnUop5uZ1hiIAj7oAF6sOCA=="],"tmpl": ["[email protected]", "", {}, "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw=="],@@ -3511,6 +3611,8 @@"vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": { "vite": "bin/vite.js" } }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="],+ "vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.1.8", "@vitest/mocker": "4.1.8", "@vitest/pretty-format": "4.1.8", "@vitest/runner": "4.1.8", "@vitest/snapshot": "4.1.8", "@vitest/spy": "4.1.8", "@vitest/utils": "4.1.8", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.8", "@vitest/browser-preview": "4.1.8", "@vitest/browser-webdriverio": "4.1.8", "@vitest/coverage-istanbul": "4.1.8", "@vitest/coverage-v8": "4.1.8", "@vitest/ui": "4.1.8", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig=="],+"void-elements": ["[email protected]", "", {}, "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w=="],"wait-on": ["[email protected]", "", { "dependencies": { "axios": "^1.13.5", "joi": "^18.0.2", "lodash": "^4.17.23", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-k8qrgfwrPVJXTeFY8tl6BxVHiclK11u72DVKhpybHfUL/K6KM4bdyK9EhIVYGytB5MJe/3lq4Tf0hrjM+pvJZQ=="],@@ -3525,6 +3627,8 @@"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],+ "why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],+"widest-line": ["[email protected]", "", { "dependencies": { "string-width": "^4.0.0" } }, "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg=="],"winston": ["[email protected]", "", { "dependencies": { "@colors/colors": "^1.6.0", "@dabh/diagnostics": "^2.0.8", "async": "^3.2.3", "is-stream": "^2.0.0", "logform": "^2.7.0", "one-time": "^1.0.0", "readable-stream": "^3.4.0", "safe-stable-stringify": "^2.3.1", "stack-trace": "0.0.x", "triple-beam": "^1.3.0", "winston-transport": "^4.9.0" } }, "sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA=="],@@ -3699,6 +3803,10 @@"@medusajs/auth-google/jsonwebtoken": ["[email protected]", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],+ "@medusajs/cache-redis/ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],++ "@medusajs/caching-redis/ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],+"@medusajs/cli/execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],"@medusajs/cli/ora": ["[email protected]", "", { "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-spinners": "^2.5.0", "is-interactive": "^1.0.0", "is-unicode-supported": "^0.1.0", "log-symbols": "^4.1.0", "strip-ansi": "^6.0.0", "wcwidth": "^1.0.1" } }, "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ=="],@@ -3713,8 +3821,12 @@"@medusajs/draft-order/@medusajs/admin-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/admin-shared": "2.13.3", "zod": "3.25.76" } }, "sha512-XE7R2OLMsoLqnTh6GHxI8wShwv/j02pKxpOPc4/D+Zy133xy2XYfg+d8keI68V6t+HIrGHcIO04nju6psBhegw=="],+ "@medusajs/event-bus-redis/ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],+"@medusajs/framework/jsonwebtoken": ["[email protected]", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],+ "@medusajs/locking-redis/ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],+"@medusajs/medusa/jsonwebtoken": ["[email protected]", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],"@medusajs/payment/stripe": ["[email protected]", "", { "dependencies": { "qs": "^6.11.0" }, "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-FjgIiE98dMMTNssfdjMvFdD4eZyEzdWAOwPYqzhPRNZeg9ggFWlPXmX1iJKD5pPIwZBaPlC3SayQQkwsPo6/YQ=="],@@ -3725,6 +3837,8 @@"@medusajs/utils/jsonwebtoken": ["[email protected]", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],+ "@medusajs/workflow-engine-redis/ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],+"@mercurjs/admin/react-jwt": ["[email protected]", "", { "optionalDependencies": { "fsevents": "^2.3.2" }, "peerDependencies": { "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-aC+X6q8pi63zoO7A060/4mfF5jM6Ay+4YyY4QgdD8dDOqp89sPcg0IhWEHyPACnVETMjBWzmxMPgIPosQNeYyw=="],"@mercurjs/cli/@medusajs/admin-shared": ["@medusajs/[email protected]", "", {}, "sha512-pHfPibjFa8LiUxDUf64hFGXk0Q6jcg/yTpU/b9paOdxHowIUyVoOjubmmplpV8s0YDsacL8UioSFK2Js+vrutQ=="],@@ -3929,12 +4043,20 @@"@typescript-eslint/visitor-keys/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],+ "@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.4.3", "@emnapi/runtime": "^1.4.3", "@tybys/wasm-util": "^0.10.0" } }, "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ=="],++ "@vitest/mocker/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],++ "@vitest/snapshot/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],+"accepts/negotiator": ["[email protected]", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],"ajv-formats/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2", "uri-js": "^4.4.1" } }, "sha512-PRA911Blj99jR5RMeTunVbNXMF6Lp4vZXnk5GQjcnUWUTsrXtekg/pnmFFI2u/I36Y/2bITGS30GZCXei6uNkA=="],"ansi-align/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],+ "anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],+"babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],"babel-plugin-jest-hoist/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],@@ -3949,6 +4071,8 @@"boxen/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],+ "bullmq/ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],+"cli-progress/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],"cli-ux/ansi-escapes": ["[email protected]", "", { "dependencies": { "type-fest": "^0.21.3" } }, "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ=="],@@ -3995,8 +4119,6 @@"fast-glob/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],- "fdir/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"finalhandler/debug": ["[email protected]", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],"fix-dts-default-cjs-exports/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],@@ -4043,6 +4165,8 @@"jest-util/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],+ "jest-util/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],+"jest-watcher/ansi-escapes": ["[email protected]", "", { "dependencies": { "type-fest": "^0.21.3" } }, "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ=="],"jest-worker/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],@@ -4057,6 +4181,8 @@"make-dir/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],+ "micromatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],+"mime-types/mime-db": ["[email protected]", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],"minizlib/minipass": ["[email protected]", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="],@@ -4093,6 +4219,8 @@"restore-cursor/onetime": ["[email protected]", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],+ "rolldown/@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],+"send/debug": ["[email protected]", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],"source-map-support/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],@@ -4119,8 +4247,6 @@"tinyglobby/fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],- "tinyglobby/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"ts-node/diff": ["[email protected]", "", {}, "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ=="],"tsup/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.4", "@esbuild/android-arm": "0.27.4", "@esbuild/android-arm64": "0.27.4", "@esbuild/android-x64": "0.27.4", "@esbuild/darwin-arm64": "0.27.4", "@esbuild/darwin-x64": "0.27.4", "@esbuild/freebsd-arm64": "0.27.4", "@esbuild/freebsd-x64": "0.27.4", "@esbuild/linux-arm": "0.27.4", "@esbuild/linux-arm64": "0.27.4", "@esbuild/linux-ia32": "0.27.4", "@esbuild/linux-loong64": "0.27.4", "@esbuild/linux-mips64el": "0.27.4", "@esbuild/linux-ppc64": "0.27.4", "@esbuild/linux-riscv64": "0.27.4", "@esbuild/linux-s390x": "0.27.4", "@esbuild/linux-x64": "0.27.4", "@esbuild/netbsd-arm64": "0.27.4", "@esbuild/netbsd-x64": "0.27.4", "@esbuild/openbsd-arm64": "0.27.4", "@esbuild/openbsd-x64": "0.27.4", "@esbuild/openharmony-arm64": "0.27.4", "@esbuild/sunos-x64": "0.27.4", "@esbuild/win32-arm64": "0.27.4", "@esbuild/win32-ia32": "0.27.4", "@esbuild/win32-x64": "0.27.4" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ=="],@@ -4131,6 +4257,12 @@"v8-to-istanbul/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],+ "vitest/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],++ "vitest/tinyexec": ["[email protected]", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="],++ "vitest/vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", "postcss": "^8.5.15", "rolldown": "1.0.3", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.1.18", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw=="],+"widest-line/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],"winston/is-stream": ["[email protected]", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],@@ -4201,6 +4333,14 @@"@medusajs/auth-google/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],+ "@medusajs/cache-redis/ioredis/@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],++ "@medusajs/cache-redis/ioredis/cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],++ "@medusajs/caching-redis/ioredis/@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],++ "@medusajs/caching-redis/ioredis/cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],+"@medusajs/cli/execa/get-stream": ["[email protected]", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="],"@medusajs/cli/execa/human-signals": ["[email protected]", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="],@@ -4231,14 +4371,26 @@"@medusajs/draft-order/@medusajs/admin-sdk/@medusajs/admin-shared": ["@medusajs/[email protected]", "", {}, "sha512-FLZMxH2pBy8o5XJTifgMTxnY6W8ke1skXr3fX02APjiySCdmegiUnok8u70KGVRQNU7rfPyvApldh9ZffvDNxw=="],+ "@medusajs/event-bus-redis/ioredis/@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],++ "@medusajs/event-bus-redis/ioredis/cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],+"@medusajs/framework/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],+ "@medusajs/locking-redis/ioredis/@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],++ "@medusajs/locking-redis/ioredis/cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],+"@medusajs/medusa/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],"@medusajs/user/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],"@medusajs/utils/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],+ "@medusajs/workflow-engine-redis/ioredis/@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],++ "@medusajs/workflow-engine-redis/ioredis/cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],+"@mercurjs/core/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],"@mercurjs/core/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],@@ -4329,6 +4481,10 @@"@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg=="],+ "@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.0", "tslib": "^2.4.0" } }, "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w=="],++ "@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw=="],+"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],"babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],@@ -4337,6 +4493,10 @@"body-parser/debug/ms": ["[email protected]", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="],+ "bullmq/ioredis/@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],++ "bullmq/ioredis/cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],+"cli-ux/ansi-escapes/type-fest": ["[email protected]", "", {}, "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="],"cli-ux/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],@@ -4545,6 +4705,12 @@"tsx/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg=="],+ "vitest/vite/picomatch": ["[email protected]", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],++ "vitest/vite/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="],++ "vitest/vite/tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],+"yalc/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],"yalc/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],@@ -4567,6 +4733,8 @@"@jest/snapshot-utils/@jest/types/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],+ "@medusajs/admin-vite-plugin/chokidar/readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],+"@medusajs/auth-google/jsonwebtoken/jws/jwa": ["[email protected]", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],"@medusajs/cli/ora/cli-cursor/restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA=="],@@ -4709,6 +4877,8 @@"@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],+ "@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg=="],+"babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],"cmdk/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.13.10" }, "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0" } }, "sha512-GZtyzoHz95Rhs6S63D2t/eqvdFCm7I+yHMLVQheKM7nBD8mbZIt+ct1jz4536MDnaOGKIxynJ8eHTkVGVVkoTg=="],@@ -4731,6 +4901,12 @@"jest-cli/yargs/cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],+ "tailwindcss/chokidar/readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],++ "vitest/vite/postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ=="],++ "vitest/vite/tinyglobby/fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],+"@istanbuljs/load-nyc-config/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],"@medusajs/cli/ora/cli-cursor/restore-cursor/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],@@ -4769,10 +4945,6 @@"@mercurjs/integration-tests/jest/@jest/core/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/integration-tests/jest/@jest/core/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-- "@mercurjs/integration-tests/jest/@jest/core/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/@jest/core/jest-runner/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "30.3.0", "@jest/types": "30.3.0", "@types/node": "*", "jest-mock": "30.3.0" } }, "sha512-SlLSF4Be735yQXyh2+mctBOzNDx5s5uLv88/j8Qn1wH679PDcwy67+YdADn8NJnGjzlXtN62asGH/T4vWOkfaw=="],"@mercurjs/integration-tests/jest/@jest/core/jest-runner/jest-docblock": ["[email protected]", "", { "dependencies": { "detect-newline": "^3.1.0" } }, "sha512-tR/FFgZKS1CXluOQzZvNH3+0z9jXr3ldGSD8bhyuxvlVUwbeLOGynkunvlTMxchC5urrKndYiwCFC0DLVjpOCA=="],@@ -4809,8 +4981,6 @@"@mercurjs/integration-tests/jest/@jest/core/jest-snapshot/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "@jest/get-type": "30.1.0", "chalk": "^4.1.2", "jest-diff": "30.3.0", "pretty-format": "30.3.0" } }, "sha512-HEtc9uFQgaUHkC7nLSlQL3Tph4Pjxt/yiPvkIrrDCt9jhoLIgxaubo1G+CFOnmHYMxHwwdaSN7mkIFs6ZK8OhA=="],- "@mercurjs/integration-tests/jest/@jest/core/jest-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/@jest/core/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.34.0" } }, "sha512-DmdYgtezMkh3cpU8/1uyXakv3tJRcmcXxBOcO0tbaozPwpmh4YMsnWrQm9ZmZMfa5ocbxzbFk6O4bDPEc/iAnA=="],"@mercurjs/integration-tests/jest/@jest/core/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],@@ -4849,8 +5019,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-util/ci-info": ["[email protected]", "", {}, "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-validate/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "30.0.5", "ansi-styles": "^5.2.0", "react-is": "^18.3.1" } }, "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ=="],"@mercurjs/integration-tests/jest/jest-cli/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],@@ -4891,10 +5059,6 @@"@mercurjs/registry/jest/@jest/core/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/registry/jest/@jest/core/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-- "@mercurjs/registry/jest/@jest/core/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/@jest/core/jest-runner/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "30.3.0", "@jest/types": "30.3.0", "@types/node": "*", "jest-mock": "30.3.0" } }, "sha512-SlLSF4Be735yQXyh2+mctBOzNDx5s5uLv88/j8Qn1wH679PDcwy67+YdADn8NJnGjzlXtN62asGH/T4vWOkfaw=="],"@mercurjs/registry/jest/@jest/core/jest-runner/jest-docblock": ["[email protected]", "", { "dependencies": { "detect-newline": "^3.1.0" } }, "sha512-tR/FFgZKS1CXluOQzZvNH3+0z9jXr3ldGSD8bhyuxvlVUwbeLOGynkunvlTMxchC5urrKndYiwCFC0DLVjpOCA=="],@@ -4931,8 +5095,6 @@"@mercurjs/registry/jest/@jest/core/jest-snapshot/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "@jest/get-type": "30.1.0", "chalk": "^4.1.2", "jest-diff": "30.3.0", "pretty-format": "30.3.0" } }, "sha512-HEtc9uFQgaUHkC7nLSlQL3Tph4Pjxt/yiPvkIrrDCt9jhoLIgxaubo1G+CFOnmHYMxHwwdaSN7mkIFs6ZK8OhA=="],- "@mercurjs/registry/jest/@jest/core/jest-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/@jest/core/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.34.0" } }, "sha512-DmdYgtezMkh3cpU8/1uyXakv3tJRcmcXxBOcO0tbaozPwpmh4YMsnWrQm9ZmZMfa5ocbxzbFk6O4bDPEc/iAnA=="],"@mercurjs/registry/jest/@jest/core/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],@@ -4967,8 +5129,6 @@"@mercurjs/registry/jest/jest-cli/jest-util/ci-info": ["[email protected]", "", {}, "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg=="],- "@mercurjs/registry/jest/jest-cli/jest-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-validate/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "30.0.5", "ansi-styles": "^5.2.0", "react-is": "^18.3.1" } }, "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ=="],"@mercurjs/registry/jest/jest-cli/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],@@ -5347,16 +5507,12 @@"@mercurjs/integration-tests/jest/jest-cli/@jest/test-result/@jest/console/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],- "@mercurjs/integration-tests/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "30.0.5", "ansi-styles": "^5.2.0", "react-is": "^18.3.1" } }, "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/babel-jest/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@types/node": "*", "anymatch": "^3.1.3", "fb-watchman": "^2.0.2", "graceful-fs": "^4.2.11", "jest-regex-util": "30.0.1", "jest-util": "30.3.0", "jest-worker": "30.3.0", "picomatch": "^4.0.3", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.3" } }, "sha512-mMi2oqG4KRU0R9QEtscl87JzMXfUhbKaFqOxmjb2CKcbHcUGFrJCBWHmnTiUqi6JcnzoBlO4rWfpdl2k/RfLCA=="],@@ -5381,8 +5537,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "@jest/diff-sequences": "30.3.0", "@jest/get-type": "30.1.0", "chalk": "^4.1.2", "pretty-format": "30.3.0" } }, "sha512-n3q4PDQjS4LrKxfWB3Z5KNk1XjXtZTBwQp71OP0Jo03Z6V60x++K5L8k6ZrW8MY8pOFylZvHM0zsjS1RqlHJZQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@sinonjs/fake-timers": "^15.0.0", "@types/node": "*", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-WUQDs8SOP9URStX1DzhD425CqbN/HxUYCTwVrT8sTVBfMvFqYt/s61EK5T05qnHu0po6RitXIvP9otZxYDzTGQ=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "30.3.0", "@jest/expect": "30.3.0", "@jest/types": "30.3.0", "jest-mock": "30.3.0" } }, "sha512-+owLCBBdfpgL3HU+BD5etr1SvbXpSitJK0is1kiYjJxAAJggYMRQz5hSdd5pq1sSggfxPbw2ld71pt4x5wwViA=="],@@ -5419,8 +5573,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@sinonjs/fake-timers": "^15.0.0", "@types/node": "*", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-WUQDs8SOP9URStX1DzhD425CqbN/HxUYCTwVrT8sTVBfMvFqYt/s61EK5T05qnHu0po6RitXIvP9otZxYDzTGQ=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@types/node": "*", "jest-util": "30.3.0" } }, "sha512-OTzICK8CpE+t4ndhKrwlIdbM6Pn8j00lvmSmq5ejiO+KxukbLjgOflKWMn3KE34EZdQm5RqTuKj+5RIEniYhog=="],@@ -5433,10 +5585,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@sinonjs/fake-timers": "^15.0.0", "@types/node": "*", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-WUQDs8SOP9URStX1DzhD425CqbN/HxUYCTwVrT8sTVBfMvFqYt/s61EK5T05qnHu0po6RitXIvP9otZxYDzTGQ=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "30.3.0", "@jest/expect": "30.3.0", "@jest/types": "30.3.0", "jest-mock": "30.3.0" } }, "sha512-+owLCBBdfpgL3HU+BD5etr1SvbXpSitJK0is1kiYjJxAAJggYMRQz5hSdd5pq1sSggfxPbw2ld71pt4x5wwViA=="],@@ -5501,14 +5649,10 @@"@mercurjs/registry/jest/@jest/core/jest-runtime/glob/path-scurry/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],- "@mercurjs/registry/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "30.0.5", "ansi-styles": "^5.2.0", "react-is": "^18.3.1" } }, "sha512-oG4T3wCbfeuvljnyAzhBvpN45E8iOTXCU/TD3zXW80HA3dQ4ahdqMkWGiPWZvjpQwlbyHrPTWUAqUzGzv4l1JQ=="],"@mercurjs/registry/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/registry/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/babel-jest/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],"@mercurjs/registry/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@types/node": "*", "anymatch": "^3.1.3", "fb-watchman": "^2.0.2", "graceful-fs": "^4.2.11", "jest-regex-util": "30.0.1", "jest-util": "30.3.0", "jest-worker": "30.3.0", "picomatch": "^4.0.3", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.3" } }, "sha512-mMi2oqG4KRU0R9QEtscl87JzMXfUhbKaFqOxmjb2CKcbHcUGFrJCBWHmnTiUqi6JcnzoBlO4rWfpdl2k/RfLCA=="],@@ -5531,8 +5675,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "@jest/diff-sequences": "30.3.0", "@jest/get-type": "30.1.0", "chalk": "^4.1.2", "pretty-format": "30.3.0" } }, "sha512-n3q4PDQjS4LrKxfWB3Z5KNk1XjXtZTBwQp71OP0Jo03Z6V60x++K5L8k6ZrW8MY8pOFylZvHM0zsjS1RqlHJZQ=="],- "@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@sinonjs/fake-timers": "^15.0.0", "@types/node": "*", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-WUQDs8SOP9URStX1DzhD425CqbN/HxUYCTwVrT8sTVBfMvFqYt/s61EK5T05qnHu0po6RitXIvP9otZxYDzTGQ=="],"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "30.3.0", "@jest/expect": "30.3.0", "@jest/types": "30.3.0", "jest-mock": "30.3.0" } }, "sha512-+owLCBBdfpgL3HU+BD5etr1SvbXpSitJK0is1kiYjJxAAJggYMRQz5hSdd5pq1sSggfxPbw2ld71pt4x5wwViA=="],@@ -5565,8 +5707,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/registry/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@sinonjs/fake-timers": "^15.0.0", "@types/node": "*", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-WUQDs8SOP9URStX1DzhD425CqbN/HxUYCTwVrT8sTVBfMvFqYt/s61EK5T05qnHu0po6RitXIvP9otZxYDzTGQ=="],"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@types/node": "*", "jest-util": "30.3.0" } }, "sha512-OTzICK8CpE+t4ndhKrwlIdbM6Pn8j00lvmSmq5ejiO+KxukbLjgOflKWMn3KE34EZdQm5RqTuKj+5RIEniYhog=="],@@ -5577,10 +5717,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" } }, "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw=="],- "@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-- "@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@sinonjs/fake-timers": "^15.0.0", "@types/node": "*", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-WUQDs8SOP9URStX1DzhD425CqbN/HxUYCTwVrT8sTVBfMvFqYt/s61EK5T05qnHu0po6RitXIvP9otZxYDzTGQ=="],"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "30.3.0", "@jest/expect": "30.3.0", "@jest/types": "30.3.0", "jest-mock": "30.3.0" } }, "sha512-+owLCBBdfpgL3HU+BD5etr1SvbXpSitJK0is1kiYjJxAAJggYMRQz5hSdd5pq1sSggfxPbw2ld71pt4x5wwViA=="],@@ -5645,8 +5781,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/glob/jackspeak/@isaacs/cliui/string-width": ["[email protected]", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/glob/jackspeak/@isaacs/cliui/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],@@ -5671,8 +5805,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.3", "istanbul-lib-instrument": "^6.0.2", "test-exclude": "^6.0.0" } }, "sha512-D8Z6Qm8jCvVXtIRkBnqNHX0zJ37rQcFJ9u8WOS6tkYOsRdHBzypCstaxWiu5ZIlqQtviRYbgnRLSoCEvjqcqbA=="],@@ -5683,8 +5815,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-snapshot/expect/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@types/node": "*", "jest-util": "30.3.0" } }, "sha512-OTzICK8CpE+t4ndhKrwlIdbM6Pn8j00lvmSmq5ejiO+KxukbLjgOflKWMn3KE34EZdQm5RqTuKj+5RIEniYhog=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],@@ -5749,8 +5879,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/registry/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/glob/jackspeak/@isaacs/cliui/string-width": ["[email protected]", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],"@mercurjs/registry/jest/jest-cli/jest-config/glob/jackspeak/@isaacs/cliui/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],@@ -5775,8 +5903,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.3", "istanbul-lib-instrument": "^6.0.2", "test-exclude": "^6.0.0" } }, "sha512-D8Z6Qm8jCvVXtIRkBnqNHX0zJ37rQcFJ9u8WOS6tkYOsRdHBzypCstaxWiu5ZIlqQtviRYbgnRLSoCEvjqcqbA=="],@@ -5787,8 +5913,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-snapshot/expect/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "30.3.0", "@types/node": "*", "jest-util": "30.3.0" } }, "sha512-OTzICK8CpE+t4ndhKrwlIdbM6Pn8j00lvmSmq5ejiO+KxukbLjgOflKWMn3KE34EZdQm5RqTuKj+5RIEniYhog=="],- "@mercurjs/registry/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.1" } }, "sha512-cO5W33JgAPbOh07tvZjUOJ7oWhtaqGHiZw+11DPbyqh2kHTBc3eF/CjJDeQ4205RLQsX6rxCuYOroFQwl7JDRw=="],@@ -5851,8 +5975,6 @@"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker/supports-color/has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],"@mercurjs/integration-tests/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "30.3.0", "@jest/get-type": "30.1.0", "jest-matcher-utils": "30.3.0", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-1zQrciTiQfRdo7qJM1uG4navm8DayFa2TgCSRlzUyNkhcJ6XUZF3hjnpkyr3VhAqPH7i/9GkG7Tv5abz6fqz0Q=="],@@ -5893,8 +6015,6 @@"@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", "jest-util": "30.3.0", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" } }, "sha512-DrCKkaQwHexjRUFTmPzs7sHQe0TSj9nvDALKGdwmK5mW9v7j90BudWirKAJHt3QQ9Dhrg1F7DogPzhChppkJpQ=="],- "@mercurjs/registry/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map/picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],-"@mercurjs/registry/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker/supports-color/has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],"@mercurjs/registry/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "30.3.0", "@jest/get-type": "30.1.0", "jest-matcher-utils": "30.3.0", "jest-message-util": "30.3.0", "jest-mock": "30.3.0", "jest-util": "30.3.0" } }, "sha512-1zQrciTiQfRdo7qJM1uG4navm8DayFa2TgCSRlzUyNkhcJ6XUZF3hjnpkyr3VhAqPH7i/9GkG7Tv5abz6fqz0Q=="],diff --git a/packages/registry/package.json b/packages/registry/package.jsonindex c98a2fd65..c76aba92c 100644--- a/packages/registry/package.json+++ b/packages/registry/package.json@@ -31,7 +31,8 @@"react-jwt": "2.0.0","algoliasearch": "^5.40.0","meilisearch": "^0.47.0",- "@talkjs/react": "^0.1.11"+ "@talkjs/react": "^0.1.11",+ "ioredis": "^5.10.1"},"devDependencies": {"@mercurjs/types": "workspace:*",@@ -46,6 +47,7 @@"@swc/core": "^1.7.28","@swc/jest": "^0.2.36","@types/jest": "^29.5.13",- "jest": "^30.2.0"+ "jest": "^30.2.0",+ "vitest": "^4.1.2"}-}\ No newline at end of file+}diff --git a/packages/registry/r/messaging.json b/packages/registry/r/messaging.jsonnew file mode 100644index 000000000..e64fbdddd--- /dev/null+++ b/packages/registry/r/messaging.json@@ -0,0 +1,493 @@+{+ "$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"+ }+ ]+}\ No newline at end of filediff --git a/packages/registry/r/registry.json b/packages/registry/r/registry.jsonindex e7205bff8..2078142bc 100644--- a/packages/registry/r/registry.json+++ b/packages/registry/r/registry.json@@ -797,6 +797,116 @@"vendor"]},+ {+ "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```",+ "files": [+ { "path": "messaging/modules/messaging/index.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/service.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/models/conversation.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/models/message.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/models/chat-block.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/types/common.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/types/mutations.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/index.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/service.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/models/filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/models/blocked-message-log.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/types/common.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/loaders/compile-filters.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/loaders/seed-builtin-rules.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-redis/index.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-redis/service.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-redis/loaders/connection.ts", "type": "registry:api" },+ { "path": "messaging/links/conversation-seller.ts", "type": "registry:api" },+ { "path": "messaging/links/conversation-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/validate-rate-limit.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/validate-content-filter.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/create-message.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/publish-message-event.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/create-conversation.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/mark-messages-read.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/anonymize-messages-batch.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/validate-chat-block.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/block-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/unblock-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/send-message.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/create-conversation.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/mark-messages-read.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/anonymize-buyer-messages.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/anonymize-vendor-messages.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/block-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/unblock-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/create-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/update-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/delete-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/invalidate-filter-cache.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/workflows/create-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/workflows/update-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/workflows/delete-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/query-config.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/helpers.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/middlewares.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/[id]/read/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/unread/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/sse-token/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/events/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/query-config.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/middlewares.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/[id]/read/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/unread/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/events/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/query-config.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/middlewares.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/events/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/filters/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/filters/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/filters/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/blocked/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/chat-blocks/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/chat-blocks/[customer_id]/route.ts", "type": "registry:api" },+ { "path": "messaging/subscribers/message-notification.ts", "type": "registry:api" },+ { "path": "messaging/subscribers/buyer-deletion.ts", "type": "registry:api" },+ { "path": "messaging/subscribers/vendor-removal.ts", "type": "registry:api" },+ { "path": "messaging/jobs/reconcile-unread-counts.ts", "type": "registry:api" },+ { "path": "messaging/jobs/cleanup-blocked-messages.ts", "type": "registry:api" },+ { "path": "messaging/vendor/lib/client.ts", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/use-messaging-layout.ts", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/api/messaging.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/api/use-messaging-sse.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/table/columns/use-conversation-table-columns.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/table/query/use-conversation-table-query.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/routes/messages/page.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/routes/messages/[id]/page.tsx", "type": "registry:vendor" },+ { "path": "messaging/admin/lib/client.ts", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/use-messaging-layout.ts", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/api/messaging.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/api/filters.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/api/use-admin-messaging-sse.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/page.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/[id]/page.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/filters/page.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/blocked/page.tsx", "type": "registry:admin" }+ ],+ "categories": [+ "messaging",+ "api",+ "vendor",+ "admin"+ ]+ },{"name": "meilisearch","description": "Opt-in Meilisearch search block for multi-vendor marketplaces with real-time seller-aware indexing, seller lifecycle sync, and injection-safe smart filtering.",diff --git a/packages/registry/registry.json b/packages/registry/registry.jsonindex e7205bff8..2078142bc 100644--- a/packages/registry/registry.json+++ b/packages/registry/registry.json@@ -797,6 +797,116 @@"vendor"]},+ {+ "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```",+ "files": [+ { "path": "messaging/modules/messaging/index.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/service.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/models/conversation.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/models/message.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/models/chat-block.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/types/common.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging/types/mutations.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/index.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/service.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/models/filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/models/blocked-message-log.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/types/common.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/loaders/compile-filters.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-filters/loaders/seed-builtin-rules.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-redis/index.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-redis/service.ts", "type": "registry:api" },+ { "path": "messaging/modules/messaging-redis/loaders/connection.ts", "type": "registry:api" },+ { "path": "messaging/links/conversation-seller.ts", "type": "registry:api" },+ { "path": "messaging/links/conversation-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/validate-rate-limit.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/validate-content-filter.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/create-message.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/publish-message-event.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/create-conversation.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/mark-messages-read.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/anonymize-messages-batch.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/validate-chat-block.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/block-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/steps/unblock-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/send-message.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/create-conversation.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/mark-messages-read.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/anonymize-buyer-messages.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/anonymize-vendor-messages.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/block-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging/workflows/unblock-customer.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/create-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/update-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/delete-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/steps/invalidate-filter-cache.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/workflows/create-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/workflows/update-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/workflows/messaging-filters/workflows/delete-filter-rule.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/query-config.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/helpers.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/middlewares.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/[id]/read/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/unread/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/sse-token/route.ts", "type": "registry:api" },+ { "path": "messaging/api/store/messages/events/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/query-config.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/middlewares.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/[id]/read/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/unread/route.ts", "type": "registry:api" },+ { "path": "messaging/api/vendor/messages/events/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/query-config.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/middlewares.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/events/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/filters/validators.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/filters/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/filters/[id]/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/blocked/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/chat-blocks/route.ts", "type": "registry:api" },+ { "path": "messaging/api/admin/messages/chat-blocks/[customer_id]/route.ts", "type": "registry:api" },+ { "path": "messaging/subscribers/message-notification.ts", "type": "registry:api" },+ { "path": "messaging/subscribers/buyer-deletion.ts", "type": "registry:api" },+ { "path": "messaging/subscribers/vendor-removal.ts", "type": "registry:api" },+ { "path": "messaging/jobs/reconcile-unread-counts.ts", "type": "registry:api" },+ { "path": "messaging/jobs/cleanup-blocked-messages.ts", "type": "registry:api" },+ { "path": "messaging/vendor/lib/client.ts", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/use-messaging-layout.ts", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/api/messaging.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/api/use-messaging-sse.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/table/columns/use-conversation-table-columns.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/hooks/table/query/use-conversation-table-query.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/routes/messages/page.tsx", "type": "registry:vendor" },+ { "path": "messaging/vendor/routes/messages/[id]/page.tsx", "type": "registry:vendor" },+ { "path": "messaging/admin/lib/client.ts", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/use-messaging-layout.ts", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/api/messaging.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/api/filters.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/hooks/api/use-admin-messaging-sse.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/page.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/[id]/page.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/filters/page.tsx", "type": "registry:admin" },+ { "path": "messaging/admin/routes/messages/blocked/page.tsx", "type": "registry:admin" }+ ],+ "categories": [+ "messaging",+ "api",+ "vendor",+ "admin"+ ]+ },{"name": "meilisearch","description": "Opt-in Meilisearch search block for multi-vendor marketplaces with real-time seller-aware indexing, seller lifecycle sync, and injection-safe smart filtering.",diff --git a/packages/registry/src/messaging/DOCUMENTATION.md b/packages/registry/src/messaging/DOCUMENTATION.mdnew file mode 100644index 000000000..78ead7b10--- /dev/null+++ b/packages/registry/src/messaging/DOCUMENTATION.md@@ -0,0 +1,1596 @@+# Messaging Plugin Documentation++Buyer-vendor messaging system with real-time SSE delivery, content filtering, admin oversight, chat blocking, GDPR erasure, cursor-based pagination, and dashboard UI for both vendor and admin panels.++---++## Table of Contents++1. [Architecture Overview](#architecture-overview)+2. [Installation & Configuration](#installation--configuration)+3. [Modules](#modules)+ - [Messaging Module](#messaging-module)+ - [Messaging Filters Module](#messaging-filters-module)+ - [Messaging Redis Module](#messaging-redis-module)+4. [Data Models](#data-models)+5. [Module Links](#module-links)+6. [Workflows](#workflows)+7. [API Reference — Store (Customer)](#api-reference--store-customer)+8. [API Reference — Vendor (Seller)](#api-reference--vendor-seller)+9. [API Reference — Admin](#api-reference--admin)+10. [SSE Real-Time Event System](#sse-real-time-event-system)+11. [Cursor-Based Pagination](#cursor-based-pagination)+12. [Content Filtering](#content-filtering)+13. [Rate Limiting](#rate-limiting)+14. [Context Linking](#context-linking)+15. [Unread Tracking](#unread-tracking)+16. [GDPR & Data Privacy](#gdpr--data-privacy)+17. [Chat Blocking](#chat-blocking)+18. [Event Subscribers](#event-subscribers)+19. [Scheduled Jobs](#scheduled-jobs)+20. [Error Reference](#error-reference)+21. [Testing](#testing)+22. [Configuration Reference](#configuration-reference)++---++## Architecture Overview++```+┌─────────────────────────────────────────────────────────────────────┐+│ API Layer │+│ Store (Customer) Vendor (Seller) Admin │+│ /store/messages/* /vendor/messages/* /admin/messages/*│+└──────────┬─────────────────────┬────────────────────────┬───────────┘+ │ │ │+ ▼ ▼ ▼+┌─────────────────────────────────────────────────────────────────────┐+│ Workflows │+│ send-message │ create-conversation │ mark-messages-read │+│ anonymize-buyer │ anonymize-vendor │ filter-rule CRUD │+│ block-customer │ unblock-customer │+└──────────┬──────────────────────────────────────────────────────────┘+ │+ ▼+┌────────────────────┐ ┌─────────────────────┐ ┌──────────────────┐+│ Messaging Module │ │ Messaging Filters │ │ Messaging Redis │+│ - Conversation │ │ - FilterRule │ │ - Pub/Sub │+│ - Message │ │ - BlockedMessageLog │ │ - Rate Limiting │+│ - ChatBlock │ │ - Evaluation │ │ - SSE Tokens │+│ - CRUD + Cursors │ │ │ │ │+└────────────────────┘ └─────────────────────┘ └──────────────────┘+ │ │+ ▼ ▼+ PostgreSQL Redis+```++The plugin follows Medusa's architecture strictly:++- **Modules** handle data access and CRUD operations only+- **Workflows** contain all business logic, validation, and side effects+- **API Routes** handle HTTP concerns, delegate to workflows+- **Subscribers** react to domain events asynchronously+- **Scheduled Jobs** perform periodic maintenance++Three actor types interact with the system:++| Actor | Auth Method | Capabilities |+|-------|-------------|-------------|+| Customer (Buyer) | Session / Bearer | Create conversations, send messages, mark read, SSE via token |+| Seller (Vendor) | Session / Bearer | List conversations, reply, mark read, SSE via session |+| Admin | Session / Bearer | Search all conversations, manage filters, view blocked messages, block/unblock customers, SSE (all events) |++---++## Installation & Configuration++### Install the block++```bash+mercurjs add messaging+```++### Dependencies++| Dependency | Purpose |+|-----------|---------|+| `ioredis` | Redis client for pub/sub, rate limiting, SSE tokens |++Redis is **optional but strongly recommended**. Without it, SSE, rate limiting, and notification throttling are disabled. Core REST messaging (send, receive, mark read) and content filtering continue to work.++### Environment variables++```+REDIS_URL=redis://localhost:6379+```++### Module registration++```typescript+// medusa-config.ts+module.exports = defineConfig({+ modules: [+ { resolve: "./modules/messaging" },+ { resolve: "./modules/messaging-filters" },+ {+ resolve: "./modules/messaging-redis",+ options: { redisUrl: process.env.REDIS_URL },+ },+ ],+})+```++### Run migrations++```bash+npx medusa db:migrate+```++This creates the `conversation`, `message`, `chat_block`, `filter_rule`, and `blocked_message_log` tables.++---++## Modules++### Messaging Module++**Identifier**: `messaging`++Core module handling conversations and messages. Provides cursor-based pagination, atomic message creation, and atomic read marking.++#### Service: `MessagingModuleService`++```typescript+// Cursor-paginated conversation listing+listConversationsCursor(+ filter: { buyer_id?: string; seller_id?: string },+ pagination: { cursor?: string; limit?: number }+): Promise<{ data: ConversationDTO[]; next_cursor: string | null }>++// Cursor-paginated message listing (descending order)+listMessagesCursor(+ conversationId: string,+ pagination: { cursor?: string; limit?: number }+): Promise<{ data: MessageDTO[]; next_cursor: string | null }>++// Admin search with filtering across seller/buyer names, dates, context+searchConversationsAdmin(+ filter: {+ seller_name?: string; buyer_name?: string;+ date_from?: string; date_to?: string;+ context_type?: string; context_id?: string+ },+ pagination: { cursor?: string; limit?: number }+): Promise<{ data: ConversationDTO[]; next_cursor: string | null }>++// Total unread count across all conversations for a user+getUnreadCountTotal(+ filter: { buyer_id?: string; seller_id?: string }+): Promise<number>++// Atomic: creates message + updates conversation metadata + increments unread+createMessageAtomic(data: {+ conversation_id: string; sender_id: string; sender_type: SenderType;+ body: string; context_type?: string; context_id?: string; context_label?: string;+}): Promise<MessageDTO>++// Atomic: marks opposite-party messages as read + resets unread counter+markMessagesReadAtomic(+ conversationId: string,+ readerType: "customer" | "seller"+): Promise<number> // count of messages marked++// Cursor encoding/decoding+encodeCursor(values: Record<string, string | number | null>): string+decodeCursor(cursor: string): Record<string, string | number | null> | null+```++```typescript+// Batch check which buyer IDs are chat-blocked (single WHERE IN query)+checkBuyersBlocked(+ buyerIds: string[]+): Promise<Set<string>>+```++Also inherits standard `MedusaService` CRUD methods: `listConversations`, `createConversations`, `updateConversations`, `deleteConversations`, `listMessages`, `createMessages`, `updateMessages`, `deleteMessages`, `listChatBlocks`, `createChatBlocks`, `deleteChatBlocks`.++---++### Messaging Filters Module++**Identifier**: `messagingFilters`++Manages content filter rules and blocked message logging. Compiles rules into an optimized in-memory structure for fast evaluation.++#### Service: `MessagingFiltersModuleService`++```typescript+// Evaluate a message body against the compiled ruleset+evaluateMessage(+ body: string,+ ruleset: CompiledRuleset+): FilterEvaluationResult+// Returns: { matched: boolean, rule_id?, match_type?, pattern? }+// Priority: exact > contains > regex (short-circuits on first match)+```++Inherits standard CRUD: `listFilterRules`, `createFilterRules`, `updateFilterRules`, `deleteFilterRules`, `listAndCountFilterRules`, `listAndCountBlockedMessageLogs`, `createBlockedMessageLogs`.++#### Compiled Ruleset Structure++```typescript+interface CompiledRuleset {+ exactWords: Set<string> // Lowercase words for O(1) lookup+ exactRules: Map<string, string> // word → rule_id+ containsPatterns: Array<{ id: string; pattern: string }> // Lowercase+ regexPatterns: Array<{ id: string; regex: RegExp }>+}+```++Compilation happens at module startup and is recompiled when rules change via admin CRUD workflows. Each workflow step (`invalidateFilterCacheStep`) recompiles the local in-memory cache and publishes to the Redis `filter_rules_changed` channel for future cross-instance support. Currently, filter recompilation is per-instance only — if running multiple instances, a restart or rule change on each instance is needed to refresh the cache.++#### Built-in Filter Rules++Seeded automatically on first startup:++| Rule | Type | Pattern | Purpose |+|------|------|---------|---------|+| Email addresses | Regex | `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}` | Keep communication on-platform |+| Phone numbers | Regex | Various international formats | Prevent off-platform contact |+| URLs | Regex | `https?://[^\s]+\|www\.[^\s]+` | Block spam and phishing |++Built-in rules cannot be deleted or have their pattern modified. Only `is_enabled` and `description` can be changed.++---++### Messaging Redis Module++**Identifier**: `messagingRedis`++Provides Redis-backed infrastructure for real-time features. All methods degrade gracefully if Redis is unavailable.++#### Service: `MessagingRedisModuleService`++```typescript+// Connection status+get isAvailable(): boolean++// SSE token management (one-time tokens with TTL)+setToken(token: string, value: string, ttlSeconds: number): Promise<void>+consumeToken(token: string): Promise<string | null> // Deletes after reading++// Sliding window rate limiting+checkRateLimit(+ key: string, limit: number, windowSeconds: number+): Promise<{ allowed: boolean; count: number }>++// Pub/Sub+publish(channel: string, data: Record<string, unknown>): Promise<void>+createSubscriber(): Redis | null++// Notification throttle (SET NX EX)+trySetThrottle(key: string, ttlSeconds: number): Promise<boolean>+```++#### Redis Connection++```typescript+// Connection options+{+ lazyConnect: true,+ maxRetriesPerRequest: 3,+ retryStrategy: exponential backoff (max 5 retries, 2000ms cap)+}+```++If `REDIS_URL` is not provided or connection fails, the module registers a null connection and all Redis-dependent features are silently skipped.++---++## Data Models++### Conversation++| Field | Type | Constraints |+|-------|------|-------------|+| `id` | string | Primary key, prefix: `conv` |+| `buyer_id` | string | Required |+| `seller_id` | string | Required |+| `last_message_preview` | string \| null | Max 100 chars, auto-truncated |+| `last_message_sender_type` | `"customer"` \| `"seller"` \| null | |+| `last_message_at` | datetime \| null | Updated on each message |+| `unread_count_customer` | number | Default: 0 |+| `unread_count_seller` | number | Default: 0 |+| `created_at` | datetime | Auto |+| `updated_at` | datetime | Auto |+| `deleted_at` | datetime \| null | Soft delete |++**Indexes**:+- `UNIQUE (buyer_id, seller_id)` — one conversation per buyer-seller pair+- `(seller_id, last_message_at, id)` — vendor conversation listing+- `(buyer_id, last_message_at, id)` — buyer conversation listing++**Relationship**: `messages` — hasMany → Message++### Message++| Field | Type | Constraints |+|-------|------|-------------|+| `id` | string | Primary key, prefix: `msg` |+| `conversation_id` | string | Foreign key → Conversation |+| `sender_id` | string | Customer or seller ID |+| `sender_type` | `"customer"` \| `"seller"` | |+| `body` | string | 1–2000 characters |+| `context_type` | `"product"` \| `"order"` \| null | |+| `context_id` | string \| null | Product or order ID |+| `context_label` | string \| null | Resolved label (product title or "Order #XYZ") |+| `read_at` | datetime \| null | Set when recipient reads |+| `created_at` | datetime | Auto |+| `updated_at` | datetime | Auto |+| `deleted_at` | datetime \| null | Soft delete |++**Indexes**:+- `(conversation_id, created_at, id)` — message pagination within conversation+- `(context_type, context_id)` — context lookups+- `(created_at)` — global ordering++### FilterRule++| Field | Type | Constraints |+|-------|------|-------------|+| `id` | string | Primary key, prefix: `filt` |+| `match_type` | `"exact"` \| `"contains"` \| `"regex"` | Custom rules: only `exact` or `contains` |+| `pattern` | string | 1–500 characters |+| `is_builtin` | boolean | Default: false. Built-in rules protected |+| `is_enabled` | boolean | Default: true |+| `description` | string \| null | Max 500 characters |+| `created_at` | datetime | Auto |+| `updated_at` | datetime | Auto |+| `deleted_at` | datetime \| null | Soft delete |++### BlockedMessageLog++| Field | Type | Constraints |+|-------|------|-------------|+| `id` | string | Primary key, prefix: `bml` |+| `sender_id` | string | Who sent the blocked message |+| `sender_type` | `"customer"` \| `"seller"` | |+| `conversation_id` | string | Where it was sent |+| `matched_rule_id` | string | Which rule blocked it |+| `message_body` | string | Full original message text |+| `created_at` | datetime | Auto |+| `updated_at` | datetime | Auto |+| `deleted_at` | datetime \| null | Soft delete |++**Retention**: 30 days (cleaned up daily at 4 AM).++### ChatBlock++| Field | Type | Constraints |+|-------|------|-------------|+| `id` | string | Primary key, prefix: `cblk` |+| `customer_id` | string | Required |+| `blocked_by` | string | Admin user ID who blocked |+| `reason` | string \| null | Optional reason for blocking |+| `created_at` | datetime | Auto |+| `updated_at` | datetime | Auto |+| `deleted_at` | datetime \| null | Soft delete |++**Indexes**:+- `UNIQUE (customer_id)` where `deleted_at IS NULL` — one active block per customer++A customer is either blocked or not — blocking is account-wide for chat (not per-conversation). The `blocked_by` field provides admin accountability. The unique index with a `deleted_at IS NULL` condition allows re-blocking after unblocking without conflicts.++---++## Module Links++### Conversation ↔ Customer++Links the `customer` module to `conversation`. One customer has many conversations. Enables `query.graph()` traversal from customer to their conversations.++### Conversation ↔ Seller++Links the `seller` module to `conversation`. One seller has many conversations. Enables `query.graph()` traversal from seller to their conversations.++---++## Workflows++### `sendMessageWorkflow`++Creates a message in a conversation with full validation pipeline.++**Input**:+```typescript+{+ conversation_id: string+ sender_id: string+ sender_type: "customer" | "seller"+ body: string // 1–2000 chars+ context_type?: "product" | "order"+ context_id?: string+ context_label?: string // Pre-resolved by route+ recipient_id: string+ is_new_conversation: boolean+}+```++**Steps**:+1. **validateChatBlockStep** — Checks if the customer (buyer) in this conversation is chat-blocked. Blocks both directions: blocked customers cannot send, and no one can send to a blocked customer.+2. **validateRateLimitStep** — Checks 10 msg/60s and (if new conversation) 5 conv/3600s+3. **validateContentFilterStep** — Evaluates against compiled ruleset, logs blocked+4. **createMessageStep** — Atomic insert + conversation metadata update + unread increment+5. **publishMessageEventStep** — Publishes `new_message` to Redis pub/sub+6. **emitEventStep** — Emits `messaging.message.created` Medusa event++**Output**: `MessageDTO`++**Compensation**: Step 3 deletes the message on rollback.++---++### `createConversationWorkflow`++Creates a new buyer-seller conversation with module links.++**Input**: `{ buyer_id: string, seller_id: string }`++**Steps**:+1. **createConversationStep** — Creates conversation (unique constraint on buyer_id + seller_id)+2. **createRemoteLinkStep** — Links conversation to customer and seller modules++**Output**: `ConversationDTO`++**Compensation**: Step 1 deletes the conversation on rollback.++---++### `markMessagesReadWorkflow`++Marks all unread messages from the opposite party as read and publishes notification events.++**Input**:+```typescript+{+ conversation_id: string+ reader_id: string+ reader_type: "customer" | "seller"+ sender_id: string // The opposite party+}+```++**Steps**:+1. **markMessagesReadStep** — Atomic: sets `read_at` on unread messages + resets reader's unread count+2. **publishMessageEventStep** (`messages_read`) — Notifies sender their messages were read+3. **publishMessageEventStep** (`unread_count`) — Confirms count reset to reader++**Output**: `{ conversation_id, updated: number }`++---++### `anonymizeBuyerMessagesWorkflow`++GDPR right-to-erasure handler for buyer deletion.++**Input**: `{ buyer_id: string }`++**Steps**:+1. Find all conversations where `buyer_id` matches (paginated, batch size: 100)+2. Update `buyer_id` to `deleted_{buyer_id}`+3. Set all message bodies to `"[Message removed]"` (paginated, batch size: 100)++**Compensation**:+- Step 1 (find conversations): restores original `buyer_id` on all matched conversations+- Step 2 (anonymize messages): logs a warning — message body replacement is irreversible++---++### `anonymizeVendorMessagesWorkflow`++Vendor offboarding handler.++**Input**: `{ seller_id: string }`++**Steps**:+1. Find all conversations where `seller_id` matches (paginated, batch size: 100)+2. Update `seller_id` to `deleted_{seller_id}`+3. **Message bodies are preserved** (vendor content remains per specification)++**Compensation**:+- Step 1 (find conversations): restores original `seller_id` on all matched conversations++---++### Filter Rule Workflows++| Workflow | Input | Behavior |+|----------|-------|----------|+| `createFilterRuleWorkflow` | `{ match_type, pattern, description?, is_enabled? }` | Creates rule, rejects regex type, invalidates cache |+| `updateFilterRuleWorkflow` | `{ id, match_type?, pattern?, description?, is_enabled? }` | Updates rule, blocks pattern change on built-in rules |+| `deleteFilterRuleWorkflow` | `{ id }` | Soft-deletes rule, blocks deletion of built-in rules |++All three recompile the local in-memory filter cache and publish `filter_rules_changed` to Redis (best-effort, for future cross-instance support).++---++### `blockCustomerWorkflow`++Blocks a customer from chat. Idempotent — blocking an already-blocked customer returns the existing block record.++**Input**:+```typescript+{+ customer_id: string // Customer to block+ blocked_by: string // Admin user ID performing the block+ reason?: string | null // Optional reason+}+```++**Steps**:+1. **blockCustomerStep** — Checks for existing block (idempotent). If none exists, creates a `ChatBlock` record.++**Output**: `ChatBlockDTO`++**Compensation**: Deletes the created block record on rollback.++---++### `unblockCustomerWorkflow`++Removes a chat block from a customer. Succeeds silently if the customer is not blocked.++**Input**:+```typescript+{+ customer_id: string // Customer to unblock+}+```++**Steps**:+1. **unblockCustomerStep** — Finds and soft-deletes the existing `ChatBlock` record.++**Output**: `null`++**Compensation**: Re-creates the deleted block record on rollback.++---++## API Reference — Store (Customer)++All store endpoints require customer authentication via session or bearer token.++### `POST /store/messages` — Create conversation++Creates a new conversation with a seller (or returns existing) and optionally sends the first message.++**Request body**:+```typescript+{+ seller_id: string // Required+ body?: string // 1–2000 chars, optional+ context_type?: "product" | "order" // Optional+ context_id?: string // Required if context_type set+}+```++Validation: `context_type` and `context_id` must both be set or both omitted.++**Response** `200`:+```typescript+{+ conversation: {+ id: string+ seller_id: string+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_customer: number+ created_at: string+ }+ message?: {+ id: string+ sender_type: "customer"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: null+ created_at: string+ }+}+```++**Behavior**:+- **Block check**: If the customer is chat-blocked, returns `not_allowed` error before any conversation/message processing+- If conversation exists between buyer and seller, returns it (no duplicate)+- If `body` provided: validates block → validates rate limit → validates content filter → creates message+- Resolves context labels: product title or "Order #display_id"++---++### `GET /store/messages` — List conversations++**Query parameters**:++| Param | Type | Default | Range |+|-------|------|---------|-------|+| `cursor` | string | — | Opaque cursor |+| `limit` | number | 20 | 1–50 |++**Response** `200`:+```typescript+{+ conversations: Array<{+ id: string+ seller_id: string+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_customer: number+ created_at: string+ }>+ next_cursor: string | null+}+```++Ordered by `last_message_at DESC, id DESC`.++---++### `GET /store/messages/:id` — Get messages++**Query parameters**:++| Param | Type | Default | Range |+|-------|------|---------|-------|+| `cursor` | string | — | Opaque cursor |+| `limit` | number | 20 | 1–100 |++**Response** `200`:+```typescript+{+ conversation: ConversationDTO+ messages: Array<{+ id: string+ sender_type: "customer" | "seller"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: string | null+ created_at: string+ }>+ next_cursor: string | null+}+```++Messages returned in **descending order** (newest first). Reverse for chronological display.++**Ownership check**: `conversation.buyer_id` must match authenticated customer.++---++### `POST /store/messages/:id` — Send message++**Request body**:+```typescript+{+ body: string // 1–2000 chars, required+ context_type?: "product" | "order"+ context_id?: string+}+```++**Response** `200`:+```typescript+{+ message: {+ id: string+ sender_type: "customer"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: null+ created_at: string+ }+}+```++**Pipeline**: ownership check → **block check** → rate limit → content filter → create message → publish SSE → emit event.++---++### `POST /store/messages/:id/read` — Mark as read++**Request body**: `{}` (empty)++**Response** `200`:+```typescript+{+ success: true+ unread_count_customer: 0+}+```++Marks all unread seller messages as read. Publishes `messages_read` event to seller and `unread_count` event to customer.++---++### `GET /store/messages/unread` — Unread count++**Response** `200`:+```typescript+{+ unread_count: number+}+```++Total unread messages across all conversations for the authenticated customer.++---++### `POST /store/messages/sse-token` — Get SSE token++**Response** `200`:+```typescript+{+ token: string // UUID, one-time use+ expires_in: 30 // seconds+}+```++Token stored in Redis: `sse_token:{token} = customer_id` with 30-second TTL. Consumed (deleted) on first SSE connection.++---++### `GET /store/messages/events?token={token}` — SSE stream++**Auth**: Token-based (no session required). See [SSE Real-Time Event System](#sse-real-time-event-system).++---++## API Reference — Vendor (Seller)++All vendor endpoints require seller authentication.++### `GET /vendor/messages` — List conversations++**Query parameters**: `cursor?`, `limit?` (1–50, default 20)++**Response** `200`:+```typescript+{+ conversations: Array<ConversationDTO & {+ buyer_first_name: string | null // Enriched+ is_buyer_blocked: boolean // Chat block status+ }>+ next_cursor: string | null+}+```++---++### `GET /vendor/messages/:id` — Get messages++**Query parameters**: `cursor?`, `limit?` (1–100, default 30)++**Response** `200`:+```typescript+{+ conversation: ConversationDTO & {+ buyer_first_name: string | null+ is_buyer_blocked: boolean+ }+ messages: MessageDTO[]+ next_cursor: string | null+ buyer_orders: Array<{+ id: string+ display_id: number+ status: string+ total: number+ currency_code: string+ created_at: string+ }>+}+```++The `buyer_orders` array contains the buyer's recent orders with this seller, enabling contextual customer support.++---++### `POST /vendor/messages/:id` — Send reply++**Request body**:+```typescript+{+ body: string // 1–2000 chars, required+}+```++Vendor replies have no context linking (no `context_type` / `context_id`).++**Block enforcement**: If the buyer is chat-blocked, the vendor cannot send a reply. Returns `not_allowed` error: "Cannot send messages to a blocked customer".++**Response** `200`: `{ message: MessageDTO }`++---++### `POST /vendor/messages/:id/read` — Mark as read++**Response** `200`: `{ success: true, unread_count_seller: 0 }`++---++### `GET /vendor/messages/unread` — Unread count++**Response** `200`: `{ unread_count: number }`++---++### `GET /vendor/messages/events` — SSE stream++Direct session-based auth (no token exchange). See [SSE Real-Time Event System](#sse-real-time-event-system).++---++## API Reference — Admin++All admin endpoints require admin user authentication. Admin has **read-only** access to conversations (cannot send messages) and can manage customer chat blocks.++### `GET /admin/messages` — Search conversations++**Query parameters**:++| Param | Type | Description |+|-------|------|-------------|+| `cursor` | string | Pagination cursor |+| `limit` | number (1–50, default 20) | Page size |+| `seller_name` | string | LIKE filter on seller name |+| `buyer_name` | string | LIKE filter on customer first or last name |+| `date_from` | string (ISO datetime) | Filter: last_message_at >= |+| `date_to` | string (ISO datetime) | Filter: last_message_at <= |+| `context_type` | `"product"` \| `"order"` | Filter by message context type |+| `context_id` | string | Filter by specific product/order ID |++**Response** `200`:+```typescript+{+ conversations: Array<ConversationDTO & {+ seller_name?: string+ buyer_name?: string+ buyer_email?: string+ is_buyer_blocked: boolean+ }>+ next_cursor: string | null+}+```++---++### `GET /admin/messages/:id` — Get messages++**Response** `200`:+```typescript+{+ conversation: ConversationDTO & {+ buyer_name: string | null+ buyer_email: string | null+ seller_name: string | null+ is_buyer_blocked: boolean+ block_reason: string | null // Present when is_buyer_blocked is true+ }+ messages: MessageDTO[] // includes sender_id+ next_cursor: string | null+}+```++Admin can view any conversation without ownership restrictions. Admin message fields include `sender_id` (not exposed in store/vendor responses).++---++### `GET /admin/messages/filters` — List filter rules++**Query parameters**: `limit?` (1–50, default 20)++**Response** `200`:+```typescript+{+ filter_rules: Array<{+ id: string+ match_type: "exact" | "contains" | "regex"+ pattern: string+ is_builtin: boolean+ is_enabled: boolean+ description: string | null+ created_at: string+ updated_at: string+ }>+ count: number+}+```++---++### `POST /admin/messages/filters` — Create filter rule++**Request body**:+```typescript+{+ match_type: "exact" | "contains" // "regex" not allowed for custom rules+ pattern: string // 1–500 chars+ description?: string // Max 500 chars+ is_enabled?: boolean // Default: true+}+```++**Response** `200`: `{ filter_rule: FilterRuleDTO }`++Takes effect immediately (cache invalidated).++---++### `POST /admin/messages/filters/:id` — Update filter rule++**Request body**:+```typescript+{+ match_type?: "exact" | "contains"+ pattern?: string+ description?: string+ is_enabled?: boolean+}+```++**Constraints**:+- Built-in rules: only `is_enabled` and `description` can be changed+- Attempting to modify a built-in rule's `pattern` or `match_type` returns `not_allowed`++**Response** `200`: `{ filter_rule: FilterRuleDTO }`++---++### `DELETE /admin/messages/filters/:id` — Delete filter rule++Built-in rules cannot be deleted (returns `not_allowed`).++**Response** `200`: `{ id: string, deleted: true }`++---++### `GET /admin/messages/blocked` — List blocked messages++**Query parameters**:++| Param | Type | Description |+|-------|------|-------------|+| `cursor` | string | Pagination cursor |+| `limit` | number (1–50, default 20) | Page size |+| `sender_type` | `"customer"` \| `"seller"` | Filter by sender type |+| `date_from` | string | Filter: created_at >= |+| `date_to` | string | Filter: created_at <= |++**Response** `200`:+```typescript+{+ blocked_messages: Array<{+ id: string+ sender_id: string+ sender_type: "customer" | "seller"+ conversation_id: string+ matched_rule_id: string+ message_body: string+ created_at: string+ }>+ count: number+}+```++---++### `POST /admin/messages/chat-blocks` — Block customer from chat++**Request body**:+```typescript+{+ customer_id: string // Required, customer to block+ reason?: string // Optional, max 500 chars+}+```++**Response** `201`:+```typescript+{+ block: {+ id: string+ customer_id: string+ blocked_by: string // Admin user ID who performed the block+ reason: string | null+ created_at: string+ updated_at: string+ }+}+```++**Behavior**:+- Idempotent: blocking an already-blocked customer returns the existing block record+- The `blocked_by` field is set from the authenticated admin's ID+- Takes effect immediately — blocked customer cannot create conversations or send messages+- Vendors cannot send messages to the blocked customer++---++### `GET /admin/messages/chat-blocks/:customer_id` — Check block status++**Response** `200`:+```typescript+{+ is_blocked: boolean+}+```++---++### `DELETE /admin/messages/chat-blocks/:customer_id` — Unblock customer++**Response** `200`:+```typescript+{+ success: true+}+```++Succeeds silently if the customer is not currently blocked.++---++### `GET /admin/messages/events` — SSE stream++Direct session-based auth. Admin receives **all** messaging events globally (no filtering by recipient).++---++## SSE Real-Time Event System++The plugin uses Server-Sent Events (SSE) over Redis pub/sub to deliver real-time updates to connected clients. All events are published to a single Redis channel (`messaging`) and filtered per-subscriber.++### Connection Flows++| Actor | Endpoint | Auth Method | Filtering |+|-------|----------|-------------|-----------|+| Customer | `GET /store/messages/events?token={token}` | One-time token (30s TTL) | Events where `recipient_id` or `sender_id` matches customer |+| Vendor | `GET /vendor/messages/events` | Session/bearer | Events where `recipient_id` or `sender_id` matches seller |+| Admin | `GET /admin/messages/events` | Session/bearer | **No filtering** — receives all events |++#### Store SSE Token Flow++`EventSource` cannot send custom headers, so store SSE uses a token exchange:++1. `POST /store/messages/sse-token` (authenticated) → returns `{ token, expires_in: 30 }`+2. Token stored in Redis: `sse_token:{token} = customer_id` (30s TTL)+3. `GET /store/messages/events?token={token}` (unauthenticated) — token consumed on connection+4. Token is **one-time use** — deleted from Redis after first consumption++### Event Types++#### `connected`++Sent immediately on successful SSE connection.++```+event: connected+data: {"status":"connected"}+```++#### `reconnected`++Sent when client reconnects with `Last-Event-ID` header.++```+event: reconnected+data: {"status":"reconnected","last_event_id":"..."}+```++#### `new_message`++Published when a message is created in any conversation the subscriber is part of.++```+event: new_message+data: {+ "conversation_id": "conv_01ABC",+ "recipient_id": "cus_01XYZ",+ "sender_type": "customer",+ "event_type": "new_message",+ "message_id": "msg_01DEF",+ "context_type": "product",+ "context_label": "Blue Widget"+}+```++#### `messages_read`++Published when the other party marks messages as read.++```+event: messages_read+data: {+ "conversation_id": "conv_01ABC",+ "event_type": "messages_read"+}+```++#### `unread_count`++Published when a user's unread count changes (after mark-read or new message).++```+event: unread_count+data: {+ "conversation_id": "conv_01ABC",+ "event_type": "unread_count",+ "unread_count": 3+}+```++#### Heartbeat++A comment-only frame sent every 30 seconds to keep the connection alive:++```+:heartbeat+```++### Reconnection++- `EventSource` auto-reconnects and sends `Last-Event-ID` header+- Server sends `reconnected` event but does **not** replay missed events+- Clients should refetch conversations/messages after reconnection to catch up+- Store SSE: token is consumed, so reconnection requires a new token+- Dashboard SSE hooks use **exponential backoff** on error: 1s → 2s → 4s → 8s → ... → max 30s, reset to 1s on successful connection++### Graceful Degradation++If Redis is unavailable, SSE connections cannot be established. Clients should fall back to polling the REST endpoints.++---++## Cursor-Based Pagination++All list endpoints use cursor-based pagination for consistent performance regardless of dataset size.++### How It Works++Cursors are **opaque base64url-encoded JSON** strings containing the sort fields of the last item in the current page. They encode `{ field_value, id }` for deterministic ordering.++| Entity | Cursor Fields | Sort Order |+|--------|--------------|------------|+| Conversations | `last_message_at`, `id` | DESC (most recent first) |+| Messages | `created_at`, `id` | DESC (newest first) |++### Pagination Limits++| Endpoint Type | Default | Max |+|--------------|---------|-----|+| Conversation lists | 20 | 50 |+| Message lists | 20 | 100 |++### Usage Pattern++```+# First page+GET /store/messages?limit=20+→ { conversations: [...], next_cursor: "eyJ..." }++# Next page+GET /store/messages?limit=20&cursor=eyJ...+→ { conversations: [...], next_cursor: "eyJ..." }++# Last page+GET /store/messages?limit=20&cursor=eyJ...+→ { conversations: [...], next_cursor: null }+```++`next_cursor` is `null` when there are no more items. Cursors are opaque — never parse, modify, or construct them client-side.++---++## Content Filtering++Every message (from both customers and sellers) passes through the content filter before being accepted.++### Evaluation Pipeline++1. **Exact word match** — Body split by whitespace, each word checked against `Set<string>` (O(1) per word, case-insensitive)+2. **Contains/substring match** — Body checked against each pattern (lowercased, O(n) per pattern)+3. **Regex match** — Body matched against compiled patterns (built-in rules only)++Evaluation short-circuits on first match. Priority: exact > contains > regex.++### Rule Types++| Type | Available To | Matching |+|------|-------------|----------|+| `exact` | Admin (custom) | Case-insensitive whole-word match |+| `contains` | Admin (custom) | Case-insensitive substring match |+| `regex` | Built-in only | Case-insensitive regex pattern |++### When a Message Is Blocked++1. Message is **not** created (rejected before insert)+2. Full message body logged in `blocked_message_log` with matched rule ID+3. API returns `400` with error type `invalid_data`+4. Blocked message logs retained for 30 days, cleaned up by scheduled job++### Cache Management++- Rules compiled into memory at startup (via module loader)+- Lazily compiled on first message if startup compilation fails+- Recompiled on the current instance when any rule changes (create/update/delete) via `invalidateFilterCacheStep`+- The step also publishes to Redis `filter_rules_changed` channel for future cross-instance support+- **Note**: Cross-instance invalidation requires a custom subscriber at the app level — not included by default due to MedusaJS module container limitations+- Functions: `getCompiledRuleset()`, `invalidateRuleset()`, `recompileFilters()`++---++## Rate Limiting++Enforced via Redis sliding window counters. Applies equally to customers and sellers.++| Limit | Threshold | Window | Redis Key |+|-------|-----------|--------|-----------|+| Messages per sender | 20 | 60 seconds | `ratelimit:msg:{sender_id}` |+| New conversations per sender | 5 | 3600 seconds (1 hour) | `ratelimit:conv:{sender_id}` |++### Behavior++- Implemented in `validateRateLimitStep` within `sendMessageWorkflow`+- Uses `INCR` + `EXPIRE` for atomic sliding window+- Conversation rate limit only checked when `is_new_conversation: true`+- Exceeding limit throws `MedusaError.Types.NOT_ALLOWED`+- **Graceful degradation**: If Redis unavailable, rate limiting is skipped entirely+- Window is sliding (resets based on first message in window, not fixed clock)++---++## Context Linking++Messages can be linked to a product or order, providing conversational context (e.g. "Question about this product", "Issue with order #1042").++### Resolution++When a message includes `context_type` and `context_id`, the API route resolves a `context_label` before passing to the workflow:++| Context Type | Resolution | Label Format |+|-------------|-----------|--------------|+| `product` | Fetches product by ID | Product title (e.g. "Blue Cotton T-Shirt") |+| `order` | Fetches order by ID | `"Order #<display_id>"` (e.g. "Order #1042") |++### Rules++- `context_type` and `context_id` must both be provided or both omitted+- Referenced product/order must exist (returns `404` otherwise)+- Label is resolved at send time and persisted — remains stable even if product title changes+- Different messages in the same conversation can reference different products/orders+- Vendor replies do not support context linking++---++## Unread Tracking++### Per-Conversation Counters++Each conversation tracks two independent unread counters:++- `unread_count_customer` — messages from seller that the customer hasn't read+- `unread_count_seller` — messages from customer that the seller hasn't read++### Counter Behavior++| Action | Customer Counter | Seller Counter |+|--------|-----------------|----------------|+| Customer sends message | No change | +1 |+| Seller sends message | +1 | No change |+| Customer marks read | → 0 | No change |+| Seller marks read | No change | → 0 |++Counters are updated **atomically** within the same database transaction as message creation or read marking.++### Total Unread++`GET /store/messages/unread` and `GET /vendor/messages/unread` return the **sum** of unread counts across all conversations for the authenticated user.++### Reconciliation++A scheduled job runs daily at 3 AM to reconcile drifted counters by counting actual unread messages and correcting any discrepancies.++---++## GDPR & Data Privacy++### Buyer Deletion++When a `customer.deleted` event fires:++1. `anonymizeBuyerMessagesWorkflow` runs automatically+2. All conversations: `buyer_id` → `deleted_{original_buyer_id}` (paginated, 100 per batch)+3. All buyer messages: `body` → `"[Message removed]"` (paginated, 100 per batch)+4. Module links to customer entity are cleaned up+5. Compensation: conversation `buyer_id` can be restored; message body anonymization is irreversible (logged)++### Vendor Deletion++When a `seller.deleted` event fires:++1. `anonymizeVendorMessagesWorkflow` runs automatically+2. All conversations: `seller_id` → `deleted_{original_seller_id}` (paginated, 100 per batch)+3. **Vendor message bodies are preserved** (per business specification)+4. Module links to seller entity are cleaned up+5. Compensation: conversation `seller_id` can be restored++### Data Retention++- Message data: retained indefinitely (soft delete only)+- Blocked message logs: 30-day retention, cleaned daily at 4 AM+- SSE tokens: 30-second TTL, auto-expired by Redis+- Rate limit counters: auto-expired by Redis (60s / 3600s TTL)++---++## Chat Blocking++Admin-only feature to suspend a customer's chat access. Blocking prevents the customer from creating new conversations and sending messages, and prevents vendors from sending messages to the blocked customer. The customer's storefront account is unaffected.++### How It Works++1. **Admin blocks customer** via `POST /admin/messages/chat-blocks` (with optional reason)+2. A `ChatBlock` record is created with a unique index on `customer_id`+3. Block is enforced at three layers (defense in depth):+ - **Route level**: Early exit before workflow execution (store and vendor POST handlers)+ - **Workflow step**: `validateChatBlockStep` runs first in `sendMessageWorkflow`+ - **UI level**: Compose area disabled in vendor dashboard, admin dashboard shows badge++### Block Enforcement Matrix++| Scenario | Result |+|----------|--------|+| Blocked customer creates conversation | `not_allowed`: "Your chat access has been suspended" |+| Blocked customer sends message | `not_allowed`: "Your chat access has been suspended" |+| Vendor sends to blocked customer | `not_allowed`: "Cannot send messages to a blocked customer" |+| Non-blocked customer sends message | Allowed (normal flow) |+| Admin blocks already-blocked customer | Idempotent — returns existing block |+| Admin unblocks non-blocked customer | Succeeds silently |++### Bidirectional Blocking++When a customer is blocked, **both directions** are blocked:+- The customer cannot send messages to any vendor+- No vendor can send messages to the blocked customer++This prevents vendors from unknowingly engaging with a blocked user.++### UI Indicators++| Dashboard | Location | Indicator |+|-----------|----------|-----------|+| Admin list | Next to buyer name | Red "Blocked" badge |+| Admin detail | Sidebar + dedicated section | Red "Blocked" badge + Block/Unblock button |+| Vendor list | Next to buyer name | Red "Blocked" badge |+| Vendor detail | Sidebar + compose area | Red "Blocked" badge + disabled compose with notice |++### Admin Block Dialog++The admin detail page provides:+- **Block action**: Opens an inline dialog with an optional reason input field and confirm/cancel buttons+- **Unblock action**: Shows a confirmation prompt via `usePrompt` before proceeding++### Security++- Only admin users can create or remove blocks (no vendor or store routes for block management)+- `blocked_by` field records which admin performed the block+- Block is enforced redundantly at route level, workflow level, and UI level++---++## Event Subscribers++### `messaging.message.created`++**Handler**: `message-notification.ts`++Triggered on every new message. Sends an email notification to the recipient.++**Logic**:+1. Checks notification throttle: one email per conversation per recipient per 15 minutes (Redis key: `notify:{conversation_id}:{recipient_id}`, TTL: 900s)+2. Resolves sender name (customer first name or seller name)+3. Resolves recipient email address+4. Sends notification via Medusa notification module+ - Template: `messaging-new-message`+ - Data: `{ sender_name, conversation_id }`+ - **Privacy**: Message body is never included in emails++### `customer.deleted`++**Handler**: `buyer-deletion.ts`++Runs `anonymizeBuyerMessagesWorkflow`. See [GDPR & Data Privacy](#gdpr--data-privacy).++### `seller.deleted`++**Handler**: `vendor-removal.ts`++Runs `anonymizeVendorMessagesWorkflow`. See [GDPR & Data Privacy](#gdpr--data-privacy).++---++## Scheduled Jobs++### Reconcile Unread Counts++**Schedule**: `0 3 * * *` (daily at 3 AM)++Iterates through all conversations in batches of 500. For each conversation, counts actual unread messages for both parties. If the stored counter differs from the actual count, updates it. Logs all corrections.++### Cleanup Blocked Messages++**Schedule**: `0 4 * * *` (daily at 4 AM)++Soft-deletes `blocked_message_log` entries older than 30 days. Logs the number of records cleaned up.++---++## Error Reference++| HTTP | Error Type | Cause | When |+|------|-----------|-------|------|+| 400 | `invalid_data` | Request validation failed | Missing/invalid fields, body too long/short |+| 400 | `invalid_data` | Content filter matched | Message contains blocked content |+| 400 | `not_allowed` | Rate limit exceeded | Too many messages or conversations in window |+| 400 | `not_allowed` | Chat blocked (customer) | Blocked customer attempts to create conversation or send message |+| 400 | `not_allowed` | Chat blocked (vendor) | Vendor attempts to send message to blocked customer |+| 400 | `not_allowed` | Built-in rule modification | Attempting to delete or modify built-in filter pattern |+| 401 | `unauthorized` | Missing/invalid authentication | No session, expired token |+| 401 | `unauthorized` | SSE token invalid/expired/consumed | Token already used or past 30s TTL |+| 404 | `not_found` | Conversation not found | Invalid ID or not owned by requester |+| 404 | `not_found` | Referenced entity not found | Product or order ID doesn't exist |++All errors follow the standard Medusa error format:++```json+{+ "type": "not_allowed",+ "message": "Rate limit exceeded. Please wait before sending more messages."+}+```++---++## Testing++The plugin includes unit tests covering core logic:++### `cursor-encoding.spec.ts`++- Base64url encoding roundtrip+- Conversation cursors (`last_message_at`, `id`)+- Message cursors (`created_at`, `id`)+- Null and numeric value handling+- Malformed input returns null++### `content-filter-eval.spec.ts`++- Exact match: case-insensitive whole-word matching+- Contains: substring matching+- Regex: built-in patterns (email, phone, URL)+- Priority ordering: exact > contains > regex+- Short-circuit on first match+- Edge cases: empty message, whitespace, unicode++### `rate-limit.spec.ts`++- 20 messages per 60 seconds enforced+- 5 conversations per 3600 seconds enforced+- Per-user isolation+- Applies equally to customers and sellers+- Window reset after expiry++### `unread-counter.spec.ts`++- Only recipient counter increments+- Sender counter unchanged on own message+- Reset to 0 on mark read+- Accumulation across multiple messages+- Reconciliation corrects drifted counts++### `chat-block.spec.ts` (unit)++- Block record creation with customer_id, blocked_by, reason+- Idempotent blocking (duplicate returns existing record)+- Unblocking removes block and allows chat again+- Unblocking non-blocked customer succeeds silently+- Re-blocking after unblock creates new record+- Batch checking (`checkBuyersBlocked`) with mixed blocked/unblocked IDs+- Bidirectional enforcement: blocked customer cannot send, vendor cannot send to blocked customer+- Multi-customer isolation: blocking one does not affect others+- Full lifecycle: block → verify → unblock → re-block cycle+- Admin accountability tracking (`blocked_by` field)++### `chat-block-api.spec.ts` (integration)++- Admin block API: creates block record, returns 201 with block data+- Admin unblock API: removes block, returns success+- Idempotent block (returns existing on duplicate)+- Idempotent unblock (succeeds silently for non-blocked customer)+- Store enforcement: blocked customer cannot create conversations+- Store enforcement: blocked customer cannot send messages+- Vendor enforcement: vendor cannot reply to blocked customer+- `is_buyer_blocked` and `block_reason` fields included in admin and vendor GET responses+- Cross-feature interaction: block does not affect unrelated conversations+- Full lifecycle through API: block → enforce → unblock → verify restored access++---++## Configuration Reference++### Redis Keys++| Key Pattern | TTL | Purpose |+|-------------|-----|---------|+| `sse_token:{uuid}` | 30s | One-time SSE auth token |+| `ratelimit:msg:{sender_id}` | 60s | Message rate limit counter |+| `ratelimit:conv:{sender_id}` | 3600s | Conversation creation rate limit counter |+| `notify:{conversation_id}:{recipient_id}` | 900s | Email notification throttle |++### Redis Pub/Sub Channels++| Channel | Publisher | Subscribers |+|---------|-----------|------------|+| `messaging` | `publishMessageEventStep` | SSE route handlers (store, vendor, admin) |+| `filter_rules_changed` | `invalidateFilterCacheStep` | None by default (available for custom cross-instance subscriber) |++### Module Identifiers++| Module | Identifier | Container Key |+|--------|-----------|---------------|+| Messaging | `messaging` | `messagingModuleService` |+| Messaging Filters | `messagingFilters` | `messagingFiltersModuleService` |+| Messaging Redis | `messagingRedis` | `messagingRedisModuleService` |++### Medusa Events Emitted++| Event | Payload | Trigger |+|-------|---------|---------|+| `messaging.message.created` | `{ id, conversation_id, sender_id, sender_type, recipient_id }` | After message creation |++### Notification Templates++| Template ID | Variables | Usage |+|------------|-----------|-------|+| `messaging-new-message` | `sender_name`, `conversation_id` | Email notification to message recipient |++### Database Tables++| Table | Module | Prefix |+|-------|--------|--------|+| `conversation` | messaging | `conv` |+| `message` | messaging | `msg` |+| `chat_block` | messaging | `cblk` |+| `filter_rule` | messagingFilters | `filt` |+| `blocked_message_log` | messagingFilters | `bml` |++### Vendor Dashboard Pages++| Route | Description |+|-------|-------------|+| `/messages` | Conversation list with unread badges |+| `/messages/:id` | Chat detail with reply composer and order sidebar |++### Admin Dashboard Pages++| Route | Description |+|-------|-------------|+| `/messages` | Searchable conversation list with seller/buyer names |+| `/messages/:id` | Read-only message thread with conversation metadata sidebar, block/unblock controls |+| `/messages/filters` | Content filter rule management |+| `/messages/blocked` | Blocked message log viewer |diff --git a/packages/registry/src/messaging/IMPLEMENTATION.md b/packages/registry/src/messaging/IMPLEMENTATION.mdnew file mode 100644index 000000000..1ac968474--- /dev/null+++ b/packages/registry/src/messaging/IMPLEMENTATION.md@@ -0,0 +1,1067 @@+# Messaging Plugin — Storefront Implementation Guide++This guide covers how to integrate the buyer-vendor messaging plugin into a storefront application. It documents every Store API endpoint, the SSE real-time event system, cursor-based pagination, context linking, error handling, and rate limiting behavior.++The guide is framework-agnostic. Adapt the patterns to your stack (Next.js, Remix, plain JS, React Native, etc.).++---++## Table of Contents++1. [Prerequisites](#prerequisites)+2. [Authentication](#authentication)+3. [API Overview](#api-overview)+4. [Creating a Conversation](#creating-a-conversation)+5. [Listing Conversations](#listing-conversations)+6. [Fetching Messages (Cursor Pagination)](#fetching-messages-cursor-pagination)+7. [Sending a Message](#sending-a-message)+8. [Marking Messages as Read](#marking-messages-as-read)+9. [Unread Count](#unread-count)+10. [Real-Time Updates (SSE)](#real-time-updates-sse)+11. [Context Linking (Product / Order)](#context-linking-product--order)+12. [Rate Limiting](#rate-limiting)+13. [Content Filtering](#content-filtering)+14. [Chat Blocking](#chat-blocking)+15. [Error Reference](#error-reference)+16. [Full Integration Example](#full-integration-example)++---++## Prerequisites++The messaging block must be installed and configured in your Medusa backend:++```bash+mercurjs add messaging+```++Required backend environment variable:++```+REDIS_URL=redis://localhost:6379+```++The storefront must authenticate customers via Medusa's standard session or bearer token auth. All Store messaging endpoints require an authenticated customer.++---++## Authentication++All `/store/messages/*` endpoints (except the SSE stream) require a standard Medusa customer session. If you are using the Medusa JS SDK:++```ts+import Medusa from "@medusajs/js-sdk"++const sdk = new Medusa({+ baseUrl: "http://localhost:9000",+ auth: { type: "session" },+})++// Customer must be logged in before calling messaging endpoints+await sdk.auth.login("customer", "emailpass", {+ email: "[email protected]",+ password: "password",+})+```++If using raw `fetch`, include credentials:++```ts+fetch("http://localhost:9000/store/messages", {+ credentials: "include", // sends session cookie+})+```++The SSE endpoint uses a separate token-based auth flow — see [Real-Time Updates (SSE)](#real-time-updates-sse).++---++## API Overview++| Method | Endpoint | Description |+|--------|----------|-------------|+| `GET` | `/store/messages` | List customer's conversations |+| `POST` | `/store/messages` | Create conversation (+ optional first message) |+| `GET` | `/store/messages/:id` | Get messages in a conversation |+| `POST` | `/store/messages/:id` | Send a message |+| `POST` | `/store/messages/:id/read` | Mark messages as read |+| `GET` | `/store/messages/unread` | Get total unread count |+| `POST` | `/store/messages/sse-token` | Obtain one-time SSE auth token |+| `GET` | `/store/messages/events?token=` | SSE stream (token-based auth) |++---++## Creating a Conversation++Start a new conversation with a seller. If a conversation already exists between the customer and seller, the existing one is returned.++```+POST /store/messages+```++### Request Body++```ts+{+ seller_id: string // Required — the seller to message+ body?: string // Optional — first message (1-2000 chars)+ context_type?: "product" | "order" // Optional — link to a product or order+ context_id?: string // Required if context_type is set+}+```++`context_type` and `context_id` must both be provided or both omitted. When provided, the backend resolves a human-readable label automatically (product title or "Order #display_id").++### Response++```ts+{+ conversation: {+ id: string // e.g. "conv_01ABC..."+ seller_id: string+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_customer: number+ created_at: string+ }+ message?: { // Only present if body was provided+ id: string+ sender_type: "customer"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: null+ created_at: string+ }+}+```++### Example++```ts+// Create conversation with first message about a product+const res = await sdk.client.fetch("/store/messages", {+ method: "POST",+ body: {+ seller_id: "sel_01XYZ",+ body: "Hi, is this item available in blue?",+ context_type: "product",+ context_id: "prod_01ABC",+ },+})++const { conversation, message } = res+// conversation.id → use for subsequent messages+```++### Idempotency++If a conversation already exists between the customer and seller, it is returned (not duplicated). The unique constraint is on `(buyer_id, seller_id)`. A new message is still created if `body` is provided.++---++## Listing Conversations++Retrieve the customer's conversations, ordered by most recent activity.++```+GET /store/messages+```++### Query Parameters++| Param | Type | Default | Description |+|-------|------|---------|-------------|+| `cursor` | string | — | Pagination cursor from previous response |+| `limit` | number | 20 | Items per page (1-50) |++### Response++```ts+{+ conversations: Array<{+ id: string+ seller_id: string+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_customer: number+ created_at: string+ }>+ next_cursor: string | null // null when no more pages+}+```++### Pagination++```ts+// First page+const page1 = await sdk.client.fetch("/store/messages?limit=20")++// Next page (if available)+if (page1.next_cursor) {+ const page2 = await sdk.client.fetch(+ `/store/messages?limit=20&cursor=${page1.next_cursor}`+ )+}+```++Cursors are opaque base64 strings. Do not parse or construct them — always use the `next_cursor` value from the previous response.++---++## Fetching Messages (Cursor Pagination)++Retrieve messages in a conversation. Messages are returned in **descending order** (newest first). Use cursor pagination to load older messages.++```+GET /store/messages/:id+```++### Query Parameters++| Param | Type | Default | Description |+|-------|------|---------|-------------|+| `cursor` | string | — | Pagination cursor for older messages |+| `limit` | number | 20 | Messages per page (1-100) |++### Response++```ts+{+ conversation: {+ id: string+ seller_id: string+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_customer: number+ created_at: string+ }+ messages: Array<{+ id: string+ sender_type: "customer" | "seller"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null // e.g. "Blue Widget" or "Order #1042"+ read_at: string | null+ created_at: string+ }>+ next_cursor: string | null+}+```++### Loading Older Messages++Since messages arrive newest-first, "load more" means fetching the next cursor page:++```ts+// Initial load — most recent 20 messages+const page1 = await sdk.client.fetch(`/store/messages/${conversationId}?limit=20`)++// User clicks "Load older messages"+if (page1.next_cursor) {+ const page2 = await sdk.client.fetch(+ `/store/messages/${conversationId}?limit=20&cursor=${page1.next_cursor}`+ )+ // Prepend page2.messages before page1.messages for chronological display+}+```++### Display Order++The API returns messages in descending order. Reverse them for chronological display:++```ts+const allMessages = [...olderPages, ...newerPages].flat()+const chronological = allMessages.reverse()+```++Or accumulate pages and reverse the full set:++```ts+// pages = [page1.messages, page2.messages, ...]+// Each page is desc; later pages are older+const messages = pages.flatMap((p) => p.messages)+const display = [...messages].reverse()+```++---++## Sending a Message++Send a reply in an existing conversation.++```+POST /store/messages/:id+```++### Request Body++```ts+{+ body: string // Required (1-2000 chars)+ context_type?: "product" | "order" // Optional context link+ context_id?: string // Required if context_type is set+}+```++### Response++```ts+{+ message: {+ id: string+ sender_type: "customer"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: null+ created_at: string+ }+}+```++### Example++```ts+const res = await sdk.client.fetch(`/store/messages/${conversationId}`, {+ method: "POST",+ body: {+ body: "Thanks, I'll take it!",+ context_type: "order",+ context_id: "order_01XYZ",+ },+})+```++### What happens server-side++1. Ownership verified (customer must own the conversation)+2. Rate limit checked (20 messages per 60 seconds)+3. Content filter evaluated (blocks emails, phone numbers, URLs, and custom rules)+4. Message created atomically (updates conversation preview, increments seller's unread count)+5. SSE event published to the seller in real-time+6. Medusa event `messaging.message.created` emitted++---++## Marking Messages as Read++Mark all unread messages from the seller as read and reset the customer's unread counter.++```+POST /store/messages/:id/read+```++### Request Body++Empty object `{}`.++### Response++```ts+{+ success: true,+ unread_count_customer: 0+}+```++### When to call++Call this when the customer opens a conversation or scrolls to unread messages. The backend:++1. Sets `read_at` on all unread seller messages in this conversation+2. Resets `unread_count_customer` to 0+3. Publishes a `messages_read` SSE event to the seller (so they see "Read" receipts)+4. Publishes an `unread_count` SSE event to the customer (confirms count reset)++---++## Unread Count++Get the total unread message count across all conversations.++```+GET /store/messages/unread+```++### Response++```ts+{+ unread_count: number+}+```++Use this for badge counts in navigation (e.g. "Messages (3)"). Poll this periodically as a fallback if SSE is not connected, or rely on `unread_count` SSE events for real-time updates.++---++## Real-Time Updates (SSE)++The plugin uses Server-Sent Events for real-time message delivery. The store SSE uses a **token-based authentication** flow because `EventSource` does not support custom headers.++### Connection Flow++#### Step 1: Obtain a one-time token++```+POST /store/messages/sse-token+```++This requires a standard authenticated session. Response:++```ts+{+ token: string, // UUID, one-time use+ expires_in: 30 // seconds+}+```++The token is stored in Redis with a 30-second TTL. It is consumed (deleted) on the first SSE connection attempt.++#### Step 2: Open the SSE stream++```+GET /store/messages/events?token={token}+```++This endpoint does **not** require session auth — the token authenticates the request.++```ts+// Full connection flow+async function connectSSE() {+ // Step 1: Get token (authenticated request)+ const { token } = await sdk.client.fetch("/store/messages/sse-token", {+ method: "POST",+ })++ // Step 2: Open SSE stream (token-based, no session needed)+ const eventSource = new EventSource(+ `${backendUrl}/store/messages/events?token=${token}`+ )++ return eventSource+}+```++### Event Types++The SSE stream emits these named events:++#### `connected`++Sent immediately on successful connection.++```ts+eventSource.addEventListener("connected", (e) => {+ const data = JSON.parse(e.data)+ // { status: "connected" }+})+```++#### `reconnected`++Sent when reconnecting with a `Last-Event-ID`.++```ts+eventSource.addEventListener("reconnected", (e) => {+ const data = JSON.parse(e.data)+ // { status: "reconnected", last_event_id: "..." }+})+```++#### `new_message`++A new message was sent in one of the customer's conversations (either by the customer themselves or by the seller).++```ts+eventSource.addEventListener("new_message", (e) => {+ const data = JSON.parse(e.data)+ // {+ // conversation_id: "conv_01ABC",+ // recipient_id: "cus_01XYZ",+ // sender_type: "customer" | "seller",+ // event_type: "new_message",+ // message_id: "msg_01DEF",+ // context_type?: "product" | "order",+ // context_label?: "Blue Widget"+ // }++ // Refetch the conversation or append the message+})+```++#### `messages_read`++The seller read messages in a conversation. Use this to show "Read" receipts.++```ts+eventSource.addEventListener("messages_read", (e) => {+ const data = JSON.parse(e.data)+ // {+ // conversation_id: "conv_01ABC",+ // event_type: "messages_read"+ // }++ // Update read status on displayed messages+})+```++#### `unread_count`++The customer's total unread count changed (e.g. after marking messages as read, or a new message arrived).++```ts+eventSource.addEventListener("unread_count", (e) => {+ const data = JSON.parse(e.data)+ // {+ // conversation_id: "conv_01ABC",+ // event_type: "unread_count",+ // unread_count: 5+ // }++ // Update badge count+})+```++#### Heartbeat++A comment-only heartbeat (`:heartbeat`) is sent every 30 seconds to keep the connection alive. The browser's `EventSource` handles this automatically — no action needed.++### Reconnection++`EventSource` automatically reconnects on network failure. The browser sends the `Last-Event-ID` header, and the server responds with a `reconnected` event. No messages are replayed — **refetch conversations/messages after reconnection** to catch up.++```ts+eventSource.addEventListener("reconnected", () => {+ // Refetch current conversation and unread count+ refetchConversation()+ refetchUnreadCount()+})++eventSource.addEventListener("error", () => {+ // EventSource auto-reconnects, but the token may have expired.+ // If the connection fails permanently, obtain a new token and reconnect.+ // Use exponential backoff (1s, 2s, 4s, ... max 30s) to avoid overwhelming+ // the server during outages. Reset the delay on successful reconnection.+})+```++### Token Expiry and Reconnection Strategy++The SSE token expires after 30 seconds and is consumed on first use. If the SSE connection drops and the browser's automatic reconnect fails (token already consumed), you must obtain a new token:++```ts+function createSSEConnection(backendUrl, sdk, handlers) {+ let eventSource = null+ let reconnectDelay = 1000++ async function connect() {+ // Always get a fresh token+ const { token } = await sdk.client.fetch("/store/messages/sse-token", {+ method: "POST",+ })++ eventSource = new EventSource(+ `${backendUrl}/store/messages/events?token=${token}`+ )++ eventSource.addEventListener("connected", () => {+ reconnectDelay = 1000 // Reset backoff on success+ handlers.onConnected?.()+ })+ eventSource.addEventListener("new_message", handlers.onNewMessage)+ eventSource.addEventListener("messages_read", handlers.onMessagesRead)+ eventSource.addEventListener("unread_count", handlers.onUnreadCount)++ eventSource.addEventListener("error", () => {+ // Close the dead connection and retry with a new token+ eventSource.close()+ // Exponential backoff: 1s, 2s, 4s, 8s, ..., max 30s+ setTimeout(connect, reconnectDelay)+ reconnectDelay = Math.min(reconnectDelay * 2, 30000)+ })+ }++ function disconnect() {+ if (eventSource) {+ eventSource.close()+ eventSource = null+ }+ }++ return { connect, disconnect }+}+```++### Non-Browser Clients (React Native, Node.js)++For environments where `EventSource` is not available or does not support query parameters, use any SSE client library. The flow is the same:++1. `POST /store/messages/sse-token` with auth headers+2. Connect to `/store/messages/events?token={token}` as a standard SSE stream+3. Parse `event:` and `data:` fields per the SSE spec++---++## Context Linking (Product / Order)++Messages can be linked to a product or order for contextual conversations (e.g. "Question about this product" or "Issue with order #1042").++### How it works++When sending a message with `context_type` and `context_id`, the backend:++1. **Product context** (`context_type: "product"`): Fetches the product and stores its title as `context_label`+2. **Order context** (`context_type: "order"`): Fetches the order and stores `"Order #<display_id>"` as `context_label`++The resolved `context_label` is returned on every message and persisted — it remains stable even if the product title changes later.++### Validation rules++- `context_type` and `context_id` must both be provided or both omitted+- `context_type` must be `"product"` or `"order"`+- The referenced product or order must exist+- Context is optional on all messages, not just the first one — different messages in a conversation can reference different products/orders++### Example: Asking about a product++```ts+await sdk.client.fetch("/store/messages", {+ method: "POST",+ body: {+ seller_id: "sel_01ABC",+ body: "Is this available in size L?",+ context_type: "product",+ context_id: "prod_01XYZ",+ },+})+// Response message will include:+// context_label: "Blue Cotton T-Shirt" (resolved from product title)+```++### Example: Issue with an order++```ts+await sdk.client.fetch(`/store/messages/${conversationId}`, {+ method: "POST",+ body: {+ body: "I received the wrong item in this order",+ context_type: "order",+ context_id: "order_01ABC",+ },+})+// Response message will include:+// context_label: "Order #1042" (resolved from order display_id)+```++---++## Rate Limiting++The backend enforces per-sender rate limits via Redis sliding windows.++| Limit | Window | Scope |+|-------|--------|-------|+| 20 messages | 60 seconds | Per sender (customer) |+| 5 new conversations | 3600 seconds (1 hour) | Per sender (customer) |++### Behavior++- When exceeded, the API returns HTTP 400 with error type `not_allowed`+- If Redis is unavailable, rate limiting is **skipped** (graceful degradation)+- The window is sliding — it resets based on the oldest message in the window, not on a fixed clock++### Handling rate limit errors++```ts+try {+ await sdk.client.fetch(`/store/messages/${id}`, {+ method: "POST",+ body: { body: "..." },+ })+} catch (error) {+ if (error.type === "not_allowed") {+ // Show "You're sending messages too quickly. Please wait a moment."+ }+}+```++---++## Content Filtering++The backend evaluates every message against a content filter ruleset before accepting it.++### Built-in rules (always active)++1. **Email addresses** — blocks messages containing email patterns+2. **Phone numbers** — blocks messages containing phone number patterns+3. **URLs** — blocks messages containing `http://`, `https://`, or `www.` links++### Admin-configured rules++Store admins can add custom filter rules (exact word match or substring match) via the admin panel. These take effect immediately.++### Behavior++- If a message matches any enabled filter rule, it is **rejected**+- The API returns HTTP 400 with error type `invalid_data`+- The blocked message is logged server-side for admin review+- The original message body is never stored as a message — it only appears in the blocked message log++### Handling filter errors++```ts+try {+ await sdk.client.fetch(`/store/messages/${id}`, {+ method: "POST",+ body: { body: userInput },+ })+} catch (error) {+ if (error.type === "invalid_data") {+ // Show "Your message could not be sent. Please remove any contact+ // information (email, phone, URLs) and try again."+ }+}+```++> **Note**: Do not expose the specific filter rule that matched — the error response does not include it. Show a generic message about content policy.++---++## Chat Blocking++An admin can block a customer from using chat. When a customer is blocked:++- **Creating conversations** (`POST /store/messages`) returns `not_allowed` error+- **Sending messages** (`POST /store/messages/:id`) returns `not_allowed` error+- The customer's storefront account is **not affected** — they can still browse, add to cart, and checkout++### Error messages++| Action | Error message |+|--------|--------------|+| Blocked customer creates conversation | "Your chat access has been suspended" |+| Blocked customer sends message | "Your chat access has been suspended" |++### Handling block errors++```ts+try {+ await sdk.client.fetch(`/store/messages/${id}`, {+ method: "POST",+ body: { body: userInput },+ })+} catch (error) {+ if (error.type === "not_allowed" && error.message.includes("suspended")) {+ // Customer is chat-blocked.+ // Show: "Your chat access has been suspended. Please contact support."+ // Disable the message compose UI to prevent further attempts.+ }+}+```++### UI recommendations++- When a `not_allowed` error with "suspended" message is received, disable the message input and show a notice+- Consider checking block status on the conversation detail page load — if the first `POST` fails with this error, the customer is blocked+- There is no store API to check block status directly — the error on send is the signal++---++## Error Reference++| HTTP Status | Error Type | Cause | Resolution |+|-------------|-----------|-------|------------|+| 401 | `unauthorized` | Missing or invalid session/token | Re-authenticate the customer |+| 400 | `invalid_data` | Validation failed (body too long, missing fields, content filtered) | Fix request body; check content filter rules |+| 400 | `not_allowed` | Rate limit exceeded | Wait and retry after a delay |+| 400 | `not_allowed` | Chat access suspended | Customer has been blocked from chat by an admin. Display the error message to the user. There is no self-service unblock — customer must contact support |+| 404 | `not_found` | Conversation not found or not owned by customer | Verify conversation ID and ownership |+| 404 | `not_found` | Referenced product/order does not exist | Verify context_id |+| 401 | `unauthorized` | SSE token invalid, expired, or already consumed | Obtain a new token via `POST /sse-token` |++All errors follow Medusa's standard error format:++```ts+{+ type: string, // e.g. "not_allowed", "invalid_data"+ message: string // Human-readable error description+}+```++---++## Full Integration Example++A complete storefront integration covering all features:++```ts+// messaging-client.ts+// Framework-agnostic messaging integration++// ─── Configuration ───────────────────────────────────────────────++const BACKEND_URL = "http://localhost:9000"+const MESSAGES_PER_PAGE = 20++// Assumes `sdk` is your configured Medusa JS SDK instance+// with an authenticated customer session.++// ─── Conversations ───────────────────────────────────────────────++/** List conversations with cursor pagination */+async function listConversations(cursor?: string) {+ const params = new URLSearchParams({ limit: String(MESSAGES_PER_PAGE) })+ if (cursor) params.set("cursor", cursor)++ return sdk.client.fetch(`/store/messages?${params}`)+ // → { conversations: [...], next_cursor: string | null }+}++/** Create or resume a conversation with a seller */+async function startConversation(+ sellerId: string,+ message?: string,+ context?: { type: "product" | "order"; id: string }+) {+ return sdk.client.fetch("/store/messages", {+ method: "POST",+ body: {+ seller_id: sellerId,+ ...(message ? { body: message } : {}),+ ...(context ? { context_type: context.type, context_id: context.id } : {}),+ },+ })+ // → { conversation: {...}, message?: {...} }+}++// ─── Messages ────────────────────────────────────────────────────++/** Fetch messages with cursor pagination (newest first) */+async function getMessages(conversationId: string, cursor?: string) {+ const params = new URLSearchParams({ limit: String(MESSAGES_PER_PAGE) })+ if (cursor) params.set("cursor", cursor)++ return sdk.client.fetch(`/store/messages/${conversationId}?${params}`)+ // → { conversation: {...}, messages: [...], next_cursor: string | null }+}++/** Send a message in a conversation */+async function sendMessage(+ conversationId: string,+ body: string,+ context?: { type: "product" | "order"; id: string }+) {+ return sdk.client.fetch(`/store/messages/${conversationId}`, {+ method: "POST",+ body: {+ body,+ ...(context ? { context_type: context.type, context_id: context.id } : {}),+ },+ })+ // → { message: {...} }+}++/** Mark all seller messages as read */+async function markAsRead(conversationId: string) {+ return sdk.client.fetch(`/store/messages/${conversationId}/read`, {+ method: "POST",+ body: {},+ })+ // → { success: true, unread_count_customer: 0 }+}++/** Get total unread count across all conversations */+async function getUnreadCount() {+ return sdk.client.fetch("/store/messages/unread")+ // → { unread_count: number }+}++// ─── SSE Real-Time Connection ────────────────────────────────────++function createRealtimeConnection(handlers: {+ onNewMessage: (data: any) => void+ onMessagesRead: (data: any) => void+ onUnreadCount: (data: any) => void+ onConnected?: () => void+ onDisconnected?: () => void+}) {+ let eventSource: EventSource | null = null+ let reconnectTimeout: ReturnType<typeof setTimeout> | null = null+ let isIntentionallyClosed = false+ let reconnectDelay = 1000++ async function connect() {+ isIntentionallyClosed = false++ // Step 1: Obtain one-time token (authenticated)+ const { token } = await sdk.client.fetch("/store/messages/sse-token", {+ method: "POST",+ })++ // Step 2: Open SSE stream (token-based, unauthenticated)+ eventSource = new EventSource(+ `${BACKEND_URL}/store/messages/events?token=${token}`+ )++ eventSource.addEventListener("connected", () => {+ reconnectDelay = 1000 // Reset backoff on success+ handlers.onConnected?.()+ })++ eventSource.addEventListener("new_message", (e) => {+ handlers.onNewMessage(JSON.parse(e.data))+ })++ eventSource.addEventListener("messages_read", (e) => {+ handlers.onMessagesRead(JSON.parse(e.data))+ })++ eventSource.addEventListener("unread_count", (e) => {+ handlers.onUnreadCount(JSON.parse(e.data))+ })++ eventSource.addEventListener("reconnected", () => {+ reconnectDelay = 1000 // Reset backoff on reconnect+ // Server reconnected — refetch data to catch up+ handlers.onConnected?.()+ })++ eventSource.addEventListener("error", () => {+ handlers.onDisconnected?.()+ eventSource?.close()++ if (!isIntentionallyClosed) {+ // Exponential backoff: 1s, 2s, 4s, 8s, ..., max 30s+ reconnectTimeout = setTimeout(connect, reconnectDelay)+ reconnectDelay = Math.min(reconnectDelay * 2, 30000)+ }+ })+ }++ function disconnect() {+ isIntentionallyClosed = true+ if (reconnectTimeout) clearTimeout(reconnectTimeout)+ eventSource?.close()+ eventSource = null+ }++ return { connect, disconnect }+}++// ─── Accumulating Paginated Messages ─────────────────────────────++/**+ * Helper to manage paginated message loading.+ *+ * Accumulates pages as the user loads older messages.+ * Returns messages in chronological order for display.+ */+function createMessagePaginator(conversationId: string) {+ const pages: Array<{ messages: any[]; next_cursor: string | null }> = []++ async function loadInitial() {+ const page = await getMessages(conversationId)+ pages.length = 0 // reset+ pages.push(page)+ return getDisplayState()+ }++ async function loadOlder() {+ const lastPage = pages[pages.length - 1]+ if (!lastPage?.next_cursor) return getDisplayState()++ const page = await getMessages(conversationId, lastPage.next_cursor)+ pages.push(page)+ return getDisplayState()+ }++ function getDisplayState() {+ // All pages contain messages in desc order.+ // Later pages contain older messages.+ // Merge all and reverse for chronological display.+ const allMessages = pages.flatMap((p) => p.messages)+ const lastPage = pages[pages.length - 1]++ return {+ conversation: pages[0]?.conversation ?? null,+ messages: [...allMessages].reverse(),+ hasOlderMessages: lastPage?.next_cursor != null,+ }+ }++ return { loadInitial, loadOlder, getDisplayState }+}++// ─── Usage ───────────────────────────────────────────────────────++/*+// 1. Start a conversation from a product page+const { conversation } = await startConversation(+ "sel_01ABC",+ "Is this available in blue?",+ { type: "product", id: "prod_01XYZ" }+)++// 2. Load messages with pagination+const paginator = createMessagePaginator(conversation.id)+let state = await paginator.loadInitial()+// state.messages → chronological array of last 20 messages+// state.hasOlderMessages → true if more to load++// 3. Load older messages+state = await paginator.loadOlder()++// 4. Send a reply+await sendMessage(conversation.id, "Great, I'll order it!")++// 5. Mark as read when viewing+await markAsRead(conversation.id)++// 6. Connect SSE for real-time updates+const sse = createRealtimeConnection({+ onNewMessage: (data) => {+ if (data.conversation_id === currentConversationId) {+ // Refetch messages for current conversation+ paginator.loadInitial()+ }+ // Always refetch unread count+ getUnreadCount()+ },+ onMessagesRead: (data) => {+ // Update read receipts in the UI+ },+ onUnreadCount: (data) => {+ // Update badge count+ },+ onConnected: () => {+ // Refetch data to catch up after any missed events+ getUnreadCount()+ },+})++await sse.connect()++// 7. Disconnect on cleanup (e.g. logout, page unmount)+sse.disconnect()+*/+```++---++## Notes++- **Conversation uniqueness**: Only one conversation exists per buyer-seller pair. Creating a conversation with the same seller returns the existing one.+- **Message ordering**: The API always returns messages newest-first. Reverse for chronological display.+- **Cursor opacity**: Cursors are base64-encoded. Never parse, modify, or construct them — always use `next_cursor` from the response.+- **Soft deletes**: All entities support soft deletion. Deleted conversations/messages are excluded from API responses automatically.+- **GDPR**: The backend supports buyer data anonymization. When a customer account is deleted, their `buyer_id` is anonymized across all conversations and messages.+- **Redis dependency**: SSE, rate limiting, and content filter caching require Redis. If Redis is down, SSE won't connect and rate limiting is skipped, but core messaging (send/receive via REST) continues to work.diff --git a/packages/registry/src/messaging/__tests__/integration/chat-block-api.spec.ts b/packages/registry/src/messaging/__tests__/integration/chat-block-api.spec.tsnew file mode 100644index 000000000..d354bebc5--- /dev/null+++ b/packages/registry/src/messaging/__tests__/integration/chat-block-api.spec.ts@@ -0,0 +1,508 @@+import { describe, it, expect } from "vitest"++/**+ * Integration tests for the chat-block API routes.+ *+ * These tests verify the full request/response contract of admin block+ * management endpoints and the block-enforcement behavior on store and+ * vendor routes. They do not hit a real database — they simulate the+ * route-level logic and workflow orchestration to validate:+ *+ * 1. Admin can block/unblock customers via the admin API+ * 2. Blocked customers are rejected when creating conversations+ * 3. Blocked customers are rejected when sending messages+ * 4. Vendors cannot send to blocked customers+ * 5. Block status is surfaced in list and detail responses+ * 6. Idempotent block/unblock operations+ */++// ---------------------------------------------------------------------------+// In-memory service simulation+// ---------------------------------------------------------------------------++type ChatBlock = {+ id: string+ customer_id: string+ blocked_by: string+ reason: string | null+ created_at: string+}++type Conversation = {+ id: string+ buyer_id: string+ seller_id: string+}++class MockMessagingService {+ private blocks = new Map<string, ChatBlock>()+ private conversations: Conversation[] = []+ private idCounter = 0++ // -- Block management (simulates MedusaService CRUD) --++ async createChatBlocks(+ data: Array<{ customer_id: string; blocked_by: string; reason: string | null }>+ ): Promise<ChatBlock[]> {+ return data.map((d) => {+ const block: ChatBlock = {+ id: `cblk_${++this.idCounter}`,+ customer_id: d.customer_id,+ blocked_by: d.blocked_by,+ reason: d.reason,+ created_at: new Date().toISOString(),+ }+ this.blocks.set(d.customer_id, block)+ return block+ })+ }++ async listChatBlocks(+ filter: { customer_id?: string },+ _opts?: { take?: number }+ ): Promise<ChatBlock[]> {+ if (filter.customer_id) {+ const block = this.blocks.get(filter.customer_id)+ return block ? [block] : []+ }+ return [...this.blocks.values()]+ }++ async deleteChatBlocks(ids: string[]): Promise<void> {+ for (const [key, block] of this.blocks) {+ if (ids.includes(block.id)) {+ this.blocks.delete(key)+ }+ }+ }++ async checkBuyersBlocked(buyerIds: string[]): Promise<Set<string>> {+ const result = new Set<string>()+ for (const id of buyerIds) {+ if (this.blocks.has(id)) {+ result.add(id)+ }+ }+ return result+ }++ // -- Conversations (minimal simulation) --++ addConversation(conv: Conversation) {+ this.conversations.push(conv)+ }++ async listConversations(+ filter: { id?: string; buyer_id?: string; seller_id?: string },+ _opts?: { take?: number }+ ): Promise<Conversation[]> {+ return this.conversations.filter((c) => {+ if (filter.id && c.id !== filter.id) return false+ if (filter.buyer_id && c.buyer_id !== filter.buyer_id) return false+ if (filter.seller_id && c.seller_id !== filter.seller_id) return false+ return true+ })+ }+}++// ---------------------------------------------------------------------------+// Route handler simulations+// ---------------------------------------------------------------------------++type RouteResult = {+ status: number+ body: any+}++async function adminBlockCustomer(+ service: MockMessagingService,+ adminUserId: string,+ customerId: string,+ reason?: string+): Promise<RouteResult> {+ // Simulate POST /admin/messages/chat-blocks+ const existing = await service.listChatBlocks({ customer_id: customerId }, { take: 1 })+ if (existing.length > 0) {+ return { status: 201, body: { block: existing[0] } }+ }++ const [block] = await service.createChatBlocks([{+ customer_id: customerId,+ blocked_by: adminUserId,+ reason: reason ?? null,+ }])++ return { status: 201, body: { block } }+}++async function adminUnblockCustomer(+ service: MockMessagingService,+ customerId: string+): Promise<RouteResult> {+ // Simulate DELETE /admin/messages/chat-blocks/:customer_id+ const existing = await service.listChatBlocks({ customer_id: customerId }, { take: 1 })+ if (existing.length === 0) {+ return { status: 200, body: { success: true } }+ }+ await service.deleteChatBlocks([existing[0].id])+ return { status: 200, body: { success: true } }+}++async function adminCheckBlockStatus(+ service: MockMessagingService,+ customerId: string+): Promise<RouteResult> {+ // Simulate GET /admin/messages/chat-blocks/:customer_id+ const blocked = await service.checkBuyersBlocked([customerId])+ return { status: 200, body: { is_blocked: blocked.has(customerId) } }+}++async function storeCreateConversation(+ service: MockMessagingService,+ buyerId: string,+ sellerId: string+): Promise<RouteResult> {+ // Simulate POST /store/messages (block check before conversation creation)+ const blocked = await service.checkBuyersBlocked([buyerId])+ if (blocked.has(buyerId)) {+ return {+ status: 403,+ body: { type: "not_allowed", message: "Your chat access has been suspended" },+ }+ }++ // Find or create conversation+ const existing = await service.listConversations({ buyer_id: buyerId, seller_id: sellerId })+ if (existing.length > 0) {+ return { status: 200, body: { conversation: existing[0] } }+ }++ const conv: Conversation = { id: `conv_${Date.now()}`, buyer_id: buyerId, seller_id: sellerId }+ service.addConversation(conv)+ return { status: 200, body: { conversation: conv } }+}++async function storeSendMessage(+ service: MockMessagingService,+ buyerId: string,+ conversationId: string+): Promise<RouteResult> {+ // Simulate POST /store/messages/:id (block check before reply)+ const conversations = await service.listConversations({ id: conversationId, buyer_id: buyerId })+ if (conversations.length === 0) {+ return { status: 404, body: { type: "not_found", message: "Conversation not found" } }+ }++ const blocked = await service.checkBuyersBlocked([buyerId])+ if (blocked.has(buyerId)) {+ return {+ status: 403,+ body: { type: "not_allowed", message: "Your chat access has been suspended" },+ }+ }++ return { status: 200, body: { message: { id: "msg_test", body: "test" } } }+}++async function vendorSendMessage(+ service: MockMessagingService,+ sellerId: string,+ conversationId: string+): Promise<RouteResult> {+ // Simulate POST /vendor/messages/:id (block check before sending)+ const conversations = await service.listConversations({ id: conversationId, seller_id: sellerId })+ if (conversations.length === 0) {+ return { status: 404, body: { type: "not_found", message: "Conversation not found" } }+ }++ const conv = conversations[0]+ const blocked = await service.checkBuyersBlocked([conv.buyer_id])+ if (blocked.has(conv.buyer_id)) {+ return {+ status: 403,+ body: { type: "not_allowed", message: "Cannot send messages to a blocked customer" },+ }+ }++ return { status: 200, body: { message: { id: "msg_test", body: "test" } } }+}++async function vendorGetConversation(+ service: MockMessagingService,+ sellerId: string,+ conversationId: string+): Promise<RouteResult> {+ // Simulate GET /vendor/messages/:id (includes is_buyer_blocked)+ const conversations = await service.listConversations({ id: conversationId, seller_id: sellerId })+ if (conversations.length === 0) {+ return { status: 404, body: { type: "not_found", message: "Conversation not found" } }+ }++ const conv = conversations[0]+ const blockedSet = await service.checkBuyersBlocked([conv.buyer_id])++ return {+ status: 200,+ body: {+ conversation: {+ ...conv,+ is_buyer_blocked: blockedSet.has(conv.buyer_id),+ },+ },+ }+}++async function adminGetConversationList(+ service: MockMessagingService,+ conversations: Conversation[]+): Promise<RouteResult> {+ // Simulate GET /admin/messages (annotate block status)+ const buyerIds = [...new Set(conversations.map((c) => c.buyer_id))]+ const blockedSet = await service.checkBuyersBlocked(buyerIds)++ return {+ status: 200,+ body: {+ conversations: conversations.map((c) => ({+ ...c,+ is_buyer_blocked: blockedSet.has(c.buyer_id),+ })),+ },+ }+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe("Chat Block API Integration", () => {+ describe("Admin block management", () => {+ it("POST /admin/messages/chat-blocks creates a block", async () => {+ const service = new MockMessagingService()+ const result = await adminBlockCustomer(service, "admin_1", "cust_1", "Spam")++ expect(result.status).toBe(201)+ expect(result.body.block.customer_id).toBe("cust_1")+ expect(result.body.block.blocked_by).toBe("admin_1")+ expect(result.body.block.reason).toBe("Spam")+ })++ it("POST /admin/messages/chat-blocks is idempotent", async () => {+ const service = new MockMessagingService()+ const first = await adminBlockCustomer(service, "admin_1", "cust_1")+ const second = await adminBlockCustomer(service, "admin_2", "cust_1")++ expect(first.body.block.id).toBe(second.body.block.id)+ })++ it("GET /admin/messages/chat-blocks/:id returns block status", async () => {+ const service = new MockMessagingService()++ let status = await adminCheckBlockStatus(service, "cust_1")+ expect(status.body.is_blocked).toBe(false)++ await adminBlockCustomer(service, "admin_1", "cust_1")++ status = await adminCheckBlockStatus(service, "cust_1")+ expect(status.body.is_blocked).toBe(true)+ })++ it("DELETE /admin/messages/chat-blocks/:id removes block", async () => {+ const service = new MockMessagingService()+ await adminBlockCustomer(service, "admin_1", "cust_1")+ await adminUnblockCustomer(service, "cust_1")++ const status = await adminCheckBlockStatus(service, "cust_1")+ expect(status.body.is_blocked).toBe(false)+ })++ it("DELETE for non-blocked customer succeeds silently", async () => {+ const service = new MockMessagingService()+ const result = await adminUnblockCustomer(service, "cust_999")+ expect(result.status).toBe(200)+ expect(result.body.success).toBe(true)+ })+ })++ describe("Store block enforcement", () => {+ it("blocked customer cannot create conversation", async () => {+ const service = new MockMessagingService()+ await adminBlockCustomer(service, "admin_1", "cust_1")++ const result = await storeCreateConversation(service, "cust_1", "seller_1")+ expect(result.status).toBe(403)+ expect(result.body.type).toBe("not_allowed")+ expect(result.body.message).toContain("suspended")+ })++ it("non-blocked customer can create conversation", async () => {+ const service = new MockMessagingService()+ const result = await storeCreateConversation(service, "cust_1", "seller_1")+ expect(result.status).toBe(200)+ expect(result.body.conversation).toBeTruthy()+ })++ it("blocked customer cannot send message", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ await adminBlockCustomer(service, "admin_1", "cust_1")++ const result = await storeSendMessage(service, "cust_1", "conv_1")+ expect(result.status).toBe(403)+ expect(result.body.type).toBe("not_allowed")+ })++ it("non-blocked customer can send message", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ const result = await storeSendMessage(service, "cust_1", "conv_1")+ expect(result.status).toBe(200)+ expect(result.body.message).toBeTruthy()+ })++ it("unblocked customer can send again", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ await adminBlockCustomer(service, "admin_1", "cust_1")+ const blocked = await storeSendMessage(service, "cust_1", "conv_1")+ expect(blocked.status).toBe(403)++ await adminUnblockCustomer(service, "cust_1")+ const unblocked = await storeSendMessage(service, "cust_1", "conv_1")+ expect(unblocked.status).toBe(200)+ })+ })++ describe("Vendor block enforcement", () => {+ it("vendor cannot send to blocked customer", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ await adminBlockCustomer(service, "admin_1", "cust_1")++ const result = await vendorSendMessage(service, "seller_1", "conv_1")+ expect(result.status).toBe(403)+ expect(result.body.message).toContain("blocked customer")+ })++ it("vendor can send to non-blocked customer", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ const result = await vendorSendMessage(service, "seller_1", "conv_1")+ expect(result.status).toBe(200)+ })++ it("vendor can still view conversation of blocked customer", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ await adminBlockCustomer(service, "admin_1", "cust_1")++ const result = await vendorGetConversation(service, "seller_1", "conv_1")+ expect(result.status).toBe(200)+ expect(result.body.conversation.is_buyer_blocked).toBe(true)+ })+ })++ describe("Block status in responses", () => {+ it("vendor GET /messages/:id includes is_buyer_blocked", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ // Not blocked+ let result = await vendorGetConversation(service, "seller_1", "conv_1")+ expect(result.body.conversation.is_buyer_blocked).toBe(false)++ // Blocked+ await adminBlockCustomer(service, "admin_1", "cust_1")+ result = await vendorGetConversation(service, "seller_1", "conv_1")+ expect(result.body.conversation.is_buyer_blocked).toBe(true)+ })++ it("admin GET /messages annotates block status per conversation", async () => {+ const service = new MockMessagingService()+ const convs: Conversation[] = [+ { id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" },+ { id: "conv_2", buyer_id: "cust_2", seller_id: "seller_1" },+ { id: "conv_3", buyer_id: "cust_3", seller_id: "seller_2" },+ ]++ await adminBlockCustomer(service, "admin_1", "cust_2")++ const result = await adminGetConversationList(service, convs)+ expect(result.status).toBe(200)++ const list = result.body.conversations+ expect(list[0].is_buyer_blocked).toBe(false) // cust_1+ expect(list[1].is_buyer_blocked).toBe(true) // cust_2+ expect(list[2].is_buyer_blocked).toBe(false) // cust_3+ })++ it("batch check handles same buyer in multiple conversations", async () => {+ const service = new MockMessagingService()+ const convs: Conversation[] = [+ { id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" },+ { id: "conv_2", buyer_id: "cust_1", seller_id: "seller_2" },+ ]++ await adminBlockCustomer(service, "admin_1", "cust_1")++ const result = await adminGetConversationList(service, convs)+ expect(result.body.conversations[0].is_buyer_blocked).toBe(true)+ expect(result.body.conversations[1].is_buyer_blocked).toBe(true)+ })+ })++ describe("Cross-feature interaction", () => {+ it("blocking does not affect other customers' conversations", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })+ service.addConversation({ id: "conv_2", buyer_id: "cust_2", seller_id: "seller_1" })++ await adminBlockCustomer(service, "admin_1", "cust_1")++ // cust_2 can still create and send+ const createResult = await storeCreateConversation(service, "cust_2", "seller_2")+ expect(createResult.status).toBe(200)++ const sendResult = await storeSendMessage(service, "cust_2", "conv_2")+ expect(sendResult.status).toBe(200)+ })++ it("full lifecycle: block, verify enforcement, unblock, verify restored", async () => {+ const service = new MockMessagingService()+ service.addConversation({ id: "conv_1", buyer_id: "cust_1", seller_id: "seller_1" })++ // 1. Customer can chat+ expect((await storeSendMessage(service, "cust_1", "conv_1")).status).toBe(200)+ expect((await vendorSendMessage(service, "seller_1", "conv_1")).status).toBe(200)++ // 2. Admin blocks+ await adminBlockCustomer(service, "admin_1", "cust_1", "Harassment")++ // 3. Both sides blocked+ expect((await storeSendMessage(service, "cust_1", "conv_1")).status).toBe(403)+ expect((await vendorSendMessage(service, "seller_1", "conv_1")).status).toBe(403)++ // 4. Vendor can still view+ const view = await vendorGetConversation(service, "seller_1", "conv_1")+ expect(view.status).toBe(200)+ expect(view.body.conversation.is_buyer_blocked).toBe(true)++ // 5. Admin unblocks+ await adminUnblockCustomer(service, "cust_1")++ // 6. Both sides restored+ expect((await storeSendMessage(service, "cust_1", "conv_1")).status).toBe(200)+ expect((await vendorSendMessage(service, "seller_1", "conv_1")).status).toBe(200)++ // 7. Badge cleared+ const viewAfter = await vendorGetConversation(service, "seller_1", "conv_1")+ expect(viewAfter.body.conversation.is_buyer_blocked).toBe(false)+ })+ })+})diff --git a/packages/registry/src/messaging/__tests__/unit/chat-block.spec.ts b/packages/registry/src/messaging/__tests__/unit/chat-block.spec.tsnew file mode 100644index 000000000..32e0f07d2--- /dev/null+++ b/packages/registry/src/messaging/__tests__/unit/chat-block.spec.ts@@ -0,0 +1,405 @@+import { describe, it, expect } from "vitest"++/**+ * Tests for chat-block logic.+ * The actual blocking uses a ChatBlock model with a unique customer_id index.+ * These tests verify the blocking state machine and enforcement rules+ * without database dependencies.+ */++// ---------------------------------------------------------------------------+// Types & helpers — simulate ChatBlock state in memory+// ---------------------------------------------------------------------------++type ChatBlockRecord = {+ id: string+ customer_id: string+ blocked_by: string+ reason: string | null+ created_at: Date+}++type BlockStore = {+ blocks: Map<string, ChatBlockRecord>+}++function createStore(): BlockStore {+ return { blocks: new Map() }+}++let idCounter = 0+function nextId(): string {+ return `cblk_${++idCounter}`+}++function blockCustomer(+ store: BlockStore,+ customerId: string,+ blockedBy: string,+ reason: string | null = null+): ChatBlockRecord {+ // Idempotent: if already blocked, return existing+ const existing = store.blocks.get(customerId)+ if (existing) return existing++ const record: ChatBlockRecord = {+ id: nextId(),+ customer_id: customerId,+ blocked_by: blockedBy,+ reason,+ created_at: new Date(),+ }+ store.blocks.set(customerId, record)+ return record+}++function unblockCustomer(store: BlockStore, customerId: string): boolean {+ return store.blocks.delete(customerId)+}++function isBlocked(store: BlockStore, customerId: string): boolean {+ return store.blocks.has(customerId)+}++function checkBuyersBlocked(store: BlockStore, buyerIds: string[]): Set<string> {+ const result = new Set<string>()+ for (const id of buyerIds) {+ if (store.blocks.has(id)) {+ result.add(id)+ }+ }+ return result+}++type SenderType = "customer" | "seller"++function validateChatBlock(+ store: BlockStore,+ senderId: string,+ senderType: SenderType,+ recipientId: string+): { allowed: boolean; reason?: string } {+ const customerId = senderType === "customer" ? senderId : recipientId+ if (isBlocked(store, customerId)) {+ if (senderType === "customer") {+ return { allowed: false, reason: "Your chat access has been suspended" }+ }+ return { allowed: false, reason: "Cannot send messages to a blocked customer" }+ }+ return { allowed: true }+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe("Chat Block", () => {+ describe("blocking a customer", () => {+ it("creates a block record", () => {+ const store = createStore()+ const block = blockCustomer(store, "cust_1", "admin_1", "Abusive behavior")++ expect(block.customer_id).toBe("cust_1")+ expect(block.blocked_by).toBe("admin_1")+ expect(block.reason).toBe("Abusive behavior")+ expect(block.id).toBeTruthy()+ })++ it("returns existing block on duplicate (idempotent)", () => {+ const store = createStore()+ const first = blockCustomer(store, "cust_1", "admin_1", "Reason A")+ const second = blockCustomer(store, "cust_1", "admin_2", "Reason B")++ expect(first.id).toBe(second.id)+ expect(second.blocked_by).toBe("admin_1") // original record unchanged+ expect(second.reason).toBe("Reason A")+ })++ it("allows blocking with null reason", () => {+ const store = createStore()+ const block = blockCustomer(store, "cust_1", "admin_1", null)++ expect(block.reason).toBeNull()+ expect(isBlocked(store, "cust_1")).toBe(true)+ })++ it("tracks which admin performed the block", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_42")+ blockCustomer(store, "cust_2", "admin_99")++ expect(store.blocks.get("cust_1")?.blocked_by).toBe("admin_42")+ expect(store.blocks.get("cust_2")?.blocked_by).toBe("admin_99")+ })+ })++ describe("unblocking a customer", () => {+ it("removes block and allows chat again", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ expect(isBlocked(store, "cust_1")).toBe(true)++ unblockCustomer(store, "cust_1")+ expect(isBlocked(store, "cust_1")).toBe(false)+ })++ it("unblocking a non-blocked customer succeeds silently", () => {+ const store = createStore()+ const result = unblockCustomer(store, "cust_999")+ expect(result).toBe(false) // nothing was deleted+ })++ it("customer can be re-blocked after unblocking", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1", "First offense")+ unblockCustomer(store, "cust_1")++ const reblock = blockCustomer(store, "cust_1", "admin_2", "Second offense")+ expect(isBlocked(store, "cust_1")).toBe(true)+ expect(reblock.blocked_by).toBe("admin_2")+ expect(reblock.reason).toBe("Second offense")+ })+ })++ describe("block status checking", () => {+ it("returns false for non-blocked customer", () => {+ const store = createStore()+ expect(isBlocked(store, "cust_1")).toBe(false)+ })++ it("returns true for blocked customer", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")+ expect(isBlocked(store, "cust_1")).toBe(true)+ })+ })++ describe("batch checking (checkBuyersBlocked)", () => {+ it("returns empty set for empty input", () => {+ const store = createStore()+ const result = checkBuyersBlocked(store, [])+ expect(result.size).toBe(0)+ })++ it("returns empty set when no buyers are blocked", () => {+ const store = createStore()+ const result = checkBuyersBlocked(store, ["cust_1", "cust_2", "cust_3"])+ expect(result.size).toBe(0)+ })++ it("returns only blocked buyer IDs", () => {+ const store = createStore()+ blockCustomer(store, "cust_2", "admin_1")+ blockCustomer(store, "cust_4", "admin_1")++ const result = checkBuyersBlocked(store, [+ "cust_1",+ "cust_2",+ "cust_3",+ "cust_4",+ "cust_5",+ ])++ expect(result.size).toBe(2)+ expect(result.has("cust_2")).toBe(true)+ expect(result.has("cust_4")).toBe(true)+ expect(result.has("cust_1")).toBe(false)+ })++ it("handles duplicate IDs in input", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ const result = checkBuyersBlocked(store, [+ "cust_1",+ "cust_1",+ "cust_1",+ ])++ expect(result.size).toBe(1)+ expect(result.has("cust_1")).toBe(true)+ })+ })++ describe("send-message enforcement (validateChatBlock)", () => {+ describe("customer as sender", () => {+ it("allows non-blocked customer to send", () => {+ const store = createStore()+ const result = validateChatBlock(store, "cust_1", "customer", "seller_1")+ expect(result.allowed).toBe(true)+ })++ it("blocks suspended customer from sending", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ const result = validateChatBlock(store, "cust_1", "customer", "seller_1")+ expect(result.allowed).toBe(false)+ expect(result.reason).toBe("Your chat access has been suspended")+ })++ it("does not affect other customers", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ expect(+ validateChatBlock(store, "cust_2", "customer", "seller_1").allowed+ ).toBe(true)+ })+ })++ describe("seller as sender (messaging blocked customer)", () => {+ it("allows seller to message non-blocked customer", () => {+ const store = createStore()+ const result = validateChatBlock(store, "seller_1", "seller", "cust_1")+ expect(result.allowed).toBe(true)+ })++ it("prevents seller from messaging blocked customer", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ const result = validateChatBlock(store, "seller_1", "seller", "cust_1")+ expect(result.allowed).toBe(false)+ expect(result.reason).toBe(+ "Cannot send messages to a blocked customer"+ )+ })++ it("seller can still message other customers", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ expect(+ validateChatBlock(store, "seller_1", "seller", "cust_2").allowed+ ).toBe(true)+ })+ })++ describe("block enforcement is bidirectional", () => {+ it("both directions blocked for same customer", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ // Customer can't send+ expect(+ validateChatBlock(store, "cust_1", "customer", "seller_1").allowed+ ).toBe(false)++ // Vendor can't send to blocked customer+ expect(+ validateChatBlock(store, "seller_1", "seller", "cust_1").allowed+ ).toBe(false)+ })++ it("unblocking restores both directions", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")+ unblockCustomer(store, "cust_1")++ expect(+ validateChatBlock(store, "cust_1", "customer", "seller_1").allowed+ ).toBe(true)+ expect(+ validateChatBlock(store, "seller_1", "seller", "cust_1").allowed+ ).toBe(true)+ })+ })+ })++ describe("conversation creation enforcement", () => {+ it("blocked customer cannot create conversation", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ // Simulates the route-level check before conversation creation+ expect(isBlocked(store, "cust_1")).toBe(true)+ })++ it("non-blocked customer can create conversation", () => {+ const store = createStore()+ expect(isBlocked(store, "cust_1")).toBe(false)+ })+ })++ describe("admin-only management", () => {+ it("block records track admin accountability", () => {+ const store = createStore()+ const block = blockCustomer(store, "cust_1", "admin_42", "Spamming")++ expect(block.blocked_by).toBe("admin_42")+ expect(block.reason).toBe("Spamming")+ expect(block.created_at).toBeInstanceOf(Date)+ })+ })++ describe("multi-customer scenarios", () => {+ it("blocking one customer does not affect others", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")++ expect(isBlocked(store, "cust_1")).toBe(true)+ expect(isBlocked(store, "cust_2")).toBe(false)+ expect(isBlocked(store, "cust_3")).toBe(false)+ })++ it("multiple customers can be blocked independently", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")+ blockCustomer(store, "cust_3", "admin_2")++ expect(isBlocked(store, "cust_1")).toBe(true)+ expect(isBlocked(store, "cust_2")).toBe(false)+ expect(isBlocked(store, "cust_3")).toBe(true)+ })++ it("unblocking one does not affect the other", () => {+ const store = createStore()+ blockCustomer(store, "cust_1", "admin_1")+ blockCustomer(store, "cust_2", "admin_1")++ unblockCustomer(store, "cust_1")++ expect(isBlocked(store, "cust_1")).toBe(false)+ expect(isBlocked(store, "cust_2")).toBe(true)+ })+ })++ describe("full lifecycle", () => {+ it("block → verify → unblock → re-block cycle", () => {+ const store = createStore()++ // Customer starts unblocked+ expect(isBlocked(store, "cust_1")).toBe(false)+ expect(+ validateChatBlock(store, "cust_1", "customer", "seller_1").allowed+ ).toBe(true)++ // Admin blocks customer+ blockCustomer(store, "cust_1", "admin_1", "Harassment")+ expect(isBlocked(store, "cust_1")).toBe(true)+ expect(+ validateChatBlock(store, "cust_1", "customer", "seller_1").allowed+ ).toBe(false)+ expect(+ validateChatBlock(store, "seller_1", "seller", "cust_1").allowed+ ).toBe(false)++ // Admin unblocks customer+ unblockCustomer(store, "cust_1")+ expect(isBlocked(store, "cust_1")).toBe(false)+ expect(+ validateChatBlock(store, "cust_1", "customer", "seller_1").allowed+ ).toBe(true)++ // Re-block with different admin and reason+ const reblock = blockCustomer(store, "cust_1", "admin_2", "Repeat offense")+ expect(reblock.blocked_by).toBe("admin_2")+ expect(reblock.reason).toBe("Repeat offense")+ expect(+ validateChatBlock(store, "cust_1", "customer", "seller_1").allowed+ ).toBe(false)+ })+ })+})diff --git a/packages/registry/src/messaging/__tests__/unit/content-filter-eval.spec.ts b/packages/registry/src/messaging/__tests__/unit/content-filter-eval.spec.tsnew file mode 100644index 000000000..5313d9a0a--- /dev/null+++ b/packages/registry/src/messaging/__tests__/unit/content-filter-eval.spec.ts@@ -0,0 +1,256 @@+import { describe, it, expect } from "vitest"+import type {+ CompiledRuleset,+ FilterEvaluationResult,+} from "../../modules/messaging-filters/types/common"++/**+ * Standalone evaluation function matching the logic in MessagingFiltersModuleService.evaluateMessage()+ * This allows testing the filter evaluation algorithm without instantiating the full service.+ */+function evaluateMessage(+ body: string,+ ruleset: CompiledRuleset+): FilterEvaluationResult {+ const lowercasedBody = body.toLowerCase()+ const words = lowercasedBody.split(/\s+/)++ // 1. Exact word match+ for (const word of words) {+ if (ruleset.exactWords.has(word)) {+ const ruleId = ruleset.exactRules.get(word)+ return {+ matched: true,+ rule_id: ruleId,+ match_type: "exact",+ pattern: word,+ }+ }+ }++ // 2. Contains match+ for (const entry of ruleset.containsPatterns) {+ if (lowercasedBody.includes(entry.pattern)) {+ return {+ matched: true,+ rule_id: entry.id,+ match_type: "contains",+ pattern: entry.pattern,+ }+ }+ }++ // 3. Regex match+ for (const entry of ruleset.regexPatterns) {+ if (entry.regex.test(body)) {+ return {+ matched: true,+ rule_id: entry.id,+ match_type: "regex",+ pattern: entry.regex.source,+ }+ }+ }++ return { matched: false }+}++function createEmptyRuleset(): CompiledRuleset {+ return {+ exactWords: new Set<string>(),+ exactRules: new Map<string, string>(),+ containsPatterns: [],+ regexPatterns: [],+ }+}++describe("Content Filter Evaluation", () => {+ describe("Exact match", () => {+ it("matches exact word (case-insensitive)", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("spam")+ ruleset.exactRules.set("spam", "filt_001")++ const result = evaluateMessage("This is SPAM content", ruleset)+ expect(result.matched).toBe(true)+ expect(result.rule_id).toBe("filt_001")+ expect(result.match_type).toBe("exact")+ })++ it("does not match partial words for exact match", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("spam")+ ruleset.exactRules.set("spam", "filt_001")++ // "spammer" should NOT match exact "spam"+ const result = evaluateMessage("He is a spammer", ruleset)+ expect(result.matched).toBe(false)+ })++ it("matches when word is at beginning/end of message", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("badword")+ ruleset.exactRules.set("badword", "filt_002")++ expect(evaluateMessage("badword is here", ruleset).matched).toBe(true)+ expect(evaluateMessage("here is badword", ruleset).matched).toBe(true)+ })+ })++ describe("Contains match", () => {+ it("matches substring (case-insensitive)", () => {+ const ruleset = createEmptyRuleset()+ ruleset.containsPatterns.push({ id: "filt_010", pattern: "buy now" })++ const result = evaluateMessage("You should BUY NOW at discount", ruleset)+ expect(result.matched).toBe(true)+ expect(result.rule_id).toBe("filt_010")+ expect(result.match_type).toBe("contains")+ })++ it("matches when pattern appears inside a word", () => {+ const ruleset = createEmptyRuleset()+ ruleset.containsPatterns.push({ id: "filt_011", pattern: "crypto" })++ const result = evaluateMessage("Check cryptocurrency prices", ruleset)+ expect(result.matched).toBe(true)+ })++ it("does not match when pattern is absent", () => {+ const ruleset = createEmptyRuleset()+ ruleset.containsPatterns.push({ id: "filt_012", pattern: "scam" })++ const result = evaluateMessage("This is a legitimate offer", ruleset)+ expect(result.matched).toBe(false)+ })+ })++ describe("Regex match (built-in patterns)", () => {+ it("matches email addresses", () => {+ const ruleset = createEmptyRuleset()+ ruleset.regexPatterns.push({+ id: "filt_builtin_email",+ regex: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/i,+ })++ const result = evaluateMessage("Contact me at [email protected]", ruleset)+ expect(result.matched).toBe(true)+ expect(result.rule_id).toBe("filt_builtin_email")+ expect(result.match_type).toBe("regex")+ })++ it("matches phone numbers", () => {+ const ruleset = createEmptyRuleset()+ ruleset.regexPatterns.push({+ id: "filt_builtin_phone",+ regex: /(\+?\d{1,3}[-.\s]?)?(\(?\d{2,4}\)?[-.\s]?)?\d{3,4}[-.\s]?\d{3,4}/i,+ })++ const result = evaluateMessage("Call me at +1-555-123-4567", ruleset)+ expect(result.matched).toBe(true)+ })++ it("matches URLs", () => {+ const ruleset = createEmptyRuleset()+ ruleset.regexPatterns.push({+ id: "filt_builtin_url",+ regex: /https?:\/\/[^\s]+|www\.[^\s]+/i,+ })++ expect(+ evaluateMessage("Visit https://example.com", ruleset).matched+ ).toBe(true)+ expect(+ evaluateMessage("Go to www.example.com", ruleset).matched+ ).toBe(true)+ })++ it("does not match clean messages", () => {+ const ruleset = createEmptyRuleset()+ ruleset.regexPatterns.push({+ id: "filt_builtin_email",+ regex: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/i,+ })++ const result = evaluateMessage("Is this product available in blue?", ruleset)+ expect(result.matched).toBe(false)+ })+ })++ describe("Priority and short-circuit", () => {+ it("exact match takes priority over contains", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("spam")+ ruleset.exactRules.set("spam", "filt_exact")+ ruleset.containsPatterns.push({ id: "filt_contains", pattern: "spam" })++ const result = evaluateMessage("This is spam", ruleset)+ expect(result.rule_id).toBe("filt_exact")+ expect(result.match_type).toBe("exact")+ })++ it("contains takes priority over regex", () => {+ const ruleset = createEmptyRuleset()+ ruleset.containsPatterns.push({ id: "filt_contains", pattern: "user@" })+ ruleset.regexPatterns.push({+ id: "filt_regex",+ regex: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/i,+ })++ const result = evaluateMessage("Contact [email protected]", ruleset)+ expect(result.rule_id).toBe("filt_contains")+ expect(result.match_type).toBe("contains")+ })++ it("short-circuits on first match (does not check all rules)", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("spam")+ ruleset.exactRules.set("spam", "filt_first")+ ruleset.exactWords.add("virus")+ ruleset.exactRules.set("virus", "filt_second")++ // "spam" appears as first matching word+ const result = evaluateMessage("spam virus", ruleset)+ expect(result.matched).toBe(true)+ expect(result.rule_id).toBe("filt_first")+ })+ })++ describe("Empty ruleset", () => {+ it("passes all messages when ruleset is empty", () => {+ const ruleset = createEmptyRuleset()++ expect(evaluateMessage("Buy now! Contact [email protected]", ruleset).matched).toBe(false)+ expect(evaluateMessage("Call +1-555-0000", ruleset).matched).toBe(false)+ expect(evaluateMessage("Visit https://evil.com", ruleset).matched).toBe(false)+ })+ })++ describe("Edge cases", () => {+ it("handles empty message body", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("spam")+ ruleset.exactRules.set("spam", "filt_001")++ const result = evaluateMessage("", ruleset)+ expect(result.matched).toBe(false)+ })++ it("handles message with only whitespace", () => {+ const ruleset = createEmptyRuleset()+ ruleset.exactWords.add("spam")+ ruleset.exactRules.set("spam", "filt_001")++ const result = evaluateMessage(" \n\t ", ruleset)+ expect(result.matched).toBe(false)+ })++ it("handles unicode characters", () => {+ const ruleset = createEmptyRuleset()+ ruleset.containsPatterns.push({ id: "filt_emoji", pattern: "🔥sale" })++ const result = evaluateMessage("Check this 🔥sale out!", ruleset)+ expect(result.matched).toBe(true)+ })+ })+})diff --git a/packages/registry/src/messaging/__tests__/unit/cursor-encoding.spec.ts b/packages/registry/src/messaging/__tests__/unit/cursor-encoding.spec.tsnew file mode 100644index 000000000..808f95ca7--- /dev/null+++ b/packages/registry/src/messaging/__tests__/unit/cursor-encoding.spec.ts@@ -0,0 +1,106 @@+import { describe, it, expect } from "vitest"+import {+ encodeCursor,+ decodeCursor,+} from "../../modules/messaging/service"++describe("Cursor Encoding", () => {+ describe("encodeCursor", () => {+ it("encodes a conversation cursor (last_message_at, id)", () => {+ const cursor = encodeCursor({+ last_message_at: "2026-01-15T10:30:00.000Z",+ id: "conv_abc123",+ })++ expect(cursor).toBeTruthy()+ expect(typeof cursor).toBe("string")++ // Should be base64url encoded+ expect(cursor).not.toContain("+")+ expect(cursor).not.toContain("/")+ expect(cursor).not.toContain("=")+ })++ it("encodes a message cursor (created_at, id)", () => {+ const cursor = encodeCursor({+ created_at: "2026-01-15T10:30:00.000Z",+ id: "msg_xyz789",+ })++ expect(cursor).toBeTruthy()+ expect(typeof cursor).toBe("string")+ })++ it("handles null values in cursor", () => {+ const cursor = encodeCursor({+ last_message_at: null,+ id: null,+ })++ expect(cursor).toBeTruthy()+ const decoded = decodeCursor(cursor)+ expect(decoded).toEqual({+ last_message_at: null,+ id: null,+ })+ })++ it("handles numeric values", () => {+ const cursor = encodeCursor({+ last_message_at: 1705312200000,+ id: "conv_123",+ })++ const decoded = decodeCursor(cursor)+ expect(decoded?.last_message_at).toBe(1705312200000)+ expect(decoded?.id).toBe("conv_123")+ })+ })++ describe("decodeCursor", () => {+ it("decodes a valid cursor back to original values", () => {+ const original = {+ last_message_at: "2026-01-15T10:30:00.000Z",+ id: "conv_abc123",+ }++ const cursor = encodeCursor(original)+ const decoded = decodeCursor(cursor)++ expect(decoded).toEqual(original)+ })++ it("returns null for empty string", () => {+ const decoded = decodeCursor("")+ expect(decoded).toBeNull()+ })++ it("returns null for malformed input", () => {+ expect(decodeCursor("not-valid-base64url!!!")).toBeNull()+ })++ it("returns null for invalid JSON after decoding", () => {+ // Valid base64url but not JSON+ const notJson = Buffer.from("hello world").toString("base64url")+ expect(decodeCursor(notJson)).toBeNull()+ })++ it("roundtrips correctly for conversation cursors", () => {+ const values = {+ last_message_at: "2026-03-27T15:00:00.000Z",+ id: "conv_m3rcur",+ }++ expect(decodeCursor(encodeCursor(values))).toEqual(values)+ })++ it("roundtrips correctly for message cursors", () => {+ const values = {+ created_at: "2026-03-27T15:00:00.000Z",+ id: "msg_abc123",+ }++ expect(decodeCursor(encodeCursor(values))).toEqual(values)+ })+ })+})diff --git a/packages/registry/src/messaging/__tests__/unit/rate-limit.spec.ts b/packages/registry/src/messaging/__tests__/unit/rate-limit.spec.tsnew file mode 100644index 000000000..d9e08cc7f--- /dev/null+++ b/packages/registry/src/messaging/__tests__/unit/rate-limit.spec.ts@@ -0,0 +1,241 @@+import { describe, it, expect } from "vitest"++import { MESSAGING_MODULE_OPTION_DEFAULTS } from "../../modules/messaging/types/common"++/**+ * Tests for rate limit sliding window logic.+ * The actual rate limiting uses Redis INCR + EXPIRE in validate-rate-limit step.+ * These tests verify the algorithm behavior without Redis.+ */++type RateLimitState = {+ counters: Map<string, { count: number; expiresAt: number }>+}++const MESSAGES_PER_MINUTE = MESSAGING_MODULE_OPTION_DEFAULTS.rateLimits.messagesPerMinute+const CONVERSATIONS_PER_HOUR = MESSAGING_MODULE_OPTION_DEFAULTS.rateLimits.conversationsPerHour+const MSG_WINDOW_MS = 60_000+const CONV_WINDOW_MS = 3_600_000++function createState(): RateLimitState {+ return { counters: new Map() }+}++function incrementCounter(+ state: RateLimitState,+ key: string,+ windowMs: number,+ now: number+): number {+ const existing = state.counters.get(key)++ if (!existing || existing.expiresAt <= now) {+ // Key expired or doesn't exist — start new window+ state.counters.set(key, { count: 1, expiresAt: now + windowMs })+ return 1+ }++ existing.count+++ return existing.count+}++function checkRateLimit(+ state: RateLimitState,+ senderId: string,+ isNewConversation: boolean,+ now: number+): { allowed: boolean; reason?: string } {+ const msgKey = `ratelimit:msg:${senderId}`+ const msgCount = incrementCounter(state, msgKey, MSG_WINDOW_MS, now)++ if (msgCount > MESSAGES_PER_MINUTE) {+ return { allowed: false, reason: "message_rate_exceeded" }+ }++ if (isNewConversation) {+ const convKey = `ratelimit:conv:${senderId}`+ const convCount = incrementCounter(state, convKey, CONV_WINDOW_MS, now)++ if (convCount > CONVERSATIONS_PER_HOUR) {+ return { allowed: false, reason: "conversation_rate_exceeded" }+ }+ }++ return { allowed: true }+}++describe("Rate Limit Sliding Window", () => {+ describe("message rate limit (20/min)", () => {+ it("allows first message", () => {+ const state = createState()+ const result = checkRateLimit(state, "user_1", false, Date.now())+ expect(result.allowed).toBe(true)+ })++ it("allows up to 20 messages per minute", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 20; i++) {+ const result = checkRateLimit(state, "user_1", false, now)+ expect(result.allowed).toBe(true)+ }+ })++ it("blocks 21st message within the minute", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 20; i++) {+ checkRateLimit(state, "user_1", false, now)+ }++ const result = checkRateLimit(state, "user_1", false, now)+ expect(result.allowed).toBe(false)+ expect(result.reason).toBe("message_rate_exceeded")+ })++ it("allows messages again after window expires", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 20; i++) {+ checkRateLimit(state, "user_1", false, now)+ }++ // After 60 seconds, window resets+ const afterWindow = now + MSG_WINDOW_MS + 1+ const result = checkRateLimit(state, "user_1", false, afterWindow)+ expect(result.allowed).toBe(true)+ })+ })++ describe("conversation rate limit (5/hour)", () => {+ it("allows first new conversation", () => {+ const state = createState()+ const result = checkRateLimit(state, "user_1", true, Date.now())+ expect(result.allowed).toBe(true)+ })++ it("allows up to 5 new conversations per hour", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 5; i++) {+ const result = checkRateLimit(state, "user_1", true, now)+ expect(result.allowed).toBe(true)+ }+ })++ it("blocks 6th conversation within the hour", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 5; i++) {+ checkRateLimit(state, "user_1", true, now)+ }++ const result = checkRateLimit(state, "user_1", true, now)+ expect(result.allowed).toBe(false)+ expect(result.reason).toBe("conversation_rate_exceeded")+ })++ it("allows new conversations after hour window expires", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 5; i++) {+ checkRateLimit(state, "user_1", true, now)+ }++ const afterWindow = now + CONV_WINDOW_MS + 1+ const result = checkRateLimit(state, "user_1", true, afterWindow)+ expect(result.allowed).toBe(true)+ })++ it("does not check conversation limit for non-new messages", () => {+ const state = createState()+ const now = Date.now()++ // Exhaust conversation limit+ for (let i = 0; i < 6; i++) {+ checkRateLimit(state, "user_1", true, now)+ }++ // Sending to existing conversation should still work (only msg limit applies)+ const result = checkRateLimit(state, "user_1", false, now)+ expect(result.allowed).toBe(true)+ })+ })++ describe("per-user isolation", () => {+ it("rate limits are per-user", () => {+ const state = createState()+ const now = Date.now()++ // User 1 hits limit+ for (let i = 0; i < 20; i++) {+ checkRateLimit(state, "user_1", false, now)+ }++ // User 1 is blocked+ expect(checkRateLimit(state, "user_1", false, now).allowed).toBe(false)++ // User 2 is still allowed+ expect(checkRateLimit(state, "user_2", false, now).allowed).toBe(true)+ })+ })++ describe("applies to both buyers and sellers", () => {+ it("rate limits apply equally to customers", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 20; i++) {+ checkRateLimit(state, "cust_123", false, now)+ }++ expect(checkRateLimit(state, "cust_123", false, now).allowed).toBe(false)+ })++ it("rate limits apply equally to sellers", () => {+ const state = createState()+ const now = Date.now()++ for (let i = 0; i < 20; i++) {+ checkRateLimit(state, "seller_456", false, now)+ }++ expect(checkRateLimit(state, "seller_456", false, now).allowed).toBe(false)+ })+ })++ describe("counter expiry", () => {+ it("counter resets to 1 after window expires", () => {+ const state = createState()+ const now = Date.now()++ checkRateLimit(state, "user_1", false, now)+ checkRateLimit(state, "user_1", false, now)+ checkRateLimit(state, "user_1", false, now)++ const msgKey = "ratelimit:msg:user_1"+ expect(state.counters.get(msgKey)?.count).toBe(3)++ // After window expires, next call starts fresh+ const afterWindow = now + MSG_WINDOW_MS + 1+ checkRateLimit(state, "user_1", false, afterWindow)+ expect(state.counters.get(msgKey)?.count).toBe(1)+ })+ })++ describe("module option defaults", () => {+ it("defaults to 20 messages per minute", () => {+ expect(MESSAGING_MODULE_OPTION_DEFAULTS.rateLimits.messagesPerMinute).toBe(20)+ })++ it("defaults to 5 conversations per hour", () => {+ expect(MESSAGING_MODULE_OPTION_DEFAULTS.rateLimits.conversationsPerHour).toBe(5)+ })+ })+})diff --git a/packages/registry/src/messaging/__tests__/unit/unread-counter.spec.ts b/packages/registry/src/messaging/__tests__/unit/unread-counter.spec.tsnew file mode 100644index 000000000..2210a8741--- /dev/null+++ b/packages/registry/src/messaging/__tests__/unit/unread-counter.spec.ts@@ -0,0 +1,199 @@+import { describe, it, expect } from "vitest"++/**+ * Tests for unread counter logic.+ * The actual counter operations happen in MessagingModuleService.createMessageAtomic()+ * and markMessagesReadAtomic(). These tests verify the logic rules:+ *+ * - Increment recipient counter when message from other party+ * - Do NOT increment sender's own counter+ * - Reset counter to 0 on mark read+ * - Reconciliation corrects drift+ */++type CounterState = {+ unread_count_customer: number+ unread_count_seller: number+}++function simulateSendMessage(+ state: CounterState,+ senderType: "customer" | "seller"+): CounterState {+ // Only the recipient's counter increments+ if (senderType === "customer") {+ return {+ ...state,+ unread_count_seller: state.unread_count_seller + 1,+ }+ } else {+ return {+ ...state,+ unread_count_customer: state.unread_count_customer + 1,+ }+ }+}++function simulateMarkRead(+ state: CounterState,+ readerType: "customer" | "seller"+): CounterState {+ if (readerType === "customer") {+ return { ...state, unread_count_customer: 0 }+ } else {+ return { ...state, unread_count_seller: 0 }+ }+}++function simulateReconcile(+ state: CounterState,+ actualUnreadCustomer: number,+ actualUnreadSeller: number+): { state: CounterState; corrected: boolean } {+ const corrected =+ state.unread_count_customer !== actualUnreadCustomer ||+ state.unread_count_seller !== actualUnreadSeller++ return {+ state: {+ unread_count_customer: actualUnreadCustomer,+ unread_count_seller: actualUnreadSeller,+ },+ corrected,+ }+}++describe("Unread Counter Logic", () => {+ const initial: CounterState = {+ unread_count_customer: 0,+ unread_count_seller: 0,+ }++ describe("increment on message from other party", () => {+ it("increments seller counter when customer sends message", () => {+ const result = simulateSendMessage(initial, "customer")+ expect(result.unread_count_seller).toBe(1)+ expect(result.unread_count_customer).toBe(0) // sender's counter unchanged+ })++ it("increments customer counter when seller sends message", () => {+ const result = simulateSendMessage(initial, "seller")+ expect(result.unread_count_customer).toBe(1)+ expect(result.unread_count_seller).toBe(0) // sender's counter unchanged+ })++ it("accumulates unread count across multiple messages", () => {+ let state = initial+ state = simulateSendMessage(state, "customer") // seller: 1+ state = simulateSendMessage(state, "customer") // seller: 2+ state = simulateSendMessage(state, "customer") // seller: 3++ expect(state.unread_count_seller).toBe(3)+ expect(state.unread_count_customer).toBe(0)+ })+ })++ describe("no increment on own message", () => {+ it("does not increment sender's own counter", () => {+ let state = initial+ state = simulateSendMessage(state, "customer")+ // Customer sends message — customer's own counter stays 0+ expect(state.unread_count_customer).toBe(0)++ state = simulateSendMessage(state, "seller")+ // Seller sends message — seller's own counter stays at 1 (from buyer's message)+ expect(state.unread_count_seller).toBe(1)+ })+ })++ describe("reset on mark read", () => {+ it("resets customer counter to 0 when customer reads", () => {+ let state = initial+ state = simulateSendMessage(state, "seller") // customer: 1+ state = simulateSendMessage(state, "seller") // customer: 2++ state = simulateMarkRead(state, "customer")+ expect(state.unread_count_customer).toBe(0)+ })++ it("resets seller counter to 0 when seller reads", () => {+ let state = initial+ state = simulateSendMessage(state, "customer") // seller: 1+ state = simulateSendMessage(state, "customer") // seller: 2+ state = simulateSendMessage(state, "customer") // seller: 3++ state = simulateMarkRead(state, "seller")+ expect(state.unread_count_seller).toBe(0)+ })++ it("does not affect other party's counter", () => {+ let state = initial+ state = simulateSendMessage(state, "customer") // seller: 1+ state = simulateSendMessage(state, "seller") // customer: 1++ state = simulateMarkRead(state, "customer")+ expect(state.unread_count_customer).toBe(0)+ expect(state.unread_count_seller).toBe(1) // seller's counter unchanged+ })+ })++ describe("reconciliation correction", () => {+ it("corrects drifted counter", () => {+ const drifted: CounterState = {+ unread_count_customer: 5,+ unread_count_seller: 3,+ }++ const { state, corrected } = simulateReconcile(drifted, 2, 1)+ expect(corrected).toBe(true)+ expect(state.unread_count_customer).toBe(2)+ expect(state.unread_count_seller).toBe(1)+ })++ it("does not flag correction when counts match", () => {+ const correct: CounterState = {+ unread_count_customer: 2,+ unread_count_seller: 1,+ }++ const { corrected } = simulateReconcile(correct, 2, 1)+ expect(corrected).toBe(false)+ })++ it("corrects zero drift", () => {+ const drifted: CounterState = {+ unread_count_customer: 0,+ unread_count_seller: 2,+ }++ const { state, corrected } = simulateReconcile(drifted, 0, 0)+ expect(corrected).toBe(true)+ expect(state.unread_count_seller).toBe(0)+ })+ })++ describe("full conversation flow", () => {+ it("handles typical back-and-forth conversation", () => {+ let state = initial++ // Buyer sends 3 messages+ state = simulateSendMessage(state, "customer")+ state = simulateSendMessage(state, "customer")+ state = simulateSendMessage(state, "customer")+ expect(state.unread_count_seller).toBe(3)+ expect(state.unread_count_customer).toBe(0)++ // Seller reads and replies+ state = simulateMarkRead(state, "seller")+ expect(state.unread_count_seller).toBe(0)++ state = simulateSendMessage(state, "seller")+ expect(state.unread_count_customer).toBe(1)++ // Buyer reads+ state = simulateMarkRead(state, "customer")+ expect(state.unread_count_customer).toBe(0)+ expect(state.unread_count_seller).toBe(0)+ })+ })+})diff --git a/packages/registry/src/messaging/admin/hooks/api/filters.tsx b/packages/registry/src/messaging/admin/hooks/api/filters.tsxnew file mode 100644index 000000000..45bb51df1--- /dev/null+++ b/packages/registry/src/messaging/admin/hooks/api/filters.tsx@@ -0,0 +1,127 @@+import {+ useQuery,+ useMutation,+ useQueryClient,+ UseQueryOptions,+ UseMutationOptions,+} from "@tanstack/react-query"+import { client } from "../../lib/client"+import { ClientError } from "@mercurjs/client"++const FILTERS_KEY = "admin_messaging_filters" as const+const BLOCKED_KEY = "admin_messaging_blocked" as const++export type FilterRuleDTO = {+ id: string+ match_type: "exact" | "contains" | "regex"+ pattern: string+ is_builtin: boolean+ is_enabled: boolean+ description: string | null+ created_at: string+ updated_at: string+}++export type BlockedMessageDTO = {+ id: string+ sender_id: string+ sender_type: "customer" | "seller"+ conversation_id: string+ matched_rule_id: string+ message_body: string+ created_at: string+}++type FilterListResponse = {+ filter_rules: FilterRuleDTO[]+ count: number+}++type BlockedListResponse = {+ blocked_messages: BlockedMessageDTO[]+ count: number+}++export const useAdminFilters = (+ options?: Omit<UseQueryOptions<FilterListResponse, ClientError>, "queryKey" | "queryFn">+) => {+ const { data, ...rest } = useQuery({+ queryKey: [FILTERS_KEY],+ queryFn: async () =>+ (client as any).admin.messages.filters.query() as Promise<FilterListResponse>,+ ...options,+ })++ return { ...data, ...rest }+}++export const useCreateFilter = (+ options?: UseMutationOptions<+ { filter_rule: FilterRuleDTO },+ ClientError,+ { match_type: string; pattern: string; description?: string; is_enabled?: boolean }+ >+) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: (payload) =>+ (client as any).admin.messages.filters.mutate(payload) as Promise<{ filter_rule: FilterRuleDTO }>,+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({ queryKey: [FILTERS_KEY] })+ options?.onSuccess?.(data, variables, context)+ },+ ...options,+ })+}++export const useUpdateFilter = (+ id: string,+ options?: UseMutationOptions<+ { filter_rule: FilterRuleDTO },+ ClientError,+ Record<string, any>+ >+) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: (payload) =>+ (client as any).admin.messages.filters.$id.mutate({ $id: id, ...payload }) as Promise<{ filter_rule: FilterRuleDTO }>,+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({ queryKey: [FILTERS_KEY] })+ options?.onSuccess?.(data, variables, context)+ },+ ...options,+ })+}++export const useDeleteFilter = (+ options?: UseMutationOptions<{ id: string; deleted: boolean }, ClientError, string>+) => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: (id: string) =>+ (client as any).admin.messages.filters.$id.delete({ $id: id }) as Promise<{ id: string; deleted: boolean }>,+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({ queryKey: [FILTERS_KEY] })+ options?.onSuccess?.(data, variables, context)+ },+ ...options,+ })+}++export const useAdminBlockedMessages = (+ query?: { sender_type?: string; date_from?: string; date_to?: string },+ options?: Omit<UseQueryOptions<BlockedListResponse, ClientError>, "queryKey" | "queryFn">+) => {+ const { data, ...rest } = useQuery({+ queryKey: [BLOCKED_KEY, query],+ queryFn: async () =>+ (client as any).admin.messages.blocked.query(query ?? {}) as Promise<BlockedListResponse>,+ ...options,+ })++ return { ...data, ...rest }+}diff --git a/packages/registry/src/messaging/admin/hooks/api/messaging.tsx b/packages/registry/src/messaging/admin/hooks/api/messaging.tsxnew file mode 100644index 000000000..9e7b55833--- /dev/null+++ b/packages/registry/src/messaging/admin/hooks/api/messaging.tsx@@ -0,0 +1,135 @@+import {+ useQuery,+ useInfiniteQuery,+ useMutation,+ useQueryClient,+ UseQueryOptions,+} from "@tanstack/react-query"+import { client } from "../../lib/client"+import { ClientError } from "@mercurjs/client"++const ADMIN_CONVERSATIONS_KEY = "admin_conversations" as const+const ADMIN_CONVERSATION_KEY = "admin_conversation" as const++export type AdminConversationDTO = {+ id: string+ buyer_id: string+ seller_id: string+ buyer_name?: string | null+ buyer_email?: string | null+ seller_name?: string | null+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_customer: number+ unread_count_seller: number+ created_at: string+ is_buyer_blocked?: boolean+ block_reason?: string | null+}++export type AdminMessageDTO = {+ id: string+ sender_id: string+ sender_type: "customer" | "seller"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: string | null+ created_at: string+}++type AdminConversationListResponse = {+ conversations: AdminConversationDTO[]+ next_cursor: string | null+}++type AdminConversationDetailResponse = {+ conversation: AdminConversationDTO+ messages: AdminMessageDTO[]+ next_cursor: string | null+}++type SearchParams = {+ cursor?: string+ limit?: number+ seller_name?: string+ buyer_name?: string+ date_from?: string+ date_to?: string+ context_type?: string+ context_id?: string+}++export const useAdminConversations = (+ query?: SearchParams,+ options?: Omit<UseQueryOptions<AdminConversationListResponse, ClientError>, "queryKey" | "queryFn">+) => {+ const { data, ...rest } = useQuery({+ queryKey: [ADMIN_CONVERSATIONS_KEY, query],+ queryFn: async () =>+ (client as any).admin.messages.query(query ?? {}) as Promise<AdminConversationListResponse>,+ ...options,+ })++ return { ...data, ...rest }+}++export const useAdminConversation = (+ id: string,+ query?: { limit?: number },+) => {+ const limit = query?.limit ?? 20++ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, ...rest } =+ useInfiniteQuery<AdminConversationDetailResponse, ClientError>({+ queryKey: [ADMIN_CONVERSATION_KEY, id, { limit }],+ queryFn: async ({ pageParam }) =>+ (client as any).admin.messages.$id.query({+ $id: id,+ limit,+ ...(pageParam ? { cursor: pageParam } : {}),+ }) as Promise<AdminConversationDetailResponse>,+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (lastPage) => lastPage.next_cursor ?? undefined,+ })++ const conversation = data?.pages[0]?.conversation+ const messages = data?.pages.flatMap((p) => p.messages) ?? []++ return {+ conversation,+ messages,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ ...rest,+ }+}++export const useBlockCustomer = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: async (data: { customer_id: string; reason?: string }) =>+ (client as any).admin.messages["chat-blocks"].mutate(data) as Promise<{ block: any }>,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })+ },+ })+}++export const useUnblockCustomer = () => {+ const queryClient = useQueryClient()++ return useMutation({+ mutationFn: async (customerId: string) =>+ (client as any).admin.messages["chat-blocks"].$customer_id.delete({ $customer_id: customerId }) as Promise<{ success: boolean }>,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })+ },+ })+}diff --git a/packages/registry/src/messaging/admin/hooks/api/use-admin-messaging-sse.tsx b/packages/registry/src/messaging/admin/hooks/api/use-admin-messaging-sse.tsxnew file mode 100644index 000000000..49f35e63a--- /dev/null+++ b/packages/registry/src/messaging/admin/hooks/api/use-admin-messaging-sse.tsx@@ -0,0 +1,145 @@+import { useEffect, useRef } from "react"+import { useQueryClient } from "@tanstack/react-query"++declare const __BACKEND_URL__: string++type SSEStatus = "connecting" | "connected" | "disconnected" | "polling"++const ADMIN_CONVERSATIONS_KEY = "admin_conversations"+const ADMIN_CONVERSATION_KEY = "admin_conversation"+const POLLING_INTERVAL = 30000++export const useAdminMessagingSSE = (+ activeConversationId?: string,+ onStatusChange?: (status: SSEStatus) => void+) => {+ const queryClient = useQueryClient()+ const eventSourceRef = useRef<EventSource | null>(null)+ const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null)+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const reconnectDelayRef = useRef(1000)+ const statusRef = useRef<SSEStatus>("disconnected")+ const mountedRef = useRef(true)++ // Store callbacks in refs to avoid dependency chains+ const onStatusChangeRef = useRef(onStatusChange)+ onStatusChangeRef.current = onStatusChange++ useEffect(() => {+ mountedRef.current = true++ const setStatus = (status: SSEStatus) => {+ statusRef.current = status+ onStatusChangeRef.current?.(status)+ }++ const invalidateAll = () => {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })+ }++ const stopPolling = () => {+ if (pollingRef.current) {+ clearInterval(pollingRef.current)+ pollingRef.current = null+ }+ }++ const startPolling = () => {+ if (pollingRef.current) return+ setStatus("polling")++ pollingRef.current = setInterval(() => {+ invalidateAll()+ }, POLLING_INTERVAL)+ }++ const connect = () => {+ if (!mountedRef.current) return++ if (eventSourceRef.current) {+ eventSourceRef.current.close()+ }++ setStatus("connecting")++ const baseUrl = typeof __BACKEND_URL__ !== "undefined" ? __BACKEND_URL__ : ""+ const url = `${baseUrl}/admin/messages/events`++ const es = new EventSource(url, { withCredentials: true })+ eventSourceRef.current = es++ es.addEventListener("connected", () => {+ setStatus("connected")+ stopPolling()+ reconnectDelayRef.current = 1000 // Reset backoff on success+ })++ es.addEventListener("new_message", (event: MessageEvent) => {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })+ try {+ const data = JSON.parse(event.data)+ if (data.conversation_id) {+ queryClient.invalidateQueries({+ queryKey: [ADMIN_CONVERSATION_KEY, data.conversation_id],+ })+ }+ } catch {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })+ }+ })++ es.addEventListener("messages_read", (event: MessageEvent) => {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })+ try {+ const data = JSON.parse(event.data)+ if (data.conversation_id) {+ queryClient.invalidateQueries({+ queryKey: [ADMIN_CONVERSATION_KEY, data.conversation_id],+ })+ }+ } catch {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATION_KEY] })+ }+ })++ es.addEventListener("unread_count", () => {+ queryClient.invalidateQueries({ queryKey: [ADMIN_CONVERSATIONS_KEY] })+ })++ es.onerror = () => {+ es.close()+ eventSourceRef.current = null+ startPolling()++ // Exponential backoff: 1s, 2s, 4s, 8s, ..., max 30s+ const delay = reconnectDelayRef.current+ reconnectDelayRef.current = Math.min(delay * 2, 30000)++ reconnectTimerRef.current = setTimeout(() => {+ reconnectTimerRef.current = null+ if (mountedRef.current && statusRef.current === "polling") {+ connect()+ }+ }, delay)+ }+ }++ connect()++ return () => {+ mountedRef.current = false+ if (eventSourceRef.current) {+ eventSourceRef.current.close()+ eventSourceRef.current = null+ }+ stopPolling()+ if (reconnectTimerRef.current) {+ clearTimeout(reconnectTimerRef.current)+ reconnectTimerRef.current = null+ }+ }+ }, [queryClient]) // queryClient is stable — no re-render loop++ return { status: statusRef.current }+}diff --git a/packages/registry/src/messaging/admin/hooks/use-messaging-layout.ts b/packages/registry/src/messaging/admin/hooks/use-messaging-layout.tsnew file mode 100644index 000000000..6e8df295a--- /dev/null+++ b/packages/registry/src/messaging/admin/hooks/use-messaging-layout.ts@@ -0,0 +1,35 @@+import { useLayoutEffect } from "react"++/**+ * Override the shell's scroll behavior to give the messaging+ * pages a full-height, non-scrolling layout. Restores original+ * styles on unmount.+ */+export function useMessagingLayout() {+ useLayoutEffect(() => {+ const main = document.querySelector("main") as HTMLElement | null+ const contentCol = main?.parentElement as HTMLElement | null+ const gutter = main?.firstElementChild as HTMLElement | null++ const origMain = main?.style.cssText ?? ""+ const origCol = contentCol?.style.cssText ?? ""+ const origGutter = gutter?.style.cssText ?? ""++ if (contentCol) contentCol.style.overflow = "hidden"+ if (main) {+ main.style.overflow = "hidden"+ main.style.minHeight = "0"+ }+ if (gutter) {+ gutter.style.flex = "1"+ gutter.style.minHeight = "0"+ gutter.style.overflow = "hidden"+ }++ return () => {+ if (main) main.style.cssText = origMain+ if (contentCol) contentCol.style.cssText = origCol+ if (gutter) gutter.style.cssText = origGutter+ }+ }, [])+}diff --git a/packages/registry/src/messaging/admin/lib/client.ts b/packages/registry/src/messaging/admin/lib/client.tsnew file mode 100644index 000000000..67eba000c--- /dev/null+++ b/packages/registry/src/messaging/admin/lib/client.ts@@ -0,0 +1,12 @@+// DO NOT ADD THIS TO registry.json - internal use only for type checking in the mercur monorepo+import { createClient, InferClient } from "@mercurjs/client"+import { Routes } from '../../../../.mercur/_generated'++declare const __BACKEND_URL__: string++export const client: InferClient<Routes> = createClient({+ baseUrl: __BACKEND_URL__,+ fetchOptions: {+ credentials: 'include',+ },+})diff --git a/packages/registry/src/messaging/admin/routes/messages/[id]/page.tsx b/packages/registry/src/messaging/admin/routes/messages/[id]/page.tsxnew file mode 100644index 000000000..86be9ce6a--- /dev/null+++ b/packages/registry/src/messaging/admin/routes/messages/[id]/page.tsx@@ -0,0 +1,307 @@+import { useRef, useState } from "react"+import { useParams } from "react-router-dom"+import { Badge, Button, Container, Heading, Input, Label, Text, clx, toast, usePrompt } from "@medusajs/ui"++import {+ useAdminConversation,+ useBlockCustomer,+ useUnblockCustomer,+ AdminMessageDTO,+} from "../../../hooks/api/messaging"+import { useAdminMessagingSSE } from "../../../hooks/api/use-admin-messaging-sse"+import { useMessagingLayout } from "../../../hooks/use-messaging-layout"++const formatTime = (dateStr: string): string => {+ const date = new Date(dateStr)+ return `${date.toLocaleDateString([], { month: "short", day: "numeric" })} ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`+}++const MessageRow = ({ message }: { message: AdminMessageDTO }) => {+ const isCustomer = message.sender_type === "customer"++ return (+ <div+ className={clx(+ "flex flex-col gap-0.5",+ isCustomer ? "items-start" : "items-end"+ )}+ >+ {message.context_type && (+ <Badge color="grey" size="2xsmall">+ {message.context_label || `${message.context_type}: ${message.context_id}`}+ </Badge>+ )}+ <div+ className={clx(+ "max-w-[70%] rounded-lg px-3 py-2",+ isCustomer+ ? "bg-ui-bg-subtle text-ui-fg-base"+ : "bg-ui-bg-field text-ui-fg-base"+ )}+ >+ <Text size="xsmall" className="text-ui-fg-muted mb-0.5">+ {isCustomer ? "Customer" : "Vendor"}+ </Text>+ <Text size="small" leading="compact">+ {message.body}+ </Text>+ </div>+ <Text size="xsmall" className="text-ui-fg-muted px-1">+ {formatTime(message.created_at)}+ {message.read_at && " · Read"}+ </Text>+ </div>+ )+}++const AdminConversationDetailPage = () => {+ const { id } = useParams<{ id: string }>()+ useAdminMessagingSSE(id)+ const prompt = usePrompt()++ const rootRef = useRef<HTMLDivElement>(null)+ const [showBlockDialog, setShowBlockDialog] = useState(false)+ const [blockReason, setBlockReason] = useState("")++ const blockMutation = useBlockCustomer()+ const unblockMutation = useUnblockCustomer()++ const {+ conversation,+ messages,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ isLoading,+ isError,+ error,+ } = useAdminConversation(id!)++ const handleBlock = () => {+ if (!conversation?.buyer_id) return+ blockMutation.mutate(+ {+ customer_id: conversation.buyer_id,+ reason: blockReason || undefined,+ },+ {+ onSuccess: () => {+ toast.success("Customer blocked from chat")+ setShowBlockDialog(false)+ setBlockReason("")+ },+ onError: () => {+ toast.error("Failed to block customer")+ },+ }+ )+ }++ const handleUnblock = async () => {+ if (!conversation?.buyer_id) return+ const confirmed = await prompt({+ title: "Unblock Customer",+ description:+ "Are you sure you want to unblock this customer? They will be able to use chat again.",+ })+ if (!confirmed) return++ unblockMutation.mutate(conversation.buyer_id, {+ onSuccess: () => {+ toast.success("Customer unblocked")+ },+ onError: () => {+ toast.error("Failed to unblock customer")+ },+ })+ }++ useMessagingLayout()++ if (isError) throw error++ if (isLoading) {+ return (+ <div className="flex items-center justify-center py-12">+ <Text className="text-ui-fg-muted">Loading conversation...</Text>+ </div>+ )+ }++ const displayMessages = [...(messages ?? [])].reverse()++ return (+ <div ref={rootRef} className="flex gap-4 h-full min-h-0">+ {/* Main: Read-only message thread */}+ <div className="flex-1 flex flex-col min-h-0 bg-ui-bg-base rounded-lg shadow-elevation-card-rest overflow-hidden">+ <div className="flex items-center justify-between px-6 py-4 border-b border-ui-border-base shrink-0">+ <Heading level="h2">Conversation</Heading>+ <Badge color="grey" size="small">+ Read-only+ </Badge>+ </div>+ <div className="flex-1 flex flex-col gap-3 px-6 py-4 overflow-y-auto min-h-0">+ {hasNextPage && (+ <div className="flex justify-center shrink-0">+ <Button+ size="small"+ variant="secondary"+ onClick={() => fetchNextPage()}+ disabled={isFetchingNextPage}+ isLoading={isFetchingNextPage}+ >+ Load older messages+ </Button>+ </div>+ )}+ {displayMessages.map((msg) => (+ <MessageRow key={msg.id} message={msg} />+ ))}+ {!displayMessages.length && (+ <Text className="text-ui-fg-muted text-center py-8">+ No messages in this conversation+ </Text>+ )}+ </div>+ </div>++ {/* Sidebar: Conversation metadata */}+ <div className="w-[300px] shrink-0 overflow-y-auto">+ <Container className="divide-y p-0">+ <div className="px-6 py-4">+ <Text size="small" leading="compact" weight="plus">+ Conversation Details+ </Text>+ </div>+ <div className="px-6 py-3">+ <Text size="xsmall" className="text-ui-fg-muted">+ Vendor+ </Text>+ <Text size="small" leading="compact">+ {conversation?.seller_name || conversation?.seller_id}+ </Text>+ </div>+ <div className="px-6 py-3">+ <Text size="xsmall" className="text-ui-fg-muted">+ Customer+ </Text>+ <div className="flex items-center gap-x-2">+ <Text size="small" leading="compact">+ {conversation?.buyer_name || conversation?.buyer_id}+ </Text>+ {conversation?.is_buyer_blocked && (+ <Badge color="red" size="2xsmall">+ Blocked+ </Badge>+ )}+ </div>+ {conversation?.buyer_email && (+ <Text size="xsmall" className="text-ui-fg-subtle">+ {conversation.buyer_email}+ </Text>+ )}+ {conversation?.is_buyer_blocked && conversation?.block_reason && (+ <Text size="xsmall" className="text-ui-fg-error mt-1">+ Reason: {conversation.block_reason}+ </Text>+ )}+ </div>+ <div className="px-6 py-3">+ <Text size="xsmall" className="text-ui-fg-muted">+ Created+ </Text>+ <Text size="small" leading="compact">+ {conversation?.created_at+ ? new Date(conversation.created_at).toLocaleString()+ : "-"}+ </Text>+ </div>+ <div className="px-6 py-3">+ <Text size="xsmall" className="text-ui-fg-muted">+ Last Activity+ </Text>+ <Text size="small" leading="compact">+ {conversation?.last_message_at+ ? new Date(conversation.last_message_at).toLocaleString()+ : "-"}+ </Text>+ </div>+ <div className="px-6 py-3">+ <Text size="xsmall" className="text-ui-fg-muted">+ Message Count+ </Text>+ <Text size="small" leading="compact">+ {messages?.length ?? 0}+ </Text>+ </div>+ </Container>++ {/* Chat Block Management */}+ <Container className="mt-4 p-0">+ <div className="px-6 py-4">+ <Text size="small" leading="compact" weight="plus">+ Chat Access+ </Text>+ </div>+ <div className="px-6 pb-4">+ {showBlockDialog ? (+ <div className="flex flex-col gap-3">+ <div>+ <Label size="xsmall">Reason (optional)</Label>+ <Input+ size="small"+ placeholder="Why is this customer being blocked?"+ value={blockReason}+ onChange={(e) => setBlockReason(e.target.value)}+ />+ </div>+ <div className="flex gap-2">+ <Button+ size="small"+ variant="danger"+ onClick={handleBlock}+ disabled={blockMutation.isPending}+ isLoading={blockMutation.isPending}+ >+ Confirm Block+ </Button>+ <Button+ size="small"+ variant="secondary"+ onClick={() => {+ setShowBlockDialog(false)+ setBlockReason("")+ }}+ disabled={blockMutation.isPending}+ >+ Cancel+ </Button>+ </div>+ </div>+ ) : conversation?.is_buyer_blocked ? (+ <Button+ size="small"+ variant="secondary"+ onClick={handleUnblock}+ disabled={unblockMutation.isPending}+ isLoading={unblockMutation.isPending}+ >+ Unblock Customer+ </Button>+ ) : (+ <Button+ size="small"+ variant="danger"+ onClick={() => setShowBlockDialog(true)}+ >+ Block Customer+ </Button>+ )}+ </div>+ </Container>+ </div>+ </div>+ )+}++export default AdminConversationDetailPagediff --git a/packages/registry/src/messaging/admin/routes/messages/blocked/page.tsx b/packages/registry/src/messaging/admin/routes/messages/blocked/page.tsxnew file mode 100644index 000000000..f4361e05e--- /dev/null+++ b/packages/registry/src/messaging/admin/routes/messages/blocked/page.tsx@@ -0,0 +1,74 @@+import { Badge, Container, Heading, Text } from "@medusajs/ui"++import { useAdminBlockedMessages, BlockedMessageDTO } from "../../../hooks/api/filters"++const formatDate = (dateStr: string): string => {+ return new Date(dateStr).toLocaleString()+}++const BlockedRow = ({ log }: { log: BlockedMessageDTO }) => {+ return (+ <div className="px-6 py-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Badge+ color={log.sender_type === "customer" ? "blue" : "green"}+ size="2xsmall"+ >+ {log.sender_type}+ </Badge>+ <Text size="small" leading="compact" weight="plus">+ {log.sender_id}+ </Text>+ </div>+ <Text size="xsmall" className="text-ui-fg-muted">+ {formatDate(log.created_at)}+ </Text>+ </div>+ <Text+ size="small"+ leading="compact"+ className="text-ui-fg-subtle mt-1 line-clamp-2"+ >+ {log.message_body}+ </Text>+ </div>+ )+}++const AdminBlockedMessagesPage = () => {+ const { blocked_messages, count, isLoading, isError, error } =+ useAdminBlockedMessages()++ if (isError) throw error++ return (+ <Container className="divide-y p-0">+ <div className="flex items-center justify-between px-6 py-4">+ <Heading>Blocked Messages</Heading>+ {count != null && (+ <Text size="small" className="text-ui-fg-muted">+ {count} total+ </Text>+ )}+ </div>+ {isLoading ? (+ <div className="flex items-center justify-center py-12">+ <Text className="text-ui-fg-muted">Loading...</Text>+ </div>+ ) : !blocked_messages?.length ? (+ <div className="flex items-center justify-center py-12">+ <Text className="text-ui-fg-muted">No blocked messages</Text>+ </div>+ ) : (+ <div className="divide-y">+ {blocked_messages.map((log) => (+ <BlockedRow key={log.id} log={log} />+ ))}+ </div>+ )}+ </Container>+ )+}++export default AdminBlockedMessagesPagediff --git a/packages/registry/src/messaging/admin/routes/messages/filters/page.tsx b/packages/registry/src/messaging/admin/routes/messages/filters/page.tsxnew file mode 100644index 000000000..0992ce6be--- /dev/null+++ b/packages/registry/src/messaging/admin/routes/messages/filters/page.tsx@@ -0,0 +1,204 @@+import { useState } from "react"+import {+ Badge,+ Button,+ Container,+ Heading,+ Input,+ Label,+ Select,+ Switch,+ Text,+ toast,+} from "@medusajs/ui"++import {+ useAdminFilters,+ useCreateFilter,+ useUpdateFilter,+ useDeleteFilter,+ FilterRuleDTO,+} from "../../../hooks/api/filters"++const FilterRow = ({+ rule,+ onDelete,+}: {+ rule: FilterRuleDTO+ onDelete: (id: string) => void+}) => {+ const updateFilter = useUpdateFilter(rule.id)++ const handleToggle = (checked: boolean) => {+ updateFilter.mutate(+ { is_enabled: checked },+ { onSuccess: () => toast.success(`Rule ${checked ? "enabled" : "disabled"}`) }+ )+ }++ return (+ <div className="flex items-center gap-4 px-6 py-3">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <Badge color={rule.is_builtin ? "purple" : "grey"} size="2xsmall">+ {rule.is_builtin ? "Built-in" : rule.match_type}+ </Badge>+ <Text size="small" leading="compact" weight="plus" className="truncate">+ {rule.pattern}+ </Text>+ </div>+ {rule.description && (+ <Text size="xsmall" className="text-ui-fg-subtle mt-0.5">+ {rule.description}+ </Text>+ )}+ </div>+ <div className="flex items-center gap-3 shrink-0">+ <Switch+ checked={rule.is_enabled}+ onCheckedChange={handleToggle}+ disabled={updateFilter.isPending}+ />+ {!rule.is_builtin && (+ <Button+ size="small"+ variant="danger"+ onClick={() => onDelete(rule.id)}+ >+ Delete+ </Button>+ )}+ </div>+ </div>+ )+}++const AdminFiltersPage = () => {+ const { filter_rules, isLoading, isError, error } = useAdminFilters()+ const createFilter = useCreateFilter()+ const deleteFilter = useDeleteFilter()++ const [showForm, setShowForm] = useState(false)+ const [formState, setFormState] = useState({+ match_type: "exact" as "exact" | "contains",+ pattern: "",+ description: "",+ })++ if (isError) throw error++ const handleCreate = () => {+ if (!formState.pattern.trim()) return+ createFilter.mutate(+ {+ match_type: formState.match_type,+ pattern: formState.pattern.trim(),+ description: formState.description || undefined,+ },+ {+ onSuccess: () => {+ setFormState({ match_type: "exact", pattern: "", description: "" })+ setShowForm(false)+ toast.success("Filter rule created")+ },+ }+ )+ }++ const handleDelete = (id: string) => {+ deleteFilter.mutate(id, {+ onSuccess: () => toast.success("Filter rule deleted"),+ })+ }++ return (+ <div className="flex flex-col gap-4">+ <Container className="p-0">+ <div className="flex items-center justify-between px-6 py-4">+ <Heading>Content Filters</Heading>+ <Button size="small" onClick={() => setShowForm(!showForm)}>+ {showForm ? "Cancel" : "Add Rule"}+ </Button>+ </div>++ {showForm && (+ <div className="border-t border-ui-border-base px-6 py-4">+ <div className="grid grid-cols-2 gap-3">+ <div>+ <Label size="xsmall">Match Type</Label>+ <Select+ value={formState.match_type}+ onValueChange={(v) =>+ setFormState((s) => ({ ...s, match_type: v as any }))+ }+ >+ <Select.Trigger>+ <Select.Value />+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="exact">Exact Match</Select.Item>+ <Select.Item value="contains">Contains</Select.Item>+ </Select.Content>+ </Select>+ </div>+ <div>+ <Label size="xsmall">Pattern</Label>+ <Input+ size="small"+ placeholder="Word or phrase to filter..."+ value={formState.pattern}+ onChange={(e) =>+ setFormState((s) => ({ ...s, pattern: e.target.value }))+ }+ />+ </div>+ <div className="col-span-2">+ <Label size="xsmall">Description (optional)</Label>+ <Input+ size="small"+ placeholder="Why this filter exists..."+ value={formState.description}+ onChange={(e) =>+ setFormState((s) => ({ ...s, description: e.target.value }))+ }+ />+ </div>+ </div>+ <div className="mt-3">+ <Button+ size="small"+ onClick={handleCreate}+ disabled={!formState.pattern.trim() || createFilter.isPending}+ isLoading={createFilter.isPending}+ >+ Create Rule+ </Button>+ </div>+ </div>+ )}++ <div className="divide-y border-t border-ui-border-base">+ {isLoading ? (+ <div className="flex items-center justify-center py-12">+ <Text className="text-ui-fg-muted">Loading...</Text>+ </div>+ ) : !filter_rules?.length ? (+ <div className="flex items-center justify-center py-12">+ <Text className="text-ui-fg-muted">No filter rules configured</Text>+ </div>+ ) : (+ filter_rules.map((rule) => (+ <FilterRow+ key={rule.id}+ rule={rule}+ onDelete={handleDelete}+ />+ ))+ )}+ </div>+ </Container>+ </div>+ )+}++export default AdminFiltersPagediff --git a/packages/registry/src/messaging/admin/routes/messages/page.tsx b/packages/registry/src/messaging/admin/routes/messages/page.tsxnew file mode 100644index 000000000..7bf3d1e9d--- /dev/null+++ b/packages/registry/src/messaging/admin/routes/messages/page.tsx@@ -0,0 +1,206 @@+import { useState } from "react"+import { useNavigate } from "react-router-dom"+import { Badge, Button, Container, Heading, Input, Label, Text } from "@medusajs/ui"+import type { RouteConfig } from "@mercurjs/dashboard-sdk"++import { useAdminConversations, AdminConversationDTO } from "../../hooks/api/messaging"+import { useAdminMessagingSSE } from "../../hooks/api/use-admin-messaging-sse"+import { useMessagingLayout } from "../../hooks/use-messaging-layout"++export const config: RouteConfig = {+ label: "Messages",+}++export const handle = {+ breadcrumb: () => "Messages",+}++const formatDate = (dateStr: string | null): string => {+ if (!dateStr) return "-"+ return new Date(dateStr).toLocaleString()+}++const ConversationRow = ({+ conversation,+ onClick,+}: {+ conversation: AdminConversationDTO+ onClick: () => void+}) => {+ return (+ <button+ onClick={onClick}+ className="flex w-full items-center gap-4 px-6 py-3 text-left transition-colors hover:bg-ui-bg-base-hover"+ >+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <Text size="small" leading="compact" weight="plus">+ {conversation.seller_name || conversation.seller_id}+ </Text>+ <Text size="xsmall" className="text-ui-fg-muted">+ ↔+ </Text>+ <Text size="small" leading="compact" weight="plus">+ {conversation.buyer_name || conversation.buyer_id}+ </Text>+ {conversation.is_buyer_blocked && (+ <Badge color="red" size="2xsmall">+ Blocked+ </Badge>+ )}+ </div>+ <Text+ size="small"+ leading="compact"+ className="text-ui-fg-subtle truncate mt-0.5"+ >+ {conversation.last_message_preview || "No messages"}+ </Text>+ </div>+ <div className="shrink-0 text-right">+ <Text size="xsmall" className="text-ui-fg-muted">+ {formatDate(conversation.last_message_at)}+ </Text>+ {(conversation.buyer_email) && (+ <Text size="xsmall" className="text-ui-fg-muted">+ {conversation.buyer_email}+ </Text>+ )}+ </div>+ </button>+ )+}++const AdminMessagesPage = () => {+ useAdminMessagingSSE()+ const navigate = useNavigate()+ const [searchParams, setSearchParams] = useState<{+ seller_name?: string+ buyer_name?: string+ date_from?: string+ date_to?: string+ }>({})++ const [formState, setFormState] = useState({+ seller_name: "",+ buyer_name: "",+ date_from: "",+ date_to: "",+ })++ const { conversations, next_cursor, isLoading, isError, error } =+ useAdminConversations({ limit: 50, ...searchParams })++ useMessagingLayout()++ if (isError) throw error++ const handleSearch = () => {+ setSearchParams({+ seller_name: formState.seller_name || undefined,+ buyer_name: formState.buyer_name || undefined,+ date_from: formState.date_from || undefined,+ date_to: formState.date_to || undefined,+ })+ }++ const handleClear = () => {+ setFormState({ seller_name: "", buyer_name: "", date_from: "", date_to: "" })+ setSearchParams({})+ }++ return (+ <div className="flex h-full flex-col gap-4">+ {/* Search Form */}+ <Container className="shrink-0 p-0">+ <div className="px-6 py-4">+ <Heading>Message Oversight</Heading>+ </div>+ <div className="grid grid-cols-2 gap-3 px-6 pb-4">+ <div>+ <Label size="xsmall">Vendor Name</Label>+ <Input+ size="small"+ placeholder="Search vendor..."+ value={formState.seller_name}+ onChange={(e) =>+ setFormState((s) => ({ ...s, seller_name: e.target.value }))+ }+ />+ </div>+ <div>+ <Label size="xsmall">Customer Name</Label>+ <Input+ size="small"+ placeholder="Search customer..."+ value={formState.buyer_name}+ onChange={(e) =>+ setFormState((s) => ({ ...s, buyer_name: e.target.value }))+ }+ />+ </div>+ <div>+ <Label size="xsmall">Date From</Label>+ <Input+ size="small"+ type="date"+ value={formState.date_from}+ onChange={(e) =>+ setFormState((s) => ({ ...s, date_from: e.target.value }))+ }+ />+ </div>+ <div>+ <Label size="xsmall">Date To</Label>+ <Input+ size="small"+ type="date"+ value={formState.date_to}+ onChange={(e) =>+ setFormState((s) => ({ ...s, date_to: e.target.value }))+ }+ />+ </div>+ </div>+ <div className="flex gap-2 px-6 pb-4">+ <Button size="small" onClick={handleSearch}>+ Search+ </Button>+ <Button size="small" variant="secondary" onClick={handleClear}>+ Clear+ </Button>+ </div>+ </Container>++ {/* Results */}+ <Container className="flex min-h-0 flex-1 flex-col divide-y p-0">+ <div className="shrink-0 px-6 py-4">+ <Text size="small" weight="plus">+ Conversations+ </Text>+ </div>+ {isLoading ? (+ <div className="flex flex-1 items-center justify-center py-12">+ <Text className="text-ui-fg-muted">Loading...</Text>+ </div>+ ) : !conversations?.length ? (+ <div className="flex flex-1 items-center justify-center py-12">+ <Text className="text-ui-fg-muted">No conversations found</Text>+ </div>+ ) : (+ <div className="flex-1 divide-y overflow-y-auto">+ {conversations.map((conv) => (+ <ConversationRow+ key={conv.id}+ conversation={conv}+ onClick={() => navigate(`/messages/${conv.id}`)}+ />+ ))}+ </div>+ )}+ </Container>+ </div>+ )+}++export default AdminMessagesPagediff --git a/packages/registry/src/messaging/api/admin/messages/[id]/route.ts b/packages/registry/src/messaging/api/admin/messages/[id]/route.tsnew file mode 100644index 000000000..fcb3d344a--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/[id]/route.ts@@ -0,0 +1,91 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../../modules/messaging"+import type MessagingModuleService from "../../../../modules/messaging/service"+import { AdminGetMessagesType } from "../validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminGetMessagesType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const conversationId = req.params.id!++ // Admin can access any conversation — no ownership check+ const conversations = await service.listConversations(+ { id: conversationId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ const conversation = conversations[0]!++ const queryParams = (req.validatedQuery ?? {}) as AdminGetMessagesType+ const { data: messages, next_cursor } = await service.listMessagesCursor(+ conversationId,+ {+ cursor: queryParams.cursor,+ limit: queryParams.limit,+ }+ )++ // Resolve buyer + seller names for admin view+ let buyer_name: string | null = null+ let buyer_email: string | null = null+ let seller_name: string | null = null++ try {+ const query = req.scope.resolve("query")++ const { data: customers } = await query.graph({+ entity: "customer",+ fields: ["id", "first_name", "last_name", "email"],+ filters: { id: conversation.buyer_id },+ })++ if (customers?.length > 0) {+ buyer_name = [customers[0].first_name, customers[0].last_name]+ .filter(Boolean)+ .join(" ")+ buyer_email = customers[0].email+ }++ const { data: sellers } = await query.graph({+ entity: "seller",+ fields: ["id", "name"],+ filters: { id: conversation.seller_id },+ })++ if (sellers?.length > 0) {+ seller_name = sellers[0].name+ }+ } catch {+ // Continue without enrichment+ }++ // Check block status with reason+ const blockDetail = await service.getBlockDetail(conversation.buyer_id)++ res.json({+ conversation: {+ ...conversation,+ buyer_name,+ buyer_email,+ seller_name,+ is_buyer_blocked: blockDetail.blocked,+ block_reason: blockDetail.reason,+ },+ messages,+ next_cursor,+ })+}diff --git a/packages/registry/src/messaging/api/admin/messages/blocked/route.ts b/packages/registry/src/messaging/api/admin/messages/blocked/route.tsnew file mode 100644index 000000000..1f8198a45--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/blocked/route.ts@@ -0,0 +1,34 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_FILTERS_MODULE } from "../../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../../modules/messaging-filters/service"+import { AdminListBlockedType } from "../filters/validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminListBlockedType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ const limit = req.validatedQuery?.limit ?? 20+ const filters: Record<string, any> = {}++ if (req.validatedQuery?.sender_type) {+ filters.sender_type = req.validatedQuery.sender_type+ }++ const [logs, count] = await service.listAndCountBlockedMessageLogs(+ filters,+ {+ take: limit,+ order: { created_at: "DESC" },+ }+ )++ res.json({ blocked_messages: logs, count })+}diff --git a/packages/registry/src/messaging/api/admin/messages/chat-blocks/[customer_id]/route.ts b/packages/registry/src/messaging/api/admin/messages/chat-blocks/[customer_id]/route.tsnew file mode 100644index 000000000..ce490dcb2--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/chat-blocks/[customer_id]/route.ts@@ -0,0 +1,30 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_MODULE } from "../../../../../modules/messaging"+import type MessagingModuleService from "../../../../../modules/messaging/service"+import { unblockCustomerWorkflow } from "../../../../../workflows/messaging/workflows/unblock-customer"++export const GET = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const blocked = await service.checkBuyersBlocked([req.params.customer_id])++ res.json({ is_blocked: blocked.has(req.params.customer_id) })+}++export const DELETE = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ await unblockCustomerWorkflow.run({+ container: req.scope,+ input: { customer_id: req.params.customer_id },+ })++ res.status(200).json({ success: true })+}diff --git a/packages/registry/src/messaging/api/admin/messages/chat-blocks/route.ts b/packages/registry/src/messaging/api/admin/messages/chat-blocks/route.tsnew file mode 100644index 000000000..698fe212c--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/chat-blocks/route.ts@@ -0,0 +1,25 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { blockCustomerWorkflow } from "../../../../workflows/messaging/workflows/block-customer"+import { AdminBlockCustomerType } from "../validators"++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminBlockCustomerType>,+ res: MedusaResponse+) => {+ const adminUserId = req.auth_context.actor_id++ const { result: block } = await blockCustomerWorkflow.run({+ container: req.scope,+ input: {+ customer_id: req.validatedBody.customer_id,+ blocked_by: adminUserId,+ reason: req.validatedBody.reason ?? null,+ },+ })++ res.status(201).json({ block })+}diff --git a/packages/registry/src/messaging/api/admin/messages/events/route.ts b/packages/registry/src/messaging/api/admin/messages/events/route.tsnew file mode 100644index 000000000..aa48200a5--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/events/route.ts@@ -0,0 +1,75 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_REDIS_MODULE } from "../../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../../modules/messaging-redis/service"++export const GET = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)++ // SSE headers+ res.writeHead(200, {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ "X-Accel-Buffering": "no",+ })+ res.flushHeaders()++ const heartbeat = setInterval(() => {+ res.write(":heartbeat\n\n")+ }, 30000)++ let subscriber: ReturnType<MessagingRedisModuleService["createSubscriber"]> = null++ try {+ subscriber = redisService.createSubscriber()++ if (subscriber) {+ await subscriber.subscribe("messaging")++ // Admin receives ALL messaging events (no filtering)+ subscriber.on("message", (_channel: string, message: string) => {+ try {+ const event = JSON.parse(message)+ const eventId = event.message_id || `evt_${Date.now()}`+ const eventType = event.event_type || "message"++ res.write(`id: ${eventId}\n`)+ res.write(`event: ${eventType}\n`)+ res.write(`data: ${JSON.stringify(event)}\n\n`)+ } catch {+ // Skip malformed events+ }+ })+ }++ res.write(`event: connected\ndata: {"status":"connected"}\n\n`)++ // Sanitize Last-Event-ID to prevent SSE frame injection+ const lastEventId = req.headers["last-event-id"] as string | undefined+ if (lastEventId) {+ const sanitized = lastEventId.replace(/[\n\r]/g, "")+ res.write(`event: reconnected\ndata: ${JSON.stringify({ last_event_id: sanitized })}\n\n`)+ }+ } catch {+ // Redis unavailable+ }++ req.on("close", async () => {+ clearInterval(heartbeat)+ if (subscriber) {+ try {+ subscriber.unsubscribe("messaging")+ subscriber.quit()+ } catch {+ // Best effort cleanup+ }+ }+ })+}diff --git a/packages/registry/src/messaging/api/admin/messages/filters/[id]/route.ts b/packages/registry/src/messaging/api/admin/messages/filters/[id]/route.tsnew file mode 100644index 000000000..af4a64b1f--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/filters/[id]/route.ts@@ -0,0 +1,42 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_FILTERS_MODULE } from "../../../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../../../modules/messaging-filters/service"+import { updateFilterRuleWorkflow } from "../../../../../workflows/messaging-filters/workflows/update-filter-rule"+import { deleteFilterRuleWorkflow } from "../../../../../workflows/messaging-filters/workflows/delete-filter-rule"+import { AdminUpdateFilterType } from "../validators"++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminUpdateFilterType>,+ res: MedusaResponse+) => {+ const ruleId = req.params.id++ const { result: rule } = await updateFilterRuleWorkflow.run({+ container: req.scope,+ input: {+ id: ruleId,+ ...req.validatedBody,+ },+ })++ res.json({ filter_rule: rule })+}++export const DELETE = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const ruleId = req.params.id++ await deleteFilterRuleWorkflow.run({+ container: req.scope,+ input: { id: ruleId },+ })++ res.json({ id: ruleId, deleted: true })+}diff --git a/packages/registry/src/messaging/api/admin/messages/filters/route.ts b/packages/registry/src/messaging/api/admin/messages/filters/route.tsnew file mode 100644index 000000000..4e4f93b38--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/filters/route.ts@@ -0,0 +1,59 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_FILTERS_MODULE } from "../../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../../modules/messaging-filters/service"+import { createFilterRuleWorkflow } from "../../../../workflows/messaging-filters/workflows/create-filter-rule"+import { AdminCreateFilterType, AdminListFiltersType } from "./validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminListFiltersType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ const limit = req.validatedQuery?.limit ?? 20++ const [rules, count] = await service.listAndCountFilterRules(+ {},+ {+ take: limit,+ order: { created_at: "ASC" },+ }+ )++ res.json({ filter_rules: rules, count })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminCreateFilterType>,+ res: MedusaResponse+) => {+ const { match_type, pattern, description, is_enabled } = req.validatedBody++ // Custom rules cannot use regex match type+ if (match_type === "regex" as any) {+ throw new MedusaError(+ MedusaError.Types.INVALID_DATA,+ "Regex match type is reserved for built-in rules only"+ )+ }++ const { result: rule } = await createFilterRuleWorkflow.run({+ container: req.scope,+ input: {+ match_type,+ pattern,+ description: description ?? null,+ is_enabled: is_enabled ?? true,+ is_builtin: false,+ },+ })++ res.status(201).json({ filter_rule: rule })+}diff --git a/packages/registry/src/messaging/api/admin/messages/filters/validators.ts b/packages/registry/src/messaging/api/admin/messages/filters/validators.tsnew file mode 100644index 000000000..e5a8534cf--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/filters/validators.ts@@ -0,0 +1,32 @@+import { z } from "zod"++export type AdminCreateFilterType = z.infer<typeof AdminCreateFilter>+export const AdminCreateFilter = z.object({+ match_type: z.enum(["exact", "contains"]),+ pattern: z.string().min(1).max(500),+ description: z.string().max(500).optional(),+ is_enabled: z.boolean().optional().default(true),+})++export type AdminUpdateFilterType = z.infer<typeof AdminUpdateFilter>+export const AdminUpdateFilter = z.object({+ match_type: z.enum(["exact", "contains"]).optional(),+ pattern: z.string().min(1).max(500).optional(),+ description: z.string().max(500).optional(),+ is_enabled: z.boolean().optional(),+})++export type AdminListFiltersType = z.infer<typeof AdminListFilters>+export const AdminListFilters = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(50).optional().default(20),+})++export type AdminListBlockedType = z.infer<typeof AdminListBlocked>+export const AdminListBlocked = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(50).optional().default(20),+ sender_type: z.enum(["customer", "seller"]).optional(),+ date_from: z.string().optional(),+ date_to: z.string().optional(),+})diff --git a/packages/registry/src/messaging/api/admin/messages/middlewares.ts b/packages/registry/src/messaging/api/admin/messages/middlewares.tsnew file mode 100644index 000000000..b4bb00057--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/middlewares.ts@@ -0,0 +1,76 @@+import {+ validateAndTransformBody,+ validateAndTransformQuery,+} from "@medusajs/framework"+import { MiddlewareRoute } from "@medusajs/medusa"++import {+ AdminBlockCustomer,+ AdminGetMessages,+ AdminSearchConversations,+} from "./validators"+import {+ AdminCreateFilter,+ AdminUpdateFilter,+ AdminListFilters,+ AdminListBlocked,+} from "./filters/validators"+import { adminMessagingQueryConfig } from "./query-config"++export const adminMessagingMiddlewares: MiddlewareRoute[] = [+ {+ method: ["GET"],+ matcher: "/admin/messages",+ middlewares: [+ validateAndTransformQuery(+ AdminSearchConversations,+ adminMessagingQueryConfig.listConversations+ ),+ ],+ },+ {+ method: ["GET"],+ matcher: "/admin/messages/filters",+ middlewares: [+ validateAndTransformQuery(AdminListFilters, { defaults: ["*"], isList: true }),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/messages/filters",+ middlewares: [+ validateAndTransformBody(AdminCreateFilter),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/messages/filters/:id",+ middlewares: [+ validateAndTransformBody(AdminUpdateFilter),+ ],+ },+ {+ method: ["GET"],+ matcher: "/admin/messages/blocked",+ middlewares: [+ validateAndTransformQuery(AdminListBlocked, { defaults: ["*"], isList: true }),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/messages/chat-blocks",+ middlewares: [+ validateAndTransformBody(AdminBlockCustomer),+ ],+ },+ {+ method: ["GET"],+ matcher: "/admin/messages/:id",+ middlewares: [+ validateAndTransformQuery(+ AdminGetMessages,+ adminMessagingQueryConfig.listMessages+ ),+ ],+ },+]diff --git a/packages/registry/src/messaging/api/admin/messages/query-config.ts b/packages/registry/src/messaging/api/admin/messages/query-config.tsnew file mode 100644index 000000000..4d9efef54--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/query-config.ts@@ -0,0 +1,38 @@+export const adminMessagingConversationFields = [+ "id",+ "buyer_id",+ "seller_id",+ "buyer_name",+ "buyer_email",+ "seller_name",+ "last_message_preview",+ "last_message_sender_type",+ "last_message_at",+ "unread_count_customer",+ "unread_count_seller",+ "created_at",+ "updated_at",+]++export const adminMessagingMessageFields = [+ "id",+ "sender_id",+ "sender_type",+ "body",+ "context_type",+ "context_id",+ "context_label",+ "read_at",+ "created_at",+]++export const adminMessagingQueryConfig = {+ listConversations: {+ defaults: adminMessagingConversationFields,+ isList: true,+ },+ listMessages: {+ defaults: adminMessagingMessageFields,+ isList: true,+ },+}diff --git a/packages/registry/src/messaging/api/admin/messages/route.ts b/packages/registry/src/messaging/api/admin/messages/route.tsnew file mode 100644index 000000000..1c4f97f4f--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/route.ts@@ -0,0 +1,60 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { ConversationDTO } from "../../../modules/messaging/types/common"+import { AdminSearchConversationsType } from "./validators"++type AdminEnrichedConversation = ConversationDTO & {+ seller_name?: string | null+ buyer_name?: string | null+ buyer_email?: string | null+ is_buyer_blocked?: boolean+}++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminSearchConversationsType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const {+ cursor,+ limit,+ seller_name,+ buyer_name,+ date_from,+ date_to,+ context_type,+ context_id,+ } = (req.validatedQuery ?? {}) as AdminSearchConversationsType++ const { data: conversations, next_cursor } =+ await service.searchConversationsAdmin(+ {+ seller_name,+ buyer_name,+ date_from,+ date_to,+ context_type,+ context_id,+ },+ { cursor, limit }+ )++ const enriched = conversations as AdminEnrichedConversation[]++ // Annotate block status+ if (enriched.length > 0) {+ const buyerIds = [...new Set(enriched.map((c) => c.buyer_id))]+ const blockedSet = await service.checkBuyersBlocked(buyerIds)+ for (const conv of enriched) {+ conv.is_buyer_blocked = blockedSet.has(conv.buyer_id)+ }+ }++ res.json({ conversations: enriched, next_cursor })+}diff --git a/packages/registry/src/messaging/api/admin/messages/validators.ts b/packages/registry/src/messaging/api/admin/messages/validators.tsnew file mode 100644index 000000000..801f737db--- /dev/null+++ b/packages/registry/src/messaging/api/admin/messages/validators.ts@@ -0,0 +1,25 @@+import { z } from "zod"++export type AdminSearchConversationsType = z.infer<typeof AdminSearchConversations>+export const AdminSearchConversations = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(50).optional().default(20),+ seller_name: z.string().optional(),+ buyer_name: z.string().optional(),+ date_from: z.string().optional(),+ date_to: z.string().optional(),+ context_type: z.enum(["product", "order"]).optional(),+ context_id: z.string().optional(),+})++export type AdminGetMessagesType = z.infer<typeof AdminGetMessages>+export const AdminGetMessages = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(100).optional().default(30),+})++export type AdminBlockCustomerType = z.infer<typeof AdminBlockCustomer>+export const AdminBlockCustomer = z.object({+ customer_id: z.string().min(1),+ reason: z.string().max(500).optional(),+})diff --git a/packages/registry/src/messaging/api/store/messages/[id]/read/route.ts b/packages/registry/src/messaging/api/store/messages/[id]/read/route.tsnew file mode 100644index 000000000..7040cccf0--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/[id]/read/route.ts@@ -0,0 +1,43 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../../../modules/messaging"+import type MessagingModuleService from "../../../../../modules/messaging/service"+import { markMessagesReadWorkflow } from "../../../../../workflows/messaging/workflows/mark-messages-read"++export const POST = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const customerId = req.auth_context.actor_id+ const conversationId = req.params.id!++ // Verify ownership+ const conversations = await service.listConversations(+ { id: conversationId, buyer_id: customerId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ await markMessagesReadWorkflow.run({+ container: req.scope,+ input: {+ conversation_id: conversationId,+ reader_id: customerId,+ reader_type: "customer",+ sender_id: conversations[0]!.seller_id,+ },+ })++ res.json({ success: true, unread_count_customer: 0 })+}diff --git a/packages/registry/src/messaging/api/store/messages/[id]/route.ts b/packages/registry/src/messaging/api/store/messages/[id]/route.tsnew file mode 100644index 000000000..47d493dc5--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/[id]/route.ts@@ -0,0 +1,101 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../../modules/messaging"+import type MessagingModuleService from "../../../../modules/messaging/service"+import { sendMessageWorkflow } from "../../../../workflows/messaging/workflows/send-message"+import { resolveContextLabel } from "../helpers"+import { StoreGetMessagesType, StoreSendMessageType } from "../validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<StoreGetMessagesType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const customerId = req.auth_context.actor_id+ const conversationId = req.params.id!++ // Verify ownership+ const conversations = await service.listConversations(+ { id: conversationId, buyer_id: customerId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ const conversation = conversations[0]!++ const queryParams = (req.validatedQuery ?? {}) as StoreGetMessagesType+ const { data: messages, next_cursor } = await service.listMessagesCursor(+ conversationId,+ {+ cursor: queryParams.cursor,+ limit: queryParams.limit,+ }+ )++ res.json({ conversation, messages, next_cursor })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<StoreSendMessageType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const customerId = req.auth_context.actor_id+ const conversationId = req.params.id!++ // Verify ownership+ const conversations = await service.listConversations(+ { id: conversationId, buyer_id: customerId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ const conversation = conversations[0]!++ // Check if buyer is blocked from chat+ const blocked = await service.checkBuyersBlocked([customerId])+ if (blocked.has(customerId)) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Your chat access has been suspended"+ )+ }++ const { body, context_type, context_id } = req.validatedBody++ // Resolve context label for display+ const context_label = await resolveContextLabel(req.scope, context_type ?? null, context_id ?? null)++ const { result: message } = await sendMessageWorkflow.run({+ container: req.scope,+ input: {+ conversation_id: conversationId,+ sender_id: customerId,+ sender_type: "customer",+ body,+ context_type: context_type ?? null,+ context_id: context_id ?? null,+ context_label,+ recipient_id: conversation.seller_id,+ is_new_conversation: false,+ },+ })++ res.json({ message })+}diff --git a/packages/registry/src/messaging/api/store/messages/events/route.ts b/packages/registry/src/messaging/api/store/messages/events/route.tsnew file mode 100644index 000000000..1112c0f02--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/events/route.ts@@ -0,0 +1,101 @@+import { MedusaRequest, MedusaResponse } from "@medusajs/framework"++import { MESSAGING_REDIS_MODULE } from "../../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../../modules/messaging-redis/service"++export const GET = async (req: MedusaRequest, res: MedusaResponse) => {+ const token = req.query.token as string | undefined++ if (!token) {+ res.status(401).json({ message: "Missing token" })+ return+ }++ const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)++ if (!redisService.isAvailable) {+ res.status(503).json({ message: "Token service unavailable" })+ return+ }++ let customerId: string | null = null++ try {+ customerId = await redisService.consumeToken(token)+ } catch {+ res.status(503).json({ message: "Token service unavailable" })+ return+ }++ if (!customerId) {+ res.status(401).json({ message: "Invalid or expired token" })+ return+ }++ // SSE headers+ res.writeHead(200, {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ "X-Accel-Buffering": "no",+ })+ res.flushHeaders()++ // Heartbeat+ const heartbeat = setInterval(() => {+ res.write(":heartbeat\n\n")+ }, 30000)++ let subscriber: ReturnType<MessagingRedisModuleService["createSubscriber"]> = null++ try {+ subscriber = redisService.createSubscriber()++ if (subscriber) {+ await subscriber.subscribe("messaging")++ subscriber.on("message", (_channel: string, message: string) => {+ try {+ const event = JSON.parse(message)++ // Only deliver events for this buyer+ if (event.recipient_id !== customerId && event.sender_id !== customerId) {+ return+ }++ const eventId = event.message_id || `evt_${Date.now()}`+ const eventType = event.event_type || "message"++ res.write(`id: ${eventId}\n`)+ res.write(`event: ${eventType}\n`)+ res.write(`data: ${JSON.stringify(event)}\n\n`)+ } catch {+ // Skip malformed events+ }+ })+ }++ res.write(`event: connected\ndata: {"status":"connected"}\n\n`)++ // Handle Last-Event-ID (sanitize to prevent SSE frame injection)+ const lastEventId = req.query.last_event_id as string | undefined+ if (lastEventId) {+ const sanitized = lastEventId.replace(/[\n\r]/g, "")+ res.write(`event: reconnected\ndata: ${JSON.stringify({ last_event_id: sanitized })}\n\n`)+ }+ } catch {+ // Redis unavailable+ }++ req.on("close", async () => {+ clearInterval(heartbeat)+ if (subscriber) {+ try {+ subscriber.unsubscribe("messaging")+ subscriber.quit()+ } catch {+ // Best effort cleanup+ }+ }+ })+}diff --git a/packages/registry/src/messaging/api/store/messages/helpers.ts b/packages/registry/src/messaging/api/store/messages/helpers.tsnew file mode 100644index 000000000..2588b38ed--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/helpers.ts@@ -0,0 +1,45 @@+import { MedusaContainer } from "@medusajs/framework/types"++/**+ * Resolve a human-readable label for a message context attachment.+ * Returns null if the entity cannot be found or context is not provided.+ */+export async function resolveContextLabel(+ scope: MedusaContainer,+ context_type: string | null,+ context_id: string | null+): Promise<string | null> {+ if (!context_type || !context_id) return null++ const query = scope.resolve("query")++ if (context_type === "product") {+ try {+ const { data: products } = await query.graph({+ entity: "product",+ fields: ["id", "title"],+ filters: { id: context_id },+ })+ if (products?.length > 0) {+ return products[0].title+ }+ } catch {+ // Product may not exist+ }+ } else if (context_type === "order") {+ try {+ const { data: orders } = await query.graph({+ entity: "order",+ fields: ["id", "display_id"],+ filters: { id: context_id },+ })+ if (orders?.length > 0) {+ return `Order #${orders[0].display_id}`+ }+ } catch {+ // Order may not exist+ }+ }++ return null+}diff --git a/packages/registry/src/messaging/api/store/messages/middlewares.ts b/packages/registry/src/messaging/api/store/messages/middlewares.tsnew file mode 100644index 000000000..d4b3f43af--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/middlewares.ts@@ -0,0 +1,83 @@+import {+ authenticate,+ validateAndTransformBody,+ validateAndTransformQuery,+} from "@medusajs/framework"+import { MiddlewareRoute } from "@medusajs/medusa"++import {+ StoreCreateConversation,+ StoreGetMessages,+ StoreListConversations,+ StoreMarkRead,+ StoreSendMessage,+} from "./validators"+import { storeMessagingQueryConfig } from "./query-config"++export const storeMessagingMiddlewares: MiddlewareRoute[] = [+ {+ method: ["GET"],+ matcher: "/store/messages",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ validateAndTransformQuery(+ StoreListConversations,+ storeMessagingQueryConfig.listConversations+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/store/messages",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ validateAndTransformBody(StoreCreateConversation),+ ],+ },+ {+ method: ["GET"],+ matcher: "/store/messages/:id",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ validateAndTransformQuery(+ StoreGetMessages,+ storeMessagingQueryConfig.listMessages+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/store/messages/:id",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ validateAndTransformBody(StoreSendMessage),+ ],+ },+ {+ method: ["POST"],+ matcher: "/store/messages/:id/read",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ validateAndTransformBody(StoreMarkRead),+ ],+ },+ {+ method: ["GET"],+ matcher: "/store/messages/unread",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ ],+ },+ {+ method: ["POST"],+ matcher: "/store/messages/sse-token",+ middlewares: [+ authenticate("customer", ["session", "bearer"]),+ ],+ },+ {+ method: ["GET"],+ matcher: "/store/messages/events",+ middlewares: [],+ },+]diff --git a/packages/registry/src/messaging/api/store/messages/query-config.ts b/packages/registry/src/messaging/api/store/messages/query-config.tsnew file mode 100644index 000000000..7589733b3--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/query-config.ts@@ -0,0 +1,35 @@+export const storeConversationFields = [+ "id",+ "seller_id",+ "last_message_preview",+ "last_message_sender_type",+ "last_message_at",+ "unread_count_customer",+ "created_at",+]++export const storeMessageFields = [+ "id",+ "sender_type",+ "body",+ "context_type",+ "context_id",+ "context_label",+ "read_at",+ "created_at",+]++export const storeMessagingQueryConfig = {+ listConversations: {+ defaults: storeConversationFields,+ isList: true,+ },+ retrieveConversation: {+ defaults: storeConversationFields,+ isList: false,+ },+ listMessages: {+ defaults: storeMessageFields,+ isList: true,+ },+}diff --git a/packages/registry/src/messaging/api/store/messages/route.ts b/packages/registry/src/messaging/api/store/messages/route.tsnew file mode 100644index 000000000..f78a5cb6e--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/route.ts@@ -0,0 +1,115 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { createConversationWorkflow } from "../../../workflows/messaging/workflows/create-conversation"+import { sendMessageWorkflow } from "../../../workflows/messaging/workflows/send-message"+import { resolveContextLabel } from "./helpers"+import {+ StoreCreateConversationType,+ StoreListConversationsType,+} from "./validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<StoreListConversationsType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const customerId = req.auth_context.actor_id++ const queryParams = (req.validatedQuery ?? {}) as StoreListConversationsType+ const { data: conversations, next_cursor } =+ await service.listConversationsCursor(+ { buyer_id: customerId },+ {+ cursor: queryParams.cursor,+ limit: queryParams.limit,+ }+ )++ res.json({ conversations, next_cursor })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<StoreCreateConversationType>,+ res: MedusaResponse+) => {+ const customerId = req.auth_context.actor_id+ const { seller_id, body, context_type, context_id } = req.validatedBody++ // Check if buyer is blocked from chat+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const blocked = await service.checkBuyersBlocked([customerId])+ if (blocked.has(customerId)) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Your chat access has been suspended"+ )+ }++ // Check if seller exists and is active+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)++ const { data: sellers } = await query.graph({+ entity: "seller",+ fields: ["id", "name"],+ filters: { id: seller_id },+ })++ if (!sellers || sellers.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Seller not found"+ )+ }++ // Find or create conversation+ let conversation: any+ const existing = await service.listConversations(+ { buyer_id: customerId, seller_id },+ { take: 1 }+ )++ if (existing && existing.length > 0) {+ conversation = existing[0]+ } else {+ const { result } = await createConversationWorkflow.run({+ container: req.scope,+ input: { buyer_id: customerId, seller_id },+ })+ conversation = result+ }++ let message+ if (body) {+ // Resolve context label for display+ const context_label = await resolveContextLabel(req.scope, context_type ?? null, context_id ?? null)++ const { result } = await sendMessageWorkflow.run({+ container: req.scope,+ input: {+ conversation_id: conversation.id,+ sender_id: customerId,+ sender_type: "customer",+ body,+ context_type: context_type ?? null,+ context_id: context_id ?? null,+ context_label,+ recipient_id: seller_id,+ is_new_conversation: existing.length === 0,+ },+ })+ message = result+ }++ const response: any = { conversation }+ if (message) {+ response.message = message+ }++ res.status(200).json(response)+}diff --git a/packages/registry/src/messaging/api/store/messages/sse-token/route.ts b/packages/registry/src/messaging/api/store/messages/sse-token/route.tsnew file mode 100644index 000000000..54a6a07bc--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/sse-token/route.ts@@ -0,0 +1,34 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { randomUUID } from "crypto"++import { MESSAGING_REDIS_MODULE } from "../../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../../modules/messaging-redis/service"++const SSE_TOKEN_TTL_SECONDS = 30++export const POST = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const customerId = req.auth_context.actor_id+ const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)++ if (!redisService.isAvailable) {+ res.status(503).json({ message: "Token service unavailable" })+ return+ }++ const token = randomUUID()++ try {+ await redisService.setToken(token, customerId, SSE_TOKEN_TTL_SECONDS)+ } catch {+ res.status(503).json({ message: "Token service unavailable" })+ return+ }++ res.json({ token, expires_in: SSE_TOKEN_TTL_SECONDS })+}diff --git a/packages/registry/src/messaging/api/store/messages/unread/route.ts b/packages/registry/src/messaging/api/store/messages/unread/route.tsnew file mode 100644index 000000000..0edfbdcac--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/unread/route.ts@@ -0,0 +1,21 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_MODULE } from "../../../../modules/messaging"+import type MessagingModuleService from "../../../../modules/messaging/service"++export const GET = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const customerId = req.auth_context.actor_id++ const unread_count = await service.getUnreadCountTotal({+ buyer_id: customerId,+ })++ res.json({ unread_count })+}diff --git a/packages/registry/src/messaging/api/store/messages/validators.ts b/packages/registry/src/messaging/api/store/messages/validators.tsnew file mode 100644index 000000000..e3895eed6--- /dev/null+++ b/packages/registry/src/messaging/api/store/messages/validators.ts@@ -0,0 +1,41 @@+import { z } from "zod"++export type StoreListConversationsType = z.infer<typeof StoreListConversations>+export const StoreListConversations = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(50).optional().default(20),+})++export type StoreCreateConversationType = z.infer<typeof StoreCreateConversation>+export const StoreCreateConversation = z.object({+ seller_id: z.string().min(1),+ body: z.string().min(1).max(2000).optional(),+ context_type: z.enum(["product", "order"]).optional().nullable(),+ context_id: z.string().optional().nullable(),+}).refine(+ (data) =>+ (!data.context_type && !data.context_id) ||+ (data.context_type && data.context_id),+ { message: "context_type and context_id must both be set or both be omitted" }+)++export type StoreGetMessagesType = z.infer<typeof StoreGetMessages>+export const StoreGetMessages = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(100).optional().default(30),+})++export type StoreSendMessageType = z.infer<typeof StoreSendMessage>+export const StoreSendMessage = z.object({+ body: z.string().min(1).max(2000),+ context_type: z.enum(["product", "order"]).optional().nullable(),+ context_id: z.string().optional().nullable(),+}).refine(+ (data) =>+ (!data.context_type && !data.context_id) ||+ (data.context_type && data.context_id),+ { message: "context_type and context_id must both be set or both be omitted" }+)++export type StoreMarkReadType = z.infer<typeof StoreMarkRead>+export const StoreMarkRead = z.object({})diff --git a/packages/registry/src/messaging/api/vendor/messages/[id]/read/route.ts b/packages/registry/src/messaging/api/vendor/messages/[id]/read/route.tsnew file mode 100644index 000000000..941de7f32--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/[id]/read/route.ts@@ -0,0 +1,43 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../../../modules/messaging"+import type MessagingModuleService from "../../../../../modules/messaging/service"+import { markMessagesReadWorkflow } from "../../../../../workflows/messaging/workflows/mark-messages-read"++export const POST = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const sellerId = req.auth_context.actor_id+ const conversationId = req.params.id!++ // Verify ownership+ const conversations = await service.listConversations(+ { id: conversationId, seller_id: sellerId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ await markMessagesReadWorkflow.run({+ container: req.scope,+ input: {+ conversation_id: conversationId,+ reader_id: sellerId,+ reader_type: "seller",+ sender_id: conversations[0]!.buyer_id,+ },+ })++ res.json({ success: true, unread_count_seller: 0 })+}diff --git a/packages/registry/src/messaging/api/vendor/messages/[id]/route.ts b/packages/registry/src/messaging/api/vendor/messages/[id]/route.tsnew file mode 100644index 000000000..f6e689055--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/[id]/route.ts@@ -0,0 +1,140 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../../modules/messaging"+import type MessagingModuleService from "../../../../modules/messaging/service"+import { sendMessageWorkflow } from "../../../../workflows/messaging/workflows/send-message"+import { VendorGetMessagesType, VendorSendReplyType } from "../validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<VendorGetMessagesType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const sellerId = req.auth_context.actor_id+ const conversationId = req.params.id!++ // Verify ownership+ const conversations = await service.listConversations(+ { id: conversationId, seller_id: sellerId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ const conversation = conversations[0]!++ const queryParams = (req.validatedQuery ?? {}) as VendorGetMessagesType+ const { data: messages, next_cursor } = await service.listMessagesCursor(+ conversationId,+ {+ cursor: queryParams.cursor,+ limit: queryParams.limit,+ }+ )++ // Resolve buyer first name + recent orders for context sidebar+ let buyer_first_name: string | null = null+ let buyer_orders: any[] = []++ try {+ const query = req.scope.resolve("query")++ const { data: customers } = await query.graph({+ entity: "customer",+ fields: ["id", "first_name"],+ filters: { id: conversation.buyer_id },+ })++ if (customers?.length > 0) {+ buyer_first_name = customers[0].first_name+ }++ // Get recent orders for this buyer, including linked seller to filter+ const { data: orders } = await query.graph({+ entity: "order",+ fields: ["id", "display_id", "status", "total", "currency_code", "created_at", "seller.id"],+ filters: {+ customer_id: conversation.buyer_id,+ },+ })++ // Only include orders that belong to this seller+ buyer_orders = (orders ?? [])+ .filter((o: any) => o.seller?.id === sellerId)+ .map(({ seller, ...rest }: any) => rest)+ } catch {+ // Continue without enrichment+ }++ // Check block status+ const blockedSet = await service.checkBuyersBlocked([conversation.buyer_id])+ const is_buyer_blocked = blockedSet.has(conversation.buyer_id)++ res.json({+ conversation: { ...conversation, buyer_first_name, is_buyer_blocked },+ messages,+ next_cursor,+ buyer_orders,+ })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<VendorSendReplyType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const sellerId = req.auth_context.actor_id+ const conversationId = req.params.id!++ // Verify ownership+ const conversations = await service.listConversations(+ { id: conversationId, seller_id: sellerId },+ { take: 1 }+ )++ if (!conversations || conversations.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ "Conversation not found"+ )+ }++ const conversation = conversations[0]!++ // Check if buyer is blocked from chat+ const blockedSet = await service.checkBuyersBlocked([conversation.buyer_id])+ if (blockedSet.has(conversation.buyer_id)) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Cannot send messages to a blocked customer"+ )+ }++ const { body } = req.validatedBody++ const { result: message } = await sendMessageWorkflow.run({+ container: req.scope,+ input: {+ conversation_id: conversationId,+ sender_id: sellerId,+ sender_type: "seller",+ body,+ context_type: null,+ context_id: null,+ context_label: null,+ recipient_id: conversation.buyer_id,+ is_new_conversation: false,+ },+ })++ res.json({ message })+}diff --git a/packages/registry/src/messaging/api/vendor/messages/events/route.ts b/packages/registry/src/messaging/api/vendor/messages/events/route.tsnew file mode 100644index 000000000..41addd665--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/events/route.ts@@ -0,0 +1,84 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_REDIS_MODULE } from "../../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../../modules/messaging-redis/service"++export const GET = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const sellerId = req.auth_context.actor_id+ const redisService = req.scope.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)++ // SSE headers+ res.writeHead(200, {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ "X-Accel-Buffering": "no",+ })+ res.flushHeaders()++ // Heartbeat to keep connection alive+ const heartbeat = setInterval(() => {+ res.write(":heartbeat\n\n")+ }, 30000)++ let subscriber: ReturnType<MessagingRedisModuleService["createSubscriber"]> = null++ try {+ subscriber = redisService.createSubscriber()++ if (subscriber) {+ await subscriber.subscribe("messaging")++ subscriber.on("message", (_channel: string, message: string) => {+ try {+ const event = JSON.parse(message)++ // Only deliver events for this vendor+ if (event.recipient_id !== sellerId && event.sender_id !== sellerId) {+ return+ }++ const eventId = event.message_id || `evt_${Date.now()}`+ const eventType = event.event_type || "message"++ res.write(`id: ${eventId}\n`)+ res.write(`event: ${eventType}\n`)+ res.write(`data: ${JSON.stringify(event)}\n\n`)+ } catch {+ // Skip malformed events+ }+ })+ }++ // Send initial connection event+ res.write(`event: connected\ndata: {"status":"connected"}\n\n`)++ // Handle Last-Event-ID for reconnection (sanitize to prevent SSE frame injection)+ const lastEventId = req.headers["last-event-id"] as string | undefined+ if (lastEventId) {+ const sanitized = lastEventId.replace(/[\n\r]/g, "")+ res.write(`event: reconnected\ndata: ${JSON.stringify({ last_event_id: sanitized })}\n\n`)+ }+ } catch {+ // Redis unavailable, connection will close+ }++ // Cleanup on disconnect+ req.on("close", async () => {+ clearInterval(heartbeat)+ if (subscriber) {+ try {+ subscriber.unsubscribe("messaging")+ subscriber.quit()+ } catch {+ // Best effort cleanup+ }+ }+ })+}diff --git a/packages/registry/src/messaging/api/vendor/messages/middlewares.ts b/packages/registry/src/messaging/api/vendor/messages/middlewares.tsnew file mode 100644index 000000000..16bbf58f7--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/middlewares.ts@@ -0,0 +1,50 @@+import {+ validateAndTransformBody,+ validateAndTransformQuery,+} from "@medusajs/framework"+import { MiddlewareRoute } from "@medusajs/medusa"++import {+ VendorGetMessages,+ VendorListConversations,+ VendorMarkRead,+ VendorSendReply,+} from "./validators"+import { vendorMessagingQueryConfig } from "./query-config"++export const vendorMessagingMiddlewares: MiddlewareRoute[] = [+ {+ method: ["GET"],+ matcher: "/vendor/messages",+ middlewares: [+ validateAndTransformQuery(+ VendorListConversations,+ vendorMessagingQueryConfig.listConversations+ ),+ ],+ },+ {+ method: ["GET"],+ matcher: "/vendor/messages/:id",+ middlewares: [+ validateAndTransformQuery(+ VendorGetMessages,+ vendorMessagingQueryConfig.listMessages+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/vendor/messages/:id",+ middlewares: [+ validateAndTransformBody(VendorSendReply),+ ],+ },+ {+ method: ["POST"],+ matcher: "/vendor/messages/:id/read",+ middlewares: [+ validateAndTransformBody(VendorMarkRead),+ ],+ },+]diff --git a/packages/registry/src/messaging/api/vendor/messages/query-config.ts b/packages/registry/src/messaging/api/vendor/messages/query-config.tsnew file mode 100644index 000000000..19e945087--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/query-config.ts@@ -0,0 +1,33 @@+export const vendorMessagingConversationFields = [+ "id",+ "seller_id",+ "buyer_id",+ "last_message_preview",+ "last_message_sender_type",+ "last_message_at",+ "unread_count_seller",+ "created_at",+ "updated_at",+]++export const vendorMessagingMessageFields = [+ "id",+ "sender_type",+ "body",+ "context_type",+ "context_id",+ "context_label",+ "read_at",+ "created_at",+]++export const vendorMessagingQueryConfig = {+ listConversations: {+ defaults: vendorMessagingConversationFields,+ isList: true,+ },+ listMessages: {+ defaults: vendorMessagingMessageFields,+ isList: true,+ },+}diff --git a/packages/registry/src/messaging/api/vendor/messages/route.ts b/packages/registry/src/messaging/api/vendor/messages/route.tsnew file mode 100644index 000000000..9fddc8902--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/route.ts@@ -0,0 +1,68 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { ConversationDTO } from "../../../modules/messaging/types/common"+import { VendorListConversationsType } from "./validators"++type EnrichedConversation = ConversationDTO & {+ buyer_first_name?: string | null+ is_buyer_blocked?: boolean+}++export const GET = async (+ req: AuthenticatedMedusaRequest<VendorListConversationsType>,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const sellerId = req.auth_context.actor_id++ const { data: conversations, next_cursor } =+ await service.listConversationsCursor(+ { seller_id: sellerId },+ {+ cursor: (req.validatedQuery as VendorListConversationsType)?.cursor,+ limit: (req.validatedQuery as VendorListConversationsType)?.limit,+ }+ )++ const enriched = conversations as EnrichedConversation[]++ // Resolve buyer first names via customer link+ if (enriched.length > 0) {+ try {+ const query = req.scope.resolve("query")+ const buyerIds = [...new Set(enriched.map((c) => c.buyer_id))]++ const { data: customers } = await query.graph({+ entity: "customer",+ fields: ["id", "first_name"],+ filters: { id: buyerIds },+ })++ const customerMap = new Map(+ (customers ?? []).map((c: { id: string; first_name: string }) => [c.id, c.first_name])+ )++ for (const conv of enriched) {+ conv.buyer_first_name = customerMap.get(conv.buyer_id) ?? null+ }+ } catch {+ // Continue without buyer names+ }+ }++ // Annotate block status+ if (enriched.length > 0) {+ const buyerIds = [...new Set(enriched.map((c) => c.buyer_id))]+ const blockedSet = await service.checkBuyersBlocked(buyerIds)+ for (const conv of enriched) {+ conv.is_buyer_blocked = blockedSet.has(conv.buyer_id)+ }+ }++ res.json({ conversations: enriched, next_cursor })+}diff --git a/packages/registry/src/messaging/api/vendor/messages/unread/route.ts b/packages/registry/src/messaging/api/vendor/messages/unread/route.tsnew file mode 100644index 000000000..5fb2be62b--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/unread/route.ts@@ -0,0 +1,21 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework"++import { MESSAGING_MODULE } from "../../../../modules/messaging"+import type MessagingModuleService from "../../../../modules/messaging/service"++export const GET = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse+) => {+ const service = req.scope.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const sellerId = req.auth_context.actor_id++ const unread_count = await service.getUnreadCountTotal({+ seller_id: sellerId,+ })++ res.json({ unread_count })+}diff --git a/packages/registry/src/messaging/api/vendor/messages/validators.ts b/packages/registry/src/messaging/api/vendor/messages/validators.tsnew file mode 100644index 000000000..04fa38dbd--- /dev/null+++ b/packages/registry/src/messaging/api/vendor/messages/validators.ts@@ -0,0 +1,21 @@+import { z } from "zod"++export type VendorListConversationsType = z.infer<typeof VendorListConversations>+export const VendorListConversations = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(50).optional().default(20),+})++export type VendorGetMessagesType = z.infer<typeof VendorGetMessages>+export const VendorGetMessages = z.object({+ cursor: z.string().optional(),+ limit: z.coerce.number().int().min(1).max(100).optional().default(30),+})++export type VendorSendReplyType = z.infer<typeof VendorSendReply>+export const VendorSendReply = z.object({+ body: z.string().min(1).max(2000),+})++export type VendorMarkReadType = z.infer<typeof VendorMarkRead>+export const VendorMarkRead = z.object({})diff --git a/packages/registry/src/messaging/jobs/cleanup-blocked-messages.ts b/packages/registry/src/messaging/jobs/cleanup-blocked-messages.tsnew file mode 100644index 000000000..9c82f375f--- /dev/null+++ b/packages/registry/src/messaging/jobs/cleanup-blocked-messages.ts@@ -0,0 +1,50 @@+import { MedusaContainer } from "@medusajs/framework/types"++import { MESSAGING_FILTERS_MODULE } from "../modules/messaging-filters"+import type MessagingFiltersModuleService from "../modules/messaging-filters/service"++const RETENTION_DAYS = 30++export default async function cleanupBlockedMessages(+ container: MedusaContainer+) {+ const logger = container.resolve("logger")+ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ try {+ const cutoffDate = new Date()+ cutoffDate.setDate(cutoffDate.getDate() - RETENTION_DAYS)++ // List old blocked message logs+ const oldLogs = await service.listBlockedMessageLogs(+ {+ created_at: { $lt: cutoffDate },+ },+ { take: 1000, select: ["id"] }+ )++ if (!oldLogs || oldLogs.length === 0) {+ logger.debug("Messaging: cleanup-blocked-messages — nothing to clean up")+ return+ }++ const ids = oldLogs.map((log: any) => log.id)++ await service.deleteBlockedMessageLogs(ids)++ logger.info(+ `Messaging: cleanup-blocked-messages deleted ${ids.length} log(s) older than ${RETENTION_DAYS} days`+ )+ } catch (err) {+ logger.error(+ `Messaging: cleanup-blocked-messages error: ${(err as Error).message}`+ )+ }+}++export const config = {+ name: "messaging-cleanup-blocked-messages",+ schedule: "0 4 * * *", // Daily at 4 AM+}diff --git a/packages/registry/src/messaging/jobs/reconcile-unread-counts.ts b/packages/registry/src/messaging/jobs/reconcile-unread-counts.tsnew file mode 100644index 000000000..bad928060--- /dev/null+++ b/packages/registry/src/messaging/jobs/reconcile-unread-counts.ts@@ -0,0 +1,71 @@+import { MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++export default async function reconcileUnreadCounts(+ container: MedusaContainer+) {+ const logger = container.resolve("logger")+ const pgConnection = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)++ try {+ // Single query: compute actual unread counts for ALL conversations at once+ const BATCH_SIZE = 500+ let totalCorrected = 0+ let offset = 0++ // Process in batches to avoid unbounded result sets+ while (true) {+ const { rows: actualCounts } = await pgConnection.raw(`+ SELECT+ c.id,+ c.unread_count_customer AS stored_customer,+ c.unread_count_seller AS stored_seller,+ COALESCE(SUM(CASE WHEN m.sender_type = 'seller' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)::int AS actual_customer,+ COALESCE(SUM(CASE WHEN m.sender_type = 'customer' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)::int AS actual_seller+ FROM conversation c+ LEFT JOIN message m ON m.conversation_id = c.id AND m.deleted_at IS NULL+ WHERE c.deleted_at IS NULL+ GROUP BY c.id, c.unread_count_customer, c.unread_count_seller+ HAVING+ c.unread_count_customer != COALESCE(SUM(CASE WHEN m.sender_type = 'seller' AND m.read_at IS NULL THEN 1 ELSE 0 END), 0)+ 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)+ ORDER BY c.id+ LIMIT ?+ OFFSET ?+ `, [BATCH_SIZE, offset])++ if (!actualCounts || actualCounts.length === 0) break++ for (const row of actualCounts) {+ await pgConnection.raw(`+ UPDATE conversation+ SET unread_count_customer = ?, unread_count_seller = ?, updated_at = NOW()+ WHERE id = ?+ `, [row.actual_customer, row.actual_seller, row.id])+ }++ totalCorrected += actualCounts.length+ offset += BATCH_SIZE++ if (actualCounts.length < BATCH_SIZE) break+ }++ if (totalCorrected === 0) {+ logger.debug("Messaging: reconcile-unread-counts — no drift detected")+ return+ }++ logger.info(+ `Messaging: reconcile-unread-counts corrected ${totalCorrected} conversation(s)`+ )+ } catch (err) {+ logger.error(+ `Messaging: reconcile-unread-counts error: ${(err as Error).message}`+ )+ }+}++export const config = {+ name: "messaging-reconcile-unread-counts",+ schedule: "0 3 * * *", // Daily at 3 AM+}diff --git a/packages/registry/src/messaging/links/conversation-customer.ts b/packages/registry/src/messaging/links/conversation-customer.tsnew file mode 100644index 000000000..f79dd30d5--- /dev/null+++ b/packages/registry/src/messaging/links/conversation-customer.ts@@ -0,0 +1,9 @@+import { defineLink } from "@medusajs/framework/utils"+import CustomerModule from "@medusajs/medusa/customer"++import MessagingModule from "../modules/messaging"++export default defineLink(CustomerModule.linkable.customer, {+ linkable: MessagingModule.linkable.conversation,+ isList: true,+})diff --git a/packages/registry/src/messaging/links/conversation-seller.ts b/packages/registry/src/messaging/links/conversation-seller.tsnew file mode 100644index 000000000..bb0b13608--- /dev/null+++ b/packages/registry/src/messaging/links/conversation-seller.ts@@ -0,0 +1,9 @@+import { defineLink } from "@medusajs/framework/utils"++import SellerModule from "@mercurjs/core/modules/seller"+import MessagingModule from "../modules/messaging"++export default defineLink(SellerModule.linkable.seller, {+ linkable: MessagingModule.linkable.conversation,+ isList: true,+})diff --git a/packages/registry/src/messaging/modules/messaging-filters/index.ts b/packages/registry/src/messaging/modules/messaging-filters/index.tsnew file mode 100644index 000000000..06052a4fb--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/index.ts@@ -0,0 +1,15 @@+import { Module } from "@medusajs/framework/utils"++import MessagingFiltersModuleService from "./service"+import seedBuiltinRules from "./loaders/seed-builtin-rules"+import compileFiltersLoader from "./loaders/compile-filters"++export const MESSAGING_FILTERS_MODULE = "messagingFilters"++export * from "./types/common"+export { MessagingFiltersModuleService }++export default Module(MESSAGING_FILTERS_MODULE, {+ service: MessagingFiltersModuleService,+ loaders: [seedBuiltinRules, compileFiltersLoader],+})diff --git a/packages/registry/src/messaging/modules/messaging-filters/loaders/compile-filters.ts b/packages/registry/src/messaging/modules/messaging-filters/loaders/compile-filters.tsnew file mode 100644index 000000000..55e384bdf--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/loaders/compile-filters.ts@@ -0,0 +1,114 @@+import { LoaderOptions, IMedusaInternalService } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { FilterRule } from "../models/filter-rule"+import { CompiledRuleset } from "../types/common"++let compiledRuleset: CompiledRuleset = {+ exactWords: new Set<string>(),+ exactRules: new Map<string, string>(),+ containsPatterns: [],+ regexPatterns: [],+}++export function getCompiledRuleset(): CompiledRuleset {+ return compiledRuleset+}++export function isRulesetEmpty(): boolean {+ return (+ compiledRuleset.exactWords.size === 0 &&+ compiledRuleset.containsPatterns.length === 0 &&+ compiledRuleset.regexPatterns.length === 0+ )+}++export function invalidateRuleset(): void {+ compiledRuleset = {+ exactWords: new Set<string>(),+ exactRules: new Map<string, string>(),+ containsPatterns: [],+ regexPatterns: [],+ }+}++async function compileFilters(container: any): Promise<void> {+ // Try module container first (when called from module loader), then app container+ let rules: any[]+ try {+ const service = container.resolve("filterRuleService") as IMedusaInternalService<typeof FilterRule>+ const [results] = await service.listAndCount({ is_enabled: true } as any, { take: 1000 })+ rules = results+ } catch {+ // Fallback: resolve from app container via module name (used by workflow steps)+ try {+ const service = container.resolve("messagingFilters")+ rules = await service.listFilterRules({ is_enabled: true }, { take: 1000 })+ } catch {+ return+ }+ }++ const newRuleset: CompiledRuleset = {+ exactWords: new Set<string>(),+ exactRules: new Map<string, string>(),+ containsPatterns: [],+ regexPatterns: [],+ }++ for (const rule of rules) {+ switch (rule.match_type) {+ case "exact": {+ const lowered = rule.pattern.toLowerCase()+ newRuleset.exactWords.add(lowered)+ newRuleset.exactRules.set(lowered, rule.id)+ break+ }+ case "contains": {+ newRuleset.containsPatterns.push({+ id: rule.id,+ pattern: rule.pattern.toLowerCase(),+ })+ break+ }+ case "regex": {+ try {+ const regex = new RegExp(rule.pattern, "i")+ // ReDoS protection: test with a probe string under a time budget+ const probeStart = Date.now()+ regex.test("a".repeat(50))+ if (Date.now() - probeStart > 10) {+ // Pattern took >10ms on a short string — likely catastrophic backtracking+ try {+ const logger = container.resolve?.(ContainerRegistrationKeys.LOGGER)+ logger?.warn(`[messaging] Skipping ReDoS-prone regex rule ${rule.id}: ${rule.pattern}`)+ } catch { /* no logger available */ }+ break+ }+ newRuleset.regexPatterns.push({+ id: rule.id,+ regex,+ })+ } catch {+ // Skip invalid regex patterns+ }+ break+ }+ }+ }++ compiledRuleset = newRuleset+}++export async function recompileFilters(container: any): Promise<void> {+ await compileFilters(container)+}++export default async function compileFiltersLoader({+ container,+}: LoaderOptions): Promise<void> {+ try {+ await compileFilters(container)+ } catch {+ // Will be compiled lazily on first message+ }+}diff --git a/packages/registry/src/messaging/modules/messaging-filters/loaders/seed-builtin-rules.ts b/packages/registry/src/messaging/modules/messaging-filters/loaders/seed-builtin-rules.tsnew file mode 100644index 000000000..8181258e2--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/loaders/seed-builtin-rules.ts@@ -0,0 +1,47 @@+import { LoaderOptions, IMedusaInternalService } from "@medusajs/framework/types"+import { FilterRule } from "../models/filter-rule"++const BUILTIN_RULES = [+ {+ match_type: "regex",+ pattern: "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}",+ description: "Blocks email addresses to keep communication on-platform",+ is_builtin: true,+ is_enabled: true,+ },+ {+ match_type: "regex",+ pattern: "(?:\\+\\d{1,3}[-.\\s]?)?(?:\\(?\\d{2,4}\\)?[-.\\s]?)?\\d{3,4}[-.\\s]?\\d{4,}",+ description: "Blocks phone numbers to keep communication on-platform",+ is_builtin: true,+ is_enabled: true,+ },+ {+ match_type: "regex",+ pattern: "https?://[^\\s]+|www\\.[^\\s]+",+ description: "Blocks URLs and links to prevent spam and phishing",+ is_builtin: true,+ is_enabled: true,+ },+]++export default async function seedBuiltinRules({+ container,+}: LoaderOptions): Promise<void> {+ const service = container.resolve("filterRuleService") as IMedusaInternalService<typeof FilterRule>++ for (const rule of BUILTIN_RULES) {+ try {+ const [existing, count] = await service.listAndCount({+ pattern: rule.pattern,+ is_builtin: true,+ } as any, { take: 1 })++ if (count === 0) {+ await service.create(rule as any)+ }+ } catch {+ // Skip if already seeded+ }+ }+}diff --git a/packages/registry/src/messaging/modules/messaging-filters/models/blocked-message-log.ts b/packages/registry/src/messaging/modules/messaging-filters/models/blocked-message-log.tsnew file mode 100644index 000000000..4cba18318--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/models/blocked-message-log.ts@@ -0,0 +1,10 @@+import { model } from "@medusajs/framework/utils"++export const BlockedMessageLog = model.define("blocked_message_log", {+ id: model.id({ prefix: "bml" }).primaryKey(),+ sender_id: model.text(),+ sender_type: model.enum(["customer", "seller"]),+ conversation_id: model.text(),+ matched_rule_id: model.text(),+ message_body: model.text(),+})diff --git a/packages/registry/src/messaging/modules/messaging-filters/models/filter-rule.ts b/packages/registry/src/messaging/modules/messaging-filters/models/filter-rule.tsnew file mode 100644index 000000000..f1f6903ed--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/models/filter-rule.ts@@ -0,0 +1,10 @@+import { model } from "@medusajs/framework/utils"++export const FilterRule = model.define("filter_rule", {+ id: model.id({ prefix: "filt" }).primaryKey(),+ match_type: model.enum(["exact", "contains", "regex"]),+ pattern: model.text(),+ is_builtin: model.boolean().default(false),+ is_enabled: model.boolean().default(true),+ description: model.text().nullable(),+})diff --git a/packages/registry/src/messaging/modules/messaging-filters/service.ts b/packages/registry/src/messaging/modules/messaging-filters/service.tsnew file mode 100644index 000000000..6b29ce026--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/service.ts@@ -0,0 +1,62 @@+import { MedusaService } from "@medusajs/framework/utils"++import { FilterRule } from "./models/filter-rule"+import { BlockedMessageLog } from "./models/blocked-message-log"+import {+ CompiledRuleset,+ FilterEvaluationResult,+} from "./types/common"++class MessagingFiltersModuleService extends MedusaService({+ FilterRule,+ BlockedMessageLog,+}) {+ evaluateMessage(+ body: string,+ ruleset: CompiledRuleset+ ): FilterEvaluationResult {+ const lowercasedBody = body.toLowerCase()+ const words = lowercasedBody.split(/\s+/)++ // 1. Exact word match — O(1) per word via hash set+ for (const word of words) {+ if (ruleset.exactWords.has(word)) {+ const ruleId = ruleset.exactRules.get(word)+ return {+ matched: true,+ rule_id: ruleId,+ match_type: "exact",+ pattern: word,+ }+ }+ }++ // 2. Contains/substring match — O(n) per pattern+ for (const entry of ruleset.containsPatterns) {+ if (lowercasedBody.includes(entry.pattern)) {+ return {+ matched: true,+ rule_id: entry.id,+ match_type: "contains",+ pattern: entry.pattern,+ }+ }+ }++ // 3. Regex match (built-in only) — O(n) per pattern+ for (const entry of ruleset.regexPatterns) {+ if (entry.regex.test(body)) {+ return {+ matched: true,+ rule_id: entry.id,+ match_type: "regex",+ pattern: entry.regex.source,+ }+ }+ }++ return { matched: false }+ }+}++export default MessagingFiltersModuleServicediff --git a/packages/registry/src/messaging/modules/messaging-filters/types/common.ts b/packages/registry/src/messaging/modules/messaging-filters/types/common.tsnew file mode 100644index 000000000..0f568d165--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-filters/types/common.ts@@ -0,0 +1,53 @@+export type MatchType = "exact" | "contains" | "regex"++export interface FilterRuleDTO {+ id: string+ match_type: MatchType+ pattern: string+ is_builtin: boolean+ is_enabled: boolean+ description: string | null+ created_at: Date | string+ updated_at: Date | string+ deleted_at: Date | string | null+}++export interface BlockedMessageLogDTO {+ id: string+ sender_id: string+ sender_type: "customer" | "seller"+ conversation_id: string+ matched_rule_id: string+ message_body: string+ created_at: Date | string+ updated_at: Date | string+ deleted_at: Date | string | null+}++export interface CompiledRuleset {+ exactWords: Set<string>+ exactRules: Map<string, string> // lowercased word -> rule id+ containsPatterns: Array<{ id: string; pattern: string }> // lowercased+ regexPatterns: Array<{ id: string; regex: RegExp }>+}++export interface FilterEvaluationResult {+ matched: boolean+ rule_id?: string+ match_type?: MatchType+ pattern?: string+}++export interface AdminFilterRuleResponse {+ filter: FilterRuleDTO+}++export type AdminFilterRuleListResponse = {+ filters: FilterRuleDTO[]+ next_cursor: string | null+}++export interface AdminBlockedMessageLogListResponse {+ blocked_messages: BlockedMessageLogDTO[]+ next_cursor: string | null+}diff --git a/packages/registry/src/messaging/modules/messaging-redis/index.ts b/packages/registry/src/messaging/modules/messaging-redis/index.tsnew file mode 100644index 000000000..f19a7ea07--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-redis/index.ts@@ -0,0 +1,13 @@+import { Module } from "@medusajs/framework/utils"++import MessagingRedisModuleService from "./service"+import messagingRedisConnectionLoader from "./loaders/connection"++export const MESSAGING_REDIS_MODULE = "messagingRedis"++export { MessagingRedisModuleService }++export default Module(MESSAGING_REDIS_MODULE, {+ service: MessagingRedisModuleService,+ loaders: [messagingRedisConnectionLoader],+})diff --git a/packages/registry/src/messaging/modules/messaging-redis/loaders/connection.ts b/packages/registry/src/messaging/modules/messaging-redis/loaders/connection.tsnew file mode 100644index 000000000..cdc6f5170--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-redis/loaders/connection.ts@@ -0,0 +1,43 @@+import { LoaderOptions } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { asValue } from "@medusajs/framework/awilix"+import Redis from "ioredis"++export default async function messagingRedisConnectionLoader({+ container,+ options,+}: LoaderOptions): Promise<void> {+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)++ const redisUrl = options?.redisUrl as string | undefined++ if (!redisUrl) {+ logger.warn(+ "[messaging-redis] No redisUrl provided in module options — Redis features disabled"+ )+ container.register("messagingRedisConnection", asValue(null))+ return+ }++ try {+ const connection = new Redis(redisUrl, {+ lazyConnect: true,+ maxRetriesPerRequest: 3,+ retryStrategy(times: number) {+ if (times > 5) return null+ return Math.min(times * 200, 2000)+ },+ })++ await connection.connect()++ container.register("messagingRedisConnection", asValue(connection))++ logger.info("[messaging-redis] Connected to Redis")+ } catch (err) {+ logger.error(+ `[messaging-redis] Failed to connect to Redis: ${(err as Error).message}`+ )+ container.register("messagingRedisConnection", asValue(null))+ }+}diff --git a/packages/registry/src/messaging/modules/messaging-redis/service.ts b/packages/registry/src/messaging/modules/messaging-redis/service.tsnew file mode 100644index 000000000..e96144b7d--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging-redis/service.ts@@ -0,0 +1,95 @@+import Redis from "ioredis"++type MessagingRedisModuleOptions = {+ redisUrl?: string+}++class MessagingRedisModuleService {+ private connection_: Redis | null++ static readonly identifier = "messagingRedis"++ __hooks: Record<string, () => Promise<void>>++ constructor(+ { messagingRedisConnection }: { messagingRedisConnection: Redis | null },+ options: MessagingRedisModuleOptions+ ) {+ this.connection_ = messagingRedisConnection++ this.__hooks = {+ onApplicationShutdown: async () => {+ if (this.connection_) {+ this.connection_.disconnect()+ }+ },+ }+ }++ get isAvailable(): boolean {+ return this.connection_ !== null+ }++ // --- Token operations (SSE one-time tokens) ---++ async setToken(token: string, value: string, ttlSeconds: number): Promise<void> {+ if (!this.connection_) return+ await this.connection_.set(`sse_token:${token}`, value, "EX", ttlSeconds)+ }++ async consumeToken(token: string): Promise<string | null> {+ if (!this.connection_) return null+ // Atomic get-and-delete to prevent TOCTOU race (token reuse)+ const value = await this.connection_.getdel(`sse_token:${token}`)+ return value+ }++ // --- Rate limiting ---++ async checkRateLimit(+ key: string,+ limit: number,+ windowSeconds: number+ ): Promise<{ allowed: boolean; count: number }> {+ if (!this.connection_) return { allowed: true, count: 0 }++ // Atomic INCR + conditional EXPIRE via Lua to prevent orphaned keys+ const luaScript = `+ local count = redis.call('INCR', KEYS[1])+ if count == 1 then+ redis.call('EXPIRE', KEYS[1], ARGV[1])+ end+ return count+ `+ const count = await this.connection_.eval(+ luaScript, 1, key, windowSeconds+ ) as number++ return { allowed: count <= limit, count }+ }++ // --- Pub/Sub: publish ---++ async publish(channel: string, data: Record<string, unknown>): Promise<void> {+ if (!this.connection_) return+ await this.connection_.publish(channel, JSON.stringify(data))+ }++ // --- Pub/Sub: create subscriber ---++ createSubscriber(): Redis | null {+ if (!this.connection_) return null+ return this.connection_.duplicate()+ }++ // --- Notification throttle ---++ async trySetThrottle(key: string, ttlSeconds: number): Promise<boolean> {+ if (!this.connection_) return true // No Redis = allow (don't block notifications)++ const result = await this.connection_.set(key, "1", "EX", ttlSeconds, "NX")+ return result === "OK"+ }+}++export default MessagingRedisModuleServicediff --git a/packages/registry/src/messaging/modules/messaging/index.ts b/packages/registry/src/messaging/modules/messaging/index.tsnew file mode 100644index 000000000..c70cc88c5--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/index.ts@@ -0,0 +1,13 @@+import { Module } from "@medusajs/framework/utils"++import MessagingModuleService from "./service"++export const MESSAGING_MODULE = "messaging"++export * from "./types/common"+export * from "./types/mutations"+export { MessagingModuleService }++export default Module(MESSAGING_MODULE, {+ service: MessagingModuleService,+})diff --git a/packages/registry/src/messaging/modules/messaging/models/chat-block.ts b/packages/registry/src/messaging/modules/messaging/models/chat-block.tsnew file mode 100644index 000000000..c57a1f850--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/models/chat-block.ts@@ -0,0 +1,15 @@+import { model } from "@medusajs/framework/utils"++export const ChatBlock = model+ .define("chat_block", {+ id: model.id({ prefix: "cblk" }).primaryKey(),+ customer_id: model.text(),+ blocked_by: model.text(),+ reason: model.text().nullable(),+ })+ .indexes([+ {+ on: ["customer_id"],+ unique: true,+ },+ ])diff --git a/packages/registry/src/messaging/modules/messaging/models/conversation.ts b/packages/registry/src/messaging/modules/messaging/models/conversation.tsnew file mode 100644index 000000000..a41d10321--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/models/conversation.ts@@ -0,0 +1,28 @@+import { model } from "@medusajs/framework/utils"++export const Conversation = model+ .define("conversation", {+ id: model.id({ prefix: "conv" }).primaryKey(),+ buyer_id: model.text(),+ seller_id: model.text(),+ last_message_preview: model.text().nullable(),+ last_message_sender_type: model.enum(["customer", "seller"]).nullable(),+ last_message_at: model.dateTime().nullable(),+ unread_count_customer: model.number().default(0),+ unread_count_seller: model.number().default(0),+ messages: model.hasMany(() => Message, { mappedBy: "conversation" }),+ })+ .indexes([+ {+ on: ["buyer_id", "seller_id"],+ unique: true,+ },+ {+ on: ["seller_id", "last_message_at", "id"],+ },+ {+ on: ["buyer_id", "last_message_at", "id"],+ },+ ])++import { Message } from "./message"diff --git a/packages/registry/src/messaging/modules/messaging/models/message.ts b/packages/registry/src/messaging/modules/messaging/models/message.tsnew file mode 100644index 000000000..cbe573d36--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/models/message.ts@@ -0,0 +1,28 @@+import { model } from "@medusajs/framework/utils"+import { Conversation } from "./conversation"++export const Message = model+ .define("message", {+ id: model.id({ prefix: "msg" }).primaryKey(),+ conversation: model.belongsTo(() => Conversation, {+ mappedBy: "messages",+ }),+ sender_id: model.text(),+ sender_type: model.enum(["customer", "seller"]),+ body: model.text(),+ context_type: model.enum(["product", "order"]).nullable(),+ context_id: model.text().nullable(),+ context_label: model.text().nullable(),+ read_at: model.dateTime().nullable(),+ })+ .indexes([+ {+ on: ["conversation_id", "created_at", "id"],+ },+ {+ on: ["context_type", "context_id"],+ },+ {+ on: ["created_at"],+ },+ ])diff --git a/packages/registry/src/messaging/modules/messaging/service.ts b/packages/registry/src/messaging/modules/messaging/service.tsnew file mode 100644index 000000000..35971006d--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/service.ts@@ -0,0 +1,433 @@+import { InjectManager, MedusaContext, MedusaService } from "@medusajs/framework/utils"+import { Context } from "@medusajs/framework/types"+import { EntityManager, type Knex } from "@medusajs/framework/mikro-orm/knex"++import { Conversation } from "./models/conversation"+import { Message } from "./models/message"+import { ChatBlock } from "./models/chat-block"+import {+ CursorPaginatedResult,+ ConversationDTO,+ MessageDTO,+ MessagingModuleOptions,+ ResolvedMessagingModuleOptions,+ MESSAGING_MODULE_OPTION_DEFAULTS,+} from "./types/common"++const TABLE_CONVERSATION = "conversation"+const TABLE_MESSAGE = "message"+const TABLE_CHAT_BLOCK = "chat_block"+const MAX_PREVIEW_LENGTH = 100++function escapeLike(value: string): string {+ return value.replace(/[\\%_]/g, (ch) => `\\${ch}`)+}++export function encodeCursor(values: Record<string, string | number | null>): string {+ return Buffer.from(JSON.stringify(values)).toString("base64url")+}++export function decodeCursor(cursor: string): Record<string, string | number | null> | null {+ try {+ return JSON.parse(Buffer.from(cursor, "base64url").toString("utf-8"))+ } catch {+ return null+ }+}++class MessagingModuleService extends MedusaService({+ Conversation,+ Message,+ ChatBlock,+}) {+ protected readonly options_: ResolvedMessagingModuleOptions++ constructor(_deps: unknown, options?: MessagingModuleOptions) {+ // @ts-ignore — MedusaService base accepts arbitrary constructor args+ super(...arguments)+ this.options_ = {+ rateLimits: {+ ...MESSAGING_MODULE_OPTION_DEFAULTS.rateLimits,+ ...(options?.rateLimits ?? {}),+ },+ }+ }++ getOptions(): ResolvedMessagingModuleOptions {+ return this.options_+ }++ @InjectManager()+ async checkBuyersBlocked(+ buyerIds: string[],+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<Set<string>> {+ if (buyerIds.length === 0) return new Set()+ const knex = sharedContext!.manager!.getKnex()+ const rows: { customer_id: string }[] = await knex(TABLE_CHAT_BLOCK)+ .select("customer_id")+ .whereIn("customer_id", buyerIds)+ .whereNull("deleted_at")+ return new Set(rows.map((r) => r.customer_id))+ }++ @InjectManager()+ async getBlockDetail(+ customerId: string,+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<{ blocked: boolean; reason: string | null }> {+ const knex = sharedContext!.manager!.getKnex()+ const row: { reason: string | null } | undefined = await knex(TABLE_CHAT_BLOCK)+ .select("reason")+ .where("customer_id", customerId)+ .whereNull("deleted_at")+ .first()++ return row+ ? { blocked: true, reason: row.reason }+ : { blocked: false, reason: null }+ }++ @InjectManager()+ async listConversationsCursor(+ filter: { buyer_id?: string; seller_id?: string },+ pagination: { cursor?: string | null; limit?: number },+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<CursorPaginatedResult<ConversationDTO>> {+ const knex = sharedContext!.manager!.getKnex()+ const limit = Math.min(pagination.limit ?? 20, 50)++ let query = knex(TABLE_CONVERSATION)+ .select("*")+ .where("deleted_at", null)+ .orderByRaw("last_message_at DESC NULLS LAST, id DESC")+ .limit(limit + 1)++ if (filter.buyer_id) {+ query = query.where("buyer_id", filter.buyer_id)+ }++ if (filter.seller_id) {+ query = query.where("seller_id", filter.seller_id)+ }++ if (pagination.cursor) {+ const decoded = decodeCursor(pagination.cursor)+ if (decoded && decoded.last_message_at && decoded.id) {+ query = query.where(function () {+ this.where("last_message_at", "<", decoded.last_message_at!)+ .orWhere(function () {+ this.where("last_message_at", "=", decoded.last_message_at!)+ .andWhere("id", "<", decoded.id!)+ })+ })+ }+ }++ const rows: any[] = await query++ const hasMore = rows.length > limit+ const data = hasMore ? rows.slice(0, limit) : rows++ let next_cursor: string | null = null+ if (hasMore && data.length > 0) {+ const lastRow = data[data.length - 1]+ next_cursor = encodeCursor({+ last_message_at: lastRow.last_message_at?.toISOString?.() ?? lastRow.last_message_at,+ id: lastRow.id,+ })+ }++ return { data, next_cursor }+ }++ @InjectManager()+ async listMessagesCursor(+ conversationId: string,+ pagination: { cursor?: string | null; limit?: number },+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<CursorPaginatedResult<MessageDTO>> {+ const knex = sharedContext!.manager!.getKnex()+ const limit = Math.min(pagination.limit ?? 30, 100)++ let query = knex(TABLE_MESSAGE)+ .select("*")+ .where("conversation_id", conversationId)+ .where("deleted_at", null)+ .orderByRaw("created_at DESC, id DESC")+ .limit(limit + 1)++ if (pagination.cursor) {+ const decoded = decodeCursor(pagination.cursor)+ if (decoded && decoded.created_at && decoded.id) {+ query = query.where(function () {+ this.where("created_at", "<", decoded.created_at!)+ .orWhere(function () {+ this.where("created_at", "=", decoded.created_at!)+ .andWhere("id", "<", decoded.id!)+ })+ })+ }+ }++ const rows: any[] = await query++ const hasMore = rows.length > limit+ const data = hasMore ? rows.slice(0, limit) : rows++ let next_cursor: string | null = null+ if (hasMore && data.length > 0) {+ const lastRow = data[data.length - 1]+ next_cursor = encodeCursor({+ created_at: lastRow.created_at?.toISOString?.() ?? lastRow.created_at,+ id: lastRow.id,+ })+ }++ return { data, next_cursor }+ }++ /**+ * Cross-module admin search: joins conversation with seller + customer+ * tables via raw Knex for performance (avoids N+1 queries). This is+ * intentional — admin oversight requires denormalized data in a single+ * paginated query. Module isolation is preserved at the application+ * layer; this method is only used by the admin search route.+ */+ @InjectManager()+ async searchConversationsAdmin(+ filter: {+ seller_name?: string+ buyer_name?: string+ date_from?: string+ date_to?: string+ context_type?: string+ context_id?: string+ },+ pagination: { cursor?: string | null; limit?: number },+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<CursorPaginatedResult<ConversationDTO & { seller_name?: string; buyer_name?: string; buyer_email?: string; message_count?: number }>> {+ const knex = sharedContext!.manager!.getKnex()+ const limit = Math.min(pagination.limit ?? 20, 50)++ let query = knex(`${TABLE_CONVERSATION} as c`)+ .select(+ "c.*",+ "s.name as seller_name",+ "cust.first_name as buyer_first_name",+ "cust.last_name as buyer_last_name",+ "cust.email as buyer_email"+ )+ .leftJoin(+ "seller_seller_messaging_conversation as sc",+ "sc.conversation_id",+ "c.id"+ )+ .leftJoin("seller as s", "s.id", "sc.seller_id")+ .leftJoin(+ "customer_customer_messaging_conversation as cc",+ "cc.conversation_id",+ "c.id"+ )+ .leftJoin("customer as cust", "cust.id", "cc.customer_id")+ .where("c.deleted_at", null)+ .orderByRaw("c.last_message_at DESC NULLS LAST, c.id DESC")+ .limit(limit + 1)++ if (filter.seller_name) {+ query = query.whereILike("s.name", `%${escapeLike(filter.seller_name)}%`)+ }++ if (filter.buyer_name) {+ const escaped = escapeLike(filter.buyer_name)+ query = query.where(function () {+ this.whereILike("cust.first_name", `%${escaped}%`)+ .orWhereILike("cust.last_name", `%${escaped}%`)+ })+ }++ if (filter.date_from) {+ query = query.where("c.last_message_at", ">=", filter.date_from)+ }++ if (filter.date_to) {+ query = query.where("c.last_message_at", "<=", filter.date_to)+ }++ if (filter.context_type || filter.context_id) {+ query = query.whereExists(function () {+ this.select(knex.raw("1"))+ .from(`${TABLE_MESSAGE} as m`)+ .whereRaw("m.conversation_id = c.id")++ if (filter.context_type) {+ this.where("m.context_type", filter.context_type)+ }+ if (filter.context_id) {+ this.where("m.context_id", filter.context_id)+ }+ })+ }++ if (pagination.cursor) {+ const decoded = decodeCursor(pagination.cursor)+ if (decoded && decoded.last_message_at && decoded.id) {+ query = query.where(function () {+ this.where("c.last_message_at", "<", decoded.last_message_at!)+ .orWhere(function () {+ this.where("c.last_message_at", "=", decoded.last_message_at!)+ .andWhere("c.id", "<", decoded.id!)+ })+ })+ }+ }++ const rows: any[] = await query++ const hasMore = rows.length > limit+ const data = (hasMore ? rows.slice(0, limit) : rows).map((row: any) => ({+ ...row,+ buyer_name: [row.buyer_first_name, row.buyer_last_name]+ .filter(Boolean)+ .join(" "),+ }))++ let next_cursor: string | null = null+ if (hasMore && data.length > 0) {+ const lastRow = data[data.length - 1]+ next_cursor = encodeCursor({+ last_message_at: lastRow.last_message_at?.toISOString?.() ?? lastRow.last_message_at,+ id: lastRow.id,+ })+ }++ return { data, next_cursor }+ }++ @InjectManager()+ async getUnreadCountTotal(+ filter: { buyer_id?: string; seller_id?: string },+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<number> {+ const knex = sharedContext!.manager!.getKnex()++ const countField = filter.buyer_id+ ? "unread_count_customer"+ : "unread_count_seller"++ let query = knex(TABLE_CONVERSATION)+ .sum({ total: countField })+ .where("deleted_at", null)++ if (filter.buyer_id) {+ query = query.where("buyer_id", filter.buyer_id)+ }++ if (filter.seller_id) {+ query = query.where("seller_id", filter.seller_id)+ }++ const [result] = await query++ return Number(result?.total ?? 0)+ }++ @InjectManager()+ async createMessageAtomic(+ data: {+ conversation_id: string+ sender_id: string+ sender_type: "customer" | "seller"+ body: string+ context_type?: string | null+ context_id?: string | null+ context_label?: string | null+ },+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<MessageDTO> {+ const knex = sharedContext!.manager!.getKnex()++ const preview = data.body.substring(0, MAX_PREVIEW_LENGTH)+ const recipientCounterField =+ data.sender_type === "customer"+ ? "unread_count_seller"+ : "unread_count_customer"++ const now = new Date()++ return await knex.transaction(async (trx) => {+ const [message] = await trx(TABLE_MESSAGE)+ .insert({+ id: `msg_${generateId()}`,+ conversation_id: data.conversation_id,+ sender_id: data.sender_id,+ sender_type: data.sender_type,+ body: data.body,+ context_type: data.context_type ?? null,+ context_id: data.context_id ?? null,+ context_label: data.context_label ?? null,+ read_at: null,+ created_at: now,+ updated_at: now,+ deleted_at: null,+ })+ .returning("*")++ await trx(TABLE_CONVERSATION)+ .where("id", data.conversation_id)+ .update({+ last_message_preview: preview,+ last_message_sender_type: data.sender_type,+ last_message_at: now,+ [recipientCounterField]: knex.raw(`?? + 1`, [recipientCounterField]),+ updated_at: now,+ })++ return message+ })+ }++ @InjectManager()+ async markMessagesReadAtomic(+ conversationId: string,+ readerType: "customer" | "seller",+ @MedusaContext() sharedContext?: Context<EntityManager>+ ): Promise<number> {+ const knex = sharedContext!.manager!.getKnex()++ const senderType = readerType === "customer" ? "seller" : "customer"+ const counterField =+ readerType === "customer"+ ? "unread_count_customer"+ : "unread_count_seller"++ const now = new Date()++ return await knex.transaction(async (trx) => {+ const updated = await trx(TABLE_MESSAGE)+ .where("conversation_id", conversationId)+ .where("sender_type", senderType)+ .whereNull("read_at")+ .whereNull("deleted_at")+ .update({+ read_at: now,+ updated_at: now,+ })++ await trx(TABLE_CONVERSATION)+ .where("id", conversationId)+ .update({+ [counterField]: 0,+ updated_at: now,+ })++ return updated+ })+ }+}++function generateId(): string {+ return crypto.randomUUID().replace(/-/g, "").substring(0, 16)+}++export default MessagingModuleServicediff --git a/packages/registry/src/messaging/modules/messaging/types/common.ts b/packages/registry/src/messaging/modules/messaging/types/common.tsnew file mode 100644index 000000000..bb5adf836--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/types/common.ts@@ -0,0 +1,125 @@+export type SenderType = "customer" | "seller"+export type ContextType = "product" | "order"++export interface ConversationDTO {+ id: string+ buyer_id: string+ seller_id: string+ last_message_preview: string | null+ last_message_sender_type: SenderType | null+ last_message_at: Date | string | null+ unread_count_customer: number+ unread_count_seller: number+ created_at: Date | string+ updated_at: Date | string+ deleted_at: Date | string | null+}++export interface MessageDTO {+ id: string+ conversation_id: string+ sender_id: string+ sender_type: SenderType+ body: string+ context_type: ContextType | null+ context_id: string | null+ context_label: string | null+ read_at: Date | string | null+ created_at: Date | string+ updated_at: Date | string+ deleted_at: Date | string | null+}++export interface CursorPaginationParams {+ cursor?: string | null+ limit?: number+}++export interface CursorPaginatedResult<T> {+ data: T[]+ next_cursor: string | null+}++export interface StoreConversationResponse {+ conversation: ConversationDTO+}++export type StoreConversationListResponse = {+ conversations: ConversationDTO[]+ next_cursor: string | null+}++export interface StoreMessageResponse {+ message: MessageDTO+}++export type StoreMessageListResponse = {+ messages: MessageDTO[]+ next_cursor: string | null+}++export interface VendorConversationResponse {+ conversation: ConversationDTO+}++export type VendorConversationListResponse = {+ conversations: ConversationDTO[]+ next_cursor: string | null+}++export interface VendorMessageResponse {+ message: MessageDTO+}++export type AdminConversationListResponse = {+ conversations: ConversationDTO[]+ next_cursor: string | null+}++export interface AdminConversationResponse {+ conversation: ConversationDTO+}++export interface ChatBlockDTO {+ id: string+ customer_id: string+ blocked_by: string+ reason: string | null+ created_at: Date | string+ updated_at: Date | string+}++export interface UnreadCountResponse {+ unread_count: number+}++export interface SseTokenResponse {+ token: string+}++export type MessagingRateLimitOptions = {+ /** Maximum messages a single sender can send per minute. */+ messagesPerMinute?: number+ /** Maximum new conversations a single sender can open per hour. */+ conversationsPerHour?: number+}++export type MessagingModuleOptions = {+ rateLimits?: MessagingRateLimitOptions+}++export type ResolvedMessagingRateLimitOptions = {+ messagesPerMinute: number+ conversationsPerHour: number+}++export type ResolvedMessagingModuleOptions = {+ rateLimits: ResolvedMessagingRateLimitOptions+}++export const MESSAGING_MODULE_OPTION_DEFAULTS: ResolvedMessagingModuleOptions = {+ rateLimits: {+ messagesPerMinute: 20,+ conversationsPerHour: 5,+ },+}diff --git a/packages/registry/src/messaging/modules/messaging/types/mutations.ts b/packages/registry/src/messaging/modules/messaging/types/mutations.tsnew file mode 100644index 000000000..c40339bd8--- /dev/null+++ b/packages/registry/src/messaging/modules/messaging/types/mutations.ts@@ -0,0 +1,43 @@+import { ContextType, SenderType } from "./common"++export interface CreateConversationInput {+ buyer_id: string+ seller_id: string+}++export interface SendMessageInput {+ conversation_id: string+ sender_id: string+ sender_type: SenderType+ body: string+ context_type?: ContextType | null+ context_id?: string | null+ context_label?: string | null+}++export interface MarkMessagesReadInput {+ conversation_id: string+ reader_id: string+ reader_type: SenderType+}++export interface BlockCustomerInput {+ customer_id: string+ blocked_by: string+ reason?: string | null+}++export interface UnblockCustomerInput {+ customer_id: string+}++export interface PublishMessageEventInput {+ conversation_id: string+ recipient_id: string+ sender_type: SenderType+ event_type: "new_message" | "messages_read" | "unread_count"+ context_type?: string | null+ context_label?: string | null+ message_id?: string+ unread_count?: number+}diff --git a/packages/registry/src/messaging/subscribers/buyer-deletion.ts b/packages/registry/src/messaging/subscribers/buyer-deletion.tsnew file mode 100644index 000000000..91f5f1520--- /dev/null+++ b/packages/registry/src/messaging/subscribers/buyer-deletion.ts@@ -0,0 +1,30 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import { anonymizeBuyerMessagesWorkflow } from "../workflows/messaging/workflows/anonymize-buyer-messages"++export default async function buyerDeletionHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)++ try {+ await anonymizeBuyerMessagesWorkflow.run({+ container,+ input: { buyer_id: event.data.id },+ })++ logger.info(+ `Messaging: buyer ${event.data.id} messages anonymized (GDPR erasure)`+ )+ } catch (err) {+ logger.error(+ `Messaging: buyer deletion handler error: ${(err as Error).message}`+ )+ }+}++export const config: SubscriberConfig = {+ event: "customer.deleted",+}diff --git a/packages/registry/src/messaging/subscribers/message-notification.ts b/packages/registry/src/messaging/subscribers/message-notification.tsnew file mode 100644index 000000000..18f73c88d--- /dev/null+++ b/packages/registry/src/messaging/subscribers/message-notification.ts@@ -0,0 +1,128 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import { MESSAGING_REDIS_MODULE } from "../modules/messaging-redis"+import type MessagingRedisModuleService from "../modules/messaging-redis/service"++type MessageCreatedData = {+ id: string+ conversation_id: string+ sender_id: string+ sender_type: "customer" | "seller"+ recipient_id: string+}++const THROTTLE_TTL_SECONDS = 900 // 15 minutes++export default async function messageNotificationHandler({+ event,+ container,+}: SubscriberArgs<MessageCreatedData>) {+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)+ const { conversation_id, sender_id, sender_type, recipient_id } = event.data++ try {+ // Check throttle — one notification per conversation per recipient per 15 min+ const redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)+ const throttleKey = `notify:${conversation_id}:${recipient_id}`++ const allowed = await redisService.trySetThrottle(throttleKey, THROTTLE_TTL_SECONDS)++ if (!allowed) {+ // Already notified recently, skip+ return+ }++ // Resolve sender name for the email+ const query = container.resolve(ContainerRegistrationKeys.QUERY)+ let senderName = "Someone"++ if (sender_type === "customer") {+ try {+ const { data: customers } = await query.graph({+ entity: "customer",+ fields: ["id", "first_name"],+ filters: { id: sender_id },+ })+ if (customers?.length > 0) {+ senderName = customers[0].first_name || "A customer"+ }+ } catch {+ // Use default name+ }+ } else {+ try {+ const { data: sellers } = await query.graph({+ entity: "seller",+ fields: ["id", "name"],+ filters: { id: sender_id },+ })+ if (sellers?.length > 0) {+ senderName = sellers[0].name || "A vendor"+ }+ } catch {+ // Use default name+ }+ }++ // Resolve recipient email+ let recipientEmail: string | null = null+ const recipientType = sender_type === "customer" ? "seller" : "customer"++ if (recipientType === "customer") {+ try {+ const { data: customers } = await query.graph({+ entity: "customer",+ fields: ["id", "email"],+ filters: { id: recipient_id },+ })+ if (customers?.length > 0) {+ recipientEmail = customers[0].email+ }+ } catch {+ // Cannot determine email+ }+ }+ // For sellers, email notification requires seller email which may be in auth_identity+ // This is operator-customizable — emit notification event for flexibility++ if (!recipientEmail) {+ logger.debug(+ `Messaging: skipping email notification for ${recipientType} ${recipient_id} — no email found`+ )+ return+ }++ // Send notification via Medusa notification module+ // Privacy: no message body included in email+ try {+ const notificationService: { createNotifications: (data: Record<string, unknown>) => Promise<void> } =+ container.resolve("notification")+ await notificationService.createNotifications({+ to: recipientEmail,+ channel: "email",+ template: "messaging-new-message",+ data: {+ sender_name: senderName,+ conversation_id,+ },+ })++ logger.debug(+ `Messaging: email notification sent to ${recipientEmail} for conversation ${conversation_id}`+ )+ } catch (err) {+ logger.warn(+ `Messaging: failed to send email notification: ${(err as Error).message}`+ )+ }+ } catch (err) {+ logger.error(+ `Messaging: notification handler error: ${(err as Error).message}`+ )+ }+}++export const config: SubscriberConfig = {+ event: "messaging.message.created",+}diff --git a/packages/registry/src/messaging/subscribers/vendor-removal.ts b/packages/registry/src/messaging/subscribers/vendor-removal.tsnew file mode 100644index 000000000..23454fc60--- /dev/null+++ b/packages/registry/src/messaging/subscribers/vendor-removal.ts@@ -0,0 +1,30 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import { anonymizeVendorMessagesWorkflow } from "../workflows/messaging/workflows/anonymize-vendor-messages"++export default async function vendorRemovalHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)++ try {+ await anonymizeVendorMessagesWorkflow.run({+ container,+ input: { seller_id: event.data.id },+ })++ logger.info(+ `Messaging: vendor ${event.data.id} conversations anonymized (offboarding)`+ )+ } catch (err) {+ logger.error(+ `Messaging: vendor removal handler error: ${(err as Error).message}`+ )+ }+}++export const config: SubscriberConfig = {+ event: "seller.deleted",+}diff --git a/packages/registry/src/messaging/vendor/hooks/api/messaging.tsx b/packages/registry/src/messaging/vendor/hooks/api/messaging.tsxnew file mode 100644index 000000000..a67a5ad90--- /dev/null+++ b/packages/registry/src/messaging/vendor/hooks/api/messaging.tsx@@ -0,0 +1,179 @@+import {+ useQuery,+ useInfiniteQuery,+ useMutation,+ useQueryClient,+ UseQueryOptions,+ UseMutationOptions,+} from "@tanstack/react-query"+import { queryKeysFactory } from "@mercurjs/dashboard-shared"+import { client } from "../../lib/client"+import { ClientError } from "@mercurjs/client"++const CONVERSATIONS_QUERY_KEY = "vendor_conversations" as const+export const conversationsQueryKeys = queryKeysFactory(CONVERSATIONS_QUERY_KEY)++const UNREAD_QUERY_KEY = "vendor_messaging_unread" as const+export const unreadQueryKeys = queryKeysFactory(UNREAD_QUERY_KEY)++export type ConversationDTO = {+ id: string+ seller_id: string+ buyer_id: string+ buyer_first_name?: string | null+ last_message_preview: string | null+ last_message_sender_type: "customer" | "seller" | null+ last_message_at: string | null+ unread_count_seller: number+ created_at: string+ updated_at: string+ is_buyer_blocked?: boolean+}++export type MessageDTO = {+ id: string+ sender_type: "customer" | "seller"+ body: string+ context_type: "product" | "order" | null+ context_id: string | null+ context_label: string | null+ read_at: string | null+ created_at: string+}++type ConversationListResponse = {+ conversations: ConversationDTO[]+ next_cursor: string | null+}++type ConversationDetailResponse = {+ conversation: ConversationDTO+ messages: MessageDTO[]+ next_cursor: string | null+ buyer_orders: any[]+}++type UnreadResponse = {+ unread_count: number+}++export const useVendorConversations = (+ query?: { cursor?: string; limit?: number },+ options?: Omit<+ UseQueryOptions<ConversationListResponse, ClientError>,+ "queryKey" | "queryFn"+ >+) => {+ const { data, ...rest } = useQuery({+ queryKey: conversationsQueryKeys.list(query),+ queryFn: async () =>+ (client as any).vendor.messages.query(query ?? {}) as Promise<ConversationListResponse>,+ ...options,+ })++ return { ...data, ...rest }+}++export const useVendorConversation = (+ id: string,+ query?: { limit?: number },+) => {+ const limit = query?.limit ?? 20++ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, ...rest } =+ useInfiniteQuery<ConversationDetailResponse, ClientError>({+ queryKey: conversationsQueryKeys.detail(id, { limit }),+ queryFn: async ({ pageParam }) =>+ (client as any).vendor.messages.$id.query({+ $id: id,+ limit,+ ...(pageParam ? { cursor: pageParam } : {}),+ }) as Promise<ConversationDetailResponse>,+ initialPageParam: undefined as string | undefined,+ getNextPageParam: (lastPage) => lastPage.next_cursor ?? undefined,+ })++ const conversation = data?.pages[0]?.conversation+ const buyer_orders = data?.pages[0]?.buyer_orders+ const messages = data?.pages.flatMap((p) => p.messages) ?? []++ return {+ conversation,+ messages,+ buyer_orders,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ ...rest,+ }+}++export const useVendorUnread = (+ options?: Omit<+ UseQueryOptions<UnreadResponse, ClientError>,+ "queryKey" | "queryFn"+ >+) => {+ const { data, ...rest } = useQuery({+ queryKey: unreadQueryKeys.detail("total"),+ queryFn: async () =>+ (client as any).vendor.messages.unread.query() as Promise<UnreadResponse>,+ ...options,+ })++ return { ...data, ...rest }+}++export const useSendVendorReply = (+ conversationId: string,+ options?: UseMutationOptions<{ message: MessageDTO }, ClientError, { body: string }>+) => {+ const queryClient = useQueryClient()+ const { onSuccess, onError, ...restOptions } = options ?? {}++ return useMutation({+ ...restOptions,+ mutationFn: (payload: { body: string }) =>+ (client as any).vendor.messages.$id.mutate({ $id: conversationId, ...payload }) as Promise<{ message: MessageDTO }>,+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({+ queryKey: conversationsQueryKeys.detail(conversationId),+ })+ queryClient.invalidateQueries({+ queryKey: conversationsQueryKeys.lists(),+ })+ queryClient.invalidateQueries({+ queryKey: unreadQueryKeys.all,+ })+ onSuccess?.(data, variables, context)+ },+ onError,+ })+}++export const useMarkVendorRead = (+ conversationId: string,+ options?: UseMutationOptions<{ success: boolean }, ClientError, void>+) => {+ const queryClient = useQueryClient()+ const { onSuccess, onError, ...restOptions } = options ?? {}++ return useMutation({+ ...restOptions,+ mutationFn: () =>+ (client as any).vendor.messages.$id.read.mutate({ $id: conversationId }) as Promise<{ success: boolean }>,+ onSuccess: (data, variables, context) => {+ queryClient.invalidateQueries({+ queryKey: conversationsQueryKeys.detail(conversationId),+ })+ queryClient.invalidateQueries({+ queryKey: conversationsQueryKeys.lists(),+ })+ queryClient.invalidateQueries({+ queryKey: unreadQueryKeys.all,+ })+ onSuccess?.(data, variables, context)+ },+ onError,+ })+}diff --git a/packages/registry/src/messaging/vendor/hooks/api/use-messaging-sse.tsx b/packages/registry/src/messaging/vendor/hooks/api/use-messaging-sse.tsxnew file mode 100644index 000000000..4bbc571b2--- /dev/null+++ b/packages/registry/src/messaging/vendor/hooks/api/use-messaging-sse.tsx@@ -0,0 +1,159 @@+import { useEffect, useRef } from "react"+import { useQueryClient } from "@tanstack/react-query"+import { conversationsQueryKeys, unreadQueryKeys } from "./messaging"++declare const __BACKEND_URL__: string++type SSEStatus = "connecting" | "connected" | "disconnected" | "polling"++const POLLING_INTERVAL_LIST = 30000+const POLLING_INTERVAL_UNREAD = 15000++export const useMessagingSSE = (+ activeConversationId?: string,+ onStatusChange?: (status: SSEStatus) => void+) => {+ const queryClient = useQueryClient()+ const eventSourceRef = useRef<EventSource | null>(null)+ const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null)+ const unreadPollingRef = useRef<ReturnType<typeof setInterval> | null>(null)+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const reconnectDelayRef = useRef(1000)+ const statusRef = useRef<SSEStatus>("disconnected")+ const mountedRef = useRef(true)++ // Store callbacks in refs to avoid dependency chains+ const onStatusChangeRef = useRef(onStatusChange)+ onStatusChangeRef.current = onStatusChange++ const activeIdRef = useRef(activeConversationId)+ activeIdRef.current = activeConversationId++ useEffect(() => {+ mountedRef.current = true++ const setStatus = (status: SSEStatus) => {+ statusRef.current = status+ onStatusChangeRef.current?.(status)+ }++ const invalidateQueries = () => {+ queryClient.invalidateQueries({ queryKey: conversationsQueryKeys.all })+ queryClient.invalidateQueries({ queryKey: unreadQueryKeys.all })+ }++ const invalidateConversation = (conversationId: string) => {+ queryClient.invalidateQueries({+ queryKey: conversationsQueryKeys.detail(conversationId),+ })+ }++ const stopPolling = () => {+ if (pollingRef.current) {+ clearInterval(pollingRef.current)+ pollingRef.current = null+ }+ if (unreadPollingRef.current) {+ clearInterval(unreadPollingRef.current)+ unreadPollingRef.current = null+ }+ }++ const startPolling = () => {+ if (pollingRef.current) return+ setStatus("polling")++ pollingRef.current = setInterval(() => {+ invalidateQueries()+ }, POLLING_INTERVAL_LIST)++ unreadPollingRef.current = setInterval(() => {+ queryClient.invalidateQueries({ queryKey: unreadQueryKeys.all })+ }, POLLING_INTERVAL_UNREAD)+ }++ const connect = () => {+ if (!mountedRef.current) return++ if (eventSourceRef.current) {+ eventSourceRef.current.close()+ }++ setStatus("connecting")++ const baseUrl = typeof __BACKEND_URL__ !== "undefined" ? __BACKEND_URL__ : ""+ const url = `${baseUrl}/vendor/messages/events`++ const es = new EventSource(url, { withCredentials: true })+ eventSourceRef.current = es++ es.addEventListener("connected", () => {+ setStatus("connected")+ stopPolling()+ reconnectDelayRef.current = 1000 // Reset backoff on success+ })++ es.addEventListener("new_message", (event: MessageEvent) => {+ invalidateQueries()+ try {+ const data = JSON.parse(event.data)+ if (data.conversation_id) {+ invalidateConversation(data.conversation_id)+ }+ } catch {+ // Broad invalidation already handled above+ }+ })++ es.addEventListener("messages_read", (event: MessageEvent) => {+ invalidateQueries()+ try {+ const data = JSON.parse(event.data)+ if (data.conversation_id) {+ invalidateConversation(data.conversation_id)+ }+ } catch {+ // Broad invalidation already handled above+ }+ })++ es.addEventListener("unread_count", () => {+ queryClient.invalidateQueries({ queryKey: unreadQueryKeys.all })+ })++ es.onerror = () => {+ es.close()+ eventSourceRef.current = null+ startPolling()++ // Exponential backoff: 1s, 2s, 4s, 8s, ..., max 30s+ const delay = reconnectDelayRef.current+ reconnectDelayRef.current = Math.min(delay * 2, 30000)++ reconnectTimerRef.current = setTimeout(() => {+ reconnectTimerRef.current = null+ if (mountedRef.current && statusRef.current === "polling") {+ connect()+ }+ }, delay)+ }+ }++ connect()++ return () => {+ mountedRef.current = false+ if (eventSourceRef.current) {+ eventSourceRef.current.close()+ eventSourceRef.current = null+ }+ stopPolling()+ if (reconnectTimerRef.current) {+ clearTimeout(reconnectTimerRef.current)+ reconnectTimerRef.current = null+ }+ }+ }, [queryClient]) // queryClient is stable — no re-render loop++ return { status: statusRef.current }+}diff --git a/packages/registry/src/messaging/vendor/hooks/table/columns/use-conversation-table-columns.tsx b/packages/registry/src/messaging/vendor/hooks/table/columns/use-conversation-table-columns.tsxnew file mode 100644index 000000000..1a501bc00--- /dev/null+++ b/packages/registry/src/messaging/vendor/hooks/table/columns/use-conversation-table-columns.tsx@@ -0,0 +1,76 @@+import { createColumnHelper } from "@tanstack/react-table"+import { useMemo } from "react"+import { StatusBadge, Text } from "@medusajs/ui"+import { DateCell, DateHeader } from "@mercurjs/dashboard-shared"+import { ConversationDTO } from "../../api/messaging"++const columnHelper = createColumnHelper<ConversationDTO>()++export const useConversationTableColumns = () => {+ return useMemo(+ () => [+ columnHelper.accessor("buyer_first_name", {+ header: () => (+ <div className="flex h-full w-full items-center">+ <span className="truncate">Customer</span>+ </div>+ ),+ cell: ({ getValue }) => {+ const name = getValue()+ return (+ <Text size="small" leading="compact">+ {name || "Customer"}+ </Text>+ )+ },+ }),+ columnHelper.accessor("last_message_preview", {+ header: () => (+ <div className="flex h-full w-full items-center">+ <span className="truncate">Last Message</span>+ </div>+ ),+ cell: ({ getValue, row }) => {+ const preview = getValue()+ const senderType = row.original.last_message_sender_type+ const prefix = senderType === "seller" ? "You: " : ""+ return (+ <div className="flex h-full w-full items-center overflow-hidden">+ <Text+ size="small"+ leading="compact"+ className="text-ui-fg-subtle truncate"+ >+ {preview ? `${prefix}${preview}` : "No messages yet"}+ </Text>+ </div>+ )+ },+ }),+ columnHelper.accessor("unread_count_seller", {+ header: () => (+ <div className="flex h-full w-full items-center">+ <span className="truncate">Unread</span>+ </div>+ ),+ cell: ({ getValue }) => {+ const count = getValue()+ if (!count) return null+ return (+ <StatusBadge color="blue">{count}</StatusBadge>+ )+ },+ }),+ columnHelper.accessor("last_message_at", {+ header: () => <DateHeader />,+ cell: ({ getValue }) => {+ const val = getValue()+ if (!val) return <Text size="small" className="text-ui-fg-muted">-</Text>+ const date = new Date(val)+ return <DateCell date={date} />+ },+ }),+ ],+ []+ )+}diff --git a/packages/registry/src/messaging/vendor/hooks/table/query/use-conversation-table-query.tsx b/packages/registry/src/messaging/vendor/hooks/table/query/use-conversation-table-query.tsxnew file mode 100644index 000000000..057bed64a--- /dev/null+++ b/packages/registry/src/messaging/vendor/hooks/table/query/use-conversation-table-query.tsx@@ -0,0 +1,29 @@+import { useQueryParams } from "@mercurjs/dashboard-shared"++type UseConversationTableQueryProps = {+ prefix?: string+ pageSize?: number+}++export const useConversationTableQuery = ({+ prefix,+ pageSize = 20,+}: UseConversationTableQueryProps) => {+ const queryObject = useQueryParams(+ ["offset", "order"],+ prefix+ )++ const { offset, order } = queryObject++ const searchParams: Record<string, any> = {+ limit: pageSize,+ offset: offset ? Number(offset) : 0,+ order: order ? order : "-last_message_at",+ }++ return {+ searchParams,+ raw: queryObject,+ }+}diff --git a/packages/registry/src/messaging/vendor/hooks/use-messaging-layout.ts b/packages/registry/src/messaging/vendor/hooks/use-messaging-layout.tsnew file mode 100644index 000000000..6e8df295a--- /dev/null+++ b/packages/registry/src/messaging/vendor/hooks/use-messaging-layout.ts@@ -0,0 +1,35 @@+import { useLayoutEffect } from "react"++/**+ * Override the shell's scroll behavior to give the messaging+ * pages a full-height, non-scrolling layout. Restores original+ * styles on unmount.+ */+export function useMessagingLayout() {+ useLayoutEffect(() => {+ const main = document.querySelector("main") as HTMLElement | null+ const contentCol = main?.parentElement as HTMLElement | null+ const gutter = main?.firstElementChild as HTMLElement | null++ const origMain = main?.style.cssText ?? ""+ const origCol = contentCol?.style.cssText ?? ""+ const origGutter = gutter?.style.cssText ?? ""++ if (contentCol) contentCol.style.overflow = "hidden"+ if (main) {+ main.style.overflow = "hidden"+ main.style.minHeight = "0"+ }+ if (gutter) {+ gutter.style.flex = "1"+ gutter.style.minHeight = "0"+ gutter.style.overflow = "hidden"+ }++ return () => {+ if (main) main.style.cssText = origMain+ if (contentCol) contentCol.style.cssText = origCol+ if (gutter) gutter.style.cssText = origGutter+ }+ }, [])+}diff --git a/packages/registry/src/messaging/vendor/lib/client.ts b/packages/registry/src/messaging/vendor/lib/client.tsnew file mode 100644index 000000000..018fdf2a0--- /dev/null+++ b/packages/registry/src/messaging/vendor/lib/client.ts@@ -0,0 +1,12 @@+// DO NOT ADD THIS TO registry.json its only meant for internal use+import { createClient, InferClient } from "@mercurjs/client"+import { Routes } from '../../../../.mercur/_generated'++declare const __BACKEND_URL__: string++export const client: InferClient<Routes> = createClient({+ baseUrl: __BACKEND_URL__,+ fetchOptions: {+ credentials: 'include',+ },+})diff --git a/packages/registry/src/messaging/vendor/routes/messages/[id]/page.tsx b/packages/registry/src/messaging/vendor/routes/messages/[id]/page.tsxnew file mode 100644index 000000000..74bafde04--- /dev/null+++ b/packages/registry/src/messaging/vendor/routes/messages/[id]/page.tsx@@ -0,0 +1,288 @@+import { useEffect, useRef, useState } from "react"+import { useParams } from "react-router-dom"+import {+ Badge,+ Button,+ Container,+ Heading,+ Text,+ Textarea,+ clx,+} from "@medusajs/ui"+import {+ useVendorConversation,+ useMarkVendorRead,+ useSendVendorReply,+ MessageDTO,+} from "../../../hooks/api/messaging"+import { useMessagingSSE } from "../../../hooks/api/use-messaging-sse"+import { useMessagingLayout } from "../../../hooks/use-messaging-layout"++export const handle = {+ breadcrumb: () => "Conversation",+}++const formatTime = (dateStr: string): string => {+ const date = new Date(dateStr)+ const now = new Date()+ const isToday = date.toDateString() === now.toDateString()++ if (isToday) {+ return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })+ }++ const yesterday = new Date(now)+ yesterday.setDate(yesterday.getDate() - 1)+ if (date.toDateString() === yesterday.toDateString()) {+ return `Yesterday ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`+ }++ return `${date.toLocaleDateString([], { month: "short", day: "numeric" })} ${date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`+}++const ContextBadge = ({ message }: { message: MessageDTO }) => {+ if (!message.context_type) return null+ return (+ <Badge color="grey" size="2xsmall" className="mb-1">+ {message.context_label || `${message.context_type}: ${message.context_id}`}+ </Badge>+ )+}++const MessageBubble = ({ message }: { message: MessageDTO }) => {+ const isSeller = message.sender_type === "seller"+ return (+ <div+ className={clx(+ "flex flex-col gap-0.5",+ isSeller ? "items-end" : "items-start"+ )}+ >+ <ContextBadge message={message} />+ <div+ className={clx(+ "max-w-[70%] rounded-lg px-3 py-2",+ isSeller+ ? "bg-ui-bg-interactive text-ui-fg-on-color"+ : "bg-ui-bg-subtle text-ui-fg-base"+ )}+ >+ <Text size="small" leading="compact">+ {message.body}+ </Text>+ </div>+ <Text size="xsmall" className="text-ui-fg-muted px-1">+ {formatTime(message.created_at)}+ {isSeller && message.read_at && " · Read"}+ </Text>+ </div>+ )+}++const OrderSidebar = ({+ buyerName,+ orders,+ isBuyerBlocked,+}: {+ buyerName: string | null+ orders: any[]+ isBuyerBlocked?: boolean+}) => {+ return (+ <Container className="divide-y p-0">+ <div className="px-6 py-4">+ <Text size="small" leading="compact" weight="plus">+ Customer+ </Text>+ <div className="flex items-center gap-x-2 mt-1">+ <Text size="small" leading="compact" className="text-ui-fg-subtle">+ {buyerName || "Customer"}+ </Text>+ {isBuyerBlocked && (+ <Badge color="red" size="2xsmall">+ Blocked+ </Badge>+ )}+ </div>+ </div>+ {orders.length > 0 && (+ <div className="px-6 py-4">+ <Text size="small" leading="compact" weight="plus" className="mb-2">+ Recent Orders+ </Text>+ <div className="flex flex-col gap-2">+ {orders.slice(0, 5).map((order: any) => (+ <div+ key={order.id}+ className="flex items-center justify-between rounded border border-ui-border-base px-3 py-2"+ >+ <div>+ <Text size="small" leading="compact">+ #{order.display_id}+ </Text>+ <Text+ size="xsmall"+ className="text-ui-fg-muted"+ >+ {new Date(order.created_at).toLocaleDateString()}+ </Text>+ </div>+ <Badge color="grey" size="2xsmall">+ {order.status}+ </Badge>+ </div>+ ))}+ </div>+ </div>+ )}+ </Container>+ )+}++const VendorConversationDetailPage = () => {+ const { id } = useParams<{ id: string }>()+ useMessagingSSE(id)+ const [replyBody, setReplyBody] = useState("")+ const messagesContainerRef = useRef<HTMLDivElement>(null)+ const rootRef = useRef<HTMLDivElement>(null)++ const {+ conversation,+ messages,+ buyer_orders,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ isLoading,+ isError,+ error,+ } = useVendorConversation(id!)++ const markRead = useMarkVendorRead(id!)+ const sendReply = useSendVendorReply(id!)++ useMessagingLayout()++ // Mark messages as read on mount+ useEffect(() => {+ if (conversation && conversation.unread_count_seller > 0) {+ markRead.mutate()+ }+ }, [conversation?.id, conversation?.unread_count_seller])++ // Scroll to bottom when messages change+ useEffect(() => {+ const el = messagesContainerRef.current+ if (el) {+ el.scrollTop = el.scrollHeight+ }+ }, [messages?.length])++ if (isError) throw error++ const handleSend = () => {+ const trimmed = replyBody.trim()+ if (!trimmed || sendReply.isPending) return++ sendReply.mutate(+ { body: trimmed },+ { onSuccess: () => setReplyBody("") }+ )+ }++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault()+ handleSend()+ }+ }++ if (isLoading) {+ return (+ <div className="flex items-center justify-center py-12">+ <Text className="text-ui-fg-muted">Loading conversation...</Text>+ </div>+ )+ }++ // Messages come in desc order from API; reverse for display+ const displayMessages = [...(messages ?? [])].reverse()++ return (+ <div id="chat-root" ref={rootRef} className="flex gap-4 h-full min-h-0">+ {/* Main: Message Thread */}+ <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">+ <div id="chat-header" className="flex items-center justify-between px-6 py-4 border-b border-ui-border-base shrink-0">+ <Heading level="h2">+ {conversation?.buyer_first_name || "Customer"}+ </Heading>+ </div>++ {/* Messages list */}+ <div+ id="chat-messages"+ ref={messagesContainerRef}+ className="flex-1 flex flex-col gap-3 px-6 py-4 overflow-y-auto min-h-0"+ >+ {hasNextPage && (+ <div className="flex justify-center shrink-0">+ <Button+ size="small"+ variant="secondary"+ onClick={() => fetchNextPage()}+ disabled={isFetchingNextPage}+ isLoading={isFetchingNextPage}+ >+ Load older messages+ </Button>+ </div>+ )}+ {displayMessages.map((msg) => (+ <MessageBubble key={msg.id} message={msg} />+ ))}+ </div>++ {/* Compose area */}+ {conversation?.is_buyer_blocked ? (+ <div className="border-t border-ui-border-base px-6 py-4 shrink-0">+ <Text size="small" className="text-ui-fg-muted">+ This customer has been blocked from chat by an administrator.+ </Text>+ </div>+ ) : (+ <div id="chat-compose" className="border-t border-ui-border-base px-6 py-4 shrink-0">+ <div className="flex gap-2">+ <Textarea+ placeholder="Type your reply..."+ value={replyBody}+ onChange={(e) => setReplyBody(e.target.value)}+ onKeyDown={handleKeyDown}+ className="flex-1 resize-none"+ rows={2}+ />+ <Button+ size="small"+ onClick={handleSend}+ disabled={!replyBody.trim() || sendReply.isPending}+ isLoading={sendReply.isPending}+ >+ Send+ </Button>+ </div>+ </div>+ )}+ </div>++ {/* Sidebar: Customer + Orders */}+ <div id="chat-sidebar" className="w-[280px] shrink-0 overflow-y-auto">+ <OrderSidebar+ buyerName={conversation?.buyer_first_name ?? null}+ orders={buyer_orders ?? []}+ isBuyerBlocked={conversation?.is_buyer_blocked}+ />+ </div>+ </div>+ )+}++export default VendorConversationDetailPagediff --git a/packages/registry/src/messaging/vendor/routes/messages/page.tsx b/packages/registry/src/messaging/vendor/routes/messages/page.tsxnew file mode 100644index 000000000..de93a36cf--- /dev/null+++ b/packages/registry/src/messaging/vendor/routes/messages/page.tsx@@ -0,0 +1,135 @@+import { useNavigate } from "react-router-dom"+import { Badge, Container, Heading, Text, clx } from "@medusajs/ui"+import type { RouteConfig } from "@mercurjs/dashboard-sdk"++import { useVendorConversations, ConversationDTO } from "../../hooks/api/messaging"+import { useMessagingSSE } from "../../hooks/api/use-messaging-sse"+import { useMessagingLayout } from "../../hooks/use-messaging-layout"++export const config: RouteConfig = {+ label: "Messages",+}++export const handle = {+ breadcrumb: () => "Messages",+}++const formatRelativeTime = (dateStr: string | null): string => {+ if (!dateStr) return ""+ const date = new Date(dateStr)+ const now = new Date()+ const diffMs = now.getTime() - date.getTime()+ const diffMin = Math.floor(diffMs / 60000)+ if (diffMin < 1) return "Just now"+ if (diffMin < 60) return `${diffMin}m ago`+ const diffHours = Math.floor(diffMin / 60)+ if (diffHours < 24) return `${diffHours}h ago`+ const diffDays = Math.floor(diffHours / 24)+ if (diffDays < 7) return `${diffDays}d ago`+ return date.toLocaleDateString()+}++const ConversationRow = ({+ conversation,+ onClick,+}: {+ conversation: ConversationDTO+ onClick: () => void+}) => {+ const isUnread = conversation.unread_count_seller > 0+ const senderPrefix =+ conversation.last_message_sender_type === "seller" ? "You: " : ""++ return (+ <button+ onClick={onClick}+ className={clx(+ "flex w-full items-center gap-3 px-6 py-3 text-left transition-colors hover:bg-ui-bg-base-hover",+ isUnread && "bg-ui-bg-highlight"+ )}+ >+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-x-2">+ <Text+ size="small"+ leading="compact"+ weight={isUnread ? "plus" : "regular"}+ >+ {conversation.buyer_first_name || "Customer"}+ </Text>+ {conversation.is_buyer_blocked && (+ <Badge color="red" size="2xsmall">+ Blocked+ </Badge>+ )}+ </div>+ <Text size="xsmall" className="text-ui-fg-muted shrink-0">+ {formatRelativeTime(conversation.last_message_at)}+ </Text>+ </div>+ <div className="flex items-center justify-between gap-2">+ <Text+ size="small"+ leading="compact"+ className={clx(+ "truncate",+ isUnread ? "text-ui-fg-base" : "text-ui-fg-subtle"+ )}+ >+ {conversation.last_message_preview+ ? `${senderPrefix}${conversation.last_message_preview}`+ : "No messages yet"}+ </Text>+ {isUnread && (+ <Badge color="blue" size="2xsmall">+ {conversation.unread_count_seller}+ </Badge>+ )}+ </div>+ </div>+ </button>+ )+}++const VendorMessagesPage = () => {+ useMessagingSSE()+ const navigate = useNavigate()+ const { conversations, next_cursor, isLoading, isError, error } =+ useVendorConversations({ limit: 50 })++ useMessagingLayout()++ if (isError) throw error++ return (+ <div className="flex h-full flex-col">+ <Container className="flex h-full flex-col divide-y p-0">+ <div className="flex shrink-0 items-center justify-between px-6 py-4">+ <Heading>Messages</Heading>+ </div>+ {isLoading ? (+ <div className="flex flex-1 items-center justify-center px-6 py-12">+ <Text className="text-ui-fg-muted">Loading conversations...</Text>+ </div>+ ) : !conversations?.length ? (+ <div className="flex flex-1 items-center justify-center px-6 py-12">+ <Text className="text-ui-fg-muted">No conversations yet</Text>+ </div>+ ) : (+ <div className="flex-1 divide-y overflow-y-auto">+ {conversations.map((conv) => (+ <ConversationRow+ key={conv.id}+ conversation={conv}+ onClick={() => navigate(`/messages/${conv.id}`)}+ />+ ))}+ </div>+ )}+ </Container>+ </div>+ )+}++export default VendorMessagesPagediff --git a/packages/registry/src/messaging/workflows/messaging-filters/steps/create-filter-rule.ts b/packages/registry/src/messaging/workflows/messaging-filters/steps/create-filter-rule.tsnew file mode 100644index 000000000..e7a4e31a3--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/steps/create-filter-rule.ts@@ -0,0 +1,38 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_FILTERS_MODULE } from "../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../modules/messaging-filters/service"++type CreateFilterRuleInput = {+ match_type: "exact" | "contains"+ pattern: string+ description?: string | null+ is_enabled?: boolean+}++export const createFilterRuleStep = createStep(+ "create-filter-rule",+ async (input: CreateFilterRuleInput, { container }) => {+ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ const rule = await service.createFilterRules({+ match_type: input.match_type,+ pattern: input.pattern,+ description: input.description ?? null,+ is_enabled: input.is_enabled ?? true,+ is_builtin: false,+ })++ return new StepResponse(rule, rule.id)+ },+ async (ruleId, { container }) => {+ if (!ruleId) return++ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )+ await service.deleteFilterRules([ruleId])+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging-filters/steps/delete-filter-rule.ts b/packages/registry/src/messaging/workflows/messaging-filters/steps/delete-filter-rule.tsnew file mode 100644index 000000000..77bc1e1f2--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/steps/delete-filter-rule.ts@@ -0,0 +1,47 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_FILTERS_MODULE } from "../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../modules/messaging-filters/service"++type DeleteFilterRuleInput = {+ id: string+}++export const deleteFilterRuleStep = createStep(+ "delete-filter-rule",+ async (input: DeleteFilterRuleInput, { container }) => {+ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ const existing = await service.listFilterRules({ id: input.id })+ if (!existing || existing.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ `Filter rule ${input.id} not found`+ )+ }++ const current = existing[0]!++ if (current.is_builtin) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Built-in filter rules cannot be deleted"+ )+ }++ await service.deleteFilterRules([input.id])++ return new StepResponse(undefined, current)+ },+ async (previousData: any, { container }) => {+ if (!previousData) return++ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )+ await service.createFilterRules(previousData)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging-filters/steps/invalidate-filter-cache.ts b/packages/registry/src/messaging/workflows/messaging-filters/steps/invalidate-filter-cache.tsnew file mode 100644index 000000000..b5221c547--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/steps/invalidate-filter-cache.ts@@ -0,0 +1,23 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_REDIS_MODULE } from "../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../modules/messaging-redis/service"+import { invalidateRuleset, recompileFilters } from "../../../modules/messaging-filters/loaders/compile-filters"++export const invalidateFilterCacheStep = createStep(+ "invalidate-filter-cache",+ async (_input: undefined, { container }) => {+ // Recompile locally+ await recompileFilters(container)++ // Notify other instances via Redis pub/sub+ try {+ const redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)+ await redisService.publish("filter_rules_changed", { invalidated: true })+ } catch {+ // Best-effort cross-instance invalidation+ }++ return new StepResponse(undefined)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging-filters/steps/update-filter-rule.ts b/packages/registry/src/messaging/workflows/messaging-filters/steps/update-filter-rule.tsnew file mode 100644index 000000000..8ce3041ce--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/steps/update-filter-rule.ts@@ -0,0 +1,67 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_FILTERS_MODULE } from "../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../modules/messaging-filters/service"++type UpdateFilterRuleInput = {+ id: string+ match_type?: "exact" | "contains"+ pattern?: string+ description?: string | null+ is_enabled?: boolean+}++export const updateFilterRuleStep = createStep(+ "update-filter-rule",+ async (input: UpdateFilterRuleInput, { container }) => {+ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ // Retrieve current state for compensation+ const existing = await service.listFilterRules({ id: input.id })+ if (!existing || existing.length === 0) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ `Filter rule ${input.id} not found`+ )+ }++ const current = existing[0]!++ // Built-in rules: only allow is_enabled and description changes+ if (current.is_builtin) {+ if (input.match_type || input.pattern) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Built-in filter rules can only be enabled or disabled"+ )+ }+ }++ const updateData: Record<string, any> = { id: input.id }+ if (input.is_enabled !== undefined) updateData.is_enabled = input.is_enabled+ if (input.description !== undefined) updateData.description = input.description+ if (input.pattern !== undefined && !current.is_builtin) updateData.pattern = input.pattern+ if (input.match_type !== undefined && !current.is_builtin) updateData.match_type = input.match_type++ const updated = await service.updateFilterRules(updateData)++ return new StepResponse(updated, {+ id: input.id,+ is_enabled: current.is_enabled,+ description: current.description,+ pattern: current.pattern,+ match_type: current.match_type,+ })+ },+ async (previousData: any, { container }) => {+ if (!previousData) return++ const service = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )+ await service.updateFilterRules(previousData)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging-filters/workflows/create-filter-rule.ts b/packages/registry/src/messaging/workflows/messaging-filters/workflows/create-filter-rule.tsnew file mode 100644index 000000000..e5d694c82--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/workflows/create-filter-rule.ts@@ -0,0 +1,25 @@+import {+ createWorkflow,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { createFilterRuleStep } from "../steps/create-filter-rule"+import { invalidateFilterCacheStep } from "../steps/invalidate-filter-cache"++type CreateFilterRuleWorkflowInput = {+ match_type: "exact" | "contains"+ pattern: string+ description?: string | null+ is_enabled?: boolean+}++export const createFilterRuleWorkflow = createWorkflow(+ { name: "create-filter-rule" },+ function (input: CreateFilterRuleWorkflowInput) {+ const rule = createFilterRuleStep(input)++ invalidateFilterCacheStep()++ return new WorkflowResponse(rule)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging-filters/workflows/delete-filter-rule.ts b/packages/registry/src/messaging/workflows/messaging-filters/workflows/delete-filter-rule.tsnew file mode 100644index 000000000..20490af17--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/workflows/delete-filter-rule.ts@@ -0,0 +1,28 @@+import {+ createWorkflow,+ transform,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { deleteFilterRuleStep } from "../steps/delete-filter-rule"+import { invalidateFilterCacheStep } from "../steps/invalidate-filter-cache"++type DeleteFilterRuleWorkflowInput = {+ id: string+}++export const deleteFilterRuleWorkflow = createWorkflow(+ { name: "delete-filter-rule" },+ function (input: DeleteFilterRuleWorkflowInput) {+ deleteFilterRuleStep(input)++ invalidateFilterCacheStep()++ const result = transform(input, (data) => ({+ id: data.id,+ deleted: true,+ }))++ return new WorkflowResponse(result)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging-filters/workflows/update-filter-rule.ts b/packages/registry/src/messaging/workflows/messaging-filters/workflows/update-filter-rule.tsnew file mode 100644index 000000000..5d1441d5c--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging-filters/workflows/update-filter-rule.ts@@ -0,0 +1,26 @@+import {+ createWorkflow,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { updateFilterRuleStep } from "../steps/update-filter-rule"+import { invalidateFilterCacheStep } from "../steps/invalidate-filter-cache"++type UpdateFilterRuleWorkflowInput = {+ id: string+ match_type?: "exact" | "contains"+ pattern?: string+ description?: string | null+ is_enabled?: boolean+}++export const updateFilterRuleWorkflow = createWorkflow(+ { name: "update-filter-rule" },+ function (input: UpdateFilterRuleWorkflowInput) {+ const rule = updateFilterRuleStep(input)++ invalidateFilterCacheStep()++ return new WorkflowResponse(rule)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/anonymize-messages-batch.ts b/packages/registry/src/messaging/workflows/messaging/steps/anonymize-messages-batch.tsnew file mode 100644index 000000000..a538891d0--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/anonymize-messages-batch.ts@@ -0,0 +1,71 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"++type AnonymizeBatchInput = {+ conversation_ids: string[]+ actor_type: "customer" | "seller"+ batch_size?: number+}++export const anonymizeMessagesBatchStep = createStep(+ "anonymize-messages-batch",+ async (input: AnonymizeBatchInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const batchSize = input.batch_size ?? 500+ let totalAnonymized = 0++ for (const conversationId of input.conversation_ids) {+ let hasMore = true+ let skip = 0++ while (hasMore) {+ const messages = await service.listMessages(+ {+ conversation_id: conversationId,+ sender_type: input.actor_type,+ },+ { take: batchSize, skip }+ )++ if (!messages || messages.length === 0) {+ hasMore = false+ break+ }++ const messageIds = messages.map((m: { id: string }) => m.id)++ for (const msgId of messageIds) {+ await service.updateMessages({+ id: msgId,+ body: "[Message removed]",+ })+ }++ totalAnonymized += messageIds.length+ skip += batchSize++ if (messages.length < batchSize) {+ hasMore = false+ }+ }+ }++ return new StepResponse(+ { anonymized_count: totalAnonymized },+ { conversation_ids: input.conversation_ids, actor_type: input.actor_type, count: totalAnonymized }+ )+ },+ async (compensationData, { container }) => {+ if (!compensationData) return+ // Message body anonymization is irreversible — original content is lost.+ // Log for auditability so operators know a partial rollback occurred.+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)+ logger.warn(+ `Messaging: anonymize-messages-batch compensation triggered for ${compensationData.count} messages ` ++ `in conversations [${compensationData.conversation_ids.join(", ")}]. ` ++ `Message bodies cannot be restored — they were replaced with "[Message removed]".`+ )+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/block-customer.ts b/packages/registry/src/messaging/workflows/messaging/steps/block-customer.tsnew file mode 100644index 000000000..7d5ebd571--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/block-customer.ts@@ -0,0 +1,37 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { BlockCustomerInput } from "../../../modules/messaging/types/mutations"++export const blockCustomerStep = createStep(+ "block-customer",+ async (input: BlockCustomerInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const existing = await service.listChatBlocks(+ { customer_id: input.customer_id },+ { take: 1 }+ )++ if (existing.length > 0) {+ return new StepResponse(existing[0], null)+ }++ const [block] = await service.createChatBlocks([+ {+ customer_id: input.customer_id,+ blocked_by: input.blocked_by,+ reason: input.reason ?? null,+ },+ ])++ return new StepResponse(block, block.id)+ },+ async (blockId, { container }) => {+ if (!blockId) return++ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ await service.deleteChatBlocks([blockId])+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/create-conversation.ts b/packages/registry/src/messaging/workflows/messaging/steps/create-conversation.tsnew file mode 100644index 000000000..a9c91743e--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/create-conversation.ts@@ -0,0 +1,25 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { CreateConversationInput } from "../../../modules/messaging/types/mutations"++export const createConversationStep = createStep(+ "create-conversation",+ async (input: CreateConversationInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const conversation = await service.createConversations({+ buyer_id: input.buyer_id,+ seller_id: input.seller_id,+ })++ return new StepResponse(conversation, conversation.id)+ },+ async (conversationId, { container }) => {+ if (!conversationId) return++ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ await service.deleteConversations([conversationId])+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/create-message.ts b/packages/registry/src/messaging/workflows/messaging/steps/create-message.tsnew file mode 100644index 000000000..53ab574d7--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/create-message.ts@@ -0,0 +1,39 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { SendMessageInput } from "../../../modules/messaging/types/mutations"++function escapeHtml(str: string): string {+ return str+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'")+}++export const createMessageStep = createStep(+ "create-message",+ async (input: SendMessageInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const message = await service.createMessageAtomic({+ conversation_id: input.conversation_id,+ sender_id: input.sender_id,+ sender_type: input.sender_type,+ body: escapeHtml(input.body),+ context_type: input.context_type,+ context_id: input.context_id,+ context_label: input.context_label,+ })++ return new StepResponse(message, message.id)+ },+ async (messageId, { container }) => {+ if (!messageId) return++ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ await service.deleteMessages([messageId])+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/mark-messages-read.ts b/packages/registry/src/messaging/workflows/messaging/steps/mark-messages-read.tsnew file mode 100644index 000000000..1d60ed2d2--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/mark-messages-read.ts@@ -0,0 +1,19 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { MarkMessagesReadInput } from "../../../modules/messaging/types/mutations"++export const markMessagesReadStep = createStep(+ "mark-messages-read",+ async (input: MarkMessagesReadInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const updated = await service.markMessagesReadAtomic(+ input.conversation_id,+ input.reader_type+ )++ return new StepResponse({ conversation_id: input.conversation_id, updated })+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/publish-message-event.ts b/packages/registry/src/messaging/workflows/messaging/steps/publish-message-event.tsnew file mode 100644index 000000000..86063b26b--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/publish-message-event.ts@@ -0,0 +1,29 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_REDIS_MODULE } from "../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../modules/messaging-redis/service"+import { PublishMessageEventInput } from "../../../modules/messaging/types/mutations"++export const publishMessageEventStep = createStep(+ "publish-message-event",+ async (input: PublishMessageEventInput, { container }) => {+ try {+ const redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)++ await redisService.publish("messaging", {+ conversation_id: input.conversation_id,+ recipient_id: input.recipient_id,+ sender_type: input.sender_type,+ event_type: input.event_type,+ context_type: input.context_type ?? null,+ context_label: input.context_label ?? null,+ message_id: input.message_id ?? null,+ unread_count: input.unread_count ?? null,+ })+ } catch {+ // Redis publish is best-effort — client catches up via Last-Event-ID+ }++ return new StepResponse(undefined)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/unblock-customer.ts b/packages/registry/src/messaging/workflows/messaging/steps/unblock-customer.tsnew file mode 100644index 000000000..0caaa4449--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/unblock-customer.ts@@ -0,0 +1,36 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { UnblockCustomerInput } from "../../../modules/messaging/types/mutations"++export const unblockCustomerStep = createStep(+ "unblock-customer",+ async (input: UnblockCustomerInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const existing = await service.listChatBlocks(+ { customer_id: input.customer_id },+ { take: 1 }+ )++ if (existing.length === 0) {+ return new StepResponse(null, null)+ }++ await service.deleteChatBlocks([existing[0].id])+ return new StepResponse(null, existing[0])+ },+ async (deletedBlock: any, { container }) => {+ if (!deletedBlock) return++ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ await service.createChatBlocks([+ {+ customer_id: deletedBlock.customer_id,+ blocked_by: deletedBlock.blocked_by,+ reason: deletedBlock.reason,+ },+ ])+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/validate-chat-block.ts b/packages/registry/src/messaging/workflows/messaging/steps/validate-chat-block.tsnew file mode 100644index 000000000..02f014667--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/validate-chat-block.ts@@ -0,0 +1,38 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"++type ValidateChatBlockInput = {+ sender_id: string+ sender_type: "customer" | "seller"+ recipient_id: string+}++export const validateChatBlockStep = createStep(+ "validate-chat-block",+ async (input: ValidateChatBlockInput, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ const customerId =+ input.sender_type === "customer" ? input.sender_id : input.recipient_id+ const blocked = await service.checkBuyersBlocked([customerId])++ if (blocked.has(customerId)) {+ if (input.sender_type === "customer") {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Your chat access has been suspended"+ )+ } else {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "Cannot send messages to a blocked customer"+ )+ }+ }++ return new StepResponse(undefined)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/validate-content-filter.ts b/packages/registry/src/messaging/workflows/messaging/steps/validate-content-filter.tsnew file mode 100644index 000000000..87bc3a250--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/validate-content-filter.ts@@ -0,0 +1,52 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_FILTERS_MODULE } from "../../../modules/messaging-filters"+import type MessagingFiltersModuleService from "../../../modules/messaging-filters/service"+import { getCompiledRuleset, recompileFilters, isRulesetEmpty } from "../../../modules/messaging-filters/loaders/compile-filters"++type ValidateContentFilterInput = {+ body: string+ sender_id: string+ sender_type: "customer" | "seller"+ conversation_id: string+}++export const validateContentFilterStep = createStep(+ "validate-content-filter",+ async (input: ValidateContentFilterInput, { container }) => {+ const filtersService = container.resolve<MessagingFiltersModuleService>(+ MESSAGING_FILTERS_MODULE+ )++ // Lazy-compile rules if ruleset is empty (first message or after invalidation)+ if (isRulesetEmpty()) {+ try {+ await recompileFilters(container)+ } catch {+ // Continue with empty ruleset+ }+ }++ const ruleset = getCompiledRuleset()+ const result = filtersService.evaluateMessage(input.body, ruleset)++ if (result.matched) {+ // Log the blocked message+ await filtersService.createBlockedMessageLogs({+ sender_id: input.sender_id,+ sender_type: input.sender_type,+ conversation_id: input.conversation_id,+ matched_rule_id: result.rule_id!,+ message_body: input.body,+ })++ throw new MedusaError(+ MedusaError.Types.INVALID_DATA,+ "Your message could not be sent. Please revise and try again."+ )+ }++ return new StepResponse(undefined)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/steps/validate-rate-limit.ts b/packages/registry/src/messaging/workflows/messaging/steps/validate-rate-limit.tsnew file mode 100644index 000000000..f32453668--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/steps/validate-rate-limit.ts@@ -0,0 +1,70 @@+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"+import { MedusaError } from "@medusajs/framework/utils"++import { MESSAGING_REDIS_MODULE } from "../../../modules/messaging-redis"+import type MessagingRedisModuleService from "../../../modules/messaging-redis/service"+import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"++type ValidateRateLimitInput = {+ sender_id: string+ is_new_conversation: boolean+}++export const validateRateLimitStep = createStep(+ "validate-rate-limit",+ async (input: ValidateRateLimitInput, { container }) => {+ let redisService: MessagingRedisModuleService++ try {+ redisService = container.resolve<MessagingRedisModuleService>(MESSAGING_REDIS_MODULE)+ } catch {+ // Module not registered — skip rate limiting gracefully+ return new StepResponse(undefined)+ }++ if (!redisService.isAvailable) {+ return new StepResponse(undefined)+ }++ const messagingService = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ const rateLimits = messagingService.getOptions().rateLimits++ try {+ const msgResult = await redisService.checkRateLimit(+ `ratelimit:msg:${input.sender_id}`,+ rateLimits.messagesPerMinute,+ 60+ )++ if (!msgResult.allowed) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "You are sending messages too quickly. Please wait a moment and try again."+ )+ }++ if (input.is_new_conversation) {+ const convResult = await redisService.checkRateLimit(+ `ratelimit:conv:${input.sender_id}`,+ rateLimits.conversationsPerHour,+ 3600+ )++ if (!convResult.allowed) {+ throw new MedusaError(+ MedusaError.Types.NOT_ALLOWED,+ "You are sending messages too quickly. Please wait a moment and try again."+ )+ }+ }+ } catch (err) {+ if (err instanceof MedusaError) {+ throw err+ }+ // Redis operation failed — skip rate limiting gracefully+ }++ return new StepResponse(undefined)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/anonymize-buyer-messages.ts b/packages/registry/src/messaging/workflows/messaging/workflows/anonymize-buyer-messages.tsnew file mode 100644index 000000000..ca9dba5cf--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/anonymize-buyer-messages.ts@@ -0,0 +1,87 @@+import {+ createWorkflow,+ transform,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"+import { anonymizeMessagesBatchStep } from "../steps/anonymize-messages-batch"++type AnonymizeBuyerInput = {+ buyer_id: string+}++const BATCH_SIZE = 100++const findBuyerConversationsStep = createStep(+ "find-buyer-conversations",+ async (input: { buyer_id: string }, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ // Paginate to avoid unbounded queries+ const allIds: string[] = []+ let skip = 0++ while (true) {+ const conversations = await service.listConversations(+ { buyer_id: input.buyer_id },+ { take: BATCH_SIZE, skip, select: ["id"] }+ )++ if (!conversations || conversations.length === 0) break++ const ids = conversations.map((c: { id: string }) => c.id)+ allIds.push(...ids)+ skip += BATCH_SIZE++ if (conversations.length < BATCH_SIZE) break+ }++ // Update all conversations to reflect deleted buyer+ for (const id of allIds) {+ await service.updateConversations({+ id,+ buyer_id: `deleted_${input.buyer_id}`,+ })+ }++ return new StepResponse(+ { conversation_ids: allIds },+ { conversation_ids: allIds, original_buyer_id: input.buyer_id }+ )+ },+ async (compensationData, { container }) => {+ if (!compensationData) return+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ // Restore original buyer_id on rollback+ for (const id of compensationData.conversation_ids) {+ await service.updateConversations({+ id,+ buyer_id: compensationData.original_buyer_id,+ })+ }+ }+)++export const anonymizeBuyerMessagesWorkflow = createWorkflow(+ { name: "anonymize-buyer-messages" },+ function (input: AnonymizeBuyerInput) {+ const findInput = transform(input, (data) => ({+ buyer_id: data.buyer_id,+ }))++ const result = findBuyerConversationsStep(findInput)++ const batchInput = transform(result, (data) => ({+ conversation_ids: data.conversation_ids,+ actor_type: "customer" as const,+ batch_size: 500,+ }))++ const anonymizeResult = anonymizeMessagesBatchStep(batchInput)++ return new WorkflowResponse(anonymizeResult)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/anonymize-vendor-messages.ts b/packages/registry/src/messaging/workflows/messaging/workflows/anonymize-vendor-messages.tsnew file mode 100644index 000000000..de2104637--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/anonymize-vendor-messages.ts@@ -0,0 +1,79 @@+import {+ createWorkflow,+ transform,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { MESSAGING_MODULE } from "../../../modules/messaging"+import type MessagingModuleService from "../../../modules/messaging/service"++type AnonymizeVendorInput = {+ seller_id: string+}++const BATCH_SIZE = 100++const anonymizeVendorConversationsStep = createStep(+ "anonymize-vendor-conversations",+ async (input: { seller_id: string }, { container }) => {+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)++ // Paginate to avoid unbounded queries+ const allIds: string[] = []+ let skip = 0++ while (true) {+ const conversations = await service.listConversations(+ { seller_id: input.seller_id },+ { take: BATCH_SIZE, skip, select: ["id"] }+ )++ if (!conversations || conversations.length === 0) break++ const ids = conversations.map((c: { id: string }) => c.id)+ allIds.push(...ids)+ skip += BATCH_SIZE++ if (conversations.length < BATCH_SIZE) break+ }++ // Mark conversations as having a deleted vendor+ // Vendor message bodies are preserved per spec (FR-006)+ for (const id of allIds) {+ await service.updateConversations({+ id,+ seller_id: `deleted_${input.seller_id}`,+ })+ }++ return new StepResponse(+ { conversation_ids: allIds, anonymized_count: allIds.length },+ { conversation_ids: allIds, original_seller_id: input.seller_id }+ )+ },+ async (compensationData, { container }) => {+ if (!compensationData) return+ const service = container.resolve<MessagingModuleService>(MESSAGING_MODULE)+ // Restore original seller_id on rollback+ for (const id of compensationData.conversation_ids) {+ await service.updateConversations({+ id,+ seller_id: compensationData.original_seller_id,+ })+ }+ }+)++export const anonymizeVendorMessagesWorkflow = createWorkflow(+ { name: "anonymize-vendor-messages" },+ function (input: AnonymizeVendorInput) {+ const stepInput = transform(input, (data) => ({+ seller_id: data.seller_id,+ }))++ const result = anonymizeVendorConversationsStep(stepInput)++ return new WorkflowResponse(result)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/block-customer.ts b/packages/registry/src/messaging/workflows/messaging/workflows/block-customer.tsnew file mode 100644index 000000000..5ca1eb708--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/block-customer.ts@@ -0,0 +1,15 @@+import {+ createWorkflow,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { blockCustomerStep } from "../steps/block-customer"+import { BlockCustomerInput } from "../../../modules/messaging/types/mutations"++export const blockCustomerWorkflow = createWorkflow(+ { name: "block-customer" },+ function (input: BlockCustomerInput) {+ const block = blockCustomerStep(input)+ return new WorkflowResponse(block)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/create-conversation.ts b/packages/registry/src/messaging/workflows/messaging/workflows/create-conversation.tsnew file mode 100644index 000000000..9de3e2ee0--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/create-conversation.ts@@ -0,0 +1,34 @@+import {+ createWorkflow,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"+import { Modules } from "@medusajs/framework/utils"++import { createConversationStep } from "../steps/create-conversation"+import { MESSAGING_MODULE } from "../../../modules/messaging"++type CreateConversationWorkflowInput = {+ buyer_id: string+ seller_id: string+}++export const createConversationWorkflow = createWorkflow(+ { name: "create-conversation" },+ function (input: CreateConversationWorkflowInput) {+ const conversation = createConversationStep(input)++ createRemoteLinkStep([+ {+ [Modules.CUSTOMER]: { customer_id: input.buyer_id },+ [MESSAGING_MODULE]: { conversation_id: conversation.id },+ },+ {+ "seller": { seller_id: input.seller_id },+ [MESSAGING_MODULE]: { conversation_id: conversation.id },+ },+ ] as any)++ return new WorkflowResponse(conversation)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/mark-messages-read.ts b/packages/registry/src/messaging/workflows/messaging/workflows/mark-messages-read.tsnew file mode 100644index 000000000..154776fd6--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/mark-messages-read.ts@@ -0,0 +1,41 @@+import {+ createWorkflow,+ transform,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { markMessagesReadStep } from "../steps/mark-messages-read"+import { publishMessageEventStep } from "../steps/publish-message-event"+import { MarkMessagesReadInput } from "../../../modules/messaging/types/mutations"++type MarkMessagesReadWorkflowInput = MarkMessagesReadInput & {+ sender_id: string+}++export const markMessagesReadWorkflow = createWorkflow(+ { name: "mark-messages-read" },+ function (input: MarkMessagesReadWorkflowInput) {+ const result = markMessagesReadStep(input)++ const readEventInput = transform({ input }, ({ input }) => ({+ conversation_id: input.conversation_id,+ recipient_id: input.sender_id,+ sender_type: input.reader_type,+ event_type: "messages_read" as const,+ }))++ publishMessageEventStep(readEventInput)++ const unreadEventInput = transform({ input }, ({ input }) => ({+ conversation_id: input.conversation_id,+ recipient_id: input.reader_id,+ sender_type: input.reader_type,+ event_type: "unread_count" as const,+ unread_count: 0,+ }))++ ;(publishMessageEventStep(unreadEventInput) as any).config({ name: "publish-unread-count" })++ return new WorkflowResponse(result)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/send-message.ts b/packages/registry/src/messaging/workflows/messaging/workflows/send-message.tsnew file mode 100644index 000000000..6dd874724--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/send-message.ts@@ -0,0 +1,86 @@+import {+ createWorkflow,+ transform,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"+import { emitEventStep } from "@medusajs/medusa/core-flows"++import { validateChatBlockStep } from "../steps/validate-chat-block"+import { validateRateLimitStep } from "../steps/validate-rate-limit"+import { validateContentFilterStep } from "../steps/validate-content-filter"+import { createMessageStep } from "../steps/create-message"+import { publishMessageEventStep } from "../steps/publish-message-event"+import { SendMessageInput } from "../../../modules/messaging/types/mutations"++type SendMessageWorkflowInput = SendMessageInput & {+ recipient_id: string+ is_new_conversation: boolean+}++export const sendMessageWorkflow = createWorkflow(+ { name: "send-message" },+ function (input: SendMessageWorkflowInput) {+ const blockCheckInput = transform(input, (data) => ({+ sender_id: data.sender_id,+ sender_type: data.sender_type,+ recipient_id: data.recipient_id,+ }))++ validateChatBlockStep(blockCheckInput)++ const rateLimitInput = transform(input, (data) => ({+ sender_id: data.sender_id,+ is_new_conversation: data.is_new_conversation,+ }))++ validateRateLimitStep(rateLimitInput)++ const filterInput = transform(input, (data) => ({+ body: data.body,+ sender_id: data.sender_id,+ sender_type: data.sender_type,+ conversation_id: data.conversation_id,+ }))++ validateContentFilterStep(filterInput)++ const messageInput = transform(input, (data) => ({+ conversation_id: data.conversation_id,+ sender_id: data.sender_id,+ sender_type: data.sender_type,+ body: data.body,+ context_type: data.context_type,+ context_id: data.context_id,+ context_label: data.context_label,+ }))++ const message = createMessageStep(messageInput)++ const publishInput = transform({ input, message }, ({ input, message }) => ({+ conversation_id: input.conversation_id,+ recipient_id: input.recipient_id,+ sender_type: input.sender_type,+ event_type: "new_message" as const,+ context_type: input.context_type,+ context_label: input.context_label,+ message_id: message.id,+ }))++ publishMessageEventStep(publishInput)++ const eventData = transform({ input, message }, ({ input, message }) => ({+ eventName: "messaging.message.created",+ data: {+ id: message.id,+ conversation_id: input.conversation_id,+ sender_id: input.sender_id,+ sender_type: input.sender_type,+ recipient_id: input.recipient_id,+ },+ }))++ emitEventStep(eventData)++ return new WorkflowResponse(message)+ }+)diff --git a/packages/registry/src/messaging/workflows/messaging/workflows/unblock-customer.ts b/packages/registry/src/messaging/workflows/messaging/workflows/unblock-customer.tsnew file mode 100644index 000000000..cb4bdf7d8--- /dev/null+++ b/packages/registry/src/messaging/workflows/messaging/workflows/unblock-customer.ts@@ -0,0 +1,15 @@+import {+ createWorkflow,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"++import { unblockCustomerStep } from "../steps/unblock-customer"+import { UnblockCustomerInput } from "../../../modules/messaging/types/mutations"++export const unblockCustomerWorkflow = createWorkflow(+ { name: "unblock-customer" },+ function (input: UnblockCustomerInput) {+ const result = unblockCustomerStep(input)+ return new WorkflowResponse(result)+ }+)