@augment-vir/node 31.41.0 → 31.42.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.
@@ -1,252 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-deprecated */
2
-
3
- import {assert, check} from '@augment-vir/assert';
4
- import {
5
- type AnyObject,
6
- arrayToObject,
7
- awaitedForEach,
8
- type BasePrismaClient,
9
- type BaseTypeMap,
10
- ensureErrorAndPrependMessage,
11
- filterMap,
12
- type FirstLetterLowercase,
13
- getObjectTypedEntries,
14
- getObjectTypedValues,
15
- mergeDefinedProperties,
16
- omitObjectKeys,
17
- type PartialWithUndefined,
18
- type PrismaAllModelsCreate,
19
- type PrismaBasicModel,
20
- prismaModelCreateExclude,
21
- prismaModelCreateOmitId,
22
- type PrismaModelName,
23
- setFirstLetterCasing,
24
- StringCase,
25
- } from '@augment-vir/common';
26
- import {type IsAny} from 'type-fest';
27
-
28
- /**
29
- * Params for `prisma.client.addData()`. This is similar to {@link PrismaAllModelsCreate} but allows
30
- * an array of {@link PrismaAllModelsCreate} for sequential data creation.
31
- *
32
- * @deprecated Use the `prisma-vir` package instead.
33
- * @category Prisma : Node
34
- * @category Package : @augment-vir/node
35
- * @example
36
- *
37
- * ```ts
38
- * import {PrismaAddModelData} from '@augment-vir/common';
39
- * import {type PrismaClient} from '@prisma/client';
40
- *
41
- * const mockData: PrismaAddModelData<PrismaClient> = [
42
- * {
43
- * user: {
44
- * mockUser1: {
45
- * first_name: 'one',
46
- * id: 123,
47
- * // etc.
48
- * },
49
- * mockUser2: {
50
- * first_name: 'two',
51
- * id: 124,
52
- * authRole: 'user',
53
- * // etc.
54
- * },
55
- * },
56
- * },
57
- * {
58
- * region: [
59
- * {
60
- * id: 1,
61
- * name: 'North America',
62
- * // etc.
63
- * },
64
- * {
65
- * id: 2,
66
- * name: 'Europe',
67
- * // etc.
68
- * },
69
- * ],
70
- * },
71
- * ];
72
- * ```
73
- *
74
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
75
- */
76
- export type PrismaAddDataData<PrismaClient extends BasePrismaClient, TypeMap extends BaseTypeMap> =
77
- | Readonly<PrismaAllModelsCreate<PrismaClient, TypeMap>>
78
- | ReadonlyArray<Readonly<PrismaAllModelsCreate<PrismaClient, TypeMap>>>;
79
-
80
- export async function addData<
81
- const PrismaClient extends BasePrismaClient,
82
- const TypeMap extends BaseTypeMap,
83
- >(
84
- prismaClient: Readonly<PrismaClient>,
85
- data: IsAny<PrismaClient> extends true ? any : PrismaAddDataData<PrismaClient, TypeMap>,
86
- ): Promise<void> {
87
- const dataArray: Record<string, AnyObject>[] = (check.isArray(data) ? data : [data]) as Record<
88
- string,
89
- AnyObject
90
- >[];
91
-
92
- await awaitedForEach(dataArray, async (dataEntry) => {
93
- await addModelDataObject(prismaClient, dataEntry);
94
- });
95
- }
96
-
97
- async function addModelDataObject(
98
- prismaClient: Readonly<BasePrismaClient>,
99
- data: Record<string, AnyObject>,
100
- ) {
101
- /** Add the mock data to the mock prisma client. */
102
- await awaitedForEach(
103
- getObjectTypedEntries(data),
104
- async ([
105
- modelName,
106
- mockData,
107
- ]) => {
108
- /**
109
- * This type is dumbed down to just `AnyObject[]` because the union of all possible
110
- * model data is just way too big (and not helpful as the inputs to this function are
111
- * already type guarded).
112
- */
113
- const mockModelInstances: AnyObject[] = Array.isArray(mockData)
114
- ? mockData
115
- : getObjectTypedValues(mockData);
116
-
117
- const modelApi: AnyObject | undefined =
118
- prismaClient[setFirstLetterCasing(modelName, StringCase.Lower)];
119
-
120
- assert.isDefined(modelApi, `No PrismaClient API found for model '${modelName}'`);
121
-
122
- try {
123
- const allData = filterMap(
124
- mockModelInstances,
125
- (entry) => {
126
- return entry;
127
- },
128
- (mapped, modelEntry) => !modelEntry[prismaModelCreateExclude],
129
- );
130
-
131
- await awaitedForEach(allData, async (modelEntry) => {
132
- if (modelEntry[prismaModelCreateOmitId]) {
133
- modelEntry = omitObjectKeys<AnyObject, PropertyKey>(modelEntry, ['id']);
134
- }
135
-
136
- await modelApi.create({
137
- data: modelEntry,
138
- });
139
- });
140
- } catch (error) {
141
- throw ensureErrorAndPrependMessage(
142
- error,
143
- `Failed to create many '${modelName}' entries.\n\n${JSON.stringify(mockModelInstances, null, 4)}\n\n`,
144
- );
145
- }
146
- },
147
- );
148
- }
149
-
150
- const prismockKeys = [
151
- 'getData',
152
- 'setData',
153
- ];
154
-
155
- /** These are not the real model names, they are the names on the PrismaClient (which are lowercase). */
156
- export function getAllPrismaModelKeys(prismaClient: BasePrismaClient): string[] {
157
- return Object.keys(prismaClient)
158
- .filter(
159
- (key) =>
160
- !key.startsWith('$') &&
161
- !key.startsWith('_') &&
162
- !prismockKeys.includes(key) &&
163
- key !== 'constructor',
164
- )
165
- .sort();
166
- }
167
-
168
- /**
169
- * Options for `prisma.client.dumpData`.
170
- *
171
- * @deprecated Use the `prisma-vir` package instead.
172
- * @category Prisma : Node
173
- * @category Package : @augment-vir/node
174
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
175
- */
176
- export type PrismaDataDumpOptions = {
177
- /**
178
- * The max number of entries to load per model. Set to `0` to remove this limit altogether
179
- * (which could be _very_ expensive for your database).
180
- *
181
- * @default 100
182
- */
183
- limit: number;
184
- /**
185
- * Strings to omit from the dumped data. For testability, omitting date or UUID id fields is a
186
- * common practice.
187
- */
188
- omitFields: string[];
189
- };
190
-
191
- const defaultPrismaDumpDataOptions: PrismaDataDumpOptions = {
192
- limit: 100,
193
- omitFields: [],
194
- };
195
-
196
- /**
197
- * Output for `prisma.client.dumpData`.
198
- *
199
- * @deprecated Use the `prisma-vir` package instead.
200
- * @category Prisma : Node
201
- * @category Package : @augment-vir/node
202
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
203
- */
204
- export type PrismaDumpOutput<TypeMap extends BaseTypeMap> = Partial<{
205
- [Model in PrismaModelName<TypeMap> as FirstLetterLowercase<Model>]: PrismaBasicModel<
206
- TypeMap,
207
- Model
208
- >[];
209
- }>;
210
-
211
- export async function dumpData<const TypeMap extends BaseTypeMap>(
212
- prismaClient: BasePrismaClient,
213
- options: Readonly<PartialWithUndefined<PrismaDataDumpOptions>> = {},
214
- ): Promise<PrismaDumpOutput<TypeMap>> {
215
- const modelNames = getAllPrismaModelKeys(prismaClient);
216
- const finalOptions = mergeDefinedProperties(defaultPrismaDumpDataOptions, options);
217
-
218
- const data: Partial<Record<PrismaModelName<TypeMap>, AnyObject[]>> = await arrayToObject(
219
- modelNames,
220
- async (modelName) => {
221
- try {
222
- const entries: AnyObject[] = await prismaClient[modelName].findMany(
223
- finalOptions.limit > 0
224
- ? {
225
- take: finalOptions.limit,
226
- }
227
- : {},
228
- );
229
-
230
- if (!entries.length) {
231
- return undefined;
232
- }
233
-
234
- const filteredEntries = finalOptions.omitFields.length
235
- ? entries.map((entry) => omitObjectKeys(entry, finalOptions.omitFields))
236
- : entries;
237
-
238
- return {
239
- key: modelName,
240
- value: filteredEntries,
241
- };
242
- } catch (error) {
243
- throw ensureErrorAndPrependMessage(
244
- error,
245
- `Failed to read data for model '${modelName}'`,
246
- );
247
- }
248
- },
249
- );
250
-
251
- return data as PrismaDumpOutput<TypeMap>;
252
- }
@@ -1,45 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-deprecated */
2
-
3
- import {collapseWhiteSpace} from '@augment-vir/common';
4
- import {existsSync} from 'node:fs';
5
- import {readFile} from 'node:fs/promises';
6
- import {join} from 'node:path';
7
- import {runPrismaCommand} from './run-prisma-command.js';
8
-
9
- export async function generatePrismaClient(
10
- schemaFilePath: string,
11
- env: Record<string, string> = {},
12
- ) {
13
- await runPrismaCommand({command: 'generate'}, schemaFilePath, env);
14
- }
15
-
16
- async function areSchemasEqual(
17
- originalSchema: string,
18
- generatedClientSchema: string,
19
- ): Promise<boolean> {
20
- if (!existsSync(originalSchema)) {
21
- throw new Error(`Schema file does not exist: '${originalSchema}'`);
22
- } else if (!existsSync(generatedClientSchema)) {
23
- return false;
24
- }
25
-
26
- const originalSchemaContents: string = String(await readFile(originalSchema));
27
- const generatedClientSchemaContents: string = String(await readFile(generatedClientSchema));
28
-
29
- return (
30
- collapseWhiteSpace(originalSchemaContents, {keepNewLines: true}) ===
31
- collapseWhiteSpace(generatedClientSchemaContents, {keepNewLines: true})
32
- );
33
- }
34
-
35
- export async function isGeneratedPrismaClientCurrent({
36
- jsClientOutputDir,
37
- schemaFilePath,
38
- }: {
39
- schemaFilePath: string;
40
- jsClientOutputDir: string;
41
- }) {
42
- const clientSchemaFilePath = join(jsClientOutputDir, 'schema.prisma');
43
-
44
- return areSchemasEqual(schemaFilePath, clientSchemaFilePath);
45
- }
@@ -1,31 +0,0 @@
1
- import {awaitedForEach, retry, wait} from '@augment-vir/common';
2
- import {interpolationSafeWindowsPath} from '../augments/path/os-path.js';
3
- import {runShellCommand} from '../augments/terminal/shell.js';
4
- import {
5
- generatedPrismaClientDirPath,
6
- notCommittedDirPath,
7
- testPrismaMigrationsDirPath,
8
- } from '../file-paths.mock.js';
9
-
10
- const pathsToDelete = [
11
- generatedPrismaClientDirPath,
12
- notCommittedDirPath,
13
- testPrismaMigrationsDirPath,
14
- ];
15
-
16
- export async function clearTestDatabaseOutputs() {
17
- await retry(10, async () => {
18
- await wait({seconds: 1});
19
- await awaitedForEach(pathsToDelete, async (pathToDelete) => {
20
- /**
21
- * This way of deleting files is required for Windows tests running on GitHub Actions.
22
- * Otherwise, we get the following error:
23
- *
24
- * EPERM: operation not permitted, unlink 'D:\a\augment-vir\augment-vir\packages\node\node_modules\.prisma\query_engine-windows.dll.node'
25
- */
26
- await runShellCommand(`rm -rf ${interpolationSafeWindowsPath(pathToDelete)}`, {
27
- rejectOnError: true,
28
- });
29
- });
30
- });
31
- }
@@ -1,60 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-deprecated */
2
-
3
- import {runPrismaCommand} from './run-prisma-command.js';
4
-
5
- export async function getPrismaDiff(
6
- schemaFilePath: string,
7
- env: Record<string, string> = {},
8
- ): Promise<string> {
9
- const command = [
10
- 'migrate',
11
- 'diff',
12
- `--from-schema-datamodel='${schemaFilePath}'`,
13
- `--to-schema-datasource='${schemaFilePath}'`,
14
- ].join(' ');
15
-
16
- const results = await runPrismaCommand({command}, undefined, env);
17
-
18
- if (results.stdout.trim() === 'No difference detected.') {
19
- return '';
20
- } else {
21
- return results.stdout.trim();
22
- }
23
- }
24
-
25
- export async function doesPrismaDiffExist(
26
- schemaFilePath: string,
27
- env: Record<string, string> = {},
28
- ): Promise<boolean> {
29
- return !!(await getPrismaDiff(schemaFilePath, env));
30
- }
31
-
32
- export async function resetDevPrismaDatabase(
33
- schemaFilePath: string,
34
- options: {
35
- /**
36
- * If you already have migrations created, set this to `true`. If you don't, set it to
37
- * `false`. If you don't know which one to use, try both, see which one creates a valid
38
- * database for you (try querying it with PrismaClient after running this; if it errors,
39
- * this didn't create a valid database).
40
- */
41
- withMigrations: boolean;
42
- },
43
- env: Record<string, string> = {},
44
- ) {
45
- if (options.withMigrations) {
46
- await runPrismaCommand(
47
- {command: 'migrate reset --force --skip-generate --skip-seed'},
48
- schemaFilePath,
49
- env,
50
- );
51
- } else {
52
- await runPrismaCommand(
53
- {
54
- command: 'db push --accept-data-loss --skip-generate',
55
- },
56
- schemaFilePath,
57
- env,
58
- );
59
- }
60
- }
@@ -1,45 +0,0 @@
1
- /**
2
- * An error thrown by the Prisma API that indicates that something is wrong with the given Prisma
3
- * schema. See the error message for more details.
4
- *
5
- * @category Prisma : Node : Util
6
- * @category Package : @augment-vir/node
7
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
8
- */
9
- export class PrismaSchemaError extends Error {
10
- public override readonly name = 'PrismaSchemaError';
11
- constructor(message: string) {
12
- super(message);
13
- }
14
- }
15
-
16
- /**
17
- * An error thrown by the Prisma API that indicates that applying migrations in dev failed such that
18
- * a new migration is needed. You can do that by prompting user for a new migration name and passing
19
- * it to `prisma.migration.create`.
20
- *
21
- * @category Prisma : Node : Util
22
- * @category Package : @augment-vir/node
23
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
24
- */
25
- export class PrismaMigrationNeededError extends Error {
26
- public override readonly name = 'PrismaMigrationNeededError';
27
- constructor(schemaFilePath: string) {
28
- super(`A new Prisma migration is needed for '${schemaFilePath}'`);
29
- }
30
- }
31
-
32
- /**
33
- * An error thrown by the Prisma API that indicates that applying migrations in dev failed such that
34
- * the entire database needs to be reset. You can do that by calling `prisma.database.resetDev`.
35
- *
36
- * @category Prisma : Node : Util
37
- * @category Package : @augment-vir/node
38
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
39
- */
40
- export class PrismaResetNeededError extends Error {
41
- public override readonly name = 'PrismaResetNeededError';
42
- constructor(schemaFilePath: string) {
43
- super(`A database reset is needed for '${schemaFilePath}'`);
44
- }
45
- }
@@ -1,153 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-deprecated */
2
-
3
- import {check} from '@augment-vir/assert';
4
- import {log, safeMatch, toEnsuredNumber} from '@augment-vir/common';
5
- import terminate from 'terminate';
6
- import {runShellCommand} from '../augments/terminal/shell.js';
7
- import {PrismaMigrationNeededError, PrismaResetNeededError} from './prisma-errors.js';
8
- import {runPrismaCommand, verifyOutput} from './run-prisma-command.js';
9
-
10
- /**
11
- * Output of `prisma.migration.status`.
12
- *
13
- * @deprecated Use the `prisma-vir` package instead.
14
- * @category Prisma : Node : Util
15
- * @category Package : @augment-vir/node
16
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
17
- */
18
- export type PrismaMigrationStatus = {
19
- totalMigrations: number;
20
- unappliedMigrations: string[];
21
- };
22
-
23
- export async function applyPrismaMigrationsToProd(
24
- schemaFilePath: string,
25
- env: Record<string, string> = {},
26
- ) {
27
- await runPrismaCommand({command: 'migrate deploy'}, schemaFilePath, env);
28
- }
29
-
30
- enum DbChangeRequired {
31
- MigrationNeeded = 'migration-needed',
32
- ResetNeeded = 'reset-needed',
33
- }
34
-
35
- export async function applyPrismaMigrationsToDev(
36
- schemaFilePath: string,
37
- env: Record<string, string> = {},
38
- ) {
39
- const command = [
40
- 'prisma',
41
- 'migrate',
42
- 'dev',
43
- `--schema='${schemaFilePath}'`,
44
- ].join(' ');
45
-
46
- log.faint(`> ${command}`);
47
-
48
- let dbRequirement = undefined as DbChangeRequired | undefined;
49
-
50
- const result = await runShellCommand(command, {
51
- env: {
52
- ...process.env,
53
- ...env,
54
- },
55
- stdoutCallback(stdout, childProcess) {
56
- if (stdout.includes('Enter a name for the new migration')) {
57
- if (childProcess.pid) {
58
- terminate(childProcess.pid);
59
- }
60
- dbRequirement = DbChangeRequired.MigrationNeeded;
61
- } else if (stdout.includes('We need to reset the SQLite database')) {
62
- if (childProcess.pid) {
63
- terminate(childProcess.pid);
64
- }
65
- dbRequirement = DbChangeRequired.ResetNeeded;
66
- }
67
- },
68
- });
69
-
70
- if (dbRequirement === DbChangeRequired.MigrationNeeded) {
71
- throw new PrismaMigrationNeededError(schemaFilePath);
72
- } else if (dbRequirement === DbChangeRequired.ResetNeeded) {
73
- throw new PrismaResetNeededError(schemaFilePath);
74
- }
75
- verifyOutput(schemaFilePath, result, false);
76
- }
77
-
78
- export async function getMigrationStatus(
79
- schemaFilePath: string,
80
- env: Record<string, string> = {},
81
- ): Promise<PrismaMigrationStatus> {
82
- const output = await runPrismaCommand(
83
- {
84
- command: 'migrate status',
85
- ignoreExitCode: true,
86
- },
87
- schemaFilePath,
88
- env,
89
- );
90
-
91
- const listedMigrations: PrismaMigrationStatus = {
92
- totalMigrations: 0,
93
- unappliedMigrations: [],
94
- };
95
-
96
- let foundNotAppliedMigrations = false;
97
-
98
- output.stdout.split('\n').some((rawLine) => {
99
- const line = rawLine.trim();
100
- if (foundNotAppliedMigrations) {
101
- if (line) {
102
- listedMigrations.unappliedMigrations.push(line);
103
- } else {
104
- /** We're done parsing. */
105
- return true;
106
- }
107
- } else if (line.endsWith('not yet been applied:')) {
108
- foundNotAppliedMigrations = true;
109
- } else {
110
- const [
111
- ,
112
- countMatch,
113
- ] = safeMatch(line, /^([\d,]+) migrations? found in/);
114
-
115
- if (countMatch) {
116
- listedMigrations.totalMigrations = toEnsuredNumber(countMatch);
117
- }
118
- }
119
-
120
- /** Still need to keep parsing. */
121
- return false;
122
- });
123
-
124
- return listedMigrations;
125
- }
126
-
127
- export async function createPrismaMigration(
128
- {
129
- migrationName,
130
- createOnly = false,
131
- }: {
132
- migrationName: string;
133
- /**
134
- * Set this to `true` to create a new migration without applying it to the database.
135
- *
136
- * @default false
137
- */
138
- createOnly?: boolean | undefined;
139
- },
140
- schemaFilePath: string,
141
- env: Record<string, string> = {},
142
- ) {
143
- const command = [
144
- 'migrate',
145
- 'dev',
146
- `--name='${migrationName}'`,
147
- createOnly ? '--create-only' : '',
148
- ]
149
- .filter(check.isTruthy)
150
- .join(' ');
151
-
152
- await runPrismaCommand({command}, schemaFilePath, env);
153
- }
@@ -1,94 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-deprecated */
2
-
3
- import {log, type PartialWithUndefined, wrapString} from '@augment-vir/common';
4
- import {dirname} from 'node:path';
5
- import {interpolationSafeWindowsPath} from '../augments/path/os-path.js';
6
- import {runShellCommand, type ShellOutput} from '../augments/terminal/shell.js';
7
- import {PrismaSchemaError} from './prisma-errors.js';
8
-
9
- /**
10
- * All commands in the Prisma CLI that support the `--no-hints` flag, used to turn off ads.
11
- *
12
- * @deprecated Use the `prisma-vir` package instead.
13
- * @category Prisma : Node : Util
14
- * @category Package : @augment-vir/node
15
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
16
- */
17
- export const prismaCommandsThatSupportNoHints = ['generate'];
18
-
19
- /**
20
- * Directly run a Prisma command.
21
- *
22
- * @deprecated Use the `prisma-vir` package instead.
23
- * @category Prisma : Node : Util
24
- * @category Package : @augment-vir/node
25
- * @package [`@augment-vir/node`](https://www.npmjs.com/package/@augment-vir/node)
26
- */
27
- export async function runPrismaCommand(
28
- {
29
- command,
30
- ignoreExitCode = false,
31
- hideLogs = false,
32
- }: {
33
- command: string;
34
- } & PartialWithUndefined<{
35
- /** If `true`, prevents errors from being thrown if this command exits with a non-0 status. */
36
- ignoreExitCode: boolean;
37
- hideLogs: boolean;
38
- }>,
39
- /** Set to `undefined` to omit the `--schema` flag. */
40
- schemaFilePath: string | undefined,
41
- env: Record<string, string> | undefined = {},
42
- ) {
43
- const schemaFileArgs = schemaFilePath
44
- ? [
45
- '--schema',
46
- wrapString({value: schemaFilePath, wrapper: "'"}),
47
- ]
48
- : [];
49
-
50
- /** Disable Prisma's in-CLI ads. */
51
- const noHintsArg = prismaCommandsThatSupportNoHints.some((commandName) =>
52
- command.startsWith(commandName),
53
- )
54
- ? '--no-hints'
55
- : '';
56
-
57
- const fullCommand = [
58
- 'prisma',
59
- command,
60
- ...schemaFileArgs,
61
- noHintsArg,
62
- ].join(' ');
63
-
64
- log.faint(`> ${fullCommand}`);
65
-
66
- const result = await runShellCommand(interpolationSafeWindowsPath(fullCommand), {
67
- env: {
68
- ...process.env,
69
- ...env,
70
- },
71
- hookUpToConsole: !hideLogs,
72
- cwd: schemaFilePath ? dirname(schemaFilePath) : process.cwd(),
73
- });
74
-
75
- return verifyOutput(schemaFilePath || '', result, ignoreExitCode);
76
- }
77
-
78
- export function verifyOutput(
79
- schemaFilePath: string,
80
- shellOutput: Readonly<ShellOutput>,
81
- ignoreExitCode: boolean,
82
- ) {
83
- if (shellOutput.stderr.includes('Validation Error Count')) {
84
- throw new PrismaSchemaError(
85
- `Invalid schema file at '${schemaFilePath}':\n\n${shellOutput.stderr}`,
86
- );
87
- } else if (shellOutput.stderr.includes('does not exist')) {
88
- throw new PrismaSchemaError(`Database does not exist: ${shellOutput.stderr}`);
89
- } else if (shellOutput.exitCode === 0 || ignoreExitCode) {
90
- return shellOutput;
91
- } else {
92
- throw new Error(shellOutput.stdout + shellOutput.stderr);
93
- }
94
- }