Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

chore(core)!: remove the search module and store search endpoint (#1220)

Viktor Holik7c77d6beffba
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index a541e2686..544f1ed9a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -28,7 +28,7 @@ The repository is a Turborepo monorepo managed with Bun. It contains the framewo
+-----------------------------------------------------------------+
| @mercurjs/core (Medusa plugin) |
| modules: seller, commission, offer, payout, order-group, |
-| product-attribute, product-edit, media, search, |
+| product-attribute, product-edit, media, |
| shipping-profile, price-list, promotion, ... |
| workflows: seller lifecycle, payouts, commissions, |
| order-group split, cart, fulfilment, ... |
@@ -58,7 +58,7 @@ Dashboards (separate Vite apps that talk to the API above):
### `packages/core` — marketplace plugin
The Medusa plugin that holds all marketplace business logic. Wired into the API via `withMercur()` in `apps/api/medusa-config.ts`.
-- **Modules** (`src/modules/`): `seller` (registration, profiles, members, order groups), `commission` (rates, rules, calculation), `offer` (seller listings against master products), `payout` (accounts, onboarding, payouts), `product-attribute` (typed attribute catalog), `product-edit` (product change-request pipeline), `order-group`, `media`, `search`, `custom-fields`, `inventory-item`, `stock-location`, `shipping-profile`, `shipping-option`, `price-list`, `promotion`, `campaign`.
+- **Modules** (`src/modules/`): `seller` (registration, profiles, members, order groups), `commission` (rates, rules, calculation), `offer` (seller listings against master products), `payout` (accounts, onboarding, payouts), `product-attribute` (typed attribute catalog), `product-edit` (product change-request pipeline), `order-group`, `media`, `custom-fields`, `inventory-item`, `stock-location`, `shipping-profile`, `shipping-option`, `price-list`, `promotion`, `campaign`.
- **Workflows** (`src/workflows/`): 22+ workflow groups for seller lifecycle (create / approve / suspend), member invites, commissions, payouts, multi-vendor cart and order split, offers, product change-requests, fulfilment. Workflows support compensation (automatic rollback on failure) and expose hooks as extension points; steps return `StepResponse` and compose into a `WorkflowResponse`.
- **Modules never reference each other directly** — cross-module communication happens only through **links** and **workflows**. Links are relationships defined separately (e.g. `product-seller-link`, `offer-product-link`, `offer-variant-link`, `order-group-order-link`); dozens of them wire the marketplace layer into the commerce layer.
- **Scheduled jobs + subscribers**: jobs run on intervals (e.g. payout capture-check every 15 min, daily payouts at 1 AM UTC) and emit events; subscribers listen and fire async side effects (notifications, webhook calls, payout transfers).
diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md
index 7b22d88e3..57051fbba 100644
--- a/docs/PRODUCT.md
+++ b/docs/PRODUCT.md
@@ -158,7 +158,7 @@ The product has three audiences:
| Mercur Core Plugin (@mercurjs/core) |
| Modules: Seller · Commission · Offer · Payout · |
| Product Attribute · Product Edit (change pipeline) · |
-| Order Group · Media · Search · Custom Fields · |
+| Order Group · Media · Custom Fields · |
| Admin UI · Vendor UI · Codegen |
+---------------------------------------------------------------+
| Medusa Framework (core commerce) |
diff --git a/integration-tests/http/search/store/search-sync.spec.ts b/integration-tests/http/search/store/search-sync.spec.ts
deleted file mode 100644
index 5af0dce43..000000000
--- a/integration-tests/http/search/store/search-sync.spec.ts
+++ /dev/null
@@ -1,262 +0,0 @@
-import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
-import {
- IRegionModuleService,
- ISalesChannelModuleService,
- MedusaContainer,
-} from "@medusajs/framework/types"
-import {
- ContainerRegistrationKeys,
- Modules,
-} from "@medusajs/framework/utils"
-import { MercurModules, SellerStatus } from "@mercurjs/types"
-import {
- offersForSeller,
- reindexProductsById,
- removeOfferDocs,
- removeProductAndOffers,
-} from "@mercurjs/core/modules/search"
-
-import { createSellerUser } from "../../../helpers/create-seller-user"
-import { createVendorProduct } from "../../../helpers/create-product"
-import {
- generatePublishableKey,
- generateStoreHeaders,
-} from "../../../helpers/create-admin-user"
-
-const setSellerStatus = async (
- container: MedusaContainer,
- sellerId: string,
- status: SellerStatus
-) => {
- const sellerModule = container.resolve(MercurModules.SELLER)
- await (
- sellerModule as { updateSellers: (input: unknown) => Promise<unknown> }
- ).updateSellers({ id: sellerId, status })
-}
-
-jest.setTimeout(120000)
-
-medusaIntegrationTestRunner({
- testSuite: ({ getContainer, api }) => {
- describe("Store - Search incremental sync", () => {
- let appContainer: MedusaContainer
- let storeHeaders: ReturnType<typeof generateStoreHeaders>
- let region: { id: string }
- let salesChannel: { id: string }
- let seedCounter = 0
-
- const seedSellerOffer = async (opts: {
- email: string
- name: string
- offerPrice: number
- approve?: boolean
- published?: boolean
- }) => {
- const tag = `s${++seedCounter}${Date.now()}`
- const result = await createSellerUser(appContainer, {
- email: opts.email,
- name: opts.name,
- })
- if (opts.approve !== false) {
- await setSellerStatus(appContainer, result.seller.id, SellerStatus.OPEN)
- }
- const headers = result.headers
-
- const stockLocation = (
- await api.post(
- `/vendor/stock-locations`,
- { name: `${opts.name} WH ${tag}` },
- headers
- )
- ).data.stock_location
-
- await api.post(
- `/vendor/stock-locations/${stockLocation.id}/sales-channels`,
- { add: [salesChannel.id] },
- headers
- )
-
- const product = await createVendorProduct(api, headers, {
- status: opts.published === false ? "draft" : "published",
- title: `${opts.name} Product ${tag}`,
- sku: `${opts.email}-V-SKU-${tag}`,
- })
-
- await api.post(
- `/vendor/sales-channels/${salesChannel.id}/products`,
- { add: [product.id] },
- headers
- )
-
- const shippingProfile = (
- await api.post(
- `/vendor/shipping-profiles`,
- { name: `${opts.name} Profile ${tag}`, type: "default" },
- headers
- )
- ).data.shipping_profile
-
- const offer = (
- await api.post(
- `/vendor/offers`,
- {
- sku: `${opts.name.replace(/\s/g, "")}-OFFER-${tag}`,
- variant_id: product.variants[0].id,
- shipping_profile_id: shippingProfile.id,
- inventory_items: [
- {
- title: `${opts.name} Inv ${tag}`,
- required_quantity: 1,
- stock_levels: [
- { location_id: stockLocation.id, stocked_quantity: 10 },
- ],
- },
- ],
- prices: [{ amount: opts.offerPrice, currency_code: "usd" }],
- },
- headers
- )
- ).data.offer
-
- return {
- headers,
- sellerId: result.seller.id as string,
- productId: product.id as string,
- offer,
- }
- }
-
- const searchHits = async (q: string) => {
- const response = await api.post(
- `/store/search`,
- { q, region_id: region.id },
- storeHeaders
- )
- expect(response.status).toEqual(200)
- return response.data.hits as {
- type: string
- id: string
- calculated_price?: { calculated_amount: number }
- }[]
- }
-
- beforeAll(async () => {
- appContainer = getContainer()
- })
-
- beforeEach(async () => {
- const salesChannelModule =
- appContainer.resolve<ISalesChannelModuleService>(
- Modules.SALES_CHANNEL
- )
- salesChannel = await salesChannelModule.createSalesChannels({
- name: "Default Store",
- })
-
- const regionModule = appContainer.resolve<IRegionModuleService>(
- Modules.REGION
- )
- region = await regionModule.createRegions({
- name: "Test Region",
- currency_code: "usd",
- countries: ["us"],
- })
-
- const apiKey = await generatePublishableKey(appContainer)
- storeHeaders = generateStoreHeaders({ publishableKey: apiKey })
-
- const link = appContainer.resolve(ContainerRegistrationKeys.LINK)
- await link.create({
- [Modules.API_KEY]: { publishable_key_id: apiKey.id },
- [Modules.SALES_CHANNEL]: { sales_channel_id: salesChannel.id },
- })
- })
-
- it("reindexProductsById indexes a published product and its offer", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "SyncIndex",
- offerPrice: 2500,
- })
-
- await reindexProductsById(appContainer, [seed.productId])
-
- const hits = await searchHits("SyncIndex")
- const productHit = hits.find(
- (h) => h.type === "product" && h.id === seed.productId
- )
- const offerHit = hits.find(
- (h) => h.type === "offer" && h.id === seed.offer.id
- )
- expect(productHit?.calculated_price?.calculated_amount).toEqual(2500)
- expect(offerHit?.calculated_price?.calculated_amount).toEqual(2500)
- })
-
- it("removeProductAndOffers drops the product and its offer docs", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "SyncDelete",
- offerPrice: 1800,
- })
- await reindexProductsById(appContainer, [seed.productId])
-
- await removeProductAndOffers(appContainer, [seed.productId])
-
- const hits = await searchHits("SyncDelete")
- expect(hits.find((h) => h.id === seed.productId)).toBeFalsy()
- expect(hits.find((h) => h.id === seed.offer.id)).toBeFalsy()
- })
-
- it("suspending a seller drops its offer doc but keeps the product", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "SyncSuspend",
- offerPrice: 3000,
- })
- await reindexProductsById(appContainer, [seed.productId])
-
- await setSellerStatus(appContainer, seed.sellerId, SellerStatus.SUSPENDED)
-
- const { offerIds, productIds } = await offersForSeller(
- appContainer,
- seed.sellerId
- )
- await removeOfferDocs(appContainer, offerIds)
- await reindexProductsById(appContainer, productIds)
-
- const hits = await searchHits("SyncSuspend")
- expect(
- hits.find((h) => h.type === "offer" && h.id === seed.offer.id)
- ).toBeFalsy()
- expect(
- hits.find((h) => h.type === "product" && h.id === seed.productId)
- ).toBeTruthy()
- })
-
- it("deleting an offer removes its doc and recomputes the product", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "SyncOfferDelete",
- offerPrice: 2100,
- })
- await reindexProductsById(appContainer, [seed.productId])
-
- const offerModule = appContainer.resolve(MercurModules.OFFER)
- await (
- offerModule as { deleteOffers: (ids: string[]) => Promise<unknown> }
- ).deleteOffers([seed.offer.id])
-
- await removeOfferDocs(appContainer, [seed.offer.id])
- await reindexProductsById(appContainer, [seed.productId])
-
- const hits = await searchHits("SyncOfferDelete")
- expect(
- hits.find((h) => h.type === "offer" && h.id === seed.offer.id)
- ).toBeFalsy()
- expect(
- hits.find((h) => h.type === "product" && h.id === seed.productId)
- ).toBeTruthy()
- })
- })
- },
-})
diff --git a/integration-tests/http/search/store/search.spec.ts b/integration-tests/http/search/store/search.spec.ts
deleted file mode 100644
index f3bcb616e..000000000
--- a/integration-tests/http/search/store/search.spec.ts
+++ /dev/null
@@ -1,299 +0,0 @@
-import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
-import {
- IRegionModuleService,
- ISalesChannelModuleService,
- MedusaContainer,
-} from "@medusajs/framework/types"
-import {
- ContainerRegistrationKeys,
- Modules,
-} from "@medusajs/framework/utils"
-import { MercurModules, SellerStatus } from "@mercurjs/types"
-import {
- reindexAll,
- SearchModuleService,
-} from "@mercurjs/core/modules/search"
-
-import { createSellerUser } from "../../../helpers/create-seller-user"
-import { createVendorProduct } from "../../../helpers/create-product"
-import {
- generatePublishableKey,
- generateStoreHeaders,
-} from "../../../helpers/create-admin-user"
-
-const approveSeller = async (container: MedusaContainer, sellerId: string) => {
- const sellerModule = container.resolve(MercurModules.SELLER)
- await (sellerModule as { updateSellers: (input: unknown) => Promise<unknown> }).updateSellers(
- {
- id: sellerId,
- status: SellerStatus.OPEN,
- }
- )
-}
-
-jest.setTimeout(120000)
-
-medusaIntegrationTestRunner({
- testSuite: ({ getContainer, api }) => {
- describe("Store - Search (search-orama)", () => {
- let appContainer: MedusaContainer
- let storeHeaders: ReturnType<typeof generateStoreHeaders>
- let region: { id: string }
- let salesChannel: { id: string }
- let seedCounter = 0
-
- const seedSellerOffer = async (opts: {
- email: string
- name: string
- offerPrice: number
- approve?: boolean
- published?: boolean
- }) => {
- const tag = `s${++seedCounter}${Date.now()}`
- const result = await createSellerUser(appContainer, {
- email: opts.email,
- name: opts.name,
- })
- if (opts.approve !== false) {
- await approveSeller(appContainer, result.seller.id)
- }
- const headers = result.headers
-
- const stockLocation = (
- await api.post(
- `/vendor/stock-locations`,
- { name: `${opts.name} WH ${tag}` },
- headers
- )
- ).data.stock_location
-
- await api.post(
- `/vendor/stock-locations/${stockLocation.id}/sales-channels`,
- { add: [salesChannel.id] },
- headers
- )
-
- const product = await createVendorProduct(api, headers, {
- status: opts.published === false ? "draft" : "published",
- title: `${opts.name} Product ${tag}`,
- sku: `${opts.email}-V-SKU-${tag}`,
- })
-
- await api.post(
- `/vendor/sales-channels/${salesChannel.id}/products`,
- { add: [product.id] },
- headers
- )
-
- const shippingProfile = (
- await api.post(
- `/vendor/shipping-profiles`,
- { name: `${opts.name} Profile ${tag}`, type: "default" },
- headers
- )
- ).data.shipping_profile
-
- const offer = (
- await api.post(
- `/vendor/offers`,
- {
- sku: `${opts.name.replace(/\s/g, "")}-OFFER-${tag}`,
- variant_id: product.variants[0].id,
- shipping_profile_id: shippingProfile.id,
- inventory_items: [
- {
- title: `${opts.name} Inv ${tag}`,
- required_quantity: 1,
- stock_levels: [
- { location_id: stockLocation.id, stocked_quantity: 10 },
- ],
- },
- ],
- prices: [{ amount: opts.offerPrice, currency_code: "usd" }],
- },
- headers
- )
- ).data.offer
-
- return {
- headers,
- sellerId: result.seller.id as string,
- productId: product.id as string,
- title: product.title as string,
- offer,
- }
- }
-
- const reindex = async () => {
- // Synchronous full reindex via `reindexAll` (calls `search.index`
- // directly) — awaited, so tests never race the async boot path.
- await reindexAll(appContainer)
- }
-
- beforeAll(async () => {
- appContainer = getContainer()
- })
-
- beforeEach(async () => {
- const salesChannelModule =
- appContainer.resolve<ISalesChannelModuleService>(
- Modules.SALES_CHANNEL
- )
- salesChannel = await salesChannelModule.createSalesChannels({
- name: "Default Store",
- })
-
- const regionModule = appContainer.resolve<IRegionModuleService>(
- Modules.REGION
- )
- region = await regionModule.createRegions({
- name: "Test Region",
- currency_code: "usd",
- countries: ["us"],
- })
-
- const apiKey = await generatePublishableKey(appContainer)
- storeHeaders = generateStoreHeaders({ publishableKey: apiKey })
-
- const link = appContainer.resolve(ContainerRegistrationKeys.LINK)
- await link.create({
- [Modules.API_KEY]: { publishable_key_id: apiKey.id },
- [Modules.SALES_CHANNEL]: { sales_channel_id: salesChannel.id },
- })
- })
-
- describe("POST /store/search", () => {
- it("returns a published product and its offer after reindex, priced per region", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "Searchable",
- offerPrice: 2500,
- })
-
- await reindex()
-
- const response = await api.post(
- `/store/search`,
- {
- q: "Searchable",
- region_id: region.id,
- },
- storeHeaders
- )
-
- expect(response.status).toEqual(200)
-
- const productHit = response.data.hits.find(
- (h: { type: string; id: string }) =>
- h.type === "product" && h.id === seed.productId
- )
- expect(productHit).toBeTruthy()
- expect(productHit.calculated_price?.calculated_amount).toEqual(2500)
-
- const offerHit = response.data.hits.find(
- (h: { type: string; id: string }) =>
- h.type === "offer" && h.id === seed.offer.id
- )
- expect(offerHit).toBeTruthy()
- expect(offerHit.calculated_price?.calculated_amount).toEqual(2500)
- })
-
- it("indexes when passed an explicit search service", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "Explicit",
- offerPrice: 4200,
- })
-
- const search = appContainer.resolve<SearchModuleService>(
- MercurModules.SEARCH
- )
- await reindexAll(appContainer, search)
-
- const response = await api.post(
- `/store/search`,
- { q: "Explicit", region_id: region.id },
- storeHeaders
- )
-
- expect(response.status).toEqual(200)
-
- const productHit = response.data.hits.find(
- (h: { type: string; id: string }) =>
- h.type === "product" && h.id === seed.productId
- )
- expect(productHit).toBeTruthy()
-
- const offerHit = response.data.hits.find(
- (h: { type: string; id: string }) =>
- h.type === "offer" && h.id === seed.offer.id
- )
- expect(offerHit).toBeTruthy()
- })
-
- it("omits draft products from results", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "Hidden",
- offerPrice: 1500,
- published: false,
- })
-
- await reindex()
-
- const response = await api.post(
- `/store/search`,
- { q: "Hidden", region_id: region.id },
- storeHeaders
- )
-
- expect(response.status).toEqual(200)
- const hit = response.data.hits.find(
- (h: { id: string }) => h.id === seed.productId
- )
- expect(hit).toBeFalsy()
- })
-
- it("drops a suspended seller's offer but keeps the master product", async () => {
- const seed = await seedSellerOffer({
- email: "[email protected]",
- name: "Suspended",
- offerPrice: 3000,
- })
-
- const sellerModule = appContainer.resolve(MercurModules.SELLER)
- await (
- sellerModule as {
- updateSellers: (input: unknown) => Promise<unknown>
- }
- ).updateSellers({
- id: seed.sellerId,
- status: SellerStatus.SUSPENDED,
- })
-
- await reindex()
-
- const response = await api.post(
- `/store/search`,
- { q: "Suspended", region_id: region.id },
- storeHeaders
- )
-
- expect(response.status).toEqual(200)
- expect(
- response.data.hits.find(
- (h: { type: string; id: string }) =>
- h.type === "offer" && h.id === seed.offer.id
- )
- ).toBeFalsy()
- expect(
- response.data.hits.find(
- (h: { type: string; id: string }) =>
- h.type === "product" && h.id === seed.productId
- )
- ).toBeTruthy()
- })
- })
- })
- },
-})
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index d07dfcf5d..76b21f2b0 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -366,7 +366,6 @@
"/store/return-reasons": "typeof import(\"@medusajs/medusa/api/store/return-reasons/route\")",
"/store/return-reasons/:id": "typeof import(\"@medusajs/medusa/api/store/return-reasons/[id]/route\")",
"/store/returns": "typeof import(\"@medusajs/medusa/api/store/returns/route\")",
- "/store/search": "typeof import(\"@mercurjs/core/api/store/search/route\")",
"/store/sellers": "typeof import(\"@mercurjs/core/api/store/sellers/route\")",
"/store/sellers/:id": "typeof import(\"@mercurjs/core/api/store/sellers/[id]/route\")",
"/store/shipping-options": "typeof import(\"@mercurjs/core/api/store/shipping-options/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 3c0788ccb..c9a7a9095 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -628,7 +628,6 @@ export type Routes = {
$id: typeof import("@medusajs/medusa/api/store/return-reasons/[id]/route");
};
returns: typeof import("@medusajs/medusa/api/store/returns/route");
- search: typeof import("../src/api/store/search/route");
sellers: typeof import("../src/api/store/sellers/route") & {
$id: typeof import("../src/api/store/sellers/[id]/route");
};
diff --git a/packages/core/src/api/store/middlewares.ts b/packages/core/src/api/store/middlewares.ts
index 87e2706ef..0366c99a5 100644
--- a/packages/core/src/api/store/middlewares.ts
+++ b/packages/core/src/api/store/middlewares.ts
@@ -6,7 +6,6 @@ import { storeOrderGroupsMiddlewares } from "./order-groups/middlewares"
import { storeProductAttributesMiddlewares } from "./product-attributes/middlewares"
import { storeProductCategoriesMiddlewares } from "./product-categories/middlewares"
import { storeProductsMiddlewares } from "./products/middlewares"
-import { storeSearchMiddlewares } from "./search/middlewares"
import { storeSellersMiddlewares } from "./sellers/middlewares"
export const storeMiddlewares: MiddlewareRoute[] = [
@@ -16,6 +15,5 @@ export const storeMiddlewares: MiddlewareRoute[] = [
...storeProductAttributesMiddlewares,
...storeProductCategoriesMiddlewares,
...storeProductsMiddlewares,
- ...storeSearchMiddlewares,
...storeSellersMiddlewares,
]
diff --git a/packages/core/src/api/store/search/middlewares.ts b/packages/core/src/api/store/search/middlewares.ts
deleted file mode 100644
index 17a8b513d..000000000
--- a/packages/core/src/api/store/search/middlewares.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import {
- authenticate,
- MedusaNextFunction,
- MedusaResponse,
- MedusaStoreRequest,
- MiddlewareRoute,
- refetchEntities,
- refetchEntity,
-} from "@medusajs/framework/http"
-import { MedusaPricingContext } from "@medusajs/framework/types"
-import { validateAndTransformBody } from "@medusajs/framework"
-import { MedusaError } from "@medusajs/framework/utils"
-
-import { StoreSearchSchema, StoreSearchType } from "./validators"
-
-type StoreSearchRequest = MedusaStoreRequest<StoreSearchType> & {
- pricingContext?: MedusaPricingContext
- taxContext?: {
- taxLineContext?: { address?: { country_code?: string; province_code?: string } }
- taxInclusivityContext?: { automaticTaxes: boolean }
- }
-}
-
-// Refetches the region (never trusts the body) to build the pricing/tax context,
-// mirroring the /store/products chain. No region_id -> no pricing context.
-const setSearchPricingContext = async (
- req: StoreSearchRequest,
- _res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- const body = req.validatedBody
- const regionId = body?.region_id
- if (!regionId) {
- return next()
- }
-
- try {
- const region = await refetchEntity({
- entity: "region",
- idOrFilter: regionId,
- scope: req.scope,
- fields: ["id", "currency_code", "automatic_taxes"],
- options: { cache: { enable: true } },
- })
-
- if (!region) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Region with id ${regionId} not found when populating the pricing context`
- )
- }
-
- const pricingContext: MedusaPricingContext = {
- region_id: region.id,
- currency_code: region.currency_code,
- }
-
- if (req.auth_context?.actor_id) {
- const { data: customerGroups } = await refetchEntities({
- entity: "customer_group",
- idOrFilter: { customers: { id: req.auth_context.actor_id } },
- scope: req.scope,
- fields: ["id"],
- })
- pricingContext.customer = {
- groups: customerGroups.map((cg: { id: string }) => ({ id: cg.id })),
- }
- }
-
- req.pricingContext = pricingContext
-
- if (region.automatic_taxes && body?.country_code) {
- req.taxContext = {
- taxInclusivityContext: { automaticTaxes: true },
- taxLineContext: {
- address: {
- country_code: body.country_code,
- province_code: body.province,
- },
- },
- }
- }
-
- return next()
- } catch (e) {
- return next(e)
- }
-}
-
-export const storeSearchMiddlewares: MiddlewareRoute[] = [
- {
- method: ["POST"],
- matcher: "/store/search",
- middlewares: [
- authenticate("customer", ["session", "bearer"], {
- allowUnauthenticated: true,
- }),
- validateAndTransformBody(StoreSearchSchema),
- setSearchPricingContext,
- ],
- },
-]
diff --git a/packages/core/src/api/store/search/route.ts b/packages/core/src/api/store/search/route.ts
deleted file mode 100644
index c2d611867..000000000
--- a/packages/core/src/api/store/search/route.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { MedusaResponse, MedusaStoreRequest } from "@medusajs/framework/http"
-import { MedusaPricingContext } from "@medusajs/framework/types"
-import { MercurModules, SearchResults } from "@mercurjs/types"
-
-import SearchModuleService from "../../../modules/search/services/search-module-service"
-import { StoreSearchType } from "./validators"
-
-type StoreSearchRequest = MedusaStoreRequest<StoreSearchType> & {
- pricingContext?: MedusaPricingContext
-}
-
-export const POST = async (
- req: StoreSearchRequest,
- res: MedusaResponse
-) => {
- const search = req.scope.resolve<SearchModuleService>(MercurModules.SEARCH)
- const body = req.validatedBody
-
- const result: SearchResults = await search.search({
- q: body.q,
- limit: body.limit,
- offset: body.offset,
- // Built by `setSearchPricingContext`; the provider projects calculated_price.
- context: req.pricingContext,
- filters: body.filters,
- })
-
- res.json({
- hits: result.hits,
- count: result.count,
- limit: body.limit,
- offset: body.offset,
- facets: result.facets,
- })
-}
diff --git a/packages/core/src/api/store/search/validators.ts b/packages/core/src/api/store/search/validators.ts
deleted file mode 100644
index d85aee04a..000000000
--- a/packages/core/src/api/store/search/validators.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { z } from "zod"
-
-// `filters` is passed straight to the active provider, which owns its shape.
-export const StoreSearchSchema = z
- .object({
- q: z.string().optional().default(""),
- limit: z.coerce.number().int().min(1).max(100).optional().default(12),
- offset: z.coerce.number().int().min(0).optional().default(0),
- region_id: z.string().optional(),
- country_code: z.string().optional(),
- province: z.string().optional(),
- filters: z.record(z.string(), z.unknown()).optional(),
- })
- .strict()
-
-export type StoreSearchType = z.infer<typeof StoreSearchSchema>
diff --git a/packages/core/src/modules/search/abstract-search-provider.ts b/packages/core/src/modules/search/abstract-search-provider.ts
deleted file mode 100644
index f454bfa5b..000000000
--- a/packages/core/src/modules/search/abstract-search-provider.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import {
- SearchDoc,
- SearchProvider,
- SearchQueryBase,
- SearchResults,
-} from "@mercurjs/types"
-
-export class AbstractSearchProvider implements SearchProvider {
- static identifier: string
-
- static validateOptions(_options: Record<string, unknown>): void | never {}
-
- getIdentifier(): string {
- return (this.constructor as typeof AbstractSearchProvider).identifier
- }
-
- async index(_docs: SearchDoc[]): Promise<void> {
- throw new Error("index must be overridden by the search provider")
- }
-
- async remove(_ids: string[]): Promise<void> {
- throw new Error("remove must be overridden by the search provider")
- }
-
- async search(_query: SearchQueryBase): Promise<SearchResults> {
- throw new Error("search must be overridden by the search provider")
- }
-}
diff --git a/packages/core/src/modules/search/index.ts b/packages/core/src/modules/search/index.ts
deleted file mode 100644
index ab59bd393..000000000
--- a/packages/core/src/modules/search/index.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Module } from "@medusajs/framework/utils"
-import { MercurModules } from "@mercurjs/types"
-
-import SearchModuleService from "./services/search-module-service"
-import loadProviders from "./loaders/providers"
-
-export { AbstractSearchProvider } from "./abstract-search-provider"
-export { default as SearchModuleService } from "./services/search-module-service"
-export {
- SearchProviderRegistrationPrefix,
- SearchProviderIdentifierRegistrationName,
-} from "./services/search-provider-service"
-export {
- reindexAll,
- indexProductPage,
- SEARCH_REINDEX_EVENT,
-} from "./lib/reindex"
-export {
- reindexProductsById,
- removeProductAndOffers,
- removeOfferDocs,
- offersForSeller,
-} from "./lib/sync"
-
-export default Module(MercurModules.SEARCH, {
- service: SearchModuleService,
- loaders: [loadProviders],
-})
diff --git a/packages/core/src/modules/search/lib/build-docs.ts b/packages/core/src/modules/search/lib/build-docs.ts
deleted file mode 100644
index 29627f666..000000000
--- a/packages/core/src/modules/search/lib/build-docs.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-import { MedusaContainer } from "@medusajs/framework/types"
-import { SellerStatus } from "@mercurjs/types"
-import {
- SearchDoc,
- SearchDocAttribute,
- SearchDocPrice,
-} from "@mercurjs/types"
-
-import { wrapProductVariantsWithOfferPrice } from "../../../api/utils/offers"
-import {
- EnrichableOffer,
- wrapOffersWithCalculatedPrices,
- wrapOffersWithTaxPrices,
-} from "../../../api/store/offers/helpers"
-
-export type SearchRegion = {
- id: string
- currency_code: string
- automatic_taxes?: boolean
- countries?: { iso_2?: string | null }[] | null
-}
-
-type CalculatedPrice = {
- calculated_amount?: number | null
- original_amount?: number | null
- currency_code?: string | null
- calculated_amount_with_tax?: number | null
- original_amount_with_tax?: number | null
-}
-
-type ProductVariantRow = {
- id: string
- calculated_price?: CalculatedPrice | null
-}
-
-type ProductAttributeValueRow = {
- id: string
- name: string
- attribute?: {
- id: string
- handle?: string | null
- name?: string | null
- type?: string | null
- is_filterable?: boolean | null
- } | null
-}
-
-// Master products carry no seller — sellers live only on offers.
-export type SearchProductRow = {
- id: string
- title: string
- description?: string | null
- handle?: string | null
- thumbnail?: string | null
- status?: string | null
- collection_id?: string | null
- collection?: { id?: string; title?: string | null } | null
- categories?: { id: string; name?: string | null }[] | null
- variants?: ProductVariantRow[] | null
- product_attribute_values?: ProductAttributeValueRow[] | null
-}
-
-// Curated list — never `+`-prefixed on a default product list, which 500s
-// ("Cannot resolve alias path").
-export const searchProductFields = [
- "id",
- "title",
- "description",
- "handle",
- "thumbnail",
- "status",
- "collection_id",
- "collection.id",
- "collection.title",
- "categories.id",
- "categories.name",
- "variants.id",
- "product_attribute_values.id",
- "product_attribute_values.name",
- "product_attribute_values.attribute.id",
- "product_attribute_values.attribute.handle",
- "product_attribute_values.attribute.name",
- "product_attribute_values.attribute.type",
- "product_attribute_values.attribute.is_filterable",
-]
-
-export const searchOfferFields = [
- "id",
- "seller_id",
- "variant_id",
- "product_id",
- "sku",
- "seller.id",
- "seller.handle",
- "seller.status",
- "product_variant.id",
- "product_variant.title",
- "product_variant.price_set.id",
-]
-
-const buildRegionTaxContext = (region: SearchRegion) => {
- if (!region.automatic_taxes) {
- return { taxInclusivityContext: { automaticTaxes: false } }
- }
- const countryCode = (region.countries ?? [])
- .map((c) => c?.iso_2)
- .find((iso): iso is string => Boolean(iso))
- return {
- taxInclusivityContext: { automaticTaxes: true },
- taxLineContext: countryCode
- ? { address: { country_code: countryCode } }
- : undefined,
- }
-}
-
-const fakeReq = (container: MedusaContainer, region: SearchRegion) =>
- ({
- scope: container,
- pricingContext: {
- region_id: region.id,
- currency_code: region.currency_code,
- },
- taxContext: buildRegionTaxContext(region),
- }) as unknown as Parameters<typeof wrapProductVariantsWithOfferPrice>[0]
-
-const toPrice = (cp: CalculatedPrice): SearchDocPrice | undefined => {
- const calculated = cp.calculated_amount_with_tax ?? cp.calculated_amount
- if (calculated == null) {
- return undefined
- }
- return {
- calculated_amount: calculated,
- original_amount:
- cp.original_amount_with_tax ?? cp.original_amount ?? calculated,
- currency_code: cp.currency_code ?? "",
- }
-}
-
-const cheapestVariantPrice = (
- product: SearchProductRow
-): SearchDocPrice | undefined => {
- let best: SearchDocPrice | undefined
- for (const variant of product.variants ?? []) {
- if (!variant.calculated_price) {
- continue
- }
- const price = toPrice(variant.calculated_price)
- if (price && (!best || price.calculated_amount < best.calculated_amount)) {
- best = price
- }
- }
- return best
-}
-
-const buildAttributes = (
- product: SearchProductRow
-): { tokens: string[]; attributes: SearchDocAttribute[] } => {
- const byAttribute = new Map<string, SearchDocAttribute>()
- const tokens: string[] = []
-
- for (const pav of product.product_attribute_values ?? []) {
- const attribute = pav.attribute
- if (!attribute?.is_filterable) {
- continue
- }
- const handle = attribute.handle ?? attribute.id
- tokens.push(`attr:${handle}:${pav.id}`)
-
- const existing = byAttribute.get(attribute.id) ?? {
- id: attribute.id,
- handle,
- name: attribute.name ?? handle,
- type: attribute.type ?? "text",
- values: [],
- }
- existing.values.push({ id: pav.id, name: pav.name })
- byAttribute.set(attribute.id, existing)
- }
-
- return { tokens, attributes: [...byAttribute.values()] }
-}
-
-// Per-region buybox comes from the store price helper via a faked request (no
-// HTTP) so the stored number matches `/store/products`.
-export const buildProductDocs = async (
- container: MedusaContainer,
- products: SearchProductRow[],
- regions: SearchRegion[]
-): Promise<{
- docs: SearchDoc[]
- attributesByProduct: Map<
- string,
- { tokens: string[]; attributes: SearchDocAttribute[] }
- >
-}> => {
- if (!products.length) {
- return { docs: [], attributesByProduct: new Map() }
- }
-
- const pricesByProduct = new Map<string, Record<string, SearchDocPrice>>()
- for (const region of regions) {
- await wrapProductVariantsWithOfferPrice(fakeReq(container, region), products)
- for (const product of products) {
- const price = cheapestVariantPrice(product)
- if (!price) {
- continue
- }
- const map = pricesByProduct.get(product.id) ?? {}
- map[region.id] = price
- pricesByProduct.set(product.id, map)
- }
- }
-
- const attributesByProduct = new Map<
- string,
- { tokens: string[]; attributes: SearchDocAttribute[] }
- >()
- const docs: SearchDoc[] = products.map((product) => {
- const attrs = buildAttributes(product)
- attributesByProduct.set(product.id, attrs)
-
- return {
- id: product.id,
- type: "product",
- title: product.title,
- description: product.description ?? undefined,
- handle: product.handle ?? undefined,
- thumbnail: product.thumbnail ?? undefined,
- collection_id: product.collection?.id ?? product.collection_id ?? undefined,
- collection: product.collection?.title ?? undefined,
- category_ids: (product.categories ?? []).map((c) => c.id),
- // Kept index-aligned with `category_ids` so the route can join id → label.
- categories: (product.categories ?? []).map((c) => c.name ?? c.id),
- attribute_tokens: attrs.tokens,
- attributes: attrs.attributes,
- prices: pricesByProduct.get(product.id) ?? {},
- }
- })
-
- return { docs, attributesByProduct }
-}
-
-type OfferRow = EnrichableOffer & {
- variant_id?: string
- sku?: string | null
- seller?: { handle?: string | null; status?: string | null } | null
- product_variant?: {
- id?: string
- title?: string | null
- price_set?: { id?: string } | null
- } | null
-}
-
-// Suspended sellers' offers are dropped here; the master product doc is untouched.
-export const buildOfferDocs = async (
- container: MedusaContainer,
- offers: OfferRow[],
- regions: SearchRegion[],
- context: {
- productById: Map<string, SearchProductRow>
- attributesByProduct: Map<
- string,
- { tokens: string[]; attributes: SearchDocAttribute[] }
- >
- }
-): Promise<SearchDoc[]> => {
- const openOffers = offers.filter(
- (offer) => offer.seller?.status === SellerStatus.OPEN
- )
- if (!openOffers.length) {
- return []
- }
-
- const pricesByOffer = new Map<string, Record<string, SearchDocPrice>>()
- for (const region of regions) {
- const req = fakeReq(container, region)
- await wrapOffersWithCalculatedPrices(req, openOffers)
- await wrapOffersWithTaxPrices(req, openOffers)
- for (const offer of openOffers) {
- if (!offer.calculated_price) {
- continue
- }
- const price = toPrice(offer.calculated_price as CalculatedPrice)
- if (!price) {
- continue
- }
- const map = pricesByOffer.get(offer.id) ?? {}
- map[region.id] = price
- pricesByOffer.set(offer.id, map)
- }
- }
-
- return openOffers.map((offer) => {
- const product = offer.product_id
- ? context.productById.get(offer.product_id)
- : undefined
- const attrs = offer.product_id
- ? context.attributesByProduct.get(offer.product_id)
- : undefined
-
- return {
- id: offer.id,
- type: "offer",
- title: product?.title ?? offer.product_variant?.title ?? "",
- description: product?.description ?? undefined,
- handle: product?.handle ?? undefined,
- thumbnail: product?.thumbnail ?? undefined,
- seller_handle: offer.seller?.handle ?? undefined,
- collection_id: product?.collection?.id ?? undefined,
- collection: product?.collection?.title ?? undefined,
- category_ids: (product?.categories ?? []).map((c) => c.id),
- categories: (product?.categories ?? []).map((c) => c.name ?? c.id),
- product_id: offer.product_id ?? undefined,
- variant_id: offer.variant_id ?? undefined,
- sku: offer.sku ?? undefined,
- attribute_tokens: attrs?.tokens ?? [],
- attributes: attrs?.attributes ?? [],
- prices: pricesByOffer.get(offer.id) ?? {},
- }
- })
-}
diff --git a/packages/core/src/modules/search/lib/reindex.ts b/packages/core/src/modules/search/lib/reindex.ts
deleted file mode 100644
index d373628dc..000000000
--- a/packages/core/src/modules/search/lib/reindex.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { MedusaContainer } from "@medusajs/framework/types"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-import { MercurModules } from "@mercurjs/types"
-
-import type SearchModuleService from "../services/search-module-service"
-import {
- buildOfferDocs,
- buildProductDocs,
- SearchProductRow,
- SearchRegion,
- searchOfferFields,
- searchProductFields,
-} from "./build-docs"
-
-const PAGE_SIZE = 100
-
-export const SEARCH_REINDEX_EVENT = "search.reindex"
-
-export const loadRegions = async (
- container: MedusaContainer
-): Promise<SearchRegion[]> => {
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const { data } = await query.graph({
- entity: "region",
- fields: ["id", "currency_code", "automatic_taxes", "countries.iso_2"],
- })
- return data as SearchRegion[]
-}
-
-export const reindexAll = async (
- container: MedusaContainer,
- search: SearchModuleService = container.resolve<SearchModuleService>(
- MercurModules.SEARCH
- )
-): Promise<void> => {
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
-
- const regions = await loadRegions(container)
-
- let skip = 0
- for (;;) {
- const { data: products, metadata } = await query.graph({
- entity: "product",
- fields: searchProductFields,
- filters: { status: "published" },
- pagination: { skip, take: PAGE_SIZE },
- })
-
- if (!products.length) {
- break
- }
-
- await indexProductPage(
- container,
- search,
- products as SearchProductRow[],
- regions
- )
-
- skip += PAGE_SIZE
- const count = metadata?.count ?? 0
- if (skip >= count) {
- break
- }
- }
-}
-
-export const indexProductPage = async (
- container: MedusaContainer,
- search: SearchModuleService,
- products: SearchProductRow[],
- regions: SearchRegion[]
-): Promise<void> => {
- const { docs: productDocs, attributesByProduct } = await buildProductDocs(
- container,
- products,
- regions
- )
-
- if (!productDocs.length) {
- return
- }
-
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const productIds = productDocs.map((doc) => doc.id)
- const productById = new Map<string, SearchProductRow>(
- products.map((product) => [product.id, product])
- )
-
- const { data: offers } = await query.graph({
- entity: "offer",
- fields: searchOfferFields,
- filters: { product_id: productIds },
- })
-
- const offerDocs = await buildOfferDocs(container, offers, regions, {
- productById,
- attributesByProduct,
- })
-
- await search.index([...productDocs, ...offerDocs])
-}
diff --git a/packages/core/src/modules/search/lib/sync.ts b/packages/core/src/modules/search/lib/sync.ts
deleted file mode 100644
index c496ecb3b..000000000
--- a/packages/core/src/modules/search/lib/sync.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { MedusaContainer } from "@medusajs/framework/types"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-import { MercurModules } from "@mercurjs/types"
-
-import type SearchModuleService from "../services/search-module-service"
-import { searchProductFields, SearchProductRow } from "./build-docs"
-import { indexProductPage, loadRegions } from "./reindex"
-
-const resolveSearch = (container: MedusaContainer): SearchModuleService =>
- container.resolve<SearchModuleService>(MercurModules.SEARCH)
-
-const uniq = (ids: (string | undefined | null)[]): string[] =>
- Array.from(new Set(ids.filter((id): id is string => Boolean(id))))
-
-const offerIdsForProducts = async (
- container: MedusaContainer,
- productIds: string[]
-): Promise<string[]> => {
- if (!productIds.length) {
- return []
- }
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const { data: offers } = await query.graph({
- entity: "offer",
- fields: ["id"],
- filters: { product_id: productIds },
- })
- return offers.map((o: { id: string }) => o.id)
-}
-
-export const removeProductAndOffers = async (
- container: MedusaContainer,
- productIds: string[],
- search: SearchModuleService = resolveSearch(container)
-): Promise<void> => {
- const ids = uniq(productIds)
- if (!ids.length) {
- return
- }
- const offerIds = await offerIdsForProducts(container, ids)
- await search.remove([...ids, ...offerIds])
-}
-
-export const removeOfferDocs = async (
- container: MedusaContainer,
- offerIds: string[],
- search: SearchModuleService = resolveSearch(container)
-): Promise<void> => {
- const ids = uniq(offerIds)
- if (ids.length) {
- await search.remove(ids)
- }
-}
-
-export const reindexProductsById = async (
- container: MedusaContainer,
- productIds: string[],
- search: SearchModuleService = resolveSearch(container)
-): Promise<void> => {
- const ids = uniq(productIds)
- if (!ids.length) {
- return
- }
-
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const { data: products } = await query.graph({
- entity: "product",
- fields: searchProductFields,
- filters: { id: ids, status: "published" },
- })
-
- const publishedIds = new Set(products.map((p: { id: string }) => p.id))
- const staleIds = ids.filter((id) => !publishedIds.has(id))
-
- if (products.length) {
- const regions = await loadRegions(container)
- await indexProductPage(
- container,
- search,
- products as SearchProductRow[],
- regions
- )
- }
-
- if (staleIds.length) {
- await removeProductAndOffers(container, staleIds, search)
- }
-}
-
-export const offersForSeller = async (
- container: MedusaContainer,
- sellerId: string
-): Promise<{ offerIds: string[]; productIds: string[] }> => {
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const { data: offers } = await query.graph({
- entity: "offer",
- fields: ["id", "product_id"],
- filters: { seller_id: sellerId },
- })
- return {
- offerIds: uniq(offers.map((o: { id: string }) => o.id)),
- productIds: uniq(
- offers.map((o: { product_id?: string }) => o.product_id)
- ),
- }
-}
diff --git a/packages/core/src/modules/search/loaders/providers.ts b/packages/core/src/modules/search/loaders/providers.ts
deleted file mode 100644
index e16c67210..000000000
--- a/packages/core/src/modules/search/loaders/providers.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { asFunction, Lifetime, LifetimeType } from "@medusajs/framework/awilix"
-import { moduleProviderLoader } from "@medusajs/framework/modules-sdk"
-import {
- LoaderOptions,
- ModuleProvider,
- ModulesSdkTypes,
-} from "@medusajs/framework/types"
-
-import { SearchProviderRegistrationPrefix } from "../services/search-provider-service"
-import { OramaSearchProvider } from "../providers"
-
-const registrationFn = async (
- klass: { identifier: string; LIFE_TIME?: LifetimeType },
- container: { register: (m: Record<string, unknown>) => void },
- pluginOptions: { id: string; options?: Record<string, unknown> }
-) => {
- const key = `${SearchProviderRegistrationPrefix}${klass.identifier}_${pluginOptions.id}`
-
- container.register({
- [key]: asFunction(
- (cradle) =>
- new (klass as unknown as new (
- cradle: unknown,
- options: Record<string, unknown>
- ) => unknown)(cradle, pluginOptions.options ?? {}),
- {
- lifetime: klass.LIFE_TIME || Lifetime.SINGLETON,
- }
- ),
- })
-}
-
-export default async ({
- container,
- options,
-}: LoaderOptions<
- (
- | ModulesSdkTypes.ModuleServiceInitializeOptions
- | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
- ) & { provider?: ModuleProvider }
->): Promise<void> => {
- const provider = options?.provider
-
- if (!provider) {
- return await registrationFn(
- OramaSearchProvider as unknown as { identifier: string },
- container as unknown as {
- register: (m: Record<string, unknown>) => void
- },
- { id: "default" }
- )
- }
-
- await moduleProviderLoader({
- container,
- providers: [provider],
- registerServiceFn: registrationFn,
- })
-}
diff --git a/packages/core/src/modules/search/providers/index.ts b/packages/core/src/modules/search/providers/index.ts
deleted file mode 100644
index 7e90fafcb..000000000
--- a/packages/core/src/modules/search/providers/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { OramaSearchProvider } from "./orama"
diff --git a/packages/core/src/modules/search/providers/orama/index.ts b/packages/core/src/modules/search/providers/orama/index.ts
deleted file mode 100644
index 585cf8c3f..000000000
--- a/packages/core/src/modules/search/providers/orama/index.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { ModuleProvider } from "@medusajs/framework/utils"
-import { MercurModules } from "@mercurjs/types"
-
-import { OramaSearchProvider } from "./service"
-
-export { OramaSearchProvider } from "./service"
-export type { OramaSearchQuery } from "./types"
-
-export default ModuleProvider(MercurModules.SEARCH, {
- services: [OramaSearchProvider],
-})
diff --git a/packages/core/src/modules/search/providers/orama/service.ts b/packages/core/src/modules/search/providers/orama/service.ts
deleted file mode 100644
index 3be7bbe55..000000000
--- a/packages/core/src/modules/search/providers/orama/service.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import {
- AnyOrama,
- create,
- insertMultiple,
- removeMultiple,
- search as oramaSearch,
-} from "@orama/orama"
-import {
- SearchDoc,
- SearchFacetAttribute,
- SearchFacetValue,
- SearchResults,
-} from "@mercurjs/types"
-
-import { AbstractSearchProvider } from "../../abstract-search-provider"
-import { OramaSearchQuery } from "./types"
-
-const SEARCH_SCHEMA = {
- type: "enum",
- title: "string",
- description: "string",
- handle: "string",
- sku: "string",
- seller_handle: "enum",
- collection_id: "enum",
- category_ids: "enum[]",
- product_id: "enum",
- variant_id: "enum",
- attribute_tokens: "enum[]",
-} as const
-
-const SEARCHABLE_PROPERTIES = ["title", "description", "handle", "sku"]
-
-// In-memory index living in the API process's RAM — it starts empty and needs a
-// reindex to populate. id → label maps are kept at index time so `search` can
-// label facets without a second lookup.
-export class OramaSearchProvider extends AbstractSearchProvider {
- static identifier = "search-orama"
-
- protected readonly db_: AnyOrama
-
- protected readonly collectionLabels_ = new Map<string, string>()
- protected readonly categoryLabels_ = new Map<string, string>()
- protected readonly attributeHandleLabels_ = new Map<string, string>()
- protected readonly attributeValueLabels_ = new Map<string, string>()
-
- constructor() {
- super()
- this.db_ = create({ schema: SEARCH_SCHEMA })
- }
-
- private recordLabels_(docs: SearchDoc[]): void {
- for (const doc of docs) {
- if (doc.collection_id && doc.collection) {
- this.collectionLabels_.set(doc.collection_id, doc.collection)
- }
- const ids = doc.category_ids ?? []
- const labels = doc.categories ?? []
- ids.forEach((id, i) => {
- if (labels[i]) {
- this.categoryLabels_.set(id, labels[i])
- }
- })
- for (const attribute of doc.attributes ?? []) {
- this.attributeHandleLabels_.set(attribute.handle, attribute.name)
- for (const value of attribute.values) {
- this.attributeValueLabels_.set(value.id, value.name)
- }
- }
- }
- }
-
- async index(docs: SearchDoc[]): Promise<void> {
- if (!docs.length) {
- return
- }
- this.recordLabels_(docs)
- await removeMultiple(
- this.db_,
- docs.map((doc) => doc.id)
- )
- await insertMultiple(
- this.db_,
- docs as unknown as Parameters<typeof insertMultiple>[1]
- )
- }
-
- async remove(ids: string[]): Promise<void> {
- if (!ids.length) {
- return
- }
- await removeMultiple(this.db_, ids)
- }
-
- async search(query: OramaSearchQuery): Promise<SearchResults> {
- const filters = query.filters ?? {}
- const term = query.q?.trim()
-
- const where: Record<string, unknown> = {}
- if (filters.type) {
- where.type = { eq: filters.type }
- }
- if (filters.seller_handle) {
- where.seller_handle = { eq: filters.seller_handle }
- }
- if (filters.collection_ids?.length) {
- where.collection_id = { in: filters.collection_ids }
- }
- if (filters.category_ids?.length) {
- where.category_ids = { containsAny: filters.category_ids }
- }
- if (filters.attributes) {
- const tokens = Object.entries(filters.attributes).flatMap(
- ([handle, valueIds]) =>
- valueIds.map((valueId) => `attr:${handle}:${valueId}`)
- )
- if (tokens.length) {
- where.attribute_tokens = { containsAny: tokens }
- }
- }
-
- const result = await oramaSearch(this.db_, {
- term: term || undefined,
- properties: term ? SEARCHABLE_PROPERTIES : undefined,
- where: where as never,
- limit: query.limit ?? 12,
- offset: query.offset ?? 0,
- threshold: 0,
- facets: {
- collection_id: { limit: 200 },
- category_ids: { limit: 200 },
- attribute_tokens: { limit: 1000 },
- } as never,
- })
-
- const regionId = (query.context?.region_id ?? undefined) as
- | string
- | undefined
- const hits = result.hits.map((hit) => {
- const doc = hit.document as unknown as SearchDoc
- const price =
- regionId && doc.prices?.[regionId] ? doc.prices[regionId] : null
- return { ...doc, calculated_price: price }
- })
-
- return {
- hits,
- count: result.count,
- facets: {
- collections: this.toFacetValues_(
- result.facets?.collection_id?.values,
- this.collectionLabels_
- ),
- categories: this.toFacetValues_(
- result.facets?.category_ids?.values,
- this.categoryLabels_
- ),
- attributes: this.toAttributeFacets_(
- result.facets?.attribute_tokens?.values
- ),
- },
- }
- }
-
- private toFacetValues_(
- values: Record<string, number> | undefined,
- labels: Map<string, string>
- ): SearchFacetValue[] {
- return Object.entries(values ?? {}).map(([id, count]) => ({
- id,
- label: labels.get(id) ?? id,
- count,
- }))
- }
-
- private toAttributeFacets_(
- values: Record<string, number> | undefined
- ): SearchFacetAttribute[] {
- const byHandle = new Map<string, SearchFacetValue[]>()
-
- for (const [token, count] of Object.entries(values ?? {})) {
- const [, handle, valueId] = token.split(":")
- if (!handle || !valueId) {
- continue
- }
- const group = byHandle.get(handle) ?? []
- group.push({
- id: valueId,
- label: this.attributeValueLabels_.get(valueId) ?? valueId,
- count,
- })
- byHandle.set(handle, group)
- }
-
- return [...byHandle.entries()].map(([handle, valuesForHandle]) => ({
- handle,
- label: this.attributeHandleLabels_.get(handle) ?? handle,
- values: valuesForHandle,
- }))
- }
-}
diff --git a/packages/core/src/modules/search/providers/orama/types.ts b/packages/core/src/modules/search/providers/orama/types.ts
deleted file mode 100644
index d59c61e87..000000000
--- a/packages/core/src/modules/search/providers/orama/types.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { SearchQueryBase } from "@mercurjs/types"
-
-export interface OramaSearchQuery extends SearchQueryBase {
- filters?: {
- type?: "product" | "offer"
- collection_ids?: string[]
- category_ids?: string[]
- seller_handle?: string
- // attribute handle -> selected value ids
- attributes?: Record<string, string[]>
- }
-}
diff --git a/packages/core/src/modules/search/services/index.ts b/packages/core/src/modules/search/services/index.ts
deleted file mode 100644
index 491dd4be4..000000000
--- a/packages/core/src/modules/search/services/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { default as SearchProviderService } from "./search-provider-service"
-export * from "./search-provider-service"
diff --git a/packages/core/src/modules/search/services/search-module-service.ts b/packages/core/src/modules/search/services/search-module-service.ts
deleted file mode 100644
index 66cb8e0d9..000000000
--- a/packages/core/src/modules/search/services/search-module-service.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import {
- IEventBusModuleService,
- InternalModuleDeclaration,
- Logger,
-} from "@medusajs/framework/types"
-import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
-import {
- SearchDoc,
- SearchQueryBase,
- SearchResults,
-} from "@mercurjs/types"
-
-import { SEARCH_REINDEX_EVENT } from "../lib/reindex"
-import SearchProviderService from "./search-provider-service"
-
-type InjectedDependencies = {
- searchProviderService: SearchProviderService
- [ContainerRegistrationKeys.LOGGER]: Logger
- [Modules.EVENT_BUS]: IEventBusModuleService
-}
-
-export default class SearchModuleService {
- protected readonly searchProviderService_: SearchProviderService
- protected readonly logger_: Logger
- protected readonly eventBus_: IEventBusModuleService
- #isWorkerMode = false
-
- constructor(
- container: InjectedDependencies,
- moduleDeclaration: InternalModuleDeclaration
- ) {
- this.searchProviderService_ = container.searchProviderService
- this.logger_ = container[ContainerRegistrationKeys.LOGGER]
- this.eventBus_ = container[Modules.EVENT_BUS]
- this.#isWorkerMode = moduleDeclaration.worker_mode !== "server"
- }
-
- __hooks = {
- onApplicationStart(this: SearchModuleService) {
- return this.onApplicationStart_()
- },
- }
-
- // The module service is constructed with the awilix cradle, not the app
- // container, so it can't run the cross-module reindex itself. It emits an
- // event instead; the `search-reindex` subscriber handles it with the real
- // request-scoped container.
- protected async onApplicationStart_(): Promise<void> {
- if (!this.#isWorkerMode) {
- return
- }
-
- try {
- await this.eventBus_.emit({ name: SEARCH_REINDEX_EVENT, data: {} })
- } catch (e) {
- this.logger_.error(e)
- }
- }
-
- getProviderIdentifier(): string {
- return this.searchProviderService_.getIdentifier()
- }
-
- async index(docs: SearchDoc[]): Promise<void> {
- return await this.searchProviderService_.index(docs)
- }
-
- async remove(ids: string[]): Promise<void> {
- return await this.searchProviderService_.remove(ids)
- }
-
- async search(query: SearchQueryBase): Promise<SearchResults> {
- return await this.searchProviderService_.search(query)
- }
-}
diff --git a/packages/core/src/modules/search/services/search-provider-service.ts b/packages/core/src/modules/search/services/search-provider-service.ts
deleted file mode 100644
index 7ccfdfdb4..000000000
--- a/packages/core/src/modules/search/services/search-provider-service.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { MedusaError } from "@medusajs/framework/utils"
-import {
- SearchDoc,
- SearchProvider,
- SearchQueryBase,
- SearchResults,
-} from "@mercurjs/types"
-
-export const SearchProviderIdentifierRegistrationName =
- "search_providers_identifier"
-
-export const SearchProviderRegistrationPrefix = "search_"
-
-type InjectedDependencies = {
- [key: `${typeof SearchProviderRegistrationPrefix}${string}`]: SearchProvider
-}
-
-export default class SearchProviderService {
- protected readonly searchProvider_: SearchProvider
-
- constructor(container: InjectedDependencies) {
- const searchProviderKeys = Object.keys(container).filter((k) =>
- k.startsWith(SearchProviderRegistrationPrefix)
- )
-
- if (searchProviderKeys.length !== 1) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Search module should be initialized with exactly one provider`
- )
- }
-
- this.searchProvider_ = container[
- searchProviderKeys[0] as keyof InjectedDependencies
- ] as SearchProvider
- }
-
- getIdentifier(): string {
- const provider = this.searchProvider_ as SearchProvider & {
- getIdentifier?: () => string
- }
- return provider.getIdentifier?.() ?? "unknown"
- }
-
- async index(docs: SearchDoc[]): Promise<void> {
- return await this.searchProvider_.index(docs)
- }
-
- async remove(ids: string[]): Promise<void> {
- return await this.searchProvider_.remove(ids)
- }
-
- async search(query: SearchQueryBase): Promise<SearchResults> {
- return await this.searchProvider_.search(query)
- }
-}
diff --git a/packages/core/src/subscribers/search-offer-changed.ts b/packages/core/src/subscribers/search-offer-changed.ts
deleted file mode 100644
index f193fef34..000000000
--- a/packages/core/src/subscribers/search-offer-changed.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-import { OfferWorkflowEvents } from "../workflows/events"
-import {
- reindexProductsById,
- removeOfferDocs,
-} from "../modules/search/lib/sync"
-
-export default async function searchOfferChangedHandler({
- event,
- container,
-}: SubscriberArgs<{ id: string; product_id?: string }>) {
- const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
- const { id, product_id } = event.data
-
- try {
- if (event.name === OfferWorkflowEvents.DELETED) {
- await removeOfferDocs(container, [id])
- }
- if (product_id) {
- await reindexProductsById(container, [product_id])
- }
- } catch (error) {
- logger.error(`Search sync failed for offer ${id}:`, error as Error)
- throw error
- }
-}
-
-export const config: SubscriberConfig = {
- event: [
- OfferWorkflowEvents.CREATED,
- OfferWorkflowEvents.UPDATED,
- OfferWorkflowEvents.DELETED,
- ],
- context: {
- subscriberId: "search-offer-changed-handler",
- },
-}
diff --git a/packages/core/src/subscribers/search-product-changed.ts b/packages/core/src/subscribers/search-product-changed.ts
deleted file mode 100644
index 52b87584b..000000000
--- a/packages/core/src/subscribers/search-product-changed.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-import { ProductWorkflowEvents } from "../workflows/product/events"
-import { reindexProductsById } from "../modules/search/lib/sync"
-
-export default async function searchProductChangedHandler({
- event,
- container,
-}: SubscriberArgs<{ id: string }>) {
- const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
- try {
- await reindexProductsById(container, [event.data.id])
- } catch (error) {
- logger.error(
- `Search sync failed for product ${event.data.id}:`,
- error as Error
- )
- throw error
- }
-}
-
-export const config: SubscriberConfig = {
- event: [
- ProductWorkflowEvents.PUBLISHED,
- ProductWorkflowEvents.REJECTED,
- "product.updated",
- "product.product.updated",
- ],
- context: {
- subscriberId: "search-product-changed-handler",
- },
-}
diff --git a/packages/core/src/subscribers/search-product-deleted.ts b/packages/core/src/subscribers/search-product-deleted.ts
deleted file mode 100644
index 947d2055e..000000000
--- a/packages/core/src/subscribers/search-product-deleted.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-import { removeProductAndOffers } from "../modules/search/lib/sync"
-
-export default async function searchProductDeletedHandler({
- event,
- container,
-}: SubscriberArgs<{ id: string }>) {
- const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
- try {
- await removeProductAndOffers(container, [event.data.id])
- } catch (error) {
- logger.error(
- `Search delete failed for product ${event.data.id}:`,
- error as Error
- )
- throw error
- }
-}
-
-export const config: SubscriberConfig = {
- event: ["product.deleted", "product.product.deleted"],
- context: {
- subscriberId: "search-product-deleted-handler",
- },
-}
diff --git a/packages/core/src/subscribers/search-reindex.ts b/packages/core/src/subscribers/search-reindex.ts
deleted file mode 100644
index 156cf5a2b..000000000
--- a/packages/core/src/subscribers/search-reindex.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-import { reindexAll, SEARCH_REINDEX_EVENT } from "../modules/search"
-
-export default async function searchReindexHandler({
- container,
-}: SubscriberArgs) {
- const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
- try {
- await reindexAll(container)
- } catch (error) {
- logger.error("Full search reindex failed:", error as Error)
- throw error
- }
-}
-
-export const config: SubscriberConfig = {
- event: SEARCH_REINDEX_EVENT,
- context: {
- subscriberId: "search-reindex-handler",
- },
-}
diff --git a/packages/core/src/subscribers/search-seller-changed.ts b/packages/core/src/subscribers/search-seller-changed.ts
deleted file mode 100644
index ff7f168bd..000000000
--- a/packages/core/src/subscribers/search-seller-changed.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
-import { SellerWorkflowEvents } from "../workflows/events"
-import {
- offersForSeller,
- reindexProductsById,
- removeOfferDocs,
-} from "../modules/search/lib/sync"
-
-// unterminated lands on SUSPENDED, still not OPEN, so its offers stay dropped.
-const DEACTIVATING = new Set<string>([
- SellerWorkflowEvents.SUSPENDED,
- SellerWorkflowEvents.TERMINATED,
- SellerWorkflowEvents.UNTERMINATED,
- SellerWorkflowEvents.DELETED,
-])
-
-export default async function searchSellerChangedHandler({
- event,
- container,
-}: SubscriberArgs<{ id: string }>) {
- const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
- const sellerId = event.data.id
-
- try {
- const { offerIds, productIds } = await offersForSeller(container, sellerId)
-
- if (DEACTIVATING.has(event.name)) {
- await removeOfferDocs(container, offerIds)
- }
- await reindexProductsById(container, productIds)
- } catch (error) {
- logger.error(
- `Search sync failed for seller ${sellerId} (${event.name}):`,
- error as Error
- )
- throw error
- }
-}
-
-export const config: SubscriberConfig = {
- event: [
- SellerWorkflowEvents.APPROVED,
- SellerWorkflowEvents.UNSUSPENDED,
- SellerWorkflowEvents.UPDATED,
- SellerWorkflowEvents.SUSPENDED,
- SellerWorkflowEvents.TERMINATED,
- SellerWorkflowEvents.UNTERMINATED,
- SellerWorkflowEvents.DELETED,
- ],
- context: {
- subscriberId: "search-seller-changed-handler",
- },
-}
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 76c1b973f..4328b97d1 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -18,9 +18,6 @@ export * from "./payout"
// Offer types
export * from "./offer"
-// Search types
-export * from "./search"
-
// Product types — explicit re-export overrides Medusa's product surface.
// Mercur's runtime enums and Mercur-extended DTOs (Omit + intersection over
// upstream) win over the wholesale `export * from "@medusajs/types"` above.
diff --git a/packages/types/src/search/common.ts b/packages/types/src/search/common.ts
deleted file mode 100644
index ae910cb90..000000000
--- a/packages/types/src/search/common.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { ModuleProviderExports } from "@medusajs/types"
-
-export interface SearchDoc {
- id: string
- type: "product" | "offer"
- title: string
- description?: string
- handle?: string
- thumbnail?: string
- seller_handle?: string
- collection_id?: string
- collection?: string
- category_ids?: string[]
- categories?: string[]
- product_id?: string
- variant_id?: string
- sku?: string
- // Composite tokens `attr:<attribute_handle>:<value_id>`; only is_filterable
- // attribute values are tokenized.
- attribute_tokens?: string[]
- attributes?: SearchDocAttribute[]
- // Price snapshot per region, computed at index time.
- prices?: Record<string, SearchDocPrice>
- calculated_price?: SearchDocPrice | null
-}
-
-export interface SearchDocAttribute {
- id: string
- handle: string
- name: string
- type: string
- values: Array<{ id: string; name: string }>
-}
-
-export interface SearchDocPrice {
- calculated_amount: number
- original_amount: number
- currency_code: string
-}
-
-export interface SearchQueryBase {
- q?: string
- limit?: number
- offset?: number
- context?: Record<string, unknown>
- filters?: Record<string, unknown>
-}
-
-export interface SearchFacetValue {
- id: string
- label: string
- count: number
-}
-
-export interface SearchFacetAttribute {
- handle: string
- label: string
- values: SearchFacetValue[]
-}
-
-export interface SearchFacets {
- collections: SearchFacetValue[]
- categories: SearchFacetValue[]
- attributes: SearchFacetAttribute[]
-}
-
-export interface SearchResults {
- hits: SearchDoc[]
- count: number
- facets?: SearchFacets
-}
-
-export interface SearchProvider<
- TQuery extends SearchQueryBase = SearchQueryBase,
-> {
- index(docs: SearchDoc[]): Promise<void>
- remove(ids: string[]): Promise<void>
- search(query: TQuery): Promise<SearchResults>
-}
-
-export interface SearchModuleOptions {
- provider?: {
- resolve: string | ModuleProviderExports
- id: string
- options?: Record<string, unknown>
- }
-}
diff --git a/packages/types/src/search/index.ts b/packages/types/src/search/index.ts
deleted file mode 100644
index 488a94fdf..000000000
--- a/packages/types/src/search/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./common"