@porulle/adapter-woocommerce 0.73.2 → 0.74.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.
package/dist/index.js CHANGED
@@ -1,815 +1,170 @@
1
- import { defineChannelConnector, Err, Ok, toMinorUnits } from "@porulle/core";
2
- import { createHmac, timingSafeEqual } from "node:crypto";
3
- const PORULLE_META_PREFIX = "porulle_";
4
- const WOO_BATCH_LIMIT = 100;
5
- const catalogRequestOptions = { retryableClientErrors: true };
6
- const wooProductNativeFields = new Set([
7
- "name",
8
- "slug",
9
- "type",
10
- "status",
11
- "featured",
12
- "catalog_visibility",
13
- "description",
14
- "short_description",
15
- "sku",
16
- "regular_price",
17
- "sale_price",
18
- "date_on_sale_from",
19
- "date_on_sale_to",
20
- "virtual",
21
- "downloadable",
22
- "downloads",
23
- "download_limit",
24
- "download_expiry",
25
- "external_url",
26
- "button_text",
27
- "tax_status",
28
- "tax_class",
29
- "manage_stock",
30
- "stock_quantity",
31
- "backorders",
32
- "sold_individually",
33
- "weight",
34
- "dimensions",
35
- "shipping_class",
36
- "reviews_allowed",
37
- "upsell_ids",
38
- "cross_sell_ids",
39
- "parent_id",
40
- "purchase_note",
41
- "menu_order",
42
- "images",
43
- ]);
44
- const wooVariationNativeFields = new Set([
45
- "description",
46
- "sku",
47
- "regular_price",
48
- "sale_price",
49
- "date_on_sale_from",
50
- "date_on_sale_to",
51
- "status",
52
- "virtual",
53
- "downloadable",
54
- "downloads",
55
- "download_limit",
56
- "download_expiry",
57
- "tax_status",
58
- "tax_class",
59
- "manage_stock",
60
- "stock_quantity",
61
- "backorders",
62
- "weight",
63
- "dimensions",
64
- "shipping_class",
65
- "shipping_class_id",
66
- "image",
67
- "menu_order",
68
- ]);
69
- function buildWooUrl(base, path, key, secret, page, cursor) {
70
- const url = new URL(path, base.replace(/\/$/, "/"));
71
- url.searchParams.set("consumer_key", key);
72
- url.searchParams.set("consumer_secret", secret);
73
- url.searchParams.set("per_page", "100");
74
- url.searchParams.set("page", String(page));
75
- if (cursor)
76
- url.searchParams.set("modified_after", cursor);
77
- return url.toString();
78
- }
79
- function normalizeCurrency(value) {
80
- if (typeof value !== "string" || value.trim() === "")
81
- return undefined;
82
- return value.trim().toUpperCase();
83
- }
84
- function pricesForVariation(variation, currency) {
85
- if (!currency)
86
- return undefined;
87
- const amount = toMinorUnits(variation.price, currency);
88
- return amount === undefined ? undefined : [{ currency, amount }];
89
- }
90
- function catalogStatus(value) {
91
- if (value === "publish")
92
- return "active";
93
- if (value === "draft" || value === "private")
94
- return "draft";
95
- return undefined;
96
- }
97
- function asRecord(value) {
98
- return typeof value === "object" && value !== null ? value : undefined;
99
- }
100
- function settingCurrency(data) {
101
- if (Array.isArray(data)) {
102
- for (const entry of data) {
103
- const setting = asRecord(entry);
104
- if (setting?.id === "woocommerce_currency")
105
- return normalizeCurrency(setting.value);
106
- }
107
- }
108
- const object = asRecord(data);
109
- if (!object)
110
- return undefined;
111
- const direct = normalizeCurrency(object.woocommerce_currency);
112
- if (direct)
113
- return direct;
114
- const systemStatus = asRecord(object.system_status);
115
- return normalizeCurrency(systemStatus?.woocommerce_currency);
116
- }
117
- async function fetchWooCurrency(fetchImpl, url) {
118
- const result = await request(fetchImpl, url);
119
- return result.ok ? settingCurrency(result.value.data) : undefined;
120
- }
121
- async function fetchProductVariations(fetchImpl, storeDomain, auth, productId, modifiedAfter) {
122
- const variations = [];
123
- let page = 1;
124
- while (true) {
125
- const result = await request(fetchImpl, buildWooUrl(storeDomain, `/wp-json/wc/v3/products/${encodeURIComponent(productId)}/variations`, auth.key, auth.secret, page, modifiedAfter));
126
- if (!result.ok)
127
- return result;
128
- variations.push(...result.value.data);
129
- const totalPages = Number.parseInt(result.value.response.headers.get("x-wp-totalpages") ?? "1", 10);
130
- if (!Number.isFinite(totalPages) || page >= totalPages)
131
- break;
132
- page += 1;
133
- }
134
- return Ok(variations);
135
- }
136
- function variationFromReference(reference) {
137
- return typeof reference === "object" && reference !== null ? reference : { id: reference };
138
- }
139
- function mergeProductVariations(references, details) {
140
- const detailById = new Map(details.map((variation) => [String(variation.id), variation]));
141
- const referencedIds = new Set();
142
- const merged = references.map((reference) => {
143
- const fallback = variationFromReference(reference);
144
- const id = String(fallback.id);
145
- referencedIds.add(id);
146
- return detailById.get(id) ?? fallback;
147
- });
148
- return [...merged, ...details.filter((variation) => !referencedIds.has(String(variation.id)))];
149
- }
150
- function isRetriableStatus(status, options) {
151
- return status !== undefined && (status >= 500 || (options?.retryableClientErrors === true && (status === 408 || status === 429)));
152
- }
153
- async function request(fetchImpl, url, init, options) {
154
- try {
155
- const response = await fetchImpl(url, { ...init, headers: { accept: "application/json", ...(init?.headers ?? {}) } });
156
- if (!response.ok)
157
- return Err({ code: "WOO_API_FAILED", message: `WooCommerce request failed (${response.status}) for ${url}.`, retriable: isRetriableStatus(response.status, options) });
158
- return Ok({ data: await response.json(), response });
159
- }
160
- catch (error) {
161
- return Err({ code: "WOO_API_FAILED", message: error instanceof Error ? error.message : "WooCommerce request failed.", retriable: true });
162
- }
163
- }
164
- function connectorError(error) {
165
- return {
166
- code: error.code,
167
- message: error.message,
168
- ...(error.retriable !== undefined ? { retriable: error.retriable } : {}),
1
+ import { defineChannelConnector, Err, Ok } from "@porulle/core";
2
+ import { z } from "zod";
3
+ import { catalogItems, importPage, storeProfile } from "./catalog.js";
4
+ import { pushCatalog, pushCaches } from "./catalog-push.js";
5
+ import { discoverStore, normalizeStoreDomain, wooClient, wooCredentialsSchema } from "./client.js";
6
+ import { inventoryFor, inventoryPage } from "./inventory.js";
7
+ import { cancelOrder, orderStatus, pushOrder } from "./orders.js";
8
+ import { decodeDelivery, orderEvents, registerWebhooks, unregisterWebhooks, verifyDelivery, webhookHealth, WOO_WEBHOOK_TOPICS } from "./webhooks.js";
9
+ export { normalizeStoreDomain, probeStore, refusedStoreUrl, WOO_BLOCKED_BY_FIREWALL } from "./client.js";
10
+ export { ORDER_META_KEY } from "./orders.js";
11
+ export { WOO_WEBHOOK_TOPICS } from "./webhooks.js";
12
+ /** What WooCommerce posts to the callback when the merchant approves: keys, and our own `user_id` back. */
13
+ const authCallbackSchema = z.object({
14
+ key_id: z.union([z.number(), z.string()]).optional(),
15
+ user_id: z.union([z.string(), z.number()]).transform(String),
16
+ consumer_key: z.string(),
17
+ consumer_secret: z.string(),
18
+ key_permissions: z.string(),
19
+ });
20
+ const refused = (code, message) => Err({ code, message, retriable: false });
21
+ export function wooConnector(options = {}) {
22
+ const transport = {
23
+ fetchImpl: options.fetchImpl ?? ((input, init) => fetch(input, init)),
24
+ userAgent: options.userAgent ?? "Porulle-WooCommerce/1.0",
25
+ allowPrivateHosts: options.allowPrivateHosts === true,
169
26
  };
170
- }
171
- function batchErrorMessage(error) {
172
- const record = asRecord(error);
173
- return typeof record?.message === "string" && record.message.trim() !== ""
174
- ? record.message
175
- : typeof error === "string" && error.trim() !== ""
176
- ? error
177
- : "WooCommerce batch update failed.";
178
- }
179
- function batchErrorStatus(error) {
180
- const record = asRecord(error);
181
- const data = asRecord(record?.data);
182
- return typeof data?.status === "number" ? data.status : undefined;
183
- }
184
- function batchItemError(error) {
185
- return {
186
- code: "WOO_API_FAILED",
187
- message: batchErrorMessage(error),
188
- retriable: isRetriableStatus(batchErrorStatus(error), { retryableClientErrors: true }),
27
+ const untracked = options.untrackedStockQuantity ?? 99;
28
+ const caches = pushCaches();
29
+ const withClient = async (store, call) => {
30
+ const client = wooClient(store, transport);
31
+ return client.ok ? call(client.value) : client;
189
32
  };
190
- }
191
- function catalogPushError(code, message) {
192
- return Err({ code, message, retriable: false });
193
- }
194
- function remoteKey(field) {
195
- if (typeof field.remoteKey !== "string" || field.remoteKey.trim() === "") {
196
- return catalogPushError("WOO_REMOTE_KEY_REQUIRED", `WooCommerce remoteKey is required for catalog field "${field.fieldPath}".`);
197
- }
198
- return Ok(field.remoteKey.trim());
199
- }
200
- function porulleMetaKey(key) {
201
- const normalized = key.trim();
202
- return normalized.startsWith(PORULLE_META_PREFIX) ? normalized : `${PORULLE_META_PREFIX}${normalized}`;
203
- }
204
- function tagValues(value) {
205
- const values = Array.isArray(value) ? value : [value];
206
- return values.flatMap((entry) => {
207
- if (typeof entry === "string" && entry.trim() !== "")
208
- return [entry.trim()];
209
- if (typeof entry === "number" && Number.isFinite(entry))
210
- return [String(entry)];
211
- const object = asRecord(entry);
212
- return typeof object?.name === "string" && object.name.trim() !== "" ? [object.name.trim()] : [];
213
- });
214
- }
215
- function filterableTerms(value) {
216
- const values = Array.isArray(value) ? value : [value];
217
- return [...new Set(values.flatMap((entry) => {
218
- if (typeof entry === "string" && entry.trim() !== "")
219
- return [entry.trim()];
220
- if (typeof entry === "number" && Number.isFinite(entry))
221
- return [String(entry)];
222
- return [];
223
- }))];
224
- }
225
- function addNativeField(body, locales, field, key) {
226
- const currentLocale = locales.get(key);
227
- if (!Object.prototype.hasOwnProperty.call(body, key) || (field.locale === "en" && currentLocale !== "en")) {
228
- body[key] = field.value;
229
- locales.set(key, field.locale);
230
- }
231
- }
232
- function addMetaField(metaData, locales, field, key) {
233
- const currentLocale = locales.get(key);
234
- const existingIndex = metaData.findIndex((entry) => entry.key === key);
235
- if (existingIndex === -1 || (field.locale === "en" && currentLocale !== "en")) {
236
- const entry = { key, value: field.value };
237
- if (existingIndex === -1)
238
- metaData.push(entry);
239
- else
240
- metaData[existingIndex] = entry;
241
- locales.set(key, field.locale);
242
- }
243
- }
244
- function appendCatalogFields(fields, nativeFields, body, filterableFields, metaData, tags) {
245
- const locales = new Map();
246
- const metaLocales = new Map();
247
- let hasTagField = false;
248
- for (const field of fields) {
249
- if (field.intent === "filterable") {
250
- const key = remoteKey(field);
251
- if (!key.ok)
252
- return key;
253
- filterableFields.push(field);
254
- continue;
255
- }
256
- if (field.intent === "tag") {
257
- hasTagField = true;
258
- for (const tag of tagValues(field.value))
259
- tags.add(tag);
260
- continue;
261
- }
262
- const key = remoteKey(field);
263
- if (!key.ok)
264
- return key;
265
- if (nativeFields.has(key.value)) {
266
- addNativeField(body, locales, field, key.value);
267
- }
268
- else {
269
- addMetaField(metaData, metaLocales, field, porulleMetaKey(key.value));
270
- }
271
- }
272
- return Ok({ hasTagField });
273
- }
274
- function wooImages(images) {
275
- return images.map((image, index) => ({
276
- ...(image.externalId?.trim() ? { id: batchId(image.externalId.trim()) } : { src: image.url }),
277
- ...(image.alt !== undefined ? { alt: image.alt } : {}),
278
- position: image.sortOrder ?? index,
279
- }));
280
- }
281
- function mergeWooImages(current, incoming) {
282
- const incomingById = new Map();
283
- for (const image of incoming) {
284
- if (typeof image.id === "number" || typeof image.id === "string")
285
- incomingById.set(String(image.id), image);
286
- }
287
- const currentIds = new Set(current.map((image) => String(image.id)));
288
- const merged = current.map((image, index) => {
289
- const replacement = incomingById.get(String(image.id));
290
- return replacement ?? {
291
- id: image.id,
292
- ...(image.alt !== undefined ? { alt: image.alt } : {}),
293
- position: image.position ?? index,
294
- };
295
- });
296
- const appendedIds = new Set();
297
- for (const image of incoming) {
298
- if (typeof image.id === "number" || typeof image.id === "string") {
299
- const id = String(image.id);
300
- if (currentIds.has(id) || appendedIds.has(id))
301
- continue;
302
- appendedIds.add(id);
303
- }
304
- merged.push(image);
305
- }
306
- return merged;
307
- }
308
- function batchId(externalId) {
309
- return /^\d+$/.test(externalId) ? Number(externalId) : externalId;
310
- }
311
- function buildCatalogPlan(item) {
312
- const productBody = {};
313
- const productFilterableFields = [];
314
- const productMetaData = [];
315
- const productTags = new Set();
316
- const productFields = appendCatalogFields(item.fields, wooProductNativeFields, productBody, productFilterableFields, productMetaData, productTags);
317
- if (!productFields.ok)
318
- return productFields;
319
- if (productMetaData.length > 0)
320
- productBody.meta_data = productMetaData;
321
- if (productFields.value.hasTagField)
322
- productBody.tags = [...productTags].map((name) => ({ name }));
323
- if (item.images !== undefined)
324
- productBody.images = wooImages(item.images);
325
- const variants = [];
326
- for (const variant of item.variants ?? []) {
327
- const variantBody = {};
328
- const filterableFields = [];
329
- const metaData = [];
330
- const tags = new Set();
331
- const variantFields = appendCatalogFields(variant.fields, wooVariationNativeFields, variantBody, filterableFields, metaData, tags);
332
- if (!variantFields.ok)
333
- return variantFields;
334
- if (filterableFields.length > 0) {
335
- return catalogPushError("WOO_VARIANT_FILTERABLE_UNSUPPORTED", `WooCommerce filterable fields must be assigned on product "${item.externalId}", not variation "${variant.externalId}".`);
336
- }
337
- if (variantFields.value.hasTagField) {
338
- return catalogPushError("WOO_VARIANT_TAG_UNSUPPORTED", `WooCommerce tags must be assigned on product "${item.externalId}", not variation "${variant.externalId}".`);
339
- }
340
- if (metaData.length > 0)
341
- variantBody.meta_data = metaData;
342
- variants.push({ variant, body: variantBody });
343
- }
344
- return Ok({ productBody, filterableFields: productFilterableFields, variants });
345
- }
346
- function queryUrl(storeDomain, path, key, secret, params) {
347
- const url = new URL(buildWooUrl(storeDomain, path, key, secret, 1));
348
- for (const [name, value] of Object.entries(params))
349
- url.searchParams.set(name, value);
350
- return url.toString();
351
- }
352
- function taxonomyParts(remoteName) {
353
- const withoutPrefix = remoteName.trim().toLowerCase().replace(/^pa[_-]/, "");
354
- const base = withoutPrefix.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
355
- return {
356
- base,
357
- taxonomy: `pa_${base}`,
358
- name: withoutPrefix.replace(/[-_]+/g, " ").trim(),
359
- };
360
- }
361
- async function ensureGlobalAttribute(fetchImpl, store, auth, remoteName) {
362
- const parts = taxonomyParts(remoteName);
363
- const existing = await request(fetchImpl, queryUrl(store.storeDomain, "/wp-json/wc/v3/products/attributes", auth.key, auth.secret, { search: parts.name }), undefined, catalogRequestOptions);
364
- if (!existing.ok)
365
- return Err(connectorError(existing.error));
366
- const found = existing.value.data.find((attribute) => {
367
- const slug = attribute.slug?.toLowerCase();
368
- return slug === parts.taxonomy || slug === parts.base || attribute.name.toLowerCase() === parts.name;
369
- });
370
- if (found)
371
- return Ok(found);
372
- const created = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products/attributes", auth.key, auth.secret, 1), {
373
- method: "POST",
374
- headers: { "content-type": "application/json" },
375
- body: JSON.stringify({ name: parts.name, slug: parts.base }),
376
- }, catalogRequestOptions);
377
- return created.ok ? Ok(created.value.data) : Err(connectorError(created.error));
378
- }
379
- async function ensureTerm(fetchImpl, store, auth, attributeId, termName) {
380
- const path = `/wp-json/wc/v3/products/attributes/${encodeURIComponent(String(attributeId))}/terms`;
381
- const existing = await request(fetchImpl, queryUrl(store.storeDomain, path, auth.key, auth.secret, { search: termName }), undefined, catalogRequestOptions);
382
- if (!existing.ok)
383
- return Err(connectorError(existing.error));
384
- const found = existing.value.data.find((term) => term.name.toLowerCase() === termName.toLowerCase());
385
- if (found)
386
- return Ok(found);
387
- const created = await request(fetchImpl, buildWooUrl(store.storeDomain, path, auth.key, auth.secret, 1), {
388
- method: "POST",
389
- headers: { "content-type": "application/json" },
390
- body: JSON.stringify({ name: termName }),
391
- }, catalogRequestOptions);
392
- return created.ok ? Ok(created.value.data) : Err(connectorError(created.error));
393
- }
394
- async function mergedFilterableAttributes(fetchImpl, store, auth, productId, fields, attributeCache, termCache) {
395
- const termsByRemoteName = new Map();
396
- for (const field of fields) {
397
- const key = remoteKey(field);
398
- if (!key.ok)
399
- return key;
400
- const terms = termsByRemoteName.get(key.value) ?? new Set();
401
- for (const term of filterableTerms(field.value))
402
- terms.add(term);
403
- termsByRemoteName.set(key.value, terms);
404
- }
405
- const assignments = [];
406
- for (const [remoteName, termNames] of termsByRemoteName) {
407
- const parts = taxonomyParts(remoteName);
408
- const attributeKey = `${store.storeDomain}|${parts.taxonomy}`;
409
- let attributePromise = attributeCache.get(attributeKey);
410
- if (!attributePromise) {
411
- attributePromise = ensureGlobalAttribute(fetchImpl, store, auth, remoteName);
412
- attributeCache.set(attributeKey, attributePromise);
413
- }
414
- const attribute = await attributePromise;
415
- if (!attribute.ok) {
416
- attributeCache.delete(attributeKey);
417
- return attribute;
418
- }
419
- const terms = [];
420
- for (const termName of termNames) {
421
- const termKey = `${store.storeDomain}|${String(attribute.value.id)}|${termName.toLowerCase()}`;
422
- let termPromise = termCache.get(termKey);
423
- if (!termPromise) {
424
- termPromise = ensureTerm(fetchImpl, store, auth, attribute.value.id, termName);
425
- termCache.set(termKey, termPromise);
426
- }
427
- const term = await termPromise;
428
- if (!term.ok) {
429
- termCache.delete(termKey);
430
- return term;
431
- }
432
- terms.push(term.value.name);
433
- }
434
- assignments.push({ attribute: attribute.value, terms });
435
- }
436
- const current = await request(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/products/${encodeURIComponent(productId)}`, auth.key, auth.secret, 1), undefined, catalogRequestOptions);
437
- if (!current.ok)
438
- return Err(connectorError(current.error));
439
- const merged = (current.value.data.attributes ?? []).map((attribute) => ({
440
- ...attribute,
441
- ...(attribute.options ? { options: [...attribute.options] } : {}),
442
- }));
443
- for (const assignment of assignments) {
444
- const existing = merged.find((attribute) => attribute.id !== undefined && String(attribute.id) === String(assignment.attribute.id));
445
- if (existing) {
446
- existing.visible = existing.visible ?? true;
447
- existing.variation = existing.variation ?? false;
448
- existing.options = [...new Set([...(existing.options ?? []), ...assignment.terms])];
449
- }
450
- else {
451
- merged.push({
452
- id: assignment.attribute.id,
453
- name: assignment.attribute.name,
454
- visible: true,
455
- variation: false,
456
- options: assignment.terms,
457
- });
458
- }
459
- }
460
- return Ok(merged);
461
- }
462
- async function updateProduct(fetchImpl, store, auth, item, plan, attributeCache, termCache) {
463
- const body = { ...plan.productBody };
464
- if (Array.isArray(body.images)) {
465
- const current = await request(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/products/${encodeURIComponent(item.externalId)}`, auth.key, auth.secret, 1), undefined, catalogRequestOptions);
466
- if (!current.ok)
467
- return Err(connectorError(current.error));
468
- body.images = mergeWooImages(current.value.data.images ?? [], body.images);
469
- }
470
- if (plan.filterableFields.length > 0) {
471
- const attributes = await mergedFilterableAttributes(fetchImpl, store, auth, item.externalId, plan.filterableFields, attributeCache, termCache);
472
- if (!attributes.ok)
473
- return attributes;
474
- body.attributes = attributes.value;
475
- }
476
- if (Object.keys(body).length === 0)
477
- return Ok(undefined);
478
- const result = await request(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/products/${encodeURIComponent(item.externalId)}`, auth.key, auth.secret, 1), {
479
- method: "PUT",
480
- headers: { "content-type": "application/json" },
481
- body: JSON.stringify(body),
482
- }, catalogRequestOptions);
483
- return result.ok ? Ok(undefined) : Err(connectorError(result.error));
484
- }
485
- async function updateVariant(fetchImpl, store, auth, productId, variant, body) {
486
- if (Object.keys(body).length === 0)
487
- return Ok(undefined);
488
- const result = await request(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/products/${encodeURIComponent(productId)}/variations/${encodeURIComponent(variant.externalId)}`, auth.key, auth.secret, 1), {
489
- method: "PUT",
490
- headers: { "content-type": "application/json" },
491
- body: JSON.stringify(body),
492
- }, catalogRequestOptions);
493
- return result.ok ? Ok(undefined) : Err(connectorError(result.error));
494
- }
495
- async function pushCatalogItem(fetchImpl, store, auth, item, plan, attributeCache, termCache) {
496
- const product = await updateProduct(fetchImpl, store, auth, item, plan, attributeCache, termCache);
497
- if (!product.ok)
498
- return product;
499
- for (const variant of plan.variants) {
500
- const updated = await updateVariant(fetchImpl, store, auth, item.externalId, variant.variant, variant.body);
501
- if (!updated.ok)
502
- return updated;
503
- }
504
- return Ok(undefined);
505
- }
506
- async function pushCatalogBatch(fetchImpl, store, auth, entries) {
507
- const update = entries.map(({ item, plan }) => ({ id: batchId(item.externalId), ...plan.productBody }));
508
- const result = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products/batch", auth.key, auth.secret, 1), {
509
- method: "POST",
510
- headers: { "content-type": "application/json" },
511
- body: JSON.stringify({ update }),
512
- }, { retryableClientErrors: true });
513
- if (!result.ok)
514
- return Err(connectorError(result.error));
515
- const responseById = new Map((result.value.data.update ?? []).map((entry) => [String(entry.id), entry]));
516
- return Ok(entries.map((entry) => {
517
- const responseEntry = responseById.get(String(batchId(entry.item.externalId)));
518
- if (!responseEntry) {
519
- return { index: entry.index, error: { code: "WOO_API_FAILED", message: "WooCommerce batch response omitted this product.", retriable: false } };
520
- }
521
- return responseEntry.error === undefined ? { index: entry.index } : { index: entry.index, error: batchItemError(responseEntry.error) };
522
- }));
523
- }
524
- function wooStatus(status) {
525
- if (status === "completed")
526
- return { status: "fulfilled" };
527
- if (status === "processing" || status === "on-hold")
528
- return { status: "confirmed" };
529
- if (status === "cancelled")
530
- return { status: "cancelled" };
531
- if (status === "failed" || status === "refunded")
532
- return { status: "failed" };
533
- return { status: "pending" };
534
- }
535
- function credentials(store) {
536
- const key = store.credentials.consumerKey;
537
- const secret = store.credentials.consumerSecret;
538
- return typeof key === "string" && typeof secret === "string" && key && secret ? { key, secret } : undefined;
539
- }
540
- function validBase64Hmac(secret, body, signature) {
541
- if (!signature)
542
- return false;
543
- const expected = createHmac("sha256", secret).update(body).digest();
544
- const actual = Buffer.from(signature, "base64");
545
- return actual.length === expected.length && timingSafeEqual(actual, expected);
546
- }
547
- function oauthError(code, message) {
548
- return Err({ code, message, retriable: false });
549
- }
550
- function storeUrl(domain) {
551
- try {
552
- const url = new URL(/^https?:\/\//i.test(domain) ? domain : `https://${domain}`);
553
- return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
554
- }
555
- catch {
556
- return undefined;
557
- }
558
- }
559
- export function wooConnector(options = {}) {
560
- const fetchImpl = options.fetchImpl ?? fetch;
561
- const currencyCache = new Map();
562
- const attributeCache = new Map();
563
- const termCache = new Map();
564
33
  return defineChannelConnector({
565
34
  providerId: "woocommerce",
566
35
  capabilities: { importCatalog: true, importInventory: true, pushOrder: true, pushCatalog: true, receiveWebhooks: true },
36
+ webhookTopics: WOO_WEBHOOK_TOPICS,
37
+ normalizeStoreDomain: (input) => normalizeStoreDomain(input, { allowPrivateHosts: transport.allowPrivateHosts }),
567
38
  buildAuthUrl(params) {
568
- const store = storeUrl(params.storeDomain);
39
+ const store = normalizeStoreDomain(params.storeDomain, { allowPrivateHosts: transport.allowPrivateHosts });
569
40
  if (!store)
570
- return oauthError("WOO_INVALID_STORE_DOMAIN", "WooCommerce storeDomain must be an HTTP(S) URL.");
41
+ return refused("WOO_INVALID_STORE_DOMAIN", "A WooCommerce store is named by its https address.");
571
42
  let callback;
572
43
  try {
573
44
  callback = new URL(params.callbackUri);
574
45
  }
575
46
  catch {
576
- return oauthError("WOO_INVALID_CALLBACK_URL", "WooCommerce callbackUri must be an HTTPS URL.");
47
+ return refused("WOO_INVALID_CALLBACK_URL", "WooCommerce needs an https callback address.");
577
48
  }
578
49
  if (callback.protocol !== "https:")
579
- return oauthError("WOO_INVALID_CALLBACK_URL", "WooCommerce callbackUri must be an HTTPS URL.");
50
+ return refused("WOO_INVALID_CALLBACK_URL", "WooCommerce needs an https callback address.");
580
51
  callback.searchParams.set("state", params.state);
581
52
  const returnUrl = new URL(params.callbackUri);
582
53
  returnUrl.searchParams.set("state", params.state);
583
54
  returnUrl.searchParams.set("return", "1");
584
- const url = new URL("/wc-auth/v1/authorize", store.origin);
585
- url.searchParams.set("app_name", "Porulle");
55
+ const url = new URL(`${store}/wc-auth/v1/authorize`);
56
+ url.searchParams.set("app_name", options.appName ?? "Runvae");
586
57
  url.searchParams.set("scope", "read_write");
587
- url.searchParams.set("user_id", "porulle");
58
+ // Echoed back in the posted keys: the keys are bound to the connection this state started.
59
+ url.searchParams.set("user_id", params.state);
588
60
  url.searchParams.set("return_url", returnUrl.toString());
589
61
  url.searchParams.set("callback_url", callback.toString());
590
62
  return Ok(url.toString());
591
63
  },
64
+ /**
65
+ * The keys WooCommerce posts. They carry no store address and no signature, so they are accepted
66
+ * only for the connection they were issued for (`user_id` is our state), only read-write, only
67
+ * in WooCommerce's key format. Any refusal answers non-200, and WooCommerce deletes the key.
68
+ */
592
69
  async completeAuth(request, ctx) {
593
70
  if (request.method !== "POST")
594
- return oauthError("WOO_AUTH_METHOD_REQUIRED", "WooCommerce auth credentials must be posted.");
595
- const store = storeUrl(ctx.storeDomain);
596
- if (!store)
597
- return oauthError("WOO_INVALID_STORE_DOMAIN", "WooCommerce storeDomain must be an HTTP(S) URL.");
71
+ return refused("WOO_AUTH_METHOD_REQUIRED", "WooCommerce posts the keys.");
72
+ let raw;
598
73
  try {
599
- const body = await request.json();
600
- const consumerKey = body.consumer_key;
601
- const consumerSecret = body.consumer_secret;
602
- if (typeof consumerKey !== "string" || !consumerKey || typeof consumerSecret !== "string" || !consumerSecret) {
603
- return oauthError("WOO_AUTH_CREDENTIALS_INVALID", "WooCommerce auth response must include consumer_key and consumer_secret.");
604
- }
605
- return Ok({ credentials: { consumerKey, consumerSecret }, storeDomain: ctx.storeDomain });
74
+ raw = await request.json();
606
75
  }
607
76
  catch {
608
- return oauthError("WOO_AUTH_RESPONSE_INVALID", "WooCommerce auth response must be valid JSON.");
609
- }
77
+ return refused("WOO_AUTH_RESPONSE_INVALID", "WooCommerce's callback body was not JSON.");
78
+ }
79
+ const body = authCallbackSchema.safeParse(raw);
80
+ if (!body.success)
81
+ return refused("WOO_AUTH_RESPONSE_INVALID", "WooCommerce's callback did not carry keys.");
82
+ if (body.data.user_id !== ctx.state)
83
+ return refused("WOO_AUTH_STATE_MISMATCH", "The keys were issued for another connection.");
84
+ if (body.data.key_permissions !== "read_write")
85
+ return refused("WOO_AUTH_READ_ONLY", "The store granted read-only access; we need read and write to send orders.");
86
+ const credentials = wooCredentialsSchema.safeParse({ consumerKey: body.data.consumer_key, consumerSecret: body.data.consumer_secret });
87
+ if (!credentials.success)
88
+ return refused("WOO_AUTH_CREDENTIALS_INVALID", "The keys WooCommerce sent are not in its key format.");
89
+ return Ok({ credentials: { ...credentials.data }, storeDomain: ctx.storeDomain });
90
+ },
91
+ /**
92
+ * Learns, once, how to call the store (where its REST API answers, how it accepts our keys, how it
93
+ * prices) and hands it to the plugin to persist. Forced after a rejected key: a host that began
94
+ * stripping the Authorization header is met in query mode; a key both modes refuse is gone.
95
+ */
96
+ async liveCredentials(store, refresh) {
97
+ const credentials = wooCredentialsSchema.safeParse(store.credentials);
98
+ if (!credentials.success)
99
+ return refused("WOO_CREDENTIALS_REQUIRED", "The store holds no valid WooCommerce keys; it must be reconnected.");
100
+ const known = credentials.data;
101
+ if (refresh?.force !== true && known.authMode && known.restRoute && known.currency && known.priceDecimals !== undefined)
102
+ return Ok(null);
103
+ const discovered = await discoverStore(transport, store.storeDomain, known);
104
+ if (!discovered.ok)
105
+ return discovered;
106
+ return Ok({ ...store.credentials, ...discovered.value });
107
+ },
108
+ async fetchStoreProfile(store) {
109
+ return withClient(store, storeProfile);
610
110
  },
611
111
  async importCatalog(store, cursor) {
612
- const auth = credentials(store);
613
- if (!auth)
614
- return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
615
- const [pagePart, ...afterParts] = cursor?.split("|") ?? [];
616
- const isPage = pagePart === undefined || /^\d+$/.test(pagePart);
617
- const parsedPage = isPage && pagePart ? Number.parseInt(pagePart, 10) : 1;
618
- const page = Number.isFinite(parsedPage) && parsedPage > 0 ? parsedPage : 1;
619
- const modifiedAfter = afterParts.length > 0 ? afterParts.join("|") : (!isPage ? cursor : undefined);
620
- const currencyKey = store.storeDomain.replace(/\/$/, "");
621
- let currencyPromise = currencyCache.get(currencyKey);
622
- if (!currencyPromise) {
623
- currencyPromise = fetchWooCurrency(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/settings/general", auth.key, auth.secret, 1));
624
- currencyCache.set(currencyKey, currencyPromise);
625
- }
626
- const currency = await currencyPromise;
627
- const result = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products", auth.key, auth.secret, page, modifiedAfter));
628
- if (!result.ok)
629
- return result;
630
- const totalPages = Number.parseInt(result.value.response.headers.get("x-wp-totalpages") ?? "1", 10);
631
- const nextCursor = page < totalPages ? (modifiedAfter ? `${page + 1}|${modifiedAfter}` : String(page + 1)) : null;
632
- const items = [];
633
- for (const product of result.value.data) {
634
- const references = product.variations ?? [];
635
- const details = references.length > 0
636
- ? await fetchProductVariations(fetchImpl, store.storeDomain, auth, String(product.id), modifiedAfter)
637
- : Ok([]);
638
- if (!details.ok)
639
- return details;
640
- const variants = mergeProductVariations(references, details.value).map((variant) => {
641
- const optionValues = Object.fromEntries((variant.attributes ?? []).flatMap((attribute) => (attribute.option != null && attribute.option !== "" ? [[attribute.name, attribute.option]] : [])));
642
- const prices = pricesForVariation(variant, currency);
643
- return {
644
- externalId: String(variant.id),
645
- ...(variant.sku ? { sku: variant.sku } : {}),
646
- ...(Object.keys(optionValues).length > 0 ? { optionValues } : {}),
647
- ...(prices ? { prices } : {}),
648
- };
649
- });
650
- const options = product.attributes?.filter((attribute) => attribute.variation === true).map((attribute, index) => ({
651
- name: attribute.name,
652
- displayName: attribute.name,
653
- ...(attribute.position != null ? { sortOrder: attribute.position } : { sortOrder: index }),
654
- values: (attribute.options ?? []).map((value, valueIndex) => ({ value, displayValue: value, sortOrder: valueIndex })),
655
- }));
656
- const status = catalogStatus(product.status);
657
- items.push({
658
- externalId: String(product.id),
659
- slug: product.slug ?? String(product.id),
660
- title: product.name,
661
- attributes: [{ locale: "en", title: product.name, ...(product.description != null ? { description: product.description } : {}) }],
662
- variants,
663
- ...(product.images ? {
664
- images: product.images.map((image, index) => ({
665
- externalId: String(image.id),
666
- url: image.src,
667
- ...(image.alt != null ? { alt: image.alt } : {}),
668
- role: index === 0 ? "primary" : "gallery",
669
- ...(image.position != null ? { sortOrder: image.position } : {}),
670
- })),
671
- } : {}),
672
- ...(options ? { options } : {}),
673
- ...(product.tags ? { tags: product.tags.flatMap((tag) => tag.slug ? [tag.slug] : []) } : {}),
674
- ...(product.categories ? { categories: product.categories.flatMap((category) => category.slug ? [category.slug] : []) } : {}),
675
- ...(status ? { status } : {}),
676
- });
677
- }
678
- return Ok({ items, nextCursor });
112
+ return withClient(store, (client) => importPage(client, cursor));
679
113
  },
680
- async fetchInventory(store, ids) {
681
- const auth = credentials(store);
682
- if (!auth)
683
- return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
684
- const page = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products", auth.key, auth.secret, 1));
685
- if (!page.ok)
686
- return page;
687
- const requested = ids ? new Set(ids) : undefined;
688
- return Ok(page.value.data.filter((product) => !requested || requested.has(String(product.id))).map((product) => ({ externalId: String(product.id), available: product.stock_quantity ?? 0 })));
114
+ async fetchCatalogItems(store, externalIds) {
115
+ return withClient(store, (client) => catalogItems(client, externalIds));
689
116
  },
690
- async pushOrder(store, slice) {
691
- const auth = credentials(store);
692
- if (!auth)
693
- return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
694
- const url = buildWooUrl(store.storeDomain, "/wp-json/wc/v3/orders", auth.key, auth.secret, 1);
695
- const [firstName, ...lastParts] = slice.customer.name.trim().split(/\s+/);
696
- const source = slice.customer.shippingAddress;
697
- // WooCommerce's order address spelling (REST v3 `shipping`/`billing`).
698
- const address = {
699
- first_name: source.firstName,
700
- last_name: source.lastName,
701
- address_1: source.line1,
702
- ...(source.line2 ? { address_2: source.line2 } : {}),
703
- city: source.city,
704
- ...(source.region ? { state: source.region } : {}),
705
- ...(source.postalCode ? { postcode: source.postalCode } : {}),
706
- country: source.countryCode,
707
- ...(source.phone ? { phone: source.phone } : {}),
708
- };
709
- const billing = { ...address, first_name: firstName ?? source.firstName, last_name: lastParts.join(" ") || source.lastName, email: slice.customer.email };
710
- const result = await request(fetchImpl, url, {
711
- method: "POST",
712
- headers: { "content-type": "application/json", "idempotency-key": `porulle:${slice.orderId}` },
713
- body: JSON.stringify({ set_paid: true, line_items: slice.lines.map((line) => ({ variation_id: line.externalVariantId, quantity: line.quantity, total: line.totalPrice / 100 })), billing, shipping: address }),
117
+ async fetchInventory(store, ids) {
118
+ return withClient(store, async (client) => {
119
+ if (ids !== undefined)
120
+ return inventoryFor(client, ids, untracked);
121
+ const levels = [];
122
+ let cursor = null;
123
+ do {
124
+ const page = await inventoryPage(client, cursor, untracked);
125
+ if (!page.ok)
126
+ return page;
127
+ levels.push(...page.value.levels);
128
+ cursor = page.value.nextCursor;
129
+ } while (cursor !== null);
130
+ return Ok(levels);
714
131
  });
715
- if (!result.ok)
716
- return result;
717
- const id = String(result.value.data.id);
718
- return Ok({ remoteOrderId: id, remoteUrl: `${store.storeDomain.replace(/\/$/, "")}/wp-admin/post.php?post=${id}&action=edit` });
719
132
  },
720
- async pushCatalog(store, items, opts) {
721
- if (store.provider !== "woocommerce") {
722
- return Err({ code: "WOO_INVALID_STORE_PROVIDER", message: "WooCommerce catalog pushes require a WooCommerce store.", retriable: false });
723
- }
724
- const auth = credentials(store);
725
- if (!auth)
726
- return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
727
- const outcomes = items.map((item) => ({ externalId: item.externalId, ok: true }));
728
- const planned = [];
729
- for (const [index, item] of items.entries()) {
730
- const plan = buildCatalogPlan(item);
731
- if (!plan.ok) {
732
- outcomes[index] = { externalId: item.externalId, ok: false, error: plan.error };
733
- }
734
- else {
735
- planned.push({ index, item, plan: plan.value });
736
- }
737
- }
738
- if (opts?.dryRun)
739
- return Ok({ outcomes });
740
- const batchable = planned.filter(({ plan }) => plan.filterableFields.length === 0 && plan.variants.length === 0 && !Object.prototype.hasOwnProperty.call(plan.productBody, "images") && Object.keys(plan.productBody).length > 0);
741
- const batched = new Set();
742
- if (batchable.length > 1) {
743
- for (let offset = 0; offset < batchable.length; offset += WOO_BATCH_LIMIT) {
744
- const chunk = batchable.slice(offset, offset + WOO_BATCH_LIMIT);
745
- const batchResult = await pushCatalogBatch(fetchImpl, store, auth, chunk);
746
- for (const entry of chunk) {
747
- batched.add(entry.index);
748
- }
749
- if (!batchResult.ok) {
750
- for (const entry of chunk)
751
- outcomes[entry.index] = { externalId: entry.item.externalId, ok: false, error: batchResult.error };
752
- }
753
- else {
754
- const entryByIndex = new Map(chunk.map((entry) => [entry.index, entry.item]));
755
- for (const entry of batchResult.value) {
756
- if (entry.error) {
757
- const item = entryByIndex.get(entry.index);
758
- if (item)
759
- outcomes[entry.index] = { externalId: item.externalId, ok: false, error: entry.error };
760
- }
761
- }
762
- }
763
- }
764
- }
765
- for (const entry of planned) {
766
- if (batched.has(entry.index))
767
- continue;
768
- const pushed = await pushCatalogItem(fetchImpl, store, auth, entry.item, entry.plan, attributeCache, termCache);
769
- if (!pushed.ok)
770
- outcomes[entry.index] = { externalId: entry.item.externalId, ok: false, error: pushed.error };
771
- }
772
- return Ok({ outcomes });
133
+ async fetchInventoryPage(store, cursor) {
134
+ return withClient(store, (client) => inventoryPage(client, cursor, untracked));
135
+ },
136
+ async pushOrder(store, slice) {
137
+ return withClient(store, (client) => pushOrder(client, slice, { paymentMethodTitle: options.paymentMethodTitle ?? "Paid on Runvae", untrackedStockQuantity: untracked }));
773
138
  },
774
139
  async fetchOrderStatus(store, remoteId) {
775
- const auth = credentials(store);
776
- if (!auth)
777
- return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
778
- const result = await request(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/orders/${encodeURIComponent(remoteId)}`, auth.key, auth.secret, 1));
779
- return result.ok ? Ok(wooStatus(result.value.data.status)) : result;
140
+ return withClient(store, (client) => orderStatus(client, remoteId));
141
+ },
142
+ async cancelOrder(store, remoteId, input) {
143
+ return withClient(store, (client) => cancelOrder(client, remoteId, input));
144
+ },
145
+ async pushCatalog(store, items, opts) {
146
+ return withClient(store, (client) => pushCatalog(client, store, items, opts, caches));
780
147
  },
781
148
  async verifyWebhook(store, request) {
782
- const body = await request.text();
783
- if (!validBase64Hmac(store.webhookSecret ?? "", body, request.headers.get("x-wc-webhook-signature"))) {
784
- return Err({ code: "INVALID_WEBHOOK_SIGNATURE", message: "Invalid WooCommerce webhook signature." });
785
- }
786
- try {
787
- const data = JSON.parse(body);
788
- const id = request.headers.get("x-wc-webhook-id");
789
- const type = request.headers.get("x-wc-webhook-topic");
790
- if (!id || !type)
791
- return Err({ code: "INVALID_WEBHOOK", message: "WooCommerce webhook headers are incomplete." });
792
- return Ok({ id, type, data });
793
- }
794
- catch {
795
- return Err({ code: "INVALID_WEBHOOK", message: "WooCommerce webhook body must be valid JSON." });
796
- }
149
+ return verifyDelivery(store, request);
150
+ },
151
+ async decodeWebhook(store, event) {
152
+ return withClient(store, (client) => decodeDelivery(client, event, untracked));
797
153
  },
798
154
  async registerWebhooks(store, topics, callbackUrl) {
799
- const auth = credentials(store);
800
- if (!auth)
801
- return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
802
- for (const topic of topics) {
803
- const result = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/webhooks", auth.key, auth.secret, 1), {
804
- method: "POST",
805
- headers: { "content-type": "application/json" },
806
- body: JSON.stringify({ name: `Porulle ${topic}`, topic, delivery_url: callbackUrl, secret: store.webhookSecret }),
807
- });
808
- if (!result.ok)
809
- return result;
810
- }
811
- return Ok({ registered: topics.length });
155
+ return withClient(store, (client) => registerWebhooks(client, store, topics, callbackUrl));
156
+ },
157
+ async unregisterWebhooks(store, callbackUrl) {
158
+ return withClient(store, (client) => unregisterWebhooks(client, callbackUrl));
159
+ },
160
+ async orderEvents(store, remoteOrderId) {
161
+ return withClient(store, (client) => orderEvents(client, remoteOrderId));
162
+ },
163
+ async webhookHealth(store, callbackUrl) {
164
+ return withClient(store, (client) => webhookHealth(client, store, WOO_WEBHOOK_TOPICS, callbackUrl));
165
+ },
166
+ async refundExecute() {
167
+ return refused("NOT_IMPLEMENTED", "Refunds are issued by the platform, not executed in the WooCommerce store.");
812
168
  },
813
- async refundExecute() { return Err({ code: "NOT_IMPLEMENTED", message: "WooCommerce refund execution is not implemented in this slice." }); },
814
169
  });
815
170
  }