@nymbalhq/platform 0.2.0 → 1.1.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.
package/dist/index.js CHANGED
@@ -44,13 +44,103 @@ import {
44
44
  registerAllRoutes,
45
45
  routeSchemas,
46
46
  settlementOf
47
- } from "./chunk-74KODSYJ.js";
47
+ } from "./chunk-2GFZHF5W.js";
48
48
  import "./chunk-PZ5AY32C.js";
49
49
 
50
+ // src/platform.ts
51
+ import { join as join4 } from "path";
52
+ import {
53
+ ConfigError as ConfigError3
54
+ } from "@nymbalhq/types";
55
+
56
+ // src/adapters/loader.ts
57
+ import { existsSync } from "fs";
58
+ import { join } from "path";
59
+ import { ConfigError } from "@nymbalhq/types";
60
+ var PROVIDER_PACKAGES = {
61
+ payments: { stripe: { package: "@nymbalhq/adapter-stripe", sdk: "stripe" } },
62
+ ai: { anthropic: { package: "@nymbalhq/adapter-anthropic", sdk: "@anthropic-ai/sdk" } },
63
+ email: { smtp: { package: "@nymbalhq/adapter-smtp", sdk: "nodemailer" } },
64
+ documentStore: {
65
+ redis: { package: "@nymbalhq/doc-store-redis", sdk: "ioredis" },
66
+ "postgres-jsonb": { package: "@nymbalhq/doc-store-postgres-jsonb", sdk: "pg" }
67
+ },
68
+ eventBus: {
69
+ "redis-streams": { package: "@nymbalhq/event-bus-redis-streams", sdk: "ioredis" }
70
+ },
71
+ media: { s3: { package: "@nymbalhq/media-s3", sdk: "@aws-sdk/client-s3" } }
72
+ };
73
+ var INFRASTRUCTURE_SLOTS = /* @__PURE__ */ new Set(["documentStore", "eventBus", "media"]);
74
+ function choiceOf(slot, provider) {
75
+ return INFRASTRUCTURE_SLOTS.has(slot) ? `infrastructure.${slot} '${provider}'` : `${slot}.provider '${provider}'`;
76
+ }
77
+ var INSTALL_VERBS = {
78
+ npm: "npm install",
79
+ pnpm: "pnpm add",
80
+ yarn: "yarn add",
81
+ bun: "bun add"
82
+ };
83
+ var LOCKFILES = [
84
+ ["pnpm-lock.yaml", "pnpm"],
85
+ ["yarn.lock", "yarn"],
86
+ ["bun.lock", "bun"],
87
+ ["bun.lockb", "bun"],
88
+ ["package-lock.json", "npm"]
89
+ ];
90
+ function packageManager(env, cwd) {
91
+ const agent = env["npm_config_user_agent"]?.split("/")[0];
92
+ if (agent !== void 0 && agent in INSTALL_VERBS) return agent;
93
+ for (const [file, pm] of LOCKFILES) {
94
+ if (existsSync(join(cwd, file))) return pm;
95
+ }
96
+ return "npm";
97
+ }
98
+ function installLine(packages, env, cwd) {
99
+ return [INSTALL_VERBS[packageManager(env, cwd)], ...packages].join(" ");
100
+ }
101
+ function packageOf(specifier) {
102
+ const parts = specifier.split("/");
103
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
104
+ }
105
+ function missingPackage(error) {
106
+ if (error?.code !== "ERR_MODULE_NOT_FOUND") return null;
107
+ const match = /Cannot find (?:package|module) '([^']+)'/.exec(String(error.message));
108
+ return match?.[1] === void 0 ? null : packageOf(match[1]);
109
+ }
110
+ async function importProviderPackage(slot, provider, env) {
111
+ const entry = PROVIDER_PACKAGES[slot]?.[provider];
112
+ if (entry === void 0) return void 0;
113
+ let mod;
114
+ try {
115
+ mod = await import(entry.package);
116
+ } catch (error) {
117
+ const missing = missingPackage(error);
118
+ if (missing !== entry.package && missing !== entry.sdk) throw error;
119
+ const install = installLine([entry.package, entry.sdk], env, process.cwd());
120
+ throw new ConfigError(`${choiceOf(slot, provider)} needs ${entry.package}: ${install}`, {
121
+ code: "adapter.package_missing",
122
+ cause: error,
123
+ context: { slot, provider, missing, install }
124
+ });
125
+ }
126
+ if (typeof mod.createAdapter !== "function") {
127
+ throw new ConfigError(`${entry.package} exports no createAdapter(ctx)`, {
128
+ code: "adapter.package_invalid",
129
+ context: { slot, provider, package: entry.package }
130
+ });
131
+ }
132
+ return mod;
133
+ }
134
+ async function loadProviderAdapter(slot, provider, ctx) {
135
+ const mod = await importProviderPackage(slot, provider, ctx.env);
136
+ if (mod === void 0) return void 0;
137
+ return await mod.createAdapter({ ...ctx, slot });
138
+ }
139
+
50
140
  // src/db/command-store.ts
51
141
  import { AsyncLocalStorage } from "async_hooks";
52
142
  import { envOptional } from "@nymbalhq/config";
53
- import { AdapterError, ConfigError } from "@nymbalhq/types";
143
+ import { AdapterError, ConfigError as ConfigError2 } from "@nymbalhq/types";
54
144
  import BetterSqlite3 from "better-sqlite3";
55
145
  import pg from "pg";
56
146
  import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3";
@@ -79,6 +169,11 @@ var Scope = class {
79
169
  };
80
170
  var context = new AsyncLocalStorage();
81
171
  var rawByStore = /* @__PURE__ */ new WeakMap();
172
+ var turnByRaw = /* @__PURE__ */ new WeakMap();
173
+ async function sqliteTurn(raw, fn) {
174
+ const turn = turnByRaw.get(raw);
175
+ return turn === void 0 ? fn() : turn(fn);
176
+ }
82
177
  function liveScope(tx) {
83
178
  if (!(tx instanceof Scope)) {
84
179
  throw new TypeError("expected a handle from CommandStore.read or CommandStore.transaction");
@@ -115,7 +210,7 @@ function joinable(owner) {
115
210
  const scope = context.getStore();
116
211
  return scope !== void 0 && scope.owner === owner && !scope.settled ? scope : void 0;
117
212
  }
118
- async function join(scope, fn) {
213
+ async function join2(scope, fn) {
119
214
  if (!scope.writable) {
120
215
  throw new Error(
121
216
  "CommandStore.transaction() was called inside CommandStore.read(); open the transaction first"
@@ -217,8 +312,8 @@ function createQueue() {
217
312
  async acquire() {
218
313
  const previous = tail;
219
314
  let release;
220
- tail = new Promise((resolve2) => {
221
- release = resolve2;
315
+ tail = new Promise((resolve4) => {
316
+ release = resolve4;
222
317
  });
223
318
  await previous;
224
319
  return release;
@@ -239,18 +334,23 @@ async function beginImmediate(raw) {
239
334
  throw error;
240
335
  }
241
336
  }
242
- await new Promise((resolve2) => setTimeout(resolve2, pauseMs));
337
+ await new Promise((resolve4) => setTimeout(resolve4, pauseMs));
243
338
  }
244
339
  } finally {
245
340
  raw.pragma(`busy_timeout = ${SQLITE_BUSY_WAIT_MS}`);
246
341
  }
247
342
  }
343
+ function sqliteFile(options = {}) {
344
+ return options.sqlitePath ?? envOptional("NYMBAL_SQLITE_PATH") ?? "./nymbal.db";
345
+ }
248
346
  function createCommandStore(config, options = {}) {
249
347
  if (config.infrastructure.commandStore === "sqlite") {
250
- const path = options.sqlitePath ?? envOptional("NYMBAL_SQLITE_PATH") ?? "./nymbal.db";
251
- const raw = new BetterSqlite3(path);
252
- raw.pragma("journal_mode = WAL");
253
- raw.pragma("foreign_keys = ON");
348
+ const path = sqliteFile(options);
349
+ const raw = options.readOnly ? new BetterSqlite3(path, { readonly: true, fileMustExist: true }) : new BetterSqlite3(path);
350
+ if (!options.readOnly) {
351
+ raw.pragma("journal_mode = WAL");
352
+ raw.pragma("foreign_keys = ON");
353
+ }
254
354
  const db = drizzleSqlite(raw, { schema: sqlite_exports });
255
355
  const client = { kind: "sqlite", db };
256
356
  const queue = createQueue();
@@ -264,7 +364,7 @@ function createCommandStore(config, options = {}) {
264
364
  },
265
365
  async transaction(fn) {
266
366
  const scope = joinable(owner);
267
- if (scope !== void 0) return join(scope, fn);
367
+ if (scope !== void 0) return join2(scope, fn);
268
368
  const release = await queue.acquire();
269
369
  return runTransaction(
270
370
  owner,
@@ -294,17 +394,29 @@ function createCommandStore(config, options = {}) {
294
394
  }
295
395
  };
296
396
  rawByStore.set(store, { kind: "sqlite", db, raw });
397
+ turnByRaw.set(raw, async (fn) => {
398
+ if (joinable(owner) !== void 0) return fn();
399
+ const release = await queue.acquire();
400
+ try {
401
+ return fn();
402
+ } finally {
403
+ release();
404
+ }
405
+ });
297
406
  return store;
298
407
  }
299
408
  if (config.infrastructure.commandStore === "postgres") {
300
409
  const connectionString = options.postgresUrl ?? envOptional("DATABASE_URL");
301
410
  if (!connectionString) {
302
- throw new ConfigError(
411
+ throw new ConfigError2(
303
412
  "commandStore=postgres requires DATABASE_URL to be set (or pass postgresUrl option).",
304
413
  { context: { commandStore: "postgres" } }
305
414
  );
306
415
  }
307
- const pool = new pg.Pool({ connectionString });
416
+ const pool = new pg.Pool({
417
+ connectionString,
418
+ ...options.readOnly && { options: "-c default_transaction_read_only=on" }
419
+ });
308
420
  const db = drizzlePg(pool, { schema: postgres_exports });
309
421
  const owner = {};
310
422
  const connect = async () => {
@@ -324,7 +436,7 @@ function createCommandStore(config, options = {}) {
324
436
  },
325
437
  async transaction(fn) {
326
438
  const scope = joinable(owner);
327
- if (scope !== void 0) return join(scope, fn);
439
+ if (scope !== void 0) return join2(scope, fn);
328
440
  const { client, connection } = await connect();
329
441
  return runTransaction(
330
442
  owner,
@@ -367,16 +479,13 @@ function createCommandStore(config, options = {}) {
367
479
  rawByStore.set(store, { kind: "postgres", db, pool });
368
480
  return store;
369
481
  }
370
- throw new ConfigError(`Unsupported commandStore: ${String(config.infrastructure.commandStore)}`, {
482
+ throw new ConfigError2(`Unsupported commandStore: ${String(config.infrastructure.commandStore)}`, {
371
483
  context: { commandStore: config.infrastructure.commandStore }
372
484
  });
373
485
  }
374
486
 
375
- // src/document-store/factory.ts
376
- import { ConfigError as ConfigError2 } from "@nymbalhq/types";
377
-
378
487
  // src/document-store/in-memory.ts
379
- import { AdapterError as AdapterError2, ValidationError } from "@nymbalhq/types";
488
+ import { AdapterError as AdapterError2, queryDocuments } from "@nymbalhq/types";
380
489
  var InMemoryDocumentStore = class {
381
490
  #data = /* @__PURE__ */ new Map();
382
491
  #now;
@@ -391,6 +500,13 @@ var InMemoryDocumentStore = class {
391
500
  this.#sweepTimer = null;
392
501
  }
393
502
  }
503
+ capabilities() {
504
+ return ["get", "put", "delete", "query", "batch", "ttl", "conditional-put"];
505
+ }
506
+ /** The process's own memory: healthy whenever it can answer. */
507
+ async healthCheck() {
508
+ return { status: "healthy" };
509
+ }
394
510
  async get(collection, key) {
395
511
  const entry = this.#data.get(collection)?.get(key);
396
512
  if (!entry) return null;
@@ -437,37 +553,11 @@ var InMemoryDocumentStore = class {
437
553
  async query(collection, params) {
438
554
  const bucket = this.#data.get(collection);
439
555
  if (!bucket) return { items: [], nextCursor: null };
440
- const ascending = params.ascending ?? true;
441
- const limit = params.limit ?? 50;
442
- const decodedCursor = params.cursor ? decodeCursor(params.cursor) : null;
443
- const matches = [];
556
+ const live = [];
444
557
  for (const [key, entry] of bucket) {
445
- if (this.#isExpired(entry)) continue;
446
- const doc = entry.doc;
447
- const partition = params.partitionKey;
448
- if (partition.value !== "*" && doc[partition.field] !== partition.value) continue;
449
- if (params.sortKey) {
450
- const value = doc[params.sortKey.field];
451
- if (!sortKeyMatches(value, params.sortKey.operator, params.sortKey.value)) continue;
452
- }
453
- matches.push({ key, doc });
454
- }
455
- if (params.orderBy) return orderedPage(matches, params.orderBy, params, limit);
456
- const sortField = params.sortKey?.field;
457
- matches.sort((a, b) => {
458
- const aKey = sortField ? a.doc[sortField] : a.key;
459
- const bKey = sortField ? b.doc[sortField] : b.key;
460
- const cmp = compare(aKey, bKey);
461
- return ascending ? cmp : -cmp;
462
- });
463
- let start = 0;
464
- if (decodedCursor) {
465
- const idx = matches.findIndex((m) => m.key === decodedCursor);
466
- start = idx >= 0 ? idx + 1 : 0;
558
+ if (!this.#isExpired(entry)) live.push([key, entry.doc]);
467
559
  }
468
- const page = matches.slice(start, start + limit);
469
- const nextCursor = start + limit < matches.length && page.length > 0 ? encodeCursor(page[page.length - 1].key) : null;
470
- return { items: page.map((m) => m.doc), nextCursor };
560
+ return queryDocuments(live, params);
471
561
  }
472
562
  async batchGet(collection, keys) {
473
563
  const result = /* @__PURE__ */ new Map();
@@ -508,130 +598,23 @@ var InMemoryDocumentStore = class {
508
598
  }
509
599
  }
510
600
  };
511
- function sortKeyMatches(value, operator, target) {
512
- switch (operator) {
513
- case "eq":
514
- return value === target;
515
- case "gt":
516
- return compare(value, target) > 0;
517
- case "lt":
518
- return compare(value, target) < 0;
519
- case "between": {
520
- if (!Array.isArray(target) || target.length !== 2) return false;
521
- const [low, high] = target;
522
- return compare(value, low) >= 0 && compare(value, high) <= 0;
523
- }
524
- }
525
- }
526
- function compare(a, b) {
527
- if (a === b) return 0;
528
- if (a === null || a === void 0) return -1;
529
- if (b === null || b === void 0) return 1;
530
- if (typeof a === "number" && typeof b === "number") return a - b;
531
- return String(a) < String(b) ? -1 : 1;
532
- }
533
- function orderedPage(matches, orderBy, params, limit) {
534
- const order = JSON.stringify([
535
- orderBy.field,
536
- orderBy.direction,
537
- orderBy.nulls ?? null,
538
- params.partitionKey
539
- ]);
540
- const positions = matches.map((m) => ({
541
- position: { key: m.key, value: valueAt(m.doc, orderBy.field) },
542
- doc: m.doc
543
- }));
544
- positions.sort((a, b) => compareOrdered(a.position, b.position, orderBy));
545
- let start = 0;
546
- if (params.cursor) {
547
- const after = decodeOrderedCursor(params.cursor, order);
548
- const idx = positions.findIndex((p) => compareOrdered(p.position, after, orderBy) > 0);
549
- start = idx >= 0 ? idx : positions.length;
550
- }
551
- const page = positions.slice(start, start + limit);
552
- const last = page[page.length - 1];
553
- const nextCursor = start + limit < positions.length && last !== void 0 ? Buffer.from(
554
- JSON.stringify({ o: order, k: last.position.key, v: last.position.value }),
555
- "utf8"
556
- ).toString("base64url") : null;
557
- return { items: page.map((p) => p.doc), nextCursor };
558
- }
559
- function decodeOrderedCursor(cursor, order) {
560
- let decoded;
561
- try {
562
- decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
563
- } catch {
564
- decoded = null;
565
- }
566
- const c = decoded;
567
- if (c === null || typeof c !== "object" || typeof c.k !== "string" || !("v" in c)) {
568
- throw new ValidationError("The cursor is not valid", { context: { cursor } });
569
- }
570
- if (c.o !== order) {
571
- throw new ValidationError("The cursor was issued under another order", { context: { cursor } });
572
- }
573
- return { key: c.k, value: c.v };
574
- }
575
- function valueAt(doc, path) {
576
- let value = doc;
577
- for (const part of path.split(".")) {
578
- if (value === null || typeof value !== "object") return null;
579
- value = value[part];
580
- }
581
- return value ?? null;
582
- }
583
- var collator = new Intl.Collator(void 0, { sensitivity: "base" });
584
- function compareOrdered(a, b, orderBy) {
585
- const aNull = a.value === null;
586
- const bNull = b.value === null;
587
- let c = 0;
588
- if (orderBy.nulls === "last" && aNull !== bNull) return aNull ? 1 : -1;
589
- if (typeof a.value === "string" && typeof b.value === "string")
590
- c = collator.compare(a.value, b.value);
591
- else c = compare(a.value, b.value);
592
- if (orderBy.direction === "desc") c = -c;
593
- if (c !== 0) return c;
594
- return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
595
- }
596
- function encodeCursor(key) {
597
- return Buffer.from(key, "utf8").toString("base64url");
598
- }
599
- function decodeCursor(cursor) {
600
- return Buffer.from(cursor, "base64url").toString("utf8");
601
- }
602
-
603
- // src/document-store/factory.ts
604
- function createDocumentStore(config) {
605
- switch (config.infrastructure.documentStore) {
606
- case "in-memory":
607
- return new InMemoryDocumentStore();
608
- case "dynamodb":
609
- case "firestore":
610
- case "cosmosdb":
611
- case "postgres-jsonb":
612
- throw new ConfigError2(
613
- `documentStore=${config.infrastructure.documentStore} is planned for v1.0 and not yet implemented.`,
614
- { context: { documentStore: config.infrastructure.documentStore } }
615
- );
616
- default: {
617
- const exhaustive = config.infrastructure.documentStore;
618
- throw new ConfigError2(`Unknown documentStore: ${String(exhaustive)}`);
619
- }
620
- }
621
- }
622
-
623
- // src/event-bus/factory.ts
624
- import { ConfigError as ConfigError3 } from "@nymbalhq/types";
625
601
 
626
602
  // src/event-bus/in-process.ts
627
603
  import { v7 as uuidv7 } from "uuid";
628
- import { ValidationError as ValidationError2 } from "@nymbalhq/types";
604
+ import { ValidationError } from "@nymbalhq/types";
629
605
  var InProcessEventBus = class {
630
606
  #registrations = /* @__PURE__ */ new Map();
631
607
  #logger;
632
608
  constructor(options = {}) {
633
609
  this.#logger = options.logger;
634
610
  }
611
+ capabilities() {
612
+ return ["publish", "subscribe", "wildcard", "replay"];
613
+ }
614
+ /** Delivery within the process: healthy whenever it can answer. */
615
+ async healthCheck() {
616
+ return { status: "healthy" };
617
+ }
635
618
  async publish(event) {
636
619
  await this.#deliver(event, () => true);
637
620
  }
@@ -686,12 +669,12 @@ var InProcessEventBus = class {
686
669
  }
687
670
  #validate(event) {
688
671
  if (!event.id || !event.type || !event.timestamp || !event.source) {
689
- throw new ValidationError2("Event is missing required envelope fields", {
672
+ throw new ValidationError("Event is missing required envelope fields", {
690
673
  context: { event }
691
674
  });
692
675
  }
693
676
  if (!event.metadata || !event.metadata.storeId || !event.metadata.environment) {
694
- throw new ValidationError2("Event metadata is missing required fields", {
677
+ throw new ValidationError("Event metadata is missing required fields", {
695
678
  context: { event }
696
679
  });
697
680
  }
@@ -702,26 +685,6 @@ function compilePattern(pattern) {
702
685
  return new RegExp(`^${escaped}$`);
703
686
  }
704
687
 
705
- // src/event-bus/factory.ts
706
- function createEventBus(config, logger) {
707
- switch (config.infrastructure.eventBus) {
708
- case "in-process":
709
- return new InProcessEventBus(logger ? { logger } : {});
710
- case "eventbridge":
711
- case "pubsub":
712
- case "service-bus":
713
- case "redis-streams":
714
- throw new ConfigError3(
715
- `eventBus=${config.infrastructure.eventBus} is planned for v1.0 and not yet implemented.`,
716
- { context: { eventBus: config.infrastructure.eventBus } }
717
- );
718
- default: {
719
- const exhaustive = config.infrastructure.eventBus;
720
- throw new ConfigError3(`Unknown eventBus: ${String(exhaustive)}`);
721
- }
722
- }
723
- }
724
-
725
688
  // src/logger.ts
726
689
  import { pino } from "pino";
727
690
  function createLogger(options = {}) {
@@ -750,8 +713,198 @@ function wrap(p) {
750
713
  };
751
714
  }
752
715
 
716
+ // src/media/local-fs-storage.ts
717
+ import { constants } from "fs";
718
+ import { access, mkdir, writeFile } from "fs/promises";
719
+ import { dirname, join as join3, resolve } from "path";
720
+ var LOCAL_FS_MEDIA_CAPABILITIES = ["put"];
721
+ async function nearestExisting(root) {
722
+ let dir = resolve(root);
723
+ for (; ; ) {
724
+ try {
725
+ await access(dir, constants.F_OK);
726
+ return dir;
727
+ } catch {
728
+ const parent = dirname(dir);
729
+ if (parent === dir) return dir;
730
+ dir = parent;
731
+ }
732
+ }
733
+ }
734
+ function createLocalFsMediaStorage(options) {
735
+ const { root } = options;
736
+ const urlPrefix = options.urlPrefix ?? "/imported-media";
737
+ return {
738
+ capabilities: () => LOCAL_FS_MEDIA_CAPABILITIES,
739
+ async put(key, body, _contentType) {
740
+ const dest = join3(root, key);
741
+ const dir = dest.substring(0, dest.lastIndexOf("/"));
742
+ await mkdir(dir, { recursive: true });
743
+ await writeFile(dest, body);
744
+ return { url: `${urlPrefix}/${key}` };
745
+ },
746
+ // Permission is read with access(2), never probed by writing a file.
747
+ async healthCheck() {
748
+ const dir = await nearestExisting(root);
749
+ try {
750
+ await access(dir, constants.W_OK);
751
+ return { status: "healthy", detail: root };
752
+ } catch {
753
+ return { status: "down", detail: `${dir} is not writable` };
754
+ }
755
+ }
756
+ };
757
+ }
758
+
753
759
  // src/platform.ts
754
- function createPlatform(config, options = {}) {
760
+ var REDIS_DEFAULTS = {
761
+ prefix: "nymbal",
762
+ ackTimeoutMs: 15e3,
763
+ claimIdleMs: 5e3,
764
+ streamMaxLen: 1e4
765
+ };
766
+ var S3_DEFAULT_REGION = "us-east-1";
767
+ var JSONB_PREFIX = "nymbal";
768
+ function nonEmpty(value) {
769
+ return value === void 0 || value === "" ? void 0 : value;
770
+ }
771
+ function redisUrlOf(config, env) {
772
+ return config.infrastructure.redis?.url ?? nonEmpty(env["REDIS_URL"]);
773
+ }
774
+ function redisConnection(config, env, slot) {
775
+ const block = config.infrastructure.redis ?? {};
776
+ const url = redisUrlOf(config, env);
777
+ if (url === void 0) {
778
+ throw new ConfigError3(
779
+ `infrastructure.${slot} needs a Redis server: set infrastructure.redis.url or REDIS_URL`,
780
+ { code: "config.redis_url_missing", context: { slot } }
781
+ );
782
+ }
783
+ return {
784
+ url,
785
+ prefix: block.prefix ?? nonEmpty(env["NYMBAL_REDIS_PREFIX"]) ?? REDIS_DEFAULTS.prefix,
786
+ ackTimeoutMs: block.ackTimeoutMs ?? REDIS_DEFAULTS.ackTimeoutMs,
787
+ claimIdleMs: block.claimIdleMs ?? REDIS_DEFAULTS.claimIdleMs,
788
+ streamMaxLen: block.streamMaxLen ?? REDIS_DEFAULTS.streamMaxLen
789
+ };
790
+ }
791
+ function s3Connection(config, env) {
792
+ const block = config.infrastructure.s3 ?? {};
793
+ const bucket = nonEmpty(block.bucket) ?? nonEmpty(env["S3_BUCKET"]);
794
+ if (bucket === void 0) {
795
+ throw new ConfigError3(
796
+ "infrastructure.media 's3' needs a bucket: set infrastructure.s3.bucket or S3_BUCKET",
797
+ { code: "config.s3_bucket_missing", context: { slot: "media" } }
798
+ );
799
+ }
800
+ const endpoint = nonEmpty(block.endpoint) ?? nonEmpty(env["S3_ENDPOINT"]);
801
+ const publicUrl = nonEmpty(block.publicUrl) ?? nonEmpty(env["S3_PUBLIC_URL"]);
802
+ return {
803
+ bucket,
804
+ region: nonEmpty(block.region) ?? nonEmpty(env["AWS_REGION"]) ?? S3_DEFAULT_REGION,
805
+ prefix: block.prefix ?? nonEmpty(env["NYMBAL_S3_PREFIX"]) ?? "",
806
+ forcePathStyle: block.forcePathStyle ?? endpoint !== void 0,
807
+ ...endpoint !== void 0 && { endpoint },
808
+ ...publicUrl !== void 0 && { publicUrl }
809
+ };
810
+ }
811
+ async function loadPrimitive(slot, provider, config, logger, env) {
812
+ const instance = await loadProviderAdapter(slot, provider, {
813
+ config,
814
+ logger: logger.child({ primitive: slot }),
815
+ env
816
+ });
817
+ if (instance === void 0) {
818
+ throw new ConfigError3(`infrastructure.${slot} '${provider}' has no implementation`, {
819
+ context: { slot, provider }
820
+ });
821
+ }
822
+ return instance;
823
+ }
824
+ async function buildDocumentStore(config, options, logger, env) {
825
+ const choice = config.infrastructure.documentStore;
826
+ switch (choice) {
827
+ case "in-memory":
828
+ return new InMemoryDocumentStore();
829
+ case "redis": {
830
+ const { url, prefix } = redisConnection(config, env, "documentStore");
831
+ return loadPrimitive("documentStore", choice, { url, prefix }, logger, env);
832
+ }
833
+ case "postgres-jsonb": {
834
+ const postgresUrl = options.postgresUrl ?? nonEmpty(env["DATABASE_URL"]);
835
+ if (postgresUrl === void 0) {
836
+ throw new ConfigError3(
837
+ "documentStore 'postgres-jsonb' uses the command store's Postgres: set DATABASE_URL (or pass postgresUrl)",
838
+ { code: "config.postgres_url_missing", context: { slot: "documentStore" } }
839
+ );
840
+ }
841
+ return loadPrimitive(
842
+ "documentStore",
843
+ choice,
844
+ { postgresUrl, prefix: JSONB_PREFIX },
845
+ logger,
846
+ env
847
+ );
848
+ }
849
+ default: {
850
+ const exhaustive = choice;
851
+ throw new ConfigError3(`Unknown documentStore: ${String(exhaustive)}`);
852
+ }
853
+ }
854
+ }
855
+ async function buildEventBus(config, logger, env) {
856
+ const choice = config.infrastructure.eventBus;
857
+ switch (choice) {
858
+ case "in-process":
859
+ return new InProcessEventBus({ logger });
860
+ case "redis-streams":
861
+ return loadPrimitive(
862
+ "eventBus",
863
+ choice,
864
+ redisConnection(config, env, "eventBus"),
865
+ logger,
866
+ env
867
+ );
868
+ default: {
869
+ const exhaustive = choice;
870
+ throw new ConfigError3(`Unknown eventBus: ${String(exhaustive)}`);
871
+ }
872
+ }
873
+ }
874
+ async function buildMedia(config, options, logger, env) {
875
+ const choice = config.infrastructure.media;
876
+ switch (choice) {
877
+ case "local-fs":
878
+ return createLocalFsMediaStorage({
879
+ root: options.mediaRoot ?? join4(process.cwd(), "public", "imported-media"),
880
+ urlPrefix: "/imported-media"
881
+ });
882
+ case "s3":
883
+ return loadPrimitive("media", choice, s3Connection(config, env), logger, env);
884
+ default: {
885
+ const exhaustive = choice;
886
+ throw new ConfigError3(`Unknown media: ${String(exhaustive)}`);
887
+ }
888
+ }
889
+ }
890
+ async function resolvePrimitives(config, options = {}) {
891
+ const env = options.env ?? process.env;
892
+ const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
893
+ if (config.infrastructure.media === "s3") s3Connection(config, env);
894
+ if (config.infrastructure.documentStore === "redis") redisConnection(config, env, "documentStore");
895
+ if (config.infrastructure.eventBus === "redis-streams") redisConnection(config, env, "eventBus");
896
+ const media = await buildMedia(config, options, logger, env);
897
+ const documentStore = await buildDocumentStore(config, options, logger, env);
898
+ try {
899
+ if (config.infrastructure.documentStore === "postgres-jsonb") await documentStore.initialize?.();
900
+ const eventBus = await buildEventBus(config, logger, env);
901
+ return { documentStore, eventBus, media };
902
+ } catch (error) {
903
+ await documentStore.close();
904
+ throw error;
905
+ }
906
+ }
907
+ function createPlatform(config, options) {
755
908
  const logger = options.logger ?? createLogger({
756
909
  base: { store: config.store.name }
757
910
  });
@@ -759,34 +912,68 @@ function createPlatform(config, options = {}) {
759
912
  ...options.sqlitePath !== void 0 && { sqlitePath: options.sqlitePath },
760
913
  ...options.postgresUrl !== void 0 && { postgresUrl: options.postgresUrl }
761
914
  });
762
- const documentStore = createDocumentStore(config);
763
- const eventBus = createEventBus(config, logger);
915
+ const { documentStore, eventBus, media } = options;
764
916
  return {
765
917
  config,
766
918
  commandStore,
767
919
  documentStore,
768
920
  eventBus,
921
+ media,
769
922
  logger,
770
923
  async close() {
771
- await commandStore.close();
772
- await documentStore.close();
773
924
  await eventBus.close();
925
+ await documentStore.close();
926
+ await commandStore.close();
774
927
  }
775
928
  };
776
929
  }
777
930
 
778
931
  // src/db/migrate.ts
779
- import { resolve } from "path";
932
+ import { readFileSync } from "fs";
933
+ import { resolve as resolve2 } from "path";
780
934
  import { migrate as migrateSqlite } from "drizzle-orm/better-sqlite3/migrator";
781
935
  import { migrate as migratePostgres } from "drizzle-orm/node-postgres/migrator";
936
+ function rootOf(options) {
937
+ return options.migrationsRoot ?? resolve2(process.cwd(), "migrations");
938
+ }
782
939
  async function runMigrations(store, options = {}) {
783
- const root = options.migrationsRoot ?? resolve(process.cwd(), "migrations");
940
+ const root = rootOf(options);
941
+ const clients = rawClients(store);
942
+ if (clients.kind === "sqlite") {
943
+ migrateSqlite(clients.db, { migrationsFolder: resolve2(root, "sqlite") });
944
+ } else {
945
+ await migratePostgres(clients.db, { migrationsFolder: resolve2(root, "postgres") });
946
+ }
947
+ }
948
+ async function migrationState(store, options = {}) {
784
949
  const clients = rawClients(store);
950
+ const journal = JSON.parse(
951
+ readFileSync(resolve2(rootOf(options), clients.kind, "meta", "_journal.json"), "utf8")
952
+ );
953
+ let applied = 0;
954
+ let newest = Number.NEGATIVE_INFINITY;
785
955
  if (clients.kind === "sqlite") {
786
- migrateSqlite(clients.db, { migrationsFolder: resolve(root, "sqlite") });
956
+ const table = clients.raw.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'").get();
957
+ if (table !== void 0) {
958
+ const row = clients.raw.prepare("SELECT count(*) AS n, max(created_at) AS last FROM __drizzle_migrations").get();
959
+ applied = row.n;
960
+ if (row.last !== null) newest = Number(row.last);
961
+ }
787
962
  } else {
788
- await migratePostgres(clients.db, { migrationsFolder: resolve(root, "postgres") });
963
+ const { rows } = await clients.pool.query(
964
+ "SELECT to_regclass('drizzle.__drizzle_migrations')::text AS table"
965
+ );
966
+ if (rows[0]?.table != null) {
967
+ const counted = await clients.pool.query(
968
+ "SELECT count(*)::int AS n, max(created_at)::text AS last FROM drizzle.__drizzle_migrations"
969
+ );
970
+ applied = counted.rows[0]?.n ?? 0;
971
+ const last = counted.rows[0]?.last ?? null;
972
+ if (last !== null) newest = Number(last);
973
+ }
789
974
  }
975
+ const pending = journal.entries.filter((entry) => entry.when > newest).length;
976
+ return { applied, pending };
790
977
  }
791
978
 
792
979
  // src/db/repositories/products.ts
@@ -2565,11 +2752,11 @@ function createEventPublisher(opts) {
2565
2752
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2566
2753
  var PAGE_SIZE = 100;
2567
2754
  function deferred() {
2568
- let resolve2;
2755
+ let resolve4;
2569
2756
  const promise = new Promise((r) => {
2570
- resolve2 = r;
2757
+ resolve4 = r;
2571
2758
  });
2572
- return { promise, resolve: resolve2 };
2759
+ return { promise, resolve: resolve4 };
2573
2760
  }
2574
2761
  function createRelay(opts) {
2575
2762
  const { store, eventLog } = opts;
@@ -2657,9 +2844,23 @@ function createRelay(opts) {
2657
2844
  timer = void 0;
2658
2845
  if (delivering.getStore() === true) return Promise.resolve();
2659
2846
  return idle?.promise ?? Promise.resolve();
2847
+ },
2848
+ asDelivery(handler) {
2849
+ return (event) => delivering.run(true, () => handler(event));
2660
2850
  }
2661
2851
  };
2662
2852
  }
2853
+ function deliveringBus(bus, relay) {
2854
+ return {
2855
+ capabilities: () => bus.capabilities(),
2856
+ publish: (event) => bus.publish(event),
2857
+ publishBatch: (events3) => bus.publishBatch(events3),
2858
+ replay: (events3) => bus.replay(events3),
2859
+ subscribe: (pattern, handler, config) => bus.subscribe(pattern, relay.asDelivery(handler), config),
2860
+ unsubscribe: (subscription) => bus.unsubscribe(subscription),
2861
+ close: () => bus.close()
2862
+ };
2863
+ }
2663
2864
 
2664
2865
  // src/handlers/idempotency.ts
2665
2866
  function withIdempotency(handlerName, handler, { repo, logger }) {
@@ -2722,7 +2923,21 @@ import {
2722
2923
  } from "@nymbalhq/types";
2723
2924
  var PRODUCTS = "products";
2724
2925
  var PRODUCTS_BY_CATEGORY = "products-by-category";
2725
- function denormalise(p, storeId, storeCurrency, categories3) {
2926
+ var isVariantOption = (o) => typeof o === "object" && o !== null && typeof o.name === "string" && typeof o.value === "string";
2927
+ function variantOptions(raw, logger, sku) {
2928
+ let value = raw;
2929
+ if (typeof raw === "string") {
2930
+ try {
2931
+ value = JSON.parse(raw);
2932
+ } catch (err) {
2933
+ logger.warn({ sku, err }, "variant options are not JSON; projected as none");
2934
+ return [];
2935
+ }
2936
+ }
2937
+ if (!Array.isArray(value)) return [];
2938
+ return value.filter(isVariantOption).map((o) => ({ name: o.name, value: o.value }));
2939
+ }
2940
+ function denormalise(p, storeId, storeCurrency, categories3, logger) {
2726
2941
  const prices = p.variants.map((v) => v.priceMinor);
2727
2942
  const priceRange = prices.length ? { minMinor: Math.min(...prices), maxMinor: Math.max(...prices) } : null;
2728
2943
  const inStock = p.variants.some((v) => v.stock > 0);
@@ -2747,7 +2962,7 @@ function denormalise(p, storeId, storeCurrency, categories3) {
2747
2962
  name: v.name,
2748
2963
  priceMinor: v.priceMinor,
2749
2964
  stock: v.stock,
2750
- options: v.options
2965
+ options: variantOptions(v.options, logger, v.sku)
2751
2966
  })),
2752
2967
  categoryIds: p.categoryIds,
2753
2968
  categories: categories3,
@@ -2772,7 +2987,7 @@ async function registerProductProjection(deps) {
2772
2987
  const onUpsert = async (event) => {
2773
2988
  const { product } = event.payload;
2774
2989
  const categories3 = await resolveCategories(product.categoryIds, documentStore, storeId);
2775
- const doc = denormalise(product, storeId, currency, categories3);
2990
+ const doc = denormalise(product, storeId, currency, categories3, logger);
2776
2991
  await documentStore.put(PRODUCTS, product.slug, doc);
2777
2992
  for (const cat of categories3) {
2778
2993
  await documentStore.put(
@@ -3165,12 +3380,17 @@ async function registerHandlers(deps) {
3165
3380
  logger: handlerLogger.child({ handler: "reviews" }),
3166
3381
  processedEventRepo: repos.processedEvent
3167
3382
  });
3168
- logger.info("event handlers registered");
3383
+ logger.debug("event handlers registered");
3169
3384
  }
3170
3385
 
3171
3386
  // src/app.ts
3172
3387
  import { DEFAULT_JWT_SECRET } from "@nymbalhq/config";
3173
- import { ConfigError as ConfigError4 } from "@nymbalhq/types";
3388
+ import { ConfigError as ConfigError5 } from "@nymbalhq/types";
3389
+
3390
+ // src/adapters/registry.ts
3391
+ import {
3392
+ ConfigError as ConfigError4
3393
+ } from "@nymbalhq/types";
3174
3394
 
3175
3395
  // src/adapters/security/headers.ts
3176
3396
  function buildSecurityHeaders(security) {
@@ -3203,7 +3423,7 @@ function createMiddlewareSecurityAdapter(deps) {
3203
3423
  const { logger } = deps;
3204
3424
  let lastAppliedAt = "";
3205
3425
  return {
3206
- capabilities: ["headers"],
3426
+ capabilities: () => ["headers"],
3207
3427
  producesEvents: [],
3208
3428
  consumesEvents: [],
3209
3429
  initialize: noopInitialize,
@@ -3225,220 +3445,17 @@ function createMiddlewareSecurityAdapter(deps) {
3225
3445
  };
3226
3446
  }
3227
3447
 
3228
- // src/adapters/payments/stripe-adapter.ts
3229
- import Stripe from "stripe";
3448
+ // src/adapters/payments/native-stub.ts
3449
+ import { v7 as uuidv73 } from "uuid";
3230
3450
  import {
3231
3451
  EVT_PAYMENT_CAPTURED,
3232
3452
  EVT_PAYMENT_FAILED,
3233
3453
  EVT_PAYMENT_REFUNDED,
3234
3454
  PaymentError
3235
3455
  } from "@nymbalhq/types";
3236
- function toIsoCurrency(currency) {
3237
- return currency.toUpperCase();
3238
- }
3239
- function mapStatus(status) {
3240
- switch (status) {
3241
- case "requires_payment_method":
3242
- case "requires_confirmation":
3243
- case "requires_action":
3244
- case "processing":
3245
- case "requires_capture":
3246
- case "succeeded":
3247
- case "canceled":
3248
- return status === "canceled" ? "cancelled" : status;
3249
- default:
3250
- return "failed";
3251
- }
3252
- }
3253
- function refundStatus(status) {
3254
- if (status === "succeeded") return "succeeded";
3255
- if (status === "failed" || status === "canceled") return "failed";
3256
- return "pending";
3257
- }
3258
- function isDefiniteRefusal(err) {
3259
- const type = err?.type;
3260
- return type === "StripeCardError" || type === "StripeInvalidRequestError";
3261
- }
3262
- function toIntent(intent) {
3263
- return {
3264
- id: intent.id,
3265
- clientSecret: intent.client_secret ?? "",
3266
- amountMinor: intent.amount,
3267
- currency: toIsoCurrency(intent.currency),
3268
- status: mapStatus(intent.status)
3269
- };
3270
- }
3271
- function createStripePaymentsAdapter(deps) {
3272
- const { logger } = deps;
3273
- const cfg = deps.config;
3274
- if (!cfg.secretKey) throw new PaymentError("not_configured", "Stripe secretKey missing");
3275
- if (!cfg.webhookSecret) throw new PaymentError("not_configured", "Stripe webhookSecret missing");
3276
- const stripeClient = new Stripe(cfg.secretKey, {
3277
- ...cfg.apiVersion !== void 0 && {
3278
- apiVersion: cfg.apiVersion
3279
- },
3280
- ...cfg.host !== void 0 && { host: cfg.host },
3281
- ...cfg.port !== void 0 && { port: cfg.port },
3282
- ...cfg.protocol !== void 0 && { protocol: cfg.protocol }
3283
- });
3284
- return {
3285
- kind: "payments",
3286
- providerName: "stripe",
3287
- capabilities: ["intent", "capture", "refund", "webhook"],
3288
- producesEvents: [EVT_PAYMENT_CAPTURED, EVT_PAYMENT_FAILED, EVT_PAYMENT_REFUNDED],
3289
- consumesEvents: [],
3290
- async initialize() {
3291
- },
3292
- async healthCheck() {
3293
- try {
3294
- await stripeClient.balance.retrieve();
3295
- return { status: "healthy" };
3296
- } catch (err) {
3297
- return {
3298
- status: "down",
3299
- detail: err instanceof Error ? err.message : String(err)
3300
- };
3301
- }
3302
- },
3303
- async createPaymentIntent(params) {
3304
- try {
3305
- const intent = await stripeClient.paymentIntents.create({
3306
- amount: params.amountMinor,
3307
- currency: params.currency.toLowerCase(),
3308
- automatic_payment_methods: { enabled: true },
3309
- ...params.receiptEmail !== void 0 && { receipt_email: params.receiptEmail },
3310
- metadata: {
3311
- ...params.metadata ?? {},
3312
- ...params.orderRef !== void 0 ? { orderRef: params.orderRef } : {},
3313
- ...params.customerId !== void 0 ? { customerId: params.customerId } : {}
3314
- }
3315
- });
3316
- return toIntent(intent);
3317
- } catch (err) {
3318
- throw new PaymentError("intent_failed", "Stripe createPaymentIntent failed", { cause: err });
3319
- }
3320
- },
3321
- async capturePayment(intentId, amountMinor) {
3322
- try {
3323
- const captured = await stripeClient.paymentIntents.capture(intentId, {
3324
- ...amountMinor !== void 0 && { amount_to_capture: amountMinor }
3325
- });
3326
- return {
3327
- paymentId: captured.id,
3328
- capturedAmountMinor: captured.amount_received ?? captured.amount,
3329
- currency: toIsoCurrency(captured.currency),
3330
- status: mapStatus(captured.status)
3331
- };
3332
- } catch (err) {
3333
- throw new PaymentError("capture_failed", "Stripe capturePayment failed", { cause: err });
3334
- }
3335
- },
3336
- async refund(paymentId, amountMinor, reason, opts) {
3337
- const params = {
3338
- payment_intent: paymentId,
3339
- ...amountMinor !== void 0 && { amount: amountMinor },
3340
- ...reason !== void 0 && { reason }
3341
- };
3342
- try {
3343
- const refund = opts?.idempotencyKey === void 0 ? await stripeClient.refunds.create(params) : await stripeClient.refunds.create(params, { idempotencyKey: opts.idempotencyKey });
3344
- return {
3345
- refundId: refund.id,
3346
- paymentId,
3347
- amountMinor: refund.amount,
3348
- currency: toIsoCurrency(refund.currency),
3349
- reason: refund.reason ?? null,
3350
- status: refundStatus(refund.status)
3351
- };
3352
- } catch (err) {
3353
- if (isDefiniteRefusal(err)) {
3354
- throw new PaymentError("refund_rejected", "Stripe refused the refund", { cause: err });
3355
- }
3356
- throw new PaymentError("refund_unknown", "Stripe refund outcome unknown", { cause: err });
3357
- }
3358
- },
3359
- async getPaymentStatus(intentId) {
3360
- const intent = await stripeClient.paymentIntents.retrieve(intentId);
3361
- return mapStatus(intent.status);
3362
- },
3363
- async getPaymentIntent(intentId) {
3364
- try {
3365
- return toIntent(await stripeClient.paymentIntents.retrieve(intentId));
3366
- } catch (err) {
3367
- throw new PaymentError("intent_failed", "Stripe getPaymentIntent failed", { cause: err });
3368
- }
3369
- },
3370
- async cancelPaymentIntent(intentId) {
3371
- try {
3372
- await stripeClient.paymentIntents.cancel(intentId);
3373
- } catch (err) {
3374
- const status = await stripeClient.paymentIntents.retrieve(intentId).then((intent) => intent.status).catch(() => void 0);
3375
- if (status === "canceled") return;
3376
- throw new PaymentError("cancel_refused", `Stripe would not cancel ${intentId}`, {
3377
- cause: err
3378
- });
3379
- }
3380
- },
3381
- async parseWebhook(rawBody, signature) {
3382
- let event;
3383
- try {
3384
- event = stripeClient.webhooks.constructEvent(rawBody, signature, cfg.webhookSecret);
3385
- } catch (err) {
3386
- throw new PaymentError("webhook_invalid", "Stripe webhook signature invalid", {
3387
- cause: err
3388
- });
3389
- }
3390
- const baseResult = { verified: true, eventId: event.id };
3391
- switch (event.type) {
3392
- case "payment_intent.succeeded": {
3393
- const intent = event.data.object;
3394
- return {
3395
- ...baseResult,
3396
- kind: "payment.captured",
3397
- paymentIntentId: intent.id,
3398
- amountMinor: intent.amount_received ?? intent.amount,
3399
- currency: toIsoCurrency(intent.currency),
3400
- raw: { ...intent }
3401
- };
3402
- }
3403
- case "payment_intent.payment_failed": {
3404
- const intent = event.data.object;
3405
- return {
3406
- ...baseResult,
3407
- kind: "payment.failed",
3408
- paymentIntentId: intent.id,
3409
- reason: intent.last_payment_error?.message ?? "payment failed"
3410
- };
3411
- }
3412
- case "charge.refunded": {
3413
- const charge = event.data.object;
3414
- const pi = typeof charge.payment_intent === "string" ? charge.payment_intent : charge.payment_intent?.id;
3415
- return {
3416
- ...baseResult,
3417
- kind: "payment.refunded",
3418
- ...pi !== void 0 && { paymentIntentId: pi },
3419
- amountMinor: charge.amount_refunded,
3420
- currency: toIsoCurrency(charge.currency)
3421
- };
3422
- }
3423
- default:
3424
- logger.debug({ type: event.type }, "stripe webhook ignored");
3425
- return { ...baseResult, kind: "ignored" };
3426
- }
3427
- }
3428
- };
3429
- }
3430
-
3431
- // src/adapters/payments/native-stub.ts
3432
- import { v7 as uuidv73 } from "uuid";
3433
- import {
3434
- EVT_PAYMENT_CAPTURED as EVT_PAYMENT_CAPTURED2,
3435
- EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
3436
- EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
3437
- PaymentError as PaymentError2
3438
- } from "@nymbalhq/types";
3439
3456
  var STUB_ID_PREFIX = "pi_stub_";
3440
3457
  function rejected(message) {
3441
- return new PaymentError2("refund_rejected", message);
3458
+ return new PaymentError("refund_rejected", message);
3442
3459
  }
3443
3460
  function statusFor(receiptEmail) {
3444
3461
  const address = receiptEmail ?? "";
@@ -3448,7 +3465,7 @@ function statusFor(receiptEmail) {
3448
3465
  if (local.endsWith("+stub-decline")) return "failed";
3449
3466
  return "succeeded";
3450
3467
  }
3451
- function toIntent2(intent) {
3468
+ function toIntent(intent) {
3452
3469
  return {
3453
3470
  id: intent.id,
3454
3471
  clientSecret: `${intent.id}_secret`,
@@ -3463,8 +3480,11 @@ function createNativeStubPaymentsAdapter(deps) {
3463
3480
  return {
3464
3481
  kind: "payments",
3465
3482
  providerName: "native-stub",
3466
- capabilities: ["intent", "capture", "refund", "webhook"],
3467
- producesEvents: [EVT_PAYMENT_CAPTURED2, EVT_PAYMENT_FAILED2, EVT_PAYMENT_REFUNDED2],
3483
+ // No `webhook`: parseWebhook verifies no signature, so a template cannot rely on it.
3484
+ capabilities: () => ["intent", "capture", "refund"],
3485
+ // Nothing to collect: the receipt email decides the outcome.
3486
+ client: () => ({ driver: "test-mode", options: {} }),
3487
+ producesEvents: [EVT_PAYMENT_CAPTURED, EVT_PAYMENT_FAILED, EVT_PAYMENT_REFUNDED],
3468
3488
  consumesEvents: [],
3469
3489
  initialize: noopInitialize,
3470
3490
  healthCheck: () => okHealth("stub \u2014 always healthy"),
@@ -3480,11 +3500,11 @@ function createNativeStubPaymentsAdapter(deps) {
3480
3500
  };
3481
3501
  intents.set(id, intent);
3482
3502
  logger.debug({ intentId: id, status: intent.status }, "stub payment intent created");
3483
- return toIntent2(intent);
3503
+ return toIntent(intent);
3484
3504
  },
3485
3505
  async capturePayment(intentId) {
3486
3506
  const intent = intents.get(intentId);
3487
- if (!intent) throw new PaymentError2("capture_failed", `unknown intent ${intentId}`);
3507
+ if (!intent) throw new PaymentError("capture_failed", `unknown intent ${intentId}`);
3488
3508
  intent.status = "succeeded";
3489
3509
  return {
3490
3510
  paymentId: intent.id,
@@ -3524,14 +3544,14 @@ function createNativeStubPaymentsAdapter(deps) {
3524
3544
  },
3525
3545
  async getPaymentIntent(intentId) {
3526
3546
  const intent = intents.get(intentId);
3527
- if (!intent) throw new PaymentError2("intent_failed", `unknown intent ${intentId}`);
3528
- return toIntent2(intent);
3547
+ if (!intent) throw new PaymentError("intent_failed", `unknown intent ${intentId}`);
3548
+ return toIntent(intent);
3529
3549
  },
3530
3550
  async cancelPaymentIntent(intentId) {
3531
3551
  const intent = intents.get(intentId);
3532
3552
  if (!intent) return;
3533
3553
  if (intent.status === "succeeded") {
3534
- throw new PaymentError2("cancel_refused", `intent ${intentId} is already captured`);
3554
+ throw new PaymentError("cancel_refused", `intent ${intentId} is already captured`);
3535
3555
  }
3536
3556
  intent.status = "cancelled";
3537
3557
  },
@@ -3550,142 +3570,33 @@ function createNativeStubPaymentsAdapter(deps) {
3550
3570
  ...event.currency !== void 0 && { currency: event.currency }
3551
3571
  };
3552
3572
  } catch (err) {
3553
- throw new PaymentError2("webhook_invalid", "stub webhook body not JSON", { cause: err });
3573
+ throw new PaymentError("webhook_invalid", "stub webhook body not JSON", { cause: err });
3554
3574
  }
3555
3575
  }
3556
3576
  };
3557
3577
  }
3558
3578
 
3559
3579
  // src/adapters/email/native-email-adapter.ts
3560
- import nodemailer from "nodemailer";
3561
3580
  import {
3562
- AdapterError as AdapterError3,
3563
3581
  EVT_CART_ABANDONED as EVT_CART_ABANDONED2,
3564
3582
  EVT_CUSTOMER_CREATED as EVT_CUSTOMER_CREATED3,
3565
3583
  EVT_ORDER_PLACED as EVT_ORDER_PLACED2,
3566
- EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED3
3584
+ EVT_ORDER_SHIPPED as EVT_ORDER_SHIPPED3,
3585
+ renderEmailTemplate
3567
3586
  } from "@nymbalhq/types";
3568
-
3569
- // src/adapters/email/templates.ts
3570
- function render(template, vars) {
3571
- return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, path) => {
3572
- const parts = path.split(".");
3573
- let cur = vars;
3574
- for (const p of parts) {
3575
- if (cur && typeof cur === "object" && p in cur) {
3576
- cur = cur[p];
3577
- } else {
3578
- return "";
3579
- }
3580
- }
3581
- return cur == null ? "" : String(cur);
3582
- });
3583
- }
3584
- var TEMPLATES = {
3585
- "order-placed": {
3586
- subject: "Order {{orderNumber}} confirmed",
3587
- body: `Hi {{customerName}},
3588
-
3589
- Thank you for your order {{orderNumber}}. Total: {{totalFormatted}}.
3590
-
3591
- We'll let you know when it ships.`
3592
- },
3593
- "order-shipped": {
3594
- subject: "Order {{orderNumber}} is on its way",
3595
- body: `Hi {{customerName}},
3596
-
3597
- Your order {{orderNumber}} has shipped via {{carrier}}.
3598
- Tracking: {{trackingNumber}}`
3599
- },
3600
- welcome: {
3601
- subject: "Welcome to {{storeName}}",
3602
- body: `Welcome {{customerName}}! Your account is ready.`
3603
- },
3604
- "cart-abandoned": {
3605
- subject: "Don't forget your cart at {{storeName}}",
3606
- body: `Hi,
3607
-
3608
- You left items in your cart. Pick up where you left off: {{resumeUrl}}`
3609
- }
3610
- };
3611
- function renderTemplate(template, vars) {
3612
- const t = TEMPLATES[template];
3613
- if (!t) {
3614
- return {
3615
- subject: `[nymbal] ${template}`,
3616
- text: JSON.stringify(vars),
3617
- html: `<pre>${JSON.stringify(vars, null, 2)}</pre>`
3618
- };
3619
- }
3620
- const subject = render(t.subject, vars);
3621
- const text = render(t.body, vars);
3622
- const html = `<pre>${text.replace(/</g, "&lt;")}</pre>`;
3623
- return { subject, text, html };
3624
- }
3625
-
3626
- // src/adapters/email/native-email-adapter.ts
3627
3587
  function createNativeEmailAdapter(deps) {
3628
3588
  const log = deps.logger.child({ adapter: "email", provider: "native" });
3629
- let cfg = deps.config ?? { transport: "console" };
3630
- let transporter = null;
3631
- function ensureTransport() {
3632
- if (cfg.transport !== "smtp") return;
3633
- if (transporter) return;
3634
- if (!cfg.smtp) {
3635
- throw new AdapterError3("email.misconfigured", "SMTP transport selected but smtp.host not set");
3636
- }
3637
- transporter = nodemailer.createTransport({
3638
- host: cfg.smtp.host,
3639
- port: cfg.smtp.port,
3640
- secure: cfg.smtp.secure ?? cfg.smtp.port === 465,
3641
- ...cfg.smtp.user !== void 0 && cfg.smtp.pass !== void 0 ? { auth: { user: cfg.smtp.user, pass: cfg.smtp.pass } } : {}
3642
- });
3643
- }
3644
3589
  return {
3645
3590
  kind: "email",
3646
3591
  providerName: "native",
3647
- capabilities: ["transactional", "list-sync"],
3592
+ capabilities: () => ["transactional", "list-sync"],
3648
3593
  producesEvents: [],
3649
- consumesEvents: [
3650
- EVT_ORDER_PLACED2,
3651
- EVT_ORDER_SHIPPED3,
3652
- EVT_CUSTOMER_CREATED3,
3653
- EVT_CART_ABANDONED2
3654
- ],
3655
- async initialize(rawConfig) {
3656
- cfg = { ...cfg, ...rawConfig };
3657
- if (cfg.transport === "smtp") ensureTransport();
3658
- },
3659
- async healthCheck() {
3660
- if (cfg.transport === "smtp" && transporter) {
3661
- try {
3662
- await transporter.verify();
3663
- return { status: "healthy", detail: "SMTP verified" };
3664
- } catch (err) {
3665
- return {
3666
- status: "degraded",
3667
- detail: `SMTP verify failed: ${err instanceof Error ? err.message : String(err)}`
3668
- };
3669
- }
3670
- }
3671
- return okHealth("console transport");
3594
+ consumesEvents: [EVT_ORDER_PLACED2, EVT_ORDER_SHIPPED3, EVT_CUSTOMER_CREATED3, EVT_CART_ABANDONED2],
3595
+ async initialize() {
3672
3596
  },
3597
+ healthCheck: () => okHealth("console transport"),
3673
3598
  async sendTransactional(params) {
3674
- const rendered = renderTemplate(params.template, params.vars);
3675
- if (cfg.transport === "smtp") {
3676
- ensureTransport();
3677
- if (!transporter) {
3678
- throw new AdapterError3("email.transport_missing", "SMTP transport not initialised");
3679
- }
3680
- const info = await transporter.sendMail({
3681
- from: cfg.from ?? "no-reply@nymbal.dev",
3682
- to: params.to,
3683
- subject: rendered.subject,
3684
- text: rendered.text,
3685
- html: rendered.html
3686
- });
3687
- return { messageId: info.messageId ?? null, accepted: (info.accepted ?? []).length > 0 };
3688
- }
3599
+ const rendered = renderEmailTemplate(params.template, params.vars);
3689
3600
  log.info(
3690
3601
  { to: params.to, subject: rendered.subject, template: params.template },
3691
3602
  "email.sent (console)"
@@ -3706,96 +3617,306 @@ function createNativeEmailAdapter(deps) {
3706
3617
  import {
3707
3618
  EVT_PRODUCT_CREATED as EVT_PRODUCT_CREATED3,
3708
3619
  EVT_PRODUCT_DELETED as EVT_PRODUCT_DELETED3,
3709
- EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED3
3620
+ EVT_PRODUCT_UPDATED as EVT_PRODUCT_UPDATED3,
3621
+ ValidationError as ValidationError2
3710
3622
  } from "@nymbalhq/types";
3711
- var INDEX_COLLECTION = "search-index";
3712
- function flatten(value) {
3713
- if (value == null) return "";
3714
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3715
- return String(value);
3716
- }
3717
- if (Array.isArray(value)) return value.map(flatten).join(" ");
3718
- if (typeof value === "object") {
3719
- return Object.values(value).map(flatten).join(" ");
3623
+
3624
+ // src/adapters/search/terms.ts
3625
+ function searchTerms(text) {
3626
+ return text.toLowerCase().match(/[a-z0-9]+/g) ?? [];
3627
+ }
3628
+ var textOf = (value) => typeof value === "string" ? value : "";
3629
+ function toIndexRow(doc) {
3630
+ const { fields } = doc;
3631
+ const variants3 = Array.isArray(fields["variants"]) ? fields["variants"].filter(
3632
+ (v) => typeof v === "object" && v !== null
3633
+ ) : [];
3634
+ const categoryIds = Array.isArray(fields["categoryIds"]) ? [...new Set(fields["categoryIds"].filter((c) => typeof c === "string"))] : [];
3635
+ return {
3636
+ id: doc.id,
3637
+ type: doc.type,
3638
+ fields,
3639
+ categoryIds,
3640
+ name: searchTerms(textOf(fields["name"])),
3641
+ strong: variants3.flatMap((v) => [
3642
+ ...searchTerms(textOf(v["sku"])),
3643
+ ...searchTerms(textOf(v["name"]))
3644
+ ]),
3645
+ body: searchTerms(textOf(fields["description"]))
3646
+ };
3647
+ }
3648
+ function latestById(rows) {
3649
+ return [...new Map(rows.map((row) => [row.id, row])).values()];
3650
+ }
3651
+
3652
+ // src/adapters/search/postgres-index.ts
3653
+ var MAX_LEXEME = 2046;
3654
+ var MAX_POSITION = 16383;
3655
+ var MAX_POSITIONS = 256;
3656
+ var lexeme = (term) => term.slice(0, MAX_LEXEME);
3657
+ function tsvectorLiteral(row) {
3658
+ const positions = /* @__PURE__ */ new Map();
3659
+ let position = 0;
3660
+ const add = (terms, weight) => {
3661
+ for (const term of terms) {
3662
+ position = Math.min(position + 1, MAX_POSITION);
3663
+ const key = lexeme(term);
3664
+ const list = positions.get(key) ?? [];
3665
+ if (list.length < MAX_POSITIONS) list.push(`${position}${weight}`);
3666
+ positions.set(key, list);
3667
+ }
3668
+ };
3669
+ add(row.name, "A");
3670
+ add(row.strong, "B");
3671
+ add(row.body, "C");
3672
+ return [...positions].map(([key, list]) => `'${key}':${list.join(",")}`).join(" ");
3673
+ }
3674
+ function tsqueryLiteral(terms, weights) {
3675
+ return terms.map((t) => `'${lexeme(t)}':*${weights}`).join(" & ");
3676
+ }
3677
+ var IN_CATEGORY = `($2::text[] IS NULL OR category_ids && $2::text[])`;
3678
+ var SQL = {
3679
+ upsert: `INSERT INTO search_documents (id, type, fields, category_ids, tsv)
3680
+ SELECT r.id, r.type, r.fields, ARRAY(SELECT jsonb_array_elements_text(r.cats)), r.tsv::tsvector
3681
+ FROM jsonb_to_recordset($1::jsonb) AS r(id text, type text, fields jsonb, cats jsonb, tsv text)
3682
+ ON CONFLICT (id) DO UPDATE SET
3683
+ type = excluded.type, fields = excluded.fields, category_ids = excluded.category_ids, tsv = excluded.tsv
3684
+ WHERE search_documents.type IS DISTINCT FROM excluded.type
3685
+ OR search_documents.fields IS DISTINCT FROM excluded.fields`,
3686
+ remove: `DELETE FROM search_documents WHERE id = ANY($1::text[])`,
3687
+ // Rank: every term in the name, then every term in name, SKU or variant name, then ts_rank, then id.
3688
+ page: `SELECT id, type, fields, (count(*) OVER ())::int AS total
3689
+ FROM search_documents
3690
+ WHERE tsv @@ $1::tsquery AND ${IN_CATEGORY}
3691
+ ORDER BY tsv @@ $3::tsquery DESC, tsv @@ $4::tsquery DESC, ts_rank(tsv, $1::tsquery) DESC, id COLLATE "C"
3692
+ LIMIT $5 OFFSET $6`,
3693
+ count: `SELECT count(*)::int AS total FROM search_documents WHERE tsv @@ $1::tsquery AND ${IN_CATEGORY}`,
3694
+ facet: `SELECT c AS value, count(*)::int AS count
3695
+ FROM search_documents, unnest(category_ids) AS c
3696
+ WHERE ($1::tsquery IS NULL OR tsv @@ $1::tsquery) AND ${IN_CATEGORY}
3697
+ GROUP BY c ORDER BY count DESC, c COLLATE "C" LIMIT $3`
3698
+ };
3699
+ var named = (key, values) => ({
3700
+ name: `nymbal-search-${key}`,
3701
+ text: SQL[key],
3702
+ values
3703
+ });
3704
+ function createPostgresSearchIndex(pool) {
3705
+ return {
3706
+ async upsert(rows) {
3707
+ const batch = latestById(rows).map((row) => ({
3708
+ id: row.id,
3709
+ type: row.type,
3710
+ fields: row.fields,
3711
+ cats: row.categoryIds,
3712
+ tsv: tsvectorLiteral(row)
3713
+ }));
3714
+ if (batch.length > 0) await pool.query(named("upsert", [JSON.stringify(batch)]));
3715
+ },
3716
+ async remove(ids) {
3717
+ if (ids.length > 0) await pool.query(named("remove", [ids]));
3718
+ },
3719
+ async page(terms, categories3, limit, offset) {
3720
+ const result = await pool.query(SQL.page, [
3721
+ tsqueryLiteral(terms, ""),
3722
+ categories3,
3723
+ tsqueryLiteral(terms, "A"),
3724
+ tsqueryLiteral(terms, "AB"),
3725
+ limit,
3726
+ offset
3727
+ ]);
3728
+ const docs = result.rows.map(({ id, type, fields }) => ({ id, type, fields }));
3729
+ return { docs, total: result.rows[0]?.total ?? null };
3730
+ },
3731
+ async count(terms, categories3) {
3732
+ const result = await pool.query(SQL.count, [
3733
+ tsqueryLiteral(terms, ""),
3734
+ categories3
3735
+ ]);
3736
+ return result.rows[0].total;
3737
+ },
3738
+ async categoryCounts(terms, categories3, limit) {
3739
+ const result = await pool.query(SQL.facet, [
3740
+ terms === null ? null : tsqueryLiteral(terms, ""),
3741
+ categories3,
3742
+ limit
3743
+ ]);
3744
+ return result.rows;
3745
+ }
3746
+ };
3747
+ }
3748
+
3749
+ // src/adapters/search/sqlite-index.ts
3750
+ function matchAll(terms) {
3751
+ return terms.map((t) => `"${t}"*`).join(" AND ");
3752
+ }
3753
+ var IN_CATEGORY2 = `(@cats IS NULL OR EXISTS (
3754
+ SELECT 1 FROM json_each(d.category_ids) c WHERE c.value IN (SELECT value FROM json_each(@cats))))`;
3755
+ var matching = (score) => `hits AS MATERIALIZED (
3756
+ SELECT rowid AS rid${score ? ", bm25(search_documents_fts) AS score" : ""}
3757
+ FROM search_documents_fts WHERE search_documents_fts MATCH @all)`;
3758
+ var SQL2 = {
3759
+ upsert: `INSERT INTO search_documents (id, type, fields, category_ids, name_terms, strong_terms, body_terms)
3760
+ VALUES (@id, @type, @fields, @cats, @name, @strong, @body)
3761
+ ON CONFLICT (id) DO UPDATE SET
3762
+ type = excluded.type, fields = excluded.fields, category_ids = excluded.category_ids,
3763
+ name_terms = excluded.name_terms, strong_terms = excluded.strong_terms, body_terms = excluded.body_terms
3764
+ WHERE search_documents.type IS NOT excluded.type OR search_documents.fields IS NOT excluded.fields`,
3765
+ remove: `DELETE FROM search_documents WHERE id = ?`,
3766
+ // Rank: every term in the name, then every term in name, SKU or variant name, then bm25 (lower is better), then id.
3767
+ page: `WITH ${matching(true)},
3768
+ named AS MATERIALIZED (
3769
+ SELECT rowid AS rid FROM search_documents_fts WHERE search_documents_fts MATCH @name),
3770
+ strong AS MATERIALIZED (
3771
+ SELECT rowid AS rid FROM search_documents_fts WHERE search_documents_fts MATCH @strong)
3772
+ SELECT d.id, d.type, d.fields, count(*) OVER () AS total
3773
+ FROM hits h JOIN search_documents d ON d.rid = h.rid
3774
+ WHERE ${IN_CATEGORY2}
3775
+ ORDER BY h.rid IN (SELECT rid FROM named) DESC, h.rid IN (SELECT rid FROM strong) DESC, h.score, d.id
3776
+ LIMIT @limit OFFSET @offset`,
3777
+ count: `WITH ${matching(false)}
3778
+ SELECT count(*) AS total FROM hits h JOIN search_documents d ON d.rid = h.rid WHERE ${IN_CATEGORY2}`,
3779
+ facet: `WITH ${matching(false)}
3780
+ SELECT c.value AS value, count(*) AS count
3781
+ FROM hits h JOIN search_documents d ON d.rid = h.rid JOIN json_each(d.category_ids) c
3782
+ WHERE ${IN_CATEGORY2}
3783
+ GROUP BY c.value ORDER BY count DESC, c.value LIMIT @limit`,
3784
+ facetAll: `SELECT c.value AS value, count(*) AS count
3785
+ FROM search_documents d JOIN json_each(d.category_ids) c
3786
+ WHERE ${IN_CATEGORY2}
3787
+ GROUP BY c.value ORDER BY count DESC, c.value LIMIT @limit`
3788
+ };
3789
+ function createSqliteSearchIndex(raw) {
3790
+ const prepared = /* @__PURE__ */ new Map();
3791
+ const statement = (key) => {
3792
+ let stmt = prepared.get(key);
3793
+ if (stmt === void 0) {
3794
+ stmt = raw.prepare(SQL2[key]);
3795
+ prepared.set(key, stmt);
3796
+ }
3797
+ return stmt;
3798
+ };
3799
+ const cats = (categories3) => categories3 === null ? null : JSON.stringify(categories3);
3800
+ const queryParams = (terms, categories3) => ({
3801
+ all: matchAll(terms),
3802
+ cats: cats(categories3)
3803
+ });
3804
+ return {
3805
+ upsert: (rows) => sqliteTurn(raw, () => {
3806
+ const upsert = statement("upsert");
3807
+ raw.transaction((batch) => {
3808
+ for (const row of batch) {
3809
+ upsert.run({
3810
+ id: row.id,
3811
+ type: row.type,
3812
+ fields: JSON.stringify(row.fields),
3813
+ cats: JSON.stringify(row.categoryIds),
3814
+ name: row.name.join(" "),
3815
+ strong: row.strong.join(" "),
3816
+ body: row.body.join(" ")
3817
+ });
3818
+ }
3819
+ })(latestById(rows));
3820
+ }),
3821
+ remove: (ids) => sqliteTurn(raw, () => {
3822
+ const remove = statement("remove");
3823
+ raw.transaction((batch) => {
3824
+ for (const id of batch) remove.run(id);
3825
+ })(ids);
3826
+ }),
3827
+ page: (terms, categories3, limit, offset) => sqliteTurn(raw, () => {
3828
+ const all = matchAll(terms);
3829
+ const rows = statement("page").all({
3830
+ ...queryParams(terms, categories3),
3831
+ name: `name_terms : (${all})`,
3832
+ strong: `{name_terms strong_terms} : (${all})`,
3833
+ limit,
3834
+ offset
3835
+ });
3836
+ const docs = rows.map((r) => ({
3837
+ id: r.id,
3838
+ type: r.type,
3839
+ fields: JSON.parse(r.fields)
3840
+ }));
3841
+ return { docs, total: rows[0]?.total ?? null };
3842
+ }),
3843
+ count: (terms, categories3) => sqliteTurn(
3844
+ raw,
3845
+ () => statement("count").get(queryParams(terms, categories3)).total
3846
+ ),
3847
+ categoryCounts: (terms, categories3, limit) => sqliteTurn(raw, () => {
3848
+ const params = { cats: cats(categories3), limit: limit ?? -1 };
3849
+ return terms === null ? statement("facetAll").all(params) : statement("facet").all({ ...params, all: matchAll(terms) });
3850
+ })
3851
+ };
3852
+ }
3853
+
3854
+ // src/adapters/search/native-adapter.ts
3855
+ var DEFAULT_LIMIT = 20;
3856
+ function encodeSearchCursor(offset) {
3857
+ return Buffer.from(String(offset), "utf8").toString("base64url");
3858
+ }
3859
+ function decodeSearchCursor(cursor) {
3860
+ const text = Buffer.from(cursor, "base64url").toString("utf8");
3861
+ const offset = Number(text);
3862
+ if (!/^\d+$/.test(text) || !Number.isSafeInteger(offset) || encodeSearchCursor(offset) !== cursor) {
3863
+ throw new ValidationError2("malformed search cursor");
3720
3864
  }
3721
- return "";
3865
+ return offset;
3722
3866
  }
3867
+ function categoryFilter(filters) {
3868
+ const value = filters?.["categoryIds"];
3869
+ if (typeof value === "string") return [value];
3870
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
3871
+ return null;
3872
+ }
3873
+ var uniqueTerms = (query) => [...new Set(searchTerms(query))];
3723
3874
  function createNativeSearchAdapter(deps) {
3724
- const { documentStore, logger } = deps;
3875
+ const { sql: sql6, logger } = deps;
3876
+ const index = sql6.kind === "sqlite" ? createSqliteSearchIndex(sql6.raw) : createPostgresSearchIndex(sql6.pool);
3725
3877
  return {
3726
3878
  kind: "search",
3727
3879
  providerName: "native",
3728
- capabilities: ["index", "search", "facet"],
3880
+ capabilities: () => ["index", "search", "facet"],
3729
3881
  producesEvents: [],
3730
3882
  consumesEvents: [EVT_PRODUCT_CREATED3, EVT_PRODUCT_UPDATED3, EVT_PRODUCT_DELETED3],
3731
3883
  initialize: noopInitialize,
3732
3884
  healthCheck: () => okHealth(),
3733
3885
  async index(documents) {
3734
- const entries = /* @__PURE__ */ new Map();
3735
- for (const doc of documents) {
3736
- entries.set(doc.id, {
3737
- id: doc.id,
3738
- type: doc.type,
3739
- fields: doc.fields,
3740
- text: flatten(doc.fields).toLowerCase()
3741
- });
3742
- }
3743
- await documentStore.batchPut(INDEX_COLLECTION, entries);
3886
+ await index.upsert(documents.map(toIndexRow));
3744
3887
  logger.debug({ count: documents.length }, "search.index");
3745
3888
  return { indexed: documents.length };
3746
3889
  },
3747
3890
  async remove(ids) {
3748
- for (const id of ids) {
3749
- await documentStore.delete(INDEX_COLLECTION, id);
3750
- }
3891
+ await index.remove(ids);
3751
3892
  },
3752
3893
  async search(query, params) {
3753
- const q = query.trim().toLowerCase();
3754
- const limit = params?.limit ?? 20;
3755
- const result = await documentStore.query(INDEX_COLLECTION, {
3756
- partitionKey: { field: "type", value: "product" },
3757
- limit: 1e3
3758
- });
3759
- const filtered = result.items.filter((item) => {
3760
- if (!q) return true;
3761
- if (!item.text.includes(q)) return false;
3762
- for (const [k, v] of Object.entries(params?.filters ?? {})) {
3763
- const field = item.fields[k];
3764
- if (field !== v) return false;
3765
- }
3766
- return true;
3767
- });
3894
+ const offset = params?.cursor === void 0 ? 0 : decodeSearchCursor(params.cursor);
3895
+ const requested = params?.limit ?? DEFAULT_LIMIT;
3896
+ const limit = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : DEFAULT_LIMIT;
3897
+ const terms = uniqueTerms(query);
3898
+ if (terms.length === 0) return { items: [], total: 0, nextCursor: null };
3899
+ const categories3 = categoryFilter(params?.filters);
3900
+ const page = await index.page(terms, categories3, limit, offset);
3901
+ const total = page.total ?? await index.count(terms, categories3);
3902
+ const end = offset + page.docs.length;
3768
3903
  return {
3769
- items: filtered.slice(0, limit).map((it) => ({
3770
- id: it.id,
3771
- type: it.type,
3772
- fields: it.fields
3773
- })),
3774
- total: filtered.length,
3775
- nextCursor: null
3904
+ items: page.docs,
3905
+ total,
3906
+ nextCursor: page.docs.length > 0 && end < total ? encodeSearchCursor(end) : null
3776
3907
  };
3777
3908
  },
3778
- async facet(field) {
3779
- const result = await documentStore.query(INDEX_COLLECTION, {
3780
- partitionKey: { field: "type", value: "product" },
3781
- limit: 1e3
3782
- });
3783
- const counts = /* @__PURE__ */ new Map();
3784
- for (const item of result.items) {
3785
- const raw = item.fields[field];
3786
- if (raw == null) continue;
3787
- const vals = Array.isArray(raw) ? raw : [raw];
3788
- for (const v of vals) {
3789
- const key = String(v);
3790
- counts.set(key, (counts.get(key) ?? 0) + 1);
3791
- }
3792
- }
3793
- const label = field.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
3794
- return {
3795
- field,
3796
- label,
3797
- values: [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([value, count]) => ({ value, count }))
3798
- };
3909
+ async facet(field, params) {
3910
+ const label = field === "categoryIds" ? "Category" : field;
3911
+ if (field !== "categoryIds") return { field, label, values: [] };
3912
+ const terms = params?.query === void 0 ? null : uniqueTerms(params.query);
3913
+ if (terms !== null && terms.length === 0) return { field, label, values: [] };
3914
+ const values = await index.categoryCounts(
3915
+ terms,
3916
+ categoryFilter(params?.filters),
3917
+ params?.limit ?? null
3918
+ );
3919
+ return { field, label, values };
3799
3920
  }
3800
3921
  };
3801
3922
  }
@@ -3810,7 +3931,7 @@ function createNativeReviewsAdapter(deps) {
3810
3931
  return {
3811
3932
  kind: "reviews",
3812
3933
  providerName: "native",
3813
- capabilities: ["submit", "moderate", "aggregate"],
3934
+ capabilities: () => ["submit", "moderate", "aggregate"],
3814
3935
  producesEvents: [],
3815
3936
  consumesEvents: [EVT_ORDER_DELIVERED3],
3816
3937
  initialize: noopInitialize,
@@ -3860,7 +3981,7 @@ function createNativeAnalyticsAdapter(logger) {
3860
3981
  return {
3861
3982
  kind: "analytics",
3862
3983
  providerName: "native",
3863
- capabilities: ["track", "identify"],
3984
+ capabilities: () => ["track", "identify"],
3864
3985
  producesEvents: [],
3865
3986
  consumesEvents: [],
3866
3987
  initialize: noopInitialize,
@@ -3880,7 +4001,7 @@ function createNativeShippingAdapter(logger) {
3880
4001
  return {
3881
4002
  kind: "shipping",
3882
4003
  providerName: "native",
3883
- capabilities: ["flat-rate"],
4004
+ capabilities: () => ["flat-rate"],
3884
4005
  producesEvents: [],
3885
4006
  consumesEvents: [],
3886
4007
  initialize: noopInitialize,
@@ -3919,7 +4040,7 @@ function createNativeTaxAdapter(logger, defaultRate = 0) {
3919
4040
  return {
3920
4041
  kind: "tax",
3921
4042
  providerName: "native",
3922
- capabilities: ["flat-rate"],
4043
+ capabilities: () => ["flat-rate"],
3923
4044
  producesEvents: [],
3924
4045
  consumesEvents: [],
3925
4046
  initialize: noopInitialize,
@@ -3935,91 +4056,95 @@ function createNativeTaxAdapter(logger, defaultRate = 0) {
3935
4056
  };
3936
4057
  }
3937
4058
 
3938
- // src/adapters/ai/native-adapter.ts
3939
- import { AdapterError as AdapterError4 } from "@nymbalhq/types";
3940
- function createNativeAiAdapter(_logger) {
3941
- return {
3942
- kind: "ai",
3943
- providerName: "native",
3944
- capabilities: [],
3945
- producesEvents: [],
3946
- consumesEvents: [],
3947
- initialize: noopInitialize,
3948
- healthCheck: () => okHealth("AI adapter is stubbed \u2014 configure a real provider for v1.0"),
3949
- async embed() {
3950
- throw new AdapterError4("not_configured", "AI embedding is not configured in v0.1");
3951
- },
3952
- async complete() {
3953
- throw new AdapterError4("not_configured", "AI completion is not configured in v0.1");
4059
+ // src/adapters/registry.ts
4060
+ var COMMERCE_SLOTS = [
4061
+ "payments",
4062
+ "email",
4063
+ "reviews",
4064
+ "search",
4065
+ "analytics",
4066
+ "shipping",
4067
+ "tax",
4068
+ "ai"
4069
+ ];
4070
+ function checkInjectedAdapters(config, injected = {}) {
4071
+ for (const slot of COMMERCE_SLOTS) checkInjectedSlot(config, slot, injected);
4072
+ }
4073
+ function checkInjectedSlot(config, slot, injected = {}) {
4074
+ const provider = config.commerce[slot].provider;
4075
+ const given = injected[slot] !== void 0;
4076
+ if (provider === "custom" && !given) {
4077
+ throw new ConfigError4(
4078
+ `commerce.${slot}.provider is 'custom' but createApp was given no ${slot} adapter (createApp(config, { adapters: { ${slot} } })); nymbal dev takes it from the \`adapters\` export of nymbal.config.ts.`,
4079
+ { code: "adapter.custom_mismatch", context: { slot } }
4080
+ );
4081
+ }
4082
+ if (provider !== "custom" && given) {
4083
+ throw new ConfigError4(
4084
+ `createApp was given a ${slot} adapter, but commerce.${slot}.provider is '${provider}'; set it to 'custom' to use the injected adapter.`,
4085
+ { code: "adapter.custom_mismatch", context: { slot, provider } }
4086
+ );
4087
+ }
4088
+ }
4089
+ async function resolveSlot(slot, config, logger, injected, builtIns) {
4090
+ const block = config.commerce[slot];
4091
+ const blockConfig = block.config ?? {};
4092
+ let adapter;
4093
+ if (block.provider === "custom") {
4094
+ adapter = injected[slot];
4095
+ } else {
4096
+ adapter = await loadProviderAdapter(slot, block.provider, {
4097
+ config: blockConfig,
4098
+ logger: logger.child({ adapter: slot }),
4099
+ env: process.env
4100
+ });
4101
+ if (adapter === void 0 && Object.hasOwn(builtIns, block.provider)) {
4102
+ adapter = builtIns[block.provider]();
3954
4103
  }
3955
- };
4104
+ }
4105
+ if (adapter === void 0) {
4106
+ throw new ConfigError4(`commerce.${slot}.provider '${block.provider}' has no adapter`, {
4107
+ context: { slot, provider: block.provider }
4108
+ });
4109
+ }
4110
+ await adapter?.initialize(blockConfig);
4111
+ return adapter;
3956
4112
  }
3957
-
3958
- // src/adapters/ai/anthropic-adapter.ts
3959
- import Anthropic from "@anthropic-ai/sdk";
3960
- import { AdapterError as AdapterError5 } from "@nymbalhq/types";
3961
- function createAnthropicAiAdapter(config) {
3962
- const model = config.model ?? "claude-sonnet-4-6";
3963
- const client = new Anthropic({ apiKey: config.apiKey });
4113
+ function resolvePaymentsAdapter(config, logger, injected = {}) {
4114
+ return resolveSlot("payments", config, logger, injected, {
4115
+ native: () => createNativeStubPaymentsAdapter({ logger: logger.child({ adapter: "payments" }) })
4116
+ });
4117
+ }
4118
+ function slotBuilders(deps) {
4119
+ const { config, logger, sql: sql6, repos } = deps;
4120
+ const injected = deps.injected ?? {};
4121
+ const slot = (name, builtIns) => resolveSlot(name, config, logger, injected, builtIns);
3964
4122
  return {
3965
- kind: "ai",
3966
- providerName: "anthropic",
3967
- capabilities: ["complete"],
3968
- producesEvents: [],
3969
- consumesEvents: [],
3970
- initialize: noopInitialize,
3971
- healthCheck: () => okHealth(`Anthropic AI adapter using model ${model}`),
3972
- async embed() {
3973
- throw new AdapterError5("not_configured", "Embedding not yet supported by the Anthropic adapter");
3974
- },
3975
- async complete(prompt, opts) {
3976
- const maxTokens = opts?.maxTokens ?? 1024;
3977
- const message = await client.messages.create({
3978
- model,
3979
- max_tokens: maxTokens,
3980
- messages: [{ role: "user", content: prompt }]
3981
- });
3982
- const block = message.content[0];
3983
- if (!block || block.type !== "text") {
3984
- throw new AdapterError5("unexpected_response", "Anthropic returned no text content");
3985
- }
3986
- return block.text;
3987
- }
4123
+ email: () => slot("email", {
4124
+ native: () => createNativeEmailAdapter({ logger: logger.child({ adapter: "email" }) })
4125
+ }),
4126
+ search: () => slot("search", {
4127
+ native: () => createNativeSearchAdapter({ sql: sql6, logger: logger.child({ adapter: "search" }) })
4128
+ }),
4129
+ reviews: () => slot("reviews", {
4130
+ native: () => createNativeReviewsAdapter({ repos, logger: logger.child({ adapter: "reviews" }) })
4131
+ }),
4132
+ analytics: () => slot("analytics", { native: () => createNativeAnalyticsAdapter(logger) }),
4133
+ shipping: () => slot("shipping", { native: () => createNativeShippingAdapter(logger) }),
4134
+ tax: () => slot("tax", { native: () => createNativeTaxAdapter(logger) }),
4135
+ ai: () => slot("ai", { none: () => null })
3988
4136
  };
3989
4137
  }
3990
-
3991
- // src/adapters/registry.ts
3992
- function paymentsAdapterFor(provider) {
3993
- return provider === "stripe" ? "stripe" : "native-stub";
3994
- }
3995
4138
  async function buildAdapters(deps) {
3996
- const { config, logger, documentStore, repos } = deps;
3997
- const payments = paymentsAdapterFor(config.commerce.payments.provider) === "stripe" ? createStripePaymentsAdapter({
3998
- logger: logger.child({ adapter: "payments" }),
3999
- config: config.commerce.payments.config ?? {}
4000
- }) : createNativeStubPaymentsAdapter({ logger: logger.child({ adapter: "payments" }) });
4001
- const email = createNativeEmailAdapter({
4002
- logger: logger.child({ adapter: "email" }),
4003
- config: config.commerce.email.config ?? {}
4004
- });
4005
- await email.initialize(email ? config.commerce.email.config ?? {} : {});
4006
- const search = createNativeSearchAdapter({
4007
- documentStore,
4008
- logger: logger.child({ adapter: "search" })
4009
- });
4010
- const reviews3 = createNativeReviewsAdapter({
4011
- repos,
4012
- logger: logger.child({ adapter: "reviews" })
4013
- });
4014
- const analytics = createNativeAnalyticsAdapter(logger);
4015
- const shipping = createNativeShippingAdapter(logger);
4016
- const tax = createNativeTaxAdapter(logger);
4017
- const aiProvider = config.commerce.ai?.provider;
4018
- const ai = aiProvider === "anthropic" ? createAnthropicAiAdapter({
4019
- apiKey: process.env["ANTHROPIC_API_KEY"] ?? "",
4020
- model: config.commerce.ai?.config?.["model"] ?? "claude-sonnet-4-6",
4021
- logger: logger.child({ adapter: "ai" })
4022
- }) : createNativeAiAdapter(logger);
4139
+ const { logger, payments } = deps;
4140
+ const build = slotBuilders(deps);
4141
+ const email = await build.email();
4142
+ const search = await build.search();
4143
+ const reviews3 = await build.reviews();
4144
+ const analytics = await build.analytics();
4145
+ const shipping = await build.shipping();
4146
+ const tax = await build.tax();
4147
+ const ai = await build.ai();
4023
4148
  const security = createMiddlewareSecurityAdapter({
4024
4149
  logger: logger.child({ adapter: "security" })
4025
4150
  });
@@ -4926,7 +5051,7 @@ function createOrderService(deps) {
4926
5051
  // src/services/inventory-service.ts
4927
5052
  import { v7 as uuidv711 } from "uuid";
4928
5053
  import {
4929
- AdapterError as AdapterError6,
5054
+ AdapterError as AdapterError3,
4930
5055
  NotFoundError as NotFoundError6,
4931
5056
  ValidationError as ValidationError9,
4932
5057
  EVT_INVENTORY_CHANGED as EVT_INVENTORY_CHANGED2,
@@ -5025,7 +5150,7 @@ function createInventoryService(deps) {
5025
5150
  async reserveStock(variantId, qty, orderRef = null, ttlSeconds) {
5026
5151
  const taken = await take(variantId, qty, orderRef, ttlSeconds);
5027
5152
  if ("available" in taken) {
5028
- throw new AdapterError6(
5153
+ throw new AdapterError3(
5029
5154
  "inventory.insufficient",
5030
5155
  `Insufficient stock for variant ${variantId}`,
5031
5156
  {
@@ -5126,12 +5251,12 @@ import {
5126
5251
  EVT_CART_CONVERTED,
5127
5252
  EVT_CART_UPDATED as EVT_CART_UPDATED2,
5128
5253
  EVT_ORDER_PAID as EVT_ORDER_PAID4,
5129
- EVT_PAYMENT_CAPTURED as EVT_PAYMENT_CAPTURED3,
5130
- EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED3,
5131
- EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED3,
5254
+ EVT_PAYMENT_CAPTURED as EVT_PAYMENT_CAPTURED2,
5255
+ EVT_PAYMENT_FAILED as EVT_PAYMENT_FAILED2,
5256
+ EVT_PAYMENT_REFUNDED as EVT_PAYMENT_REFUNDED2,
5132
5257
  NotFoundError as NotFoundError7,
5133
5258
  OrderConflictError as OrderConflictError2,
5134
- PaymentError as PaymentError3,
5259
+ PaymentError as PaymentError2,
5135
5260
  StatusTransitionError as StatusTransitionError2
5136
5261
  } from "@nymbalhq/types";
5137
5262
  var StockUnavailable = class extends Error {
@@ -5203,7 +5328,7 @@ function createCheckoutService(deps) {
5203
5328
  return recordOutcome(tx, paymentIntentId, order, `order_not_pending: ${order.status}`);
5204
5329
  }
5205
5330
  async function recordOutcome(tx, paymentIntentId, order, reason, detail) {
5206
- await publisher.publish(EVT_PAYMENT_FAILED3, {
5331
+ await publisher.publish(EVT_PAYMENT_FAILED2, {
5207
5332
  paymentId: paymentIntentId,
5208
5333
  orderId: order?.id ?? "",
5209
5334
  reason
@@ -5259,7 +5384,7 @@ function createCheckoutService(deps) {
5259
5384
  }
5260
5385
  return settlement;
5261
5386
  } catch (err) {
5262
- if (err instanceof PaymentError3 && err.code === "payment.refund_rejected") {
5387
+ if (err instanceof PaymentError2 && err.code === "payment.refund_rejected") {
5263
5388
  logger.error({ ...context2, err }, "provider refused the refund of a capture");
5264
5389
  return { status: "failed", providerRefundId: null, mismatch: false };
5265
5390
  }
@@ -5308,7 +5433,7 @@ function createCheckoutService(deps) {
5308
5433
  });
5309
5434
  await refreshRefunded(repos, tx, order.id, /* @__PURE__ */ new Date());
5310
5435
  if (settlement.status === "succeeded") {
5311
- await publisher.publish(EVT_PAYMENT_REFUNDED3, {
5436
+ await publisher.publish(EVT_PAYMENT_REFUNDED2, {
5312
5437
  paymentId: paymentIntentId,
5313
5438
  orderId: order.id,
5314
5439
  refundId,
@@ -5383,7 +5508,7 @@ function createCheckoutService(deps) {
5383
5508
  if (order.customerId) {
5384
5509
  await repos.customer.incrementStats(tx, order.customerId, 1, paid.amountMinor, now);
5385
5510
  }
5386
- await publisher.publish(EVT_PAYMENT_CAPTURED3, {
5511
+ await publisher.publish(EVT_PAYMENT_CAPTURED2, {
5387
5512
  paymentId: paymentIntentId,
5388
5513
  orderId: order.id,
5389
5514
  amountMinor: paid.amountMinor,
@@ -5525,7 +5650,7 @@ function createCheckoutService(deps) {
5525
5650
  try {
5526
5651
  await payments.cancelPaymentIntent(order.paymentIntentId);
5527
5652
  } catch (err) {
5528
- if (!(err instanceof PaymentError3 && err.code === "payment.cancel_refused")) throw err;
5653
+ if (!(err instanceof PaymentError2 && err.code === "payment.cancel_refused")) throw err;
5529
5654
  throw new CheckoutError(
5530
5655
  "payment_in_progress",
5531
5656
  `The payment for order ${order.orderNumber} is already under way`,
@@ -5565,7 +5690,7 @@ function createCheckoutService(deps) {
5565
5690
  } else if (outcome === "failed") {
5566
5691
  const reason = `payment_${intent.status}`;
5567
5692
  await cancelDraft(order.id, reason);
5568
- await publisher.publish(EVT_PAYMENT_FAILED3, {
5693
+ await publisher.publish(EVT_PAYMENT_FAILED2, {
5569
5694
  paymentId: intent.id,
5570
5695
  orderId: order.id,
5571
5696
  reason
@@ -5662,7 +5787,7 @@ function createCheckoutService(deps) {
5662
5787
  try {
5663
5788
  await payments.cancelPaymentIntent(found.paymentIntentId);
5664
5789
  } catch (err) {
5665
- if (!(err instanceof PaymentError3 && err.code === "payment.cancel_refused")) throw err;
5790
+ if (!(err instanceof PaymentError2 && err.code === "payment.cancel_refused")) throw err;
5666
5791
  throw new OrderConflictError2(
5667
5792
  "order.payment_in_progress",
5668
5793
  `The payment for order ${found.orderNumber} is under way with the provider`,
@@ -5835,7 +5960,7 @@ async function warmDocumentStore(deps) {
5835
5960
  if (events3.length > 0) {
5836
5961
  await eventBus.replay(events3);
5837
5962
  }
5838
- logger.info(
5963
+ logger.debug(
5839
5964
  { products: products3.length, orders: orders3.length, customers: customers3.length },
5840
5965
  `Warmed document store: ${products3.length} products, ${orders3.length} orders, ${customers3.length} customers`
5841
5966
  );
@@ -5960,126 +6085,178 @@ function startEventRetentionSweeper(deps) {
5960
6085
  }
5961
6086
 
5962
6087
  // src/app.ts
5963
- function refuseUnsafeProduction(config) {
6088
+ function refuseUnsafeProduction(config, payments) {
5964
6089
  if (process.env.NODE_ENV !== "production") return;
5965
6090
  const provider = config.commerce.payments.provider;
5966
- if (paymentsAdapterFor(provider) === "native-stub") {
5967
- throw new ConfigError4(
6091
+ if (payments.providerName === "native-stub") {
6092
+ throw new ConfigError5(
5968
6093
  `Payments provider "${provider}" resolves to the stub adapter, which verifies no webhook signature; configure a real payments provider for production.`,
5969
6094
  { code: "config.production_stub_payments", context: { provider } }
5970
6095
  );
5971
6096
  }
5972
6097
  if (config.security.auth.jwtSecret === DEFAULT_JWT_SECRET) {
5973
- throw new ConfigError4(
6098
+ throw new ConfigError5(
5974
6099
  "security.auth.jwtSecret is the schema default; set a secret of your own for production.",
5975
6100
  { code: "config.production_default_jwt_secret" }
5976
6101
  );
5977
6102
  }
5978
6103
  }
5979
6104
  async function createApp(config, options = {}) {
5980
- refuseUnsafeProduction(config);
5981
- const platform = createPlatform(config, options);
5982
- const version = options.version ?? "0.1.0";
5983
- const logger = platform.logger;
5984
- const repos = buildRepositories(platform.commandStore, platform.documentStore);
5985
- const adapters = await buildAdapters({
5986
- config,
5987
- logger: logger.child({ layer: "adapter" }),
5988
- documentStore: platform.documentStore,
5989
- repos
5990
- });
5991
- const relay = createRelay({
5992
- store: platform.commandStore,
5993
- eventLog: repos.eventLog,
5994
- eventBus: platform.eventBus,
5995
- logger
5996
- });
5997
- const publisher = createEventPublisher({
5998
- eventBus: platform.eventBus,
5999
- store: platform.commandStore,
6000
- eventLog: repos.eventLog,
6001
- relay,
6002
- builderContext: {
6003
- storeId: config.store.name,
6004
- environment: process.env.NODE_ENV === "production" ? "production" : process.env.NODE_ENV === "staging" ? "staging" : "development",
6005
- version,
6006
- source: "nymbal-app"
6007
- }
6008
- });
6009
- const services = buildServices({
6010
- config,
6011
- store: platform.commandStore,
6012
- repos,
6013
- publisher,
6014
- logger: logger.child({ layer: "service" }),
6015
- payments: adapters.payments,
6016
- searchAdapter: adapters.search
6017
- });
6018
- await registerHandlers({
6019
- config,
6020
- eventBus: platform.eventBus,
6021
- documentStore: platform.documentStore,
6022
- repos,
6023
- adapters,
6024
- logger
6025
- });
6026
- await warmDocumentStore({
6027
- config,
6028
- repos,
6029
- eventBus: platform.eventBus,
6030
- logger,
6031
- version
6032
- });
6033
- await relay.drain();
6034
- relay.start();
6035
- const sweepers = [
6036
- startInventoryReservationSweeper({
6037
- inventoryService: services.inventory,
6038
- reservationRepo: repos.inventoryReservation,
6039
- logger
6040
- }),
6041
- startCartAbandonmentSweeper({
6105
+ const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
6106
+ const adapterLogger = logger.child({ layer: "adapter" });
6107
+ checkInjectedAdapters(config, options.adapters);
6108
+ const payments = await resolvePaymentsAdapter(config, adapterLogger, options.adapters);
6109
+ refuseUnsafeProduction(config, payments);
6110
+ const primitives = await resolvePrimitives(config, { ...options, logger });
6111
+ let release = async () => {
6112
+ await primitives.eventBus.close();
6113
+ await primitives.documentStore.close();
6114
+ };
6115
+ try {
6116
+ const platform = createPlatform(config, { ...options, ...primitives, logger });
6117
+ release = () => platform.close();
6118
+ const version = options.version ?? "0.1.0";
6119
+ const repos = buildRepositories(platform.commandStore, platform.documentStore);
6120
+ const adapters = await buildAdapters({
6121
+ config,
6122
+ logger: adapterLogger,
6123
+ sql: rawClients(platform.commandStore),
6124
+ repos,
6125
+ payments,
6126
+ ...options.adapters !== void 0 && { injected: options.adapters }
6127
+ });
6128
+ const relay = createRelay({
6042
6129
  store: platform.commandStore,
6043
- carts: repos.cart,
6044
- publisher,
6130
+ eventLog: repos.eventLog,
6131
+ eventBus: platform.eventBus,
6045
6132
  logger
6046
- }),
6047
- startEventRetentionSweeper({
6133
+ });
6134
+ const subscriberBus = deliveringBus(platform.eventBus, relay);
6135
+ const publisher = createEventPublisher({
6136
+ eventBus: platform.eventBus,
6048
6137
  store: platform.commandStore,
6049
6138
  eventLog: repos.eventLog,
6050
- processedEvents: repos.processedEvent,
6139
+ relay,
6140
+ builderContext: {
6141
+ storeId: config.store.name,
6142
+ environment: process.env.NODE_ENV === "production" ? "production" : process.env.NODE_ENV === "staging" ? "staging" : "development",
6143
+ version,
6144
+ source: "nymbal-app"
6145
+ }
6146
+ });
6147
+ const services = buildServices({
6148
+ config,
6149
+ store: platform.commandStore,
6150
+ repos,
6151
+ publisher,
6152
+ logger: logger.child({ layer: "service" }),
6153
+ payments: adapters.payments,
6154
+ searchAdapter: adapters.search
6155
+ });
6156
+ await registerHandlers({
6157
+ config,
6158
+ eventBus: subscriberBus,
6159
+ documentStore: platform.documentStore,
6160
+ repos,
6161
+ adapters,
6051
6162
  logger
6052
- })
6053
- ];
6054
- const app = {
6055
- platform,
6056
- repos,
6057
- adapters,
6058
- services,
6059
- publisher,
6060
- relay,
6061
- async attachHttp(adapter, options2 = {}) {
6062
- await adapters.security.applyMiddleware(adapter, config.security);
6063
- const { registerAllRoutes: registerAllRoutes2 } = await import("./register-IVFYBJSX.js");
6064
- registerAllRoutes2({
6065
- config,
6066
- adapter,
6067
- services,
6068
- adapters,
6069
- repos,
6070
- documentStore: platform.documentStore,
6071
- eventBus: platform.eventBus,
6163
+ });
6164
+ await warmDocumentStore({
6165
+ config,
6166
+ repos,
6167
+ eventBus: platform.eventBus,
6168
+ logger,
6169
+ version
6170
+ });
6171
+ await relay.drain();
6172
+ relay.start();
6173
+ const sweepers = [
6174
+ startInventoryReservationSweeper({
6175
+ inventoryService: services.inventory,
6176
+ reservationRepo: repos.inventoryReservation,
6177
+ logger
6178
+ }),
6179
+ startCartAbandonmentSweeper({
6180
+ store: platform.commandStore,
6181
+ carts: repos.cart,
6072
6182
  publisher,
6073
- adminRoot: options2.adminRoot !== void 0 ? options2.adminRoot : process.env["NYMBAL_ADMIN_DIST"]
6074
- });
6075
- },
6076
- async stop() {
6077
- await relay.stop();
6078
- for (const s of sweepers) s.stop();
6079
- await platform.close();
6080
- }
6081
- };
6082
- return app;
6183
+ logger
6184
+ }),
6185
+ startEventRetentionSweeper({
6186
+ store: platform.commandStore,
6187
+ eventLog: repos.eventLog,
6188
+ processedEvents: repos.processedEvent,
6189
+ logger
6190
+ })
6191
+ ];
6192
+ const app = {
6193
+ platform,
6194
+ repos,
6195
+ adapters,
6196
+ services,
6197
+ publisher,
6198
+ relay,
6199
+ async attachHttp(adapter, options2 = {}) {
6200
+ await adapters.security.applyMiddleware(adapter, config.security);
6201
+ const { registerAllRoutes: registerAllRoutes2 } = await import("./register-FJA7YJV3.js");
6202
+ registerAllRoutes2({
6203
+ config,
6204
+ adapter,
6205
+ services,
6206
+ adapters,
6207
+ repos,
6208
+ documentStore: platform.documentStore,
6209
+ eventBus: subscriberBus,
6210
+ publisher,
6211
+ adminRoot: options2.adminRoot !== void 0 ? options2.adminRoot : process.env["NYMBAL_ADMIN_DIST"]
6212
+ });
6213
+ },
6214
+ capabilities() {
6215
+ const commerce = Object.fromEntries(
6216
+ COMMERCE_SLOTS.map((slot) => {
6217
+ const adapter = adapters[slot];
6218
+ return [
6219
+ slot,
6220
+ {
6221
+ provider: config.commerce[slot].provider,
6222
+ capabilities: adapter === null ? [] : adapter.capabilities()
6223
+ }
6224
+ ];
6225
+ })
6226
+ );
6227
+ return {
6228
+ ...commerce,
6229
+ security: {
6230
+ provider: config.security.adapter,
6231
+ capabilities: adapters.security.capabilities()
6232
+ },
6233
+ documentStore: {
6234
+ provider: config.infrastructure.documentStore,
6235
+ capabilities: platform.documentStore.capabilities()
6236
+ },
6237
+ eventBus: {
6238
+ provider: config.infrastructure.eventBus,
6239
+ capabilities: platform.eventBus.capabilities()
6240
+ },
6241
+ media: {
6242
+ provider: config.infrastructure.media,
6243
+ capabilities: platform.media.capabilities()
6244
+ }
6245
+ };
6246
+ },
6247
+ async stop() {
6248
+ await relay.stop();
6249
+ for (const s of sweepers) s.stop();
6250
+ await platform.close();
6251
+ }
6252
+ };
6253
+ return app;
6254
+ } catch (error) {
6255
+ await release().catch(
6256
+ (err) => logger.error({ err }, "closing the primitives after a failed start failed")
6257
+ );
6258
+ throw error;
6259
+ }
6083
6260
  }
6084
6261
 
6085
6262
  // src/adapters/security/rate-limit.ts
@@ -6141,6 +6318,296 @@ function compilePathPattern(pattern) {
6141
6318
  return new RegExp(`^${escaped}$`);
6142
6319
  }
6143
6320
 
6321
+ // src/adapters/ai/native-adapter.ts
6322
+ import { AdapterError as AdapterError4 } from "@nymbalhq/types";
6323
+ function createNativeAiAdapter(_logger) {
6324
+ return {
6325
+ kind: "ai",
6326
+ providerName: "native",
6327
+ capabilities: () => [],
6328
+ producesEvents: [],
6329
+ consumesEvents: [],
6330
+ initialize: noopInitialize,
6331
+ healthCheck: () => okHealth("AI adapter is stubbed \u2014 configure a real provider for v1.0"),
6332
+ async embed() {
6333
+ throw new AdapterError4("not_configured", "AI embedding is not configured in v0.1");
6334
+ },
6335
+ async complete() {
6336
+ throw new AdapterError4("not_configured", "AI completion is not configured in v0.1");
6337
+ }
6338
+ };
6339
+ }
6340
+
6341
+ // src/diagnose.ts
6342
+ import { existsSync as existsSync2 } from "fs";
6343
+ import { resolve as resolve3 } from "path";
6344
+ import { fileURLToPath } from "url";
6345
+ import { nymbalConfigSchema } from "@nymbalhq/config";
6346
+ import {
6347
+ boundedHealthCheck,
6348
+ connectionSecrets,
6349
+ displayUrl,
6350
+ errorText,
6351
+ HEALTH_CHECK_TIMEOUT_MS
6352
+ } from "@nymbalhq/types";
6353
+ var OWN_MIGRATIONS = fileURLToPath(new URL("../migrations", import.meta.url));
6354
+ var PRIMITIVES = ["documentStore", "eventBus", "media"];
6355
+ async function within(timeoutMs, run, dispose) {
6356
+ let timer;
6357
+ let timedOut = false;
6358
+ const work = Promise.resolve().then(run);
6359
+ const timeout = new Promise((resolveTimeout) => {
6360
+ timer = setTimeout(() => {
6361
+ timedOut = true;
6362
+ resolveTimeout({ ok: false, detail: `timed out after ${timeoutMs} ms` });
6363
+ }, timeoutMs);
6364
+ });
6365
+ try {
6366
+ return await Promise.race([
6367
+ work.then(
6368
+ (value) => ({ ok: true, value }),
6369
+ (error) => ({ ok: false, detail: errorText(error) })
6370
+ ),
6371
+ timeout
6372
+ ]);
6373
+ } finally {
6374
+ clearTimeout(timer);
6375
+ if (timedOut && dispose !== void 0) {
6376
+ work.then(dispose).catch(() => void 0);
6377
+ }
6378
+ }
6379
+ }
6380
+ function unavailableCommandStore(kind) {
6381
+ const refuse = () => Promise.reject(new Error("the command store is down"));
6382
+ return { kind, read: refuse, transaction: refuse, savepoint: refuse, close: async () => {
6383
+ } };
6384
+ }
6385
+ function unavailableRawClients(kind) {
6386
+ const refuse = () => {
6387
+ throw new Error("the command store is down");
6388
+ };
6389
+ const client = new Proxy({}, { get: () => refuse });
6390
+ return kind === "sqlite" ? { kind, db: client, raw: client } : { kind, db: client, pool: client };
6391
+ }
6392
+ function unavailableDocumentStore() {
6393
+ const refuse = () => Promise.reject(new Error("the document store is down"));
6394
+ return {
6395
+ capabilities: () => [],
6396
+ get: refuse,
6397
+ put: refuse,
6398
+ delete: refuse,
6399
+ query: refuse,
6400
+ batchGet: refuse,
6401
+ batchPut: refuse,
6402
+ close: async () => {
6403
+ }
6404
+ };
6405
+ }
6406
+ function described(what, detail) {
6407
+ return detail === void 0 || detail === "" ? what : `${what}: ${detail}`;
6408
+ }
6409
+ function notChecked(prerequisite) {
6410
+ return `not checked: ${prerequisite} down`;
6411
+ }
6412
+ async function diagnose(input, options = {}) {
6413
+ const parsed = nymbalConfigSchema.safeParse(input);
6414
+ if (!parsed.success) {
6415
+ const detail = parsed.error.issues.map((issue) => `${issue.path.length > 0 ? issue.path.join(".") : "<root>"}: ${issue.message}`).join("; ");
6416
+ return { checks: [{ name: "config", status: "down", detail }] };
6417
+ }
6418
+ const config = parsed.data;
6419
+ const timeoutMs = options.timeoutMs ?? HEALTH_CHECK_TIMEOUT_MS;
6420
+ const env = options.env ?? process.env;
6421
+ const logger = options.logger ?? createLogger({ base: { store: config.store.name } });
6422
+ const injected = options.adapters ?? {};
6423
+ const infrastructure = config.infrastructure;
6424
+ const providers = {
6425
+ ...Object.fromEntries(COMMERCE_SLOTS.map((s) => [s, config.commerce[s].provider])),
6426
+ documentStore: infrastructure.documentStore,
6427
+ eventBus: infrastructure.eventBus,
6428
+ media: infrastructure.media
6429
+ };
6430
+ const packages = [];
6431
+ for (const slot of [...COMMERCE_SLOTS, ...PRIMITIVES]) {
6432
+ const entry = PROVIDER_PACKAGES[slot]?.[providers[slot]];
6433
+ if (entry === void 0) continue;
6434
+ const found = await within(
6435
+ timeoutMs,
6436
+ () => importProviderPackage(slot, providers[slot], env)
6437
+ );
6438
+ packages.push({
6439
+ name: `package ${slot}`,
6440
+ status: found.ok ? "ok" : "down",
6441
+ detail: found.ok ? entry.package : found.detail
6442
+ });
6443
+ }
6444
+ const closers = [];
6445
+ let commandStore;
6446
+ let storeCheck;
6447
+ let migrationsCheck;
6448
+ const storeOptions = {
6449
+ readOnly: true,
6450
+ ...options.sqlitePath !== void 0 && { sqlitePath: options.sqlitePath },
6451
+ ...options.postgresUrl !== void 0 && { postgresUrl: options.postgresUrl }
6452
+ };
6453
+ const postgresUrl = options.postgresUrl ?? (env["DATABASE_URL"] === "" ? void 0 : env["DATABASE_URL"]);
6454
+ const redisUrl = redisUrlOf(config, env);
6455
+ const where = infrastructure.commandStore === "sqlite" ? `sqlite ${sqliteFile(storeOptions)}` : `postgres ${postgresUrl === void 0 ? "(no DATABASE_URL)" : displayUrl(postgresUrl)}`;
6456
+ if (infrastructure.commandStore === "sqlite" && !existsSync2(resolve3(sqliteFile(storeOptions)))) {
6457
+ storeCheck = {
6458
+ name: "command store",
6459
+ status: "down",
6460
+ detail: `no database at ${sqliteFile(storeOptions)}: run \`nymbal migrate\``
6461
+ };
6462
+ } else {
6463
+ const opened = await within(
6464
+ timeoutMs,
6465
+ async () => {
6466
+ const store = createCommandStore(config, storeOptions);
6467
+ try {
6468
+ const clients = rawClients(store);
6469
+ if (clients.kind === "sqlite") clients.raw.prepare("SELECT 1").get();
6470
+ else await clients.pool.query("SELECT 1");
6471
+ return store;
6472
+ } catch (error) {
6473
+ await store.close().catch(() => void 0);
6474
+ throw error;
6475
+ }
6476
+ },
6477
+ (late) => late.close()
6478
+ );
6479
+ if (opened.ok) {
6480
+ commandStore = opened.value;
6481
+ closers.push(() => opened.value.close());
6482
+ storeCheck = { name: "command store", status: "healthy", detail: where };
6483
+ } else {
6484
+ storeCheck = { name: "command store", status: "down", detail: `${where}: ${opened.detail}` };
6485
+ }
6486
+ }
6487
+ if (commandStore === void 0) {
6488
+ migrationsCheck = { name: "migrations", status: "down", detail: notChecked("command store") };
6489
+ } else {
6490
+ const store = commandStore;
6491
+ const state = await within(
6492
+ timeoutMs,
6493
+ () => migrationState(store, { migrationsRoot: options.migrationsRoot ?? OWN_MIGRATIONS })
6494
+ );
6495
+ migrationsCheck = !state.ok ? { name: "migrations", status: "down", detail: state.detail } : state.value.pending > 0 ? {
6496
+ name: "migrations",
6497
+ status: "down",
6498
+ detail: `${state.value.pending} pending: run \`nymbal migrate\``
6499
+ } : { name: "migrations", status: "ok", detail: `${state.value.applied} applied, none pending` };
6500
+ }
6501
+ const primitiveOptions = {
6502
+ logger,
6503
+ env,
6504
+ ...options.postgresUrl !== void 0 && { postgresUrl: options.postgresUrl },
6505
+ ...options.mediaRoot !== void 0 && { mediaRoot: options.mediaRoot }
6506
+ };
6507
+ const subject = (name) => {
6508
+ const provider = providers[name];
6509
+ const url = provider === "redis" || provider === "redis-streams" ? redisUrl : provider === "postgres-jsonb" ? postgresUrl : void 0;
6510
+ return url === void 0 ? provider : `${provider} ${displayUrl(url)}`;
6511
+ };
6512
+ const built = {};
6513
+ const primitiveFailures = {};
6514
+ let documentStore;
6515
+ if (infrastructure.documentStore === "postgres-jsonb" && commandStore === void 0) {
6516
+ primitiveFailures.documentStore = notChecked("command store");
6517
+ } else {
6518
+ const store = await within(
6519
+ timeoutMs,
6520
+ () => buildDocumentStore(config, primitiveOptions, logger, env),
6521
+ (late) => late.close()
6522
+ );
6523
+ if (store.ok) {
6524
+ documentStore = store.value;
6525
+ built.documentStore = store.value;
6526
+ closers.unshift(() => store.value.close());
6527
+ } else {
6528
+ primitiveFailures.documentStore = described(subject("documentStore"), store.detail);
6529
+ }
6530
+ }
6531
+ const bus = await within(
6532
+ timeoutMs,
6533
+ () => buildEventBus(config, logger, env),
6534
+ (late) => late.close()
6535
+ );
6536
+ if (bus.ok) {
6537
+ built.eventBus = bus.value;
6538
+ closers.unshift(() => bus.value.close());
6539
+ } else {
6540
+ primitiveFailures.eventBus = described(subject("eventBus"), bus.detail);
6541
+ }
6542
+ const media = await within(timeoutMs, () => buildMedia(config, primitiveOptions, logger, env));
6543
+ if (media.ok) built.media = media.value;
6544
+ else primitiveFailures.media = described(subject("media"), media.detail);
6545
+ const health = (subject2) => {
6546
+ if (typeof subject2.healthCheck !== "function") {
6547
+ return Promise.resolve({ status: "degraded", detail: "no healthCheck" });
6548
+ }
6549
+ const check = subject2.healthCheck.bind(subject2);
6550
+ return boundedHealthCheck(() => check(), { timeoutMs });
6551
+ };
6552
+ const slots = [];
6553
+ const adapterLogger = logger.child({ layer: "adapter" });
6554
+ const builders = slotBuilders({
6555
+ config,
6556
+ logger: adapterLogger,
6557
+ sql: commandStore === void 0 ? unavailableRawClients(infrastructure.commandStore) : rawClients(commandStore),
6558
+ repos: buildRepositories(
6559
+ commandStore ?? unavailableCommandStore(infrastructure.commandStore),
6560
+ documentStore ?? unavailableDocumentStore()
6561
+ ),
6562
+ injected
6563
+ });
6564
+ for (const slot of COMMERCE_SLOTS) {
6565
+ const provider = providers[slot];
6566
+ const adapter = await within(timeoutMs, async () => {
6567
+ checkInjectedSlot(config, slot, injected);
6568
+ return slot === "payments" ? resolvePaymentsAdapter(config, adapterLogger, injected) : builders[slot]();
6569
+ });
6570
+ if (!adapter.ok) {
6571
+ slots.push({ name: `slot ${slot}`, status: "down", detail: described(provider, adapter.detail) });
6572
+ } else if (adapter.value === null) {
6573
+ slots.push({ name: `slot ${slot}`, status: "ok", detail: provider });
6574
+ } else {
6575
+ slots.push(fromReport(`slot ${slot}`, provider, await health(adapter.value)));
6576
+ }
6577
+ }
6578
+ const primitives = [];
6579
+ for (const name of PRIMITIVES) {
6580
+ const primitive = built[name];
6581
+ if (primitive === void 0) {
6582
+ primitives.push({ name: `primitive ${name}`, status: "down", detail: primitiveFailures[name] ?? "" });
6583
+ } else {
6584
+ primitives.push(fromReport(`primitive ${name}`, subject(name), await health(primitive)));
6585
+ }
6586
+ }
6587
+ for (const close of closers) {
6588
+ const closed = await within(timeoutMs, close);
6589
+ if (!closed.ok) logger.debug({ detail: closed.detail }, "diagnose: a connection did not close");
6590
+ }
6591
+ const secrets = [postgresUrl, redisUrl].flatMap(
6592
+ (url) => url === void 0 ? [] : connectionSecrets(url, { user: false })
6593
+ );
6594
+ const checks = [
6595
+ { name: "config", status: "ok", detail: "valid" },
6596
+ ...packages,
6597
+ storeCheck,
6598
+ migrationsCheck,
6599
+ ...slots,
6600
+ ...primitives
6601
+ ].map((check) => ({
6602
+ ...check,
6603
+ detail: secrets.reduce((text, secret) => text.split(secret).join("***"), check.detail)
6604
+ }));
6605
+ return { checks };
6606
+ }
6607
+ function fromReport(name, what, report) {
6608
+ return { name, status: report.status, detail: described(what, report.detail) };
6609
+ }
6610
+
6144
6611
  // src/seed/run.ts
6145
6612
  import { inArray as inArray3 } from "drizzle-orm";
6146
6613
  import { v7 as uuidv713 } from "uuid";
@@ -6553,35 +7020,20 @@ async function runSeed(deps) {
6553
7020
  alreadySeeded: false
6554
7021
  };
6555
7022
  }
6556
-
6557
- // src/media/local-fs-storage.ts
6558
- import { mkdir, writeFile } from "fs/promises";
6559
- import { join as join2 } from "path";
6560
- function createLocalFsMediaStorage(options) {
6561
- const { root } = options;
6562
- const urlPrefix = options.urlPrefix ?? "/imported-media";
6563
- return {
6564
- async put(key, body, _contentType) {
6565
- const dest = join2(root, key);
6566
- const dir = dest.substring(0, dest.lastIndexOf("/"));
6567
- await mkdir(dir, { recursive: true });
6568
- await writeFile(dest, body);
6569
- return { url: `${urlPrefix}/${key}` };
6570
- }
6571
- };
6572
- }
6573
7023
  export {
6574
7024
  CSRF_COOKIE,
6575
7025
  CSRF_HEADER,
6576
7026
  InMemoryDocumentStore,
6577
7027
  InProcessEventBus,
7028
+ LOCAL_FS_MEDIA_CAPABILITIES,
7029
+ PROVIDER_PACKAGES,
6578
7030
  PROVIDER_REFUND_REASON,
7031
+ REDIS_DEFAULTS,
6579
7032
  RateLimiter,
6580
7033
  buildAdapters,
6581
7034
  buildRepositories,
6582
7035
  buildSecurityHeaders,
6583
7036
  buildServices,
6584
- createAnthropicAiAdapter,
6585
7037
  createApp,
6586
7038
  createAuthService,
6587
7039
  createCartRepository,
@@ -6592,9 +7044,7 @@ export {
6592
7044
  createCommandStore,
6593
7045
  createCustomerRepository,
6594
7046
  createCustomerService,
6595
- createDocumentStore,
6596
7047
  createEventBuilder,
6597
- createEventBus,
6598
7048
  createEventLogRepository,
6599
7049
  createEventPublisher,
6600
7050
  createInventoryReservationRepository,
@@ -6628,21 +7078,24 @@ export {
6628
7078
  createReviewRepository,
6629
7079
  createSearchService,
6630
7080
  createStockAdjustmentRepository,
6631
- createStripePaymentsAdapter,
6632
7081
  createVariantRepository,
7082
+ diagnose,
7083
+ encodeSearchCursor,
7084
+ installLine,
6633
7085
  orderPayment,
6634
- paymentsAdapterFor,
6635
7086
  rawClients,
6636
7087
  refreshRefunded,
6637
7088
  registerAdminStaticRoute,
6638
7089
  registerAllRoutes,
6639
7090
  registerHandlers,
7091
+ resolvePrimitives,
6640
7092
  routeSchemas,
6641
7093
  runMigrations,
6642
7094
  runSeed,
6643
7095
  seedCategories,
6644
7096
  seedProducts,
6645
7097
  settlementOf,
7098
+ sqliteFile,
6646
7099
  startCartAbandonmentSweeper,
6647
7100
  startEventRetentionSweeper,
6648
7101
  startInventoryReservationSweeper,