zenstack 0.6.0-pre.11 → 0.6.0-pre.13
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/cli/cli-error.d.ts +5 -0
- package/cli/cli-error.js +12 -0
- package/cli/cli-error.js.map +1 -0
- package/cli/cli-util.d.ts +18 -0
- package/cli/cli-util.js +168 -0
- package/cli/cli-util.js.map +1 -0
- package/cli/index.d.ts +10 -0
- package/cli/index.js +78 -6531
- package/cli/index.js.map +1 -0
- package/cli/plugin-runner.d.ts +14 -0
- package/cli/plugin-runner.js +133 -0
- package/cli/plugin-runner.js.map +1 -0
- package/global.d.js +1 -0
- package/global.d.js.map +1 -0
- package/language-server/constants.d.ts +12 -0
- package/language-server/constants.js +24 -0
- package/language-server/constants.js.map +1 -0
- package/language-server/main.d.ts +1 -0
- package/language-server/main.js +20 -6436
- package/language-server/main.js.map +1 -0
- package/language-server/types.d.ts +10 -0
- package/language-server/types.js +1 -0
- package/language-server/types.js.map +1 -0
- package/language-server/utils.d.ts +10 -0
- package/language-server/utils.js +28 -0
- package/language-server/utils.js.map +1 -0
- package/language-server/validator/attribute-validator.d.ts +9 -0
- package/language-server/validator/attribute-validator.js +15 -0
- package/language-server/validator/attribute-validator.js.map +1 -0
- package/language-server/validator/datamodel-validator.d.ts +16 -0
- package/language-server/validator/datamodel-validator.js +365 -0
- package/language-server/validator/datamodel-validator.js.map +1 -0
- package/language-server/validator/datasource-validator.d.ts +13 -0
- package/language-server/validator/datasource-validator.js +85 -0
- package/language-server/validator/datasource-validator.js.map +1 -0
- package/language-server/validator/enum-validator.d.ts +9 -0
- package/language-server/validator/enum-validator.js +18 -0
- package/language-server/validator/enum-validator.js.map +1 -0
- package/language-server/validator/expression-validator.d.ts +11 -0
- package/language-server/validator/expression-validator.js +40 -0
- package/language-server/validator/expression-validator.js.map +1 -0
- package/language-server/validator/schema-validator.d.ts +10 -0
- package/language-server/validator/schema-validator.js +35 -0
- package/language-server/validator/schema-validator.js.map +1 -0
- package/language-server/validator/utils.d.ts +24 -0
- package/language-server/validator/utils.js +116 -0
- package/language-server/validator/utils.js.map +1 -0
- package/language-server/validator/zmodel-validator.d.ts +21 -0
- package/language-server/validator/zmodel-validator.js +72 -0
- package/language-server/validator/zmodel-validator.js.map +1 -0
- package/language-server/zmodel-linker.d.ts +29 -0
- package/language-server/zmodel-linker.js +364 -0
- package/language-server/zmodel-linker.js.map +1 -0
- package/language-server/zmodel-module.d.ts +41 -0
- package/language-server/zmodel-module.js +84 -0
- package/language-server/zmodel-module.js.map +1 -0
- package/language-server/zmodel-scope.d.ts +10 -0
- package/language-server/zmodel-scope.js +34 -0
- package/language-server/zmodel-scope.js.map +1 -0
- package/language-server/zmodel-workspace-manager.d.ts +8 -0
- package/language-server/zmodel-workspace-manager.js +25 -0
- package/language-server/zmodel-workspace-manager.js.map +1 -0
- package/package.json +20 -15
- package/plugins/access-policy/expression-writer.d.ts +38 -0
- package/plugins/access-policy/expression-writer.js +323 -0
- package/plugins/access-policy/expression-writer.js.map +1 -0
- package/plugins/access-policy/index.d.ts +4 -0
- package/plugins/access-policy/index.js +15 -4289
- package/plugins/access-policy/index.js.map +1 -0
- package/plugins/access-policy/policy-guard-generator.d.ts +15 -0
- package/plugins/access-policy/policy-guard-generator.js +345 -0
- package/plugins/access-policy/policy-guard-generator.js.map +1 -0
- package/plugins/access-policy/typescript-expression-transformer.d.ts +26 -0
- package/plugins/access-policy/typescript-expression-transformer.js +110 -0
- package/plugins/access-policy/typescript-expression-transformer.js.map +1 -0
- package/plugins/access-policy/utils.d.ts +5 -0
- package/plugins/access-policy/utils.js +16 -0
- package/plugins/access-policy/utils.js.map +1 -0
- package/plugins/access-policy/zod-schema-generator.d.ts +12 -0
- package/plugins/access-policy/zod-schema-generator.js +174 -0
- package/plugins/access-policy/zod-schema-generator.js.map +1 -0
- package/plugins/model-meta/index.d.ts +4 -0
- package/plugins/model-meta/index.js +130 -0
- package/plugins/model-meta/index.js.map +1 -0
- package/plugins/plugin-utils.d.ts +16 -0
- package/plugins/plugin-utils.js +58 -0
- package/plugins/plugin-utils.js.map +1 -0
- package/plugins/prisma/indent-string.d.ts +4 -0
- package/plugins/prisma/indent-string.js +16 -0
- package/plugins/prisma/indent-string.js.map +1 -0
- package/plugins/prisma/index.d.ts +4 -0
- package/plugins/prisma/index.js +15 -3740
- package/plugins/prisma/index.js.map +1 -0
- package/plugins/prisma/prisma-builder.d.ts +123 -0
- package/plugins/prisma/prisma-builder.js +256 -0
- package/plugins/prisma/prisma-builder.js.map +1 -0
- package/plugins/prisma/schema-generator.d.ts +22 -0
- package/plugins/prisma/schema-generator.js +201 -0
- package/plugins/prisma/schema-generator.js.map +1 -0
- package/plugins/react-hooks/index.d.ts +4 -0
- package/plugins/react-hooks/index.js +14 -4332
- package/plugins/react-hooks/index.js.map +1 -0
- package/plugins/react-hooks/react-hooks-generator.d.ts +3 -0
- package/plugins/react-hooks/react-hooks-generator.js +333 -0
- package/plugins/react-hooks/react-hooks-generator.js.map +1 -0
- package/plugins/trpc/config.d.ts +9 -0
- package/plugins/trpc/config.js +12 -0
- package/plugins/trpc/config.js.map +1 -0
- package/plugins/trpc/generator.d.ts +4 -0
- package/plugins/trpc/generator.js +132 -0
- package/plugins/trpc/generator.js.map +1 -0
- package/plugins/trpc/helpers.d.ts +9 -0
- package/plugins/trpc/helpers.js +144 -0
- package/plugins/trpc/helpers.js.map +1 -0
- package/plugins/trpc/index.d.ts +5 -0
- package/plugins/trpc/index.js +14 -5401
- package/plugins/trpc/index.js.map +1 -0
- package/plugins/trpc/project.d.ts +2 -0
- package/plugins/trpc/project.js +21 -0
- package/plugins/trpc/project.js.map +1 -0
- package/plugins/trpc/types.d.ts +0 -0
- package/plugins/trpc/types.js +1 -0
- package/plugins/trpc/types.js.map +1 -0
- package/plugins/trpc/utils/removeDir.d.ts +1 -0
- package/plugins/trpc/utils/removeDir.js +22 -0
- package/plugins/trpc/utils/removeDir.js.map +1 -0
- package/plugins/trpc/utils/uncapitalizeFirstLetter.d.ts +1 -0
- package/plugins/trpc/utils/uncapitalizeFirstLetter.js +11 -0
- package/plugins/trpc/utils/uncapitalizeFirstLetter.js.map +1 -0
- package/plugins/zod/generator.d.ts +4 -0
- package/plugins/zod/generator.js +78 -0
- package/plugins/zod/generator.js.map +1 -0
- package/plugins/zod/helpers/aggregate-helpers.d.ts +5 -0
- package/plugins/zod/helpers/aggregate-helpers.js +77 -0
- package/plugins/zod/helpers/aggregate-helpers.js.map +1 -0
- package/plugins/zod/helpers/comments-helpers.d.ts +6 -0
- package/plugins/zod/helpers/comments-helpers.js +91 -0
- package/plugins/zod/helpers/comments-helpers.js.map +1 -0
- package/plugins/zod/helpers/helpers.d.ts +8 -0
- package/plugins/zod/helpers/helpers.js +39 -0
- package/plugins/zod/helpers/helpers.js.map +1 -0
- package/plugins/zod/helpers/include-helpers.d.ts +2 -0
- package/plugins/zod/helpers/include-helpers.js +94 -0
- package/plugins/zod/helpers/include-helpers.js.map +1 -0
- package/plugins/zod/helpers/index.d.ts +4 -0
- package/plugins/zod/helpers/index.js +50 -0
- package/plugins/zod/helpers/index.js.map +1 -0
- package/plugins/zod/helpers/model-helpers.d.ts +6 -0
- package/plugins/zod/helpers/model-helpers.js +50 -0
- package/plugins/zod/helpers/model-helpers.js.map +1 -0
- package/plugins/zod/helpers/modelArgs-helpers.d.ts +2 -0
- package/plugins/zod/helpers/modelArgs-helpers.js +62 -0
- package/plugins/zod/helpers/modelArgs-helpers.js.map +1 -0
- package/plugins/zod/helpers/mongodb-helpers.d.ts +3 -0
- package/plugins/zod/helpers/mongodb-helpers.js +63 -0
- package/plugins/zod/helpers/mongodb-helpers.js.map +1 -0
- package/plugins/zod/helpers/select-helpers.d.ts +2 -0
- package/plugins/zod/helpers/select-helpers.js +150 -0
- package/plugins/zod/helpers/select-helpers.js.map +1 -0
- package/plugins/zod/index.d.ts +5 -0
- package/plugins/zod/index.js +14 -4824
- package/plugins/zod/index.js.map +1 -0
- package/plugins/zod/transformer.d.ts +70 -0
- package/plugins/zod/transformer.js +464 -0
- package/plugins/zod/transformer.js.map +1 -0
- package/plugins/zod/types.d.ts +20 -0
- package/plugins/zod/types.js +1 -0
- package/plugins/zod/types.js.map +1 -0
- package/plugins/zod/utils/formatFile.d.ts +1 -0
- package/plugins/zod/utils/formatFile.js +35 -0
- package/plugins/zod/utils/formatFile.js.map +1 -0
- package/plugins/zod/utils/removeDir.d.ts +1 -0
- package/plugins/zod/utils/removeDir.js +22 -0
- package/plugins/zod/utils/removeDir.js.map +1 -0
- package/plugins/zod/utils/writeFileSafely.d.ts +1 -0
- package/plugins/zod/utils/writeFileSafely.js +18 -0
- package/plugins/zod/utils/writeFileSafely.js.map +1 -0
- package/res/prism-zmodel.js +2 -4
- package/res/stdlib.zmodel +12 -1
- package/telemetry.d.ts +21 -0
- package/telemetry.js +102 -0
- package/telemetry.js.map +1 -0
- package/types.d.ts +11 -0
- package/types.js +1 -0
- package/types.js.map +1 -0
- package/utils/ast-utils.d.ts +15 -0
- package/utils/ast-utils.js +79 -0
- package/utils/ast-utils.js.map +1 -0
- package/utils/exec-utils.d.ts +6 -0
- package/utils/exec-utils.js +17 -0
- package/utils/exec-utils.js.map +1 -0
- package/utils/indent-string.d.ts +4 -0
- package/utils/indent-string.js +16 -0
- package/utils/indent-string.js.map +1 -0
- package/utils/pkg-utils.d.ts +3 -0
- package/utils/pkg-utils.js +43 -0
- package/utils/pkg-utils.js.map +1 -0
- package/asset/logo-256-bg.png +0 -0
- package/asset/logo-dark-256.png +0 -0
- package/asset/logo-light-256.png +0 -0
- package/extension.js +0 -39
- package/res/package.template.json +0 -9
- package/res/tsconfig.template.json +0 -17
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["name","run","model","options","generate"],"sources":["../../../src/plugins/react-hooks/index.ts"],"sourcesContent":["import { Model } from '@zenstackhq/language/ast';\nimport { PluginOptions } from '@zenstackhq/sdk';\nimport { generate } from './react-hooks-generator';\n\nexport const name = 'React Hooks';\n\nexport default async function run(model: Model, options: PluginOptions) {\n return generate(model, options);\n}\n"],"mappings":";;;;;;;AAEA;AAEO,MAAMA,IAAI,GAAG,aAAa;AAAC;AAEnB,eAAeC,GAAG,CAACC,KAAY,EAAEC,OAAsB,EAAE;EACpE,OAAO,IAAAC,6BAAQ,EAACF,KAAK,EAAEC,OAAO,CAAC;AACnC"}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.generate = generate;
|
|
7
|
+
var _ast = require("@zenstackhq/language/ast");
|
|
8
|
+
var _changeCase = require("change-case");
|
|
9
|
+
var path = _interopRequireWildcard(require("path"));
|
|
10
|
+
var _tsMorph = require("ts-morph");
|
|
11
|
+
var _pluginUtils = require("../plugin-utils");
|
|
12
|
+
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
|
|
13
|
+
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
|
14
|
+
async function generate(model, options) {
|
|
15
|
+
const project = new _tsMorph.Project();
|
|
16
|
+
const models = [];
|
|
17
|
+
const warnings = [];
|
|
18
|
+
for (const dm of model.declarations.filter(d => (0, _ast.isDataModel)(d))) {
|
|
19
|
+
const hasAllowRule = dm.attributes.find(attr => {
|
|
20
|
+
var _attr$decl$ref;
|
|
21
|
+
return ((_attr$decl$ref = attr.decl.ref) === null || _attr$decl$ref === void 0 ? void 0 : _attr$decl$ref.name) === '@@allow';
|
|
22
|
+
});
|
|
23
|
+
if (!hasAllowRule) {
|
|
24
|
+
warnings.push(`Not generating hooks for "${dm.name}" because it doesn't have any @@allow rule`);
|
|
25
|
+
} else {
|
|
26
|
+
models.push(dm);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const outDir = options.output ?? 'node_modules/.zenstack/src/hooks';
|
|
30
|
+
generateIndex(project, outDir, models);
|
|
31
|
+
models.forEach(d => generateModelHooks(project, outDir, d));
|
|
32
|
+
await project.save();
|
|
33
|
+
return warnings;
|
|
34
|
+
}
|
|
35
|
+
function wrapReadbackErrorCheck(code) {
|
|
36
|
+
return `try {
|
|
37
|
+
${code}
|
|
38
|
+
} catch (err: any) {
|
|
39
|
+
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2004') {
|
|
40
|
+
// unable to readback data
|
|
41
|
+
return undefined;
|
|
42
|
+
} else {
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
}`;
|
|
46
|
+
}
|
|
47
|
+
function generateModelHooks(project, outDir, model) {
|
|
48
|
+
const fileName = (0, _changeCase.paramCase)(model.name);
|
|
49
|
+
const sf = project.createSourceFile(path.join(outDir, `${fileName}.ts`), undefined, {
|
|
50
|
+
overwrite: true
|
|
51
|
+
});
|
|
52
|
+
sf.addImportDeclaration({
|
|
53
|
+
namedImports: [{
|
|
54
|
+
name: 'Prisma'
|
|
55
|
+
}, `type ${model.name}`],
|
|
56
|
+
moduleSpecifier: '@prisma/client'
|
|
57
|
+
});
|
|
58
|
+
sf.addStatements([`import { useContext } from 'react';`, `import { RequestHandlerContext } from '@zenstackhq/next';`, `import * as request from '${_pluginUtils.RUNTIME_PACKAGE}/request';`, `import { RequestOptions } from '${_pluginUtils.RUNTIME_PACKAGE}/types';`]);
|
|
59
|
+
const useFunc = sf.addFunction({
|
|
60
|
+
name: `use${model.name}`,
|
|
61
|
+
isExported: true
|
|
62
|
+
});
|
|
63
|
+
useFunc.addStatements(['const mutate = request.getMutate();', 'const { endpoint } = useContext(RequestHandlerContext);']);
|
|
64
|
+
|
|
65
|
+
// create
|
|
66
|
+
{
|
|
67
|
+
const argsType = `Prisma.${model.name}CreateArgs`;
|
|
68
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
69
|
+
const returnType = `Prisma.CheckSelect<T, ${model.name}, Prisma.${model.name}GetPayload<T>>`;
|
|
70
|
+
useFunc.addFunction({
|
|
71
|
+
name: 'create',
|
|
72
|
+
isAsync: true,
|
|
73
|
+
typeParameters: [`T extends ${argsType}`],
|
|
74
|
+
parameters: [{
|
|
75
|
+
name: 'args',
|
|
76
|
+
type: inputType
|
|
77
|
+
}]
|
|
78
|
+
}).addBody().addStatements([wrapReadbackErrorCheck(`return await request.post<${inputType}, ${returnType}>(\`\${endpoint}/${model.name}/create\`, args, mutate);`)]);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// createMany
|
|
82
|
+
{
|
|
83
|
+
const argsType = `Prisma.${model.name}CreateManyArgs`;
|
|
84
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
85
|
+
const returnType = `Prisma.BatchPayload`;
|
|
86
|
+
useFunc.addFunction({
|
|
87
|
+
name: 'createMany',
|
|
88
|
+
isAsync: true,
|
|
89
|
+
typeParameters: [`T extends ${argsType}`],
|
|
90
|
+
parameters: [{
|
|
91
|
+
name: 'args',
|
|
92
|
+
type: inputType
|
|
93
|
+
}]
|
|
94
|
+
}).addBody().addStatements([`return await request.post<${inputType}, ${returnType}>(\`\${endpoint}/${model.name}/createMany\`, args, mutate);`]);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// findMany
|
|
98
|
+
{
|
|
99
|
+
const argsType = `Prisma.${model.name}FindManyArgs`;
|
|
100
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
101
|
+
const returnType = `Array<Prisma.${model.name}GetPayload<T>>`;
|
|
102
|
+
useFunc.addFunction({
|
|
103
|
+
name: 'findMany',
|
|
104
|
+
typeParameters: [`T extends ${argsType}`],
|
|
105
|
+
parameters: [{
|
|
106
|
+
name: 'args?',
|
|
107
|
+
type: inputType
|
|
108
|
+
}, {
|
|
109
|
+
name: 'options?',
|
|
110
|
+
type: `RequestOptions<${returnType}>`
|
|
111
|
+
}]
|
|
112
|
+
}).addBody().addStatements([`return request.get<${returnType}>(\`\${endpoint}/${model.name}/findMany\`, args, options);`]);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// findUnique
|
|
116
|
+
{
|
|
117
|
+
const argsType = `Prisma.${model.name}FindUniqueArgs`;
|
|
118
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
119
|
+
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
120
|
+
useFunc.addFunction({
|
|
121
|
+
name: 'findUnique',
|
|
122
|
+
typeParameters: [`T extends ${argsType}`],
|
|
123
|
+
parameters: [{
|
|
124
|
+
name: 'args',
|
|
125
|
+
type: inputType
|
|
126
|
+
}, {
|
|
127
|
+
name: 'options?',
|
|
128
|
+
type: `RequestOptions<${returnType}>`
|
|
129
|
+
}]
|
|
130
|
+
}).addBody().addStatements([`return request.get<${returnType}>(\`\${endpoint}/${model.name}/findUnique\`, args, options);`]);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// findFirst
|
|
134
|
+
{
|
|
135
|
+
const argsType = `Prisma.${model.name}FindFirstArgs`;
|
|
136
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
137
|
+
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
138
|
+
useFunc.addFunction({
|
|
139
|
+
name: 'findFirst',
|
|
140
|
+
typeParameters: [`T extends ${argsType}`],
|
|
141
|
+
parameters: [{
|
|
142
|
+
name: 'args',
|
|
143
|
+
type: inputType
|
|
144
|
+
}, {
|
|
145
|
+
name: 'options?',
|
|
146
|
+
type: `RequestOptions<${returnType}>`
|
|
147
|
+
}]
|
|
148
|
+
}).addBody().addStatements([`return request.get<${returnType}>(\`\${endpoint}/${model.name}/findFirst\`, args, options);`]);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// update
|
|
152
|
+
{
|
|
153
|
+
const argsType = `Prisma.${model.name}UpdateArgs`;
|
|
154
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
155
|
+
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
156
|
+
useFunc.addFunction({
|
|
157
|
+
name: 'update',
|
|
158
|
+
isAsync: true,
|
|
159
|
+
typeParameters: [`T extends ${argsType}`],
|
|
160
|
+
parameters: [{
|
|
161
|
+
name: 'args',
|
|
162
|
+
type: inputType
|
|
163
|
+
}]
|
|
164
|
+
}).addBody().addStatements([wrapReadbackErrorCheck(`return await request.put<${inputType}, ${returnType}>(\`\${endpoint}/${model.name}/update\`, args, mutate);`)]);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// updateMany
|
|
168
|
+
{
|
|
169
|
+
const argsType = `Prisma.${model.name}UpdateManyArgs`;
|
|
170
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
171
|
+
const returnType = `Prisma.BatchPayload`;
|
|
172
|
+
useFunc.addFunction({
|
|
173
|
+
name: 'updateMany',
|
|
174
|
+
isAsync: true,
|
|
175
|
+
typeParameters: [`T extends ${argsType}`],
|
|
176
|
+
parameters: [{
|
|
177
|
+
name: 'args',
|
|
178
|
+
type: inputType
|
|
179
|
+
}]
|
|
180
|
+
}).addBody().addStatements([`return await request.put<${inputType}, ${returnType}>(\`\${endpoint}/${model.name}/updateMany\`, args, mutate);`]);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// upsert
|
|
184
|
+
{
|
|
185
|
+
const argsType = `Prisma.${model.name}UpsertArgs`;
|
|
186
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
187
|
+
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
188
|
+
useFunc.addFunction({
|
|
189
|
+
name: 'upsert',
|
|
190
|
+
isAsync: true,
|
|
191
|
+
typeParameters: [`T extends ${argsType}`],
|
|
192
|
+
parameters: [{
|
|
193
|
+
name: 'args',
|
|
194
|
+
type: inputType
|
|
195
|
+
}]
|
|
196
|
+
}).addBody().addStatements([wrapReadbackErrorCheck(`return await request.put<${inputType}, ${returnType}>(\`\${endpoint}/${model.name}/upsert\`, args, mutate);`)]);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// del
|
|
200
|
+
{
|
|
201
|
+
const argsType = `Prisma.${model.name}DeleteArgs`;
|
|
202
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
203
|
+
const returnType = `Prisma.${model.name}GetPayload<T>`;
|
|
204
|
+
useFunc.addFunction({
|
|
205
|
+
name: 'del',
|
|
206
|
+
isAsync: true,
|
|
207
|
+
typeParameters: [`T extends ${argsType}`],
|
|
208
|
+
parameters: [{
|
|
209
|
+
name: 'args?',
|
|
210
|
+
type: inputType
|
|
211
|
+
}]
|
|
212
|
+
}).addBody().addStatements([wrapReadbackErrorCheck(`return await request.del<${returnType}>(\`\${endpoint}/${model.name}/delete\`, args, mutate);`)]);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// deleteMany
|
|
216
|
+
{
|
|
217
|
+
const argsType = `Prisma.${model.name}DeleteManyArgs`;
|
|
218
|
+
const inputType = `Prisma.SelectSubset<T, ${argsType}>`;
|
|
219
|
+
const returnType = `Prisma.BatchPayload`;
|
|
220
|
+
useFunc.addFunction({
|
|
221
|
+
name: 'deleteMany',
|
|
222
|
+
isAsync: true,
|
|
223
|
+
typeParameters: [`T extends ${argsType}`],
|
|
224
|
+
parameters: [{
|
|
225
|
+
name: 'args?',
|
|
226
|
+
type: inputType
|
|
227
|
+
}]
|
|
228
|
+
}).addBody().addStatements([`return await request.del<${returnType}>(\`\${endpoint}/${model.name}/deleteMany\`, args, mutate);`]);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// aggregate
|
|
232
|
+
{
|
|
233
|
+
const argsType = `Prisma.${model.name}AggregateArgs`;
|
|
234
|
+
const inputType = `Prisma.Subset<T, ${argsType}>`;
|
|
235
|
+
const returnType = `Prisma.Get${model.name}AggregateType<T>`;
|
|
236
|
+
useFunc.addFunction({
|
|
237
|
+
name: 'aggregate',
|
|
238
|
+
typeParameters: [`T extends ${argsType}`],
|
|
239
|
+
parameters: [{
|
|
240
|
+
name: 'args',
|
|
241
|
+
type: inputType
|
|
242
|
+
}, {
|
|
243
|
+
name: 'options?',
|
|
244
|
+
type: `RequestOptions<${returnType}>`
|
|
245
|
+
}]
|
|
246
|
+
}).addBody().addStatements([`return request.get<${returnType}>(\`\${endpoint}/${model.name}/aggregate\`, args, options);`]);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// groupBy
|
|
250
|
+
{
|
|
251
|
+
const returnType = `{} extends InputErrors ? Prisma.Get${model.name}GroupByPayload<T> : InputErrors`;
|
|
252
|
+
useFunc.addFunction({
|
|
253
|
+
name: 'groupBy',
|
|
254
|
+
typeParameters: [`T extends Prisma.${model.name}GroupByArgs`, `HasSelectOrTake extends Prisma.Or<Prisma.Extends<'skip', Prisma.Keys<T>>, Prisma.Extends<'take', Prisma.Keys<T>>>`, `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.UserGroupByArgs['orderBy'] }: { orderBy?: Prisma.UserGroupByArgs['orderBy'] },`, `OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>`, `ByFields extends Prisma.TupleToUnion<T['by']>`, `ByValid extends Prisma.Has<ByFields, OrderFields>`, `HavingFields extends Prisma.GetHavingFields<T['having']>`, `HavingValid extends Prisma.Has<ByFields, HavingFields>`, `ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False`, `InputErrors extends ByEmpty extends Prisma.True
|
|
255
|
+
? \`Error: "by" must not be empty.\`
|
|
256
|
+
: HavingValid extends Prisma.False
|
|
257
|
+
? {
|
|
258
|
+
[P in HavingFields]: P extends ByFields
|
|
259
|
+
? never
|
|
260
|
+
: P extends string
|
|
261
|
+
? \`Error: Field "\${P}" used in "having" needs to be provided in "by".\`
|
|
262
|
+
: [
|
|
263
|
+
Error,
|
|
264
|
+
'Field ',
|
|
265
|
+
P,
|
|
266
|
+
\` in "having" needs to be provided in "by"\`,
|
|
267
|
+
]
|
|
268
|
+
}[HavingFields]
|
|
269
|
+
: 'take' extends Prisma.Keys<T>
|
|
270
|
+
? 'orderBy' extends Prisma.Keys<T>
|
|
271
|
+
? ByValid extends Prisma.True
|
|
272
|
+
? {}
|
|
273
|
+
: {
|
|
274
|
+
[P in OrderFields]: P extends ByFields
|
|
275
|
+
? never
|
|
276
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
277
|
+
}[OrderFields]
|
|
278
|
+
: 'Error: If you provide "take", you also need to provide "orderBy"'
|
|
279
|
+
: 'skip' extends Prisma.Keys<T>
|
|
280
|
+
? 'orderBy' extends Prisma.Keys<T>
|
|
281
|
+
? ByValid extends Prisma.True
|
|
282
|
+
? {}
|
|
283
|
+
: {
|
|
284
|
+
[P in OrderFields]: P extends ByFields
|
|
285
|
+
? never
|
|
286
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
287
|
+
}[OrderFields]
|
|
288
|
+
: 'Error: If you provide "skip", you also need to provide "orderBy"'
|
|
289
|
+
: ByValid extends Prisma.True
|
|
290
|
+
? {}
|
|
291
|
+
: {
|
|
292
|
+
[P in OrderFields]: P extends ByFields
|
|
293
|
+
? never
|
|
294
|
+
: \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\`
|
|
295
|
+
}[OrderFields]`],
|
|
296
|
+
parameters: [{
|
|
297
|
+
name: 'args',
|
|
298
|
+
type: `Prisma.SubsetIntersection<T, Prisma.${model.name}GroupByArgs, OrderByArg> & InputErrors`
|
|
299
|
+
}, {
|
|
300
|
+
name: 'options?',
|
|
301
|
+
type: `RequestOptions<${returnType}>`
|
|
302
|
+
}]
|
|
303
|
+
}).addBody().addStatements([`return request.get<${returnType}>(\`\${endpoint}/${model.name}/groupBy\`, args, options);`]);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// count
|
|
307
|
+
{
|
|
308
|
+
const argsType = `Prisma.${model.name}CountArgs`;
|
|
309
|
+
const inputType = `Prisma.Subset<T, ${argsType}>`;
|
|
310
|
+
const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType<T['select'], Prisma.${model.name}CountAggregateOutputType> : number`;
|
|
311
|
+
useFunc.addFunction({
|
|
312
|
+
name: 'count',
|
|
313
|
+
typeParameters: [`T extends ${argsType}`],
|
|
314
|
+
parameters: [{
|
|
315
|
+
name: 'args',
|
|
316
|
+
type: inputType
|
|
317
|
+
}, {
|
|
318
|
+
name: 'options?',
|
|
319
|
+
type: `RequestOptions<${returnType}>`
|
|
320
|
+
}]
|
|
321
|
+
}).addBody().addStatements([`return request.get<${returnType}>(\`\${endpoint}/${model.name}/count\`, args, options);`]);
|
|
322
|
+
}
|
|
323
|
+
useFunc.addStatements(['return { create, createMany, findMany, findUnique, findFirst, update, updateMany, upsert, del, deleteMany, aggregate, groupBy, count };']);
|
|
324
|
+
sf.formatText();
|
|
325
|
+
}
|
|
326
|
+
function generateIndex(project, outDir, models) {
|
|
327
|
+
const sf = project.createSourceFile(path.join(outDir, 'index.ts'), undefined, {
|
|
328
|
+
overwrite: true
|
|
329
|
+
});
|
|
330
|
+
sf.addStatements(models.map(d => `export * from './${(0, _changeCase.paramCase)(d.name)}';`));
|
|
331
|
+
sf.formatText();
|
|
332
|
+
}
|
|
333
|
+
//# sourceMappingURL=react-hooks-generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react-hooks-generator.js","names":["generate","model","options","project","Project","models","warnings","dm","declarations","filter","d","isDataModel","hasAllowRule","attributes","find","attr","decl","ref","name","push","outDir","output","generateIndex","forEach","generateModelHooks","save","wrapReadbackErrorCheck","code","fileName","paramCase","sf","createSourceFile","path","join","undefined","overwrite","addImportDeclaration","namedImports","moduleSpecifier","addStatements","RUNTIME_PACKAGE","useFunc","addFunction","isExported","argsType","inputType","returnType","isAsync","typeParameters","parameters","type","addBody","formatText","map"],"sources":["../../../src/plugins/react-hooks/react-hooks-generator.ts"],"sourcesContent":["import { DataModel, Model, isDataModel } from '@zenstackhq/language/ast';\nimport { PluginOptions } from '@zenstackhq/sdk';\nimport { paramCase } from 'change-case';\nimport * as path from 'path';\nimport { Project } from 'ts-morph';\nimport { RUNTIME_PACKAGE } from '../plugin-utils';\n\nexport async function generate(model: Model, options: PluginOptions) {\n const project = new Project();\n const models: DataModel[] = [];\n const warnings: string[] = [];\n\n for (const dm of model.declarations.filter((d): d is DataModel => isDataModel(d))) {\n const hasAllowRule = dm.attributes.find((attr) => attr.decl.ref?.name === '@@allow');\n if (!hasAllowRule) {\n warnings.push(`Not generating hooks for \"${dm.name}\" because it doesn't have any @@allow rule`);\n } else {\n models.push(dm);\n }\n }\n\n const outDir = (options.output as string) ?? 'node_modules/.zenstack/src/hooks';\n\n generateIndex(project, outDir, models);\n\n models.forEach((d) => generateModelHooks(project, outDir, d));\n\n await project.save();\n return warnings;\n}\n\nfunction wrapReadbackErrorCheck(code: string) {\n return `try {\n ${code}\n } catch (err: any) {\n if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2004') {\n // unable to readback data\n return undefined;\n } else {\n throw err;\n }\n }`;\n}\n\nfunction generateModelHooks(project: Project, outDir: string, model: DataModel) {\n const fileName = paramCase(model.name);\n const sf = project.createSourceFile(path.join(outDir, `${fileName}.ts`), undefined, { overwrite: true });\n\n sf.addImportDeclaration({\n namedImports: [{ name: 'Prisma' }, `type ${model.name}`],\n moduleSpecifier: '@prisma/client',\n });\n sf.addStatements([\n `import { useContext } from 'react';`,\n `import { RequestHandlerContext } from '@zenstackhq/next';`,\n `import * as request from '${RUNTIME_PACKAGE}/request';`,\n `import { RequestOptions } from '${RUNTIME_PACKAGE}/types';`,\n ]);\n\n const useFunc = sf.addFunction({\n name: `use${model.name}`,\n isExported: true,\n });\n\n useFunc.addStatements([\n 'const mutate = request.getMutate();',\n 'const { endpoint } = useContext(RequestHandlerContext);',\n ]);\n\n // create\n {\n const argsType = `Prisma.${model.name}CreateArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.CheckSelect<T, ${model.name}, Prisma.${model.name}GetPayload<T>>`;\n useFunc\n .addFunction({\n name: 'create',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n wrapReadbackErrorCheck(\n `return await request.post<${inputType}, ${returnType}>(\\`\\${endpoint}/${model.name}/create\\`, args, mutate);`\n ),\n ]);\n }\n\n // createMany\n {\n const argsType = `Prisma.${model.name}CreateManyArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.BatchPayload`;\n useFunc\n .addFunction({\n name: 'createMany',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return await request.post<${inputType}, ${returnType}>(\\`\\${endpoint}/${model.name}/createMany\\`, args, mutate);`,\n ]);\n }\n\n // findMany\n {\n const argsType = `Prisma.${model.name}FindManyArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Array<Prisma.${model.name}GetPayload<T>>`;\n useFunc\n .addFunction({\n name: 'findMany',\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args?',\n type: inputType,\n },\n {\n name: 'options?',\n type: `RequestOptions<${returnType}>`,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return request.get<${returnType}>(\\`\\${endpoint}/${model.name}/findMany\\`, args, options);`,\n ]);\n }\n\n // findUnique\n {\n const argsType = `Prisma.${model.name}FindUniqueArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.${model.name}GetPayload<T>`;\n useFunc\n .addFunction({\n name: 'findUnique',\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n {\n name: 'options?',\n type: `RequestOptions<${returnType}>`,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return request.get<${returnType}>(\\`\\${endpoint}/${model.name}/findUnique\\`, args, options);`,\n ]);\n }\n\n // findFirst\n {\n const argsType = `Prisma.${model.name}FindFirstArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.${model.name}GetPayload<T>`;\n useFunc\n .addFunction({\n name: 'findFirst',\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n {\n name: 'options?',\n type: `RequestOptions<${returnType}>`,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return request.get<${returnType}>(\\`\\${endpoint}/${model.name}/findFirst\\`, args, options);`,\n ]);\n }\n\n // update\n {\n const argsType = `Prisma.${model.name}UpdateArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.${model.name}GetPayload<T>`;\n useFunc\n .addFunction({\n name: 'update',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n wrapReadbackErrorCheck(\n `return await request.put<${inputType}, ${returnType}>(\\`\\${endpoint}/${model.name}/update\\`, args, mutate);`\n ),\n ]);\n }\n\n // updateMany\n {\n const argsType = `Prisma.${model.name}UpdateManyArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.BatchPayload`;\n useFunc\n .addFunction({\n name: 'updateMany',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return await request.put<${inputType}, ${returnType}>(\\`\\${endpoint}/${model.name}/updateMany\\`, args, mutate);`,\n ]);\n }\n\n // upsert\n {\n const argsType = `Prisma.${model.name}UpsertArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.${model.name}GetPayload<T>`;\n useFunc\n .addFunction({\n name: 'upsert',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n wrapReadbackErrorCheck(\n `return await request.put<${inputType}, ${returnType}>(\\`\\${endpoint}/${model.name}/upsert\\`, args, mutate);`\n ),\n ]);\n }\n\n // del\n {\n const argsType = `Prisma.${model.name}DeleteArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.${model.name}GetPayload<T>`;\n useFunc\n .addFunction({\n name: 'del',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args?',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n wrapReadbackErrorCheck(\n `return await request.del<${returnType}>(\\`\\${endpoint}/${model.name}/delete\\`, args, mutate);`\n ),\n ]);\n }\n\n // deleteMany\n {\n const argsType = `Prisma.${model.name}DeleteManyArgs`;\n const inputType = `Prisma.SelectSubset<T, ${argsType}>`;\n const returnType = `Prisma.BatchPayload`;\n useFunc\n .addFunction({\n name: 'deleteMany',\n isAsync: true,\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args?',\n type: inputType,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return await request.del<${returnType}>(\\`\\${endpoint}/${model.name}/deleteMany\\`, args, mutate);`,\n ]);\n }\n\n // aggregate\n {\n const argsType = `Prisma.${model.name}AggregateArgs`;\n const inputType = `Prisma.Subset<T, ${argsType}>`;\n const returnType = `Prisma.Get${model.name}AggregateType<T>`;\n useFunc\n .addFunction({\n name: 'aggregate',\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n {\n name: 'options?',\n type: `RequestOptions<${returnType}>`,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return request.get<${returnType}>(\\`\\${endpoint}/${model.name}/aggregate\\`, args, options);`,\n ]);\n }\n\n // groupBy\n {\n const returnType = `{} extends InputErrors ? Prisma.Get${model.name}GroupByPayload<T> : InputErrors`;\n useFunc\n .addFunction({\n name: 'groupBy',\n typeParameters: [\n `T extends Prisma.${model.name}GroupByArgs`,\n `HasSelectOrTake extends Prisma.Or<Prisma.Extends<'skip', Prisma.Keys<T>>, Prisma.Extends<'take', Prisma.Keys<T>>>`,\n `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.UserGroupByArgs['orderBy'] }: { orderBy?: Prisma.UserGroupByArgs['orderBy'] },`,\n `OrderFields extends Prisma.ExcludeUnderscoreKeys<Prisma.Keys<Prisma.MaybeTupleToUnion<T['orderBy']>>>`,\n `ByFields extends Prisma.TupleToUnion<T['by']>`,\n `ByValid extends Prisma.Has<ByFields, OrderFields>`,\n `HavingFields extends Prisma.GetHavingFields<T['having']>`,\n `HavingValid extends Prisma.Has<ByFields, HavingFields>`,\n `ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False`,\n `InputErrors extends ByEmpty extends Prisma.True\n ? \\`Error: \"by\" must not be empty.\\`\n : HavingValid extends Prisma.False\n ? {\n [P in HavingFields]: P extends ByFields\n ? never\n : P extends string\n ? \\`Error: Field \"\\${P}\" used in \"having\" needs to be provided in \"by\".\\`\n : [\n Error,\n 'Field ',\n P,\n \\` in \"having\" needs to be provided in \"by\"\\`,\n ]\n }[HavingFields]\n : 'take' extends Prisma.Keys<T>\n ? 'orderBy' extends Prisma.Keys<T>\n ? ByValid extends Prisma.True\n ? {}\n : {\n [P in OrderFields]: P extends ByFields\n ? never\n : \\`Error: Field \"\\${P}\" in \"orderBy\" needs to be provided in \"by\"\\`\n }[OrderFields]\n : 'Error: If you provide \"take\", you also need to provide \"orderBy\"'\n : 'skip' extends Prisma.Keys<T>\n ? 'orderBy' extends Prisma.Keys<T>\n ? ByValid extends Prisma.True\n ? {}\n : {\n [P in OrderFields]: P extends ByFields\n ? never\n : \\`Error: Field \"\\${P}\" in \"orderBy\" needs to be provided in \"by\"\\`\n }[OrderFields]\n : 'Error: If you provide \"skip\", you also need to provide \"orderBy\"'\n : ByValid extends Prisma.True\n ? {}\n : {\n [P in OrderFields]: P extends ByFields\n ? never\n : \\`Error: Field \"\\${P}\" in \"orderBy\" needs to be provided in \"by\"\\`\n }[OrderFields]`,\n ],\n parameters: [\n {\n name: 'args',\n type: `Prisma.SubsetIntersection<T, Prisma.${model.name}GroupByArgs, OrderByArg> & InputErrors`,\n },\n {\n name: 'options?',\n type: `RequestOptions<${returnType}>`,\n },\n ],\n })\n .addBody()\n .addStatements([\n `return request.get<${returnType}>(\\`\\${endpoint}/${model.name}/groupBy\\`, args, options);`,\n ]);\n }\n\n // count\n {\n const argsType = `Prisma.${model.name}CountArgs`;\n const inputType = `Prisma.Subset<T, ${argsType}>`;\n const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType<T['select'], Prisma.${model.name}CountAggregateOutputType> : number`;\n useFunc\n .addFunction({\n name: 'count',\n typeParameters: [`T extends ${argsType}`],\n parameters: [\n {\n name: 'args',\n type: inputType,\n },\n {\n name: 'options?',\n type: `RequestOptions<${returnType}>`,\n },\n ],\n })\n .addBody()\n .addStatements([`return request.get<${returnType}>(\\`\\${endpoint}/${model.name}/count\\`, args, options);`]);\n }\n\n useFunc.addStatements([\n 'return { create, createMany, findMany, findUnique, findFirst, update, updateMany, upsert, del, deleteMany, aggregate, groupBy, count };',\n ]);\n\n sf.formatText();\n}\n\nfunction generateIndex(project: Project, outDir: string, models: DataModel[]) {\n const sf = project.createSourceFile(path.join(outDir, 'index.ts'), undefined, { overwrite: true });\n\n sf.addStatements(models.map((d) => `export * from './${paramCase(d.name)}';`));\n\n sf.formatText();\n}\n"],"mappings":";;;;;;AAAA;AAEA;AACA;AACA;AACA;AAAkD;AAAA;AAE3C,eAAeA,QAAQ,CAACC,KAAY,EAAEC,OAAsB,EAAE;EACjE,MAAMC,OAAO,GAAG,IAAIC,gBAAO,EAAE;EAC7B,MAAMC,MAAmB,GAAG,EAAE;EAC9B,MAAMC,QAAkB,GAAG,EAAE;EAE7B,KAAK,MAAMC,EAAE,IAAIN,KAAK,CAACO,YAAY,CAACC,MAAM,CAAEC,CAAC,IAAqB,IAAAC,gBAAW,EAACD,CAAC,CAAC,CAAC,EAAE;IAC/E,MAAME,YAAY,GAAGL,EAAE,CAACM,UAAU,CAACC,IAAI,CAAEC,IAAI;MAAA;MAAA,OAAK,mBAAAA,IAAI,CAACC,IAAI,CAACC,GAAG,mDAAb,eAAeC,IAAI,MAAK,SAAS;IAAA,EAAC;IACpF,IAAI,CAACN,YAAY,EAAE;MACfN,QAAQ,CAACa,IAAI,CAAE,6BAA4BZ,EAAE,CAACW,IAAK,4CAA2C,CAAC;IACnG,CAAC,MAAM;MACHb,MAAM,CAACc,IAAI,CAACZ,EAAE,CAAC;IACnB;EACJ;EAEA,MAAMa,MAAM,GAAIlB,OAAO,CAACmB,MAAM,IAAe,kCAAkC;EAE/EC,aAAa,CAACnB,OAAO,EAAEiB,MAAM,EAAEf,MAAM,CAAC;EAEtCA,MAAM,CAACkB,OAAO,CAAEb,CAAC,IAAKc,kBAAkB,CAACrB,OAAO,EAAEiB,MAAM,EAAEV,CAAC,CAAC,CAAC;EAE7D,MAAMP,OAAO,CAACsB,IAAI,EAAE;EACpB,OAAOnB,QA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A,SAAS9B,aAAa,CAACnB,OAAgB,EAAEiB,MAAc,EAAEf,MAAmB,EAAE;EAC1E,MAAMyB,EAAE,GAAG3B,OAAO,CAAC4B,gBAAgB,CAACC,IAAI,CAACC,IAAI,CAACb,MAAM,EAAE,UAAU,CAAC,EAAEc,SAAS,EAAE;IAAEC,SAAS,EAAE;EAAK,CAAC,CAAC;EAElGL,EAAE,CAACS,aAAa,CAAClC,MAAM,CAACgD,GAAG,CAAE3C,CAAC,IAAM,oBAAmB,IAAAmB,qBAAS,EAACnB,CAAC,CAACQ,IAAI,CAAE,IAAG,CAAC,CAAC;EAE9EY,EAAE,CAACsB,UAAU,EAAE;AACnB"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const configSchema: z.ZodObject<{
|
|
3
|
+
contextPath: z.ZodDefault<z.ZodString>;
|
|
4
|
+
}, "strip", z.ZodTypeAny, {
|
|
5
|
+
contextPath: string;
|
|
6
|
+
}, {
|
|
7
|
+
contextPath?: string | undefined;
|
|
8
|
+
}>;
|
|
9
|
+
export declare type Config = z.infer<typeof configSchema>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.configSchema = void 0;
|
|
7
|
+
var _zod = require("zod");
|
|
8
|
+
const configSchema = _zod.z.object({
|
|
9
|
+
contextPath: _zod.z.string().default('../../../../src/context')
|
|
10
|
+
});
|
|
11
|
+
exports.configSchema = configSchema;
|
|
12
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","names":["configSchema","z","object","contextPath","string","default"],"sources":["../../../src/plugins/trpc/config.ts"],"sourcesContent":["import { z } from 'zod';\n\nexport const configSchema = z.object({\n contextPath: z.string().default('../../../../src/context'),\n});\n\nexport type Config = z.infer<typeof configSchema>;\n"],"mappings":";;;;;;AAAA;AAEO,MAAMA,YAAY,GAAGC,MAAC,CAACC,MAAM,CAAC;EACjCC,WAAW,EAAEF,MAAC,CAACG,MAAM,EAAE,CAACC,OAAO,CAAC,yBAAyB;AAC7D,CAAC,CAAC;AAAC"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.generate = generate;
|
|
7
|
+
var _fs = require("fs");
|
|
8
|
+
var _path = _interopRequireDefault(require("path"));
|
|
9
|
+
var _generator = require("../zod/generator");
|
|
10
|
+
var _helpers = require("./helpers");
|
|
11
|
+
var _project = require("./project");
|
|
12
|
+
var _removeDir = _interopRequireDefault(require("./utils/removeDir"));
|
|
13
|
+
var _changeCase = require("change-case");
|
|
14
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
15
|
+
async function generate(model, options, dmmf) {
|
|
16
|
+
const outputDir = options.output;
|
|
17
|
+
await _fs.promises.mkdir(outputDir, {
|
|
18
|
+
recursive: true
|
|
19
|
+
});
|
|
20
|
+
await (0, _removeDir.default)(outputDir, true);
|
|
21
|
+
await (0, _generator.generate)(model, options, dmmf);
|
|
22
|
+
const prismaClientDmmf = dmmf;
|
|
23
|
+
const modelOperations = prismaClientDmmf.mappings.modelOperations;
|
|
24
|
+
const models = prismaClientDmmf.datamodel.models;
|
|
25
|
+
const hiddenModels = [];
|
|
26
|
+
(0, _helpers.resolveModelsComments)(models, hiddenModels);
|
|
27
|
+
const appRouter = _project.project.createSourceFile(_path.default.resolve(outputDir, 'routers', `index.ts`), undefined, {
|
|
28
|
+
overwrite: true
|
|
29
|
+
});
|
|
30
|
+
appRouter.addImportDeclarations([{
|
|
31
|
+
namedImports: ['AnyRootConfig'],
|
|
32
|
+
moduleSpecifier: '@trpc/server'
|
|
33
|
+
}, {
|
|
34
|
+
namedImports: ['PrismaClient'],
|
|
35
|
+
moduleSpecifier: '@prisma/client'
|
|
36
|
+
}, {
|
|
37
|
+
namedImports: ['createRouterFactory'],
|
|
38
|
+
moduleSpecifier: '@trpc/server/dist/core/router'
|
|
39
|
+
}, {
|
|
40
|
+
namedImports: ['createBuilder'],
|
|
41
|
+
moduleSpecifier: '@trpc/server/dist/core/internals/procedureBuilder'
|
|
42
|
+
}]);
|
|
43
|
+
appRouter.addStatements(`
|
|
44
|
+
export type BaseConfig = AnyRootConfig;
|
|
45
|
+
|
|
46
|
+
export type RouterFactory<Config extends BaseConfig> = ReturnType<
|
|
47
|
+
typeof createRouterFactory<Config>
|
|
48
|
+
>;
|
|
49
|
+
|
|
50
|
+
export type ProcBuilder<Config extends BaseConfig> = ReturnType<
|
|
51
|
+
typeof createBuilder<Config>
|
|
52
|
+
>;
|
|
53
|
+
|
|
54
|
+
export function db(ctx: any) {
|
|
55
|
+
if (!ctx.prisma) {
|
|
56
|
+
throw new Error('Missing "prisma" field in trpc context');
|
|
57
|
+
}
|
|
58
|
+
return ctx.prisma as PrismaClient;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
`);
|
|
62
|
+
const createFunction = appRouter.addFunction({
|
|
63
|
+
name: 'createRouter<Config extends BaseConfig>',
|
|
64
|
+
parameters: [{
|
|
65
|
+
name: 'router',
|
|
66
|
+
type: 'RouterFactory<Config>'
|
|
67
|
+
}, {
|
|
68
|
+
name: 'procedure',
|
|
69
|
+
type: 'ProcBuilder<Config>'
|
|
70
|
+
}],
|
|
71
|
+
isExported: true
|
|
72
|
+
});
|
|
73
|
+
createFunction.setBodyText(writer => {
|
|
74
|
+
writer.write('return router(');
|
|
75
|
+
writer.block(() => {
|
|
76
|
+
for (const modelOperation of modelOperations) {
|
|
77
|
+
const {
|
|
78
|
+
model,
|
|
79
|
+
...operations
|
|
80
|
+
} = modelOperation;
|
|
81
|
+
if (hiddenModels.includes(model)) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
generateModelCreateRouter(_project.project, model, operations, outputDir);
|
|
85
|
+
appRouter.addImportDeclaration({
|
|
86
|
+
defaultImport: `create${model}Router`,
|
|
87
|
+
moduleSpecifier: `./${model}.router`
|
|
88
|
+
});
|
|
89
|
+
writer.writeLine(`${(0, _changeCase.camelCase)(model)}: create${model}Router<Config>(router, procedure),`);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
writer.write(');');
|
|
93
|
+
});
|
|
94
|
+
appRouter.formatText();
|
|
95
|
+
await _project.project.save();
|
|
96
|
+
}
|
|
97
|
+
function generateModelCreateRouter(project, model, operations, outputDir) {
|
|
98
|
+
const modelRouter = project.createSourceFile(_path.default.resolve(outputDir, 'routers', `${model}.router.ts`), undefined, {
|
|
99
|
+
overwrite: true
|
|
100
|
+
});
|
|
101
|
+
modelRouter.addImportDeclarations([{
|
|
102
|
+
namedImports: ['type RouterFactory', 'type ProcBuilder', 'type BaseConfig', 'db'],
|
|
103
|
+
moduleSpecifier: '.'
|
|
104
|
+
}]);
|
|
105
|
+
(0, _helpers.generateRouterSchemaImports)(modelRouter, model);
|
|
106
|
+
modelRouter.addFunction({
|
|
107
|
+
name: 'createRouter<Config extends BaseConfig>',
|
|
108
|
+
parameters: [{
|
|
109
|
+
name: 'router',
|
|
110
|
+
type: 'RouterFactory<Config>'
|
|
111
|
+
}, {
|
|
112
|
+
name: 'procedure',
|
|
113
|
+
type: 'ProcBuilder<Config>'
|
|
114
|
+
}],
|
|
115
|
+
isExported: true,
|
|
116
|
+
isDefaultExport: true
|
|
117
|
+
}).setBodyText(writer => {
|
|
118
|
+
writer.write('return router(');
|
|
119
|
+
writer.block(() => {
|
|
120
|
+
for (const [opType, opNameWithModel] of Object.entries(operations)) {
|
|
121
|
+
const baseOpType = opType.replace('OrThrow', '');
|
|
122
|
+
const inputType = (0, _helpers.getInputTypeByOpName)(baseOpType, model);
|
|
123
|
+
if (opNameWithModel && inputType) {
|
|
124
|
+
(0, _helpers.generateProcedure)(writer, opType.replace(/One$/, ''), inputType, model, baseOpType);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
writer.write(');');
|
|
129
|
+
});
|
|
130
|
+
modelRouter.formatText();
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generator.js","names":["generate","model","options","dmmf","outputDir","output","fs","mkdir","recursive","removeDir","PrismaZodGenerator","prismaClientDmmf","modelOperations","mappings","models","datamodel","hiddenModels","resolveModelsComments","appRouter","project","createSourceFile","path","resolve","undefined","overwrite","addImportDeclarations","namedImports","moduleSpecifier","addStatements","createFunction","addFunction","name","parameters","type","isExported","setBodyText","writer","write","block","modelOperation","operations","includes","generateModelCreateRouter","addImportDeclaration","defaultImport","writeLine","camelCase","formatText","save","modelRouter","generateRouterSchemaImports","isDefaultExport","opType","opNameWithModel","Object","entries","baseOpType","replace","inputType","getInputTypeByOpName","generateProcedure"],"sources":["../../../src/plugins/trpc/generator.ts"],"sourcesContent":["import { DMMF } from '@prisma/generator-helper';\nimport { PluginOptions } from '@zenstackhq/sdk';\nimport { Model } from '@zenstackhq/sdk/ast';\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport { generate as PrismaZodGenerator } from '../zod/generator';\nimport { generateProcedure, generateRouterSchemaImports, getInputTypeByOpName, resolveModelsComments } from './helpers';\nimport { project } from './project';\nimport removeDir from './utils/removeDir';\nimport { camelCase } from 'change-case';\nimport { Project } from 'ts-morph';\n\nexport async function generate(model: Model, options: PluginOptions, dmmf: DMMF.Document) {\n const outputDir = options.output as string;\n\n await fs.mkdir(outputDir, { recursive: true });\n await removeDir(outputDir, true);\n\n await PrismaZodGenerator(model, options, dmmf);\n\n const prismaClientDmmf = dmmf;\n\n const modelOperations = prismaClientDmmf.mappings.modelOperations;\n const models = prismaClientDmmf.datamodel.models;\n const hiddenModels: string[] = [];\n resolveModelsComments(models, hiddenModels);\n\n const appRouter = project.createSourceFile(path.resolve(outputDir, 'routers', `index.ts`), undefined, {\n overwrite: true,\n });\n\n appRouter.addImportDeclarations([\n {\n namedImports: ['AnyRootConfig'],\n moduleSpecifier: '@trpc/server',\n },\n {\n namedImports: ['PrismaClient'],\n moduleSpecifier: '@prisma/client',\n },\n {\n namedImports: ['createRouterFactory'],\n moduleSpecifier: '@trpc/server/dist/core/router',\n },\n {\n namedImports: ['createBuilder'],\n moduleSpecifier: '@trpc/server/dist/core/internals/procedureBuilder',\n },\n ]);\n\n appRouter.addStatements(`\n export type BaseConfig = AnyRootConfig;\n\n export type RouterFactory<Config extends BaseConfig> = ReturnType<\n typeof createRouterFactory<Config>\n >;\n \n export type ProcBuilder<Config extends BaseConfig> = ReturnType<\n typeof createBuilder<Config>\n >;\n \n export function db(ctx: any) {\n if (!ctx.prisma) {\n throw new Error('Missing \"prisma\" field in trpc context');\n }\n return ctx.prisma as PrismaClient;\n }\n \n `);\n\n const createFunction = appRouter.addFunction({\n name: 'createRouter<Config extends BaseConfig>',\n parameters: [\n { name: 'router', type: 'RouterFactory<Config>' },\n { name: 'procedure', type: 'ProcBuilder<Config>' },\n ],\n isExported: true,\n });\n\n createFunction.setBodyText((writer) => {\n writer.write('return router(');\n writer.block(() => {\n for (const modelOperation of modelOperations) {\n const { model, ...operations } = modelOperation;\n if (hiddenModels.includes(model)) {\n continue;\n }\n\n generateModelCreateRouter(project, model, operations, outputDir);\n\n appRouter.addImportDeclaration({\n defaultImport: `create${model}Router`,\n moduleSpecifier: `./${model}.router`,\n });\n\n writer.writeLine(`${camelCase(model)}: create${model}Router<Config>(router, procedure),`);\n }\n });\n writer.write(');');\n });\n\n appRouter.formatText();\n await project.save();\n}\n\nfunction generateModelCreateRouter(\n project: Project,\n model: string,\n operations: Record<string, string | undefined | null>,\n outputDir: string\n) {\n const modelRouter = project.createSourceFile(path.resolve(outputDir, 'routers', `${model}.router.ts`), undefined, {\n overwrite: true,\n });\n\n modelRouter.addImportDeclarations([\n {\n namedImports: ['type RouterFactory', 'type ProcBuilder', 'type BaseConfig', 'db'],\n moduleSpecifier: '.',\n },\n ]);\n\n generateRouterSchemaImports(modelRouter, model);\n\n modelRouter\n .addFunction({\n name: 'createRouter<Config extends BaseConfig>',\n parameters: [\n { name: 'router', type: 'RouterFactory<Config>' },\n { name: 'procedure', type: 'ProcBuilder<Config>' },\n ],\n isExported: true,\n isDefaultExport: true,\n })\n .setBodyText((writer) => {\n writer.write('return router(');\n writer.block(() => {\n for (const [opType, opNameWithModel] of Object.entries(operations)) {\n const baseOpType = opType.replace('OrThrow', '');\n\n const inputType = getInputTypeByOpName(baseOpType, model);\n\n if (opNameWithModel && inputType) {\n generateProcedure(writer, opType.replace(/One$/, ''), inputType, model, baseOpType);\n }\n }\n });\n writer.write(');');\n });\n\n modelRouter.formatText();\n}\n"],"mappings":";;;;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AAAwC;AAGjC,eAAeA,QAAQ,CAACC,KAAY,EAAEC,OAAsB,EAAEC,IAAmB,EAAE;EACtF,MAAMC,SAAS,GAAGF,OAAO,CAACG,MAAgB;EAE1C,MAAMC,YAAE,CAACC,KAAK,CAACH,SAAS,EAAE;IAAEI,SAAS,EAAE;EAAK,CAAC,CAAC;EAC9C,MAAM,IAAAC,kBAAS,EAACL,SAAS,EAAE,IAAI,CAAC;EAEhC,MAAM,IAAAM,mBAAkB,EAACT,KAAK,EAAEC,OAAO,EAAEC,IAAI,CAAC;EAE9C,MAAMQ,gBAAgB,GAAGR,IAAI;EAE7B,MAAMS,eAAe,GAAGD,gBAAgB,CAACE,QAAQ,CAACD,eAAe;EACjE,MAAME,MAAM,GAAGH,gBAAgB,CAACI,SAAS,CAACD,MAAM;EAChD,MAAME,YAAsB,GAAG,EAAE;EACjC,IAAAC,8BAAqB,EAACH,MAAM,EAAEE,YAAY,CAAC;EAE3C,MAAME,SAAS,GAAGC,gBAAO,CAACC,gBAAgB,CAACC,aAAI,CAACC,OAAO,CAAClB,SAAS,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,CAAC;IAC9BD,MAAM,CAACE,KAAK,CAAC,MAAM;MACf,KAAK,MAAM,CAACc,MAAM,EAAEC,eAAe,CAAC,IAAIC,MAAM,CAACC,OAAO,CAACf,UAAU,CAAC,EAAE;QAChE,MAAMgB,UAAU,GAAGJ,MAAM,CAACK,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC;QAEhD,MAAMC,SAAS,GAAG,IAAAC,6BAAoB,EAACH,UAAU,EAAEvD,KAAK,CAAC;QAEzD,IAAIoD,eAAe,IAAIK,SAAS,EAAE;UAC9B,IAAAE,0BAAiB,EAACxB,MAAM,EAAEgB,MAAM,CAACK,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAEC,SAAS,EAAEzD,KAAK,EAAEuD,UAAU,CAAC;QACvF;MACJ;IACJ,CAAC,CAAC;IACFpB,MAAM,CAACC,KAAK,CAAC,IAAI,CAAC;EACtB,CAAC,CAAC;EAENY,WAAW,CAACF,UAAU,EAAE;AAC5B"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { DMMF } from '@prisma/generator-helper';
|
|
2
|
+
import { CodeBlockWriter, SourceFile } from 'ts-morph';
|
|
3
|
+
export declare const generatetRPCImport: (sourceFile: SourceFile) => void;
|
|
4
|
+
export declare const generateRouterImport: (sourceFile: SourceFile, modelNamePlural: string, modelNameCamelCase: string) => void;
|
|
5
|
+
export declare function generateProcedure(writer: CodeBlockWriter, opType: string, typeName: string, modelName: string, baseOpType: string): void;
|
|
6
|
+
export declare function generateRouterSchemaImports(sourceFile: SourceFile, name: string): void;
|
|
7
|
+
export declare const getInputTypeByOpName: (opName: string, modelName: string) => string | undefined;
|
|
8
|
+
export declare const getProcedureTypeByOpName: (opName: string) => string | undefined;
|
|
9
|
+
export declare function resolveModelsComments(models: DMMF.Model[], hiddenModels: string[]): void;
|