@geekmidas/testkit 0.0.17 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +302 -199
- package/dist/{Factory-CRquB4vz.d.mts → Factory-Cmr3s3-s.d.mts} +2 -2
- package/dist/Factory.d.mts +2 -2
- package/dist/{KyselyFactory-DRQ83r0o.d.cts → KyselyFactory-BFygzOlO.d.cts} +21 -8
- package/dist/{KyselyFactory-BDS_QqRT.d.mts → KyselyFactory-BTdygZ-i.d.mts} +23 -10
- package/dist/{KyselyFactory-BcYkC0t2.mjs → KyselyFactory-CXY5gJk2.mjs} +25 -12
- package/dist/KyselyFactory-CXY5gJk2.mjs.map +1 -0
- package/dist/{KyselyFactory-Cf0o2YxO.cjs → KyselyFactory-DaaCykWP.cjs} +25 -12
- package/dist/KyselyFactory-DaaCykWP.cjs.map +1 -0
- package/dist/KyselyFactory.cjs +1 -1
- package/dist/KyselyFactory.d.cts +1 -1
- package/dist/KyselyFactory.d.mts +3 -3
- package/dist/KyselyFactory.mjs +1 -1
- package/dist/{ObjectionFactory-C3tHvX1d.d.mts → ObjectionFactory-BagGjikT.d.mts} +26 -13
- package/dist/{ObjectionFactory-C4X78k0B.d.cts → ObjectionFactory-CeSIN3kZ.d.cts} +24 -11
- package/dist/{ObjectionFactory-CDriunkS.cjs → ObjectionFactory-Eb04AOnv.cjs} +28 -15
- package/dist/ObjectionFactory-Eb04AOnv.cjs.map +1 -0
- package/dist/{ObjectionFactory-8hebmnai.mjs → ObjectionFactory-zf2fLKrL.mjs} +28 -15
- package/dist/ObjectionFactory-zf2fLKrL.mjs.map +1 -0
- package/dist/ObjectionFactory.cjs +1 -1
- package/dist/ObjectionFactory.d.cts +1 -1
- package/dist/ObjectionFactory.d.mts +3 -3
- package/dist/ObjectionFactory.mjs +1 -1
- package/dist/{VitestKyselyTransactionIsolator-COCVfvfr.d.mts → VitestKyselyTransactionIsolator-4HOeLQ0d.d.cts} +2 -2
- package/dist/{VitestKyselyTransactionIsolator-Cst3vFjb.cjs → VitestKyselyTransactionIsolator-DX_VPKS-.cjs} +2 -2
- package/dist/{VitestKyselyTransactionIsolator-Cst3vFjb.cjs.map → VitestKyselyTransactionIsolator-DX_VPKS-.cjs.map} +1 -1
- package/dist/{VitestKyselyTransactionIsolator-DYUYVEh9.d.cts → VitestKyselyTransactionIsolator-DnyZMaA-.d.mts} +2 -2
- package/dist/{VitestKyselyTransactionIsolator-BxjlD1YM.mjs → VitestKyselyTransactionIsolator-XDL3ngs_.mjs} +2 -2
- package/dist/{VitestKyselyTransactionIsolator-BxjlD1YM.mjs.map → VitestKyselyTransactionIsolator-XDL3ngs_.mjs.map} +1 -1
- package/dist/VitestKyselyTransactionIsolator.cjs +2 -2
- package/dist/VitestKyselyTransactionIsolator.d.cts +2 -2
- package/dist/VitestKyselyTransactionIsolator.d.mts +2 -2
- package/dist/VitestKyselyTransactionIsolator.mjs +2 -2
- package/dist/{VitestObjectionTransactionIsolator-b973r9O1.d.mts → VitestObjectionTransactionIsolator-COVDlpEo.d.cts} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-DzeF4UAq.cjs → VitestObjectionTransactionIsolator-D_tlOtq8.cjs} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-DzeF4UAq.cjs.map → VitestObjectionTransactionIsolator-D_tlOtq8.cjs.map} +1 -1
- package/dist/{VitestObjectionTransactionIsolator-BU-jXEhz.mjs → VitestObjectionTransactionIsolator-_EhJKu_O.mjs} +2 -2
- package/dist/{VitestObjectionTransactionIsolator-BU-jXEhz.mjs.map → VitestObjectionTransactionIsolator-_EhJKu_O.mjs.map} +1 -1
- package/dist/{VitestObjectionTransactionIsolator-CJ4ds5Qv.d.cts → VitestObjectionTransactionIsolator-lZUSz1w0.d.mts} +2 -2
- package/dist/VitestObjectionTransactionIsolator.cjs +2 -2
- package/dist/VitestObjectionTransactionIsolator.d.cts +2 -2
- package/dist/VitestObjectionTransactionIsolator.d.mts +2 -2
- package/dist/VitestObjectionTransactionIsolator.mjs +2 -2
- package/dist/{VitestTransactionIsolator-CskiiJbW.mjs → VitestTransactionIsolator-BIaMs4c2.mjs} +40 -2
- package/dist/VitestTransactionIsolator-BIaMs4c2.mjs.map +1 -0
- package/dist/{VitestTransactionIsolator-BQ5FpLtC.cjs → VitestTransactionIsolator-BKIrj3Uy.cjs} +45 -1
- package/dist/VitestTransactionIsolator-BKIrj3Uy.cjs.map +1 -0
- package/dist/{VitestTransactionIsolator-DdLNODZg.d.cts → VitestTransactionIsolator-CyG_i_Nj.d.cts} +61 -3
- package/dist/{VitestTransactionIsolator-CsfJBxcb.d.mts → VitestTransactionIsolator-DWDbnITQ.d.mts} +61 -3
- package/dist/VitestTransactionIsolator.cjs +3 -2
- package/dist/VitestTransactionIsolator.d.cts +2 -2
- package/dist/VitestTransactionIsolator.d.mts +2 -2
- package/dist/VitestTransactionIsolator.mjs +2 -2
- package/dist/better-auth.cjs +8 -11
- package/dist/better-auth.cjs.map +1 -1
- package/dist/better-auth.d.cts +2 -2
- package/dist/better-auth.d.mts +2 -2
- package/dist/better-auth.mjs +8 -11
- package/dist/better-auth.mjs.map +1 -1
- package/dist/{directory-B4oYx02C.d.mts → directory-BXavAeJZ.d.mts} +3 -3
- package/dist/{directory-BUcnztHI.d.cts → directory-DlkPEzL4.d.cts} +3 -3
- package/dist/{faker-Br8MzXil.d.mts → faker-DHh7xs4u.d.mts} +3 -3
- package/dist/faker.d.mts +1 -1
- package/dist/kysely.cjs +58 -4
- package/dist/kysely.cjs.map +1 -1
- package/dist/kysely.d.cts +58 -5
- package/dist/kysely.d.mts +59 -6
- package/dist/kysely.mjs +57 -5
- package/dist/kysely.mjs.map +1 -1
- package/dist/objection.cjs +54 -4
- package/dist/objection.cjs.map +1 -1
- package/dist/objection.d.cts +54 -5
- package/dist/objection.d.mts +55 -6
- package/dist/objection.mjs +53 -5
- package/dist/objection.mjs.map +1 -1
- package/dist/os/directory.d.cts +1 -1
- package/dist/os/directory.d.mts +1 -1
- package/dist/os/index.d.cts +1 -1
- package/dist/os/index.d.mts +1 -1
- package/package.json +7 -3
- package/src/KyselyFactory.ts +29 -16
- package/src/ObjectionFactory.ts +34 -19
- package/src/VitestTransactionIsolator.ts +110 -2
- package/src/__tests__/KyselyFactory.spec.ts +10 -10
- package/src/__tests__/ObjectionFactory.spec.ts +9 -12
- package/src/__tests__/integration.spec.ts +171 -14
- package/src/better-auth.ts +13 -15
- package/src/kysely.ts +66 -0
- package/src/objection.ts +61 -0
- package/dist/KyselyFactory-BcYkC0t2.mjs.map +0 -1
- package/dist/KyselyFactory-Cf0o2YxO.cjs.map +0 -1
- package/dist/ObjectionFactory-8hebmnai.mjs.map +0 -1
- package/dist/ObjectionFactory-CDriunkS.cjs.map +0 -1
- package/dist/VitestTransactionIsolator-BQ5FpLtC.cjs.map +0 -1
- package/dist/VitestTransactionIsolator-CskiiJbW.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VitestTransactionIsolator-BIaMs4c2.mjs","names":["api: TestAPI","createConnection: DatabaseConnection<TConn>","setup?: (trx: Transaction) => Promise<void>","level: IsolationLevel","use: (value: Transaction) => Promise<void>","testError: Error | undefined","wrappedTest: T","fixtures: FixtureCreators<Transaction, Extended>","fixtureDefinitions: Record<string, any>","use: (value: unknown) => Promise<void>"],"sources":["../src/VitestTransactionIsolator.ts"],"sourcesContent":["import type { TestAPI } from 'vitest';\n\n/**\n * Type definition for test fixtures that provide transaction access.\n * Used with Vitest's test.extend() API to inject transactions into tests.\n *\n * @template Transaction - The transaction type specific to the database driver\n * @template Extended - Additional context properties provided by the extend function\n */\nexport interface DatabaseFixtures<Transaction, Extended = object> {\n /**\n * The database transaction available to the test.\n * All database operations should use this transaction to ensure proper rollback.\n */\n trx: Transaction;\n}\n\n/**\n * Combined fixtures type that merges the base transaction fixture with extended context.\n */\nexport type ExtendedDatabaseFixtures<\n Transaction,\n Extended = object,\n> = DatabaseFixtures<Transaction> & Extended;\n\n/**\n * Function type for extending test context with additional properties.\n * Receives the transaction and returns additional context to be merged with { trx }.\n *\n * @template Transaction - The transaction type\n * @template Extended - The type of additional context to provide\n *\n * @example\n * ```typescript\n * const extendContext: ExtendContextFn<Transaction<DB>, { factory: KyselyFactory }> =\n * (trx) => ({ factory: new KyselyFactory(builders, seeds, trx) });\n * ```\n */\nexport type ExtendContextFn<Transaction, Extended> = (\n trx: Transaction,\n) => Extended | Promise<Extended>;\n\n/**\n * PostgreSQL transaction isolation levels.\n * Controls the visibility of concurrent transactions.\n *\n * @see https://www.postgresql.org/docs/current/transaction-iso.html\n */\nexport enum IsolationLevel {\n /**\n * Lowest isolation level. Allows dirty reads.\n * Not recommended for testing.\n */\n READ_UNCOMMITTED = 'READ UNCOMMITTED',\n /**\n * Default PostgreSQL isolation level.\n * Prevents dirty reads but allows non-repeatable reads.\n */\n READ_COMMITTED = 'READ COMMITTED',\n /**\n * Prevents dirty reads and non-repeatable reads.\n * Recommended for most test scenarios.\n */\n REPEATABLE_READ = 'REPEATABLE READ',\n /**\n * Highest isolation level. Prevents all phenomena.\n * May cause performance overhead in tests.\n */\n SERIALIZABLE = 'SERIALIZABLE',\n}\n\n/**\n * Abstract base class for implementing database transaction isolation in Vitest tests.\n * Provides automatic transaction rollback after each test to maintain test isolation.\n * Subclasses must implement the transact() method for their specific database driver.\n *\n * @template TConn - The database connection type\n * @template Transaction - The transaction type\n *\n * @example\n * ```typescript\n * // Implement for your database driver\n * class MyDatabaseIsolator extends VitestPostgresTransactionIsolator<MyDB, MyTx> {\n * async transact(conn: MyDB, level: IsolationLevel, fn: (tx: MyTx) => Promise<void>) {\n * await conn.transaction(level, fn);\n * }\n * }\n *\n * // Use in tests\n * const isolator = new MyDatabaseIsolator(test);\n * const isolatedTest = isolator.wrapVitestWithTransaction(db);\n *\n * isolatedTest('should create user', async ({ trx }) => {\n * await trx.insert('users', { name: 'Test' });\n * // Data is automatically rolled back after test\n * });\n * ```\n */\nexport abstract class VitestPostgresTransactionIsolator<TConn, Transaction> {\n /**\n * Abstract method to create a transaction with the specified isolation level.\n * Must be implemented by subclasses for specific database drivers.\n *\n * @param conn - The database connection\n * @param isolationLevel - The transaction isolation level\n * @param fn - The function to execute within the transaction\n * @returns Promise that resolves when the transaction completes\n */\n abstract transact(\n conn: TConn,\n isolationLevel: IsolationLevel,\n fn: (trx: Transaction) => Promise<void>,\n ): Promise<void>;\n\n abstract destroy(conn: TConn): Promise<void>;\n /**\n * Creates a new VitestPostgresTransactionIsolator instance.\n *\n * @param api - The Vitest test API (usually the `test` export from vitest)\n */\n constructor(private readonly api: TestAPI) {}\n\n /**\n * Creates a wrapped version of Vitest's test API that provides transaction isolation.\n * Each test will run within a database transaction that is automatically rolled back.\n *\n * @param conn - The database connection to use\n * @param setup - Optional setup function to run within the transaction before each test\n * @param level - The transaction isolation level (defaults to REPEATABLE_READ)\n * @returns A wrapped test API with transaction support\n *\n * @example\n * ```typescript\n * const isolatedTest = isolator.wrapVitestWithTransaction(db, async (trx) => {\n * // Optional setup: create common test data\n * await trx.insert('settings', { key: 'test', value: 'true' });\n * });\n *\n * isolatedTest('test with transaction', async ({ trx }) => {\n * const user = await trx.insert('users', { name: 'Test' });\n * expect(user).toBeDefined();\n * });\n * ```\n */\n wrapVitestWithTransaction(\n createConnection: DatabaseConnection<TConn>,\n setup?: (trx: Transaction) => Promise<void>,\n level: IsolationLevel = IsolationLevel.REPEATABLE_READ,\n ) {\n return this.api.extend<DatabaseFixtures<Transaction>>({\n // This fixture automatically provides a transaction to each test\n trx: async ({}, use: (value: Transaction) => Promise<void>) => {\n // Create a custom error class for rollback\n class TestRollback extends Error {\n constructor() {\n super('Test rollback');\n this.name = 'TestRollback';\n }\n }\n\n let testError: Error | undefined;\n const conn = await createConnection();\n try {\n await this.transact(conn, level, async (transaction) => {\n try {\n // Provide the transaction to the test\n await setup?.(transaction);\n await use(transaction);\n } catch (error) {\n // Capture any test errors\n testError = error as Error;\n }\n\n // Always throw to trigger rollback\n throw new TestRollback();\n });\n } catch (error) {\n // Only rethrow if it's not our rollback error\n if (!(error instanceof TestRollback)) {\n throw error;\n }\n\n // If the test had an error, throw it now\n if (testError) {\n throw testError;\n }\n } finally {\n await this.destroy(conn);\n }\n },\n });\n }\n}\n\nexport type DatabaseConnectionFn<Conn> = () => Conn | Promise<Conn>;\nexport type DatabaseConnection<Conn> = DatabaseConnectionFn<Conn>;\n\n/**\n * Type for fixture creator functions that depend on the transaction.\n * Each function receives the transaction and returns the fixture value.\n */\nexport type FixtureCreators<\n Transaction,\n Extended extends Record<string, unknown>,\n> = {\n [K in keyof Extended]: (\n trx: Transaction,\n ) => Extended[K] | Promise<Extended[K]>;\n};\n\n/**\n * Extends a wrapped test API with additional fixtures that depend on the transaction.\n * This allows composing test context with factories, repositories, or other helpers.\n *\n * @template Transaction - The transaction type\n * @template Extended - The type of additional context to provide\n * @param wrappedTest - The base wrapped test from wrapVitestWithTransaction\n * @param fixtures - Object mapping fixture names to creator functions\n * @returns An extended test API with both trx and the additional fixtures\n *\n * @example\n * ```typescript\n * import { wrapVitestKyselyTransaction, extendWithFixtures } from '@geekmidas/testkit/kysely';\n *\n * // Create base wrapped test\n * const baseTest = wrapVitestKyselyTransaction(test, db, createTestTables);\n *\n * // Extend with fixtures\n * const it = extendWithFixtures(baseTest, {\n * factory: (trx) => new KyselyFactory(builders, seeds, trx),\n * userRepo: (trx) => new UserRepository(trx),\n * });\n *\n * // Use in tests - trx and all fixtures are available\n * it('should create user with factory', async ({ trx, factory, userRepo }) => {\n * const user = await factory.insert('user', { name: 'Test' });\n * expect(user).toBeDefined();\n * });\n * ```\n */\nexport function extendWithFixtures<\n Transaction,\n Extended extends Record<string, unknown>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends ReturnType<TestAPI['extend']> = any,\n>(\n wrappedTest: T,\n fixtures: FixtureCreators<Transaction, Extended>,\n): T & {\n <C extends object>(\n name: string,\n fn: (\n context: DatabaseFixtures<Transaction> & Extended & C,\n ) => Promise<void>,\n ): void;\n <C extends object>(\n name: string,\n options: object,\n fn: (\n context: DatabaseFixtures<Transaction> & Extended & C,\n ) => Promise<void>,\n ): void;\n} {\n // Build fixture definitions for Vitest's extend API\n const fixtureDefinitions: Record<string, any> = {};\n\n for (const [key, creator] of Object.entries(fixtures)) {\n fixtureDefinitions[key] = async (\n { trx }: { trx: Transaction },\n use: (value: unknown) => Promise<void>,\n ) => {\n const value = await (creator as (trx: Transaction) => unknown)(trx);\n await use(value);\n };\n }\n\n return (wrappedTest as any).extend(fixtureDefinitions);\n}\n"],"mappings":";;;;;;;AAgDA,IAAY,4DAAL;;;;;AAKL;;;;;AAKA;;;;;AAKA;;;;;AAKA;;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BD,IAAsB,oCAAtB,MAA4E;;;;;;CAsB1E,YAA6BA,KAAc;EAAd;CAAgB;;;;;;;;;;;;;;;;;;;;;;;CAwB7C,0BACEC,kBACAC,OACAC,QAAwB,eAAe,iBACvC;AACA,SAAO,KAAK,IAAI,OAAsC,EAEpD,KAAK,OAAO,EAAE,EAAEC,QAA+C;GAE7D,MAAM,qBAAqB,MAAM;IAC/B,cAAc;AACZ,WAAM,gBAAgB;AACtB,UAAK,OAAO;IACb;GACF;GAED,IAAIC;GACJ,MAAM,OAAO,MAAM,kBAAkB;AACrC,OAAI;AACF,UAAM,KAAK,SAAS,MAAM,OAAO,OAAO,gBAAgB;AACtD,SAAI;AAEF,YAAM,QAAQ,YAAY;AAC1B,YAAM,IAAI,YAAY;KACvB,SAAQ,OAAO;AAEd,kBAAY;KACb;AAGD,WAAM,IAAI;IACX,EAAC;GACH,SAAQ,OAAO;AAEd,UAAM,iBAAiB,cACrB,OAAM;AAIR,QAAI,UACF,OAAM;GAET,UAAS;AACR,UAAM,KAAK,QAAQ,KAAK;GACzB;EACF,EACF,EAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDD,SAAgB,mBAMdC,aACAC,UAeA;CAEA,MAAMC,qBAA0C,CAAE;AAElD,MAAK,MAAM,CAAC,KAAK,QAAQ,IAAI,OAAO,QAAQ,SAAS,CACnD,oBAAmB,OAAO,OACxB,EAAE,KAA2B,EAC7BC,QACG;EACH,MAAM,QAAQ,MAAM,AAAC,QAA0C,IAAI;AACnE,QAAM,IAAI,MAAM;CACjB;AAGH,QAAO,AAAC,YAAoB,OAAO,mBAAmB;AACvD"}
|
package/dist/{VitestTransactionIsolator-BQ5FpLtC.cjs → VitestTransactionIsolator-BKIrj3Uy.cjs}
RENAMED
|
@@ -116,6 +116,44 @@ var VitestPostgresTransactionIsolator = class {
|
|
|
116
116
|
} });
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
|
+
/**
|
|
120
|
+
* Extends a wrapped test API with additional fixtures that depend on the transaction.
|
|
121
|
+
* This allows composing test context with factories, repositories, or other helpers.
|
|
122
|
+
*
|
|
123
|
+
* @template Transaction - The transaction type
|
|
124
|
+
* @template Extended - The type of additional context to provide
|
|
125
|
+
* @param wrappedTest - The base wrapped test from wrapVitestWithTransaction
|
|
126
|
+
* @param fixtures - Object mapping fixture names to creator functions
|
|
127
|
+
* @returns An extended test API with both trx and the additional fixtures
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```typescript
|
|
131
|
+
* import { wrapVitestKyselyTransaction, extendWithFixtures } from '@geekmidas/testkit/kysely';
|
|
132
|
+
*
|
|
133
|
+
* // Create base wrapped test
|
|
134
|
+
* const baseTest = wrapVitestKyselyTransaction(test, db, createTestTables);
|
|
135
|
+
*
|
|
136
|
+
* // Extend with fixtures
|
|
137
|
+
* const it = extendWithFixtures(baseTest, {
|
|
138
|
+
* factory: (trx) => new KyselyFactory(builders, seeds, trx),
|
|
139
|
+
* userRepo: (trx) => new UserRepository(trx),
|
|
140
|
+
* });
|
|
141
|
+
*
|
|
142
|
+
* // Use in tests - trx and all fixtures are available
|
|
143
|
+
* it('should create user with factory', async ({ trx, factory, userRepo }) => {
|
|
144
|
+
* const user = await factory.insert('user', { name: 'Test' });
|
|
145
|
+
* expect(user).toBeDefined();
|
|
146
|
+
* });
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
function extendWithFixtures(wrappedTest, fixtures) {
|
|
150
|
+
const fixtureDefinitions = {};
|
|
151
|
+
for (const [key, creator] of Object.entries(fixtures)) fixtureDefinitions[key] = async ({ trx }, use) => {
|
|
152
|
+
const value = await creator(trx);
|
|
153
|
+
await use(value);
|
|
154
|
+
};
|
|
155
|
+
return wrappedTest.extend(fixtureDefinitions);
|
|
156
|
+
}
|
|
119
157
|
|
|
120
158
|
//#endregion
|
|
121
159
|
Object.defineProperty(exports, 'IsolationLevel', {
|
|
@@ -130,4 +168,10 @@ Object.defineProperty(exports, 'VitestPostgresTransactionIsolator', {
|
|
|
130
168
|
return VitestPostgresTransactionIsolator;
|
|
131
169
|
}
|
|
132
170
|
});
|
|
133
|
-
|
|
171
|
+
Object.defineProperty(exports, 'extendWithFixtures', {
|
|
172
|
+
enumerable: true,
|
|
173
|
+
get: function () {
|
|
174
|
+
return extendWithFixtures;
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
//# sourceMappingURL=VitestTransactionIsolator-BKIrj3Uy.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"VitestTransactionIsolator-BKIrj3Uy.cjs","names":["api: TestAPI","createConnection: DatabaseConnection<TConn>","setup?: (trx: Transaction) => Promise<void>","level: IsolationLevel","use: (value: Transaction) => Promise<void>","testError: Error | undefined","wrappedTest: T","fixtures: FixtureCreators<Transaction, Extended>","fixtureDefinitions: Record<string, any>","use: (value: unknown) => Promise<void>"],"sources":["../src/VitestTransactionIsolator.ts"],"sourcesContent":["import type { TestAPI } from 'vitest';\n\n/**\n * Type definition for test fixtures that provide transaction access.\n * Used with Vitest's test.extend() API to inject transactions into tests.\n *\n * @template Transaction - The transaction type specific to the database driver\n * @template Extended - Additional context properties provided by the extend function\n */\nexport interface DatabaseFixtures<Transaction, Extended = object> {\n /**\n * The database transaction available to the test.\n * All database operations should use this transaction to ensure proper rollback.\n */\n trx: Transaction;\n}\n\n/**\n * Combined fixtures type that merges the base transaction fixture with extended context.\n */\nexport type ExtendedDatabaseFixtures<\n Transaction,\n Extended = object,\n> = DatabaseFixtures<Transaction> & Extended;\n\n/**\n * Function type for extending test context with additional properties.\n * Receives the transaction and returns additional context to be merged with { trx }.\n *\n * @template Transaction - The transaction type\n * @template Extended - The type of additional context to provide\n *\n * @example\n * ```typescript\n * const extendContext: ExtendContextFn<Transaction<DB>, { factory: KyselyFactory }> =\n * (trx) => ({ factory: new KyselyFactory(builders, seeds, trx) });\n * ```\n */\nexport type ExtendContextFn<Transaction, Extended> = (\n trx: Transaction,\n) => Extended | Promise<Extended>;\n\n/**\n * PostgreSQL transaction isolation levels.\n * Controls the visibility of concurrent transactions.\n *\n * @see https://www.postgresql.org/docs/current/transaction-iso.html\n */\nexport enum IsolationLevel {\n /**\n * Lowest isolation level. Allows dirty reads.\n * Not recommended for testing.\n */\n READ_UNCOMMITTED = 'READ UNCOMMITTED',\n /**\n * Default PostgreSQL isolation level.\n * Prevents dirty reads but allows non-repeatable reads.\n */\n READ_COMMITTED = 'READ COMMITTED',\n /**\n * Prevents dirty reads and non-repeatable reads.\n * Recommended for most test scenarios.\n */\n REPEATABLE_READ = 'REPEATABLE READ',\n /**\n * Highest isolation level. Prevents all phenomena.\n * May cause performance overhead in tests.\n */\n SERIALIZABLE = 'SERIALIZABLE',\n}\n\n/**\n * Abstract base class for implementing database transaction isolation in Vitest tests.\n * Provides automatic transaction rollback after each test to maintain test isolation.\n * Subclasses must implement the transact() method for their specific database driver.\n *\n * @template TConn - The database connection type\n * @template Transaction - The transaction type\n *\n * @example\n * ```typescript\n * // Implement for your database driver\n * class MyDatabaseIsolator extends VitestPostgresTransactionIsolator<MyDB, MyTx> {\n * async transact(conn: MyDB, level: IsolationLevel, fn: (tx: MyTx) => Promise<void>) {\n * await conn.transaction(level, fn);\n * }\n * }\n *\n * // Use in tests\n * const isolator = new MyDatabaseIsolator(test);\n * const isolatedTest = isolator.wrapVitestWithTransaction(db);\n *\n * isolatedTest('should create user', async ({ trx }) => {\n * await trx.insert('users', { name: 'Test' });\n * // Data is automatically rolled back after test\n * });\n * ```\n */\nexport abstract class VitestPostgresTransactionIsolator<TConn, Transaction> {\n /**\n * Abstract method to create a transaction with the specified isolation level.\n * Must be implemented by subclasses for specific database drivers.\n *\n * @param conn - The database connection\n * @param isolationLevel - The transaction isolation level\n * @param fn - The function to execute within the transaction\n * @returns Promise that resolves when the transaction completes\n */\n abstract transact(\n conn: TConn,\n isolationLevel: IsolationLevel,\n fn: (trx: Transaction) => Promise<void>,\n ): Promise<void>;\n\n abstract destroy(conn: TConn): Promise<void>;\n /**\n * Creates a new VitestPostgresTransactionIsolator instance.\n *\n * @param api - The Vitest test API (usually the `test` export from vitest)\n */\n constructor(private readonly api: TestAPI) {}\n\n /**\n * Creates a wrapped version of Vitest's test API that provides transaction isolation.\n * Each test will run within a database transaction that is automatically rolled back.\n *\n * @param conn - The database connection to use\n * @param setup - Optional setup function to run within the transaction before each test\n * @param level - The transaction isolation level (defaults to REPEATABLE_READ)\n * @returns A wrapped test API with transaction support\n *\n * @example\n * ```typescript\n * const isolatedTest = isolator.wrapVitestWithTransaction(db, async (trx) => {\n * // Optional setup: create common test data\n * await trx.insert('settings', { key: 'test', value: 'true' });\n * });\n *\n * isolatedTest('test with transaction', async ({ trx }) => {\n * const user = await trx.insert('users', { name: 'Test' });\n * expect(user).toBeDefined();\n * });\n * ```\n */\n wrapVitestWithTransaction(\n createConnection: DatabaseConnection<TConn>,\n setup?: (trx: Transaction) => Promise<void>,\n level: IsolationLevel = IsolationLevel.REPEATABLE_READ,\n ) {\n return this.api.extend<DatabaseFixtures<Transaction>>({\n // This fixture automatically provides a transaction to each test\n trx: async ({}, use: (value: Transaction) => Promise<void>) => {\n // Create a custom error class for rollback\n class TestRollback extends Error {\n constructor() {\n super('Test rollback');\n this.name = 'TestRollback';\n }\n }\n\n let testError: Error | undefined;\n const conn = await createConnection();\n try {\n await this.transact(conn, level, async (transaction) => {\n try {\n // Provide the transaction to the test\n await setup?.(transaction);\n await use(transaction);\n } catch (error) {\n // Capture any test errors\n testError = error as Error;\n }\n\n // Always throw to trigger rollback\n throw new TestRollback();\n });\n } catch (error) {\n // Only rethrow if it's not our rollback error\n if (!(error instanceof TestRollback)) {\n throw error;\n }\n\n // If the test had an error, throw it now\n if (testError) {\n throw testError;\n }\n } finally {\n await this.destroy(conn);\n }\n },\n });\n }\n}\n\nexport type DatabaseConnectionFn<Conn> = () => Conn | Promise<Conn>;\nexport type DatabaseConnection<Conn> = DatabaseConnectionFn<Conn>;\n\n/**\n * Type for fixture creator functions that depend on the transaction.\n * Each function receives the transaction and returns the fixture value.\n */\nexport type FixtureCreators<\n Transaction,\n Extended extends Record<string, unknown>,\n> = {\n [K in keyof Extended]: (\n trx: Transaction,\n ) => Extended[K] | Promise<Extended[K]>;\n};\n\n/**\n * Extends a wrapped test API with additional fixtures that depend on the transaction.\n * This allows composing test context with factories, repositories, or other helpers.\n *\n * @template Transaction - The transaction type\n * @template Extended - The type of additional context to provide\n * @param wrappedTest - The base wrapped test from wrapVitestWithTransaction\n * @param fixtures - Object mapping fixture names to creator functions\n * @returns An extended test API with both trx and the additional fixtures\n *\n * @example\n * ```typescript\n * import { wrapVitestKyselyTransaction, extendWithFixtures } from '@geekmidas/testkit/kysely';\n *\n * // Create base wrapped test\n * const baseTest = wrapVitestKyselyTransaction(test, db, createTestTables);\n *\n * // Extend with fixtures\n * const it = extendWithFixtures(baseTest, {\n * factory: (trx) => new KyselyFactory(builders, seeds, trx),\n * userRepo: (trx) => new UserRepository(trx),\n * });\n *\n * // Use in tests - trx and all fixtures are available\n * it('should create user with factory', async ({ trx, factory, userRepo }) => {\n * const user = await factory.insert('user', { name: 'Test' });\n * expect(user).toBeDefined();\n * });\n * ```\n */\nexport function extendWithFixtures<\n Transaction,\n Extended extends Record<string, unknown>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends ReturnType<TestAPI['extend']> = any,\n>(\n wrappedTest: T,\n fixtures: FixtureCreators<Transaction, Extended>,\n): T & {\n <C extends object>(\n name: string,\n fn: (\n context: DatabaseFixtures<Transaction> & Extended & C,\n ) => Promise<void>,\n ): void;\n <C extends object>(\n name: string,\n options: object,\n fn: (\n context: DatabaseFixtures<Transaction> & Extended & C,\n ) => Promise<void>,\n ): void;\n} {\n // Build fixture definitions for Vitest's extend API\n const fixtureDefinitions: Record<string, any> = {};\n\n for (const [key, creator] of Object.entries(fixtures)) {\n fixtureDefinitions[key] = async (\n { trx }: { trx: Transaction },\n use: (value: unknown) => Promise<void>,\n ) => {\n const value = await (creator as (trx: Transaction) => unknown)(trx);\n await use(value);\n };\n }\n\n return (wrappedTest as any).extend(fixtureDefinitions);\n}\n"],"mappings":";;;;;;;;AAgDA,IAAY,4DAAL;;;;;AAKL;;;;;AAKA;;;;;AAKA;;;;;AAKA;;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BD,IAAsB,oCAAtB,MAA4E;;;;;;CAsB1E,YAA6BA,KAAc;EAAd;CAAgB;;;;;;;;;;;;;;;;;;;;;;;CAwB7C,0BACEC,kBACAC,OACAC,QAAwB,eAAe,iBACvC;AACA,SAAO,KAAK,IAAI,OAAsC,EAEpD,KAAK,OAAO,EAAE,EAAEC,QAA+C;GAE7D,MAAM,qBAAqB,MAAM;IAC/B,cAAc;AACZ,WAAM,gBAAgB;AACtB,UAAK,OAAO;IACb;GACF;GAED,IAAIC;GACJ,MAAM,OAAO,MAAM,kBAAkB;AACrC,OAAI;AACF,UAAM,KAAK,SAAS,MAAM,OAAO,OAAO,gBAAgB;AACtD,SAAI;AAEF,YAAM,QAAQ,YAAY;AAC1B,YAAM,IAAI,YAAY;KACvB,SAAQ,OAAO;AAEd,kBAAY;KACb;AAGD,WAAM,IAAI;IACX,EAAC;GACH,SAAQ,OAAO;AAEd,UAAM,iBAAiB,cACrB,OAAM;AAIR,QAAI,UACF,OAAM;GAET,UAAS;AACR,UAAM,KAAK,QAAQ,KAAK;GACzB;EACF,EACF,EAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDD,SAAgB,mBAMdC,aACAC,UAeA;CAEA,MAAMC,qBAA0C,CAAE;AAElD,MAAK,MAAM,CAAC,KAAK,QAAQ,IAAI,OAAO,QAAQ,SAAS,CACnD,oBAAmB,OAAO,OACxB,EAAE,KAA2B,EAC7BC,QACG;EACH,MAAM,QAAQ,MAAM,AAAC,QAA0C,IAAI;AACnE,QAAM,IAAI,MAAM;CACjB;AAGH,QAAO,AAAC,YAAoB,OAAO,mBAAmB;AACvD"}
|
package/dist/{VitestTransactionIsolator-DdLNODZg.d.cts → VitestTransactionIsolator-CyG_i_Nj.d.cts}
RENAMED
|
@@ -7,14 +7,33 @@ import { TestAPI } from "vitest";
|
|
|
7
7
|
* Used with Vitest's test.extend() API to inject transactions into tests.
|
|
8
8
|
*
|
|
9
9
|
* @template Transaction - The transaction type specific to the database driver
|
|
10
|
+
* @template Extended - Additional context properties provided by the extend function
|
|
10
11
|
*/
|
|
11
|
-
interface DatabaseFixtures<Transaction> {
|
|
12
|
+
interface DatabaseFixtures<Transaction, Extended = object> {
|
|
12
13
|
/**
|
|
13
14
|
* The database transaction available to the test.
|
|
14
15
|
* All database operations should use this transaction to ensure proper rollback.
|
|
15
16
|
*/
|
|
16
17
|
trx: Transaction;
|
|
17
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Combined fixtures type that merges the base transaction fixture with extended context.
|
|
21
|
+
*/
|
|
22
|
+
type ExtendedDatabaseFixtures<Transaction, Extended = object> = DatabaseFixtures<Transaction> & Extended;
|
|
23
|
+
/**
|
|
24
|
+
* Function type for extending test context with additional properties.
|
|
25
|
+
* Receives the transaction and returns additional context to be merged with { trx }.
|
|
26
|
+
*
|
|
27
|
+
* @template Transaction - The transaction type
|
|
28
|
+
* @template Extended - The type of additional context to provide
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* const extendContext: ExtendContextFn<Transaction<DB>, { factory: KyselyFactory }> =
|
|
33
|
+
* (trx) => ({ factory: new KyselyFactory(builders, seeds, trx) });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
type ExtendContextFn<Transaction, Extended> = (trx: Transaction) => Extended | Promise<Extended>;
|
|
18
37
|
/**
|
|
19
38
|
* PostgreSQL transaction isolation levels.
|
|
20
39
|
* Controls the visibility of concurrent transactions.
|
|
@@ -117,6 +136,45 @@ declare abstract class VitestPostgresTransactionIsolator<TConn, Transaction> {
|
|
|
117
136
|
}
|
|
118
137
|
type DatabaseConnectionFn<Conn> = () => Conn | Promise<Conn>;
|
|
119
138
|
type DatabaseConnection<Conn> = DatabaseConnectionFn<Conn>;
|
|
139
|
+
/**
|
|
140
|
+
* Type for fixture creator functions that depend on the transaction.
|
|
141
|
+
* Each function receives the transaction and returns the fixture value.
|
|
142
|
+
*/
|
|
143
|
+
type FixtureCreators<Transaction, Extended extends Record<string, unknown>> = { [K in keyof Extended]: (trx: Transaction) => Extended[K] | Promise<Extended[K]> };
|
|
144
|
+
/**
|
|
145
|
+
* Extends a wrapped test API with additional fixtures that depend on the transaction.
|
|
146
|
+
* This allows composing test context with factories, repositories, or other helpers.
|
|
147
|
+
*
|
|
148
|
+
* @template Transaction - The transaction type
|
|
149
|
+
* @template Extended - The type of additional context to provide
|
|
150
|
+
* @param wrappedTest - The base wrapped test from wrapVitestWithTransaction
|
|
151
|
+
* @param fixtures - Object mapping fixture names to creator functions
|
|
152
|
+
* @returns An extended test API with both trx and the additional fixtures
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```typescript
|
|
156
|
+
* import { wrapVitestKyselyTransaction, extendWithFixtures } from '@geekmidas/testkit/kysely';
|
|
157
|
+
*
|
|
158
|
+
* // Create base wrapped test
|
|
159
|
+
* const baseTest = wrapVitestKyselyTransaction(test, db, createTestTables);
|
|
160
|
+
*
|
|
161
|
+
* // Extend with fixtures
|
|
162
|
+
* const it = extendWithFixtures(baseTest, {
|
|
163
|
+
* factory: (trx) => new KyselyFactory(builders, seeds, trx),
|
|
164
|
+
* userRepo: (trx) => new UserRepository(trx),
|
|
165
|
+
* });
|
|
166
|
+
*
|
|
167
|
+
* // Use in tests - trx and all fixtures are available
|
|
168
|
+
* it('should create user with factory', async ({ trx, factory, userRepo }) => {
|
|
169
|
+
* const user = await factory.insert('user', { name: 'Test' });
|
|
170
|
+
* expect(user).toBeDefined();
|
|
171
|
+
* });
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
declare function extendWithFixtures<Transaction, Extended extends Record<string, unknown>, T extends ReturnType<TestAPI['extend']> = any>(wrappedTest: T, fixtures: FixtureCreators<Transaction, Extended>): T & {
|
|
175
|
+
<C extends object>(name: string, fn: (context: DatabaseFixtures<Transaction> & Extended & C) => Promise<void>): void;
|
|
176
|
+
<C extends object>(name: string, options: object, fn: (context: DatabaseFixtures<Transaction> & Extended & C) => Promise<void>): void;
|
|
177
|
+
};
|
|
120
178
|
//#endregion
|
|
121
|
-
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, IsolationLevel, VitestPostgresTransactionIsolator };
|
|
122
|
-
//# sourceMappingURL=VitestTransactionIsolator-
|
|
179
|
+
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, ExtendContextFn, ExtendedDatabaseFixtures, FixtureCreators, IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures };
|
|
180
|
+
//# sourceMappingURL=VitestTransactionIsolator-CyG_i_Nj.d.cts.map
|
package/dist/{VitestTransactionIsolator-CsfJBxcb.d.mts → VitestTransactionIsolator-DWDbnITQ.d.mts}
RENAMED
|
@@ -7,14 +7,33 @@ import { TestAPI } from "vitest";
|
|
|
7
7
|
* Used with Vitest's test.extend() API to inject transactions into tests.
|
|
8
8
|
*
|
|
9
9
|
* @template Transaction - The transaction type specific to the database driver
|
|
10
|
+
* @template Extended - Additional context properties provided by the extend function
|
|
10
11
|
*/
|
|
11
|
-
interface DatabaseFixtures<Transaction> {
|
|
12
|
+
interface DatabaseFixtures<Transaction, Extended = object> {
|
|
12
13
|
/**
|
|
13
14
|
* The database transaction available to the test.
|
|
14
15
|
* All database operations should use this transaction to ensure proper rollback.
|
|
15
16
|
*/
|
|
16
17
|
trx: Transaction;
|
|
17
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Combined fixtures type that merges the base transaction fixture with extended context.
|
|
21
|
+
*/
|
|
22
|
+
type ExtendedDatabaseFixtures<Transaction, Extended = object> = DatabaseFixtures<Transaction> & Extended;
|
|
23
|
+
/**
|
|
24
|
+
* Function type for extending test context with additional properties.
|
|
25
|
+
* Receives the transaction and returns additional context to be merged with { trx }.
|
|
26
|
+
*
|
|
27
|
+
* @template Transaction - The transaction type
|
|
28
|
+
* @template Extended - The type of additional context to provide
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* const extendContext: ExtendContextFn<Transaction<DB>, { factory: KyselyFactory }> =
|
|
33
|
+
* (trx) => ({ factory: new KyselyFactory(builders, seeds, trx) });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
type ExtendContextFn<Transaction, Extended> = (trx: Transaction) => Extended | Promise<Extended>;
|
|
18
37
|
/**
|
|
19
38
|
* PostgreSQL transaction isolation levels.
|
|
20
39
|
* Controls the visibility of concurrent transactions.
|
|
@@ -117,6 +136,45 @@ declare abstract class VitestPostgresTransactionIsolator<TConn, Transaction> {
|
|
|
117
136
|
}
|
|
118
137
|
type DatabaseConnectionFn<Conn> = () => Conn | Promise<Conn>;
|
|
119
138
|
type DatabaseConnection<Conn> = DatabaseConnectionFn<Conn>;
|
|
139
|
+
/**
|
|
140
|
+
* Type for fixture creator functions that depend on the transaction.
|
|
141
|
+
* Each function receives the transaction and returns the fixture value.
|
|
142
|
+
*/
|
|
143
|
+
type FixtureCreators<Transaction, Extended extends Record<string, unknown>> = { [K in keyof Extended]: (trx: Transaction) => Extended[K] | Promise<Extended[K]> };
|
|
144
|
+
/**
|
|
145
|
+
* Extends a wrapped test API with additional fixtures that depend on the transaction.
|
|
146
|
+
* This allows composing test context with factories, repositories, or other helpers.
|
|
147
|
+
*
|
|
148
|
+
* @template Transaction - The transaction type
|
|
149
|
+
* @template Extended - The type of additional context to provide
|
|
150
|
+
* @param wrappedTest - The base wrapped test from wrapVitestWithTransaction
|
|
151
|
+
* @param fixtures - Object mapping fixture names to creator functions
|
|
152
|
+
* @returns An extended test API with both trx and the additional fixtures
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```typescript
|
|
156
|
+
* import { wrapVitestKyselyTransaction, extendWithFixtures } from '@geekmidas/testkit/kysely';
|
|
157
|
+
*
|
|
158
|
+
* // Create base wrapped test
|
|
159
|
+
* const baseTest = wrapVitestKyselyTransaction(test, db, createTestTables);
|
|
160
|
+
*
|
|
161
|
+
* // Extend with fixtures
|
|
162
|
+
* const it = extendWithFixtures(baseTest, {
|
|
163
|
+
* factory: (trx) => new KyselyFactory(builders, seeds, trx),
|
|
164
|
+
* userRepo: (trx) => new UserRepository(trx),
|
|
165
|
+
* });
|
|
166
|
+
*
|
|
167
|
+
* // Use in tests - trx and all fixtures are available
|
|
168
|
+
* it('should create user with factory', async ({ trx, factory, userRepo }) => {
|
|
169
|
+
* const user = await factory.insert('user', { name: 'Test' });
|
|
170
|
+
* expect(user).toBeDefined();
|
|
171
|
+
* });
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
declare function extendWithFixtures<Transaction, Extended extends Record<string, unknown>, T extends ReturnType<TestAPI['extend']> = any>(wrappedTest: T, fixtures: FixtureCreators<Transaction, Extended>): T & {
|
|
175
|
+
<C extends object>(name: string, fn: (context: DatabaseFixtures<Transaction> & Extended & C) => Promise<void>): void;
|
|
176
|
+
<C extends object>(name: string, options: object, fn: (context: DatabaseFixtures<Transaction> & Extended & C) => Promise<void>): void;
|
|
177
|
+
};
|
|
120
178
|
//#endregion
|
|
121
|
-
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, IsolationLevel, VitestPostgresTransactionIsolator };
|
|
122
|
-
//# sourceMappingURL=VitestTransactionIsolator-
|
|
179
|
+
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, ExtendContextFn, ExtendedDatabaseFixtures, FixtureCreators, IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures };
|
|
180
|
+
//# sourceMappingURL=VitestTransactionIsolator-DWDbnITQ.d.mts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
const require_VitestTransactionIsolator = require('./VitestTransactionIsolator-
|
|
1
|
+
const require_VitestTransactionIsolator = require('./VitestTransactionIsolator-BKIrj3Uy.cjs');
|
|
2
2
|
|
|
3
3
|
exports.IsolationLevel = require_VitestTransactionIsolator.IsolationLevel;
|
|
4
|
-
exports.VitestPostgresTransactionIsolator = require_VitestTransactionIsolator.VitestPostgresTransactionIsolator;
|
|
4
|
+
exports.VitestPostgresTransactionIsolator = require_VitestTransactionIsolator.VitestPostgresTransactionIsolator;
|
|
5
|
+
exports.extendWithFixtures = require_VitestTransactionIsolator.extendWithFixtures;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, IsolationLevel, VitestPostgresTransactionIsolator } from "./VitestTransactionIsolator-
|
|
2
|
-
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, IsolationLevel, VitestPostgresTransactionIsolator };
|
|
1
|
+
import { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, ExtendContextFn, ExtendedDatabaseFixtures, FixtureCreators, IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures } from "./VitestTransactionIsolator-CyG_i_Nj.cjs";
|
|
2
|
+
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, ExtendContextFn, ExtendedDatabaseFixtures, FixtureCreators, IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, IsolationLevel, VitestPostgresTransactionIsolator } from "./VitestTransactionIsolator-
|
|
2
|
-
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, IsolationLevel, VitestPostgresTransactionIsolator };
|
|
1
|
+
import { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, ExtendContextFn, ExtendedDatabaseFixtures, FixtureCreators, IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures } from "./VitestTransactionIsolator-DWDbnITQ.mjs";
|
|
2
|
+
export { DatabaseConnection, DatabaseConnectionFn, DatabaseFixtures, ExtendContextFn, ExtendedDatabaseFixtures, FixtureCreators, IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { IsolationLevel, VitestPostgresTransactionIsolator } from "./VitestTransactionIsolator-
|
|
1
|
+
import { IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures } from "./VitestTransactionIsolator-BIaMs4c2.mjs";
|
|
2
2
|
|
|
3
|
-
export { IsolationLevel, VitestPostgresTransactionIsolator };
|
|
3
|
+
export { IsolationLevel, VitestPostgresTransactionIsolator, extendWithFixtures };
|
package/dist/better-auth.cjs
CHANGED
|
@@ -39,16 +39,16 @@ function matchesWhere(record, where) {
|
|
|
39
39
|
matches = recordValue !== value;
|
|
40
40
|
break;
|
|
41
41
|
case "lt":
|
|
42
|
-
matches = recordValue < value;
|
|
42
|
+
matches = value != null && recordValue < value;
|
|
43
43
|
break;
|
|
44
44
|
case "lte":
|
|
45
|
-
matches = recordValue <= value;
|
|
45
|
+
matches = value != null && recordValue <= value;
|
|
46
46
|
break;
|
|
47
47
|
case "gt":
|
|
48
|
-
matches = recordValue > value;
|
|
48
|
+
matches = value != null && recordValue > value;
|
|
49
49
|
break;
|
|
50
50
|
case "gte":
|
|
51
|
-
matches = recordValue >= value;
|
|
51
|
+
matches = value != null && recordValue >= value;
|
|
52
52
|
break;
|
|
53
53
|
case "in":
|
|
54
54
|
matches = Array.isArray(value) && value.includes(recordValue);
|
|
@@ -138,7 +138,7 @@ const memoryAdapter = (config = {}, store = /* @__PURE__ */ new Map()) => {
|
|
|
138
138
|
}
|
|
139
139
|
return null;
|
|
140
140
|
},
|
|
141
|
-
findMany: async ({ where, model, limit, offset, sortBy
|
|
141
|
+
findMany: async ({ where, model, limit, offset, sortBy }) => {
|
|
142
142
|
debugLog("FIND_MANY", {
|
|
143
143
|
model,
|
|
144
144
|
where
|
|
@@ -153,12 +153,9 @@ const memoryAdapter = (config = {}, store = /* @__PURE__ */ new Map()) => {
|
|
|
153
153
|
if (sortBy) results = applySorting(results, sortBy);
|
|
154
154
|
if (offset) results = results.slice(offset);
|
|
155
155
|
if (limit) results = results.slice(0, limit);
|
|
156
|
-
return Promise.all(results.map(
|
|
157
|
-
const transformed = await transformOutput(record, model, select);
|
|
158
|
-
return transformed;
|
|
159
|
-
}));
|
|
156
|
+
return Promise.all(results.map((record) => transformOutput(record, model)));
|
|
160
157
|
},
|
|
161
|
-
update: async ({ where, update, model
|
|
158
|
+
update: async ({ where, update, model }) => {
|
|
162
159
|
debugLog("UPDATE", {
|
|
163
160
|
model,
|
|
164
161
|
where
|
|
@@ -176,7 +173,7 @@ const memoryAdapter = (config = {}, store = /* @__PURE__ */ new Map()) => {
|
|
|
176
173
|
...transformedData
|
|
177
174
|
};
|
|
178
175
|
modelData.set(id, updated);
|
|
179
|
-
return transformOutput(updated, model
|
|
176
|
+
return transformOutput(updated, model);
|
|
180
177
|
}
|
|
181
178
|
return null;
|
|
182
179
|
},
|
package/dist/better-auth.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"better-auth.cjs","names":["initialData?: Record<string, any[]>","data: Map<string, any>","modelName: string","result: Record<string, any[]>","record: any","where?: Where[]","result: boolean | null","records: any[]","sortBy?: SortBy","config: MemoryAdapterConfig","toDelete: string[]"],"sources":["../src/better-auth.ts"],"sourcesContent":["import {\n type DBAdapterDebugLogOption,\n type Where,\n createAdapterFactory,\n} from 'better-auth/adapters';\n\ninterface MemoryAdapterConfig {\n debugLogs?: DBAdapterDebugLogOption;\n usePlural?: boolean;\n initialData?: Record<string, any[]>;\n}\n\nclass MemoryStore {\n constructor(\n initialData?: Record<string, any[]>,\n private readonly data: Map<string, any> = new Map(),\n ) {\n if (initialData) {\n for (const [model, records] of Object.entries(initialData)) {\n const modelData = new Map();\n for (const record of records) {\n modelData.set(record.id, { ...record });\n }\n this.data.set(model, modelData);\n }\n }\n }\n\n getModel(modelName: string): Map<string, any> {\n if (!this.data.has(modelName)) {\n this.data.set(modelName, new Map());\n }\n return this.data.get(modelName)!;\n }\n\n clear() {\n this.data.clear();\n }\n\n getAllData() {\n const result: Record<string, any[]> = {};\n for (const [model, records] of this.data.entries()) {\n result[model] = Array.from(records.values());\n }\n return result;\n }\n}\n\nfunction matchesWhere(record: any, where?: Where[]): boolean {\n if (!where || where.length === 0) return true;\n\n let result: boolean | null = null;\n\n for (const condition of where) {\n const { field, value, operator = 'eq', connector = 'AND' } = condition;\n const recordValue = record[field];\n\n let matches = false;\n\n switch (operator) {\n case 'eq':\n matches = recordValue === value;\n break;\n case 'ne':\n matches = recordValue !== value;\n break;\n case 'lt':\n matches = recordValue < value;\n break;\n case 'lte':\n matches = recordValue <= value;\n break;\n case 'gt':\n matches = recordValue > value;\n break;\n case 'gte':\n matches = recordValue >= value;\n break;\n case 'in':\n matches = Array.isArray(value) && value.includes(recordValue);\n break;\n case 'not_in':\n matches = Array.isArray(value) && !value.includes(recordValue);\n break;\n case 'contains':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.includes(value);\n break;\n case 'starts_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.startsWith(value);\n break;\n case 'ends_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.endsWith(value);\n break;\n default:\n matches = recordValue === value;\n }\n\n // Apply connector logic\n if (result === null) {\n result = matches;\n } else if (connector === 'OR') {\n result = result || matches;\n } else {\n // Default: AND\n result = result && matches;\n }\n }\n\n return result ?? true;\n}\ntype SortBy = {\n field: string;\n direction: 'asc' | 'desc';\n};\n\nfunction applySorting(records: any[], sortBy?: SortBy): any[] {\n if (!sortBy) return records;\n\n const { field, direction } = sortBy;\n\n return records.sort((a, b) => {\n const aVal = a[field];\n const bVal = b[field];\n\n if (aVal === bVal) return 0;\n if (aVal == null) return direction === 'asc' ? -1 : 1;\n if (bVal == null) return direction === 'asc' ? 1 : -1;\n\n const comparison = aVal < bVal ? -1 : 1;\n return direction === 'asc' ? comparison : -comparison;\n });\n}\n\nexport const memoryAdapter = (\n config: MemoryAdapterConfig = {},\n store = new Map(),\n) => {\n const storeInstance = new MemoryStore(config.initialData, store);\n\n const adapterInstance = createAdapterFactory({\n config: {\n adapterId: 'memory-adapter',\n adapterName: 'Memory Adapter',\n usePlural: config.usePlural ?? false,\n debugLogs: config.debugLogs ?? false,\n supportsJSON: true,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: false,\n },\n\n adapter: ({\n debugLog,\n transformInput,\n transformOutput,\n getModelName,\n transformWhereClause,\n }) => ({\n create: async ({ data, model, select }) => {\n debugLog('CREATE', { model, data });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const transformedData = await transformInput(data, model, 'create');\n\n if (!transformedData.id) {\n transformedData.id = crypto.randomUUID();\n }\n\n modelData.set(transformedData.id, { ...transformedData, ...data });\n\n if (data.email_address) {\n modelData.set(transformedData.id, {\n ...transformedData,\n email: data.email_address,\n });\n }\n const created = modelData.get(transformedData.id);\n\n const out = (await transformOutput(created, model, select)) as any;\n\n return out;\n },\n\n findOne: async ({ where, model, select }) => {\n debugLog('FIND_ONE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const record of modelData.values()) {\n if (matchesWhere(record, transformedWhere)) {\n const t = (await transformOutput(record, model, select)) as any;\n\n return t;\n }\n }\n return null;\n },\n\n findMany: async ({ where, model, limit, offset, sortBy, select }) => {\n debugLog('FIND_MANY', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let results = Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, transformedWhere),\n );\n\n if (sortBy) {\n results = applySorting(results, sortBy);\n }\n\n if (offset) {\n results = results.slice(offset);\n }\n if (limit) {\n results = results.slice(0, limit);\n }\n\n return Promise.all(\n results.map(async (record) => {\n const transformed = await transformOutput(record, model, select);\n\n return transformed;\n }),\n );\n },\n\n update: async ({ where, update, model, select }) => {\n debugLog('UPDATE', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n const transformedData = await transformInput(\n update as any,\n model,\n 'update',\n );\n const updated = { ...record, ...transformedData };\n modelData.set(id, updated);\n return transformOutput(updated, model, select) as any;\n }\n }\n return null;\n },\n\n updateMany: async ({ where, update, model }) => {\n debugLog('UPDATE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let count = 0;\n const transformedData = await transformInput(update, model, 'update');\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n modelData.set(id, { ...record, ...transformedData });\n count++;\n }\n }\n return count;\n },\n\n delete: async ({ where, model }) => {\n debugLog('DELETE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n modelData.delete(id);\n return;\n }\n }\n },\n\n deleteMany: async ({ where, model }) => {\n debugLog('DELETE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const toDelete: string[] = [];\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n toDelete.push(id);\n }\n }\n\n toDelete.forEach((id) => modelData.delete(id));\n return toDelete.length;\n },\n\n count: async ({ where, model }) => {\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n return Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, where),\n ).length;\n },\n }),\n });\n\n // Add utility methods to the adapter\n return Object.assign(adapterInstance, {\n clear: () => store.clear(),\n getAllData: () => storeInstance.getAllData(),\n getStore: () => store,\n });\n};\n"],"mappings":";;;;AAYA,IAAM,cAAN,MAAkB;CAChB,YACEA,aACiBC,uBAAyB,IAAI,OAC9C;EADiB;AAEjB,MAAI,YACF,MAAK,MAAM,CAAC,OAAO,QAAQ,IAAI,OAAO,QAAQ,YAAY,EAAE;GAC1D,MAAM,4BAAY,IAAI;AACtB,QAAK,MAAM,UAAU,QACnB,WAAU,IAAI,OAAO,IAAI,EAAE,GAAG,OAAQ,EAAC;AAEzC,QAAK,KAAK,IAAI,OAAO,UAAU;EAChC;CAEJ;CAED,SAASC,WAAqC;AAC5C,OAAK,KAAK,KAAK,IAAI,UAAU,CAC3B,MAAK,KAAK,IAAI,2BAAW,IAAI,MAAM;AAErC,SAAO,KAAK,KAAK,IAAI,UAAU;CAChC;CAED,QAAQ;AACN,OAAK,KAAK,OAAO;CAClB;CAED,aAAa;EACX,MAAMC,SAAgC,CAAE;AACxC,OAAK,MAAM,CAAC,OAAO,QAAQ,IAAI,KAAK,KAAK,SAAS,CAChD,QAAO,SAAS,MAAM,KAAK,QAAQ,QAAQ,CAAC;AAE9C,SAAO;CACR;AACF;AAED,SAAS,aAAaC,QAAaC,OAA0B;AAC3D,MAAK,SAAS,MAAM,WAAW,EAAG,QAAO;CAEzC,IAAIC,SAAy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,CAAC,OAAO,CAAC,WAC5C,aAAa,QAAQ,MAAM,CAC5B,CAAC;GACH;EACF;CACF,EAAC;AAGF,QAAO,OAAO,OAAO,iBAAiB;EACpC,OAAO,MAAM,MAAM,OAAO;EAC1B,YAAY,MAAM,cAAc,YAAY;EAC5C,UAAU,MAAM;CACjB,EAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"better-auth.cjs","names":["initialData?: Record<string, any[]>","data: Map<string, any>","modelName: string","result: Record<string, any[]>","record: any","where?: Where[]","result: boolean | null","records: any[]","sortBy?: SortBy","config: MemoryAdapterConfig","toDelete: string[]"],"sources":["../src/better-auth.ts"],"sourcesContent":["import {\n type DBAdapterDebugLogOption,\n type Where,\n createAdapterFactory,\n} from 'better-auth/adapters';\n\ninterface MemoryAdapterConfig {\n debugLogs?: DBAdapterDebugLogOption;\n usePlural?: boolean;\n initialData?: Record<string, any[]>;\n}\n\nclass MemoryStore {\n constructor(\n initialData?: Record<string, any[]>,\n private readonly data: Map<string, any> = new Map(),\n ) {\n if (initialData) {\n for (const [model, records] of Object.entries(initialData)) {\n const modelData = new Map();\n for (const record of records) {\n modelData.set(record.id, { ...record });\n }\n this.data.set(model, modelData);\n }\n }\n }\n\n getModel(modelName: string): Map<string, any> {\n if (!this.data.has(modelName)) {\n this.data.set(modelName, new Map());\n }\n return this.data.get(modelName)!;\n }\n\n clear() {\n this.data.clear();\n }\n\n getAllData() {\n const result: Record<string, any[]> = {};\n for (const [model, records] of this.data.entries()) {\n result[model] = Array.from(records.values());\n }\n return result;\n }\n}\n\nfunction matchesWhere(record: any, where?: Where[]): boolean {\n if (!where || where.length === 0) return true;\n\n let result: boolean | null = null;\n\n for (const condition of where) {\n const { field, value, operator = 'eq', connector = 'AND' } = condition;\n const recordValue = record[field];\n\n let matches = false;\n\n switch (operator) {\n case 'eq':\n matches = recordValue === value;\n break;\n case 'ne':\n matches = recordValue !== value;\n break;\n case 'lt':\n matches = value != null && recordValue < value;\n break;\n case 'lte':\n matches = value != null && recordValue <= value;\n break;\n case 'gt':\n matches = value != null && recordValue > value;\n break;\n case 'gte':\n matches = value != null && recordValue >= value;\n break;\n case 'in':\n matches =\n Array.isArray(value) && (value as unknown[]).includes(recordValue);\n break;\n case 'not_in':\n matches =\n Array.isArray(value) && !(value as unknown[]).includes(recordValue);\n break;\n case 'contains':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.includes(value);\n break;\n case 'starts_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.startsWith(value);\n break;\n case 'ends_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.endsWith(value);\n break;\n default:\n matches = recordValue === value;\n }\n\n // Apply connector logic\n if (result === null) {\n result = matches;\n } else if (connector === 'OR') {\n result = result || matches;\n } else {\n // Default: AND\n result = result && matches;\n }\n }\n\n return result ?? true;\n}\ntype SortBy = {\n field: string;\n direction: 'asc' | 'desc';\n};\n\nfunction applySorting(records: any[], sortBy?: SortBy): any[] {\n if (!sortBy) return records;\n\n const { field, direction } = sortBy;\n\n return records.sort((a, b) => {\n const aVal = a[field];\n const bVal = b[field];\n\n if (aVal === bVal) return 0;\n if (aVal == null) return direction === 'asc' ? -1 : 1;\n if (bVal == null) return direction === 'asc' ? 1 : -1;\n\n const comparison = aVal < bVal ? -1 : 1;\n return direction === 'asc' ? comparison : -comparison;\n });\n}\n\nexport const memoryAdapter = (\n config: MemoryAdapterConfig = {},\n store = new Map(),\n) => {\n const storeInstance = new MemoryStore(config.initialData, store);\n\n const adapterInstance = createAdapterFactory({\n config: {\n adapterId: 'memory-adapter',\n adapterName: 'Memory Adapter',\n usePlural: config.usePlural ?? false,\n debugLogs: config.debugLogs ?? false,\n supportsJSON: true,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: false,\n },\n\n adapter: ({\n debugLog,\n transformInput,\n transformOutput,\n getModelName,\n transformWhereClause,\n }) => ({\n create: async ({ data, model, select }) => {\n debugLog('CREATE', { model, data });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const transformedData = await transformInput(data, model, 'create');\n\n if (!transformedData.id) {\n transformedData.id = crypto.randomUUID();\n }\n\n modelData.set(transformedData.id, { ...transformedData, ...data });\n\n if (data.email_address) {\n modelData.set(transformedData.id, {\n ...transformedData,\n email: data.email_address,\n });\n }\n const created = modelData.get(transformedData.id);\n\n const out = (await transformOutput(created, model, select)) as any;\n\n return out;\n },\n\n findOne: async ({ where, model, select }) => {\n debugLog('FIND_ONE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const record of modelData.values()) {\n if (matchesWhere(record, transformedWhere)) {\n const t = (await transformOutput(record, model, select)) as any;\n\n return t;\n }\n }\n return null;\n },\n\n findMany: async ({ where, model, limit, offset, sortBy }) => {\n debugLog('FIND_MANY', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let results = Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, transformedWhere),\n );\n\n if (sortBy) {\n results = applySorting(results, sortBy);\n }\n\n if (offset) {\n results = results.slice(offset);\n }\n if (limit) {\n results = results.slice(0, limit);\n }\n\n return Promise.all(\n results.map((record) => transformOutput(record, model)),\n ) as any;\n },\n\n update: async ({ where, update, model }) => {\n debugLog('UPDATE', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n const transformedData = await transformInput(\n update as any,\n model,\n 'update',\n );\n const updated = { ...record, ...transformedData };\n modelData.set(id, updated);\n return transformOutput(updated, model) as any;\n }\n }\n return null;\n },\n\n updateMany: async ({ where, update, model }) => {\n debugLog('UPDATE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let count = 0;\n const transformedData = await transformInput(update, model, 'update');\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n modelData.set(id, { ...record, ...transformedData });\n count++;\n }\n }\n return count;\n },\n\n delete: async ({ where, model }) => {\n debugLog('DELETE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n modelData.delete(id);\n return;\n }\n }\n },\n\n deleteMany: async ({ where, model }) => {\n debugLog('DELETE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const toDelete: string[] = [];\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n toDelete.push(id);\n }\n }\n\n toDelete.forEach((id) => modelData.delete(id));\n return toDelete.length;\n },\n\n count: async ({ where, model }) => {\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n return Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, where),\n ).length;\n },\n }),\n });\n\n // Add utility methods to the adapter\n return Object.assign(adapterInstance, {\n clear: () => store.clear(),\n getAllData: () => storeInstance.getAllData(),\n getStore: () => store,\n });\n};\n"],"mappings":";;;;AAYA,IAAM,cAAN,MAAkB;CAChB,YACEA,aACiBC,uBAAyB,IAAI,OAC9C;EADiB;AAEjB,MAAI,YACF,MAAK,MAAM,CAAC,OAAO,QAAQ,IAAI,OAAO,QAAQ,YAAY,EAAE;GAC1D,MAAM,4BAAY,IAAI;AACtB,QAAK,MAAM,UAAU,QACnB,WAAU,IAAI,OAAO,IAAI,EAAE,GAAG,OAAQ,EAAC;AAEzC,QAAK,KAAK,IAAI,OAAO,UAAU;EAChC;CAEJ;CAED,SAASC,WAAqC;AAC5C,OAAK,KAAK,KAAK,IAAI,UAAU,CAC3B,MAAK,KAAK,IAAI,2BAAW,IAAI,MAAM;AAErC,SAAO,KAAK,KAAK,IAAI,UAAU;CAChC;C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,UAAU,SAAS,CAC5C,KAAI,aAAa,QAAQ,MAAM,CAC7B,UAAS,KAAK,GAAG;AAIrB,aAAS,QAAQ,CAAC,OAAO,UAAU,OAAO,GAAG,CAAC;AAC9C,WAAO,SAAS;GACjB;GAED,OAAO,OAAO,EAAE,OAAO,OAAO,KAAK;IACjC,MAAM,YAAY,aAAa,MAAM;IACrC,MAAM,YAAY,cAAc,SAAS,UAAU;AAEnD,WAAO,MAAM,KAAK,UAAU,QAAQ,CAAC,CAAC,OAAO,CAAC,WAC5C,aAAa,QAAQ,MAAM,CAC5B,CAAC;GACH;EACF;CACF,EAAC;AAGF,QAAO,OAAO,OAAO,iBAAiB;EACpC,OAAO,MAAM,MAAM,OAAO;EAC1B,YAAY,MAAM,cAAc,YAAY;EAC5C,UAAU,MAAM;CACjB,EAAC;AACH"}
|
package/dist/better-auth.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as better_auth_adapters0 from "better-auth/adapters";
|
|
2
2
|
import { DBAdapterDebugLogOption } from "better-auth/adapters";
|
|
3
3
|
|
|
4
4
|
//#region src/better-auth.d.ts
|
|
@@ -7,7 +7,7 @@ interface MemoryAdapterConfig {
|
|
|
7
7
|
usePlural?: boolean;
|
|
8
8
|
initialData?: Record<string, any[]>;
|
|
9
9
|
}
|
|
10
|
-
declare const memoryAdapter: (config?: MemoryAdapterConfig, store?: Map<any, any>) =>
|
|
10
|
+
declare const memoryAdapter: (config?: MemoryAdapterConfig, store?: Map<any, any>) => better_auth_adapters0.AdapterFactory & {
|
|
11
11
|
clear: () => void;
|
|
12
12
|
getAllData: () => Record<string, any[]>;
|
|
13
13
|
getStore: () => Map<any, any>;
|
package/dist/better-auth.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as better_auth_adapters0 from "better-auth/adapters";
|
|
2
2
|
import { DBAdapterDebugLogOption } from "better-auth/adapters";
|
|
3
3
|
|
|
4
4
|
//#region src/better-auth.d.ts
|
|
@@ -7,7 +7,7 @@ interface MemoryAdapterConfig {
|
|
|
7
7
|
usePlural?: boolean;
|
|
8
8
|
initialData?: Record<string, any[]>;
|
|
9
9
|
}
|
|
10
|
-
declare const memoryAdapter: (config?: MemoryAdapterConfig, store?: Map<any, any>) =>
|
|
10
|
+
declare const memoryAdapter: (config?: MemoryAdapterConfig, store?: Map<any, any>) => better_auth_adapters0.AdapterFactory & {
|
|
11
11
|
clear: () => void;
|
|
12
12
|
getAllData: () => Record<string, any[]>;
|
|
13
13
|
getStore: () => Map<any, any>;
|
package/dist/better-auth.mjs
CHANGED
|
@@ -38,16 +38,16 @@ function matchesWhere(record, where) {
|
|
|
38
38
|
matches = recordValue !== value;
|
|
39
39
|
break;
|
|
40
40
|
case "lt":
|
|
41
|
-
matches = recordValue < value;
|
|
41
|
+
matches = value != null && recordValue < value;
|
|
42
42
|
break;
|
|
43
43
|
case "lte":
|
|
44
|
-
matches = recordValue <= value;
|
|
44
|
+
matches = value != null && recordValue <= value;
|
|
45
45
|
break;
|
|
46
46
|
case "gt":
|
|
47
|
-
matches = recordValue > value;
|
|
47
|
+
matches = value != null && recordValue > value;
|
|
48
48
|
break;
|
|
49
49
|
case "gte":
|
|
50
|
-
matches = recordValue >= value;
|
|
50
|
+
matches = value != null && recordValue >= value;
|
|
51
51
|
break;
|
|
52
52
|
case "in":
|
|
53
53
|
matches = Array.isArray(value) && value.includes(recordValue);
|
|
@@ -137,7 +137,7 @@ const memoryAdapter = (config = {}, store = /* @__PURE__ */ new Map()) => {
|
|
|
137
137
|
}
|
|
138
138
|
return null;
|
|
139
139
|
},
|
|
140
|
-
findMany: async ({ where, model, limit, offset, sortBy
|
|
140
|
+
findMany: async ({ where, model, limit, offset, sortBy }) => {
|
|
141
141
|
debugLog("FIND_MANY", {
|
|
142
142
|
model,
|
|
143
143
|
where
|
|
@@ -152,12 +152,9 @@ const memoryAdapter = (config = {}, store = /* @__PURE__ */ new Map()) => {
|
|
|
152
152
|
if (sortBy) results = applySorting(results, sortBy);
|
|
153
153
|
if (offset) results = results.slice(offset);
|
|
154
154
|
if (limit) results = results.slice(0, limit);
|
|
155
|
-
return Promise.all(results.map(
|
|
156
|
-
const transformed = await transformOutput(record, model, select);
|
|
157
|
-
return transformed;
|
|
158
|
-
}));
|
|
155
|
+
return Promise.all(results.map((record) => transformOutput(record, model)));
|
|
159
156
|
},
|
|
160
|
-
update: async ({ where, update, model
|
|
157
|
+
update: async ({ where, update, model }) => {
|
|
161
158
|
debugLog("UPDATE", {
|
|
162
159
|
model,
|
|
163
160
|
where
|
|
@@ -175,7 +172,7 @@ const memoryAdapter = (config = {}, store = /* @__PURE__ */ new Map()) => {
|
|
|
175
172
|
...transformedData
|
|
176
173
|
};
|
|
177
174
|
modelData.set(id, updated);
|
|
178
|
-
return transformOutput(updated, model
|
|
175
|
+
return transformOutput(updated, model);
|
|
179
176
|
}
|
|
180
177
|
return null;
|
|
181
178
|
},
|
package/dist/better-auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"better-auth.mjs","names":["initialData?: Record<string, any[]>","data: Map<string, any>","modelName: string","result: Record<string, any[]>","record: any","where?: Where[]","result: boolean | null","records: any[]","sortBy?: SortBy","config: MemoryAdapterConfig","toDelete: string[]"],"sources":["../src/better-auth.ts"],"sourcesContent":["import {\n type DBAdapterDebugLogOption,\n type Where,\n createAdapterFactory,\n} from 'better-auth/adapters';\n\ninterface MemoryAdapterConfig {\n debugLogs?: DBAdapterDebugLogOption;\n usePlural?: boolean;\n initialData?: Record<string, any[]>;\n}\n\nclass MemoryStore {\n constructor(\n initialData?: Record<string, any[]>,\n private readonly data: Map<string, any> = new Map(),\n ) {\n if (initialData) {\n for (const [model, records] of Object.entries(initialData)) {\n const modelData = new Map();\n for (const record of records) {\n modelData.set(record.id, { ...record });\n }\n this.data.set(model, modelData);\n }\n }\n }\n\n getModel(modelName: string): Map<string, any> {\n if (!this.data.has(modelName)) {\n this.data.set(modelName, new Map());\n }\n return this.data.get(modelName)!;\n }\n\n clear() {\n this.data.clear();\n }\n\n getAllData() {\n const result: Record<string, any[]> = {};\n for (const [model, records] of this.data.entries()) {\n result[model] = Array.from(records.values());\n }\n return result;\n }\n}\n\nfunction matchesWhere(record: any, where?: Where[]): boolean {\n if (!where || where.length === 0) return true;\n\n let result: boolean | null = null;\n\n for (const condition of where) {\n const { field, value, operator = 'eq', connector = 'AND' } = condition;\n const recordValue = record[field];\n\n let matches = false;\n\n switch (operator) {\n case 'eq':\n matches = recordValue === value;\n break;\n case 'ne':\n matches = recordValue !== value;\n break;\n case 'lt':\n matches = recordValue < value;\n break;\n case 'lte':\n matches = recordValue <= value;\n break;\n case 'gt':\n matches = recordValue > value;\n break;\n case 'gte':\n matches = recordValue >= value;\n break;\n case 'in':\n matches = Array.isArray(value) && value.includes(recordValue);\n break;\n case 'not_in':\n matches = Array.isArray(value) && !value.includes(recordValue);\n break;\n case 'contains':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.includes(value);\n break;\n case 'starts_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.startsWith(value);\n break;\n case 'ends_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.endsWith(value);\n break;\n default:\n matches = recordValue === value;\n }\n\n // Apply connector logic\n if (result === null) {\n result = matches;\n } else if (connector === 'OR') {\n result = result || matches;\n } else {\n // Default: AND\n result = result && matches;\n }\n }\n\n return result ?? true;\n}\ntype SortBy = {\n field: string;\n direction: 'asc' | 'desc';\n};\n\nfunction applySorting(records: any[], sortBy?: SortBy): any[] {\n if (!sortBy) return records;\n\n const { field, direction } = sortBy;\n\n return records.sort((a, b) => {\n const aVal = a[field];\n const bVal = b[field];\n\n if (aVal === bVal) return 0;\n if (aVal == null) return direction === 'asc' ? -1 : 1;\n if (bVal == null) return direction === 'asc' ? 1 : -1;\n\n const comparison = aVal < bVal ? -1 : 1;\n return direction === 'asc' ? comparison : -comparison;\n });\n}\n\nexport const memoryAdapter = (\n config: MemoryAdapterConfig = {},\n store = new Map(),\n) => {\n const storeInstance = new MemoryStore(config.initialData, store);\n\n const adapterInstance = createAdapterFactory({\n config: {\n adapterId: 'memory-adapter',\n adapterName: 'Memory Adapter',\n usePlural: config.usePlural ?? false,\n debugLogs: config.debugLogs ?? false,\n supportsJSON: true,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: false,\n },\n\n adapter: ({\n debugLog,\n transformInput,\n transformOutput,\n getModelName,\n transformWhereClause,\n }) => ({\n create: async ({ data, model, select }) => {\n debugLog('CREATE', { model, data });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const transformedData = await transformInput(data, model, 'create');\n\n if (!transformedData.id) {\n transformedData.id = crypto.randomUUID();\n }\n\n modelData.set(transformedData.id, { ...transformedData, ...data });\n\n if (data.email_address) {\n modelData.set(transformedData.id, {\n ...transformedData,\n email: data.email_address,\n });\n }\n const created = modelData.get(transformedData.id);\n\n const out = (await transformOutput(created, model, select)) as any;\n\n return out;\n },\n\n findOne: async ({ where, model, select }) => {\n debugLog('FIND_ONE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const record of modelData.values()) {\n if (matchesWhere(record, transformedWhere)) {\n const t = (await transformOutput(record, model, select)) as any;\n\n return t;\n }\n }\n return null;\n },\n\n findMany: async ({ where, model, limit, offset, sortBy, select }) => {\n debugLog('FIND_MANY', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let results = Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, transformedWhere),\n );\n\n if (sortBy) {\n results = applySorting(results, sortBy);\n }\n\n if (offset) {\n results = results.slice(offset);\n }\n if (limit) {\n results = results.slice(0, limit);\n }\n\n return Promise.all(\n results.map(async (record) => {\n const transformed = await transformOutput(record, model, select);\n\n return transformed;\n }),\n );\n },\n\n update: async ({ where, update, model, select }) => {\n debugLog('UPDATE', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n const transformedData = await transformInput(\n update as any,\n model,\n 'update',\n );\n const updated = { ...record, ...transformedData };\n modelData.set(id, updated);\n return transformOutput(updated, model, select) as any;\n }\n }\n return null;\n },\n\n updateMany: async ({ where, update, model }) => {\n debugLog('UPDATE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let count = 0;\n const transformedData = await transformInput(update, model, 'update');\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n modelData.set(id, { ...record, ...transformedData });\n count++;\n }\n }\n return count;\n },\n\n delete: async ({ where, model }) => {\n debugLog('DELETE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n modelData.delete(id);\n return;\n }\n }\n },\n\n deleteMany: async ({ where, model }) => {\n debugLog('DELETE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const toDelete: string[] = [];\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n toDelete.push(id);\n }\n }\n\n toDelete.forEach((id) => modelData.delete(id));\n return toDelete.length;\n },\n\n count: async ({ where, model }) => {\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n return Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, where),\n ).length;\n },\n }),\n });\n\n // Add utility methods to the adapter\n return Object.assign(adapterInstance, {\n clear: () => store.clear(),\n getAllData: () => storeInstance.getAllData(),\n getStore: () => store,\n });\n};\n"],"mappings":";;;AAYA,IAAM,cAAN,MA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IAAO,EAAC;IACpC,MAAM,YAAY,aAAa,MAAM;IACrC,MAAM,YAAY,cAAc,SAAS,UAAU;AAEnD,SAAK,MAAM,CAAC,IAAI,OAAO,IAAI,UAAU,SAAS,CAC5C,KAAI,aAAa,QAAQ,MAAM,EAAE;AAC/B,eAAU,OAAO,GAAG;AACpB;IACD;GAEJ;GAED,YAAY,OAAO,EAAE,OAAO,OAAO,KAAK;AACtC,aAAS,eAAe;KAAE;KAAO;IAAO,EAAC;IACzC,MAAM,YAAY,aAAa,MAAM;IACrC,MAAM,YAAY,cAAc,SAAS,UAAU;IAEnD,MAAMC,WAAqB,CAAE;AAC7B,SAAK,MAAM,CAAC,IAAI,OAAO,IAAI,UAAU,SAAS,CAC5C,KAAI,aAAa,QAAQ,MAAM,CAC7B,UAAS,KAAK,GAAG;AAIrB,aAAS,QAAQ,CAAC,OAAO,UAAU,OAAO,GAAG,CAAC;AAC9C,WAAO,SAAS;GACjB;GAED,OAAO,OAAO,EAAE,OAAO,OAAO,KAAK;IACjC,MAAM,YAAY,aAAa,MAAM;IACrC,MAAM,YAAY,cAAc,SAAS,UAAU;AAEnD,WAAO,MAAM,KAAK,UAAU,QAAQ,CAAC,CAAC,OAAO,CAAC,WAC5C,aAAa,QAAQ,MAAM,CAC5B,CAAC;GACH;EACF;CACF,EAAC;AAGF,QAAO,OAAO,OAAO,iBAAiB;EACpC,OAAO,MAAM,MAAM,OAAO;EAC1B,YAAY,MAAM,cAAc,YAAY;EAC5C,UAAU,MAAM;CACjB,EAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"better-auth.mjs","names":["initialData?: Record<string, any[]>","data: Map<string, any>","modelName: string","result: Record<string, any[]>","record: any","where?: Where[]","result: boolean | null","records: any[]","sortBy?: SortBy","config: MemoryAdapterConfig","toDelete: string[]"],"sources":["../src/better-auth.ts"],"sourcesContent":["import {\n type DBAdapterDebugLogOption,\n type Where,\n createAdapterFactory,\n} from 'better-auth/adapters';\n\ninterface MemoryAdapterConfig {\n debugLogs?: DBAdapterDebugLogOption;\n usePlural?: boolean;\n initialData?: Record<string, any[]>;\n}\n\nclass MemoryStore {\n constructor(\n initialData?: Record<string, any[]>,\n private readonly data: Map<string, any> = new Map(),\n ) {\n if (initialData) {\n for (const [model, records] of Object.entries(initialData)) {\n const modelData = new Map();\n for (const record of records) {\n modelData.set(record.id, { ...record });\n }\n this.data.set(model, modelData);\n }\n }\n }\n\n getModel(modelName: string): Map<string, any> {\n if (!this.data.has(modelName)) {\n this.data.set(modelName, new Map());\n }\n return this.data.get(modelName)!;\n }\n\n clear() {\n this.data.clear();\n }\n\n getAllData() {\n const result: Record<string, any[]> = {};\n for (const [model, records] of this.data.entries()) {\n result[model] = Array.from(records.values());\n }\n return result;\n }\n}\n\nfunction matchesWhere(record: any, where?: Where[]): boolean {\n if (!where || where.length === 0) return true;\n\n let result: boolean | null = null;\n\n for (const condition of where) {\n const { field, value, operator = 'eq', connector = 'AND' } = condition;\n const recordValue = record[field];\n\n let matches = false;\n\n switch (operator) {\n case 'eq':\n matches = recordValue === value;\n break;\n case 'ne':\n matches = recordValue !== value;\n break;\n case 'lt':\n matches = value != null && recordValue < value;\n break;\n case 'lte':\n matches = value != null && recordValue <= value;\n break;\n case 'gt':\n matches = value != null && recordValue > value;\n break;\n case 'gte':\n matches = value != null && recordValue >= value;\n break;\n case 'in':\n matches =\n Array.isArray(value) && (value as unknown[]).includes(recordValue);\n break;\n case 'not_in':\n matches =\n Array.isArray(value) && !(value as unknown[]).includes(recordValue);\n break;\n case 'contains':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.includes(value);\n break;\n case 'starts_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.startsWith(value);\n break;\n case 'ends_with':\n matches =\n typeof recordValue === 'string' &&\n typeof value === 'string' &&\n recordValue.endsWith(value);\n break;\n default:\n matches = recordValue === value;\n }\n\n // Apply connector logic\n if (result === null) {\n result = matches;\n } else if (connector === 'OR') {\n result = result || matches;\n } else {\n // Default: AND\n result = result && matches;\n }\n }\n\n return result ?? true;\n}\ntype SortBy = {\n field: string;\n direction: 'asc' | 'desc';\n};\n\nfunction applySorting(records: any[], sortBy?: SortBy): any[] {\n if (!sortBy) return records;\n\n const { field, direction } = sortBy;\n\n return records.sort((a, b) => {\n const aVal = a[field];\n const bVal = b[field];\n\n if (aVal === bVal) return 0;\n if (aVal == null) return direction === 'asc' ? -1 : 1;\n if (bVal == null) return direction === 'asc' ? 1 : -1;\n\n const comparison = aVal < bVal ? -1 : 1;\n return direction === 'asc' ? comparison : -comparison;\n });\n}\n\nexport const memoryAdapter = (\n config: MemoryAdapterConfig = {},\n store = new Map(),\n) => {\n const storeInstance = new MemoryStore(config.initialData, store);\n\n const adapterInstance = createAdapterFactory({\n config: {\n adapterId: 'memory-adapter',\n adapterName: 'Memory Adapter',\n usePlural: config.usePlural ?? false,\n debugLogs: config.debugLogs ?? false,\n supportsJSON: true,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: false,\n },\n\n adapter: ({\n debugLog,\n transformInput,\n transformOutput,\n getModelName,\n transformWhereClause,\n }) => ({\n create: async ({ data, model, select }) => {\n debugLog('CREATE', { model, data });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const transformedData = await transformInput(data, model, 'create');\n\n if (!transformedData.id) {\n transformedData.id = crypto.randomUUID();\n }\n\n modelData.set(transformedData.id, { ...transformedData, ...data });\n\n if (data.email_address) {\n modelData.set(transformedData.id, {\n ...transformedData,\n email: data.email_address,\n });\n }\n const created = modelData.get(transformedData.id);\n\n const out = (await transformOutput(created, model, select)) as any;\n\n return out;\n },\n\n findOne: async ({ where, model, select }) => {\n debugLog('FIND_ONE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const record of modelData.values()) {\n if (matchesWhere(record, transformedWhere)) {\n const t = (await transformOutput(record, model, select)) as any;\n\n return t;\n }\n }\n return null;\n },\n\n findMany: async ({ where, model, limit, offset, sortBy }) => {\n debugLog('FIND_MANY', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let results = Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, transformedWhere),\n );\n\n if (sortBy) {\n results = applySorting(results, sortBy);\n }\n\n if (offset) {\n results = results.slice(offset);\n }\n if (limit) {\n results = results.slice(0, limit);\n }\n\n return Promise.all(\n results.map((record) => transformOutput(record, model)),\n ) as any;\n },\n\n update: async ({ where, update, model }) => {\n debugLog('UPDATE', { model, where });\n\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n const transformedData = await transformInput(\n update as any,\n model,\n 'update',\n );\n const updated = { ...record, ...transformedData };\n modelData.set(id, updated);\n return transformOutput(updated, model) as any;\n }\n }\n return null;\n },\n\n updateMany: async ({ where, update, model }) => {\n debugLog('UPDATE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n const transformedWhere = transformWhereClause({ model, where });\n\n let count = 0;\n const transformedData = await transformInput(update, model, 'update');\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, transformedWhere)) {\n modelData.set(id, { ...record, ...transformedData });\n count++;\n }\n }\n return count;\n },\n\n delete: async ({ where, model }) => {\n debugLog('DELETE', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n modelData.delete(id);\n return;\n }\n }\n },\n\n deleteMany: async ({ where, model }) => {\n debugLog('DELETE_MANY', { model, where });\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n const toDelete: string[] = [];\n for (const [id, record] of modelData.entries()) {\n if (matchesWhere(record, where)) {\n toDelete.push(id);\n }\n }\n\n toDelete.forEach((id) => modelData.delete(id));\n return toDelete.length;\n },\n\n count: async ({ where, model }) => {\n const modelName = getModelName(model);\n const modelData = storeInstance.getModel(modelName);\n\n return Array.from(modelData.values()).filter((record) =>\n matchesWhere(record, where),\n ).length;\n },\n }),\n });\n\n // Add utility methods to the adapter\n return Object.assign(adapterInstance, {\n clear: () => store.clear(),\n getAllData: () => storeInstance.getAllData(),\n getStore: () => store,\n });\n};\n"],"mappings":";;;AAYA,IAAM,cAAN,MAAkB;CAChB,YACEA,aACiBC,uBAAyB,IAAI,OAC9C;EADiB;AAEjB,MAAI,YACF,MAAK,MAAM,CAAC,OAAO,QAAQ,IAAI,OAAO,QAAQ,YAAY,EAAE;GAC1D,MAAM,4BAAY,IAAI;AACtB,QAAK,MAAM,UAAU,QACnB,WAAU,IAAI,OAAO,IAAI,EAAE,GAAG,OAAQ,EAAC;AAEzC,QAAK,KAAK,IAAI,OAAO,UAAU;EAChC;CAEJ;CAED,SAASC,WAAqC;AAC5C,OAAK,KAAK,KAAK,IAAI,UAAU,CAC3B,MAAK,KAAK,IAAI,2BAAW,IAAI,MAAM;AAErC,SAAO,KAAK,KAAK,IAAI,UAAU;CAChC;CAED,QAAQ;AACN,OAAK,KAAK,OAAO;CAClB;CAED,aAAa;EACX,MAAMC,SAAgC,CAAE;AACxC,OAAK,MAAM,CAAC,OAAO,QAAQ,IAAI,KAAK,KAAK,SAAS,CAChD,QAAO,SAAS,MAAM,KAAK,QAAQ,QAAQ,CAAC;AAE9C,SAAO;CACR;AACF;AAED,SAAS,aAAaC,QAAaC,OAA0B;AAC3D,MAAK,SAAS,MAAM,WAAW,EAAG,QAAO;CAEzC,IAAIC,SAAyB;AAE7B,MAAK,MAAM,aAAa,OAAO;EAC7B,MAAM,EAAE,OAAO,OAAO,WAAW,MAAM,YAAY,OAAO,GAAG;EAC7D,MAAM,cAAc,OAAO;EAE3B,IAAI,UAAU;AAEd,UAAQ,UAAR;GACE,KAAK;AACH,cAAU,gBAAgB;A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CACjB,EAAC;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as vitest6 from "vitest";
|
|
2
2
|
|
|
3
3
|
//#region src/os/directory.d.ts
|
|
4
|
-
declare const itWithDir:
|
|
4
|
+
declare const itWithDir: vitest6.TestAPI<{
|
|
5
5
|
dir: string;
|
|
6
6
|
}>;
|
|
7
7
|
interface DirectoryFixtures {
|
|
@@ -9,4 +9,4 @@ interface DirectoryFixtures {
|
|
|
9
9
|
}
|
|
10
10
|
//#endregion
|
|
11
11
|
export { DirectoryFixtures, itWithDir };
|
|
12
|
-
//# sourceMappingURL=directory-
|
|
12
|
+
//# sourceMappingURL=directory-BXavAeJZ.d.mts.map
|