@h3ravel/arquebus 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/bin/.gitkeep +0 -0
  2. package/{dist/index.cjs → bin/cli.cjs} +1161 -803
  3. package/bin/cli.d.cts +18 -0
  4. package/bin/cli.d.ts +18 -0
  5. package/bin/cli.js +4887 -183
  6. package/bin/index.cjs +4948 -0
  7. package/bin/index.d.cts +2 -0
  8. package/bin/index.d.ts +2 -0
  9. package/bin/index.js +4923 -0
  10. package/bin/migrations/stubs/migration-js.stub +21 -0
  11. package/bin/migrations/stubs/migration-ts.stub +18 -0
  12. package/bin/migrations/stubs/migration.create-js.stub +24 -0
  13. package/bin/migrations/stubs/migration.create-ts.stub +21 -0
  14. package/bin/migrations/stubs/migration.update-js.stub +25 -0
  15. package/bin/migrations/stubs/migration.update-ts.stub +22 -0
  16. package/bin/stubs/arquebus.config-js.stub +25 -0
  17. package/bin/stubs/arquebus.config-ts.stub +24 -0
  18. package/bin/stubs/model-js.stub +5 -0
  19. package/bin/stubs/model-ts.stub +5 -0
  20. package/dist/browser/index.cjs +117 -97
  21. package/dist/browser/index.d.cts +1205 -165
  22. package/dist/browser/index.d.ts +1205 -165
  23. package/dist/browser/index.js +115 -96
  24. package/dist/index.d.ts +1279 -347
  25. package/dist/index.js +3758 -3547
  26. package/package.json +24 -9
  27. package/src/migrations/stubs/migration-js.stub +21 -0
  28. package/src/migrations/stubs/migration-ts.stub +18 -0
  29. package/src/migrations/stubs/migration.create-js.stub +24 -0
  30. package/src/migrations/stubs/migration.create-ts.stub +21 -0
  31. package/src/migrations/stubs/migration.update-js.stub +25 -0
  32. package/src/migrations/stubs/migration.update-ts.stub +22 -0
  33. package/src/stubs/arquebus.config-js.stub +25 -0
  34. package/src/stubs/arquebus.config-ts.stub +24 -0
  35. package/src/stubs/model-js.stub +5 -0
  36. package/src/stubs/model-ts.stub +5 -0
  37. package/dist/index.d.cts +0 -457
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  "use strict";
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
@@ -11,9 +12,9 @@ var __export = (target, all) => {
11
12
  };
12
13
  var __copyProps = (to, from, except, desc) => {
13
14
  if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key2 of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key2) && key2 !== except)
16
- __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
18
  }
18
19
  return to;
19
20
  };
@@ -27,49 +28,149 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
28
  ));
28
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
30
 
30
- // src/index.js
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Attribute: () => attribute_default,
34
- Builder: () => builder_default,
35
- CastsAttributes: () => casts_attributes_default,
36
- Collection: () => collection_default,
37
- HasUniqueIds: () => has_unique_ids_default,
38
- InvalidArgumentError: () => InvalidArgumentError,
39
- Migration: () => migration_default,
40
- Model: () => model_default,
41
- ModelNotFoundError: () => ModelNotFoundError2,
42
- Paginator: () => paginator_default,
43
- Pivot: () => pivot_default,
44
- QueryBuilder: () => query_builder_default,
45
- RelationNotFoundError: () => RelationNotFoundError,
46
- Scope: () => scope_default,
47
- SoftDeletes: () => soft_deletes_default,
48
- arquebus: () => arquebus_default,
49
- compose: () => compose,
50
- flattenDeep: () => flattenDeep,
51
- getAttrMethod: () => getAttrMethod,
52
- getAttrName: () => getAttrName,
53
- getGetterMethod: () => getGetterMethod,
54
- getRelationMethod: () => getRelationMethod,
55
- getRelationName: () => getRelationName,
56
- getScopeMethod: () => getScopeMethod,
57
- getScopeName: () => getScopeName,
58
- getSetterMethod: () => getSetterMethod,
59
- kebabCase: () => kebabCase,
60
- make: () => make,
61
- makeCollection: () => makeCollection,
62
- makePaginator: () => makePaginator,
63
- migrateRollback: () => migrateRollback,
64
- migrateRun: () => migrateRun,
65
- migrateStatus: () => migrateStatus,
66
- now: () => now,
67
- snakeCase: () => snakeCase,
68
- tap: () => tap
31
+ // src/cli/cli.ts
32
+ var cli_exports = {};
33
+ __export(cli_exports, {
34
+ Cli: () => Cli
69
35
  });
70
- module.exports = __toCommonJS(index_exports);
36
+ module.exports = __toCommonJS(cli_exports);
37
+ var import_commander = require("commander");
71
38
 
72
- // src/migrations/migration-repository.js
39
+ // src/cli/utils.ts
40
+ var import_promises = require("fs/promises");
41
+ var import_chalk = __toESM(require("chalk"), 1);
42
+ var import_sync = __toESM(require("escalade/sync"), 1);
43
+ var import_path = __toESM(require("path"), 1);
44
+ var import_resolve_from = __toESM(require("resolve-from"), 1);
45
+ var join = import_path.default.join;
46
+ var Utils = class {
47
+ /**
48
+ * Wraps text with chalk
49
+ *
50
+ * @param txt
51
+ * @param color
52
+ * @returns
53
+ */
54
+ static textFormat(txt, color2) {
55
+ return String(txt).split(":").map((e, i, a) => i == 0 && a.length > 1 ? color2(" " + e + ": ") : e).join("");
56
+ }
57
+ /**
58
+ * Ouput formater object
59
+ *
60
+ * @returns
61
+ */
62
+ static output() {
63
+ return {
64
+ success: (msg, exit = false) => {
65
+ console.log(import_chalk.default.green("\u2713"), this.textFormat(msg, import_chalk.default.bgGreen), "\n");
66
+ if (exit) process.exit(0);
67
+ },
68
+ info: (msg, exit = false) => {
69
+ console.log(import_chalk.default.blue("\u2139"), this.textFormat(msg, import_chalk.default.bgBlue), "\n");
70
+ if (exit) process.exit(0);
71
+ },
72
+ error: (msg, exit = true) => {
73
+ if (msg instanceof Error) {
74
+ if (msg.message) {
75
+ console.error(import_chalk.default.red("\u2716"), this.textFormat(msg.message, import_chalk.default.bgRed));
76
+ }
77
+ console.error(import_chalk.default.red(`${msg.detail ? `${msg.detail}
78
+ ` : ""}${msg.stack}`), "\n");
79
+ } else {
80
+ console.error(import_chalk.default.red("\u2716"), this.textFormat(msg, import_chalk.default.bgRed), "\n");
81
+ }
82
+ if (exit) process.exit(1);
83
+ },
84
+ quiet: () => {
85
+ process.exit(0);
86
+ }
87
+ };
88
+ }
89
+ static findModulePkg(moduleId, cwd) {
90
+ const parts = moduleId.replace(/\\/g, "/").split("/");
91
+ let packageName = "";
92
+ if (parts.length > 0 && parts[0][0] === "@") {
93
+ packageName += parts.shift() + "/";
94
+ }
95
+ packageName += parts.shift();
96
+ const packageJson = import_path.default.join(packageName, "package.json");
97
+ const resolved = import_resolve_from.default.silent(cwd ?? process.cwd(), packageJson);
98
+ if (!resolved) {
99
+ return;
100
+ }
101
+ return import_path.default.join(import_path.default.dirname(resolved), parts.join("/"));
102
+ }
103
+ static async getMigrationPaths(cwd, migrator, defaultPath, path5) {
104
+ if (path5) {
105
+ return [join(cwd, path5)];
106
+ }
107
+ return [
108
+ ...migrator.getPaths(),
109
+ join(cwd, defaultPath)
110
+ ];
111
+ }
112
+ static twoColumnDetail(name, value) {
113
+ const regex = /\x1b\[\d+m/g;
114
+ const width = Math.min(process.stdout.columns, 100);
115
+ const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
116
+ return console.log(name, import_chalk.default.gray(".".repeat(dots)), value);
117
+ }
118
+ /**
119
+ * Check if file exists
120
+ *
121
+ * @param path
122
+ * @returns
123
+ */
124
+ static async fileExists(path5) {
125
+ try {
126
+ await (0, import_promises.access)(path5);
127
+ return true;
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
132
+ static findUpConfig(cwd, name, extensions) {
133
+ return (0, import_sync.default)(cwd, (_dir, names) => {
134
+ for (const ext of extensions) {
135
+ const filename = `${name}.${ext}`;
136
+ if (names.includes(filename)) {
137
+ return filename;
138
+ }
139
+ }
140
+ return false;
141
+ });
142
+ }
143
+ };
144
+ var TableGuesser = class _TableGuesser {
145
+ static CREATE_PATTERNS = [
146
+ /^create_(\w+)_table$/,
147
+ /^create_(\w+)$/
148
+ ];
149
+ static CHANGE_PATTERNS = [
150
+ /.+_(to|from|in)_(\w+)_table$/,
151
+ /.+_(to|from|in)_(\w+)$/
152
+ ];
153
+ static guess(migration) {
154
+ for (const pattern of _TableGuesser.CREATE_PATTERNS) {
155
+ const matches = migration.match(pattern);
156
+ if (matches) {
157
+ return [matches[1], true];
158
+ }
159
+ }
160
+ for (const pattern of _TableGuesser.CHANGE_PATTERNS) {
161
+ const matches = migration.match(pattern);
162
+ if (matches) {
163
+ return [matches[2], false];
164
+ }
165
+ }
166
+ return [];
167
+ }
168
+ };
169
+
170
+ // src/cli/cli.ts
171
+ var import_promises4 = require("fs/promises");
172
+
173
+ // src/migrations/migration-repository.ts
73
174
  var MigrationRepository = class {
74
175
  resolver;
75
176
  table;
@@ -143,17 +244,16 @@ var MigrationRepository = class {
143
244
  };
144
245
  var migration_repository_default = MigrationRepository;
145
246
 
146
- // src/migrations/migrator.js
147
- var color = __toESM(require("colorette"), 1);
148
- var import_fs = __toESM(require("fs"), 1);
149
- var import_path = __toESM(require("path"), 1);
150
- var import_util = require("util");
247
+ // src/migrations/migrator.ts
248
+ var import_chalk2 = __toESM(require("chalk"), 1);
249
+ var import_promises2 = __toESM(require("fs/promises"), 1);
250
+ var import_path2 = __toESM(require("path"), 1);
151
251
  async function glob(folderPath) {
152
- const files = await (0, import_util.promisify)(import_fs.default.readdir)(folderPath);
252
+ const files = await import_promises2.default.readdir(folderPath);
153
253
  const allFiles = [];
154
254
  for (const file of files) {
155
255
  const filePath = `${folderPath}/${file}`;
156
- const stats = await (0, import_util.promisify)(import_fs.default.stat)(filePath);
256
+ const stats = await import_promises2.default.stat(filePath);
157
257
  if (stats.isFile()) {
158
258
  allFiles.push(filePath);
159
259
  } else if (stats.isDirectory()) {
@@ -168,7 +268,7 @@ var Migrator = class {
168
268
  repository;
169
269
  files;
170
270
  resolver;
171
- connection = null;
271
+ connection;
172
272
  paths = [];
173
273
  output = null;
174
274
  constructor(repository, resolver = null, files = null, dispatcher = null) {
@@ -203,12 +303,18 @@ var Migrator = class {
203
303
  }
204
304
  }
205
305
  }
206
- async runUp(file, batch, pretend) {
207
- const migration = this.resolvePath(file);
306
+ async runUp(file, batch, _pretend) {
307
+ const migration = await this.resolvePath(file);
208
308
  const name = this.getMigrationName(file);
209
309
  await this.writeTask(name, () => this.runMigration(migration, "up"));
210
310
  await this.repository.log(name, batch);
211
311
  }
312
+ async runDown(file, migration, _pretend) {
313
+ const instance = await this.resolvePath(file);
314
+ const name = this.getMigrationName(file);
315
+ await this.writeTask(name, () => this.runMigration(instance, "down"));
316
+ await this.repository.delete(migration);
317
+ }
212
318
  async rollback(paths = [], options = {}) {
213
319
  const migrations = await this.getMigrationsForRollback(options);
214
320
  if (migrations.length === 0) {
@@ -218,10 +324,10 @@ var Migrator = class {
218
324
  return await this.rollbackMigrations(migrations, paths, options);
219
325
  }
220
326
  async getMigrationsForRollback(options) {
221
- if (options.step > 0) {
327
+ if (options.step && options.step > 0) {
222
328
  return await this.repository.getMigrations(options.step);
223
329
  }
224
- if (options.batch > 0) {
330
+ if (options.batch && options.batch > 0) {
225
331
  return await this.repository.getMigrationsByBatch(options.batch);
226
332
  }
227
333
  return await this.repository.getLast();
@@ -233,7 +339,7 @@ var Migrator = class {
233
339
  for (const migration of migrations) {
234
340
  const file = files[migration.migration];
235
341
  if (!file) {
236
- this.writeTwoColumns(migration.migration, color.yellow("Migration not found"));
342
+ this.writeTwoColumns(migration.migration, import_chalk2.default.yellow("Migration not found"));
237
343
  continue;
238
344
  }
239
345
  rolledBack.push(file);
@@ -241,22 +347,11 @@ var Migrator = class {
241
347
  }
242
348
  return rolledBack;
243
349
  }
244
- async runDown(file, migration, pretend) {
245
- const instance = this.resolvePath(file);
246
- const name = this.getMigrationName(file);
247
- await this.writeTask(name, () => this.runMigration(instance, "down"));
248
- await this.repository.delete(migration);
249
- }
250
- reset(paths = [], pretend = false) {
251
- const migrations = this.repository.getRan().reverse();
252
- if (migrations.length === 0) {
253
- this.write(Info, "Nothing to rollback.");
254
- return [];
255
- }
256
- return this.resetMigrations(migrations, paths, pretend);
350
+ reset(_paths = [], _pretend = false) {
351
+ const _migrations = this.repository.getRan().then((r) => r.reverse());
352
+ return [];
257
353
  }
258
354
  resetMigrations(migrations, paths, pretend = false) {
259
- migrations = migrations.map((m) => ({ migration: m }));
260
355
  return this.rollbackMigrations(migrations, paths, { pretend });
261
356
  }
262
357
  async runMigration(migration, method) {
@@ -273,25 +368,27 @@ var Migrator = class {
273
368
  }
274
369
  }
275
370
  async runMethod(connection, migration, method) {
371
+ await migration[method]?.(connection.schema, connection);
372
+ }
373
+ async resolvePath(filePath) {
276
374
  try {
277
- await migration[method](connection.schema, connection);
278
- } finally {
375
+ return new (await import(filePath)).default();
376
+ } catch {
279
377
  }
280
- }
281
- resolvePath(path3) {
282
- return new migrationClass();
378
+ return new class {
379
+ }();
283
380
  }
284
381
  getMigrationClass(migrationName) {
285
382
  return migrationName.split("_").slice(4).map((str) => str.charAt(0).toUpperCase() + str.slice(1)).join("");
286
383
  }
287
384
  async getMigrationFiles(paths) {
288
385
  const files = [];
289
- for (const path3 of paths) {
290
- if (path3.endsWith(".js")) {
291
- files.push(path3);
386
+ for (const p of paths) {
387
+ if (p.endsWith(".js") || p.endsWith(".ts")) {
388
+ files.push(p);
292
389
  continue;
293
390
  }
294
- files.push(...await glob(path3));
391
+ files.push(...await glob(p));
295
392
  }
296
393
  return files.filter(Boolean).reduce((result, file) => {
297
394
  result[this.getMigrationName(file)] = file;
@@ -299,10 +396,10 @@ var Migrator = class {
299
396
  }, {});
300
397
  }
301
398
  getMigrationName(filePath) {
302
- return import_path.default.basename(filePath).replace(".js", "");
399
+ return import_path2.default.basename(filePath).replace(".js", "");
303
400
  }
304
- path(path3) {
305
- this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, path3]));
401
+ path(p) {
402
+ this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
306
403
  }
307
404
  getPaths() {
308
405
  return this.paths;
@@ -341,36 +438,34 @@ var Migrator = class {
341
438
  const regex = /\x1b\[\d+m/g;
342
439
  const width = Math.min(process.stdout.columns, 100);
343
440
  const dots = Math.max(width - name.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
344
- return this.write(name, color.gray(".".repeat(dots)), value);
441
+ this.write(name, import_chalk2.default.gray(".".repeat(dots)), value);
345
442
  }
346
443
  async writeTask(description, task) {
347
444
  const startTime = process.hrtime();
348
445
  let result = false;
349
446
  try {
350
447
  result = await (task || (() => true))();
351
- } catch (e) {
352
- throw e;
353
448
  } finally {
354
449
  const endTime = process.hrtime(startTime);
355
450
  const duration = (endTime[0] * 1e9 + endTime[1]) / 1e6;
356
- this.writeTwoColumns(color.green(description), color.gray(`${Math.floor(duration)}ms`), result !== false ? color.green("\u2714") : color.red("\u2718"));
451
+ this.writeTwoColumns(
452
+ import_chalk2.default.green(description),
453
+ import_chalk2.default.gray(`${Math.floor(duration)}ms`),
454
+ result !== false ? import_chalk2.default.green("\u2714") : import_chalk2.default.red("\u2718")
455
+ );
357
456
  }
358
457
  }
359
458
  };
360
459
  var migrator_default = Migrator;
361
460
 
362
- // src/utils.js
461
+ // src/utils.ts
363
462
  var import_radashi = require("radashi");
364
- var import_advancedFormat = __toESM(require("dayjs/plugin/advancedFormat"), 1);
463
+ var import_advancedFormat = __toESM(require("dayjs/plugin/advancedFormat.js"), 1);
365
464
  var import_dayjs = __toESM(require("dayjs"), 1);
366
465
  import_dayjs.default.extend(import_advancedFormat.default);
367
- var now = (format = "YYYY-MM-DD HH:mm:ss") => (0, import_dayjs.default)().format(format);
368
466
  var getRelationName = (relationMethod) => {
369
467
  return (0, import_radashi.snake)(relationMethod.substring(8));
370
468
  };
371
- var getScopeName = (scopeMethod) => {
372
- return (0, import_radashi.snake)(scopeMethod.substring(5));
373
- };
374
469
  var getRelationMethod = (relation) => {
375
470
  return (0, import_radashi.camel)(`relation_${relation}`);
376
471
  };
@@ -386,41 +481,37 @@ var getGetterMethod = (attr) => {
386
481
  var getSetterMethod = (attr) => {
387
482
  return (0, import_radashi.camel)(`set_${attr}_attribute`);
388
483
  };
389
- var getAttrName = (attrMethod) => {
390
- return attrMethod.substring(3, attrMethod.length - 9).toLowerCase();
391
- };
392
484
  var tap = (instance, callback) => {
393
485
  const result = callback(instance);
394
486
  return result instanceof Promise ? result.then(() => instance) : instance;
395
487
  };
396
488
  function compose(Base, ...mixins) {
397
- return mixins.reduce(
398
- (cls, mixin) => mixin(cls),
399
- Base
400
- );
489
+ return mixins.reduce((acc, mixin) => mixin(acc), Base);
401
490
  }
402
491
  var flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
403
- var kebabCase = (str) => (0, import_radashi.trim)((0, import_radashi.dash)(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
404
492
  var snakeCase = (str) => (0, import_radashi.trim)((0, import_radashi.snake)(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
405
493
 
406
- // src/casts/attribute.js
494
+ // src/casts/attribute.ts
407
495
  var Attribute = class _Attribute {
408
496
  get;
409
497
  set;
410
498
  withCaching = false;
411
499
  withObjectCaching = true;
412
- constructor({ get: get2 = null, set: set2 = null }) {
500
+ constructor({
501
+ get: get2 = null,
502
+ set: set2 = null
503
+ }) {
413
504
  this.get = get2;
414
505
  this.set = set2;
415
506
  }
416
- static make(get2 = null, set2 = null) {
417
- return new _Attribute(get2, set2);
507
+ static make({ get: get2 = null, set: set2 = null }) {
508
+ return new _Attribute({ get: get2, set: set2 });
418
509
  }
419
510
  static get(get2) {
420
- return new _Attribute(get2);
511
+ return new _Attribute({ get: get2 });
421
512
  }
422
513
  static set(set2) {
423
- return new _Attribute(null, set2);
514
+ return new _Attribute({ set: set2 });
424
515
  }
425
516
  withoutObjectCaching() {
426
517
  this.withObjectCaching = false;
@@ -433,16 +524,17 @@ var Attribute = class _Attribute {
433
524
  };
434
525
  var attribute_default = Attribute;
435
526
 
436
- // src/arquebus.js
527
+ // src/arquebus.ts
437
528
  var import_knex = __toESM(require("knex"), 1);
438
529
 
439
- // src/relations/relation.js
530
+ // src/relations/relation.ts
440
531
  var Relation = class {
441
532
  query;
442
533
  parent;
443
534
  related;
444
535
  eagerKeysWereEmpty = false;
445
536
  static constraints = true;
537
+ static selfJoinCount = 0;
446
538
  constructor(query, parent) {
447
539
  this.query = query;
448
540
  this.parent = parent;
@@ -483,30 +575,30 @@ var Relation = class {
483
575
  getRelated() {
484
576
  return this.related;
485
577
  }
486
- getKeys(models, key2) {
487
- return models.map((model) => key2 ? model.attributes[key2] : model.getKey()).sort();
578
+ getKeys(models, key) {
579
+ return models.map((model) => key ? model.attributes[key] : model.getKey()).sort();
488
580
  }
489
581
  getRelationQuery() {
490
582
  return this.query;
491
583
  }
492
- whereInEager(whereIn, key2, modelKeys, query = null) {
493
- (query || this.query)[whereIn](key2, modelKeys);
584
+ whereInEager(whereIn, key, modelKeys, query = null) {
585
+ (query || this.query)[whereIn](key, modelKeys);
494
586
  if (modelKeys.length === 0) {
495
587
  this.eagerKeysWereEmpty = true;
496
588
  }
497
589
  }
498
- whereInMethod(model, key2) {
590
+ whereInMethod(model, key) {
499
591
  return "whereIn";
500
- const segments = key2.split(".");
592
+ const segments = key.split(".");
501
593
  return model.getKeyName() === segments.pop() && ["int", "integer"].includes(model.getKeyType()) ? "whereIntegerInRaw" : "whereIn";
502
594
  }
503
595
  getEager() {
504
596
  return this.eagerKeysWereEmpty ? this.query.getModel().newCollection() : this.get();
505
597
  }
506
- async get(columns = "*") {
598
+ async get(columns = ["*"]) {
507
599
  return await this.query.get(columns);
508
600
  }
509
- async first(columns = "*") {
601
+ async first(columns = ["*"]) {
510
602
  return await this.query.first(columns);
511
603
  }
512
604
  async paginate(...args) {
@@ -533,10 +625,13 @@ var Relation = class {
533
625
  getQualifiedParentKeyName() {
534
626
  return this.parent.getQualifiedKeyName();
535
627
  }
628
+ getExistenceCompareKey() {
629
+ return this.getQualifiedForeignKeyName?.();
630
+ }
536
631
  };
537
632
  var relation_default = Relation;
538
633
 
539
- // src/relations/concerns/supports-default-models.js
634
+ // src/relations/concerns/supports-default-models.ts
540
635
  var SupportsDefaultModels = (Relation2) => {
541
636
  return class extends Relation2 {
542
637
  _withDefault;
@@ -553,8 +648,8 @@ var SupportsDefaultModels = (Relation2) => {
553
648
  return this._withDefault(instance, parent) || instance;
554
649
  }
555
650
  if (typeof this._withDefault === "object") {
556
- for (const key2 in this._withDefault) {
557
- instance.setAttribute(key2, this._withDefault[key2]);
651
+ for (const key in this._withDefault) {
652
+ instance.setAttribute(key, this._withDefault[key]);
558
653
  }
559
654
  }
560
655
  return instance;
@@ -563,7 +658,7 @@ var SupportsDefaultModels = (Relation2) => {
563
658
  };
564
659
  var supports_default_models_default = SupportsDefaultModels;
565
660
 
566
- // src/relations/belongs-to.js
661
+ // src/relations/belongs-to.ts
567
662
  var BelongsTo = class extends compose(relation_default, supports_default_models_default) {
568
663
  foreignKey;
569
664
  ownerKey;
@@ -605,7 +700,7 @@ var BelongsTo = class extends compose(relation_default, supports_default_models_
605
700
  return this.child.qualifyColumn(this.foreignKey);
606
701
  }
607
702
  getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
608
- if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) {
703
+ if (parentQuery.getQuery()._single.table === query.getQuery()._single.table) {
609
704
  return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
610
705
  }
611
706
  return query.select(columns).whereColumn(this.getQualifiedForeignKeyName(), "=", query.qualifyColumn(this.ownerKey));
@@ -614,21 +709,21 @@ var BelongsTo = class extends compose(relation_default, supports_default_models_
614
709
  const hash = this.getRelationCountHash();
615
710
  query.select(columns).from(query.getModel().getTable() + " as " + hash);
616
711
  query.getModel().setTable(hash);
617
- return query.whereColumn(hash + "." + this.ownerKey, "=", this.getQualifiedForeignKeyName());
712
+ return query.whereColumn(`${hash}.${this.ownerKey}`, "=", this.getQualifiedForeignKeyName());
618
713
  }
619
714
  initRelation(models, relation) {
620
- models.map((model) => {
715
+ models.forEach((model) => {
621
716
  model.setRelation(relation, this.getDefaultFor(model));
622
717
  });
623
718
  return models;
624
719
  }
625
720
  addEagerConstraints(models) {
626
- const key2 = `${this.related.getTable()}.${this.ownerKey}`;
627
- this.query.whereIn(key2, this.getEagerModelKeys(models));
721
+ const key = `${this.related.getTable()}.${this.ownerKey}`;
722
+ this.query.whereIn(key, this.getEagerModelKeys(models));
628
723
  }
629
724
  getEagerModelKeys(models) {
630
725
  const keys = [];
631
- models.map((model) => {
726
+ models.forEach((model) => {
632
727
  const value = model[this.foreignKey];
633
728
  if (value !== null && value !== void 0) {
634
729
  keys.push(value);
@@ -654,27 +749,34 @@ var BelongsTo = class extends compose(relation_default, supports_default_models_
654
749
  addConstraints() {
655
750
  if (this.constructor.constraints) {
656
751
  const table = this.related.getTable();
657
- this.query.where(table + "." + this.ownerKey, "=", this.child[this.foreignKey]);
752
+ this.query.where(`${table}.${this.ownerKey}`, "=", this.child[this.foreignKey]);
658
753
  }
659
754
  }
660
- newRelatedInstanceFor(parent) {
755
+ newRelatedInstanceFor(_parent) {
661
756
  return this.related.newInstance();
662
757
  }
663
758
  };
664
759
  var belongs_to_default = BelongsTo;
665
760
 
666
- // src/relations/belongs-to-many.js
667
- var import_radashi4 = require("radashi");
761
+ // src/relations/belongs-to-many.ts
762
+ var import_radashi5 = require("radashi");
668
763
 
669
- // src/collection.js
764
+ // src/collection.ts
670
765
  var import_collect = require("collect.js");
671
766
  var import_radashi2 = require("radashi");
672
767
  var Collection = class _Collection extends import_collect.Collection {
768
+ newConstructor(...args) {
769
+ const constr = this.getConstructor();
770
+ return new constr(...args);
771
+ }
772
+ getConstructor() {
773
+ return this.constructor;
774
+ }
673
775
  async load(...relations) {
674
776
  if (this.isNotEmpty()) {
675
777
  const query = this.first().constructor.query().with(...relations);
676
778
  const items = await query.eagerLoadRelations(this.items);
677
- return new this.constructor(items);
779
+ return this.newConstructor(items);
678
780
  }
679
781
  return this;
680
782
  }
@@ -686,7 +788,7 @@ var Collection = class _Collection extends import_collect.Collection {
686
788
  const attributes = (0, import_radashi2.diff)(Object.keys(models.first().getAttributes()), [models.first().getKeyName()]);
687
789
  this.each((model) => {
688
790
  const extraAttributes = (0, import_radashi2.pick)(models.get(model.getKey()).getAttributes(), attributes);
689
- model.fill(extraAttributes).syncOriginalAttributes(attributes);
791
+ model.fill(extraAttributes).syncOriginalAttributes(...attributes);
690
792
  });
691
793
  return this;
692
794
  }
@@ -711,17 +813,17 @@ var Collection = class _Collection extends import_collect.Collection {
711
813
  modelKeys() {
712
814
  return this.all().map((item) => item.getKey());
713
815
  }
714
- contains(key2, operator = null, value = null) {
816
+ contains(key, operator, value) {
715
817
  if (arguments.length > 1) {
716
- return super.contains(key2, operator, value);
818
+ return super.contains(key, value ?? operator);
717
819
  }
718
- if (key2 instanceof model_default) {
820
+ if (key instanceof model_default) {
719
821
  return super.contains((model) => {
720
- return model.is(key2);
822
+ return model.is(key);
721
823
  });
722
824
  }
723
825
  return super.contains((model) => {
724
- return model.getKey() == key2;
826
+ return model.getKey() == key;
725
827
  });
726
828
  }
727
829
  diff(items) {
@@ -744,34 +846,34 @@ var Collection = class _Collection extends import_collect.Collection {
744
846
  return intersect;
745
847
  }
746
848
  const dictionary = this.getDictionary(items);
747
- for (let item of this.items) {
849
+ for (const item of this.items) {
748
850
  if (dictionary[item.getKey()] !== void 0) {
749
851
  intersect.add(item);
750
852
  }
751
853
  }
752
854
  return intersect;
753
855
  }
754
- unique(key2 = null, strict = false) {
755
- if (key2 !== null) {
756
- return super.unique(key2, strict);
856
+ unique(key, _strict = false) {
857
+ if (key) {
858
+ return super.unique(key);
757
859
  }
758
860
  return new this.constructor(Object.values(this.getDictionary()));
759
861
  }
760
- find(key2, defaultValue = null) {
761
- if (key2 instanceof model_default) {
762
- key2 = key2.getKey();
862
+ find(key, defaultValue = null) {
863
+ if (key instanceof model_default) {
864
+ key = key.getKey();
763
865
  }
764
- if ((0, import_radashi2.isArray)(key2)) {
866
+ if ((0, import_radashi2.isArray)(key)) {
765
867
  if (this.isEmpty()) {
766
868
  return new this.constructor();
767
869
  }
768
- return this.whereIn(this.first().getKeyName(), key2);
870
+ return this.whereIn(this.first().getKeyName(), key);
769
871
  }
770
872
  (0, import_collect.collect)(this.items).first((model) => {
771
- return model.getKey() == key2;
873
+ return model.getKey() == key;
772
874
  });
773
875
  return this.items.filter((model) => {
774
- return model.getKey() == key2;
876
+ return model.getKey() == key;
775
877
  })[0] || defaultValue;
776
878
  }
777
879
  async fresh(...args) {
@@ -808,8 +910,8 @@ var Collection = class _Collection extends import_collect.Collection {
808
910
  const dictionary = (0, import_radashi2.pick)(this.getDictionary(), keys);
809
911
  return new this.constructor(Object.values(dictionary));
810
912
  }
811
- getDictionary(items = null) {
812
- items = items === null ? this.items : items;
913
+ getDictionary(items) {
914
+ items = !items ? this.items : items;
813
915
  const dictionary = {};
814
916
  items.map((value) => {
815
917
  dictionary[value.getKey()] = value;
@@ -838,9 +940,9 @@ var Collection = class _Collection extends import_collect.Collection {
838
940
  toJson(...args) {
839
941
  return JSON.stringify(this.toData(), ...args);
840
942
  }
841
- [Symbol.iterator]() {
943
+ [Symbol.iterator] = () => {
842
944
  const items = this.items;
843
- let length = this.items.length;
945
+ const length = this.items.length;
844
946
  let n = 0;
845
947
  return {
846
948
  next() {
@@ -852,11 +954,11 @@ var Collection = class _Collection extends import_collect.Collection {
852
954
  };
853
955
  }
854
956
  };
855
- }
957
+ };
856
958
  };
857
959
  var collection_default = Collection;
858
960
 
859
- // src/relations/concerns/interacts-with-pivot-table.js
961
+ // src/relations/concerns/interacts-with-pivot-table.ts
860
962
  var import_radashi3 = require("radashi");
861
963
  var import_collect2 = require("collect.js");
862
964
  var InteractsWithPivotTable = (Relation2) => {
@@ -868,14 +970,14 @@ var InteractsWithPivotTable = (Relation2) => {
868
970
  const pivot = this.related.newPivot(this.parent, attributes, this.getTable(), exists, this.using);
869
971
  return pivot.setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
870
972
  }
871
- async attach(id, attributes = {}, touch = true) {
973
+ async attach(id, attributes = {}, _touch = true) {
872
974
  if (this.using) {
873
975
  await this.attachUsingCustomClass(id, attributes);
874
976
  } else {
875
977
  await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(id), attributes));
876
978
  }
877
979
  }
878
- async detach(ids = null, touch = true) {
980
+ async detach(ids, _touch = true) {
879
981
  let results;
880
982
  if (this.using && ids !== null && this.pivotWheres.length == 0 && this.pivotWhereIns.length == 0 && this.pivotWhereNulls.length == 0) {
881
983
  results = await this.detachUsingCustomClass(ids);
@@ -906,7 +1008,7 @@ var InteractsWithPivotTable = (Relation2) => {
906
1008
  await this.detach(detach);
907
1009
  changes.detached = this.castKeys(detach);
908
1010
  }
909
- changes = (0, import_radashi3.merge)(changes, await this.attachNew(records, current, false));
1011
+ changes = (0, import_radashi3.assign)(changes, await this.attachNew(records, current, false));
910
1012
  return changes;
911
1013
  }
912
1014
  syncWithoutDetaching(ids) {
@@ -918,7 +1020,7 @@ var InteractsWithPivotTable = (Relation2) => {
918
1020
  }), detaching);
919
1021
  }
920
1022
  withPivot(columns) {
921
- this.pivotColumns = this.pivotColumns.concat((0, import_radashi3.isArray)(columns) ? columns : Array.prototype.slice.call(arguments));
1023
+ this.pivotColumns = this.pivotColumns.concat((0, import_radashi3.isArray)(columns) ? columns : Array.prototype.slice.call(columns));
922
1024
  return this;
923
1025
  }
924
1026
  async attachNew(records, current, touch = true) {
@@ -961,7 +1063,7 @@ var InteractsWithPivotTable = (Relation2) => {
961
1063
  }
962
1064
  return record;
963
1065
  }
964
- async updateExistingPivotUsingCustomClass(id, attributes, touch) {
1066
+ async updateExistingPivotUsingCustomClass(id, attributes, _touch) {
965
1067
  const pivot = await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey, this.parent[this.parentKey]).where(this.relatedPivotKey, this.parseId(id)).first();
966
1068
  const updated = pivot ? pivot.fill(attributes).isDirty() : false;
967
1069
  if (updated) {
@@ -991,8 +1093,8 @@ var InteractsWithPivotTable = (Relation2) => {
991
1093
  return this.castKey(v);
992
1094
  });
993
1095
  }
994
- castKey(key2) {
995
- return this.getTypeSwapValue(this.related.getKeyType(), key2);
1096
+ castKey(key) {
1097
+ return this.getTypeSwapValue(this.related.getKeyType(), key);
996
1098
  }
997
1099
  getTypeSwapValue(type, value) {
998
1100
  switch (type.toLowerCase()) {
@@ -1047,15 +1149,15 @@ var InteractsWithPivotTable = (Relation2) => {
1047
1149
  formatAttachRecords(ids, attributes) {
1048
1150
  const records = [];
1049
1151
  const hasTimestamps = this.hasPivotColumn(this.createdAt()) || this.hasPivotColumn(this.updatedAt());
1050
- for (const key2 in ids) {
1051
- const value = ids[key2];
1052
- records.push(this.formatAttachRecord(key2, value, attributes, hasTimestamps));
1152
+ for (const key in ids) {
1153
+ const value = ids[key];
1154
+ records.push(this.formatAttachRecord(key, value, attributes, hasTimestamps));
1053
1155
  }
1054
1156
  return records;
1055
1157
  }
1056
- formatAttachRecord(key2, value, attributes, hasTimestamps) {
1057
- const [id, newAttributes] = this.extractAttachIdAndAttributes(key2, value, attributes);
1058
- return (0, import_radashi3.merge)(this.baseAttachRecord(id, hasTimestamps), newAttributes);
1158
+ formatAttachRecord(key, value, attributes, hasTimestamps) {
1159
+ const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
1160
+ return (0, import_radashi3.assign)(this.baseAttachRecord(id, hasTimestamps), newAttributes);
1059
1161
  }
1060
1162
  baseAttachRecord(id, timed) {
1061
1163
  let record = {};
@@ -1069,12 +1171,12 @@ var InteractsWithPivotTable = (Relation2) => {
1069
1171
  });
1070
1172
  return record;
1071
1173
  }
1072
- extractAttachIdAndAttributes(key2, value, newAttributes) {
1073
- return (0, import_radashi3.isArray)(value) ? [key2, { ...value, ...newAttributes }] : [value, newAttributes];
1174
+ extractAttachIdAndAttributes(key, value, newAttributes) {
1175
+ return (0, import_radashi3.isArray)(value) ? [key, { ...value, ...newAttributes }] : [value, newAttributes];
1074
1176
  }
1075
- hasPivotColumn = function(column) {
1177
+ hasPivotColumn(column) {
1076
1178
  return this.pivotColumns.includes(column);
1077
- };
1179
+ }
1078
1180
  parseIds(value) {
1079
1181
  if (value instanceof Model) {
1080
1182
  return [value[this.relatedKey]];
@@ -1088,7 +1190,46 @@ var InteractsWithPivotTable = (Relation2) => {
1088
1190
  };
1089
1191
  var interacts_with_pivot_table_default = InteractsWithPivotTable;
1090
1192
 
1091
- // src/relations/belongs-to-many.js
1193
+ // src/errors.ts
1194
+ var import_radashi4 = require("radashi");
1195
+ var BaseError = class extends Error {
1196
+ constructor(message, _entity) {
1197
+ super(message);
1198
+ Error.captureStackTrace(this, this.constructor);
1199
+ this.name = this.constructor.name;
1200
+ this.message = message;
1201
+ }
1202
+ };
1203
+ var ModelNotFoundError = class extends BaseError {
1204
+ model;
1205
+ ids = [];
1206
+ constructor() {
1207
+ super("");
1208
+ }
1209
+ setModel(model, ids = []) {
1210
+ this.model = model;
1211
+ this.ids = (0, import_radashi4.isArray)(ids) ? ids : [ids];
1212
+ this.message = `No query results for model [${model}]`;
1213
+ if (this.ids.length > 0) {
1214
+ this.message += " " + this.ids.join(", ");
1215
+ } else {
1216
+ this.message += ".";
1217
+ }
1218
+ return this;
1219
+ }
1220
+ getModel() {
1221
+ return this.model;
1222
+ }
1223
+ getIds() {
1224
+ return this.ids;
1225
+ }
1226
+ };
1227
+ var RelationNotFoundError = class extends BaseError {
1228
+ };
1229
+ var InvalidArgumentError = class extends BaseError {
1230
+ };
1231
+
1232
+ // src/relations/belongs-to-many.ts
1092
1233
  var import_collect3 = require("collect.js");
1093
1234
  var BelongsToMany = class extends compose(relation_default, interacts_with_pivot_table_default) {
1094
1235
  table;
@@ -1102,7 +1243,6 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1102
1243
  pivotWhereIns = [];
1103
1244
  pivotWhereNulls = [];
1104
1245
  accessor = "pivot";
1105
- // withTimestamps = false;
1106
1246
  using;
1107
1247
  pivotCreatedAt;
1108
1248
  pivotUpdatedAt;
@@ -1130,7 +1270,12 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1130
1270
  }
1131
1271
  performJoin(query = null) {
1132
1272
  query = query || this.query;
1133
- query.join(this.getTable(), this.getQualifiedRelatedKeyName(), "=", this.qualifyPivotColumn(this.relatedPivotKey));
1273
+ query.join(
1274
+ this.getTable(),
1275
+ this.getQualifiedRelatedKeyName(),
1276
+ "=",
1277
+ this.qualifyPivotColumn(this.relatedPivotKey)
1278
+ );
1134
1279
  return this;
1135
1280
  }
1136
1281
  getTable() {
@@ -1143,10 +1288,14 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1143
1288
  return this.parent[this.parentKey] !== null ? await this.get() : new collection_default([]);
1144
1289
  }
1145
1290
  addWhereConstraints() {
1146
- this.query.where(this.getQualifiedForeignPivotKeyName(), "=", this.parent[this.parentKey]);
1291
+ this.query.where(
1292
+ this.getQualifiedForeignPivotKeyName(),
1293
+ "=",
1294
+ this.parent[this.parentKey]
1295
+ );
1147
1296
  return this;
1148
1297
  }
1149
- async get(columns = ["*"]) {
1298
+ async get(columns) {
1150
1299
  const builder = this.query.applyScopes();
1151
1300
  columns = builder.query?._statements?.find((item) => item.grouping == "columns") ? [] : columns;
1152
1301
  let models = await builder.select(this.shouldSelect(columns)).getModels();
@@ -1192,16 +1341,19 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1192
1341
  }
1193
1342
  hydratePivotRelation(models) {
1194
1343
  models.map((model) => {
1195
- model.setRelation(this.accessor, this.newExistingPivot(this.migratePivotAttributes(model)));
1344
+ model.setRelation(
1345
+ this.accessor,
1346
+ this.newExistingPivot(this.migratePivotAttributes(model))
1347
+ );
1196
1348
  });
1197
1349
  }
1198
1350
  migratePivotAttributes(model) {
1199
1351
  const values = {};
1200
- for (const key2 in model.attributes) {
1201
- const value = model.attributes[key2];
1202
- if (key2.startsWith("pivot_")) {
1203
- values[key2.substring(6)] = value;
1204
- model.attributes = (0, import_radashi4.omit)(model.attributes, [key2]);
1352
+ for (const key in model.attributes) {
1353
+ const value = model.attributes[key];
1354
+ if (key.startsWith("pivot_")) {
1355
+ values[key.substring(6)] = value;
1356
+ model.attributes = (0, import_radashi5.omit)(model.attributes, [key]);
1205
1357
  }
1206
1358
  }
1207
1359
  return values;
@@ -1212,7 +1364,7 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1212
1364
  return this.withPivot(this.createdAt(), this.updatedAt());
1213
1365
  }
1214
1366
  shouldSelect(columns = ["*"]) {
1215
- if ((0, import_radashi4.isEqual)(columns, ["*"])) {
1367
+ if ((0, import_radashi5.isEqual)(columns, ["*"])) {
1216
1368
  columns = [this.related.getTable() + ".*"];
1217
1369
  }
1218
1370
  return columns.concat(this.aliasedPivotColumns());
@@ -1229,9 +1381,9 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1229
1381
  match(models, results, relation) {
1230
1382
  const dictionary = this.buildDictionary(results);
1231
1383
  models.map((model) => {
1232
- const key2 = model.getKey();
1233
- if (dictionary[key2] !== void 0) {
1234
- model.setRelation(relation, dictionary[key2]);
1384
+ const key = model.getKey();
1385
+ if (dictionary[key] !== void 0) {
1386
+ model.setRelation(relation, dictionary[key]);
1235
1387
  }
1236
1388
  });
1237
1389
  return models;
@@ -1248,7 +1400,10 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1248
1400
  return dictionary;
1249
1401
  }
1250
1402
  addEagerConstraints(models) {
1251
- this.query.whereIn(this.getQualifiedForeignPivotKeyName(), this.getKeys(models, this.parentKey));
1403
+ this.query.whereIn(
1404
+ this.getQualifiedForeignPivotKeyName(),
1405
+ this.getKeys(models, this.parentKey)
1406
+ );
1252
1407
  }
1253
1408
  getQualifiedForeignPivotKeyName() {
1254
1409
  return this.qualifyPivotColumn(this.foreignPivotKey);
@@ -1311,14 +1466,6 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1311
1466
  getExistenceCompareKey() {
1312
1467
  return this.getQualifiedForeignPivotKeyName();
1313
1468
  }
1314
- // touchIfTouching() {
1315
- // if (this.touchingParent()) {
1316
- // this.getParent().touch();
1317
- // }
1318
- // if (this.getParent().touches(this.relationName)) {
1319
- // this.touch();
1320
- // }
1321
- // }
1322
1469
  getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
1323
1470
  if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) {
1324
1471
  return this.getRelationExistenceQueryForSelfJoin(query, parentQuery, columns);
@@ -1336,68 +1483,35 @@ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot
1336
1483
  };
1337
1484
  var belongs_to_many_default = BelongsToMany;
1338
1485
 
1339
- // src/errors.js
1340
- var import_radashi5 = require("radashi");
1341
- var BaseError = class extends Error {
1342
- constructor(message, entity) {
1343
- super(message);
1344
- Error.captureStackTrace(this, this.constructor);
1345
- this.name = this.constructor.name;
1346
- this.message = message;
1347
- }
1348
- };
1349
- var ModelNotFoundError2 = class extends BaseError {
1350
- model;
1351
- ids;
1352
- setModel(model, ids = []) {
1353
- this.model = model;
1354
- this.ids = (0, import_radashi5.isArray)(ids) ? ids : [ids];
1355
- this.message = `No query results for model [${model}]`;
1356
- if (this.ids.length > 0) {
1357
- this.message += " " + this.ids.join(", ");
1358
- } else {
1359
- this.message += ".";
1360
- }
1361
- return this;
1362
- }
1363
- getModel() {
1364
- return this.model;
1365
- }
1366
- getIds() {
1367
- return this.ids;
1368
- }
1369
- };
1370
- var RelationNotFoundError = class extends BaseError {
1371
- };
1372
- var InvalidArgumentError = class extends BaseError {
1373
- };
1374
-
1375
- // src/builder.js
1486
+ // src/builder.ts
1376
1487
  var import_radashi6 = require("radashi");
1377
1488
  var import_collect4 = require("collect.js");
1378
1489
 
1379
- // src/paginator.js
1490
+ // src/paginator.ts
1380
1491
  var Paginator = class {
1381
- static formatter = null;
1492
+ static formatter;
1382
1493
  _items;
1383
1494
  _total;
1384
1495
  _perPage;
1385
1496
  _lastPage;
1386
1497
  _currentPage;
1498
+ hasMore = false;
1499
+ options = {};
1387
1500
  static setFormatter(formatter) {
1388
1501
  if (typeof formatter !== "function" && formatter !== null && formatter !== void 0) {
1389
1502
  throw new Error("Paginator formatter must be a function or null");
1390
1503
  }
1391
1504
  this.formatter = formatter;
1392
1505
  }
1393
- constructor(items, total, perPage, currentPage = null, options = {}) {
1506
+ constructor(items, total, perPage, currentPage = 1, options = {}) {
1394
1507
  this.options = options;
1395
- for (const key2 in options) {
1396
- const value = options[key2];
1397
- this[key2] = value;
1508
+ for (const key in options) {
1509
+ const value = options[key];
1510
+ this[key] = value;
1398
1511
  }
1512
+ this._items = new collection_default([]);
1399
1513
  this._total = total;
1400
- this._perPage = parseInt(perPage);
1514
+ this._perPage = parseInt(String(perPage));
1401
1515
  this._lastPage = Math.max(Math.ceil(total / perPage), 1);
1402
1516
  this._currentPage = currentPage;
1403
1517
  this.setItems(items);
@@ -1411,7 +1525,7 @@ var Paginator = class {
1411
1525
  return this.count() > 0 ? (this._currentPage - 1) * this._perPage + 1 : null;
1412
1526
  }
1413
1527
  lastItem() {
1414
- return this.count() > 0 ? this.firstItem() + this.count() - 1 : null;
1528
+ return this.count() > 0 ? (this.firstItem() ?? 0) + this.count() - 1 : null;
1415
1529
  }
1416
1530
  hasMorePages() {
1417
1531
  return this._currentPage < this._lastPage;
@@ -1465,21 +1579,23 @@ var Paginator = class {
1465
1579
  };
1466
1580
  var paginator_default = Paginator;
1467
1581
 
1468
- // src/scope.js
1582
+ // src/scope.ts
1469
1583
  var Scope = class _Scope {
1470
1584
  constructor() {
1471
1585
  if (this.constructor === _Scope) {
1472
1586
  throw new Error("Scope cannot be instantiated");
1473
1587
  }
1474
1588
  }
1475
- apply(builder, model) {
1589
+ apply(_builder, _model) {
1476
1590
  throw new Error("apply not implemented");
1477
1591
  }
1478
1592
  };
1479
1593
  var scope_default = Scope;
1480
1594
 
1481
- // src/builder.js
1482
- var Builder = class _Builder {
1595
+ // src/builder.ts
1596
+ var Inference = class {
1597
+ };
1598
+ var Builder = class _Builder extends Inference {
1483
1599
  query;
1484
1600
  connection;
1485
1601
  model;
@@ -1487,13 +1603,15 @@ var Builder = class _Builder {
1487
1603
  localMacros = {};
1488
1604
  eagerLoad = {};
1489
1605
  globalScopes = {};
1606
+ onDeleteCallback;
1490
1607
  constructor(query) {
1608
+ super();
1491
1609
  this.query = query;
1492
1610
  return this.asProxy();
1493
1611
  }
1494
1612
  asProxy() {
1495
1613
  const handler = {
1496
- get: function(target, prop) {
1614
+ get(target, prop) {
1497
1615
  if (typeof target[prop] !== "undefined") {
1498
1616
  return target[prop];
1499
1617
  }
@@ -1719,7 +1837,7 @@ var Builder = class _Builder {
1719
1837
  if (typeof this.query?.client?.table == "function") {
1720
1838
  this.query = this.query.client.table(this.model.getTable());
1721
1839
  } else {
1722
- this.query = this.query?.table(this.model.getTable());
1840
+ this.query = this.query.table(this.model.getTable());
1723
1841
  }
1724
1842
  return this;
1725
1843
  }
@@ -1734,16 +1852,15 @@ var Builder = class _Builder {
1734
1852
  if (!this.globalScopes) {
1735
1853
  return this;
1736
1854
  }
1737
- const builder = this;
1738
- for (const identifier in builder.globalScopes) {
1739
- const scope = builder.globalScopes[identifier];
1855
+ for (const identifier in this.globalScopes) {
1856
+ const scope = this.globalScopes[identifier];
1740
1857
  if (scope instanceof scope_default) {
1741
- scope.apply(builder, builder.getModel());
1858
+ scope.apply(this, this.getModel());
1742
1859
  } else {
1743
- scope(builder);
1860
+ scope(this);
1744
1861
  }
1745
1862
  }
1746
- return builder;
1863
+ return this;
1747
1864
  }
1748
1865
  hasNamedScope(name) {
1749
1866
  return this.model && this.model.hasNamedScope(name);
@@ -1780,7 +1897,7 @@ var Builder = class _Builder {
1780
1897
  }
1781
1898
  macro(name, callback) {
1782
1899
  this.localMacros[name] = callback;
1783
- return;
1900
+ return this;
1784
1901
  }
1785
1902
  hasMacro(name) {
1786
1903
  return name in this.localMacros;
@@ -1791,7 +1908,7 @@ var Builder = class _Builder {
1791
1908
  with(...args) {
1792
1909
  let eagerLoads = {};
1793
1910
  if (typeof args[1] === "function") {
1794
- let eagerLoad = this.parseWithRelations({
1911
+ const eagerLoad = this.parseWithRelations({
1795
1912
  [args[0]]: args[1]
1796
1913
  });
1797
1914
  this.eagerLoad = (0, import_radashi6.assign)(this.eagerLoad, eagerLoad);
@@ -1872,7 +1989,12 @@ var Builder = class _Builder {
1872
1989
  count = 1;
1873
1990
  }
1874
1991
  const closure = (q) => {
1875
- relations.length > 1 ? q.whereHas(relations.shift(), closure) : q.has(relations.shift(), operator, count, "and", callback);
1992
+ if (relations.length > 1) {
1993
+ q.whereHas(relations.shift(), closure);
1994
+ } else {
1995
+ q.has(relations.shift(), operator, count, "and", callback);
1996
+ }
1997
+ return null;
1876
1998
  };
1877
1999
  return this.has(relations.shift(), doesntHave ? "<" : ">=", 1, boolean, closure);
1878
2000
  }
@@ -1948,11 +2070,8 @@ var Builder = class _Builder {
1948
2070
  query.applyScopes();
1949
2071
  return query.query.toSQL();
1950
2072
  }
1951
- mergeConstraintsFrom(from) {
2073
+ mergeConstraintsFrom(_from) {
1952
2074
  return this;
1953
- const whereBindings = from.getQuery().getRawBindings()["where"] || [];
1954
- const wheres = from.getQuery()._single.table !== this.getQuery()._single.table ? this.requalifyWhereTables(from.getQuery().wheres, from.getQuery().from, this.getModel().getTable()) : from.getQuery().wheres;
1955
- return this.where([], []);
1956
2075
  }
1957
2076
  selectSub(query, as) {
1958
2077
  const [querySub, bindings] = this.createSub(query);
@@ -2032,20 +2151,20 @@ var Builder = class _Builder {
2032
2151
  if (prefix !== "") {
2033
2152
  prefix += ".";
2034
2153
  }
2035
- for (const key2 in relations) {
2036
- const value = relations[key2];
2154
+ for (const key in relations) {
2155
+ const value = relations[key];
2037
2156
  if ((0, import_radashi6.isString)(value) || Number.isFinite(parseInt(value))) {
2038
2157
  continue;
2039
2158
  }
2040
- const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key2, value);
2041
- preparedRelationships = (0, import_radashi6.assign)(preparedRelationships, {
2159
+ const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
2160
+ preparedRelationships = Object.assign({}, preparedRelationships, {
2042
2161
  [`${prefix}${attribute}`]: attributeSelectConstraint
2043
2162
  }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
2044
- relations = (0, import_radashi6.omit)(relations, [key2]);
2163
+ relations = (0, import_radashi6.omit)(relations, [key]);
2045
2164
  }
2046
- for (const key2 in relations) {
2047
- const value = relations[key2];
2048
- let attribute = key2, attributeSelectConstraint = value;
2165
+ for (const key in relations) {
2166
+ const value = relations[key];
2167
+ let attribute = key, attributeSelectConstraint = value;
2049
2168
  if ((0, import_radashi6.isString)(value)) {
2050
2169
  [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
2051
2170
  }
@@ -2103,20 +2222,20 @@ var Builder = class _Builder {
2103
2222
  async firstOrFail(...columns) {
2104
2223
  const data = await this.first(...columns);
2105
2224
  if (data === null) {
2106
- throw new ModelNotFoundError2().setModel(this.model.constructor.name);
2225
+ throw new ModelNotFoundError().setModel(this.model.constructor.name);
2107
2226
  }
2108
2227
  return data;
2109
2228
  }
2110
- async findOrFail(ids, columns = "*") {
2111
- const data = await this.find(ids, columns);
2112
- if ((0, import_radashi6.isArray)(ids)) {
2113
- if (data.count() !== ids.length) {
2114
- throw new ModelNotFoundError2().setModel(this.model.constructor.name, (0, import_radashi6.diff)(ids, data.modelKeys()));
2229
+ async findOrFail(...args) {
2230
+ const data = await this.find(...args);
2231
+ if ((0, import_radashi6.isArray)(args[0])) {
2232
+ if (data.count() !== args[0].length) {
2233
+ throw new ModelNotFoundError().setModel(this.model.constructor.name, (0, import_radashi6.diff)(args[0], data.modelKeys()));
2115
2234
  }
2116
2235
  return data;
2117
2236
  }
2118
2237
  if (data === null) {
2119
- throw new ModelNotFoundError2().setModel(this.model.constructor.name, ids);
2238
+ throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
2120
2239
  }
2121
2240
  return data;
2122
2241
  }
@@ -2152,27 +2271,27 @@ var Builder = class _Builder {
2152
2271
  });
2153
2272
  });
2154
2273
  }
2155
- latest(column = null) {
2274
+ latest(column = "id") {
2156
2275
  if (column === null) {
2157
2276
  column = this.model.getCreatedAtColumn() || "created_at";
2158
2277
  }
2159
2278
  this.query.orderBy(column, "desc");
2160
2279
  return this;
2161
2280
  }
2162
- oldest(column = null) {
2281
+ oldest(column = "id") {
2163
2282
  if (column === null) {
2164
2283
  column = this.model.getCreatedAtColumn() || "created_at";
2165
2284
  }
2166
2285
  this.query.orderBy(column, "asc");
2167
2286
  return this;
2168
2287
  }
2169
- async find(id, columns = "*") {
2288
+ async find(id, columns) {
2170
2289
  if ((0, import_radashi6.isArray)(id) || id instanceof collection_default) {
2171
2290
  return await this.findMany(id, columns);
2172
2291
  }
2173
2292
  return await this.where(this.model.getKeyName(), id).first(columns);
2174
2293
  }
2175
- async findMany(ids, columns = "*") {
2294
+ async findMany(ids, columns = ["*"]) {
2176
2295
  if (ids instanceof collection_default) {
2177
2296
  ids = ids.modelKeys();
2178
2297
  }
@@ -2193,14 +2312,14 @@ var Builder = class _Builder {
2193
2312
  if (ids instanceof import_collect4.Collection) {
2194
2313
  ids = ids.all();
2195
2314
  }
2196
- ids = (0, import_radashi6.isArray)(ids) ? ids : Array.prototype.slice.call(arguments);
2315
+ ids = (0, import_radashi6.isArray)(ids) ? ids : Array.prototype.slice.call(ids);
2197
2316
  if (ids.length === 0) {
2198
2317
  return 0;
2199
2318
  }
2200
2319
  const instance = this.model.newInstance();
2201
- const key2 = instance.getKeyName();
2320
+ const key = instance.getKeyName();
2202
2321
  let count = 0;
2203
- const models = await this.model.newModelQuery().whereIn(key2, ids).get();
2322
+ const models = await this.model.newModelQuery().whereIn(key, ids).get();
2204
2323
  for (const model of models) {
2205
2324
  if (await model.delete()) {
2206
2325
  count++;
@@ -2208,7 +2327,7 @@ var Builder = class _Builder {
2208
2327
  }
2209
2328
  return count;
2210
2329
  }
2211
- async get(columns = "*") {
2330
+ async get(columns = ["*"]) {
2212
2331
  this.applyScopes();
2213
2332
  let models = await this.getModels(columns);
2214
2333
  if (models.length > 0) {
@@ -2216,18 +2335,18 @@ var Builder = class _Builder {
2216
2335
  }
2217
2336
  return new collection_default(models);
2218
2337
  }
2219
- async all(columns = "*") {
2338
+ async all(columns = ["*"]) {
2220
2339
  return await this.model.newModelQuery().get(columns);
2221
2340
  }
2222
- async paginate(page, perPage) {
2341
+ async paginate(page = 1, perPage = 10) {
2223
2342
  page = page || 1;
2224
2343
  perPage = perPage || this?.model?.perPage || 15;
2225
2344
  this.applyScopes();
2226
2345
  const query = this.query.clone();
2227
2346
  const total = await query.clearOrder().clearSelect().count(this.primaryKey);
2228
- let results;
2347
+ let results = [];
2229
2348
  if (total > 0) {
2230
- const skip = (page - 1) * perPage;
2349
+ const skip = (page - 1) * (perPage ?? 10);
2231
2350
  this.take(perPage).skip(skip);
2232
2351
  results = await this.getModels();
2233
2352
  if (results.length > 0) {
@@ -2299,26 +2418,26 @@ var Builder = class _Builder {
2299
2418
  };
2300
2419
  var builder_default = Builder;
2301
2420
 
2302
- // src/concerns/has-attributes.js
2421
+ // src/concerns/has-attributes.ts
2303
2422
  var import_radashi7 = require("radashi");
2304
2423
 
2305
- // src/casts-attributes.js
2424
+ // src/casts-attributes.ts
2306
2425
  var CastsAttributes = class _CastsAttributes {
2307
2426
  constructor() {
2308
2427
  if (this.constructor === _CastsAttributes) {
2309
2428
  throw new Error("CastsAttributes cannot be instantiated");
2310
2429
  }
2311
2430
  }
2312
- static get() {
2431
+ static get(_model, _key, _value, _attributes) {
2313
2432
  throw new Error("get not implemented");
2314
2433
  }
2315
- static set() {
2434
+ static set(_model, _key, _value, _attributes) {
2316
2435
  throw new Error("set not implemented");
2317
2436
  }
2318
2437
  };
2319
2438
  var casts_attributes_default = CastsAttributes;
2320
2439
 
2321
- // src/concerns/has-attributes.js
2440
+ // src/concerns/has-attributes.ts
2322
2441
  var import_collect5 = __toESM(require("collect.js"), 1);
2323
2442
  var import_dayjs2 = __toESM(require("dayjs"), 1);
2324
2443
  var HasAttributes = (Model2) => {
@@ -2338,9 +2457,9 @@ var HasAttributes = (Model2) => {
2338
2457
  this.appends = [...this.appends, ...appends];
2339
2458
  return this;
2340
2459
  }
2341
- normalizeCastClassResponse(key2, value) {
2460
+ normalizeCastClassResponse(key, value) {
2342
2461
  return value?.constructor?.name === "Object" ? value : {
2343
- [key2]: value
2462
+ [key]: value
2344
2463
  };
2345
2464
  }
2346
2465
  syncOriginal() {
@@ -2378,20 +2497,20 @@ var HasAttributes = (Model2) => {
2378
2497
  getDirty() {
2379
2498
  const dirty = {};
2380
2499
  const attributes = this.getAttributes();
2381
- for (const key2 in attributes) {
2382
- const value = attributes[key2];
2383
- if (!this.originalIsEquivalent(key2)) {
2384
- dirty[key2] = value;
2500
+ for (const key in attributes) {
2501
+ const value = attributes[key];
2502
+ if (!this.originalIsEquivalent(key)) {
2503
+ dirty[key] = value;
2385
2504
  }
2386
2505
  }
2387
2506
  return dirty;
2388
2507
  }
2389
- originalIsEquivalent(key2) {
2390
- if (this.original[key2] === void 0) {
2508
+ originalIsEquivalent(key) {
2509
+ if (this.original[key] === void 0) {
2391
2510
  return false;
2392
2511
  }
2393
- const attribute = this.attributes[key2];
2394
- const original = this.original[key2];
2512
+ const attribute = this.attributes[key];
2513
+ const original = this.original[key];
2395
2514
  if (attribute === original) {
2396
2515
  return true;
2397
2516
  } else {
@@ -2411,28 +2530,28 @@ var HasAttributes = (Model2) => {
2411
2530
  getAttributes() {
2412
2531
  return { ...this.attributes };
2413
2532
  }
2414
- setAttribute(key2, value) {
2415
- const setterMethod = getSetterMethod(key2);
2533
+ setAttribute(key, value) {
2534
+ const setterMethod = getSetterMethod(key);
2416
2535
  if (typeof this[setterMethod] === "function") {
2417
2536
  this[setterMethod](value);
2418
2537
  return this;
2419
2538
  }
2420
- const attrMethod = getAttrMethod(key2);
2539
+ const attrMethod = getAttrMethod(key);
2421
2540
  if (typeof this[attrMethod] === "function") {
2422
2541
  const attribute = this[attrMethod]();
2423
2542
  const callback = attribute.set || ((value2) => {
2424
- this.attributes[key2] = value2;
2543
+ this.attributes[key] = value2;
2425
2544
  });
2426
2545
  this.attributes = {
2427
2546
  ...this.attributes,
2428
- ...this.normalizeCastClassResponse(key2, callback(value, this.attributes))
2547
+ ...this.normalizeCastClassResponse(key, callback(value, this.attributes))
2429
2548
  };
2430
2549
  return this;
2431
2550
  }
2432
2551
  const casts = this.getCasts();
2433
- const castType = casts[key2];
2434
- if (this.isCustomCast(castType)) {
2435
- value = castType.set(this, key2, value, this.attributes);
2552
+ const castType = casts[key];
2553
+ if (this.isCustomCast(castType) && typeof castType !== "string") {
2554
+ value = castType.set(this, key, value, this.attributes) ?? "";
2436
2555
  }
2437
2556
  if (castType === "json") {
2438
2557
  value = JSON.stringify(value);
@@ -2440,41 +2559,41 @@ var HasAttributes = (Model2) => {
2440
2559
  if (castType === "collection") {
2441
2560
  value = JSON.stringify(value);
2442
2561
  }
2443
- if (value !== null && this.isDateAttribute(key2)) {
2562
+ if (value !== null && this.isDateAttribute(key)) {
2444
2563
  value = this.fromDateTime(value);
2445
2564
  }
2446
- this.attributes[key2] = value;
2565
+ this.attributes[key] = value;
2447
2566
  return this;
2448
2567
  }
2449
- getAttribute(key2) {
2450
- if (!key2) {
2568
+ getAttribute(key) {
2569
+ if (!key) {
2451
2570
  return;
2452
2571
  }
2453
- const getterMethod = getGetterMethod(key2);
2572
+ const getterMethod = getGetterMethod(key);
2454
2573
  if (typeof this[getterMethod] === "function") {
2455
- return this[getterMethod](this.attributes[key2], this.attributes);
2574
+ return this[getterMethod](this.attributes[key], this.attributes);
2456
2575
  }
2457
- const attrMethod = getAttrMethod(key2);
2576
+ const attrMethod = getAttrMethod(key);
2458
2577
  if (typeof this[attrMethod] === "function") {
2459
2578
  const caster = this[attrMethod]();
2460
- return caster.get(this.attributes[key2], this.attributes);
2579
+ return caster.get(this.attributes[key], this.attributes);
2461
2580
  }
2462
- if (key2 in this.attributes) {
2463
- if (this.hasCast(key2)) {
2464
- return this.castAttribute(key2, this.attributes[key2]);
2581
+ if (key in this.attributes) {
2582
+ if (this.hasCast(key)) {
2583
+ return this.castAttribute(key, this.attributes[key]);
2465
2584
  }
2466
- if (this.getDates().includes(key2)) {
2467
- return this.asDateTime(this.attributes[key2]);
2585
+ if (this.getDates().includes(key)) {
2586
+ return this.asDateTime(this.attributes[key]);
2468
2587
  }
2469
- return this.attributes[key2];
2588
+ return this.attributes[key];
2470
2589
  }
2471
- if (key2 in this.relations) {
2472
- return this.relations[key2];
2590
+ if (key in this.relations) {
2591
+ return this.relations[key];
2473
2592
  }
2474
2593
  return;
2475
2594
  }
2476
- castAttribute(key2, value) {
2477
- const castType = this.getCastType(key2);
2595
+ castAttribute(key, value) {
2596
+ const castType = this.getCastType(key);
2478
2597
  if (!castType) {
2479
2598
  return value;
2480
2599
  }
@@ -2500,13 +2619,13 @@ var HasAttributes = (Model2) => {
2500
2619
  case "json":
2501
2620
  try {
2502
2621
  return JSON.parse(value);
2503
- } catch (e) {
2622
+ } catch {
2504
2623
  return null;
2505
2624
  }
2506
2625
  case "collection":
2507
2626
  try {
2508
2627
  return (0, import_collect5.default)(JSON.parse(value));
2509
- } catch (e) {
2628
+ } catch {
2510
2629
  return (0, import_collect5.default)([]);
2511
2630
  }
2512
2631
  case "date":
@@ -2518,60 +2637,60 @@ var HasAttributes = (Model2) => {
2518
2637
  return this.asTimestamp(value);
2519
2638
  }
2520
2639
  if (this.isCustomCast(castType)) {
2521
- return castType.get(this, key2, value, this.attributes);
2640
+ return castType.get(this, key, value, this.attributes);
2522
2641
  }
2523
2642
  return value;
2524
2643
  }
2525
2644
  attributesToData() {
2526
2645
  let attributes = { ...this.attributes };
2527
- for (const key2 in attributes) {
2528
- if (this.hidden.includes(key2)) {
2529
- attributes = (0, import_radashi7.omit)(attributes, [key2]);
2646
+ for (const key in attributes) {
2647
+ if (this.hidden.includes(key)) {
2648
+ attributes = (0, import_radashi7.omit)(attributes, [key]);
2530
2649
  }
2531
- if (this.visible.length > 0 && this.visible.includes(key2) === false) {
2532
- attributes = (0, import_radashi7.omit)(attributes, [key2]);
2650
+ if (this.visible.length > 0 && this.visible.includes(key) === false) {
2651
+ attributes = (0, import_radashi7.omit)(attributes, [key]);
2533
2652
  }
2534
2653
  }
2535
- for (const key2 of this.getDates()) {
2536
- if (attributes[key2] === void 0) {
2654
+ for (const key of this.getDates()) {
2655
+ if (attributes[key] === void 0) {
2537
2656
  continue;
2538
2657
  }
2539
- attributes[key2] = this.serializeDate(this.asDateTime(attributes[key2]));
2658
+ attributes[key] = this.serializeDate(this.asDateTime(attributes[key]));
2540
2659
  }
2541
2660
  const casts = this.getCasts();
2542
- for (const key2 in casts) {
2543
- const value = casts[key2];
2544
- if (key2 in attributes === false) {
2661
+ for (const key in casts) {
2662
+ const value = casts[key];
2663
+ if (key in attributes === false) {
2545
2664
  continue;
2546
2665
  }
2547
- attributes[key2] = this.castAttribute(key2, attributes[key2]);
2548
- if (key2 in attributes && ["date", "datetime"].includes(value)) {
2549
- attributes[key2] = this.serializeDate(attributes[key2]);
2666
+ attributes[key] = this.castAttribute(key, attributes[key]);
2667
+ if (key in attributes && ["date", "datetime"].includes(String(value))) {
2668
+ attributes[key] = this.serializeDate(attributes[key]);
2550
2669
  }
2551
- if (key2 in attributes && this.isCustomDateTimeCast(value)) {
2552
- attributes[key2] = (0, import_dayjs2.default)(attributes[key2]).format(value.split(":")[1]);
2670
+ if (key in attributes && this.isCustomDateTimeCast(value)) {
2671
+ attributes[key] = (0, import_dayjs2.default)(attributes[key]).format(String(value).split(":")[1]);
2553
2672
  }
2554
2673
  }
2555
- for (const key2 of this.appends) {
2556
- attributes[key2] = this.mutateAttribute(key2, null);
2674
+ for (const key of this.appends) {
2675
+ attributes[key] = this.mutateAttribute(key, null);
2557
2676
  }
2558
2677
  return attributes;
2559
2678
  }
2560
- mutateAttribute(key2, value) {
2561
- if (typeof this[getGetterMethod(key2)] === "function") {
2562
- return this[getGetterMethod(key2)](value);
2563
- } else if (typeof this[getAttrMethod(key2)] === "function") {
2564
- const caster = this[getAttrMethod(key2)]();
2565
- return caster.get(key2, this.attributes);
2566
- } else if (key2 in this) {
2567
- return this[key2];
2679
+ mutateAttribute(key, value) {
2680
+ if (typeof this[getGetterMethod(key)] === "function") {
2681
+ return this[getGetterMethod(key)](value);
2682
+ } else if (typeof this[getAttrMethod(key)] === "function") {
2683
+ const caster = this[getAttrMethod(key)]();
2684
+ return caster.get(key, this.attributes);
2685
+ } else if (key in this) {
2686
+ return this[key];
2568
2687
  }
2569
2688
  return value;
2570
2689
  }
2571
- mutateAttributeForArray(key2, value) {
2690
+ mutateAttributeForArray(_key, _value) {
2572
2691
  }
2573
- isDateAttribute(key2) {
2574
- return this.getDates().includes(key2) || this.isDateCastable(key2);
2692
+ isDateAttribute(key) {
2693
+ return this.getDates().includes(key) || this.isDateCastable(key);
2575
2694
  }
2576
2695
  serializeDate(date) {
2577
2696
  return date ? (0, import_dayjs2.default)(date).toISOString() : null;
@@ -2591,16 +2710,16 @@ var HasAttributes = (Model2) => {
2591
2710
  }
2592
2711
  return this.casts;
2593
2712
  }
2594
- getCastType(key2) {
2595
- const castType = this.getCasts()[key2];
2713
+ getCastType(key) {
2714
+ const castType = this.getCasts()[key];
2596
2715
  let castTypeCacheKey;
2597
2716
  if (typeof castType === "string") {
2598
2717
  castTypeCacheKey = castType;
2599
2718
  } else if (new castType() instanceof casts_attributes_default) {
2600
2719
  castTypeCacheKey = castType.name;
2601
2720
  }
2602
- if (castTypeCacheKey && this.constructor.castTypeCache[castTypeCacheKey] !== void 0) {
2603
- return this.constructor.castTypeCache[castTypeCacheKey];
2721
+ if (castTypeCacheKey && this.getConstructor().castTypeCache[castTypeCacheKey] !== void 0) {
2722
+ return this.getConstructor().castTypeCache[castTypeCacheKey];
2604
2723
  }
2605
2724
  let convertedCastType;
2606
2725
  if (this.isCustomDateTimeCast(castType)) {
@@ -2610,14 +2729,14 @@ var HasAttributes = (Model2) => {
2610
2729
  } else if (this.isCustomCast(castType)) {
2611
2730
  convertedCastType = castType;
2612
2731
  } else {
2613
- convertedCastType = castType.toLocaleLowerCase().trim();
2732
+ convertedCastType = String(castType).toLocaleLowerCase().trim();
2614
2733
  }
2615
- return this.constructor.castTypeCache[castTypeCacheKey] = convertedCastType;
2734
+ return this.getConstructor()[castTypeCacheKey] = convertedCastType;
2616
2735
  }
2617
- hasCast(key2, types = []) {
2618
- if (key2 in this.casts) {
2736
+ hasCast(key, types = []) {
2737
+ if (key in this.casts) {
2619
2738
  types = (0, import_radashi7.flat)(types);
2620
- return types.length > 0 ? types.includes(this.getCastType(key2)) : true;
2739
+ return types.length > 0 ? types.includes(this.getCastType(key)) : true;
2621
2740
  }
2622
2741
  return false;
2623
2742
  }
@@ -2639,8 +2758,8 @@ var HasAttributes = (Model2) => {
2639
2758
  }
2640
2759
  return cast.startsWith("decimal:");
2641
2760
  }
2642
- isDateCastable(key2) {
2643
- return this.hasCast(key2, ["date", "datetime"]);
2761
+ isDateCastable(key) {
2762
+ return this.hasCast(key, ["date", "datetime"]);
2644
2763
  }
2645
2764
  fromDateTime(value) {
2646
2765
  return (0, import_dayjs2.default)(this.asDateTime(value)).format(this.getDateFormat());
@@ -2671,16 +2790,17 @@ var HasAttributes = (Model2) => {
2671
2790
  };
2672
2791
  var has_attributes_default = HasAttributes;
2673
2792
 
2674
- // src/concerns/has-global-scopes.js
2793
+ // src/concerns/has-global-scopes.ts
2675
2794
  var import_radashi8 = require("radashi");
2676
2795
  var HasGlobalScopes = (Model2) => {
2677
2796
  return class extends Model2 {
2797
+ static globalScopes;
2678
2798
  static addGlobalScope(scope, implementation = null) {
2679
2799
  if (typeof scope === "string" && implementation instanceof scope_default) {
2680
- this.globalScopes = (0, import_radashi8.set)(this.globalScopes, this.name + "." + scope, implementation);
2800
+ this.globalScopes = (0, import_radashi8.set)(this.globalScopes ?? {}, this.name + "." + scope, implementation);
2681
2801
  return implementation;
2682
2802
  } else if (scope instanceof scope_default) {
2683
- this.globalScopes = (0, import_radashi8.set)(this.globalScopes, this.name + "." + scope.constructor.name, scope);
2803
+ this.globalScopes = (0, import_radashi8.set)(this.globalScopes ?? {}, this.name + "." + scope.constructor.name, scope);
2684
2804
  return scope;
2685
2805
  }
2686
2806
  throw new InvalidArgumentError("Global scope must be an instance of Scope.");
@@ -2707,7 +2827,7 @@ var HasGlobalScopes = (Model2) => {
2707
2827
  };
2708
2828
  var has_global_scopes_default = HasGlobalScopes;
2709
2829
 
2710
- // src/hooks.js
2830
+ // src/hooks.ts
2711
2831
  var Hooks = class {
2712
2832
  hooks = {
2713
2833
  creating: [],
@@ -2725,16 +2845,11 @@ var Hooks = class {
2725
2845
  forceDeleted: []
2726
2846
  };
2727
2847
  add(hook, callback) {
2728
- if (typeof this.hooks[hook] === "undefined") {
2729
- this.hooks[hook] = [];
2730
- }
2731
2848
  this.hooks[hook].push(callback);
2732
2849
  }
2733
2850
  async exec(hook, data) {
2734
- if (typeof this.hooks[hook] === "undefined") {
2735
- return true;
2736
- }
2737
- for (const callback of this.hooks[hook]) {
2851
+ const callbacks = this.hooks[hook] ?? [];
2852
+ for (const callback of callbacks) {
2738
2853
  await callback(...data);
2739
2854
  }
2740
2855
  return true;
@@ -2742,7 +2857,7 @@ var Hooks = class {
2742
2857
  };
2743
2858
  var hooks_default = Hooks;
2744
2859
 
2745
- // src/concerns/has-hooks.js
2860
+ // src/concerns/has-hooks.ts
2746
2861
  var HasHooks = (Model2) => {
2747
2862
  return class extends Model2 {
2748
2863
  static hooks = null;
@@ -2798,20 +2913,20 @@ var HasHooks = (Model2) => {
2798
2913
  };
2799
2914
  var has_hooks_default = HasHooks;
2800
2915
 
2801
- // src/relations/has-one-or-many.js
2916
+ // src/relations/has-one-or-many.ts
2802
2917
  var import_collect6 = __toESM(require("collect.js"), 1);
2803
2918
  var HasOneOrMany = (Relation2) => {
2804
2919
  return class extends Relation2 {
2805
- getRelationValue(dictionary, key2, type) {
2806
- const value = dictionary[key2];
2920
+ getRelationValue(dictionary, key, type) {
2921
+ const value = dictionary[key];
2807
2922
  return type === "one" ? value[0] : new collection_default(value);
2808
2923
  }
2809
2924
  matchOneOrMany(models, results, relation, type) {
2810
2925
  const dictionary = this.buildDictionary(results);
2811
2926
  models.map((model) => {
2812
- const key2 = model.attributes[this.localKey];
2813
- if (dictionary[key2] !== void 0) {
2814
- model.setRelation(relation, this.getRelationValue(dictionary, key2, type));
2927
+ const key = model.attributes[this.localKey];
2928
+ if (dictionary[key] !== void 0) {
2929
+ model.setRelation(relation, this.getRelationValue(dictionary, key, type));
2815
2930
  }
2816
2931
  });
2817
2932
  return models;
@@ -2872,7 +2987,7 @@ var HasOneOrMany = (Relation2) => {
2872
2987
  };
2873
2988
  var has_one_or_many_default = HasOneOrMany;
2874
2989
 
2875
- // src/relations/has-many.js
2990
+ // src/relations/has-many.ts
2876
2991
  var import_collect7 = require("collect.js");
2877
2992
  var HasMany = class extends compose(relation_default, has_one_or_many_default) {
2878
2993
  foreignKey;
@@ -2894,8 +3009,8 @@ var HasMany = class extends compose(relation_default, has_one_or_many_default) {
2894
3009
  return this.getParentKey() !== null ? await this.query.get() : new collection_default([]);
2895
3010
  }
2896
3011
  getForeignKeyName() {
2897
- const segments = this.foreignKey.split(".");
2898
- return segments.pop();
3012
+ const segments = this.foreignKey?.split(".");
3013
+ return segments?.pop();
2899
3014
  }
2900
3015
  buildDictionary(results) {
2901
3016
  const foreign = this.getForeignKeyName();
@@ -2913,8 +3028,12 @@ var HasMany = class extends compose(relation_default, has_one_or_many_default) {
2913
3028
  };
2914
3029
  var has_many_default = HasMany;
2915
3030
 
2916
- // src/relations/has-one.js
2917
- var HasOne = class extends compose(relation_default, has_one_or_many_default, supports_default_models_default) {
3031
+ // src/relations/has-one.ts
3032
+ var HasOne = class extends compose(
3033
+ relation_default,
3034
+ has_one_or_many_default,
3035
+ supports_default_models_default
3036
+ ) {
2918
3037
  foreignKey;
2919
3038
  localKey;
2920
3039
  constructor(query, parent, foreignKey, localKey) {
@@ -2934,8 +3053,8 @@ var HasOne = class extends compose(relation_default, has_one_or_many_default, su
2934
3053
  return this.matchOneOrMany(models, results, relation, "one");
2935
3054
  }
2936
3055
  getForeignKeyName() {
2937
- const segments = this.foreignKey.split(".");
2938
- return segments.pop();
3056
+ const segments = this.foreignKey?.split(".");
3057
+ return segments?.pop();
2939
3058
  }
2940
3059
  async getResults() {
2941
3060
  if (this.getParentKey() === null) {
@@ -2956,7 +3075,7 @@ var HasOne = class extends compose(relation_default, has_one_or_many_default, su
2956
3075
  };
2957
3076
  var has_one_default = HasOne;
2958
3077
 
2959
- // src/relations/has-many-through.js
3078
+ // src/relations/has-many-through.ts
2960
3079
  var import_radashi9 = require("radashi");
2961
3080
  var HasManyThrough = class extends relation_default {
2962
3081
  throughParent;
@@ -3015,7 +3134,8 @@ var HasManyThrough = class extends relation_default {
3015
3134
  match(models, results, relation) {
3016
3135
  const dictionary = this.buildDictionary(results);
3017
3136
  for (const model of models) {
3018
- if (dictionary[key = this.getDictionaryKey(model.getAttribute(this.localKey))] !== void 0) {
3137
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
3138
+ if (dictionary[key] !== void 0) {
3019
3139
  model.setRelation(relation, this.related.newCollection(dictionary[key]));
3020
3140
  }
3021
3141
  }
@@ -3032,7 +3152,7 @@ var HasManyThrough = class extends relation_default {
3032
3152
  return dictionary;
3033
3153
  }
3034
3154
  async firstOrNew(attributes) {
3035
- let instance = await this.where(attributes).first();
3155
+ const instance = await this.where(attributes).first();
3036
3156
  return instance || this.related.newInstance(attributes);
3037
3157
  }
3038
3158
  async updateOrCreate(attributes, values = {}) {
@@ -3054,7 +3174,7 @@ var HasManyThrough = class extends relation_default {
3054
3174
  if (model) {
3055
3175
  return model;
3056
3176
  }
3057
- throw new ModelNotFoundError2().setModel(this.related.constructor);
3177
+ throw new ModelNotFoundError().setModel(this.related.constructor);
3058
3178
  }
3059
3179
  async firstOr(columns = ["*"], callback = null) {
3060
3180
  if (typeof columns === "function") {
@@ -3065,7 +3185,7 @@ var HasManyThrough = class extends relation_default {
3065
3185
  if (model) {
3066
3186
  return model;
3067
3187
  }
3068
- return callback();
3188
+ return callback?.();
3069
3189
  }
3070
3190
  async find(id, columns = ["*"]) {
3071
3191
  if ((0, import_radashi9.isArray)(id)) {
@@ -3081,14 +3201,14 @@ var HasManyThrough = class extends relation_default {
3081
3201
  }
3082
3202
  async findOrFail(id, columns = ["*"]) {
3083
3203
  const result = await this.find(id, columns);
3084
- if ((0, import_radashi9.isArray)(id)) {
3204
+ if (Array.isArray(id)) {
3085
3205
  if (result.count() === id.length) {
3086
3206
  return result;
3087
3207
  }
3088
3208
  } else if (result) {
3089
3209
  return result;
3090
3210
  }
3091
- throw new ModelNotFoundError2().setModel(this.related.constructor, id);
3211
+ throw new ModelNotFoundError().setModel(this.related.constructor, id);
3092
3212
  }
3093
3213
  async getResults() {
3094
3214
  return this.farParent[this.localKey] ? await this.get() : this.related.newCollection();
@@ -3106,7 +3226,7 @@ var HasManyThrough = class extends relation_default {
3106
3226
  return await this.query.paginate(perPage, columns, pageName, page);
3107
3227
  }
3108
3228
  shouldSelect(columns = ["*"]) {
3109
- if (columns == ["*"]) {
3229
+ if (columns?.at(0) == "*") {
3110
3230
  columns = [this.related.getTable() + ".*"];
3111
3231
  }
3112
3232
  return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
@@ -3174,8 +3294,11 @@ var HasManyThrough = class extends relation_default {
3174
3294
  };
3175
3295
  var has_many_through_default = HasManyThrough;
3176
3296
 
3177
- // src/relations/has-one-through.js
3178
- var HasOneThrough = class extends compose(has_many_through_default, supports_default_models_default) {
3297
+ // src/relations/has-one-through.ts
3298
+ var HasOneThrough = class extends compose(
3299
+ has_many_through_default,
3300
+ supports_default_models_default
3301
+ ) {
3179
3302
  async getResults() {
3180
3303
  return await this.first() || this.getDefaultFor(this.farParent);
3181
3304
  }
@@ -3188,21 +3311,21 @@ var HasOneThrough = class extends compose(has_many_through_default, supports_def
3188
3311
  match(models, results, relation) {
3189
3312
  const dictionary = this.buildDictionary(results);
3190
3313
  for (const model of models) {
3191
- const key2 = this.getDictionaryKey(model.getAttribute(this.localKey));
3192
- if (dictionary[key2] !== void 0) {
3193
- const value = dictionary[key2];
3314
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
3315
+ if (dictionary[key] !== void 0) {
3316
+ const value = dictionary[key];
3194
3317
  model.setRelation(relation, value[0]);
3195
3318
  }
3196
3319
  }
3197
3320
  return models;
3198
3321
  }
3199
- newRelatedInstanceFor(parent) {
3322
+ newRelatedInstanceFor(_parent) {
3200
3323
  return this.related.newInstance();
3201
3324
  }
3202
3325
  };
3203
3326
  var has_one_through_default = HasOneThrough;
3204
3327
 
3205
- // src/concerns/has-relations.js
3328
+ // src/concerns/has-relations.ts
3206
3329
  var import_radashi10 = require("radashi");
3207
3330
  var HasRelations = (Model2) => {
3208
3331
  return class extends Model2 {
@@ -3233,21 +3356,21 @@ var HasRelations = (Model2) => {
3233
3356
  }
3234
3357
  relationsToData() {
3235
3358
  const data = {};
3236
- for (const key2 in this.relations) {
3237
- if (this.hidden.includes(key2)) {
3359
+ for (const key in this.relations) {
3360
+ if (this.hidden.includes(key)) {
3238
3361
  continue;
3239
3362
  }
3240
- if (this.visible.length > 0 && this.visible.includes(key2) === false) {
3363
+ if (this.visible.length > 0 && this.visible.includes(key) === false) {
3241
3364
  continue;
3242
3365
  }
3243
- data[key2] = this.relations[key2] instanceof Array ? this.relations[key2].map((item) => item.toData()) : this.relations[key2] === null ? null : this.relations[key2].toData();
3366
+ data[key] = this.relations[key] instanceof Array ? this.relations[key].map((item) => item.toData()) : this.relations[key] === null ? null : this.relations[key].toData();
3244
3367
  }
3245
3368
  return data;
3246
3369
  }
3247
3370
  guessBelongsToRelation() {
3248
- let e = new Error();
3249
- let frame = e.stack.split("\n")[2];
3250
- let functionName = frame.split(" ")[5];
3371
+ const e = new Error();
3372
+ const frame = e.stack.split("\n")[2];
3373
+ const functionName = frame.split(" ")[5];
3251
3374
  return getRelationName(functionName);
3252
3375
  }
3253
3376
  joiningTable(related, instance = null) {
@@ -3310,7 +3433,7 @@ var HasRelations = (Model2) => {
3310
3433
  };
3311
3434
  var has_relations_default = HasRelations;
3312
3435
 
3313
- // src/concerns/has-timestamps.js
3436
+ // src/concerns/has-timestamps.ts
3314
3437
  var HasTimestamps = (Model2) => {
3315
3438
  return class extends Model2 {
3316
3439
  static CREATED_AT = "created_at";
@@ -3359,7 +3482,7 @@ var HasTimestamps = (Model2) => {
3359
3482
  };
3360
3483
  var has_timestamps_default = HasTimestamps;
3361
3484
 
3362
- // src/concerns/hides-attributes.js
3485
+ // src/concerns/hides-attributes.ts
3363
3486
  var import_radashi11 = require("radashi");
3364
3487
  var HidesAttributes = (Model2) => {
3365
3488
  return class extends Model2 {
@@ -3373,8 +3496,8 @@ var HidesAttributes = (Model2) => {
3373
3496
  this.hidden = (0, import_radashi11.diff)(this.hidden, visible);
3374
3497
  return this;
3375
3498
  }
3376
- makeHidden(...keys) {
3377
- const hidden = flattenDeep(keys);
3499
+ makeHidden(key, ...keys) {
3500
+ const hidden = flattenDeep([...key, ...keys]);
3378
3501
  if (this.hidden.length > 0) {
3379
3502
  this.hidden = [...this.hidden, ...hidden];
3380
3503
  }
@@ -3398,7 +3521,7 @@ var HidesAttributes = (Model2) => {
3398
3521
  };
3399
3522
  var hides_attributes_default = HidesAttributes;
3400
3523
 
3401
- // src/concerns/unique-ids.js
3524
+ // src/concerns/unique-ids.ts
3402
3525
  var UniqueIds = (Model2) => {
3403
3526
  return class extends Model2 {
3404
3527
  useUniqueIds = false;
@@ -3423,37 +3546,47 @@ var UniqueIds = (Model2) => {
3423
3546
  };
3424
3547
  var unique_ids_default = UniqueIds;
3425
3548
 
3426
- // src/model.js
3549
+ // src/model.ts
3427
3550
  var import_collect8 = __toESM(require("collect.js"), 1);
3428
3551
  var import_radashi12 = require("radashi");
3429
3552
  var import_pluralize = __toESM(require("pluralize"), 1);
3430
- var BaseModel = compose(class {
3431
- }, has_attributes_default, hides_attributes_default, has_relations_default, has_timestamps_default, has_hooks_default, has_global_scopes_default, unique_ids_default);
3553
+ var BaseModel = compose(
3554
+ class {
3555
+ },
3556
+ has_attributes_default,
3557
+ hides_attributes_default,
3558
+ has_relations_default,
3559
+ has_timestamps_default,
3560
+ has_hooks_default,
3561
+ has_global_scopes_default,
3562
+ unique_ids_default
3563
+ );
3432
3564
  var Model = class _Model extends BaseModel {
3433
3565
  primaryKey = "id";
3434
- // protected
3435
3566
  builder = null;
3436
- // protected
3437
3567
  table = null;
3438
- // protected
3439
- connection = null;
3440
- // protected
3441
3568
  keyType = "int";
3442
- // protected
3443
3569
  incrementing = true;
3444
- // protected
3445
- perPage = 15;
3446
- // protected
3447
- exists = false;
3448
- eagerLoad = {};
3449
- with = [];
3450
3570
  withCount = [];
3451
3571
  // protected
3452
- trx = null;
3572
+ perPage = 15;
3453
3573
  static globalScopes = {};
3454
3574
  static pluginInitializers = {};
3455
3575
  static _booted = {};
3456
- static resolver = null;
3576
+ static resolver;
3577
+ connection = null;
3578
+ eagerLoad = {};
3579
+ exists = false;
3580
+ with = [];
3581
+ trx = null;
3582
+ constructor(attributes = {}) {
3583
+ super();
3584
+ this.bootIfNotBooted();
3585
+ this.initializePlugins();
3586
+ this.syncOriginal();
3587
+ this.fill(attributes);
3588
+ return this.asProxy();
3589
+ }
3457
3590
  static query(trx = null) {
3458
3591
  const instance = new this();
3459
3592
  return instance.newQuery(trx);
@@ -3471,7 +3604,7 @@ var Model = class _Model extends BaseModel {
3471
3604
  }
3472
3605
  static make(attributes = {}) {
3473
3606
  const instance = new this();
3474
- for (let attribute in attributes) {
3607
+ for (const attribute in attributes) {
3475
3608
  if (typeof instance[getRelationMethod(attribute)] !== "function") {
3476
3609
  instance.setAttribute(attribute, attributes[attribute]);
3477
3610
  } else {
@@ -3486,13 +3619,8 @@ var Model = class _Model extends BaseModel {
3486
3619
  }
3487
3620
  return instance;
3488
3621
  }
3489
- constructor(attributes = {}) {
3490
- super();
3491
- this.bootIfNotBooted();
3492
- this.initializePlugins();
3493
- this.syncOriginal();
3494
- this.fill(attributes);
3495
- return this.asProxy();
3622
+ getConstructor() {
3623
+ return this.constructor;
3496
3624
  }
3497
3625
  bootIfNotBooted() {
3498
3626
  if (this.constructor._booted[this.constructor.name] === void 0) {
@@ -3632,6 +3760,7 @@ var Model = class _Model extends BaseModel {
3632
3760
  return this;
3633
3761
  }
3634
3762
  async loadAggregate(relations, column, callback = null) {
3763
+ console.log(relations);
3635
3764
  await new collection_default([this]).loadAggregate(relations, column, callback);
3636
3765
  return this;
3637
3766
  }
@@ -3660,8 +3789,8 @@ var Model = class _Model extends BaseModel {
3660
3789
  return await query[method](column, amount, extra);
3661
3790
  }
3662
3791
  this.attributes[column] = this[column] + (method === "increment" ? amount : amount * -1);
3663
- for (let key2 in extra) {
3664
- this.attributes[key2] = extra[key2];
3792
+ for (const key in extra) {
3793
+ this.attributes[key] = extra[key];
3665
3794
  }
3666
3795
  await this.execHooks("updating", options);
3667
3796
  return await tap(await query.where(this.getKeyName(), this.getKey())[method](column, amount, extra), async () => {
@@ -3683,8 +3812,8 @@ var Model = class _Model extends BaseModel {
3683
3812
  return this.toJson();
3684
3813
  }
3685
3814
  fill(attributes) {
3686
- for (const key2 in attributes) {
3687
- this.setAttribute(key2, attributes[key2]);
3815
+ for (const key in attributes) {
3816
+ this.setAttribute(key, attributes[key]);
3688
3817
  }
3689
3818
  return this;
3690
3819
  }
@@ -3754,8 +3883,8 @@ var Model = class _Model extends BaseModel {
3754
3883
  if (!this.exists) {
3755
3884
  return false;
3756
3885
  }
3757
- for (let key2 in attributes) {
3758
- this[key2] = attributes[key2];
3886
+ for (const key in attributes) {
3887
+ this[key] = attributes[key];
3759
3888
  }
3760
3889
  return await this.save(options);
3761
3890
  }
@@ -3784,7 +3913,7 @@ var Model = class _Model extends BaseModel {
3784
3913
  }
3785
3914
  async refresh() {
3786
3915
  if (!this.exists) {
3787
- return;
3916
+ return Promise.resolve(void 0);
3788
3917
  }
3789
3918
  const model = await this.constructor.query().where(this.getKeyName(), this.getKey()).first();
3790
3919
  this.attributes = { ...model.attributes };
@@ -3862,10 +3991,15 @@ var Pivot = class extends Model {
3862
3991
  };
3863
3992
  var model_default = Model;
3864
3993
 
3865
- // src/query-builder.js
3866
- var QueryBuilder = class _QueryBuilder {
3867
- connector = null;
3994
+ // src/query-builder.ts
3995
+ var Inference2 = class {
3996
+ };
3997
+ var QueryBuilder = class _QueryBuilder extends Inference2 {
3998
+ model;
3999
+ schema;
4000
+ connector;
3868
4001
  constructor(config, connector) {
4002
+ super();
3869
4003
  this.connector = connector(config);
3870
4004
  return this.asProxy();
3871
4005
  }
@@ -3961,8 +4095,7 @@ var QueryBuilder = class _QueryBuilder {
3961
4095
  return new Proxy(this, handler);
3962
4096
  }
3963
4097
  async beginTransaction() {
3964
- const trx = await this.connector.transaction();
3965
- return new _QueryBuilder(null, () => trx);
4098
+ return await this.connector.transaction();
3966
4099
  }
3967
4100
  table(table) {
3968
4101
  const c = this.connector.table(table);
@@ -3979,7 +4112,7 @@ var QueryBuilder = class _QueryBuilder {
3979
4112
  async find(id, columns = ["*"]) {
3980
4113
  return await this.connector.where("id", id).first(...columns);
3981
4114
  }
3982
- async get(columns = ["*"]) {
4115
+ async get(_columns = ["*"]) {
3983
4116
  return await this.connector;
3984
4117
  }
3985
4118
  async exists() {
@@ -4079,15 +4212,21 @@ var QueryBuilder = class _QueryBuilder {
4079
4212
  };
4080
4213
  var query_builder_default = QueryBuilder;
4081
4214
 
4082
- // src/arquebus.js
4215
+ // src/arquebus.ts
4083
4216
  var arquebus = class _arquebus {
4084
4217
  static connectorFactory = null;
4085
4218
  static instance = null;
4219
+ manager;
4220
+ connections;
4221
+ models;
4086
4222
  constructor() {
4087
4223
  this.manager = {};
4088
4224
  this.connections = {};
4089
4225
  this.models = {};
4090
4226
  }
4227
+ getConstructor() {
4228
+ return this.constructor;
4229
+ }
4091
4230
  static getInstance() {
4092
4231
  if (this.instance === null) {
4093
4232
  this.instance = new _arquebus();
@@ -4101,7 +4240,7 @@ var arquebus = class _arquebus {
4101
4240
  this.connectorFactory = connectorFactory;
4102
4241
  }
4103
4242
  static getConnectorFactory() {
4104
- return this.connectorFactory || import_knex.default;
4243
+ return this.connectorFactory ?? import_knex.default;
4105
4244
  }
4106
4245
  static addConnection(config, name = "default") {
4107
4246
  return this.getInstance().addConnection(config, name);
@@ -4130,7 +4269,7 @@ var arquebus = class _arquebus {
4130
4269
  getConnection(name = null) {
4131
4270
  name = name || "default";
4132
4271
  if (this.manager[name] === void 0) {
4133
- const queryBuilder = new query_builder_default(this.connections[name], this.constructor.getConnectorFactory());
4272
+ const queryBuilder = new query_builder_default(this.connections[name], _arquebus.getConnectorFactory());
4134
4273
  this.manager[name] = queryBuilder;
4135
4274
  }
4136
4275
  return this.manager[name];
@@ -4151,7 +4290,7 @@ var arquebus = class _arquebus {
4151
4290
  };
4152
4291
  }
4153
4292
  beginTransaction(connection = null) {
4154
- return this.connection(connection).transaction();
4293
+ return this.connection(connection).beginTransaction();
4155
4294
  }
4156
4295
  transaction(callback, connection = null) {
4157
4296
  return this.connection(connection).transaction(callback);
@@ -4170,7 +4309,7 @@ var arquebus = class _arquebus {
4170
4309
  createModel(name, options = {}) {
4171
4310
  let BaseModel2 = Model;
4172
4311
  if ("plugins" in options) {
4173
- BaseModel2 = compose(BaseModel2, ...options.plugins);
4312
+ BaseModel2 = compose(BaseModel2, ...options.plugins ?? []);
4174
4313
  }
4175
4314
  this.models = {
4176
4315
  ...this.models,
@@ -4193,13 +4332,13 @@ var arquebus = class _arquebus {
4193
4332
  if (options.attributes[attribute] instanceof attribute_default === false) {
4194
4333
  throw new Error('Attribute must be an instance of "Attribute"');
4195
4334
  }
4196
- this.models[name].prototype[getAttrMethod(attribute)] = () => options.attributes[attribute];
4335
+ this.models[name].prototype[getAttrMethod(attribute)] = () => options.attributes?.[attribute];
4197
4336
  }
4198
4337
  }
4199
4338
  if ("relations" in options) {
4200
4339
  for (const relation in options.relations) {
4201
4340
  this.models[name].prototype[getRelationMethod(relation)] = function() {
4202
- return options.relations[relation](this);
4341
+ return options.relations?.[relation](this);
4203
4342
  };
4204
4343
  }
4205
4344
  }
@@ -4214,371 +4353,590 @@ var arquebus = class _arquebus {
4214
4353
  };
4215
4354
  var arquebus_default = arquebus;
4216
4355
 
4217
- // bin/utils.js
4218
- var color2 = __toESM(require("colorette"), 1);
4219
- var import_sync = __toESM(require("escalade/sync"), 1);
4220
- var import_path2 = __toESM(require("path"), 1);
4221
- var import_resolve_from = __toESM(require("resolve-from"), 1);
4222
- var join = import_path2.default.join;
4223
- async function getMigrationPaths(cwd, migrator, defaultPath, path3) {
4224
- if (path3) {
4225
- return [join(cwd, path3)];
4226
- }
4227
- return [
4228
- ...migrator.getPaths(),
4229
- join(cwd, defaultPath)
4230
- ];
4231
- }
4232
-
4233
- // src/migrate.js
4234
- async function prepareDatabase(migrator) {
4235
- const exists = await migrator.repositoryExists();
4236
- if (!exists) {
4237
- console.log("Preparing database.");
4238
- console.log("Creating migration table...");
4239
- await migrator.repository.createRepository();
4240
- console.log("Migration table created successfully.");
4241
- }
4242
- }
4243
- async function setupConnection(config) {
4244
- const table = config?.migration?.table || "migrations";
4245
- arquebus_default.addConnection(config, "default");
4246
- Object.entries(config.connections || {}).forEach(([name, connection]) => {
4247
- arquebus_default.addConnection(connection, name);
4248
- });
4249
- const repository = new migration_repository_default(arquebus_default, table);
4250
- const migrator = new migrator_default(repository, arquebus_default);
4251
- return { arquebus: arquebus_default, migrator };
4252
- }
4253
- async function migrateRun(config, options = {}, destroyAll = false) {
4254
- const { arquebus: arquebus2, migrator } = await setupConnection(config);
4255
- await prepareDatabase(migrator);
4256
- const paths = await getMigrationPaths(process.cwd(), migrator, config?.migrations?.path, options.path);
4257
- await migrator.setOutput(true).run(paths, {
4258
- step: options.step,
4259
- pretend: options.pretend
4260
- });
4261
- if (destroyAll) {
4262
- await arquebus2.destroyAll();
4263
- }
4264
- }
4265
- async function migrateRollback(config, options = {}, destroyAll = false) {
4266
- const { arquebus: arquebus2, migrator } = await setupConnection(config);
4267
- const paths = await getMigrationPaths(process.cwd(), migrator, config?.migrations?.path, options.path);
4268
- await migrator.setOutput(true).rollback(paths, {
4269
- step: options.step || 0,
4270
- pretend: options.pretend,
4271
- batch: options.batch || 0
4272
- });
4273
- if (destroyAll) {
4274
- await arquebus2.destroyAll();
4275
- }
4276
- }
4277
- async function migrateStatus(config, options = {}, destroyAll = false) {
4278
- const { arquebus: arquebus2, migrator } = await setupConnection(config);
4279
- async function getAllMigrationFiles() {
4280
- return await migrator.getMigrationFiles(await getMigrationPaths(process.cwd(), migrator, config?.migrations?.path, options.path));
4281
- }
4282
- async function getStatusFor(ran2, batches2) {
4283
- const files = await getAllMigrationFiles();
4284
- return Object.values(files).map(function(migration) {
4285
- const migrationName = migrator.getMigrationName(migration);
4286
- const status = {
4287
- name: migrationName,
4288
- ran: ran2.includes(migrationName),
4289
- batch: ran2.includes(migrationName) ? batches2[migrationName] : null
4290
- };
4291
- return status;
4356
+ // src/migrate.ts
4357
+ var Migrate = class {
4358
+ constructor(basePath, customStubPath, callback) {
4359
+ this.basePath = basePath;
4360
+ this.customStubPath = customStubPath;
4361
+ this.callback = callback ?? ((_ = "") => {
4292
4362
  });
4293
4363
  }
4294
- const exists = await migrator.repositoryExists();
4295
- if (!exists) {
4296
- throw new Error("Migration table does not exist.");
4297
- }
4298
- const ran = await migrator.repository.getRan();
4299
- const batches = await migrator.getRepository().getMigrationBatches();
4300
- const migrations = await getStatusFor(ran, batches);
4301
- if (destroyAll) {
4302
- await arquebus2.destroyAll();
4303
- }
4304
- return migrations;
4305
- }
4306
-
4307
- // src/concerns/has-unique-ids.js
4308
- var HasUniqueIds = (Model2) => {
4309
- return class extends Model2 {
4310
- useUniqueIds = true;
4311
- uniqueIds() {
4312
- return [this.getKeyName()];
4364
+ callback;
4365
+ /**
4366
+ * Runs all pending migrations
4367
+ *
4368
+ * @param config
4369
+ * @param options
4370
+ * @param destroyAll
4371
+ */
4372
+ async run(config, options = {}, destroyAll = false) {
4373
+ const { arquebus: arquebus2, migrator } = await this.setupConnection(config);
4374
+ await this.prepareDatabase(migrator);
4375
+ const paths = await Utils.getMigrationPaths(
4376
+ this.basePath ?? process.cwd(),
4377
+ migrator,
4378
+ config.migrations.path,
4379
+ options.path
4380
+ );
4381
+ await migrator.setOutput(true).run(paths, {
4382
+ step: options.step,
4383
+ pretend: options.pretend
4384
+ });
4385
+ if (destroyAll) {
4386
+ await arquebus2.destroyAll();
4387
+ }
4388
+ }
4389
+ /**
4390
+ * Rollback the last migration
4391
+ *
4392
+ * @param config
4393
+ * @param options
4394
+ * @param destroyAll
4395
+ */
4396
+ async rollback(config, options = {}, destroyAll = false) {
4397
+ const { arquebus: arquebus2, migrator } = await this.setupConnection(config);
4398
+ const paths = await Utils.getMigrationPaths(
4399
+ this.basePath ?? process.cwd(),
4400
+ migrator,
4401
+ config.migrations.path,
4402
+ options.path
4403
+ );
4404
+ await migrator.setOutput(true).rollback(paths, {
4405
+ step: options.step || 0,
4406
+ pretend: options.pretend,
4407
+ batch: options.batch || 0
4408
+ });
4409
+ if (destroyAll) {
4410
+ await arquebus2.destroyAll();
4411
+ }
4412
+ }
4413
+ /**
4414
+ * Prepares the database for migration
4415
+ *
4416
+ * @param migrator
4417
+ */
4418
+ async prepareDatabase(migrator) {
4419
+ const exists = await migrator.repositoryExists();
4420
+ if (!exists) {
4421
+ this.callback("INFO: Preparing database.", "info");
4422
+ this.callback("INFO: Creating migration table...", "info");
4423
+ await migrator.repository.createRepository();
4424
+ this.callback("SUCCESS: Migration table created successfully.", "success");
4425
+ }
4426
+ }
4427
+ /**
4428
+ * Check the status of available migrations
4429
+ *
4430
+ * @param config
4431
+ * @param options
4432
+ * @param destroyAll
4433
+ * @returns
4434
+ */
4435
+ async status(config, options = {}, destroyAll = false) {
4436
+ const { arquebus: arquebus2, migrator } = await this.setupConnection(config);
4437
+ const getAllMigrationFiles = async () => {
4438
+ return await migrator.getMigrationFiles(
4439
+ await Utils.getMigrationPaths(
4440
+ this.basePath ?? process.cwd(),
4441
+ migrator,
4442
+ config.migrations.path,
4443
+ options.path
4444
+ )
4445
+ );
4446
+ };
4447
+ async function getStatusFor(ran2, batches2) {
4448
+ const files = await getAllMigrationFiles();
4449
+ return Object.values(files).map((migration) => {
4450
+ const migrationName = migrator.getMigrationName(migration);
4451
+ return {
4452
+ name: migrationName,
4453
+ ran: ran2.includes(migrationName),
4454
+ batch: ran2.includes(migrationName) ? batches2[migrationName] : null
4455
+ };
4456
+ });
4313
4457
  }
4314
- getKeyType() {
4315
- if (this.uniqueIds().includes(this.getKeyName())) {
4316
- return "string";
4317
- }
4318
- return this.keyType;
4458
+ const exists = await migrator.repositoryExists();
4459
+ if (!exists) {
4460
+ this.callback("ERROR: Migration table does not exist.", "error");
4319
4461
  }
4320
- getIncrementing() {
4321
- if (this.uniqueIds().includes(this.getKeyName())) {
4322
- return false;
4323
- }
4324
- return this.incrementing;
4462
+ const ran = await migrator.repository.getRan();
4463
+ const batches = await migrator.getRepository().getMigrationBatches();
4464
+ const migrations = await getStatusFor(ran, batches);
4465
+ if (destroyAll) {
4466
+ await arquebus2.destroyAll();
4325
4467
  }
4326
- };
4327
- };
4328
- var has_unique_ids_default = HasUniqueIds;
4329
-
4330
- // src/migrations/migration.js
4331
- var Migration = class {
4332
- connection;
4333
- withinTransaction = true;
4334
- getConnection() {
4335
- return this.connection;
4468
+ return migrations;
4469
+ }
4470
+ /**
4471
+ * Setup the database connection
4472
+ *
4473
+ * @param config
4474
+ * @returns
4475
+ */
4476
+ async setupConnection(config) {
4477
+ const table = config?.migrations?.table || "migrations";
4478
+ arquebus_default.addConnection(config, "default");
4479
+ Object.entries(config.connections || {}).forEach(([name, connection]) => {
4480
+ arquebus_default.addConnection(connection, name);
4481
+ });
4482
+ const repository = new migration_repository_default(arquebus_default, table);
4483
+ const migrator = new migrator_default(repository, arquebus_default);
4484
+ return { arquebus: arquebus_default, migrator };
4336
4485
  }
4337
4486
  };
4338
- var migration_default = Migration;
4339
-
4340
- // src/pivot.js
4341
- var pivot_default = Pivot;
4342
4487
 
4343
- // src/soft-deleting-scope.js
4344
- var hasJoins = (statements) => {
4345
- for (const statement of statements) {
4346
- if (statement?.grouping === "join") {
4347
- return true;
4488
+ // src/migrations/migration-creator.ts
4489
+ var import_node_fs = require("fs");
4490
+ var import_dayjs3 = __toESM(require("dayjs"), 1);
4491
+ var import_node_path = require("path");
4492
+ var import_node_url = require("url");
4493
+ var import_promises3 = __toESM(require("fs/promises"), 1);
4494
+ var import_path3 = __toESM(require("path"), 1);
4495
+ var import_meta = {};
4496
+ var MigrationCreator = class {
4497
+ constructor(customStubPath, type = "js") {
4498
+ this.customStubPath = customStubPath;
4499
+ this.type = type;
4500
+ }
4501
+ postCreate = [];
4502
+ /**
4503
+ * Create a new migration file
4504
+ *
4505
+ * @param name
4506
+ * @param dir
4507
+ * @param table
4508
+ * @param create
4509
+ * @returns
4510
+ */
4511
+ async create(name, dir, table, create = false) {
4512
+ const stub = this.getStub(table, create);
4513
+ const filePath = this.getPath(name, dir);
4514
+ await this.ensureDirectoryExists(import_path3.default.dirname(filePath));
4515
+ await import_promises3.default.writeFile(filePath, this.populateStub(stub, table));
4516
+ await this.firePostCreateHooks(table, filePath);
4517
+ return filePath;
4518
+ }
4519
+ /**
4520
+ * Publish migrations from third party vendors
4521
+ *
4522
+ * @param dir
4523
+ * @param callback
4524
+ */
4525
+ async publish(dir, callback) {
4526
+ const migrationFiles = await import_promises3.default.readdir(this.customStubPath ?? "");
4527
+ await this.ensureDirectoryExists(dir);
4528
+ for (const migrationFile of migrationFiles) {
4529
+ const sourceFilePath = import_path3.default.join(this.customStubPath ?? "", migrationFile);
4530
+ const destinationFilePath = import_path3.default.join(dir, migrationFile);
4531
+ await import_promises3.default.copyFile(sourceFilePath, destinationFilePath);
4532
+ if (callback) callback(migrationFile, sourceFilePath, destinationFilePath);
4533
+ }
4534
+ }
4535
+ getStub(table, create = false) {
4536
+ let stub;
4537
+ if (!table) {
4538
+ const customPath = import_path3.default.join(this.customStubPath ?? "", `migration-${this.type}.stub`);
4539
+ console.log("\n", customPath, "---");
4540
+ stub = (0, import_node_fs.existsSync)(customPath) ? customPath : this.stubPath(`/migration-${this.type}.stub`);
4541
+ } else if (create) {
4542
+ const customPath = import_path3.default.join(this.customStubPath ?? "", `migration.create-${this.type}.stub`);
4543
+ stub = (0, import_node_fs.existsSync)(customPath) ? customPath : this.stubPath(`/migration.create-${this.type}.stub`);
4544
+ } else {
4545
+ const customPath = import_path3.default.join(this.customStubPath ?? "", `migration.update-${this.type}.stub`);
4546
+ stub = (0, import_node_fs.existsSync)(customPath) ? customPath : this.stubPath(`/migration.update-${this.type}.stub`);
4348
4547
  }
4548
+ return (0, import_node_fs.readFileSync)(stub, "utf-8");
4349
4549
  }
4350
- return false;
4351
- };
4352
- var SoftDeletingScope = class extends scope_default {
4353
- extensions = ["Restore", "RestoreOrCreate", "CreateOrRestore", "WithTrashed", "WithoutTrashed", "OnlyTrashed"];
4354
- apply(builder, model) {
4355
- builder.whereNull(model.getQualifiedDeletedAtColumn());
4356
- }
4357
- extend(builder) {
4358
- for (const extension of this.extensions) {
4359
- this[`add${extension}`](builder);
4360
- }
4361
- builder.onDelete(async (builder2) => {
4362
- const column = this.getDeletedAtColumn(builder2);
4363
- return await builder2.update({
4364
- [column]: builder2.getModel().freshTimestampString()
4365
- });
4366
- });
4367
- }
4368
- getDeletedAtColumn(builder) {
4369
- if (hasJoins(builder.getQuery()._statements)) {
4370
- return builder.getModel().getQualifiedDeletedAtColumn();
4550
+ populateStub(stub, table) {
4551
+ if (table !== null) {
4552
+ stub = stub.replace(/DummyTable|{{\s*table\s*}}/g, table);
4371
4553
  }
4372
- return builder.getModel().getDeletedAtColumn();
4554
+ return stub;
4373
4555
  }
4374
- addRestore(builder) {
4375
- builder.macro("restore", (builder2) => {
4376
- builder2.withTrashed();
4377
- return builder2.update({
4378
- [builder2.getModel().getDeletedAtColumn()]: null
4379
- });
4380
- });
4556
+ getClassName(name) {
4557
+ return name.replace(/_+([a-z])/g, (match, char) => char.toUpperCase());
4381
4558
  }
4382
- addRestoreOrCreate(builder) {
4383
- builder.macro("restoreOrCreate", async (builder2, attributes = {}, values = {}) => {
4384
- builder2.withTrashed();
4385
- return tap(await builder2.firstOrCreate(attributes, values), async (instance) => {
4386
- await instance.restore();
4387
- });
4388
- });
4559
+ getPath(name, dir) {
4560
+ const datePrefix = (0, import_dayjs3.default)().format("YYYY_MM_DD_HHmmss");
4561
+ return import_path3.default.join(dir, `${datePrefix}_${name}.${this.type}`);
4389
4562
  }
4390
- addCreateOrRestore(builder) {
4391
- builder.macro("createOrRestore", async (builder2, attributes = {}, values = {}) => {
4392
- builder2.withTrashed();
4393
- return tap(await builder2.createOrFirst(attributes, values), async (instance) => {
4394
- await instance.restore();
4395
- });
4396
- });
4563
+ async firePostCreateHooks(table, filePath) {
4564
+ for (const callback of this.postCreate) {
4565
+ await callback(table, filePath);
4566
+ }
4397
4567
  }
4398
- addWithTrashed(builder) {
4399
- builder.macro("withTrashed", (builder2, withTrashed = true) => {
4400
- if (!withTrashed) {
4401
- return builder2.withoutTrashed();
4402
- }
4403
- return builder2.withoutGlobalScope(this);
4404
- });
4568
+ afterCreate(callback) {
4569
+ this.postCreate.push(callback);
4405
4570
  }
4406
- addWithoutTrashed(builder) {
4407
- builder.macro("withoutTrashed", (builder2) => {
4408
- const model = builder2.getModel();
4409
- builder2.withoutGlobalScope(this).whereNull(model.getQualifiedDeletedAtColumn());
4410
- return builder2;
4411
- });
4571
+ async ensureDirectoryExists(dir) {
4572
+ await import_promises3.default.mkdir(dir, { recursive: true });
4412
4573
  }
4413
- addOnlyTrashed(builder) {
4414
- builder.macro("onlyTrashed", (builder2) => {
4415
- const model = builder2.getModel();
4416
- builder2.withoutGlobalScope(this).whereNotNull(model.getQualifiedDeletedAtColumn());
4417
- return builder2;
4418
- });
4574
+ stubPath(stub = "") {
4575
+ const __dirname2 = this.getDirname(import_meta);
4576
+ return import_path3.default.join(__dirname2, "stubs", stub);
4577
+ }
4578
+ getDirname(meta) {
4579
+ if (typeof __dirname !== "undefined") {
4580
+ return __dirname;
4581
+ }
4582
+ if (meta && meta.url) {
4583
+ return (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(meta.url));
4584
+ }
4585
+ throw new Error("Unable to determine dirname");
4419
4586
  }
4420
4587
  };
4421
- var soft_deleting_scope_default = SoftDeletingScope;
4588
+ var migration_creator_default = MigrationCreator;
4589
+
4590
+ // src/cli/cli.ts
4591
+ var import_chalk3 = __toESM(require("chalk"), 1);
4422
4592
 
4423
- // src/soft-deletes.js
4593
+ // package.json
4594
+ var package_default = {
4595
+ name: "@h3ravel/arquebus",
4596
+ version: "0.1.6",
4597
+ packageManager: "pnpm@10.14.0",
4598
+ description: "Arquebus ORM is a Beautiful, expressive ORM inspired by Laravel's Eloquent, designed for TypeScript applications and for the H3ravel Framework.",
4599
+ homepage: "https://h3ravel.net/arquebus",
4600
+ bin: {
4601
+ arquebus: "./bin/cli.js"
4602
+ },
4603
+ publishConfig: {
4604
+ access: "public"
4605
+ },
4606
+ main: "./dist/index.cjs",
4607
+ module: "./dist/index.js",
4608
+ type: "module",
4609
+ types: "./dist/index.d.ts",
4610
+ files: [
4611
+ "dist",
4612
+ "bin",
4613
+ "src/stubs",
4614
+ "src/migrations/stubs"
4615
+ ],
4616
+ exports: {
4617
+ ".": {
4618
+ worker: {
4619
+ import: {
4620
+ types: "./dist/index.d.ts",
4621
+ default: "./dist/index.js"
4622
+ },
4623
+ require: {
4624
+ types: "./dist/index.d.ts",
4625
+ default: "./dist/index.cjs"
4626
+ }
4627
+ },
4628
+ node: {
4629
+ import: {
4630
+ types: "./dist/index.d.ts",
4631
+ default: "./dist/index.js"
4632
+ },
4633
+ require: {
4634
+ types: "./dist/index.d.ts",
4635
+ default: "./dist/index.cjs"
4636
+ }
4637
+ },
4638
+ browser: {
4639
+ import: {
4640
+ types: "./dist/browser/index.d.ts",
4641
+ default: "./dist/browser/index.js"
4642
+ },
4643
+ require: {
4644
+ types: "./dist/browser/index.d.ts",
4645
+ default: "./dist/browser/index.cjs"
4646
+ }
4647
+ },
4648
+ default: {
4649
+ import: {
4650
+ types: "./dist/index.d.ts",
4651
+ default: "./dist/index.js"
4652
+ },
4653
+ require: {
4654
+ types: "./dist/index.d.ts",
4655
+ default: "./dist/index.cjs"
4656
+ }
4657
+ }
4658
+ },
4659
+ "./browser": {
4660
+ import: {
4661
+ types: "./dist/browser/index.d.ts",
4662
+ default: "./dist/browser/index.js"
4663
+ },
4664
+ require: {
4665
+ types: "./dist/browser/index.d.ts",
4666
+ default: "./dist/browser/index.cjs"
4667
+ }
4668
+ },
4669
+ "./package.json": "./package.json"
4670
+ },
4671
+ repository: {
4672
+ type: "git",
4673
+ url: "https://github.com/h3ravel/arquebus.git"
4674
+ },
4675
+ engines: {
4676
+ node: ">=14",
4677
+ pnpm: ">=4"
4678
+ },
4679
+ scripts: {
4680
+ build: "tsup",
4681
+ lint: "eslint . --ext .ts",
4682
+ cmd: "cross-env TEST=true tsx --experimental-specifier-resolution=node src/cli",
4683
+ "cmd:watch": "cross-env TEST=true tsx watch --experimental-specifier-resolution=node src/cli",
4684
+ "test:mysql": "cross-env DB=mysql vitest --project node",
4685
+ "test:postgres": "cross-env DB=postgres vitest --project node",
4686
+ "test:sqlite": "cross-env DB=sqlite vitest --project node",
4687
+ "test:browser": "vitest --project browser"
4688
+ },
4689
+ husky: {
4690
+ hooks: {
4691
+ "pre-commit": "lint-staged"
4692
+ }
4693
+ },
4694
+ "lint-staged": {
4695
+ "*.{js,json}": [
4696
+ "prettier --write",
4697
+ "git add"
4698
+ ]
4699
+ },
4700
+ dependencies: {
4701
+ chalk: "^5.6.0",
4702
+ "collect.js": "^4.36.1",
4703
+ commander: "^11.1.0",
4704
+ dayjs: "^1.11.13",
4705
+ dotenv: "^17.2.1",
4706
+ escalade: "^3.2.0",
4707
+ knex: "^3.1.0",
4708
+ pluralize: "^8.0.0",
4709
+ radashi: "^12.6.2",
4710
+ "resolve-from": "^5.0.0"
4711
+ },
4712
+ devDependencies: {
4713
+ "@eslint/js": "^9.33.0",
4714
+ "@types/node": "^24.3.0",
4715
+ "@types/pluralize": "^0.0.33",
4716
+ "@typescript-eslint/eslint-plugin": "^8.40.0",
4717
+ "@typescript-eslint/parser": "^8.40.0",
4718
+ "cross-env": "^7.0.3",
4719
+ eslint: "^9.33.0",
4720
+ husky: "^8.0.3",
4721
+ jsdom: "^26.1.0",
4722
+ "lint-staged": "^13.3.0",
4723
+ mysql2: "3.12.0",
4724
+ pg: "8.8.0",
4725
+ prettier: "2.6.2",
4726
+ sqlite3: "5.1.7",
4727
+ tedious: "15.1.0",
4728
+ "ts-node": "^10.9.2",
4729
+ tsup: "^8.5.0",
4730
+ tsx: "^4.20.4",
4731
+ typescript: "^5.9.2",
4732
+ "typescript-eslint": "^8.40.0",
4733
+ "vite-tsconfig-paths": "^5.1.4",
4734
+ vitest: "^3.2.4"
4735
+ },
4736
+ keywords: [
4737
+ "arquebus",
4738
+ "ORM",
4739
+ "mysql",
4740
+ "mariadb",
4741
+ "sqlite",
4742
+ "postgresql",
4743
+ "postgres",
4744
+ "pg",
4745
+ "mssql",
4746
+ "active record"
4747
+ ],
4748
+ readmeFilename: "README.md",
4749
+ license: "MIT"
4750
+ };
4751
+
4752
+ // src/cli/cli.ts
4753
+ var import_dotenv = require("dotenv");
4754
+ var import_path4 = __toESM(require("path"), 1);
4424
4755
  var import_radashi13 = require("radashi");
4425
- var softDeletes = (Model2) => {
4426
- return class extends Model2 {
4427
- forceDeleting = false;
4428
- static bootSoftDeletes() {
4429
- this.addGlobalScope(new soft_deleting_scope_default());
4430
- }
4431
- initialize() {
4432
- super.initialize();
4433
- this.constructor.bootSoftDeletes();
4434
- this.addPluginInitializer("initializeSoftDeletes");
4756
+ var Cli = class _Cli {
4757
+ cwd;
4758
+ output = Utils.output();
4759
+ config = {};
4760
+ basePath = "";
4761
+ modulePath;
4762
+ configPath;
4763
+ modulePackage;
4764
+ constructor(basePath) {
4765
+ this.basePath = basePath ?? (process.env.TEST === "true" ? "test/cli" : "");
4766
+ }
4767
+ terminateNotFound() {
4768
+ this.output.error(
4769
+ `ERROR: Arquebus config not found. Run ${import_chalk3.default.italic.black.bgGray("arquebus init")} first.`
4770
+ );
4771
+ }
4772
+ static init() {
4773
+ (0, import_dotenv.config)({ quiet: true });
4774
+ const instance = new _Cli();
4775
+ Promise.all([instance.loadPaths(), instance.loadConfig()]).then(([_, e]) => e.run());
4776
+ }
4777
+ async loadPaths() {
4778
+ this.cwd = import_path4.default.join(process.cwd(), this.basePath);
4779
+ this.configPath = Utils.findUpConfig(this.cwd, "arquebus.config", ["js", "ts", "cjs"]) ?? void 0;
4780
+ this.modulePath = Utils.findModulePkg("@h3ravel/arquebus", this.cwd) ?? "";
4781
+ try {
4782
+ this.modulePackage = await import(import_path4.default.join(this.modulePath, "package.json"));
4783
+ } catch {
4784
+ this.modulePackage = { version: "N/A" };
4435
4785
  }
4436
- initializeSoftDeletes() {
4437
- if (this.casts[this.getDeletedAtColumn()] === void 0) {
4438
- this.casts[this.getDeletedAtColumn()] = "datetime";
4439
- }
4786
+ return this;
4787
+ }
4788
+ async loadConfig() {
4789
+ try {
4790
+ this.config = (await import(this.configPath ?? "----")).default;
4791
+ } catch {
4792
+ this.config = {};
4440
4793
  }
4441
- async forceDelete() {
4442
- if (this.execHooks("forceDeleting") === false) {
4443
- return false;
4794
+ return this;
4795
+ }
4796
+ async run() {
4797
+ const cliVersion = [
4798
+ "Arquebus CLI version:",
4799
+ import_chalk3.default.green(package_default.version)
4800
+ ].join(" ");
4801
+ const localVersion = [
4802
+ "Arquebus Local version:",
4803
+ import_chalk3.default.green(this.modulePackage.version || "None")
4804
+ ].join(" ");
4805
+ import_commander.program.name("arquebus").version(`${cliVersion}
4806
+ ${localVersion}`);
4807
+ import_commander.program.command("init").description("Create a fresh Arquebus config.").addArgument(
4808
+ new import_commander.Argument("[type]", "Type of config to generate.").choices(["js", "ts"]).default("js", "generates a js config")
4809
+ ).action(async (type) => {
4810
+ if (!this.modulePath) this.output.error([
4811
+ "ERROR: No local arquebus install found",
4812
+ " Try running: npm install arquebus --save"
4813
+ ]);
4814
+ if (this.configPath) {
4815
+ this.output.error(`ERROR: ${this.configPath} already exists`);
4816
+ }
4817
+ try {
4818
+ const stubPath = `./arquebus.config.${type}`;
4819
+ const code = await (0, import_promises4.readFile)(
4820
+ import_path4.default.join(this.modulePath, `/src/stubs/arquebus.config-${type}.stub`),
4821
+ { encoding: "utf8" }
4822
+ );
4823
+ await (0, import_promises4.writeFile)(import_path4.default.join(this.cwd, stubPath), code);
4824
+ this.output.success(`Initialized: Arquebus has been initialized as ${stubPath}`);
4825
+ } catch (e) {
4826
+ this.output.error("ERROR: " + e);
4444
4827
  }
4445
- this.forceDeleting = true;
4446
- return tap(await this.delete(), (deleted) => {
4447
- this.forceDeleting = false;
4448
- if (deleted) {
4449
- this.execHooks("forceDeleted", false);
4828
+ });
4829
+ import_commander.program.command("migrate:make <name>").description("Create a new migration file.").addOption(
4830
+ new import_commander.Option("-l, --type [string]", "Type of migration file to generate.").choices(["js", "ts"]).default("js", "generates a js migration file")
4831
+ ).option("-t, --table [string]", "The table to migrate").option("-c, --create [string]", "The table to be created").option("-p, --path [path]", "The path to the migrations directory.").action(async (name, opts) => {
4832
+ if (!this.configPath) this.terminateNotFound();
4833
+ try {
4834
+ name = (0, import_radashi13.snake)(name);
4835
+ const migrationPath = import_path4.default.join(this.cwd, opts.path ?? this.config.migrations?.path ?? "./migrations");
4836
+ let table = opts.table;
4837
+ let create = opts.create || false;
4838
+ if (!table && typeof create === "string") {
4839
+ table = create;
4840
+ create = true;
4450
4841
  }
4451
- });
4452
- }
4453
- forceDeleteQuietly() {
4454
- return this.withoutEvents(() => this.forceDelete());
4455
- }
4456
- async performDeleteOnModel(options = {}) {
4457
- if (this.forceDeleting) {
4458
- return tap(await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete(), () => {
4459
- this.exists = false;
4842
+ if (!table) {
4843
+ const guessed = TableGuesser.guess(name);
4844
+ table = guessed[0];
4845
+ create = !!guessed[1];
4846
+ }
4847
+ this.output.info("INFO: Creating Migration");
4848
+ const creator = new migration_creator_default(void 0, opts.type);
4849
+ const fileName = await creator.create(name, migrationPath, table, create);
4850
+ this.output.success(`INFO: Migration Created
4851
+ ${import_chalk3.default.gray(import_path4.default.basename(fileName))}`, true);
4852
+ } catch (e) {
4853
+ this.output.error("ERROR: " + e);
4854
+ }
4855
+ });
4856
+ import_commander.program.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]", "The path to the migrations directory.").action(async (pkg, opts) => {
4857
+ if (!this.configPath) {
4858
+ this.terminateNotFound();
4859
+ }
4860
+ try {
4861
+ const packagePath = Utils.findModulePkg(pkg) ?? "";
4862
+ const basePath = import_path4.default.join(this.cwd, opts.path ?? this.config.migrations?.path ?? "./migrations");
4863
+ const pkgJson = await import(import_path4.default.join(packagePath, "package.json"));
4864
+ if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
4865
+ const creator = new migration_creator_default(import_path4.default.join(packagePath, pkgJson.migrations ?? "migrations"));
4866
+ this.output.info(`INFO: Publishing migrations from ${import_chalk3.default.italic.gray(pkgJson.name + "@" + pkgJson.version)}`);
4867
+ await creator.publish(basePath, (fileName) => {
4868
+ Utils.twoColumnDetail(fileName, import_chalk3.default.green("PUBLISHED"));
4460
4869
  });
4870
+ } catch (e) {
4871
+ this.output.error("ERROR: " + e);
4461
4872
  }
4462
- return await this.runSoftDelete(options);
4463
- }
4464
- async runSoftDelete(options = {}) {
4465
- const query = this.setKeysForSaveQuery(this.newModelQuery());
4466
- const time = this.freshTimestamp();
4467
- const columns = {
4468
- [this.getDeletedAtColumn()]: this.fromDateTime(time)
4469
- };
4470
- this[this.getDeletedAtColumn()] = time;
4471
- if (this.usesTimestamps() && this.getUpdatedAtColumn()) {
4472
- this[this.getUpdatedAtColumn()] = time;
4473
- columns[this.getUpdatedAtColumn()] = this.fromDateTime(time);
4873
+ });
4874
+ import_commander.program.command("migrate").description("Run all pending migrations.").option("-s, --step [number]", "Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
4875
+ if (!this.configPath) {
4876
+ this.terminateNotFound();
4474
4877
  }
4475
- await query.update(columns);
4476
- this.syncOriginalAttributes(Object.keys(columns));
4477
- this.execHooks("trashed", options);
4478
- }
4479
- async restore(options = {}) {
4480
- if (this.execHooks("restoring", options) === false) {
4481
- return false;
4878
+ const basePath = opts.path ? import_path4.default.join(this.cwd, opts.path) : this.cwd;
4879
+ try {
4880
+ await new Migrate(basePath).run(this.config, opts, true);
4881
+ } catch (e) {
4882
+ this.output.error("ERROR: " + e);
4482
4883
  }
4483
- this[this.getDeletedAtColumn()] = null;
4484
- this.exists = true;
4485
- const result = await this.save();
4486
- this.execHooks("restored", options);
4487
- return result;
4488
- }
4489
- restoreQuietly() {
4490
- return this.withoutEvents(() => this.restore());
4491
- }
4492
- trashed() {
4493
- return !(0, import_radashi13.isNullish)(this[this.getDeletedAtColumn()]);
4494
- }
4495
- static softDeleted(callback) {
4496
- this.addHook("trashed", callback);
4497
- }
4498
- static restoring(callback) {
4499
- this.addHook("restoring", callback);
4500
- }
4501
- static restored(callback) {
4502
- this.addHook("restored", callback);
4503
- }
4504
- static forceDeleting(callback) {
4505
- this.addHook("forceDeleting", callback);
4506
- }
4507
- static forceDeleted(callback) {
4508
- this.addHook("forceDeleted", callback);
4509
- }
4510
- isForceDeleting() {
4511
- return this.forceDeleting;
4512
- }
4513
- getDeletedAtColumn() {
4514
- return this.constructor.DELETED_AT || "deleted_at";
4515
- }
4516
- getQualifiedDeletedAtColumn() {
4517
- return this.qualifyColumn(this.getDeletedAtColumn());
4518
- }
4519
- };
4520
- };
4521
- var soft_deletes_default = softDeletes;
4522
-
4523
- // src/index.js
4524
- var make = (model, data, options = {}) => {
4525
- const { paginated } = options;
4526
- if (paginated) {
4527
- return new paginator_default(
4528
- data.data.map((item) => model.make(item)),
4529
- data.total,
4530
- data.per_page,
4531
- data.current_page
4532
- );
4533
- }
4534
- if (Array.isArray(data)) {
4535
- return new collection_default(data.map((item) => model.make(item)));
4884
+ });
4885
+ import_commander.program.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]", "The number of migrations to be reverted.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
4886
+ if (!this.configPath) this.terminateNotFound();
4887
+ const basePath = opts.path ? import_path4.default.join(this.cwd, opts.path) : this.cwd;
4888
+ try {
4889
+ await new Migrate(basePath, void 0, (msg, sts) => {
4890
+ if (sts) this.output[sts](msg);
4891
+ }).rollback(this.config, opts, true);
4892
+ } catch (e) {
4893
+ this.output.error("ERROR: " + e);
4894
+ }
4895
+ });
4896
+ import_commander.program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
4897
+ if (!this.configPath) this.terminateNotFound();
4898
+ const basePath = opts.path ? import_path4.default.join(this.cwd, opts.path) : this.cwd;
4899
+ try {
4900
+ const migrations = await new Migrate(basePath, void 0, (msg, sts) => {
4901
+ if (sts) this.output[sts](msg);
4902
+ }).status(this.config, opts, true);
4903
+ if (migrations.length > 0) {
4904
+ Utils.twoColumnDetail(import_chalk3.default.gray("Migration name"), import_chalk3.default.gray("Batch / Status"));
4905
+ migrations.forEach((migration) => {
4906
+ const status = migration.ran ? `[${migration.batch}] ${import_chalk3.default.green("Ran")}` : import_chalk3.default.yellow("Pending");
4907
+ Utils.twoColumnDetail(migration.name, status);
4908
+ });
4909
+ } else {
4910
+ console.log("No migrations found");
4911
+ }
4912
+ } catch (e) {
4913
+ this.output.error("ERROR: " + e);
4914
+ }
4915
+ });
4916
+ import_commander.program.command("model:make <name>").description("Create a new Model file.").addOption(
4917
+ new import_commander.Option("-l, --type [string]", "Type of migration file to generate.").choices(["js", "ts"]).default("js", "generates a js migration file")
4918
+ ).option("--force", "Force creation if model already exists.", false).option("-p, --path [path]", "The path to the models directory.").action(async (name, opts) => {
4919
+ if (!this.configPath) this.terminateNotFound();
4920
+ const modelPath = import_path4.default.join(this.cwd, opts.path ?? this.config.models?.path ?? "./models", name.toLowerCase() + "." + opts.type);
4921
+ try {
4922
+ if (!opts.force && await Utils.fileExists(modelPath)) {
4923
+ this.output.error("ERROR: Model already exists.");
4924
+ }
4925
+ await (0, import_promises4.mkdir)(import_path4.default.dirname(modelPath), { recursive: true });
4926
+ const stubPath = import_path4.default.join(this.modulePath, `src/stubs/model-${opts.type}.stub`);
4927
+ let stub = await (0, import_promises4.readFile)(stubPath, "utf-8");
4928
+ stub = stub.replace(/{{ name }}/g, name);
4929
+ await (0, import_promises4.writeFile)(modelPath, stub);
4930
+ this.output.success(`Created Model: ${modelPath}`);
4931
+ } catch (e) {
4932
+ this.output.error("ERROR: " + e);
4933
+ }
4934
+ });
4935
+ await import_commander.program.parseAsync(process.argv);
4936
+ process.exit(0);
4536
4937
  }
4537
- return model.make(data);
4538
4938
  };
4539
- var makeCollection = (model, data) => new collection_default(data.map((item) => model.make(item)));
4540
- var makePaginator = (model, data) => new paginator_default(
4541
- data.data.map((item) => model.make(item)),
4542
- data.total,
4543
- data.per_page,
4544
- data.current_page
4545
- );
4546
4939
  // Annotate the CommonJS export names for ESM import in node:
4547
4940
  0 && (module.exports = {
4548
- Attribute,
4549
- Builder,
4550
- CastsAttributes,
4551
- Collection,
4552
- HasUniqueIds,
4553
- InvalidArgumentError,
4554
- Migration,
4555
- Model,
4556
- ModelNotFoundError,
4557
- Paginator,
4558
- Pivot,
4559
- QueryBuilder,
4560
- RelationNotFoundError,
4561
- Scope,
4562
- SoftDeletes,
4563
- arquebus,
4564
- compose,
4565
- flattenDeep,
4566
- getAttrMethod,
4567
- getAttrName,
4568
- getGetterMethod,
4569
- getRelationMethod,
4570
- getRelationName,
4571
- getScopeMethod,
4572
- getScopeName,
4573
- getSetterMethod,
4574
- kebabCase,
4575
- make,
4576
- makeCollection,
4577
- makePaginator,
4578
- migrateRollback,
4579
- migrateRun,
4580
- migrateStatus,
4581
- now,
4582
- snakeCase,
4583
- tap
4941
+ Cli
4584
4942
  });