@pegasusheavy/nestjs-prisma-graphql 1.4.3 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/README.md +18 -7
  2. package/dist/benchmark/analysis.d.ts +7 -0
  3. package/dist/benchmark/analysis.d.ts.map +1 -0
  4. package/dist/benchmark/analysis.js +265 -0
  5. package/dist/benchmark/analysis.js.map +1 -0
  6. package/dist/benchmark/index.d.ts +7 -0
  7. package/dist/benchmark/index.d.ts.map +1 -0
  8. package/dist/benchmark/index.js +272 -0
  9. package/dist/benchmark/index.js.map +1 -0
  10. package/dist/event-names.d.ts +2 -0
  11. package/dist/event-names.d.ts.map +1 -0
  12. package/dist/event-names.js +2 -0
  13. package/dist/event-names.js.map +1 -0
  14. package/dist/generate.d.ts +4 -140
  15. package/dist/generate.d.ts.map +1 -0
  16. package/dist/generate.js +199 -2826
  17. package/dist/generate.js.map +1 -1
  18. package/dist/handlers/args-type.d.ts +7 -0
  19. package/dist/handlers/args-type.d.ts.map +1 -0
  20. package/dist/handlers/args-type.js +68 -0
  21. package/dist/handlers/args-type.js.map +1 -0
  22. package/dist/handlers/combine-scalar-filters.d.ts +6 -0
  23. package/dist/handlers/combine-scalar-filters.d.ts.map +1 -0
  24. package/dist/handlers/combine-scalar-filters.js +110 -0
  25. package/dist/handlers/combine-scalar-filters.js.map +1 -0
  26. package/dist/handlers/create-aggregate-input.d.ts +10 -0
  27. package/dist/handlers/create-aggregate-input.d.ts.map +1 -0
  28. package/dist/handlers/create-aggregate-input.js +33 -0
  29. package/dist/handlers/create-aggregate-input.js.map +1 -0
  30. package/dist/handlers/decimal-helpers.d.ts +10 -0
  31. package/dist/handlers/decimal-helpers.d.ts.map +1 -0
  32. package/dist/handlers/decimal-helpers.js +73 -0
  33. package/dist/handlers/decimal-helpers.js.map +1 -0
  34. package/dist/handlers/emit-single.d.ts +3 -0
  35. package/dist/handlers/emit-single.d.ts.map +1 -0
  36. package/dist/handlers/emit-single.js +14 -0
  37. package/dist/handlers/emit-single.js.map +1 -0
  38. package/dist/handlers/generate-barrel-exports.d.ts +13 -0
  39. package/dist/handlers/generate-barrel-exports.d.ts.map +1 -0
  40. package/dist/handlers/generate-barrel-exports.js +69 -0
  41. package/dist/handlers/generate-barrel-exports.js.map +1 -0
  42. package/dist/handlers/generate-files.d.ts +3 -0
  43. package/dist/handlers/generate-files.d.ts.map +1 -0
  44. package/dist/handlers/generate-files.js +133 -0
  45. package/dist/handlers/generate-files.js.map +1 -0
  46. package/dist/handlers/input-type.d.ts +7 -0
  47. package/dist/handlers/input-type.d.ts.map +1 -0
  48. package/dist/handlers/input-type.js +297 -0
  49. package/dist/handlers/input-type.js.map +1 -0
  50. package/dist/handlers/model-data.d.ts +3 -0
  51. package/dist/handlers/model-data.d.ts.map +1 -0
  52. package/dist/handlers/model-data.js +27 -0
  53. package/dist/handlers/model-data.js.map +1 -0
  54. package/dist/handlers/model-output-type.d.ts +3 -0
  55. package/dist/handlers/model-output-type.d.ts.map +1 -0
  56. package/dist/handlers/model-output-type.js +283 -0
  57. package/dist/handlers/model-output-type.js.map +1 -0
  58. package/dist/handlers/no-atomic-operations.d.ts +3 -0
  59. package/dist/handlers/no-atomic-operations.d.ts.map +1 -0
  60. package/dist/handlers/no-atomic-operations.js +41 -0
  61. package/dist/handlers/no-atomic-operations.js.map +1 -0
  62. package/dist/handlers/output-type.d.ts +3 -0
  63. package/dist/handlers/output-type.d.ts.map +1 -0
  64. package/dist/handlers/output-type.js +179 -0
  65. package/dist/handlers/output-type.js.map +1 -0
  66. package/dist/handlers/patch-type-registry.d.ts +16 -0
  67. package/dist/handlers/patch-type-registry.d.ts.map +1 -0
  68. package/dist/handlers/patch-type-registry.js +47 -0
  69. package/dist/handlers/patch-type-registry.js.map +1 -0
  70. package/dist/handlers/post-process-imports.d.ts +11 -0
  71. package/dist/handlers/post-process-imports.d.ts.map +1 -0
  72. package/dist/handlers/post-process-imports.js +44 -0
  73. package/dist/handlers/post-process-imports.js.map +1 -0
  74. package/dist/handlers/prisma-enum-doc.d.ts +11 -0
  75. package/dist/handlers/prisma-enum-doc.d.ts.map +1 -0
  76. package/dist/handlers/prisma-enum-doc.js +16 -0
  77. package/dist/handlers/prisma-enum-doc.js.map +1 -0
  78. package/dist/handlers/purge-output.d.ts +3 -0
  79. package/dist/handlers/purge-output.d.ts.map +1 -0
  80. package/dist/handlers/purge-output.js +34 -0
  81. package/dist/handlers/purge-output.js.map +1 -0
  82. package/dist/handlers/re-export.d.ts +9 -0
  83. package/dist/handlers/re-export.d.ts.map +1 -0
  84. package/dist/handlers/re-export.js +101 -0
  85. package/dist/handlers/re-export.js.map +1 -0
  86. package/dist/handlers/register-all-types.d.ts +13 -0
  87. package/dist/handlers/register-all-types.d.ts.map +1 -0
  88. package/dist/handlers/register-all-types.js +99 -0
  89. package/dist/handlers/register-all-types.js.map +1 -0
  90. package/dist/handlers/register-enum.d.ts +3 -0
  91. package/dist/handlers/register-enum.d.ts.map +1 -0
  92. package/dist/handlers/register-enum.js +65 -0
  93. package/dist/handlers/register-enum.js.map +1 -0
  94. package/dist/handlers/require-single-fields-in-whereunique-input.d.ts +3 -0
  95. package/dist/handlers/require-single-fields-in-whereunique-input.d.ts.map +1 -0
  96. package/dist/handlers/require-single-fields-in-whereunique-input.js +15 -0
  97. package/dist/handlers/require-single-fields-in-whereunique-input.js.map +1 -0
  98. package/dist/handlers/type-registry.d.ts +14 -0
  99. package/dist/handlers/type-registry.d.ts.map +1 -0
  100. package/dist/handlers/type-registry.js +151 -0
  101. package/dist/handlers/type-registry.js.map +1 -0
  102. package/dist/handlers/warning.d.ts +2 -0
  103. package/dist/handlers/warning.d.ts.map +1 -0
  104. package/dist/handlers/warning.js +14 -0
  105. package/dist/handlers/warning.js.map +1 -0
  106. package/dist/helpers/create-comment.d.ts +3 -0
  107. package/dist/helpers/create-comment.d.ts.map +1 -0
  108. package/dist/helpers/create-comment.js +23 -0
  109. package/dist/helpers/create-comment.js.map +1 -0
  110. package/dist/helpers/create-config.d.ts +51 -0
  111. package/dist/helpers/create-config.d.ts.map +1 -0
  112. package/dist/helpers/create-config.js +165 -0
  113. package/dist/helpers/create-config.js.map +1 -0
  114. package/dist/helpers/create-emit-blocks.d.ts +5 -0
  115. package/dist/helpers/create-emit-blocks.d.ts.map +1 -0
  116. package/dist/helpers/create-emit-blocks.js +37 -0
  117. package/dist/helpers/create-emit-blocks.js.map +1 -0
  118. package/dist/helpers/detect-circular-deps.d.ts +28 -0
  119. package/dist/helpers/detect-circular-deps.d.ts.map +1 -0
  120. package/dist/helpers/detect-circular-deps.js +92 -0
  121. package/dist/helpers/detect-circular-deps.js.map +1 -0
  122. package/dist/helpers/factory-get-source-file.d.ts +13 -0
  123. package/dist/helpers/factory-get-source-file.d.ts.map +1 -0
  124. package/dist/helpers/factory-get-source-file.js +17 -0
  125. package/dist/helpers/factory-get-source-file.js.map +1 -0
  126. package/dist/helpers/file-type-by-location.d.ts +3 -0
  127. package/dist/helpers/file-type-by-location.d.ts.map +1 -0
  128. package/dist/helpers/file-type-by-location.js +19 -0
  129. package/dist/helpers/file-type-by-location.js.map +1 -0
  130. package/dist/helpers/generate-file-name.d.ts +7 -0
  131. package/dist/helpers/generate-file-name.d.ts.map +1 -0
  132. package/dist/helpers/generate-file-name.js +35 -0
  133. package/dist/helpers/generate-file-name.js.map +1 -0
  134. package/dist/helpers/get-enum-name.d.ts +2 -0
  135. package/dist/helpers/get-enum-name.d.ts.map +1 -0
  136. package/dist/helpers/get-enum-name.js +5 -0
  137. package/dist/helpers/get-enum-name.js.map +1 -0
  138. package/dist/helpers/get-graphql-import.d.ts +19 -0
  139. package/dist/helpers/get-graphql-import.d.ts.map +1 -0
  140. package/dist/helpers/get-graphql-import.js +52 -0
  141. package/dist/helpers/get-graphql-import.js.map +1 -0
  142. package/dist/helpers/get-graphql-input-type.d.ts +6 -0
  143. package/dist/helpers/get-graphql-input-type.d.ts.map +1 -0
  144. package/dist/helpers/get-graphql-input-type.js +64 -0
  145. package/dist/helpers/get-graphql-input-type.js.map +1 -0
  146. package/dist/helpers/get-model-name.d.ts +2 -0
  147. package/dist/helpers/get-model-name.d.ts.map +1 -0
  148. package/dist/helpers/get-model-name.js +130 -0
  149. package/dist/helpers/get-model-name.js.map +1 -0
  150. package/dist/helpers/get-output-type-name.d.ts +2 -0
  151. package/dist/helpers/get-output-type-name.d.ts.map +1 -0
  152. package/dist/helpers/get-output-type-name.js +4 -0
  153. package/dist/helpers/get-output-type-name.js.map +1 -0
  154. package/dist/helpers/get-property-type.d.ts +9 -0
  155. package/dist/helpers/get-property-type.d.ts.map +1 -0
  156. package/dist/helpers/get-property-type.js +48 -0
  157. package/dist/helpers/get-property-type.js.map +1 -0
  158. package/dist/helpers/get-where-unique-at-least-keys.d.ts +3 -0
  159. package/dist/helpers/get-where-unique-at-least-keys.d.ts.map +1 -0
  160. package/dist/helpers/get-where-unique-at-least-keys.js +17 -0
  161. package/dist/helpers/get-where-unique-at-least-keys.js.map +1 -0
  162. package/dist/helpers/import-declaration-map.d.ts +19 -0
  163. package/dist/helpers/import-declaration-map.d.ts.map +1 -0
  164. package/dist/helpers/import-declaration-map.js +69 -0
  165. package/dist/helpers/import-declaration-map.js.map +1 -0
  166. package/dist/helpers/is-many-and-return.d.ts +2 -0
  167. package/dist/helpers/is-many-and-return.d.ts.map +1 -0
  168. package/dist/helpers/is-many-and-return.js +9 -0
  169. package/dist/helpers/is-many-and-return.js.map +1 -0
  170. package/dist/helpers/is-where-unique-input-type.d.ts +2 -0
  171. package/dist/helpers/is-where-unique-input-type.d.ts.map +1 -0
  172. package/dist/helpers/is-where-unique-input-type.js +4 -0
  173. package/dist/helpers/is-where-unique-input-type.js.map +1 -0
  174. package/dist/helpers/object-settings.d.ts +39 -0
  175. package/dist/helpers/object-settings.d.ts.map +1 -0
  176. package/dist/helpers/object-settings.js +297 -0
  177. package/dist/helpers/object-settings.js.map +1 -0
  178. package/dist/helpers/pascal-case.d.ts +2 -0
  179. package/dist/helpers/pascal-case.d.ts.map +1 -0
  180. package/dist/helpers/pascal-case.js +5 -0
  181. package/dist/helpers/pascal-case.js.map +1 -0
  182. package/dist/helpers/property-structure.d.ts +13 -0
  183. package/dist/helpers/property-structure.d.ts.map +1 -0
  184. package/dist/helpers/property-structure.js +20 -0
  185. package/dist/helpers/property-structure.js.map +1 -0
  186. package/dist/helpers/relative-path.d.ts +2 -0
  187. package/dist/helpers/relative-path.d.ts.map +1 -0
  188. package/dist/helpers/relative-path.js +20 -0
  189. package/dist/helpers/relative-path.js.map +1 -0
  190. package/dist/helpers/type-safe-assert.d.ts +7 -0
  191. package/dist/helpers/type-safe-assert.d.ts.map +1 -0
  192. package/dist/helpers/type-safe-assert.js +10 -0
  193. package/dist/helpers/type-safe-assert.js.map +1 -0
  194. package/dist/helpers/update-object-property.d.ts +7 -0
  195. package/dist/helpers/update-object-property.d.ts.map +1 -0
  196. package/dist/helpers/update-object-property.js +21 -0
  197. package/dist/helpers/update-object-property.js.map +1 -0
  198. package/dist/index.d.ts +4 -6
  199. package/dist/index.d.ts.map +1 -0
  200. package/dist/index.js +135 -2956
  201. package/dist/index.js.map +1 -1
  202. package/dist/test/test-utils.d.ts +4 -0
  203. package/dist/test/test-utils.d.ts.map +1 -0
  204. package/dist/test/test-utils.js +14 -0
  205. package/dist/test/test-utils.js.map +1 -0
  206. package/dist/types.d.ts +73 -0
  207. package/dist/types.d.ts.map +1 -0
  208. package/dist/types.js +2 -0
  209. package/dist/types.js.map +1 -0
  210. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,2975 +1,154 @@
1
- import { existsSync, readdirSync, rmdirSync as rmdirSync$1 } from 'fs';
2
- import { createRequire } from 'module';
3
- import { arch, platform } from 'os';
4
- import generatorHelper from '@prisma/generator-helper';
5
- import { memoize, mapKeys, merge, trim, castArray, uniqWith, isEqual, countBy, startCase, camelCase, keyBy, remove, partition, kebabCase, isObject, omit, cloneDeep } from 'lodash-es';
6
- import { Project, QuoteKind, StructureKind } from 'ts-morph';
7
- import { ok as ok$1 } from 'assert';
8
- import JSON52 from 'json5';
9
- import pupa from 'pupa';
10
- import getRelativePath from 'get-relative-path';
11
- import outmatch2 from 'outmatch';
12
- import { unflatten } from 'flat';
13
- import filenamify from 'filenamify';
14
- import pluralize from 'pluralize';
15
-
16
- // src/index.ts
17
- function ok(value, message) {
18
- ok$1(
19
- value,
20
- message
21
- );
22
- }
23
-
24
- // src/helpers/is-many-and-return.ts
25
- function isManyAndReturnOutputType(name) {
26
- const lowerName = name.toLowerCase();
27
- if ((lowerName.startsWith("createmany") || lowerName.startsWith("updatemany")) && (lowerName.endsWith("andreturnoutputtype") || lowerName.endsWith("andreturn"))) {
28
- return true;
29
- }
30
- return false;
31
- }
32
- function pascalCase(string) {
33
- return startCase(camelCase(string)).replaceAll(" ", "");
34
- }
35
-
36
- // src/handlers/args-type.ts
37
- function argsType(field, args) {
38
- if (["queryRaw", "executeRaw"].includes(field.name)) {
39
- return;
40
- }
41
- if (isManyAndReturnOutputType(field.name)) {
42
- return;
43
- }
44
- const { eventEmitter, getModelName: getModelName2, typeNames } = args;
45
- let className = pascalCase(`${field.name}Args`);
46
- const modelName = getModelName2(className) ?? "";
47
- switch (className) {
48
- case `Aggregate${modelName}Args`: {
49
- className = `${modelName}AggregateArgs`;
50
- break;
51
- }
52
- case `GroupBy${modelName}Args`: {
53
- className = `${modelName}GroupByArgs`;
54
- break;
55
- }
56
- }
57
- const inputType2 = {
58
- constraints: { maxNumFields: null, minNumFields: null },
59
- fields: [...field.args],
60
- name: className
61
- };
62
- if (!field.args.some((x) => x.name === "_count") && [`${modelName}AggregateArgs`, `${modelName}GroupByArgs`].includes(className)) {
63
- const names = ["Count", "Avg", "Sum", "Min", "Max"];
64
- if (`${modelName}GroupByArgs` === inputType2.name) {
65
- const byField = inputType2.fields.find((f) => f.name === "by");
66
- if (byField?.inputTypes) {
67
- byField.inputTypes = byField.inputTypes.filter((it) => it.isList);
68
- }
69
- }
70
- for (const name of names) {
71
- if (!typeNames.has(`${modelName}${name}AggregateInput`)) {
72
- continue;
73
- }
74
- inputType2.fields.push({
75
- inputTypes: [
76
- {
77
- isList: false,
78
- location: "inputObjectTypes",
79
- type: `${modelName}${name}AggregateInput`
80
- }
81
- ],
82
- isNullable: true,
83
- isRequired: false,
84
- name: `_${name.toLowerCase()}`
85
- });
86
- }
87
- }
88
- eventEmitter.emitSync("InputType", {
89
- ...args,
90
- classDecoratorName: "ArgsType",
91
- fileType: "args",
92
- inputType: inputType2
93
- });
94
- }
95
-
96
- // src/event-names.ts
97
- var BeforeGenerateField = "BeforeGenerateField";
98
-
99
- // src/handlers/combine-scalar-filters.ts
100
- function combineScalarFilters(eventEmitter) {
101
- eventEmitter.on("BeforeInputType", beforeInputType);
102
- eventEmitter.on(BeforeGenerateField, beforeGenerateField);
103
- eventEmitter.on("PostBegin", postBegin);
104
- }
105
- function beforeInputType(args) {
106
- const { inputType: inputType2, removeTypes } = args;
107
- if (isContainBogus(inputType2.name) && isScalarFilter(inputType2)) {
108
- removeTypes.add(inputType2.name);
109
- inputType2.name = replaceBogus(inputType2.name);
110
- }
111
- }
112
- function beforeGenerateField(field) {
113
- for (const fieldInput of field.inputTypes) {
114
- if (fieldInput.location !== "inputObjectTypes") {
115
- continue;
116
- }
117
- const fieldInputType = fieldInput.type;
118
- if (isContainBogus(fieldInputType)) {
119
- fieldInput.type = replaceBogus(fieldInputType);
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { arch, platform } from 'node:os';
4
+ const createRequireTyped = createRequire;
5
+ // ESLint doesn't understand import.meta.url type - cast to string explicitly
6
+ const requireCjs = createRequireTyped(String(import.meta.url));
7
+ const gracefulFsRaw = requireCjs('graceful-fs');
8
+ const gracefulFs = gracefulFsRaw;
9
+ const nodeFsRaw = requireCjs('fs');
10
+ const nodeFs = nodeFsRaw;
11
+ gracefulFs.gracefulify(nodeFs);
12
+ const globalConsole = globalThis.console;
13
+ const logError = (msg) => {
14
+ globalConsole.log(msg);
15
+ };
16
+ const processTyped = process;
17
+ processTyped.on('unhandledRejection', (reason) => {
18
+ logError(`nestjs-prisma-graphql: unhandled rejection: ${String(reason)}`);
19
+ if (reason instanceof Error && typeof reason.stack === 'string') {
20
+ logError(reason.stack);
120
21
  }
121
- }
122
- }
123
- function replaceBogus(name) {
124
- return name.replaceAll(/Nullable|Nested/g, "");
125
- }
126
- function isContainBogus(name) {
127
- return name.startsWith("Nested") || name.includes("Nullable") && name.endsWith("Filter") || name.endsWith("NullableFilter");
128
- }
129
- function isScalarFilter(inputType2) {
130
- if (!inputType2.name.endsWith("Filter")) {
131
- return false;
132
- }
133
- let result = false;
134
- const equals = inputType2.fields.find((f) => f.name === "equals");
135
- if (equals) {
136
- result = equals.inputTypes.every((x) => {
137
- return ["enumTypes", "scalar"].includes(x.location);
138
- });
139
- }
140
- return result;
141
- }
142
- function postBegin(args) {
143
- const { modelNames, schema } = args;
144
- const inputTypes = schema.inputObjectTypes.prisma ?? [];
145
- const enumTypes = schema.enumTypes.model ?? [];
146
- const types = [
147
- "Bool",
148
- "Int",
149
- "String",
150
- "DateTime",
151
- "Decimal",
152
- "Float",
153
- "Json",
154
- "Bytes",
155
- "BigInt"
156
- ];
157
- for (const enumType of enumTypes) {
158
- const { name } = enumType;
159
- types.push(`Enum${name}`);
160
- }
161
- const inputTypeByName = keyBy(inputTypes, (it) => it.name);
162
- const replaceBogusFilters = (filterName, filterNameCandidates) => {
163
- for (const filterNameCandidate of filterNameCandidates) {
164
- const candidate = inputTypeByName[filterNameCandidate];
165
- if (candidate) {
166
- const it = cloneDeep({ ...candidate, name: filterName });
167
- inputTypes.push(it);
168
- inputTypeByName[filterName] = it;
169
- break;
170
- }
22
+ });
23
+ processTyped.on('uncaughtException', (error) => {
24
+ const err = error;
25
+ logError(`nestjs-prisma-graphql: uncaught exception: ${err.message}`);
26
+ if (typeof err.stack === 'string') {
27
+ logError(err.stack);
171
28
  }
172
- };
173
- for (const type of types) {
174
- replaceBogusFilters(`${type}Filter`, [
175
- `${type}NullableFilter`,
176
- `Nested${type}NullableFilter`
177
- ]);
178
- replaceBogusFilters(`${type}WithAggregatesFilter`, [
179
- `${type}NullableWithAggregatesFilter`,
180
- `Nested${type}NullableWithAggregatesFilter`
181
- ]);
182
- replaceBogusFilters(`${type}ListFilter`, [
183
- `${type}NullableListFilter`,
184
- `Nested${type}NullableListFilter`
185
- ]);
186
- }
187
- for (const modelName of modelNames) {
188
- replaceBogusFilters(`${modelName}RelationFilter`, [
189
- `${modelName}NullableRelationFilter`
190
- ]);
191
- }
192
- for (const modelName of modelNames) {
193
- replaceBogusFilters(`${modelName}ScalarRelationFilter`, [
194
- `${modelName}NullableScalarRelationFilter`
195
- ]);
196
- }
197
- remove(inputTypes, (it) => {
198
- return isContainBogus(it.name);
199
- });
200
- }
201
-
202
- // src/handlers/create-aggregate-input.ts
203
- function createAggregateInput(args) {
204
- const { eventEmitter, outputType: outputType2 } = args;
205
- const className = `${outputType2.name}Input`;
206
- const inputType2 = {
207
- constraints: { maxNumFields: null, minNumFields: null },
208
- fields: outputType2.fields.map((x) => ({
209
- inputTypes: [
210
- {
211
- isList: false,
212
- location: "scalar",
213
- type: "true"
214
- }
215
- ],
216
- isNullable: x.isNullable ?? true,
217
- isRequired: false,
218
- name: x.name
219
- })),
220
- name: className
221
- };
222
- eventEmitter.emitSync("InputType", {
223
- ...args,
224
- classDecoratorName: "InputType",
225
- fileType: "input",
226
- inputType: inputType2
227
- });
228
- }
229
-
230
- // src/handlers/decimal-helpers.ts
231
- function generateDecimalHelpers(args) {
232
- const { output, project } = args;
233
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
234
- const sourceFile = rootDirectory.createSourceFile("decimal-helpers.ts", void 0, {
235
- overwrite: true
236
- });
237
- const helpersCode = `/**
238
- * Decimal Helpers for Prisma GraphQL
239
- *
240
- * This module provides utilities for transforming Decimal values
241
- * between GraphQL and Prisma, compatible with Prisma 7+.
242
- *
243
- * These functions replace the prisma-graphql-type-decimal package
244
- * which is incompatible with Prisma 7's new client structure.
245
- */
246
-
247
- import Decimal from 'decimal.js';
248
-
249
- /**
250
- * Reconstruct a Decimal from a serialized object.
251
- * Prisma serializes Decimals as objects with d, e, s properties.
252
- */
253
- function createDecimalFromObject(object: { d: number[]; e: number; s: number }): Decimal {
254
- return Object.create(Decimal.prototype, {
255
- d: { value: object.d },
256
- e: { value: object.e },
257
- s: { value: object.s },
258
- });
259
- }
260
-
29
+ });
30
+ import generatorHelper from '@prisma/generator-helper';
31
+ const { generatorHandler } = generatorHelper;
32
+ import { generate } from './generate.js';
261
33
  /**
262
- * Transform input values to Decimal instances.
263
- * Used as a class-transformer Transform decorator argument.
34
+ * Environment variables that can disable the generator:
35
+ * - DISABLE_NESTJS_PRISMA_GRAPHQL=true - Disable this specific generator
36
+ * - PRISMA_GENERATOR_SKIP=true - Skip all Prisma generators (common convention)
37
+ * - SKIP_PRISMA_GENERATE=true - Alternative skip flag
38
+ * - CI_SKIP_PRISMA_GRAPHQL=true - CI-specific skip flag
264
39
  *
265
- * @param params - The transform parameters from class-transformer
266
- * @returns The transformed Decimal or array of Decimals
267
- */
268
- export function transformToDecimal({ value }: { value: unknown }): Decimal | Decimal[] | null | undefined {
269
- if (value == null) return value as null | undefined;
270
-
271
- if (Array.isArray(value)) {
272
- return value.map((v) => {
273
- if (v instanceof Decimal) return v;
274
- if (typeof v === 'object' && v !== null && 'd' in v && 'e' in v && 's' in v) {
275
- return createDecimalFromObject(v as { d: number[]; e: number; s: number });
276
- }
277
- return new Decimal(v as string | number);
278
- });
279
- }
280
-
281
- if (value instanceof Decimal) return value;
282
- if (typeof value === 'object' && value !== null && 'd' in value && 'e' in value && 's' in value) {
283
- return createDecimalFromObject(value as { d: number[]; e: number; s: number });
284
- }
285
- return new Decimal(value as string | number);
286
- }
287
-
288
- /**
289
- * Re-export Decimal class for convenience
40
+ * Config options (in schema.prisma):
41
+ * - disabled = true - Disable generation
42
+ * - disabled = "true" - Disable generation (string)
43
+ * - disabled = 1 - Disable generation (number as string)
44
+ *
45
+ * @param options - Generator options or minimal config object
46
+ * @param env - Environment variables (defaults to process.env)
47
+ * @returns true if the generator should be disabled
290
48
  */
291
- export { Decimal };
292
- `;
293
- sourceFile.addStatements(helpersCode);
294
- }
295
- function emitSingle(emitter) {
296
- emitter.on("ClassProperty", classProperty);
297
- }
298
- function classProperty(property, eventArguments) {
299
- const { isList, location, propertyType } = eventArguments;
300
- if (["inputObjectTypes", "outputObjectTypes"].includes(location) && !isList) {
301
- const [safeTypes, instanceofTypes] = partition(
302
- propertyType,
303
- (t) => t === "null" || t.startsWith("Prisma.")
304
- );
305
- const mappedInstanceofTypes = instanceofTypes.map((t) => `InstanceType<typeof ${t}>`);
306
- property.type = [...mappedInstanceofTypes, ...safeTypes].join(" | ");
307
- }
308
- }
309
- var ImportDeclarationMap = class extends Map {
310
- add(name, value, isTypeOnly) {
311
- if (!this.has(name)) {
312
- const structure = typeof value === "string" ? { isTypeOnly, moduleSpecifier: value, namedImports: [{ name }] } : value;
313
- this.set(name, structure);
314
- }
315
- }
316
- /**
317
- * Add a type-only import for ESM circular dependency resolution
318
- */
319
- addType(name, moduleSpecifier) {
320
- const typeOnlyKey = `type:${name}`;
321
- if (!this.has(typeOnlyKey) && !this.has(name)) {
322
- this.set(typeOnlyKey, {
323
- isTypeOnly: true,
324
- moduleSpecifier,
325
- namedImports: [{ name }]
326
- });
327
- }
328
- }
329
- create(args) {
330
- const { defaultImport, from, isTypeOnly, namedImport, namespaceImport } = args;
331
- let { name } = args;
332
- const value = {
333
- defaultImport: void 0,
334
- isTypeOnly,
335
- moduleSpecifier: from,
336
- namedImports: [],
337
- namespaceImport: void 0
338
- };
339
- if (namedImport === true && namespaceImport !== void 0) {
340
- value.namedImports = [{ name: namespaceImport }];
341
- name = namespaceImport;
342
- } else if (defaultImport === void 0) {
343
- if (namespaceImport === void 0) {
344
- value.namedImports = [{ name }];
345
- } else {
346
- value.namespaceImport = namespaceImport;
347
- name = namespaceImport;
348
- }
349
- } else {
350
- value.defaultImport = defaultImport === true ? name : defaultImport;
351
- name = value.defaultImport;
352
- }
353
- const key = isTypeOnly === true ? `type:${name}` : name;
354
- if (this.has(key)) {
355
- return;
356
- }
357
- this.set(key, value);
358
- }
359
- *toStatements() {
360
- const iterator = this.values();
361
- let result = iterator.next();
362
- while (result.value !== void 0) {
363
- yield {
364
- ...result.value,
365
- kind: StructureKind.ImportDeclaration
366
- };
367
- result = iterator.next();
368
- }
369
- }
370
- };
371
-
372
- // src/handlers/generate-files.ts
373
- async function generateFiles(args) {
374
- const { config, eventEmitter, output, project } = args;
375
- if (config.emitSingle) {
376
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
377
- const sourceFile = rootDirectory.getSourceFile("index.ts") ?? rootDirectory.createSourceFile("index.ts", void 0, { overwrite: true });
378
- const statements = project.getSourceFiles().flatMap((s) => {
379
- if (s === sourceFile) {
380
- return [];
381
- }
382
- const classDeclaration = s.getClass(() => true);
383
- const stmts = s.getStructure().statements;
384
- if (Array.isArray(stmts)) {
385
- for (const statement of stmts) {
386
- if (!(typeof statement === "object" && statement.kind === StructureKind.Class)) {
387
- continue;
388
- }
389
- for (const property of statement.properties ?? []) {
390
- for (const decorator of property.decorators ?? []) {
391
- const fullName = classDeclaration?.getProperty(property.name)?.getDecorator(decorator.name)?.getFullName();
392
- ok(
393
- fullName !== void 0,
394
- `Cannot get full name of decorator of class ${String(statement.name)}`
395
- );
396
- decorator.name = fullName;
397
- }
398
- }
399
- }
400
- }
401
- project.removeSourceFile(s);
402
- return stmts;
403
- });
404
- const imports = new ImportDeclarationMap();
405
- const enums = [];
406
- const classes = [];
407
- for (const statement of statements) {
408
- if (typeof statement === "string") {
409
- if (statement.startsWith("registerEnumType")) {
410
- enums.push(statement);
411
- }
412
- continue;
413
- }
414
- switch (statement.kind) {
415
- case StructureKind.ImportDeclaration: {
416
- if (statement.moduleSpecifier.startsWith("./") || statement.moduleSpecifier.startsWith("..")) {
417
- continue;
418
- }
419
- for (const namedImport of statement.namedImports) {
420
- const name = namedImport.alias ?? namedImport.name;
421
- imports.add(name, statement.moduleSpecifier);
422
- }
423
- if (statement.defaultImport) {
424
- imports.create({
425
- defaultImport: statement.defaultImport,
426
- from: statement.moduleSpecifier,
427
- name: statement.defaultImport
428
- });
429
- }
430
- if (statement.namespaceImport) {
431
- imports.create({
432
- from: statement.moduleSpecifier,
433
- name: statement.namespaceImport,
434
- namespaceImport: statement.namespaceImport
435
- });
436
- }
437
- break;
438
- }
439
- case StructureKind.Enum: {
440
- enums.unshift(statement);
441
- break;
442
- }
443
- case StructureKind.Class: {
444
- classes.push(statement);
445
- break;
446
- }
447
- }
448
- }
449
- for (const customImport of config.customImport) {
450
- imports.create(customImport);
451
- }
452
- sourceFile.set({
453
- kind: StructureKind.SourceFile,
454
- statements: [...imports.toStatements(), ...enums, ...classes]
455
- });
456
- }
457
- const sourceFiles = project.getSourceFiles();
458
- const sourceFileCount = sourceFiles.length;
459
- const globalConsole3 = globalThis.console;
460
- const logMessage = (msg) => {
461
- globalConsole3.log(msg);
462
- };
463
- logMessage(
464
- `nestjs-prisma-graphql: saving ${String(sourceFileCount)} source files to ${output}`
465
- );
466
- if (sourceFileCount === 0) {
467
- throw new Error(
468
- "nestjs-prisma-graphql: project has 0 source files \u2014 nothing to write"
469
- );
470
- }
471
- if (config.emitCompiled) {
472
- project.compilerOptions.set({
473
- declaration: true,
474
- declarationDir: output,
475
- emitDecoratorMetadata: false,
476
- outDir: output,
477
- rootDir: output,
478
- skipLibCheck: true
479
- });
480
- const emitResult = await project.emit();
481
- const errors = emitResult.getDiagnostics().map((d) => String(d.getMessageText()));
482
- if (errors.length > 0) {
483
- eventEmitter.emitSync("Warning", errors);
484
- }
485
- } else {
486
- const BATCH_SIZE = 100;
487
- if (sourceFileCount > BATCH_SIZE) {
488
- logMessage(
489
- `nestjs-prisma-graphql: using batched save for large schema (${String(sourceFileCount)} files)`
490
- );
491
- for (let i = 0; i < sourceFileCount; i += BATCH_SIZE) {
492
- const batch = sourceFiles.slice(i, i + BATCH_SIZE);
493
- logMessage(
494
- `nestjs-prisma-graphql: saving batch ${String(Math.floor(i / BATCH_SIZE) + 1)}/${String(Math.ceil(sourceFileCount / BATCH_SIZE))} (${String(batch.length)} files)`
495
- );
496
- await Promise.all(batch.map(async (sf) => await sf.save()));
497
- }
498
- } else {
499
- await project.save();
500
- }
501
- }
502
- }
503
-
504
- // src/helpers/file-type-by-location.ts
505
- function fileTypeByLocation(fieldLocation) {
506
- switch (fieldLocation) {
507
- case "inputObjectTypes": {
508
- return "input";
509
- }
510
- case "outputObjectTypes": {
511
- return "output";
512
- }
513
- case "enumTypes": {
514
- return "enum";
515
- }
516
- case "fieldRefTypes":
517
- case "scalar":
518
- default: {
519
- return "object";
520
- }
521
- }
522
- }
523
- function relativePath(from, to) {
524
- let fromPath = from;
525
- let toPath = to;
526
- if (!fromPath.startsWith("/")) {
527
- fromPath = `/${fromPath}`;
528
- }
529
- if (!toPath.startsWith("/")) {
530
- toPath = `/${toPath}`;
531
- }
532
- let result = getRelativePath(fromPath, toPath);
533
- if (!result.startsWith(".")) {
534
- result = `./${result}`;
535
- }
536
- if (result.endsWith(".ts")) {
537
- result = result.slice(0, -3);
538
- }
539
- return result;
540
- }
541
-
542
- // src/helpers/get-graphql-import.ts
543
- function getGraphqlImport(args) {
544
- const {
545
- config,
546
- fileType,
547
- getSourceFile,
548
- isId,
549
- location,
550
- noTypeId,
551
- sourceFile,
552
- typeName
553
- } = args;
554
- if (location === "scalar") {
555
- if (isId && !noTypeId) {
556
- return { name: "ID", specifier: "@nestjs/graphql" };
557
- }
558
- const graphqlType = config.graphqlScalars[typeName];
559
- if (graphqlType) {
560
- return { name: graphqlType.name, specifier: graphqlType.specifier };
561
- }
562
- switch (typeName) {
563
- case "Float":
564
- case "Int": {
565
- return { name: typeName, specifier: "@nestjs/graphql" };
566
- }
567
- case "DateTime": {
568
- return { name: "Date", specifier: void 0 };
569
- }
570
- case "true":
571
- case "Boolean": {
572
- return { name: "Boolean", specifier: void 0 };
573
- }
574
- case "Decimal": {
575
- return {
576
- name: "GraphQLDecimal",
577
- specifier: "graphql-scalars"
578
- };
579
- }
580
- case "Json": {
581
- return { name: "GraphQLJSON", specifier: "graphql-type-json" };
582
- }
583
- }
584
- return { name: "String", specifier: void 0 };
585
- }
586
- let sourceFileType = fileTypeByLocation(location);
587
- if (sourceFileType === "output" && fileType === "model") {
588
- sourceFileType = "model";
589
- }
590
- let specifier = relativePath(
591
- sourceFile.getFilePath(),
592
- getSourceFile({
593
- name: typeName,
594
- type: sourceFileType
595
- }).getFilePath()
596
- );
597
- if (config.esmCompatible && !specifier.startsWith("@") && !specifier.endsWith(".js")) {
598
- specifier += ".js";
599
- }
600
- return { name: typeName, specifier };
601
- }
602
- function getGraphqlInputType(inputTypes, pattern) {
603
- let result;
604
- inputTypes = inputTypes.filter((t) => !["null", "Null"].includes(t.type));
605
- inputTypes = uniqWith(inputTypes, isEqual);
606
- if (inputTypes.length === 1) {
607
- return inputTypes[0];
608
- }
609
- const countTypes = countBy(inputTypes, (x) => x.location);
610
- const isOneType = Object.keys(countTypes).length === 1;
611
- if (isOneType) {
612
- result = inputTypes.find((x) => x.isList);
613
- if (result) {
614
- return result;
615
- }
616
- }
617
- if (pattern !== null && pattern !== void 0 && pattern.length > 0) {
618
- if (pattern.startsWith("matcher:") || pattern.startsWith("match:")) {
619
- const { 1: patternValue } = pattern.split(":", 2);
620
- const isMatch = outmatch2(patternValue, { separator: false });
621
- result = inputTypes.find((x) => isMatch(x.type));
622
- if (result !== void 0) {
623
- return result;
624
- }
625
- }
626
- result = inputTypes.find((x) => x.type.includes(pattern));
627
- if (result !== void 0) {
628
- return result;
629
- }
630
- }
631
- result = inputTypes.find((x) => x.location === "inputObjectTypes");
632
- if (result !== void 0) {
633
- return result;
634
- }
635
- if ((countTypes.enumTypes ?? 0) > 0 && (countTypes.scalar ?? 0) > 0 && inputTypes.some((x) => x.type === "Json" && x.location === "scalar")) {
636
- result = inputTypes.find((x) => x.type === "Json" && x.location === "scalar");
637
- if (result !== void 0) {
638
- return result;
639
- }
640
- }
641
- if (((countTypes.scalar ?? 0) >= 1 || (countTypes.enumTypes ?? 0) >= 1) && countTypes.fieldRefTypes === 1) {
642
- result = inputTypes.find(
643
- (x) => (x.location === "scalar" || x.location === "enumTypes") && x.isList
644
- );
645
- if (result !== void 0) {
646
- return result;
647
- }
648
- result = inputTypes.find((x) => x.location === "scalar" || x.location === "enumTypes");
649
- if (result !== void 0) {
650
- return result;
651
- }
652
- }
653
- throw new TypeError(
654
- `Cannot get matching input type from ${inputTypes.length > 0 ? inputTypes.map((x) => x.type).join(", ") : "zero length inputTypes"}`
655
- );
656
- }
657
-
658
- // src/helpers/get-property-type.ts
659
- function getPropertyType(args) {
660
- const { location, type } = args;
661
- switch (type) {
662
- case "Float":
663
- case "Int": {
664
- return ["number"];
665
- }
666
- case "String": {
667
- return ["string"];
668
- }
669
- case "Boolean": {
670
- return ["boolean"];
671
- }
672
- case "DateTime": {
673
- return ["Date", "string"];
674
- }
675
- case "Decimal": {
676
- return ["Prisma.Decimal"];
677
- }
678
- case "Json": {
679
- return ["any"];
680
- }
681
- case "Null": {
682
- return ["null"];
683
- }
684
- case "Bytes": {
685
- return ["Uint8Array"];
686
- }
687
- case "BigInt": {
688
- return ["bigint", "number"];
689
- }
690
- }
691
- if (["inputObjectTypes", "outputObjectTypes"].includes(location)) {
692
- return [type];
693
- }
694
- if (location === "enumTypes") {
695
- const enumType = `\`\${${type}}\``;
696
- return [enumType];
697
- }
698
- if (location === "scalar") {
699
- return [type];
700
- }
701
- return ["unknown"];
702
- }
703
-
704
- // src/helpers/get-where-unique-at-least-keys.ts
705
- function getWhereUniqueAtLeastKeys(model) {
706
- const names = model.fields.filter((field) => field.isUnique || field.isId).map((field) => field.name);
707
- if (model.primaryKey) {
708
- names.push(createFieldName(model.primaryKey));
709
- }
710
- for (const uniqueIndex of model.uniqueIndexes) {
711
- names.push(createFieldName(uniqueIndex));
712
- }
713
- return names;
714
- }
715
- function createFieldName(args) {
716
- const { fields, name } = args;
717
- return name !== null && name !== void 0 && name.length > 0 ? name : fields.join("_");
718
- }
719
-
720
- // src/helpers/is-where-unique-input-type.ts
721
- function isWhereUniqueInputType(name) {
722
- return name.endsWith("WhereUniqueInput");
723
- }
724
- function propertyStructure(args) {
725
- const {
726
- hasExclamationToken,
727
- hasQuestionToken,
728
- isList,
729
- isNullable,
730
- name,
731
- propertyType
732
- } = args;
733
- const typeString = propertyType.map((typeItem) => isList ? `Array<${typeItem}>` : typeItem).join(" | ");
734
- return {
735
- decorators: [],
736
- hasExclamationToken: hasExclamationToken ?? !isNullable,
737
- hasQuestionToken: hasQuestionToken ?? isNullable,
738
- kind: StructureKind.Property,
739
- leadingTrivia: "\n",
740
- name,
741
- type: typeString
742
- };
743
- }
744
-
745
- // src/handlers/input-type.ts
746
- function inputType(args) {
747
- const {
748
- classDecoratorName,
749
- classTransformerTypeModels,
750
- config,
751
- eventEmitter,
752
- fieldSettings,
753
- fileType,
754
- getModelName: getModelName2,
755
- getSourceFile,
756
- inputType: inputTypeArg,
757
- models,
758
- output,
759
- removeTypes,
760
- typeNames
761
- } = args;
762
- typeNames.add(inputTypeArg.name);
763
- const importDeclarations = new ImportDeclarationMap();
764
- const sourceFile = getSourceFile({
765
- name: inputTypeArg.name,
766
- type: fileType
767
- });
768
- const classStructure = {
769
- decorators: [
770
- {
771
- arguments: [],
772
- name: classDecoratorName
773
- }
774
- ],
775
- isExported: true,
776
- kind: StructureKind.Class,
777
- name: inputTypeArg.name,
778
- properties: []
779
- };
780
- const modelName = getModelName2(inputTypeArg.name) ?? "";
781
- const model = models.get(modelName);
782
- const modelFieldSettings = model && fieldSettings.get(model.name);
783
- const moduleSpecifier = "@nestjs/graphql";
784
- const lazyTypes = /* @__PURE__ */ new Set();
785
- importDeclarations.set("Field", {
786
- moduleSpecifier,
787
- namedImports: [{ name: "Field" }]
788
- }).set(classDecoratorName, {
789
- moduleSpecifier,
790
- namedImports: [{ name: classDecoratorName }]
791
- });
792
- if (config.esmCompatible) {
793
- let typeRegistryPath = relativePath(
794
- sourceFile.getFilePath(),
795
- `${output}/type-registry.ts`
796
- );
797
- if (!typeRegistryPath.endsWith(".js")) {
798
- typeRegistryPath += ".js";
799
- }
800
- importDeclarations.add("registerType", typeRegistryPath);
801
- importDeclarations.add("getType", typeRegistryPath);
802
- }
803
- const useInputType = config.useInputType.find(
804
- (x) => inputTypeArg.name.includes(x.typeName)
805
- );
806
- const isWhereUnique = isWhereUniqueInputType(inputTypeArg.name);
807
- for (const field of inputTypeArg.fields) {
808
- field.inputTypes = field.inputTypes.filter((t) => !removeTypes.has(t.type));
809
- eventEmitter.emitSync(BeforeGenerateField, field, args);
810
- const { inputTypes, isRequired, name } = field;
811
- if (inputTypes.length === 0) {
812
- continue;
813
- }
814
- const usePattern = useInputType?.ALL ?? useInputType?.[name];
815
- const graphqlInputType = getGraphqlInputType(inputTypes, usePattern);
816
- const { isList, location, type } = graphqlInputType;
817
- const typeName = type;
818
- const settings = modelFieldSettings?.get(name);
819
- const propertySettings = settings?.getPropertyType({
820
- input: true,
821
- name: inputTypeArg.name
822
- });
823
- const modelField = model?.fields.find((f) => f.name === name);
824
- const isCustomsApplicable = typeName === modelField?.type;
825
- const atLeastKeys = model && getWhereUniqueAtLeastKeys(model);
826
- const whereUniqueInputTypeValue = isWhereUniqueInputType(typeName) && atLeastKeys && `Prisma.AtLeast<${typeName}, ${atLeastKeys.map((n) => `'${n}'`).join(" | ")}>`;
827
- const propertyType = castArray(
828
- propertySettings?.name ?? whereUniqueInputTypeValue ?? getPropertyType({
829
- location,
830
- type: typeName
831
- })
832
- );
833
- const hasExclamationToken = Boolean(
834
- isWhereUnique && config.unsafeCompatibleWhereUniqueInput && atLeastKeys?.includes(name)
835
- );
836
- const property = propertyStructure({
837
- hasExclamationToken: hasExclamationToken || void 0,
838
- hasQuestionToken: hasExclamationToken ? false : void 0,
839
- isList,
840
- isNullable: !isRequired,
841
- name,
842
- propertyType
843
- });
844
- if (classStructure.properties) {
845
- classStructure.properties.push(property);
846
- }
847
- if (propertySettings) {
848
- importDeclarations.create({ ...propertySettings });
849
- } else if (propertyType.some(
850
- (p) => typeof p === "string" && p.includes("Prisma.Decimal")
851
- )) {
852
- importDeclarations.add("Prisma", config.prismaClientImport);
853
- } else if (propertyType.some((p) => typeof p === "string" && p.startsWith("Prisma."))) {
854
- importDeclarations.add("Prisma", config.prismaClientImport);
855
- }
856
- let graphqlType;
857
- let useGetType = false;
858
- const shouldHideField = settings?.shouldHideField({
859
- input: true,
860
- name: inputTypeArg.name
861
- }) ?? config.decorate.some(
862
- (d) => d.name === "HideField" && d.from === moduleSpecifier && d.isMatchField(name) && d.isMatchType(inputTypeArg.name)
863
- );
864
- const fieldType = settings?.getFieldType({
865
- input: true,
866
- name: inputTypeArg.name
867
- });
868
- if (fieldType && isCustomsApplicable && !shouldHideField) {
869
- graphqlType = fieldType.name;
870
- importDeclarations.create({ ...fieldType });
871
- } else {
872
- const graphqlImport = getGraphqlImport({
873
- config,
874
- getSourceFile,
875
- location,
876
- sourceFile,
877
- typeName
878
- });
879
- graphqlType = graphqlImport.name;
880
- if (location === "enumTypes") {
881
- const parts = String(propertyType[0]).split(" ");
882
- parts.at(-1);
883
- }
884
- const shouldUseLazyType = config.esmCompatible && location === "inputObjectTypes";
885
- if (graphqlImport.name === inputTypeArg.name && shouldUseLazyType) {
886
- lazyTypes.add(graphqlImport.name);
887
- useGetType = true;
888
- } else if (graphqlImport.specifier !== null && graphqlImport.specifier !== void 0 && !importDeclarations.has(graphqlImport.name) && graphqlImport.name !== inputTypeArg.name) {
889
- if (shouldUseLazyType) {
890
- importDeclarations.addType(graphqlImport.name, graphqlImport.specifier);
891
- lazyTypes.add(graphqlImport.name);
892
- } else {
893
- importDeclarations.set(graphqlImport.name, {
894
- moduleSpecifier: graphqlImport.specifier,
895
- namedImports: [{ name: graphqlImport.name }]
896
- });
897
- }
898
- }
899
- if (lazyTypes.has(graphqlImport.name)) {
900
- useGetType = true;
901
- }
902
- }
903
- ok(
904
- property.decorators !== void 0 && property.decorators !== null,
905
- "property.decorators is undefined"
906
- );
907
- if (shouldHideField) {
908
- importDeclarations.add("HideField", moduleSpecifier);
909
- property.decorators.push({ arguments: [], name: "HideField" });
910
- } else {
911
- let typeExpression;
912
- if (useGetType) {
913
- typeExpression = isList ? `() => [getType('${graphqlType}')]` : `() => getType('${graphqlType}')`;
914
- } else {
915
- typeExpression = isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`;
916
- }
917
- property.decorators.push({
918
- arguments: [
919
- typeExpression,
920
- JSON52.stringify({
921
- ...settings?.fieldArguments(),
922
- nullable: !isRequired
923
- })
924
- ],
925
- name: "Field"
926
- });
927
- if (graphqlType === "GraphQLDecimal") {
928
- let decimalHelpersPath = relativePath(
929
- sourceFile.getFilePath(),
930
- `${output}/decimal-helpers.ts`
931
- );
932
- if (config.esmCompatible && !decimalHelpersPath.endsWith(".js")) {
933
- decimalHelpersPath += ".js";
934
- }
935
- importDeclarations.add("transformToDecimal", decimalHelpersPath);
936
- importDeclarations.add("Transform", "class-transformer");
937
- importDeclarations.add("Type", "class-transformer");
938
- property.decorators.push(
939
- {
940
- arguments: ["() => Object"],
941
- name: "Type"
942
- },
943
- {
944
- arguments: ["transformToDecimal"],
945
- name: "Transform"
946
- }
947
- );
948
- } else if (location === "inputObjectTypes" && (modelField?.type === "Decimal" || [
949
- "connect",
950
- "connectOrCreate",
951
- "create",
952
- "createMany",
953
- "data",
954
- "delete",
955
- "deleteMany",
956
- "disconnect",
957
- "set",
958
- "update",
959
- "updateMany",
960
- "upsert",
961
- "where"
962
- ].includes(name) || classTransformerTypeModels.has(getModelName2(graphqlType) ?? "") || modelField?.kind === "object" && models.get(modelField.type)?.fields.some(
963
- (f) => f.kind === "object" && classTransformerTypeModels.has(f.type)
964
- ) === true)) {
965
- importDeclarations.add("Type", "class-transformer");
966
- if (useGetType) {
967
- property.decorators.push({
968
- arguments: [`getType('${graphqlType}')`],
969
- name: "Type"
970
- });
971
- } else {
972
- property.decorators.push({ arguments: [`() => ${graphqlType}`], name: "Type" });
973
- }
974
- }
975
- if (isCustomsApplicable) {
976
- for (const options of settings ?? []) {
977
- if ((options.kind === "Decorator" && options.input && options.match?.(name)) ?? true) {
978
- property.decorators.push({
979
- arguments: options.arguments,
980
- name: options.name
981
- });
982
- ok(
983
- options.from !== void 0 && options.from !== null && options.from !== "",
984
- "Missed 'from' part in configuration or field setting"
985
- );
986
- importDeclarations.create(options);
987
- }
988
- }
989
- }
990
- for (const decorate of config.decorate) {
991
- if (decorate.isMatchField(name) && decorate.isMatchType(inputTypeArg.name)) {
992
- property.decorators.push({
993
- arguments: decorate.arguments?.map((x) => pupa(x, { propertyType })),
994
- name: decorate.name
995
- });
996
- importDeclarations.create(decorate);
997
- }
998
- }
999
- }
1000
- eventEmitter.emitSync("ClassProperty", property, {
1001
- isList,
1002
- location,
1003
- propertyType
1004
- });
1005
- }
1006
- const statements = [
1007
- ...importDeclarations.toStatements(),
1008
- classStructure
1009
- ];
1010
- if (config.esmCompatible) {
1011
- statements.push(`
1012
- registerType('${inputTypeArg.name}', ${inputTypeArg.name});`);
1013
- }
1014
- sourceFile.set({
1015
- statements
1016
- });
1017
- }
1018
- var ObjectSettings = class extends Array {
1019
- shouldHideField({
1020
- input = false,
1021
- name,
1022
- output = false
1023
- }) {
1024
- const hideField = this.find((s) => s.name === "HideField");
1025
- return Boolean(
1026
- hideField?.input && input || hideField?.output && output || hideField?.match?.(name)
1027
- );
1028
- }
1029
- getFieldType({
1030
- input,
1031
- name,
1032
- output
1033
- }) {
1034
- const fieldType = this.find((s) => s.kind === "FieldType");
1035
- if (!fieldType) {
1036
- return void 0;
1037
- }
1038
- if (fieldType.match) {
1039
- return fieldType.match(name) ? fieldType : void 0;
1040
- }
1041
- if (input && !fieldType.input) {
1042
- return void 0;
1043
- }
1044
- if (output && !fieldType.output) {
1045
- return void 0;
1046
- }
1047
- return fieldType;
1048
- }
1049
- getPropertyType({
1050
- input,
1051
- name,
1052
- output
1053
- }) {
1054
- const propertyType = this.find((s) => s.kind === "PropertyType");
1055
- if (!propertyType) {
1056
- return void 0;
1057
- }
1058
- if (propertyType.match) {
1059
- return propertyType.match(name) ? propertyType : void 0;
1060
- }
1061
- if (input && !propertyType.input) {
1062
- return void 0;
1063
- }
1064
- if (output && !propertyType.output) {
1065
- return void 0;
1066
- }
1067
- return propertyType;
1068
- }
1069
- getObjectTypeArguments(options) {
1070
- const objectTypeOptions = merge({}, options);
1071
- const resultArguments = [objectTypeOptions];
1072
- const objectType = this.find((s) => s.kind === "ObjectType");
1073
- if (objectType && isObject(objectType.arguments)) {
1074
- const { name } = objectType.arguments;
1075
- merge(objectTypeOptions, omit(objectType.arguments, "name"));
1076
- if (name !== null && name !== void 0 && name !== "") {
1077
- resultArguments.unshift(name);
1078
- }
1079
- }
1080
- return resultArguments.map((x) => JSON52.stringify(x));
1081
- }
1082
- fieldArguments() {
1083
- const fieldItem = this.find((item) => item.kind === "Field");
1084
- if (fieldItem) {
1085
- return fieldItem.arguments;
1086
- }
1087
- return void 0;
1088
- }
49
+ // Helper to get process.env in a type-safe way
50
+ // Using Record<string, unknown> to avoid NodeJS.Process type resolution issues
51
+ const getProcessEnv = () => {
52
+ const globalProcess = process;
53
+ const processLike = globalProcess;
54
+ return processLike.env;
1089
55
  };
1090
- function createObjectSettings(args) {
1091
- const { config, text } = args;
1092
- const result = new ObjectSettings();
1093
- const textLines = text.split("\n");
1094
- const documentationLines = [];
1095
- let fieldElement = result.find((item) => item.kind === "Field");
1096
- if (!fieldElement) {
1097
- const newFieldElement = {
1098
- arguments: {},
1099
- from: "",
1100
- input: false,
1101
- kind: "Field",
1102
- model: false,
1103
- name: "",
1104
- output: false
1105
- };
1106
- fieldElement = newFieldElement;
1107
- }
1108
- for (const line of textLines) {
1109
- const match = /^@(?<name>\w+(\.(\w+))?)\((?<args>.*)\)/.exec(line);
1110
- const { documentLine, element } = createSettingElement({
1111
- config,
1112
- fieldElement,
1113
- line,
1114
- match
1115
- });
1116
- if (element) {
1117
- result.push(element);
1118
- }
1119
- if (documentLine) {
1120
- documentationLines.push(line);
1121
- }
1122
- }
1123
- return {
1124
- documentation: documentationLines.filter(Boolean).join("\n") || void 0,
1125
- settings: result
1126
- };
1127
- }
1128
- function createSettingElement({
1129
- config,
1130
- fieldElement,
1131
- line,
1132
- match
1133
- }) {
1134
- const result = {
1135
- documentLine: "",
1136
- element: void 0
1137
- };
1138
- if (line.startsWith("@deprecated")) {
1139
- const DEPRECATED_PREFIX_LENGTH = 11;
1140
- const updatedFieldElement = {
1141
- ...fieldElement,
1142
- arguments: {
1143
- ...fieldElement.arguments,
1144
- deprecationReason: trim(line.slice(DEPRECATED_PREFIX_LENGTH))
1145
- }
1146
- };
1147
- result.element = updatedFieldElement;
1148
- return result;
1149
- }
1150
- if (line.startsWith("@complexity")) {
1151
- const COMPLEXITY_PREFIX_LENGTH = 11;
1152
- const MIN_COMPLEXITY = 1;
1153
- let n = Number.parseInt(trim(line.slice(COMPLEXITY_PREFIX_LENGTH)), 10);
1154
- if (Number.isNaN(n) || n < MIN_COMPLEXITY) {
1155
- n = MIN_COMPLEXITY;
1156
- }
1157
- const updatedFieldElement = {
1158
- ...fieldElement,
1159
- arguments: {
1160
- ...fieldElement.arguments,
1161
- complexity: n
1162
- }
1163
- };
1164
- result.element = updatedFieldElement;
1165
- return result;
1166
- }
1167
- const name = match?.groups?.name;
1168
- if (!(match && name !== void 0 && name !== "")) {
1169
- result.documentLine = line;
1170
- return result;
1171
- }
1172
- const element = {
1173
- arguments: [],
1174
- from: "",
1175
- input: false,
1176
- kind: "Decorator",
1177
- model: false,
1178
- name: "",
1179
- output: false
1180
- };
1181
- result.element = element;
1182
- if (name === "TypeGraphQL.omit" || name === "HideField") {
1183
- Object.assign(element, hideFieldDecorator(match));
1184
- return result;
1185
- }
1186
- if (["FieldType", "PropertyType"].includes(name) && match.groups?.args !== void 0 && match.groups.args !== "") {
1187
- const options2 = customType(match.groups.args);
1188
- const namespaceConfig2 = options2.namespace !== void 0 && options2.namespace !== "" ? config.fields[options2.namespace] : void 0;
1189
- merge(element, namespaceConfig2, options2, {
1190
- kind: name
1191
- });
1192
- return result;
1193
- }
1194
- if (name === "ObjectType" && match.groups?.args !== void 0 && match.groups.args !== "") {
1195
- element.kind = "ObjectType";
1196
- const options2 = customType(match.groups.args);
1197
- if (typeof options2[0] === "string" && options2[0] !== "") {
1198
- options2.name = options2[0];
1199
- }
1200
- if (isObject(options2[1])) {
1201
- merge(options2, options2[1]);
1202
- }
1203
- element.arguments = {
1204
- isAbstract: options2.isAbstract,
1205
- name: options2.name
1206
- };
1207
- return result;
1208
- }
1209
- if (name === "Directive" && match.groups?.args !== void 0 && match.groups.args !== "") {
1210
- const options2 = customType(match.groups.args);
1211
- merge(element, { from: "@nestjs/graphql", model: true }, options2, {
1212
- arguments: Array.isArray(options2.arguments) ? options2.arguments.map((s) => JSON52.stringify(s)) : options2.arguments,
1213
- kind: "Decorator",
1214
- name,
1215
- namespace: false
1216
- });
1217
- return result;
1218
- }
1219
- const namespace = getNamespace(name);
1220
- element.namespaceImport = namespace;
1221
- const args = match.groups?.args ?? "";
1222
- const options = {
1223
- arguments: args.split(",").map((s) => trim(s)).filter(Boolean),
1224
- name
1225
- };
1226
- const namespaceConfig = namespace !== void 0 && namespace !== "" ? config.fields[namespace] : void 0;
1227
- merge(element, namespaceConfig, options);
1228
- return result;
1229
- }
1230
- function customType(args) {
1231
- const result = {};
1232
- let options = parseArgs(args);
1233
- if (typeof options === "string") {
1234
- options = { name: options };
1235
- }
1236
- Object.assign(result, options);
1237
- const namespace = getNamespace(options.name);
1238
- result.namespace = namespace;
1239
- const optionsWithName = options;
1240
- if (optionsWithName.name !== void 0 && optionsWithName.name !== "" && optionsWithName.name.includes(".")) {
1241
- result.namespaceImport = namespace;
1242
- }
1243
- if (typeof options.match === "string" || Array.isArray(options.match)) {
1244
- result.match = outmatch2(options.match, { separator: false });
1245
- }
1246
- return result;
1247
- }
1248
- function hideFieldDecorator(match) {
1249
- const result = {
1250
- arguments: [],
1251
- defaultImport: void 0,
1252
- from: "@nestjs/graphql",
1253
- match: void 0,
1254
- name: "HideField",
1255
- namespaceImport: void 0
1256
- };
1257
- const args = match.groups?.args;
1258
- if (args === void 0 || args === "") {
1259
- result.output = true;
1260
- return result;
1261
- }
1262
- if (args.includes("{") && args.includes("}")) {
1263
- const options = parseArgs(args);
1264
- result.output = Boolean(options.output);
1265
- result.input = Boolean(options.input);
1266
- if (typeof options.match === "string" || Array.isArray(options.match)) {
1267
- result.match = outmatch2(options.match, { separator: false });
1268
- }
1269
- } else {
1270
- if (/output:\s*true/.test(args)) {
1271
- result.output = true;
1272
- }
1273
- if (/input:\s*true/.test(args)) {
1274
- result.input = true;
1275
- }
1276
- }
1277
- return result;
1278
- }
1279
- function parseArgs(string) {
1280
- try {
1281
- return JSON52.parse(string);
1282
- } catch {
1283
- try {
1284
- return JSON52.parse(`[${string}]`);
1285
- } catch {
1286
- throw new Error(`Failed to parse: ${string}`);
1287
- }
1288
- }
1289
- }
1290
- function getNamespace(name) {
1291
- if (name === void 0 || name === null) {
1292
- return void 0;
1293
- }
1294
- if (typeof name !== "string") {
1295
- return void 0;
1296
- }
1297
- let result = name;
1298
- if (result === "") {
1299
- return void 0;
1300
- }
1301
- if (result.includes(".")) {
1302
- const parts = result.split(".");
1303
- result = parts[0] ?? "";
1304
- }
1305
- if (result === "") {
1306
- return void 0;
1307
- }
1308
- return result;
1309
- }
1310
-
1311
- // src/handlers/model-data.ts
1312
- function modelData(model, args) {
1313
- const {
1314
- classTransformerTypeModels,
1315
- config,
1316
- fieldSettings,
1317
- modelFields,
1318
- modelNames,
1319
- models
1320
- } = args;
1321
- modelNames.push(model.name);
1322
- models.set(model.name, model);
1323
- const modelFieldsValue = /* @__PURE__ */ new Map();
1324
- modelFields.set(model.name, modelFieldsValue);
1325
- const fieldSettingsValue = /* @__PURE__ */ new Map();
1326
- fieldSettings.set(model.name, fieldSettingsValue);
1327
- for (const field of model.fields) {
1328
- if (field.documentation !== null && field.documentation !== void 0 && field.documentation.length > 0) {
1329
- const { documentation, settings } = createObjectSettings({
1330
- config,
1331
- text: field.documentation
1332
- });
1333
- field.documentation = documentation;
1334
- fieldSettingsValue.set(field.name, settings);
1335
- }
1336
- modelFieldsValue.set(field.name, field);
1337
- }
1338
- if (model.fields.some((field) => field.type === "Decimal")) {
1339
- classTransformerTypeModels.add(model.name);
1340
- }
1341
- }
1342
-
1343
- // src/helpers/create-comment.ts
1344
- function createComment(documentation, settings) {
1345
- const documentationLines = documentation.split("\n");
1346
- const commentLines = ["/**"];
1347
- for (const line of documentationLines) {
1348
- commentLines.push(` * ${line}`);
1349
- }
1350
- const fieldArgs = settings?.fieldArguments();
1351
- let deprecationReason;
1352
- if (fieldArgs === void 0) {
1353
- deprecationReason = void 0;
1354
- } else {
1355
- deprecationReason = fieldArgs.deprecationReason;
1356
- }
1357
- if (deprecationReason !== void 0 && deprecationReason !== null && deprecationReason.length > 0) {
1358
- commentLines.push(` * @deprecated ${deprecationReason}`);
1359
- }
1360
- commentLines.push(" */\n");
1361
- return commentLines.join("\n");
1362
- }
1363
-
1364
- // src/helpers/detect-circular-deps.ts
1365
- function buildDependencyGraph(models) {
1366
- const graph = /* @__PURE__ */ new Map();
1367
- for (const model of models) {
1368
- graph.set(model.name, /* @__PURE__ */ new Set());
1369
- }
1370
- for (const model of models) {
1371
- const dependencies = graph.get(model.name);
1372
- if (!dependencies) {
1373
- continue;
1374
- }
1375
- for (const field of model.fields) {
1376
- if (field.kind === "object" && field.type !== model.name) {
1377
- if (graph.has(field.type)) {
1378
- dependencies.add(field.type);
1379
- }
1380
- }
56
+ export function isGeneratorDisabled(options, env = getProcessEnv()) {
57
+ const envVarsToCheck = [
58
+ 'DISABLE_NESTJS_PRISMA_GRAPHQL',
59
+ 'CI_SKIP_PRISMA_GRAPHQL',
60
+ 'PRISMA_GENERATOR_SKIP',
61
+ 'SKIP_PRISMA_GENERATE',
62
+ ];
63
+ for (const envVar of envVarsToCheck) {
64
+ const value = env[envVar];
65
+ if (value === 'true' || value === '1') {
66
+ return true;
67
+ }
68
+ }
69
+ const configDisabled = options.generator.config.disabled;
70
+ if (configDisabled === 'true' || configDisabled === '1' || configDisabled === 'yes') {
71
+ return true;
1381
72
  }
1382
- }
1383
- return graph;
1384
- }
1385
- function detectCircularDependencies(graph) {
1386
- const circularPairs = /* @__PURE__ */ new Set();
1387
- const visited = /* @__PURE__ */ new Set();
1388
- const recursionStack = /* @__PURE__ */ new Set();
1389
- const path = [];
1390
- function dfs(node) {
1391
- visited.add(node);
1392
- recursionStack.add(node);
1393
- path.push(node);
1394
- const dependencies = graph.get(node) ?? /* @__PURE__ */ new Set();
1395
- for (const dep of dependencies) {
1396
- if (!visited.has(dep)) {
1397
- dfs(dep);
1398
- } else if (recursionStack.has(dep)) {
1399
- const cycleStartIndex = path.indexOf(dep);
1400
- if (cycleStartIndex !== -1) {
1401
- const cyclePath = path.slice(cycleStartIndex);
1402
- for (let i = 0; i < cyclePath.length; i++) {
1403
- const a = cyclePath[i];
1404
- const b = cyclePath[(i + 1) % cyclePath.length];
1405
- const pair = a < b ? `${a}:${b}` : `${b}:${a}`;
1406
- circularPairs.add(pair);
1407
- }
1408
- }
1409
- }
1410
- }
1411
- path.pop();
1412
- recursionStack.delete(node);
1413
- }
1414
- for (const node of graph.keys()) {
1415
- if (!visited.has(node)) {
1416
- dfs(node);
1417
- }
1418
- }
1419
- return circularPairs;
1420
- }
1421
- function hasCircularDependency(circularDeps, modelA, modelB) {
1422
- const pair = modelA < modelB ? `${modelA}:${modelB}` : `${modelB}:${modelA}`;
1423
- return circularDeps.has(pair);
1424
- }
1425
-
1426
- // src/helpers/get-output-type-name.ts
1427
- function getOutputTypeName(name) {
1428
- return name.replace(/(?:OutputType|Output)$/, "");
73
+ return false;
1429
74
  }
1430
-
1431
- // src/handlers/model-output-type.ts
1432
- var nestjsGraphql = "@nestjs/graphql";
1433
- function modelOutputType(outputType2, args) {
1434
- const {
1435
- circularDependencies,
1436
- config,
1437
- eventEmitter,
1438
- fieldSettings,
1439
- getSourceFile,
1440
- modelFields,
1441
- models,
1442
- output
1443
- } = args;
1444
- if (isManyAndReturnOutputType(outputType2.name)) {
1445
- return;
1446
- }
1447
- const model = models.get(outputType2.name);
1448
- ok(model, `Cannot find model by name ${outputType2.name}`);
1449
- const sourceFile = getSourceFile({
1450
- name: outputType2.name,
1451
- type: "model"
1452
- });
1453
- const sourceFileStructure = sourceFile.getStructure();
1454
- const exportDeclaration = getExportDeclaration(
1455
- model.name,
1456
- sourceFileStructure.statements
1457
- );
1458
- const importDeclarations = new ImportDeclarationMap();
1459
- const classStructure = {
1460
- decorators: [
1461
- {
1462
- arguments: [],
1463
- name: "ObjectType"
1464
- }
1465
- ],
1466
- isExported: true,
1467
- kind: StructureKind.Class,
1468
- name: outputType2.name,
1469
- properties: []
1470
- };
1471
- sourceFileStructure.statements.push(classStructure);
1472
- ok(classStructure.decorators, "classStructure.decorators is undefined");
1473
- const decorator = classStructure.decorators.find((d) => d.name === "ObjectType");
1474
- ok(decorator, "ObjectType decorator not found");
1475
- let modelSettings;
1476
- if (model.documentation !== null && model.documentation !== void 0 && model.documentation.length > 0) {
1477
- const objectTypeOptions = {};
1478
- const { documentation, settings } = createObjectSettings({
1479
- config,
1480
- text: model.documentation
1481
- });
1482
- if (documentation !== void 0 && documentation.length > 0) {
1483
- classStructure.leadingTrivia ??= createComment(documentation);
1484
- objectTypeOptions.description = documentation;
1485
- }
1486
- decorator.arguments = settings.getObjectTypeArguments(objectTypeOptions);
1487
- modelSettings = settings;
1488
- }
1489
- importDeclarations.add("Field", nestjsGraphql);
1490
- importDeclarations.add("ObjectType", nestjsGraphql);
1491
- const lazyTypes = /* @__PURE__ */ new Set();
1492
- if (config.esmCompatible) {
1493
- let typeRegistryPath = relativePath(
1494
- sourceFile.getFilePath(),
1495
- `${output}/type-registry.ts`
1496
- );
1497
- if (!typeRegistryPath.endsWith(".js")) {
1498
- typeRegistryPath += ".js";
1499
- }
1500
- importDeclarations.add("registerType", typeRegistryPath);
1501
- importDeclarations.add("getType", typeRegistryPath);
1502
- }
1503
- for (const field of outputType2.fields) {
1504
- if (config.omitModelsCount && field.name === "_count") {
1505
- continue;
1506
- }
1507
- let fileType = "model";
1508
- const { isList, location, namespace, type } = field.outputType;
1509
- let outputTypeName = type;
1510
- if (namespace !== "model") {
1511
- fileType = "output";
1512
- outputTypeName = getOutputTypeName(outputTypeName);
1513
- }
1514
- const modelField = modelFields.get(model.name)?.get(field.name);
1515
- const settings = fieldSettings.get(model.name)?.get(field.name);
1516
- const fieldType = settings?.getFieldType({
1517
- name: outputType2.name,
1518
- output: true
1519
- });
1520
- const propertySettings = settings?.getPropertyType({
1521
- name: outputType2.name,
1522
- output: true
1523
- });
1524
- const propertyType = castArray(
1525
- propertySettings?.name ?? getPropertyType({
1526
- location,
1527
- type: outputTypeName
1528
- })
1529
- );
1530
- propertyType.splice(1, propertyType.length);
1531
- if (field.isNullable === true && !isList) {
1532
- propertyType.push("null");
1533
- }
1534
- let graphqlType;
1535
- let useGetType = false;
1536
- if (fieldType === void 0) {
1537
- const graphqlImport = getGraphqlImport({
1538
- config,
1539
- fileType,
1540
- getSourceFile,
1541
- isId: modelField?.isId,
1542
- location,
1543
- noTypeId: config.noTypeId,
1544
- sourceFile,
1545
- typeName: outputTypeName
1546
- });
1547
- graphqlType = graphqlImport.name;
1548
- if (graphqlImport.name !== outputType2.name && graphqlImport.specifier !== null && graphqlImport.specifier !== void 0 && graphqlImport.specifier.length > 0) {
1549
- const isCircular = config.esmCompatible && location === "outputObjectTypes" && namespace === "model" && hasCircularDependency(circularDependencies, outputType2.name, outputTypeName);
1550
- if (isCircular) {
1551
- importDeclarations.add(graphqlImport.name, graphqlImport.specifier);
1552
- lazyTypes.add(graphqlImport.name);
1553
- useGetType = true;
1554
- } else {
1555
- importDeclarations.add(graphqlImport.name, graphqlImport.specifier);
1556
- }
1557
- }
1558
- } else {
1559
- graphqlType = fieldType.name;
1560
- importDeclarations.create({ ...fieldType });
1561
- }
1562
- const property = propertyStructure({
1563
- hasExclamationToken: true,
1564
- hasQuestionToken: location === "outputObjectTypes",
1565
- isList,
1566
- isNullable: field.isNullable,
1567
- name: field.name,
1568
- propertyType
1569
- });
1570
- if (typeof property.leadingTrivia === "string" && modelField?.documentation !== null && modelField?.documentation !== void 0 && modelField.documentation.length > 0) {
1571
- property.leadingTrivia += createComment(modelField.documentation, settings);
1572
- }
1573
- if (classStructure.properties !== void 0) {
1574
- classStructure.properties.push(property);
1575
- }
1576
- if (propertySettings !== void 0) {
1577
- importDeclarations.create({ ...propertySettings });
1578
- } else if (propertyType.some((p) => p.includes("Prisma.Decimal"))) {
1579
- importDeclarations.add("Prisma", config.prismaClientImport);
1580
- }
1581
- ok(property.decorators !== void 0, "property.decorators is undefined");
1582
- const shouldHideField = settings?.shouldHideField({ name: outputType2.name, output: true }) === true || config.decorate.some(
1583
- (d) => d.name === "HideField" && d.from === "@nestjs/graphql" && d.isMatchField(field.name) && d.isMatchType(outputTypeName)
1584
- );
1585
- if (shouldHideField) {
1586
- importDeclarations.add("HideField", nestjsGraphql);
1587
- property.decorators.push({ arguments: [], name: "HideField" });
1588
- } else {
1589
- let typeExpression;
1590
- if (useGetType) {
1591
- typeExpression = isList ? `() => [getType('${graphqlType}')]` : `() => getType('${graphqlType}')`;
1592
- } else {
1593
- typeExpression = isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`;
1594
- }
1595
- property.decorators.push({
1596
- arguments: [
1597
- typeExpression,
1598
- JSON52.stringify({
1599
- ...settings?.fieldArguments(),
1600
- defaultValue: ["number", "string", "boolean"].includes(
1601
- typeof modelField?.default
1602
- ) ? modelField?.default : void 0,
1603
- description: modelField?.documentation !== null && modelField?.documentation !== void 0 && modelField.documentation !== "" ? modelField.documentation : void 0,
1604
- nullable: Boolean(field.isNullable)
1605
- })
1606
- ],
1607
- name: "Field"
1608
- });
1609
- for (const setting of settings ?? []) {
1610
- if (shouldBeDecorated(setting) && (setting.match?.(field.name) ?? true)) {
1611
- property.decorators.push({
1612
- arguments: setting.arguments,
1613
- name: setting.name
1614
- });
1615
- ok(
1616
- setting.from && setting.from.length > 0,
1617
- "Missed 'from' part in configuration or field setting"
1618
- );
1619
- importDeclarations.create(setting);
75
+ function countFilesRecursive(dir) {
76
+ let count = 0;
77
+ const readDirSyncTyped = readdirSync;
78
+ const rawEntries = readDirSyncTyped(dir, { withFileTypes: true });
79
+ const entries = rawEntries;
80
+ for (const entry of entries) {
81
+ const isDir = typeof entry.isDirectory === 'function' ? entry.isDirectory() : false;
82
+ if (isDir) {
83
+ count += countFilesRecursive(`${dir}/${entry.name}`);
1620
84
  }
1621
- }
1622
- for (const decorate of config.decorate) {
1623
- if (decorate.isMatchField(field.name) && decorate.isMatchType(outputTypeName)) {
1624
- property.decorators.push({
1625
- arguments: decorate.arguments?.map((x) => pupa(x, { propertyType })),
1626
- name: decorate.name
1627
- });
1628
- importDeclarations.create(decorate);
85
+ else {
86
+ count++;
1629
87
  }
1630
- }
1631
- }
1632
- eventEmitter.emitSync("ClassProperty", property, {
1633
- isList,
1634
- location,
1635
- propertyType
1636
- });
1637
- }
1638
- for (const setting of modelSettings ?? []) {
1639
- if (shouldBeDecorated(setting)) {
1640
- classStructure.decorators.push({
1641
- arguments: setting.arguments,
1642
- name: setting.name
1643
- });
1644
- importDeclarations.create(setting);
1645
88
  }
1646
- }
1647
- const statements = [
1648
- ...importDeclarations.toStatements(),
1649
- classStructure
1650
- ];
1651
- if (config.esmCompatible) {
1652
- statements.push(`
1653
- registerType('${outputType2.name}', ${outputType2.name});`);
1654
- }
1655
- if (exportDeclaration) {
1656
- sourceFile.set({
1657
- statements: [exportDeclaration, "\n", classStructure]
1658
- });
1659
- const classDeclaration = sourceFile.getClassOrThrow(model.name);
1660
- const commentedText = classDeclaration.getText().split("\n").map((x) => `// ${x}`);
1661
- classDeclaration.remove();
1662
- sourceFile.addStatements(["\n", ...commentedText]);
1663
- } else {
1664
- sourceFile.set({
1665
- statements
1666
- });
1667
- }
1668
- }
1669
- function shouldBeDecorated(setting) {
1670
- return setting.kind === "Decorator" && (setting.output || setting.model) && !(setting.output && setting.model);
1671
- }
1672
- function getExportDeclaration(name, statements) {
1673
- return statements.find((structure) => {
1674
- return structure.kind === StructureKind.ExportDeclaration && structure.namedExports.some(
1675
- (o) => (o.alias ?? o.name) === name
1676
- );
1677
- });
1678
- }
1679
-
1680
- // src/handlers/no-atomic-operations.ts
1681
- function noAtomicOperations(eventEmitter) {
1682
- eventEmitter.on("BeforeInputType", beforeInputType2);
1683
- eventEmitter.on("BeforeGenerateFiles", beforeGenerateFiles);
1684
- }
1685
- function beforeInputType2(args) {
1686
- const { getModelName: getModelName2, inputType: inputType2 } = args;
1687
- for (const field of inputType2.fields) {
1688
- const fieldName = field.name;
1689
- field.inputTypes = field.inputTypes.filter((it) => {
1690
- const inputTypeName = it.type;
1691
- const modelName = getModelName2(inputTypeName);
1692
- const isModelNameValid = modelName !== null && modelName !== void 0 && modelName.length > 0;
1693
- if (isAtomicOperation(inputTypeName) || isModelNameValid && isListInput(inputTypeName, modelName, fieldName)) {
1694
- return false;
1695
- }
1696
- return true;
1697
- });
1698
- }
1699
- }
1700
- function beforeGenerateFiles(args) {
1701
- const { project } = args;
1702
- for (const sourceFile of project.getSourceFiles()) {
1703
- const className = sourceFile.getClass(() => true)?.getName();
1704
- const isClassNameValid = className !== void 0 && className !== null && className.length > 0;
1705
- if (isClassNameValid && isAtomicOperation(className)) {
1706
- project.removeSourceFile(sourceFile);
1707
- }
1708
- }
1709
- }
1710
- function isAtomicOperation(typeName) {
1711
- if (typeName.endsWith("FieldUpdateOperationsInput")) {
1712
- return true;
1713
- }
1714
- return false;
89
+ return count;
1715
90
  }
1716
- function isListInput(typeName, model, field) {
1717
- return typeName === `${model}Create${field}Input` || typeName === `${model}Update${field}Input`;
1718
- }
1719
-
1720
- // src/helpers/get-enum-name.ts
1721
- function getEnumName(referenceName) {
1722
- return referenceName.slice(3, -2);
1723
- }
1724
-
1725
- // src/handlers/output-type.ts
1726
- var nestjsGraphql2 = "@nestjs/graphql";
1727
- function outputType(outputTypeArg, args) {
1728
- const { config, eventEmitter, fieldSettings, getModelName: getModelName2, getSourceFile, models } = args;
1729
- const importDeclarations = new ImportDeclarationMap();
1730
- const fileType = "output";
1731
- const modelName = getModelName2(outputTypeArg.name);
1732
- const model = modelName === void 0 ? void 0 : models.get(modelName);
1733
- const isAggregateOutput = model !== void 0 && /(?:Count|Avg|Sum|Min|Max)AggregateOutputType$/.test(outputTypeArg.name) && outputTypeArg.name.startsWith(model.name);
1734
- const isCountOutput = model?.name !== void 0 && model.name !== "" && outputTypeArg.name === `${model.name}CountOutputType`;
1735
- if (config.emitBlocks.outputs || isCountOutput) ; else {
1736
- return;
1737
- }
1738
- outputTypeArg.name = getOutputTypeName(outputTypeArg.name);
1739
- if (isAggregateOutput) {
1740
- eventEmitter.emitSync("AggregateOutput", { ...args, outputType: outputTypeArg });
1741
- }
1742
- const sourceFile = getSourceFile({
1743
- name: outputTypeArg.name,
1744
- type: fileType
1745
- });
1746
- const classStructure = {
1747
- decorators: [
1748
- {
1749
- arguments: [],
1750
- name: "ObjectType"
1751
- }
1752
- ],
1753
- isExported: true,
1754
- kind: StructureKind.Class,
1755
- name: outputTypeArg.name,
1756
- properties: []
1757
- };
1758
- importDeclarations.add("Field", nestjsGraphql2);
1759
- importDeclarations.add("ObjectType", nestjsGraphql2);
1760
- for (const field of outputTypeArg.fields) {
1761
- const { isList, location, type } = field.outputType;
1762
- const outputTypeName = getOutputTypeName(type);
1763
- let settings;
1764
- if (isCountOutput) {
1765
- settings = void 0;
1766
- } else if (model === void 0) {
1767
- settings = void 0;
1768
- } else {
1769
- settings = fieldSettings.get(model.name)?.get(field.name);
1770
- }
1771
- const propertySettings = settings?.getPropertyType({
1772
- name: outputTypeArg.name,
1773
- output: true
1774
- });
1775
- const isCustomsApplicable = outputTypeName === model?.fields.find((f) => f.name === field.name)?.type;
1776
- field.outputType.type = outputTypeName;
1777
- const propertyType = castArray(
1778
- propertySettings?.name ?? getPropertyType({
1779
- location,
1780
- type: outputTypeName
1781
- })
1782
- );
1783
- const property = propertyStructure({
1784
- hasQuestionToken: isCountOutput ? true : void 0,
1785
- isList,
1786
- isNullable: field.isNullable,
1787
- name: field.name,
1788
- propertyType
1789
- });
1790
- classStructure.properties?.push(property);
1791
- if (propertySettings !== void 0) {
1792
- importDeclarations.create({ ...propertySettings });
1793
- } else if (propertyType.some((p) => p.includes("Prisma.Decimal"))) {
1794
- importDeclarations.add("Prisma", config.prismaClientImport);
1795
- }
1796
- let graphqlType;
1797
- const shouldHideField = settings?.shouldHideField({
1798
- name: outputTypeArg.name,
1799
- output: true
1800
- }) === true || config.decorate.some(
1801
- (d) => d.name === "HideField" && d.from === "@nestjs/graphql" && d.isMatchField(field.name) && d.isMatchType(outputTypeName)
1802
- );
1803
- const fieldType = settings?.getFieldType({
1804
- name: outputTypeArg.name,
1805
- output: true
1806
- });
1807
- if (fieldType !== void 0 && isCustomsApplicable && !shouldHideField) {
1808
- graphqlType = fieldType.name;
1809
- importDeclarations.create({ ...fieldType });
1810
- } else {
1811
- const graphqlImport = getGraphqlImport({
1812
- config,
1813
- fileType,
1814
- getSourceFile,
1815
- isId: false,
1816
- location,
1817
- sourceFile,
1818
- typeName: outputTypeName
1819
- });
1820
- const referenceName = location === "enumTypes" ? getEnumName(propertyType[0]) : propertyType[0];
1821
- graphqlType = graphqlImport.name;
1822
- if (graphqlImport.specifier !== null && graphqlImport.specifier !== void 0 && graphqlImport.specifier.length > 0 && !importDeclarations.has(graphqlImport.name) && (graphqlImport.name !== outputTypeArg.name && !shouldHideField || shouldHideField && referenceName === graphqlImport.name)) {
1823
- importDeclarations.set(graphqlImport.name, {
1824
- moduleSpecifier: graphqlImport.specifier,
1825
- namedImports: [{ name: graphqlImport.name }]
1826
- });
1827
- }
1828
- }
1829
- ok(property.decorators !== void 0, "property.decorators is undefined");
1830
- if (shouldHideField) {
1831
- importDeclarations.add("HideField", nestjsGraphql2);
1832
- property.decorators.push({ arguments: [], name: "HideField" });
1833
- } else {
1834
- property.decorators.push({
1835
- arguments: [
1836
- isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`,
1837
- JSON52.stringify({
1838
- ...settings?.fieldArguments(),
1839
- nullable: Boolean(field.isNullable)
1840
- })
1841
- ],
1842
- name: "Field"
1843
- });
1844
- if (isCustomsApplicable) {
1845
- for (const options of settings ?? []) {
1846
- const shouldApplyDecorator = options.kind === "Decorator" && options.output && (options.match?.(field.name) ?? true);
1847
- if (shouldApplyDecorator) {
1848
- property.decorators.push({
1849
- arguments: options.arguments,
1850
- name: options.name
1851
- });
1852
- ok(
1853
- options.from !== null && options.from !== void 0 && options.from.length > 0,
1854
- "Missed 'from' part in configuration or field setting"
1855
- );
1856
- importDeclarations.create(options);
1857
- }
1858
- }
1859
- }
1860
- }
1861
- eventEmitter.emitSync("ClassProperty", property, {
1862
- isList,
1863
- location,
1864
- propertyType
1865
- });
1866
- }
1867
- sourceFile.set({
1868
- statements: [...importDeclarations.toStatements(), classStructure]
1869
- });
1870
- }
1871
- var rmdirTyped = rmdirSync$1;
1872
- var rmdirSync = (path) => {
1873
- rmdirTyped(path);
91
+ const globalConsole2 = globalThis.console;
92
+ const log = (msg) => {
93
+ globalConsole2.log(msg);
1874
94
  };
1875
- function purgeOutput(emitter) {
1876
- emitter.on("Begin", begin);
1877
- emitter.on("End", end);
1878
- }
1879
- function begin({ output, project }) {
1880
- const sourceFiles = project.getDirectory(output)?.getDescendantSourceFiles();
1881
- if (sourceFiles) {
1882
- for (const sourceFile of sourceFiles) {
1883
- sourceFile.delete();
1884
- }
1885
- }
1886
- }
1887
- function end({ output, project }) {
1888
- const directories = project.getDirectory(output)?.getDescendantDirectories().filter((directory) => directory.getSourceFiles().length === 0).map((directory) => directory.getPath());
1889
- const directoryList = directories ?? [];
1890
- for (const directory of directoryList) {
1891
- try {
1892
- rmdirSync(directory);
1893
- } catch {
1894
- }
1895
- }
1896
- }
1897
- var ReExport = /* @__PURE__ */ ((ReExport2) => {
1898
- ReExport2["None"] = "None";
1899
- ReExport2["Directories"] = "Directories";
1900
- ReExport2["Single"] = "Single";
1901
- ReExport2["All"] = "All";
1902
- return ReExport2;
1903
- })(ReExport || {});
1904
- function reExport(emitter) {
1905
- emitter.on("BeforeGenerateFiles", beforeGenerateFiles2);
1906
- }
1907
- function beforeGenerateFiles2(args) {
1908
- const { config, output, project } = args;
1909
- const rootDirectory = project.getDirectoryOrThrow(output);
1910
- if (["Directories" /* Directories */, "All" /* All */].includes(config.reExport)) {
1911
- const directories = [...rootDirectory.getDescendantDirectories()];
1912
- const indexFiles = [];
1913
- for (const directory of directories) {
1914
- const sourceFiles = directory.getSourceFiles().filter((sourceFile) => sourceFile.getBaseName() !== "index.ts");
1915
- if (sourceFiles.length > 0) {
1916
- const exportDeclarations = sourceFiles.map(
1917
- (sourceFile) => getExportDeclaration2(directory, sourceFile)
1918
- );
1919
- indexFiles.push({
1920
- path: `${directory.getPath()}/index.ts`,
1921
- statements: exportDeclarations
1922
- });
1923
- } else {
1924
- const subdirs = directory.getDirectories();
1925
- if (subdirs.length > 0) {
1926
- const namespaceExportDeclarations = subdirs.map(
1927
- (sourceDirectory) => getNamespaceExportDeclaration(directory, sourceDirectory)
1928
- );
1929
- indexFiles.push({
1930
- path: `${directory.getPath()}/index.ts`,
1931
- statements: namespaceExportDeclarations
1932
- });
95
+ generatorHandler({
96
+ async onGenerate(options) {
97
+ if (isGeneratorDisabled(options)) {
98
+ log('nestjs-prisma-graphql: generation skipped (disabled via environment variable or config)');
99
+ return;
100
+ }
101
+ const outputPath = options.generator.output?.value ?? '<unknown>';
102
+ const startTime = Date.now();
103
+ const archTyped = arch;
104
+ const platformTyped = platform;
105
+ const archValue = String(archTyped());
106
+ const platformValue = String(platformTyped());
107
+ const globalProcess2Raw = process;
108
+ const processWithVersion = globalProcess2Raw;
109
+ const nodeVersion = processWithVersion.version;
110
+ log([
111
+ 'nestjs-prisma-graphql: starting generation',
112
+ `(arch=${archValue}, platform=${platformValue}, node=${nodeVersion}, output=${outputPath})`,
113
+ ].join(' '));
114
+ try {
115
+ await generate(options);
116
+ }
117
+ catch (error) {
118
+ const elapsed = Date.now() - startTime;
119
+ const message = error instanceof Error ? error.message : String(error);
120
+ const stack = error instanceof Error ? error.stack : undefined;
121
+ log(`nestjs-prisma-graphql: generation FAILED after ${String(elapsed)}ms: ${message}`);
122
+ if (typeof stack === 'string') {
123
+ log(stack);
124
+ }
125
+ throw error;
126
+ }
127
+ const elapsed = Date.now() - startTime;
128
+ const existsSyncTyped = existsSync;
129
+ const pathExists = typeof outputPath === 'string' &&
130
+ outputPath !== '<unknown>' &&
131
+ existsSyncTyped(outputPath);
132
+ if (pathExists) {
133
+ const fileCount = countFilesRecursive(outputPath);
134
+ log(`nestjs-prisma-graphql: generated ${String(fileCount)} files in ${String(elapsed)}ms`);
135
+ if (fileCount === 0) {
136
+ const msg = 'nestjs-prisma-graphql: generation produced 0 files — this likely indicates a silent failure';
137
+ log(msg);
138
+ throw new Error(msg);
139
+ }
1933
140
  }
1934
- }
1935
- }
1936
- for (const { path, statements } of indexFiles) {
1937
- project.createSourceFile(path, { statements }, { overwrite: true });
1938
- }
1939
- }
1940
- if (config.reExport === "Single" /* Single */) {
1941
- const sourceFiles = project.getSourceFiles().filter((sourceFile) => sourceFile.getBaseName() !== "index.ts");
1942
- const exportDeclarations = sourceFiles.map(
1943
- (sourceFile) => getExportDeclaration2(rootDirectory, sourceFile)
1944
- );
1945
- rootDirectory.createSourceFile(
1946
- "index.ts",
1947
- { statements: exportDeclarations },
1948
- { overwrite: true }
1949
- );
1950
- }
1951
- if (config.reExport === "All" /* All */) {
1952
- const exportDeclarations = [];
1953
- const directories = rootDirectory.getDirectories();
1954
- for (const directory of directories) {
1955
- if (directory.getBaseName() === "node_modules") {
1956
- continue;
1957
- }
1958
- const indexFile = directory.getSourceFile("index.ts");
1959
- if (indexFile) {
1960
- const dirName = directory.getBaseName();
1961
- exportDeclarations.push({
1962
- kind: StructureKind.ExportDeclaration,
1963
- moduleSpecifier: `./${dirName}/index.js`
1964
- });
1965
- }
1966
- }
1967
- if (exportDeclarations.length > 0) {
1968
- rootDirectory.createSourceFile(
1969
- "index.ts",
1970
- { statements: exportDeclarations },
1971
- { overwrite: true }
1972
- );
1973
- }
1974
- }
1975
- }
1976
- function getExportDeclaration2(directory, sourceFile) {
1977
- let moduleSpecifier = directory.getRelativePathAsModuleSpecifierTo(sourceFile);
1978
- if (!moduleSpecifier.endsWith(".js") && !moduleSpecifier.endsWith(".ts")) {
1979
- moduleSpecifier += ".js";
1980
- } else if (moduleSpecifier.endsWith(".ts")) {
1981
- moduleSpecifier = `${moduleSpecifier.slice(0, -3)}.js`;
1982
- }
1983
- return {
1984
- kind: StructureKind.ExportDeclaration,
1985
- moduleSpecifier
1986
- };
1987
- }
1988
- function getNamespaceExportDeclaration(directory, sourceDirectory) {
1989
- let moduleSpecifier = directory.getRelativePathAsModuleSpecifierTo(sourceDirectory);
1990
- if (!moduleSpecifier.endsWith("/index.js")) {
1991
- moduleSpecifier += "/index.js";
1992
- }
1993
- return {
1994
- kind: StructureKind.ExportDeclaration,
1995
- moduleSpecifier
1996
- };
1997
- }
1998
-
1999
- // src/handlers/register-all-types.ts
2000
- function generateRegisterAllTypes(args) {
2001
- const { config, output, project } = args;
2002
- if (!config.esmCompatible) {
2003
- return;
2004
- }
2005
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
2006
- const sourceFile = rootDirectory.createSourceFile("register-all-types.ts", void 0, {
2007
- overwrite: true
2008
- });
2009
- const importPaths = [];
2010
- const typeNames = [];
2011
- const allSourceFiles = project.getSourceFiles(`${output}/**/*.ts`);
2012
- for (const file of allSourceFiles) {
2013
- const filePath = file.getFilePath();
2014
- if (filePath.endsWith("type-registry.ts") || filePath.endsWith("register-all-types.ts") || filePath.endsWith("index.ts")) {
2015
- continue;
2016
- }
2017
- const fileText = file.getText();
2018
- const registerMatch = /registerType\(['"]([^'"]+)['"]/.exec(fileText);
2019
- if (registerMatch) {
2020
- let relPath = relativePath(sourceFile.getFilePath(), filePath);
2021
- if (!relPath.endsWith(".js")) {
2022
- relPath += ".js";
2023
- }
2024
- importPaths.push(relPath);
2025
- typeNames.push(registerMatch[1]);
2026
- }
2027
- }
2028
- importPaths.sort();
2029
- typeNames.sort();
2030
- const fileContent = `/**
2031
- * ESM Type Registration Module
2032
- *
2033
- * This file registers all generated types with the type registry to solve
2034
- * ESM circular dependency issues. In ESM, unlike CommonJS, circular imports
2035
- * can result in undefined values because modules are evaluated in a different order.
2036
- *
2037
- * IMPORTANT: Import this file at the very top of your application entry point,
2038
- * BEFORE any other code that uses the generated types.
2039
- *
2040
- * Example usage in main.ts:
2041
- *
2042
- * // This MUST be the first import
2043
- * import './@generated/register-all-types.js';
2044
- *
2045
- * // Now you can safely import and use generated types
2046
- * import { NestFactory } from '@nestjs/core';
2047
- * import { AppModule } from './app.module.js';
2048
- *
2049
- * Why this is needed:
2050
- * - ESM uses "live bindings" where imports reference the actual export
2051
- * - With circular deps (User -> Post -> User), one module isn't ready when imported
2052
- * - CJS would give a partial object that fills in later; ESM gives undefined
2053
- * - This registry pattern defers type resolution until runtime when all modules are loaded
2054
- */
2055
-
2056
- import { markRegistrationComplete } from './type-registry.js';
2057
-
2058
- // Import all generated type files to trigger their registerType() calls
2059
- // These are side-effect imports that populate the type registry
2060
- ${importPaths.map((p) => `import '${p}';`).join("\n")}
2061
-
2062
- // Mark registration as complete to enable warning messages
2063
- markRegistrationComplete();
2064
-
2065
- // Export type names for validation (optional)
2066
- export const registeredTypes = [
2067
- ${typeNames.map((n) => ` '${n}',`).join("\n")}
2068
- ] as const;
2069
-
2070
- export type RegisteredTypeName = typeof registeredTypes[number];
2071
- `;
2072
- sourceFile.addStatements(fileContent);
2073
- }
2074
-
2075
- // src/handlers/prisma-enum-doc.ts
2076
- function extractEnumValueDocs(values) {
2077
- return Object.fromEntries(
2078
- values.map((value) => {
2079
- const { name } = value;
2080
- const { documentation } = value;
2081
- if (typeof documentation !== "string") {
2082
- return null;
2083
- }
2084
- if (documentation.startsWith("@deprecated")) {
2085
- return [name, { deprecationReason: documentation.slice(11).trim() }];
2086
- }
2087
- return [name, { description: documentation }];
2088
- }).filter((entry) => entry !== null)
2089
- );
2090
- }
2091
-
2092
- // src/handlers/register-enum.ts
2093
- function registerEnum(enumType, args) {
2094
- const { config, enums, getSourceFile } = args;
2095
- const enumTypeAsRecord = enumType;
2096
- const rawName = enumTypeAsRecord.name;
2097
- const enumName = typeof rawName === "string" ? rawName : String(rawName);
2098
- const enumValue = enums[enumName];
2099
- if (!config.emitBlocks.prismaEnums && enumValue === void 0) {
2100
- return;
2101
- }
2102
- const dataModelEnum = enumValue;
2103
- const enumTypesData = dataModelEnum?.values ?? [];
2104
- const sourceFile = getSourceFile({
2105
- name: enumName,
2106
- type: "enum"
2107
- });
2108
- const importDeclarations = new ImportDeclarationMap();
2109
- importDeclarations.set("registerEnumType", {
2110
- moduleSpecifier: "@nestjs/graphql",
2111
- namedImports: [{ name: "registerEnumType" }]
2112
- });
2113
- const valuesMap = extractEnumValueDocs(enumTypesData);
2114
- const filteredValuesMap = Object.fromEntries(
2115
- Object.entries(valuesMap).filter(([, v]) => Object.keys(v).length > 0)
2116
- );
2117
- const hasValuesMap = Object.keys(filteredValuesMap).length > 0;
2118
- const formattedValuesMap = hasValuesMap ? JSON.stringify(filteredValuesMap, null, 2).replace(/"([^"]+)":/g, "$1:") : "";
2119
- const valuesMapEntry = hasValuesMap ? `, valuesMap: ${formattedValuesMap}` : "";
2120
- const enumTypeRecord = enumType;
2121
- const rawValues = enumTypeRecord.values;
2122
- const enumValues = Array.isArray(rawValues) ? rawValues.map((v) => String(v)) : [];
2123
- const enumStructure = {
2124
- isExported: true,
2125
- kind: StructureKind.Enum,
2126
- members: enumValues.map((v) => ({
2127
- initializer: JSON.stringify(v),
2128
- name: v
2129
- })),
2130
- name: enumName
2131
- };
2132
- const enumTypeName = enumName;
2133
- sourceFile.set({
2134
- statements: [
2135
- ...importDeclarations.toStatements(),
2136
- enumStructure,
2137
- "\n",
2138
- `registerEnumType(${enumTypeName}, { name: '${enumTypeName}', description: ${JSON.stringify(
2139
- dataModelEnum?.documentation
2140
- )}${valuesMapEntry} })`
2141
- ]
2142
- });
2143
- }
2144
-
2145
- // src/handlers/require-single-fields-in-whereunique-input.ts
2146
- function requireSingleFieldsInWhereUniqueInput(eventEmitter) {
2147
- eventEmitter.on("BeforeInputType", beforeInputType3);
2148
- }
2149
- function beforeInputType3(args) {
2150
- const { inputType: inputType2 } = args;
2151
- if (!isWhereUniqueInputType(inputType2.name) || inputType2.fields.length !== 1) {
2152
- return;
2153
- }
2154
- for (const field of inputType2.fields) {
2155
- field.isRequired = true;
2156
- field.isNullable = false;
2157
- }
2158
- }
2159
-
2160
- // src/handlers/type-registry.ts
2161
- function generateTypeRegistry(args) {
2162
- const { config, output, project } = args;
2163
- if (!config.esmCompatible) {
2164
- return;
2165
- }
2166
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
2167
- const sourceFile = rootDirectory.createSourceFile("type-registry.ts", void 0, {
2168
- overwrite: true
2169
- });
2170
- const registryCode = `/**
2171
- * Type Registry for ESM Circular Dependency Resolution
2172
- *
2173
- * In ESM, circular dependencies behave differently than CommonJS:
2174
- * - CJS: Modules get a partial/incomplete export object that gets filled in
2175
- * - ESM: Imports are "live bindings" but can be undefined if not yet initialized
2176
- *
2177
- * This registry solves this by:
2178
- * 1. Deferring type resolution until runtime (after all modules are loaded)
2179
- * 2. Providing a forwardRef pattern for GraphQL field type declarations
2180
- * 3. Validating all types are registered before they're needed
2181
- */
2182
-
2183
- const registry = new Map<string, unknown>();
2184
- const pendingResolutions = new Map<string, Array<(type: unknown) => void>>();
2185
- let registrationComplete = false;
2186
-
2187
- /**
2188
- * Register a type with the registry.
2189
- * This should be called at module load time after the class is defined.
2190
- */
2191
- export function registerType(name: string, type: unknown): void {
2192
- if (type === undefined) {
2193
- console.warn(\`[nestjs-prisma-graphql] Warning: Registering undefined type for "\${name}". This may indicate a circular dependency issue.\`);
2194
- }
2195
- registry.set(name, type);
2196
-
2197
- // Resolve any pending forwardRef callbacks
2198
- const pending = pendingResolutions.get(name);
2199
- if (pending) {
2200
- for (const callback of pending) {
2201
- callback(type);
2202
- }
2203
- pendingResolutions.delete(name);
2204
- }
2205
- }
2206
-
2207
- /**
2208
- * Get a type from the registry.
2209
- * Returns the type if registered, undefined otherwise.
2210
- *
2211
- * For use in \\@Field(() => getType('TypeName')) decorators.
2212
- */
2213
- export function getType<T = unknown>(name: string): T {
2214
- const type = registry.get(name);
2215
- if (type === undefined && registrationComplete) {
2216
- console.warn(\`[nestjs-prisma-graphql] Warning: Type "\${name}" not found in registry. Ensure register-all-types is imported before using generated types.\`);
2217
- }
2218
- return type as T;
2219
- }
2220
-
2221
- /**
2222
- * Create a forward reference to a type that may not be registered yet.
2223
- * This is useful for handling circular dependencies where type A references type B
2224
- * and type B references type A.
2225
- *
2226
- * Usage: \\@Field(() => forwardRef('Post'))
2227
- */
2228
- export function forwardRef<T = unknown>(name: string): () => T {
2229
- return () => {
2230
- const type = registry.get(name);
2231
- if (type === undefined) {
2232
- throw new Error(
2233
- \`[nestjs-prisma-graphql] Type "\${name}" not registered. \\n\` +
2234
- \`This usually means:\\n\` +
2235
- \` 1. The register-all-types.ts file was not imported early enough\\n\` +
2236
- \` 2. There's a circular dependency that couldn't be resolved\\n\` +
2237
- \` 3. The type file failed to load\\n\\n\` +
2238
- \`Make sure to import 'register-all-types' at the top of your main.ts or app.module.ts\`
2239
- );
2240
- }
2241
- return type as T;
2242
- };
2243
- }
2244
-
2245
- /**
2246
- * Lazily resolve a type, returning a thunk that can be called later.
2247
- * This is the safest pattern for circular references in ESM.
2248
- *
2249
- * Usage: \\@Field(lazyType('Post'))
2250
- */
2251
- export function lazyType<T = unknown>(name: string): () => T {
2252
- return () => getType<T>(name);
2253
- }
2254
-
2255
- /**
2256
- * Mark registration as complete. Called after all types are imported.
2257
- * This enables warning messages for missing types.
2258
- */
2259
- export function markRegistrationComplete(): void {
2260
- registrationComplete = true;
2261
-
2262
- // Warn about any unresolved forward refs
2263
- if (pendingResolutions.size > 0) {
2264
- const missing = Array.from(pendingResolutions.keys()).join(', ');
2265
- console.warn(\`[nestjs-prisma-graphql] Warning: Unresolved forward references: \${missing}\`);
2266
- }
2267
- }
2268
-
2269
- /**
2270
- * Get all registered type names (useful for debugging)
2271
- */
2272
- export function getRegisteredTypes(): string[] {
2273
- return Array.from(registry.keys());
2274
- }
2275
-
2276
- /**
2277
- * Check if a type is registered
2278
- */
2279
- export function isTypeRegistered(name: string): boolean {
2280
- return registry.has(name);
2281
- }
2282
-
2283
- /**
2284
- * Validate that all expected types are registered.
2285
- * Throws an error if any types are missing.
2286
- */
2287
- export function validateRegistry(expectedTypes: string[]): void {
2288
- const missing = expectedTypes.filter(name => !registry.has(name));
2289
- if (missing.length > 0) {
2290
- throw new Error(
2291
- \`[nestjs-prisma-graphql] Missing type registrations: \${missing.join(', ')}\\n\` +
2292
- \`Ensure register-all-types.ts is imported before using these types.\`
2293
- );
2294
- }
2295
- }
2296
- `;
2297
- sourceFile.addStatements(registryCode);
2298
- }
2299
-
2300
- // src/handlers/warning.ts
2301
- var globalConsole = globalThis.console;
2302
- var log = (msg) => {
2303
- globalConsole.log(msg);
2304
- };
2305
- function warning(message) {
2306
- if (Array.isArray(message)) {
2307
- log("nestjs-prisma-graphql:");
2308
- log(message.join("\n"));
2309
- } else {
2310
- log(`nestjs-prisma-graphql: ${message}`);
2311
- }
2312
- }
2313
-
2314
- // src/helpers/create-emit-blocks.ts
2315
- var allEmmittedBlocks = [
2316
- "prismaEnums",
2317
- "schemaEnums",
2318
- "models",
2319
- "inputs",
2320
- "args",
2321
- "outputs"
2322
- ];
2323
- var blocksDependencyMap = {
2324
- args: ["args", "inputs", "prismaEnums"],
2325
- enums: ["schemaEnums", "prismaEnums"],
2326
- inputs: ["inputs", "prismaEnums"],
2327
- models: ["models", "schemaEnums"],
2328
- outputs: ["outputs"]
2329
- };
2330
- function createEmitBlocks(data) {
2331
- if (!data) {
2332
- const entries = allEmmittedBlocks.map((block) => [block, true]);
2333
- const allBlocks = Object.fromEntries(entries);
2334
- return allBlocks;
2335
- }
2336
- const initialBlocks = {};
2337
- let currentBlocks = initialBlocks;
2338
- for (const block of data) {
2339
- if (!Object.keys(blocksDependencyMap).includes(block)) {
2340
- continue;
2341
- }
2342
- const blockEntries = blocksDependencyMap[block].map(
2343
- (emittedBlock) => [emittedBlock, true]
2344
- );
2345
- const newBlocks = Object.fromEntries(blockEntries);
2346
- currentBlocks = {
2347
- ...currentBlocks,
2348
- ...newBlocks
2349
- };
2350
- }
2351
- return currentBlocks;
2352
- }
2353
-
2354
- // src/helpers/create-config.ts
2355
- function createConfig(data) {
2356
- const config = merge({}, unflatten(data, { delimiter: "_" }));
2357
- const $warnings = [];
2358
- const defaultPattern = `{model}/{name}.{type}.ts`;
2359
- const outputFilePatternValue = config.outputFilePattern;
2360
- const configOutputFilePattern = typeof outputFilePatternValue === "string" ? outputFilePatternValue : defaultPattern;
2361
- const sanitizedStep1 = configOutputFilePattern.replaceAll("..", "/").replaceAll(/\/+/g, "/");
2362
- const outputFilePattern = trim(sanitizedStep1, "/");
2363
- if (outputFilePattern !== configOutputFilePattern) {
2364
- $warnings.push(
2365
- `Due to invalid filepath 'outputFilePattern' changed to '${outputFilePattern}'`
2366
- );
2367
- }
2368
- if (config.reExportAll !== void 0 && config.reExportAll !== null && config.reExportAll !== false) {
2369
- $warnings.push(`Option 'reExportAll' is deprecated, use 'reExport' instead`);
2370
- if (toBoolean(config.reExportAll)) {
2371
- config.reExport = "All";
2372
- }
2373
- }
2374
- const fields = Object.fromEntries(
2375
- Object.entries(
2376
- config.fields ?? {}
2377
- ).filter(({ 1: value }) => typeof value === "object").map(([name, value]) => {
2378
- const fieldSetting = {
2379
- arguments: [],
2380
- defaultImport: toBoolean(value.defaultImport) ? true : value.defaultImport,
2381
- from: value.from,
2382
- input: toBoolean(value.input),
2383
- model: toBoolean(value.model),
2384
- namespaceImport: value.namespaceImport,
2385
- output: toBoolean(value.output)
2386
- };
2387
- return [name, fieldSetting];
2388
- })
2389
- );
2390
- const decorate = [];
2391
- const decorateConfig = config.decorate !== void 0 && config.decorate !== null ? config.decorate : {};
2392
- const configDecorate = Object.values(decorateConfig);
2393
- for (const element of configDecorate) {
2394
- if (element === void 0 || element === null) {
2395
- continue;
2396
- }
2397
- ok(
2398
- element.from !== void 0 && element.from !== "" && element.name !== void 0 && element.name !== "",
2399
- `Missed 'from' or 'name' part in configuration for decorate`
2400
- );
2401
- decorate.push({
2402
- arguments: element.arguments !== void 0 && element.arguments !== "" ? JSON52.parse(element.arguments) : void 0,
2403
- defaultImport: toBoolean(element.defaultImport) ? true : element.defaultImport,
2404
- from: element.from,
2405
- isMatchField: outmatch2(element.field, { separator: false }),
2406
- isMatchType: outmatch2(element.type, { separator: false }),
2407
- name: element.name,
2408
- namedImport: toBoolean(element.namedImport),
2409
- namespaceImport: element.namespaceImport
2410
- });
2411
- }
2412
- const customImport = [];
2413
- const customImportConfig = config.customImport !== void 0 && config.customImport !== null ? config.customImport : {};
2414
- const configCustomImport = Object.values(customImportConfig);
2415
- for (const element of configCustomImport) {
2416
- if (element === void 0 || element === null) {
2417
- continue;
2418
- }
2419
- ok(
2420
- element.from !== void 0 && element.from !== "" && element.name !== void 0 && element.name !== "",
2421
- `Missed 'from' or 'name' part in configuration for customImport`
2422
- );
2423
- customImport.push({
2424
- defaultImport: toBoolean(element.defaultImport) ? true : element.defaultImport,
2425
- from: element.from,
2426
- name: element.name,
2427
- namedImport: toBoolean(element.namedImport),
2428
- namespaceImport: element.namespaceImport
2429
- });
2430
- }
2431
- return {
2432
- $warnings,
2433
- combineScalarFilters: toBoolean(config.combineScalarFilters),
2434
- customImport,
2435
- decorate,
2436
- emitBlocks: createEmitBlocks(config.emitBlocks),
2437
- emitCompiled: toBoolean(config.emitCompiled),
2438
- emitSingle: toBoolean(config.emitSingle),
2439
- esmCompatible: toBoolean(config.esmCompatible),
2440
- fields,
2441
- graphqlScalars: config.graphqlScalars ?? {},
2442
- noAtomicOperations: toBoolean(config.noAtomicOperations),
2443
- noTypeId: toBoolean(config.noTypeId),
2444
- omitModelsCount: toBoolean(config.omitModelsCount),
2445
- outputFilePattern,
2446
- prismaClientImport: createPrismaImport(config.prismaClientImport),
2447
- purgeOutput: toBoolean(config.purgeOutput),
2448
- reExport: ReExport[String(config.reExport)] ?? "None" /* None */,
2449
- requireSingleFieldsInWhereUniqueInput: toBoolean(
2450
- config.requireSingleFieldsInWhereUniqueInput
2451
- ),
2452
- tsConfigFilePath: createTsConfigFilePathValue(config.tsConfigFilePath),
2453
- unsafeCompatibleWhereUniqueInput: toBoolean(config.unsafeCompatibleWhereUniqueInput),
2454
- useInputType: createUseInputType(
2455
- config.useInputType
2456
- )
2457
- };
2458
- }
2459
- var existsSyncTyped = existsSync;
2460
- var tsConfigFileExistsRaw = memoize((filePath) => {
2461
- const exists = existsSyncTyped(filePath);
2462
- return exists;
2463
- });
2464
- var tsConfigFileExists = tsConfigFileExistsRaw;
2465
- function createTsConfigFilePathValue(value) {
2466
- if (typeof value === "string" && value !== "") {
2467
- return value;
2468
- }
2469
- const fileExists = tsConfigFileExists("tsconfig.json");
2470
- if (fileExists) {
2471
- return "tsconfig.json";
2472
- }
2473
- return void 0;
2474
- }
2475
- function createPrismaImport(value) {
2476
- if (typeof value === "string" && value !== "") {
2477
- return value;
2478
- }
2479
- return "@prisma/client";
2480
- }
2481
- function createUseInputType(data) {
2482
- if (data === void 0 || data === null) {
2483
- return [];
2484
- }
2485
- const result = [];
2486
- for (const [typeName, useInputs] of Object.entries(data)) {
2487
- const entry = {
2488
- ALL: void 0,
2489
- typeName
2490
- };
2491
- if (useInputs.ALL !== void 0 && useInputs.ALL !== "") {
2492
- entry.ALL = useInputs.ALL;
2493
- delete useInputs.ALL;
2494
- }
2495
- for (const [propertyName, pattern] of Object.entries(useInputs)) {
2496
- entry[propertyName] = pattern;
2497
- }
2498
- result.push(entry);
2499
- }
2500
- return result;
2501
- }
2502
- function toBoolean(value) {
2503
- return ["true", "1", "on"].includes(String(value));
2504
- }
2505
- function generateFileName(args) {
2506
- const { getModelName: getModelName2, name, template, type } = args;
2507
- const rawPath = pupa(template, {
2508
- get model() {
2509
- const result = getModelName2(name) ?? "prisma";
2510
- return kebabCase(result);
2511
- },
2512
- get name() {
2513
- let result = kebabCase(name);
2514
- for (const suffix of ["input", "args", "enum"]) {
2515
- const ending = `-${suffix}`;
2516
- if (type === suffix && result.endsWith(ending)) {
2517
- result = result.slice(0, -ending.length);
141
+ else {
142
+ const msg = `nestjs-prisma-graphql: output directory not found after generation: ${outputPath}`;
143
+ log(msg);
144
+ throw new Error(msg);
2518
145
  }
2519
- }
2520
- return result;
2521
146
  },
2522
- plural: {
2523
- get type() {
2524
- return pluralize(type);
2525
- }
2526
- },
2527
- type
2528
- });
2529
- return rawPath.split("/").map((segment) => filenamify(segment, { replacement: "-" })).join("/");
2530
- }
2531
-
2532
- // src/helpers/factory-get-source-file.ts
2533
- function factoryGetSourceFile(args) {
2534
- const { getModelName: getModelName2, output, outputFilePattern, project } = args;
2535
- return function getSourceFile(getSourceFileArgs) {
2536
- const { name, type } = getSourceFileArgs;
2537
- let filePath = generateFileName({
2538
- getModelName: getModelName2,
2539
- name,
2540
- template: outputFilePattern,
2541
- type
2542
- });
2543
- filePath = `${output}/${filePath}`;
2544
- return project.getSourceFile(filePath) ?? project.createSourceFile(filePath, void 0, { overwrite: true });
2545
- };
2546
- }
2547
- var splitKeywords = [
2548
- "CreateInput",
2549
- "CreateMany",
2550
- "CreateNested",
2551
- "CreateOneWithout",
2552
- "CreateOrConnect",
2553
- "CreateWithout",
2554
- "DistinctField",
2555
- "Filter",
2556
- "ManyWithout",
2557
- "OrderByInput",
2558
- "RelationFilter",
2559
- "NullableRelationFilter",
2560
- "ListRelationFilter",
2561
- "ScalarWhereInput",
2562
- "UpdateInput",
2563
- "UpdateMany",
2564
- "UpdateOneRequiredWithout",
2565
- "UpdateOneWithout",
2566
- "UpdateWith",
2567
- "UpsertWith",
2568
- "UpsertWithout",
2569
- "WhereInput",
2570
- "WhereUniqueInput",
2571
- "AvgAggregate",
2572
- "SumAggregate",
2573
- "MinAggregate",
2574
- "MaxAggregate",
2575
- "CountAggregate",
2576
- "ScalarField",
2577
- "GroupBy",
2578
- "OrderBy",
2579
- "UncheckedUpdate",
2580
- "UncheckedCreate",
2581
- "ScalarWhere",
2582
- "CountOutputType",
2583
- "CountOrderBy",
2584
- "SumOrderBy",
2585
- "MinOrderBy",
2586
- "MaxOrderBy",
2587
- "AvgOrderBy",
2588
- "Create",
2589
- "Update",
2590
- "ScalarRelationFilter",
2591
- "NullableScalarRelationFilter"
2592
- ].sort((a, b) => b.length - a.length);
2593
- var endsWithKeywords = [
2594
- "Aggregate",
2595
- "GroupBy",
2596
- "CreateOne",
2597
- "CreateMany",
2598
- "DeleteMany",
2599
- "DeleteOne",
2600
- "FindMany",
2601
- "FindOne",
2602
- "FindUnique",
2603
- "UpdateMany",
2604
- "UpdateOne",
2605
- "UpsertOne"
2606
- ];
2607
- var middleKeywords = [
2608
- ["FindFirst", "OrThrowArgs"],
2609
- ["FindUnique", "OrThrowArgs"],
2610
- ["Aggregate", "Args"],
2611
- ["CreateOne", "Args"],
2612
- ["CreateMany", "Args"],
2613
- ["DeleteMany", "Args"],
2614
- ["DeleteOne", "Args"],
2615
- ["FindMany", "Args"],
2616
- ["FindFirst", "Args"],
2617
- ["FindOne", "Args"],
2618
- ["FindUnique", "Args"],
2619
- ["UpdateMany", "Args"],
2620
- ["UpdateMany", "AndReturnOutputType"],
2621
- ["UpdateOne", "Args"],
2622
- ["UpsertOne", "Args"],
2623
- ["GroupBy", "Args"],
2624
- ["OrderBy", "Args"]
2625
- ];
2626
- function createGetModelName(modelNames) {
2627
- return memoize(tryGetName);
2628
- function tryGetName(name) {
2629
- return getModelName({ modelNames, name });
2630
- }
2631
- }
2632
- function getModelName(args) {
2633
- const { modelNames, name } = args;
2634
- for (const keyword of splitKeywords) {
2635
- const [test] = name.split(keyword, 1);
2636
- if (test !== void 0 && modelNames.includes(test)) {
2637
- return test;
2638
- }
2639
- }
2640
- for (const keyword of endsWithKeywords) {
2641
- const test = name.split(keyword).at(-1);
2642
- if (test !== void 0 && modelNames.includes(test)) {
2643
- return test;
2644
- }
2645
- }
2646
- for (const [start, end2] of middleKeywords) {
2647
- let test = name.slice(start.length).slice(0, -end2.length);
2648
- if (modelNames.includes(test) && name.startsWith(start) && name.endsWith(end2)) {
2649
- return test;
2650
- }
2651
- test = name.slice(0, -(start + end2).length);
2652
- if (modelNames.includes(test) && name.endsWith(start + end2)) {
2653
- return test;
2654
- }
2655
- }
2656
- if (name.endsWith("CompoundUniqueInput")) {
2657
- const test = name.slice(0, -19);
2658
- const models = modelNames.filter((x) => test.startsWith(x)).sort((a, b) => b.length - a.length);
2659
- return models[0];
2660
- }
2661
- if (name.endsWith("Count")) {
2662
- const test = name.slice(0, -5);
2663
- if (modelNames.includes(test)) {
2664
- return test;
2665
- }
2666
- }
2667
- return void 0;
2668
- }
2669
-
2670
- // src/generate.ts
2671
- var createRequireTyped = createRequire;
2672
- var requireCjs = createRequireTyped(String(import.meta.url));
2673
- var AwaitEventEmitter = requireCjs(
2674
- "await-event-emitter"
2675
- );
2676
- var AwaitEventEmitterClass = AwaitEventEmitter.default;
2677
- async function generate(args) {
2678
- const { connectCallback, dmmf, generator, skipAddOutputSourceFiles } = args;
2679
- const generatorOutputValue = generator.output?.value ?? "";
2680
- ok(generatorOutputValue !== "", "Missing generator configuration: output");
2681
- const config = createConfig(generator.config);
2682
- const eventEmitter = new AwaitEventEmitterClass();
2683
- eventEmitter.on("Warning", warning);
2684
- if (config.emitBlocks.models) {
2685
- eventEmitter.on("Model", modelData);
2686
- }
2687
- if (config.emitBlocks.prismaEnums || config.emitBlocks.schemaEnums) {
2688
- eventEmitter.on("EnumType", registerEnum);
2689
- }
2690
- if (config.emitBlocks.outputs || config.emitBlocks.models && !config.omitModelsCount) {
2691
- eventEmitter.on("OutputType", outputType);
2692
- }
2693
- if (config.emitBlocks.models) {
2694
- eventEmitter.on("ModelOutputType", modelOutputType);
2695
- }
2696
- if (config.emitBlocks.outputs) {
2697
- eventEmitter.on("AggregateOutput", createAggregateInput);
2698
- }
2699
- if (config.emitBlocks.inputs) {
2700
- eventEmitter.on("InputType", inputType);
2701
- }
2702
- if (config.emitBlocks.args) {
2703
- eventEmitter.on("ArgsType", argsType);
2704
- }
2705
- eventEmitter.on("GenerateFiles", generateFiles);
2706
- for (const message of config.$warnings) {
2707
- eventEmitter.emitSync("Warning", message);
2708
- }
2709
- const project = new Project({
2710
- manipulationSettings: {
2711
- quoteKind: QuoteKind.Single
147
+ onManifest() {
148
+ return {
149
+ defaultOutput: '.',
150
+ prettyName: 'NestJS Prisma GraphQL (ESM)',
151
+ };
2712
152
  },
2713
- skipAddingFilesFromTsConfig: true,
2714
- skipLoadingLibFiles: !config.emitCompiled,
2715
- tsConfigFilePath: config.tsConfigFilePath
2716
- });
2717
- if (skipAddOutputSourceFiles !== true) {
2718
- project.addSourceFilesAtPaths([
2719
- `${generatorOutputValue}/**/*.ts`,
2720
- `!${generatorOutputValue}/**/*.d.ts`
2721
- ]);
2722
- }
2723
- if (config.combineScalarFilters) {
2724
- combineScalarFilters(eventEmitter);
2725
- }
2726
- if (config.noAtomicOperations) {
2727
- noAtomicOperations(eventEmitter);
2728
- }
2729
- if (config.reExport !== "None" /* None */) {
2730
- reExport(eventEmitter);
2731
- }
2732
- if (config.emitSingle) {
2733
- emitSingle(eventEmitter);
2734
- }
2735
- if (config.purgeOutput) {
2736
- purgeOutput(eventEmitter);
2737
- }
2738
- if (config.requireSingleFieldsInWhereUniqueInput) {
2739
- requireSingleFieldsInWhereUniqueInput(eventEmitter);
2740
- }
2741
- const models = /* @__PURE__ */ new Map();
2742
- const modelNames = [];
2743
- const modelFields = /* @__PURE__ */ new Map();
2744
- const fieldSettings = /* @__PURE__ */ new Map();
2745
- const getModelName2 = createGetModelName(modelNames);
2746
- const getSourceFile = factoryGetSourceFile({
2747
- getModelName: getModelName2,
2748
- output: generatorOutputValue,
2749
- outputFilePattern: config.outputFilePattern,
2750
- project
2751
- });
2752
- const { datamodel, schema } = JSON.parse(JSON.stringify(dmmf));
2753
- const removeTypes = /* @__PURE__ */ new Set();
2754
- const datamodelTypes = datamodel.types ?? [];
2755
- const allModels = [...datamodel.models, ...datamodelTypes];
2756
- const dependencyGraph = buildDependencyGraph(allModels);
2757
- const circularDependencies = detectCircularDependencies(dependencyGraph);
2758
- const eventArguments = {
2759
- circularDependencies,
2760
- classTransformerTypeModels: /* @__PURE__ */ new Set(),
2761
- config,
2762
- enums: mapKeys(datamodel.enums, (x) => x.name),
2763
- eventEmitter,
2764
- fieldSettings,
2765
- getModelName: getModelName2,
2766
- getSourceFile,
2767
- modelFields,
2768
- modelNames,
2769
- models,
2770
- output: generatorOutputValue,
2771
- project,
2772
- removeTypes,
2773
- schema,
2774
- typeNames: /* @__PURE__ */ new Set()
2775
- };
2776
- if (connectCallback) {
2777
- await connectCallback(eventEmitter, eventArguments);
2778
- }
2779
- await eventEmitter.emit("Begin", eventArguments);
2780
- if (config.esmCompatible) {
2781
- generateTypeRegistry(eventArguments);
2782
- }
2783
- generateDecimalHelpers(eventArguments);
2784
- for (const model of datamodel.models) {
2785
- await eventEmitter.emit("Model", model, eventArguments);
2786
- }
2787
- for (const model of datamodelTypes) {
2788
- await eventEmitter.emit("Model", model, eventArguments);
2789
- }
2790
- const { enumTypes, inputObjectTypes, outputObjectTypes } = schema;
2791
- await eventEmitter.emit("PostBegin", eventArguments);
2792
- for (const enumType of enumTypes.prisma.concat(enumTypes.model ?? [])) {
2793
- await eventEmitter.emit("EnumType", enumType, eventArguments);
2794
- }
2795
- for (const outputTypeItem of outputObjectTypes.model) {
2796
- await eventEmitter.emit("ModelOutputType", outputTypeItem, eventArguments);
2797
- }
2798
- const queryOutputTypes = [];
2799
- for (const outputTypeItem of outputObjectTypes.prisma) {
2800
- if (["Query", "Mutation"].includes(outputTypeItem.name)) {
2801
- queryOutputTypes.push(outputTypeItem);
2802
- continue;
2803
- }
2804
- await eventEmitter.emit("OutputType", outputTypeItem, eventArguments);
2805
- }
2806
- const inputTypes = (inputObjectTypes.prisma ?? []).concat(inputObjectTypes.model ?? []);
2807
- for (const inputTypeItem of inputTypes) {
2808
- const event = {
2809
- ...eventArguments,
2810
- classDecoratorName: "InputType",
2811
- fileType: "input",
2812
- inputType: inputTypeItem
2813
- };
2814
- if (inputTypeItem.fields.length === 0) {
2815
- removeTypes.add(inputTypeItem.name);
2816
- continue;
2817
- }
2818
- await eventEmitter.emit("BeforeInputType", event);
2819
- await eventEmitter.emit("InputType", event);
2820
- }
2821
- for (const outputTypeItem of queryOutputTypes) {
2822
- for (const field of outputTypeItem.fields) {
2823
- await eventEmitter.emit("ArgsType", field, eventArguments);
2824
- }
2825
- }
2826
- if (config.esmCompatible) {
2827
- generateRegisterAllTypes(eventArguments);
2828
- }
2829
- await eventEmitter.emit("BeforeGenerateFiles", eventArguments);
2830
- await eventEmitter.emit("GenerateFiles", eventArguments);
2831
- await eventEmitter.emit("End", eventArguments);
2832
- for (const name of Object.keys(
2833
- eventEmitter._events
2834
- )) {
2835
- eventEmitter.off(name);
2836
- }
2837
- }
2838
-
2839
- // src/index.ts
2840
- var createRequireTyped2 = createRequire;
2841
- var requireCjs2 = createRequireTyped2(String(import.meta.url));
2842
- var gracefulFsRaw = requireCjs2("graceful-fs");
2843
- var gracefulFs = gracefulFsRaw;
2844
- var nodeFsRaw = requireCjs2("fs");
2845
- var nodeFs = nodeFsRaw;
2846
- gracefulFs.gracefulify(nodeFs);
2847
- var globalConsole2 = globalThis.console;
2848
- var logError = (msg) => {
2849
- globalConsole2.log(msg);
2850
- };
2851
- var processTyped = process;
2852
- processTyped.on("unhandledRejection", (reason) => {
2853
- logError(`nestjs-prisma-graphql: unhandled rejection: ${String(reason)}`);
2854
- if (reason instanceof Error && typeof reason.stack === "string") {
2855
- logError(reason.stack);
2856
- }
2857
- });
2858
- processTyped.on("uncaughtException", (error) => {
2859
- const err = error;
2860
- logError(`nestjs-prisma-graphql: uncaught exception: ${err.message}`);
2861
- if (typeof err.stack === "string") {
2862
- logError(err.stack);
2863
- }
2864
- });
2865
- var { generatorHandler } = generatorHelper;
2866
- var getProcessEnv = () => {
2867
- const globalProcess = process;
2868
- const processLike = globalProcess;
2869
- return processLike.env;
2870
- };
2871
- function isGeneratorDisabled(options, env = getProcessEnv()) {
2872
- const envVarsToCheck = [
2873
- "DISABLE_NESTJS_PRISMA_GRAPHQL",
2874
- "CI_SKIP_PRISMA_GRAPHQL",
2875
- "PRISMA_GENERATOR_SKIP",
2876
- "SKIP_PRISMA_GENERATE"
2877
- ];
2878
- for (const envVar of envVarsToCheck) {
2879
- const value = env[envVar];
2880
- if (value === "true" || value === "1") {
2881
- return true;
2882
- }
2883
- }
2884
- const configDisabled = options.generator.config.disabled;
2885
- if (configDisabled === "true" || configDisabled === "1" || configDisabled === "yes") {
2886
- return true;
2887
- }
2888
- return false;
2889
- }
2890
- function countFilesRecursive(dir) {
2891
- let count = 0;
2892
- const readDirSyncTyped = readdirSync;
2893
- const rawEntries = readDirSyncTyped(dir, { withFileTypes: true });
2894
- const entries = rawEntries;
2895
- for (const entry of entries) {
2896
- const isDir = typeof entry.isDirectory === "function" ? entry.isDirectory() : false;
2897
- if (isDir) {
2898
- count += countFilesRecursive(`${dir}/${entry.name}`);
2899
- } else {
2900
- count++;
2901
- }
2902
- }
2903
- return count;
2904
- }
2905
- var globalConsole22 = globalThis.console;
2906
- var log2 = (msg) => {
2907
- globalConsole22.log(msg);
2908
- };
2909
- generatorHandler({
2910
- async onGenerate(options) {
2911
- if (isGeneratorDisabled(options)) {
2912
- log2(
2913
- "nestjs-prisma-graphql: generation skipped (disabled via environment variable or config)"
2914
- );
2915
- return;
2916
- }
2917
- const outputPath = options.generator.output?.value ?? "<unknown>";
2918
- const startTime = Date.now();
2919
- const archTyped = arch;
2920
- const platformTyped = platform;
2921
- const archValue = String(archTyped());
2922
- const platformValue = String(platformTyped());
2923
- const globalProcess2Raw = process;
2924
- const processWithVersion = globalProcess2Raw;
2925
- const nodeVersion = processWithVersion.version;
2926
- log2(
2927
- [
2928
- "nestjs-prisma-graphql: starting generation",
2929
- `(arch=${archValue}, platform=${platformValue}, node=${nodeVersion}, output=${outputPath})`
2930
- ].join(" ")
2931
- );
2932
- try {
2933
- await generate(options);
2934
- } catch (error) {
2935
- const elapsed2 = Date.now() - startTime;
2936
- const message = error instanceof Error ? error.message : String(error);
2937
- const stack = error instanceof Error ? error.stack : void 0;
2938
- log2(
2939
- `nestjs-prisma-graphql: generation FAILED after ${String(elapsed2)}ms: ${message}`
2940
- );
2941
- if (typeof stack === "string") {
2942
- log2(stack);
2943
- }
2944
- throw error;
2945
- }
2946
- const elapsed = Date.now() - startTime;
2947
- const existsSyncTyped2 = existsSync;
2948
- const pathExists = typeof outputPath === "string" && outputPath !== "<unknown>" && existsSyncTyped2(outputPath);
2949
- if (pathExists) {
2950
- const fileCount = countFilesRecursive(outputPath);
2951
- log2(
2952
- `nestjs-prisma-graphql: generated ${String(fileCount)} files in ${String(elapsed)}ms`
2953
- );
2954
- if (fileCount === 0) {
2955
- const msg = "nestjs-prisma-graphql: generation produced 0 files \u2014 this likely indicates a silent failure";
2956
- log2(msg);
2957
- throw new Error(msg);
2958
- }
2959
- } else {
2960
- const msg = `nestjs-prisma-graphql: output directory not found after generation: ${outputPath}`;
2961
- log2(msg);
2962
- throw new Error(msg);
2963
- }
2964
- },
2965
- onManifest() {
2966
- return {
2967
- defaultOutput: ".",
2968
- prettyName: "NestJS Prisma GraphQL (ESM)"
2969
- };
2970
- }
2971
153
  });
2972
-
2973
- export { isGeneratorDisabled };
2974
- //# sourceMappingURL=index.js.map
2975
154
  //# sourceMappingURL=index.js.map