@aglyn/plugins-commerce 1.29.1 → 1.29.2

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 (84) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/checkout-tax-blocked-notice.component.d.ts +18 -0
  3. package/src/lib/components/console/checkout-tax-blocked-notice.component.js +67 -0
  4. package/src/lib/components/console/checkout-tax-blocked-notice.component.js.map +1 -0
  5. package/src/lib/components/console/payments-settings-card.component.d.ts +2 -2
  6. package/src/lib/components/console/payments-settings-card.component.js +99 -5
  7. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  8. package/src/lib/components/console/product-editor-dialog.component.js +14 -3
  9. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  10. package/src/lib/components/console/stripe-tax-readiness.component.d.ts +45 -0
  11. package/src/lib/components/console/stripe-tax-readiness.component.js +276 -0
  12. package/src/lib/components/console/stripe-tax-readiness.component.js.map +1 -0
  13. package/src/lib/components/console/tax-settings-card.component.js +22 -8
  14. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  15. package/src/lib/constants/operator-alerts.d.ts +9 -0
  16. package/src/lib/constants/operator-alerts.js +22 -1
  17. package/src/lib/constants/operator-alerts.js.map +1 -1
  18. package/src/lib/declarations.server.js +11 -0
  19. package/src/lib/declarations.server.js.map +1 -1
  20. package/src/lib/model/commerce-tax-readiness.d.ts +79 -0
  21. package/src/lib/model/commerce-tax-readiness.js +99 -0
  22. package/src/lib/model/commerce-tax-readiness.js.map +1 -0
  23. package/src/lib/model/commerce.d.ts +7 -0
  24. package/src/lib/model/commerce.js +17 -4
  25. package/src/lib/model/commerce.js.map +1 -1
  26. package/src/lib/model/payments-setup-status.d.ts +68 -0
  27. package/src/lib/model/payments-setup-status.js +103 -0
  28. package/src/lib/model/payments-setup-status.js.map +1 -0
  29. package/src/lib/plan-entitlements.d.ts +2 -1
  30. package/src/lib/plan-entitlements.js +2 -1
  31. package/src/lib/plan-entitlements.js.map +1 -1
  32. package/src/lib/server/cart-checkout.js +3 -0
  33. package/src/lib/server/cart-checkout.js.map +1 -1
  34. package/src/lib/server/checkout-tax-refusal.d.ts +51 -0
  35. package/src/lib/server/checkout-tax-refusal.js +133 -0
  36. package/src/lib/server/checkout-tax-refusal.js.map +1 -0
  37. package/src/lib/server/checkout.d.ts +2 -1
  38. package/src/lib/server/checkout.js +7 -2
  39. package/src/lib/server/checkout.js.map +1 -1
  40. package/src/lib/server/connect-prefill.d.ts +65 -0
  41. package/src/lib/server/connect-prefill.js +85 -0
  42. package/src/lib/server/connect-prefill.js.map +1 -0
  43. package/src/lib/server/connect.d.ts +4 -2
  44. package/src/lib/server/connect.js +117 -37
  45. package/src/lib/server/connect.js.map +1 -1
  46. package/src/lib/server/draft-order.js +4 -2
  47. package/src/lib/server/draft-order.js.map +1 -1
  48. package/src/lib/server/pos-order.js +1 -1
  49. package/src/lib/server/pos-order.js.map +1 -1
  50. package/src/lib/server/product-writer.d.ts +27 -0
  51. package/src/lib/server/product-writer.js +174 -4
  52. package/src/lib/server/product-writer.js.map +1 -1
  53. package/src/lib/server/quote-pay.d.ts +6 -0
  54. package/src/lib/server/quote-pay.js +8 -2
  55. package/src/lib/server/quote-pay.js.map +1 -1
  56. package/src/lib/server/seller-stripe-account.d.ts +19 -0
  57. package/src/lib/server/seller-stripe-account.js +40 -4
  58. package/src/lib/server/seller-stripe-account.js.map +1 -1
  59. package/src/lib/server/site-page-resolver.d.ts +1 -6
  60. package/src/lib/server/site-page-resolver.js +4 -12
  61. package/src/lib/server/site-page-resolver.js.map +1 -1
  62. package/src/lib/server/site-search.d.ts +43 -0
  63. package/src/lib/server/site-search.js +124 -0
  64. package/src/lib/server/site-search.js.map +1 -0
  65. package/src/lib/server/tax-readiness.d.ts +56 -0
  66. package/src/lib/server/tax-readiness.js +169 -0
  67. package/src/lib/server/tax-readiness.js.map +1 -0
  68. package/src/lib/server.js +6 -0
  69. package/src/lib/server.js.map +1 -1
  70. package/src/lib/transfer/product-image-copy.server.d.ts +77 -0
  71. package/src/lib/transfer/product-image-copy.server.js +307 -0
  72. package/src/lib/transfer/product-image-copy.server.js.map +1 -0
  73. package/src/lib/transfer/product-images.d.ts +62 -0
  74. package/src/lib/transfer/product-images.js +143 -0
  75. package/src/lib/transfer/product-images.js.map +1 -0
  76. package/src/lib/transfer/product-sources.d.ts +92 -0
  77. package/src/lib/transfer/product-sources.js +519 -0
  78. package/src/lib/transfer/product-sources.js.map +1 -0
  79. package/src/lib/transfer/product-transfer.d.ts +26 -1
  80. package/src/lib/transfer/product-transfer.js +283 -11
  81. package/src/lib/transfer/product-transfer.js.map +1 -1
  82. package/src/lib/transfer/products.server.d.ts +29 -3
  83. package/src/lib/transfer/products.server.js +289 -13
  84. package/src/lib/transfer/products.server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/site-page-resolver.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 { SitePageResolver } from '@aglyn/aglyn/server'\nimport { hostCollectionKind } from '@aglyn/aglyn/server'\nimport composeScreenNodes, {\n composeNodesWithChrome,\n} from '@aglyn/tenant-runtime/compose-screen-nodes'\nimport { resolveBuiltInPageLayoutId } from '@aglyn/tenant-runtime/built-in-page-layout'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { ORDER_STATUS_PATH } from './order-status-token'\nimport { ORDER_STATUS_COMPONENT_ID } from '../constants/order-status'\nimport { RETURN_REQUEST_COMPONENT_ID, RETURN_REQUEST_PATH } from '../constants/return-request'\nimport { QUOTE_PAGE_COMPONENT_ID, QUOTE_PAGE_PATH } from '../constants/quote-page'\nimport getScreen from '@aglyn/tenant-runtime/get-screen'\nimport { collectSocialImageFacts } from '@aglyn/tenant-runtime/social-image-facts'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { productAsksUseDateAnywhere, toPublicProductDetail } from './product'\nimport { readStoreDay } from './store-day'\nimport { readProductReviews } from './reviews'\n\n/**\n * Commerce page resolver (AGL-292/298/418), relocated verbatim from the\n * tenant loader: /products/{slug} renders the host's designated PDP\n * template with product tokens, /collections/{slug} the collection\n * template — both compose server-side and return complete page props.\n * Runs only for paths that didn't match a published screen; returns\n * undefined for everything else so the loader falls through.\n */\nexport const commerceSitePageResolver: SitePageResolver = async ({\n hostId,\n host,\n path,\n}) => {\n const hostRes = { host }\n // Product detail routes (AGL-292): /products/{slug} renders the\n // host's designated PDP template screen (settings/store\n // `pdpScreenId`, AGL-295) with product tokens; the product-detail\n // block hydrates variants client-side from the same slug. Same\n // mechanism as entry-template screens below.\n const pdpSegments = path.split('/').filter(Boolean)\n // The guest order-status page (AGL-3610), at /order-status — reached only\n // when the site has no page of its own there. The site's header and footer\n // around the order-status block, which reads the signed `?o=&t=` link after\n // hydration, so this page holds no order and is safe to cache. UNLISTED, so\n // the head says noindex: it is a private page, not a landing page.\n if (pdpSegments.length === 1 && pdpSegments[0] === ORDER_STATUS_PATH) {\n return composeOrderStatusPage(hostId, host)\n }\n // The buyer's return form (AGL-3611), at /order-return, under the same\n // terms: no page of the site's own there, the order read after hydration\n // from the link's `?o=&t=` (or the member's session), UNLISTED.\n if (pdpSegments.length === 1 && pdpSegments[0] === RETURN_REQUEST_PATH) {\n return composeReturnRequestPage(hostId, host)\n }\n // The customer's quote page (AGL-4094), at /pay-quote, under the same\n // terms: no page of the site's own there, the quote read after hydration\n // from the pay link's `?q=&t=`, UNLISTED.\n if (pdpSegments.length === 1 && pdpSegments[0] === QUOTE_PAGE_PATH) {\n return composeQuotePage(hostId, host)\n }\n if (pdpSegments.length === 2 && pdpSegments[0] === 'products') {\n const adminFirestore = firebaseAdmin.app().firestore()\n const hostDocRef = adminFirestore.collection('hosts').doc(hostId)\n const [storeSettings, productSnapshot] = await Promise.all([\n hostDocRef.collection('settings').doc('store').get(),\n hostDocRef\n .collection('products')\n .where('slug', '==', pdpSegments[1])\n .limit(1)\n .get(),\n ])\n const pdpScreenId = storeSettings.get('pdpScreenId')\n const productRaw = productSnapshot.docs[0]?.data() as any\n // Live, active and sold online (AGL-4060): a product sold in person only\n // has no page here, designed or built in, and falls through to the 404.\n const listedOnline = CommerceModel.productListedOnline(productRaw)\n if (pdpScreenId && listedOnline) {\n const product = CommerceModel.liftLegacyProduct(productRaw)\n const templateRes = await getScreen({\n hostId,\n screenId: pdpScreenId,\n // A PDP template renders against a routed PRODUCT, never at an address\n // of its own, so it is served here and 404s everywhere else (AGL-1400).\n allowTemplate: true,\n })\n if (templateRes.screen) {\n const [minPrice, maxPrice] = CommerceModel.productPriceRange(product)\n // Best-effort: a reviews read that fails costs the page its rating\n // snippet, not the page.\n const productReviews = await readProductReviews(\n hostId,\n productSnapshot.docs[0].id,\n ).catch((error) => {\n console.error('product review aggregate failed', error)\n return { reviews: [], aggregate: { count: 0, average: 0 } }\n })\n // The head shares this page as the template's image, then the site\n // default, so their documents are read in the template's own batch\n // (AGL-2850).\n const card = collectSocialImageFacts([\n (templateRes.screen as any).seo?.image,\n hostRes.host?.seo?.image,\n ])\n const templateNodes = await composeScreenNodes({\n hostId,\n screenId: pdpScreenId,\n screen: templateRes.screen,\n socialImages: card.socialImages,\n // The template's host variables, and its layout's, fill in from\n // this site as they do on every other page (AGL-2883).\n host: hostRes.host,\n tokens: {\n 'product.name': product.name,\n 'product.description': product.description ?? '',\n 'product.price': productPriceText(product, minPrice, maxPrice),\n 'product.image':\n product.mediaUrls?.[0] ?? product.imageUrl ?? '',\n 'product.slug': product.slug,\n },\n // Named as the product template it is if the page review holds it\n // (AGL-3374); without it the route has no page.\n page: {\n template: {\n role: 'entry',\n route: '/products/:slug',\n collectionName: 'Products',\n entryPath: `/products/${product.slug}`,\n fallback: 'not-found',\n },\n },\n })\n if (templateNodes) {\n return {\n props: JSON.parse(\n JSON.stringify({\n // The PDP block used to fetch this in an effect, so the\n // server rendered a skeleton and crawlers saw a product page\n // with no product in it (AGL-659). The product is already\n // loaded here — hand it down so it renders server-side.\n pageData: {\n commerce: {\n product: toPublicProductDetail(\n productSnapshot.docs[0].id,\n product,\n // The store's calendar, for a pass that asks for a day.\n { timeZone: await passDayTimeZone(hostId, hostRes.host, product) },\n ),\n // Rating aggregate (AGL-686): needed HERE because\n // `aggregateRating` belongs nested inside the Product\n // structured data, and that is emitted server-side.\n // The reviews block used to publish a free-standing\n // AggregateRating node, which schema.org ignores.\n ...(productReviews.aggregate.count\n ? { reviews: productReviews }\n : {}),\n },\n },\n data: {\n host: hostRes.host,\n screen: {\n data: {\n ...templateRes.screen,\n // The product NAMES this page; the template's own name\n // (\"Product detail\") describes none of the products it\n // renders. Kept distinct from the SEO title because the\n // head treats an authored title as verbatim and a name\n // as the side the site title joins (AGL-1341) — so a\n // product with its own SEO title gets exactly that, and\n // one without gets \"Blue Widget – Acme Store\".\n displayName: product.name,\n seo: {\n ...((templateRes.screen as any).seo ?? {}),\n // Only when the PRODUCT authored one: inheriting the\n // template screen's title would give every product\n // page in the store the same `<title>`.\n title: product.seo?.title ?? undefined,\n description:\n product.seo?.description ??\n product.description ??\n undefined,\n },\n },\n },\n },\n nodes: templateNodes,\n ...card.collected(),\n }),\n ),\n revalidate: 60,\n }\n }\n }\n }\n // No product template designated, or none that renders: the store's\n // built-in product page (AGL-3676), in the site's own header and footer,\n // rather than a 404 behind every card the product grid links. A store a\n // guided start built has no template of its own, and its grid links each\n // product here.\n if (listedOnline) {\n return composeBuiltInProductPage(\n hostId,\n host,\n productSnapshot.docs[0].id,\n CommerceModel.liftLegacyProduct(productRaw),\n storeSettings.get('returns'),\n )\n }\n }\n // Commerce collection routes (AGL-298): /collections/{slug} renders\n // the designated collection template with collection tokens; the\n // product-grid block derives the same slug from the URL.\n if (pdpSegments.length === 2 && pdpSegments[0] === 'collections') {\n const adminFirestore = firebaseAdmin.app().firestore()\n const hostDocRef = adminFirestore.collection('hosts').doc(hostId)\n const [storeSettings, collectionSnapshot] = await Promise.all([\n hostDocRef.collection('settings').doc('store').get(),\n hostDocRef\n .collection('collections')\n .where('slug', '==', pdpSegments[1])\n .limit(5)\n .get(),\n ])\n const collectionScreenId = storeSettings.get('collectionScreenId')\n // Content collections share this path and a slug is only unique within a\n // kind (AGL-954), so take the first CATALOG match rather than the first\n // doc — otherwise a blog with the same slug renders as a product page.\n const shopCollection = collectionSnapshot.docs\n .find((docSnapshot) => hostCollectionKind(docSnapshot.data()) === 'catalog')\n ?.data() as CommerceModel.HostCollection | undefined\n if (collectionScreenId && shopCollection) {\n const templateRes = await getScreen({\n hostId,\n screenId: collectionScreenId,\n allowTemplate: true,\n })\n if (templateRes.screen) {\n // As on the PDP above: the template's image, then the site default\n // (AGL-2850).\n const card = collectSocialImageFacts([\n (templateRes.screen as any).seo?.image,\n hostRes.host?.seo?.image,\n ])\n const templateNodes = await composeScreenNodes({\n hostId,\n screenId: collectionScreenId,\n screen: templateRes.screen,\n socialImages: card.socialImages,\n // As on the PDP above (AGL-2883).\n host: hostRes.host,\n tokens: {\n 'collection.name': shopCollection.name,\n 'collection.description': shopCollection.description ?? '',\n 'collection.image': shopCollection.imageUrl ?? '',\n 'collection.slug': shopCollection.slug,\n },\n // As on the PDP above (AGL-3374).\n page: {\n template: {\n role: 'entry',\n route: '/collections/:slug',\n collectionName: 'Store collections',\n entryPath: `/collections/${shopCollection.slug}`,\n fallback: 'not-found',\n },\n },\n })\n if (templateNodes) {\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host: hostRes.host,\n screen: {\n data: {\n ...templateRes.screen,\n // As on the PDP above: the catalog collection names the\n // page, and a name takes the site title after it while\n // an authored SEO title would not (AGL-1341). A shop\n // collection has no SEO title field of its own, so the\n // template's must not stand in for one.\n displayName: shopCollection.name,\n seo: {\n ...((templateRes.screen as any).seo ?? {}),\n title: undefined,\n description:\n shopCollection.description ?? undefined,\n },\n },\n },\n },\n nodes: templateNodes,\n ...card.collected(),\n }),\n ),\n revalidate: 60,\n }\n }\n }\n }\n }\n return undefined\n}\n\n/**\n * What `{{product.price}}` says: the price, \"From\" the lowest where variants\n * differ, or \"Price coming soon\" for a product listed before any variant has\n * one (AGL-3676) — never \"$0\".\n */\nexport function productPriceText(\n product: Pick<CommerceModel.HostProduct, 'variants'>,\n minPrice: number,\n maxPrice: number,\n): string {\n if (!(product.variants ?? []).some((variant) => CommerceModel.variantHasPrice(variant))) {\n return 'Price coming soon'\n }\n return minPrice === maxPrice ? `$${minPrice}` : `From $${minPrice}`\n}\n\nconst PRODUCT_PAGE_NODE = 'pdp__detail'\nconst PRODUCT_PAGE_REVIEWS_NODE = 'pdp__reviews'\nconst PRODUCT_PAGE_RELATED_NODE = 'pdp__related'\n\n/**\n * The store's built-in product page (AGL-3676), root first, for the layout's\n * slot: the product block for the routed slug — with its Details and\n * Shipping & returns folds under the description, as a designer theme's\n * product page has them — then the product's reviews where the store's plan\n * collects them, then the related products as a grid of photo cards.\n */\nexport function buildProductPageNodes(\n slug: string,\n options: { reviews?: boolean } = {},\n): Record<string, Aglyn.AglynNodeSchema> {\n const reviews = Boolean(options.reviews)\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['pdp__container'],\n } as Aglyn.AglynNodeSchema,\n pdp__container: {\n $id: 'pdp__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'lg', sx: { paddingTop: 6, paddingBottom: 10 } },\n nodes: [\n PRODUCT_PAGE_NODE,\n ...(reviews ? [PRODUCT_PAGE_REVIEWS_NODE] : []),\n PRODUCT_PAGE_RELATED_NODE,\n ],\n } as Aglyn.AglynNodeSchema,\n [PRODUCT_PAGE_NODE]: {\n $id: PRODUCT_PAGE_NODE,\n parentId: 'pdp__container',\n componentId: 'product-detail',\n pluginId: 'commerce',\n props: { slug, showDetails: true, showShipping: true },\n } as Aglyn.AglynNodeSchema,\n ...(reviews\n ? {\n [PRODUCT_PAGE_REVIEWS_NODE]: {\n $id: PRODUCT_PAGE_REVIEWS_NODE,\n parentId: 'pdp__container',\n componentId: 'product-reviews',\n pluginId: 'commerce',\n props: { heading: 'Reviews', sx: { marginTop: 8 } },\n } as Aglyn.AglynNodeSchema,\n }\n : {}),\n [PRODUCT_PAGE_RELATED_NODE]: {\n $id: PRODUCT_PAGE_RELATED_NODE,\n parentId: 'pdp__container',\n componentId: 'related-products',\n pluginId: 'commerce',\n props: {\n heading: 'You may also like',\n maxItems: 4,\n layout: 'grid',\n sx: { marginTop: 8 },\n },\n } as Aglyn.AglynNodeSchema,\n }\n}\n\n/**\n * The store's return window for this product, when the store takes returns of\n * its kind: the settings the return form enforces (`readReturnSettings`), so\n * the page never states a policy the store does not keep.\n */\nexport function productReturnWindow(\n product: Pick<CommerceModel.HostProduct, 'type'>,\n rawReturns: unknown,\n): { windowDays: number } | undefined {\n const settings = CommerceModel.readReturnSettings(rawReturns)\n if (!settings.enabled || settings.windowDays <= 0) return undefined\n if (!settings.eligibleTypes.includes(product.type ?? 'physical')) return undefined\n return { windowDays: settings.windowDays }\n}\n\n/** Whether the store's plan collects reviews; a failed read leaves them off. */\nasync function storeTakesReviews(hostId: string): Promise<boolean> {\n try {\n const org = await getOrgForHost(hostId)\n return Aglyn.checkEntitlement(org?.org as never, 'productReviews')\n } catch (error) {\n console.error('reviews entitlement read failed', error)\n return false\n }\n}\n\nasync function composeBuiltInProductPage(\n hostId: string,\n host: unknown,\n productId: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n rawReturns?: unknown,\n) {\n try {\n const [layoutId, productReviews, reviewsOn] = await Promise.all([\n resolveBuiltInPageLayoutId({ hostId, host: host as never }),\n readProductReviews(hostId, productId).catch((error) => {\n console.error('product review aggregate failed', error)\n return { reviews: [], aggregate: { count: 0, average: 0 } }\n }),\n storeTakesReviews(hostId),\n ])\n const returns = productReturnWindow(product, rawReturns)\n const card = collectSocialImageFacts([\n product.mediaUrls?.[0] ?? product.imageUrl,\n (host as { seo?: { image?: string } } | null)?.seo?.image,\n ])\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildProductPageNodes(product.slug, { reviews: reviewsOn }),\n socialImages: card.socialImages,\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n // Seeded, so the product renders server-side and the head writes\n // its Product structured data, as on a template page (AGL-659).\n pageData: {\n commerce: {\n product: toPublicProductDetail(productId, product, {\n timeZone: await passDayTimeZone(hostId, host, product),\n }),\n ...(productReviews.aggregate.count ? { reviews: productReviews } : {}),\n // The Shipping & returns fold's return line, only when the\n // store takes returns of this product's kind.\n ...(returns ? { returns } : {}),\n },\n },\n data: {\n host,\n screen: {\n data: {\n displayName: product.name,\n seo: {\n title: product.seo?.title ?? undefined,\n description: product.seo?.description ?? product.description ?? undefined,\n },\n },\n },\n },\n nodes,\n ...card.collected(),\n }),\n ),\n revalidate: 60,\n }\n } catch (error) {\n console.error('built-in product page composition failed', error)\n return undefined\n }\n}\n\nconst ORDER_STATUS_NODE = 'order-status__block'\n\n/** The order-status page's node tree, root first, for the layout's slot. */\nexport function buildOrderStatusNodes(): Record<string, Aglyn.AglynNodeSchema> {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['order-status__container'],\n } as Aglyn.AglynNodeSchema,\n 'order-status__container': {\n $id: 'order-status__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'md', sx: { paddingTop: 6, paddingBottom: 8 } },\n nodes: [ORDER_STATUS_NODE],\n } as Aglyn.AglynNodeSchema,\n [ORDER_STATUS_NODE]: {\n $id: ORDER_STATUS_NODE,\n parentId: 'order-status__container',\n componentId: ORDER_STATUS_COMPONENT_ID,\n pluginId: 'commerce',\n props: {},\n } as Aglyn.AglynNodeSchema,\n }\n}\n\nasync function composeOrderStatusPage(hostId: string, host: unknown) {\n try {\n const layoutId = await resolveBuiltInPageLayoutId({ hostId, host: host as never })\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildOrderStatusNodes(),\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host,\n screen: {\n data: {\n displayName: 'Order status',\n visibility: Aglyn.HostScreenVisibility.UNLISTED,\n },\n },\n },\n nodes,\n }),\n ),\n revalidate: 3600,\n }\n } catch (error) {\n console.error('order status page composition failed', error)\n return undefined\n }\n}\n\nconst RETURN_REQUEST_NODE = 'ret__block'\n\n/** The return form's node tree, root first, for the layout's slot. */\nexport function buildReturnRequestNodes(): Record<string, Aglyn.AglynNodeSchema> {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['ret__container'],\n } as Aglyn.AglynNodeSchema,\n ret__container: {\n $id: 'ret__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'md', sx: { paddingTop: 6, paddingBottom: 8 } },\n nodes: [RETURN_REQUEST_NODE],\n } as Aglyn.AglynNodeSchema,\n [RETURN_REQUEST_NODE]: {\n $id: RETURN_REQUEST_NODE,\n parentId: 'ret__container',\n componentId: RETURN_REQUEST_COMPONENT_ID,\n pluginId: 'commerce',\n props: {},\n } as Aglyn.AglynNodeSchema,\n }\n}\n\nasync function composeReturnRequestPage(hostId: string, host: unknown) {\n try {\n const layoutId = await resolveBuiltInPageLayoutId({ hostId, host: host as never })\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildReturnRequestNodes(),\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host,\n screen: {\n data: {\n displayName: 'Request a return',\n visibility: Aglyn.HostScreenVisibility.UNLISTED,\n },\n },\n },\n nodes,\n }),\n ),\n revalidate: 3600,\n }\n } catch (error) {\n console.error('return request page composition failed', error)\n return undefined\n }\n}\n\nconst QUOTE_PAGE_NODE = 'quote-page__block'\n\n/** The quote page's node tree, root first, for the layout's slot. */\nexport function buildQuotePageNodes(): Record<string, Aglyn.AglynNodeSchema> {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['quote-page__container'],\n } as Aglyn.AglynNodeSchema,\n 'quote-page__container': {\n $id: 'quote-page__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'md', sx: { paddingTop: 6, paddingBottom: 8 } },\n nodes: [QUOTE_PAGE_NODE],\n } as Aglyn.AglynNodeSchema,\n [QUOTE_PAGE_NODE]: {\n $id: QUOTE_PAGE_NODE,\n parentId: 'quote-page__container',\n componentId: QUOTE_PAGE_COMPONENT_ID,\n pluginId: 'commerce',\n props: {},\n } as Aglyn.AglynNodeSchema,\n }\n}\n\nasync function composeQuotePage(hostId: string, host: unknown) {\n try {\n const layoutId = await resolveBuiltInPageLayoutId({ hostId, host: host as never })\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildQuotePageNodes(),\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host,\n screen: {\n data: {\n // The page is the same for a quote's link and an invoice's (AGL-4099).\n displayName: 'Your quote or invoice',\n visibility: Aglyn.HostScreenVisibility.UNLISTED,\n },\n },\n },\n nodes,\n }),\n ),\n revalidate: 3600,\n }\n } catch (error) {\n console.error('quote page composition failed', error)\n return undefined\n }\n}\n\n/**\n * The store's time zone for a product page whose product asks for a use day\n * (AGL-4043), so the seeded page offers the same days the API's does; null\n * otherwise, without a read.\n */\nasync function passDayTimeZone(\n hostId: string,\n host: unknown,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n): Promise<string | null> {\n if (!productAsksUseDateAnywhere(product)) return null\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n return (await readStoreDay(hostRef, { host: (host ?? null) as Record<string, unknown> | null })).timeZone\n}\n"],"names":["hostCollectionKind","composeScreenNodes","composeNodesWithChrome","resolveBuiltInPageLayoutId","Aglyn","ORDER_STATUS_PATH","ORDER_STATUS_COMPONENT_ID","RETURN_REQUEST_COMPONENT_ID","RETURN_REQUEST_PATH","QUOTE_PAGE_COMPONENT_ID","QUOTE_PAGE_PATH","getScreen","collectSocialImageFacts","firebaseAdmin","getOrgForHost","CommerceModel","productAsksUseDateAnywhere","toPublicProductDetail","readStoreDay","readProductReviews","commerceSitePageResolver","hostId","host","path","hostRes","pdpSegments","split","filter","Boolean","length","composeOrderStatusPage","composeReturnRequestPage","composeQuotePage","productSnapshot","adminFirestore","app","firestore","hostDocRef","collection","doc","storeSettings","Promise","all","get","where","limit","pdpScreenId","productRaw","docs","data","listedOnline","productListedOnline","product","liftLegacyProduct","templateRes","screenId","allowTemplate","screen","minPrice","maxPrice","productPriceRange","productReviews","id","catch","error","console","reviews","aggregate","count","average","card","seo","image","templateNodes","socialImages","tokens","name","description","productPriceText","mediaUrls","imageUrl","slug","page","template","role","route","collectionName","entryPath","fallback","props","JSON","parse","stringify","pageData","commerce","timeZone","passDayTimeZone","displayName","title","undefined","nodes","collected","revalidate","composeBuiltInProductPage","collectionSnapshot","collectionScreenId","shopCollection","find","docSnapshot","variants","some","variant","variantHasPrice","PRODUCT_PAGE_NODE","PRODUCT_PAGE_REVIEWS_NODE","PRODUCT_PAGE_RELATED_NODE","buildProductPageNodes","options","NODE_ROOT_ID","$id","componentId","pdp__container","parentId","pluginId","maxWidth","sx","paddingTop","paddingBottom","showDetails","showShipping","heading","marginTop","maxItems","layout","productReturnWindow","rawReturns","settings","readReturnSettings","enabled","windowDays","eligibleTypes","includes","type","storeTakesReviews","org","checkEntitlement","productId","layoutId","reviewsOn","returns","screenNodes","ORDER_STATUS_NODE","buildOrderStatusNodes","visibility","HostScreenVisibility","UNLISTED","RETURN_REQUEST_NODE","buildReturnRequestNodes","ret__container","QUOTE_PAGE_NODE","buildQuotePageNodes","hostRef"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,kBAAkB,QAAQ,sBAAqB;AACxD,OAAOC,sBACLC,sBAAsB,QACjB,6CAA4C;AACnD,SAASC,0BAA0B,QAAQ,6CAA4C;AACvF,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAASC,2BAA2B,EAAEC,mBAAmB,QAAQ,iCAA6B;AAC9F,SAASC,uBAAuB,EAAEC,eAAe,QAAQ,6BAAyB;AAClF,OAAOC,eAAe,mCAAkC;AACxD,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,0BAA0B,EAAEC,qBAAqB,QAAQ,eAAW;AAC7E,SAASC,YAAY,QAAQ,iBAAa;AAC1C,SAASC,kBAAkB,QAAQ,eAAW;AAE9C;;;;;;;CAOC,GACD,OAAO,MAAMC,2BAA6C,OAAO,EAC/DC,MAAM,EACNC,IAAI,EACJC,IAAI,EACL;IACC,MAAMC,UAAU;QAAEF;IAAK;IACvB,gEAAgE;IAChE,wDAAwD;IACxD,kEAAkE;IAClE,+DAA+D;IAC/D,6CAA6C;IAC7C,MAAMG,cAAcF,KAAKG,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;IAAwC,EAAC,EAAGyE,QAAQ;AAC3G"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/site-page-resolver.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 { SitePageResolver } from '@aglyn/aglyn/server'\nimport { hostCollectionKind } from '@aglyn/aglyn/server'\nimport composeScreenNodes, {\n composeNodesWithChrome,\n} from '@aglyn/tenant-runtime/compose-screen-nodes'\nimport { resolveBuiltInPageLayoutId } from '@aglyn/tenant-runtime/built-in-page-layout'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { ORDER_STATUS_PATH } from './order-status-token'\nimport { ORDER_STATUS_COMPONENT_ID } from '../constants/order-status'\nimport { RETURN_REQUEST_COMPONENT_ID, RETURN_REQUEST_PATH } from '../constants/return-request'\nimport { QUOTE_PAGE_COMPONENT_ID, QUOTE_PAGE_PATH } from '../constants/quote-page'\nimport getScreen from '@aglyn/tenant-runtime/get-screen'\nimport { collectSocialImageFacts } from '@aglyn/tenant-runtime/social-image-facts'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { productAsksUseDateAnywhere, toPublicProductDetail } from './product'\nimport { readStoreDay } from './store-day'\nimport { readProductReviews } from './reviews'\n\n/**\n * Commerce page resolver (AGL-292/298/418), relocated verbatim from the\n * tenant loader: /products/{slug} renders the host's designated PDP\n * template with product tokens, /collections/{slug} the collection\n * template — both compose server-side and return complete page props.\n * Runs only for paths that didn't match a published screen; returns\n * undefined for everything else so the loader falls through.\n */\nexport const commerceSitePageResolver: SitePageResolver = async ({\n hostId,\n host,\n path,\n}) => {\n const hostRes = { host }\n // Product detail routes (AGL-292): /products/{slug} renders the\n // host's designated PDP template screen (settings/store\n // `pdpScreenId`, AGL-295) with product tokens; the product-detail\n // block hydrates variants client-side from the same slug. Same\n // mechanism as entry-template screens below.\n const pdpSegments = path.split('/').filter(Boolean)\n // The guest order-status page (AGL-3610), at /order-status — reached only\n // when the site has no page of its own there. The site's header and footer\n // around the order-status block, which reads the signed `?o=&t=` link after\n // hydration, so this page holds no order and is safe to cache. UNLISTED, so\n // the head says noindex: it is a private page, not a landing page.\n if (pdpSegments.length === 1 && pdpSegments[0] === ORDER_STATUS_PATH) {\n return composeOrderStatusPage(hostId, host)\n }\n // The buyer's return form (AGL-3611), at /order-return, under the same\n // terms: no page of the site's own there, the order read after hydration\n // from the link's `?o=&t=` (or the member's session), UNLISTED.\n if (pdpSegments.length === 1 && pdpSegments[0] === RETURN_REQUEST_PATH) {\n return composeReturnRequestPage(hostId, host)\n }\n // The customer's quote page (AGL-4094), at /pay-quote, under the same\n // terms: no page of the site's own there, the quote read after hydration\n // from the pay link's `?q=&t=`, UNLISTED.\n if (pdpSegments.length === 1 && pdpSegments[0] === QUOTE_PAGE_PATH) {\n return composeQuotePage(hostId, host)\n }\n if (pdpSegments.length === 2 && pdpSegments[0] === 'products') {\n const adminFirestore = firebaseAdmin.app().firestore()\n const hostDocRef = adminFirestore.collection('hosts').doc(hostId)\n const [storeSettings, productSnapshot] = await Promise.all([\n hostDocRef.collection('settings').doc('store').get(),\n hostDocRef\n .collection('products')\n .where('slug', '==', pdpSegments[1])\n .limit(1)\n .get(),\n ])\n const pdpScreenId = storeSettings.get('pdpScreenId')\n const productRaw = productSnapshot.docs[0]?.data() as any\n // Live, active and sold online (AGL-4060): a product sold in person only\n // has no page here, designed or built in, and falls through to the 404.\n const listedOnline = CommerceModel.productListedOnline(productRaw)\n if (pdpScreenId && listedOnline) {\n const product = CommerceModel.liftLegacyProduct(productRaw)\n const templateRes = await getScreen({\n hostId,\n screenId: pdpScreenId,\n // A PDP template renders against a routed PRODUCT, never at an address\n // of its own, so it is served here and 404s everywhere else (AGL-1400).\n allowTemplate: true,\n })\n if (templateRes.screen) {\n const [minPrice, maxPrice] = CommerceModel.productPriceRange(product)\n // Best-effort: a reviews read that fails costs the page its rating\n // snippet, not the page.\n const productReviews = await readProductReviews(\n hostId,\n productSnapshot.docs[0].id,\n ).catch((error) => {\n console.error('product review aggregate failed', error)\n return { reviews: [], aggregate: { count: 0, average: 0 } }\n })\n // The head shares this page as the template's image, then the site\n // default, so their documents are read in the template's own batch\n // (AGL-2850).\n const card = collectSocialImageFacts([\n (templateRes.screen as any).seo?.image,\n hostRes.host?.seo?.image,\n ])\n const templateNodes = await composeScreenNodes({\n hostId,\n screenId: pdpScreenId,\n screen: templateRes.screen,\n socialImages: card.socialImages,\n // The template's host variables, and its layout's, fill in from\n // this site as they do on every other page (AGL-2883).\n host: hostRes.host,\n tokens: {\n 'product.name': product.name,\n 'product.description': product.description ?? '',\n 'product.price': CommerceModel.productPriceText(product, minPrice, maxPrice),\n 'product.image':\n product.mediaUrls?.[0] ?? product.imageUrl ?? '',\n 'product.slug': product.slug,\n },\n // Named as the product template it is if the page review holds it\n // (AGL-3374); without it the route has no page.\n page: {\n template: {\n role: 'entry',\n route: '/products/:slug',\n collectionName: 'Products',\n entryPath: `/products/${product.slug}`,\n fallback: 'not-found',\n },\n },\n })\n if (templateNodes) {\n return {\n props: JSON.parse(\n JSON.stringify({\n // The PDP block used to fetch this in an effect, so the\n // server rendered a skeleton and crawlers saw a product page\n // with no product in it (AGL-659). The product is already\n // loaded here — hand it down so it renders server-side.\n pageData: {\n commerce: {\n product: toPublicProductDetail(\n productSnapshot.docs[0].id,\n product,\n // The store's calendar, for a pass that asks for a day.\n { timeZone: await passDayTimeZone(hostId, hostRes.host, product) },\n ),\n // Rating aggregate (AGL-686): needed HERE because\n // `aggregateRating` belongs nested inside the Product\n // structured data, and that is emitted server-side.\n // The reviews block used to publish a free-standing\n // AggregateRating node, which schema.org ignores.\n ...(productReviews.aggregate.count\n ? { reviews: productReviews }\n : {}),\n },\n },\n data: {\n host: hostRes.host,\n screen: {\n data: {\n ...templateRes.screen,\n // The product NAMES this page; the template's own name\n // (\"Product detail\") describes none of the products it\n // renders. Kept distinct from the SEO title because the\n // head treats an authored title as verbatim and a name\n // as the side the site title joins (AGL-1341) — so a\n // product with its own SEO title gets exactly that, and\n // one without gets \"Blue Widget – Acme Store\".\n displayName: product.name,\n seo: {\n ...((templateRes.screen as any).seo ?? {}),\n // Only when the PRODUCT authored one: inheriting the\n // template screen's title would give every product\n // page in the store the same `<title>`.\n title: product.seo?.title ?? undefined,\n description:\n product.seo?.description ??\n product.description ??\n undefined,\n },\n },\n },\n },\n nodes: templateNodes,\n ...card.collected(),\n }),\n ),\n revalidate: 60,\n }\n }\n }\n }\n // No product template designated, or none that renders: the store's\n // built-in product page (AGL-3676), in the site's own header and footer,\n // rather than a 404 behind every card the product grid links. A store a\n // guided start built has no template of its own, and its grid links each\n // product here.\n if (listedOnline) {\n return composeBuiltInProductPage(\n hostId,\n host,\n productSnapshot.docs[0].id,\n CommerceModel.liftLegacyProduct(productRaw),\n storeSettings.get('returns'),\n )\n }\n }\n // Commerce collection routes (AGL-298): /collections/{slug} renders\n // the designated collection template with collection tokens; the\n // product-grid block derives the same slug from the URL.\n if (pdpSegments.length === 2 && pdpSegments[0] === 'collections') {\n const adminFirestore = firebaseAdmin.app().firestore()\n const hostDocRef = adminFirestore.collection('hosts').doc(hostId)\n const [storeSettings, collectionSnapshot] = await Promise.all([\n hostDocRef.collection('settings').doc('store').get(),\n hostDocRef\n .collection('collections')\n .where('slug', '==', pdpSegments[1])\n .limit(5)\n .get(),\n ])\n const collectionScreenId = storeSettings.get('collectionScreenId')\n // Content collections share this path and a slug is only unique within a\n // kind (AGL-954), so take the first CATALOG match rather than the first\n // doc — otherwise a blog with the same slug renders as a product page.\n const shopCollection = collectionSnapshot.docs\n .find((docSnapshot) => hostCollectionKind(docSnapshot.data()) === 'catalog')\n ?.data() as CommerceModel.HostCollection | undefined\n if (collectionScreenId && shopCollection) {\n const templateRes = await getScreen({\n hostId,\n screenId: collectionScreenId,\n allowTemplate: true,\n })\n if (templateRes.screen) {\n // As on the PDP above: the template's image, then the site default\n // (AGL-2850).\n const card = collectSocialImageFacts([\n (templateRes.screen as any).seo?.image,\n hostRes.host?.seo?.image,\n ])\n const templateNodes = await composeScreenNodes({\n hostId,\n screenId: collectionScreenId,\n screen: templateRes.screen,\n socialImages: card.socialImages,\n // As on the PDP above (AGL-2883).\n host: hostRes.host,\n tokens: {\n 'collection.name': shopCollection.name,\n 'collection.description': shopCollection.description ?? '',\n 'collection.image': shopCollection.imageUrl ?? '',\n 'collection.slug': shopCollection.slug,\n },\n // As on the PDP above (AGL-3374).\n page: {\n template: {\n role: 'entry',\n route: '/collections/:slug',\n collectionName: 'Store collections',\n entryPath: `/collections/${shopCollection.slug}`,\n fallback: 'not-found',\n },\n },\n })\n if (templateNodes) {\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host: hostRes.host,\n screen: {\n data: {\n ...templateRes.screen,\n // As on the PDP above: the catalog collection names the\n // page, and a name takes the site title after it while\n // an authored SEO title would not (AGL-1341). A shop\n // collection has no SEO title field of its own, so the\n // template's must not stand in for one.\n displayName: shopCollection.name,\n seo: {\n ...((templateRes.screen as any).seo ?? {}),\n title: undefined,\n description:\n shopCollection.description ?? undefined,\n },\n },\n },\n },\n nodes: templateNodes,\n ...card.collected(),\n }),\n ),\n revalidate: 60,\n }\n }\n }\n }\n }\n return undefined\n}\n\n// What `{{product.price}}` says (AGL-3676) lives with the model now, so the\n// site's search can caption a product the same way without loading this page.\nexport { productPriceText } from '../model'\n\nconst PRODUCT_PAGE_NODE = 'pdp__detail'\nconst PRODUCT_PAGE_REVIEWS_NODE = 'pdp__reviews'\nconst PRODUCT_PAGE_RELATED_NODE = 'pdp__related'\n\n/**\n * The store's built-in product page (AGL-3676), root first, for the layout's\n * slot: the product block for the routed slug — with its Details and\n * Shipping & returns folds under the description, as a designer theme's\n * product page has them — then the product's reviews where the store's plan\n * collects them, then the related products as a grid of photo cards.\n */\nexport function buildProductPageNodes(\n slug: string,\n options: { reviews?: boolean } = {},\n): Record<string, Aglyn.AglynNodeSchema> {\n const reviews = Boolean(options.reviews)\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['pdp__container'],\n } as Aglyn.AglynNodeSchema,\n pdp__container: {\n $id: 'pdp__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'lg', sx: { paddingTop: 6, paddingBottom: 10 } },\n nodes: [\n PRODUCT_PAGE_NODE,\n ...(reviews ? [PRODUCT_PAGE_REVIEWS_NODE] : []),\n PRODUCT_PAGE_RELATED_NODE,\n ],\n } as Aglyn.AglynNodeSchema,\n [PRODUCT_PAGE_NODE]: {\n $id: PRODUCT_PAGE_NODE,\n parentId: 'pdp__container',\n componentId: 'product-detail',\n pluginId: 'commerce',\n props: { slug, showDetails: true, showShipping: true },\n } as Aglyn.AglynNodeSchema,\n ...(reviews\n ? {\n [PRODUCT_PAGE_REVIEWS_NODE]: {\n $id: PRODUCT_PAGE_REVIEWS_NODE,\n parentId: 'pdp__container',\n componentId: 'product-reviews',\n pluginId: 'commerce',\n props: { heading: 'Reviews', sx: { marginTop: 8 } },\n } as Aglyn.AglynNodeSchema,\n }\n : {}),\n [PRODUCT_PAGE_RELATED_NODE]: {\n $id: PRODUCT_PAGE_RELATED_NODE,\n parentId: 'pdp__container',\n componentId: 'related-products',\n pluginId: 'commerce',\n props: {\n heading: 'You may also like',\n maxItems: 4,\n layout: 'grid',\n sx: { marginTop: 8 },\n },\n } as Aglyn.AglynNodeSchema,\n }\n}\n\n/**\n * The store's return window for this product, when the store takes returns of\n * its kind: the settings the return form enforces (`readReturnSettings`), so\n * the page never states a policy the store does not keep.\n */\nexport function productReturnWindow(\n product: Pick<CommerceModel.HostProduct, 'type'>,\n rawReturns: unknown,\n): { windowDays: number } | undefined {\n const settings = CommerceModel.readReturnSettings(rawReturns)\n if (!settings.enabled || settings.windowDays <= 0) return undefined\n if (!settings.eligibleTypes.includes(product.type ?? 'physical')) return undefined\n return { windowDays: settings.windowDays }\n}\n\n/** Whether the store's plan collects reviews; a failed read leaves them off. */\nasync function storeTakesReviews(hostId: string): Promise<boolean> {\n try {\n const org = await getOrgForHost(hostId)\n return Aglyn.checkEntitlement(org?.org as never, 'productReviews')\n } catch (error) {\n console.error('reviews entitlement read failed', error)\n return false\n }\n}\n\nasync function composeBuiltInProductPage(\n hostId: string,\n host: unknown,\n productId: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n rawReturns?: unknown,\n) {\n try {\n const [layoutId, productReviews, reviewsOn] = await Promise.all([\n resolveBuiltInPageLayoutId({ hostId, host: host as never }),\n readProductReviews(hostId, productId).catch((error) => {\n console.error('product review aggregate failed', error)\n return { reviews: [], aggregate: { count: 0, average: 0 } }\n }),\n storeTakesReviews(hostId),\n ])\n const returns = productReturnWindow(product, rawReturns)\n const card = collectSocialImageFacts([\n product.mediaUrls?.[0] ?? product.imageUrl,\n (host as { seo?: { image?: string } } | null)?.seo?.image,\n ])\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildProductPageNodes(product.slug, { reviews: reviewsOn }),\n socialImages: card.socialImages,\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n // Seeded, so the product renders server-side and the head writes\n // its Product structured data, as on a template page (AGL-659).\n pageData: {\n commerce: {\n product: toPublicProductDetail(productId, product, {\n timeZone: await passDayTimeZone(hostId, host, product),\n }),\n ...(productReviews.aggregate.count ? { reviews: productReviews } : {}),\n // The Shipping & returns fold's return line, only when the\n // store takes returns of this product's kind.\n ...(returns ? { returns } : {}),\n },\n },\n data: {\n host,\n screen: {\n data: {\n displayName: product.name,\n seo: {\n title: product.seo?.title ?? undefined,\n description: product.seo?.description ?? product.description ?? undefined,\n },\n },\n },\n },\n nodes,\n ...card.collected(),\n }),\n ),\n revalidate: 60,\n }\n } catch (error) {\n console.error('built-in product page composition failed', error)\n return undefined\n }\n}\n\nconst ORDER_STATUS_NODE = 'order-status__block'\n\n/** The order-status page's node tree, root first, for the layout's slot. */\nexport function buildOrderStatusNodes(): Record<string, Aglyn.AglynNodeSchema> {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['order-status__container'],\n } as Aglyn.AglynNodeSchema,\n 'order-status__container': {\n $id: 'order-status__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'md', sx: { paddingTop: 6, paddingBottom: 8 } },\n nodes: [ORDER_STATUS_NODE],\n } as Aglyn.AglynNodeSchema,\n [ORDER_STATUS_NODE]: {\n $id: ORDER_STATUS_NODE,\n parentId: 'order-status__container',\n componentId: ORDER_STATUS_COMPONENT_ID,\n pluginId: 'commerce',\n props: {},\n } as Aglyn.AglynNodeSchema,\n }\n}\n\nasync function composeOrderStatusPage(hostId: string, host: unknown) {\n try {\n const layoutId = await resolveBuiltInPageLayoutId({ hostId, host: host as never })\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildOrderStatusNodes(),\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host,\n screen: {\n data: {\n displayName: 'Order status',\n visibility: Aglyn.HostScreenVisibility.UNLISTED,\n },\n },\n },\n nodes,\n }),\n ),\n revalidate: 3600,\n }\n } catch (error) {\n console.error('order status page composition failed', error)\n return undefined\n }\n}\n\nconst RETURN_REQUEST_NODE = 'ret__block'\n\n/** The return form's node tree, root first, for the layout's slot. */\nexport function buildReturnRequestNodes(): Record<string, Aglyn.AglynNodeSchema> {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['ret__container'],\n } as Aglyn.AglynNodeSchema,\n ret__container: {\n $id: 'ret__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'md', sx: { paddingTop: 6, paddingBottom: 8 } },\n nodes: [RETURN_REQUEST_NODE],\n } as Aglyn.AglynNodeSchema,\n [RETURN_REQUEST_NODE]: {\n $id: RETURN_REQUEST_NODE,\n parentId: 'ret__container',\n componentId: RETURN_REQUEST_COMPONENT_ID,\n pluginId: 'commerce',\n props: {},\n } as Aglyn.AglynNodeSchema,\n }\n}\n\nasync function composeReturnRequestPage(hostId: string, host: unknown) {\n try {\n const layoutId = await resolveBuiltInPageLayoutId({ hostId, host: host as never })\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildReturnRequestNodes(),\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host,\n screen: {\n data: {\n displayName: 'Request a return',\n visibility: Aglyn.HostScreenVisibility.UNLISTED,\n },\n },\n },\n nodes,\n }),\n ),\n revalidate: 3600,\n }\n } catch (error) {\n console.error('return request page composition failed', error)\n return undefined\n }\n}\n\nconst QUOTE_PAGE_NODE = 'quote-page__block'\n\n/** The quote page's node tree, root first, for the layout's slot. */\nexport function buildQuotePageNodes(): Record<string, Aglyn.AglynNodeSchema> {\n return {\n [Aglyn.NODE_ROOT_ID]: {\n $id: Aglyn.NODE_ROOT_ID,\n componentId: 'div',\n nodes: ['quote-page__container'],\n } as Aglyn.AglynNodeSchema,\n 'quote-page__container': {\n $id: 'quote-page__container',\n parentId: Aglyn.NODE_ROOT_ID,\n componentId: 'muiContainer',\n pluginId: 'mui',\n props: { maxWidth: 'md', sx: { paddingTop: 6, paddingBottom: 8 } },\n nodes: [QUOTE_PAGE_NODE],\n } as Aglyn.AglynNodeSchema,\n [QUOTE_PAGE_NODE]: {\n $id: QUOTE_PAGE_NODE,\n parentId: 'quote-page__container',\n componentId: QUOTE_PAGE_COMPONENT_ID,\n pluginId: 'commerce',\n props: {},\n } as Aglyn.AglynNodeSchema,\n }\n}\n\nasync function composeQuotePage(hostId: string, host: unknown) {\n try {\n const layoutId = await resolveBuiltInPageLayoutId({ hostId, host: host as never })\n const nodes = await composeNodesWithChrome({\n hostId,\n layoutId,\n screenNodes: buildQuotePageNodes(),\n host: host as Aglyn.HostTokenSource,\n })\n if (!nodes) return undefined\n return {\n props: JSON.parse(\n JSON.stringify({\n data: {\n host,\n screen: {\n data: {\n // The page is the same for a quote's link and an invoice's (AGL-4099).\n displayName: 'Your quote or invoice',\n visibility: Aglyn.HostScreenVisibility.UNLISTED,\n },\n },\n },\n nodes,\n }),\n ),\n revalidate: 3600,\n }\n } catch (error) {\n console.error('quote page composition failed', error)\n return undefined\n }\n}\n\n/**\n * The store's time zone for a product page whose product asks for a use day\n * (AGL-4043), so the seeded page offers the same days the API's does; null\n * otherwise, without a read.\n */\nasync function passDayTimeZone(\n hostId: string,\n host: unknown,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n): Promise<string | null> {\n if (!productAsksUseDateAnywhere(product)) return null\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n return (await readStoreDay(hostRef, { host: (host ?? null) as Record<string, unknown> | null })).timeZone\n}\n"],"names":["hostCollectionKind","composeScreenNodes","composeNodesWithChrome","resolveBuiltInPageLayoutId","Aglyn","ORDER_STATUS_PATH","ORDER_STATUS_COMPONENT_ID","RETURN_REQUEST_COMPONENT_ID","RETURN_REQUEST_PATH","QUOTE_PAGE_COMPONENT_ID","QUOTE_PAGE_PATH","getScreen","collectSocialImageFacts","firebaseAdmin","getOrgForHost","CommerceModel","productAsksUseDateAnywhere","toPublicProductDetail","readStoreDay","readProductReviews","commerceSitePageResolver","hostId","host","path","hostRes","pdpSegments","split","filter","Boolean","length","composeOrderStatusPage","composeReturnRequestPage","composeQuotePage","productSnapshot","adminFirestore","app","firestore","hostDocRef","collection","doc","storeSettings","Promise","all","get","where","limit","pdpScreenId","productRaw","docs","data","listedOnline","productListedOnline","product","liftLegacyProduct","templateRes","screenId","allowTemplate","screen","minPrice","maxPrice","productPriceRange","productReviews","id","catch","error","console","reviews","aggregate","count","average","card","seo","image","templateNodes","socialImages","tokens","name","description","productPriceText","mediaUrls","imageUrl","slug","page","template","role","route","collectionName","entryPath","fallback","props","JSON","parse","stringify","pageData","commerce","timeZone","passDayTimeZone","displayName","title","undefined","nodes","collected","revalidate","composeBuiltInProductPage","collectionSnapshot","collectionScreenId","shopCollection","find","docSnapshot","PRODUCT_PAGE_NODE","PRODUCT_PAGE_REVIEWS_NODE","PRODUCT_PAGE_RELATED_NODE","buildProductPageNodes","options","NODE_ROOT_ID","$id","componentId","pdp__container","parentId","pluginId","maxWidth","sx","paddingTop","paddingBottom","showDetails","showShipping","heading","marginTop","maxItems","layout","productReturnWindow","rawReturns","settings","readReturnSettings","enabled","windowDays","eligibleTypes","includes","type","storeTakesReviews","org","checkEntitlement","productId","layoutId","reviewsOn","returns","screenNodes","ORDER_STATUS_NODE","buildOrderStatusNodes","visibility","HostScreenVisibility","UNLISTED","RETURN_REQUEST_NODE","buildReturnRequestNodes","ret__container","QUOTE_PAGE_NODE","buildQuotePageNodes","hostRef"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,kBAAkB,QAAQ,sBAAqB;AACxD,OAAOC,sBACLC,sBAAsB,QACjB,6CAA4C;AACnD,SAASC,0BAA0B,QAAQ,6CAA4C;AACvF,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAASC,2BAA2B,EAAEC,mBAAmB,QAAQ,iCAA6B;AAC9F,SA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AACF;AAEA;;;;CAIC,GACD,eAAeH,gBACb3E,MAAc,EACdC,IAAa,EACb8B,OAA2D;IAE3D,IAAI,CAACpC,2BAA2BoC,UAAU,OAAO;IACjD,MAAMyG,UAAUhJ,cAAcsB,GAAG,GAAGC,SAAS,GAAGE,UAAU,CAAC,SAASC,GAAG,CAAClB;IACxE,OAAO,AAAC,CAAA,MAAMH,aAAa2I,SAAS;QAAEvI,IAAI,EAAGA,eAAAA,OAAQ;IAAwC,EAAC,EAAGyE,QAAQ;AAC3G"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { PluginSiteSearchItem, PluginSiteSearchSource } from '@aglyn/aglyn/plugin-manager/plugin-site-search';
18
+ /**
19
+ * THE STORE'S PRODUCTS IN THE SITE'S OWN SEARCH: core's `core.site-search`
20
+ * contract, answered from this plugin's products.
21
+ *
22
+ * What a visitor may find is what the storefront lists: live, active and
23
+ * sold online (`productListedOnline`), and never a guided start's sample.
24
+ * The search page matches the typed words; this only hands it candidates.
25
+ *
26
+ * Two bounded reads, merged:
27
+ *
28
+ * - the storefront's own scope (`deletedAt == null`, `status == 'active'`),
29
+ * capped at {@link SCAN_LIMIT} products, which the search page's fuzzy
30
+ * matcher forgives a typo over;
31
+ * - the products whose name has a word starting with the query's first word
32
+ * (`nameTokens`, the storefront grid's search key), so a catalog larger
33
+ * than the scan still finds a product by its name.
34
+ *
35
+ * Category names are read only when a candidate names a category.
36
+ */
37
+ /** Products the scope read reaches; a store's whole catalog, for most. */
38
+ export declare const SCAN_LIMIT = 250;
39
+ /** Products the name-token read reaches beyond the scan. */
40
+ export declare const TOKEN_LIMIT = 50;
41
+ /** One listed product as the search page matches and shows it, or `null`. */
42
+ export declare function productSiteSearchItem(productId: string, data: Record<string, any>, categoryNames?: ReadonlyMap<string, string>): PluginSiteSearchItem | null;
43
+ export declare const commerceSiteSearch: PluginSiteSearchSource;
@@ -0,0 +1,124 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { nameSearchToken } from "@aglyn/aglyn/app-utils/name-search";
18
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
19
+ import * as CommerceModel from "../model/index.js";
20
+ import { productCard } from "./product-card.js";
21
+ import { plainDescription } from "./product-catalog.js";
22
+ /**
23
+ * THE STORE'S PRODUCTS IN THE SITE'S OWN SEARCH: core's `core.site-search`
24
+ * contract, answered from this plugin's products.
25
+ *
26
+ * What a visitor may find is what the storefront lists: live, active and
27
+ * sold online (`productListedOnline`), and never a guided start's sample.
28
+ * The search page matches the typed words; this only hands it candidates.
29
+ *
30
+ * Two bounded reads, merged:
31
+ *
32
+ * - the storefront's own scope (`deletedAt == null`, `status == 'active'`),
33
+ * capped at {@link SCAN_LIMIT} products, which the search page's fuzzy
34
+ * matcher forgives a typo over;
35
+ * - the products whose name has a word starting with the query's first word
36
+ * (`nameTokens`, the storefront grid's search key), so a catalog larger
37
+ * than the scan still finds a product by its name.
38
+ *
39
+ * Category names are read only when a candidate names a category.
40
+ */ /** Products the scope read reaches; a store's whole catalog, for most. */ export const SCAN_LIMIT = 250;
41
+ /** Products the name-token read reaches beyond the scan. */ export const TOKEN_LIMIT = 50;
42
+ /** Categories read for their names. */ const CATEGORY_LIMIT = 200;
43
+ const SNIPPET_LENGTH = 160;
44
+ const str = (value)=>typeof value === 'string' ? value : '';
45
+ const isDocumentId = (value)=>Boolean(value) && value.length <= 200 && !value.includes('/') && !/^__.*__$/.test(value);
46
+ /** One listed product as the search page matches and shows it, or `null`. */ export function productSiteSearchItem(productId, data, categoryNames = new Map()) {
47
+ var _product_variants;
48
+ if (!CommerceModel.productListedOnline(data)) return null;
49
+ if (CommerceModel.productIsSample(data)) return null;
50
+ const card = productCard(productId, data);
51
+ // A product with no slug has no page, so there is nothing to link to.
52
+ if (!card.path) return null;
53
+ const product = CommerceModel.liftLegacyProduct(data);
54
+ const [minPrice, maxPrice] = CommerceModel.productPriceRange(product);
55
+ const description = plainDescription(data['description']);
56
+ const words = (values)=>Array.isArray(values) ? values.map(str).filter(Boolean) : [];
57
+ const terms = [
58
+ description,
59
+ str(data['slug']),
60
+ ...((_product_variants = product.variants) != null ? _product_variants : []).map((variant)=>str(variant.sku)).filter(Boolean),
61
+ ...words(data['tags']),
62
+ ...words(data['categoryIds']).map((id)=>{
63
+ var _categoryNames_get;
64
+ return (_categoryNames_get = categoryNames.get(id)) != null ? _categoryNames_get : '';
65
+ }).filter(Boolean)
66
+ ].filter(Boolean);
67
+ return _extends({
68
+ title: card.title,
69
+ terms,
70
+ url: card.path,
71
+ snippet: description.replace(/\s+/g, ' ').slice(0, SNIPPET_LENGTH)
72
+ }, card.imageUrl ? {
73
+ imageUrl: String(card.imageUrl)
74
+ } : {}, {
75
+ caption: CommerceModel.productPriceText(product, minPrice, maxPrice)
76
+ });
77
+ }
78
+ export const commerceSiteSearch = {
79
+ key: 'products',
80
+ label: 'Products',
81
+ async items ({ hostId, query, limit }) {
82
+ var _ref;
83
+ if (!isDocumentId(hostId)) return [];
84
+ const products = firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('products');
85
+ const token = nameSearchToken(query);
86
+ const [scoped, named] = await Promise.all([
87
+ products.where('deletedAt', '==', null).where('status', '==', 'active').limit(SCAN_LIMIT).get(),
88
+ token ? products.where('nameTokens', 'array-contains', token).limit(TOKEN_LIMIT).get() : Promise.resolve(null)
89
+ ]);
90
+ const byId = new Map();
91
+ for (const doc of [
92
+ ...(_ref = named == null ? void 0 : named.docs) != null ? _ref : [],
93
+ ...scoped.docs
94
+ ]){
95
+ if (!byId.has(doc.id)) byId.set(doc.id, doc.data());
96
+ }
97
+ const wantsCategories = [
98
+ ...byId.values()
99
+ ].some((data)=>Array.isArray(data['categoryIds']) && data['categoryIds'].length > 0);
100
+ const categoryNames = new Map();
101
+ if (wantsCategories) {
102
+ try {
103
+ const categories = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('productCategories').limit(CATEGORY_LIMIT).get();
104
+ for (const doc of categories.docs){
105
+ const name = str(doc.get('name')).trim();
106
+ if (name) categoryNames.set(doc.id, name);
107
+ }
108
+ } catch (error) {
109
+ // A category read that fails costs the search its category names,
110
+ // not its products.
111
+ console.error(error);
112
+ }
113
+ }
114
+ const items = [];
115
+ for (const [id, data] of byId){
116
+ const item = productSiteSearchItem(id, data, categoryNames);
117
+ if (item) items.push(item);
118
+ if (items.length >= limit) break;
119
+ }
120
+ return items;
121
+ }
122
+ };
123
+
124
+ //# sourceMappingURL=site-search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/site-search.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 { nameSearchToken } from '@aglyn/aglyn/app-utils/name-search'\nimport type {\n PluginSiteSearchItem,\n PluginSiteSearchSource,\n} from '@aglyn/aglyn/plugin-manager/plugin-site-search'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport * as CommerceModel from '../model'\nimport { productCard } from './product-card'\nimport { plainDescription } from './product-catalog'\n\n/**\n * THE STORE'S PRODUCTS IN THE SITE'S OWN SEARCH: core's `core.site-search`\n * contract, answered from this plugin's products.\n *\n * What a visitor may find is what the storefront lists: live, active and\n * sold online (`productListedOnline`), and never a guided start's sample.\n * The search page matches the typed words; this only hands it candidates.\n *\n * Two bounded reads, merged:\n *\n * - the storefront's own scope (`deletedAt == null`, `status == 'active'`),\n * capped at {@link SCAN_LIMIT} products, which the search page's fuzzy\n * matcher forgives a typo over;\n * - the products whose name has a word starting with the query's first word\n * (`nameTokens`, the storefront grid's search key), so a catalog larger\n * than the scan still finds a product by its name.\n *\n * Category names are read only when a candidate names a category.\n */\n\n/** Products the scope read reaches; a store's whole catalog, for most. */\nexport const SCAN_LIMIT = 250\n/** Products the name-token read reaches beyond the scan. */\nexport const TOKEN_LIMIT = 50\n/** Categories read for their names. */\nconst CATEGORY_LIMIT = 200\n\nconst SNIPPET_LENGTH = 160\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value : '')\n\nconst isDocumentId = (value: string) =>\n Boolean(value) &&\n value.length <= 200 &&\n !value.includes('/') &&\n !/^__.*__$/.test(value)\n\n/** One listed product as the search page matches and shows it, or `null`. */\nexport function productSiteSearchItem(\n productId: string,\n data: Record<string, any>,\n categoryNames: ReadonlyMap<string, string> = new Map(),\n): PluginSiteSearchItem | null {\n if (!CommerceModel.productListedOnline(data)) return null\n if (CommerceModel.productIsSample(data)) return null\n const card = productCard(productId, data)\n // A product with no slug has no page, so there is nothing to link to.\n if (!card.path) return null\n const product = CommerceModel.liftLegacyProduct(\n data as CommerceModel.HostProduct,\n )\n const [minPrice, maxPrice] = CommerceModel.productPriceRange(product)\n const description = plainDescription(data['description'])\n const words = (values: unknown) =>\n Array.isArray(values) ? values.map(str).filter(Boolean) : []\n const terms = [\n description,\n str(data['slug']),\n ...(product.variants ?? [])\n .map((variant) => str(variant.sku))\n .filter(Boolean),\n ...words(data['tags']),\n ...words(data['categoryIds'])\n .map((id) => categoryNames.get(id) ?? '')\n .filter(Boolean),\n ].filter(Boolean)\n return {\n title: card.title,\n terms,\n url: card.path,\n snippet: description.replace(/\\s+/g, ' ').slice(0, SNIPPET_LENGTH),\n ...(card.imageUrl ? { imageUrl: String(card.imageUrl) } : {}),\n caption: CommerceModel.productPriceText(product, minPrice, maxPrice),\n }\n}\n\nexport const commerceSiteSearch: PluginSiteSearchSource = {\n key: 'products',\n label: 'Products',\n async items({ hostId, query, limit }) {\n if (!isDocumentId(hostId)) return []\n const products = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n const token = nameSearchToken(query)\n const [scoped, named] = await Promise.all([\n products\n .where('deletedAt', '==', null)\n .where('status', '==', 'active')\n .limit(SCAN_LIMIT)\n .get(),\n token\n ? products\n .where('nameTokens', 'array-contains', token)\n .limit(TOKEN_LIMIT)\n .get()\n : Promise.resolve(null),\n ])\n const byId = new Map<string, Record<string, any>>()\n for (const doc of [...(named?.docs ?? []), ...scoped.docs]) {\n if (!byId.has(doc.id)) byId.set(doc.id, doc.data() as Record<string, any>)\n }\n const wantsCategories = [...byId.values()].some(\n (data) =>\n Array.isArray(data['categoryIds']) && data['categoryIds'].length > 0,\n )\n const categoryNames = new Map<string, string>()\n if (wantsCategories) {\n try {\n const categories = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('productCategories')\n .limit(CATEGORY_LIMIT)\n .get()\n for (const doc of categories.docs) {\n const name = str(doc.get('name')).trim()\n if (name) categoryNames.set(doc.id, name)\n }\n } catch (error) {\n // A category read that fails costs the search its category names,\n // not its products.\n console.error(error)\n }\n }\n const items: PluginSiteSearchItem[] = []\n for (const [id, data] of byId) {\n const item = productSiteSearchItem(id, data, categoryNames)\n if (item) items.push(item)\n if (items.length >= limit) break\n }\n return items\n },\n}\n"],"names":["nameSearchToken","firebaseAdmin","CommerceModel","productCard","plainDescription","SCAN_LIMIT","TOKEN_LIMIT","CATEGORY_LIMIT","SNIPPET_LENGTH","str","value","isDocumentId","Boolean","length","includes","test","productSiteSearchItem","productId","data","categoryNames","Map","product","productListedOnline","productIsSample","card","path","liftLegacyProduct","minPrice","maxPrice","productPriceRange","description","words","values","Array","isArray","map","filter","terms","variants","variant","sku","id","get","title","url","snippet","replace","slice","imageUrl","String","caption","productPriceText","commerceSiteSearch","key","label","items","hostId","query","limit","products","app","firestore","collection","doc","token","scoped","named","Promise","all","where","resolve","byId","docs","has","set","wantsCategories","some","categories","name","trim","error","console","item","push"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,qCAAoC;AAKpE,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,WAAW,QAAQ,oBAAgB;AAC5C,SAASC,gBAAgB,QAAQ,uBAAmB;AAEpD;;;;;;;;;;;;;;;;;;CAkBC,GAED,wEAAwE,GACxE,OAAO,MAAMC,aAAa,IAAG;AAC7B,0DAA0D,GAC1D,OAAO,MAAMC,cAAc,GAAE;AAC7B,qCAAqC,GACrC,MAAMC,iBAAiB;AAEvB,MAAMC,iBAAiB;AAEvB,MAAMC,MAAM,CAACC,QAA4B,OAAOA,UAAU,WAAWA,QAAQ;AAE7E,MAAMC,eAAe,CAACD,QACpBE,QAAQF,UACRA,MAAMG,MAAM,IAAI,OAChB,CAACH,MAAMI,QAAQ,CAAC,QAChB,CAAC,WAAWC,IAAI,CAACL;AA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AAG;gBACN,KAAK,MAAMqB,OAAOc,WAAWL,IAAI,CAAE;oBACjC,MAAMM,OAAOrE,IAAIsD,IAAIrB,GAAG,CAAC,SAASqC,IAAI;oBACtC,IAAID,MAAM3D,cAAcuD,GAAG,CAACX,IAAItB,EAAE,EAAEqC;gBACtC;YACF,EAAE,OAAOE,OAAO;gBACd,kEAAkE;gBAClE,oBAAoB;gBACpBC,QAAQD,KAAK,CAACA;YAChB;QACF;QACA,MAAMzB,QAAgC,EAAE;QACxC,KAAK,MAAM,CAACd,IAAIvB,KAAK,IAAIqD,KAAM;YAC7B,MAAMW,OAAOlE,sBAAsByB,IAAIvB,MAAMC;YAC7C,IAAI+D,MAAM3B,MAAM4B,IAAI,CAACD;YACrB,IAAI3B,MAAM1C,MAAM,IAAI6C,OAAO;QAC7B;QACA,OAAOH;IACT;AACF,EAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type SellerStripeTaxStatus } from '../model/commerce-tax-readiness';
18
+ /**
19
+ * Whether sales tax lets shoppers check out (AGL-4245):
20
+ * `GET /api/commerce/tax-readiness?hostId=…[&fresh=1]`, served by the console
21
+ * for the Taxes card and the Payments card's notice.
22
+ *
23
+ * Answers a {@link StoreTaxReadiness}: the saved tax mode, whether the store
24
+ * sells on its own Stripe account, that account's Stripe Tax (read with the
25
+ * same `tax/settings` call checkout makes, plus whether any registration is
26
+ * active), and whether checkout is refusing every shopper because of tax.
27
+ *
28
+ * Reading it as not blocked drops the refusal marker
29
+ * (`checkout-tax-refusal.ts`), which is how the owner's alert clears once a
30
+ * mode is chosen or Stripe Tax is on.
31
+ *
32
+ * Who may ask: whoever may read the payment methods card (works the store's
33
+ * orders, or manages its payment methods). A 404 otherwise, so the route
34
+ * never confirms a site exists.
35
+ */
36
+ /** How long one account's Stripe Tax answer is reused, so a card's render does not call Stripe each time. */
37
+ export declare const SELLER_STRIPE_TAX_CACHE_MS = 60000;
38
+ /** The shortest gap between two reads that "Check again" forces. */
39
+ export declare const SELLER_STRIPE_TAX_FRESH_MIN_MS = 5000;
40
+ /** Test seam: forget every cached answer. */
41
+ export declare function resetSellerStripeTaxCacheForTests(): void;
42
+ export interface TaxReadinessReadDeps {
43
+ settings(account: string): Promise<Record<string, unknown> | null>;
44
+ registration(account: string): Promise<boolean | null>;
45
+ now(): number;
46
+ }
47
+ /**
48
+ * The seller's Stripe Tax, cached per account for
49
+ * {@link SELLER_STRIPE_TAX_CACHE_MS}. `fresh` skips the cache unless the
50
+ * cached answer is younger than {@link SELLER_STRIPE_TAX_FRESH_MIN_MS}. An
51
+ * unreadable answer is not cached, so the next paint asks again.
52
+ */
53
+ export declare function cachedSellerStripeTaxStatus(account: string, options?: {
54
+ fresh?: boolean;
55
+ }, deps?: TaxReadinessReadDeps): Promise<SellerStripeTaxStatus>;
56
+ export declare function taxReadinessHandler(request: Request): Promise<Response>;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { checkEntitlement, pluginRequestFromWeb } from "@aglyn/aglyn/server";
17
+ import { emailUnverifiedResponse, firebaseAdmin, getOrgForHost, isImpersonationSession, lockdownRefusal } from "@aglyn/tenant-data-admin";
18
+ import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
19
+ import { checkoutTaxBlock, stripeTaxStatusFromSettings } from "../model/commerce-tax-readiness.js";
20
+ import { clearCheckoutTaxRefusal, readCheckoutTaxRefusal } from "./checkout-tax-refusal.js";
21
+ import { holdsCommerceSiteKey } from "./commerce-site-keys.js";
22
+ import { directSellerAccountForHost, fetchSellerStripeTaxSettings, sellerHasActiveTaxRegistration } from "./seller-stripe-account.js";
23
+ /**
24
+ * Whether sales tax lets shoppers check out (AGL-4245):
25
+ * `GET /api/commerce/tax-readiness?hostId=…[&fresh=1]`, served by the console
26
+ * for the Taxes card and the Payments card's notice.
27
+ *
28
+ * Answers a {@link StoreTaxReadiness}: the saved tax mode, whether the store
29
+ * sells on its own Stripe account, that account's Stripe Tax (read with the
30
+ * same `tax/settings` call checkout makes, plus whether any registration is
31
+ * active), and whether checkout is refusing every shopper because of tax.
32
+ *
33
+ * Reading it as not blocked drops the refusal marker
34
+ * (`checkout-tax-refusal.ts`), which is how the owner's alert clears once a
35
+ * mode is chosen or Stripe Tax is on.
36
+ *
37
+ * Who may ask: whoever may read the payment methods card (works the store's
38
+ * orders, or manages its payment methods). A 404 otherwise, so the route
39
+ * never confirms a site exists.
40
+ */ /** How long one account's Stripe Tax answer is reused, so a card's render does not call Stripe each time. */ export const SELLER_STRIPE_TAX_CACHE_MS = 60000;
41
+ /** The shortest gap between two reads that "Check again" forces. */ export const SELLER_STRIPE_TAX_FRESH_MIN_MS = 5000;
42
+ const statusCache = new Map();
43
+ const CACHE_MAX = 500;
44
+ /** Test seam: forget every cached answer. */ export function resetSellerStripeTaxCacheForTests() {
45
+ statusCache.clear();
46
+ }
47
+ const defaultReadDeps = {
48
+ settings: fetchSellerStripeTaxSettings,
49
+ registration: sellerHasActiveTaxRegistration,
50
+ now: ()=>Date.now()
51
+ };
52
+ /**
53
+ * The seller's Stripe Tax, cached per account for
54
+ * {@link SELLER_STRIPE_TAX_CACHE_MS}. `fresh` skips the cache unless the
55
+ * cached answer is younger than {@link SELLER_STRIPE_TAX_FRESH_MIN_MS}. An
56
+ * unreadable answer is not cached, so the next paint asks again.
57
+ */ export async function cachedSellerStripeTaxStatus(account, options = {}, deps = defaultReadDeps) {
58
+ const now = deps.now();
59
+ const cached = statusCache.get(account);
60
+ const maxAge = options.fresh ? SELLER_STRIPE_TAX_FRESH_MIN_MS : SELLER_STRIPE_TAX_CACHE_MS;
61
+ if (cached && now - cached.at < maxAge) return cached.value;
62
+ const [settings, registration] = await Promise.all([
63
+ deps.settings(account),
64
+ deps.registration(account)
65
+ ]);
66
+ const value = stripeTaxStatusFromSettings(settings, registration);
67
+ if (value.readable) {
68
+ if (statusCache.size >= CACHE_MAX) statusCache.clear();
69
+ statusCache.set(account, {
70
+ at: now,
71
+ value
72
+ });
73
+ } else {
74
+ statusCache.delete(account);
75
+ }
76
+ return value;
77
+ }
78
+ const json = (body, status = 200)=>Response.json(body, {
79
+ status
80
+ });
81
+ const savedMode = (tax)=>{
82
+ const mode = tax == null ? void 0 : tax.mode;
83
+ return mode === 'manual' || mode === 'stripe' || mode === 'none' ? mode : null;
84
+ };
85
+ export async function taxReadinessHandler(request) {
86
+ var _headers_authorization, _ref, _ref1;
87
+ const { method, headers: rawHeaders, query } = await pluginRequestFromWeb(request);
88
+ const headers = rawHeaders;
89
+ if (method !== 'GET') return json({
90
+ error: 'Method not allowed'
91
+ }, 405);
92
+ const authorization = (_headers_authorization = headers.authorization) != null ? _headers_authorization : '';
93
+ const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;
94
+ if (!idToken) return json({
95
+ error: 'Unauthenticated'
96
+ }, 401);
97
+ const hostId = String((_ref = query == null ? void 0 : query['hostId']) != null ? _ref : '');
98
+ if (!hostId) return json({
99
+ error: 'Missing hostId'
100
+ }, 400);
101
+ const fresh = String((_ref1 = query == null ? void 0 : query['fresh']) != null ? _ref1 : '') === '1';
102
+ try {
103
+ var _ref2;
104
+ const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
105
+ if (!decoded.email_verified && !isImpersonationSession(decoded)) {
106
+ return emailUnverifiedResponse();
107
+ }
108
+ const firestore = firebaseAdmin.app().firestore();
109
+ const hostRef = firestore.collection('hosts').doc(hostId);
110
+ const hostSnapshot = await hostRef.get();
111
+ if (!hostSnapshot.exists) return json({
112
+ error: 'Not found'
113
+ }, 404);
114
+ const mayRead = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods') || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders');
115
+ if (!mayRead) return json({
116
+ error: 'Not found'
117
+ }, 404);
118
+ const owner = await getOrgForHost(hostId);
119
+ const locked = await lockdownRefusal({
120
+ request,
121
+ staff: decoded['staff'] === true,
122
+ uid: decoded.uid,
123
+ org: owner == null ? void 0 : owner.org,
124
+ host: hostSnapshot.data()
125
+ });
126
+ if (locked) return locked;
127
+ if (!checkEntitlement((_ref2 = owner == null ? void 0 : owner.org) != null ? _ref2 : {}, 'commerce')) {
128
+ return json({
129
+ error: 'Selling is not included on this plan'
130
+ }, 402);
131
+ }
132
+ const store = await hostRef.collection('settings').doc('store').get();
133
+ const mode = savedMode(store.get('tax'));
134
+ const account = await directSellerAccountForHost(hostId);
135
+ const stripeTax = account ? await cachedSellerStripeTaxStatus(account, {
136
+ fresh
137
+ }) : null;
138
+ const blocked = checkoutTaxBlock({
139
+ mode,
140
+ direct: Boolean(account),
141
+ stripeTax
142
+ });
143
+ let refusedAtMs = null;
144
+ if (blocked) {
145
+ const marker = await readCheckoutTaxRefusal(firestore, hostId);
146
+ refusedAtMs = (marker == null ? void 0 : marker.reason) === blocked && Number.isFinite(Number(marker.lastAtMs)) ? Number(marker.lastAtMs) : null;
147
+ } else {
148
+ // Fixed: the next refusal, if the store ever breaks again, tells the owner again.
149
+ await clearCheckoutTaxRefusal(firestore, hostId);
150
+ }
151
+ const answer = {
152
+ mode,
153
+ direct: Boolean(account),
154
+ stripeTax,
155
+ blocked,
156
+ refusedAtMs
157
+ };
158
+ return json(answer);
159
+ } catch (error) {
160
+ const refused = invalidIdTokenResponse(error);
161
+ if (refused) return refused;
162
+ console.error('[commerce] tax readiness failed', hostId, error);
163
+ return json({
164
+ error: 'Could not check sales tax setup'
165
+ }, 500);
166
+ }
167
+ }
168
+
169
+ //# sourceMappingURL=tax-readiness.js.map