@aglyn/plugins-commerce 1.36.0 → 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.
@@ -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\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)),\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: 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 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","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","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","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,aAAaP,UAAU,IAAI,OAAO;IAClE,MAAMQ,OAAO,OAAOR,UAAU,WAAWS,OAAOT,SAAS,OAAOA,UAAU,WAAWA,MAAMU,IAAI,KAAK;IACpG,IAAI,CAAC,oBAAoBC,IAAI,CAACH,OAAO,OAAOD;IAC5C,OAAOK,KAAKC,KAAK,CAACZ,OAAOO,QAAQ,OAAO;AAC1C;AAEA,uEAAuE,GACvE,OAAO,SAASM,QAAQC,EAA6B;IACnD,IAAI,OAAOA,OAAO,YAAY,CAACd,OAAOC,QAAQ,CAACa,OAAOA,MAAM,GAAG,OAAO;IACtE,OAAO,IAAIC,KAAKD,IAAIE,WAAW,GAAGC,KAAK,CAAC,GAAG;AAC7C;AAEA,0GAA0G,GAC1G,OAAO,SAASC,YAAYnB,KAAoB;IAC9C,IAAI,CAACA,OAAO,OAAO;IACnB,MAAMQ,OAAO,yBA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/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,qEAAqE,GACrE,OAAO,SAASC,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,aAAaP,UAAU,IAAI,OAAO;IAClE,MAAMQ,OAAO,OAAOR,UAAU,WAAWS,OAAOT,SAAS,OAAOA,UAAU,WAAWA,MAAMU,IAAI,KAAK;IACpG,IAAI,CAAC,oBAAoBC,IAAI,CAACH,OAAO,OAAOD;IAC5C,OAAOK,KAAKC,KAAK,CAACZ,OAAOO,QAAQ,O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B,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"}
@@ -18,7 +18,7 @@
18
18
  export declare const PRODUCT_IMPORT_FOLDER_NAME = "Imported products";
19
19
  /**
20
20
  * The largest photo copied: the media library's own limit for an uploaded
21
- * image (`IMAGE_MAX_BYTES` in the console's `media-upload-limits.ts`, 15 MB),
21
+ * image (`IMAGE_MAX_BYTES` in `app-utils/media-upload-limits.ts`, 15 MB),
22
22
  * which the library checks again when it stores the bytes.
23
23
  */
24
24
  export declare const PRODUCT_IMPORT_IMAGE_MAX_BYTES: number;
@@ -36,7 +36,7 @@
36
36
  *=========================================*/ /** The folder of the site's media library imported product photos are filed in. */ export const PRODUCT_IMPORT_FOLDER_NAME = 'Imported products';
37
37
  /**
38
38
  * The largest photo copied: the media library's own limit for an uploaded
39
- * image (`IMAGE_MAX_BYTES` in the console's `media-upload-limits.ts`, 15 MB),
39
+ * image (`IMAGE_MAX_BYTES` in `app-utils/media-upload-limits.ts`, 15 MB),
40
40
  * which the library checks again when it stores the bytes.
41
41
  */ export const PRODUCT_IMPORT_IMAGE_MAX_BYTES = 15 * 1024 * 1024;
42
42
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/product-images.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\nimport { isMediaCdnPath, isMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\n\n/*==========================================\n * A PRODUCT FILE'S PHOTOS, COPIED INTO THE STORE'S MEDIA LIBRARY (AGL-4245).\n *\n * A file from another store names its photos by their address on that\n * store. Kept as addresses, every photo would keep loading from the old\n * platform and break when the old store closes, so the apply copies each one\n * into the site's own media library and the product names the stored file\n * by its media reference, exactly as a photo the owner picked in the product\n * editor. This module is the pure half: which cells are photos to copy,\n * which are already the library's own, which are skipped and why, and the\n * file name it is stored under. The fetch, the store and the key a copied\n * photo is found by again are `product-image-copy.server.ts`.\n *\n * - **Copied**: an https address on the default port, with no user name.\n * - **Kept as it is**: a media reference or a media CDN path, which is\n * already a file of an Aglyn library (an Aglyn export read back in).\n * - **Skipped, and said so in the dry run**: anything else. An `http://`\n * address, a name with no address (a Wix file lists bare media names, and\n * its host is not guessed), and every photo past the import's limit.\n *=========================================*/\n\n/** The folder of the site's media library imported product photos are filed in. */\nexport const PRODUCT_IMPORT_FOLDER_NAME = 'Imported products'\n\n/**\n * The largest photo copied: the media library's own limit for an uploaded\n * image (`IMAGE_MAX_BYTES` in the console's `media-upload-limits.ts`, 15 MB),\n * which the library checks again when it stores the bytes.\n */\nexport const PRODUCT_IMPORT_IMAGE_MAX_BYTES = 15 * 1024 * 1024\n\n/**\n * The most distinct photos one import copies. A 500-product store with four\n * photos each is 2,000; past it the dry run lists what is skipped. The\n * storage itself is held to the plan by the library, photo by photo.\n */\nexport const PRODUCT_IMPORT_IMAGES_MAX = 2_000\n\n/** One photo's own clock, as Bring my site gives one (`SITE_IMPORT_IMAGE_TIMEOUT_MS`). */\nexport const PRODUCT_IMPORT_IMAGE_TIMEOUT_MS = 8_000\n\n/** The time a photo is started with: its fetch, and the library storing it. */\nexport const PRODUCT_IMPORT_IMAGE_SLOT_MS = PRODUCT_IMPORT_IMAGE_TIMEOUT_MS + 4_000\n\n/** How many photos are fetched at once. */\nexport const PRODUCT_IMPORT_IMAGE_CONCURRENCY = 4\n\n/** The image types the library takes from a server. */\nexport const PRODUCT_IMPORT_IMAGE_TYPES = /^image\\/(?:jpeg|jpg|pjpeg|png|webp|gif)\\b/i\n\n/** Why a cell's photo is not copied. */\nexport type ProductImageSkip = 'notHttps' | 'notAddress' | 'mediaName' | 'overLimit'\n\n/** What one photo cell is. */\nexport type ProductImageCell =\n | { kind: 'copy'; url: string }\n | { kind: 'stored'; value: string }\n | { kind: 'skip'; value: string; skip: ProductImageSkip }\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|_ga)$/i\nconst DOMAIN_PATH = /^(?:[\\w-]+\\.)+[a-z]{2,}(?:[/?#].*)?$/i\n\n/** One photo cell, read. `null` for a blank one. */\nexport function productImageCell(raw: unknown): ProductImageCell | null {\n const value = String(raw ?? '').trim()\n if (!value) return null\n if (isMediaRef(value) || isMediaCdnPath(value)) return { kind: 'stored', value }\n const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(value)\n if (!hasScheme && !DOMAIN_PATH.test(value)) return { kind: 'skip', value, skip: 'mediaName' }\n let url: URL\n try {\n url = new URL(hasScheme ? value : `https://${value}`)\n } catch {\n return { kind: 'skip', value, skip: 'notAddress' }\n }\n if (url.protocol === 'http:') return { kind: 'skip', value, skip: 'notHttps' }\n if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')) {\n return { kind: 'skip', value, skip: 'notAddress' }\n }\n url.hash = ''\n for (const key of [...url.searchParams.keys()]) if (TRACKING_PARAM.test(key)) url.searchParams.delete(key)\n return { kind: 'copy', url: url.toString() }\n}\n\n/** The photos one cell names: several, split by semicolons, spaces or bars (a Wix or Squarespace cell). */\nexport function productImageList(raw: unknown): string[] {\n const list = Array.isArray(raw) ? raw.map((item) => String(item ?? '')) : String(raw ?? '').split(/[;|\\s]+/)\n const out: string[] = []\n for (const item of list) {\n const value = item.trim()\n if (value && !out.includes(value)) out.push(value)\n }\n return out\n}\n\n/** What the dry run says of a skipped photo. */\nexport function productImageSkipDetail(skip: ProductImageSkip): string {\n switch (skip) {\n case 'notHttps':\n return 'Not copied: the address starts with http://, not https://. Add this photo on the product.'\n case 'notAddress':\n return 'Not copied: this is not a web address a photo can be copied from. Add this photo on the product.'\n case 'mediaName':\n return 'Not copied: the file names the photo but not where it is online. Add this photo on the product.'\n case 'overLimit':\n return `Not copied: one import copies up to ${PRODUCT_IMPORT_IMAGES_MAX.toLocaleString('en-US')} photos. Import the rest in a second file, or add them on the product.`\n }\n}\n\nconst EXTENSION: Record<string, string> = {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n}\n\n/** A file name for the library, from the photo's address and type. */\nexport function productImageFileName(url: string, contentType: string): string {\n let base = 'product-photo'\n try {\n const last = decodeURIComponent(new URL(url).pathname.split('/').filter(Boolean).pop() ?? '')\n base =\n last\n .replace(/\\.[a-z0-9]+$/i, '')\n .replace(/[^a-zA-Z0-9 _-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '') || base\n } catch {\n // An address that does not decode keeps the plain name.\n }\n return `${base.slice(0, 80)}.${EXTENSION[contentType] ?? 'jpg'}`\n}\n\n/** A content type as the library names it: `image/jpg` and `image/pjpeg` are JPEG. */\nexport function productImageContentType(header: string): string {\n const type = String(header ?? '').split(';')[0]?.trim().toLowerCase() ?? ''\n return type === 'image/jpg' || type === 'image/pjpeg' ? 'image/jpeg' : type\n}\n"],"names":["isMediaCdnPath","isMediaRef","PRODUCT_IMPORT_FOLDER_NAME","PRODUCT_IMPORT_IMAGE_MAX_BYTES","PRODUCT_IMPORT_IMAGES_MAX","PRODUCT_IMPORT_IMAGE_TIMEOUT_MS","PRODUCT_IMPORT_IMAGE_SLOT_MS","PRODUCT_IMPORT_IMAGE_CONCURRENCY","PRODUCT_IMPORT_IMAGE_TYPES","TRACKING_PARAM","DOMAIN_PATH","productImageCell","raw","value","String","trim","kind","hasScheme","test","skip","url","URL","protocol","username","password","port","hash","key","searchParams","keys","delete","toString","productImageList","list","Array","isArray","map","item","split","out","includes","push","productImageSkipDetail","toLocaleString","EXTENSION","productImageFileName","contentType","base","last","decodeURIComponent","pathname","filter","Boolean","pop","replace","slice","productImageContentType","header","type","toLowerCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,EAAEC,UAAU,QAAQ,mCAAkC;AAE7E;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,iFAAiF,GACjF,OAAO,MAAMC,6BAA6B,oBAAmB;AAE7D;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,KAAK,OAAO,KAAI;AAE9D;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,KAAK;AAE9C,wFAAwF,GACxF,OAAO,MAAMC,kCAAkC,KAAK;AAEpD,6EAA6E,GAC7E,OAAO,MAAMC,+BAA+BD,kCAAkC,KAAK;AAEnF,yCAAyC,GACzC,OAAO,MAAME,mCAAmC,EAAC;AAEjD,qDAAqD,GACrD,OAAO,MAAMC,6BAA6B,6CAA4C;AAWtF,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AAEpB,kDAAkD,GAClD,OAAO,SAASC,iBAAiBC,GAAY;IAC3C,MAAMC,QAAQC,OAAOF,cAAAA,MAAO,IAAIG,IAAI;IACpC,IAAI,CAACF,OAAO,OAAO;IACnB,IAAIZ,WAAWY,UAAUb,eAAea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IAAI,CAAC5B;IAC9C;IACA,OAAO0B;AACT;AAEA,8CAA8C,GAC9C,OAAO,SAASG,uBAAuBvB,IAAsB;IAC3D,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO,CAAC,oCAAoC,EAAEf,0BAA0BuC,cAAc,CAAC,SAAS,sEAAsE,CAAC;IAC3K;AACF;AAEA,MAAMC,YAAoC;IACxC,cAAc;IACd,aAAa;IACb,cAAc;IACd,aAAa;AACf;AAEA,oEAAoE,GACpE,OAAO,SAASC,qBAAqBzB,GAAW,EAAE0B,WAAmB;QAapCF;IAZ/B,IAAIG,OAAO;IACX,IAAI;YAC8B;QAAhC,MAAMC,OAAOC,oBAAmB,6BAAA,IAAI5B,IAAID,KAAK8B,QAAQ,CAACZ,KAAK,CAAC,KAAKa,MAAM,CAACC,SAASC,GAAG,cAApD,6BAA0D;QAC1FN,OACEC,KACGM,OAAO,CAAC,iBAAiB,IACzBA,OAAO,CAAC,qBAAqB,KAC7BA,OAAO,CAAC,OAAO,KACfA,OAAO,CAAC,UAAU,OAAOP;IAChC,EAAE,eAAM;IACN,wDAAwD;IAC1D;IACA,OAAO,GAAGA,KAAKQ,KAAK,CAAC,GAAG,IAAI,CAAC,GAAEX,yBAAAA,SAAS,CAACE,YAAY,YAAtBF,yBAA0B,OAAO;AAClE;AAEA,oFAAoF,GACpF,OAAO,SAASY,wBAAwBC,MAAc;;QACvC3C;IAAb,MAAM4C,gBAAO5C,iBAAAA,OAAO2C,iBAAAA,SAAU,IAAInB,KAAK,CAAC,IAAI,CAAC,EAAE,qBAAlCxB,eAAoCC,IAAI,GAAG4C,WAAW,qBAAM;IACzE,OAAOD,SAAS,eAAeA,SAAS,gBAAgB,eAAeA;AACzE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/product-images.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\nimport { isMediaCdnPath, isMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\n\n/*==========================================\n * A PRODUCT FILE'S PHOTOS, COPIED INTO THE STORE'S MEDIA LIBRARY (AGL-4245).\n *\n * A file from another store names its photos by their address on that\n * store. Kept as addresses, every photo would keep loading from the old\n * platform and break when the old store closes, so the apply copies each one\n * into the site's own media library and the product names the stored file\n * by its media reference, exactly as a photo the owner picked in the product\n * editor. This module is the pure half: which cells are photos to copy,\n * which are already the library's own, which are skipped and why, and the\n * file name it is stored under. The fetch, the store and the key a copied\n * photo is found by again are `product-image-copy.server.ts`.\n *\n * - **Copied**: an https address on the default port, with no user name.\n * - **Kept as it is**: a media reference or a media CDN path, which is\n * already a file of an Aglyn library (an Aglyn export read back in).\n * - **Skipped, and said so in the dry run**: anything else. An `http://`\n * address, a name with no address (a Wix file lists bare media names, and\n * its host is not guessed), and every photo past the import's limit.\n *=========================================*/\n\n/** The folder of the site's media library imported product photos are filed in. */\nexport const PRODUCT_IMPORT_FOLDER_NAME = 'Imported products'\n\n/**\n * The largest photo copied: the media library's own limit for an uploaded\n * image (`IMAGE_MAX_BYTES` in `app-utils/media-upload-limits.ts`, 15 MB),\n * which the library checks again when it stores the bytes.\n */\nexport const PRODUCT_IMPORT_IMAGE_MAX_BYTES = 15 * 1024 * 1024\n\n/**\n * The most distinct photos one import copies. A 500-product store with four\n * photos each is 2,000; past it the dry run lists what is skipped. The\n * storage itself is held to the plan by the library, photo by photo.\n */\nexport const PRODUCT_IMPORT_IMAGES_MAX = 2_000\n\n/** One photo's own clock, as Bring my site gives one (`SITE_IMPORT_IMAGE_TIMEOUT_MS`). */\nexport const PRODUCT_IMPORT_IMAGE_TIMEOUT_MS = 8_000\n\n/** The time a photo is started with: its fetch, and the library storing it. */\nexport const PRODUCT_IMPORT_IMAGE_SLOT_MS = PRODUCT_IMPORT_IMAGE_TIMEOUT_MS + 4_000\n\n/** How many photos are fetched at once. */\nexport const PRODUCT_IMPORT_IMAGE_CONCURRENCY = 4\n\n/** The image types the library takes from a server. */\nexport const PRODUCT_IMPORT_IMAGE_TYPES = /^image\\/(?:jpeg|jpg|pjpeg|png|webp|gif)\\b/i\n\n/** Why a cell's photo is not copied. */\nexport type ProductImageSkip = 'notHttps' | 'notAddress' | 'mediaName' | 'overLimit'\n\n/** What one photo cell is. */\nexport type ProductImageCell =\n | { kind: 'copy'; url: string }\n | { kind: 'stored'; value: string }\n | { kind: 'skip'; value: string; skip: ProductImageSkip }\n\nconst TRACKING_PARAM = /^(?:utm_[a-z]+|fbclid|gclid|msclkid|_ga)$/i\nconst DOMAIN_PATH = /^(?:[\\w-]+\\.)+[a-z]{2,}(?:[/?#].*)?$/i\n\n/** One photo cell, read. `null` for a blank one. */\nexport function productImageCell(raw: unknown): ProductImageCell | null {\n const value = String(raw ?? '').trim()\n if (!value) return null\n if (isMediaRef(value) || isMediaCdnPath(value)) return { kind: 'stored', value }\n const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(value)\n if (!hasScheme && !DOMAIN_PATH.test(value)) return { kind: 'skip', value, skip: 'mediaName' }\n let url: URL\n try {\n url = new URL(hasScheme ? value : `https://${value}`)\n } catch {\n return { kind: 'skip', value, skip: 'notAddress' }\n }\n if (url.protocol === 'http:') return { kind: 'skip', value, skip: 'notHttps' }\n if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443')) {\n return { kind: 'skip', value, skip: 'notAddress' }\n }\n url.hash = ''\n for (const key of [...url.searchParams.keys()]) if (TRACKING_PARAM.test(key)) url.searchParams.delete(key)\n return { kind: 'copy', url: url.toString() }\n}\n\n/** The photos one cell names: several, split by semicolons, spaces or bars (a Wix or Squarespace cell). */\nexport function productImageList(raw: unknown): string[] {\n const list = Array.isArray(raw) ? raw.map((item) => String(item ?? '')) : String(raw ?? '').split(/[;|\\s]+/)\n const out: string[] = []\n for (const item of list) {\n const value = item.trim()\n if (value && !out.includes(value)) out.push(value)\n }\n return out\n}\n\n/** What the dry run says of a skipped photo. */\nexport function productImageSkipDetail(skip: ProductImageSkip): string {\n switch (skip) {\n case 'notHttps':\n return 'Not copied: the address starts with http://, not https://. Add this photo on the product.'\n case 'notAddress':\n return 'Not copied: this is not a web address a photo can be copied from. Add this photo on the product.'\n case 'mediaName':\n return 'Not copied: the file names the photo but not where it is online. Add this photo on the product.'\n case 'overLimit':\n return `Not copied: one import copies up to ${PRODUCT_IMPORT_IMAGES_MAX.toLocaleString('en-US')} photos. Import the rest in a second file, or add them on the product.`\n }\n}\n\nconst EXTENSION: Record<string, string> = {\n 'image/jpeg': 'jpg',\n 'image/png': 'png',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n}\n\n/** A file name for the library, from the photo's address and type. */\nexport function productImageFileName(url: string, contentType: string): string {\n let base = 'product-photo'\n try {\n const last = decodeURIComponent(new URL(url).pathname.split('/').filter(Boolean).pop() ?? '')\n base =\n last\n .replace(/\\.[a-z0-9]+$/i, '')\n .replace(/[^a-zA-Z0-9 _-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '') || base\n } catch {\n // An address that does not decode keeps the plain name.\n }\n return `${base.slice(0, 80)}.${EXTENSION[contentType] ?? 'jpg'}`\n}\n\n/** A content type as the library names it: `image/jpg` and `image/pjpeg` are JPEG. */\nexport function productImageContentType(header: string): string {\n const type = String(header ?? '').split(';')[0]?.trim().toLowerCase() ?? ''\n return type === 'image/jpg' || type === 'image/pjpeg' ? 'image/jpeg' : type\n}\n"],"names":["isMediaCdnPath","isMediaRef","PRODUCT_IMPORT_FOLDER_NAME","PRODUCT_IMPORT_IMAGE_MAX_BYTES","PRODUCT_IMPORT_IMAGES_MAX","PRODUCT_IMPORT_IMAGE_TIMEOUT_MS","PRODUCT_IMPORT_IMAGE_SLOT_MS","PRODUCT_IMPORT_IMAGE_CONCURRENCY","PRODUCT_IMPORT_IMAGE_TYPES","TRACKING_PARAM","DOMAIN_PATH","productImageCell","raw","value","String","trim","kind","hasScheme","test","skip","url","URL","protocol","username","password","port","hash","key","searchParams","keys","delete","toString","productImageList","list","Array","isArray","map","item","split","out","includes","push","productImageSkipDetail","toLocaleString","EXTENSION","productImageFileName","contentType","base","last","decodeURIComponent","pathname","filter","Boolean","pop","replace","slice","productImageContentType","header","type","toLowerCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,EAAEC,UAAU,QAAQ,mCAAkC;AAE7E;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,iFAAiF,GACjF,OAAO,MAAMC,6BAA6B,oBAAmB;AAE7D;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,KAAK,OAAO,KAAI;AAE9D;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,KAAK;AAE9C,wFAAwF,GACxF,OAAO,MAAMC,kCAAkC,KAAK;AAEpD,6EAA6E,GAC7E,OAAO,MAAMC,+BAA+BD,kCAAkC,KAAK;AAEnF,yCAAyC,GACzC,OAAO,MAAME,mCAAmC,EAAC;AAEjD,qDAAqD,GACrD,OAAO,MAAMC,6BAA6B,6CAA4C;AAWtF,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AAEpB,kDAAkD,GAClD,OAAO,SAASC,iBAAiBC,GAAY;IAC3C,MAAMC,QAAQC,OAAOF,cAAAA,MAAO,IAAIG,IAAI;IACpC,IAAI,CAACF,OAAO,OAAO;IACnB,IAAIZ,WAAWY,UAAUb,eAAea,QAAQ,OAAO;QAAEG,MAAM;QAAUH;IAAM;IAC/E,MAAMI,YAAY,uBAAuBC,IAAI,CAACL;IAC9C,IAAI,CAACI,aAAa,CAACP,YAAYQ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