@aglyn/plugins-commerce 1.15.0 → 1.15.1

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 (87) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +8 -3
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  6. package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
  7. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/subscriptions-card.component.js +4 -2
  9. package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
  10. package/src/lib/components/product-detail.js +7 -3
  11. package/src/lib/components/product-detail.js.map +1 -1
  12. package/src/lib/components/quote-page-body.js +7 -3
  13. package/src/lib/components/quote-page-body.js.map +1 -1
  14. package/src/lib/components/related-products.js +6 -3
  15. package/src/lib/components/related-products.js.map +1 -1
  16. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  17. package/src/lib/components/storefront-payment-element.js +11 -7
  18. package/src/lib/components/storefront-payment-element.js.map +1 -1
  19. package/src/lib/model/commerce-payment-methods.d.ts +26 -39
  20. package/src/lib/model/commerce-payment-methods.js +11 -118
  21. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  22. package/src/lib/server/billing-webhook.d.ts +23 -0
  23. package/src/lib/server/billing-webhook.js +162 -30
  24. package/src/lib/server/billing-webhook.js.map +1 -1
  25. package/src/lib/server/cancel-order.js +4 -3
  26. package/src/lib/server/cancel-order.js.map +1 -1
  27. package/src/lib/server/cart-checkout.js +61 -14
  28. package/src/lib/server/cart-checkout.js.map +1 -1
  29. package/src/lib/server/catalog.js +58 -22
  30. package/src/lib/server/catalog.js.map +1 -1
  31. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  32. package/src/lib/server/checkout-session-expiry.js +19 -5
  33. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  34. package/src/lib/server/checkout-status.js +4 -3
  35. package/src/lib/server/checkout-status.js.map +1 -1
  36. package/src/lib/server/checkout.js +42 -12
  37. package/src/lib/server/checkout.js.map +1 -1
  38. package/src/lib/server/connect.js +42 -11
  39. package/src/lib/server/connect.js.map +1 -1
  40. package/src/lib/server/draft-order.js +37 -12
  41. package/src/lib/server/draft-order.js.map +1 -1
  42. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  43. package/src/lib/server/manual-tax-rate.js +10 -6
  44. package/src/lib/server/manual-tax-rate.js.map +1 -1
  45. package/src/lib/server/native-checkout.d.ts +10 -3
  46. package/src/lib/server/native-checkout.js +8 -3
  47. package/src/lib/server/native-checkout.js.map +1 -1
  48. package/src/lib/server/payment-method-domains.d.ts +50 -9
  49. package/src/lib/server/payment-method-domains.js +150 -51
  50. package/src/lib/server/payment-method-domains.js.map +1 -1
  51. package/src/lib/server/payment-methods.js +3 -2
  52. package/src/lib/server/payment-methods.js.map +1 -1
  53. package/src/lib/server/pos-order.js +5 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/pos-stripe.d.ts +7 -7
  56. package/src/lib/server/pos-stripe.js +15 -13
  57. package/src/lib/server/pos-stripe.js.map +1 -1
  58. package/src/lib/server/pos-terminal.js +11 -3
  59. package/src/lib/server/pos-terminal.js.map +1 -1
  60. package/src/lib/server/quote-pay.d.ts +23 -1
  61. package/src/lib/server/quote-pay.js +112 -32
  62. package/src/lib/server/quote-pay.js.map +1 -1
  63. package/src/lib/server/quote.d.ts +2 -1
  64. package/src/lib/server/quote.js +12 -11
  65. package/src/lib/server/quote.js.map +1 -1
  66. package/src/lib/server/refund.js +13 -6
  67. package/src/lib/server/refund.js.map +1 -1
  68. package/src/lib/server/related.js +10 -3
  69. package/src/lib/server/related.js.map +1 -1
  70. package/src/lib/server/reserve.js +19 -6
  71. package/src/lib/server/reserve.js.map +1 -1
  72. package/src/lib/server/revenue-source.d.ts +6 -0
  73. package/src/lib/server/revenue-source.js +25 -9
  74. package/src/lib/server/revenue-source.js.map +1 -1
  75. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  76. package/src/lib/server/seller-stripe-account.js +99 -0
  77. package/src/lib/server/seller-stripe-account.js.map +1 -0
  78. package/src/lib/server/storefront-tax-record.js +6 -1
  79. package/src/lib/server/storefront-tax-record.js.map +1 -1
  80. package/src/lib/server/storefront-tax.d.ts +33 -2
  81. package/src/lib/server/storefront-tax.js +39 -3
  82. package/src/lib/server/storefront-tax.js.map +1 -1
  83. package/src/lib/server/stripe-refund.d.ts +15 -0
  84. package/src/lib/server/stripe-refund.js +54 -26
  85. package/src/lib/server/stripe-refund.js.map +1 -1
  86. package/src/lib/server/subscription-portal.js +8 -3
  87. package/src/lib/server/subscription-portal.js.map +1 -1
@@ -58,13 +58,25 @@ import * as CommerceModel from "../model/index.js";
58
58
  */ const MANUAL_COLLECTION_MAX = 1000;
59
59
  /** Ids per `getAll`, well inside the Admin SDK's comfortable batch. */ const GET_ALL_CHUNK = 100;
60
60
  /**
61
- * Reads one page may make to fill itself past products sold in person only
61
+ * Most rows one page reads to fill itself past products sold in person only
62
62
  * (AGL-4060). `sellOnline` is absent on every product stored before the
63
63
  * switch, and a query cannot ask for "absent or true", so the query reads
64
64
  * the catalog's scope and the page drops what is not sold online — and reads
65
- * on, up to this many times, so a run of in-person-only products does not
66
- * leave a short page in the middle of the grid.
67
- */ const CATALOG_FILL_READS = 4;
65
+ * on until the page holds its size in products sold online (AGL-4038).
66
+ *
67
+ * Each read asks for twice the rows of the one before, starting at the page
68
+ * and one row to spare: a page of six past a run of a hundred in-person
69
+ * products takes five reads. Reading on by the rows still missing read one
70
+ * row at a time and stopped after four reads, so a run of four left the page
71
+ * short and the products sold in person took the slots they were dropped
72
+ * from. Past this many rows the page ends short, with a cursor to read on.
73
+ */ const CATALOG_FILL_SCAN_MAX = 500;
74
+ /**
75
+ * Most ids an explicit list names: a wishlist's whole list (200, the member
76
+ * route's bound). The list is read in order, a page's worth at a time, until
77
+ * the page holds its size in products on sale, so a saved product that is no
78
+ * longer listed takes no slot.
79
+ */ const CATALOG_IDS_MAX = 200;
68
80
  /**
69
81
  * Rows each price-bound read scans for the cheapest (or dearest) product
70
82
  * sold online, past any sold in person only.
@@ -330,7 +342,9 @@ async function runPublicCatalog(params, reads) {
330
342
  const tag = ((_params_tag = params.tag) != null ? _params_tag : '').trim();
331
343
  const query = ((_params_query = params.query) != null ? _params_query : '').trim();
332
344
  const type = STOREFRONT_PRODUCT_TYPES.includes(params.type) ? params.type : '';
333
- const ids = ((_params_ids = params.ids) != null ? _params_ids : []).slice(0, CATALOG_PAGE_MAX);
345
+ const ids = [
346
+ ...new Set((_params_ids = params.ids) != null ? _params_ids : [])
347
+ ].slice(0, CATALOG_IDS_MAX);
334
348
  const asked = Math.floor(Number((_params_limit = params.limit) != null ? _params_limit : CATALOG_PAGE_DEFAULT));
335
349
  const max = Number.isFinite(asked) && asked > 0 ? Math.min(CATALOG_PAGE_MAX, asked) : CATALOG_PAGE_DEFAULT;
336
350
  const sort = storefrontCatalogSort(params.sort);
@@ -343,17 +357,25 @@ async function runPublicCatalog(params, reads) {
343
357
  return reads ? (_categories = (_reads = reads).categories) != null ? _categories : _reads.categories = hostRef.collection('productCategories').limit(200).get() : hostRef.collection('productCategories').limit(200).get();
344
358
  };
345
359
  // Wishlist and related rendering (AGL-297): an explicit id list is its own
346
- // complete set — read it by id, keep what is on sale, in the given order.
360
+ // complete set — read it by id, keep what is on sale, in the given order,
361
+ // until the page holds `max` of them (AGL-4038): an id no longer on sale
362
+ // takes no slot, and the ids past a full page are never read.
347
363
  if (ids.length) {
348
364
  const order = new Map(ids.map((id, index)=>[
349
365
  id,
350
366
  index
351
367
  ]));
352
- const rows = (await readProductsById(productsRef, ids)).filter(onSale);
353
- rows.sort((a, b)=>{
354
- var _order_get, _order_get1;
355
- return ((_order_get = order.get(a.id)) != null ? _order_get : 0) - ((_order_get1 = order.get(b.id)) != null ? _order_get1 : 0);
356
- });
368
+ const rows = [];
369
+ for(let at = 0; at < ids.length && rows.length < max;){
370
+ const take = ids.slice(at, at + Math.min(GET_ALL_CHUNK, max - rows.length));
371
+ at += take.length;
372
+ const read = (await readProductsById(productsRef, take)).filter(onSale);
373
+ read.sort((a, b)=>{
374
+ var _order_get, _order_get1;
375
+ return ((_order_get = order.get(a.id)) != null ? _order_get : 0) - ((_order_get1 = order.get(b.id)) != null ? _order_get1 : 0);
376
+ });
377
+ rows.push(...read);
378
+ }
357
379
  return {
358
380
  items: rows.slice(0, max).map(toItem)
359
381
  };
@@ -606,22 +628,36 @@ async function runPublicCatalog(params, reads) {
606
628
  unpriced ? pricedBy(unpriced, 'asc') : null,
607
629
  unpriced ? pricedBy(unpriced, 'desc') : null
608
630
  ]);
609
- // A page of rows sold online, read on past the ones sold in person only.
631
+ // A page of `max` rows sold online, read on past the ones sold in person
632
+ // only (AGL-4038). The first read is the page and one row to spare, so a
633
+ // catalog with none in person reads exactly as it did; each further read
634
+ // doubles. The cursor follows the last row the page took.
610
635
  const rows = [];
611
636
  let last;
612
- let more = false;
613
- for(let read = 0; read < CATALOG_FILL_READS && rows.length < max; read += 1){
614
- const need = max - rows.length;
615
- const snapshot = await pageQuery.limit(need + 1).get();
616
- const docs = snapshot.docs.slice(0, need);
617
- for (const docSnapshot of docs){
618
- last = docSnapshot;
619
- const row = toRow(docSnapshot);
637
+ let more;
638
+ let batch = max + 1;
639
+ let scanned = 0;
640
+ for(;;){
641
+ const { docs } = await pageQuery.limit(batch).get();
642
+ scanned += docs.length;
643
+ let taken = 0;
644
+ while(taken < docs.length && rows.length < max){
645
+ last = docs[taken];
646
+ taken += 1;
647
+ const row = toRow(last);
620
648
  if (row && CommerceModel.productSellsOnline(row.product)) rows.push(row);
621
649
  }
622
- more = snapshot.docs.length > need;
623
- if (!more || !last) break;
650
+ const ended = docs.length < batch;
651
+ if (rows.length >= max) {
652
+ // Full: more follow if this read holds another row sold online, or
653
+ // did not reach the end of the scope.
654
+ more = !ended || docs.slice(taken).some((docSnapshot)=>CommerceModel.productSellsOnline(docSnapshot.data()));
655
+ break;
656
+ }
657
+ more = !ended;
658
+ if (ended || !last || scanned >= CATALOG_FILL_SCAN_MAX) break;
624
659
  pageQuery = ordered(plan).startAfter(last.get(plan.orderBy.path), last.id);
660
+ batch = Math.min(batch * 2, CATALOG_FILL_SCAN_MAX - scanned);
625
661
  }
626
662
  const [lowest, highest] = await bounds;
627
663
  const low = boundOf(lowest);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/catalog.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 { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { ListFilterClause } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport {\n type ListQueryFilter,\n type ListQueryPlan,\n type ListQueryRefusal,\n type ListQueryRequest,\n type ListQuerySort,\n planListQuery,\n} from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { applyListQuery } from '@aglyn/tenant-data-admin/server/list-query'\nimport {\n smartCollectionScope,\n STOREFRONT_CATALOG_BASE,\n STOREFRONT_CATALOG_DECLARATION,\n STOREFRONT_CATALOG_SORTS,\n STOREFRONT_PRODUCT_TYPES,\n storefrontCatalogSort,\n} from '../constants/storefront-catalog-query'\nimport * as CommerceModel from '../model'\n\nexport interface PublicCatalogItem {\n id: string\n name: string\n slug: string\n type: CommerceModel.ProductType\n priceUsd: number\n maxPriceUsd: number\n compareAtPriceUsd?: number\n imageUrl?: string\n soldOut: boolean\n tags?: string[]\n /**\n * Listed before any variant has a price (AGL-3676): the card says \"Price\n * coming soon\" instead of a price, and nothing sells it until one is set.\n * Absent for every product with a price.\n */\n priceComingSoon?: true\n /** How many variants the product sells as: one adds straight to a cart. */\n variantCount: number\n /**\n * The one variant a card's quick add puts in the cart — present only for\n * a product with exactly one variant; several need the product page.\n */\n defaultVariantId?: string\n /**\n * The product's page asks a choice first (AGL-4100): a required add-on\n * group shown on the website. Its card's quick add opens the page rather\n * than adding it, as the cart would refuse the line without the choice.\n */\n requiresChoices?: true\n}\n\n/**\n * The photo a product's card shows: the first non-blank of its media, its\n * legacy single image, then the first variant photo. Reading only the first\n * media entry passed a blank one through as the card's image — and a blank\n * resolves to no `src`, so a product WITH a photo drew an empty tile.\n */\nexport function productCardImage(\n product: Pick<CommerceModel.HostProduct, 'mediaUrls' | 'imageUrl' | 'variants'>,\n): string | undefined {\n const candidates = [\n ...(product.mediaUrls ?? []),\n product.imageUrl,\n ...(product.variants ?? []).map((variant) => variant.imageUrl),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()\n }\n return undefined\n}\n\n/** Host category surfaced to grids for filter chips (AGL-561). */\nexport interface PublicCatalogCategory {\n id: string\n name: string\n slug: string\n}\n\n/** Price facet surfaced to grids to bound a range slider (AGL-564). */\nexport interface PublicCatalogPriceBounds {\n minCents: number\n maxCents: number\n}\n\n/**\n * A control the query could not apply, and why — the plan's own refusal,\n * which the grid names through `listQueryRefusals` with the declaration's\n * fields and the categories it shows.\n */\nexport type PublicCatalogRefusal = ListQueryRefusal\n\n/** Non-negative integer cents from a query param; undefined otherwise. */\nfunction parsePriceCents(value: unknown): number | undefined {\n const raw = String(value ?? '').trim()\n if (!raw) return undefined\n const cents = Number(raw)\n if (!Number.isFinite(cents) || cents < 0) return undefined\n return Math.round(cents)\n}\n\n/** A catalog query, already parsed and bounded. */\nexport interface PublicCatalogQuery {\n hostId: string\n collectionId?: string\n collectionSlug?: string\n categoryId?: string\n categorySlug?: string\n tag?: string\n /** Search: the first word, matched as a word prefix of the product name. */\n query?: string\n type?: CommerceModel.ProductType | ''\n /** The In stock chip: only products a card would not mark sold out. */\n inStock?: boolean\n /** Explicit id list in the given order (wishlist rendering, AGL-297). */\n ids?: string[]\n minPriceCents?: number\n maxPriceCents?: number\n sort?: string\n /** Page size, 1–100. */\n limit?: number\n /** The `nextCursor` a previous page returned — continue after it. */\n after?: string\n /** Include category + price facets in the result. */\n facets?: boolean\n /**\n * Optional per-render dedupe (see {@link CatalogReadScope}). Absent for a\n * one-off call such as the API route, where there is nothing to share with.\n */\n reads?: CatalogReadScope\n}\n\n/**\n * Reads shared by every catalog query in ONE render, for ONE host.\n *\n * Two grids on one page asking the SAME question share one answer, and every\n * grid that shows category chips shares one read of the taxonomy. A grid\n * asking a different question — another collection, another sort — runs its\n * own query, because each query now reads only the page it returns rather\n * than the whole catalog (AGL-3321).\n *\n * Scoped to one host and one render deliberately: it holds promises, not\n * data, so nothing is cached across requests and no staleness window opens.\n * Reusing a scope for a second host would serve that host the first one's\n * catalog, which is why it is created per render rather than per module.\n */\nexport interface CatalogReadScope {\n categories?: Promise<FirebaseFirestore.QuerySnapshot>\n results?: Map<string, Promise<PublicCatalogResult>>\n}\n\n/** A fresh read scope. One per render, never reused across hosts. */\nexport function createCatalogReadScope(): CatalogReadScope {\n return {}\n}\n\n/** What both the API route and the SSR seed hand to a product grid. */\nexport interface PublicCatalogResult {\n items: PublicCatalogItem[]\n /** Pass back as `after` for the next page; absent on the last one. */\n nextCursor?: string\n categories?: PublicCatalogCategory[]\n priceBounds?: PublicCatalogPriceBounds\n /** Controls in force that the query could not apply (AGL-3321). */\n refused?: PublicCatalogRefusal[]\n /** Said about what WAS applied, e.g. that search reads one word. */\n notices?: string[]\n}\n\n/** Most products one page returns. */\nconst CATALOG_PAGE_MAX = 100\n/** Page size when a grid names none. */\nconst CATALOG_PAGE_DEFAULT = 24\n/**\n * Members of a MANUAL collection read by id. A hand-curated list is its own\n * complete set, so it is read whole and every visitor control is answered over\n * all of it rather than over a window of the catalog.\n */\nconst MANUAL_COLLECTION_MAX = 1000\n/** Ids per `getAll`, well inside the Admin SDK's comfortable batch. */\nconst GET_ALL_CHUNK = 100\n/**\n * Reads one page may make to fill itself past products sold in person only\n * (AGL-4060). `sellOnline` is absent on every product stored before the\n * switch, and a query cannot ask for \"absent or true\", so the query reads\n * the catalog's scope and the page drops what is not sold online — and reads\n * on, up to this many times, so a run of in-person-only products does not\n * leave a short page in the middle of the grid.\n */\nconst CATALOG_FILL_READS = 4\n/**\n * Rows each price-bound read scans for the cheapest (or dearest) product\n * sold online, past any sold in person only.\n */\nconst PRICE_BOUND_SCAN = 10\n\n/** One product as the catalog reads it: stored, lifted, and keyed. */\ninterface CatalogRow {\n id: string\n product: CommerceModel.HostProduct\n /**\n * The fields the catalog query reads, as the writers stamp them — derived\n * through the same library functions the writers spread, so a held row\n * (a manual collection's member, an id list's entry) answers a predicate\n * exactly as the stored document will once it is backfilled.\n */\n values: Record<string, unknown>\n}\n\nfunction toRow(docSnapshot: FirebaseFirestore.DocumentSnapshot): CatalogRow | null {\n const raw = docSnapshot.data() as Record<string, unknown> | undefined\n if (!raw) return null\n const product = CommerceModel.liftLegacyProduct(raw as never)\n return {\n id: docSnapshot.id,\n product,\n values: {\n ...raw,\n status: product.status,\n type: product.type,\n deletedAt: raw['deletedAt'] ?? null,\n ...CommerceModel.productSearchFields({\n name: String(product.name ?? ''),\n variants: product.variants,\n }),\n ...CommerceModel.productStockFields(product),\n },\n }\n}\n\n/** A row's value at a queried path, as the query sees it. */\nfunction rowValue(row: CatalogRow, path: string): unknown {\n return row.values[path]\n}\n\n/**\n * A held row a shopper may be shown: live and active, as the query's scope,\n * and sold online (AGL-4060).\n */\nconst onSale = (row: CatalogRow) =>\n STOREFRONT_CATALOG_BASE.every((filter) => rowMatches(row, filter)) &&\n CommerceModel.productSellsOnline(row.product)\n\n/** One plan predicate over one row, with Firestore's meaning of each operator. */\nfunction rowMatches(row: CatalogRow, filter: ListQueryFilter): boolean {\n const actual = rowValue(row, filter.path)\n if (actual === undefined) return false\n const value = filter.value\n const list = Array.isArray(value) ? (value as readonly unknown[]) : [value]\n switch (filter.op) {\n case '==':\n return actual === value\n case '!=':\n return actual !== null && actual !== value\n case 'in':\n return list.includes(actual)\n case 'array-contains':\n return Array.isArray(actual) && actual.includes(value)\n case 'array-contains-any':\n return Array.isArray(actual) && actual.some((member) => list.includes(member))\n case '<':\n return typeof actual === typeof value && (actual as number) < (value as number)\n case '<=':\n return typeof actual === typeof value && (actual as number) <= (value as number)\n case '>':\n return typeof actual === typeof value && (actual as number) > (value as number)\n case '>=':\n return typeof actual === typeof value && (actual as number) >= (value as number)\n default:\n return false\n }\n}\n\n/** A cursor: the last row's order value and id, opaque to the grid. */\nfunction encodeCursor(value: unknown, id: string): string {\n return Buffer.from(JSON.stringify([value ?? null, id])).toString('base64url')\n}\n\nfunction decodeCursor(raw: string | undefined): { value: unknown; id: string } | null {\n if (!raw) return null\n try {\n const parsed = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'))\n if (!Array.isArray(parsed) || parsed.length !== 2) return null\n const [value, id] = parsed\n if (typeof id !== 'string' || !id) return null\n if (value !== null && typeof value !== 'string' && typeof value !== 'number') return null\n return { value, id }\n } catch {\n return null\n }\n}\n\nconst compareValues = (a: unknown, b: unknown): number => {\n if (a === b) return 0\n // A row without the ordered value sorts after every row with one.\n if (a === undefined || a === null) return 1\n if (b === undefined || b === null) return -1\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n/**\n * One page of rows already held WHOLE — a manual collection, an id list, a\n * smart collection's scan — ordered by `key` then id, after the cursor.\n */\nfunction pageHeldRows(\n rows: readonly CatalogRow[],\n key: (row: CatalogRow) => unknown,\n direction: 'asc' | 'desc',\n after: string | undefined,\n max: number,\n): { rows: CatalogRow[]; nextCursor?: string } {\n const signed = (value: number) => (direction === 'desc' ? -value : value)\n const ordered = [...rows].sort(\n (a, b) =>\n signed(compareValues(key(a), key(b))) || signed(compareValues(a.id, b.id)),\n )\n const cursor = decodeCursor(after)\n const start = cursor\n ? ordered.findIndex(\n (row) =>\n signed(compareValues(key(row), cursor.value)) > 0 ||\n (compareValues(key(row), cursor.value) === 0 &&\n signed(compareValues(row.id, cursor.id)) > 0),\n )\n : 0\n if (start === -1) return { rows: [] }\n const page = ordered.slice(start, start + max)\n const last = page[page.length - 1]\n return {\n rows: page,\n ...(last && start + max < ordered.length\n ? { nextCursor: encodeCursor(key(last), last.id) }\n : {}),\n }\n}\n\n/** Documents by id, in chunks, dropping the ones that do not exist. */\nasync function readProductsById(\n productsRef: FirebaseFirestore.CollectionReference,\n ids: readonly string[],\n): Promise<CatalogRow[]> {\n const firestore = firebaseAdmin.app().firestore()\n const rows: CatalogRow[] = []\n for (let start = 0; start < ids.length; start += GET_ALL_CHUNK) {\n const refs = ids.slice(start, start + GET_ALL_CHUNK).map((id) => productsRef.doc(id))\n if (!refs.length) continue\n const snapshots = await firestore.getAll(...refs)\n for (const snapshot of snapshots) {\n if (!snapshot.exists) continue\n const row = toRow(snapshot)\n if (row) rows.push(row)\n }\n }\n return rows\n}\n\n/** The card a grid renders for one product. */\nfunction toItem(row: CatalogRow): PublicCatalogItem {\n const { product } = row\n const [minPrice, maxPrice] = CommerceModel.productPriceRange(product)\n const primary = product.variants[0]\n return {\n id: row.id,\n name: product.name,\n slug: product.slug,\n type: product.type,\n priceUsd: minPrice,\n maxPriceUsd: maxPrice,\n ...(primary?.compareAtPriceUsd\n ? { compareAtPriceUsd: primary.compareAtPriceUsd }\n : {}),\n ...(productCardImage(product) ? { imageUrl: productCardImage(product) } : {}),\n // The same verdict the In stock chip queries (`soldOut`), from the one\n // function every stock writer stores it through.\n soldOut: CommerceModel.productStockFields(product).soldOut,\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.variants.some((variant) => CommerceModel.variantHasPrice(variant))\n ? {}\n : { priceComingSoon: true as const }),\n variantCount: product.variants.length,\n ...(product.variants.length === 1 && primary?.id ? { defaultVariantId: primary.id } : {}),\n ...(CommerceModel.websiteModifiersRequired(product) ? { requiresChoices: true as const } : {}),\n }\n}\n\n/**\n * The plan's refusals, as the plan made them; the grid words each one. A\n * search refused because a smart collection already holds the query's one\n * array clause gets a reason a shopper can read.\n */\nfunction refusalsOf(plan: ListQueryPlan): PublicCatalogRefusal[] {\n return plan.refused.map((refusal) =>\n refusal.clause === 'search' && refusal.reason.startsWith('this list is already narrowed')\n ? {\n ...refusal,\n reason: 'this collection is already narrowed by a tag or category, which search cannot combine with',\n }\n : refusal,\n )\n}\n\n/** How a sort reads in the grid's select, for the notice below. */\nconst SORT_LABELS: Readonly<Record<string, string>> = {\n nameLower: 'Name',\n createdAtMs: 'Newest',\n}\n\n/** The operators that make a field a range, which must lead the order. */\nconst RANGE_OPS: ReadonlySet<string> = new Set(['<', '<=', '>', '>=', '!='])\n\n/**\n * The plan, ordered the way the visitor asked when a range forced its field.\n *\n * A range leads the order, so while the price slider (or a smart collection's\n * \"price under\" rule) is set the query is ordered by price: \"high to low\"\n * stays high to low, and any other sort — Name, Newest — becomes low to high\n * and is SAID to, rather than silently replaced (AGL-3321).\n *\n * The notice names the cause. The slider is the visitor's to clear, so the\n * sort they chose returns when they do; a collection's rule is in the scope\n * (`request.base`), which no visitor can clear, so that notice says the\n * collection is always ordered by price.\n */\nfunction planFor(request: ListQueryRequest, sort: ListQuerySort): ListQueryPlan {\n const plan = planListQuery(STOREFRONT_CATALOG_DECLARATION, request, nameSearchNormalizers)\n if (plan.orderBy.path !== sort.path) {\n const asked = SORT_LABELS[sort.path]\n if (!asked) return plan\n const byRule = (request.base ?? []).some(\n (filter) => filter.path === plan.orderBy.path && RANGE_OPS.has(filter.op),\n )\n return {\n ...plan,\n notices: [\n ...plan.notices,\n byRule\n ? `Sorted by price, low to high — this collection picks its products by price, so it cannot be sorted by ${asked}.`\n : `Sorted by price, low to high, while a price range is set — ${asked} applies again when it is cleared.`,\n ],\n }\n }\n return plan.orderBy.direction !== sort.direction ? { ...plan, orderBy: sort } : plan\n}\n\n/** A price bound as the grid's slider shows it, for a refusal's sentence. */\nconst dollars = (cents: number) => `$${(cents / 100).toFixed(cents % 100 ? 2 : 0)}`\n\n/**\n * Public catalog listing (AGL-291): active products for storefront blocks —\n * a collection, a category or a tag, searched, filtered by type and price,\n * sorted, and paged by cursor (AGL-561, AGL-564).\n *\n * EVERY CONTROL IS ON THE QUERY (AGL-3321). This used to read `limit(500)`\n * products and narrow them in memory, so a catalog past five hundred answered\n * every search, chip and slider from an arbitrary five hundred of them. Now:\n *\n * - the catalog, a category or a tag — ONE query built by the list query\n * plan (`STOREFRONT_CATALOG_DECLARATION`), paged by its own cursor;\n * - a SMART collection whose rules a query can hold — the same query, with\n * the rules as its scope (`smartCollectionScope`);\n * - a MANUAL collection, or an explicit id list — read whole by id, which\n * is a complete set, and answered over all of it;\n * - a smart collection whose rules no query can hold (a NOT, an OR, a name\n * rule, a price over) — the same query, scoped by the membership every\n * product writer stores (`collectionIds array-contains <id>`), which the\n * collection-membership route re-stamps whenever the rules change.\n *\n * What one query cannot hold — two array clauses, two ranges — is refused by\n * name in `refused` and not applied, never applied to some rows and not\n * others. Read-only public data; prices here are display-only (charges\n * always come from the docs server-side).\n *\n * Extracted from the handler (AGL-659) so the site-page enricher seeds a\n * grid's first page through THIS function rather than a reimplementation\n * of it. A seed that filters or sorts differently from the API would\n * server-render one set of products and hydrate to another.\n */\nexport async function queryPublicCatalog(\n params: PublicCatalogQuery,\n): Promise<PublicCatalogResult> {\n const { reads, ...question } = params\n if (!reads) return runPublicCatalog(question)\n const key = JSON.stringify(question)\n reads.results ??= new Map()\n const shared = reads.results.get(key)\n if (shared) return shared\n // Stored BEFORE it is awaited, so grids running together under one\n // `Promise.all` share the one in-flight read rather than racing to store it.\n const pending = runPublicCatalog(question, reads)\n reads.results.set(key, pending)\n return pending\n}\n\nasync function runPublicCatalog(\n params: Omit<PublicCatalogQuery, 'reads'>,\n reads?: CatalogReadScope,\n): Promise<PublicCatalogResult> {\n const { hostId } = params\n const collectionSlug = params.collectionSlug ?? ''\n const categorySlug = params.categorySlug ?? ''\n // Id-based filters are preferred (rename-safe, AGL-343); slugs remain\n // for legacy screens and template-URL resolution.\n const collectionIdParam = params.collectionId ?? ''\n const categoryIdParam = params.categoryId ?? ''\n const tag = (params.tag ?? '').trim()\n const query = (params.query ?? '').trim()\n const type = STOREFRONT_PRODUCT_TYPES.includes(params.type as CommerceModel.ProductType)\n ? (params.type as CommerceModel.ProductType)\n : ''\n const ids = (params.ids ?? []).slice(0, CATALOG_PAGE_MAX)\n const asked = Math.floor(Number(params.limit ?? CATALOG_PAGE_DEFAULT))\n const max =\n Number.isFinite(asked) && asked > 0\n ? Math.min(CATALOG_PAGE_MAX, asked)\n : CATALOG_PAGE_DEFAULT\n const sort = storefrontCatalogSort(params.sort)\n const wantFacets = Boolean(params.facets)\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const productsRef = hostRef.collection('products')\n const sharedCategories = () =>\n (reads\n ? (reads.categories ??=\n hostRef.collection('productCategories').limit(200).get())\n : hostRef.collection('productCategories').limit(200).get())\n\n // Wishlist and related rendering (AGL-297): an explicit id list is its own\n // complete set — read it by id, keep what is on sale, in the given order.\n if (ids.length) {\n const order = new Map(ids.map((id, index) => [id, index]))\n const rows = (await readProductsById(productsRef, ids)).filter(onSale)\n rows.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))\n return { items: rows.slice(0, max).map(toItem) }\n }\n\n const [collectionsSnapshot, categoriesSnapshot, collectionByIdSnapshot, facetsSnapshot] =\n await Promise.all([\n // limit(5) not 1: content collections share this path and a slug is\n // unique only within a kind (AGL-954) — the catalog match is picked\n // out below rather than trusting whichever doc came back first.\n !collectionIdParam && collectionSlug\n ? hostRef\n .collection('collections')\n .where('slug', '==', collectionSlug)\n .limit(5)\n .get()\n : null,\n !categoryIdParam && categorySlug\n ? hostRef\n .collection('productCategories')\n .where('slug', '==', categorySlug)\n .limit(1)\n .get()\n : null,\n collectionIdParam\n ? hostRef.collection('collections').doc(collectionIdParam).get()\n : null,\n wantFacets ? sharedCategories() : null,\n ])\n const collectionById =\n collectionByIdSnapshot?.exists &&\n Aglyn.hostCollectionKind(collectionByIdSnapshot.data()) === 'catalog'\n ? collectionByIdSnapshot\n : undefined\n const collectionDoc =\n collectionById ??\n collectionsSnapshot?.docs.find(\n (docSnapshot) => Aglyn.hostCollectionKind(docSnapshot.data()) === 'catalog',\n )\n const collection = collectionDoc\n ? (collectionDoc.data() as CommerceModel.HostCollection)\n : undefined\n const categoryId = categoryIdParam || categoriesSnapshot?.docs[0]?.id || ''\n\n // Category facets (AGL-561): id/name/slug for grid filter chips,\n // parent-tree order preserved (order, then name). The taxonomy is a\n // bounded picker, read whole.\n const categories: PublicCatalogCategory[] | undefined = facetsSnapshot\n ? facetsSnapshot.docs\n .map((docSnapshot) => {\n const data = docSnapshot.data() as CommerceModel.ProductCategory\n return {\n id: docSnapshot.id,\n name: String(data.name ?? ''),\n slug: String(data.slug ?? ''),\n order: Number(data.order ?? 0),\n }\n })\n .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))\n .map(({ id, name, slug }) => ({ id, name, slug }))\n : undefined\n\n // The visitor's controls, as clauses on the one declaration. A price\n // clause carries the dollars the slider showed, for a refusal's sentence.\n const priceClauses: ListFilterClause[] = [\n ...(params.minPriceCents != null\n ? [{\n field: 'price',\n op: '>=',\n value: String(params.minPriceCents),\n label: dollars(params.minPriceCents),\n }]\n : []),\n ...(params.maxPriceCents != null\n ? [{\n field: 'price',\n op: '<=',\n value: String(params.maxPriceCents),\n label: dollars(params.maxPriceCents),\n }]\n : []),\n ]\n const otherClauses: ListFilterClause[] = [\n ...(categoryId ? [{ field: 'category', op: 'contains', value: categoryId }] : []),\n ...(tag ? [{ field: 'tag', op: 'contains', value: tag }] : []),\n ...(type ? [{ field: 'type', op: 'equals', value: type }] : []),\n ...(params.inStock ? [{ field: 'stock', op: 'is', value: 'false' }] : []),\n ]\n // The words typed, as a quick search hands them over: the plan searches by\n // the first and says so when there were more.\n const search = query.split(/\\s+/).filter(Boolean)\n\n const result = (\n rows: CatalogRow[],\n plan: ListQueryPlan,\n extra: Partial<PublicCatalogResult> = {},\n ): PublicCatalogResult => {\n const refused = refusalsOf(plan)\n const notices = [...plan.notices, ...(extra.notices ?? [])]\n return {\n items: rows.map(toItem),\n ...(extra.nextCursor ? { nextCursor: extra.nextCursor } : {}),\n ...(categories ? { categories } : {}),\n ...(extra.priceBounds ? { priceBounds: extra.priceBounds } : {}),\n ...(refused.length ? { refused } : {}),\n ...(notices.length ? { notices } : {}),\n }\n }\n\n /*\n * A collection held WHOLE: a manual one's members, or a smart one whose\n * rules no query can hold. The plan still decides what is applied — the\n * same refusals as the query path, so a grid behaves the same whatever it\n * lists — and its predicates are answered over every held row.\n */\n const answerHeld = (\n rows: CatalogRow[],\n options: { manualOrder?: Map<string, number>; notices?: string[] },\n ): PublicCatalogResult => {\n // A member sold in person only is no row of the grid (AGL-4060).\n const held = rows.filter((row) => CommerceModel.productSellsOnline(row.product))\n const request: ListQueryRequest = {\n base: STOREFRONT_CATALOG_BASE,\n clauses: [...otherClauses, ...priceClauses],\n search,\n sort,\n }\n const plan = planFor(request, sort)\n const unpriced = planFor({ ...request, clauses: otherClauses }, sort)\n const matched = held.filter((row) => plan.filters.every((filter) => rowMatches(row, filter)))\n // Bounds span every OTHER control, so the slider stays anchored while the\n // visitor narrows it.\n const bounding = held.filter((row) =>\n unpriced.filters.every((filter) => rowMatches(row, filter)),\n )\n const priceBounds =\n wantFacets && bounding.length\n ? {\n minCents: Math.min(...bounding.map((row) => Number(rowValue(row, 'priceFromCents')))),\n maxCents: Math.max(...bounding.map((row) => Number(rowValue(row, 'priceFromCents')))),\n }\n : undefined\n // A manual collection keeps the merchant's order unless the visitor (or\n // the author) chose a price or recency sort.\n const keepManual =\n options.manualOrder && plan.orderBy.path === STOREFRONT_CATALOG_SORTS.name.path\n const page = keepManual\n ? pageHeldRows(\n matched,\n (row) => options.manualOrder?.get(row.id) ?? Number.MAX_SAFE_INTEGER,\n 'asc',\n params.after,\n max,\n )\n : pageHeldRows(\n matched,\n (row) => rowValue(row, plan.orderBy.path),\n plan.orderBy.direction,\n params.after,\n max,\n )\n return result(page.rows, plan, {\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n ...(priceBounds ? { priceBounds } : {}),\n ...(options.notices ? { notices: options.notices } : {}),\n })\n }\n\n let scope: ListQueryFilter[] = []\n if (collection) {\n if (collection.mode === 'manual') {\n const memberIds = (collection.productIds ?? []).slice(0, MANUAL_COLLECTION_MAX)\n const manualOrder = new Map(memberIds.map((id, index) => [id, index]))\n return answerHeld(await readProductsById(productsRef, memberIds), { manualOrder })\n }\n const smart = smartCollectionScope(collection)\n if (!(collection.rules ?? []).length) {\n // A smart collection with no rules holds nothing (`matchesCollection`).\n return result([], planFor({ base: STOREFRONT_CATALOG_BASE, clauses: [], sort }, sort))\n }\n if ('unservable' in smart) {\n // Rules no query can express (a NOT, an OR, a name rule, a price over)\n // are answered by the membership every product writer stores\n // (`collectionIds`, AGL-3321): one array clause on the same query, so\n // the grid's other array controls are refused by name beside it.\n scope = [\n {\n path: CommerceModel.PRODUCT_COLLECTION_IDS,\n op: 'array-contains',\n value: String(collectionDoc?.id ?? ''),\n },\n ]\n } else {\n scope = smart.filters\n // A \"type is not\" rule is `type in […]`; the visitor's Type chip is the\n // narrower question, answered inside it or not at all.\n const typeRule = scope.find((filter) => filter.path === 'type')\n if (typeRule && type) {\n const allowed = Array.isArray(typeRule.value) ? typeRule.value : [typeRule.value]\n if (!allowed.includes(type)) {\n return result([], planFor({ base: STOREFRONT_CATALOG_BASE, clauses: [], sort }, sort))\n }\n scope = scope.filter((filter) => filter !== typeRule)\n }\n }\n }\n\n // THE QUERY: every predicate, one order, a page and one row to spare.\n const request: ListQueryRequest = {\n base: [...STOREFRONT_CATALOG_BASE, ...scope],\n clauses: [...otherClauses, ...priceClauses],\n search,\n sort,\n }\n const plan = planFor(request, sort)\n const byId = firebaseAdmin.firestore.FieldPath.documentId()\n const ordered = (target: ListQueryPlan) =>\n applyListQuery(productsRef, target).orderBy(byId, target.orderBy.direction)\n let pageQuery = ordered(plan)\n const cursor = decodeCursor(params.after)\n if (cursor) pageQuery = pageQuery.startAfter(cursor.value, cursor.id)\n\n // Bounds span every OTHER control, so the slider stays anchored while the\n // visitor narrows it: the lowest and highest price the rest allows, as two\n // one-row reads ordered by price.\n const byPrice = STOREFRONT_CATALOG_SORTS['price-asc']\n const unpriced = wantFacets\n ? planFor({ ...request, clauses: otherClauses, sort: byPrice }, byPrice)\n : null\n const pricedBy = (target: ListQueryPlan, direction: 'asc' | 'desc') =>\n ordered({ ...target, orderBy: { path: 'priceFromCents', direction } }).limit(PRICE_BOUND_SCAN).get()\n // The first price sold online (AGL-4060): an in-person-only product's price\n // never anchors the slider.\n const boundOf = (snapshot: FirebaseFirestore.QuerySnapshot | null) =>\n snapshot?.docs\n .find((docSnapshot) => CommerceModel.productSellsOnline(docSnapshot.data()))\n ?.get('priceFromCents')\n\n const bounds = Promise.all([\n unpriced ? pricedBy(unpriced, 'asc') : null,\n unpriced ? pricedBy(unpriced, 'desc') : null,\n ])\n // A page of rows sold online, read on past the ones sold in person only.\n const rows: CatalogRow[] = []\n let last: FirebaseFirestore.QueryDocumentSnapshot | undefined\n let more = false\n for (let read = 0; read < CATALOG_FILL_READS && rows.length < max; read += 1) {\n const need = max - rows.length\n const snapshot = await pageQuery.limit(need + 1).get()\n const docs = snapshot.docs.slice(0, need)\n for (const docSnapshot of docs) {\n last = docSnapshot\n const row = toRow(docSnapshot)\n if (row && CommerceModel.productSellsOnline(row.product)) rows.push(row)\n }\n more = snapshot.docs.length > need\n if (!more || !last) break\n pageQuery = ordered(plan).startAfter(last.get(plan.orderBy.path), last.id)\n }\n const [lowest, highest] = await bounds\n const low = boundOf(lowest)\n const high = boundOf(highest)\n return result(rows, plan, {\n ...(last && more\n ? { nextCursor: encodeCursor(last.get(plan.orderBy.path), last.id) }\n : {}),\n ...(typeof low === 'number' && typeof high === 'number'\n ? { priceBounds: { minCents: low, maxCents: high } }\n : {}),\n })\n}\n\n/** Public catalog listing endpoint — a thin parse over queryPublicCatalog. */\nexport const catalogHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const result = await queryPublicCatalog({\n hostId,\n collectionSlug: String(req.query.collection ?? ''),\n categorySlug: String(req.query.category ?? ''),\n collectionId: String(req.query.collectionId ?? ''),\n categoryId: String(req.query.categoryId ?? ''),\n tag: String(req.query.tag ?? ''),\n query: String(req.query.q ?? ''),\n type: String(req.query.type ?? '') as CommerceModel.ProductType | '',\n inStock: String(req.query.inStock ?? '') === '1',\n ids: String(req.query.ids ?? '')\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean),\n // Price-range filter (AGL-564): integer cents on the displayed price.\n minPriceCents: parsePriceCents(req.query.minPriceCents),\n maxPriceCents: parsePriceCents(req.query.maxPriceCents),\n sort: String(req.query.sort ?? 'name'),\n limit: Number(req.query.limit ?? CATALOG_PAGE_DEFAULT),\n after: String(req.query.after ?? ''),\n facets: String(req.query.facets ?? '') === '1',\n })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json(result)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Catalog unavailable' })\n }\n}\n"],"names":["nameSearchNormalizers","Aglyn","planListQuery","firebaseAdmin","applyListQuery","smartCollectionScope","STOREFRONT_CATALOG_BASE","STOREFRONT_CATALOG_DECLARATION","STOREFRONT_CATALOG_SORTS","STOREFRONT_PRODUCT_TYPES","storefrontCatalogSort","CommerceModel","productCardImage","product","candidates","mediaUrls","imageUrl","variants","map","variant","candidate","trim","undefined","parsePriceCents","value","raw","String","cents","Number","isFinite","Math","round","createCatalogReadScope","CATALOG_PAGE_MAX","CATALOG_PAGE_DEFAULT","MANUAL_COLLECTION_MAX","GET_ALL_CHUNK","CATALOG_FILL_READS","PRICE_BOUND_SCAN","toRow","docSnapshot","data","liftLegacyProduct","id","values","status","type","deletedAt","productSearchFields","name","productStockFields","rowValue","row","path","onSale","every","filter","rowMatches","productSellsOnline","actual","list","Array","isArray","op","includes","some","member","encodeCursor","Buffer","from","JSON","stringify","toString","decodeCursor","parsed","parse","length","compareValues","a","b","pageHeldRows","rows","key","direction","after","max","signed","ordered","sort","cursor","start","findIndex","page","slice","last","nextCursor","readProductsById","productsRef","ids","firestore","app","refs","doc","snapshots","getAll","snapshot","exists","push","toItem","minPrice","maxPrice","productPriceRange","primary","slug","priceUsd","maxPriceUsd","compareAtPriceUsd","soldOut","tags","variantHasPrice","priceComingSoon","variantCount","defaultVariantId","websiteModifiersRequired","requiresChoices","refusalsOf","plan","refused","refusal","clause","reason","startsWith","SORT_LABELS","nameLower","createdAtMs","RANGE_OPS","Set","planFor","request","orderBy","asked","byRule","base","has","notices","dollars","toFixed","queryPublicCatalog","params","reads","question","runPublicCatalog","results","Map","shared","get","pending","set","categoriesSnapshot","hostId","collectionSlug","categorySlug","collectionIdParam","collectionId","categoryIdParam","categoryId","tag","query","floor","limit","min","wantFacets","Boolean","facets","hostRef","collection","sharedCategories","categories","order","index","items","collectionsSnapshot","collectionByIdSnapshot","facetsSnapshot","Promise","all","where","collectionById","hostCollectionKind","collectionDoc","docs","find","localeCompare","priceClauses","minPriceCents","field","label","maxPriceCents","otherClauses","inStock","search","split","result","extra","priceBounds","answerHeld","options","held","clauses","unpriced","matched","filters","bounding","minCents","maxCents","keepManual","manualOrder","MAX_SAFE_INTEGER","scope","mode","memberIds","productIds","smart","rules","PRODUCT_COLLECTION_IDS","typeRule","allowed","byId","FieldPath","documentId","target","pageQuery","startAfter","byPrice","pricedBy","boundOf","bounds","more","read","need","lowest","highest","low","high","catalogHandler","req","res","json","error","category","q","setHeader","console"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,qCAAoC;AAE1E,YAAYC,WAAW,sBAAqB;AAE5C,SAMEC,aAAa,QACR,6CAA4C;AACnD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,cAAc,QAAQ,6CAA4C;AAC3E,SACEC,oBAAoB,EACpBC,uBAAuB,EACvBC,8BAA8B,EAC9BC,wBAAwB,EACxBC,wBAAwB,EACxBC,qBAAqB,QAChB,2CAAuC;AAC9C,YAAYC,mBAAmB,oBAAU;AAkCzC;;;;;CAKC,GACD,OAAO,SAASC,iBACdC,OAA+E;QAGzEA,oBAEAA;IAHN,MAAMC,aAAa;YACbD,qBAAAA,QAAQE,SAAS,YAAjBF,qBAAqB,EAAE;QAC3BA,QAAQG,QAAQ;WACb,EAACH,oBAAAA,QAAQI,QAAQ,YAAhBJ,oBAAoB,EAAE,EAAEK,GAAG,CAAC,CAACC,UAAYA,QAAQH,QAAQ;KAC9D;IACD,KAAK,MAAMI,aAAaN,WAAY;QAClC,IAAI,OAAOM,cAAc,YAAYA,UAAUC,IAAI,IAAI,OAAOD,UAAUC,IAAI;IAC9E;IACA,OAAOC;AACT;AAsBA,wEAAwE,GACxE,SAASC,gBAAgBC,KAAc;IACrC,MAAMC,MAAMC,OAAOF,gBAAAA,QAAS,IAAIH,IAAI;IACpC,IAAI,CAACI,KAAK,OAAOH;IACjB,MAAMK,QAAQC,OAAOH;IACrB,IAAI,CAACG,OAAOC,QAAQ,CAACF,UAAUA,QAAQ,GAAG,OAAOL;IACjD,OAAOQ,KAAKC,KAAK,CAACJ;AACpB;AAoDA,mEAAmE,GACnE,OAAO,SAASK;IACd,OAAO,CAAC;AACV;AAeA,oCAAoC,GACpC,MAAMC,mBAAmB;AACzB,sCAAsC,GACtC,MAAMC,uB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qBAAqB,QAAQ;YAC7CnJ,KAAKxE,QAAO2N,iBAAAA,IAAI9E,KAAK,CAACrE,GAAG,YAAbmJ,iBAAiB,IAC1B5C,KAAK,CAAC,KACNvL,GAAG,CAAC,CAACyB,KAAOA,GAAGtB,IAAI,IACnBmC,MAAM,CAACoH;YACV,sEAAsE;YACtEsB,eAAe3K,gBAAgB8N,IAAI9E,KAAK,CAAC2B,aAAa;YACtDG,eAAe9K,gBAAgB8N,IAAI9E,KAAK,CAAC8B,aAAa;YACtD7G,MAAM9D,QAAO2N,kBAAAA,IAAI9E,KAAK,CAAC/E,IAAI,YAAd6J,kBAAkB;YAC/B5E,OAAO7I,QAAOyN,mBAAAA,IAAI9E,KAAK,CAACE,KAAK,YAAf4E,mBAAmBnN;YACjCkD,OAAO1D,QAAO2N,mBAAAA,IAAI9E,KAAK,CAACnF,KAAK,YAAfiK,mBAAmB;YACjCxE,QAAQnJ,QAAO2N,oBAAAA,IAAI9E,KAAK,CAACM,MAAM,YAAhBwE,oBAAoB,QAAQ;QAC7C;QACAC,IAAIK,SAAS,CACX,iBACA;QAEF,OAAOL,IAAIzM,MAAM,CAAC,KAAK0M,IAAI,CAAC7C;IAC9B,EAAE,OAAO8C,OAAO;QACdI,QAAQJ,KAAK,CAACA;QACd,OAAOF,IAAIzM,MAAM,CAAC,KAAK0M,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/catalog.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 { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { ListFilterClause } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport {\n type ListQueryFilter,\n type ListQueryPlan,\n type ListQueryRefusal,\n type ListQueryRequest,\n type ListQuerySort,\n planListQuery,\n} from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { applyListQuery } from '@aglyn/tenant-data-admin/server/list-query'\nimport {\n smartCollectionScope,\n STOREFRONT_CATALOG_BASE,\n STOREFRONT_CATALOG_DECLARATION,\n STOREFRONT_CATALOG_SORTS,\n STOREFRONT_PRODUCT_TYPES,\n storefrontCatalogSort,\n} from '../constants/storefront-catalog-query'\nimport * as CommerceModel from '../model'\n\nexport interface PublicCatalogItem {\n id: string\n name: string\n slug: string\n type: CommerceModel.ProductType\n priceUsd: number\n maxPriceUsd: number\n compareAtPriceUsd?: number\n imageUrl?: string\n soldOut: boolean\n tags?: string[]\n /**\n * Listed before any variant has a price (AGL-3676): the card says \"Price\n * coming soon\" instead of a price, and nothing sells it until one is set.\n * Absent for every product with a price.\n */\n priceComingSoon?: true\n /** How many variants the product sells as: one adds straight to a cart. */\n variantCount: number\n /**\n * The one variant a card's quick add puts in the cart — present only for\n * a product with exactly one variant; several need the product page.\n */\n defaultVariantId?: string\n /**\n * The product's page asks a choice first (AGL-4100): a required add-on\n * group shown on the website. Its card's quick add opens the page rather\n * than adding it, as the cart would refuse the line without the choice.\n */\n requiresChoices?: true\n}\n\n/**\n * The photo a product's card shows: the first non-blank of its media, its\n * legacy single image, then the first variant photo. Reading only the first\n * media entry passed a blank one through as the card's image — and a blank\n * resolves to no `src`, so a product WITH a photo drew an empty tile.\n */\nexport function productCardImage(\n product: Pick<CommerceModel.HostProduct, 'mediaUrls' | 'imageUrl' | 'variants'>,\n): string | undefined {\n const candidates = [\n ...(product.mediaUrls ?? []),\n product.imageUrl,\n ...(product.variants ?? []).map((variant) => variant.imageUrl),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()\n }\n return undefined\n}\n\n/** Host category surfaced to grids for filter chips (AGL-561). */\nexport interface PublicCatalogCategory {\n id: string\n name: string\n slug: string\n}\n\n/** Price facet surfaced to grids to bound a range slider (AGL-564). */\nexport interface PublicCatalogPriceBounds {\n minCents: number\n maxCents: number\n}\n\n/**\n * A control the query could not apply, and why — the plan's own refusal,\n * which the grid names through `listQueryRefusals` with the declaration's\n * fields and the categories it shows.\n */\nexport type PublicCatalogRefusal = ListQueryRefusal\n\n/** Non-negative integer cents from a query param; undefined otherwise. */\nfunction parsePriceCents(value: unknown): number | undefined {\n const raw = String(value ?? '').trim()\n if (!raw) return undefined\n const cents = Number(raw)\n if (!Number.isFinite(cents) || cents < 0) return undefined\n return Math.round(cents)\n}\n\n/** A catalog query, already parsed and bounded. */\nexport interface PublicCatalogQuery {\n hostId: string\n collectionId?: string\n collectionSlug?: string\n categoryId?: string\n categorySlug?: string\n tag?: string\n /** Search: the first word, matched as a word prefix of the product name. */\n query?: string\n type?: CommerceModel.ProductType | ''\n /** The In stock chip: only products a card would not mark sold out. */\n inStock?: boolean\n /** Explicit id list in the given order (wishlist rendering, AGL-297). */\n ids?: string[]\n minPriceCents?: number\n maxPriceCents?: number\n sort?: string\n /** Page size, 1–100. */\n limit?: number\n /** The `nextCursor` a previous page returned — continue after it. */\n after?: string\n /** Include category + price facets in the result. */\n facets?: boolean\n /**\n * Optional per-render dedupe (see {@link CatalogReadScope}). Absent for a\n * one-off call such as the API route, where there is nothing to share with.\n */\n reads?: CatalogReadScope\n}\n\n/**\n * Reads shared by every catalog query in ONE render, for ONE host.\n *\n * Two grids on one page asking the SAME question share one answer, and every\n * grid that shows category chips shares one read of the taxonomy. A grid\n * asking a different question — another collection, another sort — runs its\n * own query, because each query now reads only the page it returns rather\n * than the whole catalog (AGL-3321).\n *\n * Scoped to one host and one render deliberately: it holds promises, not\n * data, so nothing is cached across requests and no staleness window opens.\n * Reusing a scope for a second host would serve that host the first one's\n * catalog, which is why it is created per render rather than per module.\n */\nexport interface CatalogReadScope {\n categories?: Promise<FirebaseFirestore.QuerySnapshot>\n results?: Map<string, Promise<PublicCatalogResult>>\n}\n\n/** A fresh read scope. One per render, never reused across hosts. */\nexport function createCatalogReadScope(): CatalogReadScope {\n return {}\n}\n\n/** What both the API route and the SSR seed hand to a product grid. */\nexport interface PublicCatalogResult {\n items: PublicCatalogItem[]\n /** Pass back as `after` for the next page; absent on the last one. */\n nextCursor?: string\n categories?: PublicCatalogCategory[]\n priceBounds?: PublicCatalogPriceBounds\n /** Controls in force that the query could not apply (AGL-3321). */\n refused?: PublicCatalogRefusal[]\n /** Said about what WAS applied, e.g. that search reads one word. */\n notices?: string[]\n}\n\n/** Most products one page returns. */\nconst CATALOG_PAGE_MAX = 100\n/** Page size when a grid names none. */\nconst CATALOG_PAGE_DEFAULT = 24\n/**\n * Members of a MANUAL collection read by id. A hand-curated list is its own\n * complete set, so it is read whole and every visitor control is answered over\n * all of it rather than over a window of the catalog.\n */\nconst MANUAL_COLLECTION_MAX = 1000\n/** Ids per `getAll`, well inside the Admin SDK's comfortable batch. */\nconst GET_ALL_CHUNK = 100\n/**\n * Most rows one page reads to fill itself past products sold in person only\n * (AGL-4060). `sellOnline` is absent on every product stored before the\n * switch, and a query cannot ask for \"absent or true\", so the query reads\n * the catalog's scope and the page drops what is not sold online — and reads\n * on until the page holds its size in products sold online (AGL-4038).\n *\n * Each read asks for twice the rows of the one before, starting at the page\n * and one row to spare: a page of six past a run of a hundred in-person\n * products takes five reads. Reading on by the rows still missing read one\n * row at a time and stopped after four reads, so a run of four left the page\n * short and the products sold in person took the slots they were dropped\n * from. Past this many rows the page ends short, with a cursor to read on.\n */\nconst CATALOG_FILL_SCAN_MAX = 500\n/**\n * Most ids an explicit list names: a wishlist's whole list (200, the member\n * route's bound). The list is read in order, a page's worth at a time, until\n * the page holds its size in products on sale, so a saved product that is no\n * longer listed takes no slot.\n */\nconst CATALOG_IDS_MAX = 200\n/**\n * Rows each price-bound read scans for the cheapest (or dearest) product\n * sold online, past any sold in person only.\n */\nconst PRICE_BOUND_SCAN = 10\n\n/** One product as the catalog reads it: stored, lifted, and keyed. */\ninterface CatalogRow {\n id: string\n product: CommerceModel.HostProduct\n /**\n * The fields the catalog query reads, as the writers stamp them — derived\n * through the same library functions the writers spread, so a held row\n * (a manual collection's member, an id list's entry) answers a predicate\n * exactly as the stored document will once it is backfilled.\n */\n values: Record<string, unknown>\n}\n\nfunction toRow(docSnapshot: FirebaseFirestore.DocumentSnapshot): CatalogRow | null {\n const raw = docSnapshot.data() as Record<string, unknown> | undefined\n if (!raw) return null\n const product = CommerceModel.liftLegacyProduct(raw as never)\n return {\n id: docSnapshot.id,\n product,\n values: {\n ...raw,\n status: product.status,\n type: product.type,\n deletedAt: raw['deletedAt'] ?? null,\n ...CommerceModel.productSearchFields({\n name: String(product.name ?? ''),\n variants: product.variants,\n }),\n ...CommerceModel.productStockFields(product),\n },\n }\n}\n\n/** A row's value at a queried path, as the query sees it. */\nfunction rowValue(row: CatalogRow, path: string): unknown {\n return row.values[path]\n}\n\n/**\n * A held row a shopper may be shown: live and active, as the query's scope,\n * and sold online (AGL-4060).\n */\nconst onSale = (row: CatalogRow) =>\n STOREFRONT_CATALOG_BASE.every((filter) => rowMatches(row, filter)) &&\n CommerceModel.productSellsOnline(row.product)\n\n/** One plan predicate over one row, with Firestore's meaning of each operator. */\nfunction rowMatches(row: CatalogRow, filter: ListQueryFilter): boolean {\n const actual = rowValue(row, filter.path)\n if (actual === undefined) return false\n const value = filter.value\n const list = Array.isArray(value) ? (value as readonly unknown[]) : [value]\n switch (filter.op) {\n case '==':\n return actual === value\n case '!=':\n return actual !== null && actual !== value\n case 'in':\n return list.includes(actual)\n case 'array-contains':\n return Array.isArray(actual) && actual.includes(value)\n case 'array-contains-any':\n return Array.isArray(actual) && actual.some((member) => list.includes(member))\n case '<':\n return typeof actual === typeof value && (actual as number) < (value as number)\n case '<=':\n return typeof actual === typeof value && (actual as number) <= (value as number)\n case '>':\n return typeof actual === typeof value && (actual as number) > (value as number)\n case '>=':\n return typeof actual === typeof value && (actual as number) >= (value as number)\n default:\n return false\n }\n}\n\n/** A cursor: the last row's order value and id, opaque to the grid. */\nfunction encodeCursor(value: unknown, id: string): string {\n return Buffer.from(JSON.stringify([value ?? null, id])).toString('base64url')\n}\n\nfunction decodeCursor(raw: string | undefined): { value: unknown; id: string } | null {\n if (!raw) return null\n try {\n const parsed = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'))\n if (!Array.isArray(parsed) || parsed.length !== 2) return null\n const [value, id] = parsed\n if (typeof id !== 'string' || !id) return null\n if (value !== null && typeof value !== 'string' && typeof value !== 'number') return null\n return { value, id }\n } catch {\n return null\n }\n}\n\nconst compareValues = (a: unknown, b: unknown): number => {\n if (a === b) return 0\n // A row without the ordered value sorts after every row with one.\n if (a === undefined || a === null) return 1\n if (b === undefined || b === null) return -1\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n/**\n * One page of rows already held WHOLE — a manual collection, an id list, a\n * smart collection's scan — ordered by `key` then id, after the cursor.\n */\nfunction pageHeldRows(\n rows: readonly CatalogRow[],\n key: (row: CatalogRow) => unknown,\n direction: 'asc' | 'desc',\n after: string | undefined,\n max: number,\n): { rows: CatalogRow[]; nextCursor?: string } {\n const signed = (value: number) => (direction === 'desc' ? -value : value)\n const ordered = [...rows].sort(\n (a, b) =>\n signed(compareValues(key(a), key(b))) || signed(compareValues(a.id, b.id)),\n )\n const cursor = decodeCursor(after)\n const start = cursor\n ? ordered.findIndex(\n (row) =>\n signed(compareValues(key(row), cursor.value)) > 0 ||\n (compareValues(key(row), cursor.value) === 0 &&\n signed(compareValues(row.id, cursor.id)) > 0),\n )\n : 0\n if (start === -1) return { rows: [] }\n const page = ordered.slice(start, start + max)\n const last = page[page.length - 1]\n return {\n rows: page,\n ...(last && start + max < ordered.length\n ? { nextCursor: encodeCursor(key(last), last.id) }\n : {}),\n }\n}\n\n/** Documents by id, in chunks, dropping the ones that do not exist. */\nasync function readProductsById(\n productsRef: FirebaseFirestore.CollectionReference,\n ids: readonly string[],\n): Promise<CatalogRow[]> {\n const firestore = firebaseAdmin.app().firestore()\n const rows: CatalogRow[] = []\n for (let start = 0; start < ids.length; start += GET_ALL_CHUNK) {\n const refs = ids.slice(start, start + GET_ALL_CHUNK).map((id) => productsRef.doc(id))\n if (!refs.length) continue\n const snapshots = await firestore.getAll(...refs)\n for (const snapshot of snapshots) {\n if (!snapshot.exists) continue\n const row = toRow(snapshot)\n if (row) rows.push(row)\n }\n }\n return rows\n}\n\n/** The card a grid renders for one product. */\nfunction toItem(row: CatalogRow): PublicCatalogItem {\n const { product } = row\n const [minPrice, maxPrice] = CommerceModel.productPriceRange(product)\n const primary = product.variants[0]\n return {\n id: row.id,\n name: product.name,\n slug: product.slug,\n type: product.type,\n priceUsd: minPrice,\n maxPriceUsd: maxPrice,\n ...(primary?.compareAtPriceUsd\n ? { compareAtPriceUsd: primary.compareAtPriceUsd }\n : {}),\n ...(productCardImage(product) ? { imageUrl: productCardImage(product) } : {}),\n // The same verdict the In stock chip queries (`soldOut`), from the one\n // function every stock writer stores it through.\n soldOut: CommerceModel.productStockFields(product).soldOut,\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.variants.some((variant) => CommerceModel.variantHasPrice(variant))\n ? {}\n : { priceComingSoon: true as const }),\n variantCount: product.variants.length,\n ...(product.variants.length === 1 && primary?.id ? { defaultVariantId: primary.id } : {}),\n ...(CommerceModel.websiteModifiersRequired(product) ? { requiresChoices: true as const } : {}),\n }\n}\n\n/**\n * The plan's refusals, as the plan made them; the grid words each one. A\n * search refused because a smart collection already holds the query's one\n * array clause gets a reason a shopper can read.\n */\nfunction refusalsOf(plan: ListQueryPlan): PublicCatalogRefusal[] {\n return plan.refused.map((refusal) =>\n refusal.clause === 'search' && refusal.reason.startsWith('this list is already narrowed')\n ? {\n ...refusal,\n reason: 'this collection is already narrowed by a tag or category, which search cannot combine with',\n }\n : refusal,\n )\n}\n\n/** How a sort reads in the grid's select, for the notice below. */\nconst SORT_LABELS: Readonly<Record<string, string>> = {\n nameLower: 'Name',\n createdAtMs: 'Newest',\n}\n\n/** The operators that make a field a range, which must lead the order. */\nconst RANGE_OPS: ReadonlySet<string> = new Set(['<', '<=', '>', '>=', '!='])\n\n/**\n * The plan, ordered the way the visitor asked when a range forced its field.\n *\n * A range leads the order, so while the price slider (or a smart collection's\n * \"price under\" rule) is set the query is ordered by price: \"high to low\"\n * stays high to low, and any other sort — Name, Newest — becomes low to high\n * and is SAID to, rather than silently replaced (AGL-3321).\n *\n * The notice names the cause. The slider is the visitor's to clear, so the\n * sort they chose returns when they do; a collection's rule is in the scope\n * (`request.base`), which no visitor can clear, so that notice says the\n * collection is always ordered by price.\n */\nfunction planFor(request: ListQueryRequest, sort: ListQuerySort): ListQueryPlan {\n const plan = planListQuery(STOREFRONT_CATALOG_DECLARATION, request, nameSearchNormalizers)\n if (plan.orderBy.path !== sort.path) {\n const asked = SORT_LABELS[sort.path]\n if (!asked) return plan\n const byRule = (request.base ?? []).some(\n (filter) => filter.path === plan.orderBy.path && RANGE_OPS.has(filter.op),\n )\n return {\n ...plan,\n notices: [\n ...plan.notices,\n byRule\n ? `Sorted by price, low to high — this collection picks its products by price, so it cannot be sorted by ${asked}.`\n : `Sorted by price, low to high, while a price range is set — ${asked} applies again when it is cleared.`,\n ],\n }\n }\n return plan.orderBy.direction !== sort.direction ? { ...plan, orderBy: sort } : plan\n}\n\n/** A price bound as the grid's slider shows it, for a refusal's sentence. */\nconst dollars = (cents: number) => `$${(cents / 100).toFixed(cents % 100 ? 2 : 0)}`\n\n/**\n * Public catalog listing (AGL-291): active products for storefront blocks —\n * a collection, a category or a tag, searched, filtered by type and price,\n * sorted, and paged by cursor (AGL-561, AGL-564).\n *\n * EVERY CONTROL IS ON THE QUERY (AGL-3321). This used to read `limit(500)`\n * products and narrow them in memory, so a catalog past five hundred answered\n * every search, chip and slider from an arbitrary five hundred of them. Now:\n *\n * - the catalog, a category or a tag — ONE query built by the list query\n * plan (`STOREFRONT_CATALOG_DECLARATION`), paged by its own cursor;\n * - a SMART collection whose rules a query can hold — the same query, with\n * the rules as its scope (`smartCollectionScope`);\n * - a MANUAL collection, or an explicit id list — read whole by id, which\n * is a complete set, and answered over all of it;\n * - a smart collection whose rules no query can hold (a NOT, an OR, a name\n * rule, a price over) — the same query, scoped by the membership every\n * product writer stores (`collectionIds array-contains <id>`), which the\n * collection-membership route re-stamps whenever the rules change.\n *\n * What one query cannot hold — two array clauses, two ranges — is refused by\n * name in `refused` and not applied, never applied to some rows and not\n * others. Read-only public data; prices here are display-only (charges\n * always come from the docs server-side).\n *\n * Extracted from the handler (AGL-659) so the site-page enricher seeds a\n * grid's first page through THIS function rather than a reimplementation\n * of it. A seed that filters or sorts differently from the API would\n * server-render one set of products and hydrate to another.\n */\nexport async function queryPublicCatalog(\n params: PublicCatalogQuery,\n): Promise<PublicCatalogResult> {\n const { reads, ...question } = params\n if (!reads) return runPublicCatalog(question)\n const key = JSON.stringify(question)\n reads.results ??= new Map()\n const shared = reads.results.get(key)\n if (shared) return shared\n // Stored BEFORE it is awaited, so grids running together under one\n // `Promise.all` share the one in-flight read rather than racing to store it.\n const pending = runPublicCatalog(question, reads)\n reads.results.set(key, pending)\n return pending\n}\n\nasync function runPublicCatalog(\n params: Omit<PublicCatalogQuery, 'reads'>,\n reads?: CatalogReadScope,\n): Promise<PublicCatalogResult> {\n const { hostId } = params\n const collectionSlug = params.collectionSlug ?? ''\n const categorySlug = params.categorySlug ?? ''\n // Id-based filters are preferred (rename-safe, AGL-343); slugs remain\n // for legacy screens and template-URL resolution.\n const collectionIdParam = params.collectionId ?? ''\n const categoryIdParam = params.categoryId ?? ''\n const tag = (params.tag ?? '').trim()\n const query = (params.query ?? '').trim()\n const type = STOREFRONT_PRODUCT_TYPES.includes(params.type as CommerceModel.ProductType)\n ? (params.type as CommerceModel.ProductType)\n : ''\n const ids = [...new Set(params.ids ?? [])].slice(0, CATALOG_IDS_MAX)\n const asked = Math.floor(Number(params.limit ?? CATALOG_PAGE_DEFAULT))\n const max =\n Number.isFinite(asked) && asked > 0\n ? Math.min(CATALOG_PAGE_MAX, asked)\n : CATALOG_PAGE_DEFAULT\n const sort = storefrontCatalogSort(params.sort)\n const wantFacets = Boolean(params.facets)\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const productsRef = hostRef.collection('products')\n const sharedCategories = () =>\n (reads\n ? (reads.categories ??=\n hostRef.collection('productCategories').limit(200).get())\n : hostRef.collection('productCategories').limit(200).get())\n\n // Wishlist and related rendering (AGL-297): an explicit id list is its own\n // complete set — read it by id, keep what is on sale, in the given order,\n // until the page holds `max` of them (AGL-4038): an id no longer on sale\n // takes no slot, and the ids past a full page are never read.\n if (ids.length) {\n const order = new Map(ids.map((id, index) => [id, index]))\n const rows: CatalogRow[] = []\n for (let at = 0; at < ids.length && rows.length < max; ) {\n const take = ids.slice(at, at + Math.min(GET_ALL_CHUNK, max - rows.length))\n at += take.length\n const read = (await readProductsById(productsRef, take)).filter(onSale)\n read.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))\n rows.push(...read)\n }\n return { items: rows.slice(0, max).map(toItem) }\n }\n\n const [collectionsSnapshot, categoriesSnapshot, collectionByIdSnapshot, facetsSnapshot] =\n await Promise.all([\n // limit(5) not 1: content collections share this path and a slug is\n // unique only within a kind (AGL-954) — the catalog match is picked\n // out below rather than trusting whichever doc came back first.\n !collectionIdParam && collectionSlug\n ? hostRef\n .collection('collections')\n .where('slug', '==', collectionSlug)\n .limit(5)\n .get()\n : null,\n !categoryIdParam && categorySlug\n ? hostRef\n .collection('productCategories')\n .where('slug', '==', categorySlug)\n .limit(1)\n .get()\n : null,\n collectionIdParam\n ? hostRef.collection('collections').doc(collectionIdParam).get()\n : null,\n wantFacets ? sharedCategories() : null,\n ])\n const collectionById =\n collectionByIdSnapshot?.exists &&\n Aglyn.hostCollectionKind(collectionByIdSnapshot.data()) === 'catalog'\n ? collectionByIdSnapshot\n : undefined\n const collectionDoc =\n collectionById ??\n collectionsSnapshot?.docs.find(\n (docSnapshot) => Aglyn.hostCollectionKind(docSnapshot.data()) === 'catalog',\n )\n const collection = collectionDoc\n ? (collectionDoc.data() as CommerceModel.HostCollection)\n : undefined\n const categoryId = categoryIdParam || categoriesSnapshot?.docs[0]?.id || ''\n\n // Category facets (AGL-561): id/name/slug for grid filter chips,\n // parent-tree order preserved (order, then name). The taxonomy is a\n // bounded picker, read whole.\n const categories: PublicCatalogCategory[] | undefined = facetsSnapshot\n ? facetsSnapshot.docs\n .map((docSnapshot) => {\n const data = docSnapshot.data() as CommerceModel.ProductCategory\n return {\n id: docSnapshot.id,\n name: String(data.name ?? ''),\n slug: String(data.slug ?? ''),\n order: Number(data.order ?? 0),\n }\n })\n .sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))\n .map(({ id, name, slug }) => ({ id, name, slug }))\n : undefined\n\n // The visitor's controls, as clauses on the one declaration. A price\n // clause carries the dollars the slider showed, for a refusal's sentence.\n const priceClauses: ListFilterClause[] = [\n ...(params.minPriceCents != null\n ? [{\n field: 'price',\n op: '>=',\n value: String(params.minPriceCents),\n label: dollars(params.minPriceCents),\n }]\n : []),\n ...(params.maxPriceCents != null\n ? [{\n field: 'price',\n op: '<=',\n value: String(params.maxPriceCents),\n label: dollars(params.maxPriceCents),\n }]\n : []),\n ]\n const otherClauses: ListFilterClause[] = [\n ...(categoryId ? [{ field: 'category', op: 'contains', value: categoryId }] : []),\n ...(tag ? [{ field: 'tag', op: 'contains', value: tag }] : []),\n ...(type ? [{ field: 'type', op: 'equals', value: type }] : []),\n ...(params.inStock ? [{ field: 'stock', op: 'is', value: 'false' }] : []),\n ]\n // The words typed, as a quick search hands them over: the plan searches by\n // the first and says so when there were more.\n const search = query.split(/\\s+/).filter(Boolean)\n\n const result = (\n rows: CatalogRow[],\n plan: ListQueryPlan,\n extra: Partial<PublicCatalogResult> = {},\n ): PublicCatalogResult => {\n const refused = refusalsOf(plan)\n const notices = [...plan.notices, ...(extra.notices ?? [])]\n return {\n items: rows.map(toItem),\n ...(extra.nextCursor ? { nextCursor: extra.nextCursor } : {}),\n ...(categories ? { categories } : {}),\n ...(extra.priceBounds ? { priceBounds: extra.priceBounds } : {}),\n ...(refused.length ? { refused } : {}),\n ...(notices.length ? { notices } : {}),\n }\n }\n\n /*\n * A collection held WHOLE: a manual one's members, or a smart one whose\n * rules no query can hold. The plan still decides what is applied — the\n * same refusals as the query path, so a grid behaves the same whatever it\n * lists — and its predicates are answered over every held row.\n */\n const answerHeld = (\n rows: CatalogRow[],\n options: { manualOrder?: Map<string, number>; notices?: string[] },\n ): PublicCatalogResult => {\n // A member sold in person only is no row of the grid (AGL-4060).\n const held = rows.filter((row) => CommerceModel.productSellsOnline(row.product))\n const request: ListQueryRequest = {\n base: STOREFRONT_CATALOG_BASE,\n clauses: [...otherClauses, ...priceClauses],\n search,\n sort,\n }\n const plan = planFor(request, sort)\n const unpriced = planFor({ ...request, clauses: otherClauses }, sort)\n const matched = held.filter((row) => plan.filters.every((filter) => rowMatches(row, filter)))\n // Bounds span every OTHER control, so the slider stays anchored while the\n // visitor narrows it.\n const bounding = held.filter((row) =>\n unpriced.filters.every((filter) => rowMatches(row, filter)),\n )\n const priceBounds =\n wantFacets && bounding.length\n ? {\n minCents: Math.min(...bounding.map((row) => Number(rowValue(row, 'priceFromCents')))),\n maxCents: Math.max(...bounding.map((row) => Number(rowValue(row, 'priceFromCents')))),\n }\n : undefined\n // A manual collection keeps the merchant's order unless the visitor (or\n // the author) chose a price or recency sort.\n const keepManual =\n options.manualOrder && plan.orderBy.path === STOREFRONT_CATALOG_SORTS.name.path\n const page = keepManual\n ? pageHeldRows(\n matched,\n (row) => options.manualOrder?.get(row.id) ?? Number.MAX_SAFE_INTEGER,\n 'asc',\n params.after,\n max,\n )\n : pageHeldRows(\n matched,\n (row) => rowValue(row, plan.orderBy.path),\n plan.orderBy.direction,\n params.after,\n max,\n )\n return result(page.rows, plan, {\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n ...(priceBounds ? { priceBounds } : {}),\n ...(options.notices ? { notices: options.notices } : {}),\n })\n }\n\n let scope: ListQueryFilter[] = []\n if (collection) {\n if (collection.mode === 'manual') {\n const memberIds = (collection.productIds ?? []).slice(0, MANUAL_COLLECTION_MAX)\n const manualOrder = new Map(memberIds.map((id, index) => [id, index]))\n return answerHeld(await readProductsById(productsRef, memberIds), { manualOrder })\n }\n const smart = smartCollectionScope(collection)\n if (!(collection.rules ?? []).length) {\n // A smart collection with no rules holds nothing (`matchesCollection`).\n return result([], planFor({ base: STOREFRONT_CATALOG_BASE, clauses: [], sort }, sort))\n }\n if ('unservable' in smart) {\n // Rules no query can express (a NOT, an OR, a name rule, a price over)\n // are answered by the membership every product writer stores\n // (`collectionIds`, AGL-3321): one array clause on the same query, so\n // the grid's other array controls are refused by name beside it.\n scope = [\n {\n path: CommerceModel.PRODUCT_COLLECTION_IDS,\n op: 'array-contains',\n value: String(collectionDoc?.id ?? ''),\n },\n ]\n } else {\n scope = smart.filters\n // A \"type is not\" rule is `type in […]`; the visitor's Type chip is the\n // narrower question, answered inside it or not at all.\n const typeRule = scope.find((filter) => filter.path === 'type')\n if (typeRule && type) {\n const allowed = Array.isArray(typeRule.value) ? typeRule.value : [typeRule.value]\n if (!allowed.includes(type)) {\n return result([], planFor({ base: STOREFRONT_CATALOG_BASE, clauses: [], sort }, sort))\n }\n scope = scope.filter((filter) => filter !== typeRule)\n }\n }\n }\n\n // THE QUERY: every predicate, one order, a page and one row to spare.\n const request: ListQueryRequest = {\n base: [...STOREFRONT_CATALOG_BASE, ...scope],\n clauses: [...otherClauses, ...priceClauses],\n search,\n sort,\n }\n const plan = planFor(request, sort)\n const byId = firebaseAdmin.firestore.FieldPath.documentId()\n const ordered = (target: ListQueryPlan) =>\n applyListQuery(productsRef, target).orderBy(byId, target.orderBy.direction)\n let pageQuery = ordered(plan)\n const cursor = decodeCursor(params.after)\n if (cursor) pageQuery = pageQuery.startAfter(cursor.value, cursor.id)\n\n // Bounds span every OTHER control, so the slider stays anchored while the\n // visitor narrows it: the lowest and highest price the rest allows, as two\n // one-row reads ordered by price.\n const byPrice = STOREFRONT_CATALOG_SORTS['price-asc']\n const unpriced = wantFacets\n ? planFor({ ...request, clauses: otherClauses, sort: byPrice }, byPrice)\n : null\n const pricedBy = (target: ListQueryPlan, direction: 'asc' | 'desc') =>\n ordered({ ...target, orderBy: { path: 'priceFromCents', direction } }).limit(PRICE_BOUND_SCAN).get()\n // The first price sold online (AGL-4060): an in-person-only product's price\n // never anchors the slider.\n const boundOf = (snapshot: FirebaseFirestore.QuerySnapshot | null) =>\n snapshot?.docs\n .find((docSnapshot) => CommerceModel.productSellsOnline(docSnapshot.data()))\n ?.get('priceFromCents')\n\n const bounds = Promise.all([\n unpriced ? pricedBy(unpriced, 'asc') : null,\n unpriced ? pricedBy(unpriced, 'desc') : null,\n ])\n // A page of `max` rows sold online, read on past the ones sold in person\n // only (AGL-4038). The first read is the page and one row to spare, so a\n // catalog with none in person reads exactly as it did; each further read\n // doubles. The cursor follows the last row the page took.\n const rows: CatalogRow[] = []\n let last: FirebaseFirestore.QueryDocumentSnapshot | undefined\n let more: boolean\n let batch = max + 1\n let scanned = 0\n for (;;) {\n const { docs } = await pageQuery.limit(batch).get()\n scanned += docs.length\n let taken = 0\n while (taken < docs.length && rows.length < max) {\n last = docs[taken]\n taken += 1\n const row = toRow(last)\n if (row && CommerceModel.productSellsOnline(row.product)) rows.push(row)\n }\n const ended = docs.length < batch\n if (rows.length >= max) {\n // Full: more follow if this read holds another row sold online, or\n // did not reach the end of the scope.\n more =\n !ended ||\n docs.slice(taken).some((docSnapshot) => CommerceModel.productSellsOnline(docSnapshot.data()))\n break\n }\n more = !ended\n if (ended || !last || scanned >= CATALOG_FILL_SCAN_MAX) break\n pageQuery = ordered(plan).startAfter(last.get(plan.orderBy.path), last.id)\n batch = Math.min(batch * 2, CATALOG_FILL_SCAN_MAX - scanned)\n }\n const [lowest, highest] = await bounds\n const low = boundOf(lowest)\n const high = boundOf(highest)\n return result(rows, plan, {\n ...(last && more\n ? { nextCursor: encodeCursor(last.get(plan.orderBy.path), last.id) }\n : {}),\n ...(typeof low === 'number' && typeof high === 'number'\n ? { priceBounds: { minCents: low, maxCents: high } }\n : {}),\n })\n}\n\n/** Public catalog listing endpoint — a thin parse over queryPublicCatalog. */\nexport const catalogHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const result = await queryPublicCatalog({\n hostId,\n collectionSlug: String(req.query.collection ?? ''),\n categorySlug: String(req.query.category ?? ''),\n collectionId: String(req.query.collectionId ?? ''),\n categoryId: String(req.query.categoryId ?? ''),\n tag: String(req.query.tag ?? ''),\n query: String(req.query.q ?? ''),\n type: String(req.query.type ?? '') as CommerceModel.ProductType | '',\n inStock: String(req.query.inStock ?? '') === '1',\n ids: String(req.query.ids ?? '')\n .split(',')\n .map((id) => id.trim())\n .filter(Boolean),\n // Price-range filter (AGL-564): integer cents on the displayed price.\n minPriceCents: parsePriceCents(req.query.minPriceCents),\n maxPriceCents: parsePriceCents(req.query.maxPriceCents),\n sort: String(req.query.sort ?? 'name'),\n limit: Number(req.query.limit ?? CATALOG_PAGE_DEFAULT),\n after: String(req.query.after ?? ''),\n facets: String(req.query.facets ?? '') === '1',\n })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json(result)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Catalog unavailable' })\n }\n}\n"],"names":["nameSearchNormalizers","Aglyn","planListQuery","firebaseAdmin","applyListQuery","smartCollectionScope","STOREFRONT_CATALOG_BASE","STOREFRONT_CATALOG_DECLARATION","STOREFRONT_CATALOG_SORTS","STOREFRONT_PRODUCT_TYPES","storefrontCatalogSort","CommerceModel","productCardImage","product","candidates","mediaUrls","imageUrl","variants","map","variant","candidate","trim","undefined","parsePriceCents","value","raw","String","cents","Number","isFinite","Math","round","createCatalogReadScope","CATALOG_PAGE_MAX","CATALOG_PAGE_DEFAULT","MANUAL_COLLECTION_MAX","GET_ALL_CHUNK","CATALOG_FILL_SCAN_MAX","CATALOG_IDS_MAX","PRICE_BOUND_SCAN","toRow","docSnapshot","data","liftLegacyProduct","id","values","status","type","deletedAt","productSearchFields","name","productStockFields","rowValue","row","path","onSale","every","filter","rowMatches","productSellsOnline","actual","list","Array","isArray","op","includes","some","member","encodeCursor","Buffer","from","JSON","stringify","toString","decodeCursor","parsed","parse","length","compareValues","a","b","pageHeldRows","rows","key","direction","after","max","signed","ordered","sort","cursor","start","findIndex","page","slice","last","nextCursor","readProductsById","productsRef","ids","firestore","app","refs","doc","snapshots","getAll","snapshot","exists","push","toItem","minPrice","maxPrice","productPriceRange","primary","slug","priceUsd","maxPriceUsd","compareAtPriceUsd","soldOut","tags","variantHasPrice","priceComingSoon","variantCount","defaultVariantId","websiteModifiersRequired","requiresChoices","refusalsOf","plan","refused","refusal","clause","reason","startsWith","SORT_LABELS","nameLower","createdAtMs","RANGE_OPS","Set","planFor","request","orderBy","asked","byRule","base","has","notices","dollars","toFixed","queryPublicCatalog","params","reads","question","runPublicCatalog","results","Map","shared","get","pending","set","categoriesSnapshot","hostId","collectionSlug","categorySlug","collectionIdParam","collectionId","categoryIdParam","categoryId","tag","query","floor","limit","min","wantFacets","Boolean","facets","hostRef","collection","sharedCategories","categories","order","index","at","take","read","items","collectionsSnapshot","collectionByIdSnapshot","facetsSnapshot","Promise","all","where","collectionById","hostCollectionKind","collectionDoc","docs","find","localeCompare","priceClauses","minPriceCents","field","label","maxPriceCents","otherClauses","inStock","search","split","result","extra","priceBounds","answerHeld","options","held","clauses","unpriced","matched","filters","bounding","minCents","maxCents","keepManual","manualOrder","MAX_SAFE_INTEGER","scope","mode","memberIds","productIds","smart","rules","PRODUCT_COLLECTION_IDS","typeRule","allowed","byId","FieldPath","documentId","target","pageQuery","startAfter","byPrice","pricedBy","boundOf","bounds","more","batch","scanned","taken","ended","lowest","highest","low","high","catalogHandler","req","res","json","error","category","q","setHeader","console"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,qCAAoC;AAE1E,YAAYC,WAAW,sBAAqB;AAE5C,SAMEC,aAAa,QACR,6CAA4C;AACnD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,cAAc,QAAQ,6CAA4C;AAC3E,SACEC,oBAAoB,EACpBC,uBAAuB,EACvBC,8BAA8B,EAC9BC,wBAAwB,EACxBC,wBAAwB,EACxBC,qBAAqB,QAChB,2CAAuC;AAC9C,YAAYC,mBAAmB,oBAAU;AAkCzC;;;;;CAKC,GACD,OAAO,SAASC,iBACdC,OAA+E;QAGzEA,oBAEAA;IAHN,MAAMC,aAAa;YACbD,qBAAAA,QAAQE,SAAS,YAAjBF,qBAAqB,EAAE;QAC3BA,QAAQG,QAAQ;WACb,EAACH,oBAAAA,QAAQI,QAAQ,YAAhBJ,oBAAoB,EAAE,EAAEK,GAAG,CAAC,CAACC,UAAYA,QAAQH,QAAQ;KAC9D;IACD,KAAK,MAAMI,aAAaN,WAAY;QAClC,IAAI,OAAOM,cAAc,YAAYA,UAAUC,IAAI,IAAI,OAAOD,UAAUC,IAAI;IAC9E;IACA,OAAOC;AACT;AAsBA,wEAAwE,GACxE,SAASC,gBAAgBC,KAAc;IACrC,MAAMC,MAAMC,OAAOF,gBAAAA,QAAS,IAAIH,IAAI;IACpC,IAAI,CAACI,KAAK,OAAOH;IACjB,MAAMK,QAAQC,OAAOH;IACrB,IAAI,CAACG,OAAOC,QAAQ,CAACF,UAAUA,QAAQ,GAAG,OAAOL;IACjD,OA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KAAK,CAAC/E,IAAI,YAAdkK,kBAAkB;YAC/BjF,OAAO9I,QAAO+N,mBAAAA,IAAInF,KAAK,CAACE,KAAK,YAAfiF,mBAAmBzN;YACjCmD,OAAO3D,QAAOiO,mBAAAA,IAAInF,KAAK,CAACnF,KAAK,YAAfsK,mBAAmB;YACjC7E,QAAQpJ,QAAOiO,oBAAAA,IAAInF,KAAK,CAACM,MAAM,YAAhB6E,oBAAoB,QAAQ;QAC7C;QACAC,IAAIK,SAAS,CACX,iBACA;QAEF,OAAOL,IAAI9M,MAAM,CAAC,KAAK+M,IAAI,CAAC/C;IAC9B,EAAE,OAAOgD,OAAO;QACdI,QAAQJ,KAAK,CAACA;QACd,OAAOF,IAAI9M,MAAM,CAAC,KAAK+M,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
@@ -33,4 +33,4 @@
33
33
  * this as a failure to retry, never as closed.
34
34
  */
35
35
  export type CheckoutSessionExpiry = 'expired' | 'complete' | 'missing' | 'open';
36
- export declare function expireCheckoutSession(sessionId: string): Promise<CheckoutSessionExpiry>;
36
+ export declare function expireCheckoutSession(sessionId: string, sellerAccount?: string | null): Promise<CheckoutSessionExpiry>;
@@ -30,16 +30,30 @@
30
30
  * - `missing`: Stripe does not know it (another mode's id, or never created).
31
31
  * - `open`: it could not be closed and may still be paid. The caller treats
32
32
  * this as a failure to retry, never as closed.
33
- */ const SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/;
34
- export async function expireCheckoutSession(sessionId) {
35
- var _process_env_STRIPE_SECRET_KEY;
33
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
34
+ const SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/;
35
+ export async function expireCheckoutSession(sessionId, sellerAccount) {
36
36
  if (!SESSION_ID.test(String(sessionId != null ? sessionId : ''))) return 'missing';
37
+ // A direct-charge session lives on the seller's account. Asked there first,
38
+ // then on the platform, where a session opened before the seller switched
39
+ // (or Aglyn's own hardware sale) lives: left open, either is a second way
40
+ // to pay.
41
+ if (sellerAccount) {
42
+ const onSeller = await expireOn(sessionId, sellerAccount);
43
+ if (onSeller !== 'missing') return onSeller;
44
+ }
45
+ return expireOn(sessionId, null);
46
+ }
47
+ async function expireOn(sessionId, account) {
48
+ var _process_env_STRIPE_SECRET_KEY;
37
49
  const secretKey = String((_process_env_STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY) != null ? _process_env_STRIPE_SECRET_KEY : '').trim();
38
50
  if (!secretKey) return 'open';
39
- const headers = {
51
+ const headers = _extends({
40
52
  Authorization: `Bearer ${secretKey}`,
41
53
  'Content-Type': 'application/x-www-form-urlencoded'
42
- };
54
+ }, account ? {
55
+ 'Stripe-Account': account
56
+ } : {});
43
57
  try {
44
58
  const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {
45
59
  method: 'POST',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/checkout-session-expiry.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Closing a Checkout Session so it can no longer be paid, and saying what it\n * was (AGL-4094).\n *\n * Stripe answers 200 to `expire` for a session that was open, and 400 for one\n * that is not — already expired, or already PAID. Those two must not be read\n * alike: a caller about to open a fresh session for the same quote has to\n * know that the old one was paid a moment ago, or it hands the customer a\n * second way to pay. So a refused expiry reads the session back and answers\n * its status.\n *\n * - `expired`: it can no longer be paid (it was open and is now closed, or it\n * had expired already).\n * - `complete`: it was paid; the webhook has, or will, record it.\n * - `missing`: Stripe does not know it (another mode's id, or never created).\n * - `open`: it could not be closed and may still be paid. The caller treats\n * this as a failure to retry, never as closed.\n */\nexport type CheckoutSessionExpiry = 'expired' | 'complete' | 'missing' | 'open'\n\nconst SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/\n\nexport async function expireCheckoutSession(sessionId: string): Promise<CheckoutSessionExpiry> {\n if (!SESSION_ID.test(String(sessionId ?? ''))) return 'missing'\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) return 'open'\n const headers = {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n try {\n const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {\n method: 'POST',\n headers,\n })\n if (expired.ok) return 'expired'\n const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, { headers })\n if (read.status === 404) return 'missing'\n if (!read.ok) return 'open'\n const session = (await read.json().catch(() => ({}))) as { status?: string }\n if (session.status === 'complete') return 'complete'\n if (session.status === 'expired') return 'expired'\n return 'open'\n } catch {\n return 'open'\n }\n}\n"],"names":["SESSION_ID","expireCheckoutSession","sessionId","process","test","String","secretKey","env","STRIPE_SECRET_KEY","trim","headers","Authorization","expired","fetch","method","ok","read","status","session","json","catch"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAGD,MAAMA,aAAa;AAEnB,OAAO,eAAeC,sBAAsBC,SAAiB;QAElCC;IADzB,IAAI,CAACH,WAAWI,IAAI,CAACC,OAAOH,oBAAAA,YAAa,MAAM,OAAO;IACtD,MAAMI,YAAYD,QAAOF,iCAAAA,QAAQI,GAAG,CAACC,iBAAiB,YAA7BL,iCAAiC,IAAIM,IAAI;IAClE,IAAI,CAACH,WAAW,OAAO;IACvB,MAAMI,UAAU;QACdC,eAAe,CAAC,OAAO,EAAEL,WAAW;QACpC,gBAAgB;IAClB;IACA,IAAI;QACF,MAAMM,UAAU,MAAMC,MAAM,CAAC,4CAA4C,EAAEX,UAAU,OAAO,CAAC,EAAE;YAC7FY,QAAQ;YACRJ;QACF;QACA,IAAIE,QAAQG,EAAE,EAAE,OAAO;QACvB,MAAMC,OAAO,MAAMH,MAAM,CAAC,4CAA4C,EAAEX,WAAW,EAAE;YAAEQ;QAAQ;QAC/F,IAAIM,KAAKC,MAAM,KAAK,KAAK,OAAO;QAChC,IAAI,CAACD,KAAKD,EAAE,EAAE,OAAO;QACrB,MAAMG,UAAW,MAAMF,KAAKG,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;QACjD,IAAIF,QAAQD,MAAM,KAAK,YAAY,OAAO;QAC1C,IAAIC,QAAQD,MAAM,KAAK,WAAW,OAAO;QACzC,OAAO;IACT,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/checkout-session-expiry.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Closing a Checkout Session so it can no longer be paid, and saying what it\n * was (AGL-4094).\n *\n * Stripe answers 200 to `expire` for a session that was open, and 400 for one\n * that is not — already expired, or already PAID. Those two must not be read\n * alike: a caller about to open a fresh session for the same quote has to\n * know that the old one was paid a moment ago, or it hands the customer a\n * second way to pay. So a refused expiry reads the session back and answers\n * its status.\n *\n * - `expired`: it can no longer be paid (it was open and is now closed, or it\n * had expired already).\n * - `complete`: it was paid; the webhook has, or will, record it.\n * - `missing`: Stripe does not know it (another mode's id, or never created).\n * - `open`: it could not be closed and may still be paid. The caller treats\n * this as a failure to retry, never as closed.\n */\nexport type CheckoutSessionExpiry = 'expired' | 'complete' | 'missing' | 'open'\n\nconst SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/\n\nexport async function expireCheckoutSession(\n sessionId: string,\n sellerAccount?: string | null,\n): Promise<CheckoutSessionExpiry> {\n if (!SESSION_ID.test(String(sessionId ?? ''))) return 'missing'\n // A direct-charge session lives on the seller's account. Asked there first,\n // then on the platform, where a session opened before the seller switched\n // (or Aglyn's own hardware sale) lives: left open, either is a second way\n // to pay.\n if (sellerAccount) {\n const onSeller = await expireOn(sessionId, sellerAccount)\n if (onSeller !== 'missing') return onSeller\n }\n return expireOn(sessionId, null)\n}\n\nasync function expireOn(\n sessionId: string,\n account: string | null,\n): Promise<CheckoutSessionExpiry> {\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) return 'open'\n const headers = {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(account ? { 'Stripe-Account': account } : {}),\n }\n try {\n const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {\n method: 'POST',\n headers,\n })\n if (expired.ok) return 'expired'\n const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, { headers })\n if (read.status === 404) return 'missing'\n if (!read.ok) return 'open'\n const session = (await read.json().catch(() => ({}))) as { status?: string }\n if (session.status === 'complete') return 'complete'\n if (session.status === 'expired') return 'expired'\n return 'open'\n } catch {\n return 'open'\n }\n}\n"],"names":["SESSION_ID","expireCheckoutSession","sessionId","sellerAccount","test","String","onSeller","expireOn","account","process","secretKey","env","STRIPE_SECRET_KEY","trim","headers","Authorization","expired","fetch","method","ok","read","status","session","json","catch"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC;AAGD,MAAMA,aAAa;AAEnB,OAAO,eAAeC,sBACpBC,SAAiB,EACjBC,aAA6B;IAE7B,IAAI,CAACH,WAAWI,IAAI,CAACC,OAAOH,oBAAAA,YAAa,MAAM,OAAO;IACtD,4EAA4E;IAC5E,0EAA0E;IAC1E,0EAA0E;IAC1E,UAAU;IACV,IAAIC,eAAe;QACjB,MAAMG,WAAW,MAAMC,SAASL,WAAWC;QAC3C,IAAIG,aAAa,WAAW,OAAOA;IACrC;IACA,OAAOC,SAASL,WAAW;AAC7B;AAEA,eAAeK,SACbL,SAAiB,EACjBM,OAAsB;QAEGC;IAAzB,MAAMC,YAAYL,QAAOI,iCAAAA,QAAQE,GAAG,CAACC,iBAAiB,YAA7BH,iCAAiC,IAAII,IAAI;IAClE,IAAI,CAACH,WAAW,OAAO;IACvB,MAAMI,UAAU;QACdC,eAAe,CAAC,OAAO,EAAEL,WAAW;QACpC,gBAAgB;OACZF,UAAU;QAAE,kBAAkBA;IAAQ,IAAI,CAAC;IAEjD,IAAI;QACF,MAAMQ,UAAU,MAAMC,MAAM,CAAC,4CAA4C,EAAEf,UAAU,OAAO,CAAC,EAAE;YAC7FgB,QAAQ;YACRJ;QACF;QACA,IAAIE,QAAQG,EAAE,EAAE,OAAO;QACvB,MAAMC,OAAO,MAAMH,MAAM,CAAC,4CAA4C,EAAEf,WAAW,EAAE;YAAEY;QAAQ;QAC/F,IAAIM,KAAKC,MAAM,KAAK,KAAK,OAAO;QAChC,IAAI,CAACD,KAAKD,EAAE,EAAE,OAAO;QACrB,MAAMG,UAAW,MAAMF,KAAKG,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;QACjD,IAAIF,QAAQD,MAAM,KAAK,YAAY,OAAO;QAC1C,IAAIC,QAAQD,MAAM,KAAK,WAAW,OAAO;QACzC,OAAO;IACT,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
@@ -13,7 +13,8 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ /**
16
+ */ import { directSellerAccountForHost, fetchOnSellerThenPlatform } from "./seller-stripe-account.js";
17
+ /**
17
18
  * What became of a storefront Checkout Session, for the page Stripe returned
18
19
  * the shopper to (AGL-3606).
19
20
  *
@@ -70,11 +71,11 @@ export const checkoutStatusHandler = async (req, res)=>{
70
71
  try {
71
72
  var _ref, _session_status, _session_payment_status;
72
73
  var _session_metadata;
73
- const response = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, {
74
+ const response = await fetchOnSellerThenPlatform(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, {
74
75
  headers: {
75
76
  Authorization: `Bearer ${secretKey}`
76
77
  }
77
- });
78
+ }, await directSellerAccountForHost(hostId));
78
79
  if (!response.ok) {
79
80
  // A test-mode id under a live key (or the reverse) is a 404 at Stripe,
80
81
  // and so is an id that never existed. Both are "not ours".
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/checkout-status.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'\n\n/**\n * What became of a storefront Checkout Session, for the page Stripe returned\n * the shopper to (AGL-3606).\n *\n * ## Why the return page has to ask\n *\n * The in-page checkout sends every successful confirm to `return_url` — the\n * same `?order=success&session_id=…` the hosted redirect lands on. But a\n * redirect-based payment method (a bank redirect, a wallet that leaves the\n * page) comes back to that SAME url when the shopper abandons or fails the\n * bank step, with the session still open and nothing charged. The url alone\n * cannot tell the two apart, so a shopper whose bank step failed was shown a\n * store that said nothing at all, and had no reason to try again.\n *\n * ## What it answers, and what it never does\n *\n * Only the session's `status` and `payment_status`, and only for a session\n * this host created (`metadata[hostId]`, which both checkout routes set). No\n * email, no address, no amount, and no client secret: the session id rides a\n * url that lands in browser history and referrers, and must not become a key\n * to the shopper's details or to paying for their basket.\n *\n * It does not fulfil, and its answer fulfils nothing: the order is still\n * `checkout.session.completed` in `billing-webhook.ts`, and nothing here\n * writes anywhere.\n */\n\nconst SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/\n\nexport type CheckoutReturnStatus = 'open' | 'complete' | 'expired'\n\nexport const checkoutStatusHandler: PluginApiHandler = async (req, res) => {\n if (req.method && req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query.hostId ?? '').trim()\n const sessionId = String(req.query.sessionId ?? '').trim()\n if (!hostId || !sessionId) {\n return res.status(400).json({ error: 'Missing hostId or sessionId' })\n }\n // Shape-checked before it is interpolated into a Stripe URL path.\n if (!SESSION_ID.test(sessionId)) {\n return res.status(400).json({ error: 'Invalid sessionId' })\n }\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) {\n return res.status(501).json({ error: 'Payments are not configured' })\n }\n res.setHeader('Cache-Control', 'no-store')\n try {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${sessionId}`,\n { headers: { Authorization: `Bearer ${secretKey}` } },\n )\n if (!response.ok) {\n // A test-mode id under a live key (or the reverse) is a 404 at Stripe,\n // and so is an id that never existed. Both are \"not ours\".\n return res.status(404).json({ error: 'Not found' })\n }\n const session = (await response.json()) as {\n status?: string\n payment_status?: string\n metadata?: Record<string, string>\n }\n // The same 404 as a missing session, so this route cannot be used to\n // learn that a session exists on ANOTHER merchant's storefront.\n if (String(session?.metadata?.hostId ?? '') !== hostId) {\n return res.status(404).json({ error: 'Not found' })\n }\n const status = String(session.status ?? '')\n if (status !== 'open' && status !== 'complete' && status !== 'expired') {\n return res.status(404).json({ error: 'Not found' })\n }\n return res.status(200).json({\n status: status as CheckoutReturnStatus,\n paymentStatus: String(session.payment_status ?? ''),\n })\n } catch (error) {\n console.error('checkout-status lookup failed', error)\n return res.status(502).json({ error: 'Lookup failed' })\n }\n}\n"],"names":["SESSION_ID","checkoutStatusHandler","req","res","process","method","setHeader","status","json","error","hostId","String","query","trim","sessionId","test","secretKey","env","STRIPE_SECRET_KEY","session","response","fetch","headers","Authorization","ok","metadata","paymentStatus","payment_status","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GAED,MAAMA,aAAa;AAInB,OAAO,MAAMC,wBAA0C,OAAOC,KAAKC;QAK3CD,mBACGA,sBAQAE;IAbzB,IAAIF,IAAIG,MAAM,IAAIH,IAAIG,MAAM,KAAK,OAAO;QACtCF,IAAIG,SAAS,CAAC,SAAS;QACvB,OAAOH,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,QAAOT,oBAAAA,IAAIU,KAAK,CAACF,MAAM,YAAhBR,oBAAoB,IAAIW,IAAI;IAClD,MAAMC,YAAYH,QAAOT,uBAAAA,IAAIU,KAAK,CAACE,SAAS,YAAnBZ,uBAAuB,IAAIW,IAAI;IACxD,IAAI,CAACH,UAAU,CAACI,WAAW;QACzB,OAAOX,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA8B;IACrE;IACA,kEAAkE;IAClE,IAAI,CAACT,WAAWe,IAAI,CAACD,YAAY;QAC/B,OAAOX,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAoB;IAC3D;IACA,MAAMO,YAAYL,QAAOP,iCAAAA,QAAQa,GAAG,CAACC,iBAAiB,YAA7Bd,iCAAiC,IAAIS,IAAI;IAClE,IAAI,CAACG,WAAW;QACd,OAAOb,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA8B;IACrE;IACAN,IAAIG,SAAS,CAAC,iBAAiB;IAC/B,IAAI;kBAoBoBa,iBAMEA;YATbA;QAhBX,MAAMC,WAAW,MAAMC,MACrB,CAAC,4CAA4C,EAAEP,WAAW,EAC1D;YAAEQ,SAAS;gBAAEC,eAAe,CAAC,OAAO,EAAEP,WAAW;YAAC;QAAE;QAEtD,IAAI,CAACI,SAASI,EAAE,EAAE;YAChB,uEAAuE;YACvE,2DAA2D;YAC3D,OAAOrB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAY;QACnD;QACA,MAAMU,UAAW,MAAMC,SAASZ,IAAI;QAKpC,qEAAqE;QACrE,gEAAgE;QAChE,IAAIG,eAAOQ,4BAAAA,oBAAAA,QAASM,QAAQ,qBAAjBN,kBAAmBT,MAAM,mBAAI,QAAQA,QAAQ;YACtD,OAAOP,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAY;QACnD;QACA,MAAMF,SAASI,QAAOQ,kBAAAA,QAAQZ,MAAM,YAAdY,kBAAkB;QACxC,IAAIZ,WAAW,UAAUA,WAAW,cAAcA,WAAW,WAAW;YACtE,OAAOJ,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAY;QACnD;QACA,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BD,QAAQA;YACRmB,eAAef,QAAOQ,0BAAAA,QAAQQ,cAAc,YAAtBR,0BAA0B;QAClD;IACF,EAAE,OAAOV,OAAO;QACdmB,QAAQnB,KAAK,CAAC,iCAAiCA;QAC/C,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/checkout-status.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 { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\n\n/**\n * What became of a storefront Checkout Session, for the page Stripe returned\n * the shopper to (AGL-3606).\n *\n * ## Why the return page has to ask\n *\n * The in-page checkout sends every successful confirm to `return_url` — the\n * same `?order=success&session_id=…` the hosted redirect lands on. But a\n * redirect-based payment method (a bank redirect, a wallet that leaves the\n * page) comes back to that SAME url when the shopper abandons or fails the\n * bank step, with the session still open and nothing charged. The url alone\n * cannot tell the two apart, so a shopper whose bank step failed was shown a\n * store that said nothing at all, and had no reason to try again.\n *\n * ## What it answers, and what it never does\n *\n * Only the session's `status` and `payment_status`, and only for a session\n * this host created (`metadata[hostId]`, which both checkout routes set). No\n * email, no address, no amount, and no client secret: the session id rides a\n * url that lands in browser history and referrers, and must not become a key\n * to the shopper's details or to paying for their basket.\n *\n * It does not fulfil, and its answer fulfils nothing: the order is still\n * `checkout.session.completed` in `billing-webhook.ts`, and nothing here\n * writes anywhere.\n */\n\nconst SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/\n\nexport type CheckoutReturnStatus = 'open' | 'complete' | 'expired'\n\nexport const checkoutStatusHandler: PluginApiHandler = async (req, res) => {\n if (req.method && req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query.hostId ?? '').trim()\n const sessionId = String(req.query.sessionId ?? '').trim()\n if (!hostId || !sessionId) {\n return res.status(400).json({ error: 'Missing hostId or sessionId' })\n }\n // Shape-checked before it is interpolated into a Stripe URL path.\n if (!SESSION_ID.test(sessionId)) {\n return res.status(400).json({ error: 'Invalid sessionId' })\n }\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) {\n return res.status(501).json({ error: 'Payments are not configured' })\n }\n res.setHeader('Cache-Control', 'no-store')\n try {\n const response = await fetchOnSellerThenPlatform(\n `https://api.stripe.com/v1/checkout/sessions/${sessionId}`,\n { headers: { Authorization: `Bearer ${secretKey}` } },\n await directSellerAccountForHost(hostId),\n )\n if (!response.ok) {\n // A test-mode id under a live key (or the reverse) is a 404 at Stripe,\n // and so is an id that never existed. Both are \"not ours\".\n return res.status(404).json({ error: 'Not found' })\n }\n const session = (await response.json()) as {\n status?: string\n payment_status?: string\n metadata?: Record<string, string>\n }\n // The same 404 as a missing session, so this route cannot be used to\n // learn that a session exists on ANOTHER merchant's storefront.\n if (String(session?.metadata?.hostId ?? '') !== hostId) {\n return res.status(404).json({ error: 'Not found' })\n }\n const status = String(session.status ?? '')\n if (status !== 'open' && status !== 'complete' && status !== 'expired') {\n return res.status(404).json({ error: 'Not found' })\n }\n return res.status(200).json({\n status: status as CheckoutReturnStatus,\n paymentStatus: String(session.payment_status ?? ''),\n })\n } catch (error) {\n console.error('checkout-status lookup failed', error)\n return res.status(502).json({ error: 'Lookup failed' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","SESSION_ID","checkoutStatusHandler","req","res","process","method","setHeader","status","json","error","hostId","String","query","trim","sessionId","test","secretKey","env","STRIPE_SECRET_KEY","session","response","headers","Authorization","ok","metadata","paymentStatus","payment_status","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAG/F;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GAED,MAAMC,aAAa;AAInB,OAAO,MAAMC,wBAA0C,OAAOC,KAAKC;QAK3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