@nymbalhq/platform 1.4.0 → 1.5.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-SNNK2OX3.js → chunk-NNDIAIT6.js} +73 -5
  2. package/dist/chunk-NNDIAIT6.js.map +1 -0
  3. package/dist/{chunk-GMV3B3SC.js → chunk-TRLERRUI.js} +424 -137
  4. package/dist/chunk-TRLERRUI.js.map +1 -0
  5. package/dist/db/schema/index.d.ts +795 -105
  6. package/dist/db/schema/index.js +1 -1
  7. package/dist/index.d.ts +218 -85
  8. package/dist/index.js +658 -199
  9. package/dist/index.js.map +1 -1
  10. package/dist/register-SBGUI2L5.js +8 -0
  11. package/migrations/postgres/0016_email_suppressions.sql +7 -0
  12. package/migrations/postgres/0017_order_shipments.sql +14 -0
  13. package/migrations/postgres/0018_order_key_expiry.sql +8 -0
  14. package/migrations/postgres/meta/0016_snapshot.json +2233 -0
  15. package/migrations/postgres/meta/0017_snapshot.json +2300 -0
  16. package/migrations/postgres/meta/0018_snapshot.json +2306 -0
  17. package/migrations/postgres/meta/_journal.json +21 -0
  18. package/migrations/sqlite/0016_email_suppressions.sql +7 -0
  19. package/migrations/sqlite/0017_order_shipments.sql +9 -0
  20. package/migrations/sqlite/0018_order_key_expiry.sql +25 -0
  21. package/migrations/sqlite/meta/0016_snapshot.json +1981 -0
  22. package/migrations/sqlite/meta/0017_snapshot.json +2041 -0
  23. package/migrations/sqlite/meta/0018_snapshot.json +2048 -0
  24. package/migrations/sqlite/meta/_journal.json +21 -0
  25. package/package.json +17 -47
  26. package/dist/chunk-GMV3B3SC.js.map +0 -1
  27. package/dist/chunk-SNNK2OX3.js.map +0 -1
  28. package/dist/register-N2XGSFUF.js +0 -8
  29. /package/dist/{register-N2XGSFUF.js.map → register-SBGUI2L5.js.map} +0 -0
package/dist/index.js CHANGED
@@ -9,11 +9,11 @@ import {
9
9
  ORDERS_BY_CUSTOMER,
10
10
  PRODUCTS,
11
11
  PRODUCTS_BY_CATEGORY,
12
- PROVIDER_PACKAGES,
13
12
  PROVIDER_REFUND_REASON,
14
13
  SECRETS_KEY_ENV,
15
14
  SECRETS_KEY_OLD_ENV,
16
15
  actorOf,
16
+ addSecret,
17
17
  afterCommit,
18
18
  appendAuditEntry,
19
19
  audit,
@@ -27,6 +27,7 @@ import {
27
27
  buildSearchDoc,
28
28
  buildSecurityHeaders,
29
29
  buildServices,
30
+ checkAdapterModule,
30
31
  checkInjectedAdapters,
31
32
  checkInjectedSlot,
32
33
  createAlertService,
@@ -62,9 +63,11 @@ import {
62
63
  fillFromSettings,
63
64
  findAppliedByKey,
64
65
  formatMoney,
65
- importProviderPackage,
66
+ importAdapterModule,
66
67
  installLine,
68
+ isHooked,
67
69
  isMissingSettingsTable,
70
+ isNotConfigured,
68
71
  isValidCorrelationId,
69
72
  keyId,
70
73
  keyProblem,
@@ -73,9 +76,11 @@ import {
73
76
  loadBootSettings,
74
77
  loadProviderAdapter,
75
78
  mintOrderKey,
79
+ missingPackage,
76
80
  nativeIndexDocuments,
77
81
  newAlertToken,
78
82
  newCorrelationId,
83
+ normaliseEmail,
79
84
  orderPayment,
80
85
  orderWrites,
81
86
  outsideActor,
@@ -93,6 +98,7 @@ import {
93
98
  registerAlertRoutes,
94
99
  registerAllRoutes,
95
100
  registerRecentlyViewedProjection,
101
+ resolveChoice,
96
102
  resolvePaymentsAdapter,
97
103
  resolveSecurityAdapter,
98
104
  routeSchemas,
@@ -100,6 +106,7 @@ import {
100
106
  runWithCorrelation,
101
107
  scrub,
102
108
  scrubbingLogger,
109
+ securityChoice,
103
110
  settingAad,
104
111
  settingValues,
105
112
  settlementOf,
@@ -107,7 +114,7 @@ import {
107
114
  sqliteDb,
108
115
  sqliteFile,
109
116
  subscribeDerived
110
- } from "./chunk-GMV3B3SC.js";
117
+ } from "./chunk-TRLERRUI.js";
111
118
  import {
112
119
  alertSubscriptions,
113
120
  alertSubscriptions2,
@@ -117,6 +124,8 @@ import {
117
124
  categories2,
118
125
  customers,
119
126
  customers2,
127
+ emailSuppressions,
128
+ emailSuppressions2,
120
129
  events,
121
130
  events2,
122
131
  inventoryReservations,
@@ -129,6 +138,8 @@ import {
129
138
  orderRefunds2,
130
139
  orderSequences,
131
140
  orderSequences2,
141
+ orderShipments,
142
+ orderShipments2,
132
143
  orders,
133
144
  orders2,
134
145
  postgres_exports,
@@ -147,7 +158,7 @@ import {
147
158
  stockAdjustments2,
148
159
  variants,
149
160
  variants2
150
- } from "./chunk-SNNK2OX3.js";
161
+ } from "./chunk-NNDIAIT6.js";
151
162
 
152
163
  // src/platform.ts
153
164
  import { join as join2 } from "path";
@@ -498,22 +509,22 @@ function s3Connection(config, env) {
498
509
  ...publicUrl !== void 0 && { publicUrl }
499
510
  };
500
511
  }
501
- async function loadPrimitive(slot, provider, config, logger, env) {
502
- const instance = await loadProviderAdapter(slot, provider, {
512
+ async function loadPrimitive(slot, choice, config, logger, env) {
513
+ const instance = await loadProviderAdapter(slot, choice, {
503
514
  config,
504
515
  logger: logger.child({ primitive: slot }),
505
516
  env
506
517
  });
507
518
  if (instance === void 0) {
508
- throw new ConfigError(`infrastructure.${slot} '${provider}' has no implementation`, {
509
- context: { slot, provider }
519
+ throw new ConfigError(`infrastructure.${slot} '${choice.provider}' has no implementation`, {
520
+ context: { slot, provider: choice.provider }
510
521
  });
511
522
  }
512
523
  return instance;
513
524
  }
514
525
  async function buildDocumentStore(config, options, logger, env) {
515
526
  const choice = config.infrastructure.documentStore;
516
- switch (choice) {
527
+ switch (choice.provider) {
517
528
  case "in-memory":
518
529
  return new InMemoryDocumentStore();
519
530
  case "redis": {
@@ -536,15 +547,13 @@ async function buildDocumentStore(config, options, logger, env) {
536
547
  env
537
548
  );
538
549
  }
539
- default: {
540
- const exhaustive = choice;
541
- throw new ConfigError(`Unknown documentStore: ${String(exhaustive)}`);
542
- }
550
+ default:
551
+ return loadPrimitive("documentStore", choice, choice.config ?? {}, logger, env);
543
552
  }
544
553
  }
545
554
  async function buildEventBus(config, logger, env) {
546
555
  const choice = config.infrastructure.eventBus;
547
- switch (choice) {
556
+ switch (choice.provider) {
548
557
  case "in-process":
549
558
  return new InProcessEventBus({ logger });
550
559
  case "redis-streams":
@@ -555,15 +564,13 @@ async function buildEventBus(config, logger, env) {
555
564
  logger,
556
565
  env
557
566
  );
558
- default: {
559
- const exhaustive = choice;
560
- throw new ConfigError(`Unknown eventBus: ${String(exhaustive)}`);
561
- }
567
+ default:
568
+ return loadPrimitive("eventBus", choice, choice.config ?? {}, logger, env);
562
569
  }
563
570
  }
564
571
  async function buildMedia(config, options, logger, env) {
565
572
  const choice = config.infrastructure.media;
566
- switch (choice) {
573
+ switch (choice.provider) {
567
574
  case "local-fs":
568
575
  return createLocalFsMediaStorage({
569
576
  root: options.mediaRoot ?? join2(process.cwd(), "public", "imported-media"),
@@ -571,22 +578,21 @@ async function buildMedia(config, options, logger, env) {
571
578
  });
572
579
  case "s3":
573
580
  return loadPrimitive("media", choice, s3Connection(config, env), logger, env);
574
- default: {
575
- const exhaustive = choice;
576
- throw new ConfigError(`Unknown media: ${String(exhaustive)}`);
577
- }
581
+ default:
582
+ return loadPrimitive("media", choice, choice.config ?? {}, logger, env);
578
583
  }
579
584
  }
580
585
  async function resolvePrimitives(config, options = {}) {
581
586
  const env = options.env ?? process.env;
582
587
  const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
583
- if (config.infrastructure.media === "s3") s3Connection(config, env);
584
- if (config.infrastructure.documentStore === "redis") redisConnection(config, env, "documentStore");
585
- if (config.infrastructure.eventBus === "redis-streams") redisConnection(config, env, "eventBus");
588
+ const { documentStore: store, eventBus: bus, media: storage } = config.infrastructure;
589
+ if (storage.provider === "s3") s3Connection(config, env);
590
+ if (store.provider === "redis") redisConnection(config, env, "documentStore");
591
+ if (bus.provider === "redis-streams") redisConnection(config, env, "eventBus");
586
592
  const media = await buildMedia(config, options, logger, env);
587
593
  const documentStore = await buildDocumentStore(config, options, logger, env);
588
594
  try {
589
- if (config.infrastructure.documentStore === "postgres-jsonb") await documentStore.initialize?.();
595
+ if (store.provider === "postgres-jsonb") await documentStore.initialize?.();
590
596
  const eventBus = await buildEventBus(config, logger, env);
591
597
  return { documentStore, eventBus, media };
592
598
  } catch (error) {
@@ -1837,65 +1843,85 @@ function createOrderRefundRepository(store) {
1837
1843
  }
1838
1844
 
1839
1845
  // src/repositories/order-sequence.ts
1840
- import { eq as eq11, sql as sql3 } from "drizzle-orm";
1846
+ import { sql as sql3 } from "drizzle-orm";
1841
1847
  function createOrderSequenceRepository(store) {
1842
1848
  return {
1843
1849
  store,
1850
+ // One upsert: on a fresh store a read finds no row to lock, so concurrent first allocations would each insert it.
1851
+ // The value handed out is the one the row held before this call (startFrom on the first).
1844
1852
  async nextSequence(tx, startFrom = 1e3) {
1845
1853
  if (tx.kind === "sqlite") {
1846
- const client2 = sqliteDb(tx);
1847
- const row2 = client2.select().from(orderSequences).where(eq11(orderSequences.id, 1)).get();
1848
- if (!row2) {
1849
- const next = startFrom + 1;
1850
- client2.insert(orderSequences).values({ id: 1, nextValue: next }).run();
1851
- return startFrom;
1852
- }
1853
- const current2 = row2.nextValue;
1854
- client2.update(orderSequences).set({ nextValue: current2 + 1 }).where(eq11(orderSequences.id, 1)).run();
1855
- return current2;
1856
- }
1857
- const client = postgresDb(tx);
1858
- const [row] = await client.select().from(orderSequences2).where(eq11(orderSequences2.id, 1)).for("update");
1859
- if (!row) {
1860
- const next = startFrom + 1;
1861
- await client.insert(orderSequences2).values({ id: 1, nextValue: next });
1862
- return startFrom;
1863
- }
1864
- const current = row.nextValue;
1865
- await client.update(orderSequences2).set({ nextValue: sql3`${orderSequences2.nextValue} + 1` }).where(eq11(orderSequences2.id, 1));
1866
- return current;
1854
+ const row2 = sqliteDb(tx).insert(orderSequences).values({ id: 1, nextValue: startFrom + 1 }).onConflictDoUpdate({
1855
+ target: orderSequences.id,
1856
+ set: { nextValue: sql3`${orderSequences.nextValue} + 1` }
1857
+ }).returning({ nextValue: orderSequences.nextValue }).get();
1858
+ return row2.nextValue - 1;
1859
+ }
1860
+ const [row] = await postgresDb(tx).insert(orderSequences2).values({ id: 1, nextValue: startFrom + 1 }).onConflictDoUpdate({
1861
+ target: orderSequences2.id,
1862
+ set: { nextValue: sql3`${orderSequences2.nextValue} + 1` }
1863
+ }).returning({ nextValue: orderSequences2.nextValue });
1864
+ return row.nextValue - 1;
1867
1865
  }
1868
1866
  };
1869
1867
  }
1870
1868
 
1871
1869
  // src/repositories/order-access-key.ts
1872
- import { and as and6, eq as eq12 } from "drizzle-orm";
1870
+ import { and as and6, asc as asc8, eq as eq11, inArray as inArray2 } from "drizzle-orm";
1873
1871
  function createOrderAccessKeyRepository(store) {
1874
1872
  return {
1875
1873
  store,
1876
1874
  async insert(tx, k) {
1877
1875
  const row = { id: k.id, orderId: k.orderId, keyHash: k.keyHash, purpose: k.purpose };
1878
1876
  if (tx.kind === "sqlite") {
1879
- sqliteDb(tx).insert(orderAccessKeys).values({ ...row, createdAt: k.createdAt.toISOString() }).run();
1877
+ sqliteDb(tx).insert(orderAccessKeys).values({
1878
+ ...row,
1879
+ createdAt: k.createdAt.toISOString(),
1880
+ expiresAt: k.expiresAt.toISOString()
1881
+ }).run();
1880
1882
  return;
1881
1883
  }
1882
- await postgresDb(tx).insert(orderAccessKeys2).values({ ...row, createdAt: k.createdAt });
1884
+ await postgresDb(tx).insert(orderAccessKeys2).values({ ...row, createdAt: k.createdAt, expiresAt: k.expiresAt });
1885
+ },
1886
+ async opens(tx, orderId, keyHash, now) {
1887
+ let expiresAt;
1888
+ if (tx.kind === "sqlite") {
1889
+ const t = orderAccessKeys;
1890
+ const row = sqliteDb(tx).select({ expiresAt: t.expiresAt }).from(t).where(and6(eq11(t.orderId, orderId), eq11(t.keyHash, keyHash))).get();
1891
+ if (row !== void 0) expiresAt = Date.parse(row.expiresAt);
1892
+ } else {
1893
+ const t = orderAccessKeys2;
1894
+ const rows = await postgresDb(tx).select({ expiresAt: t.expiresAt }).from(t).where(and6(eq11(t.orderId, orderId), eq11(t.keyHash, keyHash))).limit(1);
1895
+ if (rows[0] !== void 0) expiresAt = rows[0].expiresAt.getTime();
1896
+ }
1897
+ if (expiresAt === void 0) return "none";
1898
+ return now.getTime() < expiresAt ? "open" : "expired";
1883
1899
  },
1884
- async opens(tx, orderId, keyHash) {
1900
+ async keepNewest(tx, orderId, purpose, keep) {
1901
+ let ids;
1885
1902
  if (tx.kind === "sqlite") {
1886
1903
  const t2 = orderAccessKeys;
1887
- const row = sqliteDb(tx).select({ id: t2.id }).from(t2).where(and6(eq12(t2.orderId, orderId), eq12(t2.keyHash, keyHash))).get();
1888
- return row !== void 0;
1904
+ ids = sqliteDb(tx).select({ id: t2.id }).from(t2).where(and6(eq11(t2.orderId, orderId), eq11(t2.purpose, purpose))).orderBy(asc8(t2.createdAt), asc8(t2.id)).all().map((r) => r.id);
1905
+ } else {
1906
+ const t2 = orderAccessKeys2;
1907
+ const rows = await postgresDb(tx).select({ id: t2.id }).from(t2).where(and6(eq11(t2.orderId, orderId), eq11(t2.purpose, purpose))).orderBy(asc8(t2.createdAt), asc8(t2.id));
1908
+ ids = rows.map((r) => r.id);
1909
+ }
1910
+ const stale = ids.slice(0, Math.max(0, ids.length - keep));
1911
+ if (stale.length === 0) return;
1912
+ if (tx.kind === "sqlite") {
1913
+ const t2 = orderAccessKeys;
1914
+ sqliteDb(tx).delete(t2).where(inArray2(t2.id, stale)).run();
1915
+ return;
1889
1916
  }
1890
1917
  const t = orderAccessKeys2;
1891
- const rows = await postgresDb(tx).select({ id: t.id }).from(t).where(and6(eq12(t.orderId, orderId), eq12(t.keyHash, keyHash))).limit(1);
1892
- return rows.length > 0;
1918
+ await postgresDb(tx).delete(t).where(inArray2(t.id, stale));
1893
1919
  }
1894
1920
  };
1895
1921
  }
1896
1922
 
1897
1923
  // src/repositories/inventory-reservation.ts
1898
- import { eq as eq13, lt as lt2 } from "drizzle-orm";
1924
+ import { eq as eq12, lt as lt2 } from "drizzle-orm";
1899
1925
  function rowToReservation(row) {
1900
1926
  return {
1901
1927
  reservationId: String(row.reservationId),
@@ -1932,26 +1958,26 @@ function createInventoryReservationRepository(store) {
1932
1958
  },
1933
1959
  async findById(tx, reservationId) {
1934
1960
  if (tx.kind === "sqlite") {
1935
- const row2 = sqliteDb(tx).select().from(inventoryReservations).where(eq13(inventoryReservations.reservationId, reservationId)).get();
1961
+ const row2 = sqliteDb(tx).select().from(inventoryReservations).where(eq12(inventoryReservations.reservationId, reservationId)).get();
1936
1962
  return row2 ? rowToReservation(row2) : null;
1937
1963
  }
1938
- const [row] = await postgresDb(tx).select().from(inventoryReservations2).where(eq13(inventoryReservations2.reservationId, reservationId));
1964
+ const [row] = await postgresDb(tx).select().from(inventoryReservations2).where(eq12(inventoryReservations2.reservationId, reservationId));
1939
1965
  return row ? rowToReservation(row) : null;
1940
1966
  },
1941
1967
  async findByVariant(tx, variantId) {
1942
1968
  if (tx.kind === "sqlite") {
1943
- const rows2 = sqliteDb(tx).select().from(inventoryReservations).where(eq13(inventoryReservations.variantId, variantId)).all();
1969
+ const rows2 = sqliteDb(tx).select().from(inventoryReservations).where(eq12(inventoryReservations.variantId, variantId)).all();
1944
1970
  return rows2.map((r) => rowToReservation(r));
1945
1971
  }
1946
- const rows = await postgresDb(tx).select().from(inventoryReservations2).where(eq13(inventoryReservations2.variantId, variantId));
1972
+ const rows = await postgresDb(tx).select().from(inventoryReservations2).where(eq12(inventoryReservations2.variantId, variantId));
1947
1973
  return rows.map((r) => rowToReservation(r));
1948
1974
  },
1949
1975
  async deleteById(tx, reservationId) {
1950
1976
  if (tx.kind === "sqlite") {
1951
- const row2 = sqliteDb(tx).delete(inventoryReservations).where(eq13(inventoryReservations.reservationId, reservationId)).returning().get();
1977
+ const row2 = sqliteDb(tx).delete(inventoryReservations).where(eq12(inventoryReservations.reservationId, reservationId)).returning().get();
1952
1978
  return row2 ? rowToReservation(row2) : null;
1953
1979
  }
1954
- const [row] = await postgresDb(tx).delete(inventoryReservations2).where(eq13(inventoryReservations2.reservationId, reservationId)).returning();
1980
+ const [row] = await postgresDb(tx).delete(inventoryReservations2).where(eq12(inventoryReservations2.reservationId, reservationId)).returning();
1955
1981
  return row ? rowToReservation(row) : null;
1956
1982
  },
1957
1983
  async findExpiredBefore(tx, at) {
@@ -1964,16 +1990,16 @@ function createInventoryReservationRepository(store) {
1964
1990
  },
1965
1991
  async setOrderRef(tx, reservationId, orderRef) {
1966
1992
  if (tx.kind === "sqlite") {
1967
- sqliteDb(tx).update(inventoryReservations).set({ orderRef }).where(eq13(inventoryReservations.reservationId, reservationId)).run();
1993
+ sqliteDb(tx).update(inventoryReservations).set({ orderRef }).where(eq12(inventoryReservations.reservationId, reservationId)).run();
1968
1994
  return;
1969
1995
  }
1970
- await postgresDb(tx).update(inventoryReservations2).set({ orderRef }).where(eq13(inventoryReservations2.reservationId, reservationId));
1996
+ await postgresDb(tx).update(inventoryReservations2).set({ orderRef }).where(eq12(inventoryReservations2.reservationId, reservationId));
1971
1997
  }
1972
1998
  };
1973
1999
  }
1974
2000
 
1975
2001
  // src/repositories/stock-adjustment.ts
1976
- import { desc as desc2, eq as eq14 } from "drizzle-orm";
2002
+ import { desc as desc2, eq as eq13 } from "drizzle-orm";
1977
2003
  function rowToAdjustment(row) {
1978
2004
  return {
1979
2005
  id: String(row.id),
@@ -2007,17 +2033,17 @@ function createStockAdjustmentRepository(store) {
2007
2033
  },
2008
2034
  async listByVariant(tx, variantId, limit = 100) {
2009
2035
  if (tx.kind === "sqlite") {
2010
- const rows2 = sqliteDb(tx).select().from(stockAdjustments).where(eq14(stockAdjustments.variantId, variantId)).orderBy(desc2(stockAdjustments.timestamp)).limit(limit).all();
2036
+ const rows2 = sqliteDb(tx).select().from(stockAdjustments).where(eq13(stockAdjustments.variantId, variantId)).orderBy(desc2(stockAdjustments.timestamp)).limit(limit).all();
2011
2037
  return rows2.map((r) => rowToAdjustment(r));
2012
2038
  }
2013
- const rows = await postgresDb(tx).select().from(stockAdjustments2).where(eq14(stockAdjustments2.variantId, variantId)).orderBy(desc2(stockAdjustments2.timestamp)).limit(limit);
2039
+ const rows = await postgresDb(tx).select().from(stockAdjustments2).where(eq13(stockAdjustments2.variantId, variantId)).orderBy(desc2(stockAdjustments2.timestamp)).limit(limit);
2014
2040
  return rows.map((r) => rowToAdjustment(r));
2015
2041
  }
2016
2042
  };
2017
2043
  }
2018
2044
 
2019
2045
  // src/repositories/review.ts
2020
- import { and as and7, desc as desc3, eq as eq15, lt as lt3, or } from "drizzle-orm";
2046
+ import { and as and7, desc as desc3, eq as eq14, lt as lt3, or } from "drizzle-orm";
2021
2047
  function rowToReview(row) {
2022
2048
  return {
2023
2049
  id: String(row.id),
@@ -2038,40 +2064,40 @@ function createReviewRepository(store) {
2038
2064
  store,
2039
2065
  async findById(tx, id) {
2040
2066
  if (tx.kind === "sqlite") {
2041
- const row2 = sqliteDb(tx).select().from(reviews).where(eq15(reviews.id, id)).get();
2067
+ const row2 = sqliteDb(tx).select().from(reviews).where(eq14(reviews.id, id)).get();
2042
2068
  return row2 ? rowToReview(row2) : null;
2043
2069
  }
2044
- const [row] = await postgresDb(tx).select().from(reviews2).where(eq15(reviews2.id, id));
2070
+ const [row] = await postgresDb(tx).select().from(reviews2).where(eq14(reviews2.id, id));
2045
2071
  return row ? rowToReview(row) : null;
2046
2072
  },
2047
2073
  async listByProduct(tx, productId, status, limit = 50, after) {
2048
2074
  if (tx.kind === "sqlite") {
2049
2075
  const t2 = reviews;
2050
- const conds2 = [eq15(t2.productId, productId)];
2051
- if (status) conds2.push(eq15(t2.moderationStatus, status));
2076
+ const conds2 = [eq14(t2.productId, productId)];
2077
+ if (status) conds2.push(eq14(t2.moderationStatus, status));
2052
2078
  if (after) {
2053
2079
  const at = new Date(after.submittedAt).toISOString();
2054
- conds2.push(or(lt3(t2.submittedAt, at), and7(eq15(t2.submittedAt, at), lt3(t2.id, after.id))));
2080
+ conds2.push(or(lt3(t2.submittedAt, at), and7(eq14(t2.submittedAt, at), lt3(t2.id, after.id))));
2055
2081
  }
2056
2082
  const rows2 = sqliteDb(tx).select().from(t2).where(and7(...conds2)).orderBy(desc3(t2.submittedAt), desc3(t2.id)).limit(limit).all();
2057
2083
  return rows2.map((r) => rowToReview(r));
2058
2084
  }
2059
2085
  const t = reviews2;
2060
- const conds = [eq15(t.productId, productId)];
2061
- if (status) conds.push(eq15(t.moderationStatus, status));
2086
+ const conds = [eq14(t.productId, productId)];
2087
+ if (status) conds.push(eq14(t.moderationStatus, status));
2062
2088
  if (after) {
2063
2089
  const at = new Date(after.submittedAt);
2064
- conds.push(or(lt3(t.submittedAt, at), and7(eq15(t.submittedAt, at), lt3(t.id, after.id))));
2090
+ conds.push(or(lt3(t.submittedAt, at), and7(eq14(t.submittedAt, at), lt3(t.id, after.id))));
2065
2091
  }
2066
2092
  const rows = await postgresDb(tx).select().from(t).where(and7(...conds)).orderBy(desc3(t.submittedAt), desc3(t.id)).limit(limit);
2067
2093
  return rows.map((r) => rowToReview(r));
2068
2094
  },
2069
2095
  async listByStatus(tx, status, limit = 100) {
2070
2096
  if (tx.kind === "sqlite") {
2071
- const rows2 = sqliteDb(tx).select().from(reviews).where(eq15(reviews.moderationStatus, status)).orderBy(desc3(reviews.submittedAt)).limit(limit).all();
2097
+ const rows2 = sqliteDb(tx).select().from(reviews).where(eq14(reviews.moderationStatus, status)).orderBy(desc3(reviews.submittedAt)).limit(limit).all();
2072
2098
  return rows2.map((r) => rowToReview(r));
2073
2099
  }
2074
- const rows = await postgresDb(tx).select().from(reviews2).where(eq15(reviews2.moderationStatus, status)).orderBy(desc3(reviews2.submittedAt)).limit(limit);
2100
+ const rows = await postgresDb(tx).select().from(reviews2).where(eq14(reviews2.moderationStatus, status)).orderBy(desc3(reviews2.submittedAt)).limit(limit);
2075
2101
  return rows.map((r) => rowToReview(r));
2076
2102
  },
2077
2103
  async insert(tx, r) {
@@ -2107,10 +2133,10 @@ function createReviewRepository(store) {
2107
2133
  moderationStatus: status,
2108
2134
  moderatedBy,
2109
2135
  moderatedAt: moderatedAt.toISOString()
2110
- }).where(eq15(reviews.id, id)).run();
2136
+ }).where(eq14(reviews.id, id)).run();
2111
2137
  return;
2112
2138
  }
2113
- await postgresDb(tx).update(reviews2).set({ moderationStatus: status, moderatedBy, moderatedAt }).where(eq15(reviews2.id, id));
2139
+ await postgresDb(tx).update(reviews2).set({ moderationStatus: status, moderatedBy, moderatedAt }).where(eq14(reviews2.id, id));
2114
2140
  },
2115
2141
  async aggregateByProduct(tx, productId) {
2116
2142
  const approved = await this.listByProduct(tx, productId, "approved", 1e3);
@@ -2137,7 +2163,7 @@ function createReviewRepository(store) {
2137
2163
  }
2138
2164
 
2139
2165
  // src/repositories/processed-event.ts
2140
- import { and as and8, eq as eq16, lt as lt4 } from "drizzle-orm";
2166
+ import { and as and8, eq as eq15, lt as lt4 } from "drizzle-orm";
2141
2167
  function createProcessedEventRepository(store) {
2142
2168
  const s = processedEvents;
2143
2169
  const p = processedEvents2;
@@ -2145,10 +2171,10 @@ function createProcessedEventRepository(store) {
2145
2171
  store,
2146
2172
  async seen(tx, handlerName, eventId) {
2147
2173
  if (tx.kind === "sqlite") {
2148
- const row = sqliteDb(tx).select({ eventId: s.eventId }).from(s).where(and8(eq16(s.handlerName, handlerName), eq16(s.eventId, eventId))).get();
2174
+ const row = sqliteDb(tx).select({ eventId: s.eventId }).from(s).where(and8(eq15(s.handlerName, handlerName), eq15(s.eventId, eventId))).get();
2149
2175
  return row !== void 0;
2150
2176
  }
2151
- const rows = await postgresDb(tx).select({ eventId: p.eventId }).from(p).where(and8(eq16(p.handlerName, handlerName), eq16(p.eventId, eventId))).limit(1);
2177
+ const rows = await postgresDb(tx).select({ eventId: p.eventId }).from(p).where(and8(eq15(p.handlerName, handlerName), eq15(p.eventId, eventId))).limit(1);
2152
2178
  return rows.length > 0;
2153
2179
  },
2154
2180
  async markProcessed(tx, handlerName, eventId, at) {
@@ -2179,11 +2205,11 @@ function createProcessedEventRepository(store) {
2179
2205
  // src/repositories/event-log.ts
2180
2206
  import {
2181
2207
  and as and9,
2182
- asc as asc8,
2183
- eq as eq17,
2208
+ asc as asc9,
2209
+ eq as eq16,
2184
2210
  gt as gt5,
2185
2211
  gte as gte2,
2186
- inArray as inArray2,
2212
+ inArray as inArray3,
2187
2213
  isNotNull,
2188
2214
  isNull as isNull2,
2189
2215
  lt as lt5,
@@ -2291,9 +2317,9 @@ function createEventLogRepository(store) {
2291
2317
  }
2292
2318
  async function select(tx, where, limit) {
2293
2319
  if (tx.kind === "sqlite") {
2294
- return sqliteDb(tx).select(sqliteLogged).from(s).where(and9(...where.sqlite)).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
2320
+ return sqliteDb(tx).select(sqliteLogged).from(s).where(and9(...where.sqlite)).orderBy(asc9(s.seq)).limit(limit).all().map(rowToLogged);
2295
2321
  }
2296
- const rows = await postgresDb(tx).select(postgresLogged).from(p).where(and9(...where.postgres)).orderBy(asc8(p.seq)).limit(limit);
2322
+ const rows = await postgresDb(tx).select(postgresLogged).from(p).where(and9(...where.postgres)).orderBy(asc9(p.seq)).limit(limit);
2297
2323
  return rows.map(rowToLogged);
2298
2324
  }
2299
2325
  return {
@@ -2346,10 +2372,10 @@ function createEventLogRepository(store) {
2346
2372
  async markDelivered(tx, ids, at) {
2347
2373
  if (ids.length === 0) return;
2348
2374
  if (tx.kind === "sqlite") {
2349
- sqliteDb(tx).update(s).set({ deliveredAt: at.toISOString() }).where(inArray2(s.id, ids)).run();
2375
+ sqliteDb(tx).update(s).set({ deliveredAt: at.toISOString() }).where(inArray3(s.id, ids)).run();
2350
2376
  return;
2351
2377
  }
2352
- await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray2(p.id, ids));
2378
+ await postgresDb(tx).update(p).set({ deliveredAt: at }).where(inArray3(p.id, ids));
2353
2379
  },
2354
2380
  async recordFailure(tx, id, at, maxAttempts, retryAt) {
2355
2381
  if (tx.kind === "sqlite") {
@@ -2357,14 +2383,21 @@ function createEventLogRepository(store) {
2357
2383
  attempts: sql4`${s.attempts} + 1`,
2358
2384
  deadAt: sql4`CASE WHEN ${s.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()} ELSE ${s.deadAt} END`,
2359
2385
  ...retryAt !== void 0 && { retryAt: retryAt.toISOString() }
2360
- }).where(eq17(s.id, id)).run();
2386
+ }).where(eq16(s.id, id)).run();
2361
2387
  return;
2362
2388
  }
2363
2389
  await postgresDb(tx).update(p).set({
2364
2390
  attempts: sql4`${p.attempts} + 1`,
2365
2391
  deadAt: sql4`CASE WHEN ${p.attempts} + 1 >= ${maxAttempts} THEN ${at.toISOString()}::timestamptz ELSE ${p.deadAt} END`,
2366
2392
  ...retryAt !== void 0 && { retryAt }
2367
- }).where(eq17(p.id, id));
2393
+ }).where(eq16(p.id, id));
2394
+ },
2395
+ async recordOutage(tx, id, retryAt) {
2396
+ if (tx.kind === "sqlite") {
2397
+ sqliteDb(tx).update(s).set({ retryAt: retryAt.toISOString() }).where(eq16(s.id, id)).run();
2398
+ return;
2399
+ }
2400
+ await postgresDb(tx).update(p).set({ retryAt }).where(eq16(p.id, id));
2368
2401
  },
2369
2402
  async countDead(tx) {
2370
2403
  if (tx.kind === "sqlite") {
@@ -2395,17 +2428,17 @@ function createEventLogRepository(store) {
2395
2428
  },
2396
2429
  async listAll(tx) {
2397
2430
  if (tx.kind === "sqlite") {
2398
- return sqliteDb(tx).select(sqliteLogged).from(s).orderBy(asc8(s.seq)).all().map(rowToLogged);
2431
+ return sqliteDb(tx).select(sqliteLogged).from(s).orderBy(asc9(s.seq)).all().map(rowToLogged);
2399
2432
  }
2400
- const rows = await postgresDb(tx).select(postgresLogged).from(p).orderBy(asc8(p.seq));
2433
+ const rows = await postgresDb(tx).select(postgresLogged).from(p).orderBy(asc9(p.seq));
2401
2434
  return rows.map(rowToLogged);
2402
2435
  },
2403
2436
  queryByCorrelation(tx, correlationId, filter) {
2404
2437
  return select(
2405
2438
  tx,
2406
2439
  {
2407
- sqlite: [eq17(s.correlationId, correlationId), ...sqliteWhere(filter)],
2408
- postgres: [eq17(p.correlationId, correlationId), ...postgresWhere(filter)]
2440
+ sqlite: [eq16(s.correlationId, correlationId), ...sqliteWhere(filter)],
2441
+ postgres: [eq16(p.correlationId, correlationId), ...postgresWhere(filter)]
2409
2442
  },
2410
2443
  filter.limit
2411
2444
  );
@@ -2439,7 +2472,7 @@ function createEventLogRepository(store) {
2439
2472
  or2(isNull2(s.deliveredAt), gte2(s.deliveredAt, since.toISOString())),
2440
2473
  gt5(s.seq, afterSeq)
2441
2474
  )
2442
- ).orderBy(asc8(s.seq)).limit(limit).all().map(rowToLogged);
2475
+ ).orderBy(asc9(s.seq)).limit(limit).all().map(rowToLogged);
2443
2476
  }
2444
2477
  const rows = await postgresDb(tx).select(postgresLogged).from(p).where(
2445
2478
  and9(
@@ -2447,7 +2480,7 @@ function createEventLogRepository(store) {
2447
2480
  or2(isNull2(p.deliveredAt), gte2(p.deliveredAt, since)),
2448
2481
  gt5(p.seq, afterSeq)
2449
2482
  )
2450
- ).orderBy(asc8(p.seq)).limit(limit);
2483
+ ).orderBy(asc9(p.seq)).limit(limit);
2451
2484
  return rows.map(rowToLogged);
2452
2485
  },
2453
2486
  listDeliveredBefore(tx, at, limit) {
@@ -2465,9 +2498,9 @@ function createEventLogRepository(store) {
2465
2498
  for (let i = 0; i < seqs.length; i += DELETE_CHUNK) {
2466
2499
  const chunk = seqs.slice(i, i + DELETE_CHUNK);
2467
2500
  if (tx.kind === "sqlite") {
2468
- deleted += sqliteDb(tx).delete(s).where(and9(inArray2(s.seq, chunk), isNotNull(s.deliveredAt), isNull2(s.deadAt))).run().changes;
2501
+ deleted += sqliteDb(tx).delete(s).where(and9(inArray3(s.seq, chunk), isNotNull(s.deliveredAt), isNull2(s.deadAt))).run().changes;
2469
2502
  } else {
2470
- const result = await postgresDb(tx).delete(p).where(and9(inArray2(p.seq, chunk), isNotNull(p.deliveredAt), isNull2(p.deadAt)));
2503
+ const result = await postgresDb(tx).delete(p).where(and9(inArray3(p.seq, chunk), isNotNull(p.deliveredAt), isNull2(p.deadAt)));
2471
2504
  deleted += result.rowCount ?? 0;
2472
2505
  }
2473
2506
  }
@@ -2480,12 +2513,12 @@ function createEventLogRepository(store) {
2480
2513
  tx,
2481
2514
  {
2482
2515
  sqlite: [
2483
- or2(...subjects.map((x) => and9(eq17(s.subjectType, x.type), eq17(s.subjectId, x.id)))),
2516
+ or2(...subjects.map((x) => and9(eq16(s.subjectType, x.type), eq16(s.subjectId, x.id)))),
2484
2517
  gt5(s.seq, afterSeq),
2485
2518
  ...page.until === void 0 ? [] : [lte(s.createdAt, page.until.toISOString())]
2486
2519
  ],
2487
2520
  postgres: [
2488
- or2(...subjects.map((x) => and9(eq17(p.subjectType, x.type), eq17(p.subjectId, x.id)))),
2521
+ or2(...subjects.map((x) => and9(eq16(p.subjectType, x.type), eq16(p.subjectId, x.id)))),
2489
2522
  gt5(p.seq, afterSeq),
2490
2523
  ...page.until === void 0 ? [] : [lte(p.createdAt, page.until)]
2491
2524
  ]
@@ -2497,7 +2530,7 @@ function createEventLogRepository(store) {
2497
2530
  }
2498
2531
 
2499
2532
  // src/repositories/cart.ts
2500
- import { and as and10, asc as asc9, eq as eq18, gt as gt6, isNull as isNull3, lt as lt6, lte as lte2, sql as sql5 } from "drizzle-orm";
2533
+ import { and as and10, asc as asc10, eq as eq17, gt as gt6, isNull as isNull3, lt as lt6, lte as lte2, sql as sql5 } from "drizzle-orm";
2501
2534
  function rowToCart(store, row) {
2502
2535
  return {
2503
2536
  token: String(row.token),
@@ -2570,15 +2603,15 @@ function postgresDue(window) {
2570
2603
  function createCartRepository(store) {
2571
2604
  async function findByToken(tx, token) {
2572
2605
  if (tx.kind === "sqlite") {
2573
- const row2 = sqliteDb(tx).select().from(carts).where(eq18(carts.token, token)).get();
2606
+ const row2 = sqliteDb(tx).select().from(carts).where(eq17(carts.token, token)).get();
2574
2607
  return row2 ? rowToCart("sqlite", row2) : null;
2575
2608
  }
2576
- const [row] = await postgresDb(tx).select().from(carts2).where(eq18(carts2.token, token));
2609
+ const [row] = await postgresDb(tx).select().from(carts2).where(eq17(carts2.token, token));
2577
2610
  return row ? rowToCart("postgres", row) : null;
2578
2611
  }
2579
2612
  async function lock(tx, token) {
2580
2613
  if (tx.kind === "sqlite") return findByToken(tx, token);
2581
- const [row] = await postgresDb(tx).select().from(carts2).where(eq18(carts2.token, token)).for("update");
2614
+ const [row] = await postgresDb(tx).select().from(carts2).where(eq17(carts2.token, token)).for("update");
2582
2615
  return row ? rowToCart("postgres", row) : null;
2583
2616
  }
2584
2617
  return {
@@ -2615,10 +2648,10 @@ function createCartRepository(store) {
2615
2648
  },
2616
2649
  async remove(tx, token) {
2617
2650
  if (tx.kind === "sqlite") {
2618
- sqliteDb(tx).delete(carts).where(eq18(carts.token, token)).run();
2651
+ sqliteDb(tx).delete(carts).where(eq17(carts.token, token)).run();
2619
2652
  return;
2620
2653
  }
2621
- await postgresDb(tx).delete(carts2).where(eq18(carts2.token, token));
2654
+ await postgresDb(tx).delete(carts2).where(eq17(carts2.token, token));
2622
2655
  },
2623
2656
  async clearIfLive(tx, token, at) {
2624
2657
  if (tx.kind === "sqlite") {
@@ -2629,7 +2662,7 @@ function createCartRepository(store) {
2629
2662
  subtotalMinor: 0,
2630
2663
  updatedAt: at.toISOString(),
2631
2664
  abandonedNotifiedAt: null
2632
- }).where(and10(eq18(t2.token, token), gt6(t2.expiresAt, at.toISOString()))).run();
2665
+ }).where(and10(eq17(t2.token, token), gt6(t2.expiresAt, at.toISOString()))).run();
2633
2666
  return result.changes > 0;
2634
2667
  }
2635
2668
  const t = carts2;
@@ -2639,7 +2672,7 @@ function createCartRepository(store) {
2639
2672
  subtotalMinor: 0,
2640
2673
  updatedAt: at,
2641
2674
  abandonedNotifiedAt: null
2642
- }).where(and10(eq18(t.token, token), gt6(t.expiresAt, at))).returning({ token: t.token });
2675
+ }).where(and10(eq17(t.token, token), gt6(t.expiresAt, at))).returning({ token: t.token });
2643
2676
  return rows.length > 0;
2644
2677
  },
2645
2678
  async deleteExpired(tx, at) {
@@ -2655,30 +2688,30 @@ function createCartRepository(store) {
2655
2688
  const t2 = carts;
2656
2689
  const rows2 = sqliteDb(tx).select({ token: t2.token }).from(t2).where(
2657
2690
  and10(sqliteDue(window), page.after === void 0 ? void 0 : gt6(t2.token, page.after))
2658
- ).orderBy(asc9(t2.token)).limit(page.limit).all();
2691
+ ).orderBy(asc10(t2.token)).limit(page.limit).all();
2659
2692
  return rows2.map((r) => r.token);
2660
2693
  }
2661
2694
  const t = carts2;
2662
2695
  const rows = await postgresDb(tx).select({ token: t.token }).from(t).where(
2663
2696
  and10(postgresDue(window), page.after === void 0 ? void 0 : gt6(t.token, page.after))
2664
- ).orderBy(asc9(t.token)).limit(page.limit);
2697
+ ).orderBy(asc10(t.token)).limit(page.limit);
2665
2698
  return rows.map((r) => r.token);
2666
2699
  },
2667
2700
  async claimAbandoned(tx, token, window) {
2668
2701
  if (tx.kind === "sqlite") {
2669
2702
  const t2 = carts;
2670
- const row2 = sqliteDb(tx).update(t2).set({ abandonedNotifiedAt: window.at.toISOString() }).where(and10(eq18(t2.token, token), sqliteDue(window))).returning({ token: t2.token, updatedAt: t2.updatedAt }).get();
2703
+ const row2 = sqliteDb(tx).update(t2).set({ abandonedNotifiedAt: window.at.toISOString() }).where(and10(eq17(t2.token, token), sqliteDue(window))).returning({ token: t2.token, updatedAt: t2.updatedAt }).get();
2671
2704
  return row2 ? { token: row2.token, lastActivityAt: fromTimestamp(row2.updatedAt) } : null;
2672
2705
  }
2673
2706
  const t = carts2;
2674
- const [row] = await postgresDb(tx).update(t).set({ abandonedNotifiedAt: window.at }).where(and10(eq18(t.token, token), postgresDue(window))).returning({ token: t.token, updatedAt: t.updatedAt });
2707
+ const [row] = await postgresDb(tx).update(t).set({ abandonedNotifiedAt: window.at }).where(and10(eq17(t.token, token), postgresDue(window))).returning({ token: t.token, updatedAt: t.updatedAt });
2675
2708
  return row ? { token: row.token, lastActivityAt: fromTimestamp(row.updatedAt) } : null;
2676
2709
  }
2677
2710
  };
2678
2711
  }
2679
2712
 
2680
2713
  // src/repositories/alert-subscription.ts
2681
- import { and as and11, eq as eq19, inArray as inArray3, sql as sql6 } from "drizzle-orm";
2714
+ import { and as and11, eq as eq18, inArray as inArray4, sql as sql6 } from "drizzle-orm";
2682
2715
  function fromSqlite(row) {
2683
2716
  return {
2684
2717
  ...row,
@@ -2737,14 +2770,14 @@ function createAlertSubscriptionRepository(store) {
2737
2770
  const [row] = await postgresDb(tx).insert(p).values({ ...values, createdAt: r.at, updatedAt: r.at }).onConflictDoUpdate({ target: [p.email, p.variantId, p.kind], set: set(p) }).returning();
2738
2771
  return fromPostgres(row);
2739
2772
  },
2740
- findById: (tx, id) => findOne(tx, (t) => eq19(t.id, id)),
2741
- findByConfirmToken: (tx, token) => findOne(tx, (t) => eq19(t.confirmToken, token)),
2742
- findByUnsubscribeToken: (tx, token) => findOne(tx, (t) => eq19(t.unsubscribeToken, token)),
2773
+ findById: (tx, id) => findOne(tx, (t) => eq18(t.id, id)),
2774
+ findByConfirmToken: (tx, token) => findOne(tx, (t) => eq18(t.confirmToken, token)),
2775
+ findByUnsubscribeToken: (tx, token) => findOne(tx, (t) => eq18(t.unsubscribeToken, token)),
2743
2776
  async listActive(tx, variantId, kind) {
2744
2777
  if (tx.kind === "sqlite") {
2745
- return sqliteDb(tx).select().from(s).where(and11(eq19(s.variantId, variantId), eq19(s.kind, kind), eq19(s.status, "active"))).orderBy(s.id).all().map(fromSqlite);
2778
+ return sqliteDb(tx).select().from(s).where(and11(eq18(s.variantId, variantId), eq18(s.kind, kind), eq18(s.status, "active"))).orderBy(s.id).all().map(fromSqlite);
2746
2779
  }
2747
- const rows = await postgresDb(tx).select().from(p).where(and11(eq19(p.variantId, variantId), eq19(p.kind, kind), eq19(p.status, "active"))).orderBy(p.id);
2780
+ const rows = await postgresDb(tx).select().from(p).where(and11(eq18(p.variantId, variantId), eq18(p.kind, kind), eq18(p.status, "active"))).orderBy(p.id);
2748
2781
  return rows.map(fromPostgres);
2749
2782
  },
2750
2783
  async update(tx, id, patch, from) {
@@ -2758,7 +2791,7 @@ function createAlertSubscriptionRepository(store) {
2758
2791
  ...patch.baselinePriceMinor !== void 0 && {
2759
2792
  baselinePriceMinor: patch.baselinePriceMinor
2760
2793
  }
2761
- }).where(and11(eq19(s.id, id), inArray3(s.status, [...from]))).returning().get();
2794
+ }).where(and11(eq18(s.id, id), inArray4(s.status, [...from]))).returning().get();
2762
2795
  return row2 === void 0 ? null : fromSqlite(row2);
2763
2796
  }
2764
2797
  const [row] = await postgresDb(tx).update(p).set({
@@ -2768,12 +2801,67 @@ function createAlertSubscriptionRepository(store) {
2768
2801
  ...patch.baselinePriceMinor !== void 0 && {
2769
2802
  baselinePriceMinor: patch.baselinePriceMinor
2770
2803
  }
2771
- }).where(and11(eq19(p.id, id), inArray3(p.status, [...from]))).returning();
2804
+ }).where(and11(eq18(p.id, id), inArray4(p.status, [...from]))).returning();
2772
2805
  return row === void 0 ? null : fromPostgres(row);
2773
2806
  }
2774
2807
  };
2775
2808
  }
2776
2809
 
2810
+ // src/repositories/email-suppression.ts
2811
+ import { eq as eq19 } from "drizzle-orm";
2812
+ function createEmailSuppressionRepository(store) {
2813
+ const s = emailSuppressions;
2814
+ const p = emailSuppressions2;
2815
+ return {
2816
+ store,
2817
+ async suppress(tx, { email, reason, eventId, at }) {
2818
+ const values = { email: normaliseEmail(email), reason, eventId };
2819
+ if (tx.kind === "sqlite") {
2820
+ const result2 = sqliteDb(tx).insert(s).values({ ...values, createdAt: at.toISOString() }).onConflictDoNothing().run();
2821
+ return result2.changes > 0;
2822
+ }
2823
+ const result = await postgresDb(tx).insert(p).values({ ...values, createdAt: at }).onConflictDoNothing();
2824
+ return (result.rowCount ?? 0) > 0;
2825
+ },
2826
+ async isSuppressed(tx, email) {
2827
+ const key = normaliseEmail(email);
2828
+ if (tx.kind === "sqlite") {
2829
+ const row = sqliteDb(tx).select({ email: s.email }).from(s).where(eq19(s.email, key)).get();
2830
+ return row !== void 0;
2831
+ }
2832
+ const rows = await postgresDb(tx).select({ email: p.email }).from(p).where(eq19(p.email, key)).limit(1);
2833
+ return rows.length > 0;
2834
+ }
2835
+ };
2836
+ }
2837
+
2838
+ // src/repositories/order-shipment.ts
2839
+ import { eq as eq20 } from "drizzle-orm";
2840
+ import { normaliseTrackingNumber } from "@nymbalhq/types";
2841
+ function createOrderShipmentRepository(store) {
2842
+ const s = orderShipments;
2843
+ const p = orderShipments2;
2844
+ return {
2845
+ store,
2846
+ async record(tx, { orderId, carrier, trackingNumber, at }) {
2847
+ const values = { orderId, carrier, trackingNumber: normaliseTrackingNumber(trackingNumber) };
2848
+ if (tx.kind === "sqlite") {
2849
+ sqliteDb(tx).insert(s).values({ ...values, createdAt: at.toISOString() }).run();
2850
+ return;
2851
+ }
2852
+ await postgresDb(tx).insert(p).values({ ...values, createdAt: at });
2853
+ },
2854
+ async ordersByTrackingNumber(tx, trackingNumber) {
2855
+ const key = normaliseTrackingNumber(trackingNumber);
2856
+ if (tx.kind === "sqlite") {
2857
+ return sqliteDb(tx).select({ orderId: s.orderId }).from(s).where(eq20(s.trackingNumber, key)).all().map((r) => r.orderId);
2858
+ }
2859
+ const rows = await postgresDb(tx).select({ orderId: p.orderId }).from(p).where(eq20(p.trackingNumber, key));
2860
+ return rows.map((r) => r.orderId);
2861
+ }
2862
+ };
2863
+ }
2864
+
2777
2865
  // src/repositories/index.ts
2778
2866
  function buildRepositories(commandStore, _documentStore) {
2779
2867
  return {
@@ -2796,7 +2884,9 @@ function buildRepositories(commandStore, _documentStore) {
2796
2884
  cart: createCartRepository(commandStore),
2797
2885
  settings: createSettingsRepository(commandStore),
2798
2886
  auditEntry: createAuditEntryRepository(commandStore),
2799
- alertSubscription: createAlertSubscriptionRepository(commandStore)
2887
+ alertSubscription: createAlertSubscriptionRepository(commandStore),
2888
+ emailSuppression: createEmailSuppressionRepository(commandStore),
2889
+ orderShipment: createOrderShipmentRepository(commandStore)
2800
2890
  };
2801
2891
  }
2802
2892
 
@@ -2861,7 +2951,11 @@ function createEventPublisher(opts) {
2861
2951
 
2862
2952
  // src/events/relay.ts
2863
2953
  import { AsyncLocalStorage } from "async_hooks";
2954
+ import {
2955
+ HEALTH_CHECK_TIMEOUT_MS
2956
+ } from "@nymbalhq/types";
2864
2957
  var PAGE_SIZE = 100;
2958
+ var NO_OUTAGE = { outage: false, down: [] };
2865
2959
  function deferred() {
2866
2960
  let resolve4;
2867
2961
  const promise = new Promise((r) => {
@@ -2879,6 +2973,7 @@ function createRelay(opts) {
2879
2973
  const intervalMs = opts.intervalMs ?? 1e4;
2880
2974
  const retryDelayMs = opts.retryDelayMs ?? intervalMs;
2881
2975
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
2976
+ const outageTimeoutMs = opts.outageTimeoutMs ?? HEALTH_CHECK_TIMEOUT_MS + 1e3;
2882
2977
  const logger = opts.logger.child({ component: "event-relay" });
2883
2978
  const delivering = new AsyncLocalStorage();
2884
2979
  let active = false;
@@ -2886,11 +2981,54 @@ function createRelay(opts) {
2886
2981
  let followUp;
2887
2982
  let timer;
2888
2983
  let stopped = false;
2889
- async function deliver({ event, attempts }) {
2984
+ async function probe() {
2985
+ const ask = opts.outage;
2986
+ if (ask === void 0) return NO_OUTAGE;
2987
+ let bound;
2988
+ const timedOut = new Promise((resolve4) => {
2989
+ bound = setTimeout(
2990
+ () => resolve4({
2991
+ outage: true,
2992
+ down: [{ name: "probe", detail: `timed out after ${outageTimeoutMs} ms` }]
2993
+ }),
2994
+ outageTimeoutMs
2995
+ );
2996
+ });
2997
+ try {
2998
+ return await Promise.race([Promise.resolve().then(ask), timedOut]);
2999
+ } catch (err) {
3000
+ return {
3001
+ outage: true,
3002
+ down: [{ name: "probe", detail: err instanceof Error ? err.message : String(err) }]
3003
+ };
3004
+ } finally {
3005
+ clearTimeout(bound);
3006
+ }
3007
+ }
3008
+ function outageOfPass() {
3009
+ let asked;
3010
+ return () => asked ??= probe().then((report) => {
3011
+ if (report.outage) {
3012
+ const named = report.down.map(({ name, detail }) => `${name} (${detail})`).join(", ");
3013
+ logger.warn({ down: report.down }, `outage: ${named}`);
3014
+ }
3015
+ return report;
3016
+ });
3017
+ }
3018
+ async function deliver({ event, attempts }, outage) {
2890
3019
  try {
2891
3020
  await delivering.run(true, () => opts.eventBus.publish(event));
2892
3021
  } catch (err) {
2893
3022
  const at = now();
3023
+ if ((await outage()).outage) {
3024
+ const retryAt2 = new Date(at.getTime() + retryDelayMs * 2 ** attempts);
3025
+ await store.transaction((tx) => eventLog.recordOutage(tx, event.id, retryAt2));
3026
+ logger.debug(
3027
+ { err, eventId: event.id, eventType: event.type, retryAt: retryAt2.toISOString() },
3028
+ "event delivery failed during an outage; not counted, tried again from retryAt"
3029
+ );
3030
+ return;
3031
+ }
2894
3032
  const failures = attempts + 1;
2895
3033
  const retryAt = new Date(at.getTime() + retryDelayMs * 2 ** (failures - 1));
2896
3034
  await store.transaction(
@@ -2918,6 +3056,7 @@ function createRelay(opts) {
2918
3056
  async function pass() {
2919
3057
  try {
2920
3058
  let afterSeq = 0;
3059
+ const outage = outageOfPass();
2921
3060
  for (; ; ) {
2922
3061
  if (stopped) return;
2923
3062
  const page = await store.read(
@@ -2926,7 +3065,7 @@ function createRelay(opts) {
2926
3065
  for (const logged of page) {
2927
3066
  if (stopped) return;
2928
3067
  afterSeq = logged.seq;
2929
- await deliver(logged);
3068
+ await deliver(logged, outage);
2930
3069
  }
2931
3070
  if (page.length < PAGE_SIZE) return;
2932
3071
  }
@@ -3299,21 +3438,29 @@ import {
3299
3438
  EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED2
3300
3439
  } from "@nymbalhq/types";
3301
3440
  var ORDER_PAID_EMAIL = "email:order-paid";
3441
+ var DEFAULT_EMAIL_KEY_LIFETIME_MS = 30 * 24 * 36e5;
3302
3442
  async function registerEmailHandler(deps) {
3303
3443
  const { eventBus, email, logger, processedEventRepo, orderRepo, orderAccessKeyRepo } = deps;
3304
3444
  const { storeName, storeUrl } = deps;
3445
+ const keyLifetimeMs = deps.keyLifetimeMs ?? DEFAULT_EMAIL_KEY_LIFETIME_MS;
3305
3446
  async function orderLink(base, order) {
3306
- const { key, hash } = mintOrderKey();
3307
- await orderAccessKeyRepo.store.transaction(
3308
- (tx) => orderAccessKeyRepo.insert(tx, {
3309
- id: uuidv73(),
3310
- orderId: order.id,
3311
- keyHash: hash,
3312
- purpose: "email",
3313
- createdAt: /* @__PURE__ */ new Date()
3314
- })
3315
- );
3316
- const orderUrl = `${base}/order/${encodeURIComponent(order.orderNumber)}?key=${key}`;
3447
+ const number = encodeURIComponent(order.orderNumber);
3448
+ let orderUrl = `${base}/account/orders/${number}`;
3449
+ if (order.customerId === null) {
3450
+ const { key, hash } = mintOrderKey();
3451
+ const createdAt = /* @__PURE__ */ new Date();
3452
+ await orderAccessKeyRepo.store.transaction(
3453
+ (tx) => orderAccessKeyRepo.insert(tx, {
3454
+ id: uuidv73(),
3455
+ orderId: order.id,
3456
+ keyHash: hash,
3457
+ purpose: "email",
3458
+ createdAt,
3459
+ expiresAt: new Date(createdAt.getTime() + keyLifetimeMs)
3460
+ })
3461
+ );
3462
+ orderUrl = `${base}/order/${number}?key=${key}`;
3463
+ }
3317
3464
  return { orderUrl, orderLink: `
3318
3465
 
3319
3466
  View your order: ${orderUrl}` };
@@ -3411,8 +3558,17 @@ import {
3411
3558
  EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED2
3412
3559
  } from "@nymbalhq/types";
3413
3560
  function searchHandler(deps) {
3414
- const { search: search2, repos } = deps;
3561
+ const { search: search2, repos, logger } = deps;
3562
+ const skips = (event) => {
3563
+ if (search2.capabilities().includes("index")) return false;
3564
+ logger.debug(
3565
+ { eventId: event.id, type: event.type, provider: search2.providerName },
3566
+ "search: the slot cannot index, event skipped"
3567
+ );
3568
+ return true;
3569
+ };
3415
3570
  const onUpsert = async (event) => {
3571
+ if (skips(event)) return;
3416
3572
  const { id } = event.payload.product;
3417
3573
  const snapshot = await repos.product.store.read(async (tx) => {
3418
3574
  const product = await repos.product.findById(tx, id);
@@ -3422,6 +3578,7 @@ function searchHandler(deps) {
3422
3578
  else await search2.remove([id]);
3423
3579
  };
3424
3580
  const onDelete = async (event) => {
3581
+ if (skips(event)) return;
3425
3582
  await search2.remove([event.payload.productId]);
3426
3583
  };
3427
3584
  return [
@@ -3478,16 +3635,19 @@ function links(row, product) {
3478
3635
  async function registerAlertHandler(deps) {
3479
3636
  const { eventBus, email, logger, repos, alerts, storeName } = deps;
3480
3637
  const { store } = repos.processedEvent;
3638
+ const skipped = (subscriptionId, eventId) => logger.info({ subscriptionId, eventId }, "alert mail skipped: the address is suppressed");
3481
3639
  const onRequested = async (event) => {
3482
3640
  const key = `${event.id}:${event.payload.subscriptionId}`;
3483
3641
  const found = await store.read(async (tx) => {
3484
3642
  if (await repos.processedEvent.seen(tx, HANDLER, key)) return null;
3485
3643
  const row2 = await repos.alertSubscription.findById(tx, event.payload.subscriptionId);
3486
3644
  if (row2 === null || row2.status !== "pending") return null;
3645
+ if (await repos.emailSuppression.isSuppressed(tx, row2.email)) return "suppressed";
3487
3646
  const product2 = await repos.product.findById(tx, row2.productId);
3488
3647
  return product2 === null ? null : { row: row2, product: product2 };
3489
3648
  });
3490
3649
  if (found === null) return;
3650
+ if (found === "suppressed") return skipped(event.payload.subscriptionId, event.id);
3491
3651
  const { row, product } = found;
3492
3652
  const { confirmUrl, unsubscribeUrl, productUrl } = links(row, product);
3493
3653
  await email.sendTransactional({
@@ -3503,7 +3663,12 @@ async function registerAlertHandler(deps) {
3503
3663
  const failed = [];
3504
3664
  for (const row of rows) {
3505
3665
  const key = `${event.id}:${row.id}`;
3506
- if (await store.read((tx) => repos.processedEvent.seen(tx, HANDLER, key))) continue;
3666
+ const skip = await store.read(async (tx) => {
3667
+ if (await repos.processedEvent.seen(tx, HANDLER, key)) return "sent";
3668
+ return await repos.emailSuppression.isSuppressed(tx, row.email) ? "suppressed" : null;
3669
+ });
3670
+ if (skip === "suppressed") skipped(row.id, event.id);
3671
+ if (skip !== null) continue;
3507
3672
  try {
3508
3673
  await email.sendTransactional({ ...message(row), to: row.email });
3509
3674
  await store.transaction(async (tx) => {
@@ -3578,9 +3743,111 @@ async function registerAlertHandler(deps) {
3578
3743
  });
3579
3744
  }
3580
3745
 
3746
+ // src/handlers/side-effects/email-feedback-handler.ts
3747
+ import {
3748
+ emailFeedbackType
3749
+ } from "@nymbalhq/types";
3750
+ async function registerEmailFeedbackHandler(deps) {
3751
+ const { eventBus, email, repos, logger } = deps;
3752
+ if (!isHooked(email)) return;
3753
+ const { store } = repos.emailSuppression;
3754
+ async function suppress(event, reason) {
3755
+ const suppressed = await store.transaction(
3756
+ (tx) => repos.emailSuppression.suppress(tx, {
3757
+ email: normaliseEmail(event.payload.recipient),
3758
+ reason,
3759
+ eventId: event.id,
3760
+ at: /* @__PURE__ */ new Date()
3761
+ })
3762
+ );
3763
+ logger.info(
3764
+ { eventId: event.id, reason, suppressed },
3765
+ suppressed ? "an address was suppressed" : "the address was already suppressed"
3766
+ );
3767
+ }
3768
+ const onBounced = async (event) => {
3769
+ if (event.payload.bounce !== "hard") {
3770
+ logger.info({ eventId: event.id }, "a soft bounce changes nothing");
3771
+ return;
3772
+ }
3773
+ await suppress(event, "hard_bounce");
3774
+ };
3775
+ const onComplained = (event) => suppress(event, "complaint");
3776
+ await eventBus.subscribe(
3777
+ emailFeedbackType(email.providerName, "bounced"),
3778
+ onBounced,
3779
+ { name: "email-feedback-bounced" }
3780
+ );
3781
+ await eventBus.subscribe(
3782
+ emailFeedbackType(email.providerName, "complained"),
3783
+ onComplained,
3784
+ { name: "email-feedback-complained" }
3785
+ );
3786
+ }
3787
+
3788
+ // src/handlers/side-effects/shipping-tracking-handler.ts
3789
+ import {
3790
+ StatusTransitionError,
3791
+ shippingTrackingType
3792
+ } from "@nymbalhq/types";
3793
+ var ACTOR = "system:shipping-tracking";
3794
+ async function registerShippingTrackingHandler(deps) {
3795
+ const { eventBus, shipping, repos, orderService, logger } = deps;
3796
+ if (!isHooked(shipping)) return;
3797
+ const { store } = repos.orderShipment;
3798
+ async function deliver(eventId, orderId) {
3799
+ try {
3800
+ await runAsActor(
3801
+ { kind: "system", id: "shipping-tracking" },
3802
+ () => orderService.markDelivered(orderId, ACTOR)
3803
+ );
3804
+ logger.info({ eventId, orderId }, "a tracking update delivered the order");
3805
+ } catch (err) {
3806
+ if (!(err instanceof StatusTransitionError)) throw err;
3807
+ logger.info({ eventId, orderId }, "the order was no longer shipped");
3808
+ }
3809
+ }
3810
+ const onTracking = async (event) => {
3811
+ const { status, trackingNumber } = event.payload;
3812
+ if (status !== "delivered") {
3813
+ logger.info({ eventId: event.id, status }, "a tracking update other than delivered");
3814
+ return;
3815
+ }
3816
+ const orders4 = await store.read(async (tx) => {
3817
+ const found = [];
3818
+ for (const id of await repos.orderShipment.ordersByTrackingNumber(tx, trackingNumber)) {
3819
+ const order = await repos.order.findById(tx, id);
3820
+ if (order !== null) found.push(order);
3821
+ }
3822
+ return found;
3823
+ });
3824
+ if (orders4.length === 0) {
3825
+ logger.info({ eventId: event.id }, "no order was shipped under the tracking number");
3826
+ return;
3827
+ }
3828
+ for (const order of orders4) {
3829
+ if (order.status !== "shipped") {
3830
+ logger.info(
3831
+ { eventId: event.id, orderId: order.id, orderStatus: order.status },
3832
+ "the order is not shipped"
3833
+ );
3834
+ continue;
3835
+ }
3836
+ await deliver(event.id, order.id);
3837
+ }
3838
+ };
3839
+ await eventBus.subscribe(
3840
+ shippingTrackingType(shipping.providerName),
3841
+ onTracking,
3842
+ {
3843
+ name: "shipping-tracking"
3844
+ }
3845
+ );
3846
+ }
3847
+
3581
3848
  // src/handlers/register.ts
3582
3849
  async function registerHandlers(deps) {
3583
- const { config, eventBus, documentStore, repos, adapters, alerts, logger } = deps;
3850
+ const { config, eventBus, documentStore, repos, adapters, alerts, orders: orders4, logger } = deps;
3584
3851
  const handlerLogger = logger.child({ component: "handlers" });
3585
3852
  await registerCategoryProjection({
3586
3853
  eventBus,
@@ -3632,7 +3899,8 @@ async function registerHandlers(deps) {
3632
3899
  orderRepo: repos.order,
3633
3900
  orderAccessKeyRepo: repos.orderAccessKey,
3634
3901
  storeName: config.store.name,
3635
- ...config.store.url !== void 0 && { storeUrl: config.store.url }
3902
+ ...config.store.url !== void 0 && { storeUrl: config.store.url },
3903
+ keyLifetimeMs: parseDurationToMs(config.commerce.orders.keyLifetime.email)
3636
3904
  });
3637
3905
  await registerAlertHandler({
3638
3906
  eventBus,
@@ -3642,10 +3910,24 @@ async function registerHandlers(deps) {
3642
3910
  alerts,
3643
3911
  storeName: config.store.name
3644
3912
  });
3913
+ await registerEmailFeedbackHandler({
3914
+ eventBus,
3915
+ email: adapters.email,
3916
+ repos,
3917
+ logger: handlerLogger.child({ handler: "email-feedback" })
3918
+ });
3919
+ await registerShippingTrackingHandler({
3920
+ eventBus,
3921
+ shipping: adapters.shipping,
3922
+ repos,
3923
+ orderService: orders4,
3924
+ logger: handlerLogger.child({ handler: "shipping-tracking" })
3925
+ });
3645
3926
  await registerSearchHandler({
3646
3927
  eventBus,
3647
3928
  search: adapters.search,
3648
- repos
3929
+ repos,
3930
+ logger: handlerLogger.child({ handler: "search" })
3649
3931
  });
3650
3932
  await registerReviewsHandler({
3651
3933
  eventBus,
@@ -3657,11 +3939,53 @@ async function registerHandlers(deps) {
3657
3939
  }
3658
3940
 
3659
3941
  // src/app.ts
3942
+ import { DEFAULT_JWT_SECRET as DEFAULT_JWT_SECRET2 } from "@nymbalhq/config";
3943
+ import {
3944
+ ConfigError as ConfigError3
3945
+ } from "@nymbalhq/types";
3946
+
3947
+ // src/auth-secret.ts
3660
3948
  import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
3661
3949
  import { ConfigError as ConfigError2 } from "@nymbalhq/types";
3950
+ var JWT_SECRET_ENV = "NYMBAL_JWT_SECRET";
3951
+ var MIN_LENGTH = 16;
3952
+ function resolveAuthSecret(config, env) {
3953
+ const fromEnv = env[JWT_SECRET_ENV];
3954
+ if (fromEnv !== void 0 && fromEnv.length < MIN_LENGTH) {
3955
+ throw new ConfigError2(
3956
+ `${JWT_SECRET_ENV} is shorter than ${MIN_LENGTH} characters; set it to a random secret, such as \`openssl rand -base64 32\`.`,
3957
+ { code: "config.jwt_secret_too_short", context: { variable: JWT_SECRET_ENV } }
3958
+ );
3959
+ }
3960
+ const own = config.security.auth.jwtSecret;
3961
+ if (own !== DEFAULT_JWT_SECRET) return { secret: own, source: "config" };
3962
+ if (fromEnv !== void 0) return { secret: fromEnv, source: "env" };
3963
+ return { secret: DEFAULT_JWT_SECRET, source: "default" };
3964
+ }
3965
+
3966
+ // src/events/outage.ts
3967
+ import { boundedHealthCheck, HEALTH_CHECK_TIMEOUT_MS as HEALTH_CHECK_TIMEOUT_MS2 } from "@nymbalhq/types";
3968
+ function createOutageProbe(subjects, options = {}) {
3969
+ const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS2;
3970
+ const checked = subjects.filter(
3971
+ (subject) => !isNotConfigured(subject) && typeof subject.healthCheck === "function"
3972
+ );
3973
+ return async () => {
3974
+ const reports = await Promise.all(
3975
+ checked.map(async (subject) => ({
3976
+ name: subject.name,
3977
+ report: await boundedHealthCheck(() => subject.healthCheck(), { timeoutMs })
3978
+ }))
3979
+ );
3980
+ const down = reports.filter(({ report }) => report.status === "down").map(({ name, report }) => ({ name, detail: report.detail ?? "down" }));
3981
+ return { outage: down.length > 0, down };
3982
+ };
3983
+ }
3662
3984
 
3663
3985
  // src/read-models/index.ts
3664
- import { errorText } from "@nymbalhq/types";
3986
+ import {
3987
+ errorText
3988
+ } from "@nymbalhq/types";
3665
3989
 
3666
3990
  // src/read-models/catalogue.ts
3667
3991
  function snapshotsOf({ repos }) {
@@ -3782,7 +4106,7 @@ var search = {
3782
4106
  }
3783
4107
  },
3784
4108
  handlers(deps) {
3785
- return searchHandler({ search: searchOf(deps), repos: deps.repos });
4109
+ return searchHandler({ search: searchOf(deps), repos: deps.repos, logger: deps.logger });
3786
4110
  }
3787
4111
  };
3788
4112
 
@@ -3895,6 +4219,75 @@ async function swap({ model, writes }, deps) {
3895
4219
  await search2.index(docs);
3896
4220
  return `${search2.providerName} has no replaceAll: every document was indexed, removals not guaranteed`;
3897
4221
  }
4222
+ function stagedDeps({ model, writes }, deps) {
4223
+ if (model.target === "search") return { ...deps, search: stagedSearch(searchOf(deps), writes) };
4224
+ const live = deps.documentStore;
4225
+ const documentStore = {
4226
+ capabilities: () => live.capabilities(),
4227
+ async get(collection, key) {
4228
+ const docs = writes.get(collection);
4229
+ if (docs === void 0) return live.get(collection, key);
4230
+ return docs.get(key) ?? null;
4231
+ },
4232
+ async put(collection, key, doc, options) {
4233
+ const docs = writes.get(collection);
4234
+ if (docs === void 0) return live.put(collection, key, doc, options);
4235
+ docs.set(key, doc);
4236
+ },
4237
+ async delete(collection, key) {
4238
+ const docs = writes.get(collection);
4239
+ if (docs === void 0) return live.delete(collection, key);
4240
+ docs.delete(key);
4241
+ },
4242
+ async batchGet(collection, keys) {
4243
+ const docs = writes.get(collection);
4244
+ if (docs === void 0) return live.batchGet(collection, keys);
4245
+ const out = /* @__PURE__ */ new Map();
4246
+ for (const key of keys) if (docs.has(key)) out.set(key, docs.get(key));
4247
+ return out;
4248
+ },
4249
+ async batchPut(collection, items) {
4250
+ const docs = writes.get(collection);
4251
+ if (docs === void 0) return live.batchPut(collection, items);
4252
+ for (const [key, doc] of items) docs.set(key, doc);
4253
+ },
4254
+ query() {
4255
+ throw new Error("a staged read model does not answer queries");
4256
+ },
4257
+ replaceCollection() {
4258
+ throw new Error("a staged read model is not replaced");
4259
+ },
4260
+ close: async () => void 0
4261
+ };
4262
+ return { ...deps, documentStore };
4263
+ }
4264
+ function stagedSearch(live, writes) {
4265
+ const held = writes.get(SEARCH_INDEX);
4266
+ return {
4267
+ kind: "search",
4268
+ get providerName() {
4269
+ return live.providerName;
4270
+ },
4271
+ capabilities: () => live.capabilities(),
4272
+ producesEvents: [],
4273
+ consumesEvents: [],
4274
+ initialize: async () => void 0,
4275
+ healthCheck: () => live.healthCheck(),
4276
+ async index(docs) {
4277
+ for (const doc of docs) held.set(doc.id, doc);
4278
+ return { indexed: docs.length };
4279
+ },
4280
+ async remove(ids) {
4281
+ for (const id of ids) held.delete(id);
4282
+ },
4283
+ search() {
4284
+ throw new Error("a staged search index does not answer searches");
4285
+ },
4286
+ facet() {
4287
+ throw new Error("a staged search index does not answer facets");
4288
+ }
4289
+ };
4290
+ }
3898
4291
  async function catchUp(model, since, deps, afterSeq = 0) {
3899
4292
  const handlers = model.handlers(deps);
3900
4293
  const failures = [];
@@ -3930,16 +4323,16 @@ async function rebuild(names, deps) {
3930
4323
  for (const model of modelsOf(names)) collected.push(await collect(model, deps));
3931
4324
  const report = [];
3932
4325
  for (const c of collected) {
4326
+ const since = new Date(c.startedAt - CATCH_UP_MARGIN_MS);
4327
+ await deps.onPhase?.("collected", c.model.name);
4328
+ const staged = await catchUp(c.model, since, stagedDeps(c, deps), c.logReadThrough);
3933
4329
  const note = await swap(c, deps);
3934
- const { applied, failures } = await catchUp(
3935
- c.model,
3936
- new Date(c.startedAt - CATCH_UP_MARGIN_MS),
3937
- deps,
3938
- c.logReadThrough
3939
- );
4330
+ await deps.onPhase?.("swapped", c.model.name);
4331
+ const { applied, failures } = await catchUp(c.model, since, deps, c.logReadThrough);
3940
4332
  const entry = {
3941
4333
  model: c.model.name,
3942
4334
  collections: [...c.writes].map(([name, docs]) => ({ name, documents: docs.size })),
4335
+ caughtUpBeforeSwap: staged.applied,
3943
4336
  caughtUpEvents: applied,
3944
4337
  failures,
3945
4338
  ms: Date.now() - c.startedAt,
@@ -4207,18 +4600,18 @@ function startEventRetentionSweeper(deps) {
4207
4600
  }
4208
4601
 
4209
4602
  // src/app.ts
4210
- function refuseUnsafeProduction(config, payments) {
4603
+ function refuseUnsafeProduction(config, payments, jwtSecret) {
4211
4604
  if (process.env.NODE_ENV !== "production") return;
4212
4605
  const provider = config.commerce.payments.provider;
4213
4606
  if (payments.providerName === "native-stub") {
4214
- throw new ConfigError2(
4607
+ throw new ConfigError3(
4215
4608
  `Payments provider "${provider}" resolves to the stub adapter, which verifies no webhook signature; configure a real payments provider for production.`,
4216
4609
  { code: "config.production_stub_payments", context: { provider } }
4217
4610
  );
4218
4611
  }
4219
- if (config.security.auth.jwtSecret === DEFAULT_JWT_SECRET) {
4220
- throw new ConfigError2(
4221
- "security.auth.jwtSecret is the schema default; set a secret of your own for production.",
4612
+ if (jwtSecret === DEFAULT_JWT_SECRET2) {
4613
+ throw new ConfigError3(
4614
+ `security.auth.jwtSecret is the schema default and ${JWT_SECRET_ENV} is not set; set either to a secret of your own for production.`,
4222
4615
  { code: "config.production_default_jwt_secret" }
4223
4616
  );
4224
4617
  }
@@ -4229,10 +4622,10 @@ async function eventArchiveWriter(config) {
4229
4622
  const { adapter, ...options } = archive;
4230
4623
  let mod;
4231
4624
  try {
4232
- mod = await importProviderPackage("media", adapter, process.env);
4625
+ mod = await importAdapterModule("media", { provider: adapter }, process.env);
4233
4626
  } catch (error) {
4234
- if (!(error instanceof ConfigError2 && error.code === "adapter.package_missing")) throw error;
4235
- throw new ConfigError2(
4627
+ if (!(error instanceof ConfigError3 && error.code === "adapter.package_missing")) throw error;
4628
+ throw new ConfigError3(
4236
4629
  `events.archive needs @nymbalhq/media-s3: ${String(error.context["install"])}`,
4237
4630
  {
4238
4631
  code: "adapter.package_missing",
@@ -4242,19 +4635,64 @@ async function eventArchiveWriter(config) {
4242
4635
  );
4243
4636
  }
4244
4637
  if (typeof mod?.createS3ObjectWriter !== "function") {
4245
- throw new ConfigError2("@nymbalhq/media-s3 exports no createS3ObjectWriter; upgrade it", {
4638
+ throw new ConfigError3("@nymbalhq/media-s3 exports no createS3ObjectWriter; upgrade it", {
4246
4639
  code: "adapter.package_invalid",
4247
4640
  context: { package: "@nymbalhq/media-s3" }
4248
4641
  });
4249
4642
  }
4250
4643
  return mod.createS3ObjectWriter(options);
4251
4644
  }
4645
+ function outageSubjects(config, platform, adapters) {
4646
+ const subject = (name, provider, adapter) => {
4647
+ if (isNotConfigured(adapter)) return [];
4648
+ if (typeof adapter.healthCheck !== "function") return [{ name }];
4649
+ const check = adapter.healthCheck.bind(adapter);
4650
+ const named = (detail) => detail ? `${provider}: ${detail}` : provider;
4651
+ return [
4652
+ {
4653
+ name,
4654
+ healthCheck: () => Promise.resolve().then(check).then(
4655
+ (report) => report.status === "down" ? { ...report, detail: named(report.detail) } : report,
4656
+ (err) => {
4657
+ throw new Error(named(err instanceof Error ? err.message : String(err)));
4658
+ }
4659
+ )
4660
+ }
4661
+ ];
4662
+ };
4663
+ const { infrastructure } = config;
4664
+ return [
4665
+ ...subject("eventBus", infrastructure.eventBus.provider, platform.eventBus),
4666
+ ...subject("documentStore", infrastructure.documentStore.provider, platform.documentStore),
4667
+ ...subject("media", infrastructure.media.provider, platform.media),
4668
+ ...COMMERCE_SLOTS.filter((slot) => slot !== "ai").flatMap((slot) => {
4669
+ const adapter = adapters[slot];
4670
+ const provider = typeof adapter.providerName === "string" ? adapter.providerName : config.commerce[slot].provider;
4671
+ return subject(slot, provider, adapter);
4672
+ })
4673
+ ];
4674
+ }
4252
4675
  async function createApp(config, options = {}) {
4253
4676
  const logger = scrubbingLogger(
4254
4677
  options.logger ?? createLogger({ base: { store: config.store.name } })
4255
4678
  );
4256
4679
  const adapterLogger = logger.child({ layer: "adapter" });
4257
4680
  checkInjectedAdapters(config, options.adapters);
4681
+ const jwt = resolveAuthSecret(config, process.env);
4682
+ addSecret(jwt.secret);
4683
+ const shadowed = process.env[JWT_SECRET_ENV];
4684
+ if (jwt.source === "config" && shadowed !== void 0 && shadowed !== jwt.secret) {
4685
+ logger.warn(
4686
+ { variable: JWT_SECRET_ENV },
4687
+ `security.auth.jwtSecret in the config is used; ${JWT_SECRET_ENV} is set and ignored`
4688
+ );
4689
+ }
4690
+ if (process.env.NODE_ENV === "production" && jwt.secret.length < 32) {
4691
+ logger.warn(
4692
+ { source: jwt.source },
4693
+ "the JWT secret is shorter than 32 characters; HS256 wants 256 bits (`openssl rand -base64 32`)"
4694
+ );
4695
+ }
4258
4696
  const settings = await loadBootSettings(config, {
4259
4697
  storage: {
4260
4698
  ...options.sqlitePath !== void 0 && { sqlitePath: options.sqlitePath },
@@ -4269,7 +4707,7 @@ async function createApp(config, options = {}) {
4269
4707
  options.adapters,
4270
4708
  settings.values
4271
4709
  );
4272
- refuseUnsafeProduction(config, payments);
4710
+ refuseUnsafeProduction(config, payments, jwt.secret);
4273
4711
  const security = await resolveSecurityAdapter(config, adapterLogger);
4274
4712
  const archive = await eventArchiveWriter(config);
4275
4713
  const primitives = await resolvePrimitives(config, { ...options, logger });
@@ -4297,6 +4735,7 @@ async function createApp(config, options = {}) {
4297
4735
  eventLog: repos.eventLog,
4298
4736
  eventBus: platform.eventBus,
4299
4737
  logger,
4738
+ outage: createOutageProbe(outageSubjects(config, platform, adapters)),
4300
4739
  ...options.relay
4301
4740
  });
4302
4741
  const subscriberBus = deliveringBus(platform.eventBus, relay);
@@ -4320,7 +4759,8 @@ async function createApp(config, options = {}) {
4320
4759
  logger: logger.child({ layer: "service" }),
4321
4760
  payments: adapters.payments,
4322
4761
  searchAdapter: adapters.search,
4323
- email: adapters.email
4762
+ email: adapters.email,
4763
+ jwtSecret: jwt.secret
4324
4764
  });
4325
4765
  await registerHandlers({
4326
4766
  config,
@@ -4329,16 +4769,21 @@ async function createApp(config, options = {}) {
4329
4769
  repos,
4330
4770
  adapters,
4331
4771
  alerts: services.alert,
4772
+ orders: services.order,
4332
4773
  logger
4333
4774
  });
4334
- await rebuild(READ_MODEL_NAMES, {
4335
- config,
4336
- store: platform.commandStore,
4337
- repos,
4338
- documentStore: platform.documentStore,
4339
- search: adapters.search,
4340
- logger
4341
- });
4775
+ const externalSearch = resolveChoice("search", config.commerce.search).kind === "package";
4776
+ await rebuild(
4777
+ externalSearch ? READ_MODEL_NAMES.filter((name) => name !== "search") : READ_MODEL_NAMES,
4778
+ {
4779
+ config,
4780
+ store: platform.commandStore,
4781
+ repos,
4782
+ documentStore: platform.documentStore,
4783
+ search: adapters.search,
4784
+ logger
4785
+ }
4786
+ );
4342
4787
  await relay.drain();
4343
4788
  relay.start();
4344
4789
  const sweepers = [
@@ -4371,7 +4816,7 @@ async function createApp(config, options = {}) {
4371
4816
  relay,
4372
4817
  async attachHttp(adapter, options2 = {}) {
4373
4818
  await adapters.security.applyMiddleware(adapter, config.security);
4374
- const { registerAllRoutes: registerAllRoutes2 } = await import("./register-N2XGSFUF.js");
4819
+ const { registerAllRoutes: registerAllRoutes2 } = await import("./register-SBGUI2L5.js");
4375
4820
  registerAllRoutes2({
4376
4821
  config,
4377
4822
  adapter,
@@ -4382,6 +4827,7 @@ async function createApp(config, options = {}) {
4382
4827
  eventBus: subscriberBus,
4383
4828
  publisher,
4384
4829
  settingsSlots: settings.slots,
4830
+ jwtSecret: jwt.secret,
4385
4831
  adminRoot: options2.adminRoot !== void 0 ? options2.adminRoot : process.env["NYMBAL_ADMIN_DIST"]
4386
4832
  });
4387
4833
  },
@@ -4405,15 +4851,15 @@ async function createApp(config, options = {}) {
4405
4851
  capabilities: adapters.security.capabilities()
4406
4852
  },
4407
4853
  documentStore: {
4408
- provider: config.infrastructure.documentStore,
4854
+ provider: config.infrastructure.documentStore.provider,
4409
4855
  capabilities: platform.documentStore.capabilities()
4410
4856
  },
4411
4857
  eventBus: {
4412
- provider: config.infrastructure.eventBus,
4858
+ provider: config.infrastructure.eventBus.provider,
4413
4859
  capabilities: platform.eventBus.capabilities()
4414
4860
  },
4415
4861
  media: {
4416
- provider: config.infrastructure.media,
4862
+ provider: config.infrastructure.media.provider,
4417
4863
  capabilities: platform.media.capabilities()
4418
4864
  }
4419
4865
  };
@@ -4496,13 +4942,13 @@ function compilePathPattern(pattern) {
4496
4942
  import { existsSync } from "fs";
4497
4943
  import { resolve as resolve3 } from "path";
4498
4944
  import { fileURLToPath } from "url";
4499
- import { nymbalConfigSchema } from "@nymbalhq/config";
4945
+ import { nymbalConfigSchema, slotFolder } from "@nymbalhq/config";
4500
4946
  import {
4501
- boundedHealthCheck,
4947
+ boundedHealthCheck as boundedHealthCheck2,
4502
4948
  connectionSecrets,
4503
4949
  displayUrl,
4504
4950
  errorText as errorText2,
4505
- HEALTH_CHECK_TIMEOUT_MS
4951
+ HEALTH_CHECK_TIMEOUT_MS as HEALTH_CHECK_TIMEOUT_MS3
4506
4952
  } from "@nymbalhq/types";
4507
4953
  var OWN_MIGRATIONS = fileURLToPath(new URL("../migrations", import.meta.url));
4508
4954
  var PRIMITIVES = ["documentStore", "eventBus", "media"];
@@ -4573,29 +5019,32 @@ async function diagnose(input, options = {}) {
4573
5019
  return { checks: [{ name: "config", status: "down", detail }] };
4574
5020
  }
4575
5021
  const config = parsed.data;
4576
- const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS;
5022
+ const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS3;
4577
5023
  const env = options.env ?? process.env;
4578
5024
  const logger = scrubbingLogger(
4579
5025
  options.logger ?? createLogger({ base: { store: config.store.name } })
4580
5026
  );
4581
5027
  const injected = options.adapters ?? {};
4582
5028
  const infrastructure = config.infrastructure;
4583
- const providers = {
4584
- ...Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s].provider])),
5029
+ const choices = {
5030
+ ...Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s]])),
4585
5031
  documentStore: infrastructure.documentStore,
4586
5032
  eventBus: infrastructure.eventBus,
4587
5033
  media: infrastructure.media,
4588
- security: config.security.adapter
5034
+ security: securityChoice(config)
4589
5035
  };
5036
+ const providers = Object.fromEntries(
5037
+ Object.entries(choices).map(([slot, choice]) => [slot, choice.provider])
5038
+ );
4590
5039
  const packages = [];
4591
5040
  for (const slot of [...COMMERCE_SLOTS, ...PRIMITIVES, "security"]) {
4592
- const entry = PROVIDER_PACKAGES[slot]?.[providers[slot]];
4593
- if (entry === void 0) continue;
4594
- const found = await within(timeoutMs, () => importProviderPackage(slot, providers[slot], env));
5041
+ const resolution = resolveChoice(slot, choices[slot]);
5042
+ if (resolution.kind !== "package") continue;
5043
+ const found = await within(timeoutMs, () => importAdapterModule(slot, choices[slot], env));
4595
5044
  packages.push({
4596
- name: `package ${slot}`,
5045
+ name: `package ${slotFolder(slot)}`,
4597
5046
  status: found.ok ? "ok" : "down",
4598
- detail: found.ok ? entry.package : found.detail
5047
+ detail: found.ok ? resolution.package : found.detail
4599
5048
  });
4600
5049
  }
4601
5050
  const closers = [];
@@ -4673,7 +5122,7 @@ async function diagnose(input, options = {}) {
4673
5122
  const built = {};
4674
5123
  const primitiveFailures = {};
4675
5124
  let documentStore;
4676
- if (infrastructure.documentStore === "postgres-jsonb" && commandStore === void 0) {
5125
+ if (infrastructure.documentStore.provider === "postgres-jsonb" && commandStore === void 0) {
4677
5126
  primitiveFailures.documentStore = notChecked("command store");
4678
5127
  } else {
4679
5128
  const store = await within(
@@ -4708,13 +5157,13 @@ async function diagnose(input, options = {}) {
4708
5157
  return Promise.resolve({ status: "degraded", detail: "no healthCheck" });
4709
5158
  }
4710
5159
  const check = subject2.healthCheck.bind(subject2);
4711
- return boundedHealthCheck(() => check(), { timeoutMs });
5160
+ return boundedHealthCheck2(() => check(), { timeoutMs });
4712
5161
  };
4713
5162
  const stored = commandStore === void 0 ? { ok: true, value: [] } : await within(timeoutMs, () => listStoredSettings(commandStore));
4714
5163
  const settingsOf = async (slot) => {
4715
5164
  const provider = providers[slot];
4716
5165
  if (provider === "custom") return [];
4717
- const declared = declaredSettings(await importProviderPackage(slot, provider, env));
5166
+ const declared = declaredSettings(await importAdapterModule(slot, choices[slot], env));
4718
5167
  if (declared.length === 0) return [];
4719
5168
  if (!stored.ok) throw new Error(`settings not read: ${stored.detail}`);
4720
5169
  return settingValues(config, [{ slot, provider, declared }], stored.value, env, logger);
@@ -4766,12 +5215,14 @@ async function diagnose(input, options = {}) {
4766
5215
  const primitive = built[name];
4767
5216
  if (primitive === void 0) {
4768
5217
  primitives.push({
4769
- name: `primitive ${name}`,
5218
+ name: `primitive ${slotFolder(name)}`,
4770
5219
  status: "down",
4771
5220
  detail: primitiveFailures[name] ?? ""
4772
5221
  });
4773
5222
  } else {
4774
- primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)));
5223
+ primitives.push(
5224
+ fromReport(`primitive ${slotFolder(name)}`, subject(name), await health(primitive))
5225
+ );
4775
5226
  }
4776
5227
  }
4777
5228
  const eventsCheck = commandStore === void 0 ? { name: "events", status: "down", detail: notChecked("command store") } : migrationsCheck.status !== "ok" ? { name: "events", status: "down", detail: notChecked("migrations") } : await eventLogCheck(commandStore, timeoutMs);
@@ -4825,7 +5276,7 @@ function fromReport(name, what, report) {
4825
5276
  }
4826
5277
 
4827
5278
  // src/seed/run.ts
4828
- import { inArray as inArray4 } from "drizzle-orm";
5279
+ import { inArray as inArray5 } from "drizzle-orm";
4829
5280
  import { v7 as uuidv74 } from "uuid";
4830
5281
  import bcrypt from "bcryptjs";
4831
5282
  import { EVT_CATEGORY_CREATED as EVT_CATEGORY_CREATED3, EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED3, EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3 } from "@nymbalhq/types";
@@ -4945,13 +5396,13 @@ async function demoRowsPresent(store, emails) {
4945
5396
  const clients = rawClients(store);
4946
5397
  if (clients.kind === "sqlite") {
4947
5398
  const { categories: categories4, products: products4, customers: customers5 } = sqlite_exports;
4948
- return clients.db.select({ id: categories4.id }).from(categories4).where(inArray4(categories4.slug, categorySlugs)).limit(1).all().length > 0 || clients.db.select({ id: products4.id }).from(products4).where(inArray4(products4.slug, productSlugs)).limit(1).all().length > 0 || clients.db.select({ id: customers5.id }).from(customers5).where(inArray4(customers5.email, emails)).limit(1).all().length > 0;
5399
+ return clients.db.select({ id: categories4.id }).from(categories4).where(inArray5(categories4.slug, categorySlugs)).limit(1).all().length > 0 || clients.db.select({ id: products4.id }).from(products4).where(inArray5(products4.slug, productSlugs)).limit(1).all().length > 0 || clients.db.select({ id: customers5.id }).from(customers5).where(inArray5(customers5.email, emails)).limit(1).all().length > 0;
4949
5400
  }
4950
5401
  const { categories: categories3, products: products3, customers: customers4 } = postgres_exports;
4951
5402
  const [category, product, customer] = await Promise.all([
4952
- clients.db.select({ id: categories3.id }).from(categories3).where(inArray4(categories3.slug, categorySlugs)).limit(1),
4953
- clients.db.select({ id: products3.id }).from(products3).where(inArray4(products3.slug, productSlugs)).limit(1),
4954
- clients.db.select({ id: customers4.id }).from(customers4).where(inArray4(customers4.email, emails)).limit(1)
5403
+ clients.db.select({ id: categories3.id }).from(categories3).where(inArray5(categories3.slug, categorySlugs)).limit(1),
5404
+ clients.db.select({ id: products3.id }).from(products3).where(inArray5(products3.slug, productSlugs)).limit(1),
5405
+ clients.db.select({ id: customers4.id }).from(customers4).where(inArray5(customers4.email, emails)).limit(1)
4955
5406
  ]);
4956
5407
  return category.length > 0 || product.length > 0 || customer.length > 0;
4957
5408
  }
@@ -5224,7 +5675,8 @@ async function openReadModels(config, options) {
5224
5675
  try {
5225
5676
  const documentStore = await buildDocumentStore(config, { ...storage, logger, env }, logger, env);
5226
5677
  closers.push(() => documentStore.close());
5227
- if (config.infrastructure.documentStore === "postgres-jsonb") await documentStore.initialize?.();
5678
+ if (config.infrastructure.documentStore.provider === "postgres-jsonb")
5679
+ await documentStore.initialize?.();
5228
5680
  const repos = buildRepositories(store, documentStore);
5229
5681
  const search2 = await slotBuilders({
5230
5682
  config,
@@ -5247,7 +5699,6 @@ export {
5247
5699
  InMemoryDocumentStore,
5248
5700
  InProcessEventBus,
5249
5701
  LOCAL_FS_MEDIA_CAPABILITIES,
5250
- PROVIDER_PACKAGES,
5251
5702
  PROVIDER_REFUND_REASON,
5252
5703
  READ_MODELS,
5253
5704
  READ_MODEL_NAMES,
@@ -5265,6 +5716,7 @@ export {
5265
5716
  buildRepositories,
5266
5717
  buildSecurityHeaders,
5267
5718
  buildServices,
5719
+ checkAdapterModule,
5268
5720
  createAlertService,
5269
5721
  createAlertSubscriptionRepository,
5270
5722
  createApp,
@@ -5278,6 +5730,7 @@ export {
5278
5730
  createCommandStore,
5279
5731
  createCustomerRepository,
5280
5732
  createCustomerService,
5733
+ createEmailSuppressionRepository,
5281
5734
  createEventBuilder,
5282
5735
  createEventLogRepository,
5283
5736
  createEventPublisher,
@@ -5301,6 +5754,7 @@ export {
5301
5754
  createOrderRepository,
5302
5755
  createOrderSequenceRepository,
5303
5756
  createOrderService,
5757
+ createOrderShipmentRepository,
5304
5758
  createPlatform,
5305
5759
  createProcessedEventRepository,
5306
5760
  createProductCategoryRepository,
@@ -5317,6 +5771,7 @@ export {
5317
5771
  createVariantRepository,
5318
5772
  currentActor,
5319
5773
  currentCorrelationId,
5774
+ declaredSettings,
5320
5775
  decrypt,
5321
5776
  diagnose,
5322
5777
  diffReadModel,
@@ -5325,13 +5780,15 @@ export {
5325
5780
  encrypt,
5326
5781
  fillFromSettings,
5327
5782
  findAppliedByKey,
5328
- importProviderPackage,
5783
+ importAdapterModule,
5329
5784
  installLine,
5330
5785
  isMissingSettingsTable,
5331
5786
  isValidCorrelationId,
5332
5787
  keyId,
5333
5788
  keyProblem,
5334
5789
  listAuditEntries,
5790
+ migrationState,
5791
+ missingPackage,
5335
5792
  newAlertToken,
5336
5793
  newCorrelationId,
5337
5794
  openReadModels,
@@ -5346,6 +5803,8 @@ export {
5346
5803
  registerAlertRoutes,
5347
5804
  registerAllRoutes,
5348
5805
  registerHandlers,
5806
+ resolveAuthSecret,
5807
+ resolveChoice,
5349
5808
  resolvePrimitives,
5350
5809
  routeSchemas,
5351
5810
  runAsActor,