@unifiedcommerce/core 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/package.json +2 -1
  2. package/src/adapters/console-email.ts +43 -0
  3. package/src/auth/access.ts +187 -0
  4. package/src/auth/auth-schema.ts +139 -0
  5. package/src/auth/middleware.ts +161 -0
  6. package/src/auth/org.ts +41 -0
  7. package/src/auth/permissions.ts +28 -0
  8. package/src/auth/setup.ts +171 -0
  9. package/src/auth/system-actor.ts +19 -0
  10. package/src/auth/types.ts +10 -0
  11. package/src/config/defaults.ts +82 -0
  12. package/src/config/define-config.ts +53 -0
  13. package/src/config/types.ts +301 -0
  14. package/src/generated/plugin-capabilities.d.ts +20 -0
  15. package/src/generated/plugin-manifest.ts +23 -0
  16. package/src/generated/plugin-repositories.d.ts +20 -0
  17. package/src/hooks/checkout-completion.ts +262 -0
  18. package/src/hooks/checkout.ts +677 -0
  19. package/src/hooks/order-emails.ts +62 -0
  20. package/src/index.ts +215 -0
  21. package/src/interfaces/mcp/agent-prompt.ts +174 -0
  22. package/src/interfaces/mcp/context-enrichment.ts +177 -0
  23. package/src/interfaces/mcp/server.ts +47 -0
  24. package/src/interfaces/mcp/tool-builder.ts +261 -0
  25. package/src/interfaces/mcp/tools/analytics.ts +76 -0
  26. package/src/interfaces/mcp/tools/cart.ts +57 -0
  27. package/src/interfaces/mcp/tools/catalog.ts +299 -0
  28. package/src/interfaces/mcp/tools/index.ts +22 -0
  29. package/src/interfaces/mcp/tools/inventory.ts +161 -0
  30. package/src/interfaces/mcp/tools/orders.ts +104 -0
  31. package/src/interfaces/mcp/tools/pricing.ts +94 -0
  32. package/src/interfaces/mcp/tools/promotions.ts +106 -0
  33. package/src/interfaces/mcp/tools/registry.ts +101 -0
  34. package/src/interfaces/mcp/tools/search.ts +42 -0
  35. package/src/interfaces/mcp/tools/webhooks.ts +48 -0
  36. package/src/interfaces/mcp/transport.ts +128 -0
  37. package/src/interfaces/rest/customer-portal.ts +299 -0
  38. package/src/interfaces/rest/index.ts +74 -0
  39. package/src/interfaces/rest/router.ts +333 -0
  40. package/src/interfaces/rest/routes/admin-jobs.ts +58 -0
  41. package/src/interfaces/rest/routes/audit.ts +50 -0
  42. package/src/interfaces/rest/routes/carts.ts +89 -0
  43. package/src/interfaces/rest/routes/catalog.ts +493 -0
  44. package/src/interfaces/rest/routes/checkout.ts +284 -0
  45. package/src/interfaces/rest/routes/inventory.ts +70 -0
  46. package/src/interfaces/rest/routes/media.ts +86 -0
  47. package/src/interfaces/rest/routes/orders.ts +78 -0
  48. package/src/interfaces/rest/routes/payments.ts +60 -0
  49. package/src/interfaces/rest/routes/pricing.ts +57 -0
  50. package/src/interfaces/rest/routes/promotions.ts +93 -0
  51. package/src/interfaces/rest/routes/search.ts +71 -0
  52. package/src/interfaces/rest/routes/webhooks.ts +46 -0
  53. package/src/interfaces/rest/schemas/admin-jobs.ts +40 -0
  54. package/src/interfaces/rest/schemas/audit.ts +46 -0
  55. package/src/interfaces/rest/schemas/carts.ts +125 -0
  56. package/src/interfaces/rest/schemas/catalog.ts +450 -0
  57. package/src/interfaces/rest/schemas/checkout.ts +66 -0
  58. package/src/interfaces/rest/schemas/customer-portal.ts +195 -0
  59. package/src/interfaces/rest/schemas/inventory.ts +138 -0
  60. package/src/interfaces/rest/schemas/media.ts +75 -0
  61. package/src/interfaces/rest/schemas/orders.ts +104 -0
  62. package/src/interfaces/rest/schemas/pricing.ts +80 -0
  63. package/src/interfaces/rest/schemas/promotions.ts +110 -0
  64. package/src/interfaces/rest/schemas/responses.ts +85 -0
  65. package/src/interfaces/rest/schemas/search.ts +58 -0
  66. package/src/interfaces/rest/schemas/shared.ts +62 -0
  67. package/src/interfaces/rest/schemas/webhooks.ts +68 -0
  68. package/src/interfaces/rest/utils.ts +104 -0
  69. package/src/interfaces/rest/webhook-router.ts +50 -0
  70. package/src/kernel/compensation/executor.ts +61 -0
  71. package/src/kernel/compensation/types.ts +26 -0
  72. package/src/kernel/database/adapter.ts +21 -0
  73. package/src/kernel/database/drizzle-db.ts +56 -0
  74. package/src/kernel/database/migrate.ts +76 -0
  75. package/src/kernel/database/plugin-types.ts +34 -0
  76. package/src/kernel/database/schema.ts +49 -0
  77. package/src/kernel/database/scoped-db.ts +68 -0
  78. package/src/kernel/database/tx-context.ts +46 -0
  79. package/src/kernel/error-mapper.ts +15 -0
  80. package/src/kernel/errors.ts +89 -0
  81. package/src/kernel/factory/repository-factory.ts +244 -0
  82. package/src/kernel/hooks/create-context.ts +43 -0
  83. package/src/kernel/hooks/executor.ts +88 -0
  84. package/src/kernel/hooks/registry.ts +74 -0
  85. package/src/kernel/hooks/types.ts +52 -0
  86. package/src/kernel/http-error.ts +44 -0
  87. package/src/kernel/jobs/adapter.ts +36 -0
  88. package/src/kernel/jobs/drizzle-adapter.ts +58 -0
  89. package/src/kernel/jobs/runner.ts +153 -0
  90. package/src/kernel/jobs/schema.ts +46 -0
  91. package/src/kernel/jobs/types.ts +30 -0
  92. package/src/kernel/local-api.ts +187 -0
  93. package/src/kernel/plugin/manifest.ts +271 -0
  94. package/src/kernel/query/executor.ts +184 -0
  95. package/src/kernel/query/registry.ts +46 -0
  96. package/src/kernel/result.ts +33 -0
  97. package/src/kernel/schema/extra-columns.ts +37 -0
  98. package/src/kernel/service-registry.ts +76 -0
  99. package/src/kernel/service-timing.ts +89 -0
  100. package/src/kernel/state-machine/machine.ts +101 -0
  101. package/src/modules/analytics/drizzle-adapter.ts +426 -0
  102. package/src/modules/analytics/hooks.ts +11 -0
  103. package/src/modules/analytics/models.ts +125 -0
  104. package/src/modules/analytics/repository/index.ts +6 -0
  105. package/src/modules/analytics/service.ts +245 -0
  106. package/src/modules/analytics/types.ts +180 -0
  107. package/src/modules/audit/hooks.ts +78 -0
  108. package/src/modules/audit/schema.ts +33 -0
  109. package/src/modules/audit/service.ts +151 -0
  110. package/src/modules/cart/access.ts +27 -0
  111. package/src/modules/cart/matcher.ts +26 -0
  112. package/src/modules/cart/repository/index.ts +234 -0
  113. package/src/modules/cart/schema.ts +42 -0
  114. package/src/modules/cart/schemas.ts +38 -0
  115. package/src/modules/cart/service.ts +541 -0
  116. package/src/modules/catalog/repository/index.ts +772 -0
  117. package/src/modules/catalog/schema.ts +203 -0
  118. package/src/modules/catalog/schemas.ts +104 -0
  119. package/src/modules/catalog/service.ts +1544 -0
  120. package/src/modules/customers/repository/index.ts +327 -0
  121. package/src/modules/customers/schema.ts +64 -0
  122. package/src/modules/customers/service.ts +171 -0
  123. package/src/modules/fulfillment/repository/index.ts +426 -0
  124. package/src/modules/fulfillment/schema.ts +101 -0
  125. package/src/modules/fulfillment/service.ts +555 -0
  126. package/src/modules/fulfillment/types.ts +59 -0
  127. package/src/modules/inventory/repository/index.ts +509 -0
  128. package/src/modules/inventory/schema.ts +94 -0
  129. package/src/modules/inventory/schemas.ts +38 -0
  130. package/src/modules/inventory/service.ts +490 -0
  131. package/src/modules/media/adapter.ts +17 -0
  132. package/src/modules/media/repository/index.ts +274 -0
  133. package/src/modules/media/schema.ts +41 -0
  134. package/src/modules/media/service.ts +151 -0
  135. package/src/modules/orders/repository/index.ts +287 -0
  136. package/src/modules/orders/schema.ts +66 -0
  137. package/src/modules/orders/service.ts +619 -0
  138. package/src/modules/orders/stale-order-cleanup.ts +76 -0
  139. package/src/modules/organization/service.ts +191 -0
  140. package/src/modules/payments/adapter.ts +47 -0
  141. package/src/modules/payments/repository/index.ts +6 -0
  142. package/src/modules/payments/service.ts +107 -0
  143. package/src/modules/pricing/repository/index.ts +291 -0
  144. package/src/modules/pricing/schema.ts +71 -0
  145. package/src/modules/pricing/schemas.ts +38 -0
  146. package/src/modules/pricing/service.ts +494 -0
  147. package/src/modules/promotions/repository/index.ts +325 -0
  148. package/src/modules/promotions/schema.ts +62 -0
  149. package/src/modules/promotions/schemas.ts +38 -0
  150. package/src/modules/promotions/service.ts +598 -0
  151. package/src/modules/search/adapter.ts +57 -0
  152. package/src/modules/search/hooks.ts +12 -0
  153. package/src/modules/search/repository/index.ts +6 -0
  154. package/src/modules/search/service.ts +315 -0
  155. package/src/modules/shipping/calculator.ts +188 -0
  156. package/src/modules/shipping/repository/index.ts +6 -0
  157. package/src/modules/shipping/service.ts +51 -0
  158. package/src/modules/tax/adapter.ts +60 -0
  159. package/src/modules/tax/repository/index.ts +6 -0
  160. package/src/modules/tax/service.ts +53 -0
  161. package/src/modules/webhooks/hook.ts +34 -0
  162. package/src/modules/webhooks/repository/index.ts +278 -0
  163. package/src/modules/webhooks/schema.ts +56 -0
  164. package/src/modules/webhooks/service.ts +117 -0
  165. package/src/modules/webhooks/signing.ts +6 -0
  166. package/src/modules/webhooks/ssrf-guard.ts +71 -0
  167. package/src/modules/webhooks/tasks.ts +52 -0
  168. package/src/modules/webhooks/worker.ts +134 -0
  169. package/src/runtime/commerce.ts +145 -0
  170. package/src/runtime/kernel.ts +426 -0
  171. package/src/runtime/logger.ts +36 -0
  172. package/src/runtime/server.ts +355 -0
  173. package/src/runtime/shutdown.ts +43 -0
  174. package/src/test-utils/create-pglite-adapter.ts +129 -0
  175. package/src/test-utils/create-plugin-test-app.ts +128 -0
  176. package/src/test-utils/create-repository-test-harness.ts +16 -0
  177. package/src/test-utils/create-test-config.ts +190 -0
  178. package/src/test-utils/create-test-kernel.ts +7 -0
  179. package/src/test-utils/create-test-plugin-context.ts +75 -0
  180. package/src/test-utils/rest-api-test-utils.ts +265 -0
  181. package/src/test-utils/test-actors.ts +62 -0
  182. package/src/test-utils/typed-hooks.ts +54 -0
  183. package/src/types/commerce-types.ts +34 -0
  184. package/src/utils/id.ts +3 -0
  185. package/src/utils/logger.ts +18 -0
  186. package/src/utils/pagination.ts +22 -0
@@ -0,0 +1,171 @@
1
+ import { drizzleAdapter } from "@better-auth/drizzle-adapter";
2
+ import { betterAuth } from "better-auth";
3
+ import type { Role } from "better-auth/plugins/access";
4
+ import { apiKey } from "@better-auth/api-key";
5
+ import { organization, twoFactor, phoneNumber, jwt, bearer } from "better-auth/plugins";
6
+ import type { CommerceConfig } from "../config/types.js";
7
+ import type { DatabaseAdapter } from "../kernel/database/adapter.js";
8
+ import * as authSchema from "./auth-schema.js";
9
+
10
+ type BetterAuthDbProvider = "pg" | "mysql" | "sqlite";
11
+
12
+ function resolveAuthDbProvider(provider: string): BetterAuthDbProvider {
13
+ if (
14
+ provider === "postgres" ||
15
+ provider === "postgresql" ||
16
+ provider === "pg"
17
+ ) {
18
+ return "pg";
19
+ }
20
+ if (provider === "mysql") {
21
+ return "mysql";
22
+ }
23
+ if (provider === "sqlite") {
24
+ return "sqlite";
25
+ }
26
+ throw new Error(
27
+ `Unsupported auth database provider "${provider}". Expected one of: postgres, mysql, sqlite.`,
28
+ );
29
+ }
30
+
31
+ interface AuthEmailPayload {
32
+ user: {
33
+ email: string;
34
+ name: string | null;
35
+ };
36
+ url: string;
37
+ }
38
+
39
+ export interface AuthInstance {
40
+ handler(request: Request): Promise<Response>;
41
+ api: {
42
+ getSession(input: { headers: Headers }): Promise<unknown>;
43
+ getActiveMemberRole?: (input: { headers: Headers }) => Promise<unknown>;
44
+ verifyApiKey?: (input: {
45
+ body: { key: string; permissions?: Record<string, string[]> };
46
+ }) => Promise<{
47
+ valid: boolean;
48
+ error: { message: string; code: string } | null;
49
+ key: Record<string, unknown> | null;
50
+ }>;
51
+ createApiKey?: (input: {
52
+ body: {
53
+ name?: string;
54
+ permissions?: Record<string, string[]>;
55
+ userId?: string;
56
+ };
57
+ headers?: Headers;
58
+ }) => Promise<{ key: string; id: string }>;
59
+ /** Allow access to other Better Auth API methods added by plugins */
60
+ [key: string]: unknown;
61
+ };
62
+ options?: Record<string, unknown>;
63
+ $context?: Promise<unknown>;
64
+ }
65
+
66
+ export function createAuth(
67
+ db: DatabaseAdapter,
68
+ config: CommerceConfig,
69
+ ): AuthInstance {
70
+ const plugins: Array<
71
+ | ReturnType<typeof organization>
72
+ | ReturnType<typeof twoFactor>
73
+ | ReturnType<typeof apiKey>
74
+ | ReturnType<typeof phoneNumber>
75
+ | ReturnType<typeof jwt>
76
+ | ReturnType<typeof bearer>
77
+ > = [
78
+ organization({
79
+ // Better Auth's Role includes `authorize` and `statements` fields that
80
+ // our RoleDefinition doesn't have. Double-cast is required — upstream type gap.
81
+ roles: (config.auth?.roles ?? {}) as unknown as Record<string, Role | undefined>,
82
+ }),
83
+ bearer(),
84
+ jwt(),
85
+ ];
86
+
87
+ if (config.auth?.twoFactor?.enabled) {
88
+ plugins.push(twoFactor({ issuer: config.storeName ?? "UnifiedCommerce" }));
89
+ }
90
+
91
+ if (config.auth?.apiKeys?.enabled) {
92
+ plugins.push(apiKey());
93
+ }
94
+
95
+ if (config.auth?.phoneAuth) {
96
+ plugins.push(phoneNumber({
97
+ sendOTP: config.auth.phoneAuth.sendOTP,
98
+ verifyOTP: config.auth.phoneAuth.verifyOTP,
99
+ otpLength: config.auth.phoneAuth.otpLength ?? 6,
100
+ expiresIn: config.auth.phoneAuth.expiresIn ?? 300,
101
+ signUpOnVerification: config.auth.phoneAuth.signUpOnVerification ?? {
102
+ getTempEmail: (phone: string) => `${phone.replace(/\+/g, "")}@phone.local`,
103
+ },
104
+ }));
105
+ }
106
+
107
+ // API key support can be attached via external plugin package in newer better-auth versions.
108
+
109
+ try {
110
+ const auth = betterAuth({
111
+ // Better Auth's drizzle adapter expects a plain object, not PgDatabase.
112
+ // Double-cast required — PgDatabase has no index signature.
113
+ database: drizzleAdapter(db.db as unknown as Record<string, unknown>, {
114
+ provider: resolveAuthDbProvider(db.provider),
115
+ schema: authSchema,
116
+ }),
117
+ trustedOrigins: config.auth?.trustedOrigins ?? [],
118
+ emailAndPassword: {
119
+ enabled: true,
120
+ requireEmailVerification: config.auth?.requireEmailVerification ?? true,
121
+ sendResetPassword: async ({ user, url }: AuthEmailPayload) => {
122
+ if (!config.email) return;
123
+ await config.email.send({
124
+ template: "password-reset",
125
+ to: user.email,
126
+ data: { resetUrl: url, userName: user.name },
127
+ });
128
+ },
129
+ sendVerificationEmail: async ({ user, url }: AuthEmailPayload) => {
130
+ if (!config.email) return;
131
+ await config.email.send({
132
+ template: "email-verification",
133
+ to: user.email,
134
+ data: { verifyUrl: url, userName: user.name },
135
+ });
136
+ },
137
+ },
138
+ socialProviders: config.auth?.socialProviders ?? {},
139
+ session: {
140
+ expiresIn: config.auth?.sessionDuration ?? 60 * 60 * 24 * 7,
141
+ updateAge: 60 * 60 * 24,
142
+ cookieCache: {
143
+ enabled: true,
144
+ maxAge: 60 * 5, // 5 minute cookie cache for performance
145
+ },
146
+ },
147
+ advanced: {
148
+ cookiePrefix: "uc",
149
+ useSecureCookies: process.env.NODE_ENV === "production",
150
+ },
151
+ plugins,
152
+ user: {
153
+ additionalFields: {
154
+ vendorId: { type: "string", required: false },
155
+ posOperatorPin: { type: "string", required: false },
156
+ },
157
+ },
158
+ });
159
+ // Better Auth's plugin-extended return type is structurally incompatible with
160
+ // our simplified AuthInstance interface (upstream generic union vs our narrowed shape).
161
+ // Double-cast is the accepted pattern — same approach used by PayloadCMS.
162
+ // @see https://github.com/better-auth/better-auth/discussions
163
+ return auth as unknown as AuthInstance;
164
+ } catch (error) {
165
+ const message =
166
+ error instanceof Error
167
+ ? error.message
168
+ : "Unknown better-auth initialization error.";
169
+ throw new Error(`Failed to initialize authentication: ${message}`);
170
+ }
171
+ }
@@ -0,0 +1,19 @@
1
+ import type { Actor } from "./types.js";
2
+ import { DEFAULT_ORG_ID } from "./org.js";
3
+
4
+ /**
5
+ * Creates a system actor for internal operations (webhooks, jobs, compensation chains).
6
+ * System actors have full permissions and are scoped to a specific organization.
7
+ */
8
+ export function createSystemActor(orgId: string = DEFAULT_ORG_ID): Actor {
9
+ return {
10
+ type: "api_key",
11
+ userId: "system:internal",
12
+ email: null,
13
+ name: "System",
14
+ vendorId: null,
15
+ organizationId: orgId,
16
+ role: "system",
17
+ permissions: ["*:*"],
18
+ };
19
+ }
@@ -0,0 +1,10 @@
1
+ export interface Actor {
2
+ type: "user" | "api_key";
3
+ userId: string;
4
+ email: string | null;
5
+ name: string;
6
+ vendorId: string | null;
7
+ organizationId: string | null;
8
+ role: string;
9
+ permissions: string[];
10
+ }
@@ -0,0 +1,82 @@
1
+ import type { CommerceConfig } from "./types.js";
2
+
3
+ export const defaultConfig: Partial<CommerceConfig> = {
4
+ version: "0.0.1",
5
+ auth: {
6
+ requireEmailVerification: true,
7
+ sessionDuration: 60 * 60 * 24 * 7,
8
+ twoFactor: { enabled: false },
9
+ apiKeys: { enabled: false },
10
+ posPin: { enabled: false },
11
+ roles: {
12
+ owner: { permissions: ["*:*"] },
13
+ admin: { permissions: ["*:*"] },
14
+ manager: {
15
+ permissions: [
16
+ "catalog:create",
17
+ "catalog:update",
18
+ "catalog:delete",
19
+ "catalog:read",
20
+ "inventory:read",
21
+ "inventory:adjust",
22
+ "orders:read",
23
+ "orders:update",
24
+ "cart:create",
25
+ "cart:update",
26
+ "customers:read:self",
27
+ "customers:update:self",
28
+ ],
29
+ },
30
+ customer: {
31
+ permissions: [
32
+ "catalog:read",
33
+ "cart:create",
34
+ "cart:read",
35
+ "cart:update",
36
+ "orders:create",
37
+ "orders:read:own",
38
+ "customers:read:self",
39
+ "customers:update:self",
40
+ ],
41
+ },
42
+ },
43
+ customerPermissions: [
44
+ "catalog:read",
45
+ "cart:create",
46
+ "cart:read",
47
+ "cart:update",
48
+ "orders:create",
49
+ "orders:read:own",
50
+ "customers:read:self",
51
+ "customers:update:self",
52
+ ],
53
+ },
54
+ cart: {
55
+ ttlMinutes: 60 * 24 * 7,
56
+ hooks: {},
57
+ },
58
+ checkout: {
59
+ hooks: {
60
+ beforeCreate: [],
61
+ afterCreate: [],
62
+ },
63
+ },
64
+ orders: {
65
+ hooks: {
66
+ beforeCreate: [],
67
+ afterCreate: [],
68
+ beforeStatusChange: [],
69
+ afterStatusChange: [],
70
+ beforeDelete: [],
71
+ },
72
+ },
73
+ inventory: {
74
+ hooks: {
75
+ afterAdjust: [],
76
+ },
77
+ },
78
+ mcp: {
79
+ enabled: true,
80
+ capabilities: ["catalog:read", "orders:read", "inventory:read"],
81
+ },
82
+ };
@@ -0,0 +1,53 @@
1
+ import { defaultConfig } from "./defaults.js";
2
+ import type { CommerceConfig, DefineConfigInput } from "./types.js";
3
+ import { _resetRegisteredPlugins } from "../kernel/plugin/manifest.js";
4
+
5
+ function isRecord(value: unknown): value is Record<string, unknown> {
6
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7
+ }
8
+
9
+ function merge<T extends object>(base: T, next: Partial<T>): T {
10
+ const output: Record<string, unknown> = {
11
+ ...(base as Record<string, unknown>),
12
+ };
13
+ for (const [key, value] of Object.entries(next as Record<string, unknown>)) {
14
+ if (value === undefined) continue;
15
+ const baseValue = output[key];
16
+ if (
17
+ isRecord(value) &&
18
+ isRecord(baseValue)
19
+ ) {
20
+ output[key] = merge(baseValue, value);
21
+ } else {
22
+ output[key] = value;
23
+ }
24
+ }
25
+ return output as T;
26
+ }
27
+
28
+ /**
29
+ * Builds the final CommerceConfig by:
30
+ * 1. Merging user input with defaults
31
+ * 2. Applying all plugins (each is a config transform function)
32
+ * 3. Freezing the result to prevent runtime mutation
33
+ */
34
+ export async function defineConfig(
35
+ input: DefineConfigInput,
36
+ ): Promise<CommerceConfig> {
37
+ let config = merge(defaultConfig as CommerceConfig, input);
38
+
39
+ // Merge top-level `schema` into `customSchemas` before plugins run
40
+ if (config.schema?.length) {
41
+ config = {
42
+ ...config,
43
+ customSchemas: [...(config.customSchemas ?? []), ...config.schema],
44
+ };
45
+ }
46
+
47
+ _resetRegisteredPlugins();
48
+ for (const plugin of config.plugins ?? []) {
49
+ config = await plugin(config);
50
+ }
51
+
52
+ return Object.freeze(config);
53
+ }
@@ -0,0 +1,301 @@
1
+ import type { Hono, MiddlewareHandler } from "hono";
2
+ import type { Actor } from "../auth/types.js";
3
+ import type { BeforeHook, AfterHook } from "../kernel/hooks/types.js";
4
+ import type { PaymentAdapter } from "../modules/payments/adapter.js";
5
+ import type { StorageAdapter } from "../modules/media/adapter.js";
6
+ import type { DatabaseAdapter } from "../kernel/database/adapter.js";
7
+ import type { TaxAdapter } from "../modules/tax/adapter.js";
8
+ import type { SearchAdapter } from "../modules/search/adapter.js";
9
+ import type { JobsAdapter } from "../kernel/jobs/adapter.js";
10
+ import type { TaskDefinition } from "../kernel/jobs/types.js";
11
+
12
+ export interface RoleDefinition {
13
+ permissions: string[];
14
+ }
15
+
16
+ export type FieldType = "text" | "number" | "boolean" | "date" | "json" | "relation" | "select";
17
+
18
+ export interface EntityFieldDefinition {
19
+ name: string;
20
+ type: FieldType;
21
+ unit?: string;
22
+ schema?: unknown;
23
+ target?: string;
24
+ options?: string[];
25
+ }
26
+
27
+ export interface EntityVariantConfig {
28
+ enabled: boolean;
29
+ optionTypes?: string[];
30
+ }
31
+
32
+ export interface EntityHooks {
33
+ beforeCreate?: BeforeHook<unknown>[];
34
+ afterCreate?: AfterHook<unknown>[];
35
+ beforeUpdate?: BeforeHook<unknown>[];
36
+ afterUpdate?: AfterHook<unknown>[];
37
+ beforeDelete?: BeforeHook<unknown>[];
38
+ afterDelete?: AfterHook<unknown>[];
39
+ beforeRead?: BeforeHook<unknown>[];
40
+ afterRead?: AfterHook<unknown>[];
41
+ beforeList?: BeforeHook<unknown>[];
42
+ afterList?: AfterHook<unknown>[];
43
+ }
44
+
45
+ export interface EntityConfig {
46
+ fields: EntityFieldDefinition[];
47
+ variants: EntityVariantConfig;
48
+ fulfillment: string;
49
+ hooks?: EntityHooks;
50
+ }
51
+
52
+ export interface AuthConfig {
53
+ requireEmailVerification?: boolean;
54
+ sessionDuration?: number;
55
+ socialProviders?: Record<string, { clientId: string; clientSecret: string }>;
56
+ twoFactor?: { enabled: boolean; requiredForRoles?: string[] };
57
+ apiKeys?: {
58
+ enabled: boolean;
59
+ /** Default permissions for API keys that don't specify their own. */
60
+ defaultPermissions?: string[];
61
+ };
62
+ posPin?: { enabled: boolean };
63
+ roles?: Record<string, RoleDefinition>;
64
+ customerPermissions?: string[];
65
+ /** Origins allowed for CSRF protection (Better Auth `trustedOrigins`). */
66
+ trustedOrigins?: string[];
67
+ /** Enable a config-driven dev API key. OFF by default. Only for local development. */
68
+ enableDevKey?: boolean;
69
+ /** Custom dev key value. Must be set alongside enableDevKey. */
70
+ devKey?: string;
71
+ /**
72
+ * Phone number OTP authentication via Better Auth's phoneNumber plugin.
73
+ * When configured, users can sign in/up with phone + OTP instead of email/password.
74
+ * You provide the SMS delivery callback; Better Auth handles OTP generation,
75
+ * storage, expiry, brute force protection, and session creation.
76
+ */
77
+ phoneAuth?: {
78
+ /** Send OTP to the phone number. Implement with Twilio, AWS SNS, or any SMS gateway. */
79
+ sendOTP: (params: { phoneNumber: string; code: string }, ctx: unknown) => void | Promise<void>;
80
+ /** Optional custom OTP verification (e.g., Twilio Verify). Overrides internal logic. */
81
+ verifyOTP?: (params: { phoneNumber: string; code: string }, ctx: unknown) => boolean | Promise<boolean>;
82
+ /** OTP length. Default: 6. */
83
+ otpLength?: number;
84
+ /** OTP expiry in seconds. Default: 300 (5 minutes). */
85
+ expiresIn?: number;
86
+ /** Auto-create user on first OTP verification. Default: generates temp email from phone. */
87
+ signUpOnVerification?: {
88
+ getTempEmail: (phoneNumber: string) => string;
89
+ getTempName?: (phoneNumber: string) => string;
90
+ };
91
+ };
92
+ }
93
+
94
+ export interface CartConfig {
95
+ ttlMinutes?: number;
96
+ hooks?: {
97
+ beforeAddItem?: BeforeHook<unknown>[];
98
+ afterAddItem?: AfterHook<unknown>[];
99
+ beforeRemoveItem?: BeforeHook<unknown>[];
100
+ afterRemoveItem?: AfterHook<unknown>[];
101
+ beforeUpdateQuantity?: BeforeHook<unknown>[];
102
+ afterUpdateQuantity?: AfterHook<unknown>[];
103
+ };
104
+ }
105
+
106
+ export interface CheckoutConfig {
107
+ hooks?: {
108
+ beforeCreate?: BeforeHook<unknown>[];
109
+ afterCreate?: AfterHook<unknown>[];
110
+ };
111
+ }
112
+
113
+ export interface OrdersConfig {
114
+ hooks?: {
115
+ beforeCreate?: BeforeHook<unknown>[];
116
+ afterCreate?: AfterHook<unknown>[];
117
+ beforeStatusChange?: BeforeHook<unknown>[];
118
+ afterStatusChange?: AfterHook<unknown>[];
119
+ afterGet?: AfterHook<unknown>[];
120
+ beforeDelete?: BeforeHook<unknown>[];
121
+ };
122
+ /**
123
+ * Extend the order state machine with custom transitions.
124
+ * New states (e.g., "payment_initiated", "shipped", "delivered", "defaulted")
125
+ * are added to the default machine. Existing transitions are preserved.
126
+ * See extendOrderStateMachine() for the merge logic.
127
+ */
128
+ customTransitions?: Record<string, string[]>;
129
+ }
130
+
131
+ export interface InventoryConfig {
132
+ hooks?: {
133
+ afterAdjust?: AfterHook<unknown>[];
134
+ };
135
+ }
136
+
137
+ export interface ShippingConfig {
138
+ type: "flat" | "weight_based";
139
+ flatRate: number;
140
+ freeShippingThreshold?: number;
141
+ brackets: Array<{ upToGrams: number; cost: number }>;
142
+ fallbackCost: number;
143
+ }
144
+
145
+ export interface TaxConfig {
146
+ adapter?: TaxAdapter;
147
+ defaultFromAddress?: {
148
+ country: string;
149
+ postalCode: string;
150
+ state?: string;
151
+ city?: string;
152
+ line1?: string;
153
+ };
154
+ }
155
+
156
+ export interface AnalyticsConfig {
157
+ customSchemaPath?: string;
158
+ models?: unknown[];
159
+ }
160
+
161
+ export interface SearchConfig {
162
+ adapter?: SearchAdapter;
163
+ defaultFacets?: string[];
164
+ }
165
+
166
+ export interface MCPTool {
167
+ name: string;
168
+ description: string;
169
+ inputSchema?: Record<string, unknown>;
170
+ handler: (params: unknown) => Promise<unknown>;
171
+ }
172
+
173
+ export interface MCPResource {
174
+ uri: string;
175
+ name: string;
176
+ description: string;
177
+ mimeType: string;
178
+ handler: () => Promise<{ content: Array<{ type: "text"; text: string }> }>;
179
+ }
180
+
181
+ /**
182
+ * A CommercePlugin is a config transform function (PayloadCMS pattern).
183
+ * Receives the current config, returns the modified config.
184
+ * All plugins — simple or complex — are just functions.
185
+ *
186
+ * Use `defineCommercePlugin()` for a structured way to build plugins,
187
+ * or write a raw transform function for full control.
188
+ */
189
+ export type CommercePlugin = (
190
+ config: CommerceConfig,
191
+ ) => CommerceConfig | Promise<CommerceConfig>;
192
+
193
+ export interface CommerceConfig {
194
+ storeName?: string;
195
+ version?: string;
196
+ database: {
197
+ provider: "postgresql";
198
+ options?: Record<string, unknown>;
199
+ };
200
+ databaseAdapter?: DatabaseAdapter;
201
+ auth?: AuthConfig;
202
+ entities?: Record<string, EntityConfig>;
203
+ cart?: CartConfig;
204
+ checkout?: CheckoutConfig;
205
+ orders?: OrdersConfig;
206
+ inventory?: InventoryConfig;
207
+ shipping?: ShippingConfig;
208
+ payments?: PaymentAdapter[];
209
+ storage?: StorageAdapter;
210
+ email?: {
211
+ send(input: {
212
+ template: string;
213
+ to: string;
214
+ data?: Record<string, unknown>;
215
+ }): Promise<void>;
216
+ };
217
+ tax?: TaxConfig;
218
+ analytics?: AnalyticsConfig;
219
+ search?: SearchConfig;
220
+ mcp?: {
221
+ enabled?: boolean;
222
+ capabilities?: string[];
223
+ /** Tool names to enable even when marked as dangerous */
224
+ enableDangerousTools?: string[];
225
+ };
226
+ jobs?: {
227
+ adapter?: JobsAdapter;
228
+ tasks?: TaskDefinition[];
229
+ autorun?: {
230
+ enabled: boolean;
231
+ intervalMs?: number;
232
+ };
233
+ };
234
+ /**
235
+ * Additional Drizzle table definitions — new tables or extended core tables.
236
+ * Each entry is an object of `{ exportName: pgTable(...) }`.
237
+ *
238
+ * These are merged with core schema by `buildSchema(config)` and must also
239
+ * be listed in the app's `drizzle.config.ts` for `db:push` / `db:generate`.
240
+ *
241
+ * Plugins push into this array automatically via `defineCommercePlugin({ schema })`.
242
+ * Apps can also add entries directly — no plugin wrapper needed:
243
+ *
244
+ * ```ts
245
+ * import { reviewsTable } from "./schema/reviews.js";
246
+ * import { extendedProducts } from "./schema/extended-products.js";
247
+ *
248
+ * defineConfig({
249
+ * schema: [
250
+ * { reviewsTable },
251
+ * { extendedProducts },
252
+ * ],
253
+ * // ...
254
+ * });
255
+ * ```
256
+ */
257
+ schema?: Array<Record<string, unknown>>;
258
+ /** @internal Merged from `schema` + plugin schemas. Use `schema` instead. */
259
+ customSchemas?: Array<Record<string, unknown>>;
260
+ hooks?: Record<string, Array<(...args: unknown[]) => unknown>>;
261
+ plugins?: CommercePlugin[];
262
+ middleware?: MiddlewareHandler[];
263
+ routes?: (app: Hono<any>, kernel: unknown) => void;
264
+ mcpTools?: (kernel: unknown) => MCPTool[];
265
+ /** Log level for structured logging. Default: "info". */
266
+ logLevel?: "fatal" | "error" | "warn" | "info" | "debug" | "trace";
267
+ /**
268
+ * Expose the OpenAPI spec (`/api/doc`) and Swagger UI (`/api/reference`).
269
+ * Default: `true` in development, `false` in production.
270
+ */
271
+ exposeOpenApiSpec?: boolean;
272
+ /** Rate limiting overrides. */
273
+ rateLimits?: {
274
+ /** Requests per minute for general API. Default: 100. */
275
+ api?: number;
276
+ /** Requests per minute for auth endpoints. Default: 10. */
277
+ auth?: number;
278
+ /** Requests per minute for checkout. Default: 5. */
279
+ checkout?: number;
280
+ };
281
+ }
282
+
283
+ export interface DefineConfigInput extends CommerceConfig {}
284
+
285
+ export interface AuthSessionLike {
286
+ user: {
287
+ id: string;
288
+ email?: string | null;
289
+ name?: string | null;
290
+ vendorId?: string | null;
291
+ };
292
+ session: {
293
+ activeOrganizationId?: string | null;
294
+ activeOrganizationRole?: string | null;
295
+ };
296
+ }
297
+
298
+ export interface KernelFactoryContext {
299
+ config: CommerceConfig;
300
+ actor: Actor | null;
301
+ }
@@ -0,0 +1,20 @@
1
+ /* eslint-disable */
2
+ // AUTO-GENERATED by scripts/generate-plugin-types.mjs
3
+
4
+ export interface PluginCapabilityRegistryShape {
5
+ "appointments": Record<string, unknown>;
6
+ "cubejs": Record<string, unknown>;
7
+ "gift-cards": Record<string, unknown>;
8
+ "loyalty": Record<string, unknown>;
9
+ "marketplace": Record<string, unknown>;
10
+ "notifications": Record<string, unknown>;
11
+ "pos": Record<string, unknown>;
12
+ "pos-restaurant": Record<string, unknown>;
13
+ "procurement": Record<string, unknown>;
14
+ "production": Record<string, unknown>;
15
+ "reviews": Record<string, unknown>;
16
+ "scheduled-orders": Record<string, unknown>;
17
+ "uom": Record<string, unknown>;
18
+ "warehouse": Record<string, unknown>;
19
+ "wishlist": Record<string, unknown>;
20
+ }
@@ -0,0 +1,23 @@
1
+ /* eslint-disable */
2
+ // AUTO-GENERATED by scripts/generate-plugin-types.mjs
3
+ // DO NOT EDIT MANUALLY.
4
+
5
+ export const resolvedPluginManifest = [
6
+ { id: "appointments", directory: "plugin-appointments" },
7
+ { id: "cubejs", directory: "plugin-cubejs" },
8
+ { id: "gift-cards", directory: "plugin-gift-cards" },
9
+ { id: "loyalty", directory: "plugin-loyalty" },
10
+ { id: "marketplace", directory: "plugin-marketplace" },
11
+ { id: "notifications", directory: "plugin-notifications" },
12
+ { id: "pos", directory: "plugin-pos" },
13
+ { id: "pos-restaurant", directory: "plugin-pos-restaurant" },
14
+ { id: "procurement", directory: "plugin-procurement" },
15
+ { id: "production", directory: "plugin-production" },
16
+ { id: "reviews", directory: "plugin-reviews" },
17
+ { id: "scheduled-orders", directory: "plugin-scheduled-orders" },
18
+ { id: "uom", directory: "plugin-uom" },
19
+ { id: "warehouse", directory: "plugin-warehouse" },
20
+ { id: "wishlist", directory: "plugin-wishlist" },
21
+ ] as const;
22
+
23
+ export type ResolvedPluginId = (typeof resolvedPluginManifest)[number]["id"];