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