@geekmidas/testkit 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +110 -16
  2. package/dist/{Factory-z2m01hMj.mjs → Factory-BFVnMMCC.mjs} +2 -2
  3. package/dist/Factory-BFVnMMCC.mjs.map +1 -0
  4. package/dist/{Factory-D7oHtI2D.d.cts → Factory-BK06XuDA.d.cts} +24 -10
  5. package/dist/{Factory-Cmr3s3-s.d.mts → Factory-BcGJjLc8.d.mts} +23 -9
  6. package/dist/{Factory-WMhTNZ9S.cjs → Factory-BhjUOBWN.cjs} +2 -2
  7. package/dist/Factory-BhjUOBWN.cjs.map +1 -0
  8. package/dist/Factory.cjs +1 -1
  9. package/dist/Factory.d.cts +3 -3
  10. package/dist/Factory.d.mts +2 -2
  11. package/dist/Factory.mjs +1 -1
  12. package/dist/{KyselyFactory-DaaCykWP.cjs → KyselyFactory-BFqVIn_0.cjs} +21 -4
  13. package/dist/KyselyFactory-BFqVIn_0.cjs.map +1 -0
  14. package/dist/{KyselyFactory-dYdviox2.d.cts → KyselyFactory-Bu9ssWZP.d.cts} +18 -5
  15. package/dist/{KyselyFactory-BTdygZ-i.d.mts → KyselyFactory-Cj-EultY.d.mts} +17 -4
  16. package/dist/{KyselyFactory-CXY5gJk2.mjs → KyselyFactory-DMswpwji.mjs} +21 -4
  17. package/dist/KyselyFactory-DMswpwji.mjs.map +1 -0
  18. package/dist/KyselyFactory.cjs +2 -2
  19. package/dist/KyselyFactory.d.cts +3 -3
  20. package/dist/KyselyFactory.d.mts +2 -2
  21. package/dist/KyselyFactory.mjs +2 -2
  22. package/dist/{ObjectionFactory-Eb04AOnv.cjs → ObjectionFactory-BeFBYcan.cjs} +21 -4
  23. package/dist/ObjectionFactory-BeFBYcan.cjs.map +1 -0
  24. package/dist/{ObjectionFactory-BagGjikT.d.mts → ObjectionFactory-DL4qkuF1.d.mts} +17 -4
  25. package/dist/{ObjectionFactory-zf2fLKrL.mjs → ObjectionFactory-QCJ7u0Ql.mjs} +21 -4
  26. package/dist/ObjectionFactory-QCJ7u0Ql.mjs.map +1 -0
  27. package/dist/{ObjectionFactory-0gUdx8bB.d.cts → ObjectionFactory-tKWZOiYO.d.cts} +18 -5
  28. package/dist/ObjectionFactory.cjs +2 -2
  29. package/dist/ObjectionFactory.d.cts +3 -3
  30. package/dist/ObjectionFactory.d.mts +2 -2
  31. package/dist/ObjectionFactory.mjs +2 -2
  32. package/dist/benchmark.cjs +49 -0
  33. package/dist/benchmark.cjs.map +1 -0
  34. package/dist/benchmark.d.cts +35 -0
  35. package/dist/benchmark.d.mts +35 -0
  36. package/dist/benchmark.mjs +45 -0
  37. package/dist/benchmark.mjs.map +1 -0
  38. package/dist/better-auth.d.cts +2 -2
  39. package/dist/{directory-BUcnztHI.d.cts → directory-BPf1LgNX.d.mts} +3 -3
  40. package/dist/{directory-BXavAeJZ.d.mts → directory-DlkPEzL4.d.cts} +1 -1
  41. package/dist/{faker-Dg3trU4a.d.cts → faker-Cg76aFNO.d.cts} +3 -3
  42. package/dist/faker.d.cts +1 -1
  43. package/dist/kysely.cjs +2 -2
  44. package/dist/kysely.cjs.map +1 -1
  45. package/dist/kysely.d.cts +4 -4
  46. package/dist/kysely.d.mts +3 -3
  47. package/dist/kysely.mjs +2 -2
  48. package/dist/kysely.mjs.map +1 -1
  49. package/dist/objection.cjs +2 -2
  50. package/dist/objection.cjs.map +1 -1
  51. package/dist/objection.d.cts +4 -4
  52. package/dist/objection.d.mts +3 -3
  53. package/dist/objection.mjs +2 -2
  54. package/dist/objection.mjs.map +1 -1
  55. package/dist/os/directory.d.cts +1 -1
  56. package/dist/os/directory.d.mts +1 -1
  57. package/dist/os/index.d.cts +1 -1
  58. package/dist/os/index.d.mts +1 -1
  59. package/package.json +6 -1
  60. package/src/Factory.ts +25 -11
  61. package/src/KyselyFactory.ts +21 -4
  62. package/src/ObjectionFactory.ts +21 -4
  63. package/src/__tests__/Factory.spec.ts +16 -10
  64. package/src/__tests__/KyselyFactory.spec.ts +12 -6
  65. package/src/__tests__/ObjectionFactory.spec.ts +57 -48
  66. package/src/__tests__/integration.spec.ts +16 -8
  67. package/src/benchmark.ts +48 -0
  68. package/src/kysely.ts +1 -0
  69. package/src/objection.ts +1 -0
  70. package/dist/Factory-WMhTNZ9S.cjs.map +0 -1
  71. package/dist/Factory-z2m01hMj.mjs.map +0 -1
  72. package/dist/KyselyFactory-CXY5gJk2.mjs.map +0 -1
  73. package/dist/KyselyFactory-DaaCykWP.cjs.map +0 -1
  74. package/dist/ObjectionFactory-Eb04AOnv.cjs.map +0 -1
  75. package/dist/ObjectionFactory-zf2fLKrL.mjs.map +0 -1
@@ -216,20 +216,22 @@ describe('ObjectionFactory', () => {
216
216
 
217
217
  const builders = { user: userBuilder };
218
218
 
219
- const createAdminSeed = async (attrs: any, factory: any, db: Knex) => {
220
- return await factory.insert('user', {
221
- name: attrs.name || 'Admin User',
222
- });
223
- };
224
-
225
219
  const seeds = {
226
- createAdmin: createAdminSeed,
220
+ createAdmin: ObjectionFactory.createSeed(
221
+ async ({
222
+ attrs,
223
+ factory,
224
+ }: { attrs: { name?: string }; factory: any; db: Knex }) => {
225
+ return await factory.insert('user', {
226
+ name: attrs.name || 'Admin User',
227
+ });
228
+ },
229
+ ),
227
230
  };
228
231
 
229
232
  const factory = new ObjectionFactory(builders, seeds, trx);
230
233
 
231
- const attrs = { name: 'Super Admin' };
232
- const result = await factory.seed('createAdmin', attrs);
234
+ const result = await factory.seed('createAdmin', { name: 'Super Admin' });
233
235
 
234
236
  expect(result).toBeInstanceOf(User);
235
237
  expect(result.name).toBe('Super Admin');
@@ -247,15 +249,15 @@ describe('ObjectionFactory', () => {
247
249
 
248
250
  const builders = { user: userBuilder };
249
251
 
250
- const createAdminSeed = async (attrs: any, factory: any, db: Knex) => {
251
- return await factory.insert('user', {
252
- name: 'Default Admin',
253
- role: 'admin',
254
- });
255
- };
256
-
257
252
  const seeds = {
258
- createAdmin: createAdminSeed,
253
+ createAdmin: ObjectionFactory.createSeed(
254
+ async ({ factory }: { attrs: any; factory: any; db: Knex }) => {
255
+ return await factory.insert('user', {
256
+ name: 'Default Admin',
257
+ role: 'admin',
258
+ });
259
+ },
260
+ ),
259
261
  };
260
262
 
261
263
  const factory = new ObjectionFactory(builders, seeds, trx);
@@ -283,25 +285,28 @@ describe('ObjectionFactory', () => {
283
285
 
284
286
  const builders = { user: userBuilder };
285
287
 
286
- const complexSeed = async (
287
- attrs: any,
288
- passedFactory: any,
289
- passedDb: Knex,
290
- ) => {
291
- // Verify that factory and db are passed correctly
292
- expect(passedFactory).toBe(factory);
293
- expect(passedDb).toBe(trx);
294
-
295
- return await passedFactory.insert('user', {
296
- name: `Complex ${attrs.data}`,
297
- });
298
- };
288
+ let factoryRef: any;
299
289
 
300
290
  const seeds = {
301
- complexSeed,
291
+ complexSeed: ObjectionFactory.createSeed(
292
+ async ({
293
+ attrs,
294
+ factory: passedFactory,
295
+ db: passedDb,
296
+ }: { attrs: { data: string }; factory: any; db: Knex }) => {
297
+ // Verify that factory and db are passed correctly
298
+ expect(passedFactory).toBe(factoryRef);
299
+ expect(passedDb).toBe(trx);
300
+
301
+ return await passedFactory.insert('user', {
302
+ name: `Complex ${attrs.data}`,
303
+ });
304
+ },
305
+ ),
302
306
  };
303
307
 
304
308
  const factory = new ObjectionFactory(builders, seeds, trx);
309
+ factoryRef = factory;
305
310
 
306
311
  const result = await factory.seed('complexSeed', { data: 'test' });
307
312
 
@@ -310,7 +315,7 @@ describe('ObjectionFactory', () => {
310
315
  });
311
316
 
312
317
  it('should return the seed function unchanged', () => {
313
- const seedFn = async (attrs: any, factory: any, db: any) => {
318
+ const seedFn = async ({ attrs }: { attrs: any; factory: any; db: any }) => {
314
319
  return { id: 1, name: 'test' };
315
320
  };
316
321
 
@@ -481,12 +486,12 @@ describe('ObjectionFactory', () => {
481
486
  });
482
487
 
483
488
  it('should handle seed function errors gracefully', async ({ trx }) => {
484
- const failingSeed = async (attrs: any, factory: any, db: Knex) => {
485
- throw new Error('Seed failed');
486
- };
487
-
488
489
  const seeds = {
489
- failingSeed,
490
+ failingSeed: ObjectionFactory.createSeed(
491
+ async ({}: { attrs: any; factory: any; db: Knex }) => {
492
+ throw new Error('Seed failed');
493
+ },
494
+ ),
490
495
  };
491
496
 
492
497
  const factory = new ObjectionFactory({}, seeds, trx);
@@ -508,18 +513,22 @@ describe('ObjectionFactory', () => {
508
513
  });
509
514
  };
510
515
 
511
- const adminSeed = async (
512
- attrs: { isSuper?: boolean },
513
- factory: any,
514
- db: Knex,
515
- ) => {
516
- return factory.insert('user', {
517
- name: 'Admin',
518
- });
519
- };
520
-
521
516
  const builders = { user: userBuilder };
522
- const seeds = { admin: adminSeed };
517
+ const seeds = {
518
+ admin: ObjectionFactory.createSeed(
519
+ async ({
520
+ factory,
521
+ }: {
522
+ attrs: { isSuper?: boolean };
523
+ factory: any;
524
+ db: Knex;
525
+ }) => {
526
+ return factory.insert('user', {
527
+ name: 'Admin',
528
+ });
529
+ },
530
+ ),
531
+ };
523
532
 
524
533
  // This should compile without type errors
525
534
  const factory = new ObjectionFactory(builders, seeds, trx);
@@ -192,10 +192,14 @@ describe('Testkit Integration Tests', () => {
192
192
  // Create complex seeds
193
193
  const seeds = {
194
194
  blogWithAdminAndPosts: KyselyFactory.createSeed(
195
- async (
196
- attrs: { postCount?: number },
197
- factory: KyselyFactory<TestDatabase, typeof builders, {}>,
198
- ) => {
195
+ async ({
196
+ attrs,
197
+ factory,
198
+ }: {
199
+ attrs: { postCount?: number };
200
+ factory: KyselyFactory<TestDatabase, typeof builders, {}>;
201
+ db: any;
202
+ }) => {
199
203
  // Create admin user
200
204
  const admin = await factory.insert('user', {
201
205
  name: 'Blog Admin',
@@ -229,10 +233,14 @@ describe('Testkit Integration Tests', () => {
229
233
  ),
230
234
 
231
235
  usersWithPosts: KyselyFactory.createSeed(
232
- async (
233
- attrs: { userCount?: number; postsPerUser?: number },
234
- factory: KyselyFactory<TestDatabase, typeof builders, {}>,
235
- ) => {
236
+ async ({
237
+ attrs,
238
+ factory,
239
+ }: {
240
+ attrs: { userCount?: number; postsPerUser?: number };
241
+ factory: KyselyFactory<TestDatabase, typeof builders, {}>;
242
+ db: any;
243
+ }) => {
236
244
  const userCount = attrs.userCount || 2;
237
245
  const postsPerUser = attrs.postsPerUser || 2;
238
246
 
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Generates an array of test records for benchmark data sets.
3
+ *
4
+ * @param count - Number of records to generate
5
+ * @returns Array of test data objects
6
+ */
7
+ export function generateTestData(
8
+ count: number,
9
+ ): Array<{ id: string; name: string; value: number }> {
10
+ return Array.from({ length: count }, (_, i) => ({
11
+ id: `id-${i}`,
12
+ name: `Item ${i}`,
13
+ value: Math.random() * 1000,
14
+ }));
15
+ }
16
+
17
+ /**
18
+ * Generates unique keys for cache benchmarks to avoid collisions.
19
+ *
20
+ * @param prefix - Key prefix
21
+ * @param count - Number of keys to generate
22
+ * @returns Array of unique cache keys
23
+ */
24
+ export function generateCacheKeys(prefix: string, count: number): string[] {
25
+ return Array.from({ length: count }, (_, i) => `${prefix}:${i}`);
26
+ }
27
+
28
+ /**
29
+ * Generates IP addresses for rate limit benchmarks.
30
+ *
31
+ * @param count - Number of IPs to generate
32
+ * @param subnet - Subnet prefix (default: '192.168.1')
33
+ * @returns Array of IP addresses
34
+ */
35
+ export function generateIpAddresses(
36
+ count: number,
37
+ subnet: string = '192.168.1',
38
+ ): string[] {
39
+ return Array.from({ length: count }, (_, i) => `${subnet}.${i % 256}`);
40
+ }
41
+
42
+ /**
43
+ * Creates a random IP address for rate limit benchmarks.
44
+ */
45
+ export function randomIpAddress(): string {
46
+ const octet = () => Math.floor(Math.random() * 256);
47
+ return `${octet()}.${octet()}.${octet()}.${octet()}`;
48
+ }
package/src/kysely.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  */
15
15
 
16
16
  export { KyselyFactory } from './KyselyFactory';
17
+ export type { ExtractSeedAttrs, FactorySeed } from './Factory';
17
18
  export { PostgresKyselyMigrator } from './PostgresKyselyMigrator';
18
19
  export { VitestKyselyTransactionIsolator } from './VitestKyselyTransactionIsolator';
19
20
  export { IsolationLevel } from './VitestTransactionIsolator';
package/src/objection.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  */
16
16
 
17
17
  export { ObjectionFactory } from './ObjectionFactory';
18
+ export type { ExtractSeedAttrs, FactorySeed } from './Factory';
18
19
  export { VitestObjectionTransactionIsolator } from './VitestObjectionTransactionIsolator';
19
20
  export { IsolationLevel } from './VitestTransactionIsolator';
20
21
  export { PostgresObjectionMigrator } from './PostgresObjectionMigrator';
@@ -1 +0,0 @@
1
- {"version":3,"file":"Factory-WMhTNZ9S.cjs","names":["seedFn: Seed"],"sources":["../src/Factory.ts"],"sourcesContent":["import type { FakerFactory } from './faker';\n\n/**\n * Abstract base class for database factories used in testing.\n * Provides a standardized interface for creating test data using builder and seed patterns.\n *\n * @template Builders - Record of builder functions for creating individual entities\n * @template Seeds - Record of seed functions for creating complex test scenarios\n *\n * @example\n * ```typescript\n * // Define builders for creating individual records\n * const builders = {\n * user: (attrs) => ({ name: 'Test User', email: 'test@example.com', ...attrs }),\n * post: (attrs) => ({ title: 'Test Post', content: 'Content', ...attrs })\n * };\n *\n * // Define seeds for complex scenarios\n * const seeds = {\n * userWithPosts: async (attrs, factory) => {\n * const user = await factory.insert('user', attrs);\n * await factory.insertMany(3, 'post', { userId: user.id });\n * return user;\n * }\n * };\n * ```\n */\nexport abstract class Factory<\n Builders extends Record<string, any>,\n Seeds extends Record<string, any>,\n> {\n /**\n * Creates a typed seed function with proper type inference.\n * This is a utility method to help with TypeScript type checking when defining seeds.\n *\n * @template Seed - The seed function type\n * @param seedFn - The seed function to wrap\n * @returns The same seed function with proper typing\n *\n * @example\n * ```typescript\n * const userWithPostsSeed = Factory.createSeed(async (attrs, factory, db) => {\n * const user = await factory.insert('user', attrs);\n * return user;\n * });\n * ```\n */\n static createSeed<Seed extends FactorySeed>(seedFn: Seed): Seed {\n return seedFn;\n }\n /**\n * Inserts an object into the database using a builder function.\n *\n * @param builderName - The name of the builder to use\n * @param attrs - The attributes to insert\n */\n abstract insert<K extends keyof Builders>(\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>>;\n\n /**\n * Inserts multiple objects into the database\n *\n * @param count - Number of objects to insert\n * @param builderName - The name of the builder to use\n * @param attrs - The attributes to insert\n */\n abstract insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?:\n | Parameters<Builders[K]>[0]\n | ((\n idx: number,\n faker: FakerFactory,\n ) => Promise<Parameters<Builders[K]>[0]>),\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n\n /**\n * Seeds the database using a seed function.\n *\n * @param seedName - The name of the seed to use\n * @returns The result of the seed function\n * @param attrs - The attributes to pass to the seed function\n */\n abstract seed<K extends keyof Seeds>(\n seedName: K,\n attrs?: Parameters<Seeds[K]>[0],\n ): ReturnType<Seeds[K]>;\n}\n\n/**\n * Type definition for a factory builder function that can work with different database types.\n * Builders are responsible for creating individual database records with default values and relationships.\n *\n * @template Attrs - The attributes/input type for the builder\n * @template Factory - The factory instance type\n * @template Result - The type of object returned by the builder\n * @template DB - The database connection type (Kysely, Knex, etc.)\n *\n * @param attrs - Partial attributes to override defaults\n * @param factory - The factory instance for creating related records\n * @param db - The database connection\n * @returns The created record or a promise resolving to it\n *\n * @example\n * ```typescript\n * const userBuilder: MixedFactoryBuilder<UserAttrs, Factory, User, Kysely<DB>> =\n * async (attrs, factory, db) => {\n * return {\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * ...attrs\n * };\n * };\n * ```\n */\nexport type MixedFactoryBuilder<\n Attrs = any,\n Factory = any,\n Result = any,\n DB = any,\n> = (attrs: Attrs, factory: Factory, db: DB) => Result | Promise<Result>;\n\n/**\n * Type definition for a factory seed function used to create complex test scenarios.\n * Seeds typically create multiple related records to set up a complete test environment.\n *\n * @template Attrs - The attributes/input type for the seed\n * @template Factory - The factory instance type\n * @template Result - The type of object returned by the seed\n * @template DB - The database connection type (Kysely, Knex, etc.)\n *\n * @param attrs - Configuration attributes for the seed\n * @param factory - The factory instance for creating records\n * @param db - The database connection\n * @returns A promise resolving to the seed result\n *\n * @example\n * ```typescript\n * const userWithPostsSeed: FactorySeed<{ postCount?: number }, Factory, User, DB> =\n * async (attrs, factory, db) => {\n * const user = await factory.insert('user', attrs);\n * const postCount = attrs.postCount || 3;\n *\n * for (let i = 0; i < postCount; i++) {\n * await factory.insert('post', { userId: user.id });\n * }\n *\n * return user;\n * };\n * ```\n */\nexport type FactorySeed<Attrs = any, Factory = any, Result = any, DB = any> = (\n attrs: Attrs,\n factory: Factory,\n db: DB,\n) => Promise<Result>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAsB,UAAtB,MAGE;;;;;;;;;;;;;;;;;CAiBA,OAAO,WAAqCA,QAAoB;AAC9D,SAAO;CACR;AAyCF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"Factory-z2m01hMj.mjs","names":["seedFn: Seed"],"sources":["../src/Factory.ts"],"sourcesContent":["import type { FakerFactory } from './faker';\n\n/**\n * Abstract base class for database factories used in testing.\n * Provides a standardized interface for creating test data using builder and seed patterns.\n *\n * @template Builders - Record of builder functions for creating individual entities\n * @template Seeds - Record of seed functions for creating complex test scenarios\n *\n * @example\n * ```typescript\n * // Define builders for creating individual records\n * const builders = {\n * user: (attrs) => ({ name: 'Test User', email: 'test@example.com', ...attrs }),\n * post: (attrs) => ({ title: 'Test Post', content: 'Content', ...attrs })\n * };\n *\n * // Define seeds for complex scenarios\n * const seeds = {\n * userWithPosts: async (attrs, factory) => {\n * const user = await factory.insert('user', attrs);\n * await factory.insertMany(3, 'post', { userId: user.id });\n * return user;\n * }\n * };\n * ```\n */\nexport abstract class Factory<\n Builders extends Record<string, any>,\n Seeds extends Record<string, any>,\n> {\n /**\n * Creates a typed seed function with proper type inference.\n * This is a utility method to help with TypeScript type checking when defining seeds.\n *\n * @template Seed - The seed function type\n * @param seedFn - The seed function to wrap\n * @returns The same seed function with proper typing\n *\n * @example\n * ```typescript\n * const userWithPostsSeed = Factory.createSeed(async (attrs, factory, db) => {\n * const user = await factory.insert('user', attrs);\n * return user;\n * });\n * ```\n */\n static createSeed<Seed extends FactorySeed>(seedFn: Seed): Seed {\n return seedFn;\n }\n /**\n * Inserts an object into the database using a builder function.\n *\n * @param builderName - The name of the builder to use\n * @param attrs - The attributes to insert\n */\n abstract insert<K extends keyof Builders>(\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>>;\n\n /**\n * Inserts multiple objects into the database\n *\n * @param count - Number of objects to insert\n * @param builderName - The name of the builder to use\n * @param attrs - The attributes to insert\n */\n abstract insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?:\n | Parameters<Builders[K]>[0]\n | ((\n idx: number,\n faker: FakerFactory,\n ) => Promise<Parameters<Builders[K]>[0]>),\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n\n /**\n * Seeds the database using a seed function.\n *\n * @param seedName - The name of the seed to use\n * @returns The result of the seed function\n * @param attrs - The attributes to pass to the seed function\n */\n abstract seed<K extends keyof Seeds>(\n seedName: K,\n attrs?: Parameters<Seeds[K]>[0],\n ): ReturnType<Seeds[K]>;\n}\n\n/**\n * Type definition for a factory builder function that can work with different database types.\n * Builders are responsible for creating individual database records with default values and relationships.\n *\n * @template Attrs - The attributes/input type for the builder\n * @template Factory - The factory instance type\n * @template Result - The type of object returned by the builder\n * @template DB - The database connection type (Kysely, Knex, etc.)\n *\n * @param attrs - Partial attributes to override defaults\n * @param factory - The factory instance for creating related records\n * @param db - The database connection\n * @returns The created record or a promise resolving to it\n *\n * @example\n * ```typescript\n * const userBuilder: MixedFactoryBuilder<UserAttrs, Factory, User, Kysely<DB>> =\n * async (attrs, factory, db) => {\n * return {\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * ...attrs\n * };\n * };\n * ```\n */\nexport type MixedFactoryBuilder<\n Attrs = any,\n Factory = any,\n Result = any,\n DB = any,\n> = (attrs: Attrs, factory: Factory, db: DB) => Result | Promise<Result>;\n\n/**\n * Type definition for a factory seed function used to create complex test scenarios.\n * Seeds typically create multiple related records to set up a complete test environment.\n *\n * @template Attrs - The attributes/input type for the seed\n * @template Factory - The factory instance type\n * @template Result - The type of object returned by the seed\n * @template DB - The database connection type (Kysely, Knex, etc.)\n *\n * @param attrs - Configuration attributes for the seed\n * @param factory - The factory instance for creating records\n * @param db - The database connection\n * @returns A promise resolving to the seed result\n *\n * @example\n * ```typescript\n * const userWithPostsSeed: FactorySeed<{ postCount?: number }, Factory, User, DB> =\n * async (attrs, factory, db) => {\n * const user = await factory.insert('user', attrs);\n * const postCount = attrs.postCount || 3;\n *\n * for (let i = 0; i < postCount; i++) {\n * await factory.insert('post', { userId: user.id });\n * }\n *\n * return user;\n * };\n * ```\n */\nexport type FactorySeed<Attrs = any, Factory = any, Result = any, DB = any> = (\n attrs: Attrs,\n factory: Factory,\n db: DB,\n) => Promise<Result>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAsB,UAAtB,MAGE;;;;;;;;;;;;;;;;;CAiBA,OAAO,WAAqCA,QAAoB;AAC9D,SAAO;CACR;AAyCF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"KyselyFactory-CXY5gJk2.mjs","names":["seedFn: Seed","builders: Builders","seeds: Seeds","db: Kysely<DB> | ControlledTransaction<DB, []>","table: TableName","defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Kysely<DB>;\n faker: FakerFactory;\n }) =>\n | Partial<Insertable<DB[TableName]>>\n | Promise<Partial<Insertable<DB[TableName]>>>","autoInsert?: boolean","attrs: Attrs","factory: Factory","db: Kysely<DB>","fakerInstance: FakerFactory","data: Partial<Insertable<DB[TableName]>>","builderName: K","attrs?: Parameters<Builders[K]>[0]","count: number","attrs?: any","promises: Promise<any>[]","seedName: K","attrs?: Parameters<Seeds[K]>[0]"],"sources":["../src/KyselyFactory.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n Insertable,\n Kysely,\n Selectable,\n} from 'kysely';\nimport { Factory, type FactorySeed } from './Factory.ts';\nimport { type FakerFactory, faker } from './faker.ts';\n\n/**\n * Factory implementation for Kysely ORM, providing test data creation utilities.\n * Extends the base Factory class with Kysely-specific database operations.\n *\n * @template DB - The database schema type\n * @template Builders - Record of builder functions for creating entities\n * @template Seeds - Record of seed functions for complex test scenarios\n *\n * @example\n * ```typescript\n * // Define your database schema\n * interface Database {\n * users: UsersTable;\n * posts: PostsTable;\n * }\n *\n * // Create builders\n * const builders = {\n * user: KyselyFactory.createBuilder<Database, 'users'>('users', ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * ...attrs\n * })),\n * post: KyselyFactory.createBuilder<Database, 'posts'>('posts', ({ attrs }) => ({\n * title: 'Test Post',\n * content: 'Test content',\n * ...attrs\n * }))\n * };\n *\n * // Create factory instance\n * const factory = new KyselyFactory(builders, seeds, db);\n *\n * // Use in tests\n * const user = await factory.insert('user', { name: 'John Doe' });\n * ```\n */\nexport class KyselyFactory<\n DB,\n Builders extends Record<string, any>,\n Seeds extends Record<string, any>,\n> extends Factory<Builders, Seeds> {\n /**\n * Creates a typed seed function with proper type inference.\n * Inherits from the base Factory class implementation.\n *\n * @template Seed - The seed function type\n * @param seedFn - The seed function to wrap\n * @returns The same seed function with proper typing\n */\n static createSeed<Seed extends FactorySeed>(seedFn: Seed): Seed {\n return Factory.createSeed(seedFn);\n }\n\n /**\n * Creates a new KyselyFactory instance.\n *\n * @param builders - Record of builder functions for creating individual entities\n * @param seeds - Record of seed functions for creating complex test scenarios\n * @param db - Kysely database instance or controlled transaction\n */\n constructor(\n private builders: Builders,\n private seeds: Seeds,\n private db: Kysely<DB> | ControlledTransaction<DB, []>,\n ) {\n super();\n }\n\n /**\n * Creates a typed builder function for a specific database table.\n * This is a utility method that helps create builders with proper type inference for Kysely.\n *\n * @template DB - The database schema type\n * @template TableName - The name of the table (must be a key of DB)\n * @template Attrs - The attributes type for the builder (defaults to Partial<Insertable>)\n * @template Factory - The factory instance type\n * @template Result - The result type (defaults to Selectable of the table)\n *\n * @param table - The name of the database table\n * @param defaults - Optional function to provide default values (receives destructured context)\n * @param autoInsert - Whether to automatically insert the record (default: true)\n * @returns A builder function that creates and optionally inserts records\n *\n * @example\n * ```typescript\n * // Create a simple builder with defaults - destructure only what you need\n * const userBuilder = KyselyFactory.createBuilder<DB, 'users'>('users',\n * ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * createdAt: new Date(),\n * ...attrs\n * })\n * );\n *\n * // Only need faker? Just destructure that\n * const leaveTypeBuilder = KyselyFactory.createBuilder<DB, 'leaveTypes'>('leaveTypes',\n * ({ faker }) => ({\n * name: faker.helpers.arrayElement(['Annual', 'Sick', 'Maternity']),\n * code: faker.string.alpha({ length: 3, casing: 'upper' }),\n * })\n * );\n *\n * // Create a builder that doesn't auto-insert (useful for nested inserts)\n * const addressBuilder = KyselyFactory.createBuilder<DB, 'addresses'>('addresses',\n * ({ attrs }) => ({\n * street: '123 Main St',\n * city: 'Anytown',\n * ...attrs\n * }),\n * false // Don't auto-insert\n * );\n * ```\n */\n static createBuilder<\n DB,\n TableName extends keyof DB & string,\n Attrs extends Partial<Insertable<DB[TableName]>> = Partial<\n Insertable<DB[TableName]>\n >,\n Factory = any,\n Result = Selectable<DB[TableName]>,\n >(\n table: TableName,\n defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Kysely<DB>;\n faker: FakerFactory;\n }) =>\n | Partial<Insertable<DB[TableName]>>\n | Promise<Partial<Insertable<DB[TableName]>>>,\n autoInsert?: boolean,\n ): (\n attrs: Attrs,\n factory: Factory,\n db: Kysely<DB>,\n faker: FakerFactory,\n ) => Promise<Result> {\n return async (\n attrs: Attrs,\n factory: Factory,\n db: Kysely<DB>,\n fakerInstance: FakerFactory,\n ) => {\n // Start with attributes\n let data: Partial<Insertable<DB[TableName]>> = { ...attrs };\n\n // Apply defaults\n if (defaults) {\n const defaultValues = await defaults({\n attrs,\n factory,\n db,\n faker: fakerInstance,\n });\n data = { ...defaultValues, ...data };\n }\n\n // Handle insertion based on autoInsert flag\n if (autoInsert !== false) {\n // Auto insert is enabled by default\n const result = await db\n .insertInto(table)\n .values(data as Insertable<DB[TableName]>)\n .returningAll()\n .executeTakeFirst();\n\n if (!result) {\n throw new Error(`Failed to insert into ${table}`);\n }\n\n return result as Result;\n } else {\n // Return object for factory to handle insertion\n return { table, data } as any;\n }\n };\n }\n\n /**\n * Inserts a single record into the database using the specified builder.\n * The builder function is responsible for generating the record data with defaults\n * and the factory handles the actual database insertion.\n *\n * @template K - The builder name (must be a key of Builders)\n * @param builderName - The name of the builder to use\n * @param attrs - Optional attributes to override builder defaults\n * @returns A promise resolving to the inserted record\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert with defaults\n * const user = await factory.insert('user');\n *\n * // Insert with overrides\n * const adminUser = await factory.insert('user', {\n * email: 'admin@example.com',\n * role: 'admin'\n * });\n *\n * // Use the inserted record\n * const post = await factory.insert('post', {\n * userId: user.id,\n * title: 'My First Post'\n * });\n * ```\n */\n async insert<K extends keyof Builders>(\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Factory \"${\n builderName as string\n }\" does not exist. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const result = await this.builders[builderName](\n attrs || {},\n this,\n this.db,\n faker,\n );\n\n // For Kysely, we expect the builder to return an object with table and data properties\n // or to handle the insertion itself and return the inserted record\n if (\n result &&\n typeof result === 'object' &&\n 'table' in result &&\n 'data' in result\n ) {\n // If the builder returns {table: string, data: object}, we insert it\n const inserted = await this.db\n .insertInto(result.table)\n .values(result.data)\n .returningAll()\n .executeTakeFirst();\n\n return inserted as any;\n }\n\n // Otherwise, assume the builder handled the insertion itself\n return result;\n }\n\n /**\n * Inserts multiple records into the database using the specified builder.\n * Supports both static attributes and dynamic attribute generation via a function.\n *\n * @template K - The builder name (must be a key of Builders)\n * @param count - The number of records to insert\n * @param builderName - The name of the builder to use\n * @param attrs - Static attributes or a function that generates attributes for each record\n * @returns A promise resolving to an array of inserted records\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert multiple with same attributes\n * const users = await factory.insertMany(5, 'user', { role: 'member' });\n *\n * // Insert multiple with dynamic attributes\n * const posts = await factory.insertMany(10, 'post', (idx, faker) => ({\n * title: `Post ${idx + 1}`,\n * content: faker.lorem.paragraph(),\n * publishedAt: faker.date.past()\n * }));\n *\n * // Create users with sequential emails\n * const admins = await factory.insertMany(3, 'user', (idx) => ({\n * email: `admin${idx + 1}@example.com`,\n * role: 'admin'\n * }));\n * ```\n */\n // Method overloads for better type inference\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs: (\n idx: number,\n faker: FakerFactory,\n ) => Parameters<Builders[K]>[0] | Promise<Parameters<Builders[K]>[0]>,\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: any,\n ): Promise<Awaited<ReturnType<Builders[K]>>[]> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Builder \"${\n builderName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const promises: Promise<any>[] = [];\n\n for (let i = 0; i < count; i++) {\n const newAttrs =\n typeof attrs === 'function' ? await attrs(i, faker) : attrs;\n promises.push(this.insert(builderName, newAttrs));\n }\n\n return Promise.all(promises);\n }\n\n /**\n * Executes a seed function to create complex test scenarios with multiple related records.\n * Seeds are useful for setting up complete test environments with realistic data relationships.\n *\n * @template K - The seed name (must be a key of Seeds)\n * @param seedName - The name of the seed to execute\n * @param attrs - Optional configuration attributes for the seed\n * @returns The result of the seed function (typically the primary record created)\n * @throws Error if the specified seed doesn't exist\n *\n * @example\n * ```typescript\n * // Execute a simple seed\n * const user = await factory.seed('userWithProfile');\n *\n * // Execute a seed with configuration\n * const author = await factory.seed('authorWithBooks', {\n * bookCount: 5,\n * includeReviews: true\n * });\n *\n * // Use seed result in tests\n * const company = await factory.seed('companyWithDepartments', {\n * departmentCount: 3,\n * employeesPerDepartment: 10\n * });\n * expect(company.departments).toHaveLength(3);\n * ```\n */\n seed<K extends keyof Seeds>(\n seedName: K,\n attrs?: Parameters<Seeds[K]>[0],\n ): ReturnType<Seeds[K]> {\n if (!(seedName in this.seeds)) {\n throw new Error(\n `Seed \"${\n seedName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n return this.seeds[seedName](attrs || {}, this, this.db);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAa,gBAAb,cAIU,QAAyB;;;;;;;;;CASjC,OAAO,WAAqCA,QAAoB;AAC9D,SAAO,QAAQ,WAAW,OAAO;CAClC;;;;;;;;CASD,YACUC,UACAC,OACAC,IACR;AACA,SAAO;EAJC;EACA;EACA;CAGT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDD,OAAO,cASLC,OACAC,UAQAC,YAMmB;AACnB,SAAO,OACLC,OACAC,SACAC,IACAC,kBACG;GAEH,IAAIC,OAA2C,EAAE,GAAG,MAAO;AAG3D,OAAI,UAAU;IACZ,MAAM,gBAAgB,MAAM,SAAS;KACnC;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"version":3,"file":"KyselyFactory-DaaCykWP.cjs","names":["Factory","seedFn: Seed","builders: Builders","seeds: Seeds","db: Kysely<DB> | ControlledTransaction<DB, []>","table: TableName","defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Kysely<DB>;\n faker: FakerFactory;\n }) =>\n | Partial<Insertable<DB[TableName]>>\n | Promise<Partial<Insertable<DB[TableName]>>>","autoInsert?: boolean","attrs: Attrs","factory: Factory","db: Kysely<DB>","fakerInstance: FakerFactory","data: Partial<Insertable<DB[TableName]>>","builderName: K","attrs?: Parameters<Builders[K]>[0]","faker","count: number","attrs?: any","promises: Promise<any>[]","seedName: K","attrs?: Parameters<Seeds[K]>[0]"],"sources":["../src/KyselyFactory.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n Insertable,\n Kysely,\n Selectable,\n} from 'kysely';\nimport { Factory, type FactorySeed } from './Factory.ts';\nimport { type FakerFactory, faker } from './faker.ts';\n\n/**\n * Factory implementation for Kysely ORM, providing test data creation utilities.\n * Extends the base Factory class with Kysely-specific database operations.\n *\n * @template DB - The database schema type\n * @template Builders - Record of builder functions for creating entities\n * @template Seeds - Record of seed functions for complex test scenarios\n *\n * @example\n * ```typescript\n * // Define your database schema\n * interface Database {\n * users: UsersTable;\n * posts: PostsTable;\n * }\n *\n * // Create builders\n * const builders = {\n * user: KyselyFactory.createBuilder<Database, 'users'>('users', ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * ...attrs\n * })),\n * post: KyselyFactory.createBuilder<Database, 'posts'>('posts', ({ attrs }) => ({\n * title: 'Test Post',\n * content: 'Test content',\n * ...attrs\n * }))\n * };\n *\n * // Create factory instance\n * const factory = new KyselyFactory(builders, seeds, db);\n *\n * // Use in tests\n * const user = await factory.insert('user', { name: 'John Doe' });\n * ```\n */\nexport class KyselyFactory<\n DB,\n Builders extends Record<string, any>,\n Seeds extends Record<string, any>,\n> extends Factory<Builders, Seeds> {\n /**\n * Creates a typed seed function with proper type inference.\n * Inherits from the base Factory class implementation.\n *\n * @template Seed - The seed function type\n * @param seedFn - The seed function to wrap\n * @returns The same seed function with proper typing\n */\n static createSeed<Seed extends FactorySeed>(seedFn: Seed): Seed {\n return Factory.createSeed(seedFn);\n }\n\n /**\n * Creates a new KyselyFactory instance.\n *\n * @param builders - Record of builder functions for creating individual entities\n * @param seeds - Record of seed functions for creating complex test scenarios\n * @param db - Kysely database instance or controlled transaction\n */\n constructor(\n private builders: Builders,\n private seeds: Seeds,\n private db: Kysely<DB> | ControlledTransaction<DB, []>,\n ) {\n super();\n }\n\n /**\n * Creates a typed builder function for a specific database table.\n * This is a utility method that helps create builders with proper type inference for Kysely.\n *\n * @template DB - The database schema type\n * @template TableName - The name of the table (must be a key of DB)\n * @template Attrs - The attributes type for the builder (defaults to Partial<Insertable>)\n * @template Factory - The factory instance type\n * @template Result - The result type (defaults to Selectable of the table)\n *\n * @param table - The name of the database table\n * @param defaults - Optional function to provide default values (receives destructured context)\n * @param autoInsert - Whether to automatically insert the record (default: true)\n * @returns A builder function that creates and optionally inserts records\n *\n * @example\n * ```typescript\n * // Create a simple builder with defaults - destructure only what you need\n * const userBuilder = KyselyFactory.createBuilder<DB, 'users'>('users',\n * ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * createdAt: new Date(),\n * ...attrs\n * })\n * );\n *\n * // Only need faker? Just destructure that\n * const leaveTypeBuilder = KyselyFactory.createBuilder<DB, 'leaveTypes'>('leaveTypes',\n * ({ faker }) => ({\n * name: faker.helpers.arrayElement(['Annual', 'Sick', 'Maternity']),\n * code: faker.string.alpha({ length: 3, casing: 'upper' }),\n * })\n * );\n *\n * // Create a builder that doesn't auto-insert (useful for nested inserts)\n * const addressBuilder = KyselyFactory.createBuilder<DB, 'addresses'>('addresses',\n * ({ attrs }) => ({\n * street: '123 Main St',\n * city: 'Anytown',\n * ...attrs\n * }),\n * false // Don't auto-insert\n * );\n * ```\n */\n static createBuilder<\n DB,\n TableName extends keyof DB & string,\n Attrs extends Partial<Insertable<DB[TableName]>> = Partial<\n Insertable<DB[TableName]>\n >,\n Factory = any,\n Result = Selectable<DB[TableName]>,\n >(\n table: TableName,\n defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Kysely<DB>;\n faker: FakerFactory;\n }) =>\n | Partial<Insertable<DB[TableName]>>\n | Promise<Partial<Insertable<DB[TableName]>>>,\n autoInsert?: boolean,\n ): (\n attrs: Attrs,\n factory: Factory,\n db: Kysely<DB>,\n faker: FakerFactory,\n ) => Promise<Result> {\n return async (\n attrs: Attrs,\n factory: Factory,\n db: Kysely<DB>,\n fakerInstance: FakerFactory,\n ) => {\n // Start with attributes\n let data: Partial<Insertable<DB[TableName]>> = { ...attrs };\n\n // Apply defaults\n if (defaults) {\n const defaultValues = await defaults({\n attrs,\n factory,\n db,\n faker: fakerInstance,\n });\n data = { ...defaultValues, ...data };\n }\n\n // Handle insertion based on autoInsert flag\n if (autoInsert !== false) {\n // Auto insert is enabled by default\n const result = await db\n .insertInto(table)\n .values(data as Insertable<DB[TableName]>)\n .returningAll()\n .executeTakeFirst();\n\n if (!result) {\n throw new Error(`Failed to insert into ${table}`);\n }\n\n return result as Result;\n } else {\n // Return object for factory to handle insertion\n return { table, data } as any;\n }\n };\n }\n\n /**\n * Inserts a single record into the database using the specified builder.\n * The builder function is responsible for generating the record data with defaults\n * and the factory handles the actual database insertion.\n *\n * @template K - The builder name (must be a key of Builders)\n * @param builderName - The name of the builder to use\n * @param attrs - Optional attributes to override builder defaults\n * @returns A promise resolving to the inserted record\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert with defaults\n * const user = await factory.insert('user');\n *\n * // Insert with overrides\n * const adminUser = await factory.insert('user', {\n * email: 'admin@example.com',\n * role: 'admin'\n * });\n *\n * // Use the inserted record\n * const post = await factory.insert('post', {\n * userId: user.id,\n * title: 'My First Post'\n * });\n * ```\n */\n async insert<K extends keyof Builders>(\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Factory \"${\n builderName as string\n }\" does not exist. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const result = await this.builders[builderName](\n attrs || {},\n this,\n this.db,\n faker,\n );\n\n // For Kysely, we expect the builder to return an object with table and data properties\n // or to handle the insertion itself and return the inserted record\n if (\n result &&\n typeof result === 'object' &&\n 'table' in result &&\n 'data' in result\n ) {\n // If the builder returns {table: string, data: object}, we insert it\n const inserted = await this.db\n .insertInto(result.table)\n .values(result.data)\n .returningAll()\n .executeTakeFirst();\n\n return inserted as any;\n }\n\n // Otherwise, assume the builder handled the insertion itself\n return result;\n }\n\n /**\n * Inserts multiple records into the database using the specified builder.\n * Supports both static attributes and dynamic attribute generation via a function.\n *\n * @template K - The builder name (must be a key of Builders)\n * @param count - The number of records to insert\n * @param builderName - The name of the builder to use\n * @param attrs - Static attributes or a function that generates attributes for each record\n * @returns A promise resolving to an array of inserted records\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert multiple with same attributes\n * const users = await factory.insertMany(5, 'user', { role: 'member' });\n *\n * // Insert multiple with dynamic attributes\n * const posts = await factory.insertMany(10, 'post', (idx, faker) => ({\n * title: `Post ${idx + 1}`,\n * content: faker.lorem.paragraph(),\n * publishedAt: faker.date.past()\n * }));\n *\n * // Create users with sequential emails\n * const admins = await factory.insertMany(3, 'user', (idx) => ({\n * email: `admin${idx + 1}@example.com`,\n * role: 'admin'\n * }));\n * ```\n */\n // Method overloads for better type inference\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs: (\n idx: number,\n faker: FakerFactory,\n ) => Parameters<Builders[K]>[0] | Promise<Parameters<Builders[K]>[0]>,\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: any,\n ): Promise<Awaited<ReturnType<Builders[K]>>[]> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Builder \"${\n builderName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const promises: Promise<any>[] = [];\n\n for (let i = 0; i < count; i++) {\n const newAttrs =\n typeof attrs === 'function' ? await attrs(i, faker) : attrs;\n promises.push(this.insert(builderName, newAttrs));\n }\n\n return Promise.all(promises);\n }\n\n /**\n * Executes a seed function to create complex test scenarios with multiple related records.\n * Seeds are useful for setting up complete test environments with realistic data relationships.\n *\n * @template K - The seed name (must be a key of Seeds)\n * @param seedName - The name of the seed to execute\n * @param attrs - Optional configuration attributes for the seed\n * @returns The result of the seed function (typically the primary record created)\n * @throws Error if the specified seed doesn't exist\n *\n * @example\n * ```typescript\n * // Execute a simple seed\n * const user = await factory.seed('userWithProfile');\n *\n * // Execute a seed with configuration\n * const author = await factory.seed('authorWithBooks', {\n * bookCount: 5,\n * includeReviews: true\n * });\n *\n * // Use seed result in tests\n * const company = await factory.seed('companyWithDepartments', {\n * departmentCount: 3,\n * employeesPerDepartment: 10\n * });\n * expect(company.departments).toHaveLength(3);\n * ```\n */\n seed<K extends keyof Seeds>(\n seedName: K,\n attrs?: Parameters<Seeds[K]>[0],\n ): ReturnType<Seeds[K]> {\n if (!(seedName in this.seeds)) {\n throw new Error(\n `Seed \"${\n seedName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n return this.seeds[seedName](attrs || {}, this, this.db);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAa,gBAAb,cAIUA,wBAAyB;;;;;;;;;CASjC,OAAO,WAAqCC,QAAoB;AAC9D,SAAO,wBAAQ,WAAW,OAAO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GAAG;AACxD,YAAS,KAAK,KAAK,OAAO,aAAa,SAAS,CAAC;EAClD;AAED,SAAO,QAAQ,IAAI,SAAS;CAC7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BD,KACEI,UACAC,OACsB;AACtB,QAAM,YAAY,KAAK,OACrB,OAAM,IAAI,OACP,QACC,SACD;AAIL,SAAO,KAAK,MAAM,UAAU,SAAS,CAAE,GAAE,MAAM,KAAK,GAAG;CACxD;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ObjectionFactory-Eb04AOnv.cjs","names":["Factory","seedFn: Seed","ModelClass: TModel","defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Knex;\n faker: FakerFactory;\n }) =>\n | Partial<InstanceType<TModel>>\n | Promise<Partial<InstanceType<TModel>>>","autoInsert?: boolean","attrs: Attrs","factory: Factory","db: Knex","fakerInstance: FakerFactory","data: Partial<InstanceType<TModel>>","builders: Builders","seeds: Seeds","builderName: K","attrs?: Parameters<Builders[K]>[0]","faker","count: number","attrs?: any","records: any[]","record: any","seedName: K","attrs?: Parameters<Seeds[K]>[0]"],"sources":["../src/ObjectionFactory.ts"],"sourcesContent":["import type { Knex } from 'knex';\nimport type { Model } from 'objection';\nimport { Factory, type FactorySeed } from './Factory.ts';\nimport { type FakerFactory, faker } from './faker.ts';\n\n/**\n * Factory implementation for Objection.js ORM, providing test data creation utilities.\n * Extends the base Factory class with Objection.js-specific database operations.\n *\n * @template Builders - Record of builder functions for creating entities\n * @template Seeds - Record of seed functions for complex test scenarios\n *\n * @example\n * ```typescript\n * // Define your models with Objection.js\n * class User extends Model {\n * static tableName = 'users';\n * }\n *\n * // Create builders\n * const builders = {\n * user: ObjectionFactory.createBuilder(User, ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * ...attrs\n * })),\n * post: ObjectionFactory.createBuilder(Post, ({ attrs }) => ({\n * title: 'Test Post',\n * content: 'Test content',\n * ...attrs\n * })),\n * };\n *\n * // Create factory instance\n * const factory = new ObjectionFactory(builders, seeds, knex);\n *\n * // Use in tests\n * const user = await factory.insert('user', { name: 'John Doe' });\n * ```\n */\nexport class ObjectionFactory<\n Builders extends Record<string, any>,\n Seeds extends Record<string, any>,\n> extends Factory<Builders, Seeds> {\n /**\n * Creates a typed seed function with proper type inference.\n * Inherits from the base Factory class implementation.\n *\n * @template Seed - The seed function type\n * @param seedFn - The seed function to wrap\n * @returns The same seed function with proper typing\n */\n static createSeed<Seed extends FactorySeed>(seedFn: Seed): Seed {\n return Factory.createSeed(seedFn);\n }\n\n /**\n * Creates a typed builder function for Objection.js models.\n * This is a utility method that helps create builders with proper type inference.\n *\n * @template TModel - The Objection.js Model class type\n * @template Attrs - The attributes type for the builder (defaults to Partial of model)\n * @template Factory - The factory instance type\n * @template Result - The result type (defaults to the model instance)\n *\n * @param ModelClass - The Objection.js Model class\n * @param defaults - Optional function to provide default values (receives destructured context)\n * @param autoInsert - Whether to automatically insert the record (default: true)\n * @returns A builder function that creates and optionally inserts records\n *\n * @example\n * ```typescript\n * // Create a simple builder with defaults - destructure only what you need\n * const userBuilder = ObjectionFactory.createBuilder(User,\n * ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * createdAt: new Date(),\n * ...attrs\n * })\n * );\n *\n * // Only need faker? Just destructure that\n * const leaveTypeBuilder = ObjectionFactory.createBuilder(LeaveType,\n * ({ faker }) => ({\n * name: faker.helpers.arrayElement(['Annual', 'Sick', 'Maternity']),\n * code: faker.string.alpha({ length: 3, casing: 'upper' }),\n * })\n * );\n *\n * // Create a builder that doesn't auto-insert (useful for nested inserts)\n * const addressBuilder = ObjectionFactory.createBuilder(Address,\n * ({ attrs }) => ({\n * street: '123 Main St',\n * city: 'Anytown',\n * ...attrs\n * }),\n * false // Don't auto-insert\n * );\n *\n * // Use with relations\n * const postBuilder = ObjectionFactory.createBuilder(Post,\n * async ({ attrs, factory, faker }) => ({\n * title: faker.lorem.sentence(),\n * content: faker.lorem.paragraphs(),\n * authorId: attrs.authorId || (await factory.insert('user')).id,\n * ...attrs\n * })\n * );\n * ```\n */\n static createBuilder<\n TModel extends typeof Model,\n Attrs extends Partial<InstanceType<TModel>> = Partial<InstanceType<TModel>>,\n Factory = any,\n Result = InstanceType<TModel>,\n >(\n ModelClass: TModel,\n defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Knex;\n faker: FakerFactory;\n }) =>\n | Partial<InstanceType<TModel>>\n | Promise<Partial<InstanceType<TModel>>>,\n autoInsert?: boolean,\n ): (\n attrs: Attrs,\n factory: Factory,\n db: Knex,\n faker: FakerFactory,\n ) => Promise<Result> {\n return async (\n attrs: Attrs,\n factory: Factory,\n db: Knex,\n fakerInstance: FakerFactory,\n ) => {\n // Start with attributes\n let data: Partial<InstanceType<TModel>> = { ...attrs };\n\n // Apply defaults\n if (defaults) {\n const defaultValues = await defaults({\n attrs,\n factory,\n db,\n faker: fakerInstance,\n });\n data = { ...defaultValues, ...data };\n }\n\n // Create model instance\n const model = ModelClass.fromJson(data) as InstanceType<TModel>;\n\n // Handle insertion based on autoInsert flag\n if (autoInsert !== false) {\n // Auto insert is enabled by default\n // Extract only defined values for insertion\n const insertData = Object.entries(model).reduce((acc, [key, value]) => {\n if (value !== undefined && key !== 'id') {\n acc[key] = value;\n }\n return acc;\n }, {} as any);\n\n // Use static query method to insert data directly\n // @ts-ignore\n const result = await ModelClass.query(db).insert(insertData);\n return result as Result;\n } else {\n // Return model for factory to handle insertion\n return model as Result;\n }\n };\n }\n\n /**\n * Creates a new ObjectionFactory instance.\n *\n * @param builders - Record of builder functions for creating individual entities\n * @param seeds - Record of seed functions for creating complex test scenarios\n * @param db - Knex database connection instance\n */\n constructor(\n private builders: Builders,\n private seeds: Seeds,\n private db: Knex,\n ) {\n super();\n }\n\n /**\n * Inserts a single record into the database using the specified builder.\n * Uses Objection.js's insertGraph method to handle nested relations.\n *\n * @template K - The builder name (must be a key of Builders)\n * @param builderName - The name of the builder to use\n * @param attrs - Optional attributes to override builder defaults\n * @returns A promise resolving to the inserted record with all relations\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert with defaults\n * const user = await factory.insert('user');\n *\n * // Insert with overrides\n * const adminUser = await factory.insert('user', {\n * email: 'admin@example.com',\n * role: 'admin'\n * });\n *\n * // Insert with nested relations\n * const userWithProfile = await factory.insert('user', {\n * name: 'John Doe',\n * profile: {\n * bio: 'Software Developer',\n * avatar: 'avatar.jpg'\n * }\n * });\n * ```\n */\n async insert<K extends keyof Builders>(\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Factory \"${\n builderName as string\n }\" does not exist. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const result = await this.builders[builderName](\n attrs || {},\n this,\n this.db,\n faker,\n );\n\n // If the builder returns a model instance, insert it\n if (result && typeof result.$query === 'function') {\n // Extract data from model, excluding undefined values and id\n const insertData = Object.entries(result).reduce((acc, [key, value]) => {\n if (value !== undefined && key !== 'id') {\n acc[key] = value;\n }\n return acc;\n }, {} as any);\n\n // Use the model's constructor to get the query builder\n return await result.constructor.query(this.db).insert(insertData);\n }\n\n // Otherwise, assume the builder handled insertion itself\n return result;\n }\n /**\n * Inserts multiple records into the database using the specified builder.\n * Supports both static attributes and dynamic attribute generation via a function.\n *\n * @param count - The number of records to insert\n * @param builderName - The name of the builder to use\n * @param attrs - Static attributes or a function that generates attributes for each record\n * @returns A promise resolving to an array of inserted records\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert multiple with same attributes\n * const users = await factory.insertMany(5, 'user', { role: 'member' });\n *\n * // Insert multiple with dynamic attributes\n * const posts = await factory.insertMany(10, 'post', (idx) => ({\n * title: `Post ${idx + 1}`,\n * content: `Content for post ${idx + 1}`,\n * publishedAt: new Date()\n * }));\n *\n * // Create users with sequential emails\n * const admins = await factory.insertMany(3, 'user', (idx) => ({\n * email: `admin${idx + 1}@example.com`,\n * role: 'admin'\n * }));\n * ```\n */\n // Method overloads for better type inference\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs: (idx: number, faker: FakerFactory) => Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: any,\n ): Promise<Awaited<ReturnType<Builders[K]>>[]> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Builder \"${\n builderName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const records: any[] = [];\n for (let i = 0; i < count; i++) {\n const newAttrs =\n typeof attrs === 'function' ? await (attrs as any)(i, faker) : attrs;\n\n records.push(\n this.builders[builderName](newAttrs, this, this.db, faker).then(\n (record: any) => {\n // If the builder returns a model instance, insert it\n if (record && typeof record.$query === 'function') {\n // Extract data from model, excluding undefined values and id\n const insertData = Object.entries(record).reduce(\n (acc, [key, value]) => {\n if (value !== undefined && key !== 'id') {\n acc[key] = value;\n }\n return acc;\n },\n {} as any,\n );\n\n // Use the model's constructor to get the query builder\n return record.constructor.query(this.db).insert(insertData);\n }\n // Otherwise, assume the builder handled insertion itself\n return record;\n },\n ),\n );\n }\n\n return Promise.all(records);\n }\n /**\n * Executes a seed function to create complex test scenarios with multiple related records.\n * Seeds are useful for setting up complete test environments with realistic data relationships.\n *\n * @template K - The seed name (must be a key of Seeds)\n * @param seedName - The name of the seed to execute\n * @param attrs - Optional configuration attributes for the seed\n * @returns The result of the seed function (typically the primary record created)\n * @throws Error if the specified seed doesn't exist\n *\n * @example\n * ```typescript\n * // Execute a simple seed\n * const user = await factory.seed('userWithProfile');\n *\n * // Execute a seed with configuration\n * const author = await factory.seed('authorWithBooks', {\n * bookCount: 5,\n * includeReviews: true\n * });\n *\n * // Use seed result in tests with Objection.js relations\n * const company = await factory.seed('companyWithDepartments', {\n * departmentCount: 3,\n * employeesPerDepartment: 10\n * });\n *\n * // Access eager loaded relations\n * const companyWithRelations = await Company.query()\n * .findById(company.id)\n * .withGraphFetched('[departments.employees]');\n * ```\n */\n seed<K extends keyof Seeds>(\n seedName: K,\n attrs?: Parameters<Seeds[K]>[0],\n ): ReturnType<Seeds[K]> {\n if (!(seedName in this.seeds)) {\n throw new Error(\n `Seed \"${\n seedName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n return this.seeds[seedName](attrs || {}, this, this.db);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,mBAAb,cAGUA,wBAAyB;;;;;;;;;CASjC,OAAO,WAAqCC,QAAoB;AAC9D,SAAO,wBAAQ,WAAW,OAAO;CAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0DD,OAAO,cAMLC,YACAC,UAQAC,YAMmB;AACnB,SAAO,OACLC,OACAC,SACAC,IACAC,kBACG;GAEH,IAAIC,OAAsC,EAAE,GAAG,MAAO;AAGtD,OAAI,UAAU;IACZ,MAAM,gBAAgB,MAAM,SAAS;KACnC;KACA;KACA;KACA,OAAO;IACR,EAAC;AACF,WAAO;KAAE,GAAG;KAAe,GAAG;IAAM;GACrC;GAGD,MAAM,QAAQ,WAAW,SAAS,KAAK;AAGvC,OAAI,eAAe,OAAO;IAGxB,MAAM,aAAa,OAAO,QAAQ,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,MAAM,KAAK;AACrE,SAAI,oBAAuB,QAAQ,KACjC,KAAI,OAAO;AAEb,YAAO;IACR,GAAE,CAAE,EAAQ;IAIb,MAAM,SAAS,MAAM,WAAW,M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OAAO,WAAW;IAC5D;AAED,WAAO;GACR,EACF,CACF;EACF;AAED,SAAO,QAAQ,IAAI,QAAQ;CAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCD,KACEC,UACAC,OACsB;AACtB,QAAM,YAAY,KAAK,OACrB,OAAM,IAAI,OACP,QACC,SACD;AAIL,SAAO,KAAK,MAAM,UAAU,SAAS,CAAE,GAAE,MAAM,KAAK,GAAG;CACxD;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ObjectionFactory-zf2fLKrL.mjs","names":["seedFn: Seed","ModelClass: TModel","defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Knex;\n faker: FakerFactory;\n }) =>\n | Partial<InstanceType<TModel>>\n | Promise<Partial<InstanceType<TModel>>>","autoInsert?: boolean","attrs: Attrs","factory: Factory","db: Knex","fakerInstance: FakerFactory","data: Partial<InstanceType<TModel>>","builders: Builders","seeds: Seeds","builderName: K","attrs?: Parameters<Builders[K]>[0]","count: number","attrs?: any","records: any[]","record: any","seedName: K","attrs?: Parameters<Seeds[K]>[0]"],"sources":["../src/ObjectionFactory.ts"],"sourcesContent":["import type { Knex } from 'knex';\nimport type { Model } from 'objection';\nimport { Factory, type FactorySeed } from './Factory.ts';\nimport { type FakerFactory, faker } from './faker.ts';\n\n/**\n * Factory implementation for Objection.js ORM, providing test data creation utilities.\n * Extends the base Factory class with Objection.js-specific database operations.\n *\n * @template Builders - Record of builder functions for creating entities\n * @template Seeds - Record of seed functions for complex test scenarios\n *\n * @example\n * ```typescript\n * // Define your models with Objection.js\n * class User extends Model {\n * static tableName = 'users';\n * }\n *\n * // Create builders\n * const builders = {\n * user: ObjectionFactory.createBuilder(User, ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * ...attrs\n * })),\n * post: ObjectionFactory.createBuilder(Post, ({ attrs }) => ({\n * title: 'Test Post',\n * content: 'Test content',\n * ...attrs\n * })),\n * };\n *\n * // Create factory instance\n * const factory = new ObjectionFactory(builders, seeds, knex);\n *\n * // Use in tests\n * const user = await factory.insert('user', { name: 'John Doe' });\n * ```\n */\nexport class ObjectionFactory<\n Builders extends Record<string, any>,\n Seeds extends Record<string, any>,\n> extends Factory<Builders, Seeds> {\n /**\n * Creates a typed seed function with proper type inference.\n * Inherits from the base Factory class implementation.\n *\n * @template Seed - The seed function type\n * @param seedFn - The seed function to wrap\n * @returns The same seed function with proper typing\n */\n static createSeed<Seed extends FactorySeed>(seedFn: Seed): Seed {\n return Factory.createSeed(seedFn);\n }\n\n /**\n * Creates a typed builder function for Objection.js models.\n * This is a utility method that helps create builders with proper type inference.\n *\n * @template TModel - The Objection.js Model class type\n * @template Attrs - The attributes type for the builder (defaults to Partial of model)\n * @template Factory - The factory instance type\n * @template Result - The result type (defaults to the model instance)\n *\n * @param ModelClass - The Objection.js Model class\n * @param defaults - Optional function to provide default values (receives destructured context)\n * @param autoInsert - Whether to automatically insert the record (default: true)\n * @returns A builder function that creates and optionally inserts records\n *\n * @example\n * ```typescript\n * // Create a simple builder with defaults - destructure only what you need\n * const userBuilder = ObjectionFactory.createBuilder(User,\n * ({ attrs, faker }) => ({\n * id: faker.string.uuid(),\n * name: faker.person.fullName(),\n * email: faker.internet.email(),\n * createdAt: new Date(),\n * ...attrs\n * })\n * );\n *\n * // Only need faker? Just destructure that\n * const leaveTypeBuilder = ObjectionFactory.createBuilder(LeaveType,\n * ({ faker }) => ({\n * name: faker.helpers.arrayElement(['Annual', 'Sick', 'Maternity']),\n * code: faker.string.alpha({ length: 3, casing: 'upper' }),\n * })\n * );\n *\n * // Create a builder that doesn't auto-insert (useful for nested inserts)\n * const addressBuilder = ObjectionFactory.createBuilder(Address,\n * ({ attrs }) => ({\n * street: '123 Main St',\n * city: 'Anytown',\n * ...attrs\n * }),\n * false // Don't auto-insert\n * );\n *\n * // Use with relations\n * const postBuilder = ObjectionFactory.createBuilder(Post,\n * async ({ attrs, factory, faker }) => ({\n * title: faker.lorem.sentence(),\n * content: faker.lorem.paragraphs(),\n * authorId: attrs.authorId || (await factory.insert('user')).id,\n * ...attrs\n * })\n * );\n * ```\n */\n static createBuilder<\n TModel extends typeof Model,\n Attrs extends Partial<InstanceType<TModel>> = Partial<InstanceType<TModel>>,\n Factory = any,\n Result = InstanceType<TModel>,\n >(\n ModelClass: TModel,\n defaults?: (context: {\n attrs: Attrs;\n factory: Factory;\n db: Knex;\n faker: FakerFactory;\n }) =>\n | Partial<InstanceType<TModel>>\n | Promise<Partial<InstanceType<TModel>>>,\n autoInsert?: boolean,\n ): (\n attrs: Attrs,\n factory: Factory,\n db: Knex,\n faker: FakerFactory,\n ) => Promise<Result> {\n return async (\n attrs: Attrs,\n factory: Factory,\n db: Knex,\n fakerInstance: FakerFactory,\n ) => {\n // Start with attributes\n let data: Partial<InstanceType<TModel>> = { ...attrs };\n\n // Apply defaults\n if (defaults) {\n const defaultValues = await defaults({\n attrs,\n factory,\n db,\n faker: fakerInstance,\n });\n data = { ...defaultValues, ...data };\n }\n\n // Create model instance\n const model = ModelClass.fromJson(data) as InstanceType<TModel>;\n\n // Handle insertion based on autoInsert flag\n if (autoInsert !== false) {\n // Auto insert is enabled by default\n // Extract only defined values for insertion\n const insertData = Object.entries(model).reduce((acc, [key, value]) => {\n if (value !== undefined && key !== 'id') {\n acc[key] = value;\n }\n return acc;\n }, {} as any);\n\n // Use static query method to insert data directly\n // @ts-ignore\n const result = await ModelClass.query(db).insert(insertData);\n return result as Result;\n } else {\n // Return model for factory to handle insertion\n return model as Result;\n }\n };\n }\n\n /**\n * Creates a new ObjectionFactory instance.\n *\n * @param builders - Record of builder functions for creating individual entities\n * @param seeds - Record of seed functions for creating complex test scenarios\n * @param db - Knex database connection instance\n */\n constructor(\n private builders: Builders,\n private seeds: Seeds,\n private db: Knex,\n ) {\n super();\n }\n\n /**\n * Inserts a single record into the database using the specified builder.\n * Uses Objection.js's insertGraph method to handle nested relations.\n *\n * @template K - The builder name (must be a key of Builders)\n * @param builderName - The name of the builder to use\n * @param attrs - Optional attributes to override builder defaults\n * @returns A promise resolving to the inserted record with all relations\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert with defaults\n * const user = await factory.insert('user');\n *\n * // Insert with overrides\n * const adminUser = await factory.insert('user', {\n * email: 'admin@example.com',\n * role: 'admin'\n * });\n *\n * // Insert with nested relations\n * const userWithProfile = await factory.insert('user', {\n * name: 'John Doe',\n * profile: {\n * bio: 'Software Developer',\n * avatar: 'avatar.jpg'\n * }\n * });\n * ```\n */\n async insert<K extends keyof Builders>(\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Factory \"${\n builderName as string\n }\" does not exist. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const result = await this.builders[builderName](\n attrs || {},\n this,\n this.db,\n faker,\n );\n\n // If the builder returns a model instance, insert it\n if (result && typeof result.$query === 'function') {\n // Extract data from model, excluding undefined values and id\n const insertData = Object.entries(result).reduce((acc, [key, value]) => {\n if (value !== undefined && key !== 'id') {\n acc[key] = value;\n }\n return acc;\n }, {} as any);\n\n // Use the model's constructor to get the query builder\n return await result.constructor.query(this.db).insert(insertData);\n }\n\n // Otherwise, assume the builder handled insertion itself\n return result;\n }\n /**\n * Inserts multiple records into the database using the specified builder.\n * Supports both static attributes and dynamic attribute generation via a function.\n *\n * @param count - The number of records to insert\n * @param builderName - The name of the builder to use\n * @param attrs - Static attributes or a function that generates attributes for each record\n * @returns A promise resolving to an array of inserted records\n * @throws Error if the specified builder doesn't exist\n *\n * @example\n * ```typescript\n * // Insert multiple with same attributes\n * const users = await factory.insertMany(5, 'user', { role: 'member' });\n *\n * // Insert multiple with dynamic attributes\n * const posts = await factory.insertMany(10, 'post', (idx) => ({\n * title: `Post ${idx + 1}`,\n * content: `Content for post ${idx + 1}`,\n * publishedAt: new Date()\n * }));\n *\n * // Create users with sequential emails\n * const admins = await factory.insertMany(3, 'user', (idx) => ({\n * email: `admin${idx + 1}@example.com`,\n * role: 'admin'\n * }));\n * ```\n */\n // Method overloads for better type inference\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs: (idx: number, faker: FakerFactory) => Parameters<Builders[K]>[0],\n ): Promise<Awaited<ReturnType<Builders[K]>>[]>;\n async insertMany<K extends keyof Builders>(\n count: number,\n builderName: K,\n attrs?: any,\n ): Promise<Awaited<ReturnType<Builders[K]>>[]> {\n if (!(builderName in this.builders)) {\n throw new Error(\n `Builder \"${\n builderName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n const records: any[] = [];\n for (let i = 0; i < count; i++) {\n const newAttrs =\n typeof attrs === 'function' ? await (attrs as any)(i, faker) : attrs;\n\n records.push(\n this.builders[builderName](newAttrs, this, this.db, faker).then(\n (record: any) => {\n // If the builder returns a model instance, insert it\n if (record && typeof record.$query === 'function') {\n // Extract data from model, excluding undefined values and id\n const insertData = Object.entries(record).reduce(\n (acc, [key, value]) => {\n if (value !== undefined && key !== 'id') {\n acc[key] = value;\n }\n return acc;\n },\n {} as any,\n );\n\n // Use the model's constructor to get the query builder\n return record.constructor.query(this.db).insert(insertData);\n }\n // Otherwise, assume the builder handled insertion itself\n return record;\n },\n ),\n );\n }\n\n return Promise.all(records);\n }\n /**\n * Executes a seed function to create complex test scenarios with multiple related records.\n * Seeds are useful for setting up complete test environments with realistic data relationships.\n *\n * @template K - The seed name (must be a key of Seeds)\n * @param seedName - The name of the seed to execute\n * @param attrs - Optional configuration attributes for the seed\n * @returns The result of the seed function (typically the primary record created)\n * @throws Error if the specified seed doesn't exist\n *\n * @example\n * ```typescript\n * // Execute a simple seed\n * const user = await factory.seed('userWithProfile');\n *\n * // Execute a seed with configuration\n * const author = await factory.seed('authorWithBooks', {\n * bookCount: 5,\n * includeReviews: true\n * });\n *\n * // Use seed result in tests with Objection.js relations\n * const company = await factory.seed('companyWithDepartments', {\n * departmentCount: 3,\n * employeesPerDepartment: 10\n * });\n *\n * // Access eager loaded relations\n * const companyWithRelations = await Company.query()\n * .findById(company.id)\n * .withGraphFetched('[departments.employees]');\n * ```\n */\n seed<K extends keyof Seeds>(\n seedName: K,\n attrs?: Parameters<Seeds[K]>[0],\n ): ReturnType<Seeds[K]> {\n if (!(seedName in this.seeds)) {\n throw new Error(\n `Seed \"${\n seedName as string\n }\" is not registered in this factory. Make sure it is correct and registered in src/test/setup.ts`,\n );\n }\n\n return this.seeds[seedName](attrs || {}, this, this.db);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,mBAAb,cAGU,QAAyB;;;;;;;;;CASjC,OAAO,WAAqCA,QAAoB;AAC9D,SAAO,QAAQ,WAAW,OAAO;CAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0DD,OAAO,cAMLC,YACAC,UAQAC,YAMmB;AACnB,SAAO,OACLC,OACAC,SACAC,IACAC,kBACG;GAEH,IAAIC,OAAsC,EAAE,GAAG,MAAO;AAGtD,OAAI,UAAU;IACZ,MAAM,gBAAgB,MAAM,SAAS;KACnC;KACA;KACA;KACA,OAAO;IACR,EAAC;AACF,WAAO;KAAE,GAAG;KAAe,GAAG;IAAM;GACrC;GAGD,MAAM,QAAQ,WAAW,SAAS,KAAK;AAGvC,OAAI,eAAe,OAAO;IAGxB,MAAM,aAAa,OAAO,QAAQ,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,MAAM,KAAK;AACrE,SAAI,oBAAuB,QAAQ,KACjC,KAAI,OAAO;AAEb,YAAO;IACR,GAAE,CAAE,EAAQ;IAIb,MAAM,SAAS,MAAM,WAAW,MAAM,GAAG,CAAC,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