@porulle/adapter-woocommerce 0.9.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/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@porulle/adapter-woocommerce",
3
+ "version": "0.9.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./dist/index.js",
9
+ "types": "./src/index.ts"
10
+ }
11
+ },
12
+ "dependencies": {
13
+ "@porulle/core": "0.9.0"
14
+ },
15
+ "devDependencies": {
16
+ "@types/node": "^24.5.2",
17
+ "eslint": "^9.39.1",
18
+ "typescript": "5.9.2",
19
+ "vitest": "^3.2.4",
20
+ "@porulle/eslint-config": "0.1.0",
21
+ "@porulle/typescript-config": "0.1.0"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "src",
28
+ "dist",
29
+ "README.md"
30
+ ],
31
+ "scripts": {
32
+ "build": "rm -rf dist tsconfig.build.tsbuildinfo && tsc -p tsconfig.build.json && cp -R dist/src/. dist/ && rm -rf dist/src",
33
+ "check-types": "tsc --noEmit",
34
+ "lint": "eslint . --max-warnings 1000",
35
+ "test": "vitest run"
36
+ }
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,203 @@
1
+ import { defineChannelConnector, Err, Ok } from "@porulle/core";
2
+ import { createHmac, timingSafeEqual } from "node:crypto";
3
+ import type { ChannelCatalogPage, ChannelConnector, ChannelConnectorError, ChannelInventoryLevel, ChannelStore, ChannelOrderSlice, ChannelOrderStatus, Result } from "@porulle/core";
4
+
5
+ export interface WooConnectorOptions { fetchImpl?: typeof fetch }
6
+
7
+ type WooProduct = {
8
+ id: number | string;
9
+ name: string;
10
+ slug?: string;
11
+ description?: string;
12
+ variations?: Array<{ id: number | string; sku?: string | null; price?: string | null }>;
13
+ stock_quantity?: number | null;
14
+ };
15
+
16
+ function buildWooUrl(base: string, path: string, key: string, secret: string, page: number, cursor?: string): string {
17
+ const url = new URL(path, base.replace(/\/$/, "/"));
18
+ url.searchParams.set("consumer_key", key);
19
+ url.searchParams.set("consumer_secret", secret);
20
+ url.searchParams.set("per_page", "100");
21
+ url.searchParams.set("page", String(page));
22
+ if (cursor) url.searchParams.set("modified_after", cursor);
23
+ return url.toString();
24
+ }
25
+
26
+ function parseMoney(value: string | null | undefined): number {
27
+ if (!value) return 0;
28
+ const parsed = Number.parseFloat(value);
29
+ return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0;
30
+ }
31
+
32
+ async function request<T>(fetchImpl: typeof fetch, url: string, init?: RequestInit): Promise<Result<{ data: T; response: Response }>> {
33
+ try {
34
+ const response = await fetchImpl(url, { ...init, headers: { accept: "application/json", ...(init?.headers ?? {}) } });
35
+ if (!response.ok) return Err({ code: "WOO_API_FAILED", message: `WooCommerce request failed (${response.status}) for ${url}.`, retriable: response.status >= 500 });
36
+ return Ok({ data: await response.json() as T, response });
37
+ } catch (error) {
38
+ return Err({ code: "WOO_API_FAILED", message: error instanceof Error ? error.message : "WooCommerce request failed.", retriable: true });
39
+ }
40
+ }
41
+
42
+ function wooStatus(status: string | undefined): ChannelOrderStatus {
43
+ if (status === "completed") return { status: "fulfilled" };
44
+ if (status === "processing" || status === "on-hold") return { status: "confirmed" };
45
+ if (status === "cancelled") return { status: "cancelled" };
46
+ if (status === "failed" || status === "refunded") return { status: "failed" };
47
+ return { status: "pending" };
48
+ }
49
+
50
+ function credentials(store: ChannelStore): { key: string; secret: string } | undefined {
51
+ const key = store.credentials.consumerKey;
52
+ const secret = store.credentials.consumerSecret;
53
+ return typeof key === "string" && typeof secret === "string" && key && secret ? { key, secret } : undefined;
54
+ }
55
+
56
+ function validBase64Hmac(secret: string, body: string, signature: string | null): boolean {
57
+ if (!signature) return false;
58
+ const expected = createHmac("sha256", secret).update(body).digest();
59
+ const actual = Buffer.from(signature, "base64");
60
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
61
+ }
62
+
63
+ function oauthError(code: string, message: string): Result<never, ChannelConnectorError> {
64
+ return Err({ code, message, retriable: false });
65
+ }
66
+
67
+ function storeUrl(domain: string): URL | undefined {
68
+ try {
69
+ const url = new URL(/^https?:\/\//i.test(domain) ? domain : `https://${domain}`);
70
+ return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ export function wooConnector(options: WooConnectorOptions = {}): ChannelConnector {
77
+ const fetchImpl = options.fetchImpl ?? fetch;
78
+ return defineChannelConnector({
79
+ providerId: "woocommerce",
80
+ capabilities: { importCatalog: true, importInventory: true, pushOrder: true, receiveWebhooks: true },
81
+ buildAuthUrl(params) {
82
+ const store = storeUrl(params.storeDomain);
83
+ if (!store) return oauthError("WOO_INVALID_STORE_DOMAIN", "WooCommerce storeDomain must be an HTTP(S) URL.");
84
+ let callback: URL;
85
+ try {
86
+ callback = new URL(params.callbackUri);
87
+ } catch {
88
+ return oauthError("WOO_INVALID_CALLBACK_URL", "WooCommerce callbackUri must be an HTTPS URL.");
89
+ }
90
+ if (callback.protocol !== "https:") return oauthError("WOO_INVALID_CALLBACK_URL", "WooCommerce callbackUri must be an HTTPS URL.");
91
+ callback.searchParams.set("state", params.state);
92
+ const returnUrl = new URL(params.callbackUri);
93
+ returnUrl.searchParams.set("state", params.state);
94
+ returnUrl.searchParams.set("return", "1");
95
+ const url = new URL("/wc-auth/v1/authorize", store.origin);
96
+ url.searchParams.set("app_name", "Porulle");
97
+ url.searchParams.set("scope", "read_write");
98
+ url.searchParams.set("user_id", "porulle");
99
+ url.searchParams.set("return_url", returnUrl.toString());
100
+ url.searchParams.set("callback_url", callback.toString());
101
+ return Ok(url.toString());
102
+ },
103
+ async completeAuth(request, ctx) {
104
+ if (request.method !== "POST") return oauthError("WOO_AUTH_METHOD_REQUIRED", "WooCommerce auth credentials must be posted.");
105
+ const store = storeUrl(ctx.storeDomain);
106
+ if (!store) return oauthError("WOO_INVALID_STORE_DOMAIN", "WooCommerce storeDomain must be an HTTP(S) URL.");
107
+ try {
108
+ const body = await request.json() as Record<string, unknown>;
109
+ const consumerKey = body.consumer_key;
110
+ const consumerSecret = body.consumer_secret;
111
+ if (typeof consumerKey !== "string" || !consumerKey || typeof consumerSecret !== "string" || !consumerSecret) {
112
+ return oauthError("WOO_AUTH_CREDENTIALS_INVALID", "WooCommerce auth response must include consumer_key and consumer_secret.");
113
+ }
114
+ return Ok({ credentials: { consumerKey, consumerSecret }, storeDomain: ctx.storeDomain });
115
+ } catch {
116
+ return oauthError("WOO_AUTH_RESPONSE_INVALID", "WooCommerce auth response must be valid JSON.");
117
+ }
118
+ },
119
+ async importCatalog(store, cursor): Promise<Result<ChannelCatalogPage>> {
120
+ const auth = credentials(store);
121
+ if (!auth) return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
122
+ const [pagePart, ...afterParts] = cursor?.split("|") ?? [];
123
+ const isPage = pagePart === undefined || /^\d+$/.test(pagePart);
124
+ const parsedPage = isPage && pagePart ? Number.parseInt(pagePart, 10) : 1;
125
+ const page = Number.isFinite(parsedPage) && parsedPage > 0 ? parsedPage : 1;
126
+ const modifiedAfter = afterParts.length > 0 ? afterParts.join("|") : (!isPage ? cursor : undefined);
127
+ const result = await request<WooProduct[]>(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products", auth.key, auth.secret, page, modifiedAfter));
128
+ if (!result.ok) return result;
129
+ const totalPages = Number.parseInt(result.value.response.headers.get("x-wp-totalpages") ?? "1", 10);
130
+ const nextCursor = page < totalPages ? (modifiedAfter ? `${page + 1}|${modifiedAfter}` : String(page + 1)) : null;
131
+ return Ok({ items: result.value.data.map((product) => ({
132
+ externalId: String(product.id),
133
+ slug: product.slug ?? String(product.id),
134
+ title: product.name,
135
+ ...(product.description ? { description: product.description } : {}),
136
+ variants: (product.variations ?? []).map((variant) => ({
137
+ externalId: String(variant.id),
138
+ ...(variant.sku ? { sku: variant.sku } : {}),
139
+ metadata: { price: parseMoney(variant.price) },
140
+ })),
141
+ })), nextCursor });
142
+ },
143
+ async fetchInventory(store, ids): Promise<Result<ChannelInventoryLevel[]>> {
144
+ const auth = credentials(store);
145
+ if (!auth) return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
146
+ const page = await request<WooProduct[]>(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products", auth.key, auth.secret, 1));
147
+ if (!page.ok) return page;
148
+ const requested = ids ? new Set(ids) : undefined;
149
+ return Ok(page.value.data.filter((product) => !requested || requested.has(String(product.id))).map((product) => ({ externalId: String(product.id), available: product.stock_quantity ?? 0 })));
150
+ },
151
+ async pushOrder(store, slice: ChannelOrderSlice) {
152
+ const auth = credentials(store);
153
+ if (!auth) return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
154
+ const url = buildWooUrl(store.storeDomain, "/wp-json/wc/v3/orders", auth.key, auth.secret, 1);
155
+ const [firstName, ...lastParts] = slice.customer.name.trim().split(/\s+/);
156
+ const address = slice.customer.shippingAddress;
157
+ const billing = { first_name: firstName ?? "", last_name: lastParts.join(" "), email: slice.customer.email, ...address };
158
+ const result = await request<{ id: number | string }>(fetchImpl, url, {
159
+ method: "POST",
160
+ headers: { "content-type": "application/json", "idempotency-key": `porulle:${slice.orderId}` },
161
+ 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 }),
162
+ });
163
+ if (!result.ok) return result;
164
+ const id = String(result.value.data.id);
165
+ return Ok({ remoteOrderId: id, remoteUrl: `${store.storeDomain.replace(/\/$/, "")}/wp-admin/post.php?post=${id}&action=edit` });
166
+ },
167
+ async fetchOrderStatus(store, remoteId) {
168
+ const auth = credentials(store);
169
+ if (!auth) return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
170
+ const result = await request<{ status?: string }>(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/orders/${encodeURIComponent(remoteId)}`, auth.key, auth.secret, 1));
171
+ return result.ok ? Ok(wooStatus(result.value.data.status)) : result;
172
+ },
173
+ async verifyWebhook(store, request) {
174
+ const body = await request.text();
175
+ if (!validBase64Hmac(store.webhookSecret ?? "", body, request.headers.get("x-wc-webhook-signature"))) {
176
+ return Err({ code: "INVALID_WEBHOOK_SIGNATURE", message: "Invalid WooCommerce webhook signature." });
177
+ }
178
+ try {
179
+ const data = JSON.parse(body) as unknown;
180
+ const id = request.headers.get("x-wc-webhook-id");
181
+ const type = request.headers.get("x-wc-webhook-topic");
182
+ if (!id || !type) return Err({ code: "INVALID_WEBHOOK", message: "WooCommerce webhook headers are incomplete." });
183
+ return Ok({ id, type, data });
184
+ } catch {
185
+ return Err({ code: "INVALID_WEBHOOK", message: "WooCommerce webhook body must be valid JSON." });
186
+ }
187
+ },
188
+ async registerWebhooks(store: ChannelStore, topics: string[], callbackUrl: string) {
189
+ const auth = credentials(store);
190
+ if (!auth) return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
191
+ for (const topic of topics) {
192
+ const result = await request<{ id: number | string }>(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/webhooks", auth.key, auth.secret, 1), {
193
+ method: "POST",
194
+ headers: { "content-type": "application/json" },
195
+ body: JSON.stringify({ name: `Porulle ${topic}`, topic, delivery_url: callbackUrl, secret: store.webhookSecret }),
196
+ });
197
+ if (!result.ok) return result;
198
+ }
199
+ return Ok({ registered: topics.length });
200
+ },
201
+ async refundExecute() { return Err({ code: "NOT_IMPLEMENTED", message: "WooCommerce refund execution is not implemented in this slice." }); },
202
+ });
203
+ }