@aglyn/plugins-commerce 1.0.0-beta.231 → 1.0.0-beta.232

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 (56) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/catalog-organization-card.component.js +1 -0
  3. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  4. package/src/lib/components/console/host-orders-card.component.js +4 -1
  5. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  6. package/src/lib/components/console/pos-page.component.js +56 -26
  7. package/src/lib/components/console/pos-page.component.js.map +1 -1
  8. package/src/lib/components/console/pos-zones.d.ts +23 -0
  9. package/src/lib/components/console/pos-zones.js +31 -0
  10. package/src/lib/components/console/pos-zones.js.map +1 -0
  11. package/src/lib/components/console/product-editor-dialog.component.js +10 -64
  12. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  13. package/src/lib/components/console/products-hub-card.component.js +11 -20
  14. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  15. package/src/lib/components/console/storefront-tax-summary-card.component.js +1 -0
  16. package/src/lib/components/console/storefront-tax-summary-card.component.js.map +1 -1
  17. package/src/lib/declarations.server.js +21 -0
  18. package/src/lib/declarations.server.js.map +1 -1
  19. package/src/lib/model/commerce-orders.d.ts +44 -1
  20. package/src/lib/model/commerce-orders.js +2 -1
  21. package/src/lib/model/commerce-orders.js.map +1 -1
  22. package/src/lib/model/commerce.d.ts +4 -1
  23. package/src/lib/model/commerce.js.map +1 -1
  24. package/src/lib/model/index.d.ts +1 -0
  25. package/src/lib/model/index.js +1 -0
  26. package/src/lib/model/index.js.map +1 -1
  27. package/src/lib/model/product-write.d.ts +186 -0
  28. package/src/lib/model/product-write.js +116 -0
  29. package/src/lib/model/product-write.js.map +1 -0
  30. package/src/lib/plugin.js +3 -0
  31. package/src/lib/plugin.js.map +1 -1
  32. package/src/lib/server/channel-order-updates.d.ts +50 -0
  33. package/src/lib/server/channel-order-updates.js +290 -0
  34. package/src/lib/server/channel-order-updates.js.map +1 -0
  35. package/src/lib/server/channel-orders.d.ts +85 -0
  36. package/src/lib/server/channel-orders.js +543 -0
  37. package/src/lib/server/channel-orders.js.map +1 -0
  38. package/src/lib/server/product-catalog.js +5 -1
  39. package/src/lib/server/product-catalog.js.map +1 -1
  40. package/src/lib/server/product-drafts.d.ts +5 -1
  41. package/src/lib/server/product-drafts.js +3 -3
  42. package/src/lib/server/product-drafts.js.map +1 -1
  43. package/src/lib/server/product-writer.d.ts +19 -0
  44. package/src/lib/server/product-writer.js +261 -0
  45. package/src/lib/server/product-writer.js.map +1 -0
  46. package/src/lib/server/products-write.d.ts +61 -0
  47. package/src/lib/server/products-write.js +375 -0
  48. package/src/lib/server/products-write.js.map +1 -0
  49. package/src/lib/server.js +5 -0
  50. package/src/lib/server.js.map +1 -1
  51. package/src/lib/testing/memory-firestore.d.ts +16 -3
  52. package/src/lib/testing/memory-firestore.js +11 -3
  53. package/src/lib/testing/memory-firestore.js.map +1 -1
  54. package/src/lib/transfer/products.server.d.ts +5 -0
  55. package/src/lib/transfer/products.server.js +2 -2
  56. package/src/lib/transfer/products.server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.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/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","req","res","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,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,uBAAuB,oBAAoBkF;IAC3C,yEAAyE;IACzE,kDAAkD;IAClDlF,uBAAuB,2BAA2BgF;IAClDhF,uBAAuB,4BAA4BoF;IACnD,qEAAqE;IACrE,kCAAkC;IAClCpF,uBAAuB,oCAAoC,OAAO4H,KAAKC,MACrE,AAAC,CAAA,MAAM,MAAM,CAAC,sCAAkC,EAAGC,4BAA4B,CAACF,KAAKC;IAEvF,wEAAwE;IACxE,wEAAwE;IACxE,wEAAwE;IACxE,yEAAyE;IACzE,sEAAsE;IACtE7H,uBACE,gCACA;QACEkH,KAAK,OAAOC,SAASK,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,0BAAsB,EAAGO,gBAAgB,CAACZ,SAASK;IACrE,GACA;QAAEE,SAAS;IAAK;IAElB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,oEAAoE;IACpE1H,uBACE,iCACA;QACEkH,KAAK,OAAOC,SAASK,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGQ,iBAAiB,CAACb,SAASK;IACvE,GACA;QAAEE,SAAS;IAAK;IAElB,uEAAuE;IACvE,mCAAmC;IACnC1H,uBAAuB,gCAAgC,OAAO4H,KAAKC,MACjE,AAAC,CAAA,MAAM,MAAM,CAAC,kCAA8B,EAAGI,yBAAyB,CAACL,KAAKC;IAEhF,qEAAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvDxG,2BAA2B,IAAMd,cAAc2H,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.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/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","req","res","productSaveHandler","productStockHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,0BAAsB;AACjE,SAASC,uBAAuB,QAAQ,wDAAuD;AAC/F,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,oBAAoB,QAAQ,gCAA4B;AACjE,SAASC,sBAAsB,QAAQ,qBAAiB;AACxD,SAASC,wBAAwB,QAAQ,iCAA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ACd,SAASS;IACrE,GACA;QAAEE,SAAS;IAAK;IAElB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,oEAAoE;IACpE9H,uBACE,iCACA;QACEkH,KAAK,OAAOC,SAASS,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGM,iBAAiB,CAACf,SAASS;IACvE,GACA;QAAEE,SAAS;IAAK;IAElB,uEAAuE;IACvE,mCAAmC;IACnC9H,uBAAuB,gCAAgC,OAAOuH,KAAKC,MACjE,AAAC,CAAA,MAAM,MAAM,CAAC,kCAA8B,EAAGW,yBAAyB,CAACZ,KAAKC;IAEhF,qEAAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvDnG,2BAA2B,IAAMd,cAAc6H,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
@@ -24,7 +24,8 @@
24
24
  * interleave, which is what a race spec needs.
25
25
  *
26
26
  * Supports: `collection().doc()`, `get`, `set` (with `merge`), `create`,
27
- * `update`, `delete`; queries with `==` and `in`, `orderBy`, `limit`;
27
+ * `update`, `delete`; queries with `==`, `in` and `array-contains`, `orderBy`, `limit`,
28
+ * and a collection's `count()`;
28
29
  * `runTransaction` with `get` (document or query), `set`, `update`;
29
30
  * `batch()`. Field paths are top-level only.
30
31
  */
@@ -59,13 +60,18 @@ export declare class MemoryCollection {
59
60
  readonly path: string;
60
61
  constructor(store: MemoryFirestore, path: string);
61
62
  doc(id?: string): MemoryDoc;
62
- where(field: string, op: '==' | 'in', value: unknown): MemoryQuery;
63
+ where(field: string, op: MemoryFilterOp, value: unknown): MemoryQuery;
63
64
  orderBy(field: string, direction?: 'asc' | 'desc'): MemoryQuery;
64
65
  limit(count: number): MemoryQuery;
66
+ /** The aggregate: its result's `data().count`. */
67
+ count(): MemoryQuery;
65
68
  get(): Promise<{
66
69
  docs: MemoryDocSnapshot[];
67
70
  size: number;
68
71
  empty: boolean;
72
+ data: () => {
73
+ count: number;
74
+ };
69
75
  }>;
70
76
  }
71
77
  /** What a {@link MemoryDoc} read returns, shaped like a Firestore snapshot. */
@@ -96,6 +102,7 @@ export declare class MemoryDoc {
96
102
  update(data: Record<string, any>): Promise<void>;
97
103
  delete(): Promise<void>;
98
104
  }
105
+ export type MemoryFilterOp = '==' | 'in' | 'array-contains';
99
106
  export declare class MemoryQuery {
100
107
  readonly store: MemoryFirestore;
101
108
  readonly path: string;
@@ -104,13 +111,16 @@ export declare class MemoryQuery {
104
111
  private max;
105
112
  constructor(store: MemoryFirestore, path: string);
106
113
  private clone;
107
- where(field: string, op: '==' | 'in', value: unknown): MemoryQuery;
114
+ where(field: string, op: MemoryFilterOp, value: unknown): MemoryQuery;
108
115
  orderBy(field: string, direction?: 'asc' | 'desc'): MemoryQuery;
109
116
  limit(count: number): MemoryQuery;
110
117
  run(): {
111
118
  docs: MemoryDocSnapshot[];
112
119
  size: number;
113
120
  empty: boolean;
121
+ data: () => {
122
+ count: number;
123
+ };
114
124
  };
115
125
  /** The paths and versions this query matches now, to detect a changed result. */
116
126
  signature(): string;
@@ -118,6 +128,9 @@ export declare class MemoryQuery {
118
128
  docs: MemoryDocSnapshot[];
119
129
  size: number;
120
130
  empty: boolean;
131
+ data: () => {
132
+ count: number;
133
+ };
121
134
  }>;
122
135
  }
123
136
  export {};
@@ -23,7 +23,8 @@
23
23
  * interleave, which is what a race spec needs.
24
24
  *
25
25
  * Supports: `collection().doc()`, `get`, `set` (with `merge`), `create`,
26
- * `update`, `delete`; queries with `==` and `in`, `orderBy`, `limit`;
26
+ * `update`, `delete`; queries with `==`, `in` and `array-contains`, `orderBy`, `limit`,
27
+ * and a collection's `count()`;
27
28
  * `runTransaction` with `get` (document or query), `set`, `update`;
28
29
  * `batch()`. Field paths are top-level only.
29
30
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
@@ -132,6 +133,9 @@ export class MemoryCollection {
132
133
  limit(count) {
133
134
  return new MemoryQuery(this.store, this.path).limit(count);
134
135
  }
136
+ /** The aggregate: its result's `data().count`. */ count() {
137
+ return new MemoryQuery(this.store, this.path);
138
+ }
135
139
  get() {
136
140
  return Promise.resolve(new MemoryQuery(this.store, this.path).run());
137
141
  }
@@ -241,7 +245,7 @@ export class MemoryQuery {
241
245
  const prefix = `${this.path}/`;
242
246
  let rows = [
243
247
  ...this.store.docs.entries()
244
- ].filter(([path])=>path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).filter(([, stored])=>this.filters.every(({ field, op, value })=>op === 'in' ? value.includes(stored.data[field]) : stored.data[field] === value));
248
+ ].filter(([path])=>path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).filter(([, stored])=>this.filters.every(({ field, op, value })=>op === 'in' ? value.includes(stored.data[field]) : op === 'array-contains' ? Array.isArray(stored.data[field]) && stored.data[field].includes(value) : stored.data[field] === value));
245
249
  if (this.order) {
246
250
  const { field, direction } = this.order;
247
251
  rows = rows.sort(([, a], [, b])=>{
@@ -250,10 +254,14 @@ export class MemoryQuery {
250
254
  });
251
255
  }
252
256
  const docs = rows.slice(0, this.max).map(([path])=>new MemoryDoc(this.store, path).snapshot());
257
+ // `data()` answers a `count()` aggregate read through the same query.
253
258
  return {
254
259
  docs,
255
260
  size: docs.length,
256
- empty: docs.length === 0
261
+ empty: docs.length === 0,
262
+ data: ()=>({
263
+ count: docs.length
264
+ })
257
265
  };
258
266
  }
259
267
  /** The paths and versions this query matches now, to detect a changed result. */ signature() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/testing/memory-firestore.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 * A small in-memory stand-in for the firebase-admin Firestore surface the\n * print queue uses (AGL-3619), for specs. Transactions are OPTIMISTIC, as\n * Firestore's server SDK effectively is under contention: every read records\n * the version it saw, the commit re-checks them (and re-runs any query read\n * in the transaction), and a conflict retries the whole function. Each read\n * yields to the event loop, so two transactions started together really do\n * interleave, which is what a race spec needs.\n *\n * Supports: `collection().doc()`, `get`, `set` (with `merge`), `create`,\n * `update`, `delete`; queries with `==` and `in`, `orderBy`, `limit`;\n * `runTransaction` with `get` (document or query), `set`, `update`;\n * `batch()`. Field paths are top-level only.\n */\n\ninterface Stored {\n data: Record<string, any>\n version: number\n}\n\nconst tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0))\n\nexport class MemoryFirestore {\n readonly docs = new Map<string, Stored>()\n private autoId = 0\n private clock = 0\n /** Committed transactions that had to retry, for specs that assert contention happened. */\n retries = 0\n\n collection(path: string): MemoryCollection {\n return new MemoryCollection(this, path)\n }\n\n /** The document at a slash path, for assertions. */\n read(path: string): Record<string, any> | undefined {\n const stored = this.docs.get(path)\n return stored ? { ...stored.data } : undefined\n }\n\n nextId(): string {\n this.autoId += 1\n return `auto${String(this.autoId).padStart(4, '0')}`\n }\n\n write(path: string, data: Record<string, any> | null): void {\n this.clock += 1\n if (data === null) this.docs.delete(path)\n else this.docs.set(path, { data: { ...data }, version: this.clock })\n }\n\n version(path: string): number {\n return this.docs.get(path)?.version ?? 0\n }\n\n batch() {\n const ops: Array<() => void> = []\n return {\n set: (ref: MemoryDoc, data: any, options?: { merge?: boolean }) =>\n ops.push(() => ref.applySet(data, options)),\n update: (ref: MemoryDoc, data: any) => ops.push(() => ref.applyUpdate(data)),\n delete: (ref: MemoryDoc) => ops.push(() => this.write(ref.path, null)),\n commit: async () => {\n await tick()\n for (const op of ops) op()\n },\n }\n }\n\n async runTransaction<T>(fn: (transaction: any) => Promise<T>): Promise<T> {\n for (let attempt = 0; attempt < 10; attempt += 1) {\n const seen = new Map<string, number>()\n const queries: Array<{ query: MemoryQuery; snapshot: string }> = []\n const writes: Array<() => void> = []\n const transaction = {\n get: async (target: MemoryDoc | MemoryQuery) => {\n await tick()\n if (target instanceof MemoryDoc) {\n seen.set(target.path, this.version(target.path))\n return target.snapshot()\n }\n const result = target.run()\n queries.push({ query: target, snapshot: target.signature() })\n for (const doc of result.docs) seen.set(doc.ref.path, this.version(doc.ref.path))\n return result\n },\n set: (ref: MemoryDoc, data: any, options?: { merge?: boolean }) => {\n writes.push(() => ref.applySet(data, options))\n return transaction\n },\n update: (ref: MemoryDoc, data: any) => {\n writes.push(() => ref.applyUpdate(data))\n return transaction\n },\n create: (ref: MemoryDoc, data: any) => {\n writes.push(() => ref.applyCreate(data))\n return transaction\n },\n }\n const result = await fn(transaction)\n await tick()\n const conflicted =\n [...seen].some(([path, version]) => this.version(path) !== version) ||\n queries.some(({ query, snapshot }) => query.signature() !== snapshot)\n if (conflicted) {\n this.retries += 1\n continue\n }\n for (const write of writes) write()\n return result\n }\n throw new Error('transaction contention: too many retries')\n }\n}\n\nexport class MemoryCollection {\n constructor(\n readonly store: MemoryFirestore,\n readonly path: string,\n ) {}\n\n doc(id?: string): MemoryDoc {\n return new MemoryDoc(this.store, `${this.path}/${id ?? this.store.nextId()}`)\n }\n\n where(field: string, op: '==' | 'in', value: unknown): MemoryQuery {\n return new MemoryQuery(this.store, this.path).where(field, op, value)\n }\n\n orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): MemoryQuery {\n return new MemoryQuery(this.store, this.path).orderBy(field, direction)\n }\n\n limit(count: number): MemoryQuery {\n return new MemoryQuery(this.store, this.path).limit(count)\n }\n\n get() {\n return Promise.resolve(new MemoryQuery(this.store, this.path).run())\n }\n}\n\n/** What a {@link MemoryDoc} read returns, shaped like a Firestore snapshot. */\nexport interface MemoryDocSnapshot {\n id: string\n ref: MemoryDoc\n exists: boolean\n data: () => Record<string, any> | undefined\n get: (field: string) => unknown\n}\n\nexport class MemoryDoc {\n constructor(\n readonly store: MemoryFirestore,\n readonly path: string,\n ) {}\n\n get id(): string {\n return this.path.split('/').pop() ?? ''\n }\n\n collection(name: string): MemoryCollection {\n return new MemoryCollection(this.store, `${this.path}/${name}`)\n }\n\n snapshot(): MemoryDocSnapshot {\n const stored = this.store.docs.get(this.path)\n const data = stored ? { ...stored.data } : undefined\n return {\n id: this.id,\n ref: this,\n exists: Boolean(stored),\n data: () => (data ? { ...data } : undefined),\n get: (field: string) => data?.[field],\n }\n }\n\n async get(): Promise<MemoryDocSnapshot> {\n await tick()\n return this.snapshot()\n }\n\n applySet(data: Record<string, any>, options?: { merge?: boolean }): void {\n const previous = this.store.docs.get(this.path)?.data\n this.store.write(this.path, options?.merge && previous ? { ...previous, ...data } : data)\n }\n\n applyUpdate(data: Record<string, any>): void {\n const previous = this.store.docs.get(this.path)?.data\n if (!previous) throw Object.assign(new Error('NOT_FOUND'), { code: 5 })\n this.store.write(this.path, { ...previous, ...data })\n }\n\n applyCreate(data: Record<string, any>): void {\n if (this.store.docs.has(this.path)) {\n throw Object.assign(new Error('Document already exists'), { code: 6 })\n }\n this.store.write(this.path, data)\n }\n\n async set(data: Record<string, any>, options?: { merge?: boolean }): Promise<void> {\n await tick()\n this.applySet(data, options)\n }\n\n async create(data: Record<string, any>): Promise<void> {\n await tick()\n this.applyCreate(data)\n }\n\n async update(data: Record<string, any>): Promise<void> {\n await tick()\n this.applyUpdate(data)\n }\n\n async delete(): Promise<void> {\n await tick()\n this.store.write(this.path, null)\n }\n}\n\nexport class MemoryQuery {\n private filters: Array<{ field: string; op: '==' | 'in'; value: unknown }> = []\n private order: { field: string; direction: 'asc' | 'desc' } | null = null\n private max = Infinity\n\n constructor(\n readonly store: MemoryFirestore,\n readonly path: string,\n ) {}\n\n private clone(): MemoryQuery {\n const next = new MemoryQuery(this.store, this.path)\n next.filters = [...this.filters]\n next.order = this.order\n next.max = this.max\n return next\n }\n\n where(field: string, op: '==' | 'in', value: unknown): MemoryQuery {\n const next = this.clone()\n next.filters.push({ field, op, value })\n return next\n }\n\n orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): MemoryQuery {\n const next = this.clone()\n next.order = { field, direction }\n return next\n }\n\n limit(count: number): MemoryQuery {\n const next = this.clone()\n next.max = count\n return next\n }\n\n run() {\n const prefix = `${this.path}/`\n let rows = [...this.store.docs.entries()]\n .filter(([path]) => path.startsWith(prefix) && !path.slice(prefix.length).includes('/'))\n .filter(([, stored]) =>\n this.filters.every(({ field, op, value }) =>\n op === 'in'\n ? (value as unknown[]).includes(stored.data[field])\n : stored.data[field] === value,\n ),\n )\n if (this.order) {\n const { field, direction } = this.order\n rows = rows.sort(([, a], [, b]) => {\n const delta = a.data[field] < b.data[field] ? -1 : a.data[field] > b.data[field] ? 1 : 0\n return direction === 'asc' ? delta : -delta\n })\n }\n const docs = rows\n .slice(0, this.max)\n .map(([path]) => new MemoryDoc(this.store, path).snapshot())\n return { docs, size: docs.length, empty: docs.length === 0 }\n }\n\n /** The paths and versions this query matches now, to detect a changed result. */\n signature(): string {\n return this.run()\n .docs.map((doc) => `${doc.ref.path}@${this.store.version(doc.ref.path)}`)\n .join('|')\n }\n\n get() {\n return tick().then(() => this.run())\n }\n}\n"],"names":["tick","Promise","resolve","setTimeout","MemoryFirestore","collection","path","MemoryCollection","read","stored","docs","get","data","undefined","nextId","autoId","String","padStart","write","clock","delete","set","version","batch","ops","ref","options","push","applySet","update","applyUpdate","commit","op","runTransaction","fn","attempt","seen","Map","queries","writes","transaction","target","MemoryDoc","snapshot","result","run","query","signature","doc","create","applyCreate","conflicted","some","retries","Error","id","store","where","field","value","MemoryQuery","orderBy","direction","limit","count","split","pop","name","exists","Boolean","previous","merge","Object","assign","code","has","clone","next","filters","order","max","prefix","rows","entries","filter","startsWith","slice","length","includes","every","sort","a","b","delta","map","size","empty","join","then","Infinity"],"mappings":"AAAA;;;;;;;;;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AAM,GAAG,CAAC,IAAIiC,EAAE/E,IAAI,CAAC8C,MAAM,GAAGkC,EAAEhF,IAAI,CAAC8C,MAAM,GAAG,IAAI;gBACvF,OAAOI,cAAc,QAAQ+B,QAAQ,CAACA;YACxC;QACF;QACA,MAAMnF,OAAOwE,KACVI,KAAK,CAAC,GAAG,IAAI,CAACN,GAAG,EACjBc,GAAG,CAAC,CAAC,CAACxF,KAAK,GAAK,IAAIoC,UAAU,IAAI,CAACc,KAAK,EAAElD,MAAMqC,QAAQ;QAC3D,OAAO;YAAEjC;YAAMqF,MAAMrF,KAAK6E,MAAM;YAAES,OAAOtF,KAAK6E,MAAM,KAAK;QAAE;IAC7D;IAEA,+EAA+E,GAC/ExC,YAAoB;QAClB,OAAO,IAAI,CAACF,GAAG,GACZnC,IAAI,CAACoF,GAAG,CAAC,CAAC9C,MAAQ,GAAGA,IAAIvB,GAAG,CAACnB,IAAI,CAAC,CAAC,EAAE,IAAI,CAACkD,KAAK,CAAClC,OAAO,CAAC0B,IAAIvB,GAAG,CAACnB,IAAI,GAAG,EACvE2F,IAAI,CAAC;IACV;IAEAtF,MAAM;QACJ,OAAOX,OAAOkG,IAAI,CAAC,IAAM,IAAI,CAACrD,GAAG;IACnC;IAhEA,YACE,AAASW,KAAsB,EAC/B,AAASlD,IAAY,CACrB;aAFSkD,QAAAA;aACAlD,OAAAA;aANHwE,UAAqE,EAAE;aACvEC,QAA6D;aAC7DC,MAAMmB;IAKX;AA8DL"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/testing/memory-firestore.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 * A small in-memory stand-in for the firebase-admin Firestore surface the\n * print queue uses (AGL-3619), for specs. Transactions are OPTIMISTIC, as\n * Firestore's server SDK effectively is under contention: every read records\n * the version it saw, the commit re-checks them (and re-runs any query read\n * in the transaction), and a conflict retries the whole function. Each read\n * yields to the event loop, so two transactions started together really do\n * interleave, which is what a race spec needs.\n *\n * Supports: `collection().doc()`, `get`, `set` (with `merge`), `create`,\n * `update`, `delete`; queries with `==`, `in` and `array-contains`, `orderBy`, `limit`,\n * and a collection's `count()`;\n * `runTransaction` with `get` (document or query), `set`, `update`;\n * `batch()`. Field paths are top-level only.\n */\n\ninterface Stored {\n data: Record<string, any>\n version: number\n}\n\nconst tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0))\n\nexport class MemoryFirestore {\n readonly docs = new Map<string, Stored>()\n private autoId = 0\n private clock = 0\n /** Committed transactions that had to retry, for specs that assert contention happened. */\n retries = 0\n\n collection(path: string): MemoryCollection {\n return new MemoryCollection(this, path)\n }\n\n /** The document at a slash path, for assertions. */\n read(path: string): Record<string, any> | undefined {\n const stored = this.docs.get(path)\n return stored ? { ...stored.data } : undefined\n }\n\n nextId(): string {\n this.autoId += 1\n return `auto${String(this.autoId).padStart(4, '0')}`\n }\n\n write(path: string, data: Record<string, any> | null): void {\n this.clock += 1\n if (data === null) this.docs.delete(path)\n else this.docs.set(path, { data: { ...data }, version: this.clock })\n }\n\n version(path: string): number {\n return this.docs.get(path)?.version ?? 0\n }\n\n batch() {\n const ops: Array<() => void> = []\n return {\n set: (ref: MemoryDoc, data: any, options?: { merge?: boolean }) =>\n ops.push(() => ref.applySet(data, options)),\n update: (ref: MemoryDoc, data: any) => ops.push(() => ref.applyUpdate(data)),\n delete: (ref: MemoryDoc) => ops.push(() => this.write(ref.path, null)),\n commit: async () => {\n await tick()\n for (const op of ops) op()\n },\n }\n }\n\n async runTransaction<T>(fn: (transaction: any) => Promise<T>): Promise<T> {\n for (let attempt = 0; attempt < 10; attempt += 1) {\n const seen = new Map<string, number>()\n const queries: Array<{ query: MemoryQuery; snapshot: string }> = []\n const writes: Array<() => void> = []\n const transaction = {\n get: async (target: MemoryDoc | MemoryQuery) => {\n await tick()\n if (target instanceof MemoryDoc) {\n seen.set(target.path, this.version(target.path))\n return target.snapshot()\n }\n const result = target.run()\n queries.push({ query: target, snapshot: target.signature() })\n for (const doc of result.docs) seen.set(doc.ref.path, this.version(doc.ref.path))\n return result\n },\n set: (ref: MemoryDoc, data: any, options?: { merge?: boolean }) => {\n writes.push(() => ref.applySet(data, options))\n return transaction\n },\n update: (ref: MemoryDoc, data: any) => {\n writes.push(() => ref.applyUpdate(data))\n return transaction\n },\n create: (ref: MemoryDoc, data: any) => {\n writes.push(() => ref.applyCreate(data))\n return transaction\n },\n }\n const result = await fn(transaction)\n await tick()\n const conflicted =\n [...seen].some(([path, version]) => this.version(path) !== version) ||\n queries.some(({ query, snapshot }) => query.signature() !== snapshot)\n if (conflicted) {\n this.retries += 1\n continue\n }\n for (const write of writes) write()\n return result\n }\n throw new Error('transaction contention: too many retries')\n }\n}\n\nexport class MemoryCollection {\n constructor(\n readonly store: MemoryFirestore,\n readonly path: string,\n ) {}\n\n doc(id?: string): MemoryDoc {\n return new MemoryDoc(this.store, `${this.path}/${id ?? this.store.nextId()}`)\n }\n\n where(field: string, op: MemoryFilterOp, value: unknown): MemoryQuery {\n return new MemoryQuery(this.store, this.path).where(field, op, value)\n }\n\n orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): MemoryQuery {\n return new MemoryQuery(this.store, this.path).orderBy(field, direction)\n }\n\n limit(count: number): MemoryQuery {\n return new MemoryQuery(this.store, this.path).limit(count)\n }\n\n /** The aggregate: its result's `data().count`. */\n count(): MemoryQuery {\n return new MemoryQuery(this.store, this.path)\n }\n\n get() {\n return Promise.resolve(new MemoryQuery(this.store, this.path).run())\n }\n}\n\n/** What a {@link MemoryDoc} read returns, shaped like a Firestore snapshot. */\nexport interface MemoryDocSnapshot {\n id: string\n ref: MemoryDoc\n exists: boolean\n data: () => Record<string, any> | undefined\n get: (field: string) => unknown\n}\n\nexport class MemoryDoc {\n constructor(\n readonly store: MemoryFirestore,\n readonly path: string,\n ) {}\n\n get id(): string {\n return this.path.split('/').pop() ?? ''\n }\n\n collection(name: string): MemoryCollection {\n return new MemoryCollection(this.store, `${this.path}/${name}`)\n }\n\n snapshot(): MemoryDocSnapshot {\n const stored = this.store.docs.get(this.path)\n const data = stored ? { ...stored.data } : undefined\n return {\n id: this.id,\n ref: this,\n exists: Boolean(stored),\n data: () => (data ? { ...data } : undefined),\n get: (field: string) => data?.[field],\n }\n }\n\n async get(): Promise<MemoryDocSnapshot> {\n await tick()\n return this.snapshot()\n }\n\n applySet(data: Record<string, any>, options?: { merge?: boolean }): void {\n const previous = this.store.docs.get(this.path)?.data\n this.store.write(this.path, options?.merge && previous ? { ...previous, ...data } : data)\n }\n\n applyUpdate(data: Record<string, any>): void {\n const previous = this.store.docs.get(this.path)?.data\n if (!previous) throw Object.assign(new Error('NOT_FOUND'), { code: 5 })\n this.store.write(this.path, { ...previous, ...data })\n }\n\n applyCreate(data: Record<string, any>): void {\n if (this.store.docs.has(this.path)) {\n throw Object.assign(new Error('Document already exists'), { code: 6 })\n }\n this.store.write(this.path, data)\n }\n\n async set(data: Record<string, any>, options?: { merge?: boolean }): Promise<void> {\n await tick()\n this.applySet(data, options)\n }\n\n async create(data: Record<string, any>): Promise<void> {\n await tick()\n this.applyCreate(data)\n }\n\n async update(data: Record<string, any>): Promise<void> {\n await tick()\n this.applyUpdate(data)\n }\n\n async delete(): Promise<void> {\n await tick()\n this.store.write(this.path, null)\n }\n}\n\nexport type MemoryFilterOp = '==' | 'in' | 'array-contains'\n\nexport class MemoryQuery {\n private filters: Array<{ field: string; op: MemoryFilterOp; value: unknown }> = []\n private order: { field: string; direction: 'asc' | 'desc' } | null = null\n private max = Infinity\n\n constructor(\n readonly store: MemoryFirestore,\n readonly path: string,\n ) {}\n\n private clone(): MemoryQuery {\n const next = new MemoryQuery(this.store, this.path)\n next.filters = [...this.filters]\n next.order = this.order\n next.max = this.max\n return next\n }\n\n where(field: string, op: MemoryFilterOp, value: unknown): MemoryQuery {\n const next = this.clone()\n next.filters.push({ field, op, value })\n return next\n }\n\n orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): MemoryQuery {\n const next = this.clone()\n next.order = { field, direction }\n return next\n }\n\n limit(count: number): MemoryQuery {\n const next = this.clone()\n next.max = count\n return next\n }\n\n run() {\n const prefix = `${this.path}/`\n let rows = [...this.store.docs.entries()]\n .filter(([path]) => path.startsWith(prefix) && !path.slice(prefix.length).includes('/'))\n .filter(([, stored]) =>\n this.filters.every(({ field, op, value }) =>\n op === 'in'\n ? (value as unknown[]).includes(stored.data[field])\n : op === 'array-contains'\n ? Array.isArray(stored.data[field]) && stored.data[field].includes(value)\n : stored.data[field] === value,\n ),\n )\n if (this.order) {\n const { field, direction } = this.order\n rows = rows.sort(([, a], [, b]) => {\n const delta = a.data[field] < b.data[field] ? -1 : a.data[field] > b.data[field] ? 1 : 0\n return direction === 'asc' ? delta : -delta\n })\n }\n const docs = rows\n .slice(0, this.max)\n .map(([path]) => new MemoryDoc(this.store, path).snapshot())\n // `data()` answers a `count()` aggregate read through the same query.\n return { docs, size: docs.length, empty: docs.length === 0, data: () => ({ count: docs.length }) }\n }\n\n /** The paths and versions this query matches now, to detect a changed result. */\n signature(): string {\n return this.run()\n .docs.map((doc) => `${doc.ref.path}@${this.store.version(doc.ref.path)}`)\n .join('|')\n }\n\n get() {\n return tick().then(() => this.run())\n }\n}\n"],"names":["tick","Promise","resolve","setTimeout","MemoryFirestore","collection","path","MemoryCollection","read","stored","docs","get","data","undefined","nextId","autoId","String","padStart","write","clock","delete","set","version","batch","ops","ref","options","push","applySet","update","applyUpdate","commit","op","runTransaction","fn","attempt","seen","Map","queries","writes","transaction","target","MemoryDoc","snapshot","result","run","query","signature","doc","create","applyCreate","conflicted","some","retries","Error","id","store","where","field","value","MemoryQuery","orderBy","direction","limit","count","split","pop","name","exists","Boolean","previous","merge","Object","assign","code","has","clone","next","filters","order","max","prefix","rows","entries","filter","startsWith","slice","length","includes","every","Array","isArray","sort","a","b","delta","map","size","empty","join","then","Infinity"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC;AAOD,MAAMA,OAAO,IAAM,IAAIC,QAAc,CAACC,UAAYC,WAAWD,SAAS;AAEtE,OAAO,MAAME;IAOXC,WAAWC,IAAY,EAAoB;QACzC,OAAO,IAAIC,iBAAiB,IAAI,EAAED;IACpC;IAEA,kDAAkD,GAClDE,KAAKF,IAAY,EAAmC;QAClD,MAAMG,SAAS,IAAI,CAACC,IAAI,CAACC,GAAG,CAACL;QAC7B,OAAOG,SAAS,aAAKA,OAAOG,IAAI,IAAKC;IACvC;IAEAC,SAAiB;QACf,IAAI,CAACC,MAAM,IAAI;QACf,OAAO,CAAC,IAAI,EAAEC,OAAO,IAAI,CAACD,MAAM,EAAEE,QAAQ,CAAC,GAAG,MAAM;IACtD;IAEAC,MAAMZ,IAAY,EAAEM,IAAgC,EAAQ;QAC1D,IAAI,CAACO,KAAK,IAAI;QACd,IAAIP,SAAS,MAAM,IAAI,CAACF,IAAI,CAACU,MAAM,CAACd;aAC/B,IAAI,CAACI,IAAI,CAACW,GAAG,CAACf,MAAM;YAAEM,MAAM,aAAKA;YAAQU,SAAS,IAAI,CAACH,KAAK;QAAC;IACpE;IAEAG,QAAQhB,IAAY,EAAU;;YACrB;QAAP,gBAAO,iBAAA,IAAI,CAACI,IAAI,CAACC,GAAG,CAACL,0BAAd,eAAqBgB,OAAO,mBAAI;IACzC;IAEAC,QAAQ;QACN,MAAMC,MAAyB,EAAE;QACjC,OAAO;YACLH,KAAK,CAACI,KAAgBb,MAAWc,UAC/BF,IAAIG,IAAI,CAAC,IAAMF,IAAIG,QAAQ,CAAChB,MAAMc;YACpCG,QAAQ,CAACJ,KAA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OAAOoG,IAAI,CAAC,IAAM,IAAI,CAACvD,GAAG;IACnC;IAnEA,YACE,AAASW,KAAsB,EAC/B,AAASlD,IAAY,CACrB;aAFSkD,QAAAA;aACAlD,OAAAA;aANHwE,UAAwE,EAAE;aAC1EC,QAA6D;aAC7DC,MAAMqB;IAKX;AAiEL"}
@@ -17,8 +17,13 @@
17
17
  import { type BuildTransferPlanInput, type MatchLookupRequest, type TransferChunk, type TransferPlan, type TransferUndoSnapshot } from '@aglyn/aglyn/data-transfer';
18
18
  import type { PicklistValue } from '@aglyn/aglyn/app-utils/picklists';
19
19
  import type { TransferApplyResult, TransferApplyWriter, TransferLookupResult, TransferPicklistList, TransferReadOptions, TransferReadPage, TransferResourceContext, TransferRevertDecisions, TransferRevertResult } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources';
20
+ import { type HostProduct, type SmartCollectionRules } from '../model/commerce';
20
21
  import { type ProductPlannedRow } from './product-transfer';
21
22
  import { type Firestore } from './server-common';
23
+ /** The smart collections a product's write answers (AGL-3321). */
24
+ export declare function readSmartCollections(firestore: Firestore, ctx: TransferResourceContext): Promise<SmartCollectionRules[]>;
25
+ /** The keys every product write derives, from the product as it will stand. */
26
+ export declare function derivedKeys(product: HostProduct, smart: readonly SmartCollectionRules[]): Record<string, unknown>;
22
27
  /** The rows of one page of products. A product is as many rows as it has variants (or images). */
23
28
  export declare function readProductsPage(ctx: TransferResourceContext, cursor: string | null, fieldIds: readonly string[], options?: TransferReadOptions, firestore?: Firestore): Promise<TransferReadPage>;
24
29
  /** How many rows the export writes: every live product's variant (or image) rows. */
@@ -66,7 +66,7 @@ const isLive = (data)=>Boolean(data) && ((data == null ? void 0 : data['deletedA
66
66
  return ids;
67
67
  };
68
68
  }
69
- /** The smart collections a product's write answers (AGL-3321). */ async function readSmartCollections(firestore, ctx) {
69
+ /** The smart collections a product's write answers (AGL-3321). */ export async function readSmartCollections(firestore, ctx) {
70
70
  const snapshot = await hostRefOf(firestore, ctx).collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart').get();
71
71
  return snapshot.docs.map((doc)=>{
72
72
  var _doc_get;
@@ -77,7 +77,7 @@ const isLive = (data)=>Boolean(data) && ((data == null ? void 0 : data['deletedA
77
77
  };
78
78
  });
79
79
  }
80
- /** The keys every product write derives, from the product as it will stand. */ function derivedKeys(product, smart) {
80
+ /** The keys every product write derives, from the product as it will stand. */ export function derivedKeys(product, smart) {
81
81
  var _ref, _ref1;
82
82
  var _product_variants_, _product_mediaUrls;
83
83
  return _extends({}, productSearchFields(product), productStockFields(product), {