Skip to content

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

chore: v2.0.0-canary.41

vholik8bb4b5e8a3dd
diff --git a/packages/admin/package.json b/packages/admin/package.json
index b969b98d3..923be0d6c 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/admin",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 4f2637cab..2070bb485 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/cli",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/client/package.json b/packages/client/package.json
index d69661576..6e45fccc6 100644
--- a/packages/client/package.json
+++ b/packages/client/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/client",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/core-plugin/package.json b/packages/core-plugin/package.json
index aa3c728ef..7b69acf3b 100644
--- a/packages/core-plugin/package.json
+++ b/packages/core-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/core-plugin",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/core-plugin/src/migration-scripts/sync-custom-fields.ts b/packages/core-plugin/src/migration-scripts/sync-custom-fields.ts
new file mode 100644
index 000000000..5383d0332
--- /dev/null
+++ b/packages/core-plugin/src/migration-scripts/sync-custom-fields.ts
@@ -0,0 +1,120 @@
+import { ExecArgs } from "@medusajs/framework/types";
+import {
+ camelToSnakeCase,
+ ContainerRegistrationKeys,
+ DALUtils,
+ ModulesSdkUtils,
+ normalizeMigrationSQL,
+} from "@medusajs/framework/utils";
+import { DatabaseSchema } from "@medusajs/framework/mikro-orm/knex";
+import { generateEntity } from "../modules/custom-fields/utils/generate-entity";
+import { CUSTOM_FIELDS_MODULE, CustomFieldsModuleOptions } from "../modules/custom-fields";
+
+function pickTableRelatedCommands(tableNames: string[], sqlCommand: string) {
+ const ignoreColumns = ["created_at", "updated_at", "deleted_at"];
+ const commands = sqlCommand.split(";");
+ const returnedCommands = commands
+ .filter((command) => {
+ const cmd = command.trim();
+ return (
+ cmd.length &&
+ cmd !== "set names 'utf8'" &&
+ tableNames.some((t) => cmd.includes(`"${t}"`)) &&
+ !ignoreColumns.some((column) => cmd.includes(`column "${column}"`))
+ );
+ })
+ .map((cmd) => cmd.trim());
+
+ if (returnedCommands.length > 0) {
+ returnedCommands.push("");
+ }
+
+ return returnedCommands.join(";");
+}
+
+export default async function syncCustomFields({ container }: ExecArgs) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER);
+ const configModule = container.resolve(ContainerRegistrationKeys.CONFIG_MODULE);
+
+ let moduleConfig;
+ if (configModule.modules) {
+ for (const [key, value] of Object.entries(configModule.modules)) {
+ if (
+ key === CUSTOM_FIELDS_MODULE ||
+ (typeof value === "object" &&
+ value !== null &&
+ "resolve" in value &&
+ value.resolve === "./src/modules/custom-fields")
+ ) {
+ moduleConfig = value;
+ break;
+ }
+ }
+ }
+
+ const options = (moduleConfig?.options ?? {}) as CustomFieldsModuleOptions;
+ const { customFields = {} } = options;
+
+ const tableNames: string[] = [];
+ const entities = Object.entries(customFields).map(([entityName, fields]) => {
+ const tableName = `${camelToSnakeCase(entityName)}_custom_fields`;
+ tableNames.push(tableName);
+
+ const fieldDefs = Object.entries(fields ?? {}).map(([name, field]) => ({
+ ...field,
+ name,
+ nullable: field.nullable ?? true,
+ defaultValue: field.defaultValue ?? null,
+ }));
+
+ return generateEntity(tableName, fieldDefs);
+ });
+
+ if (!entities.length) {
+ logger.info("No custom fields configured. Skipping.");
+ return;
+ }
+
+ logger.info("Syncing custom fields...");
+
+ const dbConfig = ModulesSdkUtils.loadDatabaseConfig("custom_fields");
+ const orm = await DALUtils.mikroOrmCreateConnection(dbConfig, entities, "");
+
+ try {
+ const generator = orm.getSchemaGenerator();
+ const connection = orm.em.getConnection();
+ const platform = orm.em.getPlatform();
+ const schemaName = dbConfig.schema || "public";
+
+ const dbSchema = new DatabaseSchema(platform, schemaName);
+ try {
+ await platform.getSchemaHelper?.()?.loadInformationSchema(
+ dbSchema,
+ connection,
+ tableNames.map((table_name) => ({
+ table_name,
+ schema_name: schemaName,
+ })),
+ );
+ } catch {
+ // Tables don't exist yet — empty schema will generate CREATE TABLE
+ }
+
+ const rawSql = normalizeMigrationSQL(
+ await generator.getUpdateSchemaSQL({
+ fromSchema: dbSchema,
+ }),
+ );
+
+ const sql = pickTableRelatedCommands(tableNames, rawSql);
+
+ if (sql) {
+ await connection.execute(sql);
+ logger.info("Custom fields migrated successfully.");
+ } else {
+ logger.info("Custom fields are up to date.");
+ }
+ } finally {
+ await orm.close(true);
+ }
+}
diff --git a/packages/core-plugin/src/modules/custom-fields/index.ts b/packages/core-plugin/src/modules/custom-fields/index.ts
new file mode 100644
index 000000000..bf0b6cef1
--- /dev/null
+++ b/packages/core-plugin/src/modules/custom-fields/index.ts
@@ -0,0 +1,12 @@
+import { Module } from "@medusajs/framework/utils"
+import CustomFieldsModuleService from "./services/custom-fields-module-service"
+import customFieldsLoader from "./loaders"
+
+export const CUSTOM_FIELDS_MODULE = "custom_fields"
+
+export { BaseField, EnumField, Field, CustomFieldsModuleOptions } from "@mercurjs/types"
+
+export default Module(CUSTOM_FIELDS_MODULE, {
+ service: CustomFieldsModuleService,
+ loaders: [customFieldsLoader],
+})
\ No newline at end of file
diff --git a/packages/core-plugin/src/modules/custom-fields/loaders.ts b/packages/core-plugin/src/modules/custom-fields/loaders.ts
new file mode 100644
index 000000000..c21328eee
--- /dev/null
+++ b/packages/core-plugin/src/modules/custom-fields/loaders.ts
@@ -0,0 +1,78 @@
+import { LoaderOptions, ModuleJoinerConfig } from "@medusajs/framework/types";
+import {
+ camelToSnakeCase,
+} from "@medusajs/framework/utils";
+import { CustomFieldsModuleOptions } from "@mercurjs/types";
+import { MedusaModule } from "@medusajs/framework/modules-sdk";
+
+export default async function customFieldsLoader({
+ logger,
+ options,
+}: LoaderOptions) {
+ const { customFields = {} } = (options ?? {}) as CustomFieldsModuleOptions;
+
+ MedusaModule.setCustomLink((joinerConfigs) => {
+ const entityJoinerConfigMap = new Map<string, ModuleJoinerConfig>();
+
+ for (const joinerConfig of joinerConfigs) {
+ const aliases = Array.isArray(joinerConfig.alias)
+ ? joinerConfig.alias
+ : [joinerConfig.alias];
+ aliases.forEach((alias) => {
+ if (alias?.entity) {
+ entityJoinerConfigMap.set(alias.entity, joinerConfig);
+ }
+ });
+ }
+
+ const extendsConfig: {
+ serviceName: string;
+ entity: string;
+ fieldAlias: Record<string, { path: string; isList: boolean }>;
+ relationship: {
+ serviceName: string;
+ primaryKey: string;
+ foreignKey: string;
+ alias: string;
+ isList: boolean;
+ };
+ }[] = [];
+
+ Object.entries(customFields ?? {}).forEach(([entityName]) => {
+ const joinerConfig = entityJoinerConfigMap.get(entityName);
+
+ if (!joinerConfig || !joinerConfig.serviceName) {
+ logger?.error(`Invalid entity name: ${entityName}`);
+ return;
+ }
+
+ const snakeEntity = camelToSnakeCase(entityName);
+ const linkableKey = `${snakeEntity}_id`;
+ const relationshipAlias = `${snakeEntity}_custom_fields_link`;
+
+ extendsConfig.push({
+ serviceName: joinerConfig.serviceName!,
+ entity: entityName,
+ fieldAlias: {
+ custom_fields: {
+ path: relationshipAlias,
+ isList: false,
+ },
+ },
+ relationship: {
+ serviceName: "custom_fields",
+ primaryKey: linkableKey,
+ foreignKey: "id",
+ alias: relationshipAlias,
+ isList: false,
+ },
+ });
+ });
+
+ return {
+ isLink: true,
+ isReadOnlyLink: true,
+ extends: extendsConfig,
+ };
+ });
+}
diff --git a/packages/core-plugin/src/modules/custom-fields/services/custom-fields-module-service.ts b/packages/core-plugin/src/modules/custom-fields/services/custom-fields-module-service.ts
new file mode 100644
index 000000000..5999439fe
--- /dev/null
+++ b/packages/core-plugin/src/modules/custom-fields/services/custom-fields-module-service.ts
@@ -0,0 +1,162 @@
+import { CustomFieldsModuleOptions } from "@mercurjs/types";
+import { FindConfig } from "@medusajs/framework/types";
+import {
+ MedusaError,
+ compressName,
+ generateEntityId,
+ camelToSnakeCase,
+} from "@medusajs/framework/utils";
+import { MedusaModule } from "@medusajs/framework/modules-sdk";
+
+export default class CustomFieldsModuleService {
+ protected readonly options_: CustomFieldsModuleOptions;
+ protected aliasToEntityMap_: Map<string, string> = new Map();
+ protected pgConnection_: any;
+
+ __hooks = {
+ onApplicationStart: async () => {
+ this.onApplicationStart();
+ },
+ };
+
+ constructor(container, options: CustomFieldsModuleOptions) {
+ this.options_ = options;
+ this.pgConnection_ = container.__pg_connection__;
+ }
+
+ async onApplicationStart(): Promise<void> {
+ this.buildAliasToEntityMap_();
+ }
+
+ protected buildAliasToEntityMap_(): void {
+ const joinerConfigs = MedusaModule.getAllJoinerConfigs();
+ const entityNames = Object.keys(this.options_.customFields ?? {});
+
+ for (const joinerConfig of joinerConfigs) {
+ const joinerConfigAliases = Array.isArray(joinerConfig.alias)
+ ? joinerConfig.alias
+ : [joinerConfig.alias!];
+
+ for (const entityName of entityNames) {
+ const entityAlias = joinerConfigAliases.find(
+ (alias) => alias?.entity === entityName
+ );
+
+ if (!entityAlias) {
+ continue;
+ }
+
+ const names = Array.isArray(entityAlias.name)
+ ? entityAlias.name
+ : [entityAlias.name];
+
+ const snakeEntity = camelToSnakeCase(entityName);
+
+ for (const name of names) {
+ this.aliasToEntityMap_.set(name, snakeEntity);
+ }
+ }
+ }
+ }
+
+ async list(
+ filter: Record<string, string | string[]>,
+ config: FindConfig<any>,
+ ) {
+ if (Object.keys(filter).length !== 1) {
+ throw new MedusaError(MedusaError.Types.INVALID_ARGUMENT, 'Only single filter is allowed');
+ }
+
+ const filterKey = Object.keys(filter)[0];
+ const filterValue = filter[filterKey];
+ const alias = filterKey.split('_').slice(0, -1).join('_');
+ const tableName = compressName(`${alias}_custom_fields`);
+ const knex = this.pgConnection_;
+
+ const query = knex(tableName).whereNull('deleted_at');
+
+ if (Array.isArray(filterValue)) {
+ query.whereIn(filterKey, filterValue);
+ } else {
+ query.where(filterKey, filterValue);
+ }
+
+ if (config.select) {
+ query.select(config.select as string[]);
+ }
+
+ return await query;
+ }
+
+ protected resolveAlias_(alias: string): string {
+ const snakeEntity = this.aliasToEntityMap_.get(alias);
+
+ if (!snakeEntity) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_ARGUMENT,
+ `Unknown custom fields alias: ${alias}`
+ );
+ }
+
+ return snakeEntity;
+ }
+
+ async create(
+ alias: string,
+ data: { id: string;[key: string]: unknown }[]
+ ) {
+ const snakeEntity = this.resolveAlias_(alias);
+ const tableName = compressName(`${snakeEntity}_custom_fields`);
+ const knex = this.pgConnection_;
+
+
+ const rows = data.map((entry) => {
+ const { id, ...fields } = entry
+ return {
+ ...fields,
+ [snakeEntity + '_id']: id,
+ id: generateEntityId(undefined as any, "cf"),
+ }
+ });
+
+ await knex.transaction(async (trx) => {
+ await trx(tableName).insert(rows);
+ });
+
+ return rows;
+ }
+
+ async update(
+ alias: string,
+ data: { id: string;[key: string]: unknown }[],
+ ) {
+ const snakeEntity = this.resolveAlias_(alias);
+ const tableName = compressName(`${snakeEntity}_custom_fields`);
+ const knex = this.pgConnection_;
+
+ await knex.transaction(async (trx) => {
+ for (const { id, ...fields } of data) {
+ await trx(tableName)
+ .where(`${snakeEntity + '_id'}`, id)
+ .update({ ...fields, updated_at: new Date() });
+ }
+ });
+
+ return data;
+ }
+
+ async delete(
+ alias: string,
+ ids: string[],
+ ) {
+ const snakeEntity = this.resolveAlias_(alias);
+ const tableName = compressName(`${snakeEntity}_custom_fields`);
+ const knex = this.pgConnection_;
+
+ await knex.transaction(async (trx) => {
+ await trx(tableName)
+ .whereIn('id', ids)
+ .update({ deleted_at: new Date() });
+ });
+ }
+}
diff --git a/packages/core-plugin/src/modules/custom-fields/utils/generate-entity.ts b/packages/core-plugin/src/modules/custom-fields/utils/generate-entity.ts
new file mode 100644
index 000000000..4d30035cf
--- /dev/null
+++ b/packages/core-plugin/src/modules/custom-fields/utils/generate-entity.ts
@@ -0,0 +1,128 @@
+import {
+ compressName,
+ mikroOrmSoftDeletableFilterOptions,
+ simpleHash,
+ SoftDeletableFilterKey,
+} from "@medusajs/framework/utils"
+
+import { EntityKey, EntitySchema } from "@medusajs/framework/mikro-orm/core"
+import { Field } from "@mercurjs/types"
+
+function getClass(className: string, ...properties) {
+ const cls = {
+ [className]: class {
+ constructor(...values) {
+ properties.forEach((name, idx) => {
+ this[name] = values[idx]
+ })
+ }
+ }
+ }
+ return cls[className]
+}
+
+export function generateEntity(
+ tableName: string,
+ fields: (Field & { name: string })[]
+) {
+ // e.g. "product_custom_fields" -> "product_id"
+ const entityName = tableName.replace(/_custom_fields$/, "")
+ const foreignKeyName = `${entityName}_id`
+ const fieldNames = [foreignKeyName, ...fields.map((f) => f.name)]
+
+ const typeMap: Record<string, string> = {
+ string: "string",
+ text: "text",
+ integer: "number",
+ float: "number",
+ boolean: "boolean",
+ date: "date",
+ time: "time",
+ datetime: "date",
+ json: "any",
+ array: "array",
+ enum: "enum",
+ }
+
+ const properties = fields.reduce((acc, field) => {
+ const prop: Record<string, any> = {
+ type: typeMap[field.type] ?? field.type,
+ nullable: field.nullable ?? true,
+ ...(field.defaultValue !== undefined
+ ? {
+ defaultRaw: typeof field.defaultValue === 'string'
+ ? `'${field.defaultValue.replace(/'/g, "''")}'`
+ : String(field.defaultValue)
+ }
+ : {}),
+ }
+
+ if (field.type === "enum" && "enum" in field) {
+ prop.items = () => field.enum
+ prop.enum = true
+ }
+
+ acc[field.name] = prop
+ return acc
+ }, {} as Record<string, any>)
+
+ const hashTableName = simpleHash(tableName)
+ const compressed = compressName(tableName)
+
+ return new EntitySchema({
+ class: getClass(
+ tableName,
+ ...fieldNames.concat("created_at", "updated_at", "deleted_at")
+ ) as any,
+ tableName: compressed,
+ properties: {
+ id: {
+ type: "string",
+ nullable: false,
+ primary: true,
+ },
+ [foreignKeyName]: {
+ type: "string",
+ nullable: false,
+ },
+ ...properties,
+ created_at: {
+ columnType: "timestamptz",
+ type: "date",
+ nullable: false,
+ defaultRaw: "CURRENT_TIMESTAMP",
+ },
+ updated_at: {
+ columnType: "timestamptz",
+ type: "date",
+ nullable: false,
+ defaultRaw: "CURRENT_TIMESTAMP",
+ },
+ deleted_at: {
+ columnType: "timestamptz",
+ type: "date",
+ nullable: true,
+ },
+ } as any,
+ filters: {
+ [SoftDeletableFilterKey]: mikroOrmSoftDeletableFilterOptions,
+ },
+ hooks: {
+ beforeUpdate: [
+ (args) => {
+ args.entity.updated_at = new Date()
+ },
+ ],
+ },
+ indexes: [
+ {
+ properties: ["id"],
+ name: "IDX_id_" + hashTableName,
+ },
+ {
+ properties: ["deleted_at"],
+ name: "IDX_deleted_at_" + hashTableName,
+ },
+ ],
+ })
+}
diff --git a/packages/dashboard-sdk/package.json b/packages/dashboard-sdk/package.json
index 3b9b95cea..ba32079ec 100644
--- a/packages/dashboard-sdk/package.json
+++ b/packages/dashboard-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/dashboard-sdk",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/dashboard-shared/package.json b/packages/dashboard-shared/package.json
index 0e482b03c..54e7fc237 100644
--- a/packages/dashboard-shared/package.json
+++ b/packages/dashboard-shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/dashboard-shared",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/types/package.json b/packages/types/package.json
index 7754d5c50..1ca975245 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/types",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",
diff --git a/packages/types/src/custom-fields/index.ts b/packages/types/src/custom-fields/index.ts
new file mode 100644
index 000000000..97f2a5cf2
--- /dev/null
+++ b/packages/types/src/custom-fields/index.ts
@@ -0,0 +1,23 @@
+export type BaseField = {
+ type: 'string'
+ | 'text'
+ | 'integer'
+ | 'boolean'
+ | 'date'
+ | 'time'
+ | 'datetime'
+ | 'json'
+ | 'array'
+ | 'float',
+ nullable?: boolean,
+ defaultValue?: any
+}
+
+export type EnumField = Omit<BaseField, 'type'> & {
+ type: 'enum',
+ enum: string[],
+}
+
+export type Field = BaseField | EnumField
+
+export type CustomFieldsModuleOptions = { customFields?: { [K in string]?: Record<string, Field> } }
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 9d002b669..3797a6ec7 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -18,3 +18,5 @@ export * from "./payout"
// Modules
export * from "./modules"
+// Custom fields types
+export * from "./custom-fields"
\ No newline at end of file
diff --git a/packages/types/src/modules.ts b/packages/types/src/modules.ts
index e13997411..9623d1e8e 100644
--- a/packages/types/src/modules.ts
+++ b/packages/types/src/modules.ts
@@ -2,4 +2,5 @@ export enum MercurModules {
SELLER = "seller",
COMMISSION = "commission",
PAYOUT = "payout",
+ CUSTOM_FIELDS = "custom_fields",
}
diff --git a/packages/vendor/package.json b/packages/vendor/package.json
index ea6e3d6a3..892630177 100644
--- a/packages/vendor/package.json
+++ b/packages/vendor/package.json
@@ -1,6 +1,6 @@
{
"name": "@mercurjs/vendor",
- "version": "2.0.0-canary.40",
+ "version": "2.0.0-canary.41",
"repository": {
"type": "git",
"url": "https://github.com/mercurjs/mercur",