@tallyui/connector-medusa 1.0.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.
@@ -0,0 +1,71 @@
1
+ import { ProductTraits, CollectionSync, ReplicationAdapter, TallyConnector } from '@tallyui/core';
2
+ import { RxJsonSchema } from 'rxdb';
3
+
4
+ /**
5
+ * MedusaJS v2 Product RxDB schema.
6
+ * Mirrors the Medusa Admin API product shape.
7
+ *
8
+ * Key differences from WooCommerce:
9
+ * - `title` instead of `name`
10
+ * - `handle` instead of `slug`
11
+ * - Pricing lives on variants, not the product itself
12
+ * - Variants have their own SKU, barcode, images
13
+ * - Categories use `name`, but products/collections use `title`
14
+ * - Tags use `value` field
15
+ * - Images have `url` (not `src`)
16
+ */
17
+ declare const medusaProductSchema: RxJsonSchema<any>;
18
+
19
+ /**
20
+ * Medusa v2 product trait implementations.
21
+ *
22
+ * Key mapping differences from WooCommerce:
23
+ * - Product name is `title` (not `name`)
24
+ * - Price lives on `variants[0].prices[0].amount` (cents, integer)
25
+ * - Images use `url` (not `src`)
26
+ * - SKU/barcode live on variants, not the product
27
+ * - Categories use `name`, tags use `value`
28
+ * - Stock is per-variant via `inventory_quantity`
29
+ */
30
+ declare const medusaProductTraits: ProductTraits;
31
+
32
+ /**
33
+ * Medusa v2 product sync implementation.
34
+ *
35
+ * Uses the Medusa Admin API to fetch products with variants and pricing.
36
+ * The Admin API gives us raw price data (vs Store API's calculated prices),
37
+ * which is better for a POS that needs to know the actual price entries.
38
+ */
39
+ declare const medusaProductSync: CollectionSync;
40
+
41
+ type MedusaProductCheckpoint = {
42
+ offset: number;
43
+ updated_at: string;
44
+ };
45
+ /**
46
+ * Replication adapter for Medusa v2 products.
47
+ *
48
+ * Implements pull (offset-based pagination with updated_at filtering) and
49
+ * push (POST to update individual products via Admin API). Designed for
50
+ * use with RxDB's replicateRxCollection.
51
+ */
52
+ declare const medusaProductReplication: ReplicationAdapter<any, MedusaProductCheckpoint>;
53
+
54
+ /**
55
+ * MedusaJS v2 connector for Tally UI.
56
+ *
57
+ * Connects to Medusa backends via the Admin API.
58
+ * Products are stored in RxDB using a schema that mirrors the Medusa API shape.
59
+ *
60
+ * ```ts
61
+ * import { medusaConnector } from '@tallyui/connector-medusa';
62
+ * import { ConnectorProvider } from '@tallyui/core';
63
+ *
64
+ * <ConnectorProvider connector={medusaConnector}>
65
+ * <App />
66
+ * </ConnectorProvider>
67
+ * ```
68
+ */
69
+ declare const medusaConnector: TallyConnector;
70
+
71
+ export { medusaConnector, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits };
package/dist/index.js ADDED
@@ -0,0 +1,437 @@
1
+ // src/schemas/products.ts
2
+ var medusaProductSchema = {
3
+ title: "Medusa Product",
4
+ version: 0,
5
+ type: "object",
6
+ primaryKey: "id",
7
+ properties: {
8
+ id: {
9
+ type: "string",
10
+ maxLength: 200
11
+ },
12
+ title: {
13
+ type: "string"
14
+ },
15
+ handle: {
16
+ type: "string"
17
+ },
18
+ subtitle: {
19
+ type: ["string", "null"]
20
+ },
21
+ description: {
22
+ type: ["string", "null"]
23
+ },
24
+ status: {
25
+ type: "string",
26
+ enum: ["draft", "proposed", "published", "rejected"],
27
+ default: "draft"
28
+ },
29
+ thumbnail: {
30
+ type: ["string", "null"]
31
+ },
32
+ is_giftcard: {
33
+ type: "boolean",
34
+ default: false
35
+ },
36
+ discountable: {
37
+ type: "boolean",
38
+ default: true
39
+ },
40
+ collection_id: {
41
+ type: ["string", "null"]
42
+ },
43
+ type_id: {
44
+ type: ["string", "null"]
45
+ },
46
+ external_id: {
47
+ type: ["string", "null"]
48
+ },
49
+ weight: {
50
+ type: ["number", "null"]
51
+ },
52
+ length: {
53
+ type: ["number", "null"]
54
+ },
55
+ height: {
56
+ type: ["number", "null"]
57
+ },
58
+ width: {
59
+ type: ["number", "null"]
60
+ },
61
+ origin_country: {
62
+ type: ["string", "null"]
63
+ },
64
+ hs_code: {
65
+ type: ["string", "null"]
66
+ },
67
+ mid_code: {
68
+ type: ["string", "null"]
69
+ },
70
+ material: {
71
+ type: ["string", "null"]
72
+ },
73
+ metadata: {
74
+ type: ["object", "null"]
75
+ },
76
+ categories: {
77
+ type: "array",
78
+ items: {
79
+ type: "object",
80
+ properties: {
81
+ id: { type: "string" },
82
+ name: { type: "string" },
83
+ handle: { type: "string" }
84
+ }
85
+ }
86
+ },
87
+ tags: {
88
+ type: "array",
89
+ items: {
90
+ type: "object",
91
+ properties: {
92
+ id: { type: "string" },
93
+ value: { type: "string" }
94
+ }
95
+ }
96
+ },
97
+ images: {
98
+ type: "array",
99
+ items: {
100
+ type: "object",
101
+ properties: {
102
+ id: { type: "string" },
103
+ url: { type: "string" },
104
+ rank: { type: "number" }
105
+ }
106
+ }
107
+ },
108
+ options: {
109
+ type: "array",
110
+ items: {
111
+ type: "object",
112
+ properties: {
113
+ id: { type: "string" },
114
+ title: { type: "string" },
115
+ values: {
116
+ type: "array",
117
+ items: {
118
+ type: "object",
119
+ properties: {
120
+ id: { type: "string" },
121
+ value: { type: "string" }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ },
128
+ variants: {
129
+ type: "array",
130
+ items: {
131
+ type: "object",
132
+ properties: {
133
+ id: { type: "string" },
134
+ title: { type: ["string", "null"] },
135
+ sku: { type: ["string", "null"] },
136
+ barcode: { type: ["string", "null"] },
137
+ ean: { type: ["string", "null"] },
138
+ upc: { type: ["string", "null"] },
139
+ allow_backorder: { type: ["boolean", "null"] },
140
+ manage_inventory: { type: ["boolean", "null"] },
141
+ inventory_quantity: { type: ["number", "null"] },
142
+ variant_rank: { type: ["number", "null"] },
143
+ weight: { type: ["number", "null"] },
144
+ length: { type: ["number", "null"] },
145
+ height: { type: ["number", "null"] },
146
+ width: { type: ["number", "null"] },
147
+ options: {
148
+ type: "array",
149
+ items: {
150
+ type: "object",
151
+ properties: {
152
+ id: { type: "string" },
153
+ value: { type: "string" }
154
+ }
155
+ }
156
+ },
157
+ prices: {
158
+ type: "array",
159
+ items: {
160
+ type: "object",
161
+ properties: {
162
+ id: { type: "string" },
163
+ currency_code: { type: "string" },
164
+ amount: { type: "number" },
165
+ min_quantity: { type: ["number", "null"] },
166
+ max_quantity: { type: ["number", "null"] }
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+ },
173
+ created_at: {
174
+ type: ["string", "null"]
175
+ },
176
+ updated_at: {
177
+ type: ["string", "null"]
178
+ }
179
+ },
180
+ indexes: ["handle", "status"],
181
+ required: ["id"]
182
+ };
183
+
184
+ // src/traits/product.ts
185
+ var medusaProductTraits = {
186
+ getId: (doc) => doc.id,
187
+ getName: (doc) => doc.title ?? "",
188
+ getSku: (doc) => {
189
+ return doc.variants?.[0]?.sku || void 0;
190
+ },
191
+ getPrice: (doc) => {
192
+ const amount = doc.variants?.[0]?.prices?.[0]?.amount;
193
+ if (amount == null) return void 0;
194
+ return (amount / 100).toFixed(2);
195
+ },
196
+ getRegularPrice: (doc) => {
197
+ const amount = doc.variants?.[0]?.prices?.[0]?.amount;
198
+ if (amount == null) return void 0;
199
+ return (amount / 100).toFixed(2);
200
+ },
201
+ getSalePrice: () => {
202
+ return void 0;
203
+ },
204
+ isOnSale: () => {
205
+ return false;
206
+ },
207
+ getImageUrl: (doc) => {
208
+ return doc.thumbnail || doc.images?.[0]?.url || void 0;
209
+ },
210
+ getImageUrls: (doc) => {
211
+ const urls = [];
212
+ if (doc.thumbnail) urls.push(doc.thumbnail);
213
+ for (const img of doc.images ?? []) {
214
+ if (img.url && img.url !== doc.thumbnail) urls.push(img.url);
215
+ }
216
+ return urls;
217
+ },
218
+ getDescription: (doc) => doc.description || void 0,
219
+ getStockStatus: (doc) => {
220
+ const variant = doc.variants?.[0];
221
+ if (!variant) return "unknown";
222
+ if (variant.manage_inventory === false) return "instock";
223
+ if (variant.allow_backorder) return "onbackorder";
224
+ const qty = variant.inventory_quantity;
225
+ if (qty == null) return "unknown";
226
+ return qty > 0 ? "instock" : "outofstock";
227
+ },
228
+ getStockQuantity: (doc) => {
229
+ return doc.variants?.[0]?.inventory_quantity ?? null;
230
+ },
231
+ hasVariants: (doc) => {
232
+ return (doc.variants?.length ?? 0) > 1;
233
+ },
234
+ getType: (doc) => {
235
+ if (doc.is_giftcard) return "giftcard";
236
+ if ((doc.variants?.length ?? 0) > 1) return "variable";
237
+ return "simple";
238
+ },
239
+ getBarcode: (doc) => {
240
+ const variant = doc.variants?.[0];
241
+ return variant?.barcode || variant?.ean || variant?.upc || void 0;
242
+ },
243
+ getCategoryNames: (doc) => (doc.categories ?? []).map((cat) => cat.name).filter(Boolean)
244
+ };
245
+
246
+ // src/sync/products.ts
247
+ var medusaProductSync = {
248
+ async fetchAllIds(context) {
249
+ const allIds = [];
250
+ let offset = 0;
251
+ const limit = 100;
252
+ while (true) {
253
+ const response = await fetch(
254
+ `${context.baseUrl}/admin/products?offset=${offset}&limit=${limit}&fields=id,updated_at`,
255
+ {
256
+ headers: {
257
+ ...context.headers,
258
+ "Content-Type": "application/json"
259
+ },
260
+ signal: context.signal
261
+ }
262
+ );
263
+ if (!response.ok) {
264
+ throw new Error(`Medusa API error: ${response.status}`);
265
+ }
266
+ const data = await response.json();
267
+ for (const product of data.products) {
268
+ allIds.push({
269
+ id: product.id,
270
+ dateModified: product.updated_at
271
+ });
272
+ }
273
+ if (data.products.length < limit) break;
274
+ offset += limit;
275
+ }
276
+ return allIds;
277
+ },
278
+ async fetchByIds(ids, context) {
279
+ const products = [];
280
+ for (const id of ids) {
281
+ const response = await fetch(
282
+ `${context.baseUrl}/admin/products/${id}?fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
283
+ {
284
+ headers: {
285
+ ...context.headers,
286
+ "Content-Type": "application/json"
287
+ },
288
+ signal: context.signal
289
+ }
290
+ );
291
+ if (!response.ok) {
292
+ throw new Error(`Medusa API error: ${response.status} for product ${id}`);
293
+ }
294
+ const data = await response.json();
295
+ products.push(data.product);
296
+ }
297
+ return products;
298
+ },
299
+ async fetchModifiedAfter(date, context) {
300
+ const response = await fetch(
301
+ `${context.baseUrl}/admin/products?updated_at[gte]=${date}&limit=100&fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
302
+ {
303
+ headers: {
304
+ ...context.headers,
305
+ "Content-Type": "application/json"
306
+ },
307
+ signal: context.signal
308
+ }
309
+ );
310
+ if (!response.ok) {
311
+ throw new Error(`Medusa API error: ${response.status}`);
312
+ }
313
+ const data = await response.json();
314
+ return data.products;
315
+ }
316
+ };
317
+
318
+ // src/replication/products.ts
319
+ var MEDUSA_PRODUCT_FIELDS = "*variants,*variants.prices,*images,*categories,*tags,*options,*options.values";
320
+ var medusaProductReplication = {
321
+ pull: {
322
+ async handler(lastCheckpoint, batchSize, context) {
323
+ const params = new URLSearchParams({
324
+ limit: String(batchSize),
325
+ offset: String(lastCheckpoint?.offset ?? 0),
326
+ fields: MEDUSA_PRODUCT_FIELDS
327
+ });
328
+ if (lastCheckpoint?.updated_at) {
329
+ params.set("updated_at[gte]", lastCheckpoint.updated_at);
330
+ }
331
+ const response = await fetch(
332
+ `${context.baseUrl}/admin/products?${params}`,
333
+ {
334
+ headers: {
335
+ ...context.headers,
336
+ "Content-Type": "application/json"
337
+ },
338
+ signal: context.signal
339
+ }
340
+ );
341
+ if (!response.ok) {
342
+ throw new Error(`Medusa API error: ${response.status}`);
343
+ }
344
+ const data = await response.json();
345
+ const products = data.products ?? [];
346
+ const documents = products.map((p) => ({ ...p, _deleted: false }));
347
+ const nextOffset = products.length < batchSize ? 0 : (lastCheckpoint?.offset ?? 0) + products.length;
348
+ const checkpoint = products.length > 0 ? {
349
+ offset: nextOffset,
350
+ updated_at: products[products.length - 1].updated_at
351
+ } : lastCheckpoint ?? { offset: 0, updated_at: "" };
352
+ return { documents, checkpoint };
353
+ }
354
+ },
355
+ push: {
356
+ async handler(changeRows, context) {
357
+ const conflicts = [];
358
+ for (const row of changeRows) {
359
+ const doc = row.newDocumentState;
360
+ try {
361
+ const response = await fetch(
362
+ `${context.baseUrl}/admin/products/${doc.id}`,
363
+ {
364
+ method: "POST",
365
+ headers: {
366
+ ...context.headers,
367
+ "Content-Type": "application/json"
368
+ },
369
+ body: JSON.stringify(doc),
370
+ signal: context.signal
371
+ }
372
+ );
373
+ if (!response.ok) {
374
+ if (row.assumedMasterState) {
375
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
376
+ }
377
+ }
378
+ } catch {
379
+ if (row.assumedMasterState) {
380
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
381
+ }
382
+ }
383
+ }
384
+ return conflicts;
385
+ }
386
+ }
387
+ };
388
+
389
+ // src/index.ts
390
+ var medusaConnector = {
391
+ id: "medusa",
392
+ name: "MedusaJS",
393
+ description: "Connect to MedusaJS v2 backends via the Admin API",
394
+ icon: void 0,
395
+ // TODO: Medusa logo
396
+ auth: {
397
+ type: "Medusa Admin API",
398
+ fields: [
399
+ {
400
+ key: "url",
401
+ label: "Backend URL",
402
+ type: "url",
403
+ placeholder: "https://my-medusa-backend.com",
404
+ required: true
405
+ },
406
+ {
407
+ key: "api_token",
408
+ label: "API Token",
409
+ type: "password",
410
+ placeholder: "Your admin API token",
411
+ required: true
412
+ }
413
+ ],
414
+ getHeaders: (credentials) => ({
415
+ Authorization: `Bearer ${credentials.api_token}`
416
+ })
417
+ },
418
+ schemas: {
419
+ products: medusaProductSchema
420
+ },
421
+ traits: {
422
+ product: medusaProductTraits
423
+ },
424
+ sync: {
425
+ products: medusaProductSync
426
+ },
427
+ replication: {
428
+ products: medusaProductReplication
429
+ }
430
+ };
431
+ export {
432
+ medusaConnector,
433
+ medusaProductReplication,
434
+ medusaProductSchema,
435
+ medusaProductSync,
436
+ medusaProductTraits
437
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@tallyui/connector-medusa",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "MedusaJS v2 connector for Tally UI",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "source": "./src/index.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "source": "./src/index.ts"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src"
19
+ ],
20
+ "license": "MIT",
21
+ "peerDependencies": {
22
+ "@tallyui/core": "0.2.0"
23
+ },
24
+ "devDependencies": {
25
+ "rxdb": "16.21.1"
26
+ },
27
+ "scripts": {
28
+ "build": "tsup",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "echo \"no tests yet\""
31
+ }
32
+ }