@getstrata/core 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +18 -9
  2. package/README.md +17 -9
  3. package/dist/core/auth/policy.d.ts +4 -1
  4. package/dist/core/auth/saml/samlServiceProvider.d.ts +2 -3
  5. package/dist/core/cache/store.d.ts +2 -2
  6. package/dist/core/cache/tokens.d.ts +1 -1
  7. package/dist/core/config/envSchema.d.ts +13 -0
  8. package/dist/core/contracts/application.d.ts +4 -0
  9. package/dist/core/contracts/di.d.ts +2 -2
  10. package/dist/core/contracts/provider.d.ts +13 -0
  11. package/dist/core/contracts/serviceTokens.d.ts +12 -11
  12. package/dist/core/database/factory.d.ts +3 -0
  13. package/dist/core/database/index.d.ts +1 -1
  14. package/dist/core/database/migrations/declaration.d.ts +11 -0
  15. package/dist/core/database/migrations/runner.d.ts +2 -0
  16. package/dist/core/database/model.d.ts +16 -3
  17. package/dist/core/database/modelQuery.d.ts +1 -10
  18. package/dist/core/database/modelRelationLoader.d.ts +31 -0
  19. package/dist/core/database/mysqlConnection.d.ts +2 -2
  20. package/dist/core/database/mysqlNative.d.ts +2 -0
  21. package/dist/core/database/ormRuntime.d.ts +1 -1
  22. package/dist/core/database/rawMysql.d.ts +1 -1
  23. package/dist/core/events/eventBusClass.d.ts +6 -3
  24. package/dist/core/events/index.d.ts +1 -1
  25. package/dist/core/http/formRequest.d.ts +2 -0
  26. package/dist/core/http/loginThrottleMiddleware.d.ts +1 -2
  27. package/dist/core/http/memoryThrottleMiddleware.d.ts +1 -3
  28. package/dist/core/http/webFormRequest.d.ts +3 -5
  29. package/dist/core/mail/mailer.d.ts +6 -3
  30. package/dist/core/mail/markdownMailable.d.ts +2 -2
  31. package/dist/core/notifications/dispatcher.d.ts +5 -5
  32. package/dist/core/notifications/index.d.ts +1 -1
  33. package/dist/core/notifications/types.d.ts +9 -2
  34. package/dist/core/queue/index.d.ts +8 -3
  35. package/dist/core/queue/queueHandoff.d.ts +2 -2
  36. package/dist/core/runtime/application.d.ts +2 -0
  37. package/dist/core/security/oauthState.d.ts +12 -2
  38. package/dist/core/security/safeUrl.d.ts +1 -11
  39. package/dist/core/storage/storage.d.ts +23 -6
  40. package/dist/core/testing.d.ts +5 -0
  41. package/dist/core/testingState.d.ts +22 -0
  42. package/dist/entries/audit/exportAuditLogs.js +1 -0
  43. package/dist/entries/auth/intendedUrlCookie.js +68 -2
  44. package/dist/entries/auth/jwt.js +68 -6
  45. package/dist/entries/auth/jwtGuard.js +76 -12
  46. package/dist/entries/auth/oauth/samlProvider.js +4 -5
  47. package/dist/entries/auth/passwordConfirmCookie.js +69 -3
  48. package/dist/entries/auth/saml/samlServiceProvider.js +5 -7
  49. package/dist/entries/auth/sessionCookie.js +69 -6
  50. package/dist/entries/auth/sessionGuard.js +69 -6
  51. package/dist/entries/cache/repository.js +4 -5
  52. package/dist/entries/config/envSchema.js +13 -0
  53. package/dist/entries/contracts/serviceTokens.js +2 -0
  54. package/dist/entries/database/bindings.js +18 -90
  55. package/dist/entries/database/factory.js +4 -0
  56. package/dist/entries/database/migrations.js +714 -1
  57. package/dist/entries/http/formRequest.js +12 -6
  58. package/dist/entries/http/memoryThrottleMiddleware.js +7 -9
  59. package/dist/entries/http/pagination.js +4 -4
  60. package/dist/entries/http/parseMultipartUpload.js +62 -9
  61. package/dist/entries/http/routeModelBinding.js +4 -4
  62. package/dist/entries/http/securedRouteModelBinding.js +4 -4
  63. package/dist/entries/http/uploads.js +62 -9
  64. package/dist/entries/http/validation.js +4 -4
  65. package/dist/entries/http/webFormRequest.js +74 -95
  66. package/dist/entries/jobs/exportAuditLogsJob.js +9 -4
  67. package/dist/entries/jobs/invalidateCacheTagsJob.js +9 -4
  68. package/dist/entries/queue/createAppQueue.js +10 -5
  69. package/dist/entries/queue/publicQueue.js +10 -5
  70. package/dist/entries/queue/queueWorkerTransport.js +10 -5
  71. package/dist/entries/queue.js +9 -4
  72. package/dist/entries/runtime/application.js +50 -3
  73. package/dist/entries/security/oauthState.js +61 -2
  74. package/dist/entries/security/tokenExpiry.js +62 -9
  75. package/dist/entries/storage/storage.js +102 -1
  76. package/dist/entries/testing.js +18 -0
  77. package/dist/framework/public-api.d.ts +16 -13
  78. package/dist/index.js +316 -222
  79. package/dist/internal/mysqlNative.js +97 -0
  80. package/dist/internal/ormRuntime.js +41 -4
  81. package/dist/internal/testingState.js +31 -0
  82. package/dist/types/services.d.ts +4 -1
  83. package/package.json +17 -4
@@ -211,6 +211,718 @@ async function withMigrationLock(db, callback, lockKey = MIGRATION_LOCK_KEY) {
211
211
  await db.unsafe("SELECT pg_advisory_unlock($1)", [lockKey]);
212
212
  }
213
213
  }
214
+ // ../../src/core/database/schema/columnDefinition.ts
215
+ class ColumnDefinition {
216
+ name;
217
+ kind;
218
+ length;
219
+ isNullable = false;
220
+ isPrimary = false;
221
+ isUnique = false;
222
+ autoIncrement = false;
223
+ defaultValue;
224
+ checkExpression;
225
+ foreignKey;
226
+ constructor(name, kind) {
227
+ this.name = name;
228
+ this.kind = kind;
229
+ }
230
+ nullable() {
231
+ this.isNullable = true;
232
+ return this;
233
+ }
234
+ notNullable() {
235
+ this.isNullable = false;
236
+ return this;
237
+ }
238
+ default(value) {
239
+ if (typeof value === "boolean") {
240
+ this.defaultValue = value ? "TRUE" : "FALSE";
241
+ return this;
242
+ }
243
+ if (typeof value === "number") {
244
+ this.defaultValue = String(value);
245
+ return this;
246
+ }
247
+ this.defaultValue = `'${value.replace(/'/g, "''")}'`;
248
+ return this;
249
+ }
250
+ defaultRaw(expression) {
251
+ this.defaultValue = expression;
252
+ return this;
253
+ }
254
+ unique() {
255
+ this.isUnique = true;
256
+ return this;
257
+ }
258
+ primary() {
259
+ this.isPrimary = true;
260
+ return this;
261
+ }
262
+ check(expression) {
263
+ this.checkExpression = expression;
264
+ return this;
265
+ }
266
+ }
267
+
268
+ class ForeignIdColumnDefinition extends ColumnDefinition {
269
+ constructor(name) {
270
+ super(name, "foreignId");
271
+ this.notNullable();
272
+ }
273
+ references(table, column = "id") {
274
+ this.foreignKey = {
275
+ referencesTable: table,
276
+ referencesColumn: column
277
+ };
278
+ return this;
279
+ }
280
+ constrained(table) {
281
+ const referencesTable = table ?? inferReferencedTable(this.name);
282
+ return this.references(referencesTable);
283
+ }
284
+ cascadeOnDelete() {
285
+ if (!this.foreignKey) {
286
+ throw new Error(`Foreign key is not defined for column ${this.name}`);
287
+ }
288
+ this.foreignKey.onDelete = "cascade";
289
+ return this;
290
+ }
291
+ nullOnDelete() {
292
+ if (!this.foreignKey) {
293
+ throw new Error(`Foreign key is not defined for column ${this.name}`);
294
+ }
295
+ this.foreignKey.onDelete = "set null";
296
+ return this;
297
+ }
298
+ }
299
+ function inferReferencedTable(columnName) {
300
+ if (!columnName.endsWith("_id")) {
301
+ throw new Error(`Cannot infer referenced table from column ${columnName}`);
302
+ }
303
+ return columnName.slice(0, -3);
304
+ }
305
+
306
+ // ../../src/core/database/schema/blueprint.ts
307
+ class Blueprint {
308
+ table;
309
+ action;
310
+ columns = [];
311
+ indexes = [];
312
+ foreignKeys = [];
313
+ checks = [];
314
+ droppedColumns = [];
315
+ droppedIndexes = [];
316
+ constructor(table, action) {
317
+ this.table = table;
318
+ this.action = action;
319
+ }
320
+ id(name = "id") {
321
+ const column = new ColumnDefinition(name, "id");
322
+ column.primary();
323
+ column.autoIncrement = true;
324
+ this.columns.push(column);
325
+ return column;
326
+ }
327
+ bigId(name = "id") {
328
+ const column = new ColumnDefinition(name, "bigId");
329
+ column.primary();
330
+ column.autoIncrement = true;
331
+ this.columns.push(column);
332
+ return column;
333
+ }
334
+ string(name, length) {
335
+ if (length !== undefined && (!Number.isSafeInteger(length) || length <= 0)) {
336
+ throw new Error("String length must be a positive safe integer.");
337
+ }
338
+ const column = new ColumnDefinition(name, "string");
339
+ column.length = length;
340
+ column.notNullable();
341
+ this.columns.push(column);
342
+ return column;
343
+ }
344
+ uuid(name) {
345
+ const column = new ColumnDefinition(name, "uuid");
346
+ column.notNullable();
347
+ this.columns.push(column);
348
+ return column;
349
+ }
350
+ text(name) {
351
+ const column = new ColumnDefinition(name, "text");
352
+ column.notNullable();
353
+ this.columns.push(column);
354
+ return column;
355
+ }
356
+ boolean(name) {
357
+ const column = new ColumnDefinition(name, "boolean");
358
+ column.notNullable();
359
+ this.columns.push(column);
360
+ return column;
361
+ }
362
+ integer(name) {
363
+ const column = new ColumnDefinition(name, "integer");
364
+ column.notNullable();
365
+ this.columns.push(column);
366
+ return column;
367
+ }
368
+ bigInteger(name) {
369
+ const column = new ColumnDefinition(name, "bigInteger");
370
+ column.notNullable();
371
+ this.columns.push(column);
372
+ return column;
373
+ }
374
+ timestamp(name) {
375
+ const column = new ColumnDefinition(name, "timestamp");
376
+ column.notNullable();
377
+ this.columns.push(column);
378
+ return column;
379
+ }
380
+ json(name) {
381
+ const column = new ColumnDefinition(name, "json");
382
+ column.notNullable();
383
+ this.columns.push(column);
384
+ return column;
385
+ }
386
+ jsonb(name) {
387
+ const column = new ColumnDefinition(name, "jsonb");
388
+ column.notNullable();
389
+ this.columns.push(column);
390
+ return column;
391
+ }
392
+ foreignId(name) {
393
+ const column = new ForeignIdColumnDefinition(name);
394
+ this.columns.push(column);
395
+ return column;
396
+ }
397
+ timestamps() {
398
+ this.timestamp("created_at").defaultRaw("NOW()");
399
+ this.timestamp("updated_at").defaultRaw("NOW()");
400
+ }
401
+ softDeletes() {
402
+ this.timestamp("deleted_at").nullable();
403
+ }
404
+ dropColumn(name) {
405
+ this.droppedColumns.push(name);
406
+ }
407
+ dropSoftDeletes() {
408
+ this.dropColumn("deleted_at");
409
+ this.dropIndex(`idx_${this.table}_deleted_at`);
410
+ }
411
+ dropIndex(name) {
412
+ this.droppedIndexes.push(name);
413
+ }
414
+ unique(columns, name) {
415
+ this.indexes.push({
416
+ name,
417
+ columns: Array.isArray(columns) ? columns : [columns],
418
+ kind: "unique"
419
+ });
420
+ }
421
+ foreignKey(columns, referencesTable, referencesColumns, options = {}) {
422
+ if (!columns.length || columns.length !== referencesColumns.length) {
423
+ throw new Error("Foreign key columns must be nonempty and match referenced columns.");
424
+ }
425
+ this.foreignKeys.push({
426
+ columns: [...columns],
427
+ referencesTable,
428
+ referencesColumns: [...referencesColumns],
429
+ ...options
430
+ });
431
+ }
432
+ check(expression, name) {
433
+ if (!expression.trim())
434
+ throw new Error("Check expression must not be empty.");
435
+ this.checks.push({ expression, name });
436
+ }
437
+ index(columns, options = {}) {
438
+ this.indexes.push({
439
+ name: options.name,
440
+ columns: Array.isArray(columns) ? columns : [columns],
441
+ kind: "index",
442
+ order: options.order
443
+ });
444
+ }
445
+ partialIndex(columns, where, nameOrOptions) {
446
+ const options = typeof nameOrOptions === "string" ? { name: nameOrOptions } : nameOrOptions ?? {};
447
+ this.indexes.push({
448
+ name: options.name,
449
+ columns: Array.isArray(columns) ? columns : [columns],
450
+ kind: options.unique ? "uniquePartial" : "partial",
451
+ where
452
+ });
453
+ }
454
+ fullText(columns, name) {
455
+ this.indexes.push({
456
+ name,
457
+ columns: Array.isArray(columns) ? columns : [columns],
458
+ kind: "fullText"
459
+ });
460
+ }
461
+ ginIndex(column, name) {
462
+ this.indexes.push({
463
+ name,
464
+ columns: [column],
465
+ kind: "gin"
466
+ });
467
+ }
468
+ }
469
+
470
+ // ../../src/core/database/schema/driver.ts
471
+ function normalizeConnectionName(connection) {
472
+ const normalized = connection.trim().toLowerCase();
473
+ if (normalized === "pgsql" || normalized === "postgres" || normalized === "postgresql") {
474
+ return "pgsql";
475
+ }
476
+ if (normalized === "mysql" || normalized === "mariadb") {
477
+ return "mysql";
478
+ }
479
+ if (normalized === "sqlite") {
480
+ return "sqlite";
481
+ }
482
+ throw new Error(`Unsupported DB_CONNECTION: ${connection}`);
483
+ }
484
+ function resolveDriverFromUrl(url) {
485
+ const normalized = url.trim().toLowerCase();
486
+ if (normalized.startsWith("postgres://") || normalized.startsWith("postgresql://") || normalized.startsWith("postgres:")) {
487
+ return "pgsql";
488
+ }
489
+ if (normalized.startsWith("mysql://") || normalized.startsWith("mysql:")) {
490
+ return "mysql";
491
+ }
492
+ if (normalized.startsWith("sqlite:")) {
493
+ return "sqlite";
494
+ }
495
+ return null;
496
+ }
497
+ function resolveDatabaseDriver(options) {
498
+ const connection = options.connection;
499
+ if (connection) {
500
+ return normalizeConnectionName(connection);
501
+ }
502
+ const url = options.url ?? "";
503
+ const fromUrl = resolveDriverFromUrl(url);
504
+ if (fromUrl) {
505
+ return fromUrl;
506
+ }
507
+ throw new Error("An explicit database connection or supported database URL is required.");
508
+ }
509
+
510
+ // ../../src/core/database/schema/errors.ts
511
+ class UnsupportedSchemaFeatureError extends Error {
512
+ constructor(feature, driver) {
513
+ super(`${feature} is not supported for the ${driver} driver`);
514
+ this.name = "UnsupportedSchemaFeatureError";
515
+ }
516
+ }
517
+
518
+ // ../../src/core/database/schema/grammars/grammar.ts
519
+ function compileColumnType(driver, column) {
520
+ switch (column.kind) {
521
+ case "bigId":
522
+ return driver === "pgsql" ? "BIGSERIAL" : compileIdType(driver);
523
+ case "id":
524
+ return compileIdType(driver);
525
+ case "string":
526
+ return compileStringType(driver, column.length);
527
+ case "uuid":
528
+ if (column.autoIncrement)
529
+ throw new UnsupportedSchemaFeatureError("auto-increment UUID columns", driver);
530
+ return driver === "pgsql" ? "UUID" : driver === "mysql" ? "CHAR(36)" : "TEXT";
531
+ case "text":
532
+ return compileTextType(driver);
533
+ case "boolean":
534
+ return compileBooleanType(driver);
535
+ case "integer":
536
+ case "foreignId":
537
+ return compileIntegerType(driver);
538
+ case "bigInteger":
539
+ return compileBigIntegerType(driver);
540
+ case "timestamp":
541
+ return compileTimestampType(driver);
542
+ case "json":
543
+ return compileJsonType(driver);
544
+ case "jsonb":
545
+ return compileJsonbType(driver);
546
+ default:
547
+ throw new Error(`Unsupported column kind: ${column.kind}`);
548
+ }
549
+ }
550
+ function compileIdType(driver) {
551
+ switch (driver) {
552
+ case "pgsql":
553
+ return "SERIAL";
554
+ case "mysql":
555
+ return "BIGINT UNSIGNED";
556
+ case "sqlite":
557
+ return "INTEGER";
558
+ }
559
+ }
560
+ function compileStringType(driver, length) {
561
+ switch (driver) {
562
+ case "pgsql":
563
+ return length ? `VARCHAR(${length})` : "TEXT";
564
+ case "mysql":
565
+ return length ? `VARCHAR(${length})` : "VARCHAR(255)";
566
+ case "sqlite":
567
+ return "TEXT";
568
+ }
569
+ }
570
+ function compileTextType(driver) {
571
+ switch (driver) {
572
+ case "pgsql":
573
+ case "sqlite":
574
+ return "TEXT";
575
+ case "mysql":
576
+ return "TEXT";
577
+ }
578
+ }
579
+ function compileBooleanType(driver) {
580
+ switch (driver) {
581
+ case "pgsql":
582
+ return "BOOLEAN";
583
+ case "mysql":
584
+ return "BOOLEAN";
585
+ case "sqlite":
586
+ return "INTEGER";
587
+ }
588
+ }
589
+ function compileIntegerType(driver) {
590
+ switch (driver) {
591
+ case "pgsql":
592
+ return "INTEGER";
593
+ case "mysql":
594
+ return "INT";
595
+ case "sqlite":
596
+ return "INTEGER";
597
+ }
598
+ }
599
+ function compileBigIntegerType(driver) {
600
+ switch (driver) {
601
+ case "pgsql":
602
+ return "BIGINT";
603
+ case "mysql":
604
+ return "BIGINT";
605
+ case "sqlite":
606
+ return "INTEGER";
607
+ }
608
+ }
609
+ function compileTimestampType(driver) {
610
+ switch (driver) {
611
+ case "pgsql":
612
+ return "TIMESTAMPTZ";
613
+ case "mysql":
614
+ return "TIMESTAMP";
615
+ case "sqlite":
616
+ return "TEXT";
617
+ }
618
+ }
619
+ function compileJsonType(driver) {
620
+ switch (driver) {
621
+ case "pgsql":
622
+ return "JSONB";
623
+ case "mysql":
624
+ return "JSON";
625
+ case "sqlite":
626
+ return "TEXT";
627
+ }
628
+ }
629
+ function compileJsonbType(driver) {
630
+ switch (driver) {
631
+ case "pgsql":
632
+ return "JSONB";
633
+ case "mysql":
634
+ return "JSON";
635
+ case "sqlite":
636
+ return "TEXT";
637
+ }
638
+ }
639
+
640
+ // ../../src/core/database/schema/grammars/compileStatements.ts
641
+ function compileTableConstraints(driver, blueprint) {
642
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
643
+ const named = (name) => name ? `CONSTRAINT ${quoteIdentifier(name)} ` : "";
644
+ const columns = (names) => names.map(quoteIdentifier).join(", ");
645
+ return [
646
+ ...blueprint.foreignKeys.map((key) => {
647
+ const deletion = key.onDelete ? ` ON DELETE ${key.onDelete.toUpperCase()}` : "";
648
+ return `${named(key.name)}FOREIGN KEY (${columns(key.columns)}) REFERENCES ${quoteIdentifier(key.referencesTable)}(${columns(key.referencesColumns)})${deletion}`;
649
+ }),
650
+ ...blueprint.checks.map((check) => `${named(check.name)}CHECK (${check.expression})`)
651
+ ];
652
+ }
653
+ function compileCreateTable(driver, blueprint) {
654
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
655
+ const table = quoteIdentifier(blueprint.table);
656
+ const parts = blueprint.columns.map((column) => compileColumn(driver, column, "create"));
657
+ for (const index of blueprint.indexes) {
658
+ if (index.kind === "unique") {
659
+ const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
660
+ const name = index.name ? `CONSTRAINT ${quoteIdentifier(index.name)} ` : "";
661
+ parts.push(`${name}UNIQUE (${columns})`);
662
+ }
663
+ }
664
+ parts.push(...compileTableConstraints(driver, blueprint));
665
+ const statements = [`CREATE TABLE IF NOT EXISTS ${table} (
666
+ ${parts.join(`,
667
+ `)}
668
+ )`];
669
+ for (const index of blueprint.indexes) {
670
+ if (index.kind === "unique" && index.columns.length === 1) {
671
+ continue;
672
+ }
673
+ if (index.kind === "index") {
674
+ statements.push(compileIndex(driver, blueprint.table, index));
675
+ } else if (index.kind === "partial" || index.kind === "uniquePartial" || index.kind === "gin" || index.kind === "fullText") {
676
+ statements.push(...compileSpecialIndex(driver, blueprint.table, index));
677
+ }
678
+ }
679
+ return statements;
680
+ }
681
+ function compileAlterTable(driver, blueprint) {
682
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
683
+ const statements = [];
684
+ const table = quoteIdentifier(blueprint.table);
685
+ for (const column of blueprint.columns) {
686
+ const addPrefix = driver === "pgsql" ? "ADD COLUMN IF NOT EXISTS" : "ADD COLUMN";
687
+ statements.push(`ALTER TABLE ${table}
688
+ ${addPrefix} ${compileColumn(driver, column, "alter")}`);
689
+ }
690
+ if (blueprint.foreignKeys.length || blueprint.checks.length) {
691
+ if (driver === "sqlite") {
692
+ throw new UnsupportedSchemaFeatureError("adding table constraints; rebuild the SQLite table", driver);
693
+ }
694
+ for (const constraint of compileTableConstraints(driver, blueprint)) {
695
+ statements.push(`ALTER TABLE ${table} ADD ${constraint}`);
696
+ }
697
+ }
698
+ for (const columnName of blueprint.droppedColumns) {
699
+ const dropPrefix = driver === "pgsql" ? "DROP COLUMN IF EXISTS" : "DROP COLUMN";
700
+ statements.push(`ALTER TABLE ${table} ${dropPrefix} ${quoteIdentifier(columnName)}`);
701
+ }
702
+ for (const indexName of blueprint.droppedIndexes) {
703
+ statements.push(driver === "mysql" ? `DROP INDEX ${quoteIdentifier(indexName)} ON ${table}` : `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
704
+ }
705
+ for (const index of blueprint.indexes) {
706
+ if (index.kind === "index" || index.kind === "unique") {
707
+ statements.push(compileIndex(driver, blueprint.table, index));
708
+ } else {
709
+ statements.push(...compileSpecialIndex(driver, blueprint.table, index));
710
+ }
711
+ }
712
+ return statements;
713
+ }
714
+ function compileDropTable(driver, tableName) {
715
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
716
+ const cascade = driver === "pgsql" ? " CASCADE" : "";
717
+ return [`DROP TABLE IF EXISTS ${quoteIdentifier(tableName)}${cascade}`];
718
+ }
719
+ function compileColumn(driver, column, mode) {
720
+ if (driver === "sqlite" && mode === "alter" && column.isUnique) {
721
+ throw new UnsupportedSchemaFeatureError("column-level unique() in ADD COLUMN (add the column without unique() and use table.unique(columnName) in the same schema.table callback instead)", driver);
722
+ }
723
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
724
+ const parts = [quoteIdentifier(column.name), compileColumnType(driver, column)];
725
+ if (column.autoIncrement && driver === "mysql") {
726
+ parts[1] = `${parts[1]} AUTO_INCREMENT`;
727
+ }
728
+ if (column.isPrimary && mode === "create") {
729
+ if (driver === "sqlite" && column.autoIncrement) {
730
+ parts.push("PRIMARY KEY AUTOINCREMENT");
731
+ } else {
732
+ parts.push(driver === "sqlite" && !column.isNullable ? "PRIMARY KEY NOT NULL" : "PRIMARY KEY");
733
+ }
734
+ } else if (!column.isNullable) {
735
+ parts.push("NOT NULL");
736
+ } else if (column.isNullable) {
737
+ parts.push("NULL");
738
+ }
739
+ if (column.defaultValue !== undefined) {
740
+ parts.push(`DEFAULT ${column.defaultValue}`);
741
+ }
742
+ if (column.isUnique) {
743
+ parts.push("UNIQUE");
744
+ }
745
+ if (column.checkExpression) {
746
+ parts.push(`CHECK (${column.checkExpression})`);
747
+ }
748
+ if (column.foreignKey) {
749
+ const { referencesTable, referencesColumn, onDelete } = column.foreignKey;
750
+ const reference = `${quoteIdentifier(referencesTable)}(${quoteIdentifier(referencesColumn)})`;
751
+ let clause = `REFERENCES ${reference}`;
752
+ if (onDelete === "cascade") {
753
+ clause += " ON DELETE CASCADE";
754
+ } else if (onDelete === "set null") {
755
+ clause += " ON DELETE SET NULL";
756
+ }
757
+ parts.push(clause);
758
+ }
759
+ return parts.join(" ");
760
+ }
761
+ function compileIndex(driver, tableName, index) {
762
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
763
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind === "unique" ? "unique" : "index");
764
+ const columns = index.columns.map((column) => {
765
+ const quoted = quoteIdentifier(column);
766
+ if (index.order === "desc") {
767
+ return `${quoted} DESC`;
768
+ }
769
+ return quoted;
770
+ }).join(", ");
771
+ const unique = index.kind === "unique" ? "UNIQUE " : "";
772
+ const existence = driver === "mysql" ? "" : "IF NOT EXISTS ";
773
+ return `CREATE ${unique}INDEX ${existence}${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`;
774
+ }
775
+ function compileSpecialIndex(driver, tableName, index) {
776
+ const quoteIdentifier = dialectFor(driver).quoteIdentifier;
777
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns, index.kind);
778
+ const columns = index.columns.map((column) => quoteIdentifier(column)).join(", ");
779
+ switch (index.kind) {
780
+ case "partial":
781
+ case "uniquePartial": {
782
+ if (driver !== "pgsql") {
783
+ throw new UnsupportedSchemaFeatureError("partialIndex()", driver);
784
+ }
785
+ const unique = index.kind === "uniquePartial" ? "UNIQUE " : "";
786
+ return [
787
+ `CREATE ${unique}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns}) WHERE ${index.where}`
788
+ ];
789
+ }
790
+ case "gin": {
791
+ if (driver !== "pgsql") {
792
+ throw new UnsupportedSchemaFeatureError("ginIndex()", driver);
793
+ }
794
+ return [
795
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} USING GIN(${columns})`
796
+ ];
797
+ }
798
+ case "fullText": {
799
+ if (driver === "mysql") {
800
+ return [
801
+ `CREATE FULLTEXT INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)}(${columns})`
802
+ ];
803
+ }
804
+ if (driver === "pgsql") {
805
+ throw new UnsupportedSchemaFeatureError("fullText(); use ginIndex() with a tsvector column on PostgreSQL", driver);
806
+ }
807
+ throw new UnsupportedSchemaFeatureError("fullText()", driver);
808
+ }
809
+ default:
810
+ return [];
811
+ }
812
+ }
813
+ function defaultIndexName(tableName, columns, kind) {
814
+ return `idx_${tableName}_${columns.join("_")}_${kind}`;
815
+ }
816
+ function compileBlueprint(driver, blueprint) {
817
+ switch (blueprint.action) {
818
+ case "create":
819
+ return compileCreateTable(driver, blueprint);
820
+ case "alter":
821
+ return compileAlterTable(driver, blueprint);
822
+ case "drop":
823
+ return compileDropTable(driver, blueprint.table);
824
+ default:
825
+ throw new Error(`Unsupported blueprint action: ${blueprint.action}`);
826
+ }
827
+ }
828
+
829
+ // ../../src/core/database/schema/grammars/createGrammar.ts
830
+ function createGrammar(driver) {
831
+ return {
832
+ driver,
833
+ compile(blueprint) {
834
+ return compileBlueprint(driver, blueprint);
835
+ }
836
+ };
837
+ }
838
+
839
+ // ../../src/core/database/schema/grammars/mysqlGrammar.ts
840
+ var MySqlGrammar = createGrammar("mysql");
841
+
842
+ // ../../src/core/database/schema/grammars/postgresGrammar.ts
843
+ var PostgresGrammar = createGrammar("pgsql");
844
+
845
+ // ../../src/core/database/schema/grammars/sqliteGrammar.ts
846
+ var SqliteGrammar = createGrammar("sqlite");
847
+
848
+ // ../../src/core/database/schema/grammars/index.ts
849
+ function grammarForDriver(driver) {
850
+ switch (driver) {
851
+ case "pgsql":
852
+ return PostgresGrammar;
853
+ case "mysql":
854
+ return MySqlGrammar;
855
+ case "sqlite":
856
+ return SqliteGrammar;
857
+ default:
858
+ throw new Error(`Unsupported database driver: ${driver}`);
859
+ }
860
+ }
861
+
862
+ // ../../src/core/database/schema/schema.ts
863
+ class SchemaBuilder {
864
+ #driver;
865
+ #statements = [];
866
+ constructor(driver) {
867
+ this.#driver = driver;
868
+ }
869
+ create(table, callback) {
870
+ const blueprint = new Blueprint(table, "create");
871
+ callback(blueprint);
872
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
873
+ return this;
874
+ }
875
+ table(table, callback) {
876
+ const blueprint = new Blueprint(table, "alter");
877
+ callback(blueprint);
878
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
879
+ return this;
880
+ }
881
+ drop(table) {
882
+ const blueprint = new Blueprint(table, "drop");
883
+ this.#statements.push(...grammarForDriver(this.#driver).compile(blueprint));
884
+ return this;
885
+ }
886
+ toSql() {
887
+ return [...this.#statements];
888
+ }
889
+ async execute(db) {
890
+ for (const statement of this.#statements) {
891
+ await db.unsafe(statement);
892
+ }
893
+ }
894
+ }
895
+
896
+ class Schema {
897
+ static builder(driver) {
898
+ return new SchemaBuilder(driver ?? currentSqlDialect().driver);
899
+ }
900
+ static async run(db, driver, callback) {
901
+ const schema = Schema.builder(driver);
902
+ await callback(schema);
903
+ await schema.execute(db);
904
+ }
905
+ }
906
+ function createSchemaBuilder(db, driver) {
907
+ const builder = Schema.builder(driver);
908
+ return Object.assign(builder, {
909
+ async commit() {
910
+ await builder.execute(db);
911
+ }
912
+ });
913
+ }
914
+
915
+ // ../../src/core/database/migrations/declaration.ts
916
+ function defineMigration(declaration) {
917
+ const { name, up, down } = declaration;
918
+ if (typeof name !== "string" || !name.trim() || typeof up !== "function" || typeof down !== "function")
919
+ throw new TypeError("Migrations require a name and up/down callbacks.");
920
+ return Object.freeze({
921
+ name,
922
+ up: async (db) => Schema.run(db, currentSqlDialect().driver, (schema) => up(schema, db)),
923
+ down: async (db, context) => Schema.run(db, currentSqlDialect().driver, (schema) => down(schema, db, context))
924
+ });
925
+ }
214
926
  // ../../src/core/database/migrations/rollbackGuard.ts
215
927
  async function guardMigrationRollback(context, guard) {
216
928
  if (context?.operation === "fresh")
@@ -353,7 +1065,7 @@ async function rollbackDatabase(db, migrations, options = {}) {
353
1065
  return rolledBack;
354
1066
  }
355
1067
  async function freshDatabase(db, migrations, options = {}) {
356
- if (options.destructive && isProductionEnv()) {
1068
+ if (options.destructive && isProductionEnv(options.environment ?? process.env)) {
357
1069
  throw new Error("Destructive migration reset is only available in development/test environments.");
358
1070
  }
359
1071
  validateMigrations(migrations);
@@ -380,6 +1092,7 @@ async function freshDatabase(db, migrations, options = {}) {
380
1092
  await runFresh();
381
1093
  }
382
1094
  export {
1095
+ defineMigration,
383
1096
  ensureMigrationsTable,
384
1097
  freshDatabase,
385
1098
  getAppliedMigrations,