@stryke/prisma-trpc-generator 0.13.49 → 0.13.51
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/dist/_virtual/rolldown_runtime.cjs +31 -1
- package/dist/_virtual/rolldown_runtime.mjs +32 -1
- package/dist/config.cjs +50 -1
- package/dist/config.mjs +49 -1
- package/dist/config.mjs.map +1 -1
- package/dist/generator.cjs +1 -1
- package/dist/generator.mjs +3 -1
- package/dist/helpers.cjs +281 -32
- package/dist/helpers.mjs +271 -32
- package/dist/helpers.mjs.map +1 -1
- package/dist/index.cjs +26 -1
- package/dist/index.mjs +27 -1
- package/dist/index.mjs.map +1 -1
- package/dist/packages/env/src/get-env-paths.cjs +87 -1
- package/dist/packages/env/src/get-env-paths.mjs +84 -1
- package/dist/packages/env/src/get-env-paths.mjs.map +1 -1
- package/dist/packages/string-format/src/acronyms.cjs +408 -1
- package/dist/packages/string-format/src/acronyms.mjs +407 -1
- package/dist/packages/string-format/src/acronyms.mjs.map +1 -1
- package/dist/packages/string-format/src/articles.cjs +10 -1
- package/dist/packages/string-format/src/articles.mjs +9 -1
- package/dist/packages/string-format/src/articles.mjs.map +1 -1
- package/dist/packages/string-format/src/combine.cjs +15 -1
- package/dist/packages/string-format/src/combine.mjs +14 -1
- package/dist/packages/string-format/src/combine.mjs.map +1 -1
- package/dist/packages/string-format/src/conjunctions.cjs +32 -1
- package/dist/packages/string-format/src/conjunctions.mjs +31 -1
- package/dist/packages/string-format/src/conjunctions.mjs.map +1 -1
- package/dist/packages/string-format/src/decamelize.cjs +14 -1
- package/dist/packages/string-format/src/decamelize.mjs +13 -1
- package/dist/packages/string-format/src/decamelize.mjs.map +1 -1
- package/dist/packages/string-format/src/format-special-cases.cjs +33 -1
- package/dist/packages/string-format/src/format-special-cases.mjs +33 -1
- package/dist/packages/string-format/src/format-special-cases.mjs.map +1 -1
- package/dist/packages/string-format/src/lower-case-first.cjs +17 -1
- package/dist/packages/string-format/src/lower-case-first.mjs +16 -1
- package/dist/packages/string-format/src/lower-case-first.mjs.map +1 -1
- package/dist/packages/string-format/src/prepositions.cjs +68 -1
- package/dist/packages/string-format/src/prepositions.mjs +67 -1
- package/dist/packages/string-format/src/prepositions.mjs.map +1 -1
- package/dist/packages/string-format/src/special-cases.cjs +53 -1
- package/dist/packages/string-format/src/special-cases.mjs +52 -1
- package/dist/packages/string-format/src/special-cases.mjs.map +1 -1
- package/dist/packages/string-format/src/title-case.cjs +19 -1
- package/dist/packages/string-format/src/title-case.mjs +19 -1
- package/dist/packages/string-format/src/title-case.mjs.map +1 -1
- package/dist/packages/string-format/src/upper-case-first.cjs +17 -1
- package/dist/packages/string-format/src/upper-case-first.mjs +16 -1
- package/dist/packages/string-format/src/upper-case-first.mjs.map +1 -1
- package/dist/prisma-generator.cjs +185 -8
- package/dist/prisma-generator.mjs +184 -8
- package/dist/prisma-generator.mjs.map +1 -1
- package/dist/project.cjs +15 -1
- package/dist/project.mjs +14 -1
- package/dist/project.mjs.map +1 -1
- package/dist/utils/format-file.cjs +25 -1
- package/dist/utils/format-file.mjs +23 -1
- package/dist/utils/format-file.mjs.map +1 -1
- package/dist/utils/get-jiti.cjs +21 -1
- package/dist/utils/get-jiti.mjs +20 -1
- package/dist/utils/get-jiti.mjs.map +1 -1
- package/dist/utils/get-prisma-internals.cjs +13 -1
- package/dist/utils/get-prisma-internals.mjs +12 -1
- package/dist/utils/get-prisma-internals.mjs.map +1 -1
- package/dist/utils/write-file-safely.cjs +32 -2
- package/dist/utils/write-file-safely.mjs +29 -2
- package/dist/utils/write-file-safely.mjs.map +1 -1
- package/dist/zod/aggregate-helpers.cjs +70 -1
- package/dist/zod/aggregate-helpers.mjs +67 -1
- package/dist/zod/aggregate-helpers.mjs.map +1 -1
- package/dist/zod/comments-helpers.cjs +77 -1
- package/dist/zod/comments-helpers.mjs +75 -1
- package/dist/zod/comments-helpers.mjs.map +1 -1
- package/dist/zod/docs-helpers.cjs +23 -3
- package/dist/zod/docs-helpers.mjs +20 -3
- package/dist/zod/docs-helpers.mjs.map +1 -1
- package/dist/zod/generator-helpers.cjs +34 -1
- package/dist/zod/generator-helpers.mjs +31 -1
- package/dist/zod/generator-helpers.mjs.map +1 -1
- package/dist/zod/helpers.cjs +26 -1
- package/dist/zod/helpers.mjs +26 -1
- package/dist/zod/helpers.mjs.map +1 -1
- package/dist/zod/include-helpers.cjs +69 -1
- package/dist/zod/include-helpers.mjs +69 -1
- package/dist/zod/include-helpers.mjs.map +1 -1
- package/dist/zod/model-helpers.cjs +244 -1
- package/dist/zod/model-helpers.mjs +236 -1
- package/dist/zod/model-helpers.mjs.map +1 -1
- package/dist/zod/modelArgs-helpers.cjs +56 -1
- package/dist/zod/modelArgs-helpers.mjs +56 -1
- package/dist/zod/modelArgs-helpers.mjs.map +1 -1
- package/dist/zod/mongodb-helpers.cjs +49 -1
- package/dist/zod/mongodb-helpers.mjs +48 -1
- package/dist/zod/mongodb-helpers.mjs.map +1 -1
- package/dist/zod/select-helpers.cjs +128 -1
- package/dist/zod/select-helpers.mjs +128 -1
- package/dist/zod/select-helpers.mjs.map +1 -1
- package/dist/zod/transformer.cjs +434 -19
- package/dist/zod/transformer.mjs +432 -19
- package/dist/zod/transformer.mjs.map +1 -1
- package/dist/zod/whereUniqueInput-helpers.cjs +17 -1
- package/dist/zod/whereUniqueInput-helpers.mjs +16 -1
- package/dist/zod/whereUniqueInput-helpers.mjs.map +1 -1
- package/package.json +4 -4
package/dist/helpers.mjs
CHANGED
|
@@ -1,48 +1,274 @@
|
|
|
1
|
-
import{lowerCaseFirst
|
|
1
|
+
import { lowerCaseFirst } from "./packages/string-format/src/lower-case-first.mjs";
|
|
2
|
+
import { project } from "./project.mjs";
|
|
3
|
+
import "./utils/get-prisma-internals.mjs";
|
|
4
|
+
import { generateBarrelFile, populateModelFile } from "./zod/model-helpers.mjs";
|
|
5
|
+
import { joinPaths } from "@stryke/path/join-paths";
|
|
6
|
+
import { relativePath } from "@stryke/path/file-path-fns";
|
|
7
|
+
|
|
8
|
+
//#region src/helpers.ts
|
|
9
|
+
const getProcedureName = (config) => {
|
|
10
|
+
return config.withShield ? "shieldedProcedure" : config.withMiddleware ? "protectedProcedure" : "publicProcedure";
|
|
11
|
+
};
|
|
12
|
+
const generateCreateRouterImport = ({ sourceFile, config }) => {
|
|
13
|
+
const imports = ["t"];
|
|
14
|
+
if (config) imports.push(getProcedureName(config));
|
|
15
|
+
sourceFile.addImportDeclaration({
|
|
16
|
+
moduleSpecifier: "../trpc",
|
|
17
|
+
namedImports: imports
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
const generateRouterImport = (sourceFile, modelNamePlural, modelNameCamelCase) => {
|
|
21
|
+
sourceFile.addImportDeclaration({
|
|
22
|
+
moduleSpecifier: `./${lowerCaseFirst(modelNameCamelCase)}.router`,
|
|
23
|
+
namedImports: [`${modelNamePlural}Router`]
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
async function generateTRPCExports(sourceFile, config, options, outputDir) {
|
|
27
|
+
if (config.withShield) sourceFile.addImportDeclaration({
|
|
28
|
+
moduleSpecifier: relativePath(outputDir, joinPaths(outputDir, typeof config.withShield === "string" ? config.withShield : "shield")),
|
|
29
|
+
namedImports: ["permissions"]
|
|
30
|
+
});
|
|
31
|
+
sourceFile.addStatements(`import type { Context } from '${relativePath(outputDir, joinPaths(outputDir, config.contextPath))}';`);
|
|
32
|
+
if (config.trpcOptions) sourceFile.addStatements(`import trpcOptions from '${typeof config.trpcOptions === "string" ? relativePath(outputDir, joinPaths(outputDir, config.trpcOptions)) : "./options"}';`);
|
|
33
|
+
if (config.withNext) sourceFile.addStatements(`import { createContext } from '${relativePath(outputDir, joinPaths(outputDir, config.contextPath))}';
|
|
2
34
|
import { initTRPC } from '@trpc/server';
|
|
3
35
|
import { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';
|
|
4
|
-
import { cookies } from "next/headers";`)
|
|
5
|
-
|
|
36
|
+
import { cookies } from "next/headers";`);
|
|
37
|
+
sourceFile.addStatements(`
|
|
38
|
+
export const t = initTRPC.context<Context>().create(${config.trpcOptions ? "trpcOptions" : ""});`);
|
|
39
|
+
const middlewares = [];
|
|
40
|
+
if (config.withMiddleware && typeof config.withMiddleware === "boolean") {
|
|
41
|
+
sourceFile.addStatements(`
|
|
6
42
|
export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
|
|
7
43
|
console.log('inside middleware!')
|
|
8
44
|
return next()
|
|
9
|
-
});`)
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
45
|
+
});`);
|
|
46
|
+
middlewares.push({
|
|
47
|
+
type: "global",
|
|
48
|
+
value: `.use(globalMiddleware)`
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (config.withMiddleware && typeof config.withMiddleware === "string") {
|
|
52
|
+
sourceFile.addStatements(`
|
|
53
|
+
import middleware from '${relativePath(outputDir, joinPaths(outputDir, typeof config.withMiddleware === "string" ? config.withMiddleware : "middleware"))}';
|
|
54
|
+
`);
|
|
55
|
+
sourceFile.addStatements(`
|
|
56
|
+
export const globalMiddleware = t.middleware(middleware);`);
|
|
57
|
+
middlewares.push({
|
|
58
|
+
type: "global",
|
|
59
|
+
value: `.use(globalMiddleware)`
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
if (config.withShield) {
|
|
63
|
+
sourceFile.addStatements(`
|
|
13
64
|
export const permissionsMiddleware = t.middleware(permissions);
|
|
14
|
-
`)
|
|
15
|
-
|
|
65
|
+
`);
|
|
66
|
+
middlewares.push({
|
|
67
|
+
type: "shield",
|
|
68
|
+
value: `
|
|
69
|
+
.use(permissions)`
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
sourceFile.addStatements(`
|
|
16
73
|
/**
|
|
17
74
|
* Create a server-side caller
|
|
18
75
|
* @see https://trpc.io/docs/server/server-side-calls
|
|
19
76
|
*/
|
|
20
|
-
export const createCallerFactory = t.createCallerFactory;`)
|
|
21
|
-
|
|
22
|
-
export const
|
|
77
|
+
export const createCallerFactory = t.createCallerFactory;`);
|
|
78
|
+
sourceFile.addStatements(`
|
|
79
|
+
export const publicProcedure = t.procedure; `);
|
|
80
|
+
if (middlewares.length > 0) {
|
|
81
|
+
const procName = getProcedureName(config);
|
|
82
|
+
middlewares.forEach((middleware, i) => {
|
|
83
|
+
if (i === 0) sourceFile.addStatements(`
|
|
84
|
+
export const ${procName} = t.procedure`);
|
|
85
|
+
sourceFile.addStatements(`.use(${middleware.type === "shield" ? "permissionsMiddleware" : "globalMiddleware"})`);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
if (config.withNext) sourceFile.addStatements(`
|
|
23
89
|
export const createAction: ReturnType<typeof createTRPCServerActionHandler> =
|
|
24
90
|
createTRPCServerActionHandler(cookies, t, createContext);
|
|
25
|
-
`)
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
91
|
+
`);
|
|
92
|
+
sourceFile.formatText({ indentSize: 2 });
|
|
93
|
+
}
|
|
94
|
+
function generateProcedure(sourceFile, name, typeName, modelName, opType, baseOpType, config) {
|
|
95
|
+
let input = `input${!config.withZod ? " as any" : ""}`;
|
|
96
|
+
const nameWithoutModel = name.replace(modelName, "");
|
|
97
|
+
if (nameWithoutModel === "groupBy" && config.withZod) input = "{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }";
|
|
98
|
+
sourceFile.addStatements(`${config.showModelNameInProcedure ? name : nameWithoutModel}: ${getProcedureName(config)}
|
|
99
|
+
${config.withZod ? `.input(${lowerCaseFirst(typeName)})` : ""}.${getProcedureTypeByOpName(baseOpType)}(async ({ ctx, input }) => {
|
|
100
|
+
const ${name} = await ctx.prisma.${lowerCaseFirst(modelName)}.${opType.replace("One", "")}(${input});
|
|
101
|
+
return ${name};
|
|
102
|
+
}),`);
|
|
103
|
+
}
|
|
104
|
+
function generateRouterSchemaImports(sourceFile, modelName, modelActions) {
|
|
105
|
+
sourceFile.addStatements([...new Set(modelActions.map((opName) => getRouterSchemaImportByOpName(opName, modelName)))].join("\n"));
|
|
106
|
+
}
|
|
107
|
+
const getRouterSchemaImportByOpName = (opName, modelName) => {
|
|
108
|
+
const opType = opName.replace("OrThrow", "").replace("ManyAndReturn", "");
|
|
109
|
+
const inputType = getInputTypeByOpName(opType, modelName);
|
|
110
|
+
return inputType ? `import { ${lowerCaseFirst(inputType)} } from "../schemas/${lowerCaseFirst(opType)}${modelName}.schema"; ` : "";
|
|
111
|
+
};
|
|
112
|
+
const getInputTypeByOpName = (opName, modelName) => {
|
|
113
|
+
let inputType;
|
|
114
|
+
switch (opName) {
|
|
115
|
+
case "findUnique":
|
|
116
|
+
inputType = `${modelName}FindUniqueSchema`;
|
|
117
|
+
break;
|
|
118
|
+
case "findFirst":
|
|
119
|
+
inputType = `${modelName}FindFirstSchema`;
|
|
120
|
+
break;
|
|
121
|
+
case "findMany":
|
|
122
|
+
inputType = `${modelName}FindManySchema`;
|
|
123
|
+
break;
|
|
124
|
+
case "findRaw":
|
|
125
|
+
inputType = `${modelName}FindRawObjectSchema`;
|
|
126
|
+
break;
|
|
127
|
+
case "createOne":
|
|
128
|
+
inputType = `${modelName}CreateOneSchema`;
|
|
129
|
+
break;
|
|
130
|
+
case "createMany":
|
|
131
|
+
inputType = `${modelName}CreateManySchema`;
|
|
132
|
+
break;
|
|
133
|
+
case "createManyAndReturn":
|
|
134
|
+
inputType = `${modelName}CreateManySchema`;
|
|
135
|
+
break;
|
|
136
|
+
case "deleteOne":
|
|
137
|
+
inputType = `${modelName}DeleteOneSchema`;
|
|
138
|
+
break;
|
|
139
|
+
case "deleteMany":
|
|
140
|
+
inputType = `${modelName}DeleteManySchema`;
|
|
141
|
+
break;
|
|
142
|
+
case "updateOne":
|
|
143
|
+
inputType = `${modelName}UpdateOneSchema`;
|
|
144
|
+
break;
|
|
145
|
+
case "updateMany":
|
|
146
|
+
inputType = `${modelName}UpdateManySchema`;
|
|
147
|
+
break;
|
|
148
|
+
case "updateManyAndReturn":
|
|
149
|
+
inputType = `${modelName}UpdateManySchema`;
|
|
150
|
+
break;
|
|
151
|
+
case "upsertOne":
|
|
152
|
+
inputType = `${modelName}UpsertSchema`;
|
|
153
|
+
break;
|
|
154
|
+
case "aggregate":
|
|
155
|
+
inputType = `${modelName}AggregateSchema`;
|
|
156
|
+
break;
|
|
157
|
+
case "aggregateRaw":
|
|
158
|
+
inputType = `${modelName}AggregateRawObjectSchema`;
|
|
159
|
+
break;
|
|
160
|
+
case "groupBy":
|
|
161
|
+
inputType = `${modelName}GroupBySchema`;
|
|
162
|
+
break;
|
|
163
|
+
default: console.log("getInputTypeByOpName: ", {
|
|
164
|
+
opName,
|
|
165
|
+
modelName
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
return inputType;
|
|
169
|
+
};
|
|
170
|
+
const getProcedureTypeByOpName = (opName) => {
|
|
171
|
+
let procType;
|
|
172
|
+
switch (opName) {
|
|
173
|
+
case "findUnique":
|
|
174
|
+
case "findFirst":
|
|
175
|
+
case "findMany":
|
|
176
|
+
case "findRaw":
|
|
177
|
+
case "aggregate":
|
|
178
|
+
case "aggregateRaw":
|
|
179
|
+
case "groupBy":
|
|
180
|
+
procType = "query";
|
|
181
|
+
break;
|
|
182
|
+
case "createOne":
|
|
183
|
+
case "createMany":
|
|
184
|
+
case "createManyAndReturn":
|
|
185
|
+
case "deleteOne":
|
|
186
|
+
case "updateOne":
|
|
187
|
+
case "deleteMany":
|
|
188
|
+
case "updateMany":
|
|
189
|
+
case "updateManyAndReturn":
|
|
190
|
+
case "upsertOne":
|
|
191
|
+
procType = "mutation";
|
|
192
|
+
break;
|
|
193
|
+
default: console.log("getProcedureTypeByOpName: ", { opName });
|
|
194
|
+
}
|
|
195
|
+
return procType;
|
|
196
|
+
};
|
|
197
|
+
function resolveModelsComments(models, hiddenModels) {
|
|
198
|
+
const modelAttributeRegex = /(?:@@Gen\.)+[A-z]+\(.+\)/;
|
|
199
|
+
const attributeNameRegex = /\.+[A-Z]+\(+/i;
|
|
200
|
+
const attributeArgsRegex = /\(+[A-Z]+:.+\)/i;
|
|
201
|
+
for (const model of models) if (model.documentation) {
|
|
202
|
+
const attribute = model.documentation?.match(modelAttributeRegex)?.[0];
|
|
203
|
+
if (attribute?.match(attributeNameRegex)?.[0]?.slice(1, -1) !== "model") continue;
|
|
204
|
+
const rawAttributeArgs = attribute?.match(attributeArgsRegex)?.[0]?.slice(1, -1);
|
|
205
|
+
const parsedAttributeArgs = {};
|
|
206
|
+
if (rawAttributeArgs) {
|
|
207
|
+
const rawAttributeArgsParts = rawAttributeArgs.split(":").map((it) => it.trim()).map((part) => part.startsWith("[") ? part : part.split(",")).flat().map((it) => it.trim());
|
|
208
|
+
for (let i = 0; i < rawAttributeArgsParts.length; i += 2) {
|
|
209
|
+
const key = rawAttributeArgsParts[i];
|
|
210
|
+
const value = rawAttributeArgsParts[i + 1];
|
|
211
|
+
parsedAttributeArgs[key] = JSON.parse(value);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (parsedAttributeArgs.hide) hiddenModels.push(model.name);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const getImports = (type, newPath) => {
|
|
218
|
+
let statement = "";
|
|
219
|
+
if (type === "trpc") statement = "import * as trpc from '@trpc/server';\n";
|
|
220
|
+
else if (type === "trpc-shield") statement = "import { shield, allow } from '@stryke/trpc-next/shield';\n";
|
|
221
|
+
else if (type === "context") statement = `import type { Context } from '${newPath}';\n`;
|
|
222
|
+
return statement;
|
|
223
|
+
};
|
|
224
|
+
const wrapWithObject = ({ shieldItemLines }) => {
|
|
225
|
+
let wrapped = "{";
|
|
226
|
+
wrapped += "\n";
|
|
227
|
+
wrapped += Array.isArray(shieldItemLines) ? ` ${shieldItemLines.join(",\r\n")}` : ` ${shieldItemLines}`;
|
|
228
|
+
wrapped += "\n";
|
|
229
|
+
wrapped += "}";
|
|
230
|
+
return wrapped;
|
|
231
|
+
};
|
|
232
|
+
const wrapWithTrpcShieldCall = ({ shieldObjectTextWrapped }) => {
|
|
233
|
+
let wrapped = "shield<Context>(";
|
|
234
|
+
wrapped += "\n";
|
|
235
|
+
wrapped += ` ${shieldObjectTextWrapped}`;
|
|
236
|
+
wrapped += "\n";
|
|
237
|
+
wrapped += ")";
|
|
238
|
+
return wrapped;
|
|
239
|
+
};
|
|
240
|
+
const wrapWithExport = ({ shieldObjectText }) => {
|
|
241
|
+
return `export const permissions: ReturnType<typeof shield<Context>> = ${shieldObjectText};`;
|
|
242
|
+
};
|
|
243
|
+
const constructShield = async ({ queries, mutations, subscriptions }, config, options, outputDir) => {
|
|
244
|
+
if (queries.length === 0 && mutations.length === 0 && subscriptions.length === 0) return "";
|
|
245
|
+
let rootItems = "";
|
|
246
|
+
if (queries.length > 0) {
|
|
247
|
+
const queryLinesWrapped = `query: ${wrapWithObject({ shieldItemLines: queries.map((query) => `${query}: allow`) })},`;
|
|
248
|
+
rootItems += queryLinesWrapped;
|
|
249
|
+
}
|
|
250
|
+
if (mutations.length > 0) {
|
|
251
|
+
const mutationLinesWrapped = `mutation: ${wrapWithObject({ shieldItemLines: mutations.map((mutation) => `${mutation}: allow`) })},`;
|
|
252
|
+
rootItems += mutationLinesWrapped;
|
|
253
|
+
}
|
|
254
|
+
if (subscriptions.length > 0) {
|
|
255
|
+
const subscriptionLinesWrapped = `subscription: ${wrapWithObject({ shieldItemLines: subscriptions.map((subscription) => `${subscription}: allow`) })},`;
|
|
256
|
+
rootItems += subscriptionLinesWrapped;
|
|
257
|
+
}
|
|
258
|
+
if (rootItems.length === 0) return "";
|
|
259
|
+
let shieldText = getImports("trpc-shield");
|
|
260
|
+
shieldText += getImports("context", relativePath(outputDir, joinPaths(outputDir, config.contextPath)));
|
|
261
|
+
shieldText += "\n\n";
|
|
262
|
+
shieldText += wrapWithExport({ shieldObjectText: wrapWithTrpcShieldCall({ shieldObjectTextWrapped: wrapWithObject({ shieldItemLines: rootItems }) }) });
|
|
263
|
+
return shieldText;
|
|
264
|
+
};
|
|
265
|
+
const constructDefaultOptions = (config, options, outputDir) => {
|
|
266
|
+
return `import { ZodError } from 'zod';${config.withNext ? "\nimport { transformer } from \"@stryke/trpc-next/shared\";" : ""}
|
|
41
267
|
import type {
|
|
42
268
|
DataTransformerOptions,
|
|
43
269
|
RootConfig
|
|
44
270
|
} from "@trpc/server/unstable-core-do-not-import";
|
|
45
|
-
import type { Context } from "${
|
|
271
|
+
import type { Context } from "${relativePath(outputDir, joinPaths(outputDir, config.contextPath))}";
|
|
46
272
|
|
|
47
273
|
interface RuntimeConfigOptions<
|
|
48
274
|
TContext extends object,
|
|
@@ -65,8 +291,7 @@ interface RuntimeConfigOptions<
|
|
|
65
291
|
transformer?: DataTransformerOptions;
|
|
66
292
|
}
|
|
67
293
|
|
|
68
|
-
const options: RuntimeConfigOptions<Context> = {${
|
|
69
|
-
transformer,`:``}
|
|
294
|
+
const options: RuntimeConfigOptions<Context> = {${config.withNext ? "\n transformer," : ""}
|
|
70
295
|
errorFormatter({ shape, error }) {
|
|
71
296
|
return {
|
|
72
297
|
...shape,
|
|
@@ -82,5 +307,19 @@ const options: RuntimeConfigOptions<Context> = {${e.withNext?`
|
|
|
82
307
|
};
|
|
83
308
|
|
|
84
309
|
export default options;
|
|
85
|
-
|
|
310
|
+
`;
|
|
311
|
+
};
|
|
312
|
+
const constructZodModels = async (models, outputPath, config, options) => {
|
|
313
|
+
const indexFile = project.createSourceFile(`${outputPath}/index.ts`, {}, { overwrite: true });
|
|
314
|
+
generateBarrelFile(models, indexFile);
|
|
315
|
+
indexFile.formatText({ indentSize: 2 });
|
|
316
|
+
await Promise.all(models.map(async (model) => {
|
|
317
|
+
const sourceFile = project.createSourceFile(`${outputPath}/${lowerCaseFirst(model.name)}.schema.ts`, {}, { overwrite: true });
|
|
318
|
+
await populateModelFile(model, sourceFile, config, options);
|
|
319
|
+
sourceFile.formatText({ indentSize: 2 });
|
|
320
|
+
}));
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
//#endregion
|
|
324
|
+
export { constructDefaultOptions, constructShield, constructZodModels, generateCreateRouterImport, generateProcedure, generateRouterImport, generateRouterSchemaImports, generateTRPCExports, getInputTypeByOpName, resolveModelsComments };
|
|
86
325
|
//# sourceMappingURL=helpers.mjs.map
|
package/dist/helpers.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.mjs","names":["parsedAttributeArgs: Record<string, unknown>"],"sources":["../src/helpers.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Stryke\n\n This code was released as part of the Stryke project. Stryke\n is maintained by Storm Software under the Apache-2.0 License, and is\n free for commercial and private use. For more information, please visit\n our licensing page.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/stryke\n Documentation: https://stormsoftware.com/projects/stryke/docs\n Contact: https://stormsoftware.com/contact\n License: https://stormsoftware.com/projects/stryke/license\n\n ------------------------------------------------------------------- */\n\n/* eslint-disable ts/no-use-before-define */\n\nimport type {\n DMMF,\n EnvValue,\n GeneratorOptions\n} from \"@prisma/generator-helper\";\nimport { relativePath } from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { lowerCaseFirst } from \"@stryke/string-format/lower-case-first\";\nimport type { SourceFile } from \"ts-morph\";\nimport type { Config } from \"./config\";\nimport { project } from \"./project\";\nimport type { Writeable } from \"./types\";\nimport { getPrismaInternals } from \"./utils/get-prisma-internals\";\nimport { generateBarrelFile, populateModelFile } from \"./zod/model-helpers\";\n\nconst getProcedureName = (config: Config) => {\n return config.withShield\n ? \"shieldedProcedure\"\n : config.withMiddleware\n ? \"protectedProcedure\"\n : \"publicProcedure\";\n};\n\nexport const generateCreateRouterImport = ({\n sourceFile,\n config\n}: {\n sourceFile: SourceFile;\n config?: Config;\n}) => {\n const imports = [\"t\"];\n\n if (config) {\n imports.push(getProcedureName(config));\n }\n\n sourceFile.addImportDeclaration({\n moduleSpecifier: \"../trpc\",\n namedImports: imports\n });\n};\n\nexport const generateRPCImport = (sourceFile: SourceFile) => {\n sourceFile.addImportDeclaration({\n moduleSpecifier: \"@trpc/server\",\n namespaceImport: \"trpc\"\n });\n};\n\nexport const generateMiddlewareImport = async (\n sourceFile: SourceFile,\n options: GeneratorOptions\n) => {\n const internals = await getPrismaInternals();\n\n const outputDir = internals.parseEnvValue(\n options.generator.output as EnvValue\n );\n sourceFile.addImportDeclaration({\n moduleSpecifier: relativePath(\n outputDir,\n joinPaths(outputDir, \"middleware\")\n ),\n namedImports: [\"permissions\"]\n });\n};\n\nexport const generateRouterImport = (\n sourceFile: SourceFile,\n modelNamePlural: string,\n modelNameCamelCase: string\n) => {\n sourceFile.addImportDeclaration({\n moduleSpecifier: `./${lowerCaseFirst(modelNameCamelCase)}.router`,\n namedImports: [`${modelNamePlural}Router`]\n });\n};\n\nexport async function generateTRPCExports(\n sourceFile: SourceFile,\n config: Config,\n options: GeneratorOptions,\n outputDir: string\n) {\n if (config.withShield) {\n sourceFile.addImportDeclaration({\n moduleSpecifier: relativePath(\n outputDir,\n joinPaths(\n outputDir,\n typeof config.withShield === \"string\" ? config.withShield : \"shield\"\n )\n ),\n namedImports: [\"permissions\"]\n });\n }\n\n sourceFile.addStatements(\n /* ts */ `import type { Context } from '${relativePath(\n outputDir,\n joinPaths(outputDir, config.contextPath)\n )}';`\n );\n\n if (config.trpcOptions) {\n sourceFile.addStatements(\n /* ts */ `import trpcOptions from '${\n typeof config.trpcOptions === \"string\"\n ? relativePath(outputDir, joinPaths(outputDir, config.trpcOptions))\n : \"./options\"\n }';`\n );\n }\n\n if (config.withNext) {\n sourceFile.addStatements(/* ts */ `import { createContext } from '${relativePath(\n outputDir,\n joinPaths(outputDir, config.contextPath)\n )}';\nimport { initTRPC } from '@trpc/server';\nimport { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';\nimport { cookies } from \"next/headers\";`);\n }\n\n sourceFile.addStatements(/* ts */ `\nexport const t = initTRPC.context<Context>().create(${\n config.trpcOptions ? \"trpcOptions\" : \"\"\n });`);\n\n const middlewares = [];\n\n if (config.withMiddleware && typeof config.withMiddleware === \"boolean\") {\n sourceFile.addStatements(/* ts */ `\nexport const globalMiddleware = t.middleware(async ({ ctx, next }) => {\n console.log('inside middleware!')\n return next()\n});`);\n middlewares.push({\n type: \"global\",\n value: /* ts */ `.use(globalMiddleware)`\n });\n }\n\n if (config.withMiddleware && typeof config.withMiddleware === \"string\") {\n sourceFile.addStatements(/* ts */ `\nimport middleware from '${relativePath(\n outputDir,\n joinPaths(\n outputDir,\n typeof config.withMiddleware === \"string\"\n ? config.withMiddleware\n : \"middleware\"\n )\n )}';\n `);\n sourceFile.addStatements(/* ts */ `\nexport const globalMiddleware = t.middleware(middleware);`);\n middlewares.push({\n type: \"global\",\n value: /* ts */ `.use(globalMiddleware)`\n });\n }\n\n if (config.withShield) {\n sourceFile.addStatements(/* ts */ `\nexport const permissionsMiddleware = t.middleware(permissions);\n `);\n\n middlewares.push({\n type: \"shield\",\n value: /* ts */ `\n .use(permissions)`\n });\n }\n\n sourceFile.addStatements(/* ts */ `\n/**\n * Create a server-side caller\n * @see https://trpc.io/docs/server/server-side-calls\n */\nexport const createCallerFactory = t.createCallerFactory;`);\n\n sourceFile.addStatements(/* ts */ `\nexport const publicProcedure = t.procedure; `);\n\n if (middlewares.length > 0) {\n const procName = getProcedureName(config);\n\n middlewares.forEach((middleware, i) => {\n if (i === 0) {\n sourceFile.addStatements(/* ts */ `\nexport const ${procName} = t.procedure`);\n }\n\n sourceFile.addStatements(\n /* ts */ `.use(${\n middleware.type === \"shield\"\n ? \"permissionsMiddleware\"\n : \"globalMiddleware\"\n })`\n );\n });\n }\n\n if (config.withNext) {\n sourceFile.addStatements(/* ts */ `\nexport const createAction: ReturnType<typeof createTRPCServerActionHandler> =\n createTRPCServerActionHandler(cookies, t, createContext);\n`);\n }\n\n sourceFile.formatText({\n indentSize: 2\n });\n}\n\nexport function generateProcedure(\n sourceFile: SourceFile,\n name: string,\n typeName: string,\n modelName: string,\n opType: string,\n baseOpType: string,\n config: Config\n) {\n let input = `input${!config.withZod ? \" as any\" : \"\"}`;\n const nameWithoutModel = name.replace(modelName, \"\");\n if (nameWithoutModel === \"groupBy\" && config.withZod) {\n input =\n \"{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }\";\n }\n sourceFile.addStatements(/* ts */ `${\n config.showModelNameInProcedure ? name : nameWithoutModel\n }: ${getProcedureName(config)}\n ${config.withZod ? `.input(${lowerCaseFirst(typeName)})` : \"\"}.${getProcedureTypeByOpName(\n baseOpType\n )}(async ({ ctx, input }) => {\n const ${name} = await ctx.prisma.${lowerCaseFirst(\n modelName\n )}.${opType.replace(\"One\", \"\")}(${input});\n return ${name};\n }),`);\n}\n\nexport function generateRouterSchemaImports(\n sourceFile: SourceFile,\n modelName: string,\n modelActions: string[]\n) {\n sourceFile.addStatements(\n /* ts */\n [\n // remove any duplicate import statements\n ...new Set(\n modelActions.map(opName =>\n getRouterSchemaImportByOpName(opName, modelName)\n )\n )\n ].join(\"\\n\")\n );\n}\n\nexport const getRouterSchemaImportByOpName = (\n opName: string,\n modelName: string\n) => {\n const opType = opName.replace(\"OrThrow\", \"\").replace(\"ManyAndReturn\", \"\");\n const inputType = getInputTypeByOpName(opType, modelName);\n\n return inputType\n ? `import { ${lowerCaseFirst(inputType)} } from \"../schemas/${lowerCaseFirst(opType)}${modelName}.schema\"; `\n : \"\";\n};\n\nexport const getInputTypeByOpName = (opName: string, modelName: string) => {\n let inputType;\n switch (opName) {\n case \"findUnique\":\n inputType = `${modelName}FindUniqueSchema`;\n break;\n case \"findFirst\":\n inputType = `${modelName}FindFirstSchema`;\n break;\n case \"findMany\":\n inputType = `${modelName}FindManySchema`;\n break;\n case \"findRaw\":\n inputType = `${modelName}FindRawObjectSchema`;\n break;\n case \"createOne\":\n inputType = `${modelName}CreateOneSchema`;\n break;\n case \"createMany\":\n inputType = `${modelName}CreateManySchema`;\n break;\n case \"createManyAndReturn\":\n inputType = `${modelName}CreateManySchema`;\n break;\n case \"deleteOne\":\n inputType = `${modelName}DeleteOneSchema`;\n break;\n case \"deleteMany\":\n inputType = `${modelName}DeleteManySchema`;\n break;\n case \"updateOne\":\n inputType = `${modelName}UpdateOneSchema`;\n break;\n case \"updateMany\":\n inputType = `${modelName}UpdateManySchema`;\n break;\n case \"updateManyAndReturn\":\n inputType = `${modelName}UpdateManySchema`;\n break;\n case \"upsertOne\":\n inputType = `${modelName}UpsertSchema`;\n break;\n case \"aggregate\":\n inputType = `${modelName}AggregateSchema`;\n break;\n case \"aggregateRaw\":\n inputType = `${modelName}AggregateRawObjectSchema`;\n break;\n case \"groupBy\":\n inputType = `${modelName}GroupBySchema`;\n break;\n default:\n // eslint-disable-next-line no-console\n console.log(\"getInputTypeByOpName: \", { opName, modelName });\n }\n return inputType;\n};\n\nexport const getProcedureTypeByOpName = (opName: string) => {\n let procType;\n switch (opName) {\n case \"findUnique\":\n case \"findFirst\":\n case \"findMany\":\n case \"findRaw\":\n case \"aggregate\":\n case \"aggregateRaw\":\n case \"groupBy\":\n procType = \"query\";\n break;\n case \"createOne\":\n case \"createMany\":\n case \"createManyAndReturn\":\n case \"deleteOne\":\n case \"updateOne\":\n case \"deleteMany\":\n case \"updateMany\":\n case \"updateManyAndReturn\":\n case \"upsertOne\":\n procType = \"mutation\";\n break;\n default:\n // eslint-disable-next-line no-console\n console.log(\"getProcedureTypeByOpName: \", { opName });\n }\n return procType;\n};\n\nexport function resolveModelsComments(\n models: DMMF.Model[],\n hiddenModels: string[]\n) {\n // eslint-disable-next-line regexp/no-obscure-range\n const modelAttributeRegex = /(?:@@Gen\\.)+[A-z]+\\(.+\\)/;\n const attributeNameRegex = /\\.+[A-Z]+\\(+/i;\n const attributeArgsRegex = /\\(+[A-Z]+:.+\\)/i;\n\n for (const model of models) {\n if (model.documentation) {\n const attribute = model.documentation?.match(modelAttributeRegex)?.[0];\n const attributeName = attribute\n ?.match(attributeNameRegex)?.[0]\n ?.slice(1, -1);\n if (attributeName !== \"model\") continue;\n const rawAttributeArgs = attribute\n ?.match(attributeArgsRegex)?.[0]\n ?.slice(1, -1);\n\n const parsedAttributeArgs: Record<string, unknown> = {};\n if (rawAttributeArgs) {\n const rawAttributeArgsParts = rawAttributeArgs\n .split(\":\")\n .map(it => it.trim())\n .map(part => (part.startsWith(\"[\") ? part : part.split(\",\")))\n .flat()\n .map(it => it.trim());\n\n for (let i = 0; i < rawAttributeArgsParts.length; i += 2) {\n const key = rawAttributeArgsParts[i];\n const value = rawAttributeArgsParts[i + 1];\n parsedAttributeArgs[key!] = JSON.parse(value!);\n }\n }\n\n if (parsedAttributeArgs.hide) {\n hiddenModels.push(model.name);\n }\n }\n }\n}\n\nexport const getImports = (\n type: \"trpc\" | \"trpc-shield\" | \"context\",\n newPath?: string\n) => {\n let statement = \"\";\n if (type === \"trpc\") {\n statement = \"import * as trpc from '@trpc/server';\\n\";\n } else if (type === \"trpc-shield\") {\n statement = \"import { shield, allow } from '@stryke/trpc-next/shield';\\n\";\n } else if (type === \"context\") {\n statement = `import type { Context } from '${newPath}';\\n`;\n }\n\n return statement;\n};\n\nexport const wrapWithObject = ({\n shieldItemLines\n}: {\n shieldItemLines: Array<string> | string;\n}) => {\n let wrapped = \"{\";\n wrapped += \"\\n\";\n wrapped += Array.isArray(shieldItemLines)\n ? ` ${shieldItemLines.join(\",\\r\\n\")}`\n : ` ${shieldItemLines}`;\n wrapped += \"\\n\";\n wrapped += \"}\";\n return wrapped;\n};\n\nexport const wrapWithTrpcShieldCall = ({\n shieldObjectTextWrapped\n}: {\n shieldObjectTextWrapped: string;\n}) => {\n let wrapped = \"shield<Context>(\";\n wrapped += \"\\n\";\n wrapped += ` ${shieldObjectTextWrapped}`;\n wrapped += \"\\n\";\n wrapped += \")\";\n return wrapped;\n};\n\nexport const wrapWithExport = ({\n shieldObjectText\n}: {\n shieldObjectText: string;\n}) => {\n return `export const permissions: ReturnType<typeof shield<Context>> = ${shieldObjectText};`;\n};\n\nexport const constructShield = async (\n {\n queries,\n mutations,\n subscriptions\n }: {\n queries: Array<string>;\n mutations: Array<string>;\n subscriptions: Array<string>;\n },\n config: Config,\n options: GeneratorOptions,\n outputDir: string\n) => {\n if (\n queries.length === 0 &&\n mutations.length === 0 &&\n subscriptions.length === 0\n ) {\n return \"\";\n }\n\n let rootItems = \"\";\n if (queries.length > 0) {\n const queryLinesWrapped = `query: ${wrapWithObject({\n shieldItemLines: queries.map(query => `${query}: allow`)\n })},`;\n rootItems += queryLinesWrapped;\n }\n if (mutations.length > 0) {\n const mutationLinesWrapped = `mutation: ${wrapWithObject({\n shieldItemLines: mutations.map(mutation => `${mutation}: allow`)\n })},`;\n rootItems += mutationLinesWrapped;\n }\n\n if (subscriptions.length > 0) {\n const subscriptionLinesWrapped = `subscription: ${wrapWithObject({\n shieldItemLines: subscriptions.map(\n subscription => `${subscription}: allow`\n )\n })},`;\n rootItems += subscriptionLinesWrapped;\n }\n\n if (rootItems.length === 0) {\n return \"\";\n }\n\n let shieldText = getImports(\"trpc-shield\");\n shieldText += getImports(\n \"context\",\n relativePath(outputDir, joinPaths(outputDir, config.contextPath))\n );\n shieldText += \"\\n\\n\";\n shieldText += wrapWithExport({\n shieldObjectText: wrapWithTrpcShieldCall({\n shieldObjectTextWrapped: wrapWithObject({ shieldItemLines: rootItems })\n })\n });\n\n return shieldText;\n};\n\nexport const constructDefaultOptions = (\n config: Config,\n options: GeneratorOptions,\n outputDir: string\n) => {\n return `import { ZodError } from 'zod';${config.withNext ? '\\nimport { transformer } from \"@stryke/trpc-next/shared\";' : \"\"}\nimport type {\n DataTransformerOptions,\n RootConfig\n} from \"@trpc/server/unstable-core-do-not-import\";\nimport type { Context } from \"${relativePath(outputDir, joinPaths(outputDir, config.contextPath))}\";\n\ninterface RuntimeConfigOptions<\n TContext extends object,\n TMeta extends object = object\n> extends Partial<\n Omit<\n RootConfig<{\n ctx: TContext;\n meta: TMeta;\n errorShape: any;\n transformer: any;\n }>,\n \"$types\" | \"transformer\"\n >\n > {\n /**\n * Use a data transformer\n * @see https://trpc.io/docs/v11/data-transformers\n */\n transformer?: DataTransformerOptions;\n}\n\nconst options: RuntimeConfigOptions<Context> = {${config.withNext ? \"\\n transformer,\" : \"\"}\n errorFormatter({ shape, error }) {\n return {\n ...shape,\n data: {\n ...shape.data,\n zodError:\n error.code === \"BAD_REQUEST\" && error.cause instanceof ZodError\n ? error.cause.flatten()\n : null\n }\n };\n }\n};\n\nexport default options;\n`;\n};\n\nexport const constructZodModels = async (\n models: Writeable<DMMF.Model[]>,\n outputPath: string,\n config: Config,\n options: GeneratorOptions\n) => {\n const indexFile = project.createSourceFile(\n `${outputPath}/index.ts`,\n {},\n { overwrite: true }\n );\n\n generateBarrelFile(models, indexFile);\n\n indexFile.formatText({\n indentSize: 2\n });\n\n await Promise.all(\n models.map(async model => {\n const sourceFile = project.createSourceFile(\n `${outputPath}/${lowerCaseFirst(model.name)}.schema.ts`,\n {},\n { overwrite: true }\n );\n\n await populateModelFile(model, sourceFile, config, options);\n\n sourceFile.formatText({\n indentSize: 2\n });\n })\n );\n};\n"],"mappings":"sWAkCA,MAAM,EAAoB,GACjB,EAAO,WACV,oBACA,EAAO,eACL,qBACA,kBAGK,GAA8B,CACzC,aACA,YAII,CACJ,IAAM,EAAU,CAAC,IAAI,CAEjB,GACF,EAAQ,KAAK,EAAiB,EAAO,CAAC,CAGxC,EAAW,qBAAqB,CAC9B,gBAAiB,UACjB,aAAc,EACf,CAAC,EA4BS,GACX,EACA,EACA,IACG,CACH,EAAW,qBAAqB,CAC9B,gBAAiB,KAAK,EAAe,EAAmB,CAAC,SACzD,aAAc,CAAC,GAAG,EAAgB,QAAQ,CAC3C,CAAC,EAGJ,eAAsB,EACpB,EACA,EACA,EACA,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2B,iBAAiB,EAAe,CAC/D,gBAAiB,EAAc,IAC7B,GAAgB,GAAG,EAAa,SACjC,CACF,CAAC,CAAC,GACH,GAAa,EAGf,GAAI,EAAU,SAAW,EACvB,MAAO,GAGT,IAAI,EAAa,EAAW,cAAc,CAY1C,MAXA,IAAc,EACZ,UACA,EAAa,EAAW,EAAU,EAAW,EAAO,YAAY,CAAC,CAClE,CACD,GAAc;;EACd,GAAc,EAAe,CAC3B,iBAAkB,EAAuB,CACvC,wBAAyB,EAAe,CAAE,gBAAiB,EAAW,CAAC,CACxE,CAAC,CACH,CAAC,CAEK,GAGI,GACX,EACA,EACA,IAEO,kCAAkC,EAAO,SAAW;yDAA8D,GAAG;;;;;gCAK9F,EAAa,EAAW,EAAU,EAAW,EAAO,YAAY,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;kDAuBhD,EAAO,SAAW;eAAoB,GAAG;;;;;;;;;;;;;;;;EAmB9E,EAAqB,MAChC,EACA,EACA,EACA,IACG,CACH,IAAM,EAAY,EAAQ,iBACxB,GAAG,EAAW,WACd,EAAE,CACF,CAAE,UAAW,GAAM,CACpB,CAED,EAAmB,EAAQ,EAAU,CAErC,EAAU,WAAW,CACnB,WAAY,EACb,CAAC,CAEF,MAAM,QAAQ,IACZ,EAAO,IAAI,KAAM,IAAS,CACxB,IAAM,EAAa,EAAQ,iBACzB,GAAG,EAAW,GAAG,EAAe,EAAM,KAAK,CAAC,YAC5C,EAAE,CACF,CAAE,UAAW,GAAM,CACpB,CAED,MAAM,EAAkB,EAAO,EAAY,EAAQ,EAAQ,CAE3D,EAAW,WAAW,CACpB,WAAY,EACb,CAAC,EACF,CACH"}
|
|
1
|
+
{"version":3,"file":"helpers.mjs","names":["parsedAttributeArgs: Record<string, unknown>"],"sources":["../src/helpers.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Stryke\n\n This code was released as part of the Stryke project. Stryke\n is maintained by Storm Software under the Apache-2.0 License, and is\n free for commercial and private use. For more information, please visit\n our licensing page.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/stryke\n Documentation: https://stormsoftware.com/projects/stryke/docs\n Contact: https://stormsoftware.com/contact\n License: https://stormsoftware.com/projects/stryke/license\n\n ------------------------------------------------------------------- */\n\n/* eslint-disable ts/no-use-before-define */\n\nimport type {\n DMMF,\n EnvValue,\n GeneratorOptions\n} from \"@prisma/generator-helper\";\nimport { relativePath } from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { lowerCaseFirst } from \"@stryke/string-format/lower-case-first\";\nimport type { SourceFile } from \"ts-morph\";\nimport type { Config } from \"./config\";\nimport { project } from \"./project\";\nimport type { Writeable } from \"./types\";\nimport { getPrismaInternals } from \"./utils/get-prisma-internals\";\nimport { generateBarrelFile, populateModelFile } from \"./zod/model-helpers\";\n\nconst getProcedureName = (config: Config) => {\n return config.withShield\n ? \"shieldedProcedure\"\n : config.withMiddleware\n ? \"protectedProcedure\"\n : \"publicProcedure\";\n};\n\nexport const generateCreateRouterImport = ({\n sourceFile,\n config\n}: {\n sourceFile: SourceFile;\n config?: Config;\n}) => {\n const imports = [\"t\"];\n\n if (config) {\n imports.push(getProcedureName(config));\n }\n\n sourceFile.addImportDeclaration({\n moduleSpecifier: \"../trpc\",\n namedImports: imports\n });\n};\n\nexport const generateRPCImport = (sourceFile: SourceFile) => {\n sourceFile.addImportDeclaration({\n moduleSpecifier: \"@trpc/server\",\n namespaceImport: \"trpc\"\n });\n};\n\nexport const generateMiddlewareImport = async (\n sourceFile: SourceFile,\n options: GeneratorOptions\n) => {\n const internals = await getPrismaInternals();\n\n const outputDir = internals.parseEnvValue(\n options.generator.output as EnvValue\n );\n sourceFile.addImportDeclaration({\n moduleSpecifier: relativePath(\n outputDir,\n joinPaths(outputDir, \"middleware\")\n ),\n namedImports: [\"permissions\"]\n });\n};\n\nexport const generateRouterImport = (\n sourceFile: SourceFile,\n modelNamePlural: string,\n modelNameCamelCase: string\n) => {\n sourceFile.addImportDeclaration({\n moduleSpecifier: `./${lowerCaseFirst(modelNameCamelCase)}.router`,\n namedImports: [`${modelNamePlural}Router`]\n });\n};\n\nexport async function generateTRPCExports(\n sourceFile: SourceFile,\n config: Config,\n options: GeneratorOptions,\n outputDir: string\n) {\n if (config.withShield) {\n sourceFile.addImportDeclaration({\n moduleSpecifier: relativePath(\n outputDir,\n joinPaths(\n outputDir,\n typeof config.withShield === \"string\" ? config.withShield : \"shield\"\n )\n ),\n namedImports: [\"permissions\"]\n });\n }\n\n sourceFile.addStatements(\n /* ts */ `import type { Context } from '${relativePath(\n outputDir,\n joinPaths(outputDir, config.contextPath)\n )}';`\n );\n\n if (config.trpcOptions) {\n sourceFile.addStatements(\n /* ts */ `import trpcOptions from '${\n typeof config.trpcOptions === \"string\"\n ? relativePath(outputDir, joinPaths(outputDir, config.trpcOptions))\n : \"./options\"\n }';`\n );\n }\n\n if (config.withNext) {\n sourceFile.addStatements(/* ts */ `import { createContext } from '${relativePath(\n outputDir,\n joinPaths(outputDir, config.contextPath)\n )}';\nimport { initTRPC } from '@trpc/server';\nimport { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';\nimport { cookies } from \"next/headers\";`);\n }\n\n sourceFile.addStatements(/* ts */ `\nexport const t = initTRPC.context<Context>().create(${\n config.trpcOptions ? \"trpcOptions\" : \"\"\n });`);\n\n const middlewares = [];\n\n if (config.withMiddleware && typeof config.withMiddleware === \"boolean\") {\n sourceFile.addStatements(/* ts */ `\nexport const globalMiddleware = t.middleware(async ({ ctx, next }) => {\n console.log('inside middleware!')\n return next()\n});`);\n middlewares.push({\n type: \"global\",\n value: /* ts */ `.use(globalMiddleware)`\n });\n }\n\n if (config.withMiddleware && typeof config.withMiddleware === \"string\") {\n sourceFile.addStatements(/* ts */ `\nimport middleware from '${relativePath(\n outputDir,\n joinPaths(\n outputDir,\n typeof config.withMiddleware === \"string\"\n ? config.withMiddleware\n : \"middleware\"\n )\n )}';\n `);\n sourceFile.addStatements(/* ts */ `\nexport const globalMiddleware = t.middleware(middleware);`);\n middlewares.push({\n type: \"global\",\n value: /* ts */ `.use(globalMiddleware)`\n });\n }\n\n if (config.withShield) {\n sourceFile.addStatements(/* ts */ `\nexport const permissionsMiddleware = t.middleware(permissions);\n `);\n\n middlewares.push({\n type: \"shield\",\n value: /* ts */ `\n .use(permissions)`\n });\n }\n\n sourceFile.addStatements(/* ts */ `\n/**\n * Create a server-side caller\n * @see https://trpc.io/docs/server/server-side-calls\n */\nexport const createCallerFactory = t.createCallerFactory;`);\n\n sourceFile.addStatements(/* ts */ `\nexport const publicProcedure = t.procedure; `);\n\n if (middlewares.length > 0) {\n const procName = getProcedureName(config);\n\n middlewares.forEach((middleware, i) => {\n if (i === 0) {\n sourceFile.addStatements(/* ts */ `\nexport const ${procName} = t.procedure`);\n }\n\n sourceFile.addStatements(\n /* ts */ `.use(${\n middleware.type === \"shield\"\n ? \"permissionsMiddleware\"\n : \"globalMiddleware\"\n })`\n );\n });\n }\n\n if (config.withNext) {\n sourceFile.addStatements(/* ts */ `\nexport const createAction: ReturnType<typeof createTRPCServerActionHandler> =\n createTRPCServerActionHandler(cookies, t, createContext);\n`);\n }\n\n sourceFile.formatText({\n indentSize: 2\n });\n}\n\nexport function generateProcedure(\n sourceFile: SourceFile,\n name: string,\n typeName: string,\n modelName: string,\n opType: string,\n baseOpType: string,\n config: Config\n) {\n let input = `input${!config.withZod ? \" as any\" : \"\"}`;\n const nameWithoutModel = name.replace(modelName, \"\");\n if (nameWithoutModel === \"groupBy\" && config.withZod) {\n input =\n \"{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }\";\n }\n sourceFile.addStatements(/* ts */ `${\n config.showModelNameInProcedure ? name : nameWithoutModel\n }: ${getProcedureName(config)}\n ${config.withZod ? `.input(${lowerCaseFirst(typeName)})` : \"\"}.${getProcedureTypeByOpName(\n baseOpType\n )}(async ({ ctx, input }) => {\n const ${name} = await ctx.prisma.${lowerCaseFirst(\n modelName\n )}.${opType.replace(\"One\", \"\")}(${input});\n return ${name};\n }),`);\n}\n\nexport function generateRouterSchemaImports(\n sourceFile: SourceFile,\n modelName: string,\n modelActions: string[]\n) {\n sourceFile.addStatements(\n /* ts */\n [\n // remove any duplicate import statements\n ...new Set(\n modelActions.map(opName =>\n getRouterSchemaImportByOpName(opName, modelName)\n )\n )\n ].join(\"\\n\")\n );\n}\n\nexport const getRouterSchemaImportByOpName = (\n opName: string,\n modelName: string\n) => {\n const opType = opName.replace(\"OrThrow\", \"\").replace(\"ManyAndReturn\", \"\");\n const inputType = getInputTypeByOpName(opType, modelName);\n\n return inputType\n ? `import { ${lowerCaseFirst(inputType)} } from \"../schemas/${lowerCaseFirst(opType)}${modelName}.schema\"; `\n : \"\";\n};\n\nexport const getInputTypeByOpName = (opName: string, modelName: string) => {\n let inputType;\n switch (opName) {\n case \"findUnique\":\n inputType = `${modelName}FindUniqueSchema`;\n break;\n case \"findFirst\":\n inputType = `${modelName}FindFirstSchema`;\n break;\n case \"findMany\":\n inputType = `${modelName}FindManySchema`;\n break;\n case \"findRaw\":\n inputType = `${modelName}FindRawObjectSchema`;\n break;\n case \"createOne\":\n inputType = `${modelName}CreateOneSchema`;\n break;\n case \"createMany\":\n inputType = `${modelName}CreateManySchema`;\n break;\n case \"createManyAndReturn\":\n inputType = `${modelName}CreateManySchema`;\n break;\n case \"deleteOne\":\n inputType = `${modelName}DeleteOneSchema`;\n break;\n case \"deleteMany\":\n inputType = `${modelName}DeleteManySchema`;\n break;\n case \"updateOne\":\n inputType = `${modelName}UpdateOneSchema`;\n break;\n case \"updateMany\":\n inputType = `${modelName}UpdateManySchema`;\n break;\n case \"updateManyAndReturn\":\n inputType = `${modelName}UpdateManySchema`;\n break;\n case \"upsertOne\":\n inputType = `${modelName}UpsertSchema`;\n break;\n case \"aggregate\":\n inputType = `${modelName}AggregateSchema`;\n break;\n case \"aggregateRaw\":\n inputType = `${modelName}AggregateRawObjectSchema`;\n break;\n case \"groupBy\":\n inputType = `${modelName}GroupBySchema`;\n break;\n default:\n // eslint-disable-next-line no-console\n console.log(\"getInputTypeByOpName: \", { opName, modelName });\n }\n return inputType;\n};\n\nexport const getProcedureTypeByOpName = (opName: string) => {\n let procType;\n switch (opName) {\n case \"findUnique\":\n case \"findFirst\":\n case \"findMany\":\n case \"findRaw\":\n case \"aggregate\":\n case \"aggregateRaw\":\n case \"groupBy\":\n procType = \"query\";\n break;\n case \"createOne\":\n case \"createMany\":\n case \"createManyAndReturn\":\n case \"deleteOne\":\n case \"updateOne\":\n case \"deleteMany\":\n case \"updateMany\":\n case \"updateManyAndReturn\":\n case \"upsertOne\":\n procType = \"mutation\";\n break;\n default:\n // eslint-disable-next-line no-console\n console.log(\"getProcedureTypeByOpName: \", { opName });\n }\n return procType;\n};\n\nexport function resolveModelsComments(\n models: DMMF.Model[],\n hiddenModels: string[]\n) {\n // eslint-disable-next-line regexp/no-obscure-range\n const modelAttributeRegex = /(?:@@Gen\\.)+[A-z]+\\(.+\\)/;\n const attributeNameRegex = /\\.+[A-Z]+\\(+/i;\n const attributeArgsRegex = /\\(+[A-Z]+:.+\\)/i;\n\n for (const model of models) {\n if (model.documentation) {\n const attribute = model.documentation?.match(modelAttributeRegex)?.[0];\n const attributeName = attribute\n ?.match(attributeNameRegex)?.[0]\n ?.slice(1, -1);\n if (attributeName !== \"model\") continue;\n const rawAttributeArgs = attribute\n ?.match(attributeArgsRegex)?.[0]\n ?.slice(1, -1);\n\n const parsedAttributeArgs: Record<string, unknown> = {};\n if (rawAttributeArgs) {\n const rawAttributeArgsParts = rawAttributeArgs\n .split(\":\")\n .map(it => it.trim())\n .map(part => (part.startsWith(\"[\") ? part : part.split(\",\")))\n .flat()\n .map(it => it.trim());\n\n for (let i = 0; i < rawAttributeArgsParts.length; i += 2) {\n const key = rawAttributeArgsParts[i];\n const value = rawAttributeArgsParts[i + 1];\n parsedAttributeArgs[key!] = JSON.parse(value!);\n }\n }\n\n if (parsedAttributeArgs.hide) {\n hiddenModels.push(model.name);\n }\n }\n }\n}\n\nexport const getImports = (\n type: \"trpc\" | \"trpc-shield\" | \"context\",\n newPath?: string\n) => {\n let statement = \"\";\n if (type === \"trpc\") {\n statement = \"import * as trpc from '@trpc/server';\\n\";\n } else if (type === \"trpc-shield\") {\n statement = \"import { shield, allow } from '@stryke/trpc-next/shield';\\n\";\n } else if (type === \"context\") {\n statement = `import type { Context } from '${newPath}';\\n`;\n }\n\n return statement;\n};\n\nexport const wrapWithObject = ({\n shieldItemLines\n}: {\n shieldItemLines: Array<string> | string;\n}) => {\n let wrapped = \"{\";\n wrapped += \"\\n\";\n wrapped += Array.isArray(shieldItemLines)\n ? ` ${shieldItemLines.join(\",\\r\\n\")}`\n : ` ${shieldItemLines}`;\n wrapped += \"\\n\";\n wrapped += \"}\";\n return wrapped;\n};\n\nexport const wrapWithTrpcShieldCall = ({\n shieldObjectTextWrapped\n}: {\n shieldObjectTextWrapped: string;\n}) => {\n let wrapped = \"shield<Context>(\";\n wrapped += \"\\n\";\n wrapped += ` ${shieldObjectTextWrapped}`;\n wrapped += \"\\n\";\n wrapped += \")\";\n return wrapped;\n};\n\nexport const wrapWithExport = ({\n shieldObjectText\n}: {\n shieldObjectText: string;\n}) => {\n return `export const permissions: ReturnType<typeof shield<Context>> = ${shieldObjectText};`;\n};\n\nexport const constructShield = async (\n {\n queries,\n mutations,\n subscriptions\n }: {\n queries: Array<string>;\n mutations: Array<string>;\n subscriptions: Array<string>;\n },\n config: Config,\n options: GeneratorOptions,\n outputDir: string\n) => {\n if (\n queries.length === 0 &&\n mutations.length === 0 &&\n subscriptions.length === 0\n ) {\n return \"\";\n }\n\n let rootItems = \"\";\n if (queries.length > 0) {\n const queryLinesWrapped = `query: ${wrapWithObject({\n shieldItemLines: queries.map(query => `${query}: allow`)\n })},`;\n rootItems += queryLinesWrapped;\n }\n if (mutations.length > 0) {\n const mutationLinesWrapped = `mutation: ${wrapWithObject({\n shieldItemLines: mutations.map(mutation => `${mutation}: allow`)\n })},`;\n rootItems += mutationLinesWrapped;\n }\n\n if (subscriptions.length > 0) {\n const subscriptionLinesWrapped = `subscription: ${wrapWithObject({\n shieldItemLines: subscriptions.map(\n subscription => `${subscription}: allow`\n )\n })},`;\n rootItems += subscriptionLinesWrapped;\n }\n\n if (rootItems.length === 0) {\n return \"\";\n }\n\n let shieldText = getImports(\"trpc-shield\");\n shieldText += getImports(\n \"context\",\n relativePath(outputDir, joinPaths(outputDir, config.contextPath))\n );\n shieldText += \"\\n\\n\";\n shieldText += wrapWithExport({\n shieldObjectText: wrapWithTrpcShieldCall({\n shieldObjectTextWrapped: wrapWithObject({ shieldItemLines: rootItems })\n })\n });\n\n return shieldText;\n};\n\nexport const constructDefaultOptions = (\n config: Config,\n options: GeneratorOptions,\n outputDir: string\n) => {\n return `import { ZodError } from 'zod';${config.withNext ? '\\nimport { transformer } from \"@stryke/trpc-next/shared\";' : \"\"}\nimport type {\n DataTransformerOptions,\n RootConfig\n} from \"@trpc/server/unstable-core-do-not-import\";\nimport type { Context } from \"${relativePath(outputDir, joinPaths(outputDir, config.contextPath))}\";\n\ninterface RuntimeConfigOptions<\n TContext extends object,\n TMeta extends object = object\n> extends Partial<\n Omit<\n RootConfig<{\n ctx: TContext;\n meta: TMeta;\n errorShape: any;\n transformer: any;\n }>,\n \"$types\" | \"transformer\"\n >\n > {\n /**\n * Use a data transformer\n * @see https://trpc.io/docs/v11/data-transformers\n */\n transformer?: DataTransformerOptions;\n}\n\nconst options: RuntimeConfigOptions<Context> = {${config.withNext ? \"\\n transformer,\" : \"\"}\n errorFormatter({ shape, error }) {\n return {\n ...shape,\n data: {\n ...shape.data,\n zodError:\n error.code === \"BAD_REQUEST\" && error.cause instanceof ZodError\n ? error.cause.flatten()\n : null\n }\n };\n }\n};\n\nexport default options;\n`;\n};\n\nexport const constructZodModels = async (\n models: Writeable<DMMF.Model[]>,\n outputPath: string,\n config: Config,\n options: GeneratorOptions\n) => {\n const indexFile = project.createSourceFile(\n `${outputPath}/index.ts`,\n {},\n { overwrite: true }\n );\n\n generateBarrelFile(models, indexFile);\n\n indexFile.formatText({\n indentSize: 2\n });\n\n await Promise.all(\n models.map(async model => {\n const sourceFile = project.createSourceFile(\n `${outputPath}/${lowerCaseFirst(model.name)}.schema.ts`,\n {},\n { overwrite: true }\n );\n\n await populateModelFile(model, sourceFile, config, options);\n\n sourceFile.formatText({\n indentSize: 2\n });\n })\n );\n};\n"],"mappings":";;;;;;;;AAkCA,MAAM,oBAAoB,WAAmB;AAC3C,QAAO,OAAO,aACV,sBACA,OAAO,iBACL,uBACA;;AAGR,MAAa,8BAA8B,EACzC,YACA,aAII;CACJ,MAAM,UAAU,CAAC,IAAI;AAErB,KAAI,OACF,SAAQ,KAAK,iBAAiB,OAAO,CAAC;AAGxC,YAAW,qBAAqB;EAC9B,iBAAiB;EACjB,cAAc;EACf,CAAC;;AA4BJ,MAAa,wBACX,YACA,iBACA,uBACG;AACH,YAAW,qBAAqB;EAC9B,iBAAiB,KAAK,eAAe,mBAAmB,CAAC;EACzD,cAAc,CAAC,GAAG,gBAAgB,QAAQ;EAC3C,CAAC;;AAGJ,eAAsB,oBACpB,YACA,QACA,SACA,WACA;AACA,KAAI,OAAO,WACT,YAAW,qBAAqB;EAC9B,iBAAiB,aACf,WACA,UACE,WACA,OAAO,OAAO,eAAe,WAAW,OAAO,aAAa,SAC7D,CACF;EACD,cAAc,CAAC,cAAc;EAC9B,CAAC;AAGJ,YAAW,cACA,iCAAiC,aACxC,WACA,UAAU,WAAW,OAAO,YAAY,CACzC,CAAC,IACH;AAED,KAAI,OAAO,YACT,YAAW,cACA,4BACP,OAAO,OAAO,gBAAgB,WAC1B,aAAa,WAAW,UAAU,WAAW,OAAO,YAAY,CAAC,GACjE,YACL,IACF;AAGH,KAAI,OAAO,SACT,YAAW,cAAuB,kCAAkC,aAClE,WACA,UAAU,WAAW,OAAO,YAAY,CACzC,CAAC;;;yCAGmC;AAGvC,YAAW,cAAuB;sDAEhC,OAAO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BAAkB,uBAAuB,EACvC,yBAAyB,eAAe,EAAE,iBAAiB,WAAW,CAAC,EACxE,CAAC,EACH,CAAC;AAEF,QAAO;;AAGT,MAAa,2BACX,QACA,SACA,cACG;AACH,QAAO,kCAAkC,OAAO,WAAW,gEAA8D,GAAG;;;;;gCAK9F,aAAa,WAAW,UAAU,WAAW,OAAO,YAAY,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;kDAuBhD,OAAO,WAAW,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;AAmB3F,MAAa,qBAAqB,OAChC,QACA,YACA,QACA,YACG;CACH,MAAM,YAAY,QAAQ,iBACxB,GAAG,WAAW,YACd,EAAE,EACF,EAAE,WAAW,MAAM,CACpB;AAED,oBAAmB,QAAQ,UAAU;AAErC,WAAU,WAAW,EACnB,YAAY,GACb,CAAC;AAEF,OAAM,QAAQ,IACZ,OAAO,IAAI,OAAM,UAAS;EACxB,MAAM,aAAa,QAAQ,iBACzB,GAAG,WAAW,GAAG,eAAe,MAAM,KAAK,CAAC,aAC5C,EAAE,EACF,EAAE,WAAW,MAAM,CACpB;AAED,QAAM,kBAAkB,OAAO,YAAY,QAAQ,QAAQ;AAE3D,aAAW,WAAW,EACpB,YAAY,GACb,CAAC;GACF,CACH"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1,26 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_get_prisma_internals = require('./utils/get-prisma-internals.cjs');
|
|
2
|
+
const require_prisma_generator = require('./prisma-generator.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* The prisma-trpc-generator library used by Storm Software for building NodeJS applications.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* A fork of the prisma-trpc-generator code to work in ESM
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
12
|
+
*/
|
|
13
|
+
require_get_prisma_internals.getPrismaGeneratorHelper().then((helpers) => {
|
|
14
|
+
helpers.generatorHandler({
|
|
15
|
+
onManifest: () => ({
|
|
16
|
+
defaultOutput: "./generated",
|
|
17
|
+
prettyName: "Storm Software - Prisma tRPC Generator",
|
|
18
|
+
requiresGenerators: ["prisma-client-js"]
|
|
19
|
+
}),
|
|
20
|
+
onGenerate: require_prisma_generator.generate
|
|
21
|
+
});
|
|
22
|
+
}).catch((reason) => {
|
|
23
|
+
console.error(`An error occured while generating prisma tRPC source code: ${reason}`);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
//#endregion
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,28 @@
|
|
|
1
|
-
import{getPrismaGeneratorHelper
|
|
1
|
+
import { getPrismaGeneratorHelper } from "./utils/get-prisma-internals.mjs";
|
|
2
|
+
import { generate } from "./prisma-generator.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* The prisma-trpc-generator library used by Storm Software for building NodeJS applications.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* A fork of the prisma-trpc-generator code to work in ESM
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
12
|
+
*/
|
|
13
|
+
getPrismaGeneratorHelper().then((helpers) => {
|
|
14
|
+
helpers.generatorHandler({
|
|
15
|
+
onManifest: () => ({
|
|
16
|
+
defaultOutput: "./generated",
|
|
17
|
+
prettyName: "Storm Software - Prisma tRPC Generator",
|
|
18
|
+
requiresGenerators: ["prisma-client-js"]
|
|
19
|
+
}),
|
|
20
|
+
onGenerate: generate
|
|
21
|
+
});
|
|
22
|
+
}).catch((reason) => {
|
|
23
|
+
console.error(`An error occured while generating prisma tRPC source code: ${reason}`);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
//#endregion
|
|
27
|
+
export { };
|
|
2
28
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Stryke\n\n This code was released as part of the Stryke project. Stryke\n is maintained by Storm Software under the Apache-2.0 License, and is\n free for commercial and private use. For more information, please visit\n our licensing page.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/stryke\n Documentation: https://stormsoftware.com/projects/stryke/docs\n Contact: https://stormsoftware.com/contact\n License: https://stormsoftware.com/projects/stryke/license\n\n ------------------------------------------------------------------- */\n\n/**\n * The prisma-trpc-generator library used by Storm Software for building NodeJS applications.\n *\n * @remarks\n * A fork of the prisma-trpc-generator code to work in ESM\n *\n * @packageDocumentation\n */\n\nimport { generate } from \"./prisma-generator\";\nimport { getPrismaGeneratorHelper } from \"./utils/get-prisma-internals\";\n\ngetPrismaGeneratorHelper()\n .then(helpers => {\n helpers.generatorHandler({\n onManifest: () => ({\n defaultOutput: \"./generated\",\n prettyName: \"Storm Software - Prisma tRPC Generator\",\n requiresGenerators: [\"prisma-client-js\"]\n }),\n onGenerate: generate\n });\n })\n .catch(reason => {\n // eslint-disable-next-line no-console\n console.error(\n `An error occured while generating prisma tRPC source code: ${reason}`\n );\n });\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Stryke\n\n This code was released as part of the Stryke project. Stryke\n is maintained by Storm Software under the Apache-2.0 License, and is\n free for commercial and private use. For more information, please visit\n our licensing page.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/stryke\n Documentation: https://stormsoftware.com/projects/stryke/docs\n Contact: https://stormsoftware.com/contact\n License: https://stormsoftware.com/projects/stryke/license\n\n ------------------------------------------------------------------- */\n\n/**\n * The prisma-trpc-generator library used by Storm Software for building NodeJS applications.\n *\n * @remarks\n * A fork of the prisma-trpc-generator code to work in ESM\n *\n * @packageDocumentation\n */\n\nimport { generate } from \"./prisma-generator\";\nimport { getPrismaGeneratorHelper } from \"./utils/get-prisma-internals\";\n\ngetPrismaGeneratorHelper()\n .then(helpers => {\n helpers.generatorHandler({\n onManifest: () => ({\n defaultOutput: \"./generated\",\n prettyName: \"Storm Software - Prisma tRPC Generator\",\n requiresGenerators: [\"prisma-client-js\"]\n }),\n onGenerate: generate\n });\n })\n .catch(reason => {\n // eslint-disable-next-line no-console\n console.error(\n `An error occured while generating prisma tRPC source code: ${reason}`\n );\n });\n"],"mappings":";;;;;;;;;;;;AA6BA,0BAA0B,CACvB,MAAK,YAAW;AACf,SAAQ,iBAAiB;EACvB,mBAAmB;GACjB,eAAe;GACf,YAAY;GACZ,oBAAoB,CAAC,mBAAmB;GACzC;EACD,YAAY;EACb,CAAC;EACF,CACD,OAAM,WAAU;AAEf,SAAQ,MACN,8DAA8D,SAC/D;EACD"}
|
|
@@ -1 +1,87 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_title_case = require('../../string-format/src/title-case.cjs');
|
|
3
|
+
let __stryke_path_join_paths = require("@stryke/path/join-paths");
|
|
4
|
+
let node_path = require("node:path");
|
|
5
|
+
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
6
|
+
let node_os = require("node:os");
|
|
7
|
+
node_os = require_rolldown_runtime.__toESM(node_os);
|
|
8
|
+
|
|
9
|
+
//#region ../env/src/get-env-paths.ts
|
|
10
|
+
const homedir = node_os.default.homedir();
|
|
11
|
+
const tmpdir = node_os.default.tmpdir();
|
|
12
|
+
const macos = (orgId) => {
|
|
13
|
+
const library = (0, __stryke_path_join_paths.joinPaths)(homedir, "Library");
|
|
14
|
+
return {
|
|
15
|
+
data: (0, __stryke_path_join_paths.joinPaths)(library, "Application Support", orgId),
|
|
16
|
+
config: (0, __stryke_path_join_paths.joinPaths)(library, "Preferences", orgId),
|
|
17
|
+
cache: (0, __stryke_path_join_paths.joinPaths)(library, "Caches", orgId),
|
|
18
|
+
log: (0, __stryke_path_join_paths.joinPaths)(library, "Logs", orgId),
|
|
19
|
+
temp: (0, __stryke_path_join_paths.joinPaths)(tmpdir, orgId)
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
const windows = (orgId) => {
|
|
23
|
+
const appData = process.env.APPDATA || (0, __stryke_path_join_paths.joinPaths)(homedir, "AppData", "Roaming");
|
|
24
|
+
const localAppData = process.env.LOCALAPPDATA || (0, __stryke_path_join_paths.joinPaths)(homedir, "AppData", "Local");
|
|
25
|
+
const windowsFormattedOrgId = require_title_case.titleCase(orgId).trim().replace(/\s+/g, "");
|
|
26
|
+
return {
|
|
27
|
+
data: (0, __stryke_path_join_paths.joinPaths)(localAppData, windowsFormattedOrgId, "Data"),
|
|
28
|
+
config: (0, __stryke_path_join_paths.joinPaths)(appData, windowsFormattedOrgId, "Config"),
|
|
29
|
+
cache: (0, __stryke_path_join_paths.joinPaths)(localAppData, "Cache", orgId),
|
|
30
|
+
log: (0, __stryke_path_join_paths.joinPaths)(localAppData, windowsFormattedOrgId, "Log"),
|
|
31
|
+
temp: (0, __stryke_path_join_paths.joinPaths)(tmpdir, orgId)
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
const linux = (orgId) => {
|
|
35
|
+
const username = node_path.default.basename(homedir);
|
|
36
|
+
return {
|
|
37
|
+
data: (0, __stryke_path_join_paths.joinPaths)(process.env.XDG_DATA_HOME || (0, __stryke_path_join_paths.joinPaths)(homedir, ".local", "share"), orgId),
|
|
38
|
+
config: (0, __stryke_path_join_paths.joinPaths)(process.env.XDG_CONFIG_HOME || (0, __stryke_path_join_paths.joinPaths)(homedir, ".config"), orgId),
|
|
39
|
+
cache: (0, __stryke_path_join_paths.joinPaths)(process.env.XDG_CACHE_HOME || (0, __stryke_path_join_paths.joinPaths)(homedir, ".cache"), orgId),
|
|
40
|
+
log: (0, __stryke_path_join_paths.joinPaths)(process.env.XDG_STATE_HOME || (0, __stryke_path_join_paths.joinPaths)(homedir, ".local", "state"), orgId),
|
|
41
|
+
temp: process.env.DEVENV_RUNTIME || process.env.XDG_RUNTIME_DIR ? (0, __stryke_path_join_paths.joinPaths)(process.env.DEVENV_RUNTIME || process.env.XDG_RUNTIME_DIR, orgId) : (0, __stryke_path_join_paths.joinPaths)(tmpdir, username, orgId)
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Get paths for storing things like data, config, logs, and cache in the current runtime environment.
|
|
46
|
+
*
|
|
47
|
+
* @remarks
|
|
48
|
+
* On macOS, directories are generally created in `~/Library/Application Support/<name>`.
|
|
49
|
+
* On Windows, directories are generally created in `%AppData%/<name>`.
|
|
50
|
+
* On Linux, directories are generally created in `~/.config/<name>` - this is determined via the [XDG Base Directory spec](https://specifications.freedesktop.org/basedir-spec/latest/).
|
|
51
|
+
*
|
|
52
|
+
* If the `STORM_DATA_DIR`, `STORM_CONFIG_DIR`, `STORM_CACHE_DIR`, `STORM_LOG_DIR`, or `STORM_TEMP_DIR` environment variables are set, they will be used instead of the default paths.
|
|
53
|
+
*
|
|
54
|
+
* @param options - Parameters used to determine the specific paths for the current project/runtime environment
|
|
55
|
+
* @returns An object containing the various paths for the runtime environment
|
|
56
|
+
*/
|
|
57
|
+
function getEnvPaths(options = {}) {
|
|
58
|
+
let orgId = options.orgId || "storm-software";
|
|
59
|
+
if (!orgId) throw new Error("You need to provide an orgId to the `getEnvPaths` function");
|
|
60
|
+
if (options.suffix) orgId += `-${typeof options.suffix === "string" ? options.suffix : "nodejs"}`;
|
|
61
|
+
let result = {};
|
|
62
|
+
if (process.platform === "darwin") result = macos(orgId);
|
|
63
|
+
else if (process.platform === "win32") result = windows(orgId);
|
|
64
|
+
else result = linux(orgId);
|
|
65
|
+
if (process.env.STORM_DATA_DIR) result.data = process.env.STORM_DATA_DIR;
|
|
66
|
+
else if (process.env.STORM_CONFIG_DIR) result.config = process.env.STORM_CONFIG_DIR;
|
|
67
|
+
else if (process.env.STORM_CACHE_DIR) result.cache = process.env.STORM_CACHE_DIR;
|
|
68
|
+
else if (process.env.STORM_LOG_DIR) result.log = process.env.STORM_LOG_DIR;
|
|
69
|
+
else if (process.env.STORM_TEMP_DIR) result.temp = process.env.STORM_TEMP_DIR;
|
|
70
|
+
if (options.workspaceRoot) {
|
|
71
|
+
result.cache ??= (0, __stryke_path_join_paths.joinPaths)(options.workspaceRoot, "node_modules", ".cache", orgId);
|
|
72
|
+
result.temp ??= (0, __stryke_path_join_paths.joinPaths)(options.workspaceRoot, "tmp", orgId);
|
|
73
|
+
result.log ??= (0, __stryke_path_join_paths.joinPaths)(result.temp, "logs");
|
|
74
|
+
result.config ??= (0, __stryke_path_join_paths.joinPaths)(options.workspaceRoot, ".config", orgId);
|
|
75
|
+
}
|
|
76
|
+
return Object.keys(result).reduce((ret, key) => {
|
|
77
|
+
if (result[key]) {
|
|
78
|
+
const filePath = result[key];
|
|
79
|
+
ret[key] = options.appId && options.appId !== options.orgId && options.appId !== options.nestedDir ? (0, __stryke_path_join_paths.joinPaths)(filePath, options.appId) : filePath;
|
|
80
|
+
if (options.nestedDir && options.nestedDir !== options.orgId && options.nestedDir !== options.appId) ret[key] = (0, __stryke_path_join_paths.joinPaths)(ret[key], options.nestedDir);
|
|
81
|
+
}
|
|
82
|
+
return ret;
|
|
83
|
+
}, {});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
//#endregion
|
|
87
|
+
exports.getEnvPaths = getEnvPaths;
|