diff --git a/integration-tests/modules/__tests__/modules/load-standalone.ts b/integration-tests/modules/__tests__/modules/load-standalone.ts index f593aeee8cb10..06ca63021f67d 100644 --- a/integration-tests/modules/__tests__/modules/load-standalone.ts +++ b/integration-tests/modules/__tests__/modules/load-standalone.ts @@ -1,4 +1,6 @@ import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { MedusaApp, Modules } from "@medusajs/modules-sdk" +import { IProductModuleService } from "@medusajs/types" jest.setTimeout(30000) @@ -15,10 +17,18 @@ medusaIntegrationTestRunner({ }) it("Should migrate database and initialize Product module using connection string from environment variable ", async function () { - const { initialize, runMigrations } = require("@medusajs/product") + const { modules, runMigrations } = await MedusaApp({ + modulesConfig: { + [Modules.PRODUCT]: true, + }, + }) + await runMigrations() - const product = await initialize() + const product = modules[ + Modules.PRODUCT + ] as unknown as IProductModuleService + const productList = await product.list() expect(productList).toEqual(expect.arrayContaining([])) diff --git a/packages/core/modules-sdk/src/index.ts b/packages/core/modules-sdk/src/index.ts index 843aa56371e11..62b018aa42211 100644 --- a/packages/core/modules-sdk/src/index.ts +++ b/packages/core/modules-sdk/src/index.ts @@ -5,4 +5,3 @@ export * from "./medusa-app" export * from "./medusa-module" export * from "./remote-link" export * from "./remote-query" -export * from "./utils/initialize-factory" diff --git a/packages/core/modules-sdk/src/loaders/register-modules.ts b/packages/core/modules-sdk/src/loaders/register-modules.ts index 7dfaf6a273442..d18c5920df89d 100644 --- a/packages/core/modules-sdk/src/loaders/register-modules.ts +++ b/packages/core/modules-sdk/src/loaders/register-modules.ts @@ -137,11 +137,9 @@ function getInternalModuleResolution( // If user added a module and it's overridable, we resolve that instead const isStr = isString(moduleConfig) if (isStr || (isObj && moduleConfig.resolve)) { - resolutionPath = !moduleExports - ? resolveCwd(isStr ? moduleConfig : (moduleConfig.resolve as string)) - : // Explicitly assign an empty string, later, we will check if the value is exactly false. - // This allows to continue the module loading while using the module exports instead of re importing the module itself during the process. - "" + resolutionPath = resolveCwd( + isStr ? moduleConfig : (moduleConfig.resolve as string) + ) } const moduleDeclaration = isObj ? moduleConfig : {} diff --git a/packages/core/modules-sdk/src/loaders/utils/load-internal.ts b/packages/core/modules-sdk/src/loaders/utils/load-internal.ts index dfe97b6bf9e82..04b620b1d1ceb 100644 --- a/packages/core/modules-sdk/src/loaders/utils/load-internal.ts +++ b/packages/core/modules-sdk/src/loaders/utils/load-internal.ts @@ -1,17 +1,32 @@ import { + Constructor, InternalModuleDeclaration, Logger, MedusaContainer, MODULE_RESOURCE_TYPE, ModuleExports, + ModuleLoaderFunction, ModuleResolution, } from "@medusajs/types" import { ContainerRegistrationKeys, createMedusaContainer, MedusaModuleType, + ModulesSdkUtils, } from "@medusajs/utils" import { asFunction, asValue } from "awilix" +import { join, resolve } from "path" +import { statSync } from "fs" +import { readdir } from "fs/promises" + +type ModuleResource = { + services: Function[] + models: Function[] + repositories: Function[] + loaders: ModuleLoaderFunction[] + moduleService: Constructor + normalizedPath: string +} export async function loadInternalModule( container: MedusaContainer, @@ -36,6 +51,8 @@ export async function loadInternalModule( const modulePath = resolution.resolutionPath as string if (resolution.moduleExports) { + // TODO: + // If we want to benefit from the auto load mechanism, even if the module exports is provided, we need to ask for the module path loadedModule = resolution.moduleExports } else { loadedModule = await import(modulePath) @@ -56,7 +73,17 @@ export async function loadInternalModule( return { error } } - if (!loadedModule?.service) { + let moduleResources = {} as ModuleResource + + if (resolution.resolutionPath) { + moduleResources = await loadResources( + loadedModule?.loaders ?? [], + resolution, + logger + ) + } + + if (!loadedModule?.service && !moduleResources.moduleService) { container.register({ [registrationName]: asValue(undefined), }) @@ -69,9 +96,11 @@ export async function loadInternalModule( } if (migrationOnly) { + const moduleService_ = moduleResources.moduleService ?? loadedModule.service + // Partially loaded module, only register the service __joinerConfig function to be able to resolve it later const moduleService = { - __joinerConfig: loadedModule.service.prototype.__joinerConfig, + __joinerConfig: moduleService_.prototype.__joinerConfig, } container.register({ [registrationName]: asValue(moduleService), @@ -100,32 +129,21 @@ export async function loadInternalModule( ) } - const moduleLoaders = loadedModule?.loaders ?? [] - try { - for (const loader of moduleLoaders) { - await loader( - { - container: localContainer, - logger, - options: resolution.options, - dataLoaderOnly: loaderOnly, - }, - resolution.moduleDeclaration as InternalModuleDeclaration - ) - } - } catch (err) { - container.register({ - [registrationName]: asValue(undefined), - }) + const loaders = moduleResources.loaders ?? loadedModule?.loaders ?? [] + const error = await runLoaders(loaders, { + container, + localContainer, + logger, + resolution, + loaderOnly, + registrationName, + }) - return { - error: new Error( - `Loaders for module ${resolution.definition.label} failed: ${err.message}` - ), - } + if (error) { + return error } - const moduleService = loadedModule.service + const moduleService = moduleResources.moduleService ?? loadedModule.service container.register({ [registrationName]: asFunction((cradle) => { @@ -155,8 +173,229 @@ export async function loadModuleMigrations( loadedModule = moduleExports ?? (await import(resolution.resolutionPath as string)) - return [loadedModule.runMigrations, loadedModule.revertMigration] + let runMigrations = loadedModule.runMigrations + let revertMigration = loadedModule.revertMigration + + // Generate migration scripts if they are not present + if (!runMigrations || !revertMigration) { + const moduleResources = await loadResources( + loadedModule?.loaders ?? [], + resolution, + console as unknown as Logger + ) + + const migrationScriptOptions = { + moduleName: resolution.definition.key, + models: moduleResources.models, + pathToMigrations: moduleResources.normalizedPath + "/dist/migrations", + } + + runMigrations ??= ModulesSdkUtils.buildMigrationScript( + migrationScriptOptions + ) + + revertMigration ??= ModulesSdkUtils.buildRevertMigrationScript( + migrationScriptOptions + ) + } + + return [runMigrations, revertMigration] } catch { return [undefined, undefined] } } + +async function importAllFromDir(path: string) { + let filesToLoad: string[] = [] + + await readdir(path).then((files) => { + files.forEach((file) => { + if (file !== "index.js" && file.endsWith(".js")) { + const filePath = join(path, file) + const stats = statSync(filePath) + + if (stats.isDirectory()) { + // TODO: should we handle that? dont think so but I put that here for discussion + } else if (stats.isFile()) { + filesToLoad.push(filePath) + } + } + }) + + return filesToLoad + }) + + return ( + await Promise.all(filesToLoad.map((filePath) => import(filePath))) + ).flatMap((value) => { + return Object.values(value) + }) +} + +async function loadResources( + loadedModuleLoaders: ModuleLoaderFunction[], + moduleResolution: ModuleResolution, + logger: Logger +): Promise { + const modulePath = moduleResolution.resolutionPath as string + let normalizedPath = modulePath.replace("dist/", "").replace("index.js", "") + normalizedPath = resolve(normalizedPath) + + try { + const defaultOnFail = () => { + return [] + } + + const [moduleService, services, models, repositories] = await Promise.all([ + import(modulePath).then((moduleExports) => moduleExports.default.service), + importAllFromDir(resolve(normalizedPath, "dist", "services")).catch( + defaultOnFail + ), + importAllFromDir(resolve(normalizedPath, "dist", "models")).catch( + defaultOnFail + ), + importAllFromDir(resolve(normalizedPath, "dist", "repositories")).catch( + defaultOnFail + ), + ]) + + const cleanupResources = (resources) => { + return Object.values(resources).filter( + (resource): resource is Function => { + return typeof resource === "function" + } + ) + } + + const potentialServices = [...new Set(cleanupResources(services))] + const potentialModels = [...new Set(cleanupResources(models))] + const potentialRepositories = [...new Set(cleanupResources(repositories))] + + const finalLoaders = prepareLoaders({ + loadedModuleLoaders, + models: potentialModels, + repositories: potentialRepositories, + services: potentialServices, + moduleResolution, + migrationPath: normalizedPath + "/dist/migrations", + }) + + return { + services: potentialServices, + models: potentialModels, + repositories: potentialRepositories, + loaders: finalLoaders, + moduleService, + normalizedPath + } + } catch (e) { + logger.warn( + `Unable to load resources for module ${modulePath} automagically. ${e.message}` + ) + + return {} as ModuleResource + } +} + +async function runLoaders( + loaders: Function[] = [], + { + localContainer, + container, + logger, + resolution, + loaderOnly, + registrationName, + } +): Promise { + try { + for (const loader of loaders) { + await loader( + { + container: localContainer, + logger, + options: resolution.options, + dataLoaderOnly: loaderOnly, + }, + resolution.moduleDeclaration as InternalModuleDeclaration + ) + } + } catch (err) { + container.register({ + [registrationName]: asValue(undefined), + }) + + return { + error: new Error( + `Loaders for module ${resolution.definition.label} failed: ${err.message}` + ), + } + } +} + +function prepareLoaders({ + loadedModuleLoaders, + models, + repositories, + services, + moduleResolution, + migrationPath, +}) { + const finalLoaders: ModuleLoaderFunction[] = [] + + const toObjectReducer = (acc, curr) => { + acc[curr.name] = curr + return acc + } + + /* + * If no connectionLoader function is provided, create a default connection loader. + * TODO: Validate naming convention + */ + const connectionLoaderName = "connectionLoader" + const containerLoader = "containerLoader" + + const hasConnectionLoader = loadedModuleLoaders.some( + (l) => l.name === connectionLoaderName + ) + + if (!hasConnectionLoader && models.length > 0) { + const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ + moduleName: moduleResolution.definition.key, + moduleModels: models, + migrationsPath: migrationPath, //normalizedPath + "/dist/migrations", + }) + finalLoaders.push(connectionLoader) + } + + const hasContainerLoader = loadedModuleLoaders.some( + (l) => l.name === containerLoader + ) + + if (!hasContainerLoader) { + const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ + moduleModels: models.reduce(toObjectReducer, {}), + moduleRepositories: repositories.reduce(toObjectReducer, {}), + moduleServices: services.reduce(toObjectReducer, {}), + }) + finalLoaders.push(containerLoader) + } + + finalLoaders.push( + ...loadedModuleLoaders.filter((loader) => { + if ( + loader.name !== connectionLoaderName && + loader.name !== containerLoader + ) { + return true + } + + return ( + (loader.name === containerLoader && hasContainerLoader) || + (loader.name === connectionLoaderName && hasConnectionLoader) + ) + }) + ) + + return finalLoaders +} diff --git a/packages/core/modules-sdk/src/utils/index.ts b/packages/core/modules-sdk/src/utils/index.ts index 9fc688e96147d..d1470bdcbce08 100644 --- a/packages/core/modules-sdk/src/utils/index.ts +++ b/packages/core/modules-sdk/src/utils/index.ts @@ -1,3 +1,2 @@ export * from "./clean-graphql-schema" export * from "./graphql-schema-to-fields" -export * from "./initialize-factory" diff --git a/packages/core/modules-sdk/src/utils/initialize-factory.ts b/packages/core/modules-sdk/src/utils/initialize-factory.ts deleted file mode 100644 index 6230ee0e3aac7..0000000000000 --- a/packages/core/modules-sdk/src/utils/initialize-factory.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - ModuleExports, - ModuleServiceInitializeCustomDataLayerOptions, - ModuleServiceInitializeOptions, -} from "@medusajs/types" -import { MODULE_PACKAGE_NAMES } from "../definitions" -import { MedusaModule } from "../medusa-module" - -/** - * Generate a initialize module factory that is exported by the module to be initialized manually - * - * @param moduleName - * @param moduleDefinition - */ -export function initializeFactory({ - moduleName, - moduleDefinition, -}: { - moduleName: string - moduleDefinition: ModuleExports -}) { - return async ( - options?: - | ModuleServiceInitializeOptions - | ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: any - ) => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: moduleName, - defaultPath: MODULE_PACKAGE_NAMES[moduleName], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[moduleName] as T - } -} diff --git a/packages/core/types/src/modules-sdk/index.ts b/packages/core/types/src/modules-sdk/index.ts index 0f372a3b449a1..736e5ac161a69 100644 --- a/packages/core/types/src/modules-sdk/index.ts +++ b/packages/core/types/src/modules-sdk/index.ts @@ -122,7 +122,7 @@ export type LoaderOptions> = { } export type ModuleLoaderFunction = ( - options: LoaderOptions, + options: LoaderOptions, moduleDeclaration?: InternalModuleDeclaration ) => Promise @@ -226,14 +226,6 @@ export declare type ModuleJoinerRelationship = JoinerRelationship & { export type ModuleExports = { service: Constructor loaders?: ModuleLoaderFunction[] - /** - * @deprecated property will be removed in future versions - */ - migrations?: any[] - /** - * @deprecated property will be removed in future versions - */ - models?: Constructor[] runMigrations?( options: LoaderOptions, moduleDeclaration?: InternalModuleDeclaration diff --git a/packages/core/utils/src/dal/mikro-orm/mikro-orm-create-connection.ts b/packages/core/utils/src/dal/mikro-orm/mikro-orm-create-connection.ts index f04b80c614633..745b1d4e5ca10 100644 --- a/packages/core/utils/src/dal/mikro-orm/mikro-orm-create-connection.ts +++ b/packages/core/utils/src/dal/mikro-orm/mikro-orm-create-connection.ts @@ -99,7 +99,7 @@ export async function mikroOrmCreateConnection( const { MikroORM } = await import("@mikro-orm/postgresql") return await MikroORM.init({ - discovery: { disableDynamicFileAccess: true }, + discovery: { disableDynamicFileAccess: true, warnWhenNoEntities: false, }, entities, debug: database.debug ?? process.env.NODE_ENV?.startsWith("dev") ?? false, baseDir: process.cwd(), diff --git a/packages/core/utils/src/modules-sdk/loaders/container-loader-factory.ts b/packages/core/utils/src/modules-sdk/loaders/container-loader-factory.ts index a7199d04f4ecb..6fc93ee105d42 100644 --- a/packages/core/utils/src/modules-sdk/loaders/container-loader-factory.ts +++ b/packages/core/utils/src/modules-sdk/loaders/container-loader-factory.ts @@ -10,7 +10,10 @@ import { import { asClass } from "awilix" import { internalModuleServiceFactory } from "../internal-module-service-factory" import { lowerCaseFirst } from "../../common" -import { mikroOrmBaseRepositoryFactory } from "../../dal" +import { + MikroOrmBaseRepository, + mikroOrmBaseRepositoryFactory, +} from "../../dal" type RepositoryLoaderOptions = { moduleModels: Record @@ -44,13 +47,13 @@ export function moduleContainerLoaderFactory({ moduleRepositories?: Record customRepositoryLoader?: (options: RepositoryLoaderOptions) => void }): ({ container, options }: LoaderOptions) => Promise { - return async ({ + return async function containerLoader({ container, options, }: LoaderOptions< | ModuleServiceInitializeOptions | ModuleServiceInitializeCustomDataLayerOptions - >) => { + >) { const customRepositories = ( options as ModuleServiceInitializeCustomDataLayerOptions )?.repositories @@ -85,9 +88,9 @@ export function loadModuleServices({ container, }: ServiceLoaderOptions) { const moduleServicesMap = new Map( - Object.entries(moduleServices).map(([key, repository]) => [ + Object.entries(moduleServices).map(([key, service]) => [ lowerCaseFirst(key), - repository, + service, ]) ) @@ -158,6 +161,10 @@ export function loadModuleRepositories({ const allRepositories = [...customRepositoriesMap, ...moduleRepositoriesMap] + container.register({ + ["baseRepository"]: asClass(MikroOrmBaseRepository).singleton(), + }) + allRepositories.forEach(([key, repository]) => { let finalRepository = customRepositoriesMap.get(key) diff --git a/packages/core/utils/src/modules-sdk/loaders/mikro-orm-connection-loader-factory.ts b/packages/core/utils/src/modules-sdk/loaders/mikro-orm-connection-loader-factory.ts index 84ff065225451..92d8d167b7920 100644 --- a/packages/core/utils/src/modules-sdk/loaders/mikro-orm-connection-loader-factory.ts +++ b/packages/core/utils/src/modules-sdk/loaders/mikro-orm-connection-loader-factory.ts @@ -17,10 +17,10 @@ export function mikroOrmConnectionLoaderFactory({ moduleModels: any[] migrationsPath?: string }): any { - return async ( + return async function connectionLoader( { options, container, logger }: LoaderOptions, moduleDeclaration?: InternalModuleDeclaration - ): Promise => { + ): Promise { await mikroOrmConnectionLoader({ moduleName, entities: moduleModels, diff --git a/packages/modules/api-key/src/index.ts b/packages/modules/api-key/src/index.ts index bd9fb22270d18..5dc2ece1653d6 100644 --- a/packages/modules/api-key/src/index.ts +++ b/packages/modules/api-key/src/index.ts @@ -1,14 +1,7 @@ import { moduleDefinition } from "./module-definition" -import { initializeFactory, Modules } from "@medusajs/modules-sdk" export * from "./types" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.API_KEY, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/api-key/src/module-definition.ts b/packages/modules/api-key/src/module-definition.ts index 61d2e6a2e9569..27f88e7b12088 100644 --- a/packages/modules/api-key/src/module-definition.ts +++ b/packages/modules/api-key/src/module-definition.ts @@ -1,44 +1,8 @@ import { ModuleExports } from "@medusajs/types" -import * as ModuleServices from "@services" import { ApiKeyModuleService } from "@services" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import * as ModuleModels from "@models" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleRepositories from "@repositories" - -const migrationScriptOptions = { - moduleName: Modules.API_KEY, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.API_KEY, - moduleModels: Object.values(Models), - migrationsPath: __dirname + "/migrations", -}) const service = ApiKeyModuleService -const loaders = [containerLoader, connectionLoader] as any export const moduleDefinition: ModuleExports = { service, - loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/auth/src/index.ts b/packages/modules/auth/src/index.ts index 98c26a5e9e4d7..7aa317c3f4a0f 100644 --- a/packages/modules/auth/src/index.ts +++ b/packages/modules/auth/src/index.ts @@ -1,11 +1,5 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } -export * from "./initialize" export * from "./loaders" diff --git a/packages/modules/auth/src/initialize/index.ts b/packages/modules/auth/src/initialize/index.ts deleted file mode 100644 index 4fbe09f76230b..0000000000000 --- a/packages/modules/auth/src/initialize/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { IAuthModuleService, ModulesSdkTypes } from "@medusajs/types" - -import { InitializeModuleInjectableDependencies } from "@types" -import { moduleDefinition } from "../module-definition" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleBootstrapDeclaration - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: Modules.AUTH, - defaultPath: MODULE_PACKAGE_NAMES[Modules.AUTH], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, // TODO: Add provider configuration - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.AUTH] -} diff --git a/packages/modules/auth/src/loaders/connection.ts b/packages/modules/auth/src/loaders/connection.ts deleted file mode 100644 index a7d632cfceff1..0000000000000 --- a/packages/modules/auth/src/loaders/connection.ts +++ /dev/null @@ -1,38 +0,0 @@ -import * as AuthModels from "../models" - -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" - -import { EntitySchema } from "@mikro-orm/core" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values( - AuthModels - ) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.AUTH, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/auth/src/loaders/container.ts b/packages/modules/auth/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/auth/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/auth/src/loaders/index.ts b/packages/modules/auth/src/loaders/index.ts index 11369b9206758..96bcb99b211b9 100644 --- a/packages/modules/auth/src/loaders/index.ts +++ b/packages/modules/auth/src/loaders/index.ts @@ -1,3 +1 @@ -export * from "./connection" -export * from "./container" export * from "./providers" diff --git a/packages/modules/auth/src/module-definition.ts b/packages/modules/auth/src/module-definition.ts index 601a85bbbe94e..18b27ccc31319 100644 --- a/packages/modules/auth/src/module-definition.ts +++ b/packages/modules/auth/src/module-definition.ts @@ -1,32 +1,11 @@ -import * as Models from "@models" - import { AuthModuleService } from "@services" import { ModuleExports } from "@medusajs/types" -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" import loadProviders from "./loaders/providers" -const migrationScriptOptions = { - moduleName: Modules.AUTH, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - const service = AuthModuleService -const loaders = [loadContainer, loadConnection, loadProviders] as any +const loaders = [loadProviders] as any export const moduleDefinition: ModuleExports = { service, loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/cart/src/index.ts b/packages/modules/cart/src/index.ts index d449f7354469a..dd414e1b19c57 100644 --- a/packages/modules/cart/src/index.ts +++ b/packages/modules/cart/src/index.ts @@ -1,10 +1,3 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } - -export * from "./initialize" diff --git a/packages/modules/cart/src/initialize/index.ts b/packages/modules/cart/src/initialize/index.ts deleted file mode 100644 index 759135d39930b..0000000000000 --- a/packages/modules/cart/src/initialize/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { ICartModuleService, ModulesSdkTypes } from "@medusajs/types" -import { moduleDefinition } from "../module-definition" -import { InitializeModuleInjectableDependencies } from "@types" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: Modules.CART, - defaultPath: MODULE_PACKAGE_NAMES[Modules.CART], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.CART] -} diff --git a/packages/modules/cart/src/loaders/connection.ts b/packages/modules/cart/src/loaders/connection.ts deleted file mode 100644 index 292e4e5ae1f82..0000000000000 --- a/packages/modules/cart/src/loaders/connection.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as CartModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values( - CartModels - ) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.CART, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/cart/src/loaders/container.ts b/packages/modules/cart/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/cart/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/cart/src/loaders/index.ts b/packages/modules/cart/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/cart/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/cart/src/module-definition.ts b/packages/modules/cart/src/module-definition.ts index 1db51b9c5cf38..efcb04d5fe1ee 100644 --- a/packages/modules/cart/src/module-definition.ts +++ b/packages/modules/cart/src/module-definition.ts @@ -1,30 +1,8 @@ -import { Modules } from "@medusajs/modules-sdk" import { ModuleExports } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" import { CartModuleService } from "./services" -const migrationScriptOptions = { - moduleName: Modules.CART, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - const service = CartModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/currency/src/index.ts b/packages/modules/currency/src/index.ts index af48dc4e969bd..5dc2ece1653d6 100644 --- a/packages/modules/currency/src/index.ts +++ b/packages/modules/currency/src/index.ts @@ -1,14 +1,7 @@ import { moduleDefinition } from "./module-definition" -import { initializeFactory, Modules } from "@medusajs/modules-sdk" export * from "./types" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.CURRENCY, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/currency/src/module-definition.ts b/packages/modules/currency/src/module-definition.ts index df0f5d7ba273a..1c1e5469a31a9 100644 --- a/packages/modules/currency/src/module-definition.ts +++ b/packages/modules/currency/src/module-definition.ts @@ -1,45 +1,11 @@ import { ModuleExports } from "@medusajs/types" -import * as ModuleServices from "@services" import { CurrencyModuleService } from "@services" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import * as ModuleModels from "@models" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleRepositories from "@repositories" import initialDataLoader from "./loaders/initial-data" -const migrationScriptOptions = { - moduleName: Modules.CURRENCY, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.CURRENCY, - moduleModels: Object.values(Models), - migrationsPath: __dirname + "/migrations", -}) - const service = CurrencyModuleService -const loaders = [containerLoader, connectionLoader, initialDataLoader] as any +const loaders = [initialDataLoader] export const moduleDefinition: ModuleExports = { service, loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/customer/src/index.ts b/packages/modules/customer/src/index.ts index d449f7354469a..dd414e1b19c57 100644 --- a/packages/modules/customer/src/index.ts +++ b/packages/modules/customer/src/index.ts @@ -1,10 +1,3 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } - -export * from "./initialize" diff --git a/packages/modules/customer/src/initialize/index.ts b/packages/modules/customer/src/initialize/index.ts deleted file mode 100644 index 8272f17cc51c2..0000000000000 --- a/packages/modules/customer/src/initialize/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { ICustomerModuleService, ModulesSdkTypes } from "@medusajs/types" -import { moduleDefinition } from "../module-definition" -import { InitializeModuleInjectableDependencies } from "@types" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: Modules.CUSTOMER, - defaultPath: MODULE_PACKAGE_NAMES[Modules.CUSTOMER], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.CUSTOMER] -} diff --git a/packages/modules/customer/src/loaders/connection.ts b/packages/modules/customer/src/loaders/connection.ts deleted file mode 100644 index cd0f565fa5c39..0000000000000 --- a/packages/modules/customer/src/loaders/connection.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as CustomerModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(CustomerModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.CUSTOMER, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/customer/src/loaders/container.ts b/packages/modules/customer/src/loaders/container.ts deleted file mode 100644 index 80023e35a0aa0..0000000000000 --- a/packages/modules/customer/src/loaders/container.ts +++ /dev/null @@ -1,11 +0,0 @@ -import * as ModuleModels from "@models" -import * as CustomerRepositories from "@repositories" -import * as ModuleServices from "@services" - -import { ModulesSdkUtils } from "@medusajs/utils" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleServices: ModuleServices, - moduleRepositories: CustomerRepositories, -}) diff --git a/packages/modules/customer/src/loaders/index.ts b/packages/modules/customer/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/customer/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/customer/src/module-definition.ts b/packages/modules/customer/src/module-definition.ts index 81e86620beece..65563913a2177 100644 --- a/packages/modules/customer/src/module-definition.ts +++ b/packages/modules/customer/src/module-definition.ts @@ -1,31 +1,8 @@ -import { Modules } from "@medusajs/modules-sdk" import { ModuleExports } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" import { CustomerModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" - -const migrationScriptOptions = { - moduleName: Modules.CUSTOMER, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) const service = CustomerModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/file/src/index.ts b/packages/modules/file/src/index.ts index 8bbb7fbf90a99..5167ac59b57ff 100644 --- a/packages/modules/file/src/index.ts +++ b/packages/modules/file/src/index.ts @@ -1,13 +1,5 @@ import { moduleDefinition } from "./module-definition" -import { initializeFactory, Modules } from "@medusajs/modules-sdk" export * from "./types" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.FILE, - moduleDefinition, -}) - -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/file/src/module-definition.ts b/packages/modules/file/src/module-definition.ts index c82f15d05acad..c663589052f69 100644 --- a/packages/modules/file/src/module-definition.ts +++ b/packages/modules/file/src/module-definition.ts @@ -1,28 +1,11 @@ import { ModuleExports } from "@medusajs/types" import { FileModuleService } from "@services" import loadProviders from "./loaders/providers" -import * as ModuleServices from "@services" -import { ModulesSdkUtils } from "@medusajs/utils" -export const runMigrations = () => { - return Promise.resolve() -} -export const revertMigration = () => { - return Promise.resolve() -} - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: {}, - moduleRepositories: {}, - moduleServices: ModuleServices, -}) - -const loaders = [containerLoader, loadProviders] as any +const loaders = [loadProviders] as any const service = FileModuleService export const moduleDefinition: ModuleExports = { service, loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/fulfillment/src/index.ts b/packages/modules/fulfillment/src/index.ts index 2567a38d8ee04..5dc2ece1653d6 100644 --- a/packages/modules/fulfillment/src/index.ts +++ b/packages/modules/fulfillment/src/index.ts @@ -1,14 +1,7 @@ import { moduleDefinition } from "./module-definition" -import { initializeFactory, Modules } from "@medusajs/modules-sdk" export * from "./types" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.FULFILLMENT, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/fulfillment/src/module-definition.ts b/packages/modules/fulfillment/src/module-definition.ts index 4f130ce7dd21e..6c922130c2b2e 100644 --- a/packages/modules/fulfillment/src/module-definition.ts +++ b/packages/modules/fulfillment/src/module-definition.ts @@ -1,44 +1,11 @@ import { ModuleExports } from "@medusajs/types" -import * as ModuleServices from "@services" import { FulfillmentModuleService } from "@services" -import { Modules } from "@medusajs/modules-sdk" -import * as ModuleModels from "@models" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleRepositories from "@repositories" import loadProviders from "./loaders/providers" -const migrationScriptOptions = { - moduleName: Modules.FULFILLMENT, - models: ModuleModels, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.FULFILLMENT, - moduleModels: Object.values(ModuleModels), - migrationsPath: __dirname + "/migrations", -}) - const service = FulfillmentModuleService -const loaders = [containerLoader, connectionLoader, loadProviders] +const loaders = [loadProviders] export const moduleDefinition: ModuleExports = { service, loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/inventory-next/src/index.ts b/packages/modules/inventory-next/src/index.ts index eda56a705ed60..5fb9170fa0d91 100644 --- a/packages/modules/inventory-next/src/index.ts +++ b/packages/modules/inventory-next/src/index.ts @@ -1,14 +1,6 @@ -import { Modules, initializeFactory } from "@medusajs/modules-sdk" - import { moduleDefinition } from "./module-definition" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.INVENTORY, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/inventory-next/src/module-definition.ts b/packages/modules/inventory-next/src/module-definition.ts index 18fbbf404ab7f..81e4aefe7110e 100644 --- a/packages/modules/inventory-next/src/module-definition.ts +++ b/packages/modules/inventory-next/src/module-definition.ts @@ -1,44 +1,8 @@ -import * as InventoryModels from "@models" -import * as InventoryRepositories from "@repositories" -import * as InventoryServices from "@services" - import InventoryService from "./services/inventory" import { ModuleExports } from "@medusajs/types" -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" - -const migrationScriptOptions = { - moduleName: Modules.INVENTORY, - models: InventoryModels, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: InventoryModels, - moduleRepositories: InventoryRepositories, - moduleServices: InventoryServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.INVENTORY, - moduleModels: Object.values(InventoryModels), - migrationsPath: __dirname + "/migrations", -}) const service = InventoryService -const loaders = [containerLoader, connectionLoader] export const moduleDefinition: ModuleExports = { service, - loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/notification/src/index.ts b/packages/modules/notification/src/index.ts index 0bd8f8a93038f..5dc2ece1653d6 100644 --- a/packages/modules/notification/src/index.ts +++ b/packages/modules/notification/src/index.ts @@ -1,14 +1,7 @@ import { moduleDefinition } from "./module-definition" -import { initializeFactory, Modules } from "@medusajs/modules-sdk" export * from "./types" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.NOTIFICATION, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/notification/src/module-definition.ts b/packages/modules/notification/src/module-definition.ts index 8d43ebb923e52..4c067f82127eb 100644 --- a/packages/modules/notification/src/module-definition.ts +++ b/packages/modules/notification/src/module-definition.ts @@ -1,44 +1,11 @@ import { ModuleExports } from "@medusajs/types" -import * as ModuleServices from "@services" import { NotificationModuleService } from "@services" -import { Modules } from "@medusajs/modules-sdk" -import * as ModuleModels from "@models" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleRepositories from "@repositories" import loadProviders from "./loaders/providers" -const migrationScriptOptions = { - moduleName: Modules.NOTIFICATION, - models: ModuleModels, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.NOTIFICATION, - moduleModels: Object.values(ModuleModels), - migrationsPath: __dirname + "/migrations", -}) - const service = NotificationModuleService -const loaders = [containerLoader, connectionLoader, loadProviders] +const loaders = [loadProviders] export const moduleDefinition: ModuleExports = { service, loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/notification/src/repositories/index.ts b/packages/modules/notification/src/repositories/index.ts deleted file mode 100644 index 147c9cc259fa4..0000000000000 --- a/packages/modules/notification/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/order/src/index.ts b/packages/modules/order/src/index.ts index 9b5c17201b9a5..54d1b8590983a 100644 --- a/packages/modules/order/src/index.ts +++ b/packages/modules/order/src/index.ts @@ -1,14 +1,7 @@ -import { initializeFactory, Modules } from "@medusajs/modules-sdk" import { moduleDefinition } from "./module-definition" export * from "./models" export * from "./services" export * from "./types" -export const initialize = initializeFactory({ - moduleName: Modules.ORDER, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/order/src/module-definition.ts b/packages/modules/order/src/module-definition.ts index 3a0d42e70d1ef..eb7db999f6f4c 100644 --- a/packages/modules/order/src/module-definition.ts +++ b/packages/modules/order/src/module-definition.ts @@ -1,44 +1,8 @@ -import { Modules } from "@medusajs/modules-sdk" import { ModuleExports } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" import { OrderModuleService } from "@services" -const migrationScriptOptions = { - moduleName: Modules.ORDER, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.ORDER, - moduleModels: Object.values(Models), - migrationsPath: __dirname + "/migrations", -}) - const service = OrderModuleService -const loaders = [containerLoader, connectionLoader] as any export const moduleDefinition: ModuleExports = { service, - loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/payment/src/index.ts b/packages/modules/payment/src/index.ts index d6bb9fb737609..17fdedcd8ba9f 100644 --- a/packages/modules/payment/src/index.ts +++ b/packages/modules/payment/src/index.ts @@ -1,11 +1,5 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } -export * from "./initialize" export * from "./types" diff --git a/packages/modules/payment/src/initialize/index.ts b/packages/modules/payment/src/initialize/index.ts deleted file mode 100644 index c39148dee4e0b..0000000000000 --- a/packages/modules/payment/src/initialize/index.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { - IPaymentModuleService, - ModuleProvider, - ModulesSdkTypes, -} from "@medusajs/types" - -import { moduleDefinition } from "../module-definition" -import { InitializeModuleInjectableDependencies } from "../types" - -export const initialize = async ( - options?: - | ( - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration - ) & { providers: ModuleProvider[] }, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: Modules.PAYMENT, - defaultPath: MODULE_PACKAGE_NAMES[Modules.PAYMENT], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.PAYMENT] -} diff --git a/packages/modules/payment/src/loaders/connection.ts b/packages/modules/payment/src/loaders/connection.ts deleted file mode 100644 index 97eec362afa3b..0000000000000 --- a/packages/modules/payment/src/loaders/connection.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as PaymentModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(PaymentModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.PAYMENT, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/payment/src/loaders/container.ts b/packages/modules/payment/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/payment/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/payment/src/loaders/index.ts b/packages/modules/payment/src/loaders/index.ts index 9a4ba9d183269..4fff0c18cb39b 100644 --- a/packages/modules/payment/src/loaders/index.ts +++ b/packages/modules/payment/src/loaders/index.ts @@ -1,4 +1,2 @@ -export * from "./connection" -export * from "./container" export * from "./providers" export * from "./defaults" diff --git a/packages/modules/payment/src/module-definition.ts b/packages/modules/payment/src/module-definition.ts index 456ae8d80fbec..ae5058a1ccc5d 100644 --- a/packages/modules/payment/src/module-definition.ts +++ b/packages/modules/payment/src/module-definition.ts @@ -1,41 +1,13 @@ import { ModuleExports } from "@medusajs/types" import { PaymentModuleService } from "@services" - -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" import loadProviders from "./loaders/providers" import loadDefaults from "./loaders/defaults" -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" - -import * as PaymentModels from "@models" - -const migrationScriptOptions = { - moduleName: Modules.PAYMENT, - models: PaymentModels, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - const service = PaymentModuleService -const loaders = [ - loadContainer, - loadConnection, - loadProviders, - loadDefaults, -] as any +const loaders = [loadProviders, loadDefaults] as any export const moduleDefinition: ModuleExports = { service, loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/pricing/src/index.ts b/packages/modules/pricing/src/index.ts index 515ee01a9179f..be203865a144d 100644 --- a/packages/modules/pricing/src/index.ts +++ b/packages/modules/pricing/src/index.ts @@ -1,14 +1,7 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } -export * from "./initialize" -// TODO: remove export from models and services export * from "./models" export * from "./services" export * from "./types" diff --git a/packages/modules/pricing/src/initialize/index.ts b/packages/modules/pricing/src/initialize/index.ts deleted file mode 100644 index 56f10c2ce6a9d..0000000000000 --- a/packages/modules/pricing/src/initialize/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MODULE_PACKAGE_NAMES, - MedusaModule, - Modules, -} from "@medusajs/modules-sdk" -import { IPricingModuleService, ModulesSdkTypes } from "@medusajs/types" - -import { InitializeModuleInjectableDependencies } from "@types" -import { moduleDefinition } from "../module-definition" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const serviceKey = Modules.PRICING - - const loaded = await MedusaModule.bootstrap({ - moduleKey: serviceKey, - defaultPath: MODULE_PACKAGE_NAMES[Modules.PRICING], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[serviceKey] -} diff --git a/packages/modules/pricing/src/loaders/connection.ts b/packages/modules/pricing/src/loaders/connection.ts deleted file mode 100644 index 0573cb06b77b3..0000000000000 --- a/packages/modules/pricing/src/loaders/connection.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { InternalModuleDeclaration, LoaderOptions } from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as PricingModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(PricingModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: "pricing", - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/pricing/src/loaders/container.ts b/packages/modules/pricing/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/pricing/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/pricing/src/loaders/index.ts b/packages/modules/pricing/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/pricing/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/pricing/src/module-definition.ts b/packages/modules/pricing/src/module-definition.ts index b2cbdca76290a..f3d0ca848ec65 100644 --- a/packages/modules/pricing/src/module-definition.ts +++ b/packages/modules/pricing/src/module-definition.ts @@ -1,30 +1,8 @@ -import { Modules } from "@medusajs/modules-sdk" import { ModuleExports } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" import { PricingModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" - -const migrationScriptOptions = { - moduleName: Modules.PRICING, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) const service = PricingModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/product/src/index.ts b/packages/modules/product/src/index.ts index 515ee01a9179f..be203865a144d 100644 --- a/packages/modules/product/src/index.ts +++ b/packages/modules/product/src/index.ts @@ -1,14 +1,7 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } -export * from "./initialize" -// TODO: remove export from models and services export * from "./models" export * from "./services" export * from "./types" diff --git a/packages/modules/product/src/initialize/index.ts b/packages/modules/product/src/initialize/index.ts deleted file mode 100644 index efaadadc8099a..0000000000000 --- a/packages/modules/product/src/initialize/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { IProductModuleService, ModulesSdkTypes } from "@medusajs/types" - -import { InitializeModuleInjectableDependencies } from "@types" -import { moduleDefinition } from "../module-definition" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const serviceKey = Modules.PRODUCT - - const loaded = await MedusaModule.bootstrap({ - moduleKey: serviceKey, - defaultPath: MODULE_PACKAGE_NAMES[Modules.PRODUCT], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[serviceKey] -} diff --git a/packages/modules/product/src/loaders/connection.ts b/packages/modules/product/src/loaders/connection.ts deleted file mode 100644 index 6738c53b47e8a..0000000000000 --- a/packages/modules/product/src/loaders/connection.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { InternalModuleDeclaration, LoaderOptions } from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as ProductModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(ProductModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: "product", - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/product/src/loaders/container.ts b/packages/modules/product/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/product/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/product/src/loaders/index.ts b/packages/modules/product/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/product/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/product/src/module-definition.ts b/packages/modules/product/src/module-definition.ts index 177c5c0cb978c..6b4ba9b2a9150 100644 --- a/packages/modules/product/src/module-definition.ts +++ b/packages/modules/product/src/module-definition.ts @@ -1,31 +1,8 @@ import { ModuleExports } from "@medusajs/types" import { ProductModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" - -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ProductModels from "@models" - -const migrationScriptOptions = { - moduleName: Modules.PRODUCT, - models: ProductModels, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) const service = ProductModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/product/src/repositories/index.ts b/packages/modules/product/src/repositories/index.ts index 81c895352dda6..dae4cbfa37bec 100644 --- a/packages/modules/product/src/repositories/index.ts +++ b/packages/modules/product/src/repositories/index.ts @@ -1,3 +1,2 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" export { ProductRepository } from "./product" export { ProductCategoryRepository } from "./product-category" diff --git a/packages/modules/product/src/services/__fixtures__/product.ts b/packages/modules/product/src/services/__fixtures__/product.ts deleted file mode 100644 index 7a185e0e24982..0000000000000 --- a/packages/modules/product/src/services/__fixtures__/product.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { asValue } from "awilix" - -export const nonExistingProductId = "non-existing-id" - -export const productRepositoryMock = { - productRepository: asValue({ - find: jest.fn().mockImplementation(async ({ where: { id } }) => { - if (id === nonExistingProductId) { - return [] - } - - return [{}] - }), - findAndCount: jest.fn().mockResolvedValue([[], 0]), - getFreshManager: jest.fn().mockResolvedValue({}), - }), -} diff --git a/packages/modules/product/src/services/__tests__/index.ts b/packages/modules/product/src/services/__tests__/index.ts new file mode 100644 index 0000000000000..f2e589564e4d5 --- /dev/null +++ b/packages/modules/product/src/services/__tests__/index.ts @@ -0,0 +1 @@ +it("noop", () => {}) diff --git a/packages/modules/product/src/services/__tests__/product.spec.ts b/packages/modules/product/src/services/__tests__/product.spec.ts deleted file mode 100644 index 5d3a3e1707f61..0000000000000 --- a/packages/modules/product/src/services/__tests__/product.spec.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { - nonExistingProductId, - productRepositoryMock, -} from "../__fixtures__/product" -import { createMedusaContainer } from "@medusajs/utils" -import { asValue } from "awilix" -import ContainerLoader from "../../loaders/container" - -describe("Product service", function () { - let container - - beforeEach(async function () { - jest.clearAllMocks() - - container = createMedusaContainer() - container.register("manager", asValue({})) - - await ContainerLoader({ container }) - - container.register(productRepositoryMock) - }) - - it("should retrieve a product", async function () { - const productService = container.resolve("productService") - const productRepository = container.resolve("productRepository") - const productId = "existing-product" - - await productService.retrieve(productId) - - expect(productRepository.find).toHaveBeenCalledWith( - { - where: { - id: productId, - }, - options: { - fields: undefined, - limit: undefined, - offset: 0, - populate: [], - withDeleted: undefined, - }, - }, - expect.any(Object) - ) - }) - - it("should fail to retrieve a product", async function () { - const productService = container.resolve("productService") - const productRepository = container.resolve("productRepository") - - const err = await productService - .retrieve(nonExistingProductId) - .catch((e) => e) - - expect(productRepository.find).toHaveBeenCalledWith( - { - where: { - id: nonExistingProductId, - }, - options: { - fields: undefined, - limit: undefined, - offset: 0, - populate: [], - withDeleted: undefined, - }, - }, - expect.any(Object) - ) - - expect(err.message).toBe( - `Product with id: ${nonExistingProductId} was not found` - ) - }) - - it("should list products", async function () { - const productService = container.resolve("productService") - const productRepository = container.resolve("productRepository") - - const filters = {} - const config = { - relations: [], - } - - await productService.list(filters, config) - - expect(productRepository.find).toHaveBeenCalledWith( - { - where: {}, - options: { - fields: undefined, - limit: 15, - offset: 0, - orderBy: { - id: "ASC", - }, - populate: [], - withDeleted: undefined, - }, - }, - expect.any(Object) - ) - }) - - it("should list products with filters", async function () { - const productService = container.resolve("productService") - const productRepository = container.resolve("productRepository") - - const filters = { - tags: { - value: { - $in: ["test"], - }, - }, - } - const config = { - relations: [], - } - - await productService.list(filters, config) - - expect(productRepository.find).toHaveBeenCalledWith( - { - where: { - tags: { - value: { - $in: ["test"], - }, - }, - }, - options: { - fields: undefined, - limit: 15, - offset: 0, - orderBy: { - id: "ASC", - }, - populate: [], - withDeleted: undefined, - }, - }, - expect.any(Object) - ) - }) - - it("should list products with filters and relations", async function () { - const productService = container.resolve("productService") - const productRepository = container.resolve("productRepository") - - const filters = { - tags: { - value: { - $in: ["test"], - }, - }, - } - const config = { - relations: ["tags"], - } - - await productService.list(filters, config) - - expect(productRepository.find).toHaveBeenCalledWith( - { - where: { - tags: { - value: { - $in: ["test"], - }, - }, - }, - options: { - fields: undefined, - limit: 15, - offset: 0, - orderBy: { - id: "ASC", - }, - withDeleted: undefined, - populate: ["tags"], - }, - }, - expect.any(Object) - ) - }) - - it("should list and count the products with filters and relations", async function () { - const productService = container.resolve("productService") - const productRepository = container.resolve("productRepository") - - const filters = { - tags: { - value: { - $in: ["test"], - }, - }, - } - const config = { - relations: ["tags"], - } - - await productService.listAndCount(filters, config) - - expect(productRepository.findAndCount).toHaveBeenCalledWith( - { - where: { - tags: { - value: { - $in: ["test"], - }, - }, - }, - options: { - fields: undefined, - limit: 15, - offset: 0, - orderBy: { - id: "ASC", - }, - withDeleted: undefined, - populate: ["tags"], - }, - }, - expect.any(Object) - ) - }) -}) diff --git a/packages/modules/promotion/src/index.ts b/packages/modules/promotion/src/index.ts index d449f7354469a..dd414e1b19c57 100644 --- a/packages/modules/promotion/src/index.ts +++ b/packages/modules/promotion/src/index.ts @@ -1,10 +1,3 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } - -export * from "./initialize" diff --git a/packages/modules/promotion/src/initialize/index.ts b/packages/modules/promotion/src/initialize/index.ts deleted file mode 100644 index af913a211873d..0000000000000 --- a/packages/modules/promotion/src/initialize/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MODULE_PACKAGE_NAMES, - MedusaModule, - Modules, -} from "@medusajs/modules-sdk" -import { IPromotionModuleService, ModulesSdkTypes } from "@medusajs/types" -import { moduleDefinition } from "../module-definition" -import { InitializeModuleInjectableDependencies } from "../types" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: Modules.PROMOTION, - defaultPath: MODULE_PACKAGE_NAMES[Modules.PROMOTION], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.PROMOTION] -} diff --git a/packages/modules/promotion/src/loaders/connection.ts b/packages/modules/promotion/src/loaders/connection.ts deleted file mode 100644 index fbbff60e8739c..0000000000000 --- a/packages/modules/promotion/src/loaders/connection.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as PromotionModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(PromotionModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.PROMOTION, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/promotion/src/loaders/container.ts b/packages/modules/promotion/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/promotion/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/promotion/src/loaders/index.ts b/packages/modules/promotion/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/promotion/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/promotion/src/module-definition.ts b/packages/modules/promotion/src/module-definition.ts index d2e899cef86d3..d40766cf05c0c 100644 --- a/packages/modules/promotion/src/module-definition.ts +++ b/packages/modules/promotion/src/module-definition.ts @@ -1,30 +1,8 @@ -import { Modules } from "@medusajs/modules-sdk" import { ModuleExports } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as Models from "@models" import { PromotionModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" - -const migrationScriptOptions = { - moduleName: Modules.PROMOTION, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) const service = PromotionModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/region/src/index.ts b/packages/modules/region/src/index.ts index d449f7354469a..dd414e1b19c57 100644 --- a/packages/modules/region/src/index.ts +++ b/packages/modules/region/src/index.ts @@ -1,10 +1,3 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } - -export * from "./initialize" diff --git a/packages/modules/region/src/initialize/index.ts b/packages/modules/region/src/initialize/index.ts deleted file mode 100644 index 9cad528c589f3..0000000000000 --- a/packages/modules/region/src/initialize/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { IRegionModuleService, ModulesSdkTypes } from "@medusajs/types" -import { InitializeModuleInjectableDependencies } from "@types" - -import { moduleDefinition } from "../module-definition" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const serviceKey = Modules.REGION - - const loaded = await MedusaModule.bootstrap({ - moduleKey: serviceKey, - defaultPath: MODULE_PACKAGE_NAMES[Modules.REGION], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[serviceKey] -} diff --git a/packages/modules/region/src/loaders/connection.ts b/packages/modules/region/src/loaders/connection.ts deleted file mode 100644 index 5fc66f57e87c9..0000000000000 --- a/packages/modules/region/src/loaders/connection.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" - -import * as RegionModels from "@models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(RegionModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.REGION, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/region/src/loaders/container.ts b/packages/modules/region/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/region/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/region/src/loaders/index.ts b/packages/modules/region/src/loaders/index.ts index 1f4af39e22a72..f88fd30642151 100644 --- a/packages/modules/region/src/loaders/index.ts +++ b/packages/modules/region/src/loaders/index.ts @@ -1,4 +1 @@ -export * from "./connection" -export * from "./container" export * from "./defaults" - diff --git a/packages/modules/region/src/module-definition.ts b/packages/modules/region/src/module-definition.ts index 8fc1cafe54e47..644606677476a 100644 --- a/packages/modules/region/src/module-definition.ts +++ b/packages/modules/region/src/module-definition.ts @@ -1,32 +1,11 @@ import { ModuleExports } from "@medusajs/types" import { RegionModuleService } from "./services" - -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as RegionModels from "@models" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" import loadDefaults from "./loaders/defaults" -const migrationScriptOptions = { - moduleName: Modules.REGION, - models: RegionModels, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - const service = RegionModuleService -const loaders = [loadContainer, loadConnection, loadDefaults] as any +const loaders = [loadDefaults] export const moduleDefinition: ModuleExports = { service, loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts b/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts index b43d80ad885f1..70c3cc7c4ce88 100644 --- a/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts +++ b/packages/modules/sales-channel/integration-tests/__tests__/services/sales-channel-module.spec.ts @@ -2,242 +2,241 @@ import { SqlEntityManager } from "@mikro-orm/postgresql" import { ISalesChannelModuleService } from "@medusajs/types" -import { initialize } from "../../../src" - import { createSalesChannels } from "../../__fixtures__" -import { DB_URL, MikroOrmWrapper } from "../../utils" +import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils" +import { Modules } from "@medusajs/modules-sdk" jest.setTimeout(30000) -describe("Sales Channel Service", () => { - let service: ISalesChannelModuleService - let testManager: SqlEntityManager - let repositoryManager: SqlEntityManager - - beforeEach(async () => { - await MikroOrmWrapper.setupDatabase() - repositoryManager = await MikroOrmWrapper.forkManager() +moduleIntegrationTestRunner({ + moduleName: Modules.SALES_CHANNEL, + testSuite: ({ + MikroOrmWrapper, + medusaApp, + }: SuiteOptions) => { + let service: ISalesChannelModuleService - service = await initialize({ - database: { - clientUrl: DB_URL, - schema: process.env.MEDUSA_SALES_CHANNEL_DB_SCHEMA, - }, + beforeEach(() => { + service = medusaApp.modules[Modules.SALES_CHANNEL] }) - testManager = await MikroOrmWrapper.forkManager() - - await createSalesChannels(testManager) - }) + describe("Sales Channel Service", () => { + let testManager: SqlEntityManager + let repositoryManager: SqlEntityManager - afterEach(async () => { - await MikroOrmWrapper.clearDatabase() - }) + beforeEach(async () => { + repositoryManager = await MikroOrmWrapper.forkManager() + testManager = await MikroOrmWrapper.forkManager() - describe("create", () => { - it("should create a SalesChannel successfully", async () => { - const [created] = await service.create([ - { - name: "test", - description: "test", - }, - ]) - - const [channel] = await service.list({ - name: [created.name], + await createSalesChannels(testManager) }) - expect(channel.name).toEqual("test") - expect(channel.description).toEqual("test") - }) - }) + describe("create", () => { + it("should create a SalesChannel successfully", async () => { + const [created] = await service.create([ + { + name: "test", + description: "test", + }, + ]) + + const [channel] = await service.list({ + name: [created.name], + }) + + expect(channel.name).toEqual("test") + expect(channel.description).toEqual("test") + }) + }) - describe("retrieve", () => { - const id = "channel-1" + describe("retrieve", () => { + const id = "channel-1" - it("should return SalesChannel for the given id", async () => { - const result = await service.retrieve(id) + it("should return SalesChannel for the given id", async () => { + const result = await service.retrieve(id) - expect(result).toEqual( - expect.objectContaining({ - id, + expect(result).toEqual( + expect.objectContaining({ + id, + }) + ) }) - ) - }) - - it("should throw an error when SalesChannelId with id does not exist", async () => { - let error - try { - await service.retrieve("does-not-exist") - } catch (e) { - error = e - } + it("should throw an error when SalesChannelId with id does not exist", async () => { + let error - expect(error.message).toEqual( - "SalesChannel with id: does-not-exist was not found" - ) - }) - }) - - describe("update", () => { - const id = "channel-2" + try { + await service.retrieve("does-not-exist") + } catch (e) { + error = e + } - it("should update the name of the SalesChannel successfully", async () => { - await service.update(id, { - name: "Update name 2", - is_disabled: true, + expect(error.message).toEqual( + "SalesChannel with id: does-not-exist was not found" + ) + }) }) - const channel = await service.retrieve(id) + describe("update", () => { + const id = "channel-2" - expect(channel.name).toEqual("Update name 2") - expect(channel.is_disabled).toEqual(true) - }) + it("should update the name of the SalesChannel successfully", async () => { + await service.update(id, { + name: "Update name 2", + is_disabled: true, + }) - it("should throw an error when a id does not exist", async () => { - let error + const channel = await service.retrieve(id) - try { - await service.update("does-not-exist", { - name: "does-not-exist", + expect(channel.name).toEqual("Update name 2") + expect(channel.is_disabled).toEqual(true) }) - } catch (e) { - error = e - } - expect(error.message).toEqual( - 'SalesChannel with id "does-not-exist" not found' - ) - }) - }) - - describe("list", () => { - it("should return a list of SalesChannels", async () => { - const result = await service.list() - - expect(result).toEqual([ - expect.objectContaining({ - id: "channel-1", - }), - expect.objectContaining({ - id: "channel-2", - }), - expect.objectContaining({ - id: "channel-3", - }), - ]) - }) + it("should throw an error when a id does not exist", async () => { + let error + + try { + await service.update("does-not-exist", { + name: "does-not-exist", + }) + } catch (e) { + error = e + } - it("should list SalesChannels by name", async () => { - const result = await service.list({ - name: ["Channel 2", "Channel 3"], + expect(error.message).toEqual( + 'SalesChannel with id "does-not-exist" not found' + ) + }) }) - expect(result).toEqual([ - expect.objectContaining({ - id: "channel-2", - }), - expect.objectContaining({ - id: "channel-3", - }), - ]) - }) - }) - - describe("listAndCount", () => { - it("should return sales channels and count", async () => { - const [result, count] = await service.listAndCount() - - expect(count).toEqual(3) - expect(result).toEqual([ - expect.objectContaining({ - id: "channel-1", - }), - expect.objectContaining({ - id: "channel-2", - }), - expect.objectContaining({ - id: "channel-3", - }), - ]) - }) + describe("list", () => { + it("should return a list of SalesChannels", async () => { + const result = await service.list() + + expect(result).toEqual([ + expect.objectContaining({ + id: "channel-1", + }), + expect.objectContaining({ + id: "channel-2", + }), + expect.objectContaining({ + id: "channel-3", + }), + ]) + }) - it("should return sales channels and count when filtered", async () => { - const [result, count] = await service.listAndCount({ - id: ["channel-2"], + it("should list SalesChannels by name", async () => { + const result = await service.list({ + name: ["Channel 2", "Channel 3"], + }) + + expect(result).toEqual([ + expect.objectContaining({ + id: "channel-2", + }), + expect.objectContaining({ + id: "channel-3", + }), + ]) + }) }) - expect(count).toEqual(1) - expect(result).toEqual([ - expect.objectContaining({ - id: "channel-2", - }), - ]) - }) + describe("listAndCount", () => { + it("should return sales channels and count", async () => { + const [result, count] = await service.listAndCount() + + expect(count).toEqual(3) + expect(result).toEqual([ + expect.objectContaining({ + id: "channel-1", + }), + expect.objectContaining({ + id: "channel-2", + }), + expect.objectContaining({ + id: "channel-3", + }), + ]) + }) - it("should return sales channels and count when using skip and take", async () => { - const [results, count] = await service.listAndCount( - {}, - { skip: 1, take: 1 } - ) - - expect(count).toEqual(3) - expect(results).toEqual([ - expect.objectContaining({ - id: "channel-2", - }), - ]) - }) + it("should return sales channels and count when filtered", async () => { + const [result, count] = await service.listAndCount({ + id: ["channel-2"], + }) + + expect(count).toEqual(1) + expect(result).toEqual([ + expect.objectContaining({ + id: "channel-2", + }), + ]) + }) - it("should return requested fields", async () => { - const [result, count] = await service.listAndCount( - {}, - { - take: 1, - select: ["id", "name"], - } - ) - - const serialized = JSON.parse(JSON.stringify(result)) - - expect(count).toEqual(3) - expect(serialized).toEqual([ - { - id: "channel-1", - name: "Channel 1", - }, - ]) - }) + it("should return sales channels and count when using skip and take", async () => { + const [results, count] = await service.listAndCount( + {}, + { skip: 1, take: 1 } + ) + + expect(count).toEqual(3) + expect(results).toEqual([ + expect.objectContaining({ + id: "channel-2", + }), + ]) + }) - it("should filter disabled channels", async () => { - const [result, count] = await service.listAndCount( - { is_disabled: true }, - { select: ["id"] } - ) + it("should return requested fields", async () => { + const [result, count] = await service.listAndCount( + {}, + { + take: 1, + select: ["id", "name"], + } + ) + + const serialized = JSON.parse(JSON.stringify(result)) + + expect(count).toEqual(3) + expect(serialized).toEqual([ + { + id: "channel-1", + name: "Channel 1", + }, + ]) + }) - const serialized = JSON.parse(JSON.stringify(result)) + it("should filter disabled channels", async () => { + const [result, count] = await service.listAndCount( + { is_disabled: true }, + { select: ["id"] } + ) - expect(count).toEqual(1) - expect(serialized).toEqual([ - { - id: "channel-3", - }, - ]) - }) - }) + const serialized = JSON.parse(JSON.stringify(result)) + + expect(count).toEqual(1) + expect(serialized).toEqual([ + { + id: "channel-3", + }, + ]) + }) + }) - describe("delete", () => { - const id = "channel-2" + describe("delete", () => { + const id = "channel-2" - it("should delete the SalesChannel given an id successfully", async () => { - await service.delete([id]) + it("should delete the SalesChannel given an id successfully", async () => { + await service.delete([id]) - const result = await service.list({ - id: [id], - }) + const result = await service.list({ + id: [id], + }) - expect(result).toHaveLength(0) + expect(result).toHaveLength(0) + }) + }) }) - }) + }, }) diff --git a/packages/modules/sales-channel/src/index.ts b/packages/modules/sales-channel/src/index.ts index cde39437b10bb..d464b550c03f4 100644 --- a/packages/modules/sales-channel/src/index.ts +++ b/packages/modules/sales-channel/src/index.ts @@ -1,27 +1,7 @@ -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" - -import * as SalesChannelModels from "@models" - import { moduleDefinition } from "./module-definition" export default moduleDefinition -const migrationScriptOptions = { - moduleName: Modules.SALES_CHANNEL, - models: SalesChannelModels, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -export * from "./initialize" export * from "./types" -export * from "./loaders" export * from "./models" export * from "./services" diff --git a/packages/modules/sales-channel/src/initialize/index.ts b/packages/modules/sales-channel/src/initialize/index.ts deleted file mode 100644 index 74a84a8116a6f..0000000000000 --- a/packages/modules/sales-channel/src/initialize/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MedusaModule, - MODULE_PACKAGE_NAMES, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes, ISalesChannelModuleService } from "@medusajs/types" -import { InitializeModuleInjectableDependencies } from "@types" - -import { moduleDefinition } from "../module-definition" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const serviceKey = Modules.SALES_CHANNEL - - const loaded = await MedusaModule.bootstrap({ - moduleKey: serviceKey, - defaultPath: MODULE_PACKAGE_NAMES[Modules.SALES_CHANNEL], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[serviceKey] -} diff --git a/packages/modules/sales-channel/src/loaders/connection.ts b/packages/modules/sales-channel/src/loaders/connection.ts deleted file mode 100644 index fc88330aa2b30..0000000000000 --- a/packages/modules/sales-channel/src/loaders/connection.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" - -import * as SalesChannelModels from "@models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values( - SalesChannelModels - ) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.SALES_CHANNEL, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/sales-channel/src/loaders/container.ts b/packages/modules/sales-channel/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/sales-channel/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/sales-channel/src/loaders/index.ts b/packages/modules/sales-channel/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/sales-channel/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/sales-channel/src/module-definition.ts b/packages/modules/sales-channel/src/module-definition.ts index ea646d3f28183..55251db0415fc 100644 --- a/packages/modules/sales-channel/src/module-definition.ts +++ b/packages/modules/sales-channel/src/module-definition.ts @@ -1,13 +1,8 @@ import { ModuleExports } from "@medusajs/types" import { SalesChannelModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" - const service = SalesChannelModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, } diff --git a/packages/modules/sales-channel/src/repositories/index.ts b/packages/modules/sales-channel/src/repositories/index.ts deleted file mode 100644 index 147c9cc259fa4..0000000000000 --- a/packages/modules/sales-channel/src/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils" diff --git a/packages/modules/sales-channel/src/services/__fixtures__/sales-channel.ts b/packages/modules/sales-channel/src/services/__fixtures__/sales-channel.ts deleted file mode 100644 index 4549d004b4080..0000000000000 --- a/packages/modules/sales-channel/src/services/__fixtures__/sales-channel.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { asValue } from "awilix" - -export const salesChannelRepositoryMock = { - salesChannelRepository: asValue({ - find: jest.fn().mockImplementation(async ({ where: { code } }) => { - return [{}] - }), - findAndCount: jest.fn().mockResolvedValue([[], 0]), - getFreshManager: jest.fn().mockResolvedValue({}), - }), -} diff --git a/packages/modules/sales-channel/src/services/__tests__/index.ts b/packages/modules/sales-channel/src/services/__tests__/index.ts new file mode 100644 index 0000000000000..f2e589564e4d5 --- /dev/null +++ b/packages/modules/sales-channel/src/services/__tests__/index.ts @@ -0,0 +1 @@ +it("noop", () => {}) diff --git a/packages/modules/sales-channel/src/services/__tests__/sales-channle.spec.ts b/packages/modules/sales-channel/src/services/__tests__/sales-channle.spec.ts deleted file mode 100644 index 22ec375ba1632..0000000000000 --- a/packages/modules/sales-channel/src/services/__tests__/sales-channle.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { createMedusaContainer } from "@medusajs/utils" -import { asValue } from "awilix" -import ContainerLoader from "../../loaders/container" -import { salesChannelRepositoryMock } from "../__fixtures__/sales-channel" - -describe("Sales channel service", function () { - let container - - beforeEach(async function () { - jest.clearAllMocks() - - container = createMedusaContainer() - container.register("manager", asValue({})) - - await ContainerLoader({ container }) - - container.register(salesChannelRepositoryMock) - }) - - it("should list sales channels with filters and relations", async function () { - const salesChannelRepository = container.resolve("salesChannelRepository") - const salesChannelService = container.resolve("salesChannelService") - - const config = { - select: ["id", "name"], - } - - await salesChannelService.list({}, config) - - expect(salesChannelRepository.find).toHaveBeenCalledWith( - { - where: {}, - options: { - fields: ["id", "name"], - limit: 15, - offset: 0, - orderBy: { - id: "ASC", - }, - withDeleted: undefined, - populate: [], - }, - }, - expect.any(Object) - ) - }) -}) diff --git a/packages/modules/stock-location-next/src/index.ts b/packages/modules/stock-location-next/src/index.ts index f9bdcf3c9e6a0..5fb9170fa0d91 100644 --- a/packages/modules/stock-location-next/src/index.ts +++ b/packages/modules/stock-location-next/src/index.ts @@ -1,14 +1,6 @@ -import { Modules, initializeFactory } from "@medusajs/modules-sdk" - import { moduleDefinition } from "./module-definition" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.STOCK_LOCATION, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/stock-location-next/src/module-definition.ts b/packages/modules/stock-location-next/src/module-definition.ts index aacce844a97df..028bc7f98918f 100644 --- a/packages/modules/stock-location-next/src/module-definition.ts +++ b/packages/modules/stock-location-next/src/module-definition.ts @@ -1,44 +1,8 @@ -import * as StockLocationModels from "@models" -import * as StockLocationRepostiories from "@repositories" -import * as StockLocationServices from "@services" - -import { Modules } from "@medusajs/modules-sdk" -import { ModuleExports } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" import { StockLocationModuleService } from "@services" - -const migrationScriptOptions = { - moduleName: Modules.STOCK_LOCATION, - models: StockLocationModels, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: StockLocationModels, - moduleRepositories: StockLocationRepostiories, - moduleServices: StockLocationServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.STOCK_LOCATION, - moduleModels: Object.values(StockLocationModels), - migrationsPath: __dirname + "/migrations", -}) +import { ModuleExports } from "@medusajs/types" const service = StockLocationModuleService -const loaders = [containerLoader, connectionLoader] export const moduleDefinition: ModuleExports = { service, - loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/store/src/index.ts b/packages/modules/store/src/index.ts index 7b774fa27804f..5dc2ece1653d6 100644 --- a/packages/modules/store/src/index.ts +++ b/packages/modules/store/src/index.ts @@ -1,14 +1,7 @@ import { moduleDefinition } from "./module-definition" -import { initializeFactory, Modules } from "@medusajs/modules-sdk" export * from "./types" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.STORE, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/store/src/module-definition.ts b/packages/modules/store/src/module-definition.ts index 6f9761f73e0d7..462ef1004dfdb 100644 --- a/packages/modules/store/src/module-definition.ts +++ b/packages/modules/store/src/module-definition.ts @@ -1,44 +1,8 @@ import { ModuleExports } from "@medusajs/types" -import * as ModuleServices from "@services" import { StoreModuleService } from "@services" -import { Modules } from "@medusajs/modules-sdk" -import * as Models from "@models" -import * as ModuleModels from "@models" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleRepositories from "@repositories" - -const migrationScriptOptions = { - moduleName: Modules.STORE, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.STORE, - moduleModels: Object.values(Models), - migrationsPath: __dirname + "/migrations", -}) const service = StoreModuleService -const loaders = [containerLoader, connectionLoader] as any export const moduleDefinition: ModuleExports = { service, - loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/tax/src/index.ts b/packages/modules/tax/src/index.ts index 4946d101141c9..5fb9170fa0d91 100644 --- a/packages/modules/tax/src/index.ts +++ b/packages/modules/tax/src/index.ts @@ -1,13 +1,6 @@ -import { initializeFactory, Modules } from "@medusajs/modules-sdk" import { moduleDefinition } from "./module-definition" export * from "./models" export * from "./services" -export const initialize = initializeFactory({ - moduleName: Modules.TAX, - moduleDefinition, -}) -export const runMigrations = moduleDefinition.runMigrations -export const revertMigration = moduleDefinition.revertMigration export default moduleDefinition diff --git a/packages/modules/tax/src/module-definition.ts b/packages/modules/tax/src/module-definition.ts index 3f3375578a7d3..2744a70ef0928 100644 --- a/packages/modules/tax/src/module-definition.ts +++ b/packages/modules/tax/src/module-definition.ts @@ -1,44 +1,11 @@ -import { MikroOrmBaseRepository, ModulesSdkUtils } from "@medusajs/utils" -import { Modules } from "@medusajs/modules-sdk" import { ModuleExports } from "@medusajs/types" -import * as Models from "@models" -import * as ModuleModels from "@models" -import * as ModuleServices from "@services" import { TaxModuleService } from "@services" import loadProviders from "./loaders/providers" -const migrationScriptOptions = { - moduleName: Modules.TAX, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) - -const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: { BaseRepository: MikroOrmBaseRepository }, - moduleServices: ModuleServices, -}) - -const connectionLoader = ModulesSdkUtils.mikroOrmConnectionLoaderFactory({ - moduleName: Modules.TAX, - moduleModels: Object.values(Models), - migrationsPath: __dirname + "/migrations", -}) - const service = TaxModuleService -const loaders = [containerLoader, connectionLoader, loadProviders] as any +const loaders = [loadProviders] export const moduleDefinition: ModuleExports = { service, loaders, - revertMigration, - runMigrations, } diff --git a/packages/modules/user/src/index.ts b/packages/modules/user/src/index.ts index 98c26a5e9e4d7..dd414e1b19c57 100644 --- a/packages/modules/user/src/index.ts +++ b/packages/modules/user/src/index.ts @@ -1,11 +1,3 @@ -import { - moduleDefinition, - revertMigration, - runMigrations, -} from "./module-definition" +import { moduleDefinition } from "./module-definition" export default moduleDefinition -export { revertMigration, runMigrations } - -export * from "./initialize" -export * from "./loaders" diff --git a/packages/modules/user/src/initialize/index.ts b/packages/modules/user/src/initialize/index.ts deleted file mode 100644 index f9fddbaf44bf1..0000000000000 --- a/packages/modules/user/src/initialize/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MODULE_PACKAGE_NAMES, - MedusaModule, - Modules, -} from "@medusajs/modules-sdk" -import { IUserModuleService, ModulesSdkTypes } from "@medusajs/types" - -import { InitializeModuleInjectableDependencies } from "../types" -import { moduleDefinition } from "../module-definition" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleBootstrapDeclaration - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = await MedusaModule.bootstrap({ - moduleKey: Modules.USER, - defaultPath: MODULE_PACKAGE_NAMES[Modules.USER], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.USER] -} diff --git a/packages/modules/user/src/loaders/connection.ts b/packages/modules/user/src/loaders/connection.ts deleted file mode 100644 index da26fa35a8205..0000000000000 --- a/packages/modules/user/src/loaders/connection.ts +++ /dev/null @@ -1,36 +0,0 @@ -import * as UserModels from "../models" - -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" - -import { EntitySchema } from "@mikro-orm/core" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values(UserModels) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.USER, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/user/src/loaders/container.ts b/packages/modules/user/src/loaders/container.ts deleted file mode 100644 index 28ea110f2dbd1..0000000000000 --- a/packages/modules/user/src/loaders/container.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleRepositories from "@repositories" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleRepositories: ModuleRepositories, - moduleServices: ModuleServices, -}) diff --git a/packages/modules/user/src/loaders/index.ts b/packages/modules/user/src/loaders/index.ts deleted file mode 100644 index 3614963d8c21e..0000000000000 --- a/packages/modules/user/src/loaders/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./connection" -export * from "./container" diff --git a/packages/modules/user/src/module-definition.ts b/packages/modules/user/src/module-definition.ts index 01960256fbed2..74a1931795b3d 100644 --- a/packages/modules/user/src/module-definition.ts +++ b/packages/modules/user/src/module-definition.ts @@ -1,31 +1,8 @@ -import * as Models from "@models" - import { UserModuleService } from "@services" import { ModuleExports } from "@medusajs/types" -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" - -const migrationScriptOptions = { - moduleName: Modules.USER, - models: Models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) const service = UserModuleService -const loaders = [loadContainer, loadConnection] as any export const moduleDefinition: ModuleExports = { service, - loaders, - runMigrations, - revertMigration, } diff --git a/packages/modules/workflow-engine-inmemory/src/index.ts b/packages/modules/workflow-engine-inmemory/src/index.ts index 78040405651bb..7aa317c3f4a0f 100644 --- a/packages/modules/workflow-engine-inmemory/src/index.ts +++ b/packages/modules/workflow-engine-inmemory/src/index.ts @@ -1,22 +1,5 @@ -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as models from "@models" import { moduleDefinition } from "./module-definition" export default moduleDefinition -const migrationScriptOptions = { - moduleName: Modules.WORKFLOW_ENGINE, - models: models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -export * from "./initialize" export * from "./loaders" diff --git a/packages/modules/workflow-engine-inmemory/src/initialize/index.ts b/packages/modules/workflow-engine-inmemory/src/initialize/index.ts deleted file mode 100644 index dafe1ddc8f328..0000000000000 --- a/packages/modules/workflow-engine-inmemory/src/initialize/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MODULE_PACKAGE_NAMES, - MedusaModule, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { IWorkflowEngineService } from "@medusajs/workflows-sdk" -import { moduleDefinition } from "../module-definition" -import { InitializeModuleInjectableDependencies } from "../types" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = - // eslint-disable-next-line max-len - await MedusaModule.bootstrap({ - moduleKey: Modules.WORKFLOW_ENGINE, - defaultPath: MODULE_PACKAGE_NAMES[Modules.WORKFLOW_ENGINE], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.WORKFLOW_ENGINE] -} diff --git a/packages/modules/workflow-engine-inmemory/src/loaders/connection.ts b/packages/modules/workflow-engine-inmemory/src/loaders/connection.ts deleted file mode 100644 index 580e05e95cef9..0000000000000 --- a/packages/modules/workflow-engine-inmemory/src/loaders/connection.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as WorkflowOrchestratorModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values( - WorkflowOrchestratorModels - ) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.WORKFLOW_ENGINE, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/workflow-engine-inmemory/src/loaders/container.ts b/packages/modules/workflow-engine-inmemory/src/loaders/container.ts deleted file mode 100644 index 9a0c5553b490c..0000000000000 --- a/packages/modules/workflow-engine-inmemory/src/loaders/container.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { MikroOrmBaseRepository, ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleServices: ModuleServices, - moduleRepositories: { BaseRepository: MikroOrmBaseRepository }, -}) diff --git a/packages/modules/workflow-engine-inmemory/src/loaders/index.ts b/packages/modules/workflow-engine-inmemory/src/loaders/index.ts index 5445bc7412131..3eeaeaa90c5ca 100644 --- a/packages/modules/workflow-engine-inmemory/src/loaders/index.ts +++ b/packages/modules/workflow-engine-inmemory/src/loaders/index.ts @@ -1,3 +1 @@ -export * from "./connection" -export * from "./container" export * from "./utils" diff --git a/packages/modules/workflow-engine-inmemory/src/module-definition.ts b/packages/modules/workflow-engine-inmemory/src/module-definition.ts index b86c23807bc40..7aa8cdf56875d 100644 --- a/packages/modules/workflow-engine-inmemory/src/module-definition.ts +++ b/packages/modules/workflow-engine-inmemory/src/module-definition.ts @@ -1,11 +1,9 @@ import { ModuleExports } from "@medusajs/types" import { WorkflowsModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" import loadUtils from "./loaders/utils" const service = WorkflowsModuleService -const loaders = [loadContainer, loadConnection, loadUtils] as any +const loaders = [loadUtils] export const moduleDefinition: ModuleExports = { service, diff --git a/packages/modules/workflow-engine-redis/src/index.ts b/packages/modules/workflow-engine-redis/src/index.ts index 78040405651bb..7aa317c3f4a0f 100644 --- a/packages/modules/workflow-engine-redis/src/index.ts +++ b/packages/modules/workflow-engine-redis/src/index.ts @@ -1,22 +1,5 @@ -import { Modules } from "@medusajs/modules-sdk" -import { ModulesSdkUtils } from "@medusajs/utils" -import * as models from "@models" import { moduleDefinition } from "./module-definition" export default moduleDefinition -const migrationScriptOptions = { - moduleName: Modules.WORKFLOW_ENGINE, - models: models, - pathToMigrations: __dirname + "/migrations", -} - -export const runMigrations = ModulesSdkUtils.buildMigrationScript( - migrationScriptOptions -) -export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript( - migrationScriptOptions -) - -export * from "./initialize" export * from "./loaders" diff --git a/packages/modules/workflow-engine-redis/src/initialize/index.ts b/packages/modules/workflow-engine-redis/src/initialize/index.ts deleted file mode 100644 index b548387c5755f..0000000000000 --- a/packages/modules/workflow-engine-redis/src/initialize/index.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - ExternalModuleDeclaration, - InternalModuleDeclaration, - MODULE_PACKAGE_NAMES, - MedusaModule, - Modules, -} from "@medusajs/modules-sdk" - -import { ModulesSdkTypes } from "@medusajs/types" -import { IWorkflowEngineService } from "@medusajs/workflows-sdk" -import { moduleDefinition } from "../module-definition" -import { InitializeModuleInjectableDependencies } from "../types" - -export const initialize = async ( - options?: - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - | ExternalModuleDeclaration - | InternalModuleDeclaration, - injectedDependencies?: InitializeModuleInjectableDependencies -): Promise => { - const loaded = - // eslint-disable-next-line max-len - await MedusaModule.bootstrap({ - moduleKey: Modules.WORKFLOW_ENGINE, - defaultPath: MODULE_PACKAGE_NAMES[Modules.WORKFLOW_ENGINE], - declaration: options as - | InternalModuleDeclaration - | ExternalModuleDeclaration, - injectedDependencies, - moduleExports: moduleDefinition, - }) - - return loaded[Modules.WORKFLOW_ENGINE] -} diff --git a/packages/modules/workflow-engine-redis/src/loaders/connection.ts b/packages/modules/workflow-engine-redis/src/loaders/connection.ts deleted file mode 100644 index 580e05e95cef9..0000000000000 --- a/packages/modules/workflow-engine-redis/src/loaders/connection.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { - InternalModuleDeclaration, - LoaderOptions, - Modules, -} from "@medusajs/modules-sdk" -import { ModulesSdkTypes } from "@medusajs/types" -import { ModulesSdkUtils } from "@medusajs/utils" -import { EntitySchema } from "@mikro-orm/core" -import * as WorkflowOrchestratorModels from "../models" - -export default async ( - { - options, - container, - logger, - }: LoaderOptions< - | ModulesSdkTypes.ModuleServiceInitializeOptions - | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions - >, - moduleDeclaration?: InternalModuleDeclaration -): Promise => { - const entities = Object.values( - WorkflowOrchestratorModels - ) as unknown as EntitySchema[] - const pathToMigrations = __dirname + "/../migrations" - - await ModulesSdkUtils.mikroOrmConnectionLoader({ - moduleName: Modules.WORKFLOW_ENGINE, - entities, - container, - options, - moduleDeclaration, - logger, - pathToMigrations, - }) -} diff --git a/packages/modules/workflow-engine-redis/src/loaders/container.ts b/packages/modules/workflow-engine-redis/src/loaders/container.ts deleted file mode 100644 index 9a0c5553b490c..0000000000000 --- a/packages/modules/workflow-engine-redis/src/loaders/container.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { MikroOrmBaseRepository, ModulesSdkUtils } from "@medusajs/utils" -import * as ModuleModels from "@models" -import * as ModuleServices from "@services" - -export default ModulesSdkUtils.moduleContainerLoaderFactory({ - moduleModels: ModuleModels, - moduleServices: ModuleServices, - moduleRepositories: { BaseRepository: MikroOrmBaseRepository }, -}) diff --git a/packages/modules/workflow-engine-redis/src/loaders/index.ts b/packages/modules/workflow-engine-redis/src/loaders/index.ts index 8b66bc0be45ec..3b25a131a2461 100644 --- a/packages/modules/workflow-engine-redis/src/loaders/index.ts +++ b/packages/modules/workflow-engine-redis/src/loaders/index.ts @@ -1,4 +1,2 @@ -export * from "./connection" -export * from "./container" export * from "./redis" export * from "./utils" diff --git a/packages/modules/workflow-engine-redis/src/module-definition.ts b/packages/modules/workflow-engine-redis/src/module-definition.ts index 0a3d33f5806d4..1f6edab928a2a 100644 --- a/packages/modules/workflow-engine-redis/src/module-definition.ts +++ b/packages/modules/workflow-engine-redis/src/module-definition.ts @@ -1,17 +1,10 @@ import { ModuleExports } from "@medusajs/types" import { WorkflowsModuleService } from "@services" -import loadConnection from "./loaders/connection" -import loadContainer from "./loaders/container" import redisConnection from "./loaders/redis" import loadUtils from "./loaders/utils" const service = WorkflowsModuleService -const loaders = [ - loadContainer, - loadConnection, - loadUtils, - redisConnection, -] as any +const loaders = [loadUtils, redisConnection] as any export const moduleDefinition: ModuleExports = { service, diff --git a/www/apps/api-reference/.env.sample b/www/apps/api-reference/.env.sample index 28fb95f69d187..8431f8b0f80a2 100644 --- a/www/apps/api-reference/.env.sample +++ b/www/apps/api-reference/.env.sample @@ -15,4 +15,5 @@ ANALYZE_BUNDLE= NEXT_PUBLIC_AI_ASSISTANT_URL= NEXT_PUBLIC_AI_WEBSITE_ID= NEXT_PUBLIC_AI_API_ASSISTANT_RECAPTCHA_SITE_KEY= -NEXT_PUBLIC_VERSIONING= \ No newline at end of file +NEXT_PUBLIC_VERSIONING= +NEXT_PUBLIC_SHOW_V2= \ No newline at end of file diff --git a/www/apps/api-reference/components/Navbar/index.tsx b/www/apps/api-reference/components/Navbar/index.tsx index af9c540220e4a..c910b23ac0ef8 100644 --- a/www/apps/api-reference/components/Navbar/index.tsx +++ b/www/apps/api-reference/components/Navbar/index.tsx @@ -24,6 +24,7 @@ const Navbar = () => { getNavbarItems({ basePath: config.baseUrl, activePath: pathname, + version: process.env.NEXT_PUBLIC_SHOW_V2 ? "v1" : "legacy", }), [pathname] ) diff --git a/www/apps/api-reference/config/index.ts b/www/apps/api-reference/config/index.ts index 9f82fc084ac76..f0bf29ba1009c 100644 --- a/www/apps/api-reference/config/index.ts +++ b/www/apps/api-reference/config/index.ts @@ -1,5 +1,5 @@ import { DocsConfig } from "types" -import { mobileSidebarItems } from "docs-ui" +import { mobileSidebarItemsV1, legacyMobileSidebarItems } from "docs-ui" export const config: DocsConfig = { baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000", @@ -13,6 +13,6 @@ export const config: DocsConfig = { }, ], bottom: [], - mobile: mobileSidebarItems, + mobile: process.env.NEXT_PUBLIC_SHOW_V2 ? mobileSidebarItemsV1 : legacyMobileSidebarItems, }, } diff --git a/www/apps/api-reference/next.config.mjs b/www/apps/api-reference/next.config.mjs index 2f3135a8d49c0..a91e74502e293 100644 --- a/www/apps/api-reference/next.config.mjs +++ b/www/apps/api-reference/next.config.mjs @@ -4,30 +4,44 @@ import bundleAnalyzer from "@next/bundle-analyzer" /** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { - return { - fallback: [ + const fallbacks = [ + { + source: "/ui", + destination: `${process.env.NEXT_PUBLIC_UI_URL}/ui`, + }, + { + source: "/ui/:path*", + destination: `${process.env.NEXT_PUBLIC_UI_URL}/ui/:path*`, + }, + { + source: "/:path*", + destination: `${process.env.NEXT_PUBLIC_DOCS_URL}/:path*`, + }, + ] + + if (process.env.NEXT_PUBLIC_SHOW_V2) { + fallbacks.push( { - source: "/ui", - destination: `${process.env.NEXT_PUBLIC_UI_URL}/ui`, + source: "/v2/resources", + destination: `${process.env.NEXT_PUBLIC_DOCS_V2_URL}/v2/resources`, }, { - source: "/ui/:path*", - destination: `${process.env.NEXT_PUBLIC_UI_URL}/ui/:path*`, + source: "/v2/resources/:path*", + destination: `${process.env.NEXT_PUBLIC_DOCS_V2_URL}/v2/resources/:path*`, }, - // TODO uncomment for v2 - // { - // source: "/v2", - // destination: `${process.env.NEXT_PUBLIC_DOCS_V2_URL}/resources`, - // }, - // { - // source: "/v2/:path*", - // destination: `${process.env.NEXT_PUBLIC_DOCS_V2_URL}/resources/:path*`, - // }, { - source: "/:path*", - destination: `${process.env.NEXT_PUBLIC_DOCS_URL}/:path*`, + source: "/v2", + destination: `${process.env.NEXT_PUBLIC_DOCS_V2_URL}/v2`, }, - ], + { + source: "/v2/:path*", + destination: `${process.env.NEXT_PUBLIC_DOCS_V2_URL}/v2/:path*`, + } + ) + } + + return { + fallback: fallbacks, } }, webpack: (config) => { diff --git a/www/apps/api-reference/providers/search.tsx b/www/apps/api-reference/providers/search.tsx index 354d724f245d7..1c3a2c20e74c2 100644 --- a/www/apps/api-reference/providers/search.tsx +++ b/www/apps/api-reference/providers/search.tsx @@ -5,7 +5,7 @@ import { SearchProvider as UiSearchProvider, AiAssistantCommandIcon, AiAssistantProvider, - searchFilters, + searchFiltersV1, } from "docs-ui" import { config } from "../config" @@ -53,7 +53,7 @@ const SearchProvider = ({ children }: SearchProviderProps) => { checkInternalPattern: new RegExp( `^${config.baseUrl}/api/(admin|store)` ), - filterOptions: searchFilters, + filterOptions: searchFiltersV1, }} commands={[ { diff --git a/www/apps/api-reference/providers/sidebar.tsx b/www/apps/api-reference/providers/sidebar.tsx index a3ba38032936e..8a35e2fac572c 100644 --- a/www/apps/api-reference/providers/sidebar.tsx +++ b/www/apps/api-reference/providers/sidebar.tsx @@ -1,7 +1,6 @@ "use client" import { SidebarProvider as UiSidebarProvider, - mobileSidebarItems, usePageLoading, useScrollController, } from "docs-ui" diff --git a/www/apps/book/.env.sample b/www/apps/book/.env.sample index e0717e2fb07ef..6cd0d41119993 100644 --- a/www/apps/book/.env.sample +++ b/www/apps/book/.env.sample @@ -14,4 +14,5 @@ ANALYZE_BUNDLE= NEXT_PUBLIC_AI_ASSISTANT_URL= NEXT_PUBLIC_AI_WEBSITE_ID= NEXT_PUBLIC_AI_API_ASSISTANT_RECAPTCHA_SITE_KEY= -CLOUDINARY_CLOUD_NAME= \ No newline at end of file +CLOUDINARY_CLOUD_NAME= +NEXT_PUBLIC_BASE_PATH= \ No newline at end of file diff --git a/www/apps/book/app/advanced-development/api-routes/protected-routes/page.mdx b/www/apps/book/app/advanced-development/api-routes/protected-routes/page.mdx index df7eb8ed80452..7ef4562a2822d 100644 --- a/www/apps/book/app/advanced-development/api-routes/protected-routes/page.mdx +++ b/www/apps/book/app/advanced-development/api-routes/protected-routes/page.mdx @@ -118,36 +118,43 @@ In the route handler, you resolve the `UserService`, and then use it to retrieve ## Protect Custom API Routes -To protect custom API Routes that don’t start with `/store/me` or `/admin`, apply one of the following middlewares exported by the `@medusajs/medusa` package on your routes: - -- `authenticate`: only authenticated admin users can access the API Route. -- `authenticateCustomer`: customer authentication isn’t required, but if a customer is logged in, it attaches their ID to the `MedusaRequest` object's `user.customer_id`. -- `requireCustomerAuthentication`: only authenticated customers can access the API Route. +To protect custom API Routes that don’t start with `/store/me` or `/admin`, use the `authenticate` middleware imported from `@medusajs/medusa`. For example: export const highlights = [ ["11", "authenticate", "Only authenticated admin users can access routes starting with `/custom/admin`"], - ["15", "requireCustomerAuthentication", "Only authenticated customers can access routes starting with `/custom/customers`"] + ["17", "authenticate", "Only authenticated customers can access routes starting with `/custom/customers`"] ] ```ts title="src/api/middlewares.ts" highlights={highlights} -import { +// TODO update import +import { authenticate, - requireCustomerAuthentication, - type MiddlewaresConfig, -} from "@medusajs/medusa" +} from "@medusajs/medusa/dist/utils/authenticate-middleware" export const config: MiddlewaresConfig = { routes: [ { matcher: "/custom/admin*", - middlewares: [authenticate()], + middlewares: [ + authenticate("admin", ["session", "bearer", "api-key"]), + ], }, { matcher: "/custom/customer*", - middlewares: [requireCustomerAuthentication()], + middlewares: [ + authenticate("store", ["session", "bearer"]), + ], }, ], } -``` \ No newline at end of file +``` + +The `authenticate` middleware function accepts three parameters: + +1. The scope of authentication. Use `admin` for authenticating admin users, and `store` for authenticating customers. +2. An array of the types of authentication methods allowed. Both `admin` and `store` scopes support `session` and `bearer`. The `admin` scope also supports the `api-key` authentication method. +3. An optional object of options having the following properties: + 1. `allowUnauthenticated`: (default: `false`) A boolean indicating whether authentication is required. For example, you may have an API route where you want to access the logged-in customer if available, but guest customers can still access it too. In that case, enable the `allowUnauthenticated` option. + 2. `allowUnregistered`: (default: `false`) A boolean indicating whether new users can be authenticated. diff --git a/www/apps/book/app/advanced-development/data-models/soft-deletable/page.mdx b/www/apps/book/app/advanced-development/data-models/soft-deletable/page.mdx index 98060604a3e1c..183b718dda722 100644 --- a/www/apps/book/app/advanced-development/data-models/soft-deletable/page.mdx +++ b/www/apps/book/app/advanced-development/data-models/soft-deletable/page.mdx @@ -77,7 +77,7 @@ const deletedRecords = await helloModuleService .listMySoftDeletables({ // ... }, { - withDeleted: true + withDeleted: true, }) ``` diff --git a/www/apps/book/app/advanced-development/events-and-subscribers/data-payload/page.mdx b/www/apps/book/app/advanced-development/events-and-subscribers/data-payload/page.mdx index bfa0ffd09d06c..e4d884506f03b 100644 --- a/www/apps/book/app/advanced-development/events-and-subscribers/data-payload/page.mdx +++ b/www/apps/book/app/advanced-development/events-and-subscribers/data-payload/page.mdx @@ -39,8 +39,6 @@ export const config: SubscriberConfig = { This logs the product ID received in the `ProductService.Events.CREATED` (`product-created`) event’s data payload to the console. -{/* TODO check first if the events list is still correct */} +## List of Events with Data Payload -{/* ## List of Events with Data Payload - -Refer to [this reference](!resources!/events-reference) for a full list of events emitted by Medusa and their data payloads. */} \ No newline at end of file +Refer to [this reference](!resources!/events-reference) for a full list of events emitted by Medusa and their data payloads. \ No newline at end of file diff --git a/www/apps/book/app/advanced-development/modules/module-relationships/page.mdx b/www/apps/book/app/advanced-development/modules/module-relationships/page.mdx index 06b51ffdccd3f..120a2a869fbfd 100644 --- a/www/apps/book/app/advanced-development/modules/module-relationships/page.mdx +++ b/www/apps/book/app/advanced-development/modules/module-relationships/page.mdx @@ -79,9 +79,9 @@ The `CustomProductData` data model has a `product_id` field to reference the pro When you add a new data model, make sure to: -- Create a migration for it. -- Add it to the second parameter of the main service's factory function. -- Add it to the container and connection loaders. +- [Create a migration for it.](../../../basics/data-models/page.mdx#create-a-migration) +- [Add it to the second parameter of the main service's factory function.](../service-factory/page.mdx#abstractModuleServiceFactory-parameters) +- Add it to the [container](../container/page.mdx) and [connection](../connection-loader/page.mdx) loaders. @@ -120,8 +120,8 @@ class HelloModuleService extends ModulesSdkUtils { name: ["my_custom"], args: { - entity: MyCustom.name - } + entity: MyCustom.name, + }, }, { name: ["custom_product_data"], @@ -157,23 +157,23 @@ This creates a relationship to the `Product` data model of the Product Module us name: "serviceName", type: "`string`", optional: false, - description: "The name of the module (as added in `medusa-config.js`)." + description: "The name of your module (as added in `medusa-config.js`)." }, { name: "primaryKeys", type: "`string[]`", optional: false, - description: "The primary key field names used in the module's data models.", + description: "The primary key field names used in your module's data models.", }, { name: "alias", type: "`object[]`", - description: "The alias definitions for each data model in the module. This allows other modules to reference your module's data models in relationships.", + description: "The alias definitions for each data model in your module. This allows other modules to reference your module's data models in relationships.", children: [ { name: "name", type: "`string[]`", - description: "The alias names used later when fetching or referencing the data in the model." + description: "The alias names of a data model used later when fetching or referencing the data model." }, { name: "args", @@ -197,19 +197,19 @@ This creates a relationship to the `Product` data model of the Product Module us { name: "relationships", type: "`object[]`", - description: "The module's relationships to other modules.", + description: "Your module's relationships to other modules.", children: [ { name: "serviceName", type: "`string`", optional: false, - description: "The name of the module (as added in `medusa-config.js`) that this relationship is referencing. If you’re referencing a Medusa commerce module, use the `Modules` enum imported from `@medusajs/modules-sdk`." + description: "The name of the module (as added in `medusa-config.js`) that this relationship is referencing. When referencing a Medusa commerce module, use the `Modules` enum imported from `@medusajs/modules-sdk`." }, { name: "alias", type: "`string`", optional: false, - description: "The alias of the data model you’re referencing in the other module. You can find it in the `__joinerConfig` method of the other module." + description: "The alias of the data model you’re referencing in the other module. You can find it in the `__joinerConfig` method of the other module's service." }, { name: "primaryKey", diff --git a/www/apps/book/app/advanced-development/modules/options/page.mdx b/www/apps/book/app/advanced-development/modules/options/page.mdx index 5f141db24359b..80bc9bea5719f 100644 --- a/www/apps/book/app/advanced-development/modules/options/page.mdx +++ b/www/apps/book/app/advanced-development/modules/options/page.mdx @@ -70,7 +70,7 @@ class HelloModuleService extends ModulesSdkUtils //... this.options_ = moduleOptions || { - capitalize: false + capitalize: false, } } } diff --git a/www/apps/book/app/advanced-development/workflows/advanced-example/page.mdx b/www/apps/book/app/advanced-development/workflows/advanced-example/page.mdx index 2040cdc2bbdd1..3e00b5c6f1e7a 100644 --- a/www/apps/book/app/advanced-development/workflows/advanced-example/page.mdx +++ b/www/apps/book/app/advanced-development/workflows/advanced-example/page.mdx @@ -98,14 +98,14 @@ const updateProduct = createStep( return { ...variant, - options: variantOptions + options: variantOptions, } }), options: options.map((option) => ({ ...option, - values: option.values.map((value) => value.value) + values: option.values.map((value) => value.value), })), - type_id: type.id + type_id: type.id, } ) } diff --git a/www/apps/book/app/layout.tsx b/www/apps/book/app/layout.tsx index 9db5ef718fc7f..1dfd2ea4b2553 100644 --- a/www/apps/book/app/layout.tsx +++ b/www/apps/book/app/layout.tsx @@ -4,7 +4,7 @@ import { Inter, Roboto_Mono } from "next/font/google" import Navbar from "@/components/Navbar" import Providers from "@/providers" import "./globals.css" -import { TightLayout } from "docs-ui" +import { Bannerv2, TightLayout } from "docs-ui" import { config } from "@/config" import clsx from "clsx" import Feedback from "@/components/Feedback" @@ -43,6 +43,7 @@ export default function RootLayout({ NavbarComponent={Navbar} sidebarProps={{ expandItems: true, + banner: , }} showPagination={true} bodyClassName={clsx(inter.variable, robotoMono.variable)} diff --git a/www/apps/book/components/Feedback/index.tsx b/www/apps/book/components/Feedback/index.tsx index cdf5cfa66d8d1..2b9b6686ad6e7 100644 --- a/www/apps/book/components/Feedback/index.tsx +++ b/www/apps/book/components/Feedback/index.tsx @@ -4,23 +4,34 @@ import { Feedback as UiFeedback, FeedbackProps as UiFeedbackProps, formatReportLink, + useIsBrowser, } from "docs-ui" import { usePathname } from "next/navigation" import { config } from "../../config" +import { basePathUrl } from "../../utils/base-path-url" +import { useMemo } from "react" type FeedbackProps = Omit const Feedback = (props: FeedbackProps) => { const pathname = usePathname() + const isBrowser = useIsBrowser() + + const feedbackPathname = useMemo(() => basePathUrl(pathname), [pathname]) + const reportLink = useMemo( + () => + formatReportLink( + config.titleSuffix || "", + isBrowser ? document.title : "" + ), + [isBrowser] + ) return ( diff --git a/www/apps/book/components/Navbar/index.tsx b/www/apps/book/components/Navbar/index.tsx index 8e0d9eff4a307..f6550b9dbacbd 100644 --- a/www/apps/book/components/Navbar/index.tsx +++ b/www/apps/book/components/Navbar/index.tsx @@ -4,6 +4,7 @@ import { Navbar as UiNavbar, getNavbarItems } from "docs-ui" import { useSidebar } from "docs-ui" import { useMemo } from "react" import { config } from "../../config" +import { basePathUrl } from "../../utils/base-path-url" const Navbar = () => { const { setMobileSidebarOpen, mobileSidebarOpen } = useSidebar() @@ -12,7 +13,8 @@ const Navbar = () => { () => getNavbarItems({ basePath: config.baseUrl, - activePath: "/", + activePath: basePathUrl(""), + version: "v2", }), [] ) @@ -20,8 +22,8 @@ const Navbar = () => { return ( export const sidebarConfig: SidebarConfig = { top: normalizeSidebarItems(sidebar), bottom: [], - mobile: mobileSidebarItems, + mobile: mobileSidebarItemsV2, } diff --git a/www/apps/book/next.config.mjs b/www/apps/book/next.config.mjs index a4d802f660bff..3b1df77911f34 100644 --- a/www/apps/book/next.config.mjs +++ b/www/apps/book/next.config.mjs @@ -14,7 +14,6 @@ const withMDX = mdx({ extension: /\.mdx?$/, options: { rehypePlugins: [ - // TODO add V2 to path if necessary [ crossProjectLinksPlugin, { @@ -25,13 +24,14 @@ const withMDX = mdx({ process.env.VERCEL_ENV !== "production" ? process.env.NEXT_PUBLIC_RESOURCES_URL : undefined, - path: "resources", + path: "v2/resources", }, "user-guide": { url: process.env.VERCEL_ENV !== "production" ? process.env.NEXT_PUBLIC_USER_GUIDE_URL : undefined, + path: "v2/user-guide", }, ui: { url: @@ -90,31 +90,7 @@ const nextConfig = { pageExtensions: ["js", "jsx", "mdx", "ts", "tsx"], transpilePackages: ["docs-ui"], - // TODO uncomment if we decide on baes path - // basePath: process.env.NEXT_PUBLIC_BASE_PATH || "/v2", - async rewrites() { - return { - fallback: [ - { - source: "/resources", - destination: `${process.env.NEXT_PUBLIC_RESOURCES_URL}/resources`, - }, - { - source: "/resources/:path*", - destination: `${process.env.NEXT_PUBLIC_RESOURCES_URL}/resources/:path*`, - }, - // TODO comment out once we have the user guide published - // { - // source: "/user-guide", - // destination: `${process.env.NEXT_PUBLIC_USER_GUIDE_URL}/user-guide`, - // }, - // { - // source: "/user-guide/:path*", - // destination: `${process.env.NEXT_PUBLIC_USER_GUIDE_URL}/user-guide/:path*`, - // }, - ], - } - }, + basePath: process.env.NEXT_PUBLIC_BASE_PATH || "/v2", } export default withMDX(nextConfig) diff --git a/www/apps/book/providers/search.tsx b/www/apps/book/providers/search.tsx index b8f90c0323ea1..21645c25d8fbc 100644 --- a/www/apps/book/providers/search.tsx +++ b/www/apps/book/providers/search.tsx @@ -1,11 +1,6 @@ "use client" -import { - SearchProvider as UiSearchProvider, - AiAssistantCommandIcon, - AiAssistantProvider, - searchFilters, -} from "docs-ui" +import { SearchProvider as UiSearchProvider, searchFiltersV2 } from "docs-ui" import { config } from "../config" type SearchProviderProps = { @@ -32,15 +27,15 @@ const SearchProvider = ({ children }: SearchProviderProps) => { title: "Getting started? Try one of the following terms.", items: [ "Install Medusa with create-medusa-app", - "What is a Service?", "What is an API route?", + "What is a Module?", "What is a Workflow?", ], }, { title: "Developing with Medusa", items: [ - "How to create a Service", + "How to create a Module", "How to create an API route", "How to create a data model", "How to create an admin widget", @@ -48,32 +43,11 @@ const SearchProvider = ({ children }: SearchProviderProps) => { }, ], checkInternalPattern: new RegExp( - `^${config.baseUrl}/([^(api|ui|resources)]/)*` + `^${config.baseUrl}/v2/([^(resources)])*` ), - filterOptions: searchFilters, + filterOptions: searchFiltersV2, }} - initialDefaultFilters={["docs"]} - commands={[ - { - name: "ai-assistant", - icon: , - component: ( - - ), - title: "AI Assistant", - badge: { - variant: "purple", - children: "Beta", - }, - }, - ]} + initialDefaultFilters={["book"]} > {children} diff --git a/www/apps/book/utils/base-path-url.ts b/www/apps/book/utils/base-path-url.ts new file mode 100644 index 0000000000000..b8b852fedaae0 --- /dev/null +++ b/www/apps/book/utils/base-path-url.ts @@ -0,0 +1,3 @@ +export function basePathUrl(path = "") { + return `${process.env.NEXT_PUBLIC_BASE_PATH || ""}${path}` +} diff --git a/www/apps/resources/app/configurations/medusa-admin/page.mdx b/www/apps/resources/app/configurations/medusa-admin/page.mdx index e3d15e32d2ffa..d33144949711b 100644 --- a/www/apps/resources/app/configurations/medusa-admin/page.mdx +++ b/www/apps/resources/app/configurations/medusa-admin/page.mdx @@ -1,5 +1,4 @@ -import { Table } from "docs-ui" -import TypeList from "@/components/TypeList" +import { Table, TypeList } from "docs-ui" export const metadata = { title: `Medusa Admin Configurations`, diff --git a/www/apps/resources/app/js-client/page.mdx b/www/apps/resources/app/js-client/page.mdx index ce75ca7784bbf..ab270ac9bf142 100644 --- a/www/apps/resources/app/js-client/page.mdx +++ b/www/apps/resources/app/js-client/page.mdx @@ -175,7 +175,9 @@ The client accepts the following options on initialization: - A string indicating publishable API key used for storefront requests. You can create a publishable API key either using the [Medusa Admin](!user-guide!/settings/developer/api-key-management) or the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys). + {/* TODO add link [Medusa Admin](!user-guide!/settings/developer/api-key-management) */} + + A string indicating publishable API key used for storefront requests. You can create a publishable API key either using the Medusa Admin or the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys). @@ -408,7 +410,9 @@ You can learn more about publishable API keys and how to use them in [this docum ### Create a Publishable API Key -You can create a publishable API key either using the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys), or using the [Medusa Admin](!user-guide!/settings/developer/api-key-management). +{/* TODO add link [Medusa Admin](!user-guide!/settings/developer/api-key-management) */} + +You can create a publishable API key either using the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys), or using the Medusa Admin. ### Use a Publishable API Key diff --git a/www/apps/resources/app/layout.tsx b/www/apps/resources/app/layout.tsx index 506293f34edea..cbc36af4ae475 100644 --- a/www/apps/resources/app/layout.tsx +++ b/www/apps/resources/app/layout.tsx @@ -4,7 +4,7 @@ import { Inter, Roboto_Mono } from "next/font/google" import Navbar from "@/components/Navbar" import Providers from "@/providers" import "./globals.css" -import { TightLayout } from "docs-ui" +import { Bannerv2, Breadcrumbs, TightLayout } from "docs-ui" import { config } from "@/config" import clsx from "clsx" import { Feedback } from "@/components/Feedback" @@ -44,9 +44,11 @@ export default function RootLayout({ NavbarComponent={Navbar} sidebarProps={{ expandItems: true, + banner: , }} bodyClassName={clsx(inter.variable, robotoMono.variable)} > + {children} diff --git a/www/apps/resources/app/medusa-react/page.mdx b/www/apps/resources/app/medusa-react/page.mdx index ae6d5a86027eb..dc6a0f8a40e9c 100644 --- a/www/apps/resources/app/medusa-react/page.mdx +++ b/www/apps/resources/app/medusa-react/page.mdx @@ -327,7 +327,9 @@ You can learn more about publishable API keys and how to use them in [this docum ### Create a Publishable API Key -You can create a publishable API key either using the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys), or using the [Medusa Admin](!user-guide!/settings/developer/api-key-management). +{/* TODO add link [Medusa Admin](!user-guide!/settings/developer/api-key-management) */} + +You can create a publishable API key either using the [Admin API Routes](https://docs.medusajs.com/api/admin#publishable-api-keys), or using the Medusa Admin. ### Use a Publishable API Key diff --git a/www/apps/resources/components/Feedback/index.tsx b/www/apps/resources/components/Feedback/index.tsx index 6a8d2731c4255..897f6c3a4bde1 100644 --- a/www/apps/resources/components/Feedback/index.tsx +++ b/www/apps/resources/components/Feedback/index.tsx @@ -4,23 +4,34 @@ import { Feedback as UiFeedback, FeedbackProps as UiFeedbackProps, formatReportLink, + useIsBrowser, } from "docs-ui" import { usePathname } from "next/navigation" import { config } from "../../config" +import { useMemo } from "react" +import { basePathUrl } from "../../utils/base-path-url" type FeedbackProps = Omit export const Feedback = (props: FeedbackProps) => { const pathname = usePathname() + const isBrowser = useIsBrowser() + + const feedbackPathname = useMemo(() => basePathUrl(pathname), [pathname]) + const reportLink = useMemo( + () => + formatReportLink( + config.titleSuffix || "", + isBrowser ? document.title : "" + ), + [isBrowser] + ) return ( diff --git a/www/apps/resources/components/Navbar/index.tsx b/www/apps/resources/components/Navbar/index.tsx index 7dd807ed53a23..8602b9707baa5 100644 --- a/www/apps/resources/components/Navbar/index.tsx +++ b/www/apps/resources/components/Navbar/index.tsx @@ -12,7 +12,8 @@ const Navbar = () => { () => getNavbarItems({ basePath: config.baseUrl, - activePath: process.env.NEXT_PUBLIC_BASE_PATH || "/resources", + activePath: basePathUrl(""), + version: "v2", }), [] ) diff --git a/www/apps/resources/components/TypeList/index.tsx b/www/apps/resources/components/TypeList/index.tsx deleted file mode 100644 index 6768287e536bb..0000000000000 --- a/www/apps/resources/components/TypeList/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { TypeList as UiTypeList } from "docs-ui" -import { ComponentProps } from "react" -import { config } from "@/config" - -const TypeList = (props: ComponentProps) => { - return -} - -export default TypeList diff --git a/www/apps/resources/config/index.ts b/www/apps/resources/config/index.ts index 908c5018e0d0c..2efdd0bf7eb81 100644 --- a/www/apps/resources/config/index.ts +++ b/www/apps/resources/config/index.ts @@ -1,13 +1,14 @@ import { DocsConfig } from "types" -import { mobileSidebarItems } from "docs-ui" +import { mobileSidebarItemsV2 } from "docs-ui" import { generatedSidebar } from "../generated/sidebar.mjs" export const config: DocsConfig = { titleSuffix: "Medusa Resources", baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000", + basePath: process.env.NEXT_PUBLIC_BASE_PATH, sidebar: { top: generatedSidebar, bottom: [], - mobile: mobileSidebarItems, + mobile: mobileSidebarItemsV2, }, } diff --git a/www/apps/resources/mdx-options.mjs b/www/apps/resources/mdx-options.mjs index cd365b0e0569a..7c721b6eaa1df 100644 --- a/www/apps/resources/mdx-options.mjs +++ b/www/apps/resources/mdx-options.mjs @@ -12,7 +12,6 @@ import remarkDirective from "remark-directive" const mdxPluginOptions = { options: { rehypePlugins: [ - // TODO add V2 to path if necessary [ crossProjectLinksPlugin, { @@ -23,13 +22,14 @@ const mdxPluginOptions = { process.env.VERCEL_ENV !== "production" ? process.env.NEXT_PUBLIC_DOCS_URL : undefined, + path: "v2", }, "user-guide": { url: process.env.VERCEL_ENV !== "production" ? process.env.NEXT_PUBLIC_USER_GUIDE_URL : undefined, - path: "user-guide", + path: "v2/user-guide", }, ui: { url: diff --git a/www/apps/resources/next.config.mjs b/www/apps/resources/next.config.mjs index 764e74a8a42ae..dfbbb431df89a 100644 --- a/www/apps/resources/next.config.mjs +++ b/www/apps/resources/next.config.mjs @@ -28,9 +28,7 @@ const nextConfig = { transpilePackages: ["docs-ui"], - // TODO uncomment if we decide on baes path - // basePath: process.env.NEXT_PUBLIC_BASE_PATH || "/v2/resources", - basePath: process.env.NEXT_PUBLIC_BASE_PATH || "/resources", + basePath: process.env.NEXT_PUBLIC_BASE_PATH || "/v2/resources", async rewrites() { return { fallback: [ diff --git a/www/apps/resources/providers/search.tsx b/www/apps/resources/providers/search.tsx index 8422bf9ddaa8b..44846d5677ae9 100644 --- a/www/apps/resources/providers/search.tsx +++ b/www/apps/resources/providers/search.tsx @@ -1,11 +1,6 @@ "use client" -import { - SearchProvider as UiSearchProvider, - AiAssistantCommandIcon, - AiAssistantProvider, - searchFilters, -} from "docs-ui" +import { SearchProvider as UiSearchProvider, searchFiltersV2 } from "docs-ui" import { config } from "../config" type SearchProviderProps = { @@ -39,32 +34,10 @@ const SearchProvider = ({ children }: SearchProviderProps) => { ], }, ], - checkInternalPattern: new RegExp(`^${config.baseUrl}/resources/.*`), - filterOptions: searchFilters, + checkInternalPattern: new RegExp(`^${config.baseUrl}/v2/resources/.*`), + filterOptions: searchFiltersV2, }} - // TODO change once we have a dedicated index - initialDefaultFilters={["docs"]} - commands={[ - { - name: "ai-assistant", - icon: , - component: ( - - ), - title: "AI Assistant", - badge: { - variant: "purple", - children: "Beta", - }, - }, - ]} + initialDefaultFilters={["resources"]} > {children} diff --git a/www/apps/ui/.env.example b/www/apps/ui/.env.example index e7cbf786fc340..520fe20af538b 100644 --- a/www/apps/ui/.env.example +++ b/www/apps/ui/.env.example @@ -8,4 +8,5 @@ NEXT_PUBLIC_ALGOLIA_APP_ID= NEXT_PUBLIC_SEGMENT_API_KEY= NEXT_PUBLIC_AI_ASSISTANT_URL= NEXT_PUBLIC_AI_WEBSITE_ID= -NEXT_PUBLIC_AI_API_ASSISTANT_RECAPTCHA_SITE_KEY= \ No newline at end of file +NEXT_PUBLIC_AI_API_ASSISTANT_RECAPTCHA_SITE_KEY= +NEXT_PUBLIC_SHOW_V2= \ No newline at end of file diff --git a/www/apps/ui/src/config/docs.tsx b/www/apps/ui/src/config/docs.tsx index e9dd26b5ed169..dbe092aa86926 100644 --- a/www/apps/ui/src/config/docs.tsx +++ b/www/apps/ui/src/config/docs.tsx @@ -1,10 +1,15 @@ import { ArrowUpRightOnBox } from "@medusajs/icons" -import { NavbarLinkProps, getNavbarItems, mobileSidebarItems } from "docs-ui" +import { + NavbarItem, + getNavbarItems, + legacyMobileSidebarItems, + mobileSidebarItemsV1, +} from "docs-ui" import { SidebarSectionItemsType } from "types" import { siteConfig } from "./site" type DocsConfig = { - mainNav: NavbarLinkProps[] + mainNav: NavbarItem[] sidebar: SidebarSectionItemsType } @@ -12,6 +17,7 @@ export const docsConfig: DocsConfig = { mainNav: getNavbarItems({ basePath: siteConfig.baseUrl, activePath: process.env.NEXT_PUBLIC_BASE_PATH || "/ui", + version: process.env.NEXT_PUBLIC_SHOW_V2 ? "v1" : "legacy", }), sidebar: { top: [ @@ -279,6 +285,8 @@ export const docsConfig: DocsConfig = { ], }, ], - mobile: mobileSidebarItems, + mobile: process.env.NEXT_PUBLIC_SHOW_V2 + ? mobileSidebarItemsV1 + : legacyMobileSidebarItems, }, } diff --git a/www/apps/ui/src/config/site.ts b/www/apps/ui/src/config/site.ts index 59db3a51881fe..f81e9b97761db 100644 --- a/www/apps/ui/src/config/site.ts +++ b/www/apps/ui/src/config/site.ts @@ -11,6 +11,7 @@ const baseUrl = process.env.NEXT_PUBLIC_DOCS_URL || "http://localhost:3000" export const siteConfig: SiteConfig = { name: "Medusa UI", baseUrl, + basePath: process.env.NEXT_PUBLIC_BASE_PATH, url: `${baseUrl}/${process.env.NEXT_PUBLIC_BASE_PATH}`, description: "Primitives for building Medusa applications.", // sidebar is defined in docs.tsx diff --git a/www/apps/ui/src/lib/base-path-url.ts b/www/apps/ui/src/lib/base-path-url.ts index e10c6f9cbb9ba..b8b852fedaae0 100644 --- a/www/apps/ui/src/lib/base-path-url.ts +++ b/www/apps/ui/src/lib/base-path-url.ts @@ -1,3 +1,3 @@ export function basePathUrl(path = "") { - return `${process.env.NEXT_PUBLIC_BASE_PATH}${path}` + return `${process.env.NEXT_PUBLIC_BASE_PATH || ""}${path}` } diff --git a/www/apps/ui/src/providers/search.tsx b/www/apps/ui/src/providers/search.tsx index 7538078fda7c9..95a6754f9a4ab 100644 --- a/www/apps/ui/src/providers/search.tsx +++ b/www/apps/ui/src/providers/search.tsx @@ -4,7 +4,7 @@ import { AiAssistantCommandIcon, AiAssistantProvider, SearchProvider as UiSearchProvider, - searchFilters, + searchFiltersV1, } from "docs-ui" import { absoluteUrl } from "../lib/absolute-url" @@ -34,7 +34,7 @@ const SearchProvider = ({ children }: SearchProviderProps) => { }, ], checkInternalPattern: new RegExp(`^${absoluteUrl()}/ui`), - filterOptions: searchFilters, + filterOptions: searchFiltersV1, }} initialDefaultFilters={["ui"]} commands={[ diff --git a/www/apps/user-guide/components/Feedback/index.tsx b/www/apps/user-guide/components/Feedback/index.tsx index cdf5cfa66d8d1..2b9b6686ad6e7 100644 --- a/www/apps/user-guide/components/Feedback/index.tsx +++ b/www/apps/user-guide/components/Feedback/index.tsx @@ -4,23 +4,34 @@ import { Feedback as UiFeedback, FeedbackProps as UiFeedbackProps, formatReportLink, + useIsBrowser, } from "docs-ui" import { usePathname } from "next/navigation" import { config } from "../../config" +import { basePathUrl } from "../../utils/base-path-url" +import { useMemo } from "react" type FeedbackProps = Omit const Feedback = (props: FeedbackProps) => { const pathname = usePathname() + const isBrowser = useIsBrowser() + + const feedbackPathname = useMemo(() => basePathUrl(pathname), [pathname]) + const reportLink = useMemo( + () => + formatReportLink( + config.titleSuffix || "", + isBrowser ? document.title : "" + ), + [isBrowser] + ) return ( diff --git a/www/apps/user-guide/components/Navbar/index.tsx b/www/apps/user-guide/components/Navbar/index.tsx index be11a590fdcb6..f7618199d73b9 100644 --- a/www/apps/user-guide/components/Navbar/index.tsx +++ b/www/apps/user-guide/components/Navbar/index.tsx @@ -14,6 +14,7 @@ const Navbar = () => { getNavbarItems({ basePath: config.baseUrl, activePath: process.env.NEXT_PUBLIC_BASE_PATH || "/user-guide", + version: "v2", }), [] ) diff --git a/www/apps/user-guide/config/index.ts b/www/apps/user-guide/config/index.ts index 05539e1b3cb7b..db049ff2676e6 100644 --- a/www/apps/user-guide/config/index.ts +++ b/www/apps/user-guide/config/index.ts @@ -1,13 +1,14 @@ import { DocsConfig } from "types" -import { mobileSidebarItems } from "docs-ui" +import { mobileSidebarItemsV2 } from "docs-ui" import { generatedSidebar as sidebar } from "@/generated/sidebar.mjs" export const config: DocsConfig = { titleSuffix: "Medusa Admin User Guide", baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000", + basePath: process.env.NEXT_PUBLIC_BASE_PATH, sidebar: { top: sidebar, bottom: [], - mobile: mobileSidebarItems, + mobile: mobileSidebarItemsV2, }, } diff --git a/www/apps/user-guide/providers/search.tsx b/www/apps/user-guide/providers/search.tsx index ff50b51af3fa6..0e78a7c064b53 100644 --- a/www/apps/user-guide/providers/search.tsx +++ b/www/apps/user-guide/providers/search.tsx @@ -4,7 +4,7 @@ import { SearchProvider as UiSearchProvider, AiAssistantCommandIcon, AiAssistantProvider, - searchFilters, + searchFiltersV1, } from "docs-ui" import { config } from "../config" @@ -42,7 +42,7 @@ const SearchProvider = ({ children }: SearchProviderProps) => { }, ], checkInternalPattern: new RegExp(`^${config.baseUrl}/user-guide`), - filterOptions: searchFilters, + filterOptions: searchFiltersV1, }} initialDefaultFilters={["user-guide"]} commands={[ diff --git a/www/packages/docs-ui/src/components/Bannerv2/index.tsx b/www/packages/docs-ui/src/components/Bannerv2/index.tsx new file mode 100644 index 0000000000000..bb8cdb35a1ab2 --- /dev/null +++ b/www/packages/docs-ui/src/components/Bannerv2/index.tsx @@ -0,0 +1,15 @@ +import React from "react" +import { Card, Link } from "../.." + +export const Bannerv2 = () => { + return ( + + This documentation is for Medusa v2, which isn't ready for + production. +
+
+ For production-use, refer to{" "} + this documentation instead. +
+ ) +} diff --git a/www/packages/docs-ui/src/components/Breadcrumbs/index.tsx b/www/packages/docs-ui/src/components/Breadcrumbs/index.tsx new file mode 100644 index 0000000000000..fd6bd17d74f2f --- /dev/null +++ b/www/packages/docs-ui/src/components/Breadcrumbs/index.tsx @@ -0,0 +1,76 @@ +"use client" + +import React, { useMemo } from "react" +import { CurrentItemsState, useSidebar } from "@/providers" +import { TriangleRightMini } from "@medusajs/icons" +import Link from "next/link" +import clsx from "clsx" + +type BreadcrumbItem = Map + +export const Breadcrumbs = () => { + const { currentItems } = useSidebar() + + const getBreadcrumbsOfItem = (item: CurrentItemsState): BreadcrumbItem => { + let tempBreadcrumbItems: BreadcrumbItem = new Map() + if (item.previousSidebar) { + tempBreadcrumbItems = getBreadcrumbsOfItem(item.previousSidebar) + } + + tempBreadcrumbItems.set( + item.parentItem?.path || item.top[0].path || "/", + item.parentItem?.childSidebarTitle || item.parentItem?.title || "" + ) + + return tempBreadcrumbItems + } + + const breadcrumbItems = useMemo(() => { + const tempBreadcrumbItems: BreadcrumbItem = new Map() + if (!currentItems) { + return tempBreadcrumbItems + } + + tempBreadcrumbItems.set("/", "Home") + + getBreadcrumbsOfItem(currentItems).forEach((value, key) => + tempBreadcrumbItems.set(key, value) + ) + + return tempBreadcrumbItems + }, [currentItems]) + + const getBreadcrumbItemElms = (): React.ReactNode[] => { + const elms: React.ReactNode[] = [] + breadcrumbItems.forEach((title, path) => { + elms.push( + + {elms.length !== 0 && ( + + )} + + {title} + + + ) + }) + + return elms + } + + return ( + <> + {breadcrumbItems.size > 0 && ( +
+ {...getBreadcrumbItemElms()} +
+ )} + + ) +} diff --git a/www/packages/docs-ui/src/components/Navbar/Link/index.tsx b/www/packages/docs-ui/src/components/Navbar/Link/index.tsx index 26fc8c6048941..44efccd873adb 100644 --- a/www/packages/docs-ui/src/components/Navbar/Link/index.tsx +++ b/www/packages/docs-ui/src/components/Navbar/Link/index.tsx @@ -2,7 +2,7 @@ import React from "react" import clsx from "clsx" -import { Link, LinkProps } from "@/components" +import { Badge, BadgeProps, Link, LinkProps } from "@/components" export type NavbarLinkProps = { href: string @@ -10,6 +10,7 @@ export type NavbarLinkProps = { className?: string activeValuePattern?: RegExp isActive?: boolean + badge?: BadgeProps } & LinkProps export const NavbarLink = ({ @@ -17,6 +18,7 @@ export const NavbarLink = ({ label, className, isActive, + badge }: NavbarLinkProps) => { return ( {label} + {badge && } ) } diff --git a/www/packages/docs-ui/src/components/Navbar/Logo/index.tsx b/www/packages/docs-ui/src/components/Navbar/Logo/index.tsx index 5dfcf106f82cc..e28ef7f7175d8 100644 --- a/www/packages/docs-ui/src/components/Navbar/Logo/index.tsx +++ b/www/packages/docs-ui/src/components/Navbar/Logo/index.tsx @@ -4,6 +4,7 @@ import React from "react" import { useColorMode } from "@/providers" import Link from "next/link" import clsx from "clsx" +import Image from "next/image" export type NavbarLogoProps = { light: string @@ -22,7 +23,7 @@ export const NavbarLogo = ({ return ( - Medusa Logo { + return ( +
+ ) +} \ No newline at end of file diff --git a/www/packages/docs-ui/src/components/Navbar/index.tsx b/www/packages/docs-ui/src/components/Navbar/index.tsx index 981474cdd2499..4ea2756fc9363 100644 --- a/www/packages/docs-ui/src/components/Navbar/index.tsx +++ b/www/packages/docs-ui/src/components/Navbar/index.tsx @@ -6,10 +6,19 @@ import { NavbarLogo, NavbarLogoProps } from "./Logo" import { NavbarMobileMenu } from "./MobileMenu" import { NavbarSearchModalOpener } from "./SearchModalOpener" import { NavbarMobileMenuButtonProps } from "./MobileMenu/Button" +import { NavbarDivider } from "./NavbarDivider" + +export type NavbarItem = { + type: "link" + props: NavbarLinkProps +} | { + type: "divider" + props?: {} +} export type NavbarProps = { logo: NavbarLogoProps - items: NavbarLinkProps[] + items: NavbarItem[] showSearchOpener?: boolean showColorModeToggle?: boolean additionalActionsAfter?: React.ReactNode @@ -45,9 +54,14 @@ export const Navbar = ({ >
- {items.map((item, index) => ( - - ))} + {items.map(({type, props}, index) => { + switch(type) { + case "divider": + return + default: + return + } + })}
{additionalActionsBefore} diff --git a/www/packages/docs-ui/src/components/Pagination/index.tsx b/www/packages/docs-ui/src/components/Pagination/index.tsx index 4936e3e272809..26d99d90c9a94 100644 --- a/www/packages/docs-ui/src/components/Pagination/index.tsx +++ b/www/packages/docs-ui/src/components/Pagination/index.tsx @@ -13,6 +13,7 @@ export const Pagination = () => { {previousPage && ( } showLinkIcon={false} href={previousPage.link} @@ -22,6 +23,7 @@ export const Pagination = () => { {nextPage && ( } showLinkIcon={false} href={nextPage.link} diff --git a/www/packages/docs-ui/src/components/Search/index.tsx b/www/packages/docs-ui/src/components/Search/index.tsx index 2b631bf86432c..f56deec91f1b5 100644 --- a/www/packages/docs-ui/src/components/Search/index.tsx +++ b/www/packages/docs-ui/src/components/Search/index.tsx @@ -85,6 +85,9 @@ export const Search = ({
{ return (
export const SidebarItem = ({ @@ -24,6 +26,8 @@ export const SidebarItem = ({ expandItems = false, className, currentLevel = 1, + sidebarHasParent = false, + isMobile = false }: SidebarItemProps) => { const [showLoading, setShowLoading] = useState(false) const { @@ -34,8 +38,8 @@ export const SidebarItem = ({ sidebarRef, } = useSidebar() const active = useMemo( - () => isItemActive(item, nested), - [isItemActive, item, nested] + () => !isMobile && isItemActive(item, nested), + [isItemActive, item, nested, isMobile] ) const collapsed = !expandItems && !isItemActive(item, true) const ref = useRef(null) @@ -131,7 +135,11 @@ export const SidebarItem = ({ return (
  • { return ( { const { items, @@ -32,6 +34,11 @@ export const Sidebar = ({ [items, currentItems] ) + const sidebarHasParent = useMemo( + () => sidebarItems.parentItem !== undefined, + [sidebarItems] + ) + return ( ) } diff --git a/www/packages/docs-ui/src/components/TypeList/Items/index.tsx b/www/packages/docs-ui/src/components/TypeList/Items/index.tsx index c2cf706911c16..aa00bc68cf66f 100644 --- a/www/packages/docs-ui/src/components/TypeList/Items/index.tsx +++ b/www/packages/docs-ui/src/components/TypeList/Items/index.tsx @@ -21,7 +21,7 @@ import { } from "@medusajs/icons" import { decodeStr, isInView } from "@/utils" import { usePathname } from "next/navigation" -import { useIsBrowser } from "../../.." +import { useIsBrowser, useSiteConfig } from "../../.." type CommonProps = ParentCommonProps & { level?: number @@ -39,10 +39,11 @@ const TypeListItem = ({ expandUrl, elementKey, sectionTitle, - siteUrl = "", }: TypeListItemProps) => { const isBrowser = useIsBrowser() const pathname = usePathname() + const { config: { baseUrl, basePath } } = useSiteConfig() + const siteUrl = `${baseUrl}${basePath}` const groupName = useMemo(() => { switch (level) { diff --git a/www/packages/docs-ui/src/components/TypeList/index.tsx b/www/packages/docs-ui/src/components/TypeList/index.tsx index 1813dc2a07341..2c2e42c07e74f 100644 --- a/www/packages/docs-ui/src/components/TypeList/index.tsx +++ b/www/packages/docs-ui/src/components/TypeList/index.tsx @@ -5,7 +5,6 @@ import { Loading } from "@/components" export type CommonProps = { expandUrl?: string sectionTitle?: string - siteUrl?: string } export type Type = { @@ -30,7 +29,6 @@ const TypeListItems = lazy(async () => import("./Items")) export const TypeList = ({ types, className, - siteUrl, sectionTitle, expandUrl, ...props @@ -48,7 +46,6 @@ export const TypeList = ({ types={types} expandUrl={expandUrl} sectionTitle={sectionTitle} - siteUrl={siteUrl} />
  • diff --git a/www/packages/docs-ui/src/components/index.ts b/www/packages/docs-ui/src/components/index.ts index a30ff98410f41..24c77b213ca72 100644 --- a/www/packages/docs-ui/src/components/index.ts +++ b/www/packages/docs-ui/src/components/index.ts @@ -1,8 +1,10 @@ export * from "./AiAssistant" export * from "./AiAssistant/CommandIcon" export * from "./Badge" +export * from "./Bannerv2" export * from "./Bordered" export * from "./BorderedIcon" +export * from "./Breadcrumbs" export * from "./Button" export * from "./Card" export * from "./CardList" diff --git a/www/packages/docs-ui/src/constants.ts b/www/packages/docs-ui/src/constants.ts deleted file mode 100644 index e222d0b850dcf..0000000000000 --- a/www/packages/docs-ui/src/constants.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { NavbarLinkProps } from "@/components" -import { OptionType } from "./hooks" -import { SidebarItemType } from "types" - -export const GITHUB_ISSUES_PREFIX = `https://github.com/medusajs/medusa/issues/new?assignees=&labels=type%3A+docs&template=docs.yml` -export const GITHUB_UI_ISSUES_PREFIX = `https://github.com/medusajs/ui/issues/new?labels=documentation` - -export const navbarItems: NavbarLinkProps[] = [ - { - label: "Docs", - target: "_blank", - rel: "noreferrer", - href: `/`, - }, - { - label: "Resources", - target: "_blank", - rel: "noreferrer", - href: `/resources`, - }, - { - label: "User Guide", - target: "_blank", - rel: "noreferrer", - href: `/user-guide`, - }, - { - label: "Store API", - target: "_blank", - rel: "noreferrer", - href: `/api/store`, - }, - { - label: "Admin API", - target: "_blank", - rel: "noreferrer", - href: `/api/admin`, - }, - { - label: "UI", - target: "_blank", - rel: "noreferrer", - href: `/ui`, - }, -] - -/** - * TODO Uncomment for V2 - * - * export const navbarItems: NavbarLinkProps[] = [ - { - label: "Docs", - target: "_blank", - rel: "noreferrer", - href: `/`, - activeValuePattern: /^\/(?!api\/|ui\/|user-guide\/|resources\/)/, - }, - { - label: "User Guide", - target: "_blank", - rel: "noreferrer", - href: `/user-guide`, - }, - { - label: "Store API", - target: "_blank", - rel: "noreferrer", - href: `/api/store`, - }, - { - label: "Admin API", - target: "_blank", - rel: "noreferrer", - href: `/api/admin`, - }, - { - label: "UI", - target: "_blank", - rel: "noreferrer", - href: `/ui`, - activeValuePattern: /^\/ui\//, - }, - { - label: "V2 Docs", - target: "_blank", - rel: "noreferrer", - href: `/v2`, - }, -] - -export const navbarItemsV2: NavbarLinkProps[] = [ - { - label: "Docs", - target: "_blank", - rel: "noreferrer", - href: `/v2`, - activeValuePattern: /^\/v2\/(?!api\/|ui\/|user-guide\/|resources\/)/, - }, - { - label: "Resources", - target: "_blank", - rel: "noreferrer", - href: `/v2/resources`, - activeValuePattern: /^\/v2\/resources\//, - }, - { - label: "User Guide", - target: "_blank", - rel: "noreferrer", - href: `/v2/user-guide`, - activeValuePattern: /^\/v2\/user-guide/, - }, - { - label: "Store API", - target: "_blank", - rel: "noreferrer", - href: `/api/store`, - }, - { - label: "Admin API", - target: "_blank", - rel: "noreferrer", - href: `/api/admin`, - }, - { - label: "UI", - target: "_blank", - rel: "noreferrer", - href: `/ui`, - activeValuePattern: /^\/ui\//, - }, -] - */ - -export const mobileSidebarItems: SidebarItemType[] = [ - { - title: "Docs", - path: `/`, - loaded: true, - isPathHref: true, - }, - { - title: "User Guide", - path: `/user-guide`, - loaded: true, - isPathHref: true, - }, - { - title: "Store API", - path: `/api/store`, - loaded: true, - isPathHref: true, - }, - { - title: "Admin API", - path: `/api/admin`, - loaded: true, - isPathHref: true, - }, - { - title: "UI", - path: `/ui`, - loaded: true, - isPathHref: true, - }, -] - -// TODO add resources once we create index -export const searchFilters: OptionType[] = [ - { - value: "admin", - label: "Admin API", - }, - { - value: "store", - label: "Store API", - }, - { - value: "docs", - label: "Docs", - }, - { - value: "user-guide", - label: "User Guide", - }, - { - value: "plugins", - label: "Plugins", - }, - { - value: "reference", - label: "References", - }, - { - value: "ui", - label: "UI", - }, -] diff --git a/www/packages/docs-ui/src/constants.tsx b/www/packages/docs-ui/src/constants.tsx new file mode 100644 index 0000000000000..e162cb1628774 --- /dev/null +++ b/www/packages/docs-ui/src/constants.tsx @@ -0,0 +1,368 @@ +import React from "react" +import { Badge, NavbarItem } from "@/components" +import { OptionType } from "./hooks" +import { SidebarItemType } from "types" + +export const GITHUB_ISSUES_PREFIX = `https://github.com/medusajs/medusa/issues/new?assignees=&labels=type%3A+docs&template=docs.yml` +export const GITHUB_UI_ISSUES_PREFIX = `https://github.com/medusajs/ui/issues/new?labels=documentation` + +export const navbarItemsV1: NavbarItem[] = [ + { + type: "link", + props: { + label: "Docs", + target: "_blank", + rel: "noreferrer", + href: `/`, + }, + }, + { + type: "link", + props: { + label: "User Guide", + target: "_blank", + rel: "noreferrer", + href: `/user-guide`, + }, + }, + { + type: "link", + props: { + label: "Store API", + target: "_blank", + rel: "noreferrer", + href: `/api/store`, + }, + }, + { + type: "link", + props: { + label: "Admin API", + target: "_blank", + rel: "noreferrer", + href: `/api/admin`, + }, + }, + { + type: "link", + props: { + label: "UI", + target: "_blank", + rel: "noreferrer", + href: `/ui`, + }, + }, + { + type: "divider", + }, + { + type: "link", + props: { + label: "Learn Medusa v2", + target: "_blank", + rel: "noreferrer", + href: `/v2`, + badge: { + variant: "blue", + children: "New", + }, + }, + }, +] + +export const navbarItemsV2: NavbarItem[] = [ + { + type: "link", + props: { + label: "Docs", + target: "_blank", + rel: "noreferrer", + href: `/v2`, + }, + }, + { + type: "link", + props: { + label: "Learning Resources", + target: "_blank", + rel: "noreferrer", + href: `/v2/resources`, + }, + }, + { + type: "divider", + }, + { + type: "link", + props: { + label: "Docs", + target: "_blank", + rel: "noreferrer", + href: `/`, + badge: { + variant: "neutral", + children: "v1", + }, + }, + }, + { + type: "link", + props: { + label: "User Guide", + target: "_blank", + rel: "noreferrer", + href: `/user-guide`, + badge: { + variant: "neutral", + children: "v1", + }, + }, + }, + { + type: "link", + props: { + label: "Store API", + target: "_blank", + rel: "noreferrer", + href: `/api/store`, + }, + }, + { + type: "link", + props: { + label: "Admin API", + target: "_blank", + rel: "noreferrer", + href: `/api/admin`, + }, + }, + { + type: "link", + props: { + label: "UI", + target: "_blank", + rel: "noreferrer", + href: `/ui`, + }, + }, +] + +export const legacyNavbarItems: NavbarItem[] = [ + { + type: "link", + props: { + label: "Docs", + target: "_blank", + rel: "noreferrer", + href: `/`, + }, + }, + { + type: "link", + props: { + label: "Resources", + target: "_blank", + rel: "noreferrer", + href: `/resources`, + }, + }, + { + type: "link", + props: { + label: "User Guide", + target: "_blank", + rel: "noreferrer", + href: `/user-guide`, + }, + }, + { + type: "link", + props: { + label: "Store API", + target: "_blank", + rel: "noreferrer", + href: `/api/store`, + }, + }, + { + type: "link", + props: { + label: "Admin API", + target: "_blank", + rel: "noreferrer", + href: `/api/admin`, + }, + }, + { + type: "link", + props: { + label: "UI", + target: "_blank", + rel: "noreferrer", + href: `/ui`, + }, + }, +] + +export const mobileSidebarItemsV1: SidebarItemType[] = [ + { + title: "Docs", + path: `/`, + loaded: true, + isPathHref: true, + }, + { + title: "User Guide", + path: `/user-guide`, + loaded: true, + isPathHref: true, + }, + { + title: "Store API", + path: `/api/store`, + loaded: true, + isPathHref: true, + }, + { + title: "Admin API", + path: `/api/admin`, + loaded: true, + isPathHref: true, + }, + { + title: "UI", + path: `/ui`, + loaded: true, + isPathHref: true, + }, + { + title: "Book", + path: `/v2`, + loaded: true, + isPathHref: true, + additionalElms: v2, + }, +] + +export const mobileSidebarItemsV2: SidebarItemType[] = [ + { + title: "Book", + path: `/v2`, + loaded: true, + isPathHref: true, + }, + { + title: "Learning Resources", + path: `/v2/resources`, + loaded: true, + isPathHref: true, + }, + { + title: "Docs", + path: `/`, + loaded: true, + isPathHref: true, + additionalElms: v1, + }, + { + title: "User Guide", + path: `/user-guide`, + loaded: true, + isPathHref: true, + additionalElms: v1, + }, + { + title: "Store API", + path: `/api/store`, + loaded: true, + isPathHref: true, + }, + { + title: "Admin API", + path: `/api/admin`, + loaded: true, + isPathHref: true, + }, + { + title: "UI", + path: `/ui`, + loaded: true, + isPathHref: true, + }, +] + +export const legacyMobileSidebarItems: SidebarItemType[] = [ + { + title: "Docs", + path: `/`, + loaded: true, + isPathHref: true, + }, + { + title: "User Guide", + path: `/user-guide`, + loaded: true, + isPathHref: true, + }, + { + title: "Store API", + path: `/api/store`, + loaded: true, + isPathHref: true, + }, + { + title: "Admin API", + path: `/api/admin`, + loaded: true, + isPathHref: true, + }, + { + title: "UI", + path: `/ui`, + loaded: true, + isPathHref: true, + }, +] + +export const searchFiltersV2: OptionType[] = [ + { + value: "book", + label: "Book", + }, + { + value: "resources", + label: "Resources", + }, + // TODO add more filters once V2 become the main docs +] + +export const searchFiltersV1: OptionType[] = [ + { + value: "admin", + label: "Admin API", + }, + { + value: "store", + label: "Store API", + }, + { + value: "docs", + label: "Docs", + }, + { + value: "user-guide", + label: "User Guide", + }, + { + value: "plugins", + label: "Plugins", + }, + { + value: "reference", + label: "References", + }, + { + value: "ui", + label: "UI", + }, +] diff --git a/www/packages/docs-ui/src/providers/Pagination/index.tsx b/www/packages/docs-ui/src/providers/Pagination/index.tsx index c271adcb00613..f2569df53d919 100644 --- a/www/packages/docs-ui/src/providers/Pagination/index.tsx +++ b/www/packages/docs-ui/src/providers/Pagination/index.tsx @@ -14,6 +14,7 @@ import { SidebarItemType } from "types" export type Page = { title: string description?: string + parentTitle?: string link: string } @@ -26,10 +27,14 @@ export const PaginationContext = createContext( null ) +type SidebarItemWithParent = SidebarItemType & { + parent?: SidebarItemType +} + type SearchItemsResult = { foundActive: boolean - prevItem?: SidebarItemType - nextItem?: SidebarItemType + prevItem?: SidebarItemWithParent + nextItem?: SidebarItemWithParent } export type PaginationProviderProps = { @@ -66,14 +71,20 @@ export const PaginationProvider = ({ children }: PaginationProviderProps) => { const getPrevItem = ( items: SidebarItemType[], index: number - ): SidebarItemType | undefined => { - let foundItem: SidebarItemType | undefined + ): SidebarItemWithParent | undefined => { + let foundItem: SidebarItemWithParent | undefined items .slice(0, index) .reverse() .some((item) => { if (item.children?.length) { - foundItem = getPrevItem(item.children, item.children.length) + const childItem = getPrevItem(item.children, item.children.length) + if (childItem) { + foundItem = { + ...childItem, + parent: item, + } + } } else if (item.path) { foundItem = item } @@ -87,13 +98,19 @@ export const PaginationProvider = ({ children }: PaginationProviderProps) => { const getNextItem = ( items: SidebarItemType[], index: number - ): SidebarItemType | undefined => { - let foundItem: SidebarItemType | undefined + ): SidebarItemWithParent | undefined => { + let foundItem: SidebarItemWithParent | undefined items.slice(index + 1).some((item) => { if (item.path) { foundItem = item } else if (item.children?.length) { - foundItem = getNextItem(item.children, -1) + const childItem = getNextItem(item.children, -1) + if (childItem) { + foundItem = { + ...childItem, + parent: item, + } + } } return foundItem !== undefined @@ -157,6 +174,7 @@ export const PaginationProvider = ({ children }: PaginationProviderProps) => { ? { title: result.prevItem.title, link: result.prevItem.path || "", + parentTitle: result.prevItem.parent?.title, } : undefined ) @@ -165,6 +183,7 @@ export const PaginationProvider = ({ children }: PaginationProviderProps) => { ? { title: result.nextItem.title, link: result.nextItem.path || "", + parentTitle: result.nextItem.parent?.title, } : undefined ) diff --git a/www/packages/docs-ui/src/providers/Sidebar/index.tsx b/www/packages/docs-ui/src/providers/Sidebar/index.tsx index c6223acac153f..6253e6169ea8b 100644 --- a/www/packages/docs-ui/src/providers/Sidebar/index.tsx +++ b/www/packages/docs-ui/src/providers/Sidebar/index.tsx @@ -59,7 +59,7 @@ export type SidebarContextType = { setDesktopSidebarOpen: React.Dispatch> staticSidebarItems?: boolean shouldHandleHashChange: boolean - sidebarRef: React.RefObject + sidebarRef: React.RefObject goBack: () => void } & SidebarStyleOptions @@ -198,7 +198,7 @@ export const SidebarProvider = ({ const [activePath, setActivePath] = useState("") const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false) const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true) - const sidebarRef = useRef(null) + const sidebarRef = useRef(null) const pathname = usePathname() const router = useRouter() @@ -311,7 +311,7 @@ export const SidebarProvider = ({ } setActivePath(backItem.path!) - setCurrentItems(currentItems.previousSidebar) + setCurrentItems(previousSidebar) router.replace(backItem.path!) } @@ -405,7 +405,10 @@ export const SidebarProvider = ({ bottom: [], mobile: items.mobile, parentItem: parentItem, - previousSidebar: currentItems, + previousSidebar: + currentItems?.previousSidebar?.parentItem?.path !== parentItem.path + ? currentItems + : undefined, }) } }, [getCurrentSidebar, activePath]) diff --git a/www/packages/docs-ui/src/utils/get-navbar-items.ts b/www/packages/docs-ui/src/utils/get-navbar-items.ts index dfacdc2c1186c..ebcace177d989 100644 --- a/www/packages/docs-ui/src/utils/get-navbar-items.ts +++ b/www/packages/docs-ui/src/utils/get-navbar-items.ts @@ -1,17 +1,29 @@ -import { NavbarLinkProps, navbarItems } from ".." +import { NavbarItem, legacyNavbarItems, navbarItemsV1, navbarItemsV2 } from ".." type Options = { basePath: string activePath: string + version?: "v1" | "v2" | "legacy" } export function getNavbarItems({ basePath, activePath, -}: Options): NavbarLinkProps[] { - return navbarItems.map((item) => ({ - ...item, - isActive: activePath === item.href, - href: `${basePath}${item.href}`, - })) + version = "legacy" +}: Options): NavbarItem[] { + const navbarItems = version === "v2" ? navbarItemsV2 : version === "v1" ? navbarItemsV1 : legacyNavbarItems + return navbarItems.map((item) => { + if (item.type === "divider") { + return item + } + + return { + ...item, + props: { + ...item.props, + isActive: activePath === item.props?.href, + href: `${basePath}${item.props?.href}`, + } + } + }) } diff --git a/www/packages/types/src/config.ts b/www/packages/types/src/config.ts index 4c5bb621de2fd..e912baf9e1de5 100644 --- a/www/packages/types/src/config.ts +++ b/www/packages/types/src/config.ts @@ -3,6 +3,7 @@ import { SidebarSectionItemsType } from "./sidebar.js" export declare type DocsConfig = { titleSuffix?: string baseUrl: string + basePath?: string sidebar: SidebarSectionItemsType filesBasePath?: string useNextLinks?: boolean