@tallyui/connector-shopify 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,63 @@
1
+ import { ProductTraits, CollectionSync, ReplicationAdapter, TallyConnector } from '@tallyui/core';
2
+ import { RxJsonSchema } from 'rxdb';
3
+
4
+ /**
5
+ * RxDB schema for Shopify products.
6
+ *
7
+ * Mirrors the Shopify Admin REST API product shape. Key difference from
8
+ * WooCommerce: price, SKU, barcode, and inventory live on variants, not
9
+ * the product itself. Even single-option products have one variant.
10
+ */
11
+ declare const shopifyProductSchema: RxJsonSchema<any>;
12
+
13
+ /**
14
+ * Shopify product trait implementations.
15
+ *
16
+ * Key differences from WooCommerce / Medusa:
17
+ * - Product name is `title` (same as Medusa)
18
+ * - Price, SKU, barcode, inventory all live on variants, not the product
19
+ * - Sale detection uses `compare_at_price` > `price` (no explicit on_sale flag)
20
+ * - Description is `body_html` (single field, HTML)
21
+ * - Categories don't exist on the product — `product_type` is the closest thing
22
+ * - Stock status is derived from inventory_management + inventory_policy + quantity
23
+ */
24
+ declare const shopifyProductTraits: ProductTraits;
25
+
26
+ /**
27
+ * Shopify product sync implementation.
28
+ *
29
+ * Uses the Admin REST API. Shopify uses cursor-based pagination via
30
+ * the Link header (page_info parameter), not page numbers.
31
+ */
32
+ declare const shopifyProductSync: CollectionSync;
33
+
34
+ type ShopifyProductCheckpoint = {
35
+ updated_at: string;
36
+ };
37
+ /**
38
+ * Replication adapter for Shopify products.
39
+ *
40
+ * Implements pull (cursor-based pagination via Link header, filtered by
41
+ * updated_at_min) and push (PUT to update individual products via Admin
42
+ * REST API). Designed for use with RxDB's replicateRxCollection.
43
+ */
44
+ declare const shopifyProductReplication: ReplicationAdapter<any, ShopifyProductCheckpoint>;
45
+
46
+ /**
47
+ * Shopify connector for Tally UI.
48
+ *
49
+ * Connects to Shopify stores via the Admin REST API.
50
+ * Products are stored in RxDB using a schema that mirrors the Shopify API shape.
51
+ *
52
+ * ```ts
53
+ * import { shopifyConnector } from '@tallyui/connector-shopify';
54
+ * import { ConnectorProvider } from '@tallyui/core';
55
+ *
56
+ * <ConnectorProvider connector={shopifyConnector}>
57
+ * <App />
58
+ * </ConnectorProvider>
59
+ * ```
60
+ */
61
+ declare const shopifyConnector: TallyConnector;
62
+
63
+ export { shopifyConnector, shopifyProductReplication, shopifyProductSchema, shopifyProductSync, shopifyProductTraits };
package/dist/index.js ADDED
@@ -0,0 +1,315 @@
1
+ // src/schemas/products.ts
2
+ var shopifyProductSchema = {
3
+ version: 0,
4
+ primaryKey: "id",
5
+ type: "object",
6
+ properties: {
7
+ id: { type: "string", maxLength: 100 },
8
+ title: { type: "string" },
9
+ body_html: { type: "string" },
10
+ vendor: { type: "string" },
11
+ product_type: { type: "string" },
12
+ handle: { type: "string", maxLength: 255 },
13
+ status: {
14
+ type: "string",
15
+ enum: ["active", "archived", "draft"]
16
+ },
17
+ tags: { type: "string" },
18
+ published_scope: { type: "string" },
19
+ variants: {
20
+ type: "array",
21
+ items: {
22
+ type: "object",
23
+ properties: {
24
+ id: { type: "number" },
25
+ title: { type: "string" },
26
+ price: { type: "string" },
27
+ compare_at_price: { type: ["string", "null"] },
28
+ sku: { type: ["string", "null"] },
29
+ barcode: { type: ["string", "null"] },
30
+ position: { type: "number" },
31
+ inventory_policy: { type: "string" },
32
+ inventory_management: { type: ["string", "null"] },
33
+ inventory_quantity: { type: "number" },
34
+ option1: { type: ["string", "null"] },
35
+ option2: { type: ["string", "null"] },
36
+ option3: { type: ["string", "null"] },
37
+ weight: { type: "number" },
38
+ weight_unit: { type: "string" },
39
+ taxable: { type: "boolean" },
40
+ requires_shipping: { type: "boolean" }
41
+ }
42
+ }
43
+ },
44
+ options: {
45
+ type: "array",
46
+ items: {
47
+ type: "object",
48
+ properties: {
49
+ id: { type: "number" },
50
+ name: { type: "string" },
51
+ position: { type: "number" },
52
+ values: {
53
+ type: "array",
54
+ items: { type: "string" }
55
+ }
56
+ }
57
+ }
58
+ },
59
+ images: {
60
+ type: "array",
61
+ items: {
62
+ type: "object",
63
+ properties: {
64
+ id: { type: "number" },
65
+ src: { type: "string" },
66
+ alt: { type: ["string", "null"] },
67
+ position: { type: "number" },
68
+ width: { type: "number" },
69
+ height: { type: "number" }
70
+ }
71
+ }
72
+ },
73
+ image: {
74
+ type: ["object", "null"],
75
+ properties: {
76
+ src: { type: "string" }
77
+ }
78
+ },
79
+ updated_at: { type: "string", maxLength: 50 }
80
+ },
81
+ required: ["id"],
82
+ indexes: ["handle", "status", "updated_at"]
83
+ };
84
+
85
+ // src/traits/product.ts
86
+ var shopifyProductTraits = {
87
+ getId: (doc) => String(doc.id),
88
+ getName: (doc) => doc.title ?? "",
89
+ getSku: (doc) => doc.variants?.[0]?.sku || void 0,
90
+ getPrice: (doc) => doc.variants?.[0]?.price || void 0,
91
+ getRegularPrice: (doc) => {
92
+ const variant = doc.variants?.[0];
93
+ if (!variant) return void 0;
94
+ return variant.compare_at_price || variant.price || void 0;
95
+ },
96
+ getSalePrice: (doc) => {
97
+ const variant = doc.variants?.[0];
98
+ if (!variant) return void 0;
99
+ if (variant.compare_at_price && parseFloat(variant.compare_at_price) > parseFloat(variant.price)) {
100
+ return variant.price;
101
+ }
102
+ return void 0;
103
+ },
104
+ isOnSale: (doc) => {
105
+ const variant = doc.variants?.[0];
106
+ if (!variant?.compare_at_price) return false;
107
+ return parseFloat(variant.compare_at_price) > parseFloat(variant.price);
108
+ },
109
+ getImageUrl: (doc) => doc.image?.src || doc.images?.[0]?.src || void 0,
110
+ getImageUrls: (doc) => (doc.images ?? []).map((img) => img.src).filter(Boolean),
111
+ getDescription: (doc) => doc.body_html || void 0,
112
+ getStockStatus: (doc) => {
113
+ const variant = doc.variants?.[0];
114
+ if (!variant) return "unknown";
115
+ if (variant.inventory_management == null) return "instock";
116
+ if (variant.inventory_policy === "continue") return "onbackorder";
117
+ const qty = variant.inventory_quantity;
118
+ if (qty == null) return "unknown";
119
+ return qty > 0 ? "instock" : "outofstock";
120
+ },
121
+ getStockQuantity: (doc) => doc.variants?.[0]?.inventory_quantity ?? null,
122
+ hasVariants: (doc) => (doc.variants?.length ?? 0) > 1,
123
+ getType: (doc) => doc.product_type || "simple",
124
+ getBarcode: (doc) => doc.variants?.[0]?.barcode || void 0,
125
+ getCategoryNames: (doc) => {
126
+ const names = [];
127
+ if (doc.product_type) names.push(doc.product_type);
128
+ return names;
129
+ }
130
+ };
131
+
132
+ // src/sync/products.ts
133
+ var shopifyProductSync = {
134
+ fetchAllIds: async (context) => {
135
+ const entries = [];
136
+ let url = `${context.baseUrl}/admin/api/2024-01/products.json?fields=id,updated_at&limit=250`;
137
+ while (url) {
138
+ const res = await fetch(url, {
139
+ headers: context.headers,
140
+ signal: context.signal
141
+ });
142
+ if (!res.ok) throw new Error(`Shopify API error: ${res.status}`);
143
+ const data = await res.json();
144
+ for (const product of data.products ?? []) {
145
+ entries.push({
146
+ id: String(product.id),
147
+ dateModified: product.updated_at
148
+ });
149
+ }
150
+ url = parseLinkNext(res.headers.get("Link"));
151
+ }
152
+ return entries;
153
+ },
154
+ fetchByIds: async (ids, context) => {
155
+ const idsParam = ids.join(",");
156
+ const res = await fetch(
157
+ `${context.baseUrl}/admin/api/2024-01/products.json?ids=${idsParam}`,
158
+ {
159
+ headers: context.headers,
160
+ signal: context.signal
161
+ }
162
+ );
163
+ if (!res.ok) throw new Error(`Shopify API error: ${res.status}`);
164
+ const data = await res.json();
165
+ return (data.products ?? []).map(normalizeId);
166
+ },
167
+ fetchModifiedAfter: async (date, context) => {
168
+ const products = [];
169
+ let url = `${context.baseUrl}/admin/api/2024-01/products.json?updated_at_min=${date}&limit=250`;
170
+ while (url) {
171
+ const res = await fetch(url, {
172
+ headers: context.headers,
173
+ signal: context.signal
174
+ });
175
+ if (!res.ok) throw new Error(`Shopify API error: ${res.status}`);
176
+ const data = await res.json();
177
+ products.push(...(data.products ?? []).map(normalizeId));
178
+ url = parseLinkNext(res.headers.get("Link"));
179
+ }
180
+ return products;
181
+ }
182
+ };
183
+ function normalizeId(product) {
184
+ return { ...product, id: String(product.id) };
185
+ }
186
+ function parseLinkNext(linkHeader) {
187
+ if (!linkHeader) return "";
188
+ const match = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
189
+ return match ? match[1] : "";
190
+ }
191
+
192
+ // src/replication/products.ts
193
+ function parseLinkNext2(linkHeader) {
194
+ if (!linkHeader) return "";
195
+ const match = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
196
+ return match ? match[1] : "";
197
+ }
198
+ function normalizeId2(product) {
199
+ return { ...product, id: String(product.id) };
200
+ }
201
+ var shopifyProductReplication = {
202
+ pull: {
203
+ async handler(lastCheckpoint, batchSize, context) {
204
+ const params = new URLSearchParams({
205
+ limit: String(batchSize)
206
+ });
207
+ if (lastCheckpoint?.updated_at) {
208
+ params.set("updated_at_min", lastCheckpoint.updated_at);
209
+ }
210
+ let url = `${context.baseUrl}/admin/api/2024-01/products.json?${params}`;
211
+ const allProducts = [];
212
+ while (url) {
213
+ const response = await fetch(url, {
214
+ headers: {
215
+ ...context.headers,
216
+ "Content-Type": "application/json"
217
+ },
218
+ signal: context.signal
219
+ });
220
+ if (!response.ok) {
221
+ throw new Error(`Shopify API error: ${response.status}`);
222
+ }
223
+ const data = await response.json();
224
+ const products = (data.products ?? []).map(normalizeId2);
225
+ allProducts.push(...products);
226
+ url = parseLinkNext2(response.headers.get("Link"));
227
+ }
228
+ const documents = allProducts.map((p) => ({ ...p, _deleted: false }));
229
+ const checkpoint = allProducts.length > 0 ? { updated_at: allProducts[allProducts.length - 1].updated_at } : lastCheckpoint ?? { updated_at: "" };
230
+ return { documents, checkpoint };
231
+ }
232
+ },
233
+ push: {
234
+ async handler(changeRows, context) {
235
+ const conflicts = [];
236
+ for (const row of changeRows) {
237
+ const doc = row.newDocumentState;
238
+ try {
239
+ const response = await fetch(
240
+ `${context.baseUrl}/admin/api/2024-01/products/${doc.id}.json`,
241
+ {
242
+ method: "PUT",
243
+ headers: {
244
+ ...context.headers,
245
+ "Content-Type": "application/json"
246
+ },
247
+ body: JSON.stringify({ product: doc }),
248
+ signal: context.signal
249
+ }
250
+ );
251
+ if (!response.ok) {
252
+ if (row.assumedMasterState) {
253
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
254
+ }
255
+ }
256
+ } catch {
257
+ if (row.assumedMasterState) {
258
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
259
+ }
260
+ }
261
+ }
262
+ return conflicts;
263
+ }
264
+ }
265
+ };
266
+
267
+ // src/index.ts
268
+ var shopifyConnector = {
269
+ id: "shopify",
270
+ name: "Shopify",
271
+ description: "Connect to Shopify stores via the Admin REST API",
272
+ icon: void 0,
273
+ auth: {
274
+ type: "Shopify Admin API",
275
+ fields: [
276
+ {
277
+ key: "store",
278
+ label: "Store Name",
279
+ type: "text",
280
+ placeholder: "my-store (from my-store.myshopify.com)",
281
+ required: true
282
+ },
283
+ {
284
+ key: "access_token",
285
+ label: "Access Token",
286
+ type: "password",
287
+ placeholder: "shpat_...",
288
+ required: true
289
+ }
290
+ ],
291
+ getHeaders: (credentials) => ({
292
+ "X-Shopify-Access-Token": credentials.access_token,
293
+ "Content-Type": "application/json"
294
+ })
295
+ },
296
+ schemas: {
297
+ products: shopifyProductSchema
298
+ },
299
+ traits: {
300
+ product: shopifyProductTraits
301
+ },
302
+ sync: {
303
+ products: shopifyProductSync
304
+ },
305
+ replication: {
306
+ products: shopifyProductReplication
307
+ }
308
+ };
309
+ export {
310
+ shopifyConnector,
311
+ shopifyProductReplication,
312
+ shopifyProductSchema,
313
+ shopifyProductSync,
314
+ shopifyProductTraits
315
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@tallyui/connector-shopify",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Shopify 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
+ }
@@ -0,0 +1,275 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { shopifyProductTraits } from '../traits/product';
3
+
4
+ /**
5
+ * Realistic Shopify product document, shaped like the Admin REST API response.
6
+ */
7
+ const fullProduct = {
8
+ id: 7429873610823,
9
+ title: 'Espresso Machine Pro',
10
+ body_html: '<p>High-end espresso machine with dual boilers.</p>',
11
+ vendor: 'BrewCraft',
12
+ product_type: 'Equipment',
13
+ handle: 'espresso-machine-pro',
14
+ status: 'active',
15
+ tags: 'coffee, equipment, pro-series',
16
+ variants: [
17
+ {
18
+ id: 42304918372615,
19
+ title: 'Silver',
20
+ price: '599.99',
21
+ compare_at_price: null,
22
+ sku: 'ESP-PRO-SLV',
23
+ barcode: '1234567890123',
24
+ inventory_policy: 'deny',
25
+ inventory_management: 'shopify',
26
+ inventory_quantity: 15,
27
+ option1: 'Silver',
28
+ },
29
+ {
30
+ id: 42304918372616,
31
+ title: 'Matte Black',
32
+ price: '649.99',
33
+ compare_at_price: '699.99',
34
+ sku: 'ESP-PRO-BLK',
35
+ barcode: '1234567890124',
36
+ inventory_policy: 'deny',
37
+ inventory_management: 'shopify',
38
+ inventory_quantity: 3,
39
+ option1: 'Matte Black',
40
+ },
41
+ ],
42
+ options: [
43
+ { id: 1, name: 'Color', position: 1, values: ['Silver', 'Matte Black'] },
44
+ ],
45
+ images: [
46
+ { id: 1, src: 'https://cdn.shopify.com/espresso-front.jpg', alt: 'Front', position: 1 },
47
+ { id: 2, src: 'https://cdn.shopify.com/espresso-black.jpg', alt: 'Black', position: 2 },
48
+ ],
49
+ image: {
50
+ id: 1,
51
+ src: 'https://cdn.shopify.com/espresso-front.jpg',
52
+ alt: 'Front',
53
+ },
54
+ };
55
+
56
+ /**
57
+ * Single-variant product (no meaningful options).
58
+ */
59
+ const simpleProduct = {
60
+ id: 7429873610824,
61
+ title: 'Coffee Mug',
62
+ body_html: '<p>A simple ceramic mug.</p>',
63
+ product_type: '',
64
+ status: 'active',
65
+ tags: '',
66
+ variants: [
67
+ {
68
+ id: 42304918372617,
69
+ title: 'Default Title',
70
+ price: '14.99',
71
+ compare_at_price: null,
72
+ sku: 'MUG-001',
73
+ barcode: null,
74
+ inventory_policy: 'deny',
75
+ inventory_management: null, // not tracking inventory
76
+ inventory_quantity: 0,
77
+ },
78
+ ],
79
+ options: [
80
+ { id: 1, name: 'Title', position: 1, values: ['Default Title'] },
81
+ ],
82
+ images: [],
83
+ image: null,
84
+ };
85
+
86
+ /**
87
+ * Product with an active sale (compare_at_price > price).
88
+ */
89
+ const saleProduct = {
90
+ ...fullProduct,
91
+ id: 7429873610825,
92
+ variants: [
93
+ {
94
+ ...fullProduct.variants[0],
95
+ price: '499.99',
96
+ compare_at_price: '599.99',
97
+ },
98
+ ],
99
+ };
100
+
101
+ const minimalProduct = {
102
+ id: 9999,
103
+ };
104
+
105
+ describe('Shopify product traits', () => {
106
+ describe('getId', () => {
107
+ it('returns the product id as a string', () => {
108
+ expect(shopifyProductTraits.getId(fullProduct)).toBe('7429873610823');
109
+ });
110
+ });
111
+
112
+ describe('getName', () => {
113
+ it('returns the title', () => {
114
+ expect(shopifyProductTraits.getName(fullProduct)).toBe('Espresso Machine Pro');
115
+ });
116
+
117
+ it('returns empty string for missing title', () => {
118
+ expect(shopifyProductTraits.getName(minimalProduct)).toBe('');
119
+ });
120
+ });
121
+
122
+ describe('getSku', () => {
123
+ it('returns SKU from first variant', () => {
124
+ expect(shopifyProductTraits.getSku(fullProduct)).toBe('ESP-PRO-SLV');
125
+ });
126
+
127
+ it('returns undefined when no variants', () => {
128
+ expect(shopifyProductTraits.getSku(minimalProduct)).toBeUndefined();
129
+ });
130
+ });
131
+
132
+ describe('getPrice', () => {
133
+ it('returns price string from first variant', () => {
134
+ expect(shopifyProductTraits.getPrice(fullProduct)).toBe('599.99');
135
+ });
136
+
137
+ it('returns undefined when no variants', () => {
138
+ expect(shopifyProductTraits.getPrice(minimalProduct)).toBeUndefined();
139
+ });
140
+ });
141
+
142
+ describe('getRegularPrice / getSalePrice / isOnSale', () => {
143
+ it('regular price falls back to current price when no compare_at', () => {
144
+ expect(shopifyProductTraits.getRegularPrice(fullProduct)).toBe('599.99');
145
+ });
146
+
147
+ it('not on sale when compare_at_price is null', () => {
148
+ expect(shopifyProductTraits.isOnSale(fullProduct)).toBe(false);
149
+ expect(shopifyProductTraits.getSalePrice(fullProduct)).toBeUndefined();
150
+ });
151
+
152
+ it('detects sale when compare_at_price > price', () => {
153
+ expect(shopifyProductTraits.isOnSale(saleProduct)).toBe(true);
154
+ expect(shopifyProductTraits.getSalePrice(saleProduct)).toBe('499.99');
155
+ expect(shopifyProductTraits.getRegularPrice(saleProduct)).toBe('599.99');
156
+ });
157
+ });
158
+
159
+ describe('getImageUrl / getImageUrls', () => {
160
+ it('returns the primary image src via image shortcut', () => {
161
+ expect(shopifyProductTraits.getImageUrl(fullProduct)).toBe(
162
+ 'https://cdn.shopify.com/espresso-front.jpg'
163
+ );
164
+ });
165
+
166
+ it('returns all image URLs', () => {
167
+ expect(shopifyProductTraits.getImageUrls(fullProduct)).toEqual([
168
+ 'https://cdn.shopify.com/espresso-front.jpg',
169
+ 'https://cdn.shopify.com/espresso-black.jpg',
170
+ ]);
171
+ });
172
+
173
+ it('returns undefined / empty for product with no images', () => {
174
+ expect(shopifyProductTraits.getImageUrl(simpleProduct)).toBeUndefined();
175
+ expect(shopifyProductTraits.getImageUrls(simpleProduct)).toEqual([]);
176
+ });
177
+ });
178
+
179
+ describe('getDescription', () => {
180
+ it('returns body_html', () => {
181
+ expect(shopifyProductTraits.getDescription(fullProduct)).toBe(
182
+ '<p>High-end espresso machine with dual boilers.</p>'
183
+ );
184
+ });
185
+
186
+ it('returns undefined when missing', () => {
187
+ expect(shopifyProductTraits.getDescription(minimalProduct)).toBeUndefined();
188
+ });
189
+ });
190
+
191
+ describe('getStockStatus', () => {
192
+ it('returns instock for product with quantity', () => {
193
+ expect(shopifyProductTraits.getStockStatus(fullProduct)).toBe('instock');
194
+ });
195
+
196
+ it('returns instock when inventory_management is null (not tracked)', () => {
197
+ expect(shopifyProductTraits.getStockStatus(simpleProduct)).toBe('instock');
198
+ });
199
+
200
+ it('returns outofstock when tracked and quantity is 0', () => {
201
+ const outOfStock = {
202
+ ...fullProduct,
203
+ variants: [{
204
+ ...fullProduct.variants[0],
205
+ inventory_quantity: 0,
206
+ }],
207
+ };
208
+ expect(shopifyProductTraits.getStockStatus(outOfStock)).toBe('outofstock');
209
+ });
210
+
211
+ it('returns onbackorder when inventory_policy is continue', () => {
212
+ const backorder = {
213
+ ...fullProduct,
214
+ variants: [{
215
+ ...fullProduct.variants[0],
216
+ inventory_policy: 'continue',
217
+ inventory_quantity: 0,
218
+ }],
219
+ };
220
+ expect(shopifyProductTraits.getStockStatus(backorder)).toBe('onbackorder');
221
+ });
222
+
223
+ it('returns unknown when no variants', () => {
224
+ expect(shopifyProductTraits.getStockStatus(minimalProduct)).toBe('unknown');
225
+ });
226
+ });
227
+
228
+ describe('getStockQuantity', () => {
229
+ it('returns quantity from first variant', () => {
230
+ expect(shopifyProductTraits.getStockQuantity(fullProduct)).toBe(15);
231
+ });
232
+
233
+ it('returns null when no variants', () => {
234
+ expect(shopifyProductTraits.getStockQuantity(minimalProduct)).toBeNull();
235
+ });
236
+ });
237
+
238
+ describe('hasVariants / getType', () => {
239
+ it('multi-variant product has variants', () => {
240
+ expect(shopifyProductTraits.hasVariants(fullProduct)).toBe(true);
241
+ });
242
+
243
+ it('single-variant product has no variants', () => {
244
+ expect(shopifyProductTraits.hasVariants(simpleProduct)).toBe(false);
245
+ });
246
+
247
+ it('returns product_type', () => {
248
+ expect(shopifyProductTraits.getType(fullProduct)).toBe('Equipment');
249
+ });
250
+
251
+ it('defaults to simple when product_type is empty', () => {
252
+ expect(shopifyProductTraits.getType(simpleProduct)).toBe('simple');
253
+ });
254
+ });
255
+
256
+ describe('getBarcode', () => {
257
+ it('returns barcode from first variant', () => {
258
+ expect(shopifyProductTraits.getBarcode(fullProduct)).toBe('1234567890123');
259
+ });
260
+
261
+ it('returns undefined when barcode is null', () => {
262
+ expect(shopifyProductTraits.getBarcode(simpleProduct)).toBeUndefined();
263
+ });
264
+ });
265
+
266
+ describe('getCategoryNames', () => {
267
+ it('returns product_type as category', () => {
268
+ expect(shopifyProductTraits.getCategoryNames(fullProduct)).toEqual(['Equipment']);
269
+ });
270
+
271
+ it('returns empty array when product_type is empty', () => {
272
+ expect(shopifyProductTraits.getCategoryNames(simpleProduct)).toEqual([]);
273
+ });
274
+ });
275
+ });
package/src/index.ts ADDED
@@ -0,0 +1,74 @@
1
+ import type { TallyConnector } from '@tallyui/core';
2
+
3
+ import { shopifyProductSchema } from './schemas/products';
4
+ import { shopifyProductTraits } from './traits/product';
5
+ import { shopifyProductSync } from './sync/products';
6
+ import { shopifyProductReplication } from './replication/products';
7
+
8
+ /**
9
+ * Shopify connector for Tally UI.
10
+ *
11
+ * Connects to Shopify stores via the Admin REST API.
12
+ * Products are stored in RxDB using a schema that mirrors the Shopify API shape.
13
+ *
14
+ * ```ts
15
+ * import { shopifyConnector } from '@tallyui/connector-shopify';
16
+ * import { ConnectorProvider } from '@tallyui/core';
17
+ *
18
+ * <ConnectorProvider connector={shopifyConnector}>
19
+ * <App />
20
+ * </ConnectorProvider>
21
+ * ```
22
+ */
23
+ export const shopifyConnector: TallyConnector = {
24
+ id: 'shopify',
25
+ name: 'Shopify',
26
+ description: 'Connect to Shopify stores via the Admin REST API',
27
+ icon: undefined,
28
+
29
+ auth: {
30
+ type: 'Shopify Admin API',
31
+ fields: [
32
+ {
33
+ key: 'store',
34
+ label: 'Store Name',
35
+ type: 'text',
36
+ placeholder: 'my-store (from my-store.myshopify.com)',
37
+ required: true,
38
+ },
39
+ {
40
+ key: 'access_token',
41
+ label: 'Access Token',
42
+ type: 'password',
43
+ placeholder: 'shpat_...',
44
+ required: true,
45
+ },
46
+ ],
47
+ getHeaders: (credentials) => ({
48
+ 'X-Shopify-Access-Token': credentials.access_token,
49
+ 'Content-Type': 'application/json',
50
+ }),
51
+ },
52
+
53
+ schemas: {
54
+ products: shopifyProductSchema,
55
+ },
56
+
57
+ traits: {
58
+ product: shopifyProductTraits,
59
+ },
60
+
61
+ sync: {
62
+ products: shopifyProductSync,
63
+ },
64
+
65
+ replication: {
66
+ products: shopifyProductReplication,
67
+ },
68
+ };
69
+
70
+ // Re-export pieces for advanced usage
71
+ export { shopifyProductSchema } from './schemas/products';
72
+ export { shopifyProductTraits } from './traits/product';
73
+ export { shopifyProductSync } from './sync/products';
74
+ export { shopifyProductReplication } from './replication/products';
@@ -0,0 +1,206 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import type { SyncContext } from '@tallyui/core';
3
+
4
+ import { shopifyProductReplication } from './products';
5
+
6
+ const context: SyncContext = {
7
+ connectorId: 'shopify',
8
+ baseUrl: 'https://my-store.myshopify.com',
9
+ headers: { 'X-Shopify-Access-Token': 'shpat_test_token' },
10
+ };
11
+
12
+ describe('shopifyProductReplication.pull.handler', () => {
13
+ beforeEach(() => {
14
+ vi.restoreAllMocks();
15
+ });
16
+
17
+ it('fetches products from initial checkpoint (undefined)', async () => {
18
+ const mockProducts = [
19
+ { id: 1001, title: 'Widget', updated_at: '2026-01-01T00:00:00Z' },
20
+ { id: 1002, title: 'Gadget', updated_at: '2026-01-02T00:00:00Z' },
21
+ ];
22
+
23
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
24
+ new Response(JSON.stringify({ products: mockProducts }), {
25
+ status: 200,
26
+ headers: { 'Content-Type': 'application/json' },
27
+ }),
28
+ );
29
+
30
+ const result = await shopifyProductReplication.pull.handler(undefined, 100, context);
31
+
32
+ expect(result.documents).toHaveLength(2);
33
+ expect(result.documents[0]._deleted).toBe(false);
34
+ expect(result.documents[0].id).toBe('1001');
35
+ expect(result.documents[1].id).toBe('1002');
36
+ expect(result.checkpoint).toEqual({
37
+ updated_at: '2026-01-02T00:00:00Z',
38
+ });
39
+ });
40
+
41
+ it('passes updated_at_min when checkpoint is provided', async () => {
42
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
43
+ new Response(JSON.stringify({ products: [] }), {
44
+ status: 200,
45
+ headers: { 'Content-Type': 'application/json' },
46
+ }),
47
+ );
48
+
49
+ const checkpoint = { updated_at: '2026-01-01T00:00:00Z' };
50
+ const result = await shopifyProductReplication.pull.handler(checkpoint, 100, context);
51
+
52
+ expect(result.documents).toHaveLength(0);
53
+
54
+ const calledUrl = (globalThis.fetch as any).mock.calls[0][0];
55
+ expect(calledUrl).toContain('updated_at_min=2026-01-01T00%3A00%3A00Z');
56
+ });
57
+
58
+ it('follows cursor-based pagination via Link header', async () => {
59
+ const page1 = [
60
+ { id: 1001, title: 'Widget', updated_at: '2026-01-01T00:00:00Z' },
61
+ ];
62
+ const page2 = [
63
+ { id: 1002, title: 'Gadget', updated_at: '2026-01-02T00:00:00Z' },
64
+ ];
65
+
66
+ vi.spyOn(globalThis, 'fetch')
67
+ .mockResolvedValueOnce(
68
+ new Response(JSON.stringify({ products: page1 }), {
69
+ status: 200,
70
+ headers: {
71
+ 'Content-Type': 'application/json',
72
+ Link: '<https://my-store.myshopify.com/admin/api/2024-01/products.json?page_info=abc123&limit=1>; rel="next"',
73
+ },
74
+ }),
75
+ )
76
+ .mockResolvedValueOnce(
77
+ new Response(JSON.stringify({ products: page2 }), {
78
+ status: 200,
79
+ headers: { 'Content-Type': 'application/json' },
80
+ }),
81
+ );
82
+
83
+ const result = await shopifyProductReplication.pull.handler(undefined, 1, context);
84
+
85
+ expect(result.documents).toHaveLength(2);
86
+ expect(result.checkpoint).toEqual({
87
+ updated_at: '2026-01-02T00:00:00Z',
88
+ });
89
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
90
+ });
91
+
92
+ it('throws on non-OK response', async () => {
93
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
94
+ new Response('Internal Server Error', { status: 500 }),
95
+ );
96
+
97
+ await expect(
98
+ shopifyProductReplication.pull.handler(undefined, 100, context),
99
+ ).rejects.toThrow('Shopify API error: 500');
100
+ });
101
+
102
+ it('returns lastCheckpoint when no products are returned', async () => {
103
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
104
+ new Response(JSON.stringify({ products: [] }), {
105
+ status: 200,
106
+ headers: { 'Content-Type': 'application/json' },
107
+ }),
108
+ );
109
+
110
+ const checkpoint = { updated_at: '2026-01-01T00:00:00Z' };
111
+ const result = await shopifyProductReplication.pull.handler(checkpoint, 100, context);
112
+
113
+ expect(result.checkpoint).toEqual(checkpoint);
114
+ });
115
+
116
+ it('normalizes numeric IDs to strings', async () => {
117
+ const mockProducts = [
118
+ { id: 9999, title: 'Numeric ID', updated_at: '2026-03-01T00:00:00Z' },
119
+ ];
120
+
121
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
122
+ new Response(JSON.stringify({ products: mockProducts }), {
123
+ status: 200,
124
+ headers: { 'Content-Type': 'application/json' },
125
+ }),
126
+ );
127
+
128
+ const result = await shopifyProductReplication.pull.handler(undefined, 100, context);
129
+
130
+ expect(result.documents[0].id).toBe('9999');
131
+ });
132
+ });
133
+
134
+ describe('shopifyProductReplication.push.handler', () => {
135
+ beforeEach(() => {
136
+ vi.restoreAllMocks();
137
+ });
138
+
139
+ it('sends PUT for updates with product wrapper', async () => {
140
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
141
+ new Response(JSON.stringify({}), { status: 200 }),
142
+ );
143
+
144
+ const conflicts = await shopifyProductReplication.push!.handler(
145
+ [{
146
+ newDocumentState: { id: '1001', title: 'Updated', _deleted: false } as any,
147
+ assumedMasterState: { id: '1001', title: 'Old', _deleted: false } as any,
148
+ }],
149
+ context,
150
+ );
151
+
152
+ expect(conflicts).toHaveLength(0);
153
+ const [url, opts] = (globalThis.fetch as any).mock.calls[0];
154
+ expect(url).toContain('/admin/api/2024-01/products/1001.json');
155
+ expect(opts.method).toBe('PUT');
156
+ const body = JSON.parse(opts.body);
157
+ expect(body.product).toBeDefined();
158
+ expect(body.product.title).toBe('Updated');
159
+ });
160
+
161
+ it('returns conflicts on server error', async () => {
162
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
163
+ new Response('conflict', { status: 409 }),
164
+ );
165
+
166
+ const conflicts = await shopifyProductReplication.push!.handler(
167
+ [{
168
+ newDocumentState: { id: '1001', title: 'Updated', _deleted: false } as any,
169
+ assumedMasterState: { id: '1001', title: 'Server Version', _deleted: false } as any,
170
+ }],
171
+ context,
172
+ );
173
+
174
+ expect(conflicts).toHaveLength(1);
175
+ expect(conflicts[0].title).toBe('Server Version');
176
+ });
177
+
178
+ it('returns conflicts on network failure', async () => {
179
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new Error('Network error'));
180
+
181
+ const conflicts = await shopifyProductReplication.push!.handler(
182
+ [{
183
+ newDocumentState: { id: '1001', title: 'Updated', _deleted: false } as any,
184
+ assumedMasterState: { id: '1001', title: 'Server Version', _deleted: false } as any,
185
+ }],
186
+ context,
187
+ );
188
+
189
+ expect(conflicts).toHaveLength(1);
190
+ });
191
+
192
+ it('does not return conflict when assumedMasterState is absent', async () => {
193
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
194
+ new Response('error', { status: 500 }),
195
+ );
196
+
197
+ const conflicts = await shopifyProductReplication.push!.handler(
198
+ [{
199
+ newDocumentState: { id: '1001', title: 'New Product', _deleted: false } as any,
200
+ }],
201
+ context,
202
+ );
203
+
204
+ expect(conflicts).toHaveLength(0);
205
+ });
206
+ });
@@ -0,0 +1,111 @@
1
+ import type { ReplicationAdapter } from '@tallyui/core';
2
+
3
+ export type ShopifyProductCheckpoint = {
4
+ updated_at: string;
5
+ };
6
+
7
+ /**
8
+ * Parse the "next" URL from Shopify's Link header for cursor pagination.
9
+ * Returns an empty string if there's no next page.
10
+ */
11
+ function parseLinkNext(linkHeader: string | null): string {
12
+ if (!linkHeader) return '';
13
+ const match = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
14
+ return match ? match[1] : '';
15
+ }
16
+
17
+ /**
18
+ * Shopify IDs are integers but RxDB primary keys must be strings.
19
+ */
20
+ function normalizeId(product: any) {
21
+ return { ...product, id: String(product.id) };
22
+ }
23
+
24
+ /**
25
+ * Replication adapter for Shopify products.
26
+ *
27
+ * Implements pull (cursor-based pagination via Link header, filtered by
28
+ * updated_at_min) and push (PUT to update individual products via Admin
29
+ * REST API). Designed for use with RxDB's replicateRxCollection.
30
+ */
31
+ export const shopifyProductReplication: ReplicationAdapter<any, ShopifyProductCheckpoint> = {
32
+ pull: {
33
+ async handler(lastCheckpoint, batchSize, context) {
34
+ const params = new URLSearchParams({
35
+ limit: String(batchSize),
36
+ });
37
+
38
+ if (lastCheckpoint?.updated_at) {
39
+ params.set('updated_at_min', lastCheckpoint.updated_at);
40
+ }
41
+
42
+ let url: string = `${context.baseUrl}/admin/api/2024-01/products.json?${params}`;
43
+ const allProducts: any[] = [];
44
+
45
+ while (url) {
46
+ const response = await fetch(url, {
47
+ headers: {
48
+ ...context.headers,
49
+ 'Content-Type': 'application/json',
50
+ },
51
+ signal: context.signal,
52
+ });
53
+
54
+ if (!response.ok) {
55
+ throw new Error(`Shopify API error: ${response.status}`);
56
+ }
57
+
58
+ const data = await response.json();
59
+ const products = (data.products ?? []).map(normalizeId);
60
+ allProducts.push(...products);
61
+
62
+ url = parseLinkNext(response.headers.get('Link'));
63
+ }
64
+
65
+ const documents = allProducts.map((p) => ({ ...p, _deleted: false }));
66
+
67
+ const checkpoint: ShopifyProductCheckpoint = allProducts.length > 0
68
+ ? { updated_at: allProducts[allProducts.length - 1].updated_at }
69
+ : lastCheckpoint ?? { updated_at: '' };
70
+
71
+ return { documents, checkpoint };
72
+ },
73
+ },
74
+
75
+ push: {
76
+ async handler(changeRows, context) {
77
+ const conflicts: any[] = [];
78
+
79
+ for (const row of changeRows) {
80
+ const doc = row.newDocumentState as any;
81
+
82
+ try {
83
+ const response = await fetch(
84
+ `${context.baseUrl}/admin/api/2024-01/products/${doc.id}.json`,
85
+ {
86
+ method: 'PUT',
87
+ headers: {
88
+ ...context.headers,
89
+ 'Content-Type': 'application/json',
90
+ },
91
+ body: JSON.stringify({ product: doc }),
92
+ signal: context.signal,
93
+ },
94
+ );
95
+
96
+ if (!response.ok) {
97
+ if (row.assumedMasterState) {
98
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
99
+ }
100
+ }
101
+ } catch {
102
+ if (row.assumedMasterState) {
103
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
104
+ }
105
+ }
106
+ }
107
+
108
+ return conflicts;
109
+ },
110
+ },
111
+ };
@@ -0,0 +1,91 @@
1
+ import type { RxJsonSchema } from 'rxdb';
2
+
3
+ /**
4
+ * RxDB schema for Shopify products.
5
+ *
6
+ * Mirrors the Shopify Admin REST API product shape. Key difference from
7
+ * WooCommerce: price, SKU, barcode, and inventory live on variants, not
8
+ * the product itself. Even single-option products have one variant.
9
+ */
10
+ export const shopifyProductSchema: RxJsonSchema<any> = {
11
+ version: 0,
12
+ primaryKey: 'id',
13
+ type: 'object',
14
+ properties: {
15
+ id: { type: 'string', maxLength: 100 },
16
+ title: { type: 'string' },
17
+ body_html: { type: 'string' },
18
+ vendor: { type: 'string' },
19
+ product_type: { type: 'string' },
20
+ handle: { type: 'string', maxLength: 255 },
21
+ status: {
22
+ type: 'string',
23
+ enum: ['active', 'archived', 'draft'],
24
+ },
25
+ tags: { type: 'string' },
26
+ published_scope: { type: 'string' },
27
+ variants: {
28
+ type: 'array',
29
+ items: {
30
+ type: 'object',
31
+ properties: {
32
+ id: { type: 'number' },
33
+ title: { type: 'string' },
34
+ price: { type: 'string' },
35
+ compare_at_price: { type: ['string', 'null'] },
36
+ sku: { type: ['string', 'null'] },
37
+ barcode: { type: ['string', 'null'] },
38
+ position: { type: 'number' },
39
+ inventory_policy: { type: 'string' },
40
+ inventory_management: { type: ['string', 'null'] },
41
+ inventory_quantity: { type: 'number' },
42
+ option1: { type: ['string', 'null'] },
43
+ option2: { type: ['string', 'null'] },
44
+ option3: { type: ['string', 'null'] },
45
+ weight: { type: 'number' },
46
+ weight_unit: { type: 'string' },
47
+ taxable: { type: 'boolean' },
48
+ requires_shipping: { type: 'boolean' },
49
+ },
50
+ },
51
+ },
52
+ options: {
53
+ type: 'array',
54
+ items: {
55
+ type: 'object',
56
+ properties: {
57
+ id: { type: 'number' },
58
+ name: { type: 'string' },
59
+ position: { type: 'number' },
60
+ values: {
61
+ type: 'array',
62
+ items: { type: 'string' },
63
+ },
64
+ },
65
+ },
66
+ },
67
+ images: {
68
+ type: 'array',
69
+ items: {
70
+ type: 'object',
71
+ properties: {
72
+ id: { type: 'number' },
73
+ src: { type: 'string' },
74
+ alt: { type: ['string', 'null'] },
75
+ position: { type: 'number' },
76
+ width: { type: 'number' },
77
+ height: { type: 'number' },
78
+ },
79
+ },
80
+ },
81
+ image: {
82
+ type: ['object', 'null'],
83
+ properties: {
84
+ src: { type: 'string' },
85
+ },
86
+ },
87
+ updated_at: { type: 'string', maxLength: 50 },
88
+ },
89
+ required: ['id'],
90
+ indexes: ['handle', 'status', 'updated_at'],
91
+ };
@@ -0,0 +1,91 @@
1
+ import type { CollectionSync, SyncContext } from '@tallyui/core';
2
+
3
+ /**
4
+ * Shopify product sync implementation.
5
+ *
6
+ * Uses the Admin REST API. Shopify uses cursor-based pagination via
7
+ * the Link header (page_info parameter), not page numbers.
8
+ */
9
+ export const shopifyProductSync: CollectionSync = {
10
+ fetchAllIds: async (context: SyncContext) => {
11
+ const entries: { id: string; dateModified?: string }[] = [];
12
+ let url = `${context.baseUrl}/admin/api/2024-01/products.json?fields=id,updated_at&limit=250`;
13
+
14
+ while (url) {
15
+ const res = await fetch(url, {
16
+ headers: context.headers,
17
+ signal: context.signal,
18
+ });
19
+
20
+ if (!res.ok) throw new Error(`Shopify API error: ${res.status}`);
21
+
22
+ const data = await res.json();
23
+ for (const product of data.products ?? []) {
24
+ entries.push({
25
+ id: String(product.id),
26
+ dateModified: product.updated_at,
27
+ });
28
+ }
29
+
30
+ // Parse cursor-based pagination from Link header
31
+ url = parseLinkNext(res.headers.get('Link'));
32
+ }
33
+
34
+ return entries;
35
+ },
36
+
37
+ fetchByIds: async (ids: string[], context: SyncContext) => {
38
+ // Shopify REST API supports fetching by comma-separated IDs
39
+ const idsParam = ids.join(',');
40
+ const res = await fetch(
41
+ `${context.baseUrl}/admin/api/2024-01/products.json?ids=${idsParam}`,
42
+ {
43
+ headers: context.headers,
44
+ signal: context.signal,
45
+ },
46
+ );
47
+
48
+ if (!res.ok) throw new Error(`Shopify API error: ${res.status}`);
49
+
50
+ const data = await res.json();
51
+ return (data.products ?? []).map(normalizeId);
52
+ },
53
+
54
+ fetchModifiedAfter: async (date: string, context: SyncContext) => {
55
+ const products: any[] = [];
56
+ let url = `${context.baseUrl}/admin/api/2024-01/products.json?updated_at_min=${date}&limit=250`;
57
+
58
+ while (url) {
59
+ const res = await fetch(url, {
60
+ headers: context.headers,
61
+ signal: context.signal,
62
+ });
63
+
64
+ if (!res.ok) throw new Error(`Shopify API error: ${res.status}`);
65
+
66
+ const data = await res.json();
67
+ products.push(...(data.products ?? []).map(normalizeId));
68
+
69
+ url = parseLinkNext(res.headers.get('Link'));
70
+ }
71
+
72
+ return products;
73
+ },
74
+ };
75
+
76
+ /**
77
+ * Shopify IDs are integers but RxDB primary keys must be strings.
78
+ */
79
+ function normalizeId(product: any) {
80
+ return { ...product, id: String(product.id) };
81
+ }
82
+
83
+ /**
84
+ * Parse the "next" URL from Shopify's Link header for cursor pagination.
85
+ * Returns null if there's no next page.
86
+ */
87
+ function parseLinkNext(linkHeader: string | null): string {
88
+ if (!linkHeader) return '';
89
+ const match = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
90
+ return match ? match[1] : '';
91
+ }
@@ -0,0 +1,88 @@
1
+ import type { ProductTraits } from '@tallyui/core';
2
+
3
+ /**
4
+ * Shopify product trait implementations.
5
+ *
6
+ * Key differences from WooCommerce / Medusa:
7
+ * - Product name is `title` (same as Medusa)
8
+ * - Price, SKU, barcode, inventory all live on variants, not the product
9
+ * - Sale detection uses `compare_at_price` > `price` (no explicit on_sale flag)
10
+ * - Description is `body_html` (single field, HTML)
11
+ * - Categories don't exist on the product — `product_type` is the closest thing
12
+ * - Stock status is derived from inventory_management + inventory_policy + quantity
13
+ */
14
+ export const shopifyProductTraits: ProductTraits = {
15
+ getId: (doc) => String(doc.id),
16
+
17
+ getName: (doc) => doc.title ?? '',
18
+
19
+ getSku: (doc) => doc.variants?.[0]?.sku || undefined,
20
+
21
+ getPrice: (doc) => doc.variants?.[0]?.price || undefined,
22
+
23
+ getRegularPrice: (doc) => {
24
+ const variant = doc.variants?.[0];
25
+ if (!variant) return undefined;
26
+ // compare_at_price is the "original" price; fall back to current price
27
+ return variant.compare_at_price || variant.price || undefined;
28
+ },
29
+
30
+ getSalePrice: (doc) => {
31
+ const variant = doc.variants?.[0];
32
+ if (!variant) return undefined;
33
+ // In Shopify, when compare_at_price > price, the product is on sale
34
+ // and `price` IS the sale price
35
+ if (
36
+ variant.compare_at_price &&
37
+ parseFloat(variant.compare_at_price) > parseFloat(variant.price)
38
+ ) {
39
+ return variant.price;
40
+ }
41
+ return undefined;
42
+ },
43
+
44
+ isOnSale: (doc) => {
45
+ const variant = doc.variants?.[0];
46
+ if (!variant?.compare_at_price) return false;
47
+ return parseFloat(variant.compare_at_price) > parseFloat(variant.price);
48
+ },
49
+
50
+ getImageUrl: (doc) => doc.image?.src || doc.images?.[0]?.src || undefined,
51
+
52
+ getImageUrls: (doc) =>
53
+ (doc.images ?? []).map((img: any) => img.src).filter(Boolean),
54
+
55
+ getDescription: (doc) => doc.body_html || undefined,
56
+
57
+ getStockStatus: (doc) => {
58
+ const variant = doc.variants?.[0];
59
+ if (!variant) return 'unknown';
60
+
61
+ // Not tracking inventory — always in stock
62
+ if (variant.inventory_management == null) return 'instock';
63
+
64
+ // Allows overselling — treat as backorderable
65
+ if (variant.inventory_policy === 'continue') return 'onbackorder';
66
+
67
+ // Tracking inventory, deny when out of stock
68
+ const qty = variant.inventory_quantity;
69
+ if (qty == null) return 'unknown';
70
+ return qty > 0 ? 'instock' : 'outofstock';
71
+ },
72
+
73
+ getStockQuantity: (doc) => doc.variants?.[0]?.inventory_quantity ?? null,
74
+
75
+ hasVariants: (doc) => (doc.variants?.length ?? 0) > 1,
76
+
77
+ getType: (doc) => doc.product_type || 'simple',
78
+
79
+ getBarcode: (doc) => doc.variants?.[0]?.barcode || undefined,
80
+
81
+ getCategoryNames: (doc) => {
82
+ // Shopify doesn't embed collections on the product object.
83
+ // product_type is the closest inline field.
84
+ const names: string[] = [];
85
+ if (doc.product_type) names.push(doc.product_type);
86
+ return names;
87
+ },
88
+ };