@blamejs/blamejs-shop 0.0.64 → 0.0.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.0.x
10
10
 
11
+ - v0.0.66 (2026-05-22) — **Ten new primitives: site redirects, cost layers, payment retries, pick lists, preorder, discount allocation, currency rounding, credit limits, theme assets, business hours.** Ten primitives ship in one release covering warehouse operations (pick lists, FIFO/LIFO inventory cost layers), commerce (preorder, currency rounding rules, discount allocation breakdown), B2B (credit limits with net-30 terms + aging), payment recovery (payment retries with failure-code-aware policy), and storefront infrastructure (site redirects, theme assets registry, business-hours calculator). **Added:** *`siteRedirects` primitive — operator-defined 301/302/307/308 redirects* — `bShop.siteRedirects.create({ query? })` returns `{ defineRedirect, resolveForPath, recordHit, listRedirects, getRedirect, updateRedirect, archiveRedirect, unarchiveRedirect, topHits, cleanupExpired }`. Match kinds: exact / prefix / regex. Regex patterns refused if they carry backreferences (`\1`-`\9`) or lookahead/lookbehind to keep catastrophic-backtracking out of the live table. `resolveForPath` walks exact > prefix (longest source_path wins, slug ASC tiebreak) > regex (slug ASC). `target_url` accepts /-rooted internal paths OR full https:// via `b.safeUrl`. Migration `0119_site_redirects.sql`. · *`costLayers` primitive — FIFO / LIFO / weighted-average inventory cost tracking* — `bShop.costLayers.create({ query?, catalog? })` returns `{ setMethod, getMethod, recordReceipt, consumeForSale, recordReversal, currentLayers, cogsForOrder, cogsForPeriod }`. Method enum: fifo / lifo / weighted_average. FIFO consumes oldest layers first; LIFO newest; weighted_average computes the mean of remaining layers. Each receipt adds a cost layer with `quantity_remaining` + `unit_cost_minor`. `consumeForSale` returns `{ consumed_layers: [...], total_cogs_minor, currency }` and refuses on insufficient on-hand. `recordReversal` restores stock on returns by adding back to a layer. Per-SKU strict-monotonic `occurred_at` clock so same-millisecond receipts can't tie on the FIFO/LIFO ordering key. Migration `0121_cost_layers.sql`. · *`paymentRetries` primitive — failure-code-aware retry orchestration for one-time payments* — `bShop.paymentRetries.create({ query?, payment? })` returns `{ defineRetryPolicy, enrollFailure, tickRetries, recordRetryOutcome, unenrollPayment, statusForPayment, historyForPayment, policiesForFailureCode, metricsForPolicy }`. Distinct from `dunning` (subscriptions only). Failure-code-aware: `insufficient_funds` → wait 24h + retry; `card_declined` → wait 7d + retry once; `invalid_card` → terminal-at-enrollment. `tickRetries` walks `next_retry_at <= now` rows and dispatches via composed payment.retry. `terminal_after_attempts` exhausts an enrollment + flips `abandoned` status. Migration `0120_payment_retries.sql`. · *`pickLists` primitive — warehouse pick-list workflow* — `bShop.pickLists.create({ query?, order, orderTracking?, inventoryLocations? })` returns `{ generateList, getList, listLists, confirmLine, markListComplete, cancelList, discrepanciesFor }`. Generated from N open orders for a given warehouse, sorted by aisle/sku/priority/order_id (materialized into a `sequence_number` column so picker walk order is durable across reads). Optional `inventoryLocations.binForSku` probe for aisle position. `markListComplete` fans out shipment creation via composed `orderTracking.createShipment` per-order. Migration `0118_pick_lists.sql`. · *`preorder` primitive — pre-launch reservations distinct from backorder* — `bShop.preorder.create({ query?, catalog?, order? })` returns `{ defineCampaign, reserve, getReservation, reservationsForCustomer, cancelReservation, convertReservationToOrder, launchCampaign, closeCampaign, availability, getCampaign }`. Backorder = sku exists but out-of-stock; preorder = sku not yet released. `defineCampaign({ slug, sku, launch_at, charge_at?, max_units_available?, deposit_minor?, full_price_minor })`. `launchCampaign` triggers auto-conversion of all active reservations via composed `order.createFromCart`. Cancelled reservations free capacity for re-reservation. Migration `0124_preorder.sql`. · *`discountAllocation` primitive — per-line allocation of order-level discounts* — `bShop.discountAllocation.create({ query })` returns `{ allocate, recordAllocation, allocationsForOrder, reverseAllocation, metricsForKind }`. Order has $20 off the total — primitive distributes across lines for accounting + refund precision. Kinds: proportional / equal / by_subtotal / by_quantity. Half-even rounding via `b.money.fromMinorUnits(...).multiply([num, den])`; remainder lands deterministically on highest-subtotal line. `reverseAllocation` produces per-line refund amounts that re-sum to the original total. Migration `0129_discount_allocation.sql`. · *`currencyRounding` primitive — per-currency display rounding rules* — `bShop.currencyRounding.create({ query? })` returns `{ defineRule, getRule, listRules, roundFor, updateRule, archiveRule, historyForCurrency, round }`. Distinct from `currencyDisplay` (FX rate cache) — this is the rounding behavior applied at checkout. CHF rounds to nearest 0.05; SEK to nearest 0.10; JPY whole units. Modes: half_up / half_even / half_down / ceiling / floor. `applies_to` enum: display_only / cart_total / line_total / all. Pure `_round(amount, step, mode)` exported as `currencyRounding.round` for direct composition without the factory. Migration `0132_currency_rounding.sql`. · *`creditLimits` primitive — B2B credit accounts with net-30 / net-60 terms + aging report* — `bShop.creditLimits.create({ query?, customers? })` returns `{ defineAccount, getAccount, listAccounts, updateAccount, suspendAccount, reinstateAccount, chargeOrder, releaseHold, recordPayment, availableCredit, outstandingBalance, agingReport }`. `chargeOrder` checks available credit, refuses on insufficient (no row written). `releaseHold` restores credit on cancel. `agingReport({ customer_id })` returns balance by days-past-due bucket (current / 30d / 60d / 90d+). Payments + releases FIFO-settle against oldest charges. FSM: active / suspended / closed. Migration `0122_credit_limits.sql`. · *`themeAssets` primitive — operator-uploaded theme asset registry* — `bShop.themeAssets.create({ query? })` returns `{ registerAsset, getAsset, assetsForTheme, assetsByKind, updateAsset, archiveAsset, assignToTheme, recordImpression, metricsForAsset, cleanupOrphans }`. Asset kinds: font / logo / hero_image / favicon / banner_image / og_image / icon / custom. Content-addressed via `sha3_512` digest (validated as lowercase 128-char hex). `source_url` gated via `b.safeUrl` (https-only + /-rooted internal). `cleanupOrphans({ days_idle })` archives assets not assigned to any active theme. Migration `0131_theme_assets.sql`. · *`businessHours` primitive — operator-defined business-hour windows with DST-correct math* — `bShop.businessHours.create({ query? })` returns `{ defineSchedule, isOpenAt, nextOpenAt, nextCloseAt, weekSummary, addException, removeException, addHoliday, listSchedules, archiveSchedule }`. Per-day open/close times in IANA timezone, plus per-date exceptions + holidays. `Intl.DateTimeFormat` for tz-correct calendar math (DST-correct via Intl, no manual offset arithmetic). Two-pass `_wallClockToEpochMs` algorithm converges across DST folds. `nextOpenAt` skips holidays + closed days. Migration `0127_business_hours.sql`.
12
+
13
+ - v0.0.65 (2026-05-22) — **Twenty new primitives: address validation, auto discount, captcha gate, catalog drafts, cookie consent, customer roles, cycle counting, delivery estimate, email warmup, metered usage, price display, product bulk ops, purchase orders, quotes, recommendations, reorder thresholds, shipping zones, split shipments, trust badges, webhook receiver.** Twenty primitives ship in one release. Covers per-customer self-serve flows (cookie consent, captcha gate, address validation), operator-side catalog tooling (drafts, bulk ops, reorder thresholds, purchase orders, cycle counting, delivery estimate, shipping zones), commerce primitives (auto discount, quotes, recommendations, price display, split shipments, metered usage, trust badges), and integrations (webhook receiver, email warmup, customer roles). **Added:** *`addressValidation` primitive — cache + lookup for address-validation API results* — `bShop.addressValidation.create({ query? })` returns `{ recordValidation, lookupCached, signatureFor, recordSuggestion, lookupSuggestions, cleanupExpired, metricsForSource, validationsForOrder }`. Input signature derived via `namespaceHash('address-validation-input', canonical(input))` so the same address normalizes to one cache row. Source enum: `usps / smarty / lob / google / melissa / manual`. Classification enum: `residential / commercial / po_box / military / unknown`. Migration `0115_address_validation.sql`. · *`autoDiscount` primitive — automatic discounts without coupon codes* — `bShop.autoDiscount.create({ query?, catalog?, customerSegments? })` returns `{ defineRule, getRule, listRules, updateRule, archiveRule, evaluate, recordApplication, metricsForRule }`. Trigger kinds: `cart_total_min / item_count_min / sku_purchase`. Value kinds: `percent_off / amount_off_total / amount_off_each / free_shipping / bogo`. Priority + max_redemptions + customer segment gating. Migration `0107_auto_discount.sql`. · *`captchaGate` primitive — CAPTCHA verification at high-risk entrypoints* — `bShop.captchaGate.create({ query? })` returns `{ registerProvider, verifyToken, recordOutcome, metricsForProvider, ... }`. Provider enum: `turnstile / hcaptcha / recaptcha_v2 / recaptcha_v3`. reCAPTCHA v3 gets a threshold-score floor (basis-points). Secret hashed via `namespaceHash('captcha-secret', ...)`; session id hashed before write. Provider-callback-driven verify; operator's worker calls the actual provider endpoint. Migration `0114_captcha_gate.sql`. · *`catalogDrafts` primitive — staging workflow for catalog mutations* — `bShop.catalogDrafts.create({ query?, catalog })` returns `{ openDraft, stageChange, listChanges, removeChange, previewMerged, publishDraft, cancelDraft, rollbackDraft, listDrafts, historyForSku }`. Stage N changes against catalog (create / update / archive products + variants + prices + tags + inventory); publish atomically. 7-day rollback window. Pre-flight validates every change against the live catalog before writing anything. Migration `0112_catalog_drafts.sql`. · *`cookieConsent` primitive — GDPR / ePrivacy consent management* — `bShop.cookieConsent.create({ query? })` returns `{ recordConsent, getConsentFor, withdrawConsent, categoryAllowed, metricsForBanner, cleanupOlderThan, registerPolicyVersion }`. Categories: strictly-necessary (always on) + functional + analytics + marketing + preferences. DNT / Sec-GPC headers force implicit deny on marketing + analytics regardless of recorded consent. Policy-version bump flags older session consents for re-prompt. Session id hashed before write. Migration `0103_cookie_consent.sql`. · *`customerRoles` primitive — B2B company-account roles + capabilities* — `bShop.customerRoles.create({ query?, customers? })` returns `{ defineRole, assignRole, unassignRole, rolesForEmployee, employeesForCompany, hasCapability, recordOrderApproval, listRoles, updateRole, archiveRole }`. Capabilities: `can_view_orders / can_place_order / can_approve_order / can_manage_users / can_view_pricing / can_apply_payment_terms / can_request_quote / can_view_invoices`. UNIQUE(company, employee) so an employee carries one role per company. Migration `0101_customer_roles.sql`. · *`cycleCounting` primitive — physical inventory cycle counts* — `bShop.cycleCounting.create({ query?, catalog, inventoryLocations? })` returns `{ defineCount, worksheetFor, recordCount, finalizeCount, cancelCount, discrepanciesFor, listCounts, historyForSku, getCount }`. Kinds: `rotating / abc / full`. `finalizeCount({ apply_adjustments })` writes adjustments through `inventoryLocations.adjustStock` with `reason='cycle-count:<slug>'` so the audit row carries the count slug. Migration `0108_cycle_counting.sql`. · *`deliveryEstimate` primitive — PDP + cart delivery-window calculator* — `bShop.deliveryEstimate.create({ query?, inventoryLocations?, shippingZones? })` returns `{ defineCarrierTransit, defineCutoff, defineHoliday, definePostalZone, estimate, estimateForCart, listTransits, listCutoffs, listHolidays, archiveTransit, archiveHoliday }`. Calendar math is Intl-DateTimeFormat-driven (DST-correct); weekend + region-holiday skips applied separately to origin ship-by + destination delivery-by. Migration `0117_delivery_estimate.sql`. · *`emailWarmup` primitive — gradual SMTP IP/domain warmup* — `bShop.emailWarmup.create({ query?, now? })` returns `{ defineSchedule, canSend, recordSends, recordEngagement, currentDay, pauseSchedule, resumeSchedule, archiveSchedule, listSchedules, getSchedule, metricsForSchedule }`. Daily targets array (Day 1: 50, Day 2: 100, etc.) cap outbound volume to build sender reputation. Day-index math computed against UTC midnight of `start_date`. Migration `0116_email_warmup.sql`. · *`meteredUsage` primitive — usage-based subscription billing* — `bShop.meteredUsage.create({ query?, subscriptions?, subscriptionBilling? })` returns `{ defineMeter, recordUsage, usageForPeriod, periodSummary, recordPeriodInvoice, listMeters, updateMeter, archiveMeter }`. Tier schedule for tiered pricing (first 1000 free, next 10000 at $0.001, ...). `recordUsage` idempotency_key dedups re-submitted events. `recordPeriodInvoice` queues invoice line via subscriptionBilling. Migration `0095_metered_usage.sql`. · *`priceDisplay` primitive — per-region tax-included / tax-excluded display modes* — `bShop.priceDisplay.create({ query?, tax?, taxRates?, geolocation? })` returns `{ defineRule, getModeFor, formatPrice, defineCustomerOverride, clearCustomerOverride, customerOverride, listRules, updateRule, archiveRule }`. Resolution priority: customer-override > customer_status_in > country default. Compose `tax.calculateInclusive / calculateExclusive` for the breakdown. Migration `0097_price_display.sql`. · *`productBulkOps` primitive — bulk product mutations with pre-flight + audit* — `bShop.productBulkOps.create({ query?, catalog, maxBulkRows? })` returns `{ bulkSetPrice, bulkAdjustPrice, bulkArchive, bulkUnarchive, bulkAddTag, bulkRemoveTag, bulkSetInventory, previewFilter, auditTrail, categories, tags }`. Filter `{ skus?, vendor_slug?, category?, tag_any?, tag_all? }`. Pre-flight cap default 1000, ceiling 10000. Half-up rounding on percent adjustments; floored at 0. Process-local monotonic `_now` so back-to-back audit rows sort newest-first reliably. Migration `0104_product_bulk_ops.sql`. · *`purchaseOrders` primitive — operator-facing POs to vendors* — `bShop.purchaseOrders.create({ query?, vendors?, inventoryReceive? })` returns `{ createDraft, submitToVendor, confirmByVendor, recordPartialReceipt, closePO, cancelPO, getPO, listPOs, linesForPO, update }`. FSM `draft → submitted → confirmed → partially_received → received → closed`. `recordPartialReceipt` composes `inventoryReceive.draft + apply` for restock. `closePO` refuses unless all lines fully received. Migration `0099_purchase_orders.sql`. · *`quotes` primitive — B2B RFQ / quote flow* — `bShop.quotes.create({ query?, cart?, order? })` returns `{ requestQuote, respondToQuote, customerAccept, customerReject, cancelQuote, convertToOrder, getQuote, quotesForCustomer, pendingResponse, listExpired, markExpired }`. FSM `requested → responded → accepted → converted` with `rejected / expired / cancelled` terminal branches. `convertToOrder` composes `order.createFromCart` using the quoted prices. Accepts either `lines` or `cart_id` (via cart aggregator). Migration `0102_quotes.sql`. · *`recommendations` primitive — storefront product recommendation engine* — `bShop.recommendations.create({ query?, catalog, analytics?, recentlyViewed? })` returns `{ recommendForProduct, recommendForCart, recommendForCustomer, recommendForCategory, setOverride, removeOverride, listOverrides, recordImpression, recordClick, recordConversion, metricsForKind }`. Override layer reads first then falls through co-purchase → category-popular → random-in-stock. Session id namespace-hashed before write. Migration `0105_recommendations.sql`. · *`reorderThresholds` primitive — per-SKU + per-location reorder thresholds + PO suggestions* — `bShop.reorderThresholds.create({ query?, catalog, inventoryLocations?, vendors? })` returns `{ defineThreshold, evaluate, scanAll, proposePurchaseOrder, recordVelocity, updateThreshold, archiveThreshold, listThresholds }`. Velocity-driven suggested_qty = `gap + ceil(units_per_day * lead_time_days)`. Partial-UNIQUE on `(sku, location_code)` for active rows. Migration `0098_reorder_thresholds.sql`. · *`shippingZones` primitive — operator-defined shipping zones + rate tables* — `bShop.shippingZones.create({ query? })` returns `{ defineZone, getZone, listZones, updateZone, archiveZone, rateFor, zoneForDestination }`. Region match: country-only or country + region. `rateFor` half-open `[min_weight, max_weight)` + `[min_order, max_order)` bucketing across rate rows; returns all matches sorted by rate ascending. Migration `0106_shipping_zones.sql`. · *`splitShipments` primitive — one-order N-shipment planning* — `bShop.splitShipments.create({ query?, order, orderTracking, backorder?, inventoryLocations? })` returns `{ planSplit, executeSplit, mergeShipments, splitsForOrder, recommendStrategy }`. Strategies: `availability / location / vendor / manual`. `executeSplit` writes shipment rows via `orderTracking.createShipment`. `mergeShipments` combines source shipments into a target. Migration `0096_split_shipments.sql`. · *`trustBadges` primitive — storefront trust seals + certifications* — `bShop.trustBadges.create({ query? })` returns `{ defineBadge, activeForPlacement, listAll, getBadge, updateBadge, archiveBadge, renderHtml, recordImpression, recordClick, impressionCount, clickCount }`. Placements: header / footer / pdp / cart_review / checkout / order_confirmation. SVG payload sanitized via `b.guardSvg`; link_url through `b.safeUrl`. Multiple badges can stack at one placement, sorted priority-DESC. Migration `0111_trust_badges.sql`. · *`webhookReceiver` primitive — inbound HMAC-signed webhook acceptor* — `bShop.webhookReceiver.create({ query?, now? })` returns `{ defineSource, verifyAndPersist, markProcessed, markFailed, unprocessedEvents, eventsForSource, getEvent, purgeOlderThan, rotateSecret, archiveSource, getSource, listSources }`. HMAC-SHA-256 verification + replay-window timestamps + idempotency_key dedup. Rotation carries a 24h grace window where deliveries signed under the old secret still verify. Plaintext secret returned once at `defineSource` / `rotateSecret`; storage holds only the namespaceHash digest. Migration `0110_webhook_receiver.sql`. **Fixed:** *`productBulkOps` — monotonic `_now` so back-to-back audit rows sort newest-first reliably* — Same Date.now() resolution issue that affected several earlier primitives — replaced with a process-local monotonic clock that bumps by 1ms on collision. The audit-trail `ORDER BY occurred_at DESC, id DESC` listing now returns rows in the correct insertion order even under same-millisecond bulk operations.
14
+
11
15
  - v0.0.64 (2026-05-22) — **Two new primitives: compliance export + live chat.** `complianceExport` is the GDPR / CCPA / LGPD subject-access-request export + deletion lifecycle. `liveChat` is the real-time customer-service queue with operator assignment and per-session messages. **Added:** *`complianceExport` primitive — GDPR / CCPA / LGPD subject-access-request export + deletion lifecycle* — `bShop.complianceExport.create({ query?, customers, order?, orderNotes?, subscriptions?, addresses?, paymentMethods?, supportTickets?, loyalty? })` returns `{ requestExport, requestDeletion, getRequest, listRequests, fulfillRequest, dispatchExport, processDeletion, dismissRequest, auditForCustomer }`. Composes injected per-domain readers via a `forCustomerExport(customer_id)` / `forCustomerDeletion(customer_id, { dry_run })` contract; the primitive owns the request row, the scope/section filtering, and the dry-run-vs-wet posture. Scope enum: `full / orders_only / identity_only`. Jurisdiction enum: `gdpr / ccpa / lgpd / other`. Status FSM: `received / processing / fulfilled / delivered / dismissed`. Migration `0109_compliance_export.sql`. · *`liveChat` primitive — real-time customer-service queue* — `bShop.liveChat.create({ query? })` returns `{ openSession, enqueueSession, assignToOperator, recordMessage, closeSession, getSession, messagesForSession, operatorQueue, waitingQueue, operatorWorkload, markOperatorAvailable, markOperatorAway, cleanupAbandoned }`. Six-state FSM: queued / assigned / active / waiting / closed / abandoned. Visitor session id + email hashed via `namespaceHash` under `live-chat-visitor` / `live-chat-email` namespaces; raw values never persist. Process-local monotonic `_now` so back-to-back operator assignments and message inserts paginate stably. `cleanupAbandoned({ idle_minutes })` reaps idle sessions. Migration `0113_live_chat.sql`.
12
16
 
13
17
  - v0.0.63 (2026-05-22) — **Three new primitives: invoice renderer, store credit, error log.** Three primitives ship in this release. `invoiceRenderer` produces operator + customer-facing formal invoices (HTML for PDF conversion + plain text + sequential invoice numbers). `storeCredit` is the per-customer account-bound credit wallet, distinct from gift cards (no code). `errorLog` is the operator-side HTTP error event log with top-404 / top-5xx / slow-render dashboards. **Added:** *`invoiceRenderer` primitive — formal accounting invoices with sequential numbers* — `bShop.invoiceRenderer.create({ query?, order })` returns `{ nextInvoiceNumber, renderHtml, recordInvoice, invoicesForOrder, getInvoiceByNumber }`. `nextInvoiceNumber({ series? })` returns sequential `INV-YYYY-NNNNNN`-shaped id with per-series counter. `renderHtml({ order_id, locale?, series?, due_days? })` returns the full HTML invoice with operator + customer addresses, line items, tax breakdown, totals, payment terms, due date. All operator + customer input fields HTML-escaped via `b.template.escapeHtml`. `recordInvoice` writes the audit row carrying `html_size` + `sha3_512` digest. Migration `0093_invoice_renderer.sql` (`invoice_renderings` + `invoice_sequence` tables). · *`storeCredit` primitive — per-customer account-bound credit wallet* — `bShop.storeCredit.create({ query? })` returns `{ credit, debit, expire, balance, history, transactionsForOrder, expiringWithin, bulkBalance, cleanupExpired }`. Distinct from `giftCardLedger` — store credit is account-bound, no code. `credit` source enum: `refund / goodwill / promotional / manual / loyalty_redemption`. `debit` refuses overdraft. `balance_after_minor` denormalized per row so current balance is O(1). `cleanupExpired({ now })` scheduler-callable: walks expired rows + adds offsetting expire entries. `expiringWithin({ customer_id, days })` lists balance set to expire so the storefront can prompt the customer. Migration `0094_store_credit.sql`. · *`errorLog` primitive — HTTP error event log with operator dashboards* — `bShop.errorLog.create({ query? })` returns `{ recordError, top404Paths, top5xxErrors, slowRenders, errorById, byStatus, metrics }`. Drop-silent on bad input — hot-path observability sink; throwing here would crash the request that triggered the log entry. Session id always hashed via `namespaceHash('error-log-session', ...)` before write. `top404Paths({ from, to, limit })` and `top5xxErrors({ from, to, limit })` power operator dead-link cleanup + upstream-health dashboards. `slowRenders({ from, to, limit, p99_threshold_ms? })` surfaces requests over the operator-configured p99 budget. `metrics` returns counts + p50 / p95 / p99 response time percentiles. Migration `0100_error_log.sql`.
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+ /**
3
+ * @module shop.addressValidation
4
+ * @title Address validation + autocomplete proxy cache — stores
5
+ * operator-supplied normalization results so repeat lookups
6
+ * against the same address don't re-pay the carrier API.
7
+ *
8
+ * @intro
9
+ * The primitive does not call USPS / Smarty / Lob / Google / Melissa
10
+ * itself. The operator wires the actual provider call; this
11
+ * primitive is the storage + cache layer. The operator hands the
12
+ * primitive:
13
+ *
14
+ * - `input` — the raw address (or address-suggest prefix) the
15
+ * user typed.
16
+ * - `normalized_address` — what the carrier normalized it to.
17
+ * - `deliverable` / `classification` / `dpv_match` — the
18
+ * carrier's verdict.
19
+ * - `source` — which carrier produced the answer
20
+ * (`usps / smarty / lob / google / melissa / manual`).
21
+ * - `expires_at` — operator-chosen ms-epoch when the cached row
22
+ * goes stale and `lookupCached` should fall through
23
+ * to a fresh provider call.
24
+ *
25
+ * The same raw address must hit the same cache row, even when the
26
+ * operator's call site renders the input object with the keys in a
27
+ * different order or with a slightly different shape. The primitive
28
+ * derives `input_signature` from
29
+ *
30
+ * b.crypto.namespaceHash("address-validation-input",
31
+ * b.safeJson.canonical(input))
32
+ *
33
+ * so map-order / whitespace fluctuation hashes identically. The
34
+ * schema's UNIQUE on `input_signature` makes `recordValidation` an
35
+ * upsert: a second call against the same signature overwrites the
36
+ * prior row (operators tuning expiry mid-flight get deterministic
37
+ * semantics).
38
+ *
39
+ * Surface:
40
+ * recordValidation({ input, normalized_address, deliverable,
41
+ * classification, dpv_match?, source,
42
+ * order_id?, expires_at })
43
+ * lookupCached(input)
44
+ * recordSuggestion({ partial_input, suggestions, expires_at })
45
+ * lookupSuggestions(partial_input)
46
+ * cleanupExpired({ now? })
47
+ * metricsForSource({ slug, from, to })
48
+ * validationsForOrder(order_id)
49
+ *
50
+ * Composes:
51
+ * - `b.crypto.namespaceHash` — SHA3-512 of the canonical input
52
+ * under the address-validation
53
+ * namespace.
54
+ * - `b.safeJson.canonical` — deterministic JSON serialization
55
+ * (keys sorted, no NaN / Infinity).
56
+ * - `b.uuid.v7` — row PKs.
57
+ *
58
+ * Storage:
59
+ * - `address_validations` + `address_suggestions_cache`
60
+ * (migration `0115_address_validation.sql`).
61
+ *
62
+ * @primitive addressValidation
63
+ * @related b.crypto, b.safeJson, b.uuid, shop.addresses, shop.geolocation
64
+ */
65
+
66
+ var bShop;
67
+ function _b() {
68
+ if (!bShop) bShop = require("./index");
69
+ return bShop.framework;
70
+ }
71
+
72
+ // ---- constants ----------------------------------------------------------
73
+
74
+ var INPUT_NAMESPACE = "address-validation-input";
75
+
76
+ var SOURCES = Object.freeze([
77
+ "usps", "smarty", "lob", "google", "melissa", "manual",
78
+ ]);
79
+
80
+ var CLASSIFICATIONS = Object.freeze([
81
+ "residential", "commercial", "po_box", "military", "unknown",
82
+ ]);
83
+
84
+ var MAX_NORMALIZED_JSON_LEN = 16 * 1024;
85
+ var MAX_PARTIAL_INPUT_LEN = 512;
86
+ var MAX_SUGGESTIONS_JSON_LEN = 32 * 1024;
87
+ var MAX_DPV_LEN = 16;
88
+ var MAX_ORDER_ID_LEN = 128;
89
+
90
+ // ---- validators ---------------------------------------------------------
91
+
92
+ function _input(value, label) {
93
+ label = label || "input";
94
+ if (value == null) {
95
+ throw new TypeError("addressValidation: " + label + " is required");
96
+ }
97
+ if (typeof value !== "object" || Array.isArray(value)) {
98
+ throw new TypeError("addressValidation: " + label + " must be a plain object");
99
+ }
100
+ return value;
101
+ }
102
+
103
+ function _msEpoch(n, label) {
104
+ if (typeof n !== "number" || !isFinite(n) || n < 0 || !Number.isInteger(n)) {
105
+ throw new TypeError(
106
+ "addressValidation: " + label + " must be a non-negative integer ms-epoch"
107
+ );
108
+ }
109
+ return n;
110
+ }
111
+
112
+ function _bool(v, label) {
113
+ if (typeof v !== "boolean") {
114
+ throw new TypeError("addressValidation: " + label + " must be a boolean");
115
+ }
116
+ return v;
117
+ }
118
+
119
+ function _source(s) {
120
+ if (typeof s !== "string" || SOURCES.indexOf(s) === -1) {
121
+ throw new TypeError(
122
+ "addressValidation: source must be one of " + JSON.stringify(SOURCES) +
123
+ ", got " + JSON.stringify(s)
124
+ );
125
+ }
126
+ return s;
127
+ }
128
+
129
+ function _classification(s) {
130
+ if (typeof s !== "string" || CLASSIFICATIONS.indexOf(s) === -1) {
131
+ throw new TypeError(
132
+ "addressValidation: classification must be one of " +
133
+ JSON.stringify(CLASSIFICATIONS) + ", got " + JSON.stringify(s)
134
+ );
135
+ }
136
+ return s;
137
+ }
138
+
139
+ function _dpvMatch(s) {
140
+ if (s == null) return null;
141
+ if (typeof s !== "string" || !s.length) {
142
+ throw new TypeError("addressValidation: dpv_match must be a non-empty string or null");
143
+ }
144
+ if (s.length > MAX_DPV_LEN) {
145
+ throw new TypeError(
146
+ "addressValidation: dpv_match must be <= " + MAX_DPV_LEN + " characters"
147
+ );
148
+ }
149
+ if (/[\x00-\x1F\x7F]/.test(s)) {
150
+ throw new TypeError("addressValidation: dpv_match must not contain control bytes");
151
+ }
152
+ return s;
153
+ }
154
+
155
+ function _orderId(s) {
156
+ if (s == null) return null;
157
+ if (typeof s !== "string" || !s.length) {
158
+ throw new TypeError("addressValidation: order_id must be a non-empty string or null");
159
+ }
160
+ if (s.length > MAX_ORDER_ID_LEN) {
161
+ throw new TypeError(
162
+ "addressValidation: order_id must be <= " + MAX_ORDER_ID_LEN + " characters"
163
+ );
164
+ }
165
+ if (/[\x00-\x1F\x7F]/.test(s)) {
166
+ throw new TypeError("addressValidation: order_id must not contain control bytes");
167
+ }
168
+ return s;
169
+ }
170
+
171
+ function _normalizedAddress(v) {
172
+ if (v == null || typeof v !== "object" || Array.isArray(v)) {
173
+ throw new TypeError(
174
+ "addressValidation: normalized_address must be a plain object"
175
+ );
176
+ }
177
+ var json;
178
+ try { json = _b().safeJson.canonical(v); }
179
+ catch (e) {
180
+ throw new TypeError(
181
+ "addressValidation: normalized_address must be JSON-serializable — " + e.message
182
+ );
183
+ }
184
+ if (json.length > MAX_NORMALIZED_JSON_LEN) {
185
+ throw new TypeError(
186
+ "addressValidation: normalized_address canonical-JSON must be <= " +
187
+ MAX_NORMALIZED_JSON_LEN + " bytes"
188
+ );
189
+ }
190
+ return json;
191
+ }
192
+
193
+ function _partialInput(s) {
194
+ if (typeof s !== "string" || !s.length) {
195
+ throw new TypeError("addressValidation: partial_input must be a non-empty string");
196
+ }
197
+ if (s.length > MAX_PARTIAL_INPUT_LEN) {
198
+ throw new TypeError(
199
+ "addressValidation: partial_input must be <= " + MAX_PARTIAL_INPUT_LEN + " characters"
200
+ );
201
+ }
202
+ if (/[\x00-\x1F\x7F]/.test(s)) {
203
+ throw new TypeError("addressValidation: partial_input must not contain control bytes");
204
+ }
205
+ return s;
206
+ }
207
+
208
+ function _suggestions(v) {
209
+ if (!Array.isArray(v)) {
210
+ throw new TypeError("addressValidation: suggestions must be an array");
211
+ }
212
+ var json;
213
+ try { json = _b().safeJson.canonical(v); }
214
+ catch (e) {
215
+ throw new TypeError(
216
+ "addressValidation: suggestions must be JSON-serializable — " + e.message
217
+ );
218
+ }
219
+ if (json.length > MAX_SUGGESTIONS_JSON_LEN) {
220
+ throw new TypeError(
221
+ "addressValidation: suggestions canonical-JSON must be <= " +
222
+ MAX_SUGGESTIONS_JSON_LEN + " bytes"
223
+ );
224
+ }
225
+ return json;
226
+ }
227
+
228
+ function _now() { return Date.now(); }
229
+
230
+ // ---- signature helper --------------------------------------------------
231
+
232
+ function _signatureForInput(input) {
233
+ _input(input, "input");
234
+ var canonical;
235
+ try { canonical = _b().safeJson.canonical(input); }
236
+ catch (e) {
237
+ throw new TypeError(
238
+ "addressValidation: input must be JSON-serializable — " + e.message
239
+ );
240
+ }
241
+ return _b().crypto.namespaceHash(INPUT_NAMESPACE, canonical);
242
+ }
243
+
244
+ // ---- row -> wire conversions -------------------------------------------
245
+
246
+ function _parseNormalized(raw) {
247
+ try { return JSON.parse(raw); }
248
+ catch (_e) {
249
+ throw new Error(
250
+ "addressValidation: normalized_address_json column is malformed JSON — storage corruption"
251
+ );
252
+ }
253
+ }
254
+
255
+ function _rowToValidation(row) {
256
+ if (!row) return null;
257
+ return {
258
+ id: row.id,
259
+ input_signature: row.input_signature,
260
+ normalized_address: _parseNormalized(row.normalized_address_json),
261
+ deliverable: Number(row.deliverable) === 1,
262
+ classification: row.classification,
263
+ dpv_match: row.dpv_match == null ? null : row.dpv_match,
264
+ source: row.source,
265
+ order_id: row.order_id == null ? null : row.order_id,
266
+ expires_at: Number(row.expires_at),
267
+ occurred_at: Number(row.occurred_at),
268
+ };
269
+ }
270
+
271
+ function _rowToSuggestion(row) {
272
+ if (!row) return null;
273
+ var parsed;
274
+ try { parsed = JSON.parse(row.suggestions_json); }
275
+ catch (_e) {
276
+ throw new Error(
277
+ "addressValidation: suggestions_json column is malformed JSON — storage corruption"
278
+ );
279
+ }
280
+ return {
281
+ id: row.id,
282
+ partial_input: row.partial_input,
283
+ suggestions: parsed,
284
+ expires_at: Number(row.expires_at),
285
+ occurred_at: Number(row.occurred_at),
286
+ };
287
+ }
288
+
289
+ // ---- factory -----------------------------------------------------------
290
+
291
+ function create(opts) {
292
+ opts = opts || {};
293
+ var query = opts.query;
294
+ if (!query) {
295
+ query = function (sql, params) { return _b().externalDb.query(sql, params); };
296
+ }
297
+
298
+ async function _getValidationBySig(sig) {
299
+ var r = await query(
300
+ "SELECT * FROM address_validations WHERE input_signature = ?1",
301
+ [sig],
302
+ );
303
+ return r.rows[0] || null;
304
+ }
305
+
306
+ async function _getSuggestionByInput(p) {
307
+ var r = await query(
308
+ "SELECT * FROM address_suggestions_cache WHERE partial_input = ?1",
309
+ [p],
310
+ );
311
+ return r.rows[0] || null;
312
+ }
313
+
314
+ return {
315
+ SOURCES: SOURCES,
316
+ CLASSIFICATIONS: CLASSIFICATIONS,
317
+
318
+ // Stamp a normalization result against the input that produced it.
319
+ // The schema's UNIQUE on input_signature makes this an upsert: a
320
+ // second call against the same input overwrites the prior row.
321
+ // Operators tune cache lifetime by raising / lowering `expires_at`
322
+ // on each fresh write — the cache is operator-managed, not
323
+ // primitive-managed.
324
+ recordValidation: async function (input) {
325
+ if (!input || typeof input !== "object") {
326
+ throw new TypeError("addressValidation.recordValidation: input object required");
327
+ }
328
+ var sig = _signatureForInput(input.input);
329
+ var normalizedJson = _normalizedAddress(input.normalized_address);
330
+ var deliverable = _bool(input.deliverable, "deliverable");
331
+ var classification = _classification(input.classification);
332
+ var dpvMatch = _dpvMatch(input.dpv_match == null ? null : input.dpv_match);
333
+ var source = _source(input.source);
334
+ var orderId = _orderId(input.order_id == null ? null : input.order_id);
335
+ var expiresAt = _msEpoch(input.expires_at, "expires_at");
336
+ var occurredAt = input.occurred_at == null ? _now() : _msEpoch(input.occurred_at, "occurred_at");
337
+
338
+ // Upsert. Existing row -> overwrite every operator-supplied
339
+ // column AND refresh `occurred_at` so `metricsForSource` reflects
340
+ // the latest provider call. The id stays stable so any external
341
+ // reference doesn't dangle.
342
+ var existing = await _getValidationBySig(sig);
343
+ if (existing) {
344
+ await query(
345
+ "UPDATE address_validations SET " +
346
+ "normalized_address_json = ?1, deliverable = ?2, classification = ?3, " +
347
+ "dpv_match = ?4, source = ?5, order_id = ?6, expires_at = ?7, occurred_at = ?8 " +
348
+ "WHERE input_signature = ?9",
349
+ [
350
+ normalizedJson, deliverable ? 1 : 0, classification,
351
+ dpvMatch, source, orderId, expiresAt, occurredAt, sig,
352
+ ],
353
+ );
354
+ return _rowToValidation(await _getValidationBySig(sig));
355
+ }
356
+
357
+ var id = _b().uuid.v7();
358
+ await query(
359
+ "INSERT INTO address_validations " +
360
+ "(id, input_signature, normalized_address_json, deliverable, classification, " +
361
+ " dpv_match, source, order_id, expires_at, occurred_at) " +
362
+ "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
363
+ [
364
+ id, sig, normalizedJson, deliverable ? 1 : 0, classification,
365
+ dpvMatch, source, orderId, expiresAt, occurredAt,
366
+ ],
367
+ );
368
+ return _rowToValidation(await _getValidationBySig(sig));
369
+ },
370
+
371
+ // Look up a cached validation by the raw input shape. Returns the
372
+ // hydrated row when fresh, `null` when either no row exists OR the
373
+ // row's `expires_at` is at-or-before now (expired rows are surfaced
374
+ // as a cache miss so the caller falls through to a fresh provider
375
+ // call). `cleanupExpired` actually deletes the row; this method
376
+ // never mutates.
377
+ lookupCached: async function (input) {
378
+ var sig = _signatureForInput(input);
379
+ var row = await _getValidationBySig(sig);
380
+ if (!row) return null;
381
+ var hydrated = _rowToValidation(row);
382
+ if (hydrated.expires_at <= _now()) return null;
383
+ return hydrated;
384
+ },
385
+
386
+ // Compute the cache signature for a raw input — exposed so
387
+ // operators can pre-hash and key external storage off the same
388
+ // shape without re-running the canonical-JSON pipeline.
389
+ signatureFor: function (input) {
390
+ return _signatureForInput(input);
391
+ },
392
+
393
+ // Autocomplete cache: a partial-input string -> array of
394
+ // operator-opaque suggestion objects. Same upsert + expiry shape
395
+ // as the validations table.
396
+ recordSuggestion: async function (input) {
397
+ if (!input || typeof input !== "object") {
398
+ throw new TypeError("addressValidation.recordSuggestion: input object required");
399
+ }
400
+ var partial = _partialInput(input.partial_input);
401
+ var suggestionsJson = _suggestions(input.suggestions);
402
+ var expiresAt = _msEpoch(input.expires_at, "expires_at");
403
+ var occurredAt = input.occurred_at == null ? _now() : _msEpoch(input.occurred_at, "occurred_at");
404
+
405
+ var existing = await _getSuggestionByInput(partial);
406
+ if (existing) {
407
+ await query(
408
+ "UPDATE address_suggestions_cache SET " +
409
+ "suggestions_json = ?1, expires_at = ?2, occurred_at = ?3 " +
410
+ "WHERE partial_input = ?4",
411
+ [suggestionsJson, expiresAt, occurredAt, partial],
412
+ );
413
+ return _rowToSuggestion(await _getSuggestionByInput(partial));
414
+ }
415
+
416
+ var id = _b().uuid.v7();
417
+ await query(
418
+ "INSERT INTO address_suggestions_cache " +
419
+ "(id, partial_input, suggestions_json, expires_at, occurred_at) " +
420
+ "VALUES (?1, ?2, ?3, ?4, ?5)",
421
+ [id, partial, suggestionsJson, expiresAt, occurredAt],
422
+ );
423
+ return _rowToSuggestion(await _getSuggestionByInput(partial));
424
+ },
425
+
426
+ lookupSuggestions: async function (partialInput) {
427
+ var partial = _partialInput(partialInput);
428
+ var row = await _getSuggestionByInput(partial);
429
+ if (!row) return null;
430
+ var hydrated = _rowToSuggestion(row);
431
+ if (hydrated.expires_at <= _now()) return null;
432
+ return hydrated;
433
+ },
434
+
435
+ // Delete every row in both tables whose expires_at has elapsed.
436
+ // Returns `{ validations, suggestions, now }` so operators can
437
+ // surface a "swept N stale entries" admin metric. Idempotent —
438
+ // a second call immediately after the first returns zero counts.
439
+ cleanupExpired: async function (input) {
440
+ input = input || {};
441
+ var now = input.now == null ? _now() : _msEpoch(input.now, "now");
442
+ var rV = await query(
443
+ "DELETE FROM address_validations WHERE expires_at <= ?1",
444
+ [now],
445
+ );
446
+ var rS = await query(
447
+ "DELETE FROM address_suggestions_cache WHERE expires_at <= ?1",
448
+ [now],
449
+ );
450
+ return {
451
+ validations: rV.rowCount != null ? Number(rV.rowCount) : 0,
452
+ suggestions: rS.rowCount != null ? Number(rS.rowCount) : 0,
453
+ now: now,
454
+ };
455
+ },
456
+
457
+ // Aggregate per-source counts over the [from, to] window keyed
458
+ // on `occurred_at`. `slug` (the operator-facing arg name from the
459
+ // spec) carries the source enum value; the result splits by
460
+ // classification + deliverable so operators can spot a carrier
461
+ // whose classification mix drifts.
462
+ metricsForSource: async function (input) {
463
+ if (!input || typeof input !== "object") {
464
+ throw new TypeError("addressValidation.metricsForSource: input object required");
465
+ }
466
+ var source = _source(input.slug);
467
+ var from = _msEpoch(input.from, "from");
468
+ var to = _msEpoch(input.to, "to");
469
+ if (to < from) {
470
+ throw new TypeError("addressValidation.metricsForSource: to must be >= from");
471
+ }
472
+ var rows = (await query(
473
+ "SELECT classification, deliverable, COUNT(*) AS row_count " +
474
+ "FROM address_validations " +
475
+ "WHERE source = ?1 AND occurred_at >= ?2 AND occurred_at <= ?3 " +
476
+ "GROUP BY classification, deliverable " +
477
+ "ORDER BY classification ASC, deliverable ASC",
478
+ [source, from, to],
479
+ )).rows;
480
+ var out = [];
481
+ var total = 0;
482
+ for (var i = 0; i < rows.length; i += 1) {
483
+ var r = rows[i];
484
+ var n = Number(r.row_count);
485
+ total += n;
486
+ out.push({
487
+ source: source,
488
+ classification: r.classification,
489
+ deliverable: Number(r.deliverable) === 1,
490
+ count: n,
491
+ });
492
+ }
493
+ return { source: source, from: from, to: to, total: total, buckets: out };
494
+ },
495
+
496
+ // Every validation row tagged with the given order_id, in
497
+ // recorded-newest-first order. Operators present this list as the
498
+ // audit trail for "show me every address normalization we paid
499
+ // for on order X." Rows the operator never stamped with an
500
+ // order_id are silently excluded.
501
+ validationsForOrder: async function (orderId) {
502
+ if (typeof orderId !== "string" || !orderId.length) {
503
+ throw new TypeError("addressValidation.validationsForOrder: order_id must be a non-empty string");
504
+ }
505
+ if (orderId.length > MAX_ORDER_ID_LEN) {
506
+ throw new TypeError(
507
+ "addressValidation.validationsForOrder: order_id must be <= " + MAX_ORDER_ID_LEN + " characters"
508
+ );
509
+ }
510
+ var rows = (await query(
511
+ "SELECT * FROM address_validations WHERE order_id = ?1 " +
512
+ "ORDER BY occurred_at DESC, id DESC",
513
+ [orderId],
514
+ )).rows;
515
+ var out = [];
516
+ for (var i = 0; i < rows.length; i += 1) {
517
+ out.push(_rowToValidation(rows[i]));
518
+ }
519
+ return out;
520
+ },
521
+ };
522
+ }
523
+
524
+ module.exports = {
525
+ create: create,
526
+ SOURCES: SOURCES,
527
+ CLASSIFICATIONS: CLASSIFICATIONS,
528
+ INPUT_NAMESPACE: INPUT_NAMESPACE,
529
+ };