@aglyn/plugins-commerce 1.35.2 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-webhooks.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 * WEBHOOKS, DELIVERED AS WOOCOMMERCE DELIVERS THEM.\n *\n * An app that links a store through its WooCommerce connector may register\n * webhooks (`POST /wc/v3/webhooks`, `woo-system.ts`) rather than poll for\n * orders. Commerce's own order events drive them, through the plugin event\n * outbox like the merchant's order webhooks: a failed delivery throws, and\n * the outbox retries it with its backoff; a hook that already took the event\n * is not sent it again.\n *\n * - `order.paid` → `order.created` and `order.updated`. A store order\n * exists for an app once it is paid: an unpaid checkout is never listed.\n * - fulfilled, delivered, refunded, cancelled → `order.updated`.\n *\n * The body is the order exactly as `GET /wc/v3/orders/{id}` answers it. The\n * headers are WooCommerce's: `X-WC-Webhook-Topic`, `-Resource`, `-Event`,\n * `-ID`, `-Delivery-ID`, `-Source`, and `-Signature`, the base64 HMAC-SHA256\n * of the body under the hook's secret. Each call goes through\n * `fetchConfiguredPublicUrl` (https, public address, no redirect). A hook\n * whose link has ended is skipped.\n *=========================================*/\n\nimport type { PluginDomainEventEnvelope } from '@aglyn/aglyn/plugin-manager/plugin-domain-events'\nimport { fetchConfiguredPublicUrl, firebaseAdmin, wooConnectionIsLive } from '@aglyn/tenant-data-admin'\nimport { PLUGIN_EVENT_MAX_ATTEMPTS } from '@aglyn/tenant-data-admin/server/plugin-event-outbox'\nimport { createHmac } from 'node:crypto'\nimport { shapeStoreOrders } from './woo-orders'\nimport { readWebhooks, type StoredWebhook } from './woo-meta'\nimport { WOO_REPORTED_VERSION, WP_REPORTED_VERSION } from './woo-shapes'\n\n/** How long an app's receiver has to answer, as WooCommerce allows it. */\nexport const WOO_WEBHOOK_TIMEOUT_MS = 15_000\nconst DELIVERY_LOG_TTL_MS = 30 * 86_400_000\n\n/** The WooCommerce topics one store event is delivered as. */\nexport function wooTopicsForEvent(event: string): string[] {\n if (event === 'order.paid') return ['order.created', 'order.updated']\n if (event === 'order.fulfilled' || event === 'order.delivered' || event === 'order.refunded' || event === 'order.cancelled') {\n return ['order.updated']\n }\n return []\n}\n\n/** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */\nexport function signWooWebhook(body: string, secret: string): string {\n return createHmac('sha256', secret).update(body, 'utf8').digest('base64')\n}\n\n/** The headers WooCommerce sends with a delivery. */\nexport function wooWebhookHeaders(input: {\n hook: Pick<StoredWebhook, 'id' | 'topic' | 'secret'>\n deliveryId: string\n source: string\n body: string\n}): Record<string, string> {\n const [resource, event] = input.hook.topic.split('.')\n return {\n 'content-type': 'application/json',\n 'user-agent': `WooCommerce/${WOO_REPORTED_VERSION} Hookshot (WordPress/${WP_REPORTED_VERSION})`,\n 'x-wc-webhook-source': input.source.endsWith('/') ? input.source : `${input.source}/`,\n 'x-wc-webhook-topic': input.hook.topic,\n 'x-wc-webhook-resource': resource ?? '',\n 'x-wc-webhook-event': event ?? '',\n 'x-wc-webhook-signature': signWooWebhook(input.body, input.hook.secret),\n 'x-wc-webhook-id': String(input.hook.id),\n 'x-wc-webhook-delivery-id': input.deliveryId,\n }\n}\n\ntype Fetch = typeof fetchConfiguredPublicUrl\n\n/** One POST; `null` when it was taken (2xx), otherwise why not. Never throws. */\nasync function post(url: string, init: { headers: Record<string, string>; body: string }, fetchImpl: Fetch): Promise<{ status: number | null; error: string | null }> {\n try {\n const result = await fetchImpl(url, { method: 'POST', headers: init.headers, body: init.body, signal: AbortSignal.timeout(WOO_WEBHOOK_TIMEOUT_MS) })\n if ('refusal' in result) return { status: null, error: `refused: ${result.refusal}` }\n return { status: result.status, error: result.status >= 200 && result.status < 300 ? null : `answered ${result.status}` }\n } catch (caught) {\n return { status: null, error: String((caught as Error)?.name ?? 'network') }\n }\n}\n\n/**\n * The ping WooCommerce sends when a webhook is saved active: a form post of\n * `webhook_id`, which some apps wait for before they count the hook as set\n * up. Its answer is only logged.\n */\nexport async function pingWooWebhook(hook: StoredWebhook, source: string, fetchImpl: Fetch = fetchConfiguredPublicUrl) {\n const body = new URLSearchParams({ webhook_id: String(hook.id) }).toString()\n const headers = { ...wooWebhookHeaders({ hook, deliveryId: '0', source, body }), 'content-type': 'application/x-www-form-urlencoded' }\n return post(hook.delivery_url, { headers, body }, fetchImpl)\n}\n\nexport interface WooWebhookDeps {\n fetchImpl?: Fetch\n now?: () => number\n isLive?: (grantId: string, hostId: string) => Promise<boolean>\n}\n\n/** The subscriber: delivers one store event to every live hook that takes it. */\nexport async function deliverWooWebhooks(envelope: PluginDomainEventEnvelope, deps: WooWebhookDeps = {}): Promise<{ delivered: number; failed: number }> {\n const topics = wooTopicsForEvent(envelope.event)\n if (!topics.length) return { delivered: 0, failed: 0 }\n const firestore = firebaseAdmin.app().firestore()\n const hooks = (await readWebhooks(firestore, envelope.hostId)).filter((hook) => hook.status === 'active' && topics.includes(hook.topic))\n if (!hooks.length) return { delivered: 0, failed: 0 }\n const orderId = String(((envelope.payload ?? {}) as { order?: { id?: unknown } }).order?.id ?? '')\n if (!orderId) return { delivered: 0, failed: 0 }\n const hostRef = firestore.collection('hosts').doc(envelope.hostId)\n const orderSnap = await hostRef.collection('orders').doc(orderId).get()\n if (!orderSnap.exists) return { delivered: 0, failed: 0 }\n const [order] = await shapeStoreOrders(firestore, envelope.hostId, [{ id: orderId, data: orderSnap.data() ?? {} }])\n const body = JSON.stringify(order)\n const isLive = deps.isLive ?? ((grantId: string, hostId: string) => wooConnectionIsLive(grantId, hostId))\n const fetchImpl = deps.fetchImpl ?? fetchConfiguredPublicUrl\n const clock = deps.now ?? Date.now\n const final = envelope.attempt >= PLUGIN_EVENT_MAX_ATTEMPTS\n const liveByGrant = new Map<string, Promise<boolean>>()\n let delivered = 0\n let failed = 0\n for (const hook of hooks) {\n if (!liveByGrant.has(hook.grantId)) liveByGrant.set(hook.grantId, isLive(hook.grantId, envelope.hostId).catch(() => false))\n if (!(await liveByGrant.get(hook.grantId))) continue\n const logRef = hostRef.collection('wooRequests').doc(`webhook.${envelope.id}.${hook.id}`.replace(/\\//g, '_'))\n if ((await logRef.get()).get('status') === 'delivered') {\n delivered += 1\n continue\n }\n const startedAt = clock()\n const deliveryId = `${envelope.id}.${hook.id}`\n const result = await post(hook.delivery_url, { headers: wooWebhookHeaders({ hook, deliveryId, source: hook.source ?? '', body }), body }, fetchImpl)\n const ok = result.error === null\n if (ok) delivered += 1\n else failed += 1\n await logRef\n .set({\n kind: 'webhook',\n topic: hook.topic,\n webhookId: hook.id,\n grantId: hook.grantId,\n event: envelope.event,\n orderId,\n status: ok ? 'delivered' : final ? 'failed' : 'retrying',\n httpStatus: result.status,\n error: result.error,\n attempt: envelope.attempt,\n atMs: startedAt,\n ms: Math.max(0, clock() - startedAt),\n expiresAt: firebaseAdmin.firestore.Timestamp.fromMillis(startedAt + DELIVERY_LOG_TTL_MS),\n })\n .catch(() => undefined)\n }\n if (failed > 0 && !final) throw new Error(`${failed} WooCommerce webhook(s) did not take ${envelope.event}`)\n return { delivered, failed }\n}\n"],"names":["fetchConfiguredPublicUrl","firebaseAdmin","wooConnectionIsLive","PLUGIN_EVENT_MAX_ATTEMPTS","createHmac","shapeStoreOrders","readWebhooks","WOO_REPORTED_VERSION","WP_REPORTED_VERSION","WOO_WEBHOOK_TIMEOUT_MS","DELIVERY_LOG_TTL_MS","wooTopicsForEvent","event","signWooWebhook","body","secret","update","digest","wooWebhookHeaders","input","resource","hook","topic","split","source","endsWith","String","id","deliveryId","post","url","init","fetchImpl","result","method","headers","signal","AbortSignal","timeout","status","error","refusal","caught","name","pingWooWebhook","URLSearchParams","webhook_id","toString","delivery_url","deliverWooWebhooks","envelope","deps","orderSnap","topics","length","delivered","failed","firestore","app","hooks","hostId","filter","includes","orderId","payload","order","hostRef","collection","doc","get","exists","data","JSON","stringify","isLive","grantId","clock","now","Date","final","attempt","liveByGrant","Map","has","set","catch","logRef","replace","startedAt","ok","kind","webhookId","httpStatus","atMs","ms","Math","max","expiresAt","Timestamp","fromMillis","undefined","Error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C;AAG3C,SAASA,wBAAwB,EAAEC,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AACvG,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,gBAAgB,QAAQ,kBAAc;AAC/C,SAASC,YAAY,QAA4B,gBAAY;AAC7D,SAASC,oBAAoB,EAAEC,mBAAmB,QAAQ,kBAAc;AAExE,wEAAwE,GACxE,OAAO,MAAMC,yBAAyB,MAAM;AAC5C,MAAMC,sBAAsB,KAAK;AAEjC,4DAA4D,GAC5D,OAAO,SAASC,kBAAkBC,KAAa;IAC7C,IAAIA,UAAU,cAAc,OAAO;QAAC;QAAiB;KAAgB;IACrE,IAAIA,UAAU,qBAAqBA,UAAU,qBAAqBA,UAAU,oBAAoBA,UAAU,mBAAmB;QAC3H,OAAO;YAAC;SAAgB;IAC1B;IACA,OAAO,EAAE;AACX;AAEA,yFAAyF,GACzF,OAAO,SAASC,eAAeC,IAAY,EAAEC,MAAc;IACzD,OAAOX,WAAW,UAAUW,QAAQC,MAAM,CAACF,MAAM,QAAQG,MAAM,CAAC;AAClE;AAEA,mDAAmD,GACnD,OAAO,SAASC,kBAAkBC,KAKjC;IACC,MAAM,CAACC,U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AAEN,KAAKM,EAAE,EAAE;QAC9C,MAAMM,SAAS,MAAMJ,KAAKR,KAAK2B,YAAY,EAAE;YAAEb,SAASjB,kBAAkB;gBAAEG;gBAAMO;gBAAYJ,MAAM,GAAEH,eAAAA,KAAKG,MAAM,YAAXH,eAAe;gBAAIP;YAAK;YAAIA;QAAK,GAAGkB;QAC1I,MAAMyD,KAAKxD,OAAOO,KAAK,KAAK;QAC5B,IAAIiD,IAAIlC,aAAa;aAChBC,UAAU;QACf,MAAM8B,OACHF,GAAG,CAAC;YACHM,MAAM;YACNpE,OAAOD,KAAKC,KAAK;YACjBqE,WAAWtE,KAAKM,EAAE;YAClBgD,SAAStD,KAAKsD,OAAO;YACrB/D,OAAOsC,SAAStC,KAAK;YACrBmD;YACAxB,QAAQkD,KAAK,cAAcV,QAAQ,WAAW;YAC9Ca,YAAY3D,OAAOM,MAAM;YACzBC,OAAOP,OAAOO,KAAK;YACnBwC,SAAS9B,SAAS8B,OAAO;YACzBa,MAAML;YACNM,IAAIC,KAAKC,GAAG,CAAC,GAAGpB,UAAUY;YAC1BS,WAAWhG,cAAcwD,SAAS,CAACyC,SAAS,CAACC,UAAU,CAACX,YAAY9E;QACtE,GACC2E,KAAK,CAAC,IAAMe;IACjB;IACA,IAAI5C,SAAS,KAAK,CAACuB,OAAO,MAAM,IAAIsB,MAAM,GAAG7C,OAAO,qCAAqC,EAAEN,SAAStC,KAAK,EAAE;IAC3G,OAAO;QAAE2C;QAAWC;IAAO;AAC7B"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-webhooks.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 * WEBHOOKS, DELIVERED AS WOOCOMMERCE DELIVERS THEM.\n *\n * An app that links a store through its WooCommerce connector may register\n * webhooks (`POST /wc/v3/webhooks`, `woo-system.ts`) rather than poll for\n * orders. Commerce's own order events drive them, through the plugin event\n * outbox like the merchant's order webhooks: a failed delivery throws, and\n * the outbox retries it with its backoff; a hook that already took the event\n * is not sent it again.\n *\n * - `order.paid` → `order.created` and `order.updated`. A store order\n * exists for an app once it is paid: an unpaid checkout is never listed.\n * - fulfilled, delivered, refunded, cancelled → `order.updated`.\n * - each of those also fires WooCommerce's status action, the topic\n * `action.woocommerce_order_status_<status>`: paid is `processing`,\n * fulfilled and delivered are `completed`, then `refunded` and\n * `cancelled`. Fulfillment apps subscribe to the paid one to import an\n * order. WooCommerce sends an action hook `{ action, arg }`, `arg` being\n * the order id, and so does this.\n *\n * A resource hook's body is the order exactly as `GET /wc/v3/orders/{id}` answers it. The\n * headers are WooCommerce's: `X-WC-Webhook-Topic`, `-Resource`, `-Event`,\n * `-ID`, `-Delivery-ID`, `-Source`, and `-Signature`, the base64 HMAC-SHA256\n * of the body under the hook's secret. Each call goes through\n * `fetchConfiguredPublicUrl` (https, public address, no redirect). A hook\n * whose link has ended is skipped.\n *=========================================*/\n\nimport type { PluginDomainEventEnvelope } from '@aglyn/aglyn/plugin-manager/plugin-domain-events'\nimport { fetchConfiguredPublicUrl, firebaseAdmin, wooConnectionIsLive } from '@aglyn/tenant-data-admin'\nimport { PLUGIN_EVENT_MAX_ATTEMPTS } from '@aglyn/tenant-data-admin/server/plugin-event-outbox'\nimport { createHmac } from 'node:crypto'\nimport { shapeStoreOrders } from './woo-orders'\nimport { readWebhooks, type StoredWebhook } from './woo-meta'\nimport { WOO_REPORTED_VERSION, WP_REPORTED_VERSION } from './woo-shapes'\n\n/** How long an app's receiver has to answer, as WooCommerce allows it. */\nexport const WOO_WEBHOOK_TIMEOUT_MS = 15_000\nconst DELIVERY_LOG_TTL_MS = 30 * 86_400_000\n\n/** The WooCommerce status action one store event fires, if any. */\nexport function wooActionForEvent(event: string): string | null {\n const status: Record<string, string> = {\n 'order.paid': 'processing',\n 'order.fulfilled': 'completed',\n 'order.delivered': 'completed',\n 'order.refunded': 'refunded',\n 'order.cancelled': 'cancelled',\n }\n return status[event] ? `woocommerce_order_status_${status[event]}` : null\n}\n\n/** The WooCommerce topics one store event is delivered as. */\nexport function wooTopicsForEvent(event: string): string[] {\n const action = wooActionForEvent(event)\n if (!action) return []\n const resource = event === 'order.paid' ? ['order.created', 'order.updated'] : ['order.updated']\n return [...resource, `action.${action}`]\n}\n\n/** The body WooCommerce sends an action hook: the hook's name and its argument. */\nexport function wooActionBody(topic: string, orderId: number | string): string {\n return JSON.stringify({ action: topic.slice('action.'.length), arg: orderId })\n}\n\n/** WooCommerce's signature: base64 HMAC-SHA256 of the raw body under the hook's secret. */\nexport function signWooWebhook(body: string, secret: string): string {\n return createHmac('sha256', secret).update(body, 'utf8').digest('base64')\n}\n\n/** The headers WooCommerce sends with a delivery. */\nexport function wooWebhookHeaders(input: {\n hook: Pick<StoredWebhook, 'id' | 'topic' | 'secret'>\n deliveryId: string\n source: string\n body: string\n}): Record<string, string> {\n const [resource, event] = input.hook.topic.split('.')\n return {\n 'content-type': 'application/json',\n 'user-agent': `WooCommerce/${WOO_REPORTED_VERSION} Hookshot (WordPress/${WP_REPORTED_VERSION})`,\n 'x-wc-webhook-source': input.source.endsWith('/') ? input.source : `${input.source}/`,\n 'x-wc-webhook-topic': input.hook.topic,\n 'x-wc-webhook-resource': resource ?? '',\n 'x-wc-webhook-event': event ?? '',\n 'x-wc-webhook-signature': signWooWebhook(input.body, input.hook.secret),\n 'x-wc-webhook-id': String(input.hook.id),\n 'x-wc-webhook-delivery-id': input.deliveryId,\n }\n}\n\ntype Fetch = typeof fetchConfiguredPublicUrl\n\n/** One POST; `null` when it was taken (2xx), otherwise why not. Never throws. */\nasync function post(url: string, init: { headers: Record<string, string>; body: string }, fetchImpl: Fetch): Promise<{ status: number | null; error: string | null }> {\n try {\n const result = await fetchImpl(url, { method: 'POST', headers: init.headers, body: init.body, signal: AbortSignal.timeout(WOO_WEBHOOK_TIMEOUT_MS) })\n if ('refusal' in result) return { status: null, error: `refused: ${result.refusal}` }\n return { status: result.status, error: result.status >= 200 && result.status < 300 ? null : `answered ${result.status}` }\n } catch (caught) {\n return { status: null, error: String((caught as Error)?.name ?? 'network') }\n }\n}\n\n/**\n * The ping WooCommerce sends when a webhook is saved active: a form post of\n * `webhook_id`, which some apps wait for before they count the hook as set\n * up. Its answer is only logged.\n */\nexport async function pingWooWebhook(hook: StoredWebhook, source: string, fetchImpl: Fetch = fetchConfiguredPublicUrl) {\n const body = new URLSearchParams({ webhook_id: String(hook.id) }).toString()\n const headers = { ...wooWebhookHeaders({ hook, deliveryId: '0', source, body }), 'content-type': 'application/x-www-form-urlencoded' }\n return post(hook.delivery_url, { headers, body }, fetchImpl)\n}\n\nexport interface WooWebhookDeps {\n fetchImpl?: Fetch\n now?: () => number\n isLive?: (grantId: string, hostId: string) => Promise<boolean>\n}\n\n/** The subscriber: delivers one store event to every live hook that takes it. */\nexport async function deliverWooWebhooks(envelope: PluginDomainEventEnvelope, deps: WooWebhookDeps = {}): Promise<{ delivered: number; failed: number }> {\n const topics = wooTopicsForEvent(envelope.event)\n if (!topics.length) return { delivered: 0, failed: 0 }\n const firestore = firebaseAdmin.app().firestore()\n const hooks = (await readWebhooks(firestore, envelope.hostId)).filter((hook) => hook.status === 'active' && topics.includes(hook.topic))\n if (!hooks.length) return { delivered: 0, failed: 0 }\n const orderId = String(((envelope.payload ?? {}) as { order?: { id?: unknown } }).order?.id ?? '')\n if (!orderId) return { delivered: 0, failed: 0 }\n const hostRef = firestore.collection('hosts').doc(envelope.hostId)\n const orderSnap = await hostRef.collection('orders').doc(orderId).get()\n if (!orderSnap.exists) return { delivered: 0, failed: 0 }\n const [order] = await shapeStoreOrders(firestore, envelope.hostId, [{ id: orderId, data: orderSnap.data() ?? {} }])\n const orderBody = JSON.stringify(order)\n const wooOrderId = (order as { id?: number | string } | undefined)?.id ?? orderId\n const isLive = deps.isLive ?? ((grantId: string, hostId: string) => wooConnectionIsLive(grantId, hostId))\n const fetchImpl = deps.fetchImpl ?? fetchConfiguredPublicUrl\n const clock = deps.now ?? Date.now\n const final = envelope.attempt >= PLUGIN_EVENT_MAX_ATTEMPTS\n const liveByGrant = new Map<string, Promise<boolean>>()\n let delivered = 0\n let failed = 0\n for (const hook of hooks) {\n if (!liveByGrant.has(hook.grantId)) liveByGrant.set(hook.grantId, isLive(hook.grantId, envelope.hostId).catch(() => false))\n if (!(await liveByGrant.get(hook.grantId))) continue\n const logRef = hostRef.collection('wooRequests').doc(`webhook.${envelope.id}.${hook.id}`.replace(/\\//g, '_'))\n if ((await logRef.get()).get('status') === 'delivered') {\n delivered += 1\n continue\n }\n const startedAt = clock()\n const deliveryId = `${envelope.id}.${hook.id}`\n const body = hook.topic.startsWith('action.') ? wooActionBody(hook.topic, wooOrderId) : orderBody\n const result = await post(hook.delivery_url, { headers: wooWebhookHeaders({ hook, deliveryId, source: hook.source ?? '', body }), body }, fetchImpl)\n const ok = result.error === null\n if (ok) delivered += 1\n else failed += 1\n await logRef\n .set({\n kind: 'webhook',\n topic: hook.topic,\n webhookId: hook.id,\n grantId: hook.grantId,\n event: envelope.event,\n orderId,\n status: ok ? 'delivered' : final ? 'failed' : 'retrying',\n httpStatus: result.status,\n error: result.error,\n attempt: envelope.attempt,\n atMs: startedAt,\n ms: Math.max(0, clock() - startedAt),\n expiresAt: firebaseAdmin.firestore.Timestamp.fromMillis(startedAt + DELIVERY_LOG_TTL_MS),\n })\n .catch(() => undefined)\n }\n if (failed > 0 && !final) throw new Error(`${failed} WooCommerce webhook(s) did not take ${envelope.event}`)\n return { delivered, failed }\n}\n"],"names":["fetchConfiguredPublicUrl","firebaseAdmin","wooConnectionIsLive","PLUGIN_EVENT_MAX_ATTEMPTS","createHmac","shapeStoreOrders","readWebhooks","WOO_REPORTED_VERSION","WP_REPORTED_VERSION","WOO_WEBHOOK_TIMEOUT_MS","DELIVERY_LOG_TTL_MS","wooActionForEvent","event","status","wooTopicsForEvent","action","resource","wooActionBody","topic","orderId","JSON","stringify","slice","length","arg","signWooWebhook","body","secret","update","digest","wooWebhookHeaders","input","hook","split","source","endsWith","String","id","deliveryId","post","url","init","fetchImpl","result","method","headers","signal","AbortSignal","timeout","error","refusal","caught","name","pingWooWebhook","URLSearchParams","webhook_id","toString","delivery_url","deliverWooWebhooks","envelope","deps","orderSnap","topics","delivered","failed","firestore","app","hooks","hostId","filter","includes","payload","order","hostRef","collection","doc","get","exists","data","orderBody","wooOrderId","isLive","grantId","clock","now","Date","final","attempt","liveByGrant","Map","has","set","catch","logRef","replace","startedAt","startsWith","ok","kind","webhookId","httpStatus","atMs","ms","Math","max","expiresAt","Timestamp","fromMillis","undefined","Error"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0B2C;AAG3C,SAASA,wBAAwB,EAAEC,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AACvG,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,gBAAgB,QAAQ,kBAAc;AAC/C,SAASC,YAAY,QAA4B,gBAAY;AAC7D,SAASC,oBAAoB,EAAEC,mBAAmB,QAAQ,kBAAc;AAExE,wEAAwE,GACxE,OAAO,MAAMC,yBAAyB,MAAM;AAC5C,MAAMC,sBAAsB,KAAK;AAEjC,iEAAiE,GACjE,OAAO,SAASC,kBAAkBC,KAAa;IAC7C,MAAMC,SAAiC;QACrC,cAAc;QACd,mBAAmB;QACnB,mBAAmB;QACnB,kBAAkB;QAClB,mBAAmB;IACrB;IACA,OAAOA,MAAM,CAACD,MAAM,GAAG,CAAC,yBAAyB,EAAEC,MAAM,CAACD,MAA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BiF,WAAWnE,KAAKK,EAAE;YAClB6C,SAASlD,KAAKkD,OAAO;YACrBtE,OAAO+C,SAAS/C,KAAK;YACrBO;YACAN,QAAQoF,KAAK,cAAcX,QAAQ,WAAW;YAC9Cc,YAAYzD,OAAO9B,MAAM;YACzBoC,OAAON,OAAOM,KAAK;YACnBsC,SAAS5B,SAAS4B,OAAO;YACzBc,MAAMN;YACNO,IAAIC,KAAKC,GAAG,CAAC,GAAGrB,UAAUY;YAC1BU,WAAWxG,cAAcgE,SAAS,CAACyC,SAAS,CAACC,UAAU,CAACZ,YAAYrF;QACtE,GACCkF,KAAK,CAAC,IAAMgB;IACjB;IACA,IAAI5C,SAAS,KAAK,CAACsB,OAAO,MAAM,IAAIuB,MAAM,GAAG7C,OAAO,qCAAqC,EAAEL,SAAS/C,KAAK,EAAE;IAC3G,OAAO;QAAEmD;QAAWC;IAAO;AAC7B"}
@@ -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,QAAQ,OA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5B;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,IAAI,CA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