@seedcord/plugins 0.3.3 → 0.4.1

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.mjs CHANGED
@@ -1,30 +1,37 @@
1
- import mongoose2 from 'mongoose';
2
1
  import 'reflect-metadata';
3
- import chalk from 'chalk';
2
+ import chalk3 from 'chalk';
4
3
  import { Envapter } from 'envapt';
5
- import { Plugin, Logger, ShutdownPhase, traverseDirectory, CustomError, throwCustomError, DatabaseError } from 'seedcord';
4
+ import mongoose from 'mongoose';
5
+ import { Plugin, Logger, ShutdownPhase, traverseDirectory, keepDefined as keepDefined$1, CustomError, throwCustomError, DatabaseError } from 'seedcord';
6
+ import { Pool } from 'pg';
7
+ import { promises } from 'fs';
8
+ import path from 'path';
9
+ import { pathToFileURL } from 'url';
10
+ import { inspect } from 'util';
11
+ import { keepDefined } from '@seedcord/utils';
12
+ import { Migrator, FileMigrationProvider, Kysely, PostgresDialect, NO_MIGRATIONS } from 'kysely';
6
13
 
7
14
  var __defProp = Object.defineProperty;
8
15
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
16
+
17
+ // src/mongo/decorators/RegisterMongoService.ts
18
+ var ServiceMetadataKey = Symbol("db:serviceKey");
19
+ function RegisterMongoService(key) {
20
+ return (ctor) => {
21
+ Reflect.defineMetadata(ServiceMetadataKey, key, ctor);
22
+ };
23
+ }
24
+ __name(RegisterMongoService, "RegisterMongoService");
9
25
  var ModelMetadataKey = Symbol("db:model");
10
- function DatabaseModel(collection) {
26
+ function RegisterMongoModel(collection) {
11
27
  return (target, propertyKey) => {
12
28
  const schema = target[propertyKey];
13
29
  const name = String(collection);
14
- const model = mongoose2.model(name, schema);
30
+ const model = mongoose.model(name, schema);
15
31
  Reflect.defineMetadata(ModelMetadataKey, model, target);
16
32
  };
17
33
  }
18
- __name(DatabaseModel, "DatabaseModel");
19
-
20
- // src/mongo/decorators/DatabaseService.ts
21
- var ServiceMetadataKey = Symbol("db:serviceKey");
22
- function DatabaseService(key) {
23
- return (ctor) => {
24
- Reflect.defineMetadata(ServiceMetadataKey, key, ctor);
25
- };
26
- }
27
- __name(DatabaseService, "DatabaseService");
34
+ __name(RegisterMongoModel, "RegisterMongoModel");
28
35
 
29
36
  // src/mongo/MongoService.ts
30
37
  var MongoService = class {
@@ -39,13 +46,15 @@ var MongoService = class {
39
46
  this.core = core;
40
47
  const ctor = this.constructor;
41
48
  const key = Reflect.getMetadata(ServiceMetadataKey, ctor);
42
- if (!key) throw new Error(`Missing @DatabaseService on ${ctor.name}`);
49
+ if (!key) throw new Error(`Missing @RegisterMongoService on ${ctor.name}`);
43
50
  const model = Reflect.getMetadata(ModelMetadataKey, ctor);
44
- if (!model) throw new Error(`Missing @DatabaseModel on ${ctor.name}`);
51
+ if (!model) throw new Error(`Missing @RegisterMongoModel on ${ctor.name}`);
45
52
  this.model = model;
46
53
  db._register(key, this);
47
54
  }
48
55
  };
56
+
57
+ // src/mongo/Mongo.ts
49
58
  var Mongo = class extends Plugin {
50
59
  static {
51
60
  __name(this, "Mongo");
@@ -57,7 +66,7 @@ var Mongo = class extends Plugin {
57
66
  uri;
58
67
  /**
59
68
  * Map of all loaded services.
60
- * Keys come from `@DatabaseService('key')`
69
+ * Keys come from `@RegisterMongoService('key')`
61
70
  */
62
71
  services = {};
63
72
  constructor(core, options) {
@@ -75,40 +84,662 @@ var Mongo = class extends Plugin {
75
84
  await this.disconnect();
76
85
  }
77
86
  async connect() {
78
- await mongoose2.connect(this.uri, {
87
+ this.connection = await mongoose.connect(this.uri, {
79
88
  dbName: this.options.name,
80
89
  ...Envapter.isProduction && {
81
90
  tls: true,
82
91
  ssl: true
83
92
  }
84
- }).then((i) => this.logger.info(`Connected to MongoDB: ${chalk.bold.magenta(i.connection.name)}`)).catch((err) => {
93
+ }).then((conn) => {
94
+ this.logger.info(chalk3.green.bold(`Connected to MongoDB: ${chalk3.magenta.bold(conn.connection.name)}`));
95
+ return conn;
96
+ }).catch((err) => {
85
97
  throw new Error(`Could not connect to MongoDB`, err);
86
98
  });
87
99
  }
88
100
  async disconnect() {
89
- await mongoose2.disconnect().then(() => this.logger.info(chalk.red.bold("Disconnected from MongoDB"))).catch((err) => this.logger.error(`Could not disconnect from MongoDB: ${err.message}`));
101
+ await this.connection.disconnect().then(() => this.logger.info(chalk3.red.bold("Disconnected from MongoDB"))).catch((err) => this.logger.error(`Could not disconnect from MongoDB: ${err.message}`));
90
102
  }
91
103
  async loadServices() {
92
104
  const servicesDir = this.options.dir;
93
- this.logger.info(chalk.bold(servicesDir));
105
+ this.logger.info(chalk3.bold(servicesDir));
94
106
  await traverseDirectory(servicesDir, (_full, rel, mod) => {
95
107
  for (const Service of Object.values(mod)) {
96
108
  if (this.isServiceClass(Service)) {
97
109
  const instance = new Service(this, this.core);
98
- this.logger.info(`${chalk.italic("Registered")} ${chalk.bold.yellow(instance.constructor.name)} from ${chalk.gray(rel)}`);
110
+ this.logger.info(`${chalk3.italic("Registered")} ${chalk3.bold.yellow(instance.constructor.name)} from ${chalk3.gray(rel)}`);
99
111
  }
100
112
  }
101
113
  }, this.logger);
102
- this.logger.info(`${chalk.bold.green("Loaded")}: ${chalk.magenta(Object.keys(this.services).length)} services`);
114
+ this.logger.info(`${chalk3.bold.green("Loaded")}: ${chalk3.magenta(Object.keys(this.services).length)} services`);
103
115
  }
104
116
  isServiceClass(obj) {
105
117
  return typeof obj === "function" && obj.prototype instanceof MongoService && Reflect.hasMetadata(ServiceMetadataKey, obj);
106
118
  }
119
+ /**
120
+ * Register hook used by decorated services.
121
+ *
122
+ * @internal
123
+ */
107
124
  _register(key, instance) {
108
125
  this.services[key] = instance;
109
126
  }
110
127
  };
111
- function DBCatchable(errorMessage) {
128
+ var KpgDatabaseBootstrapper = class _KpgDatabaseBootstrapper {
129
+ static {
130
+ __name(this, "KpgDatabaseBootstrapper");
131
+ }
132
+ logger;
133
+ static ADMIN_DB = "postgres";
134
+ static DATABASE_EXISTS_SQL = 'SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1) AS "exists"';
135
+ constructor(logger) {
136
+ this.logger = logger;
137
+ }
138
+ resolveDatabaseName(config) {
139
+ return _KpgDatabaseBootstrapper.parseDatabaseName(config);
140
+ }
141
+ resolveDatabaseFromPool(pool) {
142
+ const config = {};
143
+ const { options } = pool;
144
+ if (typeof options.database === "string") {
145
+ config.database = options.database;
146
+ }
147
+ if (typeof options.connectionString === "string") {
148
+ config.connectionString = options.connectionString;
149
+ }
150
+ return this.resolveDatabaseName(config);
151
+ }
152
+ async ensure(baseConfig) {
153
+ const targetDb = this.resolveDatabaseName(baseConfig);
154
+ if (!targetDb) {
155
+ this.logger.info(chalk3.gray("Skipping database existence check (no database specified)."));
156
+ return;
157
+ }
158
+ if (targetDb === _KpgDatabaseBootstrapper.ADMIN_DB) {
159
+ this.logger.info(chalk3.gray("Target database is postgres; skipping creation."));
160
+ return;
161
+ }
162
+ const adminConfig = this.buildAdminConfig(baseConfig);
163
+ if (!adminConfig) {
164
+ this.logger.warn(`Unable to derive admin connection when ensuring database ${targetDb}`);
165
+ return;
166
+ }
167
+ this.logger.info(chalk3.gray(`Ensuring database ${chalk3.yellow(targetDb)} exists...`));
168
+ const adminPool = new Pool(adminConfig);
169
+ try {
170
+ const exists = await this.databaseExists(adminPool, targetDb);
171
+ if (exists) {
172
+ this.logger.info(chalk3.gray(`Database ${chalk3.yellow(targetDb)} already exists.`));
173
+ return;
174
+ }
175
+ await this.createDatabase(adminPool, targetDb);
176
+ this.logger.info(chalk3.green(`Created database ${chalk3.bold(targetDb)}.`));
177
+ } catch (error) {
178
+ const err = error instanceof Error ? error : new Error(String(error));
179
+ this.logger.error(`Failed to ensure database ${targetDb}: ${err.message}`);
180
+ throw err;
181
+ } finally {
182
+ await adminPool.end();
183
+ }
184
+ }
185
+ buildAdminConfig(baseConfig) {
186
+ const adminConfig = {
187
+ ...baseConfig
188
+ };
189
+ const { connectionString } = adminConfig;
190
+ if (connectionString) {
191
+ const connection = _KpgDatabaseBootstrapper.applyDatabaseToConnectionString(connectionString, _KpgDatabaseBootstrapper.ADMIN_DB);
192
+ if (!connection) return null;
193
+ adminConfig.connectionString = connection;
194
+ }
195
+ adminConfig.database = _KpgDatabaseBootstrapper.ADMIN_DB;
196
+ return adminConfig;
197
+ }
198
+ async databaseExists(pool, database) {
199
+ const client = await pool.connect();
200
+ try {
201
+ const { rows } = await client.query(_KpgDatabaseBootstrapper.DATABASE_EXISTS_SQL, [
202
+ database
203
+ ]);
204
+ return Boolean(rows[0]?.exists);
205
+ } finally {
206
+ client.release();
207
+ }
208
+ }
209
+ async createDatabase(pool, database) {
210
+ const client = await pool.connect();
211
+ try {
212
+ const createSql = `CREATE DATABASE ${_KpgDatabaseBootstrapper.escapeIdentifier(database)}`;
213
+ await client.query(createSql);
214
+ } finally {
215
+ client.release();
216
+ }
217
+ }
218
+ static parseDatabaseName(config) {
219
+ if (typeof config.database === "string" && config.database.trim().length > 0) {
220
+ return config.database.trim();
221
+ }
222
+ const connectionString = config.connectionString;
223
+ if (!connectionString) return null;
224
+ try {
225
+ const url = new URL(connectionString);
226
+ const pathname = url.pathname.replace(/^\//, "");
227
+ if (!pathname) return null;
228
+ const [candidate] = pathname.split("/");
229
+ return candidate ? decodeURIComponent(candidate) : null;
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+ static applyDatabaseToConnectionString(connectionString, database) {
235
+ try {
236
+ const url = new URL(connectionString);
237
+ url.pathname = `/${encodeURIComponent(database)}`;
238
+ return url.toString();
239
+ } catch {
240
+ return null;
241
+ }
242
+ }
243
+ static escapeIdentifier(identifier) {
244
+ return `"${identifier.replace(/"/g, '""')}"`;
245
+ }
246
+ };
247
+ var KpgMigrationManager = class {
248
+ static {
249
+ __name(this, "KpgMigrationManager");
250
+ }
251
+ ctx;
252
+ constructor(ctx) {
253
+ this.ctx = ctx;
254
+ }
255
+ async migrate(options) {
256
+ const { target, direction = "latest", steps } = options ?? {};
257
+ if (typeof target !== "undefined") {
258
+ const label = target === NO_MIGRATIONS ? "NO_MIGRATIONS" : target;
259
+ await this.runMigration((migrator) => migrator.migrateTo(target), `Migrating to ${chalk3.yellow(label)}...`);
260
+ return;
261
+ }
262
+ switch (direction) {
263
+ case "latest":
264
+ await this.runMigration((migrator) => migrator.migrateToLatest());
265
+ return;
266
+ case "up":
267
+ case "down": {
268
+ const stepCount = steps ?? 1;
269
+ if (!Number.isInteger(stepCount) || stepCount < 0) {
270
+ throw new Error("Migration step count must be a non-negative integer");
271
+ }
272
+ if (stepCount === 0) {
273
+ this.logMigrationResults([]);
274
+ return;
275
+ }
276
+ const runner = direction === "up" ? (migrator) => migrator.migrateUp() : (migrator) => migrator.migrateDown();
277
+ await this.runStepwise(stepCount, direction, runner);
278
+ return;
279
+ }
280
+ default:
281
+ throw new Error(`Unknown migration direction: ${String(direction)}`);
282
+ }
283
+ }
284
+ async migrateUp(options) {
285
+ if (typeof options?.steps === "undefined") {
286
+ await this.migrate({
287
+ direction: "up"
288
+ });
289
+ return;
290
+ }
291
+ await this.migrate({
292
+ direction: "up",
293
+ steps: options.steps
294
+ });
295
+ }
296
+ async migrateDown(options) {
297
+ if (typeof options?.steps === "undefined") {
298
+ await this.migrate({
299
+ direction: "down"
300
+ });
301
+ return;
302
+ }
303
+ await this.migrate({
304
+ direction: "down",
305
+ steps: options.steps
306
+ });
307
+ }
308
+ async listMigrations() {
309
+ const migrator = await this.createMigrator();
310
+ return migrator.getMigrations();
311
+ }
312
+ async runMigration(runner, runningMessage = "Running migrations...") {
313
+ this.ctx.logger.info(chalk3.gray("Preparing migrations..."));
314
+ const migrator = await this.createMigrator();
315
+ this.ctx.logger.info(chalk3.gray(runningMessage));
316
+ const { error, results } = await runner(migrator);
317
+ this.logMigrationResults(results ?? []);
318
+ if (error) {
319
+ this.handleMigrationError(error);
320
+ }
321
+ }
322
+ async runStepwise(steps, direction, runner) {
323
+ this.ctx.logger.info(chalk3.gray("Preparing migrations..."));
324
+ const migrator = await this.createMigrator();
325
+ const directionLabel = direction === "up" ? "Running" : "Reverting";
326
+ const countLabel = steps === 1 ? "one migration" : `${chalk3.yellow(String(steps))} migrations`;
327
+ this.ctx.logger.info(chalk3.gray(`${directionLabel} ${countLabel}...`));
328
+ const aggregated = [];
329
+ let encounteredError;
330
+ for (let index = 0; index < steps; index += 1) {
331
+ const { error, results } = await runner(migrator);
332
+ if (results?.length) {
333
+ aggregated.push(...results);
334
+ }
335
+ if (error) {
336
+ encounteredError = error;
337
+ break;
338
+ }
339
+ if (!results?.length) {
340
+ break;
341
+ }
342
+ }
343
+ this.logMigrationResults(aggregated);
344
+ if (encounteredError) {
345
+ this.handleMigrationError(encounteredError);
346
+ }
347
+ }
348
+ async createMigrator() {
349
+ const provider = await this.getMigrationProvider();
350
+ const { config } = this.ctx;
351
+ return new Migrator({
352
+ db: this.ctx.db,
353
+ provider,
354
+ allowUnorderedMigrations: config.allowUnorderedMigrations ?? false,
355
+ ...keepDefined(config, "migrationTableName", "migrationLockTableName", "migrationTableSchema")
356
+ });
357
+ }
358
+ async getMigrationProvider() {
359
+ const { path: target } = this.ctx.config;
360
+ const resolvedTarget = Array.isArray(target) ? target.map((entry) => this.resolvePath(entry)) : this.resolvePath(target);
361
+ if (Array.isArray(resolvedTarget)) {
362
+ this.logMigrationFiles(resolvedTarget);
363
+ return this.createModuleProvider(resolvedTarget);
364
+ }
365
+ let migrationStat;
366
+ try {
367
+ migrationStat = await promises.stat(resolvedTarget);
368
+ } catch {
369
+ migrationStat = void 0;
370
+ }
371
+ if (migrationStat?.isDirectory()) {
372
+ const directory = this.relativePath(resolvedTarget);
373
+ this.ctx.logger.info(chalk3.gray(`Loading migrations directory ${chalk3.yellow(directory)}`));
374
+ return new FileMigrationProvider({
375
+ fs: promises,
376
+ path,
377
+ migrationFolder: resolvedTarget
378
+ });
379
+ }
380
+ if (migrationStat?.isFile() ?? true) {
381
+ this.logMigrationFiles([
382
+ resolvedTarget
383
+ ]);
384
+ return this.createModuleProvider([
385
+ resolvedTarget
386
+ ]);
387
+ }
388
+ const label = Array.isArray(target) ? target.join(", ") : target;
389
+ throw new Error(`Unable to resolve migrations at path: ${label}`);
390
+ }
391
+ async createModuleProvider(files) {
392
+ if (files.length === 0) {
393
+ throw new Error("No migration files provided");
394
+ }
395
+ const comparator = this.ctx.config.nameComparator ?? ((nameA, nameB) => nameA.localeCompare(nameB));
396
+ const entries = await Promise.all(files.map(async (filePath) => {
397
+ const moduleUrl = pathToFileURL(filePath).href;
398
+ const mod = await import(moduleUrl);
399
+ if (!this.isMigrationModule(mod)) {
400
+ throw new Error(`Migration file ${filePath} must export async functions up and down`);
401
+ }
402
+ const { up, down } = mod;
403
+ const name = path.basename(filePath);
404
+ const migration = {
405
+ async up(db) {
406
+ await up(db);
407
+ },
408
+ async down(db) {
409
+ await down(db);
410
+ }
411
+ };
412
+ return [
413
+ name,
414
+ migration
415
+ ];
416
+ }));
417
+ const sorted = entries.sort(([a], [b]) => comparator(a, b));
418
+ this.logPreparedMigrations(sorted);
419
+ return {
420
+ getMigrations: /* @__PURE__ */ __name(() => Promise.resolve(Object.fromEntries(sorted)), "getMigrations")
421
+ };
422
+ }
423
+ logMigrationFiles(files) {
424
+ if (!files.length) return;
425
+ this.ctx.logger.info("Loading migration file(s):");
426
+ for (const file of files) {
427
+ this.ctx.logger.info(`\u2192 ${chalk3.yellow(this.relativePath(file))}`);
428
+ }
429
+ }
430
+ logPreparedMigrations(entries) {
431
+ if (!entries.length) return;
432
+ this.ctx.logger.info("Prepared migrations:");
433
+ for (const [name] of entries) {
434
+ this.ctx.logger.info(`\u2192 ${chalk3.green(name)}`);
435
+ }
436
+ }
437
+ logMigrationResults(results) {
438
+ if (!results.length) {
439
+ this.ctx.logger.info(chalk3.gray("No migrations executed."));
440
+ return;
441
+ }
442
+ this.ctx.logger.info("Migration results:");
443
+ for (const result of results) {
444
+ if (result.status === "Success") {
445
+ this.ctx.logger.info(` ${chalk3.green("\u2713")} ${chalk3.bold(result.migrationName)}`);
446
+ continue;
447
+ }
448
+ if (result.status === "Error") {
449
+ this.ctx.logger.error(` ${chalk3.red("\u2717")} ${chalk3.bold(result.migrationName)}`);
450
+ continue;
451
+ }
452
+ this.ctx.logger.info(` ${chalk3.yellow("\u2022")} ${chalk3.bold(result.migrationName)} ${chalk3.gray("(skipped)")}`);
453
+ }
454
+ }
455
+ relativePath(filePath) {
456
+ const relative = path.relative(this.ctx.baseDir, filePath);
457
+ return relative.startsWith("..") ? filePath : relative;
458
+ }
459
+ resolvePath(target) {
460
+ if (path.isAbsolute(target)) return target;
461
+ return path.resolve(this.ctx.baseDir, target);
462
+ }
463
+ handleMigrationError(error) {
464
+ const message = error instanceof Error ? error.message : inspect(error);
465
+ this.ctx.logger.error(`Migration failure: ${message}`);
466
+ if (error instanceof Error) {
467
+ throw error;
468
+ }
469
+ throw new Error(message);
470
+ }
471
+ isMigrationModule(value) {
472
+ if (!value || typeof value !== "object") return false;
473
+ if (!("up" in value) || !("down" in value)) return false;
474
+ const { up, down } = value;
475
+ return typeof up === "function" && typeof down === "function";
476
+ }
477
+ };
478
+
479
+ // src/kysely-pg/decorators/RegisterKpgService.ts
480
+ var PgServiceMetadataKey = Symbol("db:pgServiceKey");
481
+ var PgTableMetadataKey = Symbol("db:pgTable");
482
+ function RegisterKpgService(key, options) {
483
+ return (ctor) => {
484
+ Reflect.defineMetadata(PgServiceMetadataKey, key, ctor);
485
+ const tableName = options?.table ?? String(key);
486
+ Reflect.defineMetadata(PgTableMetadataKey, tableName, ctor);
487
+ };
488
+ }
489
+ __name(RegisterKpgService, "RegisterKpgService");
490
+
491
+ // src/kysely-pg/KpgService.ts
492
+ var KpgService = class {
493
+ static {
494
+ __name(this, "KpgService");
495
+ }
496
+ kysely;
497
+ core;
498
+ table;
499
+ constructor(kysely, core) {
500
+ this.kysely = kysely;
501
+ this.core = core;
502
+ const ctor = this.constructor;
503
+ const key = Reflect.getMetadata(PgServiceMetadataKey, ctor);
504
+ if (!key) throw new Error(`Missing @RegisterKpgService on ${ctor.name}`);
505
+ const table = Reflect.getMetadata(PgTableMetadataKey, ctor);
506
+ if (!table) {
507
+ throw new Error(`Missing table metadata for ${ctor.name}. Provide a table via @RegisterKpgService().`);
508
+ }
509
+ this.table = table;
510
+ this.kysely._register(key, this);
511
+ }
512
+ /**
513
+ * Shared Kysely instance used to interact with the Postgres database.
514
+ */
515
+ get db() {
516
+ return this.kysely.connection;
517
+ }
518
+ };
519
+ var KpgServiceRegistry = class {
520
+ static {
521
+ __name(this, "KpgServiceRegistry");
522
+ }
523
+ plugin;
524
+ core;
525
+ logger;
526
+ services = /* @__PURE__ */ Object.create(null);
527
+ constructor(plugin, core, logger) {
528
+ this.plugin = plugin;
529
+ this.core = core;
530
+ this.logger = logger;
531
+ }
532
+ get map() {
533
+ return this.services;
534
+ }
535
+ register(key, instance) {
536
+ this.services[key] = instance;
537
+ }
538
+ async loadFromDirectory(dir) {
539
+ this.logger.info(chalk3.bold(dir));
540
+ await traverseDirectory(dir, (_full, rel, mod) => {
541
+ for (const Service of Object.values(mod)) {
542
+ if (this.isServiceClass(Service)) {
543
+ const instance = new Service(this.plugin, this.core);
544
+ this.logger.info(`${chalk3.italic("Registered")} ${chalk3.bold.yellow(instance.constructor.name)} from ${chalk3.gray(rel)}`);
545
+ }
546
+ }
547
+ }, this.logger);
548
+ this.logger.info(`${chalk3.bold.green("Loaded")}: ${chalk3.magenta(Object.keys(this.services).length)} services`);
549
+ }
550
+ isServiceClass(obj) {
551
+ return typeof obj === "function" && obj.prototype instanceof KpgService && Reflect.hasMetadata(PgServiceMetadataKey, obj);
552
+ }
553
+ };
554
+ var KyselyPg = class extends Plugin {
555
+ static {
556
+ __name(this, "KyselyPg");
557
+ }
558
+ core;
559
+ options;
560
+ logger = new Logger("KyselyPg");
561
+ isInitialised = false;
562
+ pool = null;
563
+ migrationManager = null;
564
+ serviceRegistry;
565
+ databaseBootstrapper;
566
+ databaseName = null;
567
+ /**
568
+ * Map of all services registered with the plugin, keyed by their decorator name.
569
+ */
570
+ get services() {
571
+ return this.serviceRegistry.map;
572
+ }
573
+ constructor(core, options) {
574
+ super(core), this.core = core, this.options = options;
575
+ this.serviceRegistry = new KpgServiceRegistry(this, core, this.logger);
576
+ this.databaseBootstrapper = new KpgDatabaseBootstrapper(this.logger);
577
+ this.core.shutdown.addTask(ShutdownPhase.ExternalResources, "stop-kyselypg", async () => await this.stop());
578
+ }
579
+ /**
580
+ * Connects to Postgres, runs any startup migrations, and loads decorated services.
581
+ *
582
+ * Safe to call multiple times; subsequent calls exit early.
583
+ */
584
+ async init() {
585
+ if (this.isInitialised) return;
586
+ this.isInitialised = true;
587
+ await this.connect();
588
+ const startupConfig = this.options.migrations.onStartup;
589
+ if (startupConfig !== false) {
590
+ if (startupConfig && typeof startupConfig !== "boolean") {
591
+ await this.migrate(startupConfig);
592
+ } else {
593
+ await this.migrate();
594
+ }
595
+ }
596
+ await this.serviceRegistry.loadFromDirectory(this.options.dir);
597
+ }
598
+ /**
599
+ * Tears down the connection pool and clears the migration manager reference.
600
+ */
601
+ async stop() {
602
+ await this.disconnect();
603
+ }
604
+ async connect() {
605
+ const pool = await this.resolvePool();
606
+ this.pool = pool;
607
+ this.registerOnConnectStatements(pool, this.options.onConnectSQL);
608
+ try {
609
+ await this.testPoolConnection(pool);
610
+ this.connection = new Kysely({
611
+ dialect: new PostgresDialect({
612
+ pool
613
+ }),
614
+ ...keepDefined$1(this.options.kysely ?? {})
615
+ });
616
+ this.migrationManager = new KpgMigrationManager({
617
+ db: this.connection,
618
+ logger: this.logger,
619
+ config: this.options.migrations,
620
+ baseDir: process.cwd()
621
+ });
622
+ const dbLabel = this.databaseName ?? "unknown";
623
+ this.logger.info(`Connected to Postgres database ${chalk3.bold.magenta(dbLabel)}`);
624
+ } catch (err) {
625
+ const error = err instanceof Error ? err : new Error(String(err));
626
+ this.logger.error(`Could not connect to Postgres: ${error.message}`);
627
+ throw error;
628
+ }
629
+ }
630
+ async disconnect() {
631
+ const pool = this.pool;
632
+ if (!pool) return;
633
+ this.pool = null;
634
+ this.migrationManager = null;
635
+ this.logger.info(chalk3.gray("Closing Postgres pool."));
636
+ await pool.end().catch((err) => {
637
+ this.logger.error(`Could not close pg pool: ${err.message}`);
638
+ });
639
+ this.logger.info(chalk3.red.bold("Disconnected from Postgres"));
640
+ }
641
+ /**
642
+ * Runs migrations using the supplied options or defaults to `latest`.
643
+ *
644
+ * @param options - Target migration or direction overrides
645
+ */
646
+ async migrate(options) {
647
+ await this.getMigrationManager().migrate(options);
648
+ }
649
+ /**
650
+ * Runs a single upwards migration step unless a custom count is provided.
651
+ *
652
+ * @param options - Optional configuration for step-based execution
653
+ */
654
+ async migrateUp(options) {
655
+ await this.getMigrationManager().migrateUp(options);
656
+ }
657
+ /**
658
+ * Runs a single downwards migration step unless a custom count is provided.
659
+ *
660
+ * @param options - Optional configuration for step-based execution
661
+ */
662
+ async migrateDown(options) {
663
+ await this.getMigrationManager().migrateDown(options);
664
+ }
665
+ /**
666
+ * Lists every migration the manager knows about along with its execution state.
667
+ */
668
+ listMigrations() {
669
+ return this.getMigrationManager().listMigrations();
670
+ }
671
+ /**
672
+ * Lists unapplied migrations.
673
+ */
674
+ async listPendingMigrations() {
675
+ const all = await this.listMigrations();
676
+ return all.filter((m) => !m.executedAt);
677
+ }
678
+ getMigrationManager() {
679
+ if (this.migrationManager) return this.migrationManager;
680
+ const manager = new KpgMigrationManager({
681
+ db: this.connection,
682
+ logger: this.logger,
683
+ config: this.options.migrations,
684
+ baseDir: process.cwd()
685
+ });
686
+ this.migrationManager = manager;
687
+ return manager;
688
+ }
689
+ /**
690
+ * Register hook used by decorated services.
691
+ *
692
+ * @internal
693
+ */
694
+ _register(key, instance) {
695
+ this.serviceRegistry.register(key, instance);
696
+ }
697
+ async resolvePool() {
698
+ const { pool: providedPool, connectionString } = this.options;
699
+ if (providedPool instanceof Pool) {
700
+ this.logger.info(chalk3.gray("Reusing provided Postgres pool instance."));
701
+ this.databaseName = this.databaseBootstrapper.resolveDatabaseFromPool(providedPool);
702
+ return providedPool;
703
+ }
704
+ const baseConfig = this.createPoolConfig(providedPool, connectionString);
705
+ await this.databaseBootstrapper.ensure(baseConfig);
706
+ this.databaseName = this.databaseBootstrapper.resolveDatabaseName(baseConfig);
707
+ this.logger.info(chalk3.gray("Creating new Postgres pool."));
708
+ return new Pool(baseConfig);
709
+ }
710
+ createPoolConfig(poolConfig, connectionString) {
711
+ const config = poolConfig ? {
712
+ ...poolConfig
713
+ } : {};
714
+ if (connectionString) {
715
+ config.connectionString = connectionString;
716
+ }
717
+ if (this.options.forceInsecureSSL) {
718
+ config.ssl = {
719
+ rejectUnauthorized: false
720
+ };
721
+ }
722
+ return config;
723
+ }
724
+ registerOnConnectStatements(pool, statements) {
725
+ if (!statements?.length) return;
726
+ const queuedStatements = [
727
+ ...statements
728
+ ];
729
+ pool.on("connect", (client) => {
730
+ void (async () => {
731
+ for (const sql of queuedStatements) {
732
+ await client.query(sql);
733
+ }
734
+ })();
735
+ });
736
+ }
737
+ async testPoolConnection(pool) {
738
+ const client = await pool.connect();
739
+ client.release();
740
+ }
741
+ };
742
+ function WrapDatabaseError(errorMessage) {
112
743
  return function(_target, _propertyKey, descriptor) {
113
744
  const originalMethod = descriptor.value;
114
745
  descriptor.value = async function(...args) {
@@ -127,8 +758,8 @@ function DBCatchable(errorMessage) {
127
758
  };
128
759
  };
129
760
  }
130
- __name(DBCatchable, "DBCatchable");
761
+ __name(WrapDatabaseError, "WrapDatabaseError");
131
762
 
132
- export { DBCatchable, DatabaseModel, DatabaseService, ModelMetadataKey, Mongo, MongoService, ServiceMetadataKey };
763
+ export { KpgDatabaseBootstrapper, KpgMigrationManager, KpgService, KpgServiceRegistry, KyselyPg, ModelMetadataKey, Mongo, MongoService, PgServiceMetadataKey, PgTableMetadataKey, RegisterKpgService, RegisterMongoModel, RegisterMongoService, ServiceMetadataKey, WrapDatabaseError };
133
764
  //# sourceMappingURL=index.mjs.map
134
765
  //# sourceMappingURL=index.mjs.map