@nymbalhq/platform 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/{chunk-2PLYK5RU.js → chunk-GMV3B3SC.js} +3369 -606
  2. package/dist/chunk-GMV3B3SC.js.map +1 -0
  3. package/dist/{chunk-QN56IB4G.js → chunk-SNNK2OX3.js} +119 -5
  4. package/dist/chunk-SNNK2OX3.js.map +1 -0
  5. package/dist/db/schema/index.d.ts +1766 -404
  6. package/dist/db/schema/index.js +1 -1
  7. package/dist/index.d.ts +224 -10
  8. package/dist/index.js +659 -2172
  9. package/dist/index.js.map +1 -1
  10. package/dist/register-N2XGSFUF.js +8 -0
  11. package/migrations/postgres/0013_order_access_keys.sql +11 -0
  12. package/migrations/postgres/0014_alert_subscriptions.sql +22 -0
  13. package/migrations/postgres/0015_events_retry_at.sql +1 -0
  14. package/migrations/postgres/meta/0013_snapshot.json +2000 -0
  15. package/migrations/postgres/meta/0014_snapshot.json +2185 -0
  16. package/migrations/postgres/meta/0015_snapshot.json +2191 -0
  17. package/migrations/postgres/meta/_journal.json +21 -0
  18. package/migrations/sqlite/0013_order_access_keys.sql +11 -0
  19. package/migrations/sqlite/0014_alert_subscriptions.sql +22 -0
  20. package/migrations/sqlite/0015_events_retry_at.sql +1 -0
  21. package/migrations/sqlite/meta/0013_snapshot.json +1788 -0
  22. package/migrations/sqlite/meta/0014_snapshot.json +1931 -0
  23. package/migrations/sqlite/meta/0015_snapshot.json +1938 -0
  24. package/migrations/sqlite/meta/_journal.json +21 -0
  25. package/package.json +19 -19
  26. package/dist/chunk-2PLYK5RU.js.map +0 -1
  27. package/dist/chunk-QN56IB4G.js.map +0 -1
  28. package/dist/register-UUQ64HZP.js +0 -8
  29. /package/dist/{register-UUQ64HZP.js.map → register-N2XGSFUF.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  postgres_exports,
3
3
  sqlite_exports
4
- } from "../../chunk-QN56IB4G.js";
4
+ } from "../../chunk-SNNK2OX3.js";
5
5
  export {
6
6
  postgres_exports as postgresSchema,
7
7
  sqlite_exports as sqliteSchema
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { NymbalConfig } from '@nymbalhq/config';
2
- import { Logger, DocumentStoreAdapter, EventBusAdapter, MediaStorage, Product, ProductStatus, ProductType, ProductMedia, Variant, VariantDimensions, VariantOption, VariantStatus, Category, Customer, Role, CustomerAddress, Order, OrderStatus, Address, OrderLineItem, CaptureMethod, OrderHistoryEntry, OrderRefundStatus, OrderRefund, InventoryReservation, StockAdjustmentReason, StockAdjustment, Review, ReviewModerationStatus, NymbalEvent, Cart, AuditSubject, AuditActor, AuditOutcome, AuditEntry, HealthReport, PutOptions, QueryParams, QueryResult, EventHandler, SubscriptionConfig, Subscription, NymbalEnvironment, NymbalEventType, NymbalEventMap, RequestAuth, AdapterSetting, CommerceSlotAdapters, SecurityAdapter, AiAdapter, PaymentsAdapter, ProductSnapshot, CartItem, StockStatus, PaymentIntent, CheckoutPayment, SearchParams, SearchResult, SearchAdapter, OrderPayment, Refund, CommerceSlot, HttpAdapter, Slot, ProviderPackageModule, RateLimitAction, EmailAdapter, ReviewsAdapter, AnalyticsAdapter, ShippingAdapter, TaxAdapter, HealthStatus } from '@nymbalhq/types';
2
+ import { Logger, DocumentStoreAdapter, EventBusAdapter, MediaStorage, Product, ProductStatus, ProductType, ProductMedia, Variant, VariantDimensions, VariantOption, VariantStatus, Category, Customer, Role, CustomerAddress, Order, OrderStatus, Address, OrderLineItem, CaptureMethod, OrderHistoryEntry, OrderRefundStatus, OrderRefund, InventoryReservation, StockAdjustmentReason, StockAdjustment, Review, ReviewModerationStatus, NymbalEvent, Cart, AuditSubject, AuditActor, AuditOutcome, AuditEntry, AlertKind, AlertStatus, HealthReport, PutOptions, QueryParams, QueryResult, EventHandler, SubscriptionConfig, Subscription, NymbalEnvironment, NymbalEventType, NymbalEventMap, RequestAuth, AdapterSetting, CommerceSlotAdapters, SecurityAdapter, AiAdapter, PaymentsAdapter, EmailAdapter, ProductSnapshot, CartItem, StockStatus, PaymentIntent, CheckoutPayment, SearchParams, SearchResult, SearchAdapter, OrderPayment, Refund, RecentViewer, CommerceSlot, HttpAdapter, Slot, ProviderPackageModule, RateLimitAction, ReviewsAdapter, AnalyticsAdapter, ShippingAdapter, TaxAdapter, HealthStatus } from '@nymbalhq/types';
3
3
  export { MediaStorage, buildSecurityHeaders, isValidCorrelationId } from '@nymbalhq/types';
4
4
  import BetterSqlite3 from 'better-sqlite3';
5
5
  import pg from 'pg';
@@ -485,6 +485,23 @@ interface OrderSequenceRepository extends StoreRepository {
485
485
  }
486
486
  declare function createOrderSequenceRepository(store: CommandStore): OrderSequenceRepository;
487
487
 
488
+ /** Who minted the key: a checkout answer, or the order-placed email. */
489
+ type OrderAccessKeyPurpose = 'checkout' | 'email';
490
+ interface OrderAccessKeyInsert {
491
+ id: string;
492
+ orderId: string;
493
+ /** sha256 hex of the key; the key itself is never stored. */
494
+ keyHash: string;
495
+ purpose: OrderAccessKeyPurpose;
496
+ createdAt: Date;
497
+ }
498
+ interface OrderAccessKeyRepository extends StoreRepository {
499
+ insert(tx: Tx, k: OrderAccessKeyInsert): Promise<void>;
500
+ /** Whether a key with this hash opens this order: another order's key opens nothing here. */
501
+ opens(tx: ReadTx, orderId: string, keyHash: string): Promise<boolean>;
502
+ }
503
+ declare function createOrderAccessKeyRepository(store: CommandStore): OrderAccessKeyRepository;
504
+
488
505
  interface ReservationInsert {
489
506
  reservationId: string;
490
507
  variantId: string;
@@ -558,6 +575,11 @@ interface ProcessedEventRepository extends StoreRepository {
558
575
  seen(tx: ReadTx, handlerName: string, eventId: string): Promise<boolean>;
559
576
  /** Idempotent on (handlerName, eventId): a second call keeps the first record. */
560
577
  markProcessed(tx: Tx, handlerName: string, eventId: string, at: Date): Promise<void>;
578
+ /**
579
+ * Records (handlerName, eventId) before its work runs: true when this call inserted it, false when it was there.
580
+ * On Postgres a concurrent claim of the same key waits for this transaction, so only one of them does the work.
581
+ */
582
+ claim(tx: Tx, handlerName: string, eventId: string, at: Date): Promise<boolean>;
561
583
  /** Deletes records processed before `at`; returns how many. */
562
584
  deleteBefore(tx: Tx, at: Date): Promise<number>;
563
585
  }
@@ -590,11 +612,22 @@ interface EventLogFilter {
590
612
  interface EventLogRepository extends StoreRepository {
591
613
  /** Appends in array order, so `seq` follows publish order. */
592
614
  append(tx: Tx, events: NymbalEvent<unknown>[]): Promise<void>;
593
- /** Neither delivered nor dead, by `seq`; `afterSeq` pages through one pass without re-reading rows it just tried. */
594
- listUndelivered(tx: ReadTx, limit: number, afterSeq?: number): Promise<LoggedEvent[]>;
615
+ /**
616
+ * Neither delivered nor dead, by `seq`; `afterSeq` pages through one pass without re-reading rows it just tried.
617
+ * Given `now`, a row whose `retry_at` is after it is left out.
618
+ */
619
+ listUndelivered(tx: ReadTx, limit: number, afterSeq?: number, now?: Date): Promise<LoggedEvent[]>;
595
620
  markDelivered(tx: Tx, ids: string[], at: Date): Promise<void>;
596
- /** One more failed attempt; the event is dead (`dead_at = at`) once its attempts reach `maxAttempts`. */
597
- recordFailure(tx: Tx, id: string, at: Date, maxAttempts: number): Promise<void>;
621
+ /**
622
+ * One more failed attempt; the event is dead (`dead_at = at`) once its attempts reach `maxAttempts`. `retryAt`, when
623
+ * given, is the earliest the next attempt may be made.
624
+ */
625
+ recordFailure(tx: Tx, id: string, at: Date, maxAttempts: number, retryAt?: Date): Promise<void>;
626
+ countDead(tx: ReadTx): Promise<number>;
627
+ /** Dead events, oldest first. */
628
+ listDead(tx: ReadTx, limit: number): Promise<LoggedEvent[]>;
629
+ /** Neither delivered nor dead, with at least one failed attempt. */
630
+ countRetrying(tx: ReadTx): Promise<number>;
598
631
  /** Deletes delivered events delivered before `at`; returns how many. Undelivered and dead events are never deleted. */
599
632
  deleteDeliveredBefore(tx: Tx, at: Date): Promise<number>;
600
633
  listAll(tx: ReadTx): Promise<LoggedEvent[]>;
@@ -754,6 +787,61 @@ interface AuditEntryRepository extends StoreRepository {
754
787
  }
755
788
  declare function createAuditEntryRepository(store: CommandStore): AuditEntryRepository;
756
789
 
790
+ /** A row of `alert_subscriptions`: one address's alert of one kind on one variant. */
791
+ interface AlertSubscription {
792
+ id: string;
793
+ /** Trimmed and lower-cased. */
794
+ email: string;
795
+ kind: AlertKind;
796
+ variantId: string;
797
+ productId: string;
798
+ status: AlertStatus;
799
+ confirmToken: string;
800
+ unsubscribeToken: string;
801
+ /** The storefront origin its links point at. */
802
+ origin: string;
803
+ baselinePriceMinor: number | null;
804
+ createdAt: Date;
805
+ updatedAt: Date;
806
+ confirmedAt: Date | null;
807
+ }
808
+ /** A subscribe request: a new row's values, of which a row already there takes only what its status allows. */
809
+ interface AlertSubscriptionRequest {
810
+ id: string;
811
+ email: string;
812
+ kind: AlertKind;
813
+ variantId: string;
814
+ productId: string;
815
+ confirmToken: string;
816
+ unsubscribeToken: string;
817
+ origin: string;
818
+ /** A price-drop row's price at subscribe time; null for a back-in-stock row. */
819
+ baselinePriceMinor: number | null;
820
+ at: Date;
821
+ }
822
+ interface AlertSubscriptionPatch {
823
+ status: AlertStatus;
824
+ updatedAt: Date;
825
+ confirmedAt?: Date;
826
+ /** The price a price-drop row was last told. */
827
+ baselinePriceMinor?: number;
828
+ }
829
+ interface AlertSubscriptionRepository extends StoreRepository {
830
+ /**
831
+ * One write on the unique (email, variant, kind): a new row is `pending`; a `pending` row takes the request's origin;
832
+ * an `unsubscribed` or `fired` row returns to `pending` with the request's origin, confirm token and baseline (its
833
+ * unsubscribe token is kept); an `active` row only has `updated_at` touched. Answers the row after the write.
834
+ */
835
+ upsertPending(tx: Tx, request: AlertSubscriptionRequest): Promise<AlertSubscription>;
836
+ findById(tx: ReadTx, id: string): Promise<AlertSubscription | null>;
837
+ findByConfirmToken(tx: ReadTx, token: string): Promise<AlertSubscription | null>;
838
+ findByUnsubscribeToken(tx: ReadTx, token: string): Promise<AlertSubscription | null>;
839
+ listActive(tx: ReadTx, variantId: string, kind: AlertKind): Promise<AlertSubscription[]>;
840
+ /** Applies `patch` when the row's status is one of `from`; the row after, or null when nothing changed. */
841
+ update(tx: Tx, id: string, patch: AlertSubscriptionPatch, from: readonly AlertStatus[]): Promise<AlertSubscription | null>;
842
+ }
843
+ declare function createAlertSubscriptionRepository(store: CommandStore): AlertSubscriptionRepository;
844
+
757
845
  interface Repositories {
758
846
  product: ProductRepository;
759
847
  variant: VariantRepository;
@@ -765,6 +853,7 @@ interface Repositories {
765
853
  orderHistory: OrderHistoryRepository;
766
854
  orderRefund: OrderRefundRepository;
767
855
  orderSequence: OrderSequenceRepository;
856
+ orderAccessKey: OrderAccessKeyRepository;
768
857
  inventoryReservation: InventoryReservationRepository;
769
858
  stockAdjustment: StockAdjustmentRepository;
770
859
  review: ReviewRepository;
@@ -773,6 +862,7 @@ interface Repositories {
773
862
  cart: CartRepository;
774
863
  settings: SettingsRepository;
775
864
  auditEntry: AuditEntryRepository;
865
+ alertSubscription: AlertSubscriptionRepository;
776
866
  }
777
867
  declare function buildRepositories(commandStore: CommandStore, _documentStore: DocumentStoreAdapter): Repositories;
778
868
 
@@ -851,6 +941,10 @@ interface CreateRelayOptions {
851
941
  /** Failed bus publishes after which an event is dead and never handed to the bus again. */
852
942
  maxAttempts?: number;
853
943
  intervalMs?: number;
944
+ /** The wait before the first retry of a failed event (default `intervalMs`); each later wait doubles it. */
945
+ retryDelayMs?: number;
946
+ /** The clock failures and retry waits are read from. */
947
+ now?: () => Date;
854
948
  }
855
949
  declare function createRelay(opts: CreateRelayOptions): Relay;
856
950
 
@@ -865,6 +959,14 @@ interface EventPublisher {
865
959
  options?: PublishOptions;
866
960
  };
867
961
  }[NymbalEventType]>): Promise<void>;
962
+ /**
963
+ * Events of types the kernel does not declare (an adapter's own, already checked by the caller), with the same
964
+ * append and drain as `publish`.
965
+ */
966
+ publishUntyped(events: ReadonlyArray<{
967
+ type: string;
968
+ payload: unknown;
969
+ }>, options?: PublishOptions): Promise<NymbalEvent<unknown>[]>;
868
970
  correlated(correlationId: string): EventPublisher;
869
971
  }
870
972
  interface CreatePublisherOptions {
@@ -948,16 +1050,72 @@ interface BuildAdaptersDeps {
948
1050
  }
949
1051
  declare function buildAdapters(deps: BuildAdaptersDeps): Promise<AdapterRegistry>;
950
1052
 
1053
+ interface AlertSubscribeInput {
1054
+ email: string;
1055
+ variantId: string;
1056
+ kind: AlertKind;
1057
+ /** The request's `Origin` header: the storefront the links in its emails point at. */
1058
+ origin: string | undefined;
1059
+ }
1060
+ interface AlertConfirmed {
1061
+ status: 'active';
1062
+ kind: AlertKind;
1063
+ product: {
1064
+ name: string;
1065
+ slug: string;
1066
+ };
1067
+ }
1068
+ interface AlertService {
1069
+ /**
1070
+ * Answers `pending` whatever the address's account or subscription, so the answer reveals neither; every accepted
1071
+ * request writes the row once. Only a row that is not `active` is (re)sent its confirmation.
1072
+ */
1073
+ subscribe(input: AlertSubscribeInput): Promise<{
1074
+ status: 'pending';
1075
+ }>;
1076
+ confirm(token: string): Promise<AlertConfirmed>;
1077
+ unsubscribe(token: string): Promise<{
1078
+ status: 'unsubscribed';
1079
+ }>;
1080
+ /**
1081
+ * In the transaction that marks an alert's send: a back-in-stock row is `fired`, a price-drop row stays `active` with
1082
+ * the trigger's price as its baseline; `alert.sent.v1` names the trigger.
1083
+ */
1084
+ recordSent(tx: Tx, subscription: AlertSubscription, trigger: NymbalEvent<unknown>): Promise<void>;
1085
+ }
1086
+ interface CreateAlertServiceDeps {
1087
+ store: CommandStore;
1088
+ repos: Repositories;
1089
+ publisher: EventPublisher;
1090
+ /** `http.cors.allowedOrigins`: the storefronts a subscribe may come from. A `*` entry matches no origin. */
1091
+ allowedOrigins: readonly string[];
1092
+ /** Whether the store's email reaches a mailbox; a store whose email only logs takes no subscription. */
1093
+ delivers(): boolean;
1094
+ }
1095
+ declare function createAlertService(deps: CreateAlertServiceDeps): AlertService;
1096
+
951
1097
  interface RegisterHandlersDeps {
952
1098
  config: NymbalConfig;
953
1099
  eventBus: EventBusAdapter;
954
1100
  documentStore: DocumentStoreAdapter;
955
1101
  repos: Repositories;
956
1102
  adapters: AdapterRegistry;
1103
+ /** Records each alert's send: the row fired and `alert.sent.v1` published. */
1104
+ alerts: AlertService;
957
1105
  logger: Logger;
958
1106
  }
959
1107
  declare function registerHandlers(deps: RegisterHandlersDeps): Promise<void>;
960
1108
 
1109
+ interface RegisterAlertHandlerDeps {
1110
+ eventBus: EventBusAdapter;
1111
+ email: EmailAdapter;
1112
+ logger: Logger;
1113
+ repos: Pick<Repositories, 'alertSubscription' | 'processedEvent' | 'product'>;
1114
+ alerts: AlertService;
1115
+ storeName: string;
1116
+ }
1117
+ declare function registerAlertHandler(deps: RegisterAlertHandlerDeps): Promise<void>;
1118
+
961
1119
  interface ProductCreateInput {
962
1120
  slug: string;
963
1121
  name: string;
@@ -974,8 +1132,16 @@ interface ProductCreateInput {
974
1132
  id?: string;
975
1133
  }>;
976
1134
  }
1135
+ /** A variant's prices: `compareAtPriceMinor` omitted keeps the stored one, null clears it. */
1136
+ interface VariantPriceInput {
1137
+ id: string;
1138
+ priceMinor: number;
1139
+ compareAtPriceMinor?: number | null;
1140
+ }
977
1141
  interface ProductUpdateInput extends Omit<ProductUpdate, 'updatedAt'> {
978
1142
  categoryIds?: string[];
1143
+ /** Prices of some of the product's own variants; a variant left out is unchanged, and none is added or deleted. */
1144
+ variants?: VariantPriceInput[];
979
1145
  }
980
1146
  interface ProductService {
981
1147
  create(input: ProductCreateInput): Promise<ProductSnapshot>;
@@ -996,6 +1162,8 @@ interface CreateProductServiceDeps {
996
1162
  repos: Repositories;
997
1163
  publisher: EventPublisher;
998
1164
  logger: Logger;
1165
+ /** The store's currency, which a price event names. */
1166
+ currency: string;
999
1167
  }
1000
1168
  declare function createProductService(deps: CreateProductServiceDeps): ProductService;
1001
1169
 
@@ -1117,6 +1285,7 @@ interface CreateAuthServiceDeps {
1117
1285
  refreshTtl: string;
1118
1286
  issuer?: string;
1119
1287
  }
1288
+ declare function parseDurationToMs(s: string): number;
1120
1289
  declare function createAuthService(deps: CreateAuthServiceDeps): AuthService;
1121
1290
 
1122
1291
  interface OrderCreateDraftInput {
@@ -1152,11 +1321,18 @@ interface OrderService {
1152
1321
  getById(id: string): Promise<Order>;
1153
1322
  getByOrderNumber(orderNumber: string): Promise<Order>;
1154
1323
  listByCustomer(customerId: string): Promise<Order[]>;
1324
+ /** Whether `key` opens the order: one of its own keys, well formed. Another order's key opens nothing. */
1325
+ keyOpens(orderId: string, key: string): Promise<boolean>;
1155
1326
  updateStatus(id: string, toStatus: OrderStatus, actor: string, note?: string): Promise<Order>;
1156
1327
  markShipped(id: string, trackingNumber: string, carrier: string, actor: string): Promise<Order>;
1157
1328
  markDelivered(id: string, actor: string): Promise<Order>;
1158
1329
  /** Refuses with `order.paid` once anything is captured: a paid order is refunded, never cancelled. */
1159
1330
  cancel(id: string, reason: string, actor: string): Promise<Order>;
1331
+ /**
1332
+ * Asks for the order's confirmation email again; the email handler sends it. Refuses with `order.unpaid` for an
1333
+ * order no confirmation is due for (pending, or cancelled and so never paid). Changes nothing on the order.
1334
+ */
1335
+ resendConfirmation(id: string): Promise<Order>;
1160
1336
  }
1161
1337
  interface CreateOrderServiceDeps {
1162
1338
  store: CommandStore;
@@ -1213,6 +1389,8 @@ interface BeginCheckoutResult {
1213
1389
  /** The order's status as the checkout answers. */
1214
1390
  orderStatus: OrderStatus;
1215
1391
  payment: CheckoutPayment;
1392
+ /** A fresh key that reads the order with no session (`ORDER_KEY_HEADER`). Only its hash is stored. */
1393
+ orderKey: string;
1216
1394
  }
1217
1395
  /** What the payment provider captured. */
1218
1396
  interface CapturedPayment {
@@ -1315,6 +1493,27 @@ declare function refreshRefunded(repos: Repositories, tx: Tx, orderId: string, a
1315
1493
  }>;
1316
1494
  declare function createRefundService(deps: CreateRefundServiceDeps): RefundService;
1317
1495
 
1496
+ interface RecentlyViewedServiceDeps {
1497
+ store: CommandStore;
1498
+ repos: Pick<Repositories, 'product'>;
1499
+ publisher: EventPublisher;
1500
+ logger: Logger;
1501
+ /** The view's time, which its event carries. */
1502
+ now?: () => Date;
1503
+ }
1504
+ interface RecentlyViewedService {
1505
+ /** Logs a view of an active product; false, and nothing logged, for any other id. */
1506
+ record(viewer: RecentViewer, productId: string): Promise<boolean>;
1507
+ /** Moves a visitor's views to the customer who signed in carrying its cookie. */
1508
+ fold(visitorId: string, customerId: string): Promise<void>;
1509
+ }
1510
+ declare function createRecentlyViewedService(deps: RecentlyViewedServiceDeps): RecentlyViewedService;
1511
+
1512
+ /** A confirm or unsubscribe link's bearer credential: 32 random bytes, base64url (43 characters). */
1513
+ declare function newAlertToken(): string;
1514
+
1515
+ /** A `native` email adapter only logs; any other (`smtp`, a project's own) is taken to reach a mailbox. */
1516
+ declare function emailDelivers(email: EmailAdapter): boolean;
1318
1517
  interface ServiceRegistry {
1319
1518
  product: ProductService;
1320
1519
  category: CategoryService;
@@ -1326,6 +1525,8 @@ interface ServiceRegistry {
1326
1525
  checkout: CheckoutService & ManualPayments;
1327
1526
  refund: RefundService;
1328
1527
  search: SearchService;
1528
+ recentlyViewed: RecentlyViewedService;
1529
+ alert: AlertService;
1329
1530
  }
1330
1531
  interface BuildServicesDeps {
1331
1532
  config: NymbalConfig;
@@ -1335,6 +1536,7 @@ interface BuildServicesDeps {
1335
1536
  logger: Logger;
1336
1537
  payments: PaymentsAdapter;
1337
1538
  searchAdapter: SearchAdapter;
1539
+ email: EmailAdapter;
1338
1540
  }
1339
1541
  declare function buildServices(deps: BuildServicesDeps): ServiceRegistry;
1340
1542
 
@@ -1363,6 +1565,11 @@ interface RegisterAllRoutesDeps {
1363
1565
  }
1364
1566
  declare function registerAllRoutes(deps: RegisterAllRoutesDeps): void;
1365
1567
 
1568
+ interface RegisterAlertRoutesDeps {
1569
+ alerts: AlertService;
1570
+ }
1571
+ declare function registerAlertRoutes(adapter: HttpAdapter, deps: RegisterAlertRoutesDeps): void;
1572
+
1366
1573
  /**
1367
1574
  * The input of one route: what `registerAllRoutes` parses before the handler runs, and what a tool definition is
1368
1575
  * generated from. Unknown keys are stripped, so a handler sees only what is declared here.
@@ -1417,6 +1624,8 @@ interface CreateAppOptions extends ResolvePrimitivesOptions {
1417
1624
  version?: string;
1418
1625
  /** The project's own adapters, one per slot whose provider is `custom`. */
1419
1626
  adapters?: InjectedAdapters;
1627
+ /** How the event relay retries a failed delivery (`createRelay`). */
1628
+ relay?: Pick<CreateRelayOptions, 'maxAttempts' | 'retryDelayMs' | 'intervalMs' | 'now'>;
1420
1629
  }
1421
1630
  declare function createApp(config: NymbalConfig, options?: CreateAppOptions): Promise<NymbalApp>;
1422
1631
 
@@ -1578,8 +1787,6 @@ declare function createNativeShippingAdapter(logger: Logger): ShippingAdapter;
1578
1787
 
1579
1788
  declare function createNativeTaxAdapter(logger: Logger, defaultRate?: number): TaxAdapter;
1580
1789
 
1581
- declare function createNativeAiAdapter(_logger: Logger): AiAdapter;
1582
-
1583
1790
  interface CreateLoggerOptions {
1584
1791
  level?: string;
1585
1792
  pretty?: boolean;
@@ -1702,7 +1909,7 @@ interface DocumentWrite {
1702
1909
  doc: unknown;
1703
1910
  }
1704
1911
 
1705
- type ReadModelName = 'catalogue' | 'orders' | 'customers' | 'search';
1912
+ type ReadModelName = 'catalogue' | 'orders' | 'customers' | 'search' | 'recently-viewed';
1706
1913
  interface RebuildDeps {
1707
1914
  config: NymbalConfig;
1708
1915
  store: CommandStore;
@@ -1727,6 +1934,13 @@ interface RebuildContext {
1727
1934
  pages<T extends {
1728
1935
  id: string;
1729
1936
  }>(table: string, read: (tx: ReadTx, page: KeysetPage) => Promise<T[]>): AsyncIterable<T[]>;
1937
+ /**
1938
+ * The logged events of `types`, in seq pages, each page a read of its own (`onPage` names the table `events`). A model
1939
+ * that reads them is caught up only with events above the last one it read: re-applying one it already folded
1940
+ * would fold it twice. The bound is per model, not per collection: a model that reads both `pages()` and `events()`
1941
+ * would skip catch-up for the collections it builds from tables.
1942
+ */
1943
+ events(types: readonly string[]): AsyncIterable<LoggedEvent[]>;
1730
1944
  }
1731
1945
  interface ReadModel {
1732
1946
  name: ReadModelName;
@@ -1839,5 +2053,5 @@ interface LocalFsMediaStorageOptions {
1839
2053
  declare const LOCAL_FS_MEDIA_CAPABILITIES: readonly string[];
1840
2054
  declare function createLocalFsMediaStorage(options: LocalFsMediaStorageOptions): MediaStorage;
1841
2055
 
1842
- export { CATCH_UP_MARGIN_MS, CSRF_COOKIE, CSRF_HEADER, InMemoryDocumentStore, InProcessEventBus, LOCAL_FS_MEDIA_CAPABILITIES, PROVIDER_PACKAGES, PROVIDER_REFUND_REASON, READ_MODELS, READ_MODEL_NAMES, REDIS_DEFAULTS, RateLimiter, RebuildError, SECRETS_KEY_ENV, SECRETS_KEY_OLD_ENV, actorOf, appendAuditEntry, audit, auditEntriesInOrder, auditedCommand, buildAdapters, buildRepositories, buildServices, createApp, createAuditEntryRepository, createAuthService, createCartRepository, createCartService, createCategoryRepository, createCategoryService, createCheckoutService, createCommandStore, createCustomerRepository, createCustomerService, createEventBuilder, createEventLogRepository, createEventPublisher, createInventoryReservationRepository, createInventoryService, createCategoryRepository$1 as createLegacyCategoryRepository, createProductRepository$1 as createLegacyProductRepository, createLocalFsMediaStorage, createLogger, createMiddlewareSecurityAdapter, createNativeAiAdapter, createNativeAnalyticsAdapter, createNativeEmailAdapter, createNativeReviewsAdapter, createNativeSearchAdapter, createNativeShippingAdapter, createNativeStubPaymentsAdapter, createNativeTaxAdapter, createOrderHistoryRepository, createOrderRefundRepository, createOrderRepository, createOrderSequenceRepository, createOrderService, createPlatform, createProcessedEventRepository, createProductCategoryRepository, createProductRepository, createProductService, createRefreshTokenRepository, createRefundService, createRelay, createReviewRepository, createSearchService, createSettingsRepository, createStockAdjustmentRepository, createVariantRepository, currentActor, currentCorrelationId, decrypt, diagnose, diffReadModel, encodeSearchCursor, encrypt, fillFromSettings, findAppliedByKey, importProviderPackage, installLine, isMissingSettingsTable, keyId, keyProblem, listAuditEntries, newCorrelationId, openReadModels, orderPayment, rawClients, readSecretsKey, rebuild, refreshRefunded, registerAdminStaticRoute, registerAllRoutes, registerHandlers, resolvePrimitives, routeSchemas, runAsActor, runMigrations, runSeed, runWithCorrelation, scrub, seedCategories, seedProducts, settingAad, settlementOf, sqliteFile, startCartAbandonmentSweeper, startEventRetentionSweeper, startInventoryReservationSweeper, withIdempotency };
1843
- export type { AbandonedCart, AbandonedWindow, Actor, AdapterRegistry, AppliedEntry, AttachHttpOptions, AuditCursor, AuditEntryInsert, AuditEntryRepository, AuditFilter, AuditQuery, AuthService, AuthTokens, BeginCheckoutInput, BeginCheckoutResult, BuildAdaptersDeps, BuildServicesDeps, CapabilitiesReport, CapabilitySlot, CapturedPayment, CartRepository, CartService, CatchUpFailure, CategoryCreateInput, CategoryInsert, CategoryRepository, CategoryService, CategoryUpdate, CategoryUpdateInput, CheckoutService, CollectionDiff, CommandStore, CommandStoreOptions, CommerceAdapters, CreateAppOptions, CreateAuthServiceDeps, CreateCartServiceDeps, CreateCheckoutServiceDeps, CreateInventoryServiceDeps, CreateLoggerOptions, CreateOrderServiceDeps, CreatePlatformOptions, CreateProductServiceDeps, CreatePublisherOptions, CreateRefundServiceDeps, CreateRelayOptions, CustomerInsert, CustomerJwtPayload, CustomerRepository, CustomerService, CustomerUpdate, CustomerWithHash, DiagnoseOptions, DiagnosisCheck, DiagnosisReport, DiagnosisStatus, EncryptedValue, EventArchiveWriter, EventBuilderContext, EventLogFilter, EventLogRepository, EventPublisher, EventRetentionSweeperDeps, FinalizeResult, IdempotencyOptions, ImportCustomerInput, InMemoryDocumentStoreOptions, InProcessEventBusOptions, InjectedAdapters, InventoryReservationRepository, InventoryService, KeysetPage, CategoryInsert$1 as LegacyCategoryInsert, CategoryRow as LegacyCategoryRow, ProductInsert$1 as LegacyProductInsert, ProductRow as LegacyProductRow, LocalFsMediaStorageOptions, LoggedEvent, MakeEventOptions, ManualPayments, MigrateOptions, NativeEmailAdapterConfig, NymbalApp, OpenReadModelsOptions, OrderCapture, OrderCreateDraftInput, OrderHistoryInsert, OrderHistoryRepository, OrderImportInput, OrderInsert, OrderRefundInsert, OrderRefundRepository, OrderRepository, OrderSequenceRepository, OrderService, Platform, PlatformConnectionOptions, PostgresClient, Primitives, ProcessedEventRepository, ProductCategoryRepository, ProductCreateInput, ProductInsert, ProductRepository, ProductService, ProductUpdate, ProductUpdateInput, ProfileUpdate, ProviderPackage, PublishOptions, RawClients, ReadModel, ReadModelDiff, ReadModelName, ReadTx, RebuildDeps, RebuildReport, RebuildReportEntry, RefreshTokenInsert, RefreshTokenRepository, RefreshTokenRow, RefundInput, RefundResult, RefundService, RegisterAllRoutesDeps, RegisterHandlersDeps, RegisterInput, Relay, Repositories, ReservationInsert, ReserveStockResult, ResolvePrimitivesOptions, ReviewInsert, ReviewKey, ReviewRepository, RouteSchema, SearchService, SecretsKey, SeedCategory, SeedDeps, SeedProduct, SeedResult, ServiceRegistry, SettingRow, SettingSource, SettingValue, SettingsRepository, Settlement, SlotCapabilities, SqliteClient, StockAdjustmentInsert, StockAdjustmentRepository, StoreRepository, StoredCipher, SweeperHandle, Tx, VariantInsert, VariantRepository, VariantUpdate };
2056
+ export { CATCH_UP_MARGIN_MS, CSRF_COOKIE, CSRF_HEADER, InMemoryDocumentStore, InProcessEventBus, LOCAL_FS_MEDIA_CAPABILITIES, PROVIDER_PACKAGES, PROVIDER_REFUND_REASON, READ_MODELS, READ_MODEL_NAMES, REDIS_DEFAULTS, RateLimiter, RebuildError, SECRETS_KEY_ENV, SECRETS_KEY_OLD_ENV, actorOf, appendAuditEntry, audit, auditEntriesInOrder, auditedCommand, buildAdapters, buildRepositories, buildServices, createAlertService, createAlertSubscriptionRepository, createApp, createAuditEntryRepository, createAuthService, createCartRepository, createCartService, createCategoryRepository, createCategoryService, createCheckoutService, createCommandStore, createCustomerRepository, createCustomerService, createEventBuilder, createEventLogRepository, createEventPublisher, createInventoryReservationRepository, createInventoryService, createCategoryRepository$1 as createLegacyCategoryRepository, createProductRepository$1 as createLegacyProductRepository, createLocalFsMediaStorage, createLogger, createMiddlewareSecurityAdapter, createNativeAnalyticsAdapter, createNativeEmailAdapter, createNativeReviewsAdapter, createNativeSearchAdapter, createNativeShippingAdapter, createNativeStubPaymentsAdapter, createNativeTaxAdapter, createOrderAccessKeyRepository, createOrderHistoryRepository, createOrderRefundRepository, createOrderRepository, createOrderSequenceRepository, createOrderService, createPlatform, createProcessedEventRepository, createProductCategoryRepository, createProductRepository, createProductService, createRecentlyViewedService, createRefreshTokenRepository, createRefundService, createRelay, createReviewRepository, createSearchService, createSettingsRepository, createStockAdjustmentRepository, createVariantRepository, currentActor, currentCorrelationId, decrypt, diagnose, diffReadModel, emailDelivers, encodeSearchCursor, encrypt, fillFromSettings, findAppliedByKey, importProviderPackage, installLine, isMissingSettingsTable, keyId, keyProblem, listAuditEntries, newAlertToken, newCorrelationId, openReadModels, orderPayment, parseDurationToMs, rawClients, readSecretsKey, rebuild, refreshRefunded, registerAdminStaticRoute, registerAlertHandler, registerAlertRoutes, registerAllRoutes, registerHandlers, resolvePrimitives, routeSchemas, runAsActor, runMigrations, runSeed, runWithCorrelation, scrub, seedCategories, seedProducts, settingAad, settlementOf, sqliteFile, startCartAbandonmentSweeper, startEventRetentionSweeper, startInventoryReservationSweeper, withIdempotency };
2057
+ export type { AbandonedCart, AbandonedWindow, Actor, AdapterRegistry, AlertConfirmed, AlertService, AlertSubscribeInput, AlertSubscription, AlertSubscriptionPatch, AlertSubscriptionRepository, AlertSubscriptionRequest, AppliedEntry, AttachHttpOptions, AuditCursor, AuditEntryInsert, AuditEntryRepository, AuditFilter, AuditQuery, AuthService, AuthTokens, BeginCheckoutInput, BeginCheckoutResult, BuildAdaptersDeps, BuildServicesDeps, CapabilitiesReport, CapabilitySlot, CapturedPayment, CartRepository, CartService, CatchUpFailure, CategoryCreateInput, CategoryInsert, CategoryRepository, CategoryService, CategoryUpdate, CategoryUpdateInput, CheckoutService, CollectionDiff, CommandStore, CommandStoreOptions, CommerceAdapters, CreateAlertServiceDeps, CreateAppOptions, CreateAuthServiceDeps, CreateCartServiceDeps, CreateCheckoutServiceDeps, CreateInventoryServiceDeps, CreateLoggerOptions, CreateOrderServiceDeps, CreatePlatformOptions, CreateProductServiceDeps, CreatePublisherOptions, CreateRefundServiceDeps, CreateRelayOptions, CustomerInsert, CustomerJwtPayload, CustomerRepository, CustomerService, CustomerUpdate, CustomerWithHash, DiagnoseOptions, DiagnosisCheck, DiagnosisReport, DiagnosisStatus, EncryptedValue, EventArchiveWriter, EventBuilderContext, EventLogFilter, EventLogRepository, EventPublisher, EventRetentionSweeperDeps, FinalizeResult, IdempotencyOptions, ImportCustomerInput, InMemoryDocumentStoreOptions, InProcessEventBusOptions, InjectedAdapters, InventoryReservationRepository, InventoryService, KeysetPage, CategoryInsert$1 as LegacyCategoryInsert, CategoryRow as LegacyCategoryRow, ProductInsert$1 as LegacyProductInsert, ProductRow as LegacyProductRow, LocalFsMediaStorageOptions, LoggedEvent, MakeEventOptions, ManualPayments, MigrateOptions, NativeEmailAdapterConfig, NymbalApp, OpenReadModelsOptions, OrderAccessKeyInsert, OrderAccessKeyPurpose, OrderAccessKeyRepository, OrderCapture, OrderCreateDraftInput, OrderHistoryInsert, OrderHistoryRepository, OrderImportInput, OrderInsert, OrderRefundInsert, OrderRefundRepository, OrderRepository, OrderSequenceRepository, OrderService, Platform, PlatformConnectionOptions, PostgresClient, Primitives, ProcessedEventRepository, ProductCategoryRepository, ProductCreateInput, ProductInsert, ProductRepository, ProductService, ProductUpdate, ProductUpdateInput, ProfileUpdate, ProviderPackage, PublishOptions, RawClients, ReadModel, ReadModelDiff, ReadModelName, ReadTx, RebuildDeps, RebuildReport, RebuildReportEntry, RecentlyViewedService, RecentlyViewedServiceDeps, RefreshTokenInsert, RefreshTokenRepository, RefreshTokenRow, RefundInput, RefundResult, RefundService, RegisterAlertHandlerDeps, RegisterAlertRoutesDeps, RegisterAllRoutesDeps, RegisterHandlersDeps, RegisterInput, Relay, Repositories, ReservationInsert, ReserveStockResult, ResolvePrimitivesOptions, ReviewInsert, ReviewKey, ReviewRepository, RouteSchema, SearchService, SecretsKey, SeedCategory, SeedDeps, SeedProduct, SeedResult, ServiceRegistry, SettingRow, SettingSource, SettingValue, SettingsRepository, Settlement, SlotCapabilities, SqliteClient, StockAdjustmentInsert, StockAdjustmentRepository, StoreRepository, StoredCipher, SweeperHandle, Tx, VariantInsert, VariantPriceInput, VariantRepository, VariantUpdate };