@aglyn/plugins-commerce 1.15.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  15. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  16. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  17. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  18. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  19. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  20. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  21. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  23. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  24. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  25. package/src/lib/components/console/quote-messages.component.js +185 -0
  26. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  27. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  28. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  29. package/src/lib/components/console/quote-proofs.component.js +30 -3
  30. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  31. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  32. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  33. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  34. package/src/lib/components/product-builder-context.d.ts +22 -0
  35. package/src/lib/components/product-builder-context.js +21 -0
  36. package/src/lib/components/product-builder-context.js.map +1 -0
  37. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  38. package/src/lib/components/product-builder-mockup.js +120 -0
  39. package/src/lib/components/product-builder-mockup.js.map +1 -0
  40. package/src/lib/components/product-builder-sample.d.ts +63 -0
  41. package/src/lib/components/product-builder-sample.js +96 -0
  42. package/src/lib/components/product-builder-sample.js.map +1 -0
  43. package/src/lib/components/product-choice-cards.d.ts +51 -0
  44. package/src/lib/components/product-choice-cards.js +311 -0
  45. package/src/lib/components/product-choice-cards.js.map +1 -0
  46. package/src/lib/components/product-detail-panels.d.ts +42 -0
  47. package/src/lib/components/product-detail-panels.js +185 -0
  48. package/src/lib/components/product-detail-panels.js.map +1 -0
  49. package/src/lib/components/product-detail.d.ts +20 -12
  50. package/src/lib/components/product-detail.js +136 -221
  51. package/src/lib/components/product-detail.js.map +1 -1
  52. package/src/lib/components/product-grid.d.ts +7 -0
  53. package/src/lib/components/product-grid.js +11 -8
  54. package/src/lib/components/product-grid.js.map +1 -1
  55. package/src/lib/components/product-options-field-body.d.ts +9 -8
  56. package/src/lib/components/product-options-field-body.js +152 -3
  57. package/src/lib/components/product-options-field-body.js.map +1 -1
  58. package/src/lib/components/product-options-field.js +1 -1
  59. package/src/lib/components/product-options-field.js.map +1 -1
  60. package/src/lib/components/product-photo-fit.d.ts +49 -0
  61. package/src/lib/components/product-photo-fit.js +58 -0
  62. package/src/lib/components/product-photo-fit.js.map +1 -0
  63. package/src/lib/components/product-restock-notify.d.ts +12 -0
  64. package/src/lib/components/product-restock-notify.js +86 -0
  65. package/src/lib/components/product-restock-notify.js.map +1 -0
  66. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  67. package/src/lib/components/quote-messages-panel.js +191 -0
  68. package/src/lib/components/quote-messages-panel.js.map +1 -0
  69. package/src/lib/components/quote-page-body.js +15 -1
  70. package/src/lib/components/quote-page-body.js.map +1 -1
  71. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  72. package/src/lib/components/quote-proof-panel.js +139 -14
  73. package/src/lib/components/quote-proof-panel.js.map +1 -1
  74. package/src/lib/components/related-products.d.ts +7 -0
  75. package/src/lib/components/related-products.js +8 -6
  76. package/src/lib/components/related-products.js.map +1 -1
  77. package/src/lib/constants/quote-page.d.ts +8 -0
  78. package/src/lib/constants/quote-page.js +11 -0
  79. package/src/lib/constants/quote-page.js.map +1 -1
  80. package/src/lib/model/commerce-cart.d.ts +6 -1
  81. package/src/lib/model/commerce-cart.js +5 -1
  82. package/src/lib/model/commerce-cart.js.map +1 -1
  83. package/src/lib/model/commerce-invoices.js +5 -1
  84. package/src/lib/model/commerce-invoices.js.map +1 -1
  85. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  86. package/src/lib/model/commerce-pos-ops.js +3 -0
  87. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  88. package/src/lib/model/commerce-pos.d.ts +8 -0
  89. package/src/lib/model/commerce-pos.js.map +1 -1
  90. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  91. package/src/lib/model/commerce-quote-messages.js +146 -0
  92. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  93. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  94. package/src/lib/model/commerce-quote-pay.js +31 -7
  95. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  96. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  97. package/src/lib/model/commerce-quote-proofs.js +73 -18
  98. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  99. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  100. package/src/lib/model/commerce-quote-request.js +25 -2
  101. package/src/lib/model/commerce-quote-request.js.map +1 -1
  102. package/src/lib/model/commerce-quotes.d.ts +56 -3
  103. package/src/lib/model/commerce-quotes.js +47 -2
  104. package/src/lib/model/commerce-quotes.js.map +1 -1
  105. package/src/lib/model/commerce.d.ts +12 -1
  106. package/src/lib/model/commerce.js.map +1 -1
  107. package/src/lib/model/index.d.ts +1 -0
  108. package/src/lib/model/index.js +1 -0
  109. package/src/lib/model/index.js.map +1 -1
  110. package/src/lib/model/pos-cellular.d.ts +5 -0
  111. package/src/lib/model/pos-cellular.js.map +1 -1
  112. package/src/lib/model/product-card-rules.d.ts +41 -0
  113. package/src/lib/model/product-card-rules.js +90 -0
  114. package/src/lib/model/product-card-rules.js.map +1 -0
  115. package/src/lib/model/product-modifiers.d.ts +11 -0
  116. package/src/lib/model/product-modifiers.js +10 -0
  117. package/src/lib/model/product-modifiers.js.map +1 -1
  118. package/src/lib/model/product-write.d.ts +3 -0
  119. package/src/lib/server/billing-webhook.js +6 -2
  120. package/src/lib/server/billing-webhook.js.map +1 -1
  121. package/src/lib/server/cancel-order.js +15 -0
  122. package/src/lib/server/cancel-order.js.map +1 -1
  123. package/src/lib/server/channel-order-updates.js +15 -1
  124. package/src/lib/server/channel-order-updates.js.map +1 -1
  125. package/src/lib/server/channel-orders.js +20 -0
  126. package/src/lib/server/channel-orders.js.map +1 -1
  127. package/src/lib/server/checkout.js +1 -1
  128. package/src/lib/server/checkout.js.map +1 -1
  129. package/src/lib/server/local-fulfillment.js +1 -1
  130. package/src/lib/server/local-fulfillment.js.map +1 -1
  131. package/src/lib/server/pos-cellular-billing.d.ts +1 -1
  132. package/src/lib/server/pos-cellular-billing.js +2 -1
  133. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  134. package/src/lib/server/pos-cellular.d.ts +3 -1
  135. package/src/lib/server/pos-cellular.js +15 -8
  136. package/src/lib/server/pos-cellular.js.map +1 -1
  137. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  138. package/src/lib/server/pos-offline-sync.js +17 -4
  139. package/src/lib/server/pos-offline-sync.js.map +1 -1
  140. package/src/lib/server/pos-order.js +17 -6
  141. package/src/lib/server/pos-order.js.map +1 -1
  142. package/src/lib/server/pos-payment.js +27 -11
  143. package/src/lib/server/pos-payment.js.map +1 -1
  144. package/src/lib/server/pos-reader-splash.js +10 -5
  145. package/src/lib/server/pos-reader-splash.js.map +1 -1
  146. package/src/lib/server/pos-readers.js +34 -10
  147. package/src/lib/server/pos-readers.js.map +1 -1
  148. package/src/lib/server/pos-return.js +19 -3
  149. package/src/lib/server/pos-return.js.map +1 -1
  150. package/src/lib/server/pos-stripe.d.ts +14 -0
  151. package/src/lib/server/pos-stripe.js +6 -2
  152. package/src/lib/server/pos-stripe.js.map +1 -1
  153. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  154. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  155. package/src/lib/server/pos-terminal.d.ts +80 -14
  156. package/src/lib/server/pos-terminal.js +393 -123
  157. package/src/lib/server/pos-terminal.js.map +1 -1
  158. package/src/lib/server/product-drafts.d.ts +1 -1
  159. package/src/lib/server/product-drafts.js +4 -3
  160. package/src/lib/server/product-drafts.js.map +1 -1
  161. package/src/lib/server/product-writer.js +5 -4
  162. package/src/lib/server/product-writer.js.map +1 -1
  163. package/src/lib/server/product.d.ts +11 -0
  164. package/src/lib/server/product.js +18 -3
  165. package/src/lib/server/product.js.map +1 -1
  166. package/src/lib/server/products-write.js +4 -3
  167. package/src/lib/server/products-write.js.map +1 -1
  168. package/src/lib/server/quote-email.d.ts +26 -0
  169. package/src/lib/server/quote-email.js +73 -7
  170. package/src/lib/server/quote-email.js.map +1 -1
  171. package/src/lib/server/quote-messages.d.ts +72 -0
  172. package/src/lib/server/quote-messages.js +356 -0
  173. package/src/lib/server/quote-messages.js.map +1 -0
  174. package/src/lib/server/quote-pay.d.ts +42 -0
  175. package/src/lib/server/quote-pay.js +81 -4
  176. package/src/lib/server/quote-pay.js.map +1 -1
  177. package/src/lib/server/quote-proofs.d.ts +1 -1
  178. package/src/lib/server/quote-proofs.js +63 -19
  179. package/src/lib/server/quote-proofs.js.map +1 -1
  180. package/src/lib/server/quote.d.ts +12 -0
  181. package/src/lib/server/quote.js +44 -14
  182. package/src/lib/server/quote.js.map +1 -1
  183. package/src/lib/server/refund.js +3 -1
  184. package/src/lib/server/refund.js.map +1 -1
  185. package/src/lib/server/reserve-stock.js +9 -0
  186. package/src/lib/server/reserve-stock.js.map +1 -1
  187. package/src/lib/server/returns.js +15 -1
  188. package/src/lib/server/returns.js.map +1 -1
  189. package/src/lib/server/reviews.js +15 -0
  190. package/src/lib/server/reviews.js.map +1 -1
  191. package/src/lib/server/sold-out-drop.d.ts +58 -0
  192. package/src/lib/server/sold-out-drop.js +81 -0
  193. package/src/lib/server/sold-out-drop.js.map +1 -0
  194. package/src/lib/server/stock-levels.js +9 -0
  195. package/src/lib/server/stock-levels.js.map +1 -1
  196. package/src/lib/server/stripe-refund.d.ts +7 -0
  197. package/src/lib/server/stripe-refund.js +26 -7
  198. package/src/lib/server/stripe-refund.js.map +1 -1
  199. package/src/lib/server.js +2 -0
  200. package/src/lib/server.js.map +1 -1
  201. package/src/lib/tenant-emails.js +85 -2
  202. package/src/lib/tenant-emails.js.map +1 -1
  203. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  204. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  205. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  206. package/src/lib/transfer/product-transfer.js +6 -5
  207. package/src/lib/transfer/product-transfer.js.map +1 -1
  208. package/src/lib/transfer/products.server.js +4 -3
  209. package/src/lib/transfer/products.server.js.map +1 -1
  210. package/src/lib/utils/quote-email-content.d.ts +6 -0
  211. package/src/lib/utils/quote-email-content.js +6 -3
  212. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n COMMERCE_DEFAULT_PRICE_USD,\n COMMERCE_MAX_OPTION_VALUES,\n COMMERCE_MAX_OPTIONS,\n COMMERCE_MAX_PRICE_USD,\n COMMERCE_MAX_VARIANTS,\n commerceSlug,\n type HostProduct,\n productCollectionIds,\n productPriceMissing,\n productSearchFields,\n type ProductType,\n type ProposedProduct,\n type SmartCollectionRules,\n unpricedProductDraft,\n type UnpricedProductDraft,\n validateProduct,\n} from '../model/commerce'\n\n/**\n * A PRODUCT ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `product` resource on the\n * core's resource-drafts seam. A plugin that sets a store up from a brief\n * asks for the writer by name and gets this plugin's rules:\n *\n * - THE DOCUMENT is the one the products card makes from an accepted AI\n * proposal (`unpricedProductDraft`): a `draft` — off the storefront, and\n * refused by every sale door — with one variant per combination of its\n * options, no photo, and the search, stock and smart-collection keys every\n * product write derives. Born live (`deletedAt: null`), as the product\n * resource stamps it, so the products table lists it. A caller may ask\n * for it to be LISTED before it has a price (`comingSoon`, AGL-3676): it\n * is then `active` and the storefront says \"Price coming soon\" where the\n * price would be — still sold by no door until every variant is priced —\n * and may hand it photos already in the site's media library.\n * - THE PRICE is the one the content states, else the default price\n * (`COMMERCE_DEFAULT_PRICE_USD`, AGL-3676) for the owner to change. Only\n * a caller that says `priceUsd: null` gets a product with none, which the\n * storefront lists as \"Price coming soon\" and no door sells.\n * - THE ROOM is the `productsPerHost` allowance, counted the way the\n * resources route and the importer count it, inside the transaction that\n * creates. THE PLAN is the `commerce` feature, and THE ROLE a member who\n * may write the site's content — refused in the resources route's words.\n * - THE CHECK is `validateProduct`, the rule every product write is held to,\n * with a placeholder price standing in where none was stated.\n *\n * Nothing is published, priced or sold. The writer touches the one new\n * product document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const PRODUCT_DRAFT_RESOURCE = 'product'\n\n/** The longest product name the proposals and the editor keep. */\nexport const PRODUCT_DRAFT_NAME_MAX = 120\n/** The longest description a draft keeps. */\nexport const PRODUCT_DRAFT_DESCRIPTION_MAX = 5_000\n/** The most tags a draft keeps, and the longest one. */\nexport const PRODUCT_DRAFT_TAGS_MAX = 20\nexport const PRODUCT_DRAFT_TAG_MAX = 40\n/** The most categories a draft is filed under. */\nexport const PRODUCT_DRAFT_CATEGORIES_MAX = 10\n/** The longest search-listing title and description a draft keeps. */\nexport const PRODUCT_DRAFT_SEO_TITLE_MAX = 120\nexport const PRODUCT_DRAFT_SEO_DESCRIPTION_MAX = 320\n\n/** The resources route's refusal for a member who may not write the site. */\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const PRODUCT_DRAFT_ROLE_REFUSAL = siteKeyRefusal('site.edit')\n/** The resources route's refusal for a plan without the feature. */\nexport const PRODUCT_DRAFT_PLAN_REFUSAL = 'This feature is not included in your plan — see Billing'\n\n/** The resources route's refusal at the plan's allowance. */\nexport function productDraftLimitRefusal(limit: number): string {\n return `Your plan includes ${limit} ${limit === 1 ? 'product' : 'products'} — ` +\n 'upgrade in Billing for more'\n}\n\n/**\n * What a caller sends as `content`: a proposed product, as the AI products\n * job proposes one, with an optional stated price for every variant and the\n * ids of categories the site already has, and optionally photos already in\n * the site's media library and whether to list it before it has a price.\n */\nexport interface ProductDraftContent {\n name: string\n type?: ProductType\n description?: string\n tags?: string[]\n options?: Array<{ name: string; values: string[] }>\n seoTitle?: string\n seoDescription?: string\n /**\n * One price for every variant, in dollars. Absent is the default price\n * (AGL-3676); `null` leaves them unpriced on purpose.\n */\n priceUsd?: number | null\n /** Ids of the site's product categories; one the site lacks is dropped. */\n categoryIds?: string[]\n /**\n * List the product on the storefront before it has a price (AGL-3676):\n * written `active`, so the catalog shows it and its page answers, while\n * every sale door still refuses a variant with no price\n * (`variantHasPrice`) and the storefront says \"Price coming soon\" where a\n * price would be. Absent or false, an unpriced product stays a draft.\n */\n comingSoon?: boolean\n /**\n * Photos already in the site's media library, first = primary (AGL-3676):\n * the slot a guided start fills with a stock photo, or a starter, for the\n * merchant to replace with their own.\n */\n mediaUrls?: string[]\n /**\n * A SAMPLE for the merchant to replace (AGL-4065): a guided start whose\n * brief named kinds of product and no product writes its first products\n * as samples of those kinds. Stored as `sample: true`, which Products\n * shows and the storefront never reads; the merchant's save clears it.\n */\n sample?: boolean\n}\n\n/** The most photos a draft is written with. */\nexport const PRODUCT_DRAFT_MEDIA_MAX = 4\n\n/** A photo address a draft keeps: an https URL or a path on the site, never a script or a data URL. */\nconst MEDIA_URL = /^(?:https:\\/\\/[^\\s\"'<>]+|\\/[^\\s\"'<>]*)$/\n\nconst PRODUCT_TYPES: readonly ProductType[] = ['physical', 'digital', 'service']\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\nfunction strings(label: string, value: unknown, problems: string[]): string[] {\n if (value === undefined) return []\n if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {\n problems.push(`${label} are a list of words`)\n return []\n }\n return [...new Set(value.map(line).filter(Boolean))]\n}\n\n/** A draft as the writer will store it, before its slug and keys are settled. */\nexport interface ProductDraftRead {\n proposal: ProposedProduct\n /** The price for every variant (stated, else the default), or `null` for the merchant to set. */\n priceUsd: number | null\n categoryIds: string[]\n /** Listed before it has a price (`ProductDraftContent.comingSoon`). */\n comingSoon: boolean\n mediaUrls: string[]\n /** A sample to replace (`ProductDraftContent.sample`, AGL-4065); absent where it is not one. */\n sample?: true\n}\n\nexport type ProductDraftContentRead =\n | { ok: true; value: ProductDraftRead }\n | { ok: false; problems: string[] }\n\n/** The content as the writer reads it, or every problem that stops it. */\nexport function readProductDraftContent(\n content: Readonly<Record<string, unknown>>,\n): ProductDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The product needs a name')\n else if (name.length > PRODUCT_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${PRODUCT_DRAFT_NAME_MAX} characters`)\n }\n const rawType = content['type'] ?? 'physical'\n if (!(PRODUCT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push('The type is physical, digital or service')\n }\n const rawDescription = content['description']\n const description = typeof rawDescription === 'string' ? rawDescription.trim() : ''\n if (rawDescription !== undefined && typeof rawDescription !== 'string') {\n problems.push('The description is text')\n } else if (description.length > PRODUCT_DRAFT_DESCRIPTION_MAX) {\n problems.push(`The description is longer than ${PRODUCT_DRAFT_DESCRIPTION_MAX} characters`)\n }\n const tags = strings('Tags', content['tags'], problems)\n if (tags.length > PRODUCT_DRAFT_TAGS_MAX) problems.push(`A product keeps at most ${PRODUCT_DRAFT_TAGS_MAX} tags`)\n if (tags.some((tag) => tag.length > PRODUCT_DRAFT_TAG_MAX)) {\n problems.push(`A tag is longer than ${PRODUCT_DRAFT_TAG_MAX} characters`)\n }\n const categoryIds = strings('Categories', content['categoryIds'], problems)\n if (categoryIds.length > PRODUCT_DRAFT_CATEGORIES_MAX) {\n problems.push(`A product is filed under at most ${PRODUCT_DRAFT_CATEGORIES_MAX} categories`)\n }\n const seoTitle = line(content['seoTitle'])\n const seoDescription = line(content['seoDescription'])\n if (seoTitle.length > PRODUCT_DRAFT_SEO_TITLE_MAX) {\n problems.push(`The search title is longer than ${PRODUCT_DRAFT_SEO_TITLE_MAX} characters`)\n }\n if (seoDescription.length > PRODUCT_DRAFT_SEO_DESCRIPTION_MAX) {\n problems.push(`The search description is longer than ${PRODUCT_DRAFT_SEO_DESCRIPTION_MAX} characters`)\n }\n\n // Options are held here before the draft expands them: a matrix past the\n // variant ceiling is refused, never built.\n const rawOptions = content['options'] ?? []\n const options: ProposedProduct['options'] = []\n if (!Array.isArray(rawOptions)) {\n problems.push('Options are a list of a name and its values')\n } else {\n if (rawOptions.length > COMMERCE_MAX_OPTIONS) {\n problems.push(`At most ${COMMERCE_MAX_OPTIONS} options per product`)\n }\n for (const option of rawOptions) {\n const optionName = isRecord(option) ? line(option['name']) : ''\n const values = isRecord(option) ? strings(`The values of \"${optionName}\"`, option['values'], problems) : []\n if (!optionName || !values.length) {\n problems.push('Each option needs a name and at least one value')\n continue\n }\n if (values.length > COMMERCE_MAX_OPTION_VALUES) {\n problems.push(`Option \"${optionName}\" has too many values`)\n continue\n }\n options.push({ name: optionName, values })\n }\n if (new Set(options.map((option) => option.name)).size !== options.length) {\n problems.push('Each option needs its own name')\n }\n const combinations = options.reduce((count, option) => count * option.values.length, 1)\n if (combinations > COMMERCE_MAX_VARIANTS) {\n problems.push(`Those options make ${combinations} variants; a product holds at most ${COMMERCE_MAX_VARIANTS}`)\n }\n }\n\n // The stated price, else the default (AGL-3676); `null` asks for none.\n const rawPrice = content['priceUsd']\n let priceUsd: number | null = rawPrice === null ? null : COMMERCE_DEFAULT_PRICE_USD\n if (rawPrice !== undefined && rawPrice !== null) {\n if (\n typeof rawPrice !== 'number' ||\n !Number.isFinite(rawPrice) ||\n rawPrice < 0 ||\n rawPrice > COMMERCE_MAX_PRICE_USD ||\n Math.round(rawPrice * 100) !== rawPrice * 100\n ) {\n problems.push(`A stated price is dollars and cents from 0 to ${COMMERCE_MAX_PRICE_USD}`)\n } else {\n priceUsd = rawPrice\n }\n }\n const rawComingSoon = content['comingSoon']\n if (rawComingSoon !== undefined && typeof rawComingSoon !== 'boolean') {\n problems.push('Coming soon is true or false')\n }\n const rawSample = content['sample']\n if (rawSample !== undefined && typeof rawSample !== 'boolean') problems.push('Sample is true or false')\n const mediaUrls = strings('Photos', content['mediaUrls'], problems)\n if (mediaUrls.length > PRODUCT_DRAFT_MEDIA_MAX) {\n problems.push(`A product is written with at most ${PRODUCT_DRAFT_MEDIA_MAX} photos`)\n }\n if (mediaUrls.some((url) => url.length > 2_000 || !MEDIA_URL.test(url))) {\n problems.push('A photo is an https address or a path on this site')\n }\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n return {\n ok: true,\n value: {\n proposal: {\n name,\n type: rawType as ProductType,\n description,\n tags,\n options,\n seoTitle,\n seoDescription,\n },\n priceUsd,\n categoryIds,\n comingSoon: rawComingSoon === true,\n mediaUrls,\n ...(rawSample === true ? { sample: true as const } : {}),\n },\n }\n}\n\n/** The product document a read builds, under `slug`, at `nowMs`. */\nexport function productDraftDocument(\n read: ProductDraftRead,\n slug: string,\n nowMs: number,\n): UnpricedProductDraft | HostProduct {\n const draft = unpricedProductDraft(read.proposal, new Set(), nowMs)\n const priced =\n read.priceUsd === null\n ? draft\n : ({\n ...draft,\n variants: draft.variants.map((variant) => ({ ...variant, priceUsd: read.priceUsd as number })),\n } as HostProduct)\n return {\n ...priced,\n // The search keys travel with every create; recomputed for the price.\n ...productSearchFields(priced as HostProduct),\n slug,\n // Listed before it has a price (AGL-3676): the storefront says \"Price\n // coming soon\", and no sale door sells a variant without one.\n ...(read.comingSoon ? { status: 'active' as const } : {}),\n ...(read.mediaUrls.length ? { mediaUrls: read.mediaUrls } : {}),\n ...(read.categoryIds.length ? { categoryIds: read.categoryIds } : {}),\n // A sample for the merchant to replace (AGL-4065): Products marks it.\n ...(read.sample ? { sample: true } : {}),\n }\n}\n\n/** What the owner's product rule says about a draft, a placeholder price standing in for none. */\nfunction productProblem(product: UnpricedProductDraft | HostProduct): string | null {\n return validateProduct({\n ...product,\n variants: product.variants.map((variant) => ({\n ...variant,\n priceUsd: (variant as { priceUsd?: number }).priceUsd ?? 0,\n })),\n } as HostProduct)\n}\n\nfunction factsOf(product: Partial<HostProduct>) {\n return {\n status: product.status ?? 'draft',\n slug: product.slug ?? '',\n type: product.type ?? 'physical',\n variants: product.variants?.length ?? 0,\n priceMissing: productPriceMissing({ variants: product.variants ?? [] }),\n }\n}\n\n/** Whether content is a product this plugin would store, with what it says about it. Pure. */\nexport function checkProductDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readProductDraftContent(content)\n if (read.ok === false) return read\n const slug = commerceSlug(read.value.proposal.name) || 'product'\n const product = productDraftDocument(read.value, slug, 0)\n const problem = productProblem(product)\n return problem ? { ok: false, problems: [problem] } : { ok: true, facts: factsOf(product as HostProduct) }\n}\n\nfunction recordOf(product: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (product.data() ?? {}) as Partial<HostProduct>\n return { id: product.id, name: String(data.name ?? ''), versionId: null, facts: factsOf(data) }\n}\n\nexport function roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n return holdsSiteKey(host, uid, 'site.edit') ? null : { status: 403, error: PRODUCT_DRAFT_ROLE_REFUSAL }\n}\n\nexport function planRefusal(org: PluginDraftContext['org']): PluginDraftRefusal | null {\n return checkEntitlement(org as never, 'commerce') ? null : { status: 403, error: PRODUCT_DRAFT_PLAN_REFUSAL }\n}\n\n/** The allowance, counted as the resources route and the importer count a product create. */\nexport function roomRefusal(org: PluginDraftContext['org'], used: number): PluginDraftRefusal | null {\n const quota = checkQuota(org as never, 'productsPerHost', used)\n return quota.allowed ? null : { status: 403, error: productDraftLimitRefusal(quota.limit) }\n}\n\n/** Candidates asked of the store at once, as the console's slug ledger probes. */\nconst SLUG_PROBE = 10\n\n/**\n * The first of `base`, `base-2`, `base-3`, … that no product holds, live or\n * deleted — a soft-deleted product still answers its slug on the storefront\n * (`productSlugLedger`, AGL-3321). Asked inside the transaction.\n */\nasync function freeSlug(\n products: FirebaseFirestore.CollectionReference,\n base: string,\n read: (query: FirebaseFirestore.Query) => Promise<FirebaseFirestore.QuerySnapshot>,\n): Promise<string> {\n const candidate = (suffix: number) => (suffix < 2 ? base : `${base}-${suffix}`)\n for (let first = 1; ; first += SLUG_PROBE) {\n const batch = Array.from({ length: SLUG_PROBE }, (_, offset) => candidate(first + offset))\n const held = new Set(\n (await read(products.where('slug', 'in', batch))).docs.map((doc) => String(doc.get('slug') ?? '')),\n )\n const free = batch.find((slug) => !held.has(slug))\n if (free) return free\n }\n}\n\nexport interface ProductDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nexport function createProductDraftWriter(deps: ProductDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const early = roleRefusal(host, context.uid) ?? planRefusal(context.org)\n if (early) return early\n const used = await countLiveDocuments(hostRef.collection('products'))\n return roomRefusal(context.org, Number(used) || 0)\n },\n\n check: (content) => checkProductDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const product = await firestore().collection('hosts').doc(hostId).collection('products').doc(id).get()\n return product.exists ? recordOf(product) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readProductDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(productRef)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // Asked again under the same id: the draft it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const early = roleRefusal(host, request.uid) ?? planRefusal(request.org)\n if (early) return { ok: false, ...early }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(request.org, Number(used) || 0)\n if (room) return { ok: false, ...room }\n const base = commerceSlug(read.value.proposal.name) || 'product'\n const [slug, categories, smart] = await Promise.all([\n freeSlug(products, base, (query) => tx.get(query)),\n // A category the site does not have is dropped, not stored.\n read.value.categoryIds.length\n ? Promise.all(read.value.categoryIds.map((id) => tx.get(hostRef.collection('productCategories').doc(id))))\n : Promise.resolve([]),\n tx.get(hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')),\n ])\n const categoryIds = categories.filter((category) => category.exists).map((category) => category.id)\n const nowMs = request.now.getTime()\n const product = productDraftDocument({ ...read.value, categoryIds }, slug, nowMs)\n const problem = productProblem(product)\n if (problem) return { ok: false, status: 400, error: problem }\n const rules: SmartCollectionRules[] = smart.docs.map((doc) => ({\n id: doc.id,\n rules: doc.get('rules') ?? [],\n matchAll: doc.get('matchAll'),\n }))\n const priced = read.value.priceUsd !== null\n tx.create(productRef, {\n ...product,\n collectionIds: productCollectionIds(product as HostProduct, rules),\n // The legacy flat price every create path still writes, only where\n // there is one: an unpriced draft is not a free one.\n ...(priced ? { priceUsd: read.value.priceUsd } : {}),\n deletedAt: null,\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name: product.name,\n versionId: null,\n facts: factsOf(product as HostProduct),\n }\n })\n },\n }\n}\n\nexport const productDraftWriter = createProductDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerProductDraftWriter(): void {\n registerPluginResourceDraftWriter(PRODUCT_DRAFT_RESOURCE, productDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["checkEntitlement","checkQuota","holdsSiteKey","siteKeyRefusal","countLiveDocuments","registerPluginResourceDraftWriter","firebaseAdmin","BUNDLE_ID","COMMERCE_DEFAULT_PRICE_USD","COMMERCE_MAX_OPTION_VALUES","COMMERCE_MAX_OPTIONS","COMMERCE_MAX_PRICE_USD","COMMERCE_MAX_VARIANTS","commerceSlug","productCollectionIds","productPriceMissing","productSearchFields","unpricedProductDraft","validateProduct","PRODUCT_DRAFT_RESOURCE","PRODUCT_DRAFT_NAME_MAX","PRODUCT_DRAFT_DESCRIPTION_MAX","PRODUCT_DRAFT_TAGS_MAX","PRODUCT_DRAFT_TAG_MAX","PRODUCT_DRAFT_CATEGORIES_MAX","PRODUCT_DRAFT_SEO_TITLE_MAX","PRODUCT_DRAFT_SEO_DESCRIPTION_MAX","PRODUCT_DRAFT_ROLE_REFUSAL","PRODUCT_DRAFT_PLAN_REFUSAL","productDraftLimitRefusal","limit","PRODUCT_DRAFT_MEDIA_MAX","MEDIA_URL","PRODUCT_TYPES","isRecord","value","Array","isArray","line","replace","trim","strings","label","problems","undefined","some","entry","push","Set","map","filter","Boolean","readProductDraftContent","content","name","length","rawType","includes","rawDescription","description","tags","tag","categoryIds","seoTitle","seoDescription","rawOptions","options","option","optionName","values","size","combinations","reduce","count","rawPrice","priceUsd","Number","isFinite","Math","round","rawComingSoon","rawSample","mediaUrls","url","test","ok","proposal","type","comingSoon","sample","productDraftDocument","read","slug","nowMs","draft","priced","variants","variant","status","productProblem","product","factsOf","priceMissing","checkProductDraftContent","problem","facts","recordOf","data","id","String","versionId","roleRefusal","host","uid","error","planRefusal","org","roomRefusal","used","quota","allowed","SLUG_PROBE","freeSlug","products","base","candidate","suffix","first","batch","from","_","offset","held","where","docs","doc","get","free","find","has","createProductDraftWriter","deps","firestore","app","refusal","context","hostRef","collection","hostId","exists","early","check","write","request","asked","db","productRef","runTransaction","tx","existing","Promise","all","replayed","aggregate","room","categories","smart","query","resolve","category","now","getTime","rules","matchAll","create","collectionIds","deletedAt","createdAt","updatedAt","createdBy","productDraftWriter","registerProductDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AACvF,SAASC,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,iCAAiC,QAO5B,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,oBAAoB,EACpBC,sBAAsB,EACtBC,qBAAqB,EACrBC,YAAY,EAEZC,oBAAoB,EACpBC,mBAAmB,EACnBC,mBAAmB,EAInBC,oBAAoB,EAEpBC,eAAe,QACV,uBAAmB;AAoC1B,uDAAuD,GACvD,OAAO,MAAMC,yBAAyB,UAAS;AAE/C,gEAAgE,GAChE,OAAO,MAAMC,yBAAyB,IAAG;AACzC,2CAA2C,GAC3C,OAAO,MAAMC,gCAAgC,KAAK;AAClD,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,GAAE;AACxC,OAAO,MAAMC,wBAAwB,GAAE;AACvC,gDAAgD,GAChD,OAAO,MAAMC,+BAA+B,GAAE;AAC9C,oEAAoE,GACpE,OAAO,MAAMC,8BAA8B,IAAG;AAC9C,OAAO,MAAMC,oCAAoC,IAAG;AAEpD,2EAA2E,GAC3E,qEAAqE,GACrE,OAAO,MAAMC,6BAA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AAS7D,EAAE;gBAClG,MAAMf,QAAQ4D,QAAQiB,GAAG,CAACC,OAAO;gBACjC,MAAMvE,UAAUV,qBAAqB,aAAKC,KAAKxD,KAAK;oBAAE2B;oBAAe8B,MAAMC;gBAC3E,MAAMW,UAAUL,eAAeC;gBAC/B,IAAII,SAAS,OAAO;oBAAEnB,IAAI;oBAAOa,QAAQ;oBAAKgB,OAAOV;gBAAQ;gBAC7D,MAAMoE,QAAgCN,MAAMhC,IAAI,CAACrF,GAAG,CAAC,CAACsF;wBAE7CA;2BAFsD;wBAC7D3B,IAAI2B,IAAI3B,EAAE;wBACVgE,KAAK,GAAErC,WAAAA,IAAIC,GAAG,CAAC,oBAARD,WAAoB,EAAE;wBAC7BsC,UAAUtC,IAAIC,GAAG,CAAC;oBACpB;;gBACA,MAAMzC,SAASJ,KAAKxD,KAAK,CAACwC,QAAQ,KAAK;gBACvCmF,GAAGgB,MAAM,CAAClB,YAAY,aACjBxD;oBACH2E,eAAejK,qBAAqBsF,SAAwBwE;mBAGxD7E,SAAS;oBAAEpB,UAAUgB,KAAKxD,KAAK,CAACwC,QAAQ;gBAAC,IAAI,CAAC;oBAClDqG,WAAW;oBACXC,WAAWxB,QAAQiB,GAAG;oBACtBQ,WAAWzB,QAAQiB,GAAG;oBACtBS,WAAW1B,QAAQxC,GAAG;;gBAExB,OAAO;oBACL5B,IAAI;oBACJ6E,UAAU;oBACVtD,IAAI6C,QAAQ7C,EAAE;oBACdtD,MAAM8C,QAAQ9C,IAAI;oBAClBwD,WAAW;oBACXL,OAAOJ,QAAQD;gBACjB;YACF;QACF;IACF;AACF;AAEA,OAAO,MAAMgF,qBAAqBxC,2BAA0B;AAE5D;;;CAGC,GACD,OAAO,SAASyC;IACdhL,kCAAkCc,wBAAwBiK,oBAAoB;QAAEE,UAAU/K;IAAU;AACtG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateProductForSave } from '../model/product-card-rules'\nimport { checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n COMMERCE_DEFAULT_PRICE_USD,\n COMMERCE_MAX_OPTION_VALUES,\n COMMERCE_MAX_OPTIONS,\n COMMERCE_MAX_PRICE_USD,\n COMMERCE_MAX_VARIANTS,\n commerceSlug,\n type HostProduct,\n productCollectionIds,\n productPriceMissing,\n productSearchFields,\n type ProductType,\n type ProposedProduct,\n type SmartCollectionRules,\n unpricedProductDraft,\n type UnpricedProductDraft,\n} from '../model/commerce'\n\n/**\n * A PRODUCT ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `product` resource on the\n * core's resource-drafts seam. A plugin that sets a store up from a brief\n * asks for the writer by name and gets this plugin's rules:\n *\n * - THE DOCUMENT is the one the products card makes from an accepted AI\n * proposal (`unpricedProductDraft`): a `draft` — off the storefront, and\n * refused by every sale door — with one variant per combination of its\n * options, no photo, and the search, stock and smart-collection keys every\n * product write derives. Born live (`deletedAt: null`), as the product\n * resource stamps it, so the products table lists it. A caller may ask\n * for it to be LISTED before it has a price (`comingSoon`, AGL-3676): it\n * is then `active` and the storefront says \"Price coming soon\" where the\n * price would be — still sold by no door until every variant is priced —\n * and may hand it photos already in the site's media library.\n * - THE PRICE is the one the content states, else the default price\n * (`COMMERCE_DEFAULT_PRICE_USD`, AGL-3676) for the owner to change. Only\n * a caller that says `priceUsd: null` gets a product with none, which the\n * storefront lists as \"Price coming soon\" and no door sells.\n * - THE ROOM is the `productsPerHost` allowance, counted the way the\n * resources route and the importer count it, inside the transaction that\n * creates. THE PLAN is the `commerce` feature, and THE ROLE a member who\n * may write the site's content — refused in the resources route's words.\n * - THE CHECK is `validateProductForSave` (`validateProduct` and the product builder's fields, AGL-4205), the rule every product write is held to,\n * with a placeholder price standing in where none was stated.\n *\n * Nothing is published, priced or sold. The writer touches the one new\n * product document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const PRODUCT_DRAFT_RESOURCE = 'product'\n\n/** The longest product name the proposals and the editor keep. */\nexport const PRODUCT_DRAFT_NAME_MAX = 120\n/** The longest description a draft keeps. */\nexport const PRODUCT_DRAFT_DESCRIPTION_MAX = 5_000\n/** The most tags a draft keeps, and the longest one. */\nexport const PRODUCT_DRAFT_TAGS_MAX = 20\nexport const PRODUCT_DRAFT_TAG_MAX = 40\n/** The most categories a draft is filed under. */\nexport const PRODUCT_DRAFT_CATEGORIES_MAX = 10\n/** The longest search-listing title and description a draft keeps. */\nexport const PRODUCT_DRAFT_SEO_TITLE_MAX = 120\nexport const PRODUCT_DRAFT_SEO_DESCRIPTION_MAX = 320\n\n/** The resources route's refusal for a member who may not write the site. */\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const PRODUCT_DRAFT_ROLE_REFUSAL = siteKeyRefusal('site.edit')\n/** The resources route's refusal for a plan without the feature. */\nexport const PRODUCT_DRAFT_PLAN_REFUSAL = 'This feature is not included in your plan — see Billing'\n\n/** The resources route's refusal at the plan's allowance. */\nexport function productDraftLimitRefusal(limit: number): string {\n return `Your plan includes ${limit} ${limit === 1 ? 'product' : 'products'} — ` +\n 'upgrade in Billing for more'\n}\n\n/**\n * What a caller sends as `content`: a proposed product, as the AI products\n * job proposes one, with an optional stated price for every variant and the\n * ids of categories the site already has, and optionally photos already in\n * the site's media library and whether to list it before it has a price.\n */\nexport interface ProductDraftContent {\n name: string\n type?: ProductType\n description?: string\n tags?: string[]\n options?: Array<{ name: string; values: string[] }>\n seoTitle?: string\n seoDescription?: string\n /**\n * One price for every variant, in dollars. Absent is the default price\n * (AGL-3676); `null` leaves them unpriced on purpose.\n */\n priceUsd?: number | null\n /** Ids of the site's product categories; one the site lacks is dropped. */\n categoryIds?: string[]\n /**\n * List the product on the storefront before it has a price (AGL-3676):\n * written `active`, so the catalog shows it and its page answers, while\n * every sale door still refuses a variant with no price\n * (`variantHasPrice`) and the storefront says \"Price coming soon\" where a\n * price would be. Absent or false, an unpriced product stays a draft.\n */\n comingSoon?: boolean\n /**\n * Photos already in the site's media library, first = primary (AGL-3676):\n * the slot a guided start fills with a stock photo, or a starter, for the\n * merchant to replace with their own.\n */\n mediaUrls?: string[]\n /**\n * A SAMPLE for the merchant to replace (AGL-4065): a guided start whose\n * brief named kinds of product and no product writes its first products\n * as samples of those kinds. Stored as `sample: true`, which Products\n * shows and the storefront never reads; the merchant's save clears it.\n */\n sample?: boolean\n}\n\n/** The most photos a draft is written with. */\nexport const PRODUCT_DRAFT_MEDIA_MAX = 4\n\n/** A photo address a draft keeps: an https URL or a path on the site, never a script or a data URL. */\nconst MEDIA_URL = /^(?:https:\\/\\/[^\\s\"'<>]+|\\/[^\\s\"'<>]*)$/\n\nconst PRODUCT_TYPES: readonly ProductType[] = ['physical', 'digital', 'service']\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\nfunction strings(label: string, value: unknown, problems: string[]): string[] {\n if (value === undefined) return []\n if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {\n problems.push(`${label} are a list of words`)\n return []\n }\n return [...new Set(value.map(line).filter(Boolean))]\n}\n\n/** A draft as the writer will store it, before its slug and keys are settled. */\nexport interface ProductDraftRead {\n proposal: ProposedProduct\n /** The price for every variant (stated, else the default), or `null` for the merchant to set. */\n priceUsd: number | null\n categoryIds: string[]\n /** Listed before it has a price (`ProductDraftContent.comingSoon`). */\n comingSoon: boolean\n mediaUrls: string[]\n /** A sample to replace (`ProductDraftContent.sample`, AGL-4065); absent where it is not one. */\n sample?: true\n}\n\nexport type ProductDraftContentRead =\n | { ok: true; value: ProductDraftRead }\n | { ok: false; problems: string[] }\n\n/** The content as the writer reads it, or every problem that stops it. */\nexport function readProductDraftContent(\n content: Readonly<Record<string, unknown>>,\n): ProductDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The product needs a name')\n else if (name.length > PRODUCT_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${PRODUCT_DRAFT_NAME_MAX} characters`)\n }\n const rawType = content['type'] ?? 'physical'\n if (!(PRODUCT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push('The type is physical, digital or service')\n }\n const rawDescription = content['description']\n const description = typeof rawDescription === 'string' ? rawDescription.trim() : ''\n if (rawDescription !== undefined && typeof rawDescription !== 'string') {\n problems.push('The description is text')\n } else if (description.length > PRODUCT_DRAFT_DESCRIPTION_MAX) {\n problems.push(`The description is longer than ${PRODUCT_DRAFT_DESCRIPTION_MAX} characters`)\n }\n const tags = strings('Tags', content['tags'], problems)\n if (tags.length > PRODUCT_DRAFT_TAGS_MAX) problems.push(`A product keeps at most ${PRODUCT_DRAFT_TAGS_MAX} tags`)\n if (tags.some((tag) => tag.length > PRODUCT_DRAFT_TAG_MAX)) {\n problems.push(`A tag is longer than ${PRODUCT_DRAFT_TAG_MAX} characters`)\n }\n const categoryIds = strings('Categories', content['categoryIds'], problems)\n if (categoryIds.length > PRODUCT_DRAFT_CATEGORIES_MAX) {\n problems.push(`A product is filed under at most ${PRODUCT_DRAFT_CATEGORIES_MAX} categories`)\n }\n const seoTitle = line(content['seoTitle'])\n const seoDescription = line(content['seoDescription'])\n if (seoTitle.length > PRODUCT_DRAFT_SEO_TITLE_MAX) {\n problems.push(`The search title is longer than ${PRODUCT_DRAFT_SEO_TITLE_MAX} characters`)\n }\n if (seoDescription.length > PRODUCT_DRAFT_SEO_DESCRIPTION_MAX) {\n problems.push(`The search description is longer than ${PRODUCT_DRAFT_SEO_DESCRIPTION_MAX} characters`)\n }\n\n // Options are held here before the draft expands them: a matrix past the\n // variant ceiling is refused, never built.\n const rawOptions = content['options'] ?? []\n const options: ProposedProduct['options'] = []\n if (!Array.isArray(rawOptions)) {\n problems.push('Options are a list of a name and its values')\n } else {\n if (rawOptions.length > COMMERCE_MAX_OPTIONS) {\n problems.push(`At most ${COMMERCE_MAX_OPTIONS} options per product`)\n }\n for (const option of rawOptions) {\n const optionName = isRecord(option) ? line(option['name']) : ''\n const values = isRecord(option) ? strings(`The values of \"${optionName}\"`, option['values'], problems) : []\n if (!optionName || !values.length) {\n problems.push('Each option needs a name and at least one value')\n continue\n }\n if (values.length > COMMERCE_MAX_OPTION_VALUES) {\n problems.push(`Option \"${optionName}\" has too many values`)\n continue\n }\n options.push({ name: optionName, values })\n }\n if (new Set(options.map((option) => option.name)).size !== options.length) {\n problems.push('Each option needs its own name')\n }\n const combinations = options.reduce((count, option) => count * option.values.length, 1)\n if (combinations > COMMERCE_MAX_VARIANTS) {\n problems.push(`Those options make ${combinations} variants; a product holds at most ${COMMERCE_MAX_VARIANTS}`)\n }\n }\n\n // The stated price, else the default (AGL-3676); `null` asks for none.\n const rawPrice = content['priceUsd']\n let priceUsd: number | null = rawPrice === null ? null : COMMERCE_DEFAULT_PRICE_USD\n if (rawPrice !== undefined && rawPrice !== null) {\n if (\n typeof rawPrice !== 'number' ||\n !Number.isFinite(rawPrice) ||\n rawPrice < 0 ||\n rawPrice > COMMERCE_MAX_PRICE_USD ||\n Math.round(rawPrice * 100) !== rawPrice * 100\n ) {\n problems.push(`A stated price is dollars and cents from 0 to ${COMMERCE_MAX_PRICE_USD}`)\n } else {\n priceUsd = rawPrice\n }\n }\n const rawComingSoon = content['comingSoon']\n if (rawComingSoon !== undefined && typeof rawComingSoon !== 'boolean') {\n problems.push('Coming soon is true or false')\n }\n const rawSample = content['sample']\n if (rawSample !== undefined && typeof rawSample !== 'boolean') problems.push('Sample is true or false')\n const mediaUrls = strings('Photos', content['mediaUrls'], problems)\n if (mediaUrls.length > PRODUCT_DRAFT_MEDIA_MAX) {\n problems.push(`A product is written with at most ${PRODUCT_DRAFT_MEDIA_MAX} photos`)\n }\n if (mediaUrls.some((url) => url.length > 2_000 || !MEDIA_URL.test(url))) {\n problems.push('A photo is an https address or a path on this site')\n }\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n return {\n ok: true,\n value: {\n proposal: {\n name,\n type: rawType as ProductType,\n description,\n tags,\n options,\n seoTitle,\n seoDescription,\n },\n priceUsd,\n categoryIds,\n comingSoon: rawComingSoon === true,\n mediaUrls,\n ...(rawSample === true ? { sample: true as const } : {}),\n },\n }\n}\n\n/** The product document a read builds, under `slug`, at `nowMs`. */\nexport function productDraftDocument(\n read: ProductDraftRead,\n slug: string,\n nowMs: number,\n): UnpricedProductDraft | HostProduct {\n const draft = unpricedProductDraft(read.proposal, new Set(), nowMs)\n const priced =\n read.priceUsd === null\n ? draft\n : ({\n ...draft,\n variants: draft.variants.map((variant) => ({ ...variant, priceUsd: read.priceUsd as number })),\n } as HostProduct)\n return {\n ...priced,\n // The search keys travel with every create; recomputed for the price.\n ...productSearchFields(priced as HostProduct),\n slug,\n // Listed before it has a price (AGL-3676): the storefront says \"Price\n // coming soon\", and no sale door sells a variant without one.\n ...(read.comingSoon ? { status: 'active' as const } : {}),\n ...(read.mediaUrls.length ? { mediaUrls: read.mediaUrls } : {}),\n ...(read.categoryIds.length ? { categoryIds: read.categoryIds } : {}),\n // A sample for the merchant to replace (AGL-4065): Products marks it.\n ...(read.sample ? { sample: true } : {}),\n }\n}\n\n/** What the owner's product rule says about a draft, a placeholder price standing in for none. */\nfunction productProblem(product: UnpricedProductDraft | HostProduct): string | null {\n return validateProductForSave({\n ...product,\n variants: product.variants.map((variant) => ({\n ...variant,\n priceUsd: (variant as { priceUsd?: number }).priceUsd ?? 0,\n })),\n } as HostProduct)\n}\n\nfunction factsOf(product: Partial<HostProduct>) {\n return {\n status: product.status ?? 'draft',\n slug: product.slug ?? '',\n type: product.type ?? 'physical',\n variants: product.variants?.length ?? 0,\n priceMissing: productPriceMissing({ variants: product.variants ?? [] }),\n }\n}\n\n/** Whether content is a product this plugin would store, with what it says about it. Pure. */\nexport function checkProductDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readProductDraftContent(content)\n if (read.ok === false) return read\n const slug = commerceSlug(read.value.proposal.name) || 'product'\n const product = productDraftDocument(read.value, slug, 0)\n const problem = productProblem(product)\n return problem ? { ok: false, problems: [problem] } : { ok: true, facts: factsOf(product as HostProduct) }\n}\n\nfunction recordOf(product: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (product.data() ?? {}) as Partial<HostProduct>\n return { id: product.id, name: String(data.name ?? ''), versionId: null, facts: factsOf(data) }\n}\n\nexport function roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n return holdsSiteKey(host, uid, 'site.edit') ? null : { status: 403, error: PRODUCT_DRAFT_ROLE_REFUSAL }\n}\n\nexport function planRefusal(org: PluginDraftContext['org']): PluginDraftRefusal | null {\n return checkEntitlement(org as never, 'commerce') ? null : { status: 403, error: PRODUCT_DRAFT_PLAN_REFUSAL }\n}\n\n/** The allowance, counted as the resources route and the importer count a product create. */\nexport function roomRefusal(org: PluginDraftContext['org'], used: number): PluginDraftRefusal | null {\n const quota = checkQuota(org as never, 'productsPerHost', used)\n return quota.allowed ? null : { status: 403, error: productDraftLimitRefusal(quota.limit) }\n}\n\n/** Candidates asked of the store at once, as the console's slug ledger probes. */\nconst SLUG_PROBE = 10\n\n/**\n * The first of `base`, `base-2`, `base-3`, … that no product holds, live or\n * deleted — a soft-deleted product still answers its slug on the storefront\n * (`productSlugLedger`, AGL-3321). Asked inside the transaction.\n */\nasync function freeSlug(\n products: FirebaseFirestore.CollectionReference,\n base: string,\n read: (query: FirebaseFirestore.Query) => Promise<FirebaseFirestore.QuerySnapshot>,\n): Promise<string> {\n const candidate = (suffix: number) => (suffix < 2 ? base : `${base}-${suffix}`)\n for (let first = 1; ; first += SLUG_PROBE) {\n const batch = Array.from({ length: SLUG_PROBE }, (_, offset) => candidate(first + offset))\n const held = new Set(\n (await read(products.where('slug', 'in', batch))).docs.map((doc) => String(doc.get('slug') ?? '')),\n )\n const free = batch.find((slug) => !held.has(slug))\n if (free) return free\n }\n}\n\nexport interface ProductDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nexport function createProductDraftWriter(deps: ProductDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const early = roleRefusal(host, context.uid) ?? planRefusal(context.org)\n if (early) return early\n const used = await countLiveDocuments(hostRef.collection('products'))\n return roomRefusal(context.org, Number(used) || 0)\n },\n\n check: (content) => checkProductDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const product = await firestore().collection('hosts').doc(hostId).collection('products').doc(id).get()\n return product.exists ? recordOf(product) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readProductDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(productRef)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // Asked again under the same id: the draft it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const early = roleRefusal(host, request.uid) ?? planRefusal(request.org)\n if (early) return { ok: false, ...early }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(request.org, Number(used) || 0)\n if (room) return { ok: false, ...room }\n const base = commerceSlug(read.value.proposal.name) || 'product'\n const [slug, categories, smart] = await Promise.all([\n freeSlug(products, base, (query) => tx.get(query)),\n // A category the site does not have is dropped, not stored.\n read.value.categoryIds.length\n ? Promise.all(read.value.categoryIds.map((id) => tx.get(hostRef.collection('productCategories').doc(id))))\n : Promise.resolve([]),\n tx.get(hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')),\n ])\n const categoryIds = categories.filter((category) => category.exists).map((category) => category.id)\n const nowMs = request.now.getTime()\n const product = productDraftDocument({ ...read.value, categoryIds }, slug, nowMs)\n const problem = productProblem(product)\n if (problem) return { ok: false, status: 400, error: problem }\n const rules: SmartCollectionRules[] = smart.docs.map((doc) => ({\n id: doc.id,\n rules: doc.get('rules') ?? [],\n matchAll: doc.get('matchAll'),\n }))\n const priced = read.value.priceUsd !== null\n tx.create(productRef, {\n ...product,\n collectionIds: productCollectionIds(product as HostProduct, rules),\n // The legacy flat price every create path still writes, only where\n // there is one: an unpriced draft is not a free one.\n ...(priced ? { priceUsd: read.value.priceUsd } : {}),\n deletedAt: null,\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name: product.name,\n versionId: null,\n facts: factsOf(product as HostProduct),\n }\n })\n },\n }\n}\n\nexport const productDraftWriter = createProductDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerProductDraftWriter(): void {\n registerPluginResourceDraftWriter(PRODUCT_DRAFT_RESOURCE, productDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["validateProductForSave","checkEntitlement","checkQuota","holdsSiteKey","siteKeyRefusal","countLiveDocuments","registerPluginResourceDraftWriter","firebaseAdmin","BUNDLE_ID","COMMERCE_DEFAULT_PRICE_USD","COMMERCE_MAX_OPTION_VALUES","COMMERCE_MAX_OPTIONS","COMMERCE_MAX_PRICE_USD","COMMERCE_MAX_VARIANTS","commerceSlug","productCollectionIds","productPriceMissing","productSearchFields","unpricedProductDraft","PRODUCT_DRAFT_RESOURCE","PRODUCT_DRAFT_NAME_MAX","PRODUCT_DRAFT_DESCRIPTION_MAX","PRODUCT_DRAFT_TAGS_MAX","PRODUCT_DRAFT_TAG_MAX","PRODUCT_DRAFT_CATEGORIES_MAX","PRODUCT_DRAFT_SEO_TITLE_MAX","PRODUCT_DRAFT_SEO_DESCRIPTION_MAX","PRODUCT_DRAFT_ROLE_REFUSAL","PRODUCT_DRAFT_PLAN_REFUSAL","productDraftLimitRefusal","limit","PRODUCT_DRAFT_MEDIA_MAX","MEDIA_URL","PRODUCT_TYPES","isRecord","value","Array","isArray","line","replace","trim","strings","label","problems","undefined","some","entry","push","Set","map","filter","Boolean","readProductDraftContent","content","name","length","rawType","includes","rawDescription","description","tags","tag","categoryIds","seoTitle","seoDescription","rawOptions","options","option","optionName","values","size","combinations","reduce","count","rawPrice","priceUsd","Number","isFinite","Math","round","rawComingSoon","rawSample","mediaUrls","url","test","ok","proposal","type","comingSoon","sample","productDraftDocument","read","slug","nowMs","draft","priced","variants","variant","status","productProblem","product","factsOf","priceMissing","checkProductDraftContent","problem","facts","recordOf","data","id","String","versionId","roleRefusal","host","uid","error","planRefusal","org","roomRefusal","used","quota","allowed","SLUG_PROBE","freeSlug","products","base","candidate","suffix","first","batch","from","_","offset","held","where","docs","doc","get","free","find","has","createProductDraftWriter","deps","firestore","app","refusal","context","hostRef","collection","hostId","exists","early","check","write","request","asked","db","productRef","runTransaction","tx","existing","Promise","all","replayed","aggregate","room","categories","smart","query","resolve","category","now","getTime","rules","matchAll","create","collectionIds","deletedAt","createdAt","updatedAt","createdBy","productDraftWriter","registerProductDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SAASC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AACvF,SAASC,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,iCAAiC,QAO5B,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,oBAAoB,EACpBC,sBAAsB,EACtBC,qBAAqB,EACrBC,YAAY,EAEZC,oBAAoB,EACpBC,mBAAmB,EACnBC,mBAAmB,EAInBC,oBAAoB,QAEf,uBAAmB;AAoC1B,uDAAuD,GACvD,OAAO,MAAMC,yBAAyB,UAAS;AAE/C,gEAAgE,GAChE,OAAO,MAAMC,yBAAyB,IAAG;AACzC,2CAA2C,GAC3C,OAAO,MAAMC,gCAAgC,KAAK;AAClD,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,GAAE;AACxC,OAAO,MAAMC,wBAAwB,GAAE;AACvC,gDAAgD,GAChD,OAAO,MAAMC,+BAA+B,GAAE;AAC9C,oEAAoE,GACpE,OAAO,MAAMC,8BAA8B,IAAG;AAC9C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@@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import * as Aglyn from "@aglyn/aglyn/server";
17
+ */ import { validateProductForSave } from "../model/product-card-rules.js";
18
+ import * as Aglyn from "@aglyn/aglyn/server";
18
19
  import { countLiveDocuments } from "@aglyn/aglyn/app-utils/live-document-count";
19
20
  import { firebaseAdmin, getOrgForHost, logHostActivity } from "@aglyn/tenant-data-admin";
20
21
  import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
21
- import { commerceSlug, liftLegacyProduct, validateProduct } from "../model/commerce.js";
22
+ import { commerceSlug, liftLegacyProduct } from "../model/commerce.js";
22
23
  import { derivedKeys, readSmartCollections } from "../transfer/products.server.js";
23
24
  import { withoutUndefined } from "../transfer/server-common.js";
24
25
  /** The fields an update compares to tell a change from a repeat. */ const COMPARED_KEYS = [
@@ -142,7 +143,7 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
142
143
  ...source.tags
143
144
  ]
144
145
  } : {}) : {});
145
- const invalid = validateProduct(next);
146
+ const invalid = validateProductForSave(next);
146
147
  if (invalid) throw new WriteRefusal({
147
148
  outcome: 'invalid',
148
149
  message: invalid
@@ -216,7 +217,7 @@ export async function upsertSourcedProduct(write, firestore = firebaseAdmin.app(
216
217
  })),
217
218
  oversellPolicy: 'deny'
218
219
  });
219
- const invalid = validateProduct(product);
220
+ const invalid = validateProductForSave(product);
220
221
  if (invalid) return {
221
222
  outcome: 'invalid',
222
223
  message: invalid
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product-writer.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport type {\n PluginProductWriter,\n SourcedProductWrite,\n SourcedProductWriteOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-product-writer'\nimport type { TransferResourceContext } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport {\n commerceSlug,\n liftLegacyProduct,\n validateProduct,\n type HostProduct,\n type ProductVariant,\n} from '../model/commerce'\nimport { derivedKeys, readSmartCollections } from '../transfer/products.server'\nimport { withoutUndefined } from '../transfer/server-common'\n\n/**\n * Products another plugin brings from a source of its own — a print-on-demand\n * service, a supplier — written through the store's own rules (AGL-3641),\n * behind core's `core.product-writer`.\n *\n * The same rules the console's product route and the file import keep: a\n * create is counted against the plan's product allowance in the transaction\n * that makes it, a new product takes an address no other product holds (a\n * deleted one's included), every write carries the search, stock and\n * smart-collection keys every writer derives, and the site's activity says\n * what happened.\n *\n * A configuration the source cannot make now is sold out (`inventory: 0`);\n * one it can is untracked (`inventory: null`), because a made-to-order item\n * has no count to run down.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\n/** The fields an update compares to tell a change from a repeat. */\nconst COMPARED_KEYS = ['name', 'description', 'mediaUrls', 'tags', 'options', 'variants'] as const\n\n/** How many suffixed addresses a new product tries before it gives up. */\nconst SLUG_TRIES = 30\nconst SLUGS_PER_QUERY = 30\n\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\nfunction priceUsd(minor: number): number {\n return Math.round(Math.max(0, Number(minor) || 0)) / 100\n}\n\n/** The variant a sourced configuration becomes, on top of the one it was. */\nfunction variantFrom(\n source: SourcedProductWrite['product']['variants'][number],\n existing: ProductVariant | undefined,\n options: { prices: boolean; content: boolean },\n): ProductVariant {\n const price = existing && !options.prices ? existing.priceUsd : priceUsd(source.priceMinor)\n const next: ProductVariant = {\n ...(existing ?? {}),\n id: existing?.id ?? newVariantId(),\n options: { ...source.options },\n priceUsd: price,\n inventory: source.available ? null : 0,\n }\n delete next.inventoryByLocation\n if (source.sku) next.sku = source.sku.slice(0, 120)\n else delete next.sku\n if (Number.isFinite(source.weightGrams) && Number(source.weightGrams) > 0) {\n next.weightGrams = Math.round(Number(source.weightGrams))\n }\n if (source.imageUrl && (options.content || !existing?.imageUrl)) next.imageUrl = source.imageUrl\n // A price brought below a compare-at that no longer exceeds it would be\n // refused: the strike-through goes, the price stays.\n if (next.compareAtPriceUsd != null && Number(next.compareAtPriceUsd) <= next.priceUsd) {\n delete next.compareAtPriceUsd\n }\n return next\n}\n\nasync function freeSlug(products: FirebaseFirestore.CollectionReference, name: string): Promise<string | null> {\n const base = commerceSlug(name).slice(0, 80) || 'product'\n const candidates = [base, ...Array.from({ length: SLUG_TRIES - 1 }, (_, index) => `${base}-${index + 2}`)]\n const taken = new Set<string>()\n for (let at = 0; at < candidates.length; at += SLUGS_PER_QUERY) {\n const slice = candidates.slice(at, at + SLUGS_PER_QUERY)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n return candidates.find((candidate) => !taken.has(candidate)) ?? null\n}\n\nclass WriteRefusal extends Error {\n constructor(readonly outcome: Exclude<SourcedProductWriteOutcome, { productId: string }>) {\n super(outcome.outcome)\n }\n}\n\nexport async function upsertSourcedProduct(\n write: SourcedProductWrite,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<SourcedProductWriteOutcome> {\n const { hostId, product: source } = write\n if (!isDocumentId(hostId)) return { outcome: 'no_store' }\n const owner = await getOrgForHost(hostId)\n if (!owner || !Aglyn.checkEntitlement(owner.org as never, 'commerce')) return { outcome: 'no_store' }\n const org = owner.org\n const products = firestore.collection('hosts').doc(hostId).collection('products')\n const smart = await readSmartCollections(firestore, { hostId } as TransferResourceContext)\n const { Timestamp } = firebaseAdmin.firestore\n const actor = { uid: write.actorUid ?? 'import', email: null }\n const name = source.name.trim().slice(0, 200)\n const description = (source.description ?? '').trim().slice(0, 20_000)\n\n const mapping = (product: HostProduct) =>\n source.variants.map((variant, index) => ({ key: variant.key, variantId: product.variants[index].id }))\n\n try {\n // An update, when the product is still there.\n if (write.productId && isDocumentId(write.productId)) {\n const ref = products.doc(write.productId)\n const updated = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || (data?.['deletedAt'] !== null && data?.['deletedAt'] !== undefined)) return null\n const current = liftLegacyProduct(data as ProductDoc)\n const flags = { prices: write.prices === true, content: write.content === true }\n const byId = new Map(current.variants.map((variant) => [variant.id, variant]))\n const next: HostProduct = {\n ...current,\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) =>\n variantFrom(variant, variant.variantId ? byId.get(variant.variantId) : undefined, flags),\n ),\n ...(flags.content\n ? {\n name,\n description,\n mediaUrls: [...source.mediaUrls],\n ...(source.tags ? { tags: [...source.tags] } : {}),\n }\n : {}),\n }\n const invalid = validateProduct(next)\n if (invalid) throw new WriteRefusal({ outcome: 'invalid', message: invalid })\n const changed = COMPARED_KEYS.some(\n (key) =>\n JSON.stringify((next as unknown as Record<string, unknown>)[key] ?? null) !==\n JSON.stringify((current as unknown as Record<string, unknown>)[key] ?? null),\n )\n if (changed) {\n tx.update(\n ref,\n withoutUndefined({\n ...Object.fromEntries(COMPARED_KEYS.map((key) => [key, (next as unknown as Record<string, unknown>)[key]])),\n ...derivedKeys(next, smart),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n }) as FirebaseFirestore.UpdateData<FirebaseFirestore.DocumentData>,\n )\n }\n return { next, changed }\n })\n if (updated) {\n if (updated.changed) {\n await logHostActivity(hostId, actor, 'Updated product from its source', {\n type: 'content',\n id: write.productId,\n name: updated.next.name,\n })\n }\n return {\n outcome: updated.changed ? 'updated' : 'unchanged',\n productId: write.productId,\n variants: mapping(updated.next),\n }\n }\n }\n\n if (write.productId && write.recreate === false) return { outcome: 'missing' }\n\n // A new product.\n const slug = await freeSlug(products, name)\n if (!slug) return { outcome: 'invalid', message: 'Every address for a product of this name is taken. Rename one first.' }\n const productId = Aglyn.createResourceUid()\n const product: HostProduct = {\n name,\n slug,\n description,\n type: 'physical',\n status: write.status === 'active' ? 'active' : 'draft',\n mediaUrls: [...source.mediaUrls],\n ...(source.tags?.length ? { tags: [...source.tags] } : {}),\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) => variantFrom(variant, undefined, { prices: true, content: true })),\n oversellPolicy: 'deny',\n }\n const invalid = validateProduct(product)\n if (invalid) return { outcome: 'invalid', message: invalid }\n const now = Date.now()\n const ref = products.doc(productId)\n await firestore.runTransaction(async (tx) => {\n // Live products only: a deleted one frees its slot, an archived one keeps it (AGL-3918).\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) throw new WriteRefusal({ outcome: 'plan_limit', limit: Number(quota.limit) || 0 })\n tx.create(\n ref,\n withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: write.actorUid ?? null,\n }),\n )\n })\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: productId, name: product.name })\n return { outcome: 'created', productId, variants: mapping(product) }\n } catch (error) {\n if (error instanceof WriteRefusal) return error.outcome\n throw error\n }\n}\n\nexport const commerceProductWriter: PluginProductWriter = {\n upsertSourced: (write) => upsertSourcedProduct(write),\n}\n"],"names":["Aglyn","countLiveDocuments","firebaseAdmin","getOrgForHost","logHostActivity","isDocumentId","commerceSlug","liftLegacyProduct","validateProduct","derivedKeys","readSmartCollections","withoutUndefined","COMPARED_KEYS","SLUG_TRIES","SLUGS_PER_QUERY","newVariantId","createResourceUid","slice","priceUsd","minor","Math","round","max","Number","variantFrom","source","existing","options","price","prices","priceMinor","next","id","inventory","available","inventoryByLocation","sku","isFinite","weightGrams","imageUrl","content","compareAtPriceUsd","freeSlug","products","name","candidates","base","Array","from","length","_","index","taken","Set","at","doc","where","get","docs","add","String","find","candidate","has","WriteRefusal","Error","outcome","upsertSourcedProduct","write","firestore","app","hostId","product","owner","checkEntitlement","org","collection","smart","Timestamp","actor","uid","actorUid","email","trim","description","mapping","variants","map","variant","key","variantId","productId","ref","updated","runTransaction","tx","snapshot","data","exists","undefined","current","flags","byId","Map","option","values","mediaUrls","tags","invalid","message","changed","some","JSON","stringify","update","Object","fromEntries","updatedAtMs","Date","now","updatedAt","type","recreate","slug","status","oversellPolicy","used","aggregate","quota","checkQuota","allowed","limit","create","createdAtMs","deletedAt","createdAt","createdBy","error","commerceProductWriter","upsertSourced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,kBAAkB,QAAQ,6CAA4C;AAO/E,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,QAAQ,2BAA0B;AACxF,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SACEC,YAAY,EACZC,iBAAiB,EACjBC,eAAe,QAGV,uBAAmB;AAC1B,SAASC,WAAW,EAAEC,oBAAoB,QAAQ,iCAA6B;AAC/E,SAASC,gBAAgB,QAAQ,+BAA2B;AAqB5D,kEAAkE,GAClE,MAAMC,gBAAgB;IAAC;IAAQ;IAAe;IAAa;IAAQ;IAAW;CAAW;AAEzF,wEAAwE,GACxE,MAAMC,aAAa;AACnB,MAAMC,kB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AAK;YACzGqF,gBAAgB;;QAElB,MAAMjB,UAAUpG,gBAAgBgE;QAChC,IAAIoC,SAAS,OAAO;YAAE1C,SAAS;YAAW2C,SAASD;QAAQ;QAC3D,MAAMW,MAAMD,KAAKC,GAAG;QACpB,MAAM3B,MAAMjD,SAASY,GAAG,CAACoC;QACzB,MAAMtB,UAAUyB,cAAc,CAAC,OAAOC;gBAerB3B;YAdf,yFAAyF;YACzF,MAAM0D,OAAO,MAAM7H,mBAAmB0C,UAAU,CAACoF,YAAchC,GAAGtC,GAAG,CAACsE;YACtE,MAAMC,QAAQhI,MAAMiI,UAAU,CAACtD,KAAc,mBAAmBpD,OAAOuG,SAAS;YAChF,IAAI,CAACE,MAAME,OAAO,EAAE,MAAM,IAAIlE,aAAa;gBAAEE,SAAS;gBAAciE,OAAO5G,OAAOyG,MAAMG,KAAK,KAAK;YAAE;YACpGpC,GAAGqC,MAAM,CACPxC,KACAjF,iBAAiB,aACZ6D,SACA/D,YAAY+D,SAASK;gBACxBwD,aAAad;gBACbF,aAAaE;gBACbe,WAAW;gBACXC,WAAWzD,UAAUyC,GAAG;gBACxBC,WAAW1C,UAAUyC,GAAG;gBACxBiB,SAAS,GAAEpE,kBAAAA,MAAMa,QAAQ,YAAdb,kBAAkB;;QAGnC;QACA,MAAMhE,gBAAgBmE,QAAQQ,OAAO,oBAAoB;YAAE0C,MAAM;YAAWzF,IAAI2D;YAAW/C,MAAM4B,QAAQ5B,IAAI;QAAC;QAC9G,OAAO;YAAEsB,SAAS;YAAWyB;YAAWL,UAAUD,QAAQb;QAAS;IACrE,EAAE,OAAOiE,OAAO;QACd,IAAIA,iBAAiBzE,cAAc,OAAOyE,MAAMvE,OAAO;QACvD,MAAMuE;IACR;AACF;AAEA,OAAO,MAAMC,wBAA6C;IACxDC,eAAe,CAACvE,QAAUD,qBAAqBC;AACjD,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product-writer.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateProductForSave } from '../model/product-card-rules'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport type {\n PluginProductWriter,\n SourcedProductWrite,\n SourcedProductWriteOutcome,\n} from '@aglyn/aglyn/plugin-manager/plugin-product-writer'\nimport type { TransferResourceContext } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport {\n commerceSlug,\n liftLegacyProduct,\n type HostProduct,\n type ProductVariant,\n} from '../model/commerce'\nimport { derivedKeys, readSmartCollections } from '../transfer/products.server'\nimport { withoutUndefined } from '../transfer/server-common'\n\n/**\n * Products another plugin brings from a source of its own — a print-on-demand\n * service, a supplier — written through the store's own rules (AGL-3641),\n * behind core's `core.product-writer`.\n *\n * The same rules the console's product route and the file import keep: a\n * create is counted against the plan's product allowance in the transaction\n * that makes it, a new product takes an address no other product holds (a\n * deleted one's included), every write carries the search, stock and\n * smart-collection keys every writer derives, and the site's activity says\n * what happened.\n *\n * A configuration the source cannot make now is sold out (`inventory: 0`);\n * one it can is untracked (`inventory: null`), because a made-to-order item\n * has no count to run down.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\n/** The fields an update compares to tell a change from a repeat. */\nconst COMPARED_KEYS = ['name', 'description', 'mediaUrls', 'tags', 'options', 'variants'] as const\n\n/** How many suffixed addresses a new product tries before it gives up. */\nconst SLUG_TRIES = 30\nconst SLUGS_PER_QUERY = 30\n\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\nfunction priceUsd(minor: number): number {\n return Math.round(Math.max(0, Number(minor) || 0)) / 100\n}\n\n/** The variant a sourced configuration becomes, on top of the one it was. */\nfunction variantFrom(\n source: SourcedProductWrite['product']['variants'][number],\n existing: ProductVariant | undefined,\n options: { prices: boolean; content: boolean },\n): ProductVariant {\n const price = existing && !options.prices ? existing.priceUsd : priceUsd(source.priceMinor)\n const next: ProductVariant = {\n ...(existing ?? {}),\n id: existing?.id ?? newVariantId(),\n options: { ...source.options },\n priceUsd: price,\n inventory: source.available ? null : 0,\n }\n delete next.inventoryByLocation\n if (source.sku) next.sku = source.sku.slice(0, 120)\n else delete next.sku\n if (Number.isFinite(source.weightGrams) && Number(source.weightGrams) > 0) {\n next.weightGrams = Math.round(Number(source.weightGrams))\n }\n if (source.imageUrl && (options.content || !existing?.imageUrl)) next.imageUrl = source.imageUrl\n // A price brought below a compare-at that no longer exceeds it would be\n // refused: the strike-through goes, the price stays.\n if (next.compareAtPriceUsd != null && Number(next.compareAtPriceUsd) <= next.priceUsd) {\n delete next.compareAtPriceUsd\n }\n return next\n}\n\nasync function freeSlug(products: FirebaseFirestore.CollectionReference, name: string): Promise<string | null> {\n const base = commerceSlug(name).slice(0, 80) || 'product'\n const candidates = [base, ...Array.from({ length: SLUG_TRIES - 1 }, (_, index) => `${base}-${index + 2}`)]\n const taken = new Set<string>()\n for (let at = 0; at < candidates.length; at += SLUGS_PER_QUERY) {\n const slice = candidates.slice(at, at + SLUGS_PER_QUERY)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n return candidates.find((candidate) => !taken.has(candidate)) ?? null\n}\n\nclass WriteRefusal extends Error {\n constructor(readonly outcome: Exclude<SourcedProductWriteOutcome, { productId: string }>) {\n super(outcome.outcome)\n }\n}\n\nexport async function upsertSourcedProduct(\n write: SourcedProductWrite,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<SourcedProductWriteOutcome> {\n const { hostId, product: source } = write\n if (!isDocumentId(hostId)) return { outcome: 'no_store' }\n const owner = await getOrgForHost(hostId)\n if (!owner || !Aglyn.checkEntitlement(owner.org as never, 'commerce')) return { outcome: 'no_store' }\n const org = owner.org\n const products = firestore.collection('hosts').doc(hostId).collection('products')\n const smart = await readSmartCollections(firestore, { hostId } as TransferResourceContext)\n const { Timestamp } = firebaseAdmin.firestore\n const actor = { uid: write.actorUid ?? 'import', email: null }\n const name = source.name.trim().slice(0, 200)\n const description = (source.description ?? '').trim().slice(0, 20_000)\n\n const mapping = (product: HostProduct) =>\n source.variants.map((variant, index) => ({ key: variant.key, variantId: product.variants[index].id }))\n\n try {\n // An update, when the product is still there.\n if (write.productId && isDocumentId(write.productId)) {\n const ref = products.doc(write.productId)\n const updated = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || (data?.['deletedAt'] !== null && data?.['deletedAt'] !== undefined)) return null\n const current = liftLegacyProduct(data as ProductDoc)\n const flags = { prices: write.prices === true, content: write.content === true }\n const byId = new Map(current.variants.map((variant) => [variant.id, variant]))\n const next: HostProduct = {\n ...current,\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) =>\n variantFrom(variant, variant.variantId ? byId.get(variant.variantId) : undefined, flags),\n ),\n ...(flags.content\n ? {\n name,\n description,\n mediaUrls: [...source.mediaUrls],\n ...(source.tags ? { tags: [...source.tags] } : {}),\n }\n : {}),\n }\n const invalid = validateProductForSave(next)\n if (invalid) throw new WriteRefusal({ outcome: 'invalid', message: invalid })\n const changed = COMPARED_KEYS.some(\n (key) =>\n JSON.stringify((next as unknown as Record<string, unknown>)[key] ?? null) !==\n JSON.stringify((current as unknown as Record<string, unknown>)[key] ?? null),\n )\n if (changed) {\n tx.update(\n ref,\n withoutUndefined({\n ...Object.fromEntries(COMPARED_KEYS.map((key) => [key, (next as unknown as Record<string, unknown>)[key]])),\n ...derivedKeys(next, smart),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n }) as FirebaseFirestore.UpdateData<FirebaseFirestore.DocumentData>,\n )\n }\n return { next, changed }\n })\n if (updated) {\n if (updated.changed) {\n await logHostActivity(hostId, actor, 'Updated product from its source', {\n type: 'content',\n id: write.productId,\n name: updated.next.name,\n })\n }\n return {\n outcome: updated.changed ? 'updated' : 'unchanged',\n productId: write.productId,\n variants: mapping(updated.next),\n }\n }\n }\n\n if (write.productId && write.recreate === false) return { outcome: 'missing' }\n\n // A new product.\n const slug = await freeSlug(products, name)\n if (!slug) return { outcome: 'invalid', message: 'Every address for a product of this name is taken. Rename one first.' }\n const productId = Aglyn.createResourceUid()\n const product: HostProduct = {\n name,\n slug,\n description,\n type: 'physical',\n status: write.status === 'active' ? 'active' : 'draft',\n mediaUrls: [...source.mediaUrls],\n ...(source.tags?.length ? { tags: [...source.tags] } : {}),\n options: source.options.map((option) => ({ name: option.name, values: [...option.values] })),\n variants: source.variants.map((variant) => variantFrom(variant, undefined, { prices: true, content: true })),\n oversellPolicy: 'deny',\n }\n const invalid = validateProductForSave(product)\n if (invalid) return { outcome: 'invalid', message: invalid }\n const now = Date.now()\n const ref = products.doc(productId)\n await firestore.runTransaction(async (tx) => {\n // Live products only: a deleted one frees its slot, an archived one keeps it (AGL-3918).\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) throw new WriteRefusal({ outcome: 'plan_limit', limit: Number(quota.limit) || 0 })\n tx.create(\n ref,\n withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: write.actorUid ?? null,\n }),\n )\n })\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: productId, name: product.name })\n return { outcome: 'created', productId, variants: mapping(product) }\n } catch (error) {\n if (error instanceof WriteRefusal) return error.outcome\n throw error\n }\n}\n\nexport const commerceProductWriter: PluginProductWriter = {\n upsertSourced: (write) => upsertSourcedProduct(write),\n}\n"],"names":["validateProductForSave","Aglyn","countLiveDocuments","firebaseAdmin","getOrgForHost","logHostActivity","isDocumentId","commerceSlug","liftLegacyProduct","derivedKeys","readSmartCollections","withoutUndefined","COMPARED_KEYS","SLUG_TRIES","SLUGS_PER_QUERY","newVariantId","createResourceUid","slice","priceUsd","minor","Math","round","max","Number","variantFrom","source","existing","options","price","prices","priceMinor","next","id","inventory","available","inventoryByLocation","sku","isFinite","weightGrams","imageUrl","content","compareAtPriceUsd","freeSlug","products","name","candidates","base","Array","from","length","_","index","taken","Set","at","doc","where","get","docs","add","String","find","candidate","has","WriteRefusal","Error","outcome","upsertSourcedProduct","write","firestore","app","hostId","product","owner","checkEntitlement","org","collection","smart","Timestamp","actor","uid","actorUid","email","trim","description","mapping","variants","map","variant","key","variantId","productId","ref","updated","runTransaction","tx","snapshot","data","exists","undefined","current","flags","byId","Map","option","values","mediaUrls","tags","invalid","message","changed","some","JSON","stringify","update","Object","fromEntries","updatedAtMs","Date","now","updatedAt","type","recreate","slug","status","oversellPolicy","used","aggregate","quota","checkQuota","allowed","limit","create","createdAtMs","deletedAt","createdAt","createdBy","error","commerceProductWriter","upsertSourced"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,kBAAkB,QAAQ,6CAA4C;AAO/E,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,QAAQ,2BAA0B;AACxF,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SACEC,YAAY,EACZC,iBAAiB,QAGZ,uBAAmB;AAC1B,SAASC,WAAW,EAAEC,oBAAo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AAO;QACvD,MAAMuE;IACR;AACF;AAEA,OAAO,MAAMC,wBAA6C;IACxDC,eAAe,CAACvE,QAAUD,qBAAqBC;AACjD,EAAC"}
@@ -49,7 +49,14 @@ export interface PublicProductDetail {
49
49
  * AGL-4043): the page offers an optional date. Absent when it does not.
50
50
  */
51
51
  asksUseDate?: true;
52
+ /** A short line on the variant's picture card (AGL-4205). */
53
+ note?: string;
52
54
  }>;
55
+ /**
56
+ * The page offers "Get a free mockup" (AGL-4205): the request form the site
57
+ * placed in the product block opens with the shopper's picks.
58
+ */
59
+ mockupRequests?: true;
53
60
  /**
54
61
  * The store's time zone, sent only when a variant asks for a use day, so
55
62
  * the page offers no day that has passed on the store's calendar.
@@ -84,6 +91,10 @@ export interface PublicModifierGroup {
84
91
  priceCents: number;
85
92
  /** What the choice adds on a variant priced differently, by variant id. */
86
93
  priceCentsByVariant?: Record<string, number>;
94
+ /** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */
95
+ imageUrl?: string;
96
+ note?: string;
97
+ includes?: string[];
87
98
  }>;
88
99
  }
89
100
  /** The website add-on groups of a product, in the page's shape (AGL-4100). */
@@ -23,13 +23,24 @@ import { readStoreDay } from "./store-day.js";
23
23
  name: group.name,
24
24
  min: group.min,
25
25
  max: group.max,
26
- options: group.options.map((option)=>_extends({
26
+ options: group.options.map((option)=>{
27
+ var _option_includes;
28
+ return _extends({
27
29
  id: option.id,
28
30
  name: option.name,
29
31
  priceCents: option.priceCents
30
32
  }, option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length ? {
31
33
  priceCentsByVariant: _extends({}, option.priceCentsByVariant)
32
- } : {}))
34
+ } : {}, typeof option.imageUrl === 'string' && option.imageUrl ? {
35
+ imageUrl: option.imageUrl
36
+ } : {}, typeof option.note === 'string' && option.note.trim() ? {
37
+ note: option.note.trim()
38
+ } : {}, CommerceModel.modifierOptionIsCombo(option) ? {
39
+ includes: [
40
+ ...(_option_includes = option.includes) != null ? _option_includes : []
41
+ ]
42
+ } : {});
43
+ })
33
44
  }));
34
45
  }
35
46
  /**
@@ -76,8 +87,12 @@ import { readStoreDay } from "./store-day.js";
76
87
  sku: variant.sku
77
88
  } : {}, CommerceModel.productAsksUseDate(product, variant.id) ? {
78
89
  asksUseDate: true
90
+ } : {}, typeof variant.note === 'string' && variant.note.trim() ? {
91
+ note: variant.note.trim()
79
92
  } : {}))
80
- }, asksUseDate ? {
93
+ }, product.mockupRequests === true ? {
94
+ mockupRequests: true
95
+ } : {}, asksUseDate ? {
81
96
  useDayTimeZone: options.timeZone || 'UTC'
82
97
  } : {}, ((_product_tags = product.tags) == null ? void 0 : _product_tags.length) ? {
83
98
  tags: product.tags
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readStoreDay } from './store-day'\n\nexport interface PublicProductDetail {\n id: string\n name: string\n slug: string\n description?: string\n type: CommerceModel.ProductType\n mediaUrls: string[]\n options: CommerceModel.ProductOption[]\n variants: Array<{\n id: string\n options?: Record<string, string>\n /**\n * `null` for a variant listed before it has a price (AGL-3676): the page\n * says \"Price coming soon\" and offers nothing to buy, as no sale door\n * would sell it.\n */\n priceUsd: number | null\n compareAtPriceUsd?: number\n soldOut: boolean\n imageUrl?: string\n /**\n * Merchant's stock-keeping unit (AGL-686). Carried into the public DTO\n * so the server can put `sku` on the Product structured data — Google\n * Merchant treats it as required for a product offer, and without it a\n * listing is simply ineligible for rich results rather than warned about.\n * It is already public information: it prints on receipts and invoices.\n */\n sku?: string\n /**\n * The buyer may choose the day they will use it (a pass bought ahead,\n * AGL-4043): the page offers an optional date. Absent when it does not.\n */\n asksUseDate?: true\n }>\n /**\n * The store's time zone, sent only when a variant asks for a use day, so\n * the page offers no day that has passed on the store's calendar.\n */\n useDayTimeZone?: string\n tags?: string[]\n /** Recurring billing (AGL-303) so the PDP frames the price. */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /** Buyer may choose one-time OR subscribe (AGL-545). */\n subscriptionOptional?: boolean\n /**\n * The add-ons the page offers (AGL-4100): ONLY the groups switched to\n * \"Show on the website\". A register-only group never leaves the server, so\n * a shop's in-person choices and prices are not published. Absent: none.\n * Display-only like the prices above; every sale door prices them again\n * from the product.\n */\n modifierGroups?: PublicModifierGroup[]\n}\n\n/** An add-on group as the product page shows it (AGL-4100). */\nexport interface PublicModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: Array<{\n id: string\n name: string\n priceCents: number\n /** What the choice adds on a variant priced differently, by variant id. */\n priceCentsByVariant?: Record<string, number>\n }>\n}\n\n/** The website add-on groups of a product, in the page's shape (AGL-4100). */\nexport function publicModifierGroups(\n product: { modifierGroups?: unknown },\n): PublicModifierGroup[] {\n return CommerceModel.websiteModifierGroups(product).map((group) => ({\n id: group.id,\n name: group.name,\n min: group.min,\n max: group.max,\n options: group.options.map((option) => ({\n id: option.id,\n name: option.name,\n priceCents: option.priceCents,\n ...(option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length\n ? { priceCentsByVariant: { ...option.priceCentsByVariant } }\n : {}),\n })),\n }))\n}\n\n/**\n * Map a lifted product onto the public PDP DTO.\n *\n * Extracted (AGL-659) so the site-page resolver can put the SAME payload\n * into page props as the API returns — the PDP block used to fetch this in\n * an effect, which meant the server rendered a skeleton and crawlers saw a\n * product page with no product in it. One definition keeps the server-\n * rendered and client-fetched shapes from drifting.\n *\n * Display-only by design: stock is a `soldOut` boolean rather than a raw\n * count, and the charge still prices server-side.\n */\nexport function toPublicProductDetail(\n id: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n options: { timeZone?: string | null } = {},\n): PublicProductDetail {\n const asksUseDate = productAsksUseDateAnywhere(product)\n const modifierGroups = publicModifierGroups(product)\n return {\n id,\n name: product.name,\n slug: product.slug,\n ...(product.description ? { description: product.description } : {}),\n type: product.type,\n mediaUrls:\n product.mediaUrls ?? (product.imageUrl ? [product.imageUrl] : []),\n options: product.options ?? [],\n variants: product.variants.map((variant) => ({\n id: variant.id,\n ...(variant.options ? { options: variant.options } : {}),\n priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null,\n ...(variant.compareAtPriceUsd\n ? { compareAtPriceUsd: variant.compareAtPriceUsd }\n : {}),\n soldOut:\n variant.inventory != null &&\n Number(variant.inventory) <= 0 &&\n product.oversellPolicy !== 'backorder',\n ...(variant.imageUrl ? { imageUrl: variant.imageUrl } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n ...(CommerceModel.productAsksUseDate(product, variant.id) ? { asksUseDate: true as const } : {}),\n })),\n ...(asksUseDate ? { useDayTimeZone: options.timeZone || 'UTC' } : {}),\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.subscription ? { subscription: product.subscription } : {}),\n ...(product.subscription && product.subscriptionOptional\n ? { subscriptionOptional: true }\n : {}),\n ...(modifierGroups.length ? { modifierGroups } : {}),\n }\n}\n\n/** Whether any variant of a product asks the buyer for a use day (AGL-4043). */\nexport function productAsksUseDateAnywhere(\n product: Pick<ReturnType<typeof CommerceModel.liftLegacyProduct>, 'variants' | 'checkIn'>,\n): boolean {\n return product.variants.some((variant) => CommerceModel.productAsksUseDate(product, variant.id))\n}\n\n/**\n * Public product detail by slug (AGL-292): everything the PDP block\n * needs — variants with per-option prices and stock booleans, never raw\n * counts. Display-only; the charge still prices server-side.\n */\nexport const productHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n const slug = String(req.query.slug ?? '')\n if (!hostId || !slug) {\n return res.status(400).json({ error: 'Missing hostId or slug' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .where('slug', '==', slug)\n .limit(1)\n .get()\n const docSnapshot = snapshot.docs[0]\n const raw = docSnapshot?.data() as any\n // A product sold in person only (AGL-4060) has no page online: the same\n // 404 as a draft, so its address says nothing about it.\n if (!CommerceModel.productListedOnline(raw)) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n // The store's calendar, only for a product that asks for a use day.\n const timeZone = productAsksUseDateAnywhere(product)\n ? (await readStoreDay(firestore.collection('hosts').doc(hostId))).timeZone\n : null\n const detail = toPublicProductDetail(docSnapshot.id, product, { timeZone })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json({ product: detail })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Product unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","readStoreDay","publicModifierGroups","product","websiteModifierGroups","map","group","id","name","min","max","options","option","priceCents","priceCentsByVariant","Object","keys","length","toPublicProductDetail","asksUseDate","productAsksUseDateAnywhere","modifierGroups","slug","description","type","mediaUrls","imageUrl","variants","variant","priceUsd","variantHasPrice","compareAtPriceUsd","soldOut","inventory","Number","oversellPolicy","sku","productAsksUseDate","useDayTimeZone","timeZone","tags","subscription","subscriptionOptional","some","productHandler","req","res","hostId","String","query","status","json","error","firestore","app","snapshot","collection","doc","where","limit","get","docSnapshot","docs","raw","data","productListedOnline","liftLegacyProduct","detail","setHeader","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,YAAYA,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BA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ources":["../../../../../../../libs/plugins/commerce/src/lib/server/product.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readStoreDay } from './store-day'\n\nexport interface PublicProductDetail {\n id: string\n name: string\n slug: string\n description?: string\n type: CommerceModel.ProductType\n mediaUrls: string[]\n options: CommerceModel.ProductOption[]\n variants: Array<{\n id: string\n options?: Record<string, string>\n /**\n * `null` for a variant listed before it has a price (AGL-3676): the page\n * says \"Price coming soon\" and offers nothing to buy, as no sale door\n * would sell it.\n */\n priceUsd: number | null\n compareAtPriceUsd?: number\n soldOut: boolean\n imageUrl?: string\n /**\n * Merchant's stock-keeping unit (AGL-686). Carried into the public DTO\n * so the server can put `sku` on the Product structured data — Google\n * Merchant treats it as required for a product offer, and without it a\n * listing is simply ineligible for rich results rather than warned about.\n * It is already public information: it prints on receipts and invoices.\n */\n sku?: string\n /**\n * The buyer may choose the day they will use it (a pass bought ahead,\n * AGL-4043): the page offers an optional date. Absent when it does not.\n */\n asksUseDate?: true\n /** A short line on the variant's picture card (AGL-4205). */\n note?: string\n }>\n /**\n * The page offers \"Get a free mockup\" (AGL-4205): the request form the site\n * placed in the product block opens with the shopper's picks.\n */\n mockupRequests?: true\n /**\n * The store's time zone, sent only when a variant asks for a use day, so\n * the page offers no day that has passed on the store's calendar.\n */\n useDayTimeZone?: string\n tags?: string[]\n /** Recurring billing (AGL-303) so the PDP frames the price. */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /** Buyer may choose one-time OR subscribe (AGL-545). */\n subscriptionOptional?: boolean\n /**\n * The add-ons the page offers (AGL-4100): ONLY the groups switched to\n * \"Show on the website\". A register-only group never leaves the server, so\n * a shop's in-person choices and prices are not published. Absent: none.\n * Display-only like the prices above; every sale door prices them again\n * from the product.\n */\n modifierGroups?: PublicModifierGroup[]\n}\n\n/** An add-on group as the product page shows it (AGL-4100). */\nexport interface PublicModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: Array<{\n id: string\n name: string\n priceCents: number\n /** What the choice adds on a variant priced differently, by variant id. */\n priceCentsByVariant?: Record<string, number>\n /** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */\n imageUrl?: string\n note?: string\n includes?: string[]\n }>\n}\n\n/** The website add-on groups of a product, in the page's shape (AGL-4100). */\nexport function publicModifierGroups(\n product: { modifierGroups?: unknown },\n): PublicModifierGroup[] {\n return CommerceModel.websiteModifierGroups(product).map((group) => ({\n id: group.id,\n name: group.name,\n min: group.min,\n max: group.max,\n options: group.options.map((option) => ({\n id: option.id,\n name: option.name,\n priceCents: option.priceCents,\n ...(option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length\n ? { priceCentsByVariant: { ...option.priceCentsByVariant } }\n : {}),\n // Card fields are checked at save (`modifierCardsProblem`), not on this\n // read, so only well-formed values reach the page (AGL-4205).\n ...(typeof option.imageUrl === 'string' && option.imageUrl ? { imageUrl: option.imageUrl } : {}),\n ...(typeof option.note === 'string' && option.note.trim() ? { note: option.note.trim() } : {}),\n ...(CommerceModel.modifierOptionIsCombo(option) ? { includes: [...(option.includes ?? [])] } : {}),\n })),\n }))\n}\n\n/**\n * Map a lifted product onto the public PDP DTO.\n *\n * Extracted (AGL-659) so the site-page resolver can put the SAME payload\n * into page props as the API returns — the PDP block used to fetch this in\n * an effect, which meant the server rendered a skeleton and crawlers saw a\n * product page with no product in it. One definition keeps the server-\n * rendered and client-fetched shapes from drifting.\n *\n * Display-only by design: stock is a `soldOut` boolean rather than a raw\n * count, and the charge still prices server-side.\n */\nexport function toPublicProductDetail(\n id: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n options: { timeZone?: string | null } = {},\n): PublicProductDetail {\n const asksUseDate = productAsksUseDateAnywhere(product)\n const modifierGroups = publicModifierGroups(product)\n return {\n id,\n name: product.name,\n slug: product.slug,\n ...(product.description ? { description: product.description } : {}),\n type: product.type,\n mediaUrls:\n product.mediaUrls ?? (product.imageUrl ? [product.imageUrl] : []),\n options: product.options ?? [],\n variants: product.variants.map((variant) => ({\n id: variant.id,\n ...(variant.options ? { options: variant.options } : {}),\n priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null,\n ...(variant.compareAtPriceUsd\n ? { compareAtPriceUsd: variant.compareAtPriceUsd }\n : {}),\n soldOut:\n variant.inventory != null &&\n Number(variant.inventory) <= 0 &&\n product.oversellPolicy !== 'backorder',\n ...(variant.imageUrl ? { imageUrl: variant.imageUrl } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n ...(CommerceModel.productAsksUseDate(product, variant.id) ? { asksUseDate: true as const } : {}),\n ...(typeof variant.note === 'string' && variant.note.trim() ? { note: variant.note.trim() } : {}),\n })),\n ...(product.mockupRequests === true ? { mockupRequests: true as const } : {}),\n ...(asksUseDate ? { useDayTimeZone: options.timeZone || 'UTC' } : {}),\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.subscription ? { subscription: product.subscription } : {}),\n ...(product.subscription && product.subscriptionOptional\n ? { subscriptionOptional: true }\n : {}),\n ...(modifierGroups.length ? { modifierGroups } : {}),\n }\n}\n\n/** Whether any variant of a product asks the buyer for a use day (AGL-4043). */\nexport function productAsksUseDateAnywhere(\n product: Pick<ReturnType<typeof CommerceModel.liftLegacyProduct>, 'variants' | 'checkIn'>,\n): boolean {\n return product.variants.some((variant) => CommerceModel.productAsksUseDate(product, variant.id))\n}\n\n/**\n * Public product detail by slug (AGL-292): everything the PDP block\n * needs — variants with per-option prices and stock booleans, never raw\n * counts. Display-only; the charge still prices server-side.\n */\nexport const productHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n const slug = String(req.query.slug ?? '')\n if (!hostId || !slug) {\n return res.status(400).json({ error: 'Missing hostId or slug' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .where('slug', '==', slug)\n .limit(1)\n .get()\n const docSnapshot = snapshot.docs[0]\n const raw = docSnapshot?.data() as any\n // A product sold in person only (AGL-4060) has no page online: the same\n // 404 as a draft, so its address says nothing about it.\n if (!CommerceModel.productListedOnline(raw)) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n // The store's calendar, only for a product that asks for a use day.\n const timeZone = productAsksUseDateAnywhere(product)\n ? (await readStoreDay(firestore.collection('hosts').doc(hostId))).timeZone\n : null\n const detail = toPublicProductDetail(docSnapshot.id, product, { timeZone })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json({ product: detail })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Product unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","readStoreDay","publicModifierGroups","product","websiteModifierGroups","map","group","id","name","min","max","options","option","priceCents","priceCentsByVariant","Object","keys","length","imageUrl","note","trim","modifierOptionIsCombo","includes","toPublicProductDetail","asksUseDate","productAsksUseDateAnywhere","modifierGroups","slug","description","type","mediaUrls","variants","variant","priceUsd","variantHasPrice","compareAtPriceUsd","soldOut","inventory","Number","oversellPolicy","sku","productAsksUseDate","mockupRequests","useDayTimeZone","timeZone","tags","subscription","subscriptionOptional","some","productHandler","req","res","hostId","String","query","status","json","error","firestore","app","snapshot","collection","doc","where","limit","get","docSnapshot","docs","raw","data","productListedOnline","liftLegacyProduct","detail","set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+BAAAA,YAAaG,IAAI;QAC7B,wEAAwE;QACxE,wDAAwD;QACxD,IAAI,CAACtE,cAAcuE,mBAAmB,CAACF,MAAM;YAC3C,OAAOjB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAkB;QACzD;QACA,MAAMtD,UAAUJ,cAAcwE,iBAAiB,CAACH;QAChD,oEAAoE;QACpE,MAAMxB,WAAWnB,2BAA2BtB,WACxC,AAAC,CAAA,MAAMF,aAAayD,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACV,QAAO,EAAGR,QAAQ,GACxE;QACJ,MAAM4B,SAASjD,sBAAsB2C,YAAY3D,EAAE,EAAEJ,SAAS;YAAEyC;QAAS;QACzEO,IAAIsB,SAAS,CACX,iBACA;QAEF,OAAOtB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAErD,SAASqE;QAAO;IAChD,EAAE,OAAOf,OAAO;QACdiB,QAAQjB,KAAK,CAACA;QACd,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { createHash } from "node:crypto";
17
+ */ import { validateProductForSave } from "../model/product-card-rules.js";
18
+ import { createHash } from "node:crypto";
18
19
  import { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
19
20
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
20
21
  import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
@@ -22,7 +23,7 @@ import { countLiveDocuments } from "@aglyn/aglyn/app-utils/live-document-count";
22
23
  import { dropPluginSiteCache } from "@aglyn/aglyn/plugin-manager/plugin-site-cache";
23
24
  import { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from "@aglyn/tenant-data-admin";
24
25
  import { FieldValue } from "firebase-admin/firestore";
25
- import { liftLegacyProduct, productCollectionIds, productDuplicateFields, productDuplicateName, productDuplicateSlugBase, productEditWrite, productMembershipInput, productSaveFields, smartCollectionRulesOf, stockAdjustmentWrite, validateProduct, variantMatrixProblem } from "../model/index.js";
26
+ import { liftLegacyProduct, productCollectionIds, productDuplicateFields, productDuplicateName, productDuplicateSlugBase, productEditWrite, productMembershipInput, productSaveFields, smartCollectionRulesOf, stockAdjustmentWrite, variantMatrixProblem } from "../model/index.js";
26
27
  import { planRefusal, roomRefusal } from "./product-drafts.js";
27
28
  /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */ export const ROLE_REFUSAL = siteKeyRefusal('site.edit');
28
29
  const MAX_BODY_BYTES = 256000;
@@ -180,7 +181,7 @@ export function resolved(deps) {
180
181
  const fields = productSaveFields(product, nowMs);
181
182
  // More combinations than a product holds is refused with the count
182
183
  // (AGL-4100), never saved short of the options it names.
183
- const problem = (_variantMatrixProblem = variantMatrixProblem(fields.options)) != null ? _variantMatrixProblem : validateProduct(fields);
184
+ const problem = (_variantMatrixProblem = variantMatrixProblem(fields.options)) != null ? _variantMatrixProblem : validateProductForSave(fields);
184
185
  if (problem) return res.status(400).json({
185
186
  error: problem
186
187
  });