@aglyn/plugins-commerce 1.35.2 → 1.37.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 +13 -13
- package/src/lib/components/storefront-payment-element.js +6 -25
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/server/woo/woo-images.d.ts +56 -0
- package/src/lib/server/woo/woo-images.js +166 -0
- package/src/lib/server/woo/woo-images.js.map +1 -0
- package/src/lib/server/woo/woo-products.js +22 -3
- package/src/lib/server/woo/woo-products.js.map +1 -1
- package/src/lib/server/woo/woo-shapes.js +26 -13
- package/src/lib/server/woo/woo-shapes.js.map +1 -1
- package/src/lib/server/woo/woo-system.js +10 -5
- package/src/lib/server/woo/woo-system.js.map +1 -1
- package/src/lib/server/woo/woo-webhooks.d.ts +4 -0
- package/src/lib/server/woo/woo-webhooks.js +36 -10
- package/src/lib/server/woo/woo-webhooks.js.map +1 -1
- package/src/lib/transfer/product-images.d.ts +1 -1
- package/src/lib/transfer/product-images.js +1 -1
- package/src/lib/transfer/product-images.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-shapes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE WOOCOMMERCE DIALECT, PURE (see `woo-route.ts`).\n *\n * Translations both ways between the store's own records and the shapes the\n * WooCommerce REST API v3 answers and accepts: products and their\n * variations, orders, statuses, money, dates and errors. Nothing here reads\n * or writes; the integer ids WooCommerce clients expect are looked up by the\n * caller (`woo-ids.ts`) and handed in.\n *\n * Conventions the clients lean on, kept exactly:\n * - money is a string with two decimals (`\"19.99\"`), never a number;\n * - dates are `YYYY-MM-DDTHH:mm:ss` with no zone, in the store's time and in\n * GMT (`_gmt`); every store here reports UTC, so the two agree;\n * - ids are positive integers;\n * - an error is `{ code, message, data: { status } }`.\n *=========================================*/\n\nimport type { ProductWriteValues, VariantWrite } from '../api-v1/product-writes'\n\n// ── Money, dates, errors ────────────────────────────────────────────────────\n\n/** Dollars as WooCommerce writes them: `\"19.99\"`, or `\"\"` for none. */\nexport function wooMoney(value: number | null | undefined): string {\n return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(2) : ''\n}\n\n/** Integer cents as WooCommerce money. */\nexport const wooCents = (cents: number | null | undefined): string =>\n wooMoney(typeof cents === 'number' && Number.isFinite(cents) ? cents / 100 : 0)\n\n/**\n * A WooCommerce price string as dollars: `null` for blank, `undefined` when\n * it is not a price at all (the caller refuses it).\n */\nexport function readWooMoney(value: unknown): number | null | undefined {\n if (value === null || value === undefined || value === '') return null\n const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : ''\n if (!/^\\d+(\\.\\d{1,4})?$/.test(text)) return undefined\n return Math.round(Number(text) * 100) / 100\n}\n\n/** A moment as WooCommerce dates it: no zone, seconds precision, UTC. */\nexport function wooDate(ms: number | null | undefined): string | null {\n if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return null\n return new Date(ms).toISOString().slice(0, 19)\n}\n\n/** A WooCommerce `after`/`before` filter as epoch ms; a zoneless date is UTC, as this store's dates are. */\nexport function readWooDate(value: string | null): number | null {\n if (!value) return null\n const text = /([zZ]|[+-]\\d\\d:?\\d\\d)$/.test(value) ? value : `${value}Z`\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** WooCommerce's error envelope. */\nexport function wooError(status: number, code: string, message: string, headers: Record<string, string> = {}): Response {\n return Response.json({ code, message, data: { status } }, { status, headers })\n}\n\nexport const wooNotFound = (message = 'No route was found matching the URL and request method.') =>\n wooError(404, 'rest_no_route', message)\n\nexport const wooInvalidId = (what: 'product' | 'variation' | 'order' | 'webhook' | 'note') =>\n wooError(404, `woocommerce_rest_${what === 'variation' ? 'product_variation' : what === 'note' ? 'order_note' : what}_invalid_id`, 'Invalid ID.')\n\n/** A product or order refusal from the store's own checks, in WooCommerce's words. */\nexport function wooRefusalFrom(response: { status: number; body: unknown }): Response {\n const error = (response.body as { error?: { message?: string; fields?: Record<string, string> } } | null)?.error\n const fields = error?.fields ? Object.entries(error.fields).map(([field, why]) => `${field}: ${why}`).join('; ') : ''\n const message = [error?.message ?? 'The request was refused.', fields].filter(Boolean).join(' — ')\n const status = response.status >= 400 ? response.status : 400\n const code = status === 404 ? 'woocommerce_rest_invalid_id' : status === 403 ? 'woocommerce_rest_cannot_create' : 'woocommerce_rest_invalid_param'\n return wooError(status, code, message)\n}\n\n// ── Pagination ──────────────────────────────────────────────────────────────\n\nexport interface WooPage {\n page: number\n perPage: number\n offset: number\n}\n\n/** `page`, `per_page` (1–100, default 10) and `offset`, as WooCommerce reads them. */\nexport function readWooPage(search: URLSearchParams): WooPage {\n const perPageRaw = Number(search.get('per_page') ?? 10)\n const perPage = Number.isInteger(perPageRaw) ? Math.min(100, Math.max(1, perPageRaw)) : 10\n const pageRaw = Number(search.get('page') ?? 1)\n const page = Number.isInteger(pageRaw) && pageRaw > 0 ? pageRaw : 1\n const offsetRaw = Number(search.get('offset') ?? NaN)\n const offset = Number.isInteger(offsetRaw) && offsetRaw >= 0 ? offsetRaw : (page - 1) * perPage\n return { page, perPage, offset }\n}\n\n/** One page of a list, with the headers WordPress sets on every collection. */\nexport function wooPaged<T>(items: readonly T[], page: WooPage, extra: Record<string, string> = {}): Response {\n const total = items.length\n const totalPages = Math.max(1, Math.ceil(total / page.perPage))\n return Response.json(items.slice(page.offset, page.offset + page.perPage), {\n headers: { 'X-WP-Total': String(total), 'X-WP-TotalPages': String(totalPages), ...extra },\n })\n}\n\n// ── Statuses ────────────────────────────────────────────────────────────────\n\n/** An order's status as WooCommerce names it. */\nexport function wooOrderStatus(status: unknown): string {\n switch (status) {\n case 'paid':\n case 'partially_fulfilled':\n return 'processing'\n case 'fulfilled':\n case 'delivered':\n return 'completed'\n case 'cancelled':\n return 'cancelled'\n case 'refunded':\n return 'refunded'\n default:\n return 'pending'\n }\n}\n\n/**\n * The store statuses a WooCommerce `status` filter means. `any` (or none) is\n * every status; `on-hold`, `failed`, `checkout-draft` and `trash` match none,\n * because no order here is ever in them.\n */\nexport function storeStatusesForWooFilter(filter: string | null): ReadonlySet<string> | null {\n const names = String(filter ?? '')\n .split(',')\n .map((name) => name.trim().replace(/^wc-/, ''))\n .filter(Boolean)\n if (!names.length || names.includes('any')) return null\n const statuses = new Set<string>()\n for (const name of names) {\n if (name === 'processing') ['paid', 'partially_fulfilled'].forEach((s) => statuses.add(s))\n else if (name === 'completed') ['fulfilled', 'delivered'].forEach((s) => statuses.add(s))\n else if (name === 'pending' || name === 'cancelled' || name === 'refunded') statuses.add(name)\n }\n return statuses\n}\n\n/** A product's status as WooCommerce names it. */\nexport const wooProductStatus = (status: unknown): string =>\n status === 'active' ? 'publish' : status === 'archived' ? 'private' : 'draft'\n\n/** A WooCommerce product status as the store's: only `publish` is on sale. */\nexport function storeProductStatus(status: unknown): 'active' | 'draft' | 'archived' | undefined {\n if (status === undefined || status === null || status === '') return undefined\n if (status === 'publish') return 'active'\n if (status === 'private' || status === 'trash') return 'archived'\n return 'draft'\n}\n\n// ── Products ────────────────────────────────────────────────────────────────\n\nexport interface WooProductIds {\n product: number\n /** Variant id → its WooCommerce variation id. */\n variants: ReadonlyMap<string, number>\n}\n\ninterface StoreVariant {\n id?: string\n options?: Record<string, string>\n sku?: string\n priceUsd?: number\n compareAtPriceUsd?: number\n weightGrams?: number\n inventory?: number | null\n imageUrl?: string\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n\nfunction variantsOf(data: Record<string, unknown>): StoreVariant[] {\n return Array.isArray(data['variants']) ? (data['variants'] as StoreVariant[]) : []\n}\n\nfunction optionsOf(data: Record<string, unknown>): Array<{ name: string; values: string[] }> {\n return Array.isArray(data['options'])\n ? (data['options'] as Array<Record<string, unknown>>)\n .filter(isRecord)\n .map((option) => ({ name: String(option['name'] ?? ''), values: Array.isArray(option['values']) ? option['values'].map(String) : [] }))\n : []\n}\n\n/** A stable small integer for an image, from its address. */\nexport function wooImageId(src: string): number {\n let hash = 0\n for (let index = 0; index < src.length; index += 1) hash = (hash * 31 + src.charCodeAt(index)) | 0\n return (Math.abs(hash) % 900_000_000) + 100_000\n}\n\nfunction wooImage(src: string, position: number, name: string) {\n return { id: wooImageId(src), src, name, alt: name, position, date_created: null, date_created_gmt: null }\n}\n\nconst kilograms = (grams: number | undefined): string =>\n typeof grams === 'number' && Number.isFinite(grams) ? String(Math.round(grams) / 1000) : ''\n\nfunction stockOf(variants: readonly StoreVariant[]) {\n const tracked = variants.filter((variant) => typeof variant.inventory === 'number')\n if (!tracked.length) return { manage_stock: false, stock_quantity: null, stock_status: 'instock' }\n const total = tracked.reduce((sum, variant) => sum + Number(variant.inventory ?? 0), 0)\n return { manage_stock: true, stock_quantity: total, stock_status: total > 0 ? 'instock' : 'outofstock' }\n}\n\n/** The prices of one variant in WooCommerce's three fields. */\nfunction pricesOf(variant: StoreVariant | undefined) {\n const price = typeof variant?.priceUsd === 'number' ? variant.priceUsd : null\n const compare = typeof variant?.compareAtPriceUsd === 'number' ? variant.compareAtPriceUsd : null\n const onSale = price !== null && compare !== null && compare > price\n return {\n price: wooMoney(price),\n regular_price: wooMoney(onSale ? compare : price),\n sale_price: onSale ? wooMoney(price) : '',\n on_sale: onSale,\n purchasable: price !== null,\n }\n}\n\nexport interface WooProductContext {\n /** The store's own address, for `permalink`. */\n origin: string\n categories: ReadonlyMap<string, { id: number; name: string; slug: string }>\n}\n\n/** A product as `GET /wc/v3/products/{id}` answers it. */\nexport function wooProduct(data: Record<string, unknown>, ids: WooProductIds, context: WooProductContext) {\n const variants = variantsOf(data)\n const options = optionsOf(data)\n const variable = options.length > 0\n const name = String(data['name'] ?? '')\n const media = Array.isArray(data['mediaUrls']) ? (data['mediaUrls'] as unknown[]).map(String) : []\n const first = variants[0]\n const created = wooDate(Number(data['createdAtMs'] ?? 0))\n const modified = wooDate(Number(data['updatedAtMs'] ?? data['createdAtMs'] ?? 0))\n const priced = variants.filter((variant) => typeof variant.priceUsd === 'number')\n const lowest = priced.length ? priced.reduce((low, variant) => (Number(variant.priceUsd) < Number(low.priceUsd) ? variant : low)) : undefined\n const categoryIds = Array.isArray(data['categoryIds']) ? (data['categoryIds'] as unknown[]).map(String) : []\n return {\n id: ids.product,\n name,\n slug: String(data['slug'] ?? ''),\n permalink: data['slug'] ? `${context.origin}/products/${String(data['slug'])}` : context.origin,\n date_created: created,\n date_created_gmt: created,\n date_modified: modified,\n date_modified_gmt: modified,\n type: variable ? 'variable' : 'simple',\n status: wooProductStatus(data['status']),\n featured: false,\n catalog_visibility: 'visible',\n description: String(data['description'] ?? ''),\n short_description: '',\n sku: variable ? '' : String(first?.sku ?? ''),\n ...pricesOf(variable ? lowest : first),\n total_sales: 0,\n virtual: data['type'] === 'service',\n downloadable: data['type'] === 'digital',\n downloads: [],\n tax_status: 'taxable',\n tax_class: '',\n ...stockOf(variants),\n backorders: 'no',\n backorders_allowed: false,\n backordered: false,\n sold_individually: false,\n weight: variable ? '' : kilograms(first?.weightGrams),\n dimensions: { length: '', width: '', height: '' },\n shipping_required: data['type'] !== 'service' && data['type'] !== 'digital',\n shipping_taxable: true,\n shipping_class: '',\n shipping_class_id: 0,\n reviews_allowed: false,\n average_rating: '0.00',\n rating_count: 0,\n related_ids: [],\n upsell_ids: [],\n cross_sell_ids: [],\n parent_id: 0,\n purchase_note: '',\n categories: categoryIds\n .map((id) => context.categories.get(id))\n .filter((category): category is { id: number; name: string; slug: string } => Boolean(category)),\n tags: (Array.isArray(data['tags']) ? (data['tags'] as unknown[]).map(String) : []).map((tag) => ({\n id: wooImageId(`tag:${tag}`),\n name: tag,\n slug: tag.toLowerCase().replace(/[^a-z0-9]+/g, '-'),\n })),\n images: media.map((src, position) => wooImage(src, position, name)),\n attributes: options.map((option, position) => ({\n id: 0,\n name: option.name,\n position,\n visible: true,\n variation: true,\n options: option.values,\n })),\n default_attributes: [],\n variations: variable ? variants.map((variant) => ids.variants.get(String(variant.id))).filter((id): id is number => typeof id === 'number') : [],\n grouped_products: [],\n menu_order: 0,\n meta_data: [],\n }\n}\n\n/** One variant as `GET /wc/v3/products/{id}/variations/{vid}` answers it. */\nexport function wooVariation(\n data: Record<string, unknown>,\n variant: StoreVariant,\n variationId: number,\n context: WooProductContext,\n) {\n const created = wooDate(Number(data['createdAtMs'] ?? 0))\n const modified = wooDate(Number(data['updatedAtMs'] ?? data['createdAtMs'] ?? 0))\n const tracked = typeof variant.inventory === 'number'\n const prices = pricesOf(variant)\n const image = variant.imageUrl ? wooImage(variant.imageUrl, 0, String(data['name'] ?? '')) : null\n return {\n id: variationId,\n date_created: created,\n date_created_gmt: created,\n date_modified: modified,\n date_modified_gmt: modified,\n description: '',\n permalink: data['slug'] ? `${context.origin}/products/${String(data['slug'])}` : context.origin,\n sku: String(variant.sku ?? ''),\n ...prices,\n status: prices.purchasable ? 'publish' : 'private',\n virtual: data['type'] === 'service',\n downloadable: false,\n downloads: [],\n tax_status: 'taxable',\n tax_class: '',\n manage_stock: tracked,\n stock_quantity: tracked ? Number(variant.inventory) : null,\n stock_status: tracked && Number(variant.inventory) <= 0 ? 'outofstock' : 'instock',\n backorders: 'no',\n backorders_allowed: false,\n backordered: false,\n weight: kilograms(variant.weightGrams),\n dimensions: { length: '', width: '', height: '' },\n shipping_class: '',\n shipping_class_id: 0,\n image,\n attributes: Object.entries(variant.options ?? {}).map(([name, option]) => ({ id: 0, name, option })),\n menu_order: 0,\n meta_data: [],\n }\n}\n\n// ── Reading a product write ─────────────────────────────────────────────────\n\n/** An attribute as a WooCommerce write names one. */\ninterface WooAttributeIn {\n name: string\n options: string[]\n variation: boolean\n}\n\nfunction readAttributes(value: unknown): WooAttributeIn[] | null {\n if (!Array.isArray(value)) return null\n return value.filter(isRecord).map((attribute) => ({\n name: String(attribute['name'] ?? '').trim(),\n options: (Array.isArray(attribute['options'])\n ? attribute['options']\n : typeof attribute['option'] === 'string'\n ? [attribute['option']]\n : []\n )\n .map((option) => String(option).trim())\n .filter(Boolean),\n // WooCommerce's own default for an attribute sent without the flag is\n // false; an app that sends variations always sets it.\n variation: attribute['variation'] === true,\n }))\n}\n\n/** The prices of a WooCommerce write as the store's variant write. */\nexport function variantWriteFromWoo(body: Record<string, unknown>): { write: VariantWrite } | { error: string } {\n const write: VariantWrite = {}\n const regular = 'regular_price' in body ? readWooMoney(body['regular_price']) : undefined\n const sale = 'sale_price' in body ? readWooMoney(body['sale_price']) : undefined\n if ('regular_price' in body && regular === undefined) return { error: 'regular_price is not a price' }\n if ('sale_price' in body && sale === undefined) return { error: 'sale_price is not a price' }\n if (typeof sale === 'number' && typeof regular === 'number' && sale < regular) {\n write.priceUsd = sale\n write.compareAtPriceUsd = regular\n } else if ('regular_price' in body) {\n write.priceUsd = regular ?? null\n write.compareAtPriceUsd = null\n } else if (typeof sale === 'number') {\n write.priceUsd = sale\n }\n if (typeof body['sku'] === 'string') write.sku = body['sku'].trim() || null\n if ('weight' in body) {\n const kg = readWooMoney(body['weight'])\n if (kg === undefined) return { error: 'weight is not a number' }\n write.weightGrams = kg === null ? null : Math.round(kg * 1000)\n }\n if (body['manage_stock'] === false) write.inventory = null\n else if ('stock_quantity' in body && (body['manage_stock'] === true || body['manage_stock'] === undefined)) {\n const quantity = body['stock_quantity']\n if (quantity === null) write.inventory = null\n else if (typeof quantity === 'number' && Number.isInteger(quantity)) write.inventory = Math.max(0, quantity)\n }\n return { write }\n}\n\n/** The images a WooCommerce write names, as addresses, in their order. */\nexport function imagesFromWoo(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n return value\n .filter(isRecord)\n .map((image, index) => ({ src: typeof image['src'] === 'string' ? image['src'].trim() : '', position: Number(image['position'] ?? index) }))\n .filter((image) => /^https?:\\/\\/\\S+$/.test(image.src))\n .sort((a, b) => a.position - b.position)\n .map((image) => image.src)\n}\n\nexport interface ProductWriteFromWoo {\n values: Record<string, unknown>\n /** For a simple product: its one variant's prices, SKU, weight and stock. */\n simpleVariant: VariantWrite | null\n /** WooCommerce category ids the write names, to map to the store's. */\n categoryIds: number[]\n}\n\n/**\n * A WooCommerce product create or update as the body of the store's own\n * product write (`readProductWrite`), plus the one variant a simple product\n * prices. Attributes marked for variations become the product's options, so\n * its variant grid is every combination, as the editor builds it; the other\n * attributes are descriptive in WooCommerce and are not kept.\n */\nexport function productWriteFromWoo(body: Record<string, unknown>, create: boolean): ProductWriteFromWoo | { error: string } {\n const values: Partial<Record<keyof ProductWriteValues, unknown>> = {}\n if (typeof body['name'] === 'string') values.name = body['name']\n else if (create) values.name = 'Untitled product'\n if (typeof body['description'] === 'string') values.description = body['description']\n else if (typeof body['short_description'] === 'string' && create) values.description = body['short_description']\n const status = storeProductStatus(body['status'])\n // WooCommerce publishes a product created without a status.\n if (status) values.status = status\n else if (create) values.status = 'active'\n if (body['virtual'] === true) values.type = 'service'\n else if (create) values.type = 'physical'\n const images = imagesFromWoo(body['images'])\n if (images) values.mediaUrls = images\n if (Array.isArray(body['tags'])) {\n values.tags = (body['tags'] as unknown[])\n .map((tag) => (isRecord(tag) ? String(tag['name'] ?? tag['slug'] ?? '') : String(tag)))\n .map((tag) => tag.trim())\n .filter(Boolean)\n }\n const attributes = readAttributes(body['attributes'])\n const variationAttributes = attributes?.filter((attribute) => attribute.variation && attribute.name && attribute.options.length) ?? null\n const type = body['type']\n if (variationAttributes && (type === 'variable' || (type === undefined && variationAttributes.length))) {\n values.options = variationAttributes.map((attribute) => ({ name: attribute.name, values: attribute.options }))\n } else if (type === 'simple' && create) {\n values.options = []\n }\n const categoryIds = Array.isArray(body['categories'])\n ? (body['categories'] as unknown[]).filter(isRecord).map((category) => Number(category['id'])).filter((id) => Number.isInteger(id) && id > 0)\n : []\n const variable = Array.isArray(values.options) ? (values.options as unknown[]).length > 0 : type === 'variable'\n let simpleVariant: VariantWrite | null = null\n if (!variable) {\n const read = variantWriteFromWoo(body)\n if ('error' in read) return read\n simpleVariant = Object.keys(read.write).length ? read.write : null\n }\n return { values, simpleVariant, categoryIds }\n}\n\n/**\n * The options one WooCommerce variation names: `{ Color: 'Black', Size: 'M' }`.\n * Attribute names are matched to the product's options without regard to\n * case or a `pa_` prefix, and the product's spelling is kept.\n */\nexport function variationOptionsFromWoo(\n attributes: unknown,\n productOptions: ReadonlyArray<{ name: string; values: string[] }>,\n): Record<string, string> {\n const out: Record<string, string> = {}\n const list = readAttributes(attributes) ?? []\n for (const attribute of list) {\n const option = attribute.options[0]\n if (!attribute.name || !option) continue\n const wanted = attribute.name.toLowerCase().replace(/^pa_/, '')\n const match = productOptions.find((candidate) => candidate.name.toLowerCase() === wanted)\n out[match?.name ?? attribute.name] = match?.values.find((value) => value.toLowerCase() === option.toLowerCase()) ?? option\n }\n return out\n}\n\n/**\n * The product's options with every value a variation names added, so the\n * variation exists in the grid. `null` when nothing is missing.\n */\nexport function optionsWithVariation(\n productOptions: ReadonlyArray<{ name: string; values: string[] }>,\n selection: Record<string, string>,\n): Array<{ name: string; values: string[] }> | null {\n let changed = false\n const next = productOptions.map((option) => ({ name: option.name, values: [...option.values] }))\n for (const [name, value] of Object.entries(selection)) {\n const option = next.find((candidate) => candidate.name === name)\n if (!option) {\n next.push({ name, values: [value] })\n changed = true\n } else if (!option.values.includes(value)) {\n option.values.push(value)\n changed = true\n }\n }\n return changed ? next : null\n}\n\n// ── Orders ──────────────────────────────────────────────────────────────────\n\ninterface StoreAddress {\n name?: string\n line1?: string\n line2?: string\n city?: string\n state?: string\n postalCode?: string\n country?: string\n phone?: string\n}\n\nfunction splitName(name: string | undefined | null): { first_name: string; last_name: string } {\n const parts = String(name ?? '').trim().split(/\\s+/).filter(Boolean)\n return { first_name: parts[0] ?? '', last_name: parts.slice(1).join(' ') }\n}\n\nfunction wooAddress(address: StoreAddress | undefined | null, fallbackName: string | null, phone: string | null) {\n return {\n ...splitName(address?.name ?? fallbackName),\n company: '',\n address_1: String(address?.line1 ?? ''),\n address_2: String(address?.line2 ?? ''),\n city: String(address?.city ?? ''),\n state: String(address?.state ?? ''),\n postcode: String(address?.postalCode ?? ''),\n country: String(address?.country ?? ''),\n phone: String(address?.phone ?? phone ?? ''),\n }\n}\n\nexport interface WooOrderIds {\n order: number\n /** `productId` → WooCommerce product id; `productId|variantId` → variation id. */\n lines: ReadonlyMap<string, number>\n}\n\nexport const lineIdKey = (productId: string, variantId?: string) => (variantId ? `${productId}|${variantId}` : productId)\n\n/** An order as `GET /wc/v3/orders/{id}` answers it. */\nexport function wooOrder(\n orderId: string,\n data: Record<string, unknown>,\n ids: WooOrderIds,\n extras: { meta: Record<string, string>; testMode: boolean },\n) {\n const totals = isRecord(data['totals']) ? data['totals'] : {}\n const createdMs = Number(data['createdAtMs'] ?? 0) || null\n const modifiedMs = Number(data['updatedAtMs'] ?? data['createdAtMs'] ?? 0) || null\n const status = wooOrderStatus(data['status'])\n const lines = Array.isArray(data['lineItems']) ? (data['lineItems'] as Array<Record<string, unknown>>) : []\n const fulfillments = Array.isArray(data['fulfillments']) ? (data['fulfillments'] as Array<Record<string, unknown>>) : []\n const completedMs = fulfillments.map((entry) => Number(entry['atMs'] ?? 0)).filter((ms) => ms > 0).sort((a, b) => b - a)[0] ?? null\n const shippingCents = Number(totals['shippingCents'] ?? 0)\n const email = String(data['customerEmail'] ?? '')\n const phone = typeof data['customerPhone'] === 'string' ? data['customerPhone'] : null\n const name = typeof data['customerName'] === 'string' ? data['customerName'] : null\n const shippingAddress = (isRecord(data['shippingAddress']) ? data['shippingAddress'] : null) as StoreAddress | null\n const billingAddress = (isRecord(data['billingAddress']) ? data['billingAddress'] : shippingAddress) as StoreAddress | null\n const meta: Array<{ id: number; key: string; value: string }> = Object.entries(extras.meta).map(([key, value], index) => ({\n id: index + 1,\n key,\n value,\n }))\n if (extras.testMode) meta.push({ id: meta.length + 1, key: '_aglyn_test_mode', value: 'yes' })\n const paid = status !== 'pending' && status !== 'cancelled'\n return {\n id: ids.order,\n parent_id: 0,\n number: String(typeof data['number'] === 'number' ? data['number'] : ids.order),\n order_key: `wc_order_${orderId}`,\n created_via: data['channel'] === 'pos' ? 'pos' : 'checkout',\n version: WOO_REPORTED_VERSION,\n status,\n currency: 'USD',\n currency_symbol: '$',\n date_created: wooDate(createdMs),\n date_created_gmt: wooDate(createdMs),\n date_modified: wooDate(modifiedMs),\n date_modified_gmt: wooDate(modifiedMs),\n discount_total: wooCents(Number(totals['discountCents'] ?? 0)),\n discount_tax: '0.00',\n shipping_total: wooCents(shippingCents),\n shipping_tax: '0.00',\n cart_tax: wooCents(Number(totals['taxCents'] ?? 0)),\n total: wooCents(Number(totals['totalCents'] ?? data['amountCents'] ?? 0)),\n total_tax: wooCents(Number(totals['taxCents'] ?? 0)),\n prices_include_tax: false,\n customer_id: 0,\n customer_ip_address: '',\n customer_user_agent: '',\n customer_note: '',\n billing: { ...wooAddress(billingAddress, name, phone), email },\n shipping: wooAddress(shippingAddress, name, phone),\n payment_method: paid ? 'aglyn' : '',\n payment_method_title: paid ? 'Card' : '',\n transaction_id: '',\n date_paid: paid ? wooDate(createdMs) : null,\n date_paid_gmt: paid ? wooDate(createdMs) : null,\n date_completed: status === 'completed' ? wooDate(completedMs) : null,\n date_completed_gmt: status === 'completed' ? wooDate(completedMs) : null,\n cart_hash: '',\n meta_data: meta,\n line_items: lines.map((line, index) => {\n const productId = String(line['productId'] ?? '')\n const variantId = typeof line['variantId'] === 'string' ? line['variantId'] : undefined\n const quantity = Number(line['quantity'] ?? 0)\n const unitCents = Number(line['unitAmountCents'] ?? 0)\n const variationId = variantId ? ids.lines.get(lineIdKey(productId, variantId)) ?? 0 : 0\n return {\n id: index + 1,\n name: [line['name'], line['variantLabel']].filter(Boolean).join(' - '),\n product_id: ids.lines.get(productId) ?? 0,\n variation_id: variationId,\n quantity,\n tax_class: '',\n subtotal: wooCents(unitCents * quantity),\n subtotal_tax: '0.00',\n total: wooCents(unitCents * quantity),\n total_tax: '0.00',\n taxes: [],\n meta_data: [],\n sku: String(line['sku'] ?? ''),\n price: unitCents / 100,\n image: { id: '', src: '' },\n parent_name: variationId ? String(line['name'] ?? '') : null,\n }\n }),\n tax_lines: [],\n shipping_lines:\n shippingCents > 0 || shippingAddress\n ? [{ id: 1, method_title: 'Shipping', method_id: 'flat_rate', instance_id: '', total: wooCents(shippingCents), total_tax: '0.00', taxes: [], meta_data: [] }]\n : [],\n fee_lines: [],\n coupon_lines: data['couponCode'] ? [{ id: 1, code: String(data['couponCode']), discount: wooCents(Number(totals['discountCents'] ?? 0)), discount_tax: '0.00', meta_data: [] }] : [],\n refunds: [],\n set_paid: paid,\n needs_payment: !paid,\n needs_processing: status === 'processing',\n is_editable: false,\n }\n}\n\n// ── Tracking written back ───────────────────────────────────────────────────\n\nexport interface WooTracking {\n trackingNumber: string\n carrier: string\n trackingUrl: string\n}\n\nconst TRACKING_NUMBER_KEYS = [\n '_tracking_number',\n 'tracking_number',\n '_wc_shipment_tracking_number',\n '_aftership_tracking_number',\n 'ywot_tracking_code',\n '_tracking_code',\n 'tracking_code',\n]\nconst CARRIER_KEYS = ['_tracking_provider', 'tracking_provider', '_aftership_tracking_provider_name', 'ywot_carrier_name', 'tracking_carrier', 'carrier', 'shipping_carrier']\nconst TRACKING_URL_KEYS = ['_tracking_url', 'tracking_url', 'tracking_link', '_tracking_link', 'ywot_tracking_url']\n\nfunction firstText(meta: Record<string, unknown>, keys: readonly string[]): string {\n for (const key of keys) {\n const value = meta[key]\n if (typeof value === 'string' && value.trim()) return value.trim()\n if (typeof value === 'number') return String(value)\n }\n return ''\n}\n\n/**\n * Tracking from a WooCommerce shipment-tracking entry or from an order's\n * `meta_data`, in the forms the common tracking extensions write it:\n * WooCommerce Shipment Tracking and Advanced Shipment Tracking\n * (`_wc_shipment_tracking_items`), AfterShip, YITH and the bare\n * `tracking_number` many apps set. `null` when none names a number.\n */\nexport function trackingFromWooMeta(meta: Record<string, unknown>): WooTracking | null {\n const items = meta['_wc_shipment_tracking_items']\n const parsedItems = typeof items === 'string' ? safeJson(items) : items\n if (Array.isArray(parsedItems) && parsedItems.length) {\n const last = parsedItems[parsedItems.length - 1]\n if (isRecord(last)) {\n const entry = trackingFromShipmentEntry(last)\n if (entry) return entry\n }\n }\n const trackingNumber = firstText(meta, TRACKING_NUMBER_KEYS)\n if (!trackingNumber) return null\n return { trackingNumber, carrier: firstText(meta, CARRIER_KEYS), trackingUrl: httpsOrBlank(firstText(meta, TRACKING_URL_KEYS)) }\n}\n\n/** One shipment-tracking entry (`tracking_number`, `tracking_provider`, `tracking_link`, …). */\nexport function trackingFromShipmentEntry(entry: Record<string, unknown>): WooTracking | null {\n const trackingNumber = firstText(entry, ['tracking_number'])\n if (!trackingNumber) return null\n return {\n trackingNumber,\n carrier: firstText(entry, ['custom_tracking_provider', 'tracking_provider', 'tracking_provider_name', 'formatted_tracking_provider']),\n trackingUrl: httpsOrBlank(firstText(entry, ['custom_tracking_link', 'tracking_link', 'formatted_tracking_link'])),\n }\n}\n\n/** `meta_data: [{ key, value }]` as a map; later entries win, as WooCommerce's update does. */\nexport function metaMap(value: unknown): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n if (!Array.isArray(value)) return out\n for (const entry of value) {\n if (isRecord(entry) && typeof entry['key'] === 'string') out[entry['key']] = entry['value']\n }\n return out\n}\n\nconst KNOWN_CARRIERS: ReadonlyArray<[RegExp, string]> = [\n [/\\busps\\b/i, 'USPS'],\n [/\\bups\\b/i, 'UPS'],\n [/\\bfed ?ex\\b/i, 'FedEx'],\n [/\\bdhl\\b/i, 'DHL'],\n [/\\byun ?express\\b/i, 'YunExpress'],\n [/\\bcanada post\\b/i, 'Canada Post'],\n]\n\n/**\n * Tracking in an order note's text, as fulfillment apps write it:\n * \"Tracking number: 9400…\", \"tracking no. LX123…\", or a link to a carrier's\n * tracking page. `null` when the note names no number.\n */\nexport function trackingFromNote(note: string): WooTracking | null {\n const text = String(note ?? '').replace(/<[^>]*>/g, ' ')\n const labelled = /tracking\\s*(?:number|no\\.?|#|code|id)?\\s*(?:is|:|-)?\\s*([A-Z0-9][A-Z0-9-]{7,39})\\b/gi\n let fromLabel = ''\n for (const match of text.matchAll(labelled)) {\n if (/\\d/.test(match[1])) {\n fromLabel = match[1]\n break\n }\n }\n const link = /(https:\\/\\/[^\\s\"'<>]+)/i.exec(text)\n const trackingNumber = fromLabel || (link ? trackingNumberInLink(link[1]) : '')\n if (!trackingNumber || !/\\d/.test(trackingNumber)) return null\n const carrier = KNOWN_CARRIERS.find(([pattern]) => pattern.test(text))?.[1] ?? ''\n return { trackingNumber, carrier, trackingUrl: link ? httpsOrBlank(link[1]) : '' }\n}\n\nfunction trackingNumberInLink(href: string): string {\n try {\n const url = new URL(href)\n for (const name of ['tracknum', 'tracking_number', 'trackingNumber', 'tLabels', 'tracknumbers', 'trknbr', 'number', 'nums', 'id']) {\n const value = url.searchParams.get(name)\n if (value && /^[A-Z0-9-]{8,40}$/i.test(value)) return value\n }\n const last = url.pathname.split('/').filter(Boolean).pop() ?? ''\n return /^[A-Z0-9-]{8,40}$/i.test(last) && /\\d/.test(last) ? last : ''\n } catch {\n return ''\n }\n}\n\nfunction httpsOrBlank(value: string): string {\n return /^https:\\/\\/\\S+$/i.test(value) ? value.slice(0, 2048) : ''\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return null\n }\n}\n\n// ── The store as WooCommerce describes itself ───────────────────────────────\n\n/**\n * The WooCommerce version this surface reports. Apps gate features on it;\n * this is the line whose REST API v3 the surface follows.\n */\nexport const WOO_REPORTED_VERSION = '9.4.0'\nexport const WP_REPORTED_VERSION = '6.7'\n\n/** The REST namespaces the store's `/wp-json/` index lists. */\nexport const WOO_NAMESPACES = ['wc/v3', 'wc/v2', 'wc-shipment-tracking/v3', 'wc-auth/v1'] as const\n"],"names":["wooMoney","value","Number","isFinite","toFixed","wooCents","cents","readWooMoney","undefined","text","String","trim","test","Math","round","wooDate","ms","Date","toISOString","slice","readWooDate","parse","wooError","status","code","message","headers","Response","json","data","wooNotFound","wooInvalidId","what","wooRefusalFrom","response","error","body","fields","Object","entries","map","field","why","join","filter","Boolean","readWooPage","search","perPageRaw","get","perPage","isInteger","min","max","pageRaw","page","offsetRaw","NaN","offset","wooPaged","items","extra","total","length","totalPages","ceil","wooOrderStatus","storeStatusesForWooFilter","names","split","name","replace","includes","statuses","Set","forEach","s","add","wooProductStatus","storeProductStatus","isRecord","Array","isArray","variantsOf","optionsOf","option","values","wooImageId","src","hash","index","charCodeAt","abs","wooImage","position","id","alt","date_created","date_created_gmt","kilograms","grams","stockOf","variants","tracked","variant","inventory","manage_stock","stock_quantity","stock_status","reduce","sum","pricesOf","price","priceUsd","compare","compareAtPriceUsd","onSale","regular_price","sale_price","on_sale","purchasable","wooProduct","ids","context","options","variable","media","first","created","modified","priced","lowest","low","categoryIds","product","slug","permalink","origin","date_modified","date_modified_gmt","type","featured","catalog_visibility","description","short_description","sku","total_sales","virtual","downloadable","downloads","tax_status","tax_class","backorders","backorders_allowed","backordered","sold_individually","weight","weightGrams","dimensions","width","height","shipping_required","shipping_taxable","shipping_class","shipping_class_id","reviews_allowed","average_rating","rating_count","related_ids","upsell_ids","cross_sell_ids","parent_id","purchase_note","categories","category","tags","tag","toLowerCase","images","attributes","visible","variation","default_attributes","variations","grouped_products","menu_order","meta_data","wooVariation","variationId","prices","image","imageUrl","readAttributes","attribute","variantWriteFromWoo","write","regular","sale","kg","quantity","imagesFromWoo","sort","a","b","productWriteFromWoo","create","mediaUrls","variationAttributes","simpleVariant","read","keys","variationOptionsFromWoo","productOptions","out","list","wanted","match","find","candidate","optionsWithVariation","selection","changed","next","push","splitName","parts","first_name","last_name","wooAddress","address","fallbackName","phone","company","address_1","line1","address_2","line2","city","state","postcode","postalCode","country","lineIdKey","productId","variantId","wooOrder","orderId","extras","fulfillments","totals","createdMs","modifiedMs","lines","completedMs","entry","shippingCents","email","shippingAddress","billingAddress","meta","key","testMode","paid","order","number","order_key","created_via","version","WOO_REPORTED_VERSION","currency","currency_symbol","discount_total","discount_tax","shipping_total","shipping_tax","cart_tax","total_tax","prices_include_tax","customer_id","customer_ip_address","customer_user_agent","customer_note","billing","shipping","payment_method","payment_method_title","transaction_id","date_paid","date_paid_gmt","date_completed","date_completed_gmt","cart_hash","line_items","line","unitCents","product_id","variation_id","subtotal","subtotal_tax","taxes","parent_name","tax_lines","shipping_lines","method_title","method_id","instance_id","fee_lines","coupon_lines","discount","refunds","set_paid","needs_payment","needs_processing","is_editable","TRACKING_NUMBER_KEYS","CARRIER_KEYS","TRACKING_URL_KEYS","firstText","trackingFromWooMeta","parsedItems","safeJson","last","trackingFromShipmentEntry","trackingNumber","carrier","trackingUrl","httpsOrBlank","metaMap","KNOWN_CARRIERS","trackingFromNote","note","labelled","fromLabel","matchAll","link","exec","trackingNumberInLink","pattern","href","url","URL","searchParams","pathname","pop","JSON","WP_REPORTED_VERSION","WOO_NAMESPACES"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;2CAe2C;AAI3C,+EAA+E;AAE/E,qEAAqE,GACrE,OAAO,SAASA,SAASC,KAAgC;IACvD,OAAO,OAAOA,UAAU,YAAYC,OAAOC,QAAQ,CAACF,SAASA,MAAMG,OAAO,CAAC,KAAK;AAClF;AAEA,wCAAwC,GACxC,OAAO,MAAMC,WAAW,CAACC,QACvBN,SAAS,OAAOM,UAAU,YAAYJ,OAAOC,QAAQ,CAACG,SAASA,QAAQ,MAAM,GAAE;AAEjF;;;CAGC,GACD,OAAO,SAASC,aAAaN,KAAc;IACzC,IAAIA,UAAU,QAAQA,UAAUO,aA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vU,IAAI,CAACqT,SAAS,KAAKrT,IAAI,CAACqT,QAAQA,OAAO;IACrE,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASK,aAAarU,KAAa;IACjC,OAAO,mBAAmBW,IAAI,CAACX,SAASA,MAAMkB,KAAK,CAAC,GAAG,QAAQ;AACjE;AAEA,SAAS6S,SAASvT,IAAY;IAC5B,IAAI;QACF,OAAO+U,KAAKnU,KAAK,CAACZ;IACpB,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,+EAA+E;AAE/E;;;CAGC,GACD,OAAO,MAAMmQ,uBAAuB,QAAO;AAC3C,OAAO,MAAM6E,sBAAsB,MAAK;AAExC,6DAA6D,GAC7D,OAAO,MAAMC,iBAAiB;IAAC;IAAS;IAAS;IAA2B;CAAa,CAAS"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-shapes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE WOOCOMMERCE DIALECT, PURE (see `woo-route.ts`).\n *\n * Translations both ways between the store's own records and the shapes the\n * WooCommerce REST API v3 answers and accepts: products and their\n * variations, orders, statuses, money, dates and errors. Nothing here reads\n * or writes; the integer ids WooCommerce clients expect are looked up by the\n * caller (`woo-ids.ts`) and handed in.\n *\n * Conventions the clients lean on, kept exactly:\n * - money is a string with two decimals (`\"19.99\"`), never a number;\n * - dates are `YYYY-MM-DDTHH:mm:ss` with no zone, in the store's time and in\n * GMT (`_gmt`); every store here reports UTC, so the two agree;\n * - ids are positive integers;\n * - an error is `{ code, message, data: { status } }`.\n *=========================================*/\n\nimport { htmlDescriptionToText, looksLikeHtml } from '@aglyn/aglyn/app-utils/html-description-text'\nimport { absoluteMediaSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport type { ProductWriteValues, VariantWrite } from '../api-v1/product-writes'\n\n// ── Money, dates, errors ────────────────────────────────────────────────────\n\n/** Dollars as WooCommerce writes them: `\"19.99\"`, or `\"\"` for none. */\nexport function wooMoney(value: number | null | undefined): string {\n return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(2) : ''\n}\n\n/** Integer cents as WooCommerce money. */\nexport const wooCents = (cents: number | null | undefined): string =>\n wooMoney(typeof cents === 'number' && Number.isFinite(cents) ? cents / 100 : 0)\n\n/**\n * A WooCommerce price string as dollars: `null` for blank, `undefined` when\n * it is not a price at all (the caller refuses it).\n */\nexport function readWooMoney(value: unknown): number | null | undefined {\n if (value === null || value === undefined || value === '') return null\n const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : ''\n if (!/^\\d+(\\.\\d{1,4})?$/.test(text)) return undefined\n return Math.round(Number(text) * 100) / 100\n}\n\n/** A moment as WooCommerce dates it: no zone, seconds precision, UTC. */\nexport function wooDate(ms: number | null | undefined): string | null {\n if (typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0) return null\n return new Date(ms).toISOString().slice(0, 19)\n}\n\n/** A WooCommerce `after`/`before` filter as epoch ms; a zoneless date is UTC, as this store's dates are. */\nexport function readWooDate(value: string | null): number | null {\n if (!value) return null\n const text = /([zZ]|[+-]\\d\\d:?\\d\\d)$/.test(value) ? value : `${value}Z`\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** WooCommerce's error envelope. */\nexport function wooError(status: number, code: string, message: string, headers: Record<string, string> = {}): Response {\n return Response.json({ code, message, data: { status } }, { status, headers })\n}\n\nexport const wooNotFound = (message = 'No route was found matching the URL and request method.') =>\n wooError(404, 'rest_no_route', message)\n\nexport const wooInvalidId = (what: 'product' | 'variation' | 'order' | 'webhook' | 'note') =>\n wooError(404, `woocommerce_rest_${what === 'variation' ? 'product_variation' : what === 'note' ? 'order_note' : what}_invalid_id`, 'Invalid ID.')\n\n/** A product or order refusal from the store's own checks, in WooCommerce's words. */\nexport function wooRefusalFrom(response: { status: number; body: unknown }): Response {\n const error = (response.body as { error?: { message?: string; fields?: Record<string, string> } } | null)?.error\n const fields = error?.fields ? Object.entries(error.fields).map(([field, why]) => `${field}: ${why}`).join('; ') : ''\n const message = [error?.message ?? 'The request was refused.', fields].filter(Boolean).join(' — ')\n const status = response.status >= 400 ? response.status : 400\n const code = status === 404 ? 'woocommerce_rest_invalid_id' : status === 403 ? 'woocommerce_rest_cannot_create' : 'woocommerce_rest_invalid_param'\n return wooError(status, code, message)\n}\n\n// ── Pagination ──────────────────────────────────────────────────────────────\n\nexport interface WooPage {\n page: number\n perPage: number\n offset: number\n}\n\n/** `page`, `per_page` (1–100, default 10) and `offset`, as WooCommerce reads them. */\nexport function readWooPage(search: URLSearchParams): WooPage {\n const perPageRaw = Number(search.get('per_page') ?? 10)\n const perPage = Number.isInteger(perPageRaw) ? Math.min(100, Math.max(1, perPageRaw)) : 10\n const pageRaw = Number(search.get('page') ?? 1)\n const page = Number.isInteger(pageRaw) && pageRaw > 0 ? pageRaw : 1\n const offsetRaw = Number(search.get('offset') ?? NaN)\n const offset = Number.isInteger(offsetRaw) && offsetRaw >= 0 ? offsetRaw : (page - 1) * perPage\n return { page, perPage, offset }\n}\n\n/** One page of a list, with the headers WordPress sets on every collection. */\nexport function wooPaged<T>(items: readonly T[], page: WooPage, extra: Record<string, string> = {}): Response {\n const total = items.length\n const totalPages = Math.max(1, Math.ceil(total / page.perPage))\n return Response.json(items.slice(page.offset, page.offset + page.perPage), {\n headers: { 'X-WP-Total': String(total), 'X-WP-TotalPages': String(totalPages), ...extra },\n })\n}\n\n// ── Statuses ────────────────────────────────────────────────────────────────\n\n/** An order's status as WooCommerce names it. */\nexport function wooOrderStatus(status: unknown): string {\n switch (status) {\n case 'paid':\n case 'partially_fulfilled':\n return 'processing'\n case 'fulfilled':\n case 'delivered':\n return 'completed'\n case 'cancelled':\n return 'cancelled'\n case 'refunded':\n return 'refunded'\n default:\n return 'pending'\n }\n}\n\n/**\n * The store statuses a WooCommerce `status` filter means. `any` (or none) is\n * every status; `on-hold`, `failed`, `checkout-draft` and `trash` match none,\n * because no order here is ever in them.\n */\nexport function storeStatusesForWooFilter(filter: string | null): ReadonlySet<string> | null {\n const names = String(filter ?? '')\n .split(',')\n .map((name) => name.trim().replace(/^wc-/, ''))\n .filter(Boolean)\n if (!names.length || names.includes('any')) return null\n const statuses = new Set<string>()\n for (const name of names) {\n if (name === 'processing') ['paid', 'partially_fulfilled'].forEach((s) => statuses.add(s))\n else if (name === 'completed') ['fulfilled', 'delivered'].forEach((s) => statuses.add(s))\n else if (name === 'pending' || name === 'cancelled' || name === 'refunded') statuses.add(name)\n }\n return statuses\n}\n\n/** A product's status as WooCommerce names it. */\nexport const wooProductStatus = (status: unknown): string =>\n status === 'active' ? 'publish' : status === 'archived' ? 'private' : 'draft'\n\n/** A WooCommerce product status as the store's: only `publish` is on sale. */\nexport function storeProductStatus(status: unknown): 'active' | 'draft' | 'archived' | undefined {\n if (status === undefined || status === null || status === '') return undefined\n if (status === 'publish') return 'active'\n if (status === 'private' || status === 'trash') return 'archived'\n return 'draft'\n}\n\n// ── Products ────────────────────────────────────────────────────────────────\n\nexport interface WooProductIds {\n product: number\n /** Variant id → its WooCommerce variation id. */\n variants: ReadonlyMap<string, number>\n}\n\ninterface StoreVariant {\n id?: string\n options?: Record<string, string>\n sku?: string\n priceUsd?: number\n compareAtPriceUsd?: number\n weightGrams?: number\n inventory?: number | null\n imageUrl?: string\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n\nfunction variantsOf(data: Record<string, unknown>): StoreVariant[] {\n return Array.isArray(data['variants']) ? (data['variants'] as StoreVariant[]) : []\n}\n\nfunction optionsOf(data: Record<string, unknown>): Array<{ name: string; values: string[] }> {\n return Array.isArray(data['options'])\n ? (data['options'] as Array<Record<string, unknown>>)\n .filter(isRecord)\n .map((option) => ({ name: String(option['name'] ?? ''), values: Array.isArray(option['values']) ? option['values'].map(String) : [] }))\n : []\n}\n\n/** A stable small integer for an image, from its address. */\nexport function wooImageId(src: string): number {\n let hash = 0\n for (let index = 0; index < src.length; index += 1) hash = (hash * 31 + src.charCodeAt(index)) | 0\n return (Math.abs(hash) % 900_000_000) + 100_000\n}\n\n/**\n * An image as WooCommerce answers it. A library file is stored by its\n * site-relative address, so an app is sent it absolute, on the store's own\n * address; its id stays the stored address's.\n */\nfunction wooImage(src: string, position: number, name: string, origin: string) {\n const absolute = absoluteMediaSrc(src, { origin }) ?? src\n return { id: wooImageId(src), src: absolute, name, alt: name, position, date_created: null, date_created_gmt: null }\n}\n\n/** A weight as WooCommerce writes it, in the store's unit: grams (`woocommerce_weight_unit`). */\nconst gramsText = (grams: number | undefined): string =>\n typeof grams === 'number' && Number.isFinite(grams) ? String(Math.round(grams)) : ''\n\nfunction stockOf(variants: readonly StoreVariant[]) {\n const tracked = variants.filter((variant) => typeof variant.inventory === 'number')\n if (!tracked.length) return { manage_stock: false, stock_quantity: null, stock_status: 'instock' }\n const total = tracked.reduce((sum, variant) => sum + Number(variant.inventory ?? 0), 0)\n return { manage_stock: true, stock_quantity: total, stock_status: total > 0 ? 'instock' : 'outofstock' }\n}\n\n/** The prices of one variant in WooCommerce's three fields. */\nfunction pricesOf(variant: StoreVariant | undefined) {\n const price = typeof variant?.priceUsd === 'number' ? variant.priceUsd : null\n const compare = typeof variant?.compareAtPriceUsd === 'number' ? variant.compareAtPriceUsd : null\n const onSale = price !== null && compare !== null && compare > price\n return {\n price: wooMoney(price),\n regular_price: wooMoney(onSale ? compare : price),\n sale_price: onSale ? wooMoney(price) : '',\n on_sale: onSale,\n purchasable: price !== null,\n }\n}\n\nexport interface WooProductContext {\n /** The store's own address, for `permalink`. */\n origin: string\n categories: ReadonlyMap<string, { id: number; name: string; slug: string }>\n}\n\n/** A product as `GET /wc/v3/products/{id}` answers it. */\nexport function wooProduct(data: Record<string, unknown>, ids: WooProductIds, context: WooProductContext) {\n const variants = variantsOf(data)\n const options = optionsOf(data)\n const variable = options.length > 0\n const name = String(data['name'] ?? '')\n const media = Array.isArray(data['mediaUrls']) ? (data['mediaUrls'] as unknown[]).map(String) : []\n const first = variants[0]\n const created = wooDate(Number(data['createdAtMs'] ?? 0))\n const modified = wooDate(Number(data['updatedAtMs'] ?? data['createdAtMs'] ?? 0))\n const priced = variants.filter((variant) => typeof variant.priceUsd === 'number')\n const lowest = priced.length ? priced.reduce((low, variant) => (Number(variant.priceUsd) < Number(low.priceUsd) ? variant : low)) : undefined\n const categoryIds = Array.isArray(data['categoryIds']) ? (data['categoryIds'] as unknown[]).map(String) : []\n return {\n id: ids.product,\n name,\n slug: String(data['slug'] ?? ''),\n permalink: data['slug'] ? `${context.origin}/products/${String(data['slug'])}` : context.origin,\n date_created: created,\n date_created_gmt: created,\n date_modified: modified,\n date_modified_gmt: modified,\n type: variable ? 'variable' : 'simple',\n status: wooProductStatus(data['status']),\n featured: false,\n catalog_visibility: 'visible',\n description: String(data['description'] ?? ''),\n short_description: '',\n sku: variable ? '' : String(first?.sku ?? ''),\n ...pricesOf(variable ? lowest : first),\n total_sales: 0,\n virtual: data['type'] === 'service',\n downloadable: data['type'] === 'digital',\n downloads: [],\n tax_status: 'taxable',\n tax_class: '',\n ...stockOf(variants),\n backorders: 'no',\n backorders_allowed: false,\n backordered: false,\n sold_individually: false,\n weight: variable ? '' : gramsText(first?.weightGrams),\n dimensions: { length: '', width: '', height: '' },\n shipping_required: data['type'] !== 'service' && data['type'] !== 'digital',\n shipping_taxable: true,\n shipping_class: '',\n shipping_class_id: 0,\n reviews_allowed: false,\n average_rating: '0.00',\n rating_count: 0,\n related_ids: [],\n upsell_ids: [],\n cross_sell_ids: [],\n parent_id: 0,\n purchase_note: '',\n categories: categoryIds\n .map((id) => context.categories.get(id))\n .filter((category): category is { id: number; name: string; slug: string } => Boolean(category)),\n tags: (Array.isArray(data['tags']) ? (data['tags'] as unknown[]).map(String) : []).map((tag) => ({\n id: wooImageId(`tag:${tag}`),\n name: tag,\n slug: tag.toLowerCase().replace(/[^a-z0-9]+/g, '-'),\n })),\n images: media.map((src, position) => wooImage(src, position, name, context.origin)),\n attributes: options.map((option, position) => ({\n id: 0,\n name: option.name,\n position,\n visible: true,\n variation: true,\n options: option.values,\n })),\n default_attributes: [],\n variations: variable ? variants.map((variant) => ids.variants.get(String(variant.id))).filter((id): id is number => typeof id === 'number') : [],\n grouped_products: [],\n menu_order: 0,\n meta_data: [],\n }\n}\n\n/** One variant as `GET /wc/v3/products/{id}/variations/{vid}` answers it. */\nexport function wooVariation(\n data: Record<string, unknown>,\n variant: StoreVariant,\n variationId: number,\n context: WooProductContext,\n) {\n const created = wooDate(Number(data['createdAtMs'] ?? 0))\n const modified = wooDate(Number(data['updatedAtMs'] ?? data['createdAtMs'] ?? 0))\n const tracked = typeof variant.inventory === 'number'\n const prices = pricesOf(variant)\n const image = variant.imageUrl ? wooImage(variant.imageUrl, 0, String(data['name'] ?? ''), context.origin) : null\n return {\n id: variationId,\n date_created: created,\n date_created_gmt: created,\n date_modified: modified,\n date_modified_gmt: modified,\n description: '',\n permalink: data['slug'] ? `${context.origin}/products/${String(data['slug'])}` : context.origin,\n sku: String(variant.sku ?? ''),\n ...prices,\n status: prices.purchasable ? 'publish' : 'private',\n virtual: data['type'] === 'service',\n downloadable: false,\n downloads: [],\n tax_status: 'taxable',\n tax_class: '',\n manage_stock: tracked,\n stock_quantity: tracked ? Number(variant.inventory) : null,\n stock_status: tracked && Number(variant.inventory) <= 0 ? 'outofstock' : 'instock',\n backorders: 'no',\n backorders_allowed: false,\n backordered: false,\n weight: gramsText(variant.weightGrams),\n dimensions: { length: '', width: '', height: '' },\n shipping_class: '',\n shipping_class_id: 0,\n image,\n attributes: Object.entries(variant.options ?? {}).map(([name, option]) => ({ id: 0, name, option })),\n menu_order: 0,\n meta_data: [],\n }\n}\n\n// ── Reading a product write ─────────────────────────────────────────────────\n\n/** An attribute as a WooCommerce write names one. */\ninterface WooAttributeIn {\n name: string\n options: string[]\n variation: boolean\n}\n\nfunction readAttributes(value: unknown): WooAttributeIn[] | null {\n if (!Array.isArray(value)) return null\n return value.filter(isRecord).map((attribute) => ({\n name: String(attribute['name'] ?? '').trim(),\n options: (Array.isArray(attribute['options'])\n ? attribute['options']\n : typeof attribute['option'] === 'string'\n ? [attribute['option']]\n : []\n )\n .map((option) => String(option).trim())\n .filter(Boolean),\n // WooCommerce's own default for an attribute sent without the flag is\n // false; an app that sends variations always sets it.\n variation: attribute['variation'] === true,\n }))\n}\n\n/** The prices of a WooCommerce write as the store's variant write. */\nexport function variantWriteFromWoo(body: Record<string, unknown>): { write: VariantWrite } | { error: string } {\n const write: VariantWrite = {}\n const regular = 'regular_price' in body ? readWooMoney(body['regular_price']) : undefined\n const sale = 'sale_price' in body ? readWooMoney(body['sale_price']) : undefined\n if ('regular_price' in body && regular === undefined) return { error: 'regular_price is not a price' }\n if ('sale_price' in body && sale === undefined) return { error: 'sale_price is not a price' }\n if (typeof sale === 'number' && typeof regular === 'number' && sale < regular) {\n write.priceUsd = sale\n write.compareAtPriceUsd = regular\n } else if ('regular_price' in body) {\n write.priceUsd = regular ?? null\n write.compareAtPriceUsd = null\n } else if (typeof sale === 'number') {\n write.priceUsd = sale\n }\n if (typeof body['sku'] === 'string') write.sku = body['sku'].trim() || null\n if ('weight' in body) {\n const grams = readWooMoney(body['weight'])\n if (grams === undefined) return { error: 'weight is not a number' }\n write.weightGrams = grams === null ? null : Math.round(grams)\n }\n if (body['manage_stock'] === false) write.inventory = null\n else if ('stock_quantity' in body && (body['manage_stock'] === true || body['manage_stock'] === undefined)) {\n const quantity = body['stock_quantity']\n if (quantity === null) write.inventory = null\n else if (typeof quantity === 'number' && Number.isInteger(quantity)) write.inventory = Math.max(0, quantity)\n }\n return { write }\n}\n\n/** The images a WooCommerce write names, as addresses, in their order. */\nexport function imagesFromWoo(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n return value\n .filter(isRecord)\n .map((image, index) => ({ src: typeof image['src'] === 'string' ? image['src'].trim() : '', position: Number(image['position'] ?? index) }))\n .filter((image) => /^https?:\\/\\/\\S+$/.test(image.src))\n .sort((a, b) => a.position - b.position)\n .map((image) => image.src)\n}\n\nexport interface ProductWriteFromWoo {\n values: Record<string, unknown>\n /** For a simple product: its one variant's prices, SKU, weight and stock. */\n simpleVariant: VariantWrite | null\n /** WooCommerce category ids the write names, to map to the store's. */\n categoryIds: number[]\n}\n\n/**\n * A WooCommerce product create or update as the body of the store's own\n * product write (`readProductWrite`), plus the one variant a simple product\n * prices. Attributes marked for variations become the product's options, so\n * its variant grid is every combination, as the editor builds it; the other\n * attributes are descriptive in WooCommerce and are not kept.\n */\nexport function productWriteFromWoo(body: Record<string, unknown>, create: boolean): ProductWriteFromWoo | { error: string } {\n const values: Partial<Record<keyof ProductWriteValues, unknown>> = {}\n if (typeof body['name'] === 'string') values.name = body['name']\n else if (create) values.name = 'Untitled product'\n // WooCommerce descriptions are HTML; a product page shows its description\n // as text, so markup is read into text rather than printed.\n const asText = (text: string) => (looksLikeHtml(text) ? htmlDescriptionToText(text) : text)\n if (typeof body['description'] === 'string') values.description = asText(body['description'])\n else if (typeof body['short_description'] === 'string' && create) values.description = asText(body['short_description'])\n const status = storeProductStatus(body['status'])\n // WooCommerce publishes a product created without a status.\n if (status) values.status = status\n else if (create) values.status = 'active'\n if (body['virtual'] === true) values.type = 'service'\n else if (create) values.type = 'physical'\n const images = imagesFromWoo(body['images'])\n if (images) values.mediaUrls = images\n if (Array.isArray(body['tags'])) {\n values.tags = (body['tags'] as unknown[])\n .map((tag) => (isRecord(tag) ? String(tag['name'] ?? tag['slug'] ?? '') : String(tag)))\n .map((tag) => tag.trim())\n .filter(Boolean)\n }\n const attributes = readAttributes(body['attributes'])\n const variationAttributes = attributes?.filter((attribute) => attribute.variation && attribute.name && attribute.options.length) ?? null\n const type = body['type']\n if (variationAttributes && (type === 'variable' || (type === undefined && variationAttributes.length))) {\n values.options = variationAttributes.map((attribute) => ({ name: attribute.name, values: attribute.options }))\n } else if (type === 'simple' && create) {\n values.options = []\n }\n const categoryIds = Array.isArray(body['categories'])\n ? (body['categories'] as unknown[]).filter(isRecord).map((category) => Number(category['id'])).filter((id) => Number.isInteger(id) && id > 0)\n : []\n const variable = Array.isArray(values.options) ? (values.options as unknown[]).length > 0 : type === 'variable'\n let simpleVariant: VariantWrite | null = null\n if (!variable) {\n const read = variantWriteFromWoo(body)\n if ('error' in read) return read\n simpleVariant = Object.keys(read.write).length ? read.write : null\n }\n return { values, simpleVariant, categoryIds }\n}\n\n/**\n * The options one WooCommerce variation names: `{ Color: 'Black', Size: 'M' }`.\n * Attribute names are matched to the product's options without regard to\n * case or a `pa_` prefix, and the product's spelling is kept.\n */\nexport function variationOptionsFromWoo(\n attributes: unknown,\n productOptions: ReadonlyArray<{ name: string; values: string[] }>,\n): Record<string, string> {\n const out: Record<string, string> = {}\n const list = readAttributes(attributes) ?? []\n for (const attribute of list) {\n const option = attribute.options[0]\n if (!attribute.name || !option) continue\n const wanted = attribute.name.toLowerCase().replace(/^pa_/, '')\n const match = productOptions.find((candidate) => candidate.name.toLowerCase() === wanted)\n out[match?.name ?? attribute.name] = match?.values.find((value) => value.toLowerCase() === option.toLowerCase()) ?? option\n }\n return out\n}\n\n/**\n * The product's options with every value a variation names added, so the\n * variation exists in the grid. `null` when nothing is missing.\n */\nexport function optionsWithVariation(\n productOptions: ReadonlyArray<{ name: string; values: string[] }>,\n selection: Record<string, string>,\n): Array<{ name: string; values: string[] }> | null {\n let changed = false\n const next = productOptions.map((option) => ({ name: option.name, values: [...option.values] }))\n for (const [name, value] of Object.entries(selection)) {\n const option = next.find((candidate) => candidate.name === name)\n if (!option) {\n next.push({ name, values: [value] })\n changed = true\n } else if (!option.values.includes(value)) {\n option.values.push(value)\n changed = true\n }\n }\n return changed ? next : null\n}\n\n// ── Orders ──────────────────────────────────────────────────────────────────\n\ninterface StoreAddress {\n name?: string\n line1?: string\n line2?: string\n city?: string\n state?: string\n postalCode?: string\n country?: string\n phone?: string\n}\n\nfunction splitName(name: string | undefined | null): { first_name: string; last_name: string } {\n const parts = String(name ?? '').trim().split(/\\s+/).filter(Boolean)\n return { first_name: parts[0] ?? '', last_name: parts.slice(1).join(' ') }\n}\n\nfunction wooAddress(address: StoreAddress | undefined | null, fallbackName: string | null, phone: string | null) {\n return {\n ...splitName(address?.name ?? fallbackName),\n company: '',\n address_1: String(address?.line1 ?? ''),\n address_2: String(address?.line2 ?? ''),\n city: String(address?.city ?? ''),\n state: String(address?.state ?? ''),\n postcode: String(address?.postalCode ?? ''),\n country: String(address?.country ?? ''),\n phone: String(address?.phone ?? phone ?? ''),\n }\n}\n\nexport interface WooOrderIds {\n order: number\n /** `productId` → WooCommerce product id; `productId|variantId` → variation id. */\n lines: ReadonlyMap<string, number>\n}\n\nexport const lineIdKey = (productId: string, variantId?: string) => (variantId ? `${productId}|${variantId}` : productId)\n\n/** An order as `GET /wc/v3/orders/{id}` answers it. */\nexport function wooOrder(\n orderId: string,\n data: Record<string, unknown>,\n ids: WooOrderIds,\n extras: { meta: Record<string, string>; testMode: boolean },\n) {\n const totals = isRecord(data['totals']) ? data['totals'] : {}\n const createdMs = Number(data['createdAtMs'] ?? 0) || null\n const modifiedMs = Number(data['updatedAtMs'] ?? data['createdAtMs'] ?? 0) || null\n const status = wooOrderStatus(data['status'])\n const lines = Array.isArray(data['lineItems']) ? (data['lineItems'] as Array<Record<string, unknown>>) : []\n const fulfillments = Array.isArray(data['fulfillments']) ? (data['fulfillments'] as Array<Record<string, unknown>>) : []\n const completedMs = fulfillments.map((entry) => Number(entry['atMs'] ?? 0)).filter((ms) => ms > 0).sort((a, b) => b - a)[0] ?? null\n const shippingCents = Number(totals['shippingCents'] ?? 0)\n const email = String(data['customerEmail'] ?? '')\n const phone = typeof data['customerPhone'] === 'string' ? data['customerPhone'] : null\n const name = typeof data['customerName'] === 'string' ? data['customerName'] : null\n const shippingAddress = (isRecord(data['shippingAddress']) ? data['shippingAddress'] : null) as StoreAddress | null\n const billingAddress = (isRecord(data['billingAddress']) ? data['billingAddress'] : shippingAddress) as StoreAddress | null\n const meta: Array<{ id: number; key: string; value: string }> = Object.entries(extras.meta).map(([key, value], index) => ({\n id: index + 1,\n key,\n value,\n }))\n if (extras.testMode) meta.push({ id: meta.length + 1, key: '_aglyn_test_mode', value: 'yes' })\n const paid = status !== 'pending' && status !== 'cancelled'\n return {\n id: ids.order,\n parent_id: 0,\n number: String(typeof data['number'] === 'number' ? data['number'] : ids.order),\n order_key: `wc_order_${orderId}`,\n created_via: data['channel'] === 'pos' ? 'pos' : 'checkout',\n version: WOO_REPORTED_VERSION,\n status,\n currency: 'USD',\n currency_symbol: '$',\n date_created: wooDate(createdMs),\n date_created_gmt: wooDate(createdMs),\n date_modified: wooDate(modifiedMs),\n date_modified_gmt: wooDate(modifiedMs),\n discount_total: wooCents(Number(totals['discountCents'] ?? 0)),\n discount_tax: '0.00',\n shipping_total: wooCents(shippingCents),\n shipping_tax: '0.00',\n cart_tax: wooCents(Number(totals['taxCents'] ?? 0)),\n total: wooCents(Number(totals['totalCents'] ?? data['amountCents'] ?? 0)),\n total_tax: wooCents(Number(totals['taxCents'] ?? 0)),\n prices_include_tax: false,\n customer_id: 0,\n customer_ip_address: '',\n customer_user_agent: '',\n customer_note: '',\n billing: { ...wooAddress(billingAddress, name, phone), email },\n shipping: wooAddress(shippingAddress, name, phone),\n payment_method: paid ? 'aglyn' : '',\n payment_method_title: paid ? 'Card' : '',\n transaction_id: '',\n date_paid: paid ? wooDate(createdMs) : null,\n date_paid_gmt: paid ? wooDate(createdMs) : null,\n date_completed: status === 'completed' ? wooDate(completedMs) : null,\n date_completed_gmt: status === 'completed' ? wooDate(completedMs) : null,\n cart_hash: '',\n meta_data: meta,\n line_items: lines.map((line, index) => {\n const productId = String(line['productId'] ?? '')\n const variantId = typeof line['variantId'] === 'string' ? line['variantId'] : undefined\n const quantity = Number(line['quantity'] ?? 0)\n const unitCents = Number(line['unitAmountCents'] ?? 0)\n const variationId = variantId ? ids.lines.get(lineIdKey(productId, variantId)) ?? 0 : 0\n return {\n id: index + 1,\n name: [line['name'], line['variantLabel']].filter(Boolean).join(' - '),\n product_id: ids.lines.get(productId) ?? 0,\n variation_id: variationId,\n quantity,\n tax_class: '',\n subtotal: wooCents(unitCents * quantity),\n subtotal_tax: '0.00',\n total: wooCents(unitCents * quantity),\n total_tax: '0.00',\n taxes: [],\n meta_data: [],\n sku: String(line['sku'] ?? ''),\n price: unitCents / 100,\n image: { id: '', src: '' },\n parent_name: variationId ? String(line['name'] ?? '') : null,\n }\n }),\n tax_lines: [],\n shipping_lines:\n shippingCents > 0 || shippingAddress\n ? [{ id: 1, method_title: 'Shipping', method_id: 'flat_rate', instance_id: '', total: wooCents(shippingCents), total_tax: '0.00', taxes: [], meta_data: [] }]\n : [],\n fee_lines: [],\n coupon_lines: data['couponCode'] ? [{ id: 1, code: String(data['couponCode']), discount: wooCents(Number(totals['discountCents'] ?? 0)), discount_tax: '0.00', meta_data: [] }] : [],\n refunds: [],\n set_paid: paid,\n needs_payment: !paid,\n needs_processing: status === 'processing',\n is_editable: false,\n }\n}\n\n// ── Tracking written back ───────────────────────────────────────────────────\n\nexport interface WooTracking {\n trackingNumber: string\n carrier: string\n trackingUrl: string\n}\n\nconst TRACKING_NUMBER_KEYS = [\n '_tracking_number',\n 'tracking_number',\n '_wc_shipment_tracking_number',\n '_aftership_tracking_number',\n 'ywot_tracking_code',\n '_tracking_code',\n 'tracking_code',\n]\nconst CARRIER_KEYS = ['_tracking_provider', 'tracking_provider', '_aftership_tracking_provider_name', 'ywot_carrier_name', 'tracking_carrier', 'carrier', 'shipping_carrier']\nconst TRACKING_URL_KEYS = ['_tracking_url', 'tracking_url', 'tracking_link', '_tracking_link', 'ywot_tracking_url']\n\nfunction firstText(meta: Record<string, unknown>, keys: readonly string[]): string {\n for (const key of keys) {\n const value = meta[key]\n if (typeof value === 'string' && value.trim()) return value.trim()\n if (typeof value === 'number') return String(value)\n }\n return ''\n}\n\n/**\n * Tracking from a WooCommerce shipment-tracking entry or from an order's\n * `meta_data`, in the forms the common tracking extensions write it:\n * WooCommerce Shipment Tracking and Advanced Shipment Tracking\n * (`_wc_shipment_tracking_items`), AfterShip, YITH and the bare\n * `tracking_number` many apps set. `null` when none names a number.\n */\nexport function trackingFromWooMeta(meta: Record<string, unknown>): WooTracking | null {\n const items = meta['_wc_shipment_tracking_items']\n const parsedItems = typeof items === 'string' ? safeJson(items) : items\n if (Array.isArray(parsedItems) && parsedItems.length) {\n const last = parsedItems[parsedItems.length - 1]\n if (isRecord(last)) {\n const entry = trackingFromShipmentEntry(last)\n if (entry) return entry\n }\n }\n const trackingNumber = firstText(meta, TRACKING_NUMBER_KEYS)\n if (!trackingNumber) return null\n return { trackingNumber, carrier: firstText(meta, CARRIER_KEYS), trackingUrl: httpsOrBlank(firstText(meta, TRACKING_URL_KEYS)) }\n}\n\n/** One shipment-tracking entry (`tracking_number`, `tracking_provider`, `tracking_link`, …). */\nexport function trackingFromShipmentEntry(entry: Record<string, unknown>): WooTracking | null {\n const trackingNumber = firstText(entry, ['tracking_number'])\n if (!trackingNumber) return null\n return {\n trackingNumber,\n carrier: firstText(entry, ['custom_tracking_provider', 'tracking_provider', 'tracking_provider_name', 'formatted_tracking_provider']),\n trackingUrl: httpsOrBlank(firstText(entry, ['custom_tracking_link', 'tracking_link', 'formatted_tracking_link'])),\n }\n}\n\n/** `meta_data: [{ key, value }]` as a map; later entries win, as WooCommerce's update does. */\nexport function metaMap(value: unknown): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n if (!Array.isArray(value)) return out\n for (const entry of value) {\n if (isRecord(entry) && typeof entry['key'] === 'string') out[entry['key']] = entry['value']\n }\n return out\n}\n\nconst KNOWN_CARRIERS: ReadonlyArray<[RegExp, string]> = [\n [/\\busps\\b/i, 'USPS'],\n [/\\bups\\b/i, 'UPS'],\n [/\\bfed ?ex\\b/i, 'FedEx'],\n [/\\bdhl\\b/i, 'DHL'],\n [/\\byun ?express\\b/i, 'YunExpress'],\n [/\\bcanada post\\b/i, 'Canada Post'],\n]\n\n/**\n * Tracking in an order note's text, as fulfillment apps write it:\n * \"Tracking number: 9400…\", \"tracking no. LX123…\", or a link to a carrier's\n * tracking page. `null` when the note names no number.\n */\nexport function trackingFromNote(note: string): WooTracking | null {\n const text = String(note ?? '').replace(/<[^>]*>/g, ' ')\n const labelled = /tracking\\s*(?:number|no\\.?|#|code|id)?\\s*(?:is|:|-)?\\s*([A-Z0-9][A-Z0-9-]{7,39})\\b/gi\n let fromLabel = ''\n for (const match of text.matchAll(labelled)) {\n if (/\\d/.test(match[1])) {\n fromLabel = match[1]\n break\n }\n }\n const link = /(https:\\/\\/[^\\s\"'<>]+)/i.exec(text)\n const trackingNumber = fromLabel || (link ? trackingNumberInLink(link[1]) : '')\n if (!trackingNumber || !/\\d/.test(trackingNumber)) return null\n const carrier = KNOWN_CARRIERS.find(([pattern]) => pattern.test(text))?.[1] ?? ''\n return { trackingNumber, carrier, trackingUrl: link ? httpsOrBlank(link[1]) : '' }\n}\n\nfunction trackingNumberInLink(href: string): string {\n try {\n const url = new URL(href)\n for (const name of ['tracknum', 'tracking_number', 'trackingNumber', 'tLabels', 'tracknumbers', 'trknbr', 'number', 'nums', 'id']) {\n const value = url.searchParams.get(name)\n if (value && /^[A-Z0-9-]{8,40}$/i.test(value)) return value\n }\n const last = url.pathname.split('/').filter(Boolean).pop() ?? ''\n return /^[A-Z0-9-]{8,40}$/i.test(last) && /\\d/.test(last) ? last : ''\n } catch {\n return ''\n }\n}\n\nfunction httpsOrBlank(value: string): string {\n return /^https:\\/\\/\\S+$/i.test(value) ? value.slice(0, 2048) : ''\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return null\n }\n}\n\n// ── The store as WooCommerce describes itself ───────────────────────────────\n\n/**\n * The WooCommerce version this surface reports. Apps gate features on it;\n * this is the line whose REST API v3 the surface follows.\n */\nexport const WOO_REPORTED_VERSION = '9.4.0'\nexport const WP_REPORTED_VERSION = '6.7'\n\n/** The REST namespaces the store's `/wp-json/` index lists. */\nexport const WOO_NAMESPACES = ['wc/v3', 'wc/v2', 'wc-shipment-tracking/v3', 'wc-auth/v1'] as const\n"],"names":["htmlDescriptionToText","looksLikeHtml","absoluteMediaSrc","wooMoney","value","Number","isFinite","toFixed","wooCents","cents","readWooMoney","undefined","text","String","trim","test","Math","round","wooDate","ms","Date","toISOString","slice","readWooDate","parse","wooError","status","code","message","headers","Response","json","data","wooNotFound","wooInvalidId","what","wooRefusalFrom","response","error","body","fields","Object","entries","map","field","why","join","filter","Boolean","readWooPage","search","perPageRaw","get","perPage","isInteger","min","max","pageRaw","page","offsetRaw","NaN","offset","wooPaged","items","extra","total","length","totalPages","ceil","wooOrderStatus","storeStatusesForWooFilter","names","split","name","replace","includes","statuses","Set","forEach","s","add","wooProductStatus","storeProductStatus","isRecord","Array","isArray","variantsOf","optionsOf","option","values","wooImageId","src","hash","index","charCodeAt","abs","wooImage","position","origin","absolute","id","alt","date_created","date_created_gmt","gramsText","grams","stockOf","variants","tracked","variant","inventory","manage_stock","stock_quantity","stock_status","reduce","sum","pricesOf","price","priceUsd","compare","compareAtPriceUsd","onSale","regular_price","sale_price","on_sale","purchasable","wooProduct","ids","context","options","variable","media","first","created","modified","priced","lowest","low","categoryIds","product","slug","permalink","date_modified","date_modified_gmt","type","featured","catalog_visibility","description","short_description","sku","total_sales","virtual","downloadable","downloads","tax_status","tax_class","backorders","backorders_allowed","backordered","sold_individually","weight","weightGrams","dimensions","width","height","shipping_required","shipping_taxable","shipping_class","shipping_class_id","reviews_allowed","average_rating","rating_count","related_ids","upsell_ids","cross_sell_ids","parent_id","purchase_note","categories","category","tags","tag","toLowerCase","images","attributes","visible","variation","default_attributes","variations","grouped_products","menu_order","meta_data","wooVariation","variationId","prices","image","imageUrl","readAttributes","attribute","variantWriteFromWoo","write","regular","sale","quantity","imagesFromWoo","sort","a","b","productWriteFromWoo","create","asText","mediaUrls","variationAttributes","simpleVariant","read","keys","variationOptionsFromWoo","productOptions","out","list","wanted","match","find","candidate","optionsWithVariation","selection","changed","next","push","splitName","parts","first_name","last_name","wooAddress","address","fallbackName","phone","company","address_1","line1","address_2","line2","city","state","postcode","postalCode","country","lineIdKey","productId","variantId","wooOrder","orderId","extras","fulfillments","totals","createdMs","modifiedMs","lines","completedMs","entry","shippingCents","email","shippingAddress","billingAddress","meta","key","testMode","paid","order","number","order_key","created_via","version","WOO_REPORTED_VERSION","currency","currency_symbol","discount_total","discount_tax","shipping_total","shipping_tax","cart_tax","total_tax","prices_include_tax","customer_id","customer_ip_address","customer_user_agent","customer_note","billing","shipping","payment_method","payment_method_title","transaction_id","date_paid","date_paid_gmt","date_completed","date_completed_gmt","cart_hash","line_items","line","unitCents","product_id","variation_id","subtotal","subtotal_tax","taxes","parent_name","tax_lines","shipping_lines","method_title","method_id","instance_id","fee_lines","coupon_lines","discount","refunds","set_paid","needs_payment","needs_processing","is_editable","TRACKING_NUMBER_KEYS","CARRIER_KEYS","TRACKING_URL_KEYS","firstText","trackingFromWooMeta","parsedItems","safeJson","last","trackingFromShipmentEntry","trackingNumber","carrier","trackingUrl","httpsOrBlank","metaMap","KNOWN_CARRIERS","trackingFromNote","note","labelled","fromLabel","matchAll","link","exec","trackingNumberInLink","pattern","href","url","URL","searchParams","pathname","pop","JSON","WP_REPORTED_VERSION","WOO_NAMESPACES"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;2CAe2C,GAE3C,SAASA,qBAAqB,EAAEC,aAAa,QAAQ,+CAA8C;AACnG,SAASC,gBAAgB,QAAQ,mCAAkC;AAGnE,+EAA+E;AAE/E,qEAAq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AC,CAAC,CAACwH,QAAQ,GAAKA,QAAQtU,IAAI,CAACH,2BAAhDgU,oBAAwD,CAAC,EAAE,mBAAI;IAC/E,OAAO;QAAEL;QAAgBC;QAASC,aAAaS,OAAOR,aAAaQ,IAAI,CAAC,EAAE,IAAI;IAAG;AACnF;AAEA,SAASE,qBAAqBE,IAAY;IACxC,IAAI;YAMWC;QALb,MAAMA,MAAM,IAAIC,IAAIF;QACpB,KAAK,MAAM7Q,QAAQ;YAAC;YAAY;YAAmB;YAAkB;YAAW;YAAgB;YAAU;YAAU;YAAQ;SAAK,CAAE;YACjI,MAAMrE,QAAQmV,IAAIE,YAAY,CAACrS,GAAG,CAACqB;YACnC,IAAIrE,SAAS,qBAAqBW,IAAI,CAACX,QAAQ,OAAOA;QACxD;QACA,MAAMiU,QAAOkB,iCAAAA,IAAIG,QAAQ,CAAClR,KAAK,CAAC,KAAKzB,MAAM,CAACC,SAAS2S,GAAG,cAA3CJ,iCAAiD;QAC9D,OAAO,qBAAqBxU,IAAI,CAACsT,SAAS,KAAKtT,IAAI,CAACsT,QAAQA,OAAO;IACrE,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASK,aAAatU,KAAa;IACjC,OAAO,mBAAmBW,IAAI,CAACX,SAASA,MAAMkB,KAAK,CAAC,GAAG,QAAQ;AACjE;AAEA,SAAS8S,SAASxT,IAAY;IAC5B,IAAI;QACF,OAAOgV,KAAKpU,KAAK,CAACZ;IACpB,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,+EAA+E;AAE/E;;;CAGC,GACD,OAAO,MAAMoQ,uBAAuB,QAAO;AAC3C,OAAO,MAAM6E,sBAAsB,MAAK;AAExC,6DAA6D,GAC7D,OAAO,MAAMC,iBAAiB;IAAC;IAAS;IAAS;IAA2B;CAAa,CAAS"}
|
|
@@ -21,8 +21,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
21
21
|
* WooCommerce store they can work with: the WordPress REST index
|
|
22
22
|
* (`/wp-json/`), the `wc/v3` namespace index, `system_status`, the general
|
|
23
23
|
* settings (currency, units, address), and the webhooks they register. Every
|
|
24
|
-
* store here sells in US dollars with weights in
|
|
25
|
-
* and reports UTC, so dates need no conversion.
|
|
24
|
+
* store here sells in US dollars with weights in grams, the unit the store
|
|
25
|
+
* keeps them in, and reports UTC, so dates need no conversion. The weight
|
|
26
|
+
* unit is answered wherever WooCommerce answers it, `settings/products`
|
|
27
|
+
* included: an app that can't read it guesses, and its guess may be wrong.
|
|
26
28
|
*=========================================*/ import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
|
|
27
29
|
import { randomBytes } from "node:crypto";
|
|
28
30
|
import { readWebhooks, writeWebhooks } from "./woo-meta.js";
|
|
@@ -127,7 +129,7 @@ function generalSettings(store) {
|
|
|
127
129
|
setting('woocommerce_price_thousand_sep', 'Thousand separator', ','),
|
|
128
130
|
setting('woocommerce_price_decimal_sep', 'Decimal separator', '.'),
|
|
129
131
|
setting('woocommerce_price_num_decimals', 'Number of decimals', '2'),
|
|
130
|
-
setting('woocommerce_weight_unit', 'Weight unit', '
|
|
132
|
+
setting('woocommerce_weight_unit', 'Weight unit', 'g'),
|
|
131
133
|
setting('woocommerce_dimension_unit', 'Dimensions unit', 'cm'),
|
|
132
134
|
setting('woocommerce_calc_taxes', 'Enable taxes', 'yes')
|
|
133
135
|
];
|
|
@@ -317,8 +319,11 @@ function shapeWebhook(hook) {
|
|
|
317
319
|
const one = settings.find((setting)=>setting.id === third);
|
|
318
320
|
return one ? Response.json(one) : wooError(404, 'rest_setting_setting_invalid', 'Invalid setting.');
|
|
319
321
|
}
|
|
320
|
-
if (second === 'products'
|
|
321
|
-
|
|
322
|
+
if (second === 'products') {
|
|
323
|
+
const settings = generalSettings(store).filter((setting)=>/weight|dimension/.test(setting.id));
|
|
324
|
+
if (third === undefined) return Response.json(settings);
|
|
325
|
+
const one = settings.find((setting)=>setting.id === third);
|
|
326
|
+
return one ? Response.json(one) : wooError(404, 'rest_setting_setting_invalid', 'Invalid setting.');
|
|
322
327
|
}
|
|
323
328
|
}
|
|
324
329
|
if (first === 'data' && second === 'currencies' && third === 'current' && get) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-system.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE STORE AS WOOCOMMERCE DESCRIBES ITSELF.\n *\n * What apps read when they first connect, to decide the store is a\n * WooCommerce store they can work with: the WordPress REST index\n * (`/wp-json/`), the `wc/v3` namespace index, `system_status`, the general\n * settings (currency, units, address), and the webhooks they register. Every\n * store here sells in US dollars with weights in kilograms on this surface,\n * and reports UTC, so dates need no conversion.\n *=========================================*/\n\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { randomBytes } from 'node:crypto'\nimport type { WooRequestContext } from './woo-context'\nimport { readWebhooks, type StoredWebhook, writeWebhooks } from './woo-meta'\nimport { readWooPage, WOO_NAMESPACES, WOO_REPORTED_VERSION, wooDate, wooError, wooInvalidId, wooPaged, WP_REPORTED_VERSION } from './woo-shapes'\n\nexport interface WooStoreFacts {\n name: string\n origin: string\n address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string }\n}\n\n/** `GET /wp-json/`: the WordPress REST index, with the namespaces this store answers. */\nexport function wpJsonIndex(store: WooStoreFacts): Response {\n return Response.json({\n name: store.name,\n description: '',\n url: store.origin,\n home: store.origin,\n gmt_offset: 0,\n timezone_string: 'UTC',\n namespaces: [...WOO_NAMESPACES],\n authentication: [],\n routes: Object.fromEntries(\n WOO_NAMESPACES.map((namespace) => [`/${namespace}`, { namespace, methods: ['GET'], endpoints: [{ methods: ['GET'], args: {} }] }]),\n ),\n _links: { help: [{ href: 'https://docs.aglyn.com' }] },\n })\n}\n\nconst WC_V3_ROUTES = [\n '/wc/v3/products',\n '/wc/v3/products/(?P<id>[\\\\d]+)',\n '/wc/v3/products/batch',\n '/wc/v3/products/(?P<product_id>[\\\\d]+)/variations',\n '/wc/v3/products/(?P<product_id>[\\\\d]+)/variations/(?P<id>[\\\\d]+)',\n '/wc/v3/products/(?P<product_id>[\\\\d]+)/variations/batch',\n '/wc/v3/products/categories',\n '/wc/v3/orders',\n '/wc/v3/orders/(?P<id>[\\\\d]+)',\n '/wc/v3/orders/(?P<order_id>[\\\\d]+)/notes',\n '/wc/v3/orders/(?P<order_id>[\\\\d]+)/shipment-trackings',\n '/wc/v3/webhooks',\n '/wc/v3/webhooks/(?P<id>[\\\\d]+)',\n '/wc/v3/system_status',\n '/wc/v3/settings',\n '/wc/v3/settings/general',\n '/wc/v3/data/currencies/current',\n]\n\n/** `GET /wp-json/wc/v3`: the namespace index. */\nexport function wcNamespaceIndex(namespace: string): Response {\n return Response.json({\n namespace,\n routes: Object.fromEntries(\n WC_V3_ROUTES.map((route) => [route.replace('/wc/v3', `/${namespace}`), { namespace, methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }]),\n ),\n })\n}\n\nfunction generalSettings(store: WooStoreFacts) {\n const address = store.address ?? {}\n const setting = (id: string, label: string, value: string) => ({ id, label, description: '', type: 'text', default: '', value })\n return [\n setting('woocommerce_store_address', 'Address line 1', String(address.line1 ?? '')),\n setting('woocommerce_store_address_2', 'Address line 2', String(address.line2 ?? '')),\n setting('woocommerce_store_city', 'City', String(address.city ?? '')),\n setting('woocommerce_default_country', 'Country / State', [address.country, address.state].filter(Boolean).join(':') || 'US'),\n setting('woocommerce_store_postcode', 'Postcode / ZIP', String(address.postalCode ?? '')),\n setting('woocommerce_currency', 'Currency', 'USD'),\n setting('woocommerce_currency_pos', 'Currency position', 'left'),\n setting('woocommerce_price_thousand_sep', 'Thousand separator', ','),\n setting('woocommerce_price_decimal_sep', 'Decimal separator', '.'),\n setting('woocommerce_price_num_decimals', 'Number of decimals', '2'),\n setting('woocommerce_weight_unit', 'Weight unit', 'kg'),\n setting('woocommerce_dimension_unit', 'Dimensions unit', 'cm'),\n setting('woocommerce_calc_taxes', 'Enable taxes', 'yes'),\n ]\n}\n\nfunction systemStatus(store: WooStoreFacts) {\n return {\n environment: {\n home_url: store.origin,\n site_url: store.origin,\n version: WOO_REPORTED_VERSION,\n wp_version: WP_REPORTED_VERSION,\n wp_multisite: false,\n wp_memory_limit: 268435456,\n wp_debug_mode: false,\n wp_cron: true,\n language: 'en_US',\n external_object_cache: null,\n server_info: PLATFORM_BRAND_NAME,\n php_version: '8.3',\n max_upload_size: 10485760,\n default_timezone: 'UTC',\n remote_post_successful: true,\n remote_get_successful: true,\n secure_connection: true,\n hide_errors: true,\n },\n database: { wc_database_version: WOO_REPORTED_VERSION },\n active_plugins: [\n { plugin: 'woocommerce/woocommerce.php', name: 'WooCommerce', version: WOO_REPORTED_VERSION, url: 'https://woocommerce.com', author_name: 'Automattic', network_activated: false },\n ],\n inactive_plugins: [],\n dropins_mu_plugins: { dropins: [], mu_plugins: [] },\n theme: { name: PLATFORM_BRAND_NAME, version: '1', has_woocommerce_support: true, has_woocommerce_file: false, has_outdated_templates: false, overrides: [] },\n settings: {\n api_enabled: true,\n force_ssl: true,\n currency: 'USD',\n currency_symbol: '$',\n currency_position: 'left',\n thousand_separator: ',',\n decimal_separator: '.',\n number_of_decimals: 2,\n geolocation_enabled: false,\n taxonomies: { external: 'external', grouped: 'grouped', simple: 'simple', variable: 'variable' },\n product_visibility_terms: {},\n woocommerce_com_connected: 'no',\n },\n security: { secure_connection: true, hide_errors: true },\n pages: [],\n post_type_counts: [],\n }\n}\n\nfunction shapeWebhook(hook: StoredWebhook) {\n const [resource, event] = hook.topic.split('.')\n return {\n id: hook.id,\n name: hook.name,\n status: hook.status,\n topic: hook.topic,\n resource: resource ?? '',\n event: event ?? '',\n hooks: [],\n delivery_url: hook.delivery_url,\n date_created: wooDate(hook.atMs),\n date_created_gmt: wooDate(hook.atMs),\n date_modified: wooDate(hook.atMs),\n date_modified_gmt: wooDate(hook.atMs),\n }\n}\n\n/**\n * `webhooks…`: registered, listed, changed and deleted as WooCommerce does.\n * Order topics are delivered from the store's order events\n * (`woo-webhooks.ts`); a hook saved active is pinged first, as WooCommerce\n * pings it.\n */\nasync function webhooks(ctx: WooRequestContext, raw: string | undefined): Promise<Response | null> {\n const method = ctx.request.method\n const list = await readWebhooks(ctx.api.firestore, ctx.hostId)\n if (raw === undefined) {\n if (method === 'GET') return wooPaged(list.map(shapeWebhook), readWooPage(ctx.url.searchParams))\n if (method !== 'POST') return null\n const topic = typeof ctx.body['topic'] === 'string' ? ctx.body['topic'] : ''\n const deliveryUrl = typeof ctx.body['delivery_url'] === 'string' ? ctx.body['delivery_url'] : ''\n if (!/^[a-z_]+\\.[a-z_]+$/.test(topic) || !/^https:\\/\\/\\S+$/.test(deliveryUrl)) {\n return wooError(400, 'woocommerce_rest_invalid_param', 'A webhook needs a topic such as order.created and an https delivery_url.')\n }\n const hook: StoredWebhook = {\n id: list.reduce((max, entry) => Math.max(max, entry.id), 0) + 1,\n name: typeof ctx.body['name'] === 'string' ? ctx.body['name'].slice(0, 120) : topic,\n status: 'active',\n topic,\n delivery_url: deliveryUrl.slice(0, 2048),\n secret: typeof ctx.body['secret'] === 'string' ? ctx.body['secret'].slice(0, 200) : randomBytes(16).toString('hex'),\n atMs: Date.now(),\n grantId: ctx.grantId,\n source: ctx.origin,\n }\n if (typeof ctx.body['status'] === 'string' && ['active', 'paused', 'disabled'].includes(ctx.body['status'])) hook.status = ctx.body['status']\n await writeWebhooks(ctx.api.firestore, ctx.hostId, [...list, hook])\n const ping = hook.status === 'active' ? await (await import('./woo-webhooks')).pingWooWebhook(hook, ctx.origin) : null\n ctx.note({ webhookTopic: topic, webhookPing: ping ? ping.status ?? ping.error : null })\n return Response.json(shapeWebhook(hook), { status: 201 })\n }\n const hook = list.find((entry) => entry.id === Number(raw))\n if (!hook) return wooInvalidId('webhook')\n if (method === 'GET') return Response.json(shapeWebhook(hook))\n if (method === 'DELETE') {\n await writeWebhooks(ctx.api.firestore, ctx.hostId, list.filter((entry) => entry !== hook))\n return Response.json(shapeWebhook(hook))\n }\n if (method === 'PUT' || method === 'PATCH' || method === 'POST') {\n const next = {\n ...hook,\n ...(typeof ctx.body['status'] === 'string' ? { status: ctx.body['status'] } : {}),\n ...(typeof ctx.body['delivery_url'] === 'string' && /^https:\\/\\/\\S+$/.test(ctx.body['delivery_url']) ? { delivery_url: ctx.body['delivery_url'] } : {}),\n }\n await writeWebhooks(ctx.api.firestore, ctx.hostId, list.map((entry) => (entry === hook ? next : entry)))\n return Response.json(shapeWebhook(next))\n }\n return null\n}\n\n/** The system routes under `/wc/v3`. `null` when the route is not one. */\nexport async function handleWooSystem(ctx: WooRequestContext, store: WooStoreFacts): Promise<Response | null> {\n const [first, second, third] = ctx.segments\n const get = ctx.request.method === 'GET'\n if (first === 'system_status' && second === undefined && get) return Response.json(systemStatus(store))\n if (first === 'settings' && get) {\n if (second === undefined) {\n return Response.json([\n { id: 'general', label: 'General', description: '', parent_id: '', sub_groups: [] },\n { id: 'products', label: 'Products', description: '', parent_id: '', sub_groups: [] },\n ])\n }\n if (second === 'general') {\n const settings = generalSettings(store)\n if (third === undefined) return Response.json(settings)\n const one = settings.find((setting) => setting.id === third)\n return one ? Response.json(one) : wooError(404, 'rest_setting_setting_invalid', 'Invalid setting.')\n }\n if (second === 'products' && third === undefined) {\n return Response.json(generalSettings(store).filter((setting) => /weight|dimension/.test(setting.id)))\n }\n }\n if (first === 'data' && second === 'currencies' && third === 'current' && get) {\n return Response.json({ code: 'USD', name: 'United States (US) dollar', symbol: '$' })\n }\n if ((first === 'taxes' || first === 'payment_gateways' || first === 'shipping_methods' || first === 'customers') && second === undefined && get) {\n return wooPaged([], readWooPage(ctx.url.searchParams))\n }\n if (first === 'shipping' && second === 'zones' && third === undefined && get) return Response.json([])\n if (first === 'webhooks' && ctx.segments.length <= 2) return webhooks(ctx, second)\n return null\n}\n"],"names":["PLATFORM_BRAND_NAME","randomBytes","readWebhooks","writeWebhooks","readWooPage","WOO_NAMESPACES","WOO_REPORTED_VERSION","wooDate","wooError","wooInvalidId","wooPaged","WP_REPORTED_VERSION","wpJsonIndex","store","Response","json","name","description","url","origin","home","gmt_offset","timezone_string","namespaces","authentication","routes","Object","fromEntries","map","namespace","methods","endpoints","args","_links","help","href","WC_V3_ROUTES","wcNamespaceIndex","route","replace","generalSettings","address","setting","id","label","value","type","default","String","line1","line2","city","country","state","filter","Boolean","join","postalCode","systemStatus","environment","home_url","site_url","version","wp_version","wp_multisite","wp_memory_limit","wp_debug_mode","wp_cron","language","external_object_cache","server_info","php_version","max_upload_size","default_timezone","remote_post_successful","remote_get_successful","secure_connection","hide_errors","database","wc_database_version","active_plugins","plugin","author_name","network_activated","inactive_plugins","dropins_mu_plugins","dropins","mu_plugins","theme","has_woocommerce_support","has_woocommerce_file","has_outdated_templates","overrides","settings","api_enabled","force_ssl","currency","currency_symbol","currency_position","thousand_separator","decimal_separator","number_of_decimals","geolocation_enabled","taxonomies","external","grouped","simple","variable","product_visibility_terms","woocommerce_com_connected","security","pages","post_type_counts","shapeWebhook","hook","resource","event","topic","split","status","hooks","delivery_url","date_created","atMs","date_created_gmt","date_modified","date_modified_gmt","webhooks","ctx","raw","method","request","list","api","firestore","hostId","undefined","ping","searchParams","body","deliveryUrl","test","reduce","max","entry","Math","slice","secret","toString","Date","now","grantId","source","includes","pingWooWebhook","note","webhookTopic","webhookPing","error","find","Number","next","handleWooSystem","first","second","third","segments","get","parent_id","sub_groups","one","code","symbol","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAe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YA,QAAQC,EAAE,KAAK0H;YACtD,OAAOK,MAAM5J,SAASC,IAAI,CAAC2J,OAAOlK,SAAS,KAAK,gCAAgC;QAClF;QACA,IAAI4J,WAAW,cAAcC,UAAU7B,WAAW;YAChD,OAAO1H,SAASC,IAAI,CAACyB,gBAAgB3B,OAAOyC,MAAM,CAAC,CAACZ,UAAY,mBAAmBmG,IAAI,CAACnG,QAAQC,EAAE;QACpG;IACF;IACA,IAAIwH,UAAU,UAAUC,WAAW,gBAAgBC,UAAU,aAAaE,KAAK;QAC7E,OAAOzJ,SAASC,IAAI,CAAC;YAAE4J,MAAM;YAAO3J,MAAM;YAA6B4J,QAAQ;QAAI;IACrF;IACA,IAAI,AAACT,CAAAA,UAAU,WAAWA,UAAU,sBAAsBA,UAAU,sBAAsBA,UAAU,WAAU,KAAMC,WAAW5B,aAAa+B,KAAK;QAC/I,OAAO7J,SAAS,EAAE,EAAEN,YAAY4H,IAAI9G,GAAG,CAACwH,YAAY;IACtD;IACA,IAAIyB,UAAU,cAAcC,WAAW,WAAWC,UAAU7B,aAAa+B,KAAK,OAAOzJ,SAASC,IAAI,CAAC,EAAE;IACrG,IAAIoJ,UAAU,cAAcnC,IAAIsC,QAAQ,CAACO,MAAM,IAAI,GAAG,OAAO9C,SAASC,KAAKoC;IAC3E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-system.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * THE STORE AS WOOCOMMERCE DESCRIBES ITSELF.\n *\n * What apps read when they first connect, to decide the store is a\n * WooCommerce store they can work with: the WordPress REST index\n * (`/wp-json/`), the `wc/v3` namespace index, `system_status`, the general\n * settings (currency, units, address), and the webhooks they register. Every\n * store here sells in US dollars with weights in grams, the unit the store\n * keeps them in, and reports UTC, so dates need no conversion. The weight\n * unit is answered wherever WooCommerce answers it, `settings/products`\n * included: an app that can't read it guesses, and its guess may be wrong.\n *=========================================*/\n\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { randomBytes } from 'node:crypto'\nimport type { WooRequestContext } from './woo-context'\nimport { readWebhooks, type StoredWebhook, writeWebhooks } from './woo-meta'\nimport { readWooPage, WOO_NAMESPACES, WOO_REPORTED_VERSION, wooDate, wooError, wooInvalidId, wooPaged, WP_REPORTED_VERSION } from './woo-shapes'\n\nexport interface WooStoreFacts {\n name: string\n origin: string\n address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string }\n}\n\n/** `GET /wp-json/`: the WordPress REST index, with the namespaces this store answers. */\nexport function wpJsonIndex(store: WooStoreFacts): Response {\n return Response.json({\n name: store.name,\n description: '',\n url: store.origin,\n home: store.origin,\n gmt_offset: 0,\n timezone_string: 'UTC',\n namespaces: [...WOO_NAMESPACES],\n authentication: [],\n routes: Object.fromEntries(\n WOO_NAMESPACES.map((namespace) => [`/${namespace}`, { namespace, methods: ['GET'], endpoints: [{ methods: ['GET'], args: {} }] }]),\n ),\n _links: { help: [{ href: 'https://docs.aglyn.com' }] },\n })\n}\n\nconst WC_V3_ROUTES = [\n '/wc/v3/products',\n '/wc/v3/products/(?P<id>[\\\\d]+)',\n '/wc/v3/products/batch',\n '/wc/v3/products/(?P<product_id>[\\\\d]+)/variations',\n '/wc/v3/products/(?P<product_id>[\\\\d]+)/variations/(?P<id>[\\\\d]+)',\n '/wc/v3/products/(?P<product_id>[\\\\d]+)/variations/batch',\n '/wc/v3/products/categories',\n '/wc/v3/orders',\n '/wc/v3/orders/(?P<id>[\\\\d]+)',\n '/wc/v3/orders/(?P<order_id>[\\\\d]+)/notes',\n '/wc/v3/orders/(?P<order_id>[\\\\d]+)/shipment-trackings',\n '/wc/v3/webhooks',\n '/wc/v3/webhooks/(?P<id>[\\\\d]+)',\n '/wc/v3/system_status',\n '/wc/v3/settings',\n '/wc/v3/settings/general',\n '/wc/v3/data/currencies/current',\n]\n\n/** `GET /wp-json/wc/v3`: the namespace index. */\nexport function wcNamespaceIndex(namespace: string): Response {\n return Response.json({\n namespace,\n routes: Object.fromEntries(\n WC_V3_ROUTES.map((route) => [route.replace('/wc/v3', `/${namespace}`), { namespace, methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }]),\n ),\n })\n}\n\nfunction generalSettings(store: WooStoreFacts) {\n const address = store.address ?? {}\n const setting = (id: string, label: string, value: string) => ({ id, label, description: '', type: 'text', default: '', value })\n return [\n setting('woocommerce_store_address', 'Address line 1', String(address.line1 ?? '')),\n setting('woocommerce_store_address_2', 'Address line 2', String(address.line2 ?? '')),\n setting('woocommerce_store_city', 'City', String(address.city ?? '')),\n setting('woocommerce_default_country', 'Country / State', [address.country, address.state].filter(Boolean).join(':') || 'US'),\n setting('woocommerce_store_postcode', 'Postcode / ZIP', String(address.postalCode ?? '')),\n setting('woocommerce_currency', 'Currency', 'USD'),\n setting('woocommerce_currency_pos', 'Currency position', 'left'),\n setting('woocommerce_price_thousand_sep', 'Thousand separator', ','),\n setting('woocommerce_price_decimal_sep', 'Decimal separator', '.'),\n setting('woocommerce_price_num_decimals', 'Number of decimals', '2'),\n setting('woocommerce_weight_unit', 'Weight unit', 'g'),\n setting('woocommerce_dimension_unit', 'Dimensions unit', 'cm'),\n setting('woocommerce_calc_taxes', 'Enable taxes', 'yes'),\n ]\n}\n\nfunction systemStatus(store: WooStoreFacts) {\n return {\n environment: {\n home_url: store.origin,\n site_url: store.origin,\n version: WOO_REPORTED_VERSION,\n wp_version: WP_REPORTED_VERSION,\n wp_multisite: false,\n wp_memory_limit: 268435456,\n wp_debug_mode: false,\n wp_cron: true,\n language: 'en_US',\n external_object_cache: null,\n server_info: PLATFORM_BRAND_NAME,\n php_version: '8.3',\n max_upload_size: 10485760,\n default_timezone: 'UTC',\n remote_post_successful: true,\n remote_get_successful: true,\n secure_connection: true,\n hide_errors: true,\n },\n database: { wc_database_version: WOO_REPORTED_VERSION },\n active_plugins: [\n { plugin: 'woocommerce/woocommerce.php', name: 'WooCommerce', version: WOO_REPORTED_VERSION, url: 'https://woocommerce.com', author_name: 'Automattic', network_activated: false },\n ],\n inactive_plugins: [],\n dropins_mu_plugins: { dropins: [], mu_plugins: [] },\n theme: { name: PLATFORM_BRAND_NAME, version: '1', has_woocommerce_support: true, has_woocommerce_file: false, has_outdated_templates: false, overrides: [] },\n settings: {\n api_enabled: true,\n force_ssl: true,\n currency: 'USD',\n currency_symbol: '$',\n currency_position: 'left',\n thousand_separator: ',',\n decimal_separator: '.',\n number_of_decimals: 2,\n geolocation_enabled: false,\n taxonomies: { external: 'external', grouped: 'grouped', simple: 'simple', variable: 'variable' },\n product_visibility_terms: {},\n woocommerce_com_connected: 'no',\n },\n security: { secure_connection: true, hide_errors: true },\n pages: [],\n post_type_counts: [],\n }\n}\n\nfunction shapeWebhook(hook: StoredWebhook) {\n const [resource, event] = hook.topic.split('.')\n return {\n id: hook.id,\n name: hook.name,\n status: hook.status,\n topic: hook.topic,\n resource: resource ?? '',\n event: event ?? '',\n hooks: [],\n delivery_url: hook.delivery_url,\n date_created: wooDate(hook.atMs),\n date_created_gmt: wooDate(hook.atMs),\n date_modified: wooDate(hook.atMs),\n date_modified_gmt: wooDate(hook.atMs),\n }\n}\n\n/**\n * `webhooks…`: registered, listed, changed and deleted as WooCommerce does.\n * Order topics are delivered from the store's order events\n * (`woo-webhooks.ts`); a hook saved active is pinged first, as WooCommerce\n * pings it.\n */\nasync function webhooks(ctx: WooRequestContext, raw: string | undefined): Promise<Response | null> {\n const method = ctx.request.method\n const list = await readWebhooks(ctx.api.firestore, ctx.hostId)\n if (raw === undefined) {\n if (method === 'GET') return wooPaged(list.map(shapeWebhook), readWooPage(ctx.url.searchParams))\n if (method !== 'POST') return null\n const topic = typeof ctx.body['topic'] === 'string' ? ctx.body['topic'] : ''\n const deliveryUrl = typeof ctx.body['delivery_url'] === 'string' ? ctx.body['delivery_url'] : ''\n if (!/^[a-z_]+\\.[a-z_]+$/.test(topic) || !/^https:\\/\\/\\S+$/.test(deliveryUrl)) {\n return wooError(400, 'woocommerce_rest_invalid_param', 'A webhook needs a topic such as order.created and an https delivery_url.')\n }\n const hook: StoredWebhook = {\n id: list.reduce((max, entry) => Math.max(max, entry.id), 0) + 1,\n name: typeof ctx.body['name'] === 'string' ? ctx.body['name'].slice(0, 120) : topic,\n status: 'active',\n topic,\n delivery_url: deliveryUrl.slice(0, 2048),\n secret: typeof ctx.body['secret'] === 'string' ? ctx.body['secret'].slice(0, 200) : randomBytes(16).toString('hex'),\n atMs: Date.now(),\n grantId: ctx.grantId,\n source: ctx.origin,\n }\n if (typeof ctx.body['status'] === 'string' && ['active', 'paused', 'disabled'].includes(ctx.body['status'])) hook.status = ctx.body['status']\n await writeWebhooks(ctx.api.firestore, ctx.hostId, [...list, hook])\n const ping = hook.status === 'active' ? await (await import('./woo-webhooks')).pingWooWebhook(hook, ctx.origin) : null\n ctx.note({ webhookTopic: topic, webhookPing: ping ? ping.status ?? ping.error : null })\n return Response.json(shapeWebhook(hook), { status: 201 })\n }\n const hook = list.find((entry) => entry.id === Number(raw))\n if (!hook) return wooInvalidId('webhook')\n if (method === 'GET') return Response.json(shapeWebhook(hook))\n if (method === 'DELETE') {\n await writeWebhooks(ctx.api.firestore, ctx.hostId, list.filter((entry) => entry !== hook))\n return Response.json(shapeWebhook(hook))\n }\n if (method === 'PUT' || method === 'PATCH' || method === 'POST') {\n const next = {\n ...hook,\n ...(typeof ctx.body['status'] === 'string' ? { status: ctx.body['status'] } : {}),\n ...(typeof ctx.body['delivery_url'] === 'string' && /^https:\\/\\/\\S+$/.test(ctx.body['delivery_url']) ? { delivery_url: ctx.body['delivery_url'] } : {}),\n }\n await writeWebhooks(ctx.api.firestore, ctx.hostId, list.map((entry) => (entry === hook ? next : entry)))\n return Response.json(shapeWebhook(next))\n }\n return null\n}\n\n/** The system routes under `/wc/v3`. `null` when the route is not one. */\nexport async function handleWooSystem(ctx: WooRequestContext, store: WooStoreFacts): Promise<Response | null> {\n const [first, second, third] = ctx.segments\n const get = ctx.request.method === 'GET'\n if (first === 'system_status' && second === undefined && get) return Response.json(systemStatus(store))\n if (first === 'settings' && get) {\n if (second === undefined) {\n return Response.json([\n { id: 'general', label: 'General', description: '', parent_id: '', sub_groups: [] },\n { id: 'products', label: 'Products', description: '', parent_id: '', sub_groups: [] },\n ])\n }\n if (second === 'general') {\n const settings = generalSettings(store)\n if (third === undefined) return Response.json(settings)\n const one = settings.find((setting) => setting.id === third)\n return one ? Response.json(one) : wooError(404, 'rest_setting_setting_invalid', 'Invalid setting.')\n }\n if (second === 'products') {\n const settings = generalSettings(store).filter((setting) => /weight|dimension/.test(setting.id))\n if (third === undefined) return Response.json(settings)\n const one = settings.find((setting) => setting.id === third)\n return one ? Response.json(one) : wooError(404, 'rest_setting_setting_invalid', 'Invalid setting.')\n }\n }\n if (first === 'data' && second === 'currencies' && third === 'current' && get) {\n return Response.json({ code: 'USD', name: 'United States (US) dollar', symbol: '$' })\n }\n if ((first === 'taxes' || first === 'payment_gateways' || first === 'shipping_methods' || first === 'customers') && second === undefined && get) {\n return wooPaged([], readWooPage(ctx.url.searchParams))\n }\n if (first === 'shipping' && second === 'zones' && third === undefined && get) return Response.json([])\n if (first === 'webhooks' && ctx.segments.length <= 2) return webhooks(ctx, second)\n return null\n}\n"],"names":["PLATFORM_BRAND_NAME","randomBytes","readWebhooks","writeWebhooks","readWooPage","WOO_NAMESPACES","WOO_REPORTED_VERSION","wooDate","wooError","wooInvalidId","wooPaged","WP_REPORTED_VERSION","wpJsonIndex","store","Response","json","name","description","url","origin","home","gmt_offset","timezone_string","namespaces","authentication","routes","Object","fromEntries","map","namespace","methods","endpoints","args","_links","help","href","WC_V3_ROUTES","wcNamespaceIndex","route","replace","generalSettings","address","setting","id","label","value","type","default","String","line1","line2","city","country","state","filter","Boolean","join","postalCode","systemStatus","environment","home_url","site_url","version","wp_version","wp_multisite","wp_memory_limit","wp_debug_mode","wp_cron","language","external_object_cache","server_info","php_version","max_upload_size","default_timezone","remote_post_successful","remote_get_successful","secure_connection","hide_errors","database","wc_database_version","active_plugins","plugin","author_name","network_activated","inactive_plugins","dropins_mu_plugins","dropins","mu_plugins","theme","has_woocommerce_support","has_woocommerce_file","has_outdated_templates","overrides","settings","api_enabled","force_ssl","currency","currency_symbol","currency_position","thousand_separator","decimal_separator","number_of_decimals","geolocation_enabled","taxonomies","external","grouped","simple","variable","product_visibility_terms","woocommerce_com_connected","security","pages","post_type_counts","shapeWebhook","hook","resource","event","topic","split","status","hooks","delivery_url","date_created","atMs","date_created_gmt","date_modified","date_modified_gmt","webhooks","ctx","raw","method","request","list","api","firestore","hostId","undefined","ping","searchParams","body","deliveryUrl","test","reduce","max","entry","Math","slice","secret","toString","Date","now","grantId","source","includes","pingWooWebhook","note","webhookTopic","webhookPing","error","find","Number","next","handleWooSystem","first","second","third","segments","get","parent_id","sub_groups","one","code","symbol","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;2CAW2C,GAE3C,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,cAAa;AAEzC,SAASC,YAAY,EAAsBC,aAAa,QAAQ,gBAAY;AAC5E,SAASC,WAAW,EAAEC,cAAc,EAAEC,oBAAoB,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,YAAY,EAAEC,QAAQ,EAAEC,mBAAmB,QAAQ,kBAAc;AAQhJ,uFAAuF,GACvF,OAAO,SAASC,YAAYC,KAAoB;IAC9C,OAAOC,SAASC,IAAI,CAAC;QACnBC,MAAMH,MAAM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AAOK,MAAM5J,SAASC,IAAI,CAAC2J,OAAOlK,SAAS,KAAK,gCAAgC;QAClF;IACF;IACA,IAAI2J,UAAU,UAAUC,WAAW,gBAAgBC,UAAU,aAAaE,KAAK;QAC7E,OAAOzJ,SAASC,IAAI,CAAC;YAAE4J,MAAM;YAAO3J,MAAM;YAA6B4J,QAAQ;QAAI;IACrF;IACA,IAAI,AAACT,CAAAA,UAAU,WAAWA,UAAU,sBAAsBA,UAAU,sBAAsBA,UAAU,WAAU,KAAMC,WAAW5B,aAAa+B,KAAK;QAC/I,OAAO7J,SAAS,EAAE,EAAEN,YAAY4H,IAAI9G,GAAG,CAACwH,YAAY;IACtD;IACA,IAAIyB,UAAU,cAAcC,WAAW,WAAWC,UAAU7B,aAAa+B,KAAK,OAAOzJ,SAASC,IAAI,CAAC,EAAE;IACrG,IAAIoJ,UAAU,cAAcnC,IAAIsC,QAAQ,CAACO,MAAM,IAAI,GAAG,OAAO9C,SAASC,KAAKoC;IAC3E,OAAO;AACT"}
|
|
@@ -19,8 +19,12 @@ import { fetchConfiguredPublicUrl } from '@aglyn/tenant-data-admin';
|
|
|
19
19
|
import { type StoredWebhook } from './woo-meta';
|
|
20
20
|
/** How long an app's receiver has to answer, as WooCommerce allows it. */
|
|
21
21
|
export declare const WOO_WEBHOOK_TIMEOUT_MS = 15000;
|
|
22
|
+
/** The WooCommerce status action one store event fires, if any. */
|
|
23
|
+
export declare function wooActionForEvent(event: string): string | null;
|
|
22
24
|
/** The WooCommerce topics one store event is delivered as. */
|
|
23
25
|
export declare function wooTopicsForEvent(event: string): string[];
|
|
26
|
+
/** The body WooCommerce sends an action hook: the hook's name and its argument. */
|
|
27
|
+
export declare function wooActionBody(topic: string, orderId: number | string): string;
|
|
24
28
|
/** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */
|
|
25
29
|
export declare function signWooWebhook(body: string, secret: string): string;
|
|
26
30
|
/** The headers WooCommerce sends with a delivery. */
|
|
@@ -26,8 +26,14 @@
|
|
|
26
26
|
* - `order.paid` → `order.created` and `order.updated`. A store order
|
|
27
27
|
* exists for an app once it is paid: an unpaid checkout is never listed.
|
|
28
28
|
* - fulfilled, delivered, refunded, cancelled → `order.updated`.
|
|
29
|
+
* - each of those also fires WooCommerce's status action, the topic
|
|
30
|
+
* `action.woocommerce_order_status_<status>`: paid is `processing`,
|
|
31
|
+
* fulfilled and delivered are `completed`, then `refunded` and
|
|
32
|
+
* `cancelled`. Fulfillment apps subscribe to the paid one to import an
|
|
33
|
+
* order. WooCommerce sends an action hook `{ action, arg }`, `arg` being
|
|
34
|
+
* the order id, and so does this.
|
|
29
35
|
*
|
|
30
|
-
*
|
|
36
|
+
* A resource hook's body is the order exactly as `GET /wc/v3/orders/{id}` answers it. The
|
|
31
37
|
* headers are WooCommerce's: `X-WC-Webhook-Topic`, `-Resource`, `-Event`,
|
|
32
38
|
* `-ID`, `-Delivery-ID`, `-Source`, and `-Signature`, the base64 HMAC-SHA256
|
|
33
39
|
* of the body under the hook's secret. Each call goes through
|
|
@@ -42,17 +48,35 @@ import { readWebhooks } from "./woo-meta.js";
|
|
|
42
48
|
import { WOO_REPORTED_VERSION, WP_REPORTED_VERSION } from "./woo-shapes.js";
|
|
43
49
|
/** How long an app's receiver has to answer, as WooCommerce allows it. */ export const WOO_WEBHOOK_TIMEOUT_MS = 15000;
|
|
44
50
|
const DELIVERY_LOG_TTL_MS = 30 * 86400000;
|
|
51
|
+
/** The WooCommerce status action one store event fires, if any. */ export function wooActionForEvent(event) {
|
|
52
|
+
const status = {
|
|
53
|
+
'order.paid': 'processing',
|
|
54
|
+
'order.fulfilled': 'completed',
|
|
55
|
+
'order.delivered': 'completed',
|
|
56
|
+
'order.refunded': 'refunded',
|
|
57
|
+
'order.cancelled': 'cancelled'
|
|
58
|
+
};
|
|
59
|
+
return status[event] ? `woocommerce_order_status_${status[event]}` : null;
|
|
60
|
+
}
|
|
45
61
|
/** The WooCommerce topics one store event is delivered as. */ export function wooTopicsForEvent(event) {
|
|
46
|
-
|
|
62
|
+
const action = wooActionForEvent(event);
|
|
63
|
+
if (!action) return [];
|
|
64
|
+
const resource = event === 'order.paid' ? [
|
|
47
65
|
'order.created',
|
|
48
66
|
'order.updated'
|
|
67
|
+
] : [
|
|
68
|
+
'order.updated'
|
|
49
69
|
];
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
70
|
+
return [
|
|
71
|
+
...resource,
|
|
72
|
+
`action.${action}`
|
|
73
|
+
];
|
|
74
|
+
}
|
|
75
|
+
/** The body WooCommerce sends an action hook: the hook's name and its argument. */ export function wooActionBody(topic, orderId) {
|
|
76
|
+
return JSON.stringify({
|
|
77
|
+
action: topic.slice('action.'.length),
|
|
78
|
+
arg: orderId
|
|
79
|
+
});
|
|
56
80
|
}
|
|
57
81
|
/** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */ export function signWooWebhook(body, secret) {
|
|
58
82
|
return createHmac('sha256', secret).update(body, 'utf8').digest('base64');
|
|
@@ -117,7 +141,7 @@ const DELIVERY_LOG_TTL_MS = 30 * 86400000;
|
|
|
117
141
|
}, fetchImpl);
|
|
118
142
|
}
|
|
119
143
|
/** The subscriber: delivers one store event to every live hook that takes it. */ export async function deliverWooWebhooks(envelope, deps = {}) {
|
|
120
|
-
var _ref, _envelope_payload, _orderSnap_data, _deps_isLive, _deps_fetchImpl, _deps_now;
|
|
144
|
+
var _ref, _envelope_payload, _orderSnap_data, _ref1, _deps_isLive, _deps_fetchImpl, _deps_now;
|
|
121
145
|
var _order;
|
|
122
146
|
const topics = wooTopicsForEvent(envelope.event);
|
|
123
147
|
if (!topics.length) return {
|
|
@@ -147,7 +171,8 @@ const DELIVERY_LOG_TTL_MS = 30 * 86400000;
|
|
|
147
171
|
data: (_orderSnap_data = orderSnap.data()) != null ? _orderSnap_data : {}
|
|
148
172
|
}
|
|
149
173
|
]);
|
|
150
|
-
const
|
|
174
|
+
const orderBody = JSON.stringify(order);
|
|
175
|
+
const wooOrderId = (_ref1 = order == null ? void 0 : order.id) != null ? _ref1 : orderId;
|
|
151
176
|
const isLive = (_deps_isLive = deps.isLive) != null ? _deps_isLive : (grantId, hostId)=>wooConnectionIsLive(grantId, hostId);
|
|
152
177
|
const fetchImpl = (_deps_fetchImpl = deps.fetchImpl) != null ? _deps_fetchImpl : fetchConfiguredPublicUrl;
|
|
153
178
|
const clock = (_deps_now = deps.now) != null ? _deps_now : Date.now;
|
|
@@ -166,6 +191,7 @@ const DELIVERY_LOG_TTL_MS = 30 * 86400000;
|
|
|
166
191
|
}
|
|
167
192
|
const startedAt = clock();
|
|
168
193
|
const deliveryId = `${envelope.id}.${hook.id}`;
|
|
194
|
+
const body = hook.topic.startsWith('action.') ? wooActionBody(hook.topic, wooOrderId) : orderBody;
|
|
169
195
|
const result = await post(hook.delivery_url, {
|
|
170
196
|
headers: wooWebhookHeaders({
|
|
171
197
|
hook,
|