@aglyn/plugins-commerce 1.34.2 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/woo-connections-card.component.d.ts +52 -0
  3. package/src/lib/components/console/woo-connections-card.component.js +189 -0
  4. package/src/lib/components/console/woo-connections-card.component.js.map +1 -0
  5. package/src/lib/plugin.js +13 -1
  6. package/src/lib/plugin.js.map +1 -1
  7. package/src/lib/server/order-event-triggers.js +9 -0
  8. package/src/lib/server/order-event-triggers.js.map +1 -1
  9. package/src/lib/server/woo/woo-connections.d.ts +23 -0
  10. package/src/lib/server/woo/woo-connections.js +109 -0
  11. package/src/lib/server/woo/woo-connections.js.map +1 -0
  12. package/src/lib/server/woo/woo-context.d.ts +45 -0
  13. package/src/lib/server/woo/woo-context.js +36 -0
  14. package/src/lib/server/woo/woo-context.js.map +1 -0
  15. package/src/lib/server/woo/woo-ids.d.ts +45 -0
  16. package/src/lib/server/woo/woo-ids.js +141 -0
  17. package/src/lib/server/woo/woo-ids.js.map +1 -0
  18. package/src/lib/server/woo/woo-meta.d.ts +68 -0
  19. package/src/lib/server/woo/woo-meta.js +127 -0
  20. package/src/lib/server/woo/woo-meta.js.map +1 -0
  21. package/src/lib/server/woo/woo-orders.d.ts +136 -0
  22. package/src/lib/server/woo/woo-orders.js +378 -0
  23. package/src/lib/server/woo/woo-orders.js.map +1 -0
  24. package/src/lib/server/woo/woo-products.d.ts +19 -0
  25. package/src/lib/server/woo/woo-products.js +662 -0
  26. package/src/lib/server/woo/woo-products.js.map +1 -0
  27. package/src/lib/server/woo/woo-route.d.ts +49 -0
  28. package/src/lib/server/woo/woo-route.js +333 -0
  29. package/src/lib/server/woo/woo-route.js.map +1 -0
  30. package/src/lib/server/woo/woo-shapes.d.ts +421 -0
  31. package/src/lib/server/woo/woo-shapes.js +835 -0
  32. package/src/lib/server/woo/woo-shapes.js.map +1 -0
  33. package/src/lib/server/woo/woo-system.d.ts +35 -0
  34. package/src/lib/server/woo/woo-system.js +339 -0
  35. package/src/lib/server/woo/woo-system.js.map +1 -0
  36. package/src/lib/server/woo/woo-webhooks.d.ts +53 -0
  37. package/src/lib/server/woo/woo-webhooks.js +204 -0
  38. package/src/lib/server/woo/woo-webhooks.js.map +1 -0
  39. package/src/lib/server.js +15 -0
  40. package/src/lib/server.js.map +1 -1
@@ -0,0 +1,835 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /*==========================================
17
+ * THE WOOCOMMERCE DIALECT, PURE (see `woo-route.ts`).
18
+ *
19
+ * Translations both ways between the store's own records and the shapes the
20
+ * WooCommerce REST API v3 answers and accepts: products and their
21
+ * variations, orders, statuses, money, dates and errors. Nothing here reads
22
+ * or writes; the integer ids WooCommerce clients expect are looked up by the
23
+ * caller (`woo-ids.ts`) and handed in.
24
+ *
25
+ * Conventions the clients lean on, kept exactly:
26
+ * - money is a string with two decimals (`"19.99"`), never a number;
27
+ * - dates are `YYYY-MM-DDTHH:mm:ss` with no zone, in the store's time and in
28
+ * GMT (`_gmt`); every store here reports UTC, so the two agree;
29
+ * - ids are positive integers;
30
+ * - an error is `{ code, message, data: { status } }`.
31
+ *=========================================*/ import { _ as _extends } from "@swc/helpers/_/_extends";
32
+ // ── Money, dates, errors ────────────────────────────────────────────────────
33
+ /** Dollars as WooCommerce writes them: `"19.99"`, or `""` for none. */ export function wooMoney(value) {
34
+ return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(2) : '';
35
+ }
36
+ /** Integer cents as WooCommerce money. */ export const wooCents = (cents)=>wooMoney(typeof cents === 'number' && Number.isFinite(cents) ? cents / 100 : 0);
37
+ /**
38
+ * A WooCommerce price string as dollars: `null` for blank, `undefined` when
39
+ * it is not a price at all (the caller refuses it).
40
+ */ export function readWooMoney(value) {
41
+ if (value === null || value === undefined || value === '') return null;
42
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
43
+ if (!/^\d+(\.\d{1,4})?$/.test(text)) return undefined;
44
+ return Math.round(Number(text) * 100) / 100;
45
+ }
46
+ /** A moment as WooCommerce dates it: no zone, seconds precision, UTC. */ export function wooDate(ms) {
47
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return null;
48
+ return new Date(ms).toISOString().slice(0, 19);
49
+ }
50
+ /** A WooCommerce `after`/`before` filter as epoch ms; a zoneless date is UTC, as this store's dates are. */ export function readWooDate(value) {
51
+ if (!value) return null;
52
+ const text = /([zZ]|[+-]\d\d:?\d\d)$/.test(value) ? value : `${value}Z`;
53
+ const ms = Date.parse(text);
54
+ return Number.isFinite(ms) ? ms : null;
55
+ }
56
+ /** WooCommerce's error envelope. */ export function wooError(status, code, message, headers = {}) {
57
+ return Response.json({
58
+ code,
59
+ message,
60
+ data: {
61
+ status
62
+ }
63
+ }, {
64
+ status,
65
+ headers
66
+ });
67
+ }
68
+ export const wooNotFound = (message = 'No route was found matching the URL and request method.')=>wooError(404, 'rest_no_route', message);
69
+ export const wooInvalidId = (what)=>wooError(404, `woocommerce_rest_${what === 'variation' ? 'product_variation' : what === 'note' ? 'order_note' : what}_invalid_id`, 'Invalid ID.');
70
+ /** A product or order refusal from the store's own checks, in WooCommerce's words. */ export function wooRefusalFrom(response) {
71
+ var _ref;
72
+ var _response_body;
73
+ const error = (_response_body = response.body) == null ? void 0 : _response_body.error;
74
+ const fields = (error == null ? void 0 : error.fields) ? Object.entries(error.fields).map(([field, why])=>`${field}: ${why}`).join('; ') : '';
75
+ const message = [
76
+ (_ref = error == null ? void 0 : error.message) != null ? _ref : 'The request was refused.',
77
+ fields
78
+ ].filter(Boolean).join(' — ');
79
+ const status = response.status >= 400 ? response.status : 400;
80
+ const code = status === 404 ? 'woocommerce_rest_invalid_id' : status === 403 ? 'woocommerce_rest_cannot_create' : 'woocommerce_rest_invalid_param';
81
+ return wooError(status, code, message);
82
+ }
83
+ /** `page`, `per_page` (1–100, default 10) and `offset`, as WooCommerce reads them. */ export function readWooPage(search) {
84
+ var _search_get, _search_get1, _search_get2;
85
+ const perPageRaw = Number((_search_get = search.get('per_page')) != null ? _search_get : 10);
86
+ const perPage = Number.isInteger(perPageRaw) ? Math.min(100, Math.max(1, perPageRaw)) : 10;
87
+ const pageRaw = Number((_search_get1 = search.get('page')) != null ? _search_get1 : 1);
88
+ const page = Number.isInteger(pageRaw) && pageRaw > 0 ? pageRaw : 1;
89
+ const offsetRaw = Number((_search_get2 = search.get('offset')) != null ? _search_get2 : NaN);
90
+ const offset = Number.isInteger(offsetRaw) && offsetRaw >= 0 ? offsetRaw : (page - 1) * perPage;
91
+ return {
92
+ page,
93
+ perPage,
94
+ offset
95
+ };
96
+ }
97
+ /** One page of a list, with the headers WordPress sets on every collection. */ export function wooPaged(items, page, extra = {}) {
98
+ const total = items.length;
99
+ const totalPages = Math.max(1, Math.ceil(total / page.perPage));
100
+ return Response.json(items.slice(page.offset, page.offset + page.perPage), {
101
+ headers: _extends({
102
+ 'X-WP-Total': String(total),
103
+ 'X-WP-TotalPages': String(totalPages)
104
+ }, extra)
105
+ });
106
+ }
107
+ // ── Statuses ────────────────────────────────────────────────────────────────
108
+ /** An order's status as WooCommerce names it. */ export function wooOrderStatus(status) {
109
+ switch(status){
110
+ case 'paid':
111
+ case 'partially_fulfilled':
112
+ return 'processing';
113
+ case 'fulfilled':
114
+ case 'delivered':
115
+ return 'completed';
116
+ case 'cancelled':
117
+ return 'cancelled';
118
+ case 'refunded':
119
+ return 'refunded';
120
+ default:
121
+ return 'pending';
122
+ }
123
+ }
124
+ /**
125
+ * The store statuses a WooCommerce `status` filter means. `any` (or none) is
126
+ * every status; `on-hold`, `failed`, `checkout-draft` and `trash` match none,
127
+ * because no order here is ever in them.
128
+ */ export function storeStatusesForWooFilter(filter) {
129
+ const names = String(filter != null ? filter : '').split(',').map((name)=>name.trim().replace(/^wc-/, '')).filter(Boolean);
130
+ if (!names.length || names.includes('any')) return null;
131
+ const statuses = new Set();
132
+ for (const name of names){
133
+ if (name === 'processing') [
134
+ 'paid',
135
+ 'partially_fulfilled'
136
+ ].forEach((s)=>statuses.add(s));
137
+ else if (name === 'completed') [
138
+ 'fulfilled',
139
+ 'delivered'
140
+ ].forEach((s)=>statuses.add(s));
141
+ else if (name === 'pending' || name === 'cancelled' || name === 'refunded') statuses.add(name);
142
+ }
143
+ return statuses;
144
+ }
145
+ /** A product's status as WooCommerce names it. */ export const wooProductStatus = (status)=>status === 'active' ? 'publish' : status === 'archived' ? 'private' : 'draft';
146
+ /** A WooCommerce product status as the store's: only `publish` is on sale. */ export function storeProductStatus(status) {
147
+ if (status === undefined || status === null || status === '') return undefined;
148
+ if (status === 'publish') return 'active';
149
+ if (status === 'private' || status === 'trash') return 'archived';
150
+ return 'draft';
151
+ }
152
+ const isRecord = (value)=>Boolean(value) && typeof value === 'object' && !Array.isArray(value);
153
+ function variantsOf(data) {
154
+ return Array.isArray(data['variants']) ? data['variants'] : [];
155
+ }
156
+ function optionsOf(data) {
157
+ return Array.isArray(data['options']) ? data['options'].filter(isRecord).map((option)=>{
158
+ var _option_name;
159
+ return {
160
+ name: String((_option_name = option['name']) != null ? _option_name : ''),
161
+ values: Array.isArray(option['values']) ? option['values'].map(String) : []
162
+ };
163
+ }) : [];
164
+ }
165
+ /** A stable small integer for an image, from its address. */ export function wooImageId(src) {
166
+ let hash = 0;
167
+ for(let index = 0; index < src.length; index += 1)hash = hash * 31 + src.charCodeAt(index) | 0;
168
+ return Math.abs(hash) % 900000000 + 100000;
169
+ }
170
+ function wooImage(src, position, name) {
171
+ return {
172
+ id: wooImageId(src),
173
+ src,
174
+ name,
175
+ alt: name,
176
+ position,
177
+ date_created: null,
178
+ date_created_gmt: null
179
+ };
180
+ }
181
+ const kilograms = (grams)=>typeof grams === 'number' && Number.isFinite(grams) ? String(Math.round(grams) / 1000) : '';
182
+ function stockOf(variants) {
183
+ const tracked = variants.filter((variant)=>typeof variant.inventory === 'number');
184
+ if (!tracked.length) return {
185
+ manage_stock: false,
186
+ stock_quantity: null,
187
+ stock_status: 'instock'
188
+ };
189
+ const total = tracked.reduce((sum, variant)=>{
190
+ var _variant_inventory;
191
+ return sum + Number((_variant_inventory = variant.inventory) != null ? _variant_inventory : 0);
192
+ }, 0);
193
+ return {
194
+ manage_stock: true,
195
+ stock_quantity: total,
196
+ stock_status: total > 0 ? 'instock' : 'outofstock'
197
+ };
198
+ }
199
+ /** The prices of one variant in WooCommerce's three fields. */ function pricesOf(variant) {
200
+ const price = typeof (variant == null ? void 0 : variant.priceUsd) === 'number' ? variant.priceUsd : null;
201
+ const compare = typeof (variant == null ? void 0 : variant.compareAtPriceUsd) === 'number' ? variant.compareAtPriceUsd : null;
202
+ const onSale = price !== null && compare !== null && compare > price;
203
+ return {
204
+ price: wooMoney(price),
205
+ regular_price: wooMoney(onSale ? compare : price),
206
+ sale_price: onSale ? wooMoney(price) : '',
207
+ on_sale: onSale,
208
+ purchasable: price !== null
209
+ };
210
+ }
211
+ /** A product as `GET /wc/v3/products/{id}` answers it. */ export function wooProduct(data, ids, context) {
212
+ var _data_name, _data_createdAtMs, _ref, _data_updatedAtMs, _data_slug, _data_description, _ref1;
213
+ const variants = variantsOf(data);
214
+ const options = optionsOf(data);
215
+ const variable = options.length > 0;
216
+ const name = String((_data_name = data['name']) != null ? _data_name : '');
217
+ const media = Array.isArray(data['mediaUrls']) ? data['mediaUrls'].map(String) : [];
218
+ const first = variants[0];
219
+ const created = wooDate(Number((_data_createdAtMs = data['createdAtMs']) != null ? _data_createdAtMs : 0));
220
+ const modified = wooDate(Number((_ref = (_data_updatedAtMs = data['updatedAtMs']) != null ? _data_updatedAtMs : data['createdAtMs']) != null ? _ref : 0));
221
+ const priced = variants.filter((variant)=>typeof variant.priceUsd === 'number');
222
+ const lowest = priced.length ? priced.reduce((low, variant)=>Number(variant.priceUsd) < Number(low.priceUsd) ? variant : low) : undefined;
223
+ const categoryIds = Array.isArray(data['categoryIds']) ? data['categoryIds'].map(String) : [];
224
+ return _extends({
225
+ id: ids.product,
226
+ name,
227
+ slug: String((_data_slug = data['slug']) != null ? _data_slug : ''),
228
+ permalink: data['slug'] ? `${context.origin}/products/${String(data['slug'])}` : context.origin,
229
+ date_created: created,
230
+ date_created_gmt: created,
231
+ date_modified: modified,
232
+ date_modified_gmt: modified,
233
+ type: variable ? 'variable' : 'simple',
234
+ status: wooProductStatus(data['status']),
235
+ featured: false,
236
+ catalog_visibility: 'visible',
237
+ description: String((_data_description = data['description']) != null ? _data_description : ''),
238
+ short_description: '',
239
+ sku: variable ? '' : String((_ref1 = first == null ? void 0 : first.sku) != null ? _ref1 : '')
240
+ }, pricesOf(variable ? lowest : first), {
241
+ total_sales: 0,
242
+ virtual: data['type'] === 'service',
243
+ downloadable: data['type'] === 'digital',
244
+ downloads: [],
245
+ tax_status: 'taxable',
246
+ tax_class: ''
247
+ }, stockOf(variants), {
248
+ backorders: 'no',
249
+ backorders_allowed: false,
250
+ backordered: false,
251
+ sold_individually: false,
252
+ weight: variable ? '' : kilograms(first == null ? void 0 : first.weightGrams),
253
+ dimensions: {
254
+ length: '',
255
+ width: '',
256
+ height: ''
257
+ },
258
+ shipping_required: data['type'] !== 'service' && data['type'] !== 'digital',
259
+ shipping_taxable: true,
260
+ shipping_class: '',
261
+ shipping_class_id: 0,
262
+ reviews_allowed: false,
263
+ average_rating: '0.00',
264
+ rating_count: 0,
265
+ related_ids: [],
266
+ upsell_ids: [],
267
+ cross_sell_ids: [],
268
+ parent_id: 0,
269
+ purchase_note: '',
270
+ categories: categoryIds.map((id)=>context.categories.get(id)).filter((category)=>Boolean(category)),
271
+ tags: (Array.isArray(data['tags']) ? data['tags'].map(String) : []).map((tag)=>({
272
+ id: wooImageId(`tag:${tag}`),
273
+ name: tag,
274
+ slug: tag.toLowerCase().replace(/[^a-z0-9]+/g, '-')
275
+ })),
276
+ images: media.map((src, position)=>wooImage(src, position, name)),
277
+ attributes: options.map((option, position)=>({
278
+ id: 0,
279
+ name: option.name,
280
+ position,
281
+ visible: true,
282
+ variation: true,
283
+ options: option.values
284
+ })),
285
+ default_attributes: [],
286
+ variations: variable ? variants.map((variant)=>ids.variants.get(String(variant.id))).filter((id)=>typeof id === 'number') : [],
287
+ grouped_products: [],
288
+ menu_order: 0,
289
+ meta_data: []
290
+ });
291
+ }
292
+ /** One variant as `GET /wc/v3/products/{id}/variations/{vid}` answers it. */ export function wooVariation(data, variant, variationId, context) {
293
+ var _data_createdAtMs, _ref, _data_updatedAtMs, _data_name, _variant_sku, _variant_options;
294
+ const created = wooDate(Number((_data_createdAtMs = data['createdAtMs']) != null ? _data_createdAtMs : 0));
295
+ const modified = wooDate(Number((_ref = (_data_updatedAtMs = data['updatedAtMs']) != null ? _data_updatedAtMs : data['createdAtMs']) != null ? _ref : 0));
296
+ const tracked = typeof variant.inventory === 'number';
297
+ const prices = pricesOf(variant);
298
+ const image = variant.imageUrl ? wooImage(variant.imageUrl, 0, String((_data_name = data['name']) != null ? _data_name : '')) : null;
299
+ return _extends({
300
+ id: variationId,
301
+ date_created: created,
302
+ date_created_gmt: created,
303
+ date_modified: modified,
304
+ date_modified_gmt: modified,
305
+ description: '',
306
+ permalink: data['slug'] ? `${context.origin}/products/${String(data['slug'])}` : context.origin,
307
+ sku: String((_variant_sku = variant.sku) != null ? _variant_sku : '')
308
+ }, prices, {
309
+ status: prices.purchasable ? 'publish' : 'private',
310
+ virtual: data['type'] === 'service',
311
+ downloadable: false,
312
+ downloads: [],
313
+ tax_status: 'taxable',
314
+ tax_class: '',
315
+ manage_stock: tracked,
316
+ stock_quantity: tracked ? Number(variant.inventory) : null,
317
+ stock_status: tracked && Number(variant.inventory) <= 0 ? 'outofstock' : 'instock',
318
+ backorders: 'no',
319
+ backorders_allowed: false,
320
+ backordered: false,
321
+ weight: kilograms(variant.weightGrams),
322
+ dimensions: {
323
+ length: '',
324
+ width: '',
325
+ height: ''
326
+ },
327
+ shipping_class: '',
328
+ shipping_class_id: 0,
329
+ image,
330
+ attributes: Object.entries((_variant_options = variant.options) != null ? _variant_options : {}).map(([name, option])=>({
331
+ id: 0,
332
+ name,
333
+ option
334
+ })),
335
+ menu_order: 0,
336
+ meta_data: []
337
+ });
338
+ }
339
+ function readAttributes(value) {
340
+ if (!Array.isArray(value)) return null;
341
+ return value.filter(isRecord).map((attribute)=>{
342
+ var _attribute_name;
343
+ return {
344
+ name: String((_attribute_name = attribute['name']) != null ? _attribute_name : '').trim(),
345
+ options: (Array.isArray(attribute['options']) ? attribute['options'] : typeof attribute['option'] === 'string' ? [
346
+ attribute['option']
347
+ ] : []).map((option)=>String(option).trim()).filter(Boolean),
348
+ // WooCommerce's own default for an attribute sent without the flag is
349
+ // false; an app that sends variations always sets it.
350
+ variation: attribute['variation'] === true
351
+ };
352
+ });
353
+ }
354
+ /** The prices of a WooCommerce write as the store's variant write. */ export function variantWriteFromWoo(body) {
355
+ const write = {};
356
+ const regular = 'regular_price' in body ? readWooMoney(body['regular_price']) : undefined;
357
+ const sale = 'sale_price' in body ? readWooMoney(body['sale_price']) : undefined;
358
+ if ('regular_price' in body && regular === undefined) return {
359
+ error: 'regular_price is not a price'
360
+ };
361
+ if ('sale_price' in body && sale === undefined) return {
362
+ error: 'sale_price is not a price'
363
+ };
364
+ if (typeof sale === 'number' && typeof regular === 'number' && sale < regular) {
365
+ write.priceUsd = sale;
366
+ write.compareAtPriceUsd = regular;
367
+ } else if ('regular_price' in body) {
368
+ write.priceUsd = regular != null ? regular : null;
369
+ write.compareAtPriceUsd = null;
370
+ } else if (typeof sale === 'number') {
371
+ write.priceUsd = sale;
372
+ }
373
+ if (typeof body['sku'] === 'string') write.sku = body['sku'].trim() || null;
374
+ if ('weight' in body) {
375
+ const kg = readWooMoney(body['weight']);
376
+ if (kg === undefined) return {
377
+ error: 'weight is not a number'
378
+ };
379
+ write.weightGrams = kg === null ? null : Math.round(kg * 1000);
380
+ }
381
+ if (body['manage_stock'] === false) write.inventory = null;
382
+ else if ('stock_quantity' in body && (body['manage_stock'] === true || body['manage_stock'] === undefined)) {
383
+ const quantity = body['stock_quantity'];
384
+ if (quantity === null) write.inventory = null;
385
+ else if (typeof quantity === 'number' && Number.isInteger(quantity)) write.inventory = Math.max(0, quantity);
386
+ }
387
+ return {
388
+ write
389
+ };
390
+ }
391
+ /** The images a WooCommerce write names, as addresses, in their order. */ export function imagesFromWoo(value) {
392
+ if (!Array.isArray(value)) return null;
393
+ return value.filter(isRecord).map((image, index)=>{
394
+ var _image_position;
395
+ return {
396
+ src: typeof image['src'] === 'string' ? image['src'].trim() : '',
397
+ position: Number((_image_position = image['position']) != null ? _image_position : index)
398
+ };
399
+ }).filter((image)=>/^https?:\/\/\S+$/.test(image.src)).sort((a, b)=>a.position - b.position).map((image)=>image.src);
400
+ }
401
+ /**
402
+ * A WooCommerce product create or update as the body of the store's own
403
+ * product write (`readProductWrite`), plus the one variant a simple product
404
+ * prices. Attributes marked for variations become the product's options, so
405
+ * its variant grid is every combination, as the editor builds it; the other
406
+ * attributes are descriptive in WooCommerce and are not kept.
407
+ */ export function productWriteFromWoo(body, create) {
408
+ var _ref;
409
+ const values = {};
410
+ if (typeof body['name'] === 'string') values.name = body['name'];
411
+ else if (create) values.name = 'Untitled product';
412
+ if (typeof body['description'] === 'string') values.description = body['description'];
413
+ else if (typeof body['short_description'] === 'string' && create) values.description = body['short_description'];
414
+ const status = storeProductStatus(body['status']);
415
+ // WooCommerce publishes a product created without a status.
416
+ if (status) values.status = status;
417
+ else if (create) values.status = 'active';
418
+ if (body['virtual'] === true) values.type = 'service';
419
+ else if (create) values.type = 'physical';
420
+ const images = imagesFromWoo(body['images']);
421
+ if (images) values.mediaUrls = images;
422
+ if (Array.isArray(body['tags'])) {
423
+ values.tags = body['tags'].map((tag)=>{
424
+ var _ref, _tag_name;
425
+ return isRecord(tag) ? String((_ref = (_tag_name = tag['name']) != null ? _tag_name : tag['slug']) != null ? _ref : '') : String(tag);
426
+ }).map((tag)=>tag.trim()).filter(Boolean);
427
+ }
428
+ const attributes = readAttributes(body['attributes']);
429
+ const variationAttributes = (_ref = attributes == null ? void 0 : attributes.filter((attribute)=>attribute.variation && attribute.name && attribute.options.length)) != null ? _ref : null;
430
+ const type = body['type'];
431
+ if (variationAttributes && (type === 'variable' || type === undefined && variationAttributes.length)) {
432
+ values.options = variationAttributes.map((attribute)=>({
433
+ name: attribute.name,
434
+ values: attribute.options
435
+ }));
436
+ } else if (type === 'simple' && create) {
437
+ values.options = [];
438
+ }
439
+ const categoryIds = Array.isArray(body['categories']) ? body['categories'].filter(isRecord).map((category)=>Number(category['id'])).filter((id)=>Number.isInteger(id) && id > 0) : [];
440
+ const variable = Array.isArray(values.options) ? values.options.length > 0 : type === 'variable';
441
+ let simpleVariant = null;
442
+ if (!variable) {
443
+ const read = variantWriteFromWoo(body);
444
+ if ('error' in read) return read;
445
+ simpleVariant = Object.keys(read.write).length ? read.write : null;
446
+ }
447
+ return {
448
+ values,
449
+ simpleVariant,
450
+ categoryIds
451
+ };
452
+ }
453
+ /**
454
+ * The options one WooCommerce variation names: `{ Color: 'Black', Size: 'M' }`.
455
+ * Attribute names are matched to the product's options without regard to
456
+ * case or a `pa_` prefix, and the product's spelling is kept.
457
+ */ export function variationOptionsFromWoo(attributes, productOptions) {
458
+ var _readAttributes;
459
+ const out = {};
460
+ const list = (_readAttributes = readAttributes(attributes)) != null ? _readAttributes : [];
461
+ for (const attribute of list){
462
+ var _ref, _ref1;
463
+ const option = attribute.options[0];
464
+ if (!attribute.name || !option) continue;
465
+ const wanted = attribute.name.toLowerCase().replace(/^pa_/, '');
466
+ const match = productOptions.find((candidate)=>candidate.name.toLowerCase() === wanted);
467
+ out[(_ref = match == null ? void 0 : match.name) != null ? _ref : attribute.name] = (_ref1 = match == null ? void 0 : match.values.find((value)=>value.toLowerCase() === option.toLowerCase())) != null ? _ref1 : option;
468
+ }
469
+ return out;
470
+ }
471
+ /**
472
+ * The product's options with every value a variation names added, so the
473
+ * variation exists in the grid. `null` when nothing is missing.
474
+ */ export function optionsWithVariation(productOptions, selection) {
475
+ let changed = false;
476
+ const next = productOptions.map((option)=>({
477
+ name: option.name,
478
+ values: [
479
+ ...option.values
480
+ ]
481
+ }));
482
+ for (const [name, value] of Object.entries(selection)){
483
+ const option = next.find((candidate)=>candidate.name === name);
484
+ if (!option) {
485
+ next.push({
486
+ name,
487
+ values: [
488
+ value
489
+ ]
490
+ });
491
+ changed = true;
492
+ } else if (!option.values.includes(value)) {
493
+ option.values.push(value);
494
+ changed = true;
495
+ }
496
+ }
497
+ return changed ? next : null;
498
+ }
499
+ function splitName(name) {
500
+ var _parts_;
501
+ const parts = String(name != null ? name : '').trim().split(/\s+/).filter(Boolean);
502
+ return {
503
+ first_name: (_parts_ = parts[0]) != null ? _parts_ : '',
504
+ last_name: parts.slice(1).join(' ')
505
+ };
506
+ }
507
+ function wooAddress(address, fallbackName, phone) {
508
+ var _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8;
509
+ return _extends({}, splitName((_ref = address == null ? void 0 : address.name) != null ? _ref : fallbackName), {
510
+ company: '',
511
+ address_1: String((_ref1 = address == null ? void 0 : address.line1) != null ? _ref1 : ''),
512
+ address_2: String((_ref2 = address == null ? void 0 : address.line2) != null ? _ref2 : ''),
513
+ city: String((_ref3 = address == null ? void 0 : address.city) != null ? _ref3 : ''),
514
+ state: String((_ref4 = address == null ? void 0 : address.state) != null ? _ref4 : ''),
515
+ postcode: String((_ref5 = address == null ? void 0 : address.postalCode) != null ? _ref5 : ''),
516
+ country: String((_ref6 = address == null ? void 0 : address.country) != null ? _ref6 : ''),
517
+ phone: String((_ref7 = (_ref8 = address == null ? void 0 : address.phone) != null ? _ref8 : phone) != null ? _ref7 : '')
518
+ });
519
+ }
520
+ export const lineIdKey = (productId, variantId)=>variantId ? `${productId}|${variantId}` : productId;
521
+ /** An order as `GET /wc/v3/orders/{id}` answers it. */ export function wooOrder(orderId, data, ids, extras) {
522
+ var _data_createdAtMs, _ref, _data_updatedAtMs, _fulfillments_map_filter_sort_, _totals_shippingCents, _data_customerEmail, _totals_discountCents, _totals_taxCents, _ref1, _totals_totalCents, _totals_taxCents1, _totals_discountCents1;
523
+ const totals = isRecord(data['totals']) ? data['totals'] : {};
524
+ const createdMs = Number((_data_createdAtMs = data['createdAtMs']) != null ? _data_createdAtMs : 0) || null;
525
+ const modifiedMs = Number((_ref = (_data_updatedAtMs = data['updatedAtMs']) != null ? _data_updatedAtMs : data['createdAtMs']) != null ? _ref : 0) || null;
526
+ const status = wooOrderStatus(data['status']);
527
+ const lines = Array.isArray(data['lineItems']) ? data['lineItems'] : [];
528
+ const fulfillments = Array.isArray(data['fulfillments']) ? data['fulfillments'] : [];
529
+ const completedMs = (_fulfillments_map_filter_sort_ = fulfillments.map((entry)=>{
530
+ var _entry_atMs;
531
+ return Number((_entry_atMs = entry['atMs']) != null ? _entry_atMs : 0);
532
+ }).filter((ms)=>ms > 0).sort((a, b)=>b - a)[0]) != null ? _fulfillments_map_filter_sort_ : null;
533
+ const shippingCents = Number((_totals_shippingCents = totals['shippingCents']) != null ? _totals_shippingCents : 0);
534
+ const email = String((_data_customerEmail = data['customerEmail']) != null ? _data_customerEmail : '');
535
+ const phone = typeof data['customerPhone'] === 'string' ? data['customerPhone'] : null;
536
+ const name = typeof data['customerName'] === 'string' ? data['customerName'] : null;
537
+ const shippingAddress = isRecord(data['shippingAddress']) ? data['shippingAddress'] : null;
538
+ const billingAddress = isRecord(data['billingAddress']) ? data['billingAddress'] : shippingAddress;
539
+ const meta = Object.entries(extras.meta).map(([key, value], index)=>({
540
+ id: index + 1,
541
+ key,
542
+ value
543
+ }));
544
+ if (extras.testMode) meta.push({
545
+ id: meta.length + 1,
546
+ key: '_aglyn_test_mode',
547
+ value: 'yes'
548
+ });
549
+ const paid = status !== 'pending' && status !== 'cancelled';
550
+ return {
551
+ id: ids.order,
552
+ parent_id: 0,
553
+ number: String(typeof data['number'] === 'number' ? data['number'] : ids.order),
554
+ order_key: `wc_order_${orderId}`,
555
+ created_via: data['channel'] === 'pos' ? 'pos' : 'checkout',
556
+ version: WOO_REPORTED_VERSION,
557
+ status,
558
+ currency: 'USD',
559
+ currency_symbol: '$',
560
+ date_created: wooDate(createdMs),
561
+ date_created_gmt: wooDate(createdMs),
562
+ date_modified: wooDate(modifiedMs),
563
+ date_modified_gmt: wooDate(modifiedMs),
564
+ discount_total: wooCents(Number((_totals_discountCents = totals['discountCents']) != null ? _totals_discountCents : 0)),
565
+ discount_tax: '0.00',
566
+ shipping_total: wooCents(shippingCents),
567
+ shipping_tax: '0.00',
568
+ cart_tax: wooCents(Number((_totals_taxCents = totals['taxCents']) != null ? _totals_taxCents : 0)),
569
+ total: wooCents(Number((_ref1 = (_totals_totalCents = totals['totalCents']) != null ? _totals_totalCents : data['amountCents']) != null ? _ref1 : 0)),
570
+ total_tax: wooCents(Number((_totals_taxCents1 = totals['taxCents']) != null ? _totals_taxCents1 : 0)),
571
+ prices_include_tax: false,
572
+ customer_id: 0,
573
+ customer_ip_address: '',
574
+ customer_user_agent: '',
575
+ customer_note: '',
576
+ billing: _extends({}, wooAddress(billingAddress, name, phone), {
577
+ email
578
+ }),
579
+ shipping: wooAddress(shippingAddress, name, phone),
580
+ payment_method: paid ? 'aglyn' : '',
581
+ payment_method_title: paid ? 'Card' : '',
582
+ transaction_id: '',
583
+ date_paid: paid ? wooDate(createdMs) : null,
584
+ date_paid_gmt: paid ? wooDate(createdMs) : null,
585
+ date_completed: status === 'completed' ? wooDate(completedMs) : null,
586
+ date_completed_gmt: status === 'completed' ? wooDate(completedMs) : null,
587
+ cart_hash: '',
588
+ meta_data: meta,
589
+ line_items: lines.map((line, index)=>{
590
+ var _line_productId, _line_quantity, _line_unitAmountCents, _ids_lines_get, _ids_lines_get1, _line_sku, _line_name;
591
+ const productId = String((_line_productId = line['productId']) != null ? _line_productId : '');
592
+ const variantId = typeof line['variantId'] === 'string' ? line['variantId'] : undefined;
593
+ const quantity = Number((_line_quantity = line['quantity']) != null ? _line_quantity : 0);
594
+ const unitCents = Number((_line_unitAmountCents = line['unitAmountCents']) != null ? _line_unitAmountCents : 0);
595
+ const variationId = variantId ? (_ids_lines_get = ids.lines.get(lineIdKey(productId, variantId))) != null ? _ids_lines_get : 0 : 0;
596
+ return {
597
+ id: index + 1,
598
+ name: [
599
+ line['name'],
600
+ line['variantLabel']
601
+ ].filter(Boolean).join(' - '),
602
+ product_id: (_ids_lines_get1 = ids.lines.get(productId)) != null ? _ids_lines_get1 : 0,
603
+ variation_id: variationId,
604
+ quantity,
605
+ tax_class: '',
606
+ subtotal: wooCents(unitCents * quantity),
607
+ subtotal_tax: '0.00',
608
+ total: wooCents(unitCents * quantity),
609
+ total_tax: '0.00',
610
+ taxes: [],
611
+ meta_data: [],
612
+ sku: String((_line_sku = line['sku']) != null ? _line_sku : ''),
613
+ price: unitCents / 100,
614
+ image: {
615
+ id: '',
616
+ src: ''
617
+ },
618
+ parent_name: variationId ? String((_line_name = line['name']) != null ? _line_name : '') : null
619
+ };
620
+ }),
621
+ tax_lines: [],
622
+ shipping_lines: shippingCents > 0 || shippingAddress ? [
623
+ {
624
+ id: 1,
625
+ method_title: 'Shipping',
626
+ method_id: 'flat_rate',
627
+ instance_id: '',
628
+ total: wooCents(shippingCents),
629
+ total_tax: '0.00',
630
+ taxes: [],
631
+ meta_data: []
632
+ }
633
+ ] : [],
634
+ fee_lines: [],
635
+ coupon_lines: data['couponCode'] ? [
636
+ {
637
+ id: 1,
638
+ code: String(data['couponCode']),
639
+ discount: wooCents(Number((_totals_discountCents1 = totals['discountCents']) != null ? _totals_discountCents1 : 0)),
640
+ discount_tax: '0.00',
641
+ meta_data: []
642
+ }
643
+ ] : [],
644
+ refunds: [],
645
+ set_paid: paid,
646
+ needs_payment: !paid,
647
+ needs_processing: status === 'processing',
648
+ is_editable: false
649
+ };
650
+ }
651
+ const TRACKING_NUMBER_KEYS = [
652
+ '_tracking_number',
653
+ 'tracking_number',
654
+ '_wc_shipment_tracking_number',
655
+ '_aftership_tracking_number',
656
+ 'ywot_tracking_code',
657
+ '_tracking_code',
658
+ 'tracking_code'
659
+ ];
660
+ const CARRIER_KEYS = [
661
+ '_tracking_provider',
662
+ 'tracking_provider',
663
+ '_aftership_tracking_provider_name',
664
+ 'ywot_carrier_name',
665
+ 'tracking_carrier',
666
+ 'carrier',
667
+ 'shipping_carrier'
668
+ ];
669
+ const TRACKING_URL_KEYS = [
670
+ '_tracking_url',
671
+ 'tracking_url',
672
+ 'tracking_link',
673
+ '_tracking_link',
674
+ 'ywot_tracking_url'
675
+ ];
676
+ function firstText(meta, keys) {
677
+ for (const key of keys){
678
+ const value = meta[key];
679
+ if (typeof value === 'string' && value.trim()) return value.trim();
680
+ if (typeof value === 'number') return String(value);
681
+ }
682
+ return '';
683
+ }
684
+ /**
685
+ * Tracking from a WooCommerce shipment-tracking entry or from an order's
686
+ * `meta_data`, in the forms the common tracking extensions write it:
687
+ * WooCommerce Shipment Tracking and Advanced Shipment Tracking
688
+ * (`_wc_shipment_tracking_items`), AfterShip, YITH and the bare
689
+ * `tracking_number` many apps set. `null` when none names a number.
690
+ */ export function trackingFromWooMeta(meta) {
691
+ const items = meta['_wc_shipment_tracking_items'];
692
+ const parsedItems = typeof items === 'string' ? safeJson(items) : items;
693
+ if (Array.isArray(parsedItems) && parsedItems.length) {
694
+ const last = parsedItems[parsedItems.length - 1];
695
+ if (isRecord(last)) {
696
+ const entry = trackingFromShipmentEntry(last);
697
+ if (entry) return entry;
698
+ }
699
+ }
700
+ const trackingNumber = firstText(meta, TRACKING_NUMBER_KEYS);
701
+ if (!trackingNumber) return null;
702
+ return {
703
+ trackingNumber,
704
+ carrier: firstText(meta, CARRIER_KEYS),
705
+ trackingUrl: httpsOrBlank(firstText(meta, TRACKING_URL_KEYS))
706
+ };
707
+ }
708
+ /** One shipment-tracking entry (`tracking_number`, `tracking_provider`, `tracking_link`, …). */ export function trackingFromShipmentEntry(entry) {
709
+ const trackingNumber = firstText(entry, [
710
+ 'tracking_number'
711
+ ]);
712
+ if (!trackingNumber) return null;
713
+ return {
714
+ trackingNumber,
715
+ carrier: firstText(entry, [
716
+ 'custom_tracking_provider',
717
+ 'tracking_provider',
718
+ 'tracking_provider_name',
719
+ 'formatted_tracking_provider'
720
+ ]),
721
+ trackingUrl: httpsOrBlank(firstText(entry, [
722
+ 'custom_tracking_link',
723
+ 'tracking_link',
724
+ 'formatted_tracking_link'
725
+ ]))
726
+ };
727
+ }
728
+ /** `meta_data: [{ key, value }]` as a map; later entries win, as WooCommerce's update does. */ export function metaMap(value) {
729
+ const out = {};
730
+ if (!Array.isArray(value)) return out;
731
+ for (const entry of value){
732
+ if (isRecord(entry) && typeof entry['key'] === 'string') out[entry['key']] = entry['value'];
733
+ }
734
+ return out;
735
+ }
736
+ const KNOWN_CARRIERS = [
737
+ [
738
+ /\busps\b/i,
739
+ 'USPS'
740
+ ],
741
+ [
742
+ /\bups\b/i,
743
+ 'UPS'
744
+ ],
745
+ [
746
+ /\bfed ?ex\b/i,
747
+ 'FedEx'
748
+ ],
749
+ [
750
+ /\bdhl\b/i,
751
+ 'DHL'
752
+ ],
753
+ [
754
+ /\byun ?express\b/i,
755
+ 'YunExpress'
756
+ ],
757
+ [
758
+ /\bcanada post\b/i,
759
+ 'Canada Post'
760
+ ]
761
+ ];
762
+ /**
763
+ * Tracking in an order note's text, as fulfillment apps write it:
764
+ * "Tracking number: 9400…", "tracking no. LX123…", or a link to a carrier's
765
+ * tracking page. `null` when the note names no number.
766
+ */ export function trackingFromNote(note) {
767
+ var _ref;
768
+ var _KNOWN_CARRIERS_find;
769
+ const text = String(note != null ? note : '').replace(/<[^>]*>/g, ' ');
770
+ const labelled = /tracking\s*(?:number|no\.?|#|code|id)?\s*(?:is|:|-)?\s*([A-Z0-9][A-Z0-9-]{7,39})\b/gi;
771
+ let fromLabel = '';
772
+ for (const match of text.matchAll(labelled)){
773
+ if (/\d/.test(match[1])) {
774
+ fromLabel = match[1];
775
+ break;
776
+ }
777
+ }
778
+ const link = /(https:\/\/[^\s"'<>]+)/i.exec(text);
779
+ const trackingNumber = fromLabel || (link ? trackingNumberInLink(link[1]) : '');
780
+ if (!trackingNumber || !/\d/.test(trackingNumber)) return null;
781
+ const carrier = (_ref = (_KNOWN_CARRIERS_find = KNOWN_CARRIERS.find(([pattern])=>pattern.test(text))) == null ? void 0 : _KNOWN_CARRIERS_find[1]) != null ? _ref : '';
782
+ return {
783
+ trackingNumber,
784
+ carrier,
785
+ trackingUrl: link ? httpsOrBlank(link[1]) : ''
786
+ };
787
+ }
788
+ function trackingNumberInLink(href) {
789
+ try {
790
+ var _url_pathname_split_filter_pop;
791
+ const url = new URL(href);
792
+ for (const name of [
793
+ 'tracknum',
794
+ 'tracking_number',
795
+ 'trackingNumber',
796
+ 'tLabels',
797
+ 'tracknumbers',
798
+ 'trknbr',
799
+ 'number',
800
+ 'nums',
801
+ 'id'
802
+ ]){
803
+ const value = url.searchParams.get(name);
804
+ if (value && /^[A-Z0-9-]{8,40}$/i.test(value)) return value;
805
+ }
806
+ const last = (_url_pathname_split_filter_pop = url.pathname.split('/').filter(Boolean).pop()) != null ? _url_pathname_split_filter_pop : '';
807
+ return /^[A-Z0-9-]{8,40}$/i.test(last) && /\d/.test(last) ? last : '';
808
+ } catch (unused) {
809
+ return '';
810
+ }
811
+ }
812
+ function httpsOrBlank(value) {
813
+ return /^https:\/\/\S+$/i.test(value) ? value.slice(0, 2048) : '';
814
+ }
815
+ function safeJson(text) {
816
+ try {
817
+ return JSON.parse(text);
818
+ } catch (unused) {
819
+ return null;
820
+ }
821
+ }
822
+ // ── The store as WooCommerce describes itself ───────────────────────────────
823
+ /**
824
+ * The WooCommerce version this surface reports. Apps gate features on it;
825
+ * this is the line whose REST API v3 the surface follows.
826
+ */ export const WOO_REPORTED_VERSION = '9.4.0';
827
+ export const WP_REPORTED_VERSION = '6.7';
828
+ /** The REST namespaces the store's `/wp-json/` index lists. */ export const WOO_NAMESPACES = [
829
+ 'wc/v3',
830
+ 'wc/v2',
831
+ 'wc-shipment-tracking/v3',
832
+ 'wc-auth/v1'
833
+ ];
834
+
835
+ //# sourceMappingURL=woo-shapes.js.map