@zenstackhq/trpc 1.0.0-alpha.99 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/generator.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { DMMF } from '@prisma/generator-helper';
1
+ import type { DMMF } from '@prisma/generator-helper';
2
2
  import { PluginOptions } from '@zenstackhq/sdk';
3
3
  import { Model } from '@zenstackhq/sdk/ast';
4
4
  export declare function generate(model: Model, options: PluginOptions, dmmf: DMMF.Document): Promise<void>;
package/generator.js CHANGED
@@ -25,42 +25,51 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.generate = void 0;
27
27
  const sdk_1 = require("@zenstackhq/sdk");
28
- const change_case_1 = require("change-case");
29
- const fs_1 = require("fs");
28
+ const fs_1 = __importDefault(require("fs"));
29
+ const lower_case_first_1 = require("lower-case-first");
30
30
  const path_1 = __importDefault(require("path"));
31
+ const ts_morph_1 = require("ts-morph");
32
+ const upper_case_first_1 = require("upper-case-first");
33
+ const _1 = require(".");
31
34
  const helpers_1 = require("./helpers");
32
35
  const project_1 = require("./project");
33
36
  const removeDir_1 = __importDefault(require("./utils/removeDir"));
34
- const generator_1 = require("./zod/generator");
35
37
  function generate(model, options, dmmf) {
38
+ var _a;
36
39
  return __awaiter(this, void 0, void 0, function* () {
37
- let outDir = options.output;
38
- if (!outDir) {
39
- throw new sdk_1.PluginError('"output" option is required');
40
+ let outDir = (0, sdk_1.requireOption)(options, 'output');
41
+ outDir = (0, sdk_1.resolvePath)(outDir, options);
42
+ // resolve "generateModelActions" option
43
+ const generateModelActions = parseOptionAsStrings(options, 'generateModelActions');
44
+ // resolve "generateClientHelpers" option
45
+ const generateClientHelpers = parseOptionAsStrings(options, 'generateClientHelpers');
46
+ if (generateClientHelpers && !generateClientHelpers.every((v) => ['react', 'next'].includes(v))) {
47
+ throw new sdk_1.PluginError(_1.name, `Option "generateClientHelpers" only support values "react" and "next"`);
40
48
  }
41
- if (!path_1.default.isAbsolute(outDir)) {
42
- // output dir is resolved relative to the schema file path
43
- outDir = path_1.default.join(path_1.default.dirname(options.schemaPath), outDir);
49
+ if (options.zodSchemasImport && typeof options.zodSchemasImport !== 'string') {
50
+ throw new sdk_1.PluginError(_1.name, `Option "zodSchemasImport" must be a string`);
44
51
  }
45
- yield fs_1.promises.mkdir(outDir, { recursive: true });
52
+ yield fs_1.default.promises.mkdir(outDir, { recursive: true });
46
53
  yield (0, removeDir_1.default)(outDir, true);
47
- yield (0, generator_1.generate)(model, options, dmmf);
48
54
  const prismaClientDmmf = dmmf;
49
55
  const modelOperations = prismaClientDmmf.mappings.modelOperations;
50
56
  const models = prismaClientDmmf.datamodel.models;
51
57
  const hiddenModels = [];
52
58
  (0, helpers_1.resolveModelsComments)(models, hiddenModels);
53
- createAppRouter(outDir, modelOperations, hiddenModels);
59
+ const zodSchemasImport = (_a = options.zodSchemasImport) !== null && _a !== void 0 ? _a : '@zenstackhq/runtime/zod';
60
+ createAppRouter(outDir, modelOperations, hiddenModels, generateModelActions, generateClientHelpers, model, zodSchemasImport);
54
61
  createHelper(outDir);
55
- yield project_1.project.save();
62
+ yield (0, sdk_1.saveProject)(project_1.project);
56
63
  });
57
64
  }
58
65
  exports.generate = generate;
59
- function createAppRouter(outDir, modelOperations, hiddenModels) {
60
- const appRouter = project_1.project.createSourceFile(path_1.default.resolve(outDir, 'routers', `index.ts`), undefined, {
66
+ function createAppRouter(outDir, modelOperations, hiddenModels, generateModelActions, generateClientHelpers, zmodel, zodSchemasImport) {
67
+ const indexFile = path_1.default.resolve(outDir, 'routers', `index.ts`);
68
+ const appRouter = project_1.project.createSourceFile(indexFile, undefined, {
61
69
  overwrite: true,
62
70
  });
63
71
  appRouter.addStatements('/* eslint-disable */');
72
+ const prismaImport = (0, sdk_1.getPrismaClientImportSpec)(zmodel, path_1.default.dirname(indexFile));
64
73
  appRouter.addImportDeclarations([
65
74
  {
66
75
  namedImports: ['AnyRootConfig'],
@@ -68,10 +77,10 @@ function createAppRouter(outDir, modelOperations, hiddenModels) {
68
77
  },
69
78
  {
70
79
  namedImports: ['PrismaClient'],
71
- moduleSpecifier: '@prisma/client',
80
+ moduleSpecifier: prismaImport,
72
81
  },
73
82
  {
74
- namedImports: ['createRouterFactory'],
83
+ namedImports: ['createRouterFactory', 'AnyRouter'],
75
84
  moduleSpecifier: '@trpc/server/dist/core/router',
76
85
  },
77
86
  {
@@ -98,35 +107,74 @@ function createAppRouter(outDir, modelOperations, hiddenModels) {
98
107
  }
99
108
 
100
109
  `);
101
- const createFunction = appRouter.addFunction({
110
+ const filteredModelOperations = modelOperations.filter((mo) => !hiddenModels.includes(mo.model));
111
+ appRouter
112
+ .addFunction({
102
113
  name: 'createRouter<Config extends BaseConfig>',
103
114
  parameters: [
104
115
  { name: 'router', type: 'RouterFactory<Config>' },
105
116
  { name: 'procedure', type: 'ProcBuilder<Config>' },
106
117
  ],
107
118
  isExported: true,
108
- });
109
- createFunction.setBodyText((writer) => {
119
+ })
120
+ .setBodyText((writer) => {
110
121
  writer.write('return router(');
111
122
  writer.block(() => {
112
- for (const modelOperation of modelOperations) {
123
+ for (const modelOperation of filteredModelOperations) {
113
124
  const { model } = modelOperation, operations = __rest(modelOperation, ["model"]);
114
- if (hiddenModels.includes(model)) {
115
- continue;
116
- }
117
- generateModelCreateRouter(project_1.project, model, operations, outDir);
125
+ generateModelCreateRouter(project_1.project, model, operations, outDir, generateModelActions, generateClientHelpers, zmodel, zodSchemasImport);
118
126
  appRouter.addImportDeclaration({
119
127
  defaultImport: `create${model}Router`,
120
128
  moduleSpecifier: `./${model}.router`,
121
129
  });
122
- writer.writeLine(`${(0, change_case_1.camelCase)(model)}: create${model}Router<Config>(router, procedure),`);
130
+ writer.writeLine(`${(0, lower_case_first_1.lowerCaseFirst)(model)}: create${model}Router<Config>(router, procedure),`);
123
131
  }
124
132
  });
125
133
  writer.write(');');
126
134
  });
135
+ if (generateClientHelpers) {
136
+ appRouter.addInterface({
137
+ name: 'ClientType',
138
+ typeParameters: ['AppRouter extends AnyRouter'],
139
+ isExported: true,
140
+ properties: filteredModelOperations.map(({ model }) => {
141
+ appRouter.addImportDeclaration({
142
+ namedImports: [{ name: 'ClientType', alias: `${(0, upper_case_first_1.upperCaseFirst)(model)}ClientType` }],
143
+ moduleSpecifier: `./${model}.router`,
144
+ });
145
+ return {
146
+ name: (0, lower_case_first_1.lowerCaseFirst)(model),
147
+ type: `${(0, upper_case_first_1.upperCaseFirst)(model)}ClientType<AppRouter>`,
148
+ };
149
+ }),
150
+ });
151
+ createClientHelpers(outDir, generateClientHelpers);
152
+ }
127
153
  appRouter.formatText();
128
154
  }
129
- function generateModelCreateRouter(project, model, operations, outputDir) {
155
+ function createClientHelpers(outputDir, generateClientHelpers) {
156
+ const utils = project_1.project.createSourceFile(path_1.default.resolve(outputDir, 'client', `utils.ts`), undefined, {
157
+ overwrite: true,
158
+ });
159
+ utils.replaceWithText(fs_1.default.readFileSync(path_1.default.join(__dirname, './res/client/utils.ts'), 'utf-8'));
160
+ for (const client of generateClientHelpers) {
161
+ switch (client) {
162
+ case 'react': {
163
+ const content = fs_1.default.readFileSync(path_1.default.join(__dirname, './res/client/react.ts'), 'utf-8');
164
+ project_1.project.createSourceFile(path_1.default.resolve(outputDir, 'client', 'react.ts'), content, {
165
+ overwrite: true,
166
+ });
167
+ break;
168
+ }
169
+ case 'next': {
170
+ const content = fs_1.default.readFileSync(path_1.default.join(__dirname, './res/client/next.ts'), 'utf-8');
171
+ project_1.project.createSourceFile(path_1.default.resolve(outputDir, 'client', 'next.ts'), content, { overwrite: true });
172
+ break;
173
+ }
174
+ }
175
+ }
176
+ }
177
+ function generateModelCreateRouter(project, model, operations, outputDir, generateModelActions, generateClientHelpers, zmodel, zodSchemasImport) {
130
178
  const modelRouter = project.createSourceFile(path_1.default.resolve(outputDir, 'routers', `${model}.router.ts`), undefined, {
131
179
  overwrite: true,
132
180
  });
@@ -137,10 +185,12 @@ function generateModelCreateRouter(project, model, operations, outputDir) {
137
185
  moduleSpecifier: '.',
138
186
  },
139
187
  ]);
140
- (0, helpers_1.generateRouterSchemaImports)(modelRouter, model);
188
+ (0, helpers_1.generateRouterSchemaImports)(modelRouter, model, zodSchemasImport);
141
189
  (0, helpers_1.generateHelperImport)(modelRouter);
142
- modelRouter
143
- .addFunction({
190
+ if (generateClientHelpers) {
191
+ (0, helpers_1.generateRouterTypingImports)(modelRouter, zmodel);
192
+ }
193
+ const createRouterFunc = modelRouter.addFunction({
144
194
  name: 'createRouter<Config extends BaseConfig>',
145
195
  parameters: [
146
196
  { name: 'router', type: 'RouterFactory<Config>' },
@@ -148,20 +198,48 @@ function generateModelCreateRouter(project, model, operations, outputDir) {
148
198
  ],
149
199
  isExported: true,
150
200
  isDefaultExport: true,
151
- })
152
- .setBodyText((writer) => {
153
- writer.write('return router(');
154
- writer.block(() => {
201
+ });
202
+ let routerTypingStructure = undefined;
203
+ if (generateClientHelpers) {
204
+ // generate an interface for precise Prisma-like typing for the router procedures
205
+ // which will be used to correct tRPC's typing on the client side
206
+ routerTypingStructure = {
207
+ kind: ts_morph_1.StructureKind.Interface,
208
+ name: 'ClientType',
209
+ isExported: true,
210
+ typeParameters: ['AppRouter extends AnyRouter', `Context = AppRouter['_def']['_config']['$types']['ctx']`],
211
+ properties: [],
212
+ };
213
+ }
214
+ createRouterFunc.setBodyText((funcWriter) => {
215
+ funcWriter.write('return router(');
216
+ funcWriter.block(() => {
217
+ var _a;
155
218
  for (const [opType, opNameWithModel] of Object.entries(operations)) {
156
219
  const baseOpType = opType.replace('OrThrow', '');
157
- const inputType = (0, helpers_1.getInputTypeByOpName)(baseOpType, model);
158
- if (opNameWithModel && inputType) {
159
- (0, helpers_1.generateProcedure)(writer, opType.replace(/One$/, ''), inputType, model, baseOpType);
220
+ const inputType = (0, helpers_1.getInputSchemaByOpName)(baseOpType, model);
221
+ const generateOpName = opType.replace(/One$/, '');
222
+ if (opNameWithModel &&
223
+ inputType &&
224
+ (!generateModelActions || generateModelActions.includes(generateOpName))) {
225
+ (0, helpers_1.generateProcedure)(funcWriter, generateOpName, inputType, model, baseOpType);
226
+ if (routerTypingStructure) {
227
+ (_a = routerTypingStructure.properties) === null || _a === void 0 ? void 0 : _a.push({
228
+ kind: ts_morph_1.StructureKind.PropertySignature,
229
+ name: generateOpName,
230
+ type: (writer) => {
231
+ (0, helpers_1.generateRouterTyping)(writer, generateOpName, model, baseOpType);
232
+ },
233
+ });
234
+ }
160
235
  }
161
236
  }
162
237
  });
163
- writer.write(');');
238
+ funcWriter.write(');');
164
239
  });
240
+ if (routerTypingStructure) {
241
+ modelRouter.addInterface(routerTypingStructure);
242
+ }
165
243
  modelRouter.formatText();
166
244
  }
167
245
  function createHelper(outDir) {
@@ -259,4 +337,24 @@ function createHelper(outDir) {
259
337
  `);
260
338
  checkRead.formatText();
261
339
  }
340
+ function parseOptionAsStrings(options, optionaName) {
341
+ const value = options[optionaName];
342
+ if (value === undefined) {
343
+ return undefined;
344
+ }
345
+ else if (typeof value === 'string') {
346
+ // comma separated string
347
+ return value
348
+ .split(',')
349
+ .filter((i) => !!i)
350
+ .map((i) => i.trim());
351
+ }
352
+ else if (Array.isArray(value) && value.every((i) => typeof i === 'string')) {
353
+ // string array
354
+ return value;
355
+ }
356
+ else {
357
+ throw new sdk_1.PluginError(_1.name, `Invalid "${optionaName}" option: must be a comma-separated string or an array of strings`);
358
+ }
359
+ }
262
360
  //# sourceMappingURL=generator.js.map
package/generator.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCAAiG;AAEjG,6CAAwC;AACxC,2BAAoC;AACpC,gDAAwB;AAExB,uCAMmB;AACnB,uCAAoC;AACpC,kEAA0C;AAC1C,+CAAiE;AAEjE,SAAsB,QAAQ,CAAC,KAAY,EAAE,OAAsB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CACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8BH,CACA,CAAC;IACF,SAAS,CAAC,UAAU,EAAE,CAAC;AAC3B,CAAC;AAED,SAAS,oBAAoB,CAAC,OAAsB,EAAE,WAAmB;IACrE,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACnC,IAAI,KAAK,KAAK,SAAS,EAAE;QACrB,OAAO,SAAS,CAAC;KACpB;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAClC,yBAAyB;QACzB,OAAO,KAAK;aACP,KAAK,CAAC,GAAG,CAAC;aACV,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;aAClB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;KAC7B;SAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,EAAE;QAC1E,eAAe;QACf,OAAO,KAAiB,CAAC;KAC5B;SAAM;QACH,MAAM,IAAI,iBAAW,CACjB,OAAI,EACJ,YAAY,WAAW,mEAAmE,CAC7F,CAAC;KACL;AACL,CAAC"}
package/helpers.d.ts CHANGED
@@ -1,8 +1,14 @@
1
- import { DMMF } from '@prisma/generator-helper';
1
+ import type { DMMF } from '@prisma/generator-helper';
2
+ import { Model } from '@zenstackhq/sdk/ast';
2
3
  import { CodeBlockWriter, SourceFile } from 'ts-morph';
3
4
  export declare function generateProcedure(writer: CodeBlockWriter, opType: string, typeName: string, modelName: string, baseOpType: string): void;
4
- export declare function generateRouterSchemaImports(sourceFile: SourceFile, name: string): void;
5
+ /**
6
+ * Generate precise Prisma-like typing for router procedures.
7
+ */
8
+ export declare function generateRouterTyping(writer: CodeBlockWriter, opType: string, modelName: string, baseOpType: string): void;
9
+ export declare function generateRouterTypingImports(sourceFile: SourceFile, model: Model): void;
10
+ export declare function generateRouterSchemaImports(sourceFile: SourceFile, name: string, zodSchemasImport: string): void;
5
11
  export declare function generateHelperImport(sourceFile: SourceFile): void;
6
- export declare const getInputTypeByOpName: (opName: string, modelName: string) => string | undefined;
12
+ export declare const getInputSchemaByOpName: (opName: string, modelName: string) => string | undefined;
7
13
  export declare const getProcedureTypeByOpName: (opName: string) => string | undefined;
8
14
  export declare function resolveModelsComments(models: DMMF.Model[], hiddenModels: string[]): void;
package/helpers.js CHANGED
@@ -1,81 +1,272 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveModelsComments = exports.getProcedureTypeByOpName = exports.getInputTypeByOpName = exports.generateHelperImport = exports.generateRouterSchemaImports = exports.generateProcedure = void 0;
4
- const uncapitalizeFirstLetter_1 = require("./utils/uncapitalizeFirstLetter");
3
+ exports.resolveModelsComments = exports.getProcedureTypeByOpName = exports.getInputSchemaByOpName = exports.generateHelperImport = exports.generateRouterSchemaImports = exports.generateRouterTypingImports = exports.generateRouterTyping = exports.generateProcedure = void 0;
4
+ const sdk_1 = require("@zenstackhq/sdk");
5
+ const lower_case_first_1 = require("lower-case-first");
6
+ const upper_case_first_1 = require("upper-case-first");
7
+ const _1 = require(".");
5
8
  function generateProcedure(writer, opType, typeName, modelName, baseOpType) {
6
9
  const procType = (0, exports.getProcedureTypeByOpName)(baseOpType);
7
10
  const prismaMethod = opType.replace('One', '');
8
11
  if (procType === 'query') {
12
+ // the cast "as any" is to circumvent a TS compiler misfired error in certain cases
9
13
  writer.write(`
10
- ${opType}: procedure.input(${typeName}).query(({ctx, input}) => checkRead(db(ctx).${(0, uncapitalizeFirstLetter_1.uncapitalizeFirstLetter)(modelName)}.${prismaMethod}(input))),
14
+ ${opType}: procedure.input(${typeName}).query(({ctx, input}) => checkRead(db(ctx).${(0, lower_case_first_1.lowerCaseFirst)(modelName)}.${prismaMethod}(input as any))),
11
15
  `);
12
16
  }
13
17
  else if (procType === 'mutation') {
18
+ // the cast "as any" is to circumvent a TS compiler misfired error in certain cases
14
19
  writer.write(`
15
- ${opType}: procedure.input(${typeName}).mutation(async ({ctx, input}) => checkMutate(db(ctx).${(0, uncapitalizeFirstLetter_1.uncapitalizeFirstLetter)(modelName)}.${prismaMethod}(input))),
20
+ ${opType}: procedure.input(${typeName}).mutation(async ({ctx, input}) => checkMutate(db(ctx).${(0, lower_case_first_1.lowerCaseFirst)(modelName)}.${prismaMethod}(input as any))),
16
21
  `);
17
22
  }
18
23
  }
19
24
  exports.generateProcedure = generateProcedure;
20
- function generateRouterSchemaImports(sourceFile, name) {
21
- sourceFile.addStatements(`import { ${name}Schema } from '../schemas/${name}.schema';`);
25
+ /**
26
+ * Given a model and Prisma operation, returns related TS types.
27
+ */
28
+ function getPrismaOperationTypes(model, operation) {
29
+ // TODO: find a way to derive from Prisma Client API's generic types
30
+ // instead of duplicating them
31
+ const capModel = (0, upper_case_first_1.upperCaseFirst)(model);
32
+ const capOperation = (0, upper_case_first_1.upperCaseFirst)(operation);
33
+ let genericBase = `Prisma.${capModel}${capOperation}Args`;
34
+ const getPayload = `Prisma.${capModel}GetPayload<T>`;
35
+ const selectSubset = `Prisma.SelectSubset<T, ${genericBase}>`;
36
+ let argsType;
37
+ let resultType;
38
+ switch (operation) {
39
+ case 'findUnique':
40
+ case 'findUniqueOrThrow':
41
+ case 'findFirst':
42
+ case 'findFirstOrThrow':
43
+ argsType = selectSubset;
44
+ resultType = getPayload;
45
+ break;
46
+ case 'findMany':
47
+ argsType = selectSubset;
48
+ resultType = `Array<${getPayload}>`;
49
+ break;
50
+ case 'create':
51
+ argsType = selectSubset;
52
+ resultType = getPayload;
53
+ break;
54
+ case 'createMany':
55
+ argsType = selectSubset;
56
+ resultType = `Prisma.BatchPayload`;
57
+ break;
58
+ case 'update':
59
+ argsType = selectSubset;
60
+ resultType = getPayload;
61
+ break;
62
+ case 'updateMany':
63
+ argsType = selectSubset;
64
+ resultType = `Prisma.BatchPayload`;
65
+ break;
66
+ case 'upsert':
67
+ argsType = selectSubset;
68
+ resultType = getPayload;
69
+ break;
70
+ case 'delete':
71
+ argsType = selectSubset;
72
+ resultType = getPayload;
73
+ break;
74
+ case 'deleteMany':
75
+ argsType = selectSubset;
76
+ resultType = `Prisma.BatchPayload`;
77
+ break;
78
+ case 'count':
79
+ argsType = `Prisma.Subset<T, ${genericBase}>`;
80
+ resultType = `'select' extends keyof T'
81
+ ? T['select'] extends true
82
+ ? number
83
+ : GetScalarType<T['select'], ${capModel}CountAggregateOutputType>
84
+ : number`;
85
+ break;
86
+ case 'aggregate':
87
+ argsType = `Prisma.Subset<T, ${genericBase}>`;
88
+ resultType = `Prisma.Get${capModel}AggregateType<T>`;
89
+ break;
90
+ case 'groupBy':
91
+ genericBase = `Prisma.${capModel}GroupByArgs,
92
+ HasSelectOrTake extends Prisma.Or<
93
+ Prisma.Extends<'skip', Prisma.Keys<T>>,
94
+ Prisma.Extends<'take', Prisma.Keys<T>>
95
+ >,
96
+ OrderByArg extends Prisma.True extends HasSelectOrTake
97
+ ? { orderBy: Prisma.${capModel}GroupByArgs['orderBy'] }
98
+ : { orderBy?: Prisma.${capModel}GroupByArgs['orderBy'] },
99
+ OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>,
100
+ ByFields extends Prisma.MaybeTupleToUnion<T['by']>,
101
+ ByValid extends Prisma.Has<ByFields, OrderFields>,
102
+ HavingFields extends Prisma.GetHavingFields<T['having']>,
103
+ HavingValid extends Prisma.Has<ByFields, HavingFields>,
104
+ ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False,
105
+ InputErrors extends ByEmpty extends Prisma.True
106
+ ? \`Error: "by" must not be empty.\`
107
+ : HavingValid extends Prisma.False
108
+ ? {
109
+ [P in HavingFields]: P extends ByFields
110
+ ? never
111
+ : P extends string
112
+ ? \`Error: Field "\${P}" used in "having" needs to be provided in "by".\`
113
+ : [
114
+ Error,
115
+ 'Field ',
116
+ P,
117
+ \` in "having" needs to be provided in "by"\`,
118
+ ]
119
+ }[HavingFields]
120
+ : 'take' extends Prisma.Keys<T>
121
+ ? 'orderBy' extends Prisma.Keys<T>
122
+ ? ByValid extends Prisma.True
123
+ ? {}
124
+ : {
125
+ [P in OrderFields]: P extends ByFields
126
+ ? never
127
+ : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
128
+ }[OrderFields]
129
+ : 'Error: If you provide "take", you also need to provide "orderBy"'
130
+ : 'skip' extends Prisma.Keys<T>
131
+ ? 'orderBy' extends Prisma.Keys<T>
132
+ ? ByValid extends Prisma.True
133
+ ? {}
134
+ : {
135
+ [P in OrderFields]: P extends ByFields
136
+ ? never
137
+ : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
138
+ }[OrderFields]
139
+ : 'Error: If you provide "skip", you also need to provide "orderBy"'
140
+ : ByValid extends Prisma.True
141
+ ? {}
142
+ : {
143
+ [P in OrderFields]: P extends ByFields
144
+ ? never
145
+ : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
146
+ }[OrderFields]
147
+ `;
148
+ argsType = `Prisma.SubsetIntersection<T, Prisma.${capModel}GroupByArgs, OrderByArg> & InputErrors`;
149
+ resultType = `{} extends InputErrors ? Prisma.Get${capModel}GroupByPayload<T> : InputErrors`;
150
+ break;
151
+ default:
152
+ throw new sdk_1.PluginError(_1.name, `Unsupported operation: "${operation}"`);
153
+ }
154
+ return { genericBase, argsType, resultType };
155
+ }
156
+ /**
157
+ * Generate precise Prisma-like typing for router procedures.
158
+ */
159
+ function generateRouterTyping(writer, opType, modelName, baseOpType) {
160
+ const procType = (0, exports.getProcedureTypeByOpName)(baseOpType);
161
+ const { genericBase, argsType, resultType } = getPrismaOperationTypes(modelName, opType);
162
+ const errorType = `TRPCClientErrorLike<AppRouter>`;
163
+ writer.block(() => {
164
+ if (procType === 'query') {
165
+ writer.writeLine(`
166
+ useQuery: <T extends ${genericBase}>(
167
+ input: ${argsType},
168
+ opts?: UseTRPCQueryOptions<string, T, ${resultType}, ${resultType}, Error>
169
+ ) => UseTRPCQueryResult<
170
+ ${resultType},
171
+ ${errorType}
172
+ >;
173
+ useInfiniteQuery: <T extends ${genericBase}>(
174
+ input: Omit<${argsType}, 'cursor'>,
175
+ opts?: UseTRPCInfiniteQueryOptions<string, T, ${resultType}, Error>
176
+ ) => UseTRPCInfiniteQueryResult<
177
+ ${resultType},
178
+ ${errorType}
179
+ >;
180
+ `);
181
+ }
182
+ else if (procType === 'mutation') {
183
+ writer.writeLine(`
184
+ useMutation: <T extends ${genericBase}>(opts?: UseTRPCMutationOptions<
185
+ ${genericBase},
186
+ ${errorType},
187
+ Prisma.${(0, upper_case_first_1.upperCaseFirst)(modelName)}GetPayload<null>,
188
+ Context
189
+ >,) =>
190
+ Omit<UseTRPCMutationResult<${resultType}, ${errorType}, ${argsType}, Context>, 'mutateAsync'> & {
191
+ mutateAsync:
192
+ <T extends ${genericBase}>(variables: T, opts?: UseTRPCMutationOptions<T, ${errorType}, ${resultType}, Context>) => Promise<${resultType}>
193
+ };
194
+ `);
195
+ }
196
+ });
197
+ }
198
+ exports.generateRouterTyping = generateRouterTyping;
199
+ function generateRouterTypingImports(sourceFile, model) {
200
+ const importingDir = sourceFile.getDirectoryPath();
201
+ const prismaImport = (0, sdk_1.getPrismaClientImportSpec)(model, importingDir);
202
+ sourceFile.addStatements([
203
+ `import type { Prisma } from '${prismaImport}';`,
204
+ `import type { UseTRPCMutationOptions, UseTRPCMutationResult, UseTRPCQueryOptions, UseTRPCQueryResult, UseTRPCInfiniteQueryOptions, UseTRPCInfiniteQueryResult } from '@trpc/react-query/shared';`,
205
+ `import type { TRPCClientErrorLike } from '@trpc/client';`,
206
+ `import type { AnyRouter } from '@trpc/server';`,
207
+ ]);
208
+ }
209
+ exports.generateRouterTypingImports = generateRouterTypingImports;
210
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
211
+ function generateRouterSchemaImports(sourceFile, name, zodSchemasImport) {
212
+ sourceFile.addStatements(`import { ${name}InputSchema } from '${zodSchemasImport}/input';`);
22
213
  }
23
214
  exports.generateRouterSchemaImports = generateRouterSchemaImports;
24
215
  function generateHelperImport(sourceFile) {
25
216
  sourceFile.addStatements(`import { checkRead, checkMutate } from '../helper';`);
26
217
  }
27
218
  exports.generateHelperImport = generateHelperImport;
28
- const getInputTypeByOpName = (opName, modelName) => {
219
+ const getInputSchemaByOpName = (opName, modelName) => {
29
220
  let inputType;
30
221
  switch (opName) {
31
222
  case 'findUnique':
32
- inputType = `${modelName}Schema.findUnique`;
223
+ inputType = `${modelName}InputSchema.findUnique`;
33
224
  break;
34
225
  case 'findFirst':
35
- inputType = `${modelName}Schema.findFirst`;
226
+ inputType = `${modelName}InputSchema.findFirst`;
36
227
  break;
37
228
  case 'findMany':
38
- inputType = `${modelName}Schema.findMany`;
229
+ inputType = `${modelName}InputSchema.findMany`;
39
230
  break;
40
231
  case 'findRaw':
41
- inputType = `${modelName}Schema.findRawObject`;
232
+ inputType = `${modelName}InputSchema.findRawObject`;
42
233
  break;
43
234
  case 'createOne':
44
- inputType = `${modelName}Schema.create`;
235
+ inputType = `${modelName}InputSchema.create`;
45
236
  break;
46
237
  case 'createMany':
47
- inputType = `${modelName}Schema.createMany`;
238
+ inputType = `${modelName}InputSchema.createMany`;
48
239
  break;
49
240
  case 'deleteOne':
50
- inputType = `${modelName}Schema.delete`;
241
+ inputType = `${modelName}InputSchema.delete`;
51
242
  break;
52
243
  case 'updateOne':
53
- inputType = `${modelName}Schema.update`;
244
+ inputType = `${modelName}InputSchema.update`;
54
245
  break;
55
246
  case 'deleteMany':
56
- inputType = `${modelName}Schema.deleteMany`;
247
+ inputType = `${modelName}InputSchema.deleteMany`;
57
248
  break;
58
249
  case 'updateMany':
59
- inputType = `${modelName}Schema.updateMany`;
250
+ inputType = `${modelName}InputSchema.updateMany`;
60
251
  break;
61
252
  case 'upsertOne':
62
- inputType = `${modelName}Schema.upsert`;
253
+ inputType = `${modelName}InputSchema.upsert`;
63
254
  break;
64
255
  case 'aggregate':
65
- inputType = `${modelName}Schema.aggregate`;
256
+ inputType = `${modelName}InputSchema.aggregate`;
66
257
  break;
67
258
  case 'aggregateRaw':
68
- inputType = `${modelName}Schema.aggregateRawObject`;
259
+ inputType = `${modelName}InputSchema.aggregateRawObject`;
69
260
  break;
70
261
  case 'groupBy':
71
- inputType = `${modelName}Schema.groupBy`;
262
+ inputType = `${modelName}InputSchema.groupBy`;
72
263
  break;
73
264
  default:
74
265
  console.log('getInputTypeByOpName: ', { opName, modelName });
75
266
  }
76
267
  return inputType;
77
268
  };
78
- exports.getInputTypeByOpName = getInputTypeByOpName;
269
+ exports.getInputSchemaByOpName = getInputSchemaByOpName;
79
270
  const getProcedureTypeByOpName = (opName) => {
80
271
  let procType;
81
272
  switch (opName) {