@teleporthq/teleport-plugin-next-data-source 0.43.55 → 0.43.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/array-mapper-cache-wiring.test.ts +425 -0
- package/__tests__/data-source-cache-wrapping.test.ts +152 -0
- package/__tests__/ecommerce-product-allow-backorders.test.ts +156 -0
- package/__tests__/ecommerce-product-model.test.ts +179 -0
- package/__tests__/ecommerce-product-storefront-tax.test.ts +118 -0
- package/dist/cjs/cache/ast.d.ts +71 -0
- package/dist/cjs/cache/ast.d.ts.map +1 -0
- package/dist/cjs/cache/ast.js +229 -0
- package/dist/cjs/cache/ast.js.map +1 -0
- package/dist/cjs/cache/config.d.ts +22 -0
- package/dist/cjs/cache/config.d.ts.map +1 -0
- package/dist/cjs/cache/config.js +67 -0
- package/dist/cjs/cache/config.js.map +1 -0
- package/dist/cjs/cache/types.d.ts +31 -0
- package/dist/cjs/cache/types.d.ts.map +1 -0
- package/dist/cjs/cache/types.js +3 -0
- package/dist/cjs/cache/types.js.map +1 -0
- package/dist/cjs/data-source-fetchers.d.ts +5 -3
- package/dist/cjs/data-source-fetchers.d.ts.map +1 -1
- package/dist/cjs/data-source-fetchers.js +51 -8
- package/dist/cjs/data-source-fetchers.js.map +1 -1
- package/dist/cjs/fetchers/teleport.d.ts +2 -2
- package/dist/cjs/fetchers/teleport.d.ts.map +1 -1
- package/dist/cjs/fetchers/teleport.js +3 -2
- package/dist/cjs/fetchers/teleport.js.map +1 -1
- package/dist/cjs/index.d.ts +2 -0
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +14 -9
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/loading-state.d.ts.map +1 -1
- package/dist/cjs/loading-state.js +74 -2
- package/dist/cjs/loading-state.js.map +1 -1
- package/dist/cjs/pagination-plugin.d.ts.map +1 -1
- package/dist/cjs/pagination-plugin.js +204 -64
- package/dist/cjs/pagination-plugin.js.map +1 -1
- package/dist/cjs/transformations/ecommerce-product.d.ts +27 -1
- package/dist/cjs/transformations/ecommerce-product.d.ts.map +1 -1
- package/dist/cjs/transformations/ecommerce-product.js +8 -3
- package/dist/cjs/transformations/ecommerce-product.js.map +1 -1
- package/dist/cjs/transformations/index.d.ts +14 -2
- package/dist/cjs/transformations/index.d.ts.map +1 -1
- package/dist/cjs/transformations/index.js +37 -3
- package/dist/cjs/transformations/index.js.map +1 -1
- package/dist/cjs/transformations/shared-utils.d.ts.map +1 -1
- package/dist/cjs/transformations/shared-utils.js +1 -1
- package/dist/cjs/transformations/shared-utils.js.map +1 -1
- package/dist/cjs/tsconfig.tsbuildinfo +1 -1
- package/dist/cjs/utils.d.ts +4 -3
- package/dist/cjs/utils.d.ts.map +1 -1
- package/dist/cjs/utils.js +6 -4
- package/dist/cjs/utils.js.map +1 -1
- package/dist/esm/cache/ast.d.ts +71 -0
- package/dist/esm/cache/ast.d.ts.map +1 -0
- package/dist/esm/cache/ast.js +196 -0
- package/dist/esm/cache/ast.js.map +1 -0
- package/dist/esm/cache/config.d.ts +22 -0
- package/dist/esm/cache/config.d.ts.map +1 -0
- package/dist/esm/cache/config.js +62 -0
- package/dist/esm/cache/config.js.map +1 -0
- package/dist/esm/cache/types.d.ts +31 -0
- package/dist/esm/cache/types.d.ts.map +1 -0
- package/dist/esm/cache/types.js +2 -0
- package/dist/esm/cache/types.js.map +1 -0
- package/dist/esm/data-source-fetchers.d.ts +5 -3
- package/dist/esm/data-source-fetchers.d.ts.map +1 -1
- package/dist/esm/data-source-fetchers.js +51 -8
- package/dist/esm/data-source-fetchers.js.map +1 -1
- package/dist/esm/fetchers/teleport.d.ts +2 -2
- package/dist/esm/fetchers/teleport.d.ts.map +1 -1
- package/dist/esm/fetchers/teleport.js +3 -2
- package/dist/esm/fetchers/teleport.js.map +1 -1
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +12 -8
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/loading-state.d.ts.map +1 -1
- package/dist/esm/loading-state.js +74 -2
- package/dist/esm/loading-state.js.map +1 -1
- package/dist/esm/pagination-plugin.d.ts.map +1 -1
- package/dist/esm/pagination-plugin.js +205 -65
- package/dist/esm/pagination-plugin.js.map +1 -1
- package/dist/esm/transformations/ecommerce-product.d.ts +27 -1
- package/dist/esm/transformations/ecommerce-product.d.ts.map +1 -1
- package/dist/esm/transformations/ecommerce-product.js +8 -3
- package/dist/esm/transformations/ecommerce-product.js.map +1 -1
- package/dist/esm/transformations/index.d.ts +14 -2
- package/dist/esm/transformations/index.d.ts.map +1 -1
- package/dist/esm/transformations/index.js +36 -3
- package/dist/esm/transformations/index.js.map +1 -1
- package/dist/esm/transformations/shared-utils.d.ts.map +1 -1
- package/dist/esm/transformations/shared-utils.js +1 -1
- package/dist/esm/transformations/shared-utils.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/dist/esm/utils.d.ts +4 -3
- package/dist/esm/utils.d.ts.map +1 -1
- package/dist/esm/utils.js +6 -4
- package/dist/esm/utils.js.map +1 -1
- package/package.json +5 -5
- package/src/cache/ast.ts +265 -0
- package/src/cache/config.ts +79 -0
- package/src/cache/types.ts +31 -0
- package/src/data-source-fetchers.ts +66 -12
- package/src/fetchers/teleport.ts +3 -3
- package/src/index.ts +10 -4
- package/src/loading-state.ts +65 -2
- package/src/pagination-plugin.ts +315 -116
- package/src/transformations/ecommerce-product.ts +161 -5
- package/src/transformations/index.ts +43 -4
- package/src/transformations/shared-utils.ts +14 -0
- package/src/utils.ts +10 -5
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { StorefrontTax } from '@teleporthq/teleport-shared';
|
|
1
2
|
/**
|
|
2
3
|
* Flattens the nested category tree (`ecommerceSettings.categories`, baked at
|
|
3
4
|
* export time) into an `id -> {name, slug, translations}` lookup map,
|
|
@@ -36,8 +37,12 @@ var flattenCategoriesById = function (categories) {
|
|
|
36
37
|
* Transforms raw snake_case database records into the camelCase shape
|
|
37
38
|
* that UIDL components expect.
|
|
38
39
|
*/
|
|
39
|
-
export var generateEcommerceProductTransformationCode = function (
|
|
40
|
-
var
|
|
41
|
-
return "\n// Category taxonomy (id -> {name, slug, translations}), baked in at export\n// time \u2014 see flattenCategoriesById in ecommerce-product.ts. Empty when the\n// store has no category taxonomy, or products.category_ids simply resolves\n// to nothing.\nvar PRODUCT_CATEGORIES_BY_ID = ".concat(categoriesByIdJson, "\n\n// Resolve a baked category's name to currentLang/mainLang from its\n// translations map (same per-request locale as every other i18n field via\n// resolveI18nField), falling back to the main-language name.\nfunction resolveCategoryName(categoryInfo, currentLang, mainLang) {\n if (currentLang && mainLang && currentLang !== mainLang && categoryInfo.translations) {\n var override = categoryInfo.translations[currentLang]\n if (override && override.name) return override.name\n }\n return categoryInfo.name\n}\n\n// ============================================================\n// E-Commerce Product Transformation\n// ============================================================\n\nfunction buildEcommerceProduct(record, options) {\n if (!record || typeof record !== 'object') return record\n options = options || {}\n var currentLang = options.currentLanguage || null\n var mainLang = options.mainLanguage || null\n var assetMap = options.assetMap || {}\n\n var id = record.id !== undefined && record.id !== null ? record.id : null\n\n // i18n-resolved text fields\n var name = resolveI18nField(record, 'name', 'name', currentLang, mainLang) || ''\n var slug = resolveI18nField(record, 'slug', 'slug', currentLang, mainLang) || ''\n var description = resolveI18nField(record, 'description', 'description', currentLang, mainLang) || ''\n var category = resolveI18nField(record, 'category', 'category', currentLang, mainLang) || null\n var tagsRaw = resolveI18nField(record, 'tags', 'tags', currentLang, mainLang)\n var imageAlt = resolveI18nField(record, 'image_alt', 'imageAlt', currentLang, mainLang) || null\n\n // Computed: plain-text description (HTML stripped)\n var descriptionText = stripHtmlTags(description)\n\n // Numeric fields (with NaN protection)\n var price = safeNumber(record.price, 0)\n var quantity = safeNumber(record.quantity, null)\n\n // Currency\n var currency = (record.currency || 'USD').toUpperCase()\n var rawCurrencySymbol = pickFirst(record.currency_symbol, record.currencySymbol)\n var currencySymbol = rawCurrencySymbol || getCurrencySymbol(currency)\n\n // Status and active (normalize case \u2014 DB / forms may send \"Active\", \"Inactive\", etc.)\n var statusRaw = record.status\n if (statusRaw == null || statusRaw === '') {\n statusRaw = record.active ? 'active' : 'inactive'\n }\n var status =\n typeof statusRaw === 'string'\n ? statusRaw.trim().toLowerCase()\n : String(statusRaw).toLowerCase()\n var active = status === 'active'\n\n // Payment fields\n var paymentType = pickFirst(record.payment_type, record.paymentType) || 'one_time'\n var recurringInterval = pickFirst(record.recurring_interval, record.recurringInterval) || null\n var rawRecurringCount = pickFirst(record.recurring_interval_count, record.recurringIntervalCount)\n var recurringIntervalCount = safeNumber(rawRecurringCount, null)\n\n // Physical product fields\n var sku = record.sku || null\n var weight = safeNumber(record.weight, null)\n var weightUnit = pickFirst(record.weight_unit, record.weightUnit) || null\n var dimensions = record.dimensions || null\n\n // Tags - parse as JSON array (handles JSON strings, arrays, comma-separated)\n var tags = parseJsonArray(tagsRaw)\n\n // Variant AXES (translatable). The i18n-resolved column already carries the\n // display labels for the current language (with the SAME stable keys as the\n // base column); we just parse + normalize. The purchasable combinations live\n // in teleport_product_variants and are fetched by the variant picker widget.\n var variantOptionsRaw = resolveI18nField(record, 'variant_options', 'variantOptions', currentLang, mainLang)\n var variantOptions = normalizeVariantOptions(variantOptionsRaw)\n // Emitted as a STRING ('true'/'false') to match the strict-equality checks the\n // storefront uses (same convention as outOfStock).\n var requiresVariantSelection = variantOptions.length > 0 ? 'true' : 'false'\n\n // Provider fields\n var providerType = pickFirst(record.provider_type, record.providerType) || null\n var providerProductId = pickFirst(record.provider_product_id, record.providerProductId) || null\n var defaultPrice = pickFirst(record.default_price, record.defaultPrice) || null\n\n // Metadata\n var metadata = parseJsonObject(record.metadata)\n\n // Visible custom properties -> [{key,value,kind,color,imageUrl}] for the\n // storefront pills mapper. MUST mirror buildVisibleProductProperties /\n // classifyProductProperty in\n // apps/gui/app/project-page/features/e-commerce/utils/product-property-display.ts\n // (the canvas-preview SSOT) field-for-field: same reserved-key exclusions,\n // same default-VISIBLE (opt-out) rule, same color/image classification. A\n // property is shown unless it is a reserved key, has an empty value, or is\n // explicitly hidden (false) in the _tqPropVisibility map -- so it also\n // renders for products whose form was never opened (no visibility map yet).\n var propVisibility = parseJsonObject(metadata._tqPropVisibility)\n var visibleProperties = []\n Object.keys(metadata).forEach(function (propKey) {\n if (isReservedProductMetadataKey(propKey)) return\n if (propVisibility[propKey] === false) return\n var rawValue = metadata[propKey]\n if (rawValue == null) return\n var propValue = String(rawValue)\n if (propValue.trim() === '') return\n visibleProperties.push(classifyProductProperty(propKey, propValue))\n })\n\n // Assigned category ids -> resolved {id,name,slug} objects for the\n // storefront category pills mapper. The taxonomy itself is not in the DB\n // (categories are authored in the GUI and live only in\n // ecommerceSettings.categories); resolved here against PRODUCT_CATEGORIES_BY_ID,\n // baked in at export time (see flattenCategoriesById). Unknown/stale ids\n // (a deleted category) are silently dropped.\n var categoryIds = parseJsonArray(record.category_ids)\n var categories = []\n for (var ci = 0; ci < categoryIds.length; ci++) {\n var categoryInfo = PRODUCT_CATEGORIES_BY_ID[categoryIds[ci]]\n if (categoryInfo) {\n categories.push({\n id: categoryIds[ci],\n name: resolveCategoryName(categoryInfo, currentLang, mainLang),\n slug: categoryInfo.slug,\n })\n }\n }\n\n // Purchasable variant COMBINATIONS for this product ({id, options map, price,\n // stock, image}). Empty for flat products. Fetched in ONE batched query by\n // transformRecords and passed in via options.variantsByProductId, keyed by\n // product id. The storefront card/details read these to default-select the\n // first in-stock variant, disable dead options, and resolve the chosen id.\n //\n // NULL (not {}) means the lookup could not run \u2014 the table is missing, or the\n // query failed. That is \"combinations UNKNOWN\", which is NOT \"this product has\n // none\": a transient DB failure must never turn every variant product in the\n // catalogue into an unbuyable one. See hasPurchasableVariant below.\n var variantsResolved = options.variantsByProductId != null\n var variantsByProductId = options.variantsByProductId || {}\n var rawVariants = variantsByProductId[id] || []\n var variants = []\n for (var vi = 0; vi < rawVariants.length; vi++) {\n var vrow = rawVariants[vi] || {}\n var vopts = parseJsonObject(vrow.options)\n variants.push({\n id: vrow.id != null ? String(vrow.id) : '',\n options: vopts && typeof vopts === 'object' ? vopts : {},\n price: safeNumber(vrow.price, null),\n quantity: safeNumber(vrow.quantity, null),\n image_url: vrow.image_url ? resolveAssetUrl(vrow.image_url, assetMap) : null,\n })\n }\n\n // The merchant's related-product picks. `relatedProducts` carries the\n // TRANSFORMED rows, not ids, so the details page's related-products rail can\n // map over it and draw a product card per entry; `relatedProductIds` keeps\n // the raw selection for anything that wants it. The rows arrive from ONE\n // batched query (getRelatedProductsMap) that transformRecords runs, keyed by\n // id in options.relatedProductsById.\n //\n // MUST mirror buildRelatedEcommerceProducts in\n // packages/renderer/src/utils/ecommerce-products.ts (the canvas-preview SSOT):\n // the merchant's order, inactive products dropped, self dropped, and the\n // nested build deliberately WITHOUT the map \u2014 two products referencing each\n // other is the normal case (they are each other's accessories) and threading\n // the map through would recurse until the stack ran out.\n var relatedProductIds = parseRelatedIds(record.related_product_ids)\n var relatedProductsById = options.relatedProductsById\n var relatedProducts = []\n if (relatedProductsById && relatedProductIds.length > 0) {\n var relatedNestedOptions = {\n assetMap: assetMap,\n currentLanguage: currentLang,\n mainLanguage: mainLang,\n // Passed through UNCOALESCED so a related product inherits the same\n // known/unknown answer as its parent \u2014 `|| {}` here would tell the nested\n // build \"the lookup ran and found nothing\" and strike out every related\n // card's picker. The batched query includes the related ids for exactly\n // this reason (see getTransformWrapperCode).\n variantsByProductId: options.variantsByProductId,\n }\n for (var rp = 0; rp < relatedProductIds.length; rp++) {\n var relatedId = relatedProductIds[rp]\n if (id != null && relatedId === String(id)) continue\n var relatedRecord = relatedProductsById[relatedId]\n if (!relatedRecord) continue\n // A product taken off sale must not come back through the back door on\n // every product that references it. Missing status reads as active, the\n // same default the main status normalization uses above.\n var relatedStatusRaw = relatedRecord.status\n var relatedStatus =\n relatedStatusRaw == null || relatedStatusRaw === ''\n ? 'active'\n : String(relatedStatusRaw).trim().toLowerCase()\n if (relatedStatus !== 'active') continue\n relatedProducts.push(buildEcommerceProduct(relatedRecord, relatedNestedOptions))\n }\n }\n\n // -------------------------------------------------------\n // Image resolution (complex multi-step process)\n // -------------------------------------------------------\n\n // Step 1: Get raw image values\n var rawImageUrl = pickFirst(record.image_url, record.mainImage, record.imageUrl)\n var rawGalleryImages = pickFirst(record.gallery_images, record.galleryImages)\n var legacyImages = Array.isArray(record.images)\n ? record.images.filter(function(v) { return typeof v === 'string' })\n : []\n\n // Step 2: Parse gallery images from JSON\n var parsedGalleryImages = parseJsonArray(rawGalleryImages)\n\n // Step 3: Build combined raw images array\n var allRawImages = []\n if (rawImageUrl) allRawImages.push(rawImageUrl)\n allRawImages = allRawImages.concat(parsedGalleryImages).concat(legacyImages)\n\n // Step 4: Resolve all asset URLs first, then deduplicate\n var resolvedAll = resolveAssetUrls(allRawImages, assetMap)\n var resolvedImages = deduplicateStrings(resolvedAll)\n\n // Step 5: Determine mainImage\n var mainImage = rawImageUrl\n ? resolveAssetUrl(rawImageUrl, assetMap)\n : (resolvedImages.length > 0 ? resolvedImages[0] : null)\n\n // Step 6: galleryImages = resolvedImages without mainImage\n var galleryImages = mainImage\n ? resolvedImages.filter(function(url) { return url !== mainImage })\n : resolvedImages.slice()\n\n // Step 7: images = full resolved deduplicated array\n var images = resolvedImages\n\n // Timestamps\n var rawCreatedAt = pickFirst(record.created_at, record.createdAt, record.created)\n var createdAt = normalizeTimestamp(rawCreatedAt)\n\n var rawUpdatedAt = pickFirst(record.updated_at, record.updatedAt, record.updated)\n var updatedAt = rawUpdatedAt != null ? normalizeTimestamp(rawUpdatedAt) : createdAt\n\n // Computed: created = Unix seconds\n var created = Math.floor(createdAt / 1000)\n\n // Computed: outOfStock (emitted as a STRING \u2014 'true' / 'false' \u2014 so it\n // matches the strict equality check the AI generates on product\n // cards/details pages: `ecommerceProduct?.outOfStock === 'true'`.\n // A boolean here would silently fail that comparison (boolean !==\n // string), leaving the Add to Cart button visible on out-of-stock\n // products. NULL/NaN quantity \u2192 'false' (treated as \"unlimited\n // stock\", same as the upstream cart-availability rewriter).\n var outOfStock = (quantity !== null && !isNaN(quantity) && quantity <= 0) ? 'true' : 'false'\n\n // Per-value availability + default-selection flags, derived from the\n // purchasable combinations, so the storefront picker renders its\n // Default / Selected / Unavailable states with NO runtime fetch. The card\n // (N instances) first-paints from these data flags; the details page seeds\n // its selection from the same combinations. axisValueKey (axisKey|valueKey)\n // disambiguates same-named values across axes (Size \"s\" vs Sleeve \"s\").\n // Emitted as STRINGS to match the storefront's string-equality convention.\n var variantAxisKeys = []\n for (var ak = 0; ak < variantOptions.length; ak++) { variantAxisKeys.push(variantOptions[ak].key) }\n var firstVariant = pickFirstAvailableVariant(variants, variantAxisKeys)\n var deadValueKeys = computeDeadVariantKeys(variants, variantOptions, variantsResolved)\n for (var ai = 0; ai < variantOptions.length; ai++) {\n var vax = variantOptions[ai]\n for (var vj = 0; vj < vax.values.length; vj++) {\n var vval = vax.values[vj]\n var composite = vax.key + '|' + vval.value\n vval.axisValueKey = composite\n vval.isDead = deadValueKeys[composite] ? 'true' : 'false'\n vval.isDefault =\n firstVariant && firstVariant.options && firstVariant.options[vax.key] === vval.value\n ? 'true'\n : 'false'\n // Whether THIS value renders as a colour swatch vs a text pill. A colour\n // axis whose value has no resolvable colour degrades to a text pill so it\n // is never an invisible empty circle. Emitted as a string to match the\n // picker's string-equality rendering gate. MUST mirror the renderer\n // enrichment in packages/renderer/src/utils/ecommerce-products.ts.\n vval.showSwatch = vax.type === 'color' && vval.color ? 'true' : 'false'\n }\n }\n // The combination the picker auto-selects on first paint: the first in-stock\n // one covering every axis. Absent means there is nothing the shopper could add\n // without choosing \u2014 which is what gates the buy button below.\n var hasInStockCombination = !!(firstVariant && isVariantInStock(firstVariant))\n var defaultVariantId = hasInStockCombination ? firstVariant.id : ''\n var defaultVariantPrice = firstVariant ? formatVariantPrice(firstVariant.price, price) : ''\n // Can this product be added to the cart at all, before the shopper touches the\n // picker? A STRING, same convention as outOfStock/requiresVariantSelection.\n //\n // flat product -> 'true' (stock is governed by outOfStock)\n // combinations UNKNOWN -> 'true' (the lookup could not run; a transient DB\n // failure must never make a whole catalogue\n // unbuyable \u2014 same permissive rule as\n // dead-marking)\n // otherwise -> whether an in-stock combination covering every axis\n // exists. 'false' therefore covers BOTH \"every\n // combination is sold out\" AND \"the axes have no\n // combinations at all\" \u2014 to a shopper those are the\n // same thing: there is no size to pick.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n var hasPurchasableVariant =\n (requiresVariantSelection !== 'true' || !variantsResolved || hasInStockCombination)\n ? 'true'\n : 'false'\n // Stringified companions: a data-* attr bound to an ARRAY renders\n // '[object Object]', so the picker's on-mount/click workflows read the\n // combinations + axes from these JSON strings via getAttribute.\n var variantOptionsJson = safeStringifyJson(variantOptions)\n var variantsJson = safeStringifyJson(variants)\n\n return {\n id: id,\n name: name,\n slug: slug,\n description: description,\n descriptionText: descriptionText,\n price: price,\n currency: currency,\n currencySymbol: currencySymbol,\n status: status,\n active: active,\n quantity: quantity,\n paymentType: paymentType,\n recurringInterval: recurringInterval,\n recurringIntervalCount: recurringIntervalCount,\n sku: sku,\n weight: weight,\n weightUnit: weightUnit,\n dimensions: dimensions,\n category: category,\n categories: categories,\n tags: tags,\n relatedProductIds: relatedProductIds,\n relatedProducts: relatedProducts,\n imageAlt: imageAlt,\n providerType: providerType,\n providerProductId: providerProductId,\n default_price: defaultPrice,\n metadata: metadata,\n visibleProperties: visibleProperties,\n mainImage: mainImage,\n imageUrl: mainImage,\n image_url: mainImage,\n galleryImages: galleryImages,\n images: images,\n createdAt: createdAt,\n updatedAt: updatedAt,\n created: created,\n outOfStock: outOfStock,\n variantOptions: variantOptions,\n requiresVariantSelection: requiresVariantSelection,\n variants: variants,\n variantOptionsJson: variantOptionsJson,\n variantsJson: variantsJson,\n defaultVariantId: defaultVariantId,\n defaultVariantPrice: defaultVariantPrice,\n hasPurchasableVariant: hasPurchasableVariant,\n }\n}\n\n// --- Variant availability helpers (mirror packages/renderer ecommerce-products) ---\n// A variant is in stock when its quantity is null (unlimited) or > 0.\nfunction isVariantInStock(v) {\n return !v ? false : v.quantity == null || v.quantity > 0\n}\nfunction variantCoversAllAxes(v, axisKeys) {\n if (!v || !v.options) return false\n for (var i = 0; i < axisKeys.length; i++) {\n if (v.options[axisKeys[i]] == null) return false\n }\n return true\n}\n// First in-stock combination covering every axis; falls back to the first\n// covering combination (even if OOS) so a fully-OOS product still has a\n// visual default; null when no combination covers the axes.\nfunction pickFirstAvailableVariant(variants, axisKeys) {\n if (!Array.isArray(variants) || !axisKeys.length) return null\n for (var i = 0; i < variants.length; i++) {\n if (variantCoversAllAxes(variants[i], axisKeys) && isVariantInStock(variants[i])) return variants[i]\n }\n for (var j = 0; j < variants.length; j++) {\n if (variantCoversAllAxes(variants[j], axisKeys)) return variants[j]\n }\n return null\n}\n// Map of composite \"axisKey|valueKey\" -> true for every value that appears in\n// NO in-stock combination (rendered as the Unavailable state).\n//\n// variantsResolved is the whole subtlety: dead-marking is only meaningful\n// against combinations we actually LOOKED UP. When the lookup could not run,\n// nothing is dead \u2014 a missing table or a failed query must not grey out every\n// picker in the store. When it DID run, an empty list is a fact, not a gap:\n// every value is unbuyable and renders as Unavailable.\nfunction computeDeadVariantKeys(variants, axes, variantsResolved) {\n if (!variantsResolved || !Array.isArray(variants)) return {}\n var alive = {}\n for (var i = 0; i < variants.length; i++) {\n var v = variants[i]\n if (!isVariantInStock(v)) continue\n for (var k in v.options) {\n if (Object.prototype.hasOwnProperty.call(v.options, k)) alive[k + '|' + v.options[k]] = true\n }\n }\n var dead = {}\n for (var a = 0; a < axes.length; a++) {\n var ax = axes[a]\n for (var b = 0; b < ax.values.length; b++) {\n var key = ax.key + '|' + ax.values[b].value\n if (!alive[key]) dead[key] = true\n }\n }\n return dead\n}\n// Variant price with base-price inheritance (null variant price -> product price).\nfunction formatVariantPrice(vprice, basePrice) {\n var p = vprice == null || isNaN(vprice) ? basePrice : vprice\n return String(Number(p).toFixed(2))\n}\nfunction safeStringifyJson(obj) {\n try {\n return JSON.stringify(obj)\n } catch (e) {\n return '[]'\n }\n}\n\n// Parse + normalize the variant_options JSON into render-ready axes. Tolerant of\n// null / malformed / partial data (returns []). Keeps ONLY the fields the pill\n// widget needs; the labels are already language-resolved by the caller.\nfunction normalizeVariantOptions(raw) {\n if (!raw) return []\n var parsed = raw\n if (typeof raw === 'string') {\n try { parsed = JSON.parse(raw) } catch (e) { return [] }\n }\n if (!Array.isArray(parsed)) return []\n var out = []\n for (var i = 0; i < parsed.length; i++) {\n var axis = parsed[i]\n if (!axis || typeof axis !== 'object' || !Array.isArray(axis.values)) continue\n var name = typeof axis.name === 'string' ? axis.name : ''\n var key = typeof axis.key === 'string' && axis.key ? axis.key : name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!key) continue\n var type = axis.type === 'color' ? 'color' : 'text'\n var values = []\n for (var j = 0; j < axis.values.length; j++) {\n var v = axis.values[j]\n if (!v || typeof v !== 'object') continue\n var label = typeof v.label === 'string' ? v.label : ''\n var value = typeof v.value === 'string' && v.value ? v.value : label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!value) continue\n var entry = { value: value, label: label }\n if (type === 'color' && typeof v.color === 'string' && v.color) entry.color = v.color\n values.push(entry)\n }\n if (!values.length) continue\n out.push({ key: key, name: name, type: type, values: values })\n }\n return out\n}\n\n// --- Custom-property classification (MUST mirror product-property-display.ts) ---\n\n// Product-attribute keys that can leak into the free-form `metadata` map (e.g.\n// from a payment-provider sync or legacy data) but are NOT user custom\n// properties. Kept in sync with the GUI's RESERVED_PRODUCT_METADATA_KEYS.\nvar RESERVED_PRODUCT_METADATA_KEYS = {\n paymentType: true, recurringInterval: true, recurringIntervalCount: true,\n price: true, currency: true, status: true, sku: true, weightUnit: true,\n dimensions: true, category: true, brand: true, gtin: true, mpn: true,\n condition: true, tags: true,\n}\nfunction isReservedProductMetadataKey(key) {\n return !!RESERVED_PRODUCT_METADATA_KEYS[key] ||\n key.indexOf('mainImage') === 0 ||\n key.indexOf('secondaryImage') === 0 ||\n key.indexOf('_tq') === 0\n}\n\nvar CSS_NAMED_COLORS = {\n aliceblue: 1, antiquewhite: 1, aqua: 1, aquamarine: 1, azure: 1, beige: 1, bisque: 1,\n black: 1, blanchedalmond: 1, blue: 1, blueviolet: 1, brown: 1, burlywood: 1,\n cadetblue: 1, chartreuse: 1, chocolate: 1, coral: 1, cornflowerblue: 1, cornsilk: 1,\n crimson: 1, cyan: 1, darkblue: 1, darkcyan: 1, darkgoldenrod: 1, darkgray: 1,\n darkgrey: 1, darkgreen: 1, darkkhaki: 1, darkmagenta: 1, darkolivegreen: 1,\n darkorange: 1, darkorchid: 1, darkred: 1, darksalmon: 1, darkseagreen: 1,\n darkslateblue: 1, darkslategray: 1, darkslategrey: 1, darkturquoise: 1,\n darkviolet: 1, deeppink: 1, deepskyblue: 1, dimgray: 1, dimgrey: 1, dodgerblue: 1,\n firebrick: 1, floralwhite: 1, forestgreen: 1, fuchsia: 1, gainsboro: 1,\n ghostwhite: 1, gold: 1, goldenrod: 1, gray: 1, grey: 1, green: 1, greenyellow: 1,\n honeydew: 1, hotpink: 1, indianred: 1, indigo: 1, ivory: 1, khaki: 1, lavender: 1,\n lavenderblush: 1, lawngreen: 1, lemonchiffon: 1, lightblue: 1, lightcoral: 1,\n lightcyan: 1, lightgoldenrodyellow: 1, lightgray: 1, lightgrey: 1, lightgreen: 1,\n lightpink: 1, lightsalmon: 1, lightseagreen: 1, lightskyblue: 1, lightslategray: 1,\n lightslategrey: 1, lightsteelblue: 1, lightyellow: 1, lime: 1, limegreen: 1,\n linen: 1, magenta: 1, maroon: 1, mediumaquamarine: 1, mediumblue: 1,\n mediumorchid: 1, mediumpurple: 1, mediumseagreen: 1, mediumslateblue: 1,\n mediumspringgreen: 1, mediumturquoise: 1, mediumvioletred: 1, midnightblue: 1,\n mintcream: 1, mistyrose: 1, moccasin: 1, navajowhite: 1, navy: 1, oldlace: 1,\n olive: 1, olivedrab: 1, orange: 1, orangered: 1, orchid: 1, palegoldenrod: 1,\n palegreen: 1, paleturquoise: 1, palevioletred: 1, papayawhip: 1, peachpuff: 1,\n peru: 1, pink: 1, plum: 1, powderblue: 1, purple: 1, rebeccapurple: 1, red: 1,\n rosybrown: 1, royalblue: 1, saddlebrown: 1, salmon: 1, sandybrown: 1, seagreen: 1,\n seashell: 1, sienna: 1, silver: 1, skyblue: 1, slateblue: 1, slategray: 1,\n slategrey: 1, snow: 1, springgreen: 1, steelblue: 1, tan: 1, teal: 1, thistle: 1,\n tomato: 1, turquoise: 1, violet: 1, wheat: 1, white: 1, whitesmoke: 1, yellow: 1,\n yellowgreen: 1, transparent: 1,\n}\nvar HEX_COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nvar FUNCTIONAL_COLOR_RE = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\((?:[0-9a-z%.,\\s/+-]+)\\)$/i\nvar COLOR_KEY_WORDS = {\n color: 1, colors: 1, colour: 1, colours: 1, shade: 1, shades: 1, hue: 1, hues: 1,\n tint: 1, tints: 1, tone: 1, tones: 1, swatch: 1, swatches: 1,\n}\nfunction splitKeyWords(key) {\n return key.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)\n}\nfunction keyIndicatesColor(key) {\n var normalized = key.toLowerCase()\n if (/colou?r/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!COLOR_KEY_WORDS[word] })\n}\nfunction resolvePropertyColor(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (HEX_COLOR_RE.test(v) || FUNCTIONAL_COLOR_RE.test(v)) return v\n if (CSS_NAMED_COLORS[v.toLowerCase()] && keyIndicatesColor(key)) return v\n return ''\n}\n\nvar DATA_IMAGE_URI_RE = /^data:image\\//i\nvar ABSOLUTE_URL_RE = /^(?:https?:)?\\/\\//i\nvar IMAGE_EXTENSION_RE = /\\.(?:png|jpe?g|gif|webp|svg|avif|bmp|ico|tiff?|heic|heif)$/i\nvar IMAGE_KEY_WORDS = {\n image: 1, images: 1, img: 1, imgs: 1, photo: 1, photos: 1, picture: 1, pictures: 1,\n pic: 1, pics: 1, thumbnail: 1, thumbnails: 1, thumb: 1, thumbs: 1, icon: 1, icons: 1,\n logo: 1, logos: 1, avatar: 1, avatars: 1, banner: 1, banners: 1, cover: 1, covers: 1,\n gallery: 1, screenshot: 1, screenshots: 1, poster: 1, posters: 1, artwork: 1,\n graphic: 1, graphics: 1, illustration: 1, wallpaper: 1, preview: 1, snapshot: 1,\n media: 1, visual: 1, visuals: 1,\n}\nfunction keyIndicatesImage(key) {\n var normalized = key.toLowerCase()\n if (/(?:image|img|photo|picture|thumb|icon|logo|avatar|banner|gallery|screenshot|poster|artwork|graphic|wallpaper)/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!IMAGE_KEY_WORDS[word] })\n}\nfunction stripUrlQueryAndHash(url) {\n return url.split(/[?#]/)[0]\n}\nfunction resolvePropertyImage(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (DATA_IMAGE_URI_RE.test(v)) return v\n var isAbsoluteUrl = ABSOLUTE_URL_RE.test(v)\n var isRootRelative = v.charAt(0) === '/' && !isAbsoluteUrl\n if (!isAbsoluteUrl && !isRootRelative) return ''\n if (IMAGE_EXTENSION_RE.test(stripUrlQueryAndHash(v))) return v\n if (isAbsoluteUrl && keyIndicatesImage(key)) return v\n return ''\n}\n\n// Image wins over colour (a URL can never be a CSS colour, but checking image\n// first keeps the precedence explicit), text is the fallback.\nfunction classifyProductProperty(key, value) {\n var imageUrl = resolvePropertyImage(key, value)\n if (imageUrl) return { key: key, value: value, kind: 'image', color: '', imageUrl: imageUrl }\n var color = resolvePropertyColor(key, value)\n if (color) return { key: key, value: value, kind: 'color', color: color, imageUrl: '' }\n return { key: key, value: value, kind: 'text', color: '', imageUrl: '' }\n}\n\nfunction transformEcommerceProducts(records, options) {\n if (!Array.isArray(records)) return []\n return records.map(function(record) { return buildEcommerceProduct(record, options) })\n}\n\n// Batched fetch of the purchasable variant rows for a set of product ids, keyed\n// by product_id, so buildEcommerceProduct can attach product.variants without a\n// per-product query. Best-effort: a store with no variants (or before the table\n// exists) yields an empty map and flat products keep variants: [].\n// Batched fetch of the product rows a set of products reference as \"related\",\n// keyed by id, so buildEcommerceProduct can attach product.relatedProducts\n// without a query per product.\n//\n// Best-effort by design: a store whose products table predates the column\n// yields no ids at all (the read below is of an absent property, not of a\n// column \u2014 the SQL never names it), the map stays empty, and the details page's\n// rail simply stays hidden behind its is_not_empty gate. Same for a failed\n// query.\nasync function getRelatedProductsMap(getClientFn, records) {\n var map = {}\n if (!Array.isArray(records) || records.length === 0) return map\n\n var wantedIds = []\n for (var i = 0; i < records.length; i++) {\n var ids = parseRelatedIds(records[i] && records[i].related_product_ids)\n for (var j = 0; j < ids.length; j++) {\n if (wantedIds.indexOf(ids[j]) === -1) wantedIds.push(ids[j])\n }\n }\n if (wantedIds.length === 0) return map\n\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query('SELECT * FROM teleport_products WHERE id = ANY($1)', [\n wantedIds,\n ])\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n if (row && row.id != null) map[String(row.id)] = row\n }\n }\n } catch (e) {\n // Leaves relatedProducts empty rather than failing the page.\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n\n// Combinations for every product on the page, keyed by product id. Returns NULL\n// when the lookup could not run, which the transform reads as \"unknown\" and\n// stays permissive with; an empty map means the query ran and this catalogue\n// simply has no combinations.\nasync function getVariantsMap(getClientFn, productIds) {\n var map = {}\n if (!Array.isArray(productIds) || productIds.length === 0) return map\n var uniqueIds = []\n var seenIds = {}\n for (var u = 0; u < productIds.length; u++) {\n var pid0 = productIds[u]\n if (pid0 != null && !seenIds[pid0]) { seenIds[pid0] = true; uniqueIds.push(pid0) }\n }\n if (uniqueIds.length === 0) return map\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query(\n 'SELECT id, product_id, options, price, quantity, image_url FROM teleport_product_variants WHERE product_id = ANY($1) ORDER BY position ASC, id ASC',\n [uniqueIds]\n )\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n var pid = row.product_id\n if (!map[pid]) map[pid] = []\n map[pid].push(row)\n }\n }\n } catch (e) {\n // teleport_product_variants may not exist for a non-variant store, or the\n // query may have failed. Either way the combinations are UNKNOWN \u2014 null\n // keeps every picker selectable instead of declaring the catalogue unbuyable.\n map = null\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n");
|
|
40
|
+
export var generateEcommerceProductTransformationCode = function (options) {
|
|
41
|
+
var _a;
|
|
42
|
+
if (options === void 0) { options = {}; }
|
|
43
|
+
var categoriesByIdJson = JSON.stringify(flattenCategoriesById(options.categories));
|
|
44
|
+
var taxHelperCode = StorefrontTax.generateStorefrontTaxHelperCode((_a = options.storefrontTaxRate) !== null && _a !== void 0 ? _a : 0);
|
|
45
|
+
var allowBackordersLiteral = options.allowBackorders === true ? 'true' : 'false';
|
|
46
|
+
return "\n".concat(taxHelperCode, "\n\n// Baked from the merchant's stock settings: TRUE when stock never blocks a\n// purchase (stock management off OR backorders allowed). Regenerating the\n// project refreshes it \u2014 do not hand-edit. See EcommerceProductTransformOptions.\nvar ALLOW_BACKORDERS = ").concat(allowBackordersLiteral, "\n\n// Category taxonomy (id -> {name, slug, translations}), baked in at export\n// time \u2014 see flattenCategoriesById in ecommerce-product.ts. Empty when the\n// store has no category taxonomy, or products.category_ids simply resolves\n// to nothing.\nvar PRODUCT_CATEGORIES_BY_ID = ").concat(categoriesByIdJson, "\n\n// Resolve a baked category's name to currentLang/mainLang from its\n// translations map (same per-request locale as every other i18n field via\n// resolveI18nField), falling back to the main-language name.\nfunction resolveCategoryName(categoryInfo, currentLang, mainLang) {\n if (currentLang && mainLang && currentLang !== mainLang && categoryInfo.translations) {\n var override = categoryInfo.translations[currentLang]\n if (override && override.name) return override.name\n }\n return categoryInfo.name\n}\n\n// The merchant's \"Show 3D model by default\" toggle, as every backend may hand\n// it back: a real boolean, 1/0, 'true'/'false'/'t'/'f' strings \u2014 and NULL /\n// absent / '' as ON, because a product that has a model shows it unless the\n// merchant switched it off. MUST mirror normalizeShowModelFlag in the GUI's\n// features/e-commerce/constants/product-model.ts.\nfunction normalizeShowModelFlag(raw) {\n if (raw === null || raw === undefined || raw === '') return true\n if (typeof raw === 'boolean') return raw\n if (typeof raw === 'number') return raw !== 0\n if (typeof raw === 'string') {\n var token = raw.trim().toLowerCase()\n return !(token === 'false' || token === 'f' || token === '0' || token === 'no' || token === 'off')\n }\n return true\n}\n\n// The product's media gallery in display order, HERO FIRST: the model when it\n// is shown by default, otherwise the images with the model last. Each entry is\n// { kind: 'image' | 'model', src, poster, thumbnail, alt }; 'thumbnail' is what\n// a strip draws and is never empty for an entry that can appear in one. MUST\n// mirror buildProductGalleryMedia in the GUI's\n// features/e-commerce/utils/product-gallery-media.ts.\nfunction buildProductGalleryMedia(params) {\n var imageItems = []\n for (var gi = 0; gi < params.images.length; gi++) {\n imageItems.push({\n kind: 'image',\n src: params.images[gi],\n poster: '',\n thumbnail: params.images[gi],\n alt: params.imageAlt || params.name,\n })\n }\n if (!params.modelUrl) return imageItems\n var modelItem = {\n kind: 'model',\n src: params.modelUrl,\n poster: params.modelPoster || '',\n thumbnail: params.modelPoster || params.mainImage || params.images[0] || '',\n alt: params.name,\n }\n return params.showModel === 'true' ? [modelItem].concat(imageItems) : imageItems.concat([modelItem])\n}\n\n// ============================================================\n// E-Commerce Product Transformation\n// ============================================================\n\nfunction buildEcommerceProduct(record, options) {\n if (!record || typeof record !== 'object') return record\n options = options || {}\n var currentLang = options.currentLanguage || null\n var mainLang = options.mainLanguage || null\n var assetMap = options.assetMap || {}\n\n var id = record.id !== undefined && record.id !== null ? record.id : null\n\n // i18n-resolved text fields\n var name = resolveI18nField(record, 'name', 'name', currentLang, mainLang) || ''\n var slug = resolveI18nField(record, 'slug', 'slug', currentLang, mainLang) || ''\n var description = resolveI18nField(record, 'description', 'description', currentLang, mainLang) || ''\n var category = resolveI18nField(record, 'category', 'category', currentLang, mainLang) || null\n var tagsRaw = resolveI18nField(record, 'tags', 'tags', currentLang, mainLang)\n var imageAlt = resolveI18nField(record, 'image_alt', 'imageAlt', currentLang, mainLang) || null\n\n // Computed: plain-text description (HTML stripped)\n var descriptionText = stripHtmlTags(description)\n\n // Numeric fields (with NaN protection)\n var price = safeNumber(record.price, 0)\n var quantity = safeNumber(record.quantity, null)\n\n // Currency\n var currency = (record.currency || 'USD').toUpperCase()\n var rawCurrencySymbol = pickFirst(record.currency_symbol, record.currencySymbol)\n var currencySymbol = rawCurrencySymbol || getCurrencySymbol(currency)\n\n // Status and active (normalize case \u2014 DB / forms may send \"Active\", \"Inactive\", etc.)\n var statusRaw = record.status\n if (statusRaw == null || statusRaw === '') {\n statusRaw = record.active ? 'active' : 'inactive'\n }\n var status =\n typeof statusRaw === 'string'\n ? statusRaw.trim().toLowerCase()\n : String(statusRaw).toLowerCase()\n var active = status === 'active'\n\n // Payment fields\n var paymentType = pickFirst(record.payment_type, record.paymentType) || 'one_time'\n var recurringInterval = pickFirst(record.recurring_interval, record.recurringInterval) || null\n var rawRecurringCount = pickFirst(record.recurring_interval_count, record.recurringIntervalCount)\n var recurringIntervalCount = safeNumber(rawRecurringCount, null)\n\n // Physical product fields\n var sku = record.sku || null\n var weight = safeNumber(record.weight, null)\n var weightUnit = pickFirst(record.weight_unit, record.weightUnit) || null\n var dimensions = record.dimensions || null\n\n // Tags - parse as JSON array (handles JSON strings, arrays, comma-separated)\n var tags = parseJsonArray(tagsRaw)\n\n // Variant AXES (translatable). The i18n-resolved column already carries the\n // display labels for the current language (with the SAME stable keys as the\n // base column); we just parse + normalize. The purchasable combinations live\n // in teleport_product_variants and are fetched by the variant picker widget.\n var variantOptionsRaw = resolveI18nField(record, 'variant_options', 'variantOptions', currentLang, mainLang)\n var variantOptions = normalizeVariantOptions(variantOptionsRaw)\n // Emitted as a STRING ('true'/'false') to match the strict-equality checks the\n // storefront uses (same convention as outOfStock).\n var requiresVariantSelection = variantOptions.length > 0 ? 'true' : 'false'\n\n // Provider fields\n var providerType = pickFirst(record.provider_type, record.providerType) || null\n var providerProductId = pickFirst(record.provider_product_id, record.providerProductId) || null\n var defaultPrice = pickFirst(record.default_price, record.defaultPrice) || null\n\n // Metadata\n var metadata = parseJsonObject(record.metadata)\n\n // Visible custom properties -> [{key,value,kind,color,imageUrl}] for the\n // storefront pills mapper. MUST mirror buildVisibleProductProperties /\n // classifyProductProperty in\n // apps/gui/app/project-page/features/e-commerce/utils/product-property-display.ts\n // (the canvas-preview SSOT) field-for-field: same reserved-key exclusions,\n // same default-VISIBLE (opt-out) rule, same color/image classification. A\n // property is shown unless it is a reserved key, has an empty value, or is\n // explicitly hidden (false) in the _tqPropVisibility map -- so it also\n // renders for products whose form was never opened (no visibility map yet).\n var propVisibility = parseJsonObject(metadata._tqPropVisibility)\n var visibleProperties = []\n Object.keys(metadata).forEach(function (propKey) {\n if (isReservedProductMetadataKey(propKey)) return\n if (propVisibility[propKey] === false) return\n var rawValue = metadata[propKey]\n if (rawValue == null) return\n var propValue = String(rawValue)\n if (propValue.trim() === '') return\n visibleProperties.push(classifyProductProperty(propKey, propValue))\n })\n\n // Assigned category ids -> resolved {id,name,slug} objects for the\n // storefront category pills mapper. The taxonomy itself is not in the DB\n // (categories are authored in the GUI and live only in\n // ecommerceSettings.categories); resolved here against PRODUCT_CATEGORIES_BY_ID,\n // baked in at export time (see flattenCategoriesById). Unknown/stale ids\n // (a deleted category) are silently dropped.\n var categoryIds = parseJsonArray(record.category_ids)\n var categories = []\n for (var ci = 0; ci < categoryIds.length; ci++) {\n var categoryInfo = PRODUCT_CATEGORIES_BY_ID[categoryIds[ci]]\n if (categoryInfo) {\n categories.push({\n id: categoryIds[ci],\n name: resolveCategoryName(categoryInfo, currentLang, mainLang),\n slug: categoryInfo.slug,\n })\n }\n }\n\n // Purchasable variant COMBINATIONS for this product ({id, options map, price,\n // stock, image}). Empty for flat products. Fetched in ONE batched query by\n // transformRecords and passed in via options.variantsByProductId, keyed by\n // product id. The storefront card/details read these to default-select the\n // first in-stock variant, disable dead options, and resolve the chosen id.\n //\n // NULL (not {}) means the lookup could not run \u2014 the table is missing, or the\n // query failed. That is \"combinations UNKNOWN\", which is NOT \"this product has\n // none\": a transient DB failure must never turn every variant product in the\n // catalogue into an unbuyable one. See hasPurchasableVariant below.\n var variantsResolved = options.variantsByProductId != null\n var variantsByProductId = options.variantsByProductId || {}\n var rawVariants = variantsByProductId[id] || []\n var variants = []\n for (var vi = 0; vi < rawVariants.length; vi++) {\n var vrow = rawVariants[vi] || {}\n var vopts = parseJsonObject(vrow.options)\n variants.push({\n id: vrow.id != null ? String(vrow.id) : '',\n options: vopts && typeof vopts === 'object' ? vopts : {},\n price: safeNumber(vrow.price, null),\n quantity: safeNumber(vrow.quantity, null),\n image_url: vrow.image_url ? resolveAssetUrl(vrow.image_url, assetMap) : null,\n })\n }\n\n // The merchant's related-product picks. `relatedProducts` carries the\n // TRANSFORMED rows, not ids, so the details page's related-products rail can\n // map over it and draw a product card per entry; `relatedProductIds` keeps\n // the raw selection for anything that wants it. The rows arrive from ONE\n // batched query (getRelatedProductsMap) that transformRecords runs, keyed by\n // id in options.relatedProductsById.\n //\n // MUST mirror buildRelatedEcommerceProducts in\n // packages/renderer/src/utils/ecommerce-products.ts (the canvas-preview SSOT):\n // the merchant's order, inactive products dropped, self dropped, and the\n // nested build deliberately WITHOUT the map \u2014 two products referencing each\n // other is the normal case (they are each other's accessories) and threading\n // the map through would recurse until the stack ran out.\n var relatedProductIds = parseRelatedIds(record.related_product_ids)\n var relatedProductsById = options.relatedProductsById\n var relatedProducts = []\n if (relatedProductsById && relatedProductIds.length > 0) {\n var relatedNestedOptions = {\n assetMap: assetMap,\n currentLanguage: currentLang,\n mainLanguage: mainLang,\n // Passed through UNCOALESCED so a related product inherits the same\n // known/unknown answer as its parent \u2014 `|| {}` here would tell the nested\n // build \"the lookup ran and found nothing\" and strike out every related\n // card's picker. The batched query includes the related ids for exactly\n // this reason (see getTransformWrapperCode).\n variantsByProductId: options.variantsByProductId,\n }\n for (var rp = 0; rp < relatedProductIds.length; rp++) {\n var relatedId = relatedProductIds[rp]\n if (id != null && relatedId === String(id)) continue\n var relatedRecord = relatedProductsById[relatedId]\n if (!relatedRecord) continue\n // A product taken off sale must not come back through the back door on\n // every product that references it. Missing status reads as active, the\n // same default the main status normalization uses above.\n var relatedStatusRaw = relatedRecord.status\n var relatedStatus =\n relatedStatusRaw == null || relatedStatusRaw === ''\n ? 'active'\n : String(relatedStatusRaw).trim().toLowerCase()\n if (relatedStatus !== 'active') continue\n relatedProducts.push(buildEcommerceProduct(relatedRecord, relatedNestedOptions))\n }\n }\n\n // -------------------------------------------------------\n // Image resolution (complex multi-step process)\n // -------------------------------------------------------\n\n // Step 1: Get raw image values\n var rawImageUrl = pickFirst(record.image_url, record.mainImage, record.imageUrl)\n var rawGalleryImages = pickFirst(record.gallery_images, record.galleryImages)\n var legacyImages = Array.isArray(record.images)\n ? record.images.filter(function(v) { return typeof v === 'string' })\n : []\n\n // Step 2: Parse gallery images from JSON\n var parsedGalleryImages = parseJsonArray(rawGalleryImages)\n\n // Step 3: Build combined raw images array\n var allRawImages = []\n if (rawImageUrl) allRawImages.push(rawImageUrl)\n allRawImages = allRawImages.concat(parsedGalleryImages).concat(legacyImages)\n\n // Step 4: Resolve all asset URLs first, then deduplicate\n var resolvedAll = resolveAssetUrls(allRawImages, assetMap)\n var resolvedImages = deduplicateStrings(resolvedAll)\n\n // Step 5: Determine mainImage\n var mainImage = rawImageUrl\n ? resolveAssetUrl(rawImageUrl, assetMap)\n : (resolvedImages.length > 0 ? resolvedImages[0] : null)\n\n // Step 6: galleryImages = resolvedImages without mainImage\n var galleryImages = mainImage\n ? resolvedImages.filter(function(url) { return url !== mainImage })\n : resolvedImages.slice()\n\n // Step 7: images = full resolved deduplicated array\n var images = resolvedImages\n\n // -------------------------------------------------------\n // 3D model (one per product; GUI: constants/product-model.ts)\n // -------------------------------------------------------\n // model_url / model_poster_url hold an asset id OR a raw URL like image_url.\n // A poster the merchant never got (capture failed, plan cap) falls back to\n // the main image so <model-viewer> always has something to paint first.\n var modelUrl = resolveMediaUrl(record.model_url, assetMap)\n var modelPoster = modelUrl ? resolveMediaUrl(record.model_poster_url, assetMap) || mainImage : null\n var hasModel = modelUrl ? 'true' : 'false'\n // STRING gate ('true'/'false') like outOfStock: whether the model replaces the\n // main image on the card / details hero. A product whose only media is the\n // model always shows it. An absent field must read as the IMAGE branch, so the\n // builders gate the viewer on = 'true' and the image on != 'true'.\n var showModel =\n modelUrl && (normalizeShowModelFlag(record.show_model_by_default) || images.length === 0)\n ? 'true'\n : 'false'\n var galleryMedia = buildProductGalleryMedia({\n images: images,\n mainImage: mainImage,\n modelUrl: modelUrl,\n modelPoster: modelPoster,\n showModel: showModel,\n imageAlt: imageAlt,\n name: name,\n })\n // Everything that is not the hero \u2014 the details thumbnail strip. When the\n // model is the hero the main image moves in here, so the modal stays reachable.\n var galleryThumbnails = galleryMedia.slice(1)\n\n // Timestamps\n var rawCreatedAt = pickFirst(record.created_at, record.createdAt, record.created)\n var createdAt = normalizeTimestamp(rawCreatedAt)\n\n var rawUpdatedAt = pickFirst(record.updated_at, record.updatedAt, record.updated)\n var updatedAt = rawUpdatedAt != null ? normalizeTimestamp(rawUpdatedAt) : createdAt\n\n // Computed: created = Unix seconds\n var created = Math.floor(createdAt / 1000)\n\n // Computed: outOfStock (emitted as a STRING \u2014 'true' / 'false' \u2014 so it\n // matches the strict equality check the AI generates on product\n // cards/details pages: `ecommerceProduct?.outOfStock === 'true'`.\n // A boolean here would silently fail that comparison (boolean !==\n // string), leaving the Add to Cart button visible on out-of-stock\n // products. NULL/NaN quantity \u2192 'false' (treated as \"unlimited\n // stock\", same as the upstream cart-availability rewriter).\n // With ALLOW_BACKORDERS the merchant sells past zero (or does not track\n // stock at all), so nothing is ever presented as out of stock.\n var outOfStock = (!ALLOW_BACKORDERS && quantity !== null && !isNaN(quantity) && quantity <= 0) ? 'true' : 'false'\n\n // Per-value availability + default-selection flags, derived from the\n // purchasable combinations, so the storefront picker renders its\n // Default / Selected / Unavailable states with NO runtime fetch. The card\n // (N instances) first-paints from these data flags; the details page seeds\n // its selection from the same combinations. axisValueKey (axisKey|valueKey)\n // disambiguates same-named values across axes (Size \"s\" vs Sleeve \"s\").\n // Emitted as STRINGS to match the storefront's string-equality convention.\n var variantAxisKeys = []\n for (var ak = 0; ak < variantOptions.length; ak++) { variantAxisKeys.push(variantOptions[ak].key) }\n var firstVariant = pickFirstAvailableVariant(variants, variantAxisKeys)\n var deadValueKeys = computeDeadVariantKeys(variants, variantOptions, variantsResolved)\n for (var ai = 0; ai < variantOptions.length; ai++) {\n var vax = variantOptions[ai]\n for (var vj = 0; vj < vax.values.length; vj++) {\n var vval = vax.values[vj]\n var composite = vax.key + '|' + vval.value\n vval.axisValueKey = composite\n vval.isDead = deadValueKeys[composite] ? 'true' : 'false'\n vval.isDefault =\n firstVariant && firstVariant.options && firstVariant.options[vax.key] === vval.value\n ? 'true'\n : 'false'\n // Whether THIS value renders as a colour swatch vs a text pill. A colour\n // axis whose value has no resolvable colour degrades to a text pill so it\n // is never an invisible empty circle. Emitted as a string to match the\n // picker's string-equality rendering gate. MUST mirror the renderer\n // enrichment in packages/renderer/src/utils/ecommerce-products.ts.\n vval.showSwatch = vax.type === 'color' && vval.color ? 'true' : 'false'\n }\n }\n // The combination the picker auto-selects on first paint: the first in-stock\n // one covering every axis. Absent means there is nothing the shopper could add\n // without choosing \u2014 which is what gates the buy button below.\n var hasInStockCombination = !!(firstVariant && isVariantInStock(firstVariant))\n var defaultVariantId = hasInStockCombination ? firstVariant.id : ''\n var defaultVariantPrice = firstVariant ? formatVariantPrice(firstVariant.price, price) : ''\n // Gross (tax-inclusive) counterparts of the three price fields the STOREFRONT\n // renders. `price` / `defaultVariantPrice` / `variantsJson` deliberately stay\n // NET: the same transform feeds the merchant's admin panel, and every write\n // path (add-to-cart, checkout, the invoice route) re-reads the raw row and\n // must keep seeing the price the merchant typed. Only these three are safe to\n // gross, because nothing writes them back.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n var displayPrice = grossMoney(price)\n var defaultVariantDisplayPrice = firstVariant\n ? grossMoney(formatVariantPrice(firstVariant.price, price))\n : ''\n var variantsDisplay = []\n for (var dv = 0; dv < variants.length; dv++) {\n var dvRow = variants[dv]\n variantsDisplay.push({\n id: dvRow.id,\n options: dvRow.options,\n // A null variant price INHERITS the product price, so gross the RESOLVED\n // value \u2014 otherwise an inheriting combination would fall back to the net\n // base price in the picker while an overriding one showed gross.\n price: applyStorefrontTax(dvRow.price == null ? price : dvRow.price),\n quantity: dvRow.quantity,\n image_url: dvRow.image_url,\n })\n }\n // Can this product be added to the cart at all, before the shopper touches the\n // picker? A STRING, same convention as outOfStock/requiresVariantSelection.\n //\n // flat product -> 'true' (stock is governed by outOfStock)\n // combinations UNKNOWN -> 'true' (the lookup could not run; a transient DB\n // failure must never make a whole catalogue\n // unbuyable \u2014 same permissive rule as\n // dead-marking)\n // otherwise -> whether an in-stock combination covering every axis\n // exists. 'false' therefore covers BOTH \"every\n // combination is sold out\" AND \"the axes have no\n // combinations at all\" \u2014 to a shopper those are the\n // same thing: there is no size to pick.\n //\n // MUST mirror packages/renderer/src/utils/ecommerce-products.ts.\n var hasPurchasableVariant =\n (requiresVariantSelection !== 'true' || !variantsResolved || hasInStockCombination)\n ? 'true'\n : 'false'\n // Stringified companions: a data-* attr bound to an ARRAY renders\n // '[object Object]', so the picker's on-mount/click workflows read the\n // combinations + axes from these JSON strings via getAttribute.\n var variantOptionsJson = safeStringifyJson(variantOptions)\n var variantsJson = safeStringifyJson(variants)\n var variantsDisplayJson = safeStringifyJson(variantsDisplay)\n\n return {\n id: id,\n name: name,\n slug: slug,\n description: description,\n descriptionText: descriptionText,\n price: price,\n currency: currency,\n currencySymbol: currencySymbol,\n status: status,\n active: active,\n quantity: quantity,\n paymentType: paymentType,\n recurringInterval: recurringInterval,\n recurringIntervalCount: recurringIntervalCount,\n sku: sku,\n weight: weight,\n weightUnit: weightUnit,\n dimensions: dimensions,\n category: category,\n categories: categories,\n tags: tags,\n relatedProductIds: relatedProductIds,\n relatedProducts: relatedProducts,\n imageAlt: imageAlt,\n providerType: providerType,\n providerProductId: providerProductId,\n default_price: defaultPrice,\n metadata: metadata,\n visibleProperties: visibleProperties,\n mainImage: mainImage,\n imageUrl: mainImage,\n image_url: mainImage,\n galleryImages: galleryImages,\n images: images,\n modelUrl: modelUrl,\n modelPoster: modelPoster,\n hasModel: hasModel,\n showModel: showModel,\n galleryMedia: galleryMedia,\n galleryThumbnails: galleryThumbnails,\n createdAt: createdAt,\n updatedAt: updatedAt,\n created: created,\n outOfStock: outOfStock,\n variantOptions: variantOptions,\n requiresVariantSelection: requiresVariantSelection,\n variants: variants,\n variantOptionsJson: variantOptionsJson,\n variantsJson: variantsJson,\n variantsDisplayJson: variantsDisplayJson,\n defaultVariantId: defaultVariantId,\n defaultVariantPrice: defaultVariantPrice,\n displayPrice: displayPrice,\n defaultVariantDisplayPrice: defaultVariantDisplayPrice,\n hasPurchasableVariant: hasPurchasableVariant,\n }\n}\n\n// --- Variant availability helpers (mirror packages/renderer ecommerce-products) ---\n// A variant is in stock when its quantity is null (unlimited) or > 0. With\n// ALLOW_BACKORDERS every EXISTING combination is purchasable regardless of its\n// quantity \u2014 but a missing combination (null) is still not in stock: there is\n// no variant row to backorder.\nfunction isVariantInStock(v) {\n if (!v) return false\n if (ALLOW_BACKORDERS) return true\n return v.quantity == null || v.quantity > 0\n}\nfunction variantCoversAllAxes(v, axisKeys) {\n if (!v || !v.options) return false\n for (var i = 0; i < axisKeys.length; i++) {\n if (v.options[axisKeys[i]] == null) return false\n }\n return true\n}\n// First in-stock combination covering every axis; falls back to the first\n// covering combination (even if OOS) so a fully-OOS product still has a\n// visual default; null when no combination covers the axes.\nfunction pickFirstAvailableVariant(variants, axisKeys) {\n if (!Array.isArray(variants) || !axisKeys.length) return null\n for (var i = 0; i < variants.length; i++) {\n if (variantCoversAllAxes(variants[i], axisKeys) && isVariantInStock(variants[i])) return variants[i]\n }\n for (var j = 0; j < variants.length; j++) {\n if (variantCoversAllAxes(variants[j], axisKeys)) return variants[j]\n }\n return null\n}\n// Map of composite \"axisKey|valueKey\" -> true for every value that appears in\n// NO in-stock combination (rendered as the Unavailable state).\n//\n// variantsResolved is the whole subtlety: dead-marking is only meaningful\n// against combinations we actually LOOKED UP. When the lookup could not run,\n// nothing is dead \u2014 a missing table or a failed query must not grey out every\n// picker in the store. When it DID run, an empty list is a fact, not a gap:\n// every value is unbuyable and renders as Unavailable.\nfunction computeDeadVariantKeys(variants, axes, variantsResolved) {\n if (!variantsResolved || !Array.isArray(variants)) return {}\n var alive = {}\n for (var i = 0; i < variants.length; i++) {\n var v = variants[i]\n if (!isVariantInStock(v)) continue\n for (var k in v.options) {\n if (Object.prototype.hasOwnProperty.call(v.options, k)) alive[k + '|' + v.options[k]] = true\n }\n }\n var dead = {}\n for (var a = 0; a < axes.length; a++) {\n var ax = axes[a]\n for (var b = 0; b < ax.values.length; b++) {\n var key = ax.key + '|' + ax.values[b].value\n if (!alive[key]) dead[key] = true\n }\n }\n return dead\n}\n// Variant price with base-price inheritance (null variant price -> product price).\nfunction formatVariantPrice(vprice, basePrice) {\n var p = vprice == null || isNaN(vprice) ? basePrice : vprice\n return String(Number(p).toFixed(2))\n}\nfunction safeStringifyJson(obj) {\n try {\n return JSON.stringify(obj)\n } catch (e) {\n return '[]'\n }\n}\n\n// Parse + normalize the variant_options JSON into render-ready axes. Tolerant of\n// null / malformed / partial data (returns []). Keeps ONLY the fields the pill\n// widget needs; the labels are already language-resolved by the caller.\nfunction normalizeVariantOptions(raw) {\n if (!raw) return []\n var parsed = raw\n if (typeof raw === 'string') {\n try { parsed = JSON.parse(raw) } catch (e) { return [] }\n }\n if (!Array.isArray(parsed)) return []\n var out = []\n for (var i = 0; i < parsed.length; i++) {\n var axis = parsed[i]\n if (!axis || typeof axis !== 'object' || !Array.isArray(axis.values)) continue\n var name = typeof axis.name === 'string' ? axis.name : ''\n var key = typeof axis.key === 'string' && axis.key ? axis.key : name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!key) continue\n var type = axis.type === 'color' ? 'color' : 'text'\n var values = []\n for (var j = 0; j < axis.values.length; j++) {\n var v = axis.values[j]\n if (!v || typeof v !== 'object') continue\n var label = typeof v.label === 'string' ? v.label : ''\n var value = typeof v.value === 'string' && v.value ? v.value : label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')\n if (!value) continue\n var entry = { value: value, label: label }\n if (type === 'color' && typeof v.color === 'string' && v.color) entry.color = v.color\n values.push(entry)\n }\n if (!values.length) continue\n out.push({ key: key, name: name, type: type, values: values })\n }\n return out\n}\n\n// --- Custom-property classification (MUST mirror product-property-display.ts) ---\n\n// Product-attribute keys that can leak into the free-form `metadata` map (e.g.\n// from a payment-provider sync or legacy data) but are NOT user custom\n// properties. Kept in sync with the GUI's RESERVED_PRODUCT_METADATA_KEYS.\nvar RESERVED_PRODUCT_METADATA_KEYS = {\n paymentType: true, recurringInterval: true, recurringIntervalCount: true,\n price: true, currency: true, status: true, sku: true, weightUnit: true,\n dimensions: true, category: true, brand: true, gtin: true, mpn: true,\n condition: true, tags: true,\n}\nfunction isReservedProductMetadataKey(key) {\n return !!RESERVED_PRODUCT_METADATA_KEYS[key] ||\n key.indexOf('mainImage') === 0 ||\n key.indexOf('secondaryImage') === 0 ||\n key.indexOf('_tq') === 0\n}\n\nvar CSS_NAMED_COLORS = {\n aliceblue: 1, antiquewhite: 1, aqua: 1, aquamarine: 1, azure: 1, beige: 1, bisque: 1,\n black: 1, blanchedalmond: 1, blue: 1, blueviolet: 1, brown: 1, burlywood: 1,\n cadetblue: 1, chartreuse: 1, chocolate: 1, coral: 1, cornflowerblue: 1, cornsilk: 1,\n crimson: 1, cyan: 1, darkblue: 1, darkcyan: 1, darkgoldenrod: 1, darkgray: 1,\n darkgrey: 1, darkgreen: 1, darkkhaki: 1, darkmagenta: 1, darkolivegreen: 1,\n darkorange: 1, darkorchid: 1, darkred: 1, darksalmon: 1, darkseagreen: 1,\n darkslateblue: 1, darkslategray: 1, darkslategrey: 1, darkturquoise: 1,\n darkviolet: 1, deeppink: 1, deepskyblue: 1, dimgray: 1, dimgrey: 1, dodgerblue: 1,\n firebrick: 1, floralwhite: 1, forestgreen: 1, fuchsia: 1, gainsboro: 1,\n ghostwhite: 1, gold: 1, goldenrod: 1, gray: 1, grey: 1, green: 1, greenyellow: 1,\n honeydew: 1, hotpink: 1, indianred: 1, indigo: 1, ivory: 1, khaki: 1, lavender: 1,\n lavenderblush: 1, lawngreen: 1, lemonchiffon: 1, lightblue: 1, lightcoral: 1,\n lightcyan: 1, lightgoldenrodyellow: 1, lightgray: 1, lightgrey: 1, lightgreen: 1,\n lightpink: 1, lightsalmon: 1, lightseagreen: 1, lightskyblue: 1, lightslategray: 1,\n lightslategrey: 1, lightsteelblue: 1, lightyellow: 1, lime: 1, limegreen: 1,\n linen: 1, magenta: 1, maroon: 1, mediumaquamarine: 1, mediumblue: 1,\n mediumorchid: 1, mediumpurple: 1, mediumseagreen: 1, mediumslateblue: 1,\n mediumspringgreen: 1, mediumturquoise: 1, mediumvioletred: 1, midnightblue: 1,\n mintcream: 1, mistyrose: 1, moccasin: 1, navajowhite: 1, navy: 1, oldlace: 1,\n olive: 1, olivedrab: 1, orange: 1, orangered: 1, orchid: 1, palegoldenrod: 1,\n palegreen: 1, paleturquoise: 1, palevioletred: 1, papayawhip: 1, peachpuff: 1,\n peru: 1, pink: 1, plum: 1, powderblue: 1, purple: 1, rebeccapurple: 1, red: 1,\n rosybrown: 1, royalblue: 1, saddlebrown: 1, salmon: 1, sandybrown: 1, seagreen: 1,\n seashell: 1, sienna: 1, silver: 1, skyblue: 1, slateblue: 1, slategray: 1,\n slategrey: 1, snow: 1, springgreen: 1, steelblue: 1, tan: 1, teal: 1, thistle: 1,\n tomato: 1, turquoise: 1, violet: 1, wheat: 1, white: 1, whitesmoke: 1, yellow: 1,\n yellowgreen: 1, transparent: 1,\n}\nvar HEX_COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nvar FUNCTIONAL_COLOR_RE = /^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\((?:[0-9a-z%.,\\s/+-]+)\\)$/i\nvar COLOR_KEY_WORDS = {\n color: 1, colors: 1, colour: 1, colours: 1, shade: 1, shades: 1, hue: 1, hues: 1,\n tint: 1, tints: 1, tone: 1, tones: 1, swatch: 1, swatches: 1,\n}\nfunction splitKeyWords(key) {\n return key.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)\n}\nfunction keyIndicatesColor(key) {\n var normalized = key.toLowerCase()\n if (/colou?r/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!COLOR_KEY_WORDS[word] })\n}\nfunction resolvePropertyColor(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (HEX_COLOR_RE.test(v) || FUNCTIONAL_COLOR_RE.test(v)) return v\n if (CSS_NAMED_COLORS[v.toLowerCase()] && keyIndicatesColor(key)) return v\n return ''\n}\n\nvar DATA_IMAGE_URI_RE = /^data:image\\//i\nvar ABSOLUTE_URL_RE = /^(?:https?:)?\\/\\//i\nvar IMAGE_EXTENSION_RE = /\\.(?:png|jpe?g|gif|webp|svg|avif|bmp|ico|tiff?|heic|heif)$/i\nvar IMAGE_KEY_WORDS = {\n image: 1, images: 1, img: 1, imgs: 1, photo: 1, photos: 1, picture: 1, pictures: 1,\n pic: 1, pics: 1, thumbnail: 1, thumbnails: 1, thumb: 1, thumbs: 1, icon: 1, icons: 1,\n logo: 1, logos: 1, avatar: 1, avatars: 1, banner: 1, banners: 1, cover: 1, covers: 1,\n gallery: 1, screenshot: 1, screenshots: 1, poster: 1, posters: 1, artwork: 1,\n graphic: 1, graphics: 1, illustration: 1, wallpaper: 1, preview: 1, snapshot: 1,\n media: 1, visual: 1, visuals: 1,\n}\nfunction keyIndicatesImage(key) {\n var normalized = key.toLowerCase()\n if (/(?:image|img|photo|picture|thumb|icon|logo|avatar|banner|gallery|screenshot|poster|artwork|graphic|wallpaper)/.test(normalized)) return true\n return splitKeyWords(key).some(function(word) { return !!IMAGE_KEY_WORDS[word] })\n}\nfunction stripUrlQueryAndHash(url) {\n return url.split(/[?#]/)[0]\n}\nfunction resolvePropertyImage(key, value) {\n var v = value.trim()\n if (!v) return ''\n if (DATA_IMAGE_URI_RE.test(v)) return v\n var isAbsoluteUrl = ABSOLUTE_URL_RE.test(v)\n var isRootRelative = v.charAt(0) === '/' && !isAbsoluteUrl\n if (!isAbsoluteUrl && !isRootRelative) return ''\n if (IMAGE_EXTENSION_RE.test(stripUrlQueryAndHash(v))) return v\n if (isAbsoluteUrl && keyIndicatesImage(key)) return v\n return ''\n}\n\n// Image wins over colour (a URL can never be a CSS colour, but checking image\n// first keeps the precedence explicit), text is the fallback.\nfunction classifyProductProperty(key, value) {\n var imageUrl = resolvePropertyImage(key, value)\n if (imageUrl) return { key: key, value: value, kind: 'image', color: '', imageUrl: imageUrl }\n var color = resolvePropertyColor(key, value)\n if (color) return { key: key, value: value, kind: 'color', color: color, imageUrl: '' }\n return { key: key, value: value, kind: 'text', color: '', imageUrl: '' }\n}\n\nfunction transformEcommerceProducts(records, options) {\n if (!Array.isArray(records)) return []\n return records.map(function(record) { return buildEcommerceProduct(record, options) })\n}\n\n// Batched fetch of the purchasable variant rows for a set of product ids, keyed\n// by product_id, so buildEcommerceProduct can attach product.variants without a\n// per-product query. Best-effort: a store with no variants (or before the table\n// exists) yields an empty map and flat products keep variants: [].\n// Batched fetch of the product rows a set of products reference as \"related\",\n// keyed by id, so buildEcommerceProduct can attach product.relatedProducts\n// without a query per product.\n//\n// Best-effort by design: a store whose products table predates the column\n// yields no ids at all (the read below is of an absent property, not of a\n// column \u2014 the SQL never names it), the map stays empty, and the details page's\n// rail simply stays hidden behind its is_not_empty gate. Same for a failed\n// query.\nasync function getRelatedProductsMap(getClientFn, records) {\n var map = {}\n if (!Array.isArray(records) || records.length === 0) return map\n\n var wantedIds = []\n for (var i = 0; i < records.length; i++) {\n var ids = parseRelatedIds(records[i] && records[i].related_product_ids)\n for (var j = 0; j < ids.length; j++) {\n if (wantedIds.indexOf(ids[j]) === -1) wantedIds.push(ids[j])\n }\n }\n if (wantedIds.length === 0) return map\n\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query('SELECT * FROM teleport_products WHERE id = ANY($1)', [\n wantedIds,\n ])\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n if (row && row.id != null) map[String(row.id)] = row\n }\n }\n } catch (e) {\n // Leaves relatedProducts empty rather than failing the page.\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n\n// Combinations for every product on the page, keyed by product id. Returns NULL\n// when the lookup could not run, which the transform reads as \"unknown\" and\n// stays permissive with; an empty map means the query ran and this catalogue\n// simply has no combinations.\nasync function getVariantsMap(getClientFn, productIds) {\n var map = {}\n if (!Array.isArray(productIds) || productIds.length === 0) return map\n var uniqueIds = []\n var seenIds = {}\n for (var u = 0; u < productIds.length; u++) {\n var pid0 = productIds[u]\n if (pid0 != null && !seenIds[pid0]) { seenIds[pid0] = true; uniqueIds.push(pid0) }\n }\n if (uniqueIds.length === 0) return map\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query(\n 'SELECT id, product_id, options, price, quantity, image_url FROM teleport_product_variants WHERE product_id = ANY($1) ORDER BY position ASC, id ASC',\n [uniqueIds]\n )\n if (result && result.rows) {\n for (var r = 0; r < result.rows.length; r++) {\n var row = result.rows[r]\n var pid = row.product_id\n if (!map[pid]) map[pid] = []\n map[pid].push(row)\n }\n }\n } catch (e) {\n // teleport_product_variants may not exist for a non-variant store, or the\n // query may have failed. Either way the combinations are UNKNOWN \u2014 null\n // keeps every picker selectable instead of declaring the catalogue unbuyable.\n map = null\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n");
|
|
42
47
|
};
|
|
43
48
|
//# sourceMappingURL=ecommerce-product.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ecommerce-product.js","sourceRoot":"","sources":["../../../src/transformations/ecommerce-product.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ecommerce-product.js","sourceRoot":"","sources":["../../../src/transformations/ecommerce-product.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AA6B3D;;;;;;;;;;;GAWG;AACH,IAAM,qBAAqB,GAAG,UAC5B,UAA+C;IAK/C,IAAM,IAAI,GAGN,EAAE,CAAA;IACN,IAAM,KAAK,GAAG,UAAC,KAA0C;QACvD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;YACzB,OAAM;SACP;QACD,KAAmB,UAAK,EAAL,eAAK,EAAL,mBAAK,EAAL,IAAK,EAAE;YAArB,IAAM,IAAI,cAAA;YACb,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,QAAQ,EAAE;gBACvC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG;oBACd,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE;oBACrB,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE;oBACrB,YAAY,EAAE,IAAI,CAAC,YAAY;iBAChC,CAAA;gBACD,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;aACrB;SACF;IACH,CAAC,CAAA;IACD,KAAK,CAAC,UAAU,CAAC,CAAA;IACjB,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,IAAM,0CAA0C,GAAG,UACxD,OAA8C;;IAA9C,wBAAA,EAAA,YAA8C;IAE9C,IAAM,kBAAkB,GAAG,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;IACpF,IAAM,aAAa,GAAG,aAAa,CAAC,+BAA+B,CACjE,MAAA,OAAO,CAAC,iBAAiB,mCAAI,CAAC,CAC/B,CAAA;IACD,IAAM,sBAAsB,GAAG,OAAO,CAAC,eAAe,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAA;IAElF,OAAO,YACP,aAAa,yRAKU,sBAAsB,4SAMd,kBAAkB,8jpCAwxBlD,CAAA;AACD,CAAC,CAAA"}
|
|
@@ -1,4 +1,16 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { GeneratorOptions } from '@teleporthq/teleport-types';
|
|
2
|
+
import { type EcommerceProductTransformOptions } from './ecommerce-product';
|
|
3
|
+
export type { EcommerceProductTransformOptions };
|
|
4
|
+
/**
|
|
5
|
+
* Collects everything the product transform bakes in from the generator
|
|
6
|
+
* options, in ONE place so every fetcher-emitting call site stays in step.
|
|
7
|
+
*
|
|
8
|
+
* `storefrontTaxRate` is what turns a NET catalogue price into the price the
|
|
9
|
+
* shopper is quoted; `resolveStorefrontTaxRate` returns 0 (a no-op) for
|
|
10
|
+
* tax-inclusive or untaxed stores. `allowBackorders` is the effective
|
|
11
|
+
* "stock never blocks a purchase" flag — see `resolveAllowBackorders`.
|
|
12
|
+
*/
|
|
13
|
+
export declare const buildProductTransformOptions: (options: Pick<GeneratorOptions, 'ecommerceSettings' | 'invoiceSettings'>) => EcommerceProductTransformOptions;
|
|
2
14
|
export type TransformationType = 'blog-post' | 'ecommerce-product' | null;
|
|
3
15
|
/**
|
|
4
16
|
* Detects which transformation type to apply based on the table name.
|
|
@@ -18,7 +30,7 @@ export declare const detectTransformationType: (tableName: string) => Transforma
|
|
|
18
30
|
* to be included in the generated data source fetcher file.
|
|
19
31
|
* Returns empty string if no transformation is needed for this table.
|
|
20
32
|
*/
|
|
21
|
-
export declare const getTransformationCode: (tableName: string,
|
|
33
|
+
export declare const getTransformationCode: (tableName: string, options?: EcommerceProductTransformOptions) => string;
|
|
22
34
|
/**
|
|
23
35
|
* Returns the JavaScript expression that transforms the data array.
|
|
24
36
|
* This expression assumes the data array variable is called `safeData`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAIlE,OAAO,EAEL,KAAK,gCAAgC,EACtC,MAAM,qBAAqB,CAAA;AAE5B,YAAY,EAAE,gCAAgC,EAAE,CAAA;AAkBhD;;;;;;;;GAQG;AACH,eAAO,MAAM,4BAA4B,YAC9B,KAAK,gBAAgB,EAAE,mBAAmB,GAAG,iBAAiB,CAAC,KACvE,gCAID,CAAA;AAEF,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,mBAAmB,GAAG,IAAI,CAAA;AAezE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,wBAAwB,cAAe,MAAM,KAAG,kBAY5D,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,cACrB,MAAM,YACR,gCAAgC,KACxC,MAgBF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,cAAe,MAAM,KAAG,MAAM,GAAG,IAcnE,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,cAAe,MAAM,KAAG,MAqF3D,CAAA"}
|
|
@@ -1,6 +1,38 @@
|
|
|
1
|
+
import { StorefrontTax } from '@teleporthq/teleport-shared';
|
|
1
2
|
import { generateSharedTransformationCode } from './shared-utils';
|
|
2
3
|
import { generateBlogPostTransformationCode } from './blog-post';
|
|
3
|
-
import { generateEcommerceProductTransformationCode } from './ecommerce-product';
|
|
4
|
+
import { generateEcommerceProductTransformationCode, } from './ecommerce-product';
|
|
5
|
+
/**
|
|
6
|
+
* Stock never gates purchasability when the merchant disabled stock management
|
|
7
|
+
* entirely or opted into backorders. Mirrors the GUI rule in
|
|
8
|
+
* `apps/gui/app/project-page/features/e-commerce/utils/product-variants.ts`
|
|
9
|
+
* (`isVariantInStock`). A project without e-commerce settings keeps the
|
|
10
|
+
* strict default (stock gates apply) — same behaviour as before the flag.
|
|
11
|
+
*/
|
|
12
|
+
var resolveAllowBackorders = function (settings) {
|
|
13
|
+
var _a;
|
|
14
|
+
if (!settings) {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
return !settings.stockManagement || ((_a = settings.stockManagementConfig) === null || _a === void 0 ? void 0 : _a.allowBackorders) === true;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Collects everything the product transform bakes in from the generator
|
|
21
|
+
* options, in ONE place so every fetcher-emitting call site stays in step.
|
|
22
|
+
*
|
|
23
|
+
* `storefrontTaxRate` is what turns a NET catalogue price into the price the
|
|
24
|
+
* shopper is quoted; `resolveStorefrontTaxRate` returns 0 (a no-op) for
|
|
25
|
+
* tax-inclusive or untaxed stores. `allowBackorders` is the effective
|
|
26
|
+
* "stock never blocks a purchase" flag — see `resolveAllowBackorders`.
|
|
27
|
+
*/
|
|
28
|
+
export var buildProductTransformOptions = function (options) {
|
|
29
|
+
var _a;
|
|
30
|
+
return ({
|
|
31
|
+
categories: (_a = options.ecommerceSettings) === null || _a === void 0 ? void 0 : _a.categories,
|
|
32
|
+
storefrontTaxRate: StorefrontTax.resolveStorefrontTaxRate(options.invoiceSettings),
|
|
33
|
+
allowBackorders: resolveAllowBackorders(options.ecommerceSettings),
|
|
34
|
+
});
|
|
35
|
+
};
|
|
4
36
|
/**
|
|
5
37
|
* Strips a leading `schema.` qualifier from a table name so that only the
|
|
6
38
|
* bare table identifier remains (e.g. `public.teleport_products` ->
|
|
@@ -43,7 +75,8 @@ export var detectTransformationType = function (tableName) {
|
|
|
43
75
|
* to be included in the generated data source fetcher file.
|
|
44
76
|
* Returns empty string if no transformation is needed for this table.
|
|
45
77
|
*/
|
|
46
|
-
export var getTransformationCode = function (tableName,
|
|
78
|
+
export var getTransformationCode = function (tableName, options) {
|
|
79
|
+
if (options === void 0) { options = {}; }
|
|
47
80
|
var type = detectTransformationType(tableName);
|
|
48
81
|
if (!type) {
|
|
49
82
|
return '';
|
|
@@ -53,7 +86,7 @@ export var getTransformationCode = function (tableName, categories) {
|
|
|
53
86
|
case 'blog-post':
|
|
54
87
|
return shared + generateBlogPostTransformationCode();
|
|
55
88
|
case 'ecommerce-product':
|
|
56
|
-
return shared + generateEcommerceProductTransformationCode(
|
|
89
|
+
return shared + generateEcommerceProductTransformationCode(options);
|
|
57
90
|
default:
|
|
58
91
|
return '';
|
|
59
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAA;AACjE,OAAO,EAAE,kCAAkC,EAAE,MAAM,aAAa,CAAA;AAChE,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/transformations/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAA;AACjE,OAAO,EAAE,kCAAkC,EAAE,MAAM,aAAa,CAAA;AAChE,OAAO,EACL,0CAA0C,GAE3C,MAAM,qBAAqB,CAAA;AAI5B;;;;;;GAMG;AACH,IAAM,sBAAsB,GAAG,UAC7B,QAA2D;;IAE3D,IAAI,CAAC,QAAQ,EAAE;QACb,OAAO,KAAK,CAAA;KACb;IACD,OAAO,CAAC,QAAQ,CAAC,eAAe,IAAI,CAAA,MAAA,QAAQ,CAAC,qBAAqB,0CAAE,eAAe,MAAK,IAAI,CAAA;AAC9F,CAAC,CAAA;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,IAAM,4BAA4B,GAAG,UAC1C,OAAwE;;IACnC,OAAA,CAAC;QACtC,UAAU,EAAE,MAAA,OAAO,CAAC,iBAAiB,0CAAE,UAAU;QACjD,iBAAiB,EAAE,aAAa,CAAC,wBAAwB,CAAC,OAAO,CAAC,eAAe,CAAC;QAClF,eAAe,EAAE,sBAAsB,CAAC,OAAO,CAAC,iBAAiB,CAAC;KACnE,CAAC,CAAA;CAAA,CAAA;AAIF;;;;GAIG;AACH,IAAM,oBAAoB,GAAG,UAAC,SAAiB;IAC7C,IAAM,KAAK,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAA;IAC5C,IAAM,OAAO,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IACtC,IAAM,IAAI,GAAG,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;IAC5D,kEAAkE;IAClE,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;AACnC,CAAC,CAAA;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,IAAM,wBAAwB,GAAG,UAAC,SAAiB;IACxD,IAAI,CAAC,SAAS,EAAE;QACd,OAAO,IAAI,CAAA;KACZ;IACD,IAAM,IAAI,GAAG,oBAAoB,CAAC,SAAS,CAAC,CAAA;IAC5C,IAAI,IAAI,KAAK,qBAAqB,EAAE;QAClC,OAAO,WAAW,CAAA;KACnB;IACD,IAAI,IAAI,KAAK,mBAAmB,EAAE;QAChC,OAAO,mBAAmB,CAAA;KAC3B;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,IAAM,qBAAqB,GAAG,UACnC,SAAiB,EACjB,OAA8C;IAA9C,wBAAA,EAAA,YAA8C;IAE9C,IAAM,IAAI,GAAG,wBAAwB,CAAC,SAAS,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI,EAAE;QACT,OAAO,EAAE,CAAA;KACV;IAED,IAAM,MAAM,GAAG,gCAAgC,EAAE,CAAA;IAEjD,QAAQ,IAAI,EAAE;QACZ,KAAK,WAAW;YACd,OAAO,MAAM,GAAG,kCAAkC,EAAE,CAAA;QACtD,KAAK,mBAAmB;YACtB,OAAO,MAAM,GAAG,0CAA0C,CAAC,OAAO,CAAC,CAAA;QACrE;YACE,OAAO,EAAE,CAAA;KACZ;AACH,CAAC,CAAA;AAED;;;;;GAKG;AACH,MAAM,CAAC,IAAM,sBAAsB,GAAG,UAAC,SAAiB;IACtD,IAAM,IAAI,GAAG,wBAAwB,CAAC,SAAS,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI,EAAE;QACT,OAAO,IAAI,CAAA;KACZ;IAED,QAAQ,IAAI,EAAE;QACZ,KAAK,WAAW;YACd,OAAO,wDAAwD,CAAA;QACjE,KAAK,mBAAmB;YACtB,OAAO,wDAAwD,CAAA;QACjE;YACE,OAAO,IAAI,CAAA;KACd;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,IAAM,uBAAuB,GAAG,UAAC,SAAiB;IACvD,IAAM,IAAI,GAAG,wBAAwB,CAAC,SAAS,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI,EAAE;QACT,OAAO,EAAE,CAAA;KACV;IAED,IAAM,WAAW,GAAG,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,4BAA4B,CAAA;IAE9F,+EAA+E;IAC/E,+EAA+E;IAC/E,EAAE;IACF,yEAAyE;IACzE,wEAAwE;IACxE,8EAA8E;IAC9E,2EAA2E;IAC3E,wCAAwC;IACxC,EAAE;IACF,8EAA8E;IAC9E,yEAAyE;IACzE,4EAA4E;IAC5E,IAAM,iBAAiB,GACrB,IAAI,KAAK,mBAAmB;QAC1B,CAAC,CAAC,84BAoBJ;QACE,CAAC,CAAC,EAAE,CAAA;IAER,IAAM,aAAa,GACjB,IAAI,KAAK,mBAAmB,CAAC,CAAC,CAAC,4CAA4C,CAAC,CAAC,CAAC,EAAE,CAAA;IAElF,2EAA2E;IAC3E,0EAA0E;IAC1E,6EAA6E;IAC7E,6EAA6E;IAC7E,0EAA0E;IAC1E,2EAA2E;IAC3E,qBAAqB;IACrB,EAAE;IACF,0EAA0E;IAC1E,8EAA8E;IAC9E,iBAAiB;IACjB,IAAM,aAAa,GAAG,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,qBAAqB,CAAA;IACvF,IAAM,YAAY,GAAG,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,uBAAuB,CAAA;IAC1F,IAAM,iBAAiB,GAAG,kBACpB,aAAa,gGAGb,aAAa,sBAAY,YAAY,sIAIzC,CAAA;IAEF,OAAO,6OAOJ,iBAAiB,SAAG,iBAAiB,4OAG0D,aAAa,eAAK,aAAa,eAAK,aAAa,0BAC1I,WAAW,4BAErB,CAAA;AACD,CAAC,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-utils.d.ts","sourceRoot":"","sources":["../../../src/transformations/shared-utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,QAAO,
|
|
1
|
+
{"version":3,"file":"shared-utils.d.ts","sourceRoot":"","sources":["../../../src/transformations/shared-utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,QAAO,MA2SnD,CAAA"}
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
* when the table requires blog post or e-commerce product transformations.
|
|
5
5
|
*/
|
|
6
6
|
export var generateSharedTransformationCode = function () {
|
|
7
|
-
return "\n// ============================================================\n// Shared Data Transformation Utilities\n// ============================================================\n\nvar CURRENCY_SYMBOLS = {\n USD: { symbol: '$', position: 'before' },\n EUR: { symbol: '\u20AC', position: 'before' },\n GBP: { symbol: '\u00A3', position: 'before' },\n JPY: { symbol: '\u00A5', position: 'before' },\n CAD: { symbol: 'C$', position: 'before' },\n AUD: { symbol: 'A$', position: 'before' },\n CHF: { symbol: 'CHF', position: 'before' },\n CNY: { symbol: '\u00A5', position: 'before' },\n INR: { symbol: '\u20B9', position: 'before' },\n BRL: { symbol: 'R$', position: 'before' },\n MXN: { symbol: 'MX$', position: 'before' },\n KRW: { symbol: '\u20A9', position: 'before' },\n SGD: { symbol: 'S$', position: 'before' },\n HKD: { symbol: 'HK$', position: 'before' },\n NOK: { symbol: 'kr', position: 'after' },\n SEK: { symbol: 'kr', position: 'after' },\n DKK: { symbol: 'kr', position: 'after' },\n PLN: { symbol: 'z\u0142', position: 'after' },\n CZK: { symbol: 'K\u010D', position: 'after' },\n HUF: { symbol: 'Ft', position: 'after' },\n RON: { symbol: 'lei', position: 'after' },\n TRY: { symbol: '\u20BA', position: 'before' },\n THB: { symbol: '\u0E3F', position: 'before' },\n IDR: { symbol: 'Rp', position: 'before' },\n PHP: { symbol: '\u20B1', position: 'before' },\n ZAR: { symbol: 'R', position: 'before' },\n RUB: { symbol: '\u20BD', position: 'after' },\n NZD: { symbol: 'NZ$', position: 'before' },\n TWD: { symbol: 'NT$', position: 'before' },\n ILS: { symbol: '\u20AA', position: 'before' },\n AED: { symbol: '\u062F.\u0625', position: 'before' },\n SAR: { symbol: '\uFDFC', position: 'before' },\n MYR: { symbol: 'RM', position: 'before' },\n VND: { symbol: '\u20AB', position: 'after' },\n CLP: { symbol: '$', position: 'before' },\n COP: { symbol: '$', position: 'before' },\n ARS: { symbol: '$', position: 'before' },\n PEN: { symbol: 'S/', position: 'before' },\n UAH: { symbol: '\u20B4', position: 'after' },\n BGN: { symbol: '\u043B\u0432', position: 'after' },\n HRK: { symbol: 'kn', position: 'after' },\n ISK: { symbol: 'kr', position: 'after' },\n NGN: { symbol: '\u20A6', position: 'before' },\n KES: { symbol: 'KSh', position: 'before' },\n EGP: { symbol: 'E\u00A3', position: 'before' },\n PKR: { symbol: '\u20A8', position: 'before' },\n BDT: { symbol: '\u09F3', position: 'before' },\n LKR: { symbol: '\u20A8', position: 'before' },\n GHS: { symbol: 'GH\u20B5', position: 'before' },\n}\n\nfunction getCurrencyInfo(currencyCode) {\n if (!currencyCode) return { symbol: '$', position: 'before' }\n var upper = currencyCode.toUpperCase()\n var entry = CURRENCY_SYMBOLS[upper]\n return entry || { symbol: upper, position: 'before' }\n}\n\nfunction getCurrencySymbol(currencyCode) {\n return getCurrencyInfo(currencyCode).symbol\n}\n\nfunction normalizeTimestamp(value) {\n if (value == null) return Date.now()\n if (typeof value === 'number') {\n if (isNaN(value)) return Date.now()\n return value < 100000000000 ? value * 1000 : value\n }\n if (typeof value === 'string') {\n var parsed = Date.parse(value)\n return isNaN(parsed) ? Date.now() : parsed\n }\n return Date.now()\n}\n\nfunction safeNumber(value, defaultValue) {\n if (value == null) return defaultValue\n var n = Number(value)\n return isNaN(n) ? defaultValue : n\n}\n\nfunction parseJsonArray(value) {\n if (!value) return []\n if (Array.isArray(value)) return value.filter(function(item) { return typeof item === 'string' })\n if (typeof value === 'string') {\n try {\n var parsed = JSON.parse(value)\n if (Array.isArray(parsed)) return parsed.filter(function(item) { return typeof item === 'string' })\n return []\n } catch (e) {\n return value.split(',').map(function(s) { return s.trim() }).filter(Boolean)\n }\n }\n return []\n}\n\n// The related-item picks a merchant/author made: a JSON array of row ids stored\n// in a TEXT column (`related_product_ids` / `related_post_ids`). Mirrors\n// parseRelatedEntityIds in the GUI (apps/gui/app/project-page/features/shared/\n// related-entities/related-entity-ids.ts) \u2014 order-preserving, deduplicated,\n// blanks dropped, tolerant of a comma-separated cell edited by hand.\n//\n// `indexOf` rather than a seen-map on purpose: these lists hold a handful of\n// entries, and an object keyed by arbitrary strings answers truthy for\n// 'constructor'/'toString'.\nfunction parseRelatedIds(value) {\n var raw = parseJsonArray(value)\n var ids = []\n for (var i = 0; i < raw.length; i++) {\n var id = String(raw[i] == null ? '' : raw[i]).trim()\n if (!id || ids.indexOf(id) !== -1) continue\n ids.push(id)\n }\n return ids\n}\n\nfunction parseJsonObject(value) {\n if (value == null) return {}\n if (typeof value === 'object' && !Array.isArray(value)) return value\n if (typeof value === 'string') {\n try {\n var parsed = JSON.parse(value)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed\n return {}\n } catch (e) {\n return {}\n }\n }\n return {}\n}\n\nvar HTML_ENTITY_MAP = {\n '&': '&', '<': '<', '>': '>', '"': '\"',\n ''': \"'\", ''': \"'\", ''': \"'\", ' ': ' ',\n ' ': ' ', '©': '\u00A9', '®': '\u00AE', '™': '\u2122',\n '…': '\u2026', '—': '\u2014', '–': '\u2013',\n}\n\nfunction decodeHtmlEntities(str) {\n if (!str) return str\n // Decode named and numeric entities\n return str\n .replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([a-zA-Z]+));/g, function(match, hex, dec, named) {\n if (hex) return String.fromCharCode(parseInt(hex, 16))\n if (dec) return String.fromCharCode(parseInt(dec, 10))\n var namedRef = '&' + named + ';'\n return HTML_ENTITY_MAP[namedRef] || match\n })\n}\n\nfunction stripHtmlTags(html) {\n if (!html || typeof html !== 'string') return ''\n // Remove script and style blocks entirely (including content)\n var cleaned = html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, ' ')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, ' ')\n // Strip remaining tags\n cleaned = cleaned.replace(/<[^>]*>/g, ' ')\n // Decode HTML entities\n cleaned = decodeHtmlEntities(cleaned)\n // Collapse whitespace\n return cleaned.replace(/\\s+/g, ' ').trim()\n}\n\nfunction coerceBoolean(value, defaultValue) {\n if (value === true || value === 'true' || value === 1 || value === '1') return true\n if (value === false || value === 'false' || value === 0 || value === '0') return false\n return defaultValue\n}\n\nfunction pickFirst() {\n for (var i = 0; i < arguments.length; i++) {\n var val = arguments[i]\n if (val !== undefined && val !== null) return val\n }\n return null\n}\n\nfunction resolveI18nField(record, snakeCol, camelCol, currentLang, mainLang) {\n if (currentLang && mainLang && currentLang !== mainLang) {\n // Try language-prefixed snake_case column first, then camelCase\n var langSnakeKey = currentLang + '_' + snakeCol\n if (record[langSnakeKey] !== undefined && record[langSnakeKey] !== null && record[langSnakeKey] !== '') {\n return record[langSnakeKey]\n }\n if (snakeCol !== camelCol) {\n var langCamelKey = currentLang + '_' + camelCol\n if (record[langCamelKey] !== undefined && record[langCamelKey] !== null && record[langCamelKey] !== '') {\n return record[langCamelKey]\n }\n }\n }\n if (record[snakeCol] !== undefined && record[snakeCol] !== null) return record[snakeCol]\n if (snakeCol !== camelCol && record[camelCol] !== undefined && record[camelCol] !== null) return record[camelCol]\n return null\n}\n\n// Asset URL Resolution with TTL-based caching\nvar __assetUrlCache = {}\nvar __assetMapCache = null\nvar __assetMapTimestamp = 0\nvar ASSET_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n\nfunction isUrl(value) {\n if (!value || typeof value !== 'string') return false\n return value.startsWith('http://') || value.startsWith('https://') || value.startsWith('data:')\n}\n\nfunction resolveAssetUrl(value, assetMap) {\n if (!value || typeof value !== 'string') return null\n if (isUrl(value)) return value\n // Also treat absolute paths (starting with /) as URLs\n if (value.charAt(0) === '/') return value\n if (__assetUrlCache[value]) return __assetUrlCache[value]\n if (assetMap && assetMap[value]) {\n var asset = assetMap[value]\n var resolved = asset.remoteSrc || asset.imageSrc || asset.src || asset.url || value\n __assetUrlCache[value] = resolved\n return resolved\n }\n // Not found in asset map - return as-is (might already be a usable reference)\n return value\n}\n\nfunction resolveAssetUrls(values, assetMap) {\n if (!Array.isArray(values)) return []\n return values\n .map(function(v) { return resolveAssetUrl(v, assetMap) })\n .filter(function(v) { return v != null && typeof v === 'string' })\n}\n\nfunction deduplicateStrings(arr) {\n var seen = {}\n return arr.filter(function(v) {\n if (!v || typeof v !== 'string' || seen[v]) return false\n seen[v] = true\n return true\n })\n}\n\n// Fetches the asset map from the database if available, with TTL-based caching\nasync function getAssetMap(getClientFn) {\n var now = Date.now()\n if (__assetMapCache && (now - __assetMapTimestamp) < ASSET_CACHE_TTL_MS) {\n return __assetMapCache\n }\n // Reset per-URL cache when asset map is refreshed\n __assetUrlCache = {}\n var map = {}\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query('SELECT id, src, remote_src, image_src, url FROM teleport_assets')\n if (result && result.rows) {\n result.rows.forEach(function(row) {\n map[row.id] = {\n src: row.src || null,\n remoteSrc: row.remote_src || null,\n imageSrc: row.image_src || null,\n url: row.url || null,\n }\n })\n }\n __assetMapCache = map\n __assetMapTimestamp = now\n } catch (e) {\n // teleport_assets table may not exist - cache empty map with short TTL\n __assetMapCache = map\n __assetMapTimestamp = now\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n";
|
|
7
|
+
return "\n// ============================================================\n// Shared Data Transformation Utilities\n// ============================================================\n\nvar CURRENCY_SYMBOLS = {\n USD: { symbol: '$', position: 'before' },\n EUR: { symbol: '\u20AC', position: 'before' },\n GBP: { symbol: '\u00A3', position: 'before' },\n JPY: { symbol: '\u00A5', position: 'before' },\n CAD: { symbol: 'C$', position: 'before' },\n AUD: { symbol: 'A$', position: 'before' },\n CHF: { symbol: 'CHF', position: 'before' },\n CNY: { symbol: '\u00A5', position: 'before' },\n INR: { symbol: '\u20B9', position: 'before' },\n BRL: { symbol: 'R$', position: 'before' },\n MXN: { symbol: 'MX$', position: 'before' },\n KRW: { symbol: '\u20A9', position: 'before' },\n SGD: { symbol: 'S$', position: 'before' },\n HKD: { symbol: 'HK$', position: 'before' },\n NOK: { symbol: 'kr', position: 'after' },\n SEK: { symbol: 'kr', position: 'after' },\n DKK: { symbol: 'kr', position: 'after' },\n PLN: { symbol: 'z\u0142', position: 'after' },\n CZK: { symbol: 'K\u010D', position: 'after' },\n HUF: { symbol: 'Ft', position: 'after' },\n RON: { symbol: 'lei', position: 'after' },\n TRY: { symbol: '\u20BA', position: 'before' },\n THB: { symbol: '\u0E3F', position: 'before' },\n IDR: { symbol: 'Rp', position: 'before' },\n PHP: { symbol: '\u20B1', position: 'before' },\n ZAR: { symbol: 'R', position: 'before' },\n RUB: { symbol: '\u20BD', position: 'after' },\n NZD: { symbol: 'NZ$', position: 'before' },\n TWD: { symbol: 'NT$', position: 'before' },\n ILS: { symbol: '\u20AA', position: 'before' },\n AED: { symbol: '\u062F.\u0625', position: 'before' },\n SAR: { symbol: '\uFDFC', position: 'before' },\n MYR: { symbol: 'RM', position: 'before' },\n VND: { symbol: '\u20AB', position: 'after' },\n CLP: { symbol: '$', position: 'before' },\n COP: { symbol: '$', position: 'before' },\n ARS: { symbol: '$', position: 'before' },\n PEN: { symbol: 'S/', position: 'before' },\n UAH: { symbol: '\u20B4', position: 'after' },\n BGN: { symbol: '\u043B\u0432', position: 'after' },\n HRK: { symbol: 'kn', position: 'after' },\n ISK: { symbol: 'kr', position: 'after' },\n NGN: { symbol: '\u20A6', position: 'before' },\n KES: { symbol: 'KSh', position: 'before' },\n EGP: { symbol: 'E\u00A3', position: 'before' },\n PKR: { symbol: '\u20A8', position: 'before' },\n BDT: { symbol: '\u09F3', position: 'before' },\n LKR: { symbol: '\u20A8', position: 'before' },\n GHS: { symbol: 'GH\u20B5', position: 'before' },\n}\n\nfunction getCurrencyInfo(currencyCode) {\n if (!currencyCode) return { symbol: '$', position: 'before' }\n var upper = currencyCode.toUpperCase()\n var entry = CURRENCY_SYMBOLS[upper]\n return entry || { symbol: upper, position: 'before' }\n}\n\nfunction getCurrencySymbol(currencyCode) {\n return getCurrencyInfo(currencyCode).symbol\n}\n\nfunction normalizeTimestamp(value) {\n if (value == null) return Date.now()\n if (typeof value === 'number') {\n if (isNaN(value)) return Date.now()\n return value < 100000000000 ? value * 1000 : value\n }\n if (typeof value === 'string') {\n var parsed = Date.parse(value)\n return isNaN(parsed) ? Date.now() : parsed\n }\n return Date.now()\n}\n\nfunction safeNumber(value, defaultValue) {\n if (value == null) return defaultValue\n var n = Number(value)\n return isNaN(n) ? defaultValue : n\n}\n\nfunction parseJsonArray(value) {\n if (!value) return []\n if (Array.isArray(value)) return value.filter(function(item) { return typeof item === 'string' })\n if (typeof value === 'string') {\n try {\n var parsed = JSON.parse(value)\n if (Array.isArray(parsed)) return parsed.filter(function(item) { return typeof item === 'string' })\n return []\n } catch (e) {\n return value.split(',').map(function(s) { return s.trim() }).filter(Boolean)\n }\n }\n return []\n}\n\n// The related-item picks a merchant/author made: a JSON array of row ids stored\n// in a TEXT column (`related_product_ids` / `related_post_ids`). Mirrors\n// parseRelatedEntityIds in the GUI (apps/gui/app/project-page/features/shared/\n// related-entities/related-entity-ids.ts) \u2014 order-preserving, deduplicated,\n// blanks dropped, tolerant of a comma-separated cell edited by hand.\n//\n// `indexOf` rather than a seen-map on purpose: these lists hold a handful of\n// entries, and an object keyed by arbitrary strings answers truthy for\n// 'constructor'/'toString'.\nfunction parseRelatedIds(value) {\n var raw = parseJsonArray(value)\n var ids = []\n for (var i = 0; i < raw.length; i++) {\n var id = String(raw[i] == null ? '' : raw[i]).trim()\n if (!id || ids.indexOf(id) !== -1) continue\n ids.push(id)\n }\n return ids\n}\n\nfunction parseJsonObject(value) {\n if (value == null) return {}\n if (typeof value === 'object' && !Array.isArray(value)) return value\n if (typeof value === 'string') {\n try {\n var parsed = JSON.parse(value)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed\n return {}\n } catch (e) {\n return {}\n }\n }\n return {}\n}\n\nvar HTML_ENTITY_MAP = {\n '&': '&', '<': '<', '>': '>', '"': '\"',\n ''': \"'\", ''': \"'\", ''': \"'\", ' ': ' ',\n ' ': ' ', '©': '\u00A9', '®': '\u00AE', '™': '\u2122',\n '…': '\u2026', '—': '\u2014', '–': '\u2013',\n}\n\nfunction decodeHtmlEntities(str) {\n if (!str) return str\n // Decode named and numeric entities\n return str\n .replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([a-zA-Z]+));/g, function(match, hex, dec, named) {\n if (hex) return String.fromCharCode(parseInt(hex, 16))\n if (dec) return String.fromCharCode(parseInt(dec, 10))\n var namedRef = '&' + named + ';'\n return HTML_ENTITY_MAP[namedRef] || match\n })\n}\n\nfunction stripHtmlTags(html) {\n if (!html || typeof html !== 'string') return ''\n // Remove script and style blocks entirely (including content)\n var cleaned = html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, ' ')\n .replace(/<style[\\s\\S]*?<\\/style>/gi, ' ')\n // Strip remaining tags\n cleaned = cleaned.replace(/<[^>]*>/g, ' ')\n // Decode HTML entities\n cleaned = decodeHtmlEntities(cleaned)\n // Collapse whitespace\n return cleaned.replace(/\\s+/g, ' ').trim()\n}\n\nfunction coerceBoolean(value, defaultValue) {\n if (value === true || value === 'true' || value === 1 || value === '1') return true\n if (value === false || value === 'false' || value === 0 || value === '0') return false\n return defaultValue\n}\n\nfunction pickFirst() {\n for (var i = 0; i < arguments.length; i++) {\n var val = arguments[i]\n if (val !== undefined && val !== null) return val\n }\n return null\n}\n\nfunction resolveI18nField(record, snakeCol, camelCol, currentLang, mainLang) {\n if (currentLang && mainLang && currentLang !== mainLang) {\n // Try language-prefixed snake_case column first, then camelCase\n var langSnakeKey = currentLang + '_' + snakeCol\n if (record[langSnakeKey] !== undefined && record[langSnakeKey] !== null && record[langSnakeKey] !== '') {\n return record[langSnakeKey]\n }\n if (snakeCol !== camelCol) {\n var langCamelKey = currentLang + '_' + camelCol\n if (record[langCamelKey] !== undefined && record[langCamelKey] !== null && record[langCamelKey] !== '') {\n return record[langCamelKey]\n }\n }\n }\n if (record[snakeCol] !== undefined && record[snakeCol] !== null) return record[snakeCol]\n if (snakeCol !== camelCol && record[camelCol] !== undefined && record[camelCol] !== null) return record[camelCol]\n return null\n}\n\n// Asset URL Resolution with TTL-based caching\nvar __assetUrlCache = {}\nvar __assetMapCache = null\nvar __assetMapTimestamp = 0\nvar ASSET_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n\nfunction isUrl(value) {\n if (!value || typeof value !== 'string') return false\n return value.startsWith('http://') || value.startsWith('https://') || value.startsWith('data:')\n}\n\nfunction resolveAssetUrl(value, assetMap) {\n if (!value || typeof value !== 'string') return null\n if (isUrl(value)) return value\n // Also treat absolute paths (starting with /) as URLs\n if (value.charAt(0) === '/') return value\n if (__assetUrlCache[value]) return __assetUrlCache[value]\n if (assetMap && assetMap[value]) {\n var asset = assetMap[value]\n var resolved = asset.remoteSrc || asset.imageSrc || asset.src || asset.url || value\n __assetUrlCache[value] = resolved\n return resolved\n }\n // Not found in asset map - return as-is (might already be a usable reference)\n return value\n}\n\n// Whether an asset-id resolution produced a real URL. resolveAssetUrl returns\n// an UNKNOWN id verbatim (asset deleted, teleport_assets not mirrored yet) and\n// a bare 'TQ_...' must never reach a <model-viewer src> or a poster.\nfunction isResolvedMediaUrl(value) {\n return typeof value === 'string' && (isUrl(value) || value.charAt(0) === '/')\n}\n\n// resolveAssetUrl for MEDIA that has no safe fallback: a value that did not\n// resolve to a URL is reported as absent (null) instead of passed through.\nfunction resolveMediaUrl(value, assetMap) {\n var resolved = resolveAssetUrl(value, assetMap)\n return isResolvedMediaUrl(resolved) ? resolved : null\n}\n\nfunction resolveAssetUrls(values, assetMap) {\n if (!Array.isArray(values)) return []\n return values\n .map(function(v) { return resolveAssetUrl(v, assetMap) })\n .filter(function(v) { return v != null && typeof v === 'string' })\n}\n\nfunction deduplicateStrings(arr) {\n var seen = {}\n return arr.filter(function(v) {\n if (!v || typeof v !== 'string' || seen[v]) return false\n seen[v] = true\n return true\n })\n}\n\n// Fetches the asset map from the database if available, with TTL-based caching\nasync function getAssetMap(getClientFn) {\n var now = Date.now()\n if (__assetMapCache && (now - __assetMapTimestamp) < ASSET_CACHE_TTL_MS) {\n return __assetMapCache\n }\n // Reset per-URL cache when asset map is refreshed\n __assetUrlCache = {}\n var map = {}\n var client\n try {\n client = getClientFn()\n await client.connect()\n var result = await client.query('SELECT id, src, remote_src, image_src, url FROM teleport_assets')\n if (result && result.rows) {\n result.rows.forEach(function(row) {\n map[row.id] = {\n src: row.src || null,\n remoteSrc: row.remote_src || null,\n imageSrc: row.image_src || null,\n url: row.url || null,\n }\n })\n }\n __assetMapCache = map\n __assetMapTimestamp = now\n } catch (e) {\n // teleport_assets table may not exist - cache empty map with short TTL\n __assetMapCache = map\n __assetMapTimestamp = now\n } finally {\n if (client) {\n try { await client.end() } catch (e) { /* ignore */ }\n }\n }\n return map\n}\n";
|
|
8
8
|
};
|
|
9
9
|
//# sourceMappingURL=shared-utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-utils.js","sourceRoot":"","sources":["../../../src/transformations/shared-utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,IAAM,gCAAgC,GAAG;IAC9C,OAAO,
|
|
1
|
+
{"version":3,"file":"shared-utils.js","sourceRoot":"","sources":["../../../src/transformations/shared-utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,IAAM,gCAAgC,GAAG;IAC9C,OAAO,kxVAySR,CAAA;AACD,CAAC,CAAA"}
|