@unifiedcommerce/core 0.1.0 → 0.2.0

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 (245) hide show
  1. package/dist/auth/setup.d.ts.map +1 -1
  2. package/dist/auth/setup.js +8 -3
  3. package/dist/config/types.d.ts +3 -1
  4. package/dist/config/types.d.ts.map +1 -1
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -0
  8. package/dist/interfaces/mcp/server.d.ts +3 -5
  9. package/dist/interfaces/mcp/server.d.ts.map +1 -1
  10. package/dist/interfaces/mcp/server.js +25 -510
  11. package/dist/interfaces/mcp/tool-builder.d.ts +120 -0
  12. package/dist/interfaces/mcp/tool-builder.d.ts.map +1 -0
  13. package/dist/interfaces/mcp/tool-builder.js +224 -0
  14. package/dist/interfaces/mcp/tools/analytics.d.ts +42 -0
  15. package/dist/interfaces/mcp/tools/analytics.d.ts.map +1 -0
  16. package/dist/interfaces/mcp/tools/analytics.js +70 -0
  17. package/dist/interfaces/mcp/tools/cart.d.ts +14 -0
  18. package/dist/interfaces/mcp/tools/cart.d.ts.map +1 -0
  19. package/dist/interfaces/mcp/tools/cart.js +47 -0
  20. package/dist/interfaces/mcp/tools/catalog.d.ts +53 -0
  21. package/dist/interfaces/mcp/tools/catalog.d.ts.map +1 -0
  22. package/dist/interfaces/mcp/tools/catalog.js +284 -0
  23. package/dist/interfaces/mcp/tools/index.d.ts +3 -0
  24. package/dist/interfaces/mcp/tools/index.d.ts.map +1 -0
  25. package/dist/interfaces/mcp/tools/index.js +20 -0
  26. package/dist/interfaces/mcp/tools/inventory.d.ts +27 -0
  27. package/dist/interfaces/mcp/tools/inventory.d.ts.map +1 -0
  28. package/dist/interfaces/mcp/tools/inventory.js +143 -0
  29. package/dist/interfaces/mcp/tools/orders.d.ts +18 -0
  30. package/dist/interfaces/mcp/tools/orders.d.ts.map +1 -0
  31. package/dist/interfaces/mcp/tools/orders.js +82 -0
  32. package/dist/interfaces/mcp/tools/pricing.d.ts +29 -0
  33. package/dist/interfaces/mcp/tools/pricing.d.ts.map +1 -0
  34. package/dist/interfaces/mcp/tools/pricing.js +90 -0
  35. package/dist/interfaces/mcp/tools/promotions.d.ts +44 -0
  36. package/dist/interfaces/mcp/tools/promotions.d.ts.map +1 -0
  37. package/dist/interfaces/mcp/tools/promotions.js +109 -0
  38. package/dist/interfaces/mcp/tools/registry.d.ts +32 -0
  39. package/dist/interfaces/mcp/tools/registry.d.ts.map +1 -0
  40. package/dist/interfaces/mcp/tools/registry.js +55 -0
  41. package/dist/interfaces/mcp/tools/search.d.ts +14 -0
  42. package/dist/interfaces/mcp/tools/search.d.ts.map +1 -0
  43. package/dist/interfaces/mcp/tools/search.js +39 -0
  44. package/dist/interfaces/mcp/tools/webhooks.d.ts +15 -0
  45. package/dist/interfaces/mcp/tools/webhooks.d.ts.map +1 -0
  46. package/dist/interfaces/mcp/tools/webhooks.js +48 -0
  47. package/dist/interfaces/mcp/transport.d.ts +17 -2
  48. package/dist/interfaces/mcp/transport.d.ts.map +1 -1
  49. package/dist/interfaces/mcp/transport.js +91 -44
  50. package/dist/interfaces/rest/router.d.ts.map +1 -1
  51. package/dist/interfaces/rest/routes/checkout.d.ts.map +1 -1
  52. package/dist/interfaces/rest/routes/checkout.js +1 -1
  53. package/dist/interfaces/rest/routes/promotions.d.ts.map +1 -1
  54. package/dist/interfaces/rest/routes/promotions.js +3 -2
  55. package/dist/kernel/database/adapter.d.ts +8 -0
  56. package/dist/kernel/database/adapter.d.ts.map +1 -1
  57. package/dist/kernel/factory/repository-factory.d.ts.map +1 -1
  58. package/dist/kernel/factory/repository-factory.js +3 -1
  59. package/dist/kernel/local-api.d.ts.map +1 -1
  60. package/dist/kernel/local-api.js +2 -0
  61. package/dist/kernel/plugin/manifest.d.ts +3 -3
  62. package/dist/kernel/plugin/manifest.d.ts.map +1 -1
  63. package/dist/kernel/plugin/manifest.js +36 -7
  64. package/dist/runtime/kernel.d.ts +1 -2
  65. package/dist/runtime/kernel.d.ts.map +1 -1
  66. package/dist/runtime/kernel.js +16 -8
  67. package/dist/runtime/server.d.ts.map +1 -1
  68. package/dist/runtime/server.js +8 -3
  69. package/dist/test-utils/create-pglite-adapter.d.ts.map +1 -1
  70. package/dist/test-utils/create-pglite-adapter.js +7 -6
  71. package/dist/tsconfig.tsbuildinfo +1 -0
  72. package/package.json +2 -2
  73. package/src/adapters/console-email.ts +0 -43
  74. package/src/auth/access.ts +0 -187
  75. package/src/auth/auth-schema.ts +0 -139
  76. package/src/auth/middleware.ts +0 -161
  77. package/src/auth/org.ts +0 -41
  78. package/src/auth/permissions.ts +0 -28
  79. package/src/auth/setup.ts +0 -169
  80. package/src/auth/system-actor.ts +0 -19
  81. package/src/auth/types.ts +0 -10
  82. package/src/config/defaults.ts +0 -82
  83. package/src/config/define-config.ts +0 -53
  84. package/src/config/types.ts +0 -299
  85. package/src/generated/plugin-capabilities.d.ts +0 -20
  86. package/src/generated/plugin-manifest.ts +0 -23
  87. package/src/generated/plugin-repositories.d.ts +0 -20
  88. package/src/hooks/checkout-completion.ts +0 -262
  89. package/src/hooks/checkout.ts +0 -677
  90. package/src/hooks/order-emails.ts +0 -62
  91. package/src/index.ts +0 -214
  92. package/src/interfaces/mcp/agent-prompt.ts +0 -174
  93. package/src/interfaces/mcp/context-enrichment.ts +0 -177
  94. package/src/interfaces/mcp/server.ts +0 -617
  95. package/src/interfaces/mcp/transport.ts +0 -68
  96. package/src/interfaces/rest/customer-portal.ts +0 -299
  97. package/src/interfaces/rest/index.ts +0 -74
  98. package/src/interfaces/rest/router.ts +0 -334
  99. package/src/interfaces/rest/routes/admin-jobs.ts +0 -58
  100. package/src/interfaces/rest/routes/audit.ts +0 -50
  101. package/src/interfaces/rest/routes/carts.ts +0 -89
  102. package/src/interfaces/rest/routes/catalog.ts +0 -493
  103. package/src/interfaces/rest/routes/checkout.ts +0 -283
  104. package/src/interfaces/rest/routes/inventory.ts +0 -70
  105. package/src/interfaces/rest/routes/media.ts +0 -86
  106. package/src/interfaces/rest/routes/orders.ts +0 -78
  107. package/src/interfaces/rest/routes/payments.ts +0 -60
  108. package/src/interfaces/rest/routes/pricing.ts +0 -57
  109. package/src/interfaces/rest/routes/promotions.ts +0 -92
  110. package/src/interfaces/rest/routes/search.ts +0 -71
  111. package/src/interfaces/rest/routes/webhooks.ts +0 -46
  112. package/src/interfaces/rest/schemas/admin-jobs.ts +0 -40
  113. package/src/interfaces/rest/schemas/audit.ts +0 -46
  114. package/src/interfaces/rest/schemas/carts.ts +0 -125
  115. package/src/interfaces/rest/schemas/catalog.ts +0 -450
  116. package/src/interfaces/rest/schemas/checkout.ts +0 -66
  117. package/src/interfaces/rest/schemas/customer-portal.ts +0 -195
  118. package/src/interfaces/rest/schemas/inventory.ts +0 -138
  119. package/src/interfaces/rest/schemas/media.ts +0 -75
  120. package/src/interfaces/rest/schemas/orders.ts +0 -104
  121. package/src/interfaces/rest/schemas/pricing.ts +0 -80
  122. package/src/interfaces/rest/schemas/promotions.ts +0 -110
  123. package/src/interfaces/rest/schemas/responses.ts +0 -85
  124. package/src/interfaces/rest/schemas/search.ts +0 -58
  125. package/src/interfaces/rest/schemas/shared.ts +0 -62
  126. package/src/interfaces/rest/schemas/webhooks.ts +0 -68
  127. package/src/interfaces/rest/utils.ts +0 -104
  128. package/src/interfaces/rest/webhook-router.ts +0 -50
  129. package/src/kernel/compensation/executor.ts +0 -61
  130. package/src/kernel/compensation/types.ts +0 -26
  131. package/src/kernel/database/adapter.ts +0 -13
  132. package/src/kernel/database/drizzle-db.ts +0 -56
  133. package/src/kernel/database/migrate.ts +0 -76
  134. package/src/kernel/database/plugin-types.ts +0 -34
  135. package/src/kernel/database/schema.ts +0 -49
  136. package/src/kernel/database/scoped-db.ts +0 -68
  137. package/src/kernel/database/tx-context.ts +0 -46
  138. package/src/kernel/error-mapper.ts +0 -15
  139. package/src/kernel/errors.ts +0 -89
  140. package/src/kernel/factory/repository-factory.ts +0 -242
  141. package/src/kernel/hooks/create-context.ts +0 -43
  142. package/src/kernel/hooks/executor.ts +0 -88
  143. package/src/kernel/hooks/registry.ts +0 -74
  144. package/src/kernel/hooks/types.ts +0 -52
  145. package/src/kernel/http-error.ts +0 -44
  146. package/src/kernel/jobs/adapter.ts +0 -36
  147. package/src/kernel/jobs/drizzle-adapter.ts +0 -58
  148. package/src/kernel/jobs/runner.ts +0 -153
  149. package/src/kernel/jobs/schema.ts +0 -46
  150. package/src/kernel/jobs/types.ts +0 -30
  151. package/src/kernel/local-api.ts +0 -185
  152. package/src/kernel/plugin/manifest.ts +0 -253
  153. package/src/kernel/query/executor.ts +0 -184
  154. package/src/kernel/query/registry.ts +0 -46
  155. package/src/kernel/result.ts +0 -33
  156. package/src/kernel/schema/extra-columns.ts +0 -37
  157. package/src/kernel/service-registry.ts +0 -76
  158. package/src/kernel/service-timing.ts +0 -89
  159. package/src/kernel/state-machine/machine.ts +0 -101
  160. package/src/modules/analytics/drizzle-adapter.ts +0 -426
  161. package/src/modules/analytics/hooks.ts +0 -11
  162. package/src/modules/analytics/models.ts +0 -125
  163. package/src/modules/analytics/repository/index.ts +0 -6
  164. package/src/modules/analytics/service.ts +0 -245
  165. package/src/modules/analytics/types.ts +0 -180
  166. package/src/modules/audit/hooks.ts +0 -78
  167. package/src/modules/audit/schema.ts +0 -33
  168. package/src/modules/audit/service.ts +0 -151
  169. package/src/modules/cart/access.ts +0 -27
  170. package/src/modules/cart/matcher.ts +0 -26
  171. package/src/modules/cart/repository/index.ts +0 -234
  172. package/src/modules/cart/schema.ts +0 -42
  173. package/src/modules/cart/schemas.ts +0 -38
  174. package/src/modules/cart/service.ts +0 -541
  175. package/src/modules/catalog/repository/index.ts +0 -772
  176. package/src/modules/catalog/schema.ts +0 -203
  177. package/src/modules/catalog/schemas.ts +0 -104
  178. package/src/modules/catalog/service.ts +0 -1544
  179. package/src/modules/customers/repository/index.ts +0 -327
  180. package/src/modules/customers/schema.ts +0 -64
  181. package/src/modules/customers/service.ts +0 -171
  182. package/src/modules/fulfillment/repository/index.ts +0 -426
  183. package/src/modules/fulfillment/schema.ts +0 -101
  184. package/src/modules/fulfillment/service.ts +0 -555
  185. package/src/modules/fulfillment/types.ts +0 -59
  186. package/src/modules/inventory/repository/index.ts +0 -509
  187. package/src/modules/inventory/schema.ts +0 -94
  188. package/src/modules/inventory/schemas.ts +0 -38
  189. package/src/modules/inventory/service.ts +0 -490
  190. package/src/modules/media/adapter.ts +0 -17
  191. package/src/modules/media/repository/index.ts +0 -274
  192. package/src/modules/media/schema.ts +0 -41
  193. package/src/modules/media/service.ts +0 -151
  194. package/src/modules/orders/repository/index.ts +0 -287
  195. package/src/modules/orders/schema.ts +0 -66
  196. package/src/modules/orders/service.ts +0 -619
  197. package/src/modules/orders/stale-order-cleanup.ts +0 -76
  198. package/src/modules/organization/service.ts +0 -191
  199. package/src/modules/payments/adapter.ts +0 -47
  200. package/src/modules/payments/repository/index.ts +0 -6
  201. package/src/modules/payments/service.ts +0 -107
  202. package/src/modules/pricing/repository/index.ts +0 -291
  203. package/src/modules/pricing/schema.ts +0 -71
  204. package/src/modules/pricing/schemas.ts +0 -38
  205. package/src/modules/pricing/service.ts +0 -494
  206. package/src/modules/promotions/repository/index.ts +0 -325
  207. package/src/modules/promotions/schema.ts +0 -62
  208. package/src/modules/promotions/schemas.ts +0 -38
  209. package/src/modules/promotions/service.ts +0 -598
  210. package/src/modules/search/adapter.ts +0 -57
  211. package/src/modules/search/hooks.ts +0 -12
  212. package/src/modules/search/repository/index.ts +0 -6
  213. package/src/modules/search/service.ts +0 -315
  214. package/src/modules/shipping/calculator.ts +0 -188
  215. package/src/modules/shipping/repository/index.ts +0 -6
  216. package/src/modules/shipping/service.ts +0 -51
  217. package/src/modules/tax/adapter.ts +0 -60
  218. package/src/modules/tax/repository/index.ts +0 -6
  219. package/src/modules/tax/service.ts +0 -53
  220. package/src/modules/webhooks/hook.ts +0 -34
  221. package/src/modules/webhooks/repository/index.ts +0 -278
  222. package/src/modules/webhooks/schema.ts +0 -56
  223. package/src/modules/webhooks/service.ts +0 -117
  224. package/src/modules/webhooks/signing.ts +0 -6
  225. package/src/modules/webhooks/ssrf-guard.ts +0 -71
  226. package/src/modules/webhooks/tasks.ts +0 -52
  227. package/src/modules/webhooks/worker.ts +0 -134
  228. package/src/runtime/commerce.ts +0 -145
  229. package/src/runtime/kernel.ts +0 -419
  230. package/src/runtime/logger.ts +0 -36
  231. package/src/runtime/server.ts +0 -349
  232. package/src/runtime/shutdown.ts +0 -43
  233. package/src/test-utils/create-pglite-adapter.ts +0 -129
  234. package/src/test-utils/create-plugin-test-app.ts +0 -128
  235. package/src/test-utils/create-repository-test-harness.ts +0 -16
  236. package/src/test-utils/create-test-config.ts +0 -190
  237. package/src/test-utils/create-test-kernel.ts +0 -7
  238. package/src/test-utils/create-test-plugin-context.ts +0 -75
  239. package/src/test-utils/rest-api-test-utils.ts +0 -265
  240. package/src/test-utils/test-actors.ts +0 -62
  241. package/src/test-utils/typed-hooks.ts +0 -54
  242. package/src/types/commerce-types.ts +0 -34
  243. package/src/utils/id.ts +0 -3
  244. package/src/utils/logger.ts +0 -18
  245. package/src/utils/pagination.ts +0 -22
@@ -1,315 +0,0 @@
1
- import { Ok, type Result } from "../../kernel/result.js";
2
- import { resolveOrgId } from "../../auth/org.js";
3
- import type { TxContext } from "../../kernel/database/tx-context.js";
4
- import type { CatalogRepository, SellableEntity } from "../catalog/repository/index.js";
5
- import type {
6
- SearchAdapter,
7
- SearchDocument,
8
- SearchFilters,
9
- SearchQueryParams,
10
- SearchQueryResult,
11
- SearchSuggestParams,
12
- } from "./adapter.js";
13
-
14
- interface SearchServiceDeps {
15
- catalogRepository: CatalogRepository;
16
- adapter?: SearchAdapter;
17
- defaultFacets?: string[];
18
- }
19
-
20
- function unique(values: string[]): string[] {
21
- return [...new Set(values)];
22
- }
23
-
24
- function clamp(value: number, min: number, max: number): number {
25
- return Math.max(min, Math.min(max, value));
26
- }
27
-
28
- function tokenize(query: string): string[] {
29
- return query
30
- .toLowerCase()
31
- .split(/\s+/)
32
- .map((part) => part.trim())
33
- .filter(Boolean);
34
- }
35
-
36
- function includesAllTokens(haystack: string, tokens: string[]): boolean {
37
- if (tokens.length === 0) return true;
38
- const lower = haystack.toLowerCase();
39
- return tokens.every((token) => lower.includes(token));
40
- }
41
-
42
- function scoreText(document: SearchDocument, tokens: string[]): number {
43
- if (tokens.length === 0) return 1;
44
-
45
- const title = document.title.toLowerCase();
46
- const text = document.text.toLowerCase();
47
-
48
- let score = 0;
49
- for (const token of tokens) {
50
- if (title.includes(token)) score += 2;
51
- if (text.includes(token)) score += 1;
52
- }
53
-
54
- return score;
55
- }
56
-
57
- export class SearchService {
58
- constructor(private deps: SearchServiceDeps) {}
59
-
60
- private async entityCategories(
61
- entityId: string,
62
- ctx?: TxContext,
63
- ): Promise<string[]> {
64
- const entries = await this.deps.catalogRepository.findEntityCategories(
65
- entityId,
66
- ctx,
67
- );
68
-
69
- const slugs = (
70
- await Promise.all(
71
- entries.map(async (entry) => {
72
- const category = await this.deps.catalogRepository.findCategoryById(
73
- entry.categoryId,
74
- ctx,
75
- );
76
- return category?.slug;
77
- }),
78
- )
79
- ).filter((slug): slug is string => typeof slug === "string");
80
-
81
- return unique(slugs);
82
- }
83
-
84
- private async entityBrands(
85
- entityId: string,
86
- ctx?: TxContext,
87
- ): Promise<string[]> {
88
- const entries = await this.deps.catalogRepository.findEntityBrands(
89
- entityId,
90
- ctx,
91
- );
92
-
93
- const slugs = (
94
- await Promise.all(
95
- entries.map(async (entry) => {
96
- const brand = await this.deps.catalogRepository.findBrandById(
97
- entry.brandId,
98
- ctx,
99
- );
100
- return brand?.slug;
101
- }),
102
- )
103
- ).filter((slug): slug is string => typeof slug === "string");
104
-
105
- return unique(slugs);
106
- }
107
-
108
- private async buildDocument(
109
- entity: SellableEntity,
110
- ctx?: TxContext,
111
- ): Promise<SearchDocument> {
112
- const attributes =
113
- await this.deps.catalogRepository.findAttributesByEntityId(
114
- entity.id,
115
- ctx,
116
- );
117
- const primary = attributes[0];
118
- const title = primary?.title ?? entity.slug;
119
- const description = primary?.description;
120
- const categories = await this.entityCategories(entity.id, ctx);
121
- const brands = await this.entityBrands(entity.id, ctx);
122
-
123
- const textParts: string[] = [
124
- entity.slug,
125
- title,
126
- description ?? "",
127
- ...categories,
128
- ...brands,
129
- ...attributes.map((attr) => attr.title),
130
- ...attributes.map((attr) => attr.description ?? ""),
131
- ];
132
-
133
- return {
134
- id: entity.id,
135
- type: entity.type,
136
- slug: entity.slug,
137
- title,
138
- ...(description ? { description } : {}),
139
- status: entity.status,
140
- categories,
141
- brands,
142
- text: textParts.join(" ").trim(),
143
- payload: {
144
- metadata: entity.metadata ?? undefined,
145
- },
146
- };
147
- }
148
-
149
- private async allDocuments(ctx?: TxContext): Promise<SearchDocument[]> {
150
- const orgId = resolveOrgId(ctx?.actor ?? null);
151
- const entities = await this.deps.catalogRepository.findEntities(
152
- orgId,
153
- undefined,
154
- ctx,
155
- );
156
- return Promise.all(
157
- entities.map((entity) => this.buildDocument(entity, ctx)),
158
- );
159
- }
160
-
161
- private matchesFilters(
162
- document: SearchDocument,
163
- filters: SearchFilters | undefined,
164
- ): boolean {
165
- if (!filters) return true;
166
- if (filters.type && document.type !== filters.type) return false;
167
- if (filters.status && document.status !== filters.status) return false;
168
- if (filters.category && !document.categories.includes(filters.category))
169
- return false;
170
- if (filters.brand && !document.brands.includes(filters.brand)) return false;
171
- return true;
172
- }
173
-
174
- private computeFacets(
175
- documents: SearchDocument[],
176
- requested?: string[],
177
- ): Record<string, Record<string, number>> {
178
- const facets =
179
- requested && requested.length > 0
180
- ? requested
181
- : (this.deps.defaultFacets ?? ["type", "category", "brand", "status"]);
182
- const output: Record<string, Record<string, number>> = {};
183
-
184
- for (const facet of facets) {
185
- if (facet === "type") {
186
- output.type = {};
187
- for (const document of documents) {
188
- output.type[document.type] = (output.type[document.type] ?? 0) + 1;
189
- }
190
- }
191
-
192
- if (facet === "status") {
193
- output.status = {};
194
- for (const document of documents) {
195
- const status = document.status ?? "unknown";
196
- output.status[status] = (output.status[status] ?? 0) + 1;
197
- }
198
- }
199
-
200
- if (facet === "category" || facet === "categories") {
201
- output.category = {};
202
- for (const document of documents) {
203
- for (const category of document.categories) {
204
- output.category[category] = (output.category[category] ?? 0) + 1;
205
- }
206
- }
207
- }
208
-
209
- if (facet === "brand" || facet === "brands") {
210
- output.brand = {};
211
- for (const document of documents) {
212
- for (const brand of document.brands) {
213
- output.brand[brand] = (output.brand[brand] ?? 0) + 1;
214
- }
215
- }
216
- }
217
- }
218
-
219
- return output;
220
- }
221
-
222
- async syncEntity(entityId: string, ctx?: TxContext): Promise<Result<void>> {
223
- if (!this.deps.adapter) return Ok(undefined);
224
-
225
- const entity = await this.deps.catalogRepository.findEntityById(
226
- entityId,
227
- ctx,
228
- );
229
- if (!entity) {
230
- return this.deps.adapter.remove([entityId]);
231
- }
232
-
233
- return this.deps.adapter.index([await this.buildDocument(entity, ctx)]);
234
- }
235
-
236
- async query(
237
- params: SearchQueryParams,
238
- ctx?: TxContext,
239
- ): Promise<Result<SearchQueryResult>> {
240
- const page = clamp(params.page ?? 1, 1, 100000);
241
- const limit = clamp(params.limit ?? 20, 1, 100);
242
-
243
- if (this.deps.adapter) {
244
- return this.deps.adapter.search({
245
- ...params,
246
- page,
247
- limit,
248
- });
249
- }
250
-
251
- const tokens = tokenize(params.query);
252
- const allDocs = await this.allDocuments(ctx);
253
- const filtered = allDocs.filter((document) => {
254
- if (!this.matchesFilters(document, params.filters)) return false;
255
- if (tokens.length === 0) return true;
256
- return includesAllTokens(document.text, tokens);
257
- });
258
-
259
- const scored = filtered
260
- .map((document) => ({
261
- document,
262
- score: scoreText(document, tokens),
263
- }))
264
- .sort((first, second) => {
265
- if (second.score !== first.score) return second.score - first.score;
266
- return first.document.title.localeCompare(second.document.title);
267
- });
268
-
269
- const offset = (page - 1) * limit;
270
- const hits = scored.slice(offset, offset + limit).map((row) => ({
271
- id: row.document.id,
272
- score: row.score,
273
- document: row.document,
274
- }));
275
-
276
- return Ok({
277
- hits,
278
- total: scored.length,
279
- page,
280
- limit,
281
- facets: this.computeFacets(filtered, params.facets),
282
- });
283
- }
284
-
285
- async suggest(
286
- params: SearchSuggestParams,
287
- ctx?: TxContext,
288
- ): Promise<Result<string[]>> {
289
- const limit = clamp(params.limit ?? 10, 1, 25);
290
- const prefix = params.prefix.trim().toLowerCase();
291
-
292
- if (prefix.length === 0) return Ok([]);
293
-
294
- if (this.deps.adapter) {
295
- return this.deps.adapter.suggest({
296
- ...params,
297
- prefix,
298
- limit,
299
- });
300
- }
301
-
302
- const allDocs = await this.allDocuments(ctx);
303
- const titles = allDocs
304
- .filter(
305
- (document) =>
306
- (!params.type || document.type === params.type) &&
307
- document.title.toLowerCase().startsWith(prefix),
308
- )
309
- .map((document) => document.title)
310
- .filter((title, index, list) => list.indexOf(title) === index)
311
- .slice(0, limit);
312
-
313
- return Ok(titles);
314
- }
315
- }
@@ -1,188 +0,0 @@
1
- import type { CommerceConfig } from "../../config/types.js";
2
- import type { TxContext } from "../../kernel/database/tx-context.js";
3
- import type { CatalogRepository } from "../catalog/repository/index.js";
4
-
5
- export interface ShippingAddress {
6
- country: string;
7
- postalCode: string;
8
- state?: string;
9
- city?: string;
10
- line1?: string;
11
- }
12
-
13
- export interface ShippingLineItem {
14
- entityId: string;
15
- variantId?: string;
16
- quantity: number;
17
- resolvedTotal: number;
18
- }
19
-
20
- export type ShippingStrategy =
21
- | {
22
- type: "flat";
23
- flatRate: number;
24
- freeShippingThreshold?: number;
25
- }
26
- | {
27
- type: "weight_based";
28
- brackets: Array<{ upToGrams: number; cost: number }>;
29
- fallbackCost: number;
30
- freeShippingThreshold?: number;
31
- };
32
-
33
- export interface ShippingCalculationInput {
34
- lineItems: ShippingLineItem[];
35
- subtotalAfterDiscount: number;
36
- currency: string;
37
- address?: ShippingAddress;
38
- isFreeShipping: boolean;
39
- }
40
-
41
- async function resolveWeightGrams(
42
- catalogRepo: CatalogRepository,
43
- entityId: string,
44
- variantId: string | undefined,
45
- ctx?: TxContext,
46
- ): Promise<number> {
47
- if (variantId !== undefined) {
48
- const variant = await catalogRepo.findVariantById(variantId, ctx);
49
- const weightFromVariant = (
50
- variant?.metadata as Record<string, unknown> | null
51
- )?.weightGrams;
52
- if (
53
- typeof weightFromVariant === "number" &&
54
- Number.isFinite(weightFromVariant)
55
- ) {
56
- return Math.max(0, Math.round(weightFromVariant));
57
- }
58
- }
59
-
60
- const entity = await catalogRepo.findEntityById(entityId, ctx);
61
- const weightFromEntity = (entity?.metadata as Record<string, unknown> | null)
62
- ?.weightGrams;
63
- if (
64
- typeof weightFromEntity === "number" &&
65
- Number.isFinite(weightFromEntity)
66
- ) {
67
- return Math.max(0, Math.round(weightFromEntity));
68
- }
69
-
70
- return 0;
71
- }
72
-
73
- async function isShippableEntity(
74
- config: CommerceConfig,
75
- catalogRepo: CatalogRepository,
76
- entityId: string,
77
- ctx?: TxContext,
78
- ): Promise<boolean> {
79
- const entity = await catalogRepo.findEntityById(entityId, ctx);
80
- if (!entity) return false;
81
- const fulfillment = config.entities?.[entity.type]?.fulfillment;
82
- return (
83
- fulfillment === "physical" ||
84
- fulfillment === "internal-transfer" ||
85
- fulfillment === undefined
86
- );
87
- }
88
-
89
- function resolveStrategy(config: CommerceConfig): ShippingStrategy {
90
- const shipping = config.shipping;
91
- if (!shipping) {
92
- return {
93
- type: "flat",
94
- flatRate: 0,
95
- };
96
- }
97
-
98
- if (shipping.type === "weight_based") {
99
- return {
100
- type: "weight_based",
101
- brackets: [...shipping.brackets].sort(
102
- (a, b) => a.upToGrams - b.upToGrams,
103
- ),
104
- fallbackCost: shipping.fallbackCost,
105
- ...(shipping.freeShippingThreshold !== undefined
106
- ? { freeShippingThreshold: shipping.freeShippingThreshold }
107
- : {}),
108
- };
109
- }
110
-
111
- return {
112
- type: "flat",
113
- flatRate: shipping.flatRate,
114
- ...(shipping.freeShippingThreshold !== undefined
115
- ? { freeShippingThreshold: shipping.freeShippingThreshold }
116
- : {}),
117
- };
118
- }
119
-
120
- export async function calculateShippingCost(
121
- config: CommerceConfig,
122
- catalogRepo: CatalogRepository,
123
- input: ShippingCalculationInput,
124
- ctx?: TxContext,
125
- ): Promise<{ amount: number; strategy: string; weightGrams: number }> {
126
- if (input.isFreeShipping) {
127
- return { amount: 0, strategy: "promotion:free_shipping", weightGrams: 0 };
128
- }
129
-
130
- const strategy = resolveStrategy(config);
131
- if (
132
- strategy.freeShippingThreshold !== undefined &&
133
- input.subtotalAfterDiscount >= strategy.freeShippingThreshold
134
- ) {
135
- return { amount: 0, strategy: "threshold:free_shipping", weightGrams: 0 };
136
- }
137
-
138
- // Filter to shippable items
139
- const shippableFlags = await Promise.all(
140
- input.lineItems.map((lineItem) =>
141
- isShippableEntity(config, catalogRepo, lineItem.entityId, ctx),
142
- ),
143
- );
144
- const shippableItems = input.lineItems.filter((_, i) => shippableFlags[i]);
145
-
146
- if (shippableItems.length === 0) {
147
- return {
148
- amount: 0,
149
- strategy: `${strategy.type}:digital_only`,
150
- weightGrams: 0,
151
- };
152
- }
153
-
154
- // Calculate total weight
155
- const weights = await Promise.all(
156
- shippableItems.map((lineItem) =>
157
- resolveWeightGrams(
158
- catalogRepo,
159
- lineItem.entityId,
160
- lineItem.variantId,
161
- ctx,
162
- ),
163
- ),
164
- );
165
- const weightGrams = shippableItems.reduce(
166
- (sum, lineItem, i) => sum + (weights[i] ?? 0) * lineItem.quantity,
167
- 0,
168
- );
169
-
170
- if (strategy.type === "flat") {
171
- return {
172
- amount: Math.max(0, Math.round(strategy.flatRate)),
173
- strategy: "flat",
174
- weightGrams,
175
- };
176
- }
177
-
178
- const matchedBracket = strategy.brackets.find(
179
- (bracket) => weightGrams <= bracket.upToGrams,
180
- );
181
- return {
182
- amount: matchedBracket
183
- ? Math.max(0, Math.round(matchedBracket.cost))
184
- : Math.max(0, Math.round(strategy.fallbackCost)),
185
- strategy: "weight_based",
186
- weightGrams,
187
- };
188
- }
@@ -1,6 +0,0 @@
1
- import type { TxContext } from "../../../kernel/database/tx-context.js";
2
-
3
- export interface ShippingRepository {
4
- // RFC-002 scaffold: module repositories become the only persistence boundary.
5
- ping(ctx: TxContext): Promise<void>;
6
- }
@@ -1,51 +0,0 @@
1
- import type { CommerceConfig } from "../../config/types.js";
2
- import { Ok, type Result } from "../../kernel/result.js";
3
- import type { TxContext } from "../../kernel/database/tx-context.js";
4
- import type { CatalogRepository } from "../catalog/repository/index.js";
5
- import {
6
- calculateShippingCost,
7
- type ShippingAddress,
8
- type ShippingLineItem,
9
- } from "./calculator.js";
10
-
11
- interface ShippingServiceDeps {
12
- config: CommerceConfig;
13
- catalogRepository: CatalogRepository;
14
- }
15
-
16
- export interface CalculateShippingInput {
17
- lineItems: ShippingLineItem[];
18
- subtotalAfterDiscount: number;
19
- currency: string;
20
- address?: ShippingAddress;
21
- isFreeShipping?: boolean;
22
- }
23
-
24
- export class ShippingService {
25
- private readonly catalogRepo: CatalogRepository;
26
-
27
- constructor(private deps: ShippingServiceDeps) {
28
- this.catalogRepo = deps.catalogRepository;
29
- }
30
-
31
- async calculate(
32
- input: CalculateShippingInput,
33
- ctx?: TxContext,
34
- ): Promise<
35
- Result<{ amount: number; strategy: string; weightGrams: number }>
36
- > {
37
- const result = await calculateShippingCost(
38
- this.deps.config,
39
- this.catalogRepo,
40
- {
41
- lineItems: input.lineItems,
42
- subtotalAfterDiscount: input.subtotalAfterDiscount,
43
- currency: input.currency,
44
- isFreeShipping: input.isFreeShipping ?? false,
45
- ...(input.address !== undefined ? { address: input.address } : {}),
46
- },
47
- ctx,
48
- );
49
- return Ok(result);
50
- }
51
- }
@@ -1,60 +0,0 @@
1
- import type { Result } from "../../kernel/result.js";
2
-
3
- export interface TaxAddress {
4
- country: string;
5
- postalCode: string;
6
- state?: string;
7
- city?: string;
8
- line1?: string;
9
- }
10
-
11
- export interface TaxLineItem {
12
- id: string;
13
- entityId: string;
14
- description: string;
15
- quantity: number;
16
- unitPrice: number;
17
- discount?: number;
18
- productTaxCode?: string;
19
- }
20
-
21
- export interface TaxCalculationParams {
22
- currency: string;
23
- customerId?: string;
24
- orderId?: string;
25
- fromAddress?: TaxAddress;
26
- toAddress?: TaxAddress;
27
- shippingAmount: number;
28
- lineItems: TaxLineItem[];
29
- }
30
-
31
- export interface TaxCalculationResult {
32
- amountToCollect: number;
33
- taxableAmount: number;
34
- rate: number;
35
- breakdown?: Record<string, unknown>;
36
- }
37
-
38
- export interface TaxReportParams {
39
- transactionId: string;
40
- transactionDate: Date;
41
- currency: string;
42
- customerId?: string;
43
- fromAddress?: TaxAddress;
44
- toAddress?: TaxAddress;
45
- amount: number;
46
- shipping: number;
47
- salesTax: number;
48
- lineItems: TaxLineItem[];
49
- }
50
-
51
- export interface TaxVoidParams {
52
- transactionId: string;
53
- }
54
-
55
- export interface TaxAdapter {
56
- readonly providerId: string;
57
- calculateTax(params: TaxCalculationParams): Promise<Result<TaxCalculationResult>>;
58
- reportTransaction(params: TaxReportParams): Promise<Result<{ transactionId: string }>>;
59
- voidTransaction(params: TaxVoidParams): Promise<Result<{ transactionId: string }>>;
60
- }
@@ -1,6 +0,0 @@
1
- import type { TxContext } from "../../../kernel/database/tx-context.js";
2
-
3
- export interface TaxRepository {
4
- // RFC-002 scaffold: module repositories become the only persistence boundary.
5
- ping(ctx: TxContext): Promise<void>;
6
- }
@@ -1,53 +0,0 @@
1
- import { CommerceValidationError } from "../../kernel/errors.js";
2
- import { Err, Ok, type Result } from "../../kernel/result.js";
3
- import type {
4
- TaxAdapter,
5
- TaxCalculationParams,
6
- TaxCalculationResult,
7
- TaxReportParams,
8
- TaxVoidParams,
9
- } from "./adapter.js";
10
-
11
- interface TaxServiceDeps {
12
- adapter: TaxAdapter | undefined;
13
- }
14
-
15
- export class TaxService {
16
- private adapter: TaxAdapter | undefined;
17
-
18
- constructor(deps: TaxServiceDeps) {
19
- this.adapter = deps.adapter;
20
- }
21
-
22
- async calculate(params: TaxCalculationParams): Promise<Result<TaxCalculationResult>> {
23
- if (!this.adapter) {
24
- return Ok({
25
- amountToCollect: 0,
26
- taxableAmount:
27
- params.lineItems.reduce(
28
- (sum, lineItem) => sum + lineItem.unitPrice * lineItem.quantity - (lineItem.discount ?? 0),
29
- 0,
30
- ) + params.shippingAmount,
31
- rate: 0,
32
- });
33
- }
34
- return this.adapter.calculateTax(params);
35
- }
36
-
37
- async reportTransaction(params: TaxReportParams): Promise<Result<{ transactionId: string }>> {
38
- if (!this.adapter) return Ok({ transactionId: params.transactionId });
39
- return this.adapter.reportTransaction(params);
40
- }
41
-
42
- async voidTransaction(params: TaxVoidParams): Promise<Result<{ transactionId: string }>> {
43
- if (!this.adapter) return Ok({ transactionId: params.transactionId });
44
- return this.adapter.voidTransaction(params);
45
- }
46
-
47
- requireConfigured(): Result<TaxAdapter> {
48
- if (!this.adapter) {
49
- return Err(new CommerceValidationError("Tax adapter is not configured."));
50
- }
51
- return Ok(this.adapter);
52
- }
53
- }