@stryke/prisma-trpc-generator 0.13.37 → 0.13.38
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 +1 -0
- package/dist/_virtual/rolldown_runtime.mjs +1 -0
- package/dist/config.cjs +1 -0
- package/dist/config.mjs +2 -0
- package/dist/config.mjs.map +1 -0
- package/dist/generator.d.cts +1 -2
- package/dist/generator.d.mts +1 -2
- package/dist/helpers.cjs +85 -0
- package/dist/helpers.mjs +86 -0
- package/dist/helpers.mjs.map +1 -0
- package/dist/index.cjs +1 -116
- package/dist/index.mjs +1 -116
- package/dist/index.mjs.map +1 -1
- package/dist/packages/env/src/get-env-paths.cjs +1 -0
- package/dist/packages/env/src/get-env-paths.mjs +2 -0
- package/dist/packages/env/src/get-env-paths.mjs.map +1 -0
- package/dist/packages/string-format/src/acronyms.cjs +1 -0
- package/dist/packages/string-format/src/acronyms.mjs +2 -0
- package/dist/packages/string-format/src/acronyms.mjs.map +1 -0
- package/dist/packages/string-format/src/articles.cjs +1 -0
- package/dist/packages/string-format/src/articles.mjs +2 -0
- package/dist/packages/string-format/src/articles.mjs.map +1 -0
- package/dist/packages/string-format/src/combine.cjs +1 -0
- package/dist/packages/string-format/src/combine.mjs +2 -0
- package/dist/packages/string-format/src/combine.mjs.map +1 -0
- package/dist/packages/string-format/src/conjunctions.cjs +1 -0
- package/dist/packages/string-format/src/conjunctions.mjs +2 -0
- package/dist/packages/string-format/src/conjunctions.mjs.map +1 -0
- package/dist/packages/string-format/src/decamelize.cjs +1 -0
- package/dist/packages/string-format/src/decamelize.mjs +2 -0
- package/dist/packages/string-format/src/decamelize.mjs.map +1 -0
- package/dist/packages/string-format/src/format-special-cases.cjs +1 -0
- package/dist/packages/string-format/src/format-special-cases.mjs +2 -0
- package/dist/packages/string-format/src/format-special-cases.mjs.map +1 -0
- package/dist/packages/string-format/src/lower-case-first.cjs +1 -0
- package/dist/packages/string-format/src/lower-case-first.mjs +2 -0
- package/dist/packages/string-format/src/lower-case-first.mjs.map +1 -0
- package/dist/packages/string-format/src/prepositions.cjs +1 -0
- package/dist/packages/string-format/src/prepositions.mjs +2 -0
- package/dist/packages/string-format/src/prepositions.mjs.map +1 -0
- package/dist/packages/string-format/src/special-cases.cjs +1 -0
- package/dist/packages/string-format/src/special-cases.mjs +2 -0
- package/dist/packages/string-format/src/special-cases.mjs.map +1 -0
- package/dist/packages/string-format/src/title-case.cjs +1 -0
- package/dist/packages/string-format/src/title-case.mjs +2 -0
- package/dist/packages/string-format/src/title-case.mjs.map +1 -0
- package/dist/packages/string-format/src/upper-case-first.cjs +1 -0
- package/dist/packages/string-format/src/upper-case-first.mjs +2 -0
- package/dist/packages/string-format/src/upper-case-first.mjs.map +1 -0
- package/dist/prisma-generator.cjs +9 -0
- package/dist/prisma-generator.mjs +10 -0
- package/dist/prisma-generator.mjs.map +1 -0
- package/dist/project.cjs +1 -0
- package/dist/project.mjs +2 -0
- package/dist/project.mjs.map +1 -0
- package/dist/utils/format-file.cjs +1 -0
- package/dist/utils/format-file.mjs +2 -0
- package/dist/utils/format-file.mjs.map +1 -0
- package/dist/utils/get-jiti.cjs +1 -0
- package/dist/utils/get-jiti.mjs +2 -0
- package/dist/utils/get-jiti.mjs.map +1 -0
- package/dist/utils/get-prisma-internals.cjs +1 -0
- package/dist/utils/get-prisma-internals.mjs +2 -0
- package/dist/utils/get-prisma-internals.mjs.map +1 -0
- package/dist/utils/write-file-safely.cjs +2 -0
- package/dist/utils/write-file-safely.mjs +3 -0
- package/dist/utils/write-file-safely.mjs.map +1 -0
- package/dist/zod/aggregate-helpers.cjs +1 -0
- package/dist/zod/aggregate-helpers.mjs +2 -0
- package/dist/zod/aggregate-helpers.mjs.map +1 -0
- package/dist/zod/comments-helpers.cjs +1 -0
- package/dist/zod/comments-helpers.mjs +2 -0
- package/dist/zod/comments-helpers.mjs.map +1 -0
- package/dist/zod/docs-helpers.cjs +3 -0
- package/dist/zod/docs-helpers.mjs +4 -0
- package/dist/zod/docs-helpers.mjs.map +1 -0
- package/dist/zod/generator-helpers.cjs +1 -0
- package/dist/zod/generator-helpers.mjs +2 -0
- package/dist/zod/generator-helpers.mjs.map +1 -0
- package/dist/zod/helpers.cjs +1 -0
- package/dist/zod/helpers.mjs +2 -0
- package/dist/zod/helpers.mjs.map +1 -0
- package/dist/zod/include-helpers.cjs +1 -0
- package/dist/zod/include-helpers.mjs +2 -0
- package/dist/zod/include-helpers.mjs.map +1 -0
- package/dist/zod/model-helpers.cjs +1 -0
- package/dist/zod/model-helpers.mjs +2 -0
- package/dist/zod/model-helpers.mjs.map +1 -0
- package/dist/zod/modelArgs-helpers.cjs +1 -0
- package/dist/zod/modelArgs-helpers.mjs +2 -0
- package/dist/zod/modelArgs-helpers.mjs.map +1 -0
- package/dist/zod/mongodb-helpers.cjs +1 -0
- package/dist/zod/mongodb-helpers.mjs +2 -0
- package/dist/zod/mongodb-helpers.mjs.map +1 -0
- package/dist/zod/select-helpers.cjs +1 -0
- package/dist/zod/select-helpers.mjs +2 -0
- package/dist/zod/select-helpers.mjs.map +1 -0
- package/dist/zod/transformer.cjs +21 -0
- package/dist/zod/transformer.mjs +22 -0
- package/dist/zod/transformer.mjs.map +1 -0
- package/dist/zod/whereUniqueInput-helpers.cjs +1 -0
- package/dist/zod/whereUniqueInput-helpers.mjs +2 -0
- package/dist/zod/whereUniqueInput-helpers.mjs.map +1 -0
- package/package.json +8 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));exports.__commonJSMin=o,exports.__toESM=c;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=e(import.meta.url);export{s as __commonJSMin,u as __require,l as __toESM};
|
package/dist/config.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./_virtual/rolldown_runtime.cjs`);let t=require(`zod`),n=function(e){return e.findUnique=`findUnique`,e.findUniqueOrThrow=`findUniqueOrThrow`,e.findFirst=`findFirst`,e.findFirstOrThrow=`findFirstOrThrow`,e.findMany=`findMany`,e.create=`create`,e.createMany=`createMany`,e.createManyAndReturn=`createManyAndReturn`,e.update=`update`,e.updateMany=`updateMany`,e.updateManyAndReturn=`updateManyAndReturn`,e.upsert=`upsert`,e.delete=`delete`,e.deleteMany=`deleteMany`,e.groupBy=`groupBy`,e.count=`count`,e.aggregate=`aggregate`,e.findRaw=`findRaw`,e.aggregateRaw=`aggregateRaw`,e}({});const r=t.z.nativeEnum(n),i=t.z.string().trim().transform(e=>!e||e.toLowerCase()===`false`||e.toLowerCase()===`n`||e.toLowerCase()===`no`||e===`0`?!1:e.toLowerCase()===`true`||e.toLowerCase()===`y`||e.toLowerCase()===`yes`||e===`1`?!0:e),a=t.z.object({debug:i.default(`false`),withNext:i.default(`true`),withMiddleware:i.default(`false`),withShield:i.default(`false`),contextPath:t.z.string().trim().default(`../context`),trpcOptions:i.default(`true`),showModelNameInProcedure:i.default(`false`),generateModelActions:t.z.string().default(Object.values(n).join(`,`)).transform(e=>e.split(`,`).map(e=>r.parse(e.trim()))),withZod:i.default(`true`),relationModel:i.default(`true`).or(t.z.literal(`default`)),modelSuffix:t.z.string().default(`Schema`),modelCase:t.z.enum([`PascalCase`,`camelCase`]).default(`camelCase`),useDecimalJs:i.default(`true`),imports:t.z.string().optional(),prismaJsonNullability:i.default(`true`)});exports.configSchema=a;
|
package/dist/config.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{z as e}from"zod";let t=function(e){return e.findUnique=`findUnique`,e.findUniqueOrThrow=`findUniqueOrThrow`,e.findFirst=`findFirst`,e.findFirstOrThrow=`findFirstOrThrow`,e.findMany=`findMany`,e.create=`create`,e.createMany=`createMany`,e.createManyAndReturn=`createManyAndReturn`,e.update=`update`,e.updateMany=`updateMany`,e.updateManyAndReturn=`updateManyAndReturn`,e.upsert=`upsert`,e.delete=`delete`,e.deleteMany=`deleteMany`,e.groupBy=`groupBy`,e.count=`count`,e.aggregate=`aggregate`,e.findRaw=`findRaw`,e.aggregateRaw=`aggregateRaw`,e}({});const n=e.nativeEnum(t),r=e.string().trim().transform(e=>!e||e.toLowerCase()===`false`||e.toLowerCase()===`n`||e.toLowerCase()===`no`||e===`0`?!1:e.toLowerCase()===`true`||e.toLowerCase()===`y`||e.toLowerCase()===`yes`||e===`1`?!0:e),i=e.object({debug:r.default(`false`),withNext:r.default(`true`),withMiddleware:r.default(`false`),withShield:r.default(`false`),contextPath:e.string().trim().default(`../context`),trpcOptions:r.default(`true`),showModelNameInProcedure:r.default(`false`),generateModelActions:e.string().default(Object.values(t).join(`,`)).transform(e=>e.split(`,`).map(e=>n.parse(e.trim()))),withZod:r.default(`true`),relationModel:r.default(`true`).or(e.literal(`default`)),modelSuffix:e.string().default(`Schema`),modelCase:e.enum([`PascalCase`,`camelCase`]).default(`camelCase`),useDecimalJs:r.default(`true`),imports:e.string().optional(),prismaJsonNullability:r.default(`true`)});export{i as configSchema};
|
|
2
|
+
//# sourceMappingURL=config.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.mjs","names":[],"sources":["../src/config.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 at https://stormsoftware.com/licenses/projects/stryke.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/stryke\n Documentation: https://docs.stormsoftware.com/projects/stryke\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { z } from \"zod\";\n\nexport enum ModelAction {\n findUnique = \"findUnique\",\n findUniqueOrThrow = \"findUniqueOrThrow\",\n findFirst = \"findFirst\",\n findFirstOrThrow = \"findFirstOrThrow\",\n findMany = \"findMany\",\n create = \"create\",\n createMany = \"createMany\",\n createManyAndReturn = \"createManyAndReturn\",\n update = \"update\",\n updateMany = \"updateMany\",\n updateManyAndReturn = \"updateManyAndReturn\",\n upsert = \"upsert\",\n delete = \"delete\",\n deleteMany = \"deleteMany\",\n groupBy = \"groupBy\",\n count = \"count\", // TODO: count does not actually exist, why?\n aggregate = \"aggregate\",\n findRaw = \"findRaw\",\n aggregateRaw = \"aggregateRaw\"\n}\n\nconst modelActionEnum = z.nativeEnum(ModelAction);\n\nconst configBoolean = z\n .string()\n .trim()\n .transform(value =>\n !value ||\n value.toLowerCase() === \"false\" ||\n value.toLowerCase() === \"n\" ||\n value.toLowerCase() === \"no\" ||\n value === \"0\"\n ? false\n : value.toLowerCase() === \"true\" ||\n value.toLowerCase() === \"y\" ||\n value.toLowerCase() === \"yes\" ||\n value === \"1\"\n ? true\n : value\n );\n\nexport const configSchema = z.object({\n debug: configBoolean.default(\"false\"),\n withNext: configBoolean.default(\"true\"),\n withMiddleware: configBoolean.default(\"false\"),\n withShield: configBoolean.default(\"false\"),\n contextPath: z.string().trim().default(\"../context\"),\n trpcOptions: configBoolean.default(\"true\"),\n showModelNameInProcedure: configBoolean.default(\"false\"),\n generateModelActions: z\n .string()\n .default(Object.values(ModelAction).join(\",\"))\n .transform(arg => {\n return arg.split(\",\").map(action => modelActionEnum.parse(action.trim()));\n }),\n\n // Zod configuration\n withZod: configBoolean.default(\"true\"),\n relationModel: configBoolean.default(\"true\").or(z.literal(\"default\")),\n modelSuffix: z.string().default(\"Schema\"),\n modelCase: z.enum([\"PascalCase\", \"camelCase\"]).default(\"camelCase\"),\n useDecimalJs: configBoolean.default(\"true\"),\n imports: z.string().optional(),\n prismaJsonNullability: configBoolean.default(\"true\")\n});\n\nexport type Config = z.infer<typeof configSchema>;\n"],"mappings":"wBAoBA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,WAAA,aACA,EAAA,kBAAA,oBACA,EAAA,UAAA,YACA,EAAA,iBAAA,mBACA,EAAA,SAAA,WACA,EAAA,OAAA,SACA,EAAA,WAAA,aACA,EAAA,oBAAA,sBACA,EAAA,OAAA,SACA,EAAA,WAAA,aACA,EAAA,oBAAA,sBACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,WAAA,aACA,EAAA,QAAA,UACA,EAAA,MAAA,QACA,EAAA,UAAA,YACA,EAAA,QAAA,UACA,EAAA,aAAA,sBAGF,MAAM,EAAkB,EAAE,WAAW,EAAY,CAE3C,EAAgB,EACnB,QAAQ,CACR,MAAM,CACN,UAAU,GACT,CAAC,GACD,EAAM,aAAa,GAAK,SACxB,EAAM,aAAa,GAAK,KACxB,EAAM,aAAa,GAAK,MACxB,IAAU,IACN,GACA,EAAM,aAAa,GAAK,QACtB,EAAM,aAAa,GAAK,KACxB,EAAM,aAAa,GAAK,OACxB,IAAU,IACV,GACA,EACP,CAEU,EAAe,EAAE,OAAO,CACnC,MAAO,EAAc,QAAQ,QAAQ,CACrC,SAAU,EAAc,QAAQ,OAAO,CACvC,eAAgB,EAAc,QAAQ,QAAQ,CAC9C,WAAY,EAAc,QAAQ,QAAQ,CAC1C,YAAa,EAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,aAAa,CACpD,YAAa,EAAc,QAAQ,OAAO,CAC1C,yBAA0B,EAAc,QAAQ,QAAQ,CACxD,qBAAsB,EACnB,QAAQ,CACR,QAAQ,OAAO,OAAO,EAAY,CAAC,KAAK,IAAI,CAAC,CAC7C,UAAU,GACF,EAAI,MAAM,IAAI,CAAC,IAAI,GAAU,EAAgB,MAAM,EAAO,MAAM,CAAC,CAAC,CACzE,CAGJ,QAAS,EAAc,QAAQ,OAAO,CACtC,cAAe,EAAc,QAAQ,OAAO,CAAC,GAAG,EAAE,QAAQ,UAAU,CAAC,CACrE,YAAa,EAAE,QAAQ,CAAC,QAAQ,SAAS,CACzC,UAAW,EAAE,KAAK,CAAC,aAAc,YAAY,CAAC,CAAC,QAAQ,YAAY,CACnE,aAAc,EAAc,QAAQ,OAAO,CAC3C,QAAS,EAAE,QAAQ,CAAC,UAAU,CAC9B,sBAAuB,EAAc,QAAQ,OAAO,CACrD,CAAC"}
|
package/dist/generator.d.cts
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import "./index.cjs";
|
|
1
|
+
export { };
|
package/dist/generator.d.mts
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import "./index.mjs";
|
|
1
|
+
export { };
|
package/dist/helpers.cjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
const e=require(`./_virtual/rolldown_runtime.cjs`),t=require(`./packages/string-format/src/lower-case-first.cjs`),n=require(`./project.cjs`);require(`./utils/get-prisma-internals.cjs`);const r=require(`./zod/model-helpers.cjs`);let i=require(`@stryke/path/join-paths`),a=require(`@stryke/path/file-path-fns`);const o=e=>e.withShield?`shieldedProcedure`:e.withMiddleware?`protectedProcedure`:`publicProcedure`,s=({sourceFile:e,config:t})=>{let n=[`t`];t&&n.push(o(t)),e.addImportDeclaration({moduleSpecifier:`../trpc`,namedImports:n})},c=(e,n,r)=>{e.addImportDeclaration({moduleSpecifier:`./${t.lowerCaseFirst(r)}.router`,namedImports:[`${n}Router`]})};async function l(e,t,n,r){t.withShield&&e.addImportDeclaration({moduleSpecifier:(0,a.relativePath)(r,(0,i.joinPaths)(r,typeof t.withShield==`string`?t.withShield:`shield`)),namedImports:[`permissions`]}),e.addStatements(`import type { Context } from '${(0,a.relativePath)(r,(0,i.joinPaths)(r,t.contextPath))}';`),t.trpcOptions&&e.addStatements(`import trpcOptions from '${typeof t.trpcOptions==`string`?(0,a.relativePath)(r,(0,i.joinPaths)(r,t.trpcOptions)):`./options`}';`),t.withNext&&e.addStatements(`import { createContext } from '${(0,a.relativePath)(r,(0,i.joinPaths)(r,t.contextPath))}';
|
|
2
|
+
import { initTRPC } from '@trpc/server';
|
|
3
|
+
import { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';
|
|
4
|
+
import { cookies } from "next/headers";`),e.addStatements(`
|
|
5
|
+
export const t = initTRPC.context<Context>().create(${t.trpcOptions?`trpcOptions`:``});`);let s=[];if(t.withMiddleware&&typeof t.withMiddleware==`boolean`&&(e.addStatements(`
|
|
6
|
+
export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
|
|
7
|
+
console.log('inside middleware!')
|
|
8
|
+
return next()
|
|
9
|
+
});`),s.push({type:`global`,value:`.use(globalMiddleware)`})),t.withMiddleware&&typeof t.withMiddleware==`string`&&(e.addStatements(`
|
|
10
|
+
import middleware from '${(0,a.relativePath)(r,(0,i.joinPaths)(r,typeof t.withMiddleware==`string`?t.withMiddleware:`middleware`))}';
|
|
11
|
+
`),e.addStatements(`
|
|
12
|
+
export const globalMiddleware = t.middleware(middleware);`),s.push({type:`global`,value:`.use(globalMiddleware)`})),t.withShield&&(e.addStatements(`
|
|
13
|
+
export const permissionsMiddleware = t.middleware(permissions);
|
|
14
|
+
`),s.push({type:`shield`,value:`
|
|
15
|
+
.use(permissions)`})),e.addStatements(`
|
|
16
|
+
/**
|
|
17
|
+
* Create a server-side caller
|
|
18
|
+
* @see https://trpc.io/docs/server/server-side-calls
|
|
19
|
+
*/
|
|
20
|
+
export const createCallerFactory = t.createCallerFactory;`),e.addStatements(`
|
|
21
|
+
export const publicProcedure = t.procedure; `),s.length>0){let n=o(t);s.forEach((t,r)=>{r===0&&e.addStatements(`
|
|
22
|
+
export const ${n} = t.procedure`),e.addStatements(`.use(${t.type===`shield`?`permissionsMiddleware`:`globalMiddleware`})`)})}t.withNext&&e.addStatements(`
|
|
23
|
+
export const createAction: ReturnType<typeof createTRPCServerActionHandler> =
|
|
24
|
+
createTRPCServerActionHandler(cookies, t, createContext);
|
|
25
|
+
`),e.formatText({indentSize:2})}function u(e,n,r,i,a,s,c){let l=`input${c.withZod?``:` as any`}`,u=n.replace(i,``);u===`groupBy`&&c.withZod&&(l=`{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }`),e.addStatements(`${c.showModelNameInProcedure?n:u}: ${o(c)}
|
|
26
|
+
${c.withZod?`.input(${t.lowerCaseFirst(r)})`:``}.${m(s)}(async ({ ctx, input }) => {
|
|
27
|
+
const ${n} = await ctx.prisma.${t.lowerCaseFirst(i)}.${a.replace(`One`,``)}(${l});
|
|
28
|
+
return ${n};
|
|
29
|
+
}),`)}function d(e,t,n){e.addStatements([...new Set(n.map(e=>f(e,t)))].join(`
|
|
30
|
+
`))}const f=(e,n)=>{let r=e.replace(`OrThrow`,``).replace(`ManyAndReturn`,``),i=p(r,n);return i?`import { ${t.lowerCaseFirst(i)} } from "../schemas/${t.lowerCaseFirst(r)}${n}.schema"; `:``},p=(e,t)=>{let n;switch(e){case`findUnique`:n=`${t}FindUniqueSchema`;break;case`findFirst`:n=`${t}FindFirstSchema`;break;case`findMany`:n=`${t}FindManySchema`;break;case`findRaw`:n=`${t}FindRawObjectSchema`;break;case`createOne`:n=`${t}CreateOneSchema`;break;case`createMany`:n=`${t}CreateManySchema`;break;case`createManyAndReturn`:n=`${t}CreateManySchema`;break;case`deleteOne`:n=`${t}DeleteOneSchema`;break;case`deleteMany`:n=`${t}DeleteManySchema`;break;case`updateOne`:n=`${t}UpdateOneSchema`;break;case`updateMany`:n=`${t}UpdateManySchema`;break;case`updateManyAndReturn`:n=`${t}UpdateManySchema`;break;case`upsertOne`:n=`${t}UpsertSchema`;break;case`aggregate`:n=`${t}AggregateSchema`;break;case`aggregateRaw`:n=`${t}AggregateRawObjectSchema`;break;case`groupBy`:n=`${t}GroupBySchema`;break;default:console.log(`getInputTypeByOpName: `,{opName:e,modelName:t})}return n},m=e=>{let t;switch(e){case`findUnique`:case`findFirst`:case`findMany`:case`findRaw`:case`aggregate`:case`aggregateRaw`:case`groupBy`:t=`query`;break;case`createOne`:case`createMany`:case`createManyAndReturn`:case`deleteOne`:case`updateOne`:case`deleteMany`:case`updateMany`:case`updateManyAndReturn`:case`upsertOne`:t=`mutation`;break;default:console.log(`getProcedureTypeByOpName: `,{opName:e})}return t};function h(e,t){let n=/(?:@@Gen\.)+[A-z]+\(.+\)/,r=/\.+[A-Z]+\(+/i,i=/\(+[A-Z]+:.+\)/i;for(let a of e)if(a.documentation){let e=a.documentation?.match(n)?.[0];if(e?.match(r)?.[0]?.slice(1,-1)!==`model`)continue;let o=e?.match(i)?.[0]?.slice(1,-1),s={};if(o){let e=o.split(`:`).map(e=>e.trim()).map(e=>e.startsWith(`[`)?e:e.split(`,`)).flat().map(e=>e.trim());for(let t=0;t<e.length;t+=2){let n=e[t],r=e[t+1];s[n]=JSON.parse(r)}}s.hide&&t.push(a.name)}}const g=(e,t)=>{let n=``;return e===`trpc`?n=`import * as trpc from '@trpc/server';
|
|
31
|
+
`:e===`trpc-shield`?n=`import { shield, allow } from '@stryke/trpc-next/shield';
|
|
32
|
+
`:e===`context`&&(n=`import type { Context } from '${t}';\n`),n},_=({shieldItemLines:e})=>{let t=`{`;return t+=`
|
|
33
|
+
`,t+=Array.isArray(e)?` ${e.join(`,\r
|
|
34
|
+
`)}`:` ${e}`,t+=`
|
|
35
|
+
`,t+=`}`,t},v=({shieldObjectTextWrapped:e})=>{let t=`shield<Context>(`;return t+=`
|
|
36
|
+
`,t+=` ${e}`,t+=`
|
|
37
|
+
`,t+=`)`,t},y=({shieldObjectText:e})=>`export const permissions: ReturnType<typeof shield<Context>> = ${e};`,b=async({queries:e,mutations:t,subscriptions:n},r,o,s)=>{if(e.length===0&&t.length===0&&n.length===0)return``;let c=``;if(e.length>0){let t=`query: ${_({shieldItemLines:e.map(e=>`${e}: allow`)})},`;c+=t}if(t.length>0){let e=`mutation: ${_({shieldItemLines:t.map(e=>`${e}: allow`)})},`;c+=e}if(n.length>0){let e=`subscription: ${_({shieldItemLines:n.map(e=>`${e}: allow`)})},`;c+=e}if(c.length===0)return``;let l=g(`trpc-shield`);return l+=g(`context`,(0,a.relativePath)(s,(0,i.joinPaths)(s,r.contextPath))),l+=`
|
|
38
|
+
|
|
39
|
+
`,l+=y({shieldObjectText:v({shieldObjectTextWrapped:_({shieldItemLines:c})})}),l},x=(e,t,n)=>`import { ZodError } from 'zod';${e.withNext?`
|
|
40
|
+
import { transformer } from "@stryke/trpc-next/shared";`:``}
|
|
41
|
+
import type {
|
|
42
|
+
DataTransformerOptions,
|
|
43
|
+
RootConfig
|
|
44
|
+
} from "@trpc/server/unstable-core-do-not-import";
|
|
45
|
+
import type { Context } from "${(0,a.relativePath)(n,(0,i.joinPaths)(n,e.contextPath))}";
|
|
46
|
+
|
|
47
|
+
interface RuntimeConfigOptions<
|
|
48
|
+
TContext extends object,
|
|
49
|
+
TMeta extends object = object
|
|
50
|
+
> extends Partial<
|
|
51
|
+
Omit<
|
|
52
|
+
RootConfig<{
|
|
53
|
+
ctx: TContext;
|
|
54
|
+
meta: TMeta;
|
|
55
|
+
errorShape: any;
|
|
56
|
+
transformer: any;
|
|
57
|
+
}>,
|
|
58
|
+
"$types" | "transformer"
|
|
59
|
+
>
|
|
60
|
+
> {
|
|
61
|
+
/**
|
|
62
|
+
* Use a data transformer
|
|
63
|
+
* @see https://trpc.io/docs/v11/data-transformers
|
|
64
|
+
*/
|
|
65
|
+
transformer?: DataTransformerOptions;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const options: RuntimeConfigOptions<Context> = {${e.withNext?`
|
|
69
|
+
transformer,`:``}
|
|
70
|
+
errorFormatter({ shape, error }) {
|
|
71
|
+
return {
|
|
72
|
+
...shape,
|
|
73
|
+
data: {
|
|
74
|
+
...shape.data,
|
|
75
|
+
zodError:
|
|
76
|
+
error.code === "BAD_REQUEST" && error.cause instanceof ZodError
|
|
77
|
+
? error.cause.flatten()
|
|
78
|
+
: null
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export default options;
|
|
85
|
+
`,S=async(e,i,a,o)=>{let s=n.project.createSourceFile(`${i}/index.ts`,{},{overwrite:!0});r.generateBarrelFile(e,s),s.formatText({indentSize:2}),await Promise.all(e.map(async e=>{let s=n.project.createSourceFile(`${i}/${t.lowerCaseFirst(e.name)}.schema.ts`,{},{overwrite:!0});await r.populateModelFile(e,s,a,o),s.formatText({indentSize:2})}))};exports.constructDefaultOptions=x,exports.constructShield=b,exports.constructZodModels=S,exports.generateCreateRouterImport=s,exports.generateProcedure=u,exports.generateRouterImport=c,exports.generateRouterSchemaImports=d,exports.generateTRPCExports=l,exports.getInputTypeByOpName=p,exports.resolveModelsComments=h;
|
package/dist/helpers.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import{lowerCaseFirst as e}from"./packages/string-format/src/lower-case-first.mjs";import{project as t}from"./project.mjs";import"./utils/get-prisma-internals.mjs";import{generateBarrelFile as n,populateModelFile as r}from"./zod/model-helpers.mjs";import{joinPaths as i}from"@stryke/path/join-paths";import{relativePath as a}from"@stryke/path/file-path-fns";const o=e=>e.withShield?`shieldedProcedure`:e.withMiddleware?`protectedProcedure`:`publicProcedure`,s=({sourceFile:e,config:t})=>{let n=[`t`];t&&n.push(o(t)),e.addImportDeclaration({moduleSpecifier:`../trpc`,namedImports:n})},c=(t,n,r)=>{t.addImportDeclaration({moduleSpecifier:`./${e(r)}.router`,namedImports:[`${n}Router`]})};async function l(e,t,n,r){t.withShield&&e.addImportDeclaration({moduleSpecifier:a(r,i(r,typeof t.withShield==`string`?t.withShield:`shield`)),namedImports:[`permissions`]}),e.addStatements(`import type { Context } from '${a(r,i(r,t.contextPath))}';`),t.trpcOptions&&e.addStatements(`import trpcOptions from '${typeof t.trpcOptions==`string`?a(r,i(r,t.trpcOptions)):`./options`}';`),t.withNext&&e.addStatements(`import { createContext } from '${a(r,i(r,t.contextPath))}';
|
|
2
|
+
import { initTRPC } from '@trpc/server';
|
|
3
|
+
import { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';
|
|
4
|
+
import { cookies } from "next/headers";`),e.addStatements(`
|
|
5
|
+
export const t = initTRPC.context<Context>().create(${t.trpcOptions?`trpcOptions`:``});`);let s=[];if(t.withMiddleware&&typeof t.withMiddleware==`boolean`&&(e.addStatements(`
|
|
6
|
+
export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
|
|
7
|
+
console.log('inside middleware!')
|
|
8
|
+
return next()
|
|
9
|
+
});`),s.push({type:`global`,value:`.use(globalMiddleware)`})),t.withMiddleware&&typeof t.withMiddleware==`string`&&(e.addStatements(`
|
|
10
|
+
import middleware from '${a(r,i(r,typeof t.withMiddleware==`string`?t.withMiddleware:`middleware`))}';
|
|
11
|
+
`),e.addStatements(`
|
|
12
|
+
export const globalMiddleware = t.middleware(middleware);`),s.push({type:`global`,value:`.use(globalMiddleware)`})),t.withShield&&(e.addStatements(`
|
|
13
|
+
export const permissionsMiddleware = t.middleware(permissions);
|
|
14
|
+
`),s.push({type:`shield`,value:`
|
|
15
|
+
.use(permissions)`})),e.addStatements(`
|
|
16
|
+
/**
|
|
17
|
+
* Create a server-side caller
|
|
18
|
+
* @see https://trpc.io/docs/server/server-side-calls
|
|
19
|
+
*/
|
|
20
|
+
export const createCallerFactory = t.createCallerFactory;`),e.addStatements(`
|
|
21
|
+
export const publicProcedure = t.procedure; `),s.length>0){let n=o(t);s.forEach((t,r)=>{r===0&&e.addStatements(`
|
|
22
|
+
export const ${n} = t.procedure`),e.addStatements(`.use(${t.type===`shield`?`permissionsMiddleware`:`globalMiddleware`})`)})}t.withNext&&e.addStatements(`
|
|
23
|
+
export const createAction: ReturnType<typeof createTRPCServerActionHandler> =
|
|
24
|
+
createTRPCServerActionHandler(cookies, t, createContext);
|
|
25
|
+
`),e.formatText({indentSize:2})}function u(t,n,r,i,a,s,c){let l=`input${c.withZod?``:` as any`}`,u=n.replace(i,``);u===`groupBy`&&c.withZod&&(l=`{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }`),t.addStatements(`${c.showModelNameInProcedure?n:u}: ${o(c)}
|
|
26
|
+
${c.withZod?`.input(${e(r)})`:``}.${m(s)}(async ({ ctx, input }) => {
|
|
27
|
+
const ${n} = await ctx.prisma.${e(i)}.${a.replace(`One`,``)}(${l});
|
|
28
|
+
return ${n};
|
|
29
|
+
}),`)}function d(e,t,n){e.addStatements([...new Set(n.map(e=>f(e,t)))].join(`
|
|
30
|
+
`))}const f=(t,n)=>{let r=t.replace(`OrThrow`,``).replace(`ManyAndReturn`,``),i=p(r,n);return i?`import { ${e(i)} } from "../schemas/${e(r)}${n}.schema"; `:``},p=(e,t)=>{let n;switch(e){case`findUnique`:n=`${t}FindUniqueSchema`;break;case`findFirst`:n=`${t}FindFirstSchema`;break;case`findMany`:n=`${t}FindManySchema`;break;case`findRaw`:n=`${t}FindRawObjectSchema`;break;case`createOne`:n=`${t}CreateOneSchema`;break;case`createMany`:n=`${t}CreateManySchema`;break;case`createManyAndReturn`:n=`${t}CreateManySchema`;break;case`deleteOne`:n=`${t}DeleteOneSchema`;break;case`deleteMany`:n=`${t}DeleteManySchema`;break;case`updateOne`:n=`${t}UpdateOneSchema`;break;case`updateMany`:n=`${t}UpdateManySchema`;break;case`updateManyAndReturn`:n=`${t}UpdateManySchema`;break;case`upsertOne`:n=`${t}UpsertSchema`;break;case`aggregate`:n=`${t}AggregateSchema`;break;case`aggregateRaw`:n=`${t}AggregateRawObjectSchema`;break;case`groupBy`:n=`${t}GroupBySchema`;break;default:console.log(`getInputTypeByOpName: `,{opName:e,modelName:t})}return n},m=e=>{let t;switch(e){case`findUnique`:case`findFirst`:case`findMany`:case`findRaw`:case`aggregate`:case`aggregateRaw`:case`groupBy`:t=`query`;break;case`createOne`:case`createMany`:case`createManyAndReturn`:case`deleteOne`:case`updateOne`:case`deleteMany`:case`updateMany`:case`updateManyAndReturn`:case`upsertOne`:t=`mutation`;break;default:console.log(`getProcedureTypeByOpName: `,{opName:e})}return t};function h(e,t){let n=/(?:@@Gen\.)+[A-z]+\(.+\)/,r=/\.+[A-Z]+\(+/i,i=/\(+[A-Z]+:.+\)/i;for(let a of e)if(a.documentation){let e=a.documentation?.match(n)?.[0];if(e?.match(r)?.[0]?.slice(1,-1)!==`model`)continue;let o=e?.match(i)?.[0]?.slice(1,-1),s={};if(o){let e=o.split(`:`).map(e=>e.trim()).map(e=>e.startsWith(`[`)?e:e.split(`,`)).flat().map(e=>e.trim());for(let t=0;t<e.length;t+=2){let n=e[t],r=e[t+1];s[n]=JSON.parse(r)}}s.hide&&t.push(a.name)}}const g=(e,t)=>{let n=``;return e===`trpc`?n=`import * as trpc from '@trpc/server';
|
|
31
|
+
`:e===`trpc-shield`?n=`import { shield, allow } from '@stryke/trpc-next/shield';
|
|
32
|
+
`:e===`context`&&(n=`import type { Context } from '${t}';\n`),n},_=({shieldItemLines:e})=>{let t=`{`;return t+=`
|
|
33
|
+
`,t+=Array.isArray(e)?` ${e.join(`,\r
|
|
34
|
+
`)}`:` ${e}`,t+=`
|
|
35
|
+
`,t+=`}`,t},v=({shieldObjectTextWrapped:e})=>{let t=`shield<Context>(`;return t+=`
|
|
36
|
+
`,t+=` ${e}`,t+=`
|
|
37
|
+
`,t+=`)`,t},y=({shieldObjectText:e})=>`export const permissions: ReturnType<typeof shield<Context>> = ${e};`,b=async({queries:e,mutations:t,subscriptions:n},r,o,s)=>{if(e.length===0&&t.length===0&&n.length===0)return``;let c=``;if(e.length>0){let t=`query: ${_({shieldItemLines:e.map(e=>`${e}: allow`)})},`;c+=t}if(t.length>0){let e=`mutation: ${_({shieldItemLines:t.map(e=>`${e}: allow`)})},`;c+=e}if(n.length>0){let e=`subscription: ${_({shieldItemLines:n.map(e=>`${e}: allow`)})},`;c+=e}if(c.length===0)return``;let l=g(`trpc-shield`);return l+=g(`context`,a(s,i(s,r.contextPath))),l+=`
|
|
38
|
+
|
|
39
|
+
`,l+=y({shieldObjectText:v({shieldObjectTextWrapped:_({shieldItemLines:c})})}),l},x=(e,t,n)=>`import { ZodError } from 'zod';${e.withNext?`
|
|
40
|
+
import { transformer } from "@stryke/trpc-next/shared";`:``}
|
|
41
|
+
import type {
|
|
42
|
+
DataTransformerOptions,
|
|
43
|
+
RootConfig
|
|
44
|
+
} from "@trpc/server/unstable-core-do-not-import";
|
|
45
|
+
import type { Context } from "${a(n,i(n,e.contextPath))}";
|
|
46
|
+
|
|
47
|
+
interface RuntimeConfigOptions<
|
|
48
|
+
TContext extends object,
|
|
49
|
+
TMeta extends object = object
|
|
50
|
+
> extends Partial<
|
|
51
|
+
Omit<
|
|
52
|
+
RootConfig<{
|
|
53
|
+
ctx: TContext;
|
|
54
|
+
meta: TMeta;
|
|
55
|
+
errorShape: any;
|
|
56
|
+
transformer: any;
|
|
57
|
+
}>,
|
|
58
|
+
"$types" | "transformer"
|
|
59
|
+
>
|
|
60
|
+
> {
|
|
61
|
+
/**
|
|
62
|
+
* Use a data transformer
|
|
63
|
+
* @see https://trpc.io/docs/v11/data-transformers
|
|
64
|
+
*/
|
|
65
|
+
transformer?: DataTransformerOptions;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const options: RuntimeConfigOptions<Context> = {${e.withNext?`
|
|
69
|
+
transformer,`:``}
|
|
70
|
+
errorFormatter({ shape, error }) {
|
|
71
|
+
return {
|
|
72
|
+
...shape,
|
|
73
|
+
data: {
|
|
74
|
+
...shape.data,
|
|
75
|
+
zodError:
|
|
76
|
+
error.code === "BAD_REQUEST" && error.cause instanceof ZodError
|
|
77
|
+
? error.cause.flatten()
|
|
78
|
+
: null
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export default options;
|
|
85
|
+
`,S=async(i,a,o,s)=>{let c=t.createSourceFile(`${a}/index.ts`,{},{overwrite:!0});n(i,c),c.formatText({indentSize:2}),await Promise.all(i.map(async n=>{let i=t.createSourceFile(`${a}/${e(n.name)}.schema.ts`,{},{overwrite:!0});await r(n,i,o,s),i.formatText({indentSize:2})}))};export{x as constructDefaultOptions,b as constructShield,S as constructZodModels,s as generateCreateRouterImport,u as generateProcedure,c as generateRouterImport,d as generateRouterSchemaImports,l as generateTRPCExports,p as getInputTypeByOpName,h as resolveModelsComments};
|
|
86
|
+
//# sourceMappingURL=helpers.mjs.map
|
|
@@ -0,0 +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":"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"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,116 +1 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`@stryke/fs/exists`),u=require(`@stryke/fs/helpers`),d=require(`@stryke/path/join-paths`),f=require(`node:path`);f=c(f);let p=require(`zod`),m=require(`@stryke/path/file-path-fns`),h=require(`ts-morph`),g=require(`node:os`);g=c(g);let _=require(`@stryke/fs/get-workspace-root`),v=require(`jiti`),y=require(`parenthesis`);y=c(y);let b=require(`@stryke/fs/write-file`),x=require(`@stryke/path/correct-path`),S=require(`prettier`);S=c(S);function C(e){return e&&e.charAt(0).toLowerCase()+e.slice(1)}var w=o(((e,t)=>{(function(n,r){typeof require==`function`&&typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define(function(){return r()}):n.pluralize=r()})(e,function(){var e=[],t=[],n={},r={},i={};function a(e){return typeof e==`string`?RegExp(`^`+e+`$`,`i`):e}function o(e,t){return e===t?t:e===e.toLowerCase()?t.toLowerCase():e===e.toUpperCase()?t.toUpperCase():e[0]===e[0].toUpperCase()?t.charAt(0).toUpperCase()+t.substr(1).toLowerCase():t.toLowerCase()}function s(e,t){return e.replace(/\$(\d{1,2})/g,function(e,n){return t[n]||``})}function c(e,t){return e.replace(t[0],function(n,r){var i=s(t[1],arguments);return o(n===``?e[r-1]:n,i)})}function l(e,t,r){if(!e.length||n.hasOwnProperty(e))return t;for(var i=r.length;i--;){var a=r[i];if(a[0].test(t))return c(t,a)}return t}function u(e,t,n){return function(r){var i=r.toLowerCase();return t.hasOwnProperty(i)?o(r,i):e.hasOwnProperty(i)?o(r,e[i]):l(i,r,n)}}function d(e,t,n,r){return function(r){var i=r.toLowerCase();return t.hasOwnProperty(i)?!0:e.hasOwnProperty(i)?!1:l(i,i,n)===i}}function f(e,t,n){var r=t===1?f.singular(e):f.plural(e);return(n?t+` `:``)+r}return f.plural=u(i,r,e),f.isPlural=d(i,r,e),f.singular=u(r,i,t),f.isSingular=d(r,i,t),f.addPluralRule=function(t,n){e.push([a(t),n])},f.addSingularRule=function(e,n){t.push([a(e),n])},f.addUncountableRule=function(e){if(typeof e==`string`){n[e.toLowerCase()]=!0;return}f.addPluralRule(e,`$0`),f.addSingularRule(e,`$0`)},f.addIrregularRule=function(e,t){t=t.toLowerCase(),e=e.toLowerCase(),i[e]=t,r[t]=e},[[`I`,`we`],[`me`,`us`],[`he`,`they`],[`she`,`they`],[`them`,`them`],[`myself`,`ourselves`],[`yourself`,`yourselves`],[`itself`,`themselves`],[`herself`,`themselves`],[`himself`,`themselves`],[`themself`,`themselves`],[`is`,`are`],[`was`,`were`],[`has`,`have`],[`this`,`these`],[`that`,`those`],[`echo`,`echoes`],[`dingo`,`dingoes`],[`volcano`,`volcanoes`],[`tornado`,`tornadoes`],[`torpedo`,`torpedoes`],[`genus`,`genera`],[`viscus`,`viscera`],[`stigma`,`stigmata`],[`stoma`,`stomata`],[`dogma`,`dogmata`],[`lemma`,`lemmata`],[`schema`,`schemata`],[`anathema`,`anathemata`],[`ox`,`oxen`],[`axe`,`axes`],[`die`,`dice`],[`yes`,`yeses`],[`foot`,`feet`],[`eave`,`eaves`],[`goose`,`geese`],[`tooth`,`teeth`],[`quiz`,`quizzes`],[`human`,`humans`],[`proof`,`proofs`],[`carve`,`carves`],[`valve`,`valves`],[`looey`,`looies`],[`thief`,`thieves`],[`groove`,`grooves`],[`pickaxe`,`pickaxes`],[`passerby`,`passersby`]].forEach(function(e){return f.addIrregularRule(e[0],e[1])}),[[/s?$/i,`s`],[/[^\u0000-\u007F]$/i,`$0`],[/([^aeiou]ese)$/i,`$1`],[/(ax|test)is$/i,`$1es`],[/(alias|[^aou]us|t[lm]as|gas|ris)$/i,`$1es`],[/(e[mn]u)s?$/i,`$1s`],[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i,`$1`],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,`$1i`],[/(alumn|alg|vertebr)(?:a|ae)$/i,`$1ae`],[/(seraph|cherub)(?:im)?$/i,`$1im`],[/(her|at|gr)o$/i,`$1oes`],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,`$1a`],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i,`$1a`],[/sis$/i,`ses`],[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i,`$1$2ves`],[/([^aeiouy]|qu)y$/i,`$1ies`],[/([^ch][ieo][ln])ey$/i,`$1ies`],[/(x|ch|ss|sh|zz)$/i,`$1es`],[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i,`$1ices`],[/\b((?:tit)?m|l)(?:ice|ouse)$/i,`$1ice`],[/(pe)(?:rson|ople)$/i,`$1ople`],[/(child)(?:ren)?$/i,`$1ren`],[/eaux$/i,`$0`],[/m[ae]n$/i,`men`],[`thou`,`you`]].forEach(function(e){return f.addPluralRule(e[0],e[1])}),[[/s$/i,``],[/(ss)$/i,`$1`],[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i,`$1fe`],[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i,`$1f`],[/ies$/i,`y`],[/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i,`$1ie`],[/\b(mon|smil)ies$/i,`$1ey`],[/\b((?:tit)?m|l)ice$/i,`$1ouse`],[/(seraph|cherub)im$/i,`$1`],[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i,`$1`],[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i,`$1sis`],[/(movie|twelve|abuse|e[mn]u)s$/i,`$1`],[/(test)(?:is|es)$/i,`$1is`],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,`$1us`],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i,`$1um`],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i,`$1on`],[/(alumn|alg|vertebr)ae$/i,`$1a`],[/(cod|mur|sil|vert|ind)ices$/i,`$1ex`],[/(matr|append)ices$/i,`$1ix`],[/(pe)(rson|ople)$/i,`$1rson`],[/(child)ren$/i,`$1`],[/(eau)x?$/i,`$1`],[/men$/i,`man`]].forEach(function(e){return f.addSingularRule(e[0],e[1])}),[`adulthood`,`advice`,`agenda`,`aid`,`aircraft`,`alcohol`,`ammo`,`analytics`,`anime`,`athletics`,`audio`,`bison`,`blood`,`bream`,`buffalo`,`butter`,`carp`,`cash`,`chassis`,`chess`,`clothing`,`cod`,`commerce`,`cooperation`,`corps`,`debris`,`diabetes`,`digestion`,`elk`,`energy`,`equipment`,`excretion`,`expertise`,`firmware`,`flounder`,`fun`,`gallows`,`garbage`,`graffiti`,`hardware`,`headquarters`,`health`,`herpes`,`highjinks`,`homework`,`housework`,`information`,`jeans`,`justice`,`kudos`,`labour`,`literature`,`machinery`,`mackerel`,`mail`,`media`,`mews`,`moose`,`music`,`mud`,`manga`,`news`,`only`,`personnel`,`pike`,`plankton`,`pliers`,`police`,`pollution`,`premises`,`rain`,`research`,`rice`,`salmon`,`scissors`,`series`,`sewage`,`shambles`,`shrimp`,`software`,`species`,`staff`,`swine`,`tennis`,`traffic`,`transportation`,`trout`,`tuna`,`wealth`,`welfare`,`whiting`,`wildebeest`,`wildlife`,`you`,/pok[eé]mon$/i,/[^aeiou]ese$/i,/deer$/i,/fish$/i,/measles$/i,/o[iu]s$/i,/pox$/i,/sheep$/i].forEach(f.addUncountableRule),f})})),ee=c(w(),1);let T=function(e){return e.findUnique=`findUnique`,e.findUniqueOrThrow=`findUniqueOrThrow`,e.findFirst=`findFirst`,e.findFirstOrThrow=`findFirstOrThrow`,e.findMany=`findMany`,e.create=`create`,e.createMany=`createMany`,e.createManyAndReturn=`createManyAndReturn`,e.update=`update`,e.updateMany=`updateMany`,e.updateManyAndReturn=`updateManyAndReturn`,e.upsert=`upsert`,e.delete=`delete`,e.deleteMany=`deleteMany`,e.groupBy=`groupBy`,e.count=`count`,e.aggregate=`aggregate`,e.findRaw=`findRaw`,e.aggregateRaw=`aggregateRaw`,e}({});const E=p.z.nativeEnum(T),D=p.z.string().trim().transform(e=>!e||e.toLowerCase()===`false`||e.toLowerCase()===`n`||e.toLowerCase()===`no`||e===`0`?!1:e.toLowerCase()===`true`||e.toLowerCase()===`y`||e.toLowerCase()===`yes`||e===`1`?!0:e),te=p.z.object({debug:D.default(`false`),withNext:D.default(`true`),withMiddleware:D.default(`false`),withShield:D.default(`false`),contextPath:p.z.string().trim().default(`../context`),trpcOptions:D.default(`true`),showModelNameInProcedure:D.default(`false`),generateModelActions:p.z.string().default(Object.values(T).join(`,`)).transform(e=>e.split(`,`).map(e=>E.parse(e.trim()))),withZod:D.default(`true`),relationModel:D.default(`true`).or(p.z.literal(`default`)),modelSuffix:p.z.string().default(`Schema`),modelCase:p.z.enum([`PascalCase`,`camelCase`]).default(`camelCase`),useDecimalJs:D.default(`true`),imports:p.z.string().optional(),prismaJsonNullability:D.default(`true`)}),ne={target:h.ScriptTarget.ESNext,module:h.ModuleKind.ESNext,emitDecoratorMetadata:!0,experimentalDecorators:!0,esModuleInterop:!0},O=new h.Project({compilerOptions:{...ne}});function re(e,t){return`${e} ${t}`}function ie(e){return e.replace(/([a-z\d])([A-Z])/g,`$1_$2`).replace(/([A-Z]+)([A-Z][a-z\d]+)/g,`$1_$2`).toLowerCase()}const k={"2D":{description:`Two-Dimensional`,display:`2d`},"3D":{description:`Three-Dimensional`,display:`3d`},"4D":{description:`Four-Dimensional`,display:`4d`},"5G":{description:`Fifth Generation (mobile networks)`},"6G":{description:`Sixth Generation (mobile networks)`},"7G":{description:`Seventh Generation (mobile networks)`},"8G":{description:`Eighth Generation (mobile networks)`},ACID:{description:`Atomicity, Consistency, Isolation, Durability`},AITA:{description:`Am I The Asshole`},AES:{description:`Advanced Encryption Standard`},AI:{description:`Artificial Intelligence`},AJAX:{description:`Asynchronous JavaScript and XML`},API:{description:`Application Programming Interface`},AR:{description:`Augmented Reality`},ASCII:{description:`American Standard Code for Information Interchange`},ATF:{description:`Bureau of Alcohol, Tobacco, Firearms and Explosives`},ATM:{description:`Automated Teller Machine`},B2B:{description:`Business to Business`},B2C:{description:`Business to Consumer`},BATFE:{description:`Bureau of Alcohol, Tobacco, Firearms and Explosives`},BFF:{description:`Best Friends Forever`},BFFS:{description:`Best Friends Forever (plural)`},BI:{description:`Business Intelligence`},BIOS:{description:`Basic Input/Output System`},BGP:{description:`Border Gateway Protocol`},BOM:{description:`Bill of Materials / Byte Order Mark`},BSON:{description:`Binary JSON`},BYOD:{description:`Bring Your Own Device`},C2C:{description:`Consumer to Consumer`},CAGR:{description:`Compound Annual Growth Rate`},CAPTCHA:{description:`Completely Automated Public Turing test to tell Computers and Humans Apart`},CCTV:{description:`Closed-Circuit Television`},CD:{description:`Continuous Delivery / Compact Disc`},CDN:{description:`Content Delivery Network`},CDP:{description:`Customer Data Platform`},CDT:{description:`Central Daylight Time`},CIA:{description:`Central Intelligence Agency`},CI:{description:`Continuous Integration`},"CI/CD":{description:`Continuous Integration/Continuous Delivery`},CIAM:{description:`Customer Identity and Access Management`},CICD:{description:`Continuous Integration Continuous Delivery`,display:`CI/CD`},CLI:{description:`Command Line Interface`},CMDB:{description:`Configuration Management Database`},CORS:{description:`Cross-Origin Resource Sharing`},CPA:{description:`Certified Public Accountant`},CPU:{description:`Central Processing Unit`},CRUD:{description:`Create, Read, Update, Delete`},CSR:{description:`Certificate Signing Request / Corporate Social Responsibility`},CSS:{description:`Cascading Style Sheets`},CST:{description:`Central Standard Time`},CTA:{description:`Call To Action`},CWD:{description:`Current Working Directory`},CX:{description:`Customer Experience`},DAG:{description:`Directed Acyclic Graph`},DBMS:{description:`Database Management System`},DDOS:{description:`Distributed Denial of Service`,display:`DDoS`},DEA:{description:`Drug Enforcement Administration`},DEVENV:{description:`Devenv`,display:`Devenv`},DEVOPS:{description:`Development Operations`,display:`DevOps`},DHS:{description:`Department of Homeland Security`},DIRENV:{description:`DirEnv`,display:`DirEnv`},DNC:{description:`Democratic National Committee / Do Not Call`},DNS:{description:`Domain Name System`},DNSSEC:{description:`Domain Name System Security Extensions`},DOD:{description:`Department of Defense`,display:`DoD`},DOJ:{description:`Department of Justice`,display:`DoJ`},DOM:{description:`Document Object Model`},DOT:{description:`Department of Transportation`,display:`DoT`},DOTENV:{description:`Dotenv (.env)`,display:`Dotenv`},DR:{description:`Disaster Recovery`},DRM:{description:`Digital Rights Management`},DSN:{description:`Data Source Name`},DWH:{description:`Data Warehouse`},E2E:{description:`End to End`},EAI:{description:`Enterprise Application Integration`},EDT:{description:`Eastern Daylight Time`},EEA:{description:`European Economic Area`},EKS:{description:`Elastic Kubernetes Service`},EOF:{description:`End Of File`},EOD:{description:`End Of Day / Explosive Ordnance Disposal`},EPA:{description:`Environmental Protection Agency`},ER:{description:`Emergency Room / Entity Relationship`},EST:{description:`Eastern Standard Time`},ETC:{description:`Et Cetera`},ETL:{description:`Extract, Transform, Load`},EULA:{description:`End User License Agreement`},FAAS:{description:`Function as a Service`,display:`FaaS`},FAQ:{description:`Frequently Asked Questions`,display:`FAQs`},FAQS:{description:`Frequently Asked Questions`},FBI:{description:`Federal Bureau of Investigation`},FCC:{description:`Federal Communications Commission`},FDA:{description:`Food and Drug Administration`},FIDO:{description:`Fast IDentity Online`},FLOTUS:{description:`First Lady of the United States`},FQDN:{description:`Fully Qualified Domain Name`},FTC:{description:`Federal Trade Commission`},FTP:{description:`File Transfer Protocol`},GC:{description:`Garbage Collection`},GCP:{description:`Google Cloud Platform`},GDPR:{description:`General Data Protection Regulation`},GMT:{description:`Greenwich Mean Time`},GOP:{description:`Grand Old Party`},GPU:{description:`Graphics Processing Unit`},GUID:{description:`Globally Unique Identifier`},GUI:{description:`Graphical User Interface`},GZIP:{description:`GNU Zip`},HCI:{description:`Human Computer Interaction / Hyper-Converged Infrastructure`},HDD:{description:`Hard Disk Drive`},HDFS:{description:`Hadoop Distributed File System`},HHS:{description:`Health and Human Services`},HIPAA:{description:`Health Insurance Portability and Accountability Act`},HMAC:{description:`Hash-based Message Authentication Code`},HOTP:{description:`HMAC-based One-Time Password`},HSM:{description:`Hardware Security Module`},HTML:{description:`HyperText Markup Language`},HTTP:{description:`HyperText Transfer Protocol (HTTP)`},"HTTP/2":{description:`HyperText Transfer Protocol Version 2 (HTTP/2)`},"HTTP/2.0":{description:`HyperText Transfer Protocol Version 2 (HTTP/2)`,display:`HTTP2`},"HTTP/3":{description:`HyperText Transfer Protocol Version 3 (HTTP/3)`},"HTTP/3.0":{description:`HyperText Transfer Protocol Version 3 (HTTP/3)`,display:`HTTP3`},HTTP2:{description:`HyperText Transfer Protocol Version 2 (HTTP/2)`,display:`HTTP2`},"HTTP2.0":{description:`HyperText Transfer Protocol Version 2 (HTTP/2)`,display:`HTTP2`},HTTP3:{description:`HyperText Transfer Protocol Version 3 (HTTP/3)`,display:`HTTP3`},"HTTP3.0":{description:`HyperText Transfer Protocol Version 3 (HTTP/3)`,display:`HTTP3`},HTTPS:{description:`HyperText Transfer Protocol Secure (HTTPS)`},"HTTPS/2":{description:`HyperText Transfer Protocol Secure Version 2 (HTTPS/2)`},"HTTPS/2.0":{description:`HyperText Transfer Protocol Secure Version 2 (HTTPS/2)`,display:`HTTPS2`},"HTTPS/3":{description:`HyperText Transfer Protocol Secure Version 3 (HTTPS/3)`},"HTTPS/3.0":{description:`HyperText Transfer Protocol Secure Version 3 (HTTPS/3)`,display:`HTTPS3`},HTTPS2:{description:`HyperText Transfer Protocol Secure Version 2 (HTTPS/2)`,display:`HTTPS2`},"HTTPS2.0":{description:`HyperText Transfer Protocol Secure Version 2 (HTTPS/2)`,display:`HTTPS2`},HTTPS3:{description:`HyperText Transfer Protocol Secure Version 3 (HTTPS/3)`,display:`HTTPS3`},"HTTPS3.0":{description:`HyperText Transfer Protocol Secure Version 3 (HTTPS/3)`,display:`HTTPS3`},IAAS:{description:`Infrastructure as a Service`,display:`IaaS`},IAM:{description:`Identity and Access Management`},IAMM:{description:`Identity and Access Management and Monitoring`},IAMT:{description:`Identity and Access Management Tool`},ID:{description:`Identifier`,display:`Id`},IFTTT:{description:`If This Then That`},IMAP:{description:`Internet Message Access Protocol`},IO:{description:`Input/Output`},IP:{description:`Internet Protocol`},IPFS:{description:`InterPlanetary File System`},IPS:{description:`Intrusion Prevention System`},ISO:{description:`International Organization for Standardization`},IQ:{description:`Intelligence Quotient`,display:`IQ`},IOT:{description:`Internet of Things`,display:`IoT`},JSON:{description:`JavaScript Object Notation`},JSONP:{description:`JSON with Padding`},JWT:{description:`JSON Web Token`},K8S:{description:`Kubernetes`,display:`K8s`},KMS:{description:`Key Management Service`},KPI:{description:`Key Performance Indicator`},KV:{description:`Key Value`},LAN:{description:`Local Area Network`},LHS:{description:`Left Hand Side`},LPGA:{description:`Ladies Professional Golf Association`},LXC:{description:`Linux Containers`},MDT:{description:`Mountain Daylight Time`},MFA:{description:`Multi-Factor Authentication`},ML:{description:`Machine Learning`},MLB:{description:`Major League Baseball`},MLOps:{description:`Machine Learning Operations`},MPA:{description:`Multi-Page Application`},MST:{description:`Mountain Standard Time`},MVC:{description:`Model View Controller`},MVP:{description:`Minimum Viable Product / Most Valuable Player`},NAIA:{description:`National Association of Intercollegiate Athletics`},NAS:{description:`Network Attached Storage`},NASA:{description:`National Aeronautics and Space Administration`},NASCAR:{description:`National Association for Stock Car Auto Racing`},NAT:{description:`Network Address Translation`},NBA:{description:`National Basketball Association`},NCAA:{description:`National Collegiate Athletic Association`},NDA:{description:`Non-Disclosure Agreement`},NFS:{description:`Network File System`},NHL:{description:`National Hockey League`},NIST:{description:`National Institute of Standards and Technology`},NLP:{description:`Natural Language Processing`},NPS:{description:`Net Promoter Score`},NRA:{description:`National Rifle Association`},NSFW:{description:`Not Safe For Work`},NX:{description:`Nx`,display:`Nx`},OCR:{description:`Optical Character Recognition`},OEM:{description:`Original Equipment Manufacturer`},OKR:{description:`Objectives and Key Results`},OLAP:{description:`Online Analytical Processing`},OLTP:{description:`Online Transaction Processing`},OOP:{description:`Object Oriented Programming`},ORM:{description:`Object Relational Mapping`},OS:{description:`Operating System`},OSINT:{description:`Open Source Intelligence`},OSS:{description:`Open Source Software`},OTP:{description:`One-Time Password`},P2P:{description:`Peer to Peer`},PAAS:{description:`Platform as a Service`,display:`PaaS`},PCI:{description:`Payment Card Industry`},PDP:{description:`Policy Decision Point / Product Detail Page`},PDT:{description:`Pacific Daylight Time`},PGA:{description:`Professional Golfers' Association`},POTUS:{description:`President of the United States`},PP:{description:`Pages / PayPal / Percentage Points`},PST:{description:`Pacific Standard Time`},PTO:{description:`Paid Time Off / Power Take-Off`},PKI:{description:`Public Key Infrastructure`},PWA:{description:`Progressive Web App`},PX:{description:`Pixel`},QA:{description:`Quality Assurance`},R2:{description:`R2`},RAID:{description:`Redundant Array of Independent Disks`},RAM:{description:`Random Access Memory`},RDS:{description:`Relational Database Service`},REST:{description:`Representational State Transfer`},RHS:{description:`Right Hand Side`},ROI:{description:`Return on Investment`},RPC:{description:`Remote Procedure Call`},RPA:{description:`Robotic Process Automation`},RSC:{description:`React Server Components`},RSS:{description:`Really Simple Syndication`},RUM:{description:`Real User Monitoring`},S3:{description:`Simple Storage Service (S3)`},SAN:{description:`Storage Area Network`},SASE:{description:`Secure Access Service Edge`},SCOTUS:{description:`Supreme Court of the United States`},SDLC:{description:`Software Development Life Cycle`},SDK:{description:`Software Development Kit`},SEC:{description:`Securities and Exchange Commission`},SEO:{description:`Search Engine Optimization`},SFTP:{description:`SSH File Transfer Protocol / Secure File Transfer Protocol`},SIEM:{description:`Security Information and Event Management`},SLA:{description:`Service Level Agreement`},SMB:{description:`Server Message Block / Small and Medium Business`},SMTP:{description:`Simple Mail Transfer Protocol`},SOAP:{description:`Simple Object Access Protocol`},SOA:{description:`Service Oriented Architecture`},SOC:{description:`Security Operations Center / System on Chip`},SPA:{description:`Single Page Application`},SPDY:{description:`Speedy (pronounced "SPeeDY")`},SPF:{description:`Sender Policy Framework`},SQL:{description:`Structured Query Language`},SRV:{description:`Service`},SRE:{description:`Site Reliability Engineering`},SSH:{description:`Secure Shell`},SSDL:{description:`Secure Software Development Lifecycle`},SSG:{description:`Static Site Generation`},SSR:{description:`Server Side Rendering`},SSO:{description:`Single Sign-On`},SSL:{description:`Secure Sockets Layer`},TDD:{description:`Test Driven Development`},TLD:{description:`Top Level Domain`},TLS:{description:`Transport Layer Security`},"TLS1.3":{description:`Transport Layer Security 1.3`},TOR:{description:`The Onion Router`},TOTP:{description:`Time-based One-Time Password`},TRPC:{description:`TypeScript Remote Procedure Call`},TSA:{description:`Transportation Security Administration`},TTL:{description:`Time To Live`},UDP:{description:`User Datagram Protocol`},UI:{description:`User Interface`},UID:{description:`Unique Identifier`},URI:{description:`Uniform Resource Identifier`},URL:{description:`Uniform Resource Locator`},USOPC:{description:`United States Olympic & Paralympic Committee`},USPS:{description:`United States Postal Service`},USTA:{description:`United States Tennis Association`},UTF:{description:`Unicode Transformation Format`},UTC:{description:`Coordinated Universal Time`},UUID:{description:`Universally Unique Identifier`},UX:{description:`User Experience`},VM:{description:`Virtual Machine`},VLAN:{description:`Virtual Local Area Network`},VPN:{description:`Virtual Private Network`},VPPA:{description:`Video Privacy Protection Act`},VR:{description:`Virtual Reality`},WAF:{description:`Web Application Firewall`},WAN:{description:`Wide Area Network`},WNBA:{description:`Women's National Basketball Association`},WLAN:{description:`Wireless Local Area Network`},WPA:{description:`Wi-Fi Protected Access`},WPA2:{description:`Wi-Fi Protected Access II`},WPA3:{description:`Wi-Fi Protected Access III`},WWW:{description:`World Wide Web`},WYSIWYG:{description:`What You See Is What You Get`},XACML:{description:`eXtensible Access Control Markup Language`},XDG:{description:`Cross-Desktop Group`},XML:{description:`eXtensible Markup Language`},XSRF:{description:`Cross-Site Request Forgery`},XSS:{description:`Cross-Site Scripting`},XR:{description:`Extended Reality`},YAML:{description:`YAML Ain't Markup Language`},YMCA:{description:`Young Men's Christian Association`},YWCA:{description:`Young Women's Christian Association`},ZTA:{description:`Zero Trust Architecture`}},ae=Object.fromEntries(Object.entries(k).map(([e,t])=>[e,t.display??e])),oe=Object.fromEntries(Object.entries(k).map(([e,t])=>[e,t.description])),se=Object.keys(k),ce=[`a`,`an`,`the`],le=[`and`,`that`,`but`,`or`,`as`,`if`,`when`,`than`,`because`,`while`,`where`,`after`,`so`,`though`,`since`,`until`,`whether`,`before`,`although`,`nor`,`like`,`once`,`unless`,`now`,`except`],ue=`about.above.across.after.against.along.among.around.at.because of.before.behind.below.beneath.beside.besides.between.beyond.but.by.concerning.despite.down.during.except.excepting.for.from.in.in front of.inside.in spite of.instead of.into.like.near.of.off.on.onto.out.outside.over.past.regarding.since.through.throughout.to.toward.under.underneath.until.up.upon.up to.with.within.without.with regard to.with respect to`.split(`.`),de=`2FA.4K.5K.8K.AGI.BI.ChatGPT.CTA.DateTime.FMS.GitHub.GPT.HD.IBMid.IDs.iMac.IMAX.iOS.iPad.iPhone.iPod.LDAP.LinkedIn.LLM.macOS.McDonalds.MCP.ML.MySQL.NLG.NLP.NLU.OpenAI.PDFs.PIM.PEFT.pH.PostgreSQL.SEO.TTS.UHD.UUID.XSS.YouTube.CSpell.ESLint`.split(`.`);function fe(e,t,n,r){let i=e.toLowerCase(),a=e.toUpperCase();for(let e of de)if(e.toLowerCase()===i)return e;return k[a]?r?.useDescriptions===!1?k[a].display||a:k[a].description:t===0||t===n.length-1||e.length>=4?e:ue.includes(i)||le.includes(i)||ce.includes(i)?i:e}function A(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function pe(e,t){return e?.split(/\s+-\s+/).map(e=>ie(e).split(/[\s\-_]/).map(A).map((e,n,r)=>fe(e,n,r,t)).reduce(re)).join(` - `)}const j=g.default.homedir(),M=g.default.tmpdir(),me=e=>{let t=(0,d.joinPaths)(j,`Library`);return{data:(0,d.joinPaths)(t,`Application Support`,e),config:(0,d.joinPaths)(t,`Preferences`,e),cache:(0,d.joinPaths)(t,`Caches`,e),log:(0,d.joinPaths)(t,`Logs`,e),temp:(0,d.joinPaths)(M,e)}},he=e=>{let t=process.env.APPDATA||(0,d.joinPaths)(j,`AppData`,`Roaming`),n=process.env.LOCALAPPDATA||(0,d.joinPaths)(j,`AppData`,`Local`),r=pe(e).trim().replace(/\s+/g,``);return{data:(0,d.joinPaths)(n,r,`Data`),config:(0,d.joinPaths)(t,r,`Config`),cache:(0,d.joinPaths)(n,`Cache`,e),log:(0,d.joinPaths)(n,r,`Log`),temp:(0,d.joinPaths)(M,e)}},ge=e=>{let t=f.default.basename(j);return{data:(0,d.joinPaths)(process.env.XDG_DATA_HOME||(0,d.joinPaths)(j,`.local`,`share`),e),config:(0,d.joinPaths)(process.env.XDG_CONFIG_HOME||(0,d.joinPaths)(j,`.config`),e),cache:(0,d.joinPaths)(process.env.XDG_CACHE_HOME||(0,d.joinPaths)(j,`.cache`),e),log:(0,d.joinPaths)(process.env.XDG_STATE_HOME||(0,d.joinPaths)(j,`.local`,`state`),e),temp:process.env.DEVENV_RUNTIME||process.env.XDG_RUNTIME_DIR?(0,d.joinPaths)(process.env.DEVENV_RUNTIME||process.env.XDG_RUNTIME_DIR,e):(0,d.joinPaths)(M,t,e)}};function _e(e={}){let t=e.orgId||`storm-software`;if(!t)throw Error("You need to provide an orgId to the `getEnvPaths` function");e.suffix&&(t+=`-${typeof e.suffix==`string`?e.suffix:`nodejs`}`);let n={};return n=process.platform===`darwin`?me(t):process.platform===`win32`?he(t):ge(t),process.env.STORM_DATA_DIR?n.data=process.env.STORM_DATA_DIR:process.env.STORM_CONFIG_DIR?n.config=process.env.STORM_CONFIG_DIR:process.env.STORM_CACHE_DIR?n.cache=process.env.STORM_CACHE_DIR:process.env.STORM_LOG_DIR?n.log=process.env.STORM_LOG_DIR:process.env.STORM_TEMP_DIR&&(n.temp=process.env.STORM_TEMP_DIR),e.workspaceRoot&&(n.cache??=(0,d.joinPaths)(e.workspaceRoot,`node_modules`,`.cache`,t),n.temp??=(0,d.joinPaths)(e.workspaceRoot,`tmp`,t),n.log??=(0,d.joinPaths)(n.temp,`logs`),n.config??=(0,d.joinPaths)(e.workspaceRoot,`.config`,t)),Object.keys(n).reduce((t,r)=>{if(n[r]){let i=n[r];t[r]=e.appId&&e.appId!==e.orgId&&e.appId!==e.nestedDir?(0,d.joinPaths)(i,e.appId):i,e.nestedDir&&e.nestedDir!==e.orgId&&e.nestedDir!==e.appId&&(t[r]=(0,d.joinPaths)(t[r],e.nestedDir))}return t},{})}let N;function P(){if(!N){let e=_e();N=(0,v.createJiti)((0,_.getWorkspaceRoot)(),{fsCache:(0,d.joinPaths)(e.cache,`jiti`),interopDefault:!0})}return N}async function F(){return P().import(P().esmResolve(`@prisma/internals`))}async function ve(){return P().import(P().esmResolve(`@prisma/generator-helper`))}const I=e=>{let t=[];if(e){let n=e.split(`
|
|
2
|
-
`).filter(e=>!e.trimStart().startsWith(`@zod`));n.length&&(t.push(`/**`),n.forEach(e=>t.push(` * ${e}`)),t.push(` */`))}return t},L=e=>e.split(`
|
|
3
|
-
`).filter(e=>e.trimStart().startsWith(`@zod`)).map(e=>e.trimStart().slice(4)).flatMap(e=>xe(y.default.parse(e),2).slice(0,-1).map(([e,t])=>`${e.replace(/\)?\./,``)}${y.default.stringify(t)})`));function R(e){let{fields:t}=e;for(let e of t)if(B(e))return!0;return!1}function z(e){let{fields:t}=e;for(let e of t)if(ye(e))return!0;return!1}function B(e){let{kind:t,relationName:n}=e;return t===`object`&&!!n}function ye(e){return B(e)&&e.isList}function be(e,t){return e.find(({name:e})=>e===t)}const V=(e,t,n=!0)=>t.forEach(t=>e.write(t).conditionalNewLine(n)),H=({modelCase:e,modelSuffix:t,relationModel:n})=>{let r=(n,r=``)=>(e===`camelCase`&&(n=n.slice(0,1).toLowerCase()+n.slice(1)),`${r}${n}${t}`);return{modelName:e=>r(e,n===`default`?`_`:``),relatedModelName:e=>r(n===`default`?e.toString():`Related${e.toString()}`)}},U=e=>{let t=e.replace(/^\\\\\?\\/,``).replace(/\\/g,`/`).replace(/\/{2,}/g,`/`);return t.includes(`/node_modules/`)?t.split(`/node_modules/`).slice(-1)[0]:t.startsWith(`../`)?t:`./${t}`},xe=(e,t)=>e.reduce((e,n,r)=>r%t===0?[...e,[n]]:[...e.slice(0,-1),[...e.slice(-1)[0],n]],[]),Se=(e,t)=>e.fields.some(e=>e.kind===`object`)&&t.relationModel!==!1,Ce=async(e,t,n,r)=>{let i=(await F()).parseEnvValue(r.generator.output),{relatedModelName:a}=H(n),o=[{kind:h.StructureKind.ImportDeclaration,namespaceImport:`z`,moduleSpecifier:`zod`}];n.imports&&o.push({kind:h.StructureKind.ImportDeclaration,namespaceImport:`imports`,moduleSpecifier:U(f.default.relative(i,f.default.resolve(f.default.dirname(r.schemaPath),n.imports)))}),n.useDecimalJs&&e.fields.some(e=>e.type===`Decimal`)&&o.push({kind:h.StructureKind.ImportDeclaration,namedImports:[`Decimal`],moduleSpecifier:`decimal.js`});let s=e.fields.filter(e=>e.kind===`enum`),c=e.fields.filter(e=>e.kind===`object`),l=r.otherGenerators.find(e=>e.provider.value===`prisma-client-js`).output.value,u=f.default.relative(i,l);if(s.length>0&&o.push({kind:h.StructureKind.ImportDeclaration,isTypeOnly:s.length===0,moduleSpecifier:U(u),namedImports:s.map(e=>e.type)}),n.relationModel!==!1&&c.length>0){let t=c.filter(t=>t.type!==e.name);t.length>0&&o.push({kind:h.StructureKind.ImportDeclaration,moduleSpecifier:`./index`,namedImports:Array.from(new Set(t.flatMap(e=>[`${e.type}`,a(e.type)])))})}t.addImportDeclarations(o)},we=e=>L(e).find(e=>e.startsWith(`custom(`))?.slice(7).slice(0,-1),Te=e=>L(e).filter(e=>!e.startsWith(`custom(`)),W=(e,t=e=>e.toString())=>{let n=`z.unknown()`,r=[``];if(e.kind===`scalar`)switch(e.type){case`String`:n=`z.string()`;break;case`Int`:n=`z.number()`,r.push(`int()`);break;case`BigInt`:n=`z.bigint()`;break;case`DateTime`:n=`z.date()`;break;case`Float`:n=`z.number()`;break;case`Decimal`:n=`z.number()`;break;case`Json`:n=`jsonSchema`;break;case`Boolean`:n=`z.boolean()`;break;case`Bytes`:n=`z.unknown()`;break}else e.kind===`enum`?n=`z.nativeEnum(${e.type})`:e.kind===`object`&&(n=t(e.type));return e.isList&&r.push(`array()`),e.documentation&&(n=we(e.documentation)??n,r.push(...Te(e.documentation))),!e.isRequired&&e.type!==`Json`&&r.push(`nullish()`),`${n}${r.join(`.`)}`},Ee=(e,t,n)=>{e.fields.some(e=>e.type===`Json`)&&t.addStatements(e=>{e.newLine(),V(e,[`// Helper schema for JSON fields`,`type Literal = boolean | number | string${n.prismaJsonNullability?``:`| null`}`,`type Json = Literal | { [key: string]: Json } | Json[]`,`const literalSchema = z.union([z.string(), z.number(), z.boolean()${n.prismaJsonNullability?``:`, z.null()`}])`,`const jsonSchema: z.ZodSchema<Json> = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]))`])}),n.useDecimalJs&&e.fields.some(e=>e.type===`Decimal`)&&t.addStatements(e=>{e.newLine(),V(e,[`// Helper schema for Decimal fields`,`z`,`.instanceof(Decimal)`,`.or(z.string())`,`.or(z.number())`,`.refine((value) => {`,` try {`,` return new Decimal(value);`,` } catch (error) {`,` return false;`,` }`,`})`,`.transform((value) => new Decimal(value));`])})},De=(e,t,n)=>{let{modelName:r}=H(n);t.addVariableStatement({declarationKind:h.VariableDeclarationKind.Const,isExported:!0,leadingTrivia:e=>e.blankLineIfLastNot(),declarations:[{name:r(e.name),initializer(t){t.write(`z.object(`).inlineBlock(()=>{e.fields.filter(e=>e.kind!==`object`).forEach(e=>{V(t,I(e.documentation)),t.write(`${e.name}: ${W(e)}`).write(`,`).newLine()})}).write(`)`)}}]})},Oe=(e,t,n)=>{let{modelName:r,relatedModelName:i}=H(n),a=e.fields.filter(e=>e.kind===`object`);t.addInterface({name:`${e.name}`,isExported:!0,extends:[`z.infer<typeof ${r(e.name)}>`],properties:a.map(e=>({hasQuestionToken:!e.isRequired,name:e.name,type:`${e.type}${e.isList?`[]`:``}${e.isRequired?``:` | null`}`}))}),t.addStatements(t=>V(t,[``,`/**`,` * ${i(e.name)} contains all relations on your model in addition to the scalars`,` *`,` * NOTE: Lazy required in case of potential circular dependencies within schema`,` */`])),t.addVariableStatement({declarationKind:h.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:i(e.name),type:`z.ZodSchema<${e.name}>`,initializer(t){t.write(`z.lazy(() => ${r(e.name)}.extend(`).inlineBlock(()=>{a.forEach(e=>{V(t,I(e.documentation)),t.write(`${e.name}: ${W(e,i)}`).write(`,`).newLine()})}).write(`))`)}}]})},ke=async(e,t,n,r)=>{await Ce(e,t,n,r),Ee(e,t,n),De(e,t,n),Se(e,n)&&Oe(e,t,n)},Ae=(e,t)=>{e.forEach(e=>t.addExportDeclaration({moduleSpecifier:`./${C(e.name)}.schema`}))},G=e=>e.withShield?`shieldedProcedure`:e.withMiddleware?`protectedProcedure`:`publicProcedure`,K=({sourceFile:e,config:t})=>{let n=[`t`];t&&n.push(G(t)),e.addImportDeclaration({moduleSpecifier:`../trpc`,namedImports:n})},je=(e,t,n)=>{e.addImportDeclaration({moduleSpecifier:`./${C(n)}.router`,namedImports:[`${t}Router`]})};async function Me(e,t,n,r){t.withShield&&e.addImportDeclaration({moduleSpecifier:(0,m.relativePath)(r,(0,d.joinPaths)(r,typeof t.withShield==`string`?t.withShield:`shield`)),namedImports:[`permissions`]}),e.addStatements(`import type { Context } from '${(0,m.relativePath)(r,(0,d.joinPaths)(r,t.contextPath))}';`),t.trpcOptions&&e.addStatements(`import trpcOptions from '${typeof t.trpcOptions==`string`?(0,m.relativePath)(r,(0,d.joinPaths)(r,t.trpcOptions)):`./options`}';`),t.withNext&&e.addStatements(`import { createContext } from '${(0,m.relativePath)(r,(0,d.joinPaths)(r,t.contextPath))}';
|
|
4
|
-
import { initTRPC } from '@trpc/server';
|
|
5
|
-
import { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';
|
|
6
|
-
import { cookies } from "next/headers";`),e.addStatements(`
|
|
7
|
-
export const t = initTRPC.context<Context>().create(${t.trpcOptions?`trpcOptions`:``});`);let i=[];if(t.withMiddleware&&typeof t.withMiddleware==`boolean`&&(e.addStatements(`
|
|
8
|
-
export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
|
|
9
|
-
console.log('inside middleware!')
|
|
10
|
-
return next()
|
|
11
|
-
});`),i.push({type:`global`,value:`.use(globalMiddleware)`})),t.withMiddleware&&typeof t.withMiddleware==`string`&&(e.addStatements(`
|
|
12
|
-
import middleware from '${(0,m.relativePath)(r,(0,d.joinPaths)(r,typeof t.withMiddleware==`string`?t.withMiddleware:`middleware`))}';
|
|
13
|
-
`),e.addStatements(`
|
|
14
|
-
export const globalMiddleware = t.middleware(middleware);`),i.push({type:`global`,value:`.use(globalMiddleware)`})),t.withShield&&(e.addStatements(`
|
|
15
|
-
export const permissionsMiddleware = t.middleware(permissions);
|
|
16
|
-
`),i.push({type:`shield`,value:`
|
|
17
|
-
.use(permissions)`})),e.addStatements(`
|
|
18
|
-
/**
|
|
19
|
-
* Create a server-side caller
|
|
20
|
-
* @see https://trpc.io/docs/server/server-side-calls
|
|
21
|
-
*/
|
|
22
|
-
export const createCallerFactory = t.createCallerFactory;`),e.addStatements(`
|
|
23
|
-
export const publicProcedure = t.procedure; `),i.length>0){let n=G(t);i.forEach((t,r)=>{r===0&&e.addStatements(`
|
|
24
|
-
export const ${n} = t.procedure`),e.addStatements(`.use(${t.type===`shield`?`permissionsMiddleware`:`globalMiddleware`})`)})}t.withNext&&e.addStatements(`
|
|
25
|
-
export const createAction: ReturnType<typeof createTRPCServerActionHandler> =
|
|
26
|
-
createTRPCServerActionHandler(cookies, t, createContext);
|
|
27
|
-
`),e.formatText({indentSize:2})}function Ne(e,t,n,r,i,a,o){let s=`input${o.withZod?``:` as any`}`,c=t.replace(r,``);c===`groupBy`&&o.withZod&&(s=`{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }`),e.addStatements(`${o.showModelNameInProcedure?t:c}: ${G(o)}
|
|
28
|
-
${o.withZod?`.input(${C(n)})`:``}.${Ie(a)}(async ({ ctx, input }) => {
|
|
29
|
-
const ${t} = await ctx.prisma.${C(r)}.${i.replace(`One`,``)}(${s});
|
|
30
|
-
return ${t};
|
|
31
|
-
}),`)}function Pe(e,t,n){e.addStatements([...new Set(n.map(e=>Fe(e,t)))].join(`
|
|
32
|
-
`))}const Fe=(e,t)=>{let n=e.replace(`OrThrow`,``).replace(`ManyAndReturn`,``),r=q(n,t);return r?`import { ${C(r)} } from "../schemas/${C(n)}${t}.schema"; `:``},q=(e,t)=>{let n;switch(e){case`findUnique`:n=`${t}FindUniqueSchema`;break;case`findFirst`:n=`${t}FindFirstSchema`;break;case`findMany`:n=`${t}FindManySchema`;break;case`findRaw`:n=`${t}FindRawObjectSchema`;break;case`createOne`:n=`${t}CreateOneSchema`;break;case`createMany`:n=`${t}CreateManySchema`;break;case`createManyAndReturn`:n=`${t}CreateManySchema`;break;case`deleteOne`:n=`${t}DeleteOneSchema`;break;case`deleteMany`:n=`${t}DeleteManySchema`;break;case`updateOne`:n=`${t}UpdateOneSchema`;break;case`updateMany`:n=`${t}UpdateManySchema`;break;case`updateManyAndReturn`:n=`${t}UpdateManySchema`;break;case`upsertOne`:n=`${t}UpsertSchema`;break;case`aggregate`:n=`${t}AggregateSchema`;break;case`aggregateRaw`:n=`${t}AggregateRawObjectSchema`;break;case`groupBy`:n=`${t}GroupBySchema`;break;default:console.log(`getInputTypeByOpName: `,{opName:e,modelName:t})}return n},Ie=e=>{let t;switch(e){case`findUnique`:case`findFirst`:case`findMany`:case`findRaw`:case`aggregate`:case`aggregateRaw`:case`groupBy`:t=`query`;break;case`createOne`:case`createMany`:case`createManyAndReturn`:case`deleteOne`:case`updateOne`:case`deleteMany`:case`updateMany`:case`updateManyAndReturn`:case`upsertOne`:t=`mutation`;break;default:console.log(`getProcedureTypeByOpName: `,{opName:e})}return t};function Le(e,t){let n=/(?:@@Gen\.)+[A-z]+\(.+\)/,r=/\.+[A-Z]+\(+/i,i=/\(+[A-Z]+:.+\)/i;for(let a of e)if(a.documentation){let e=a.documentation?.match(n)?.[0];if(e?.match(r)?.[0]?.slice(1,-1)!==`model`)continue;let o=e?.match(i)?.[0]?.slice(1,-1),s={};if(o){let e=o.split(`:`).map(e=>e.trim()).map(e=>e.startsWith(`[`)?e:e.split(`,`)).flat().map(e=>e.trim());for(let t=0;t<e.length;t+=2){let n=e[t],r=e[t+1];s[n]=JSON.parse(r)}}s.hide&&t.push(a.name)}}const J=(e,t)=>{let n=``;return e===`trpc`?n=`import * as trpc from '@trpc/server';
|
|
33
|
-
`:e===`trpc-shield`?n=`import { shield, allow } from '@stryke/trpc-next/shield';
|
|
34
|
-
`:e===`context`&&(n=`import type { Context } from '${t}';\n`),n},Y=({shieldItemLines:e})=>{let t=`{`;return t+=`
|
|
35
|
-
`,t+=Array.isArray(e)?` ${e.join(`,\r
|
|
36
|
-
`)}`:` ${e}`,t+=`
|
|
37
|
-
`,t+=`}`,t},Re=({shieldObjectTextWrapped:e})=>{let t=`shield<Context>(`;return t+=`
|
|
38
|
-
`,t+=` ${e}`,t+=`
|
|
39
|
-
`,t+=`)`,t},ze=({shieldObjectText:e})=>`export const permissions: ReturnType<typeof shield<Context>> = ${e};`,Be=async({queries:e,mutations:t,subscriptions:n},r,i,a)=>{if(e.length===0&&t.length===0&&n.length===0)return``;let o=``;if(e.length>0){let t=`query: ${Y({shieldItemLines:e.map(e=>`${e}: allow`)})},`;o+=t}if(t.length>0){let e=`mutation: ${Y({shieldItemLines:t.map(e=>`${e}: allow`)})},`;o+=e}if(n.length>0){let e=`subscription: ${Y({shieldItemLines:n.map(e=>`${e}: allow`)})},`;o+=e}if(o.length===0)return``;let s=J(`trpc-shield`);return s+=J(`context`,(0,m.relativePath)(a,(0,d.joinPaths)(a,r.contextPath))),s+=`
|
|
40
|
-
|
|
41
|
-
`,s+=ze({shieldObjectText:Re({shieldObjectTextWrapped:Y({shieldItemLines:o})})}),s},Ve=(e,t,n)=>`import { ZodError } from 'zod';${e.withNext?`
|
|
42
|
-
import { transformer } from "@stryke/trpc-next/shared";`:``}
|
|
43
|
-
import type {
|
|
44
|
-
DataTransformerOptions,
|
|
45
|
-
RootConfig
|
|
46
|
-
} from "@trpc/server/unstable-core-do-not-import";
|
|
47
|
-
import type { Context } from "${(0,m.relativePath)(n,(0,d.joinPaths)(n,e.contextPath))}";
|
|
48
|
-
|
|
49
|
-
interface RuntimeConfigOptions<
|
|
50
|
-
TContext extends object,
|
|
51
|
-
TMeta extends object = object
|
|
52
|
-
> extends Partial<
|
|
53
|
-
Omit<
|
|
54
|
-
RootConfig<{
|
|
55
|
-
ctx: TContext;
|
|
56
|
-
meta: TMeta;
|
|
57
|
-
errorShape: any;
|
|
58
|
-
transformer: any;
|
|
59
|
-
}>,
|
|
60
|
-
"$types" | "transformer"
|
|
61
|
-
>
|
|
62
|
-
> {
|
|
63
|
-
/**
|
|
64
|
-
* Use a data transformer
|
|
65
|
-
* @see https://trpc.io/docs/v11/data-transformers
|
|
66
|
-
*/
|
|
67
|
-
transformer?: DataTransformerOptions;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const options: RuntimeConfigOptions<Context> = {${e.withNext?`
|
|
71
|
-
transformer,`:``}
|
|
72
|
-
errorFormatter({ shape, error }) {
|
|
73
|
-
return {
|
|
74
|
-
...shape,
|
|
75
|
-
data: {
|
|
76
|
-
...shape.data,
|
|
77
|
-
zodError:
|
|
78
|
-
error.code === "BAD_REQUEST" && error.cause instanceof ZodError
|
|
79
|
-
? error.cause.flatten()
|
|
80
|
-
: null
|
|
81
|
-
}
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
export default options;
|
|
87
|
-
`,He=async(e,t,n,r)=>{let i=O.createSourceFile(`${t}/index.ts`,{},{overwrite:!0});Ae(e,i),i.formatText({indentSize:2}),await Promise.all(e.map(async e=>{let i=O.createSourceFile(`${t}/${C(e.name)}.schema.ts`,{},{overwrite:!0});await ke(e,i,n,r),i.formatText({indentSize:2})}))};async function Ue(e){let t=await S.default.resolveConfig(process.cwd()),n=t;return t||(n={trailingComma:`all`,tabWidth:2,printWidth:80,bracketSpacing:!0,semi:!0,singleQuote:!0,useTabs:!1}),await S.default.format(e,{...n,parser:`typescript`})}const X=new Set,We=e=>{X.add(e)},Z=async(e,t,n=!0)=>{let[r]=await Promise.all([Ue(t),(0,u.createDirectory)((0,m.findFilePath)(e))]);await(0,b.writeFile)(e,r),n&&We(e)},Ge=async e=>{let t=Array.from(X).map(t=>{let n=f.default.relative(f.default.dirname(e),t);return n.endsWith(`.ts`)&&(n=n.slice(0,n.lastIndexOf(`.ts`))),`export * from './${(0,x.correctPath)(n)}';`});t.push(`export * from './models';`),await Z(e,t.join(`
|
|
88
|
-
`),!1)},Ke=e=>/(?:Count|Avg|Sum|Min|Max)AggregateOutputType$/.test(e),Q=e=>e.endsWith(`CountAggregateInput`)||e.endsWith(`SumAggregateInput`)||e.endsWith(`AvgAggregateInput`)||e.endsWith(`MinAggregateInput`)||e.endsWith(`MaxAggregateInput`);function qe(e,t){let n=t.filter(({name:e})=>Ke(e));for(let t of n){let n=t.name.replace(/(?:OutputType|Output)$/,``);e.push({constraints:{maxNumFields:null,minNumFields:null},name:`${n}Input`,fields:t.fields.map(e=>({name:e.name,isNullable:!1,isRequired:!1,inputTypes:[{isList:!1,type:`True`,location:`scalar`}]}))})}}function Je(e){let t={};for(let n of e)if(Q(n.name)){let e=n.name.replace(`AggregateInput`,``);if(e.endsWith(`Count`)){let n=e.replace(`Count`,``);t[n]={...t[n],count:!0}}else if(e.endsWith(`Min`)){let n=e.replace(`Min`,``);t[n]={...t[n],min:!0}}else if(e.endsWith(`Max`)){let n=e.replace(`Max`,``);t[n]={...t[n],max:!0}}else if(e.endsWith(`Sum`)){let n=e.replace(`Sum`,``);t[n]={...t[n],sum:!0}}else if(e.endsWith(`Avg`)){let n=e.replace(`Avg`,``);t[n]={...t[n],avg:!0}}}return t}const Ye=/(?:@@Gen\.)+[A-z]+\(.+\)/,Xe=/\.+[A-Z]+\(+/i,Ze=/\(+[A-Z]+:.+\)/i;function Qe(e,t,n,r,i){e=$e(e,r),et(e,r,i),nt(e,t),tt(n,r)}function $e(e,t){return e.map(e=>{if(e.documentation){let n=e.documentation?.match(Ye)?.[0];if(n?.match(Xe)?.[0]?.slice(1,-1)!==`model`)return e;let r=n?.match(Ze)?.[0]?.slice(1,-1),i={};if(r){let e=r.split(`:`).map(e=>e.trim()).map(e=>e.startsWith(`[`)?e:e.split(`,`)).flat().map(e=>e.trim());for(let t=0;t<e.length;t+=2){let n=e[t],r=e[t+1];i[n]=JSON.parse(r)}}if(i.hide)return t.push(e.name),null}return e}).filter(Boolean)}function et(e,t,n){e.forEach(e=>{e.fields.forEach(e=>{t.includes(e.type)&&(n.push(e.name),e.relationFromFields&&e.relationFromFields.forEach(e=>n.push(e)))})})}function tt(e,t){e.prisma=e.prisma.filter(e=>!t.find(t=>e.name.startsWith(t)))}function nt(e,t){let n=t.length;for(;n>=0;){--n;let r=t[n];r&&!e.find(e=>e.name===r.model)&&t.splice(n,1)}}function rt(e,t,n){let r=e.length;for(;r>=0;){--r;let i=e[r];if(i&&(t.includes(i?.meta?.source)||t.find(e=>i.name.startsWith(e))))e.splice(r,1);else{let t=i?.fields?.length??0;for(;t>=0;){--t;let a=i?.fields?.[t];a&&n.includes(a.name)&&e[r].fields.slice(t,1)}}}}function it(e,t,n){$.rawOpsMap=at(e)??{};let r=ot(t);for(let e of r)n.push(e)}function at(e){let t={},n=[...new Set(e.reduce((e,t)=>(Object.keys(t)?.forEach(t=>{t.includes(`Raw`)&&e.push(t)}),e),[]))],r=e.map(e=>e.model);return n.forEach(e=>{r.forEach(n=>{let r=e===`findRaw`,i=`${e.replace(`Raw`,``)}${n}Raw`;t[i]=r?`${n}FindRawArgs`:`${n}AggregateRawArgs`})}),t}function ot(e){return st(e).map(e=>({name:e.name,constraints:{maxNumFields:null,minNumFields:null},fields:e.args.map(e=>({name:e.name,isRequired:e.isRequired,isNullable:e.isNullable,inputTypes:e.inputTypes}))}))}function st(e){return e.filter(e=>e.name===`Query`)?.[0].fields.filter(e=>e.name.includes(`Raw`))??[]}const ct=e=>/find[\s\S]*?Raw/.test(e)||/aggregate[\s\S]*?Raw/.test(e);var $=class e{name;fields;schemaImports=new Set;models;modelOperations;aggregateOperationSupport;enumTypes;static enumNames=[];static rawOpsMap={};static provider;static previewFeatures;static outputPath=`./generated`;hasJson=!1;static prismaClientOutputPath=`@prisma/client`;static isCustomPrismaClientOutputPath=!1;static isGenerateSelect=!0;static isGenerateInclude=!0;constructor(e){this.name=e.name??``,this.fields=e.fields??[],this.models=e.models??[],this.modelOperations=e.modelOperations??[],this.aggregateOperationSupport=e.aggregateOperationSupport??{},this.enumTypes=e.enumTypes??[]}static setOutputPath(e){this.outputPath=e}static setIsGenerateSelect(e){this.isGenerateSelect=e}static setIsGenerateInclude(e){this.isGenerateInclude=e}static getOutputPath(){return this.outputPath}static setPrismaClientOutputPath(e){this.prismaClientOutputPath=e,this.isCustomPrismaClientOutputPath=e!==`@prisma/client`}static async generateIndex(){await Ge(f.default.join(e.outputPath,`schemas/index.ts`))}async generateEnumSchemas(){for(let t of this.enumTypes){let{name:n,values:r}=t;await Z(f.default.join(e.outputPath,`schemas/enums/${C(n)}.schema.ts`),`${this.generateImportZodStatement()}\n${this.generateExportSchemaStatement(`${C(n)}`,`z.enum(${JSON.stringify(r)})`)}`)}}generateImportZodStatement(){return`import { z } from 'zod';
|
|
89
|
-
`}generateExportSchemaStatement(e,t){return`export const ${C(e)}Schema = ${t}`}async generateObjectSchema(){let t=this.generateObjectSchemaFields(),n=this.prepareObjectSchema(t),r=this.resolveObjectSchemaName();await Z(f.default.join(e.outputPath,`schemas/objects/${C(r)}.schema.ts`),n)}generateObjectSchemaFields(){return this.fields.map(e=>this.generateObjectSchemaField(e)).flatMap(e=>e).map(e=>{let[t,n,r]=e;return(r?t:this.generateFieldValidators(t,n)).trim()})}generateObjectSchemaField(e){let t=e.inputTypes;if(t.length===0)return[];let n=t.reduce((n,r)=>{if(r.type===`String`)n.push(this.wrapWithZodValidators(`z.string()`,e));else if(r.type===`Int`||r.type===`Float`||r.type===`Decimal`)n.push(this.wrapWithZodValidators(`z.number()`,e));else if(r.type===`BigInt`)n.push(this.wrapWithZodValidators(`z.bigint()`,e));else if(r.type===`Boolean`)n.push(this.wrapWithZodValidators(`z.boolean()`,e));else if(r.type===`DateTime`)n.push(this.wrapWithZodValidators(`z.coerce.date()`,e));else if(r.type===`Json`)this.hasJson=!0,n.push(this.wrapWithZodValidators(`jsonSchema`,e));else if(r.type===`True`)n.push(this.wrapWithZodValidators(`z.literal(true)`,e));else if(r.type===`Bytes`)n.push(this.wrapWithZodValidators(`z.instanceof(Buffer)`,e));else if(!r.type.endsWith(`FieldRefInput`)){let i=r.location===`enumTypes`;(r.namespace===`prisma`||i)&&(r.type!==this.name&&typeof r.type==`string`&&this.addSchemaImport(r.type),n.push(this.generatePrismaStringLine(e,r,t.length)))}return n},[]);if(n.length===0)return[];n.length>1&&(n=n.map(e=>e.replace(`.optional()`,``)));let r=n.some(e=>e.includes(`:`))?``:` ${e.name}:`,i=e.isRequired?``:`.optional()`,a=n.length===1?n.join(`,\r
|
|
90
|
-
`):`z.union([${n.join(`,\r
|
|
91
|
-
`)}])${i}`;return e.isNullable&&(a+=`.nullable()`),[[` ${r} ${a} `,e,!0]]}wrapWithZodValidators(e,t){let n=``;return n=e,t.inputTypes.some(e=>e.isList)&&(n+=`.array()`),t.isRequired||(n+=`.optional()`),n}addSchemaImport(e){this.schemaImports.add(e)}generatePrismaStringLine(e,t,n){let r=t.location===`enumTypes`,i=t.type,{isModelQueryType:a,modelName:o,queryName:s}=this.checkIsModelQueryType(i),c=a?this.resolveModelQuerySchemaName(o,s):`${i}ObjectSchema`,l=`${i}Schema`,u=t.type===this.name?c:r?l:c,d=t.isList?`.array()`:``,f=e.isRequired?``:`.optional()`;return n===1?` ${e.name}: z.lazy(() => ${C(u)})${d}${f}`:`z.lazy(() => ${C(u)})${d}${f}`}generateFieldValidators(e,t){let{isRequired:n,isNullable:r}=t;return n||(e+=`.optional()`),r&&(e+=`.nullable()`),e}prepareObjectSchema(e){let t=`${this.generateExportObjectSchemaStatement(this.addFinalWrappers({zodStringFields:e}))}\n`,n=this.generateImportPrismaStatement(),r=this.generateJsonSchemaImplementation();return`${this.generateObjectSchemaImportStatements()}${n}${r}${t}`}generateExportObjectSchemaStatement(t){let n=this.name,r=this.name;e.provider===`mongodb`&&ct(n)&&(n=e.rawOpsMap[n],r=n.replace(`Args`,``)),Q(n)&&(n=`${n}Type`);let i=`export const ${C(r)}ObjectSchema = schema`;return`const schema: z.ZodType<Prisma.${n}> = ${t};\n\n ${i}`}addFinalWrappers({zodStringFields:e}){let t=[...e];return`${this.wrapWithZodObject(t)}.strict()`}generateImportPrismaStatement(){let t;if(e.isCustomPrismaClientOutputPath){let n=f.default.join(e.outputPath,`schemas`,`objects`),r=e.prismaClientOutputPath;t=f.default.relative(n,r).split(f.default.sep).join(f.default.posix.sep)}else t=e.prismaClientOutputPath;return`import type { Prisma } from '${t}';\n\n`}generateJsonSchemaImplementation(){let e=``;return this.hasJson&&(e+=`
|
|
92
|
-
`,e+=`const literalSchema = z.union([z.string(), z.number(), z.boolean()]);
|
|
93
|
-
`,e+=`const jsonSchema: z.ZodType<Prisma.InputJsonValue> = z.lazy(() =>
|
|
94
|
-
`,e+=` z.union([literalSchema, z.array(jsonSchema.nullable()), z.record(jsonSchema.nullable())])
|
|
95
|
-
`,e+=`);
|
|
96
|
-
|
|
97
|
-
`),e}generateObjectSchemaImportStatements(){let e=this.generateImportZodStatement();return e+=this.generateSchemaImports(),e+=`
|
|
98
|
-
|
|
99
|
-
`,e}generateSchemaImports(){return[...this.schemaImports].map(t=>{let{isModelQueryType:n,modelName:r,queryName:i}=this.checkIsModelQueryType(t);return n?`import { ${this.resolveModelQuerySchemaName(r,i)} } from '../${i}${r}.schema'`:e.enumNames.includes(t)?`import { ${C(t)}Schema } from '../enums/${C(t)}.schema'`:`import { ${C(t)}ObjectSchema } from './${C(t)}.schema'`}).join(`;\r
|
|
100
|
-
`)}checkIsModelQueryType(e){let t={FindManyArgs:`findMany`};for(let n of[`FindManyArgs`])if(e.includes(n)){let r=e.indexOf(n);return{isModelQueryType:!0,modelName:e.substring(0,r),queryName:t[n]}}return{isModelQueryType:!1}}resolveModelQuerySchemaName(e,t){return`${C(e)}${A(t)}Schema`}wrapWithZodUnion(e){let t=``;return t+=`z.union([`,t+=`
|
|
101
|
-
`,t+=` ${e.join(`,`)}`,t+=`
|
|
102
|
-
`,t+=`])`,t}wrapWithZodObject(e){let t=``;return t+=`z.object({`,t+=`
|
|
103
|
-
`,t+=` ${typeof e==`string`?e:e.join(`,
|
|
104
|
-
`)}`,t+=`
|
|
105
|
-
`,t+=`})`,t}resolveObjectSchemaName(){let t=this.name,n=this.name;return ct(t)&&(t=e.rawOpsMap[t],n=t.replace(`Args`,``)),C(n)}async generateModelSchemas(){for(let t of this.modelOperations){let{findUnique:n,findFirst:r,findMany:i,createOne:a,createMany:o,createManyAndReturn:s,deleteOne:c,updateOne:l,deleteMany:u,updateMany:d,updateManyAndReturn:p,upsertOne:m,aggregate:h,groupBy:g}=t,_=be(this.models,t.model),v=C(t.model),{selectImport:y,includeImport:b,selectZodSchemaLine:x,includeZodSchemaLine:S,selectZodSchemaLineLazy:w,includeZodSchemaLineLazy:ee}=this.resolveSelectIncludeImportAndZodSchemaLine(_),{orderByImport:T,orderByZodSchemaLine:E}=this.resolveOrderByWithRelationImportAndZodSchemaLine(_);if(n){let t=[y,b,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${n}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}FindUnique`,`z.object({ ${x} ${S} where: ${v}WhereUniqueInputObjectSchema })`)}`)}if(r){let t=[y,b,T,`import { ${v}WhereInputObjectSchema } from './objects/${v}WhereInput.schema'`,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`,`import { ${v}ScalarFieldEnumSchema } from './enums/${v}ScalarFieldEnum.schema'`];await Z(f.default.join(e.outputPath,`schemas/${r}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}FindFirst`,`z.object({ ${x} ${S} ${E} where: ${v}WhereInputObjectSchema.optional(), cursor: ${v}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${v}ScalarFieldEnumSchema).optional() })`)}`)}if(i){let t=[y,b,T,`import { ${v}WhereInputObjectSchema } from './objects/${v}WhereInput.schema'`,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`,`import { ${v}ScalarFieldEnumSchema } from './enums/${v}ScalarFieldEnum.schema'`];await Z(f.default.join(e.outputPath,`schemas/${i}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}FindMany`,`z.object({ ${w} ${ee} ${E} where: ${v}WhereInputObjectSchema.optional(), cursor: ${v}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${v}ScalarFieldEnumSchema).optional() })`)}`)}if(a){let t=[y,b,`import { ${v}CreateInputObjectSchema } from './objects/${v}CreateInput.schema'`,`import { ${v}UncheckedCreateInputObjectSchema } from './objects/${v}UncheckedCreateInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${a}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}CreateOne`,`z.object({ ${x} ${S} data: z.union([${v}CreateInputObjectSchema, ${v}UncheckedCreateInputObjectSchema]) })`)}`)}if(o){let t=[`import { ${v}CreateManyInputObjectSchema } from './objects/${v}CreateManyInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${o}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}CreateMany`,`z.object({ data: z.union([ ${v}CreateManyInputObjectSchema, z.array(${v}CreateManyInputObjectSchema) ]), ${e.provider===`mongodb`||e.provider===`sqlserver`?``:`skipDuplicates: z.boolean().optional()`} })`)}`)}if(s){let t=[`import { ${v}CreateManyAndReturnInputObjectSchema } from './objects/${v}CreateManyAndReturnInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${s}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}CreateManyAndReturn`,`z.object({ data: z.union([ ${v}CreateManyAndReturnInputObjectSchema, z.array(${v}CreateManyAndReturnInputObjectSchema) ]), ${e.provider===`mongodb`||e.provider===`sqlserver`?``:`skipDuplicates: z.boolean().optional()`} })`)}`)}if(c){let t=[y,b,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${c}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}DeleteOne`,`z.object({ ${x} ${S} where: ${v}WhereUniqueInputObjectSchema })`)}`)}if(u){let t=[`import { ${v}WhereInputObjectSchema } from './objects/${v}WhereInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${u}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}DeleteMany`,`z.object({ where: ${v}WhereInputObjectSchema.optional() })`)}`)}if(l){let t=[y,b,`import { ${v}UpdateInputObjectSchema } from './objects/${v}UpdateInput.schema'`,`import { ${v}UncheckedUpdateInputObjectSchema } from './objects/${v}UncheckedUpdateInput.schema'`,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${l}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}UpdateOne`,`z.object({ ${x} ${S} data: z.union([${v}UpdateInputObjectSchema, ${v}UncheckedUpdateInputObjectSchema]), where: ${v}WhereUniqueInputObjectSchema })`)}`)}if(d){let t=[`import { ${v}UpdateManyMutationInputObjectSchema } from './objects/${v}UpdateManyMutationInput.schema'`,`import { ${v}WhereInputObjectSchema } from './objects/${v}WhereInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${d}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}UpdateMany`,`z.object({ data: ${v}UpdateManyMutationInputObjectSchema, where: ${v}WhereInputObjectSchema.optional() })`)}`)}if(p){let t=[`import { ${v}UpdateManyAndReturnInputObjectSchema } from './objects/${v}UpdateManyAndReturnInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${p}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}UpdateManyAndReturn`,`z.object({ data: z.union([ ${v}UpdateManyAndReturnInputObjectSchema, z.array(${v}UpdateManyAndReturnInputObjectSchema) ]), ${e.provider===`mongodb`||e.provider===`sqlserver`?``:`skipDuplicates: z.boolean().optional()`} })`)}`)}if(m){let t=[y,b,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`,`import { ${v}CreateInputObjectSchema } from './objects/${v}CreateInput.schema'`,`import { ${v}UncheckedCreateInputObjectSchema } from './objects/${v}UncheckedCreateInput.schema'`,`import { ${v}UpdateInputObjectSchema } from './objects/${v}UpdateInput.schema'`,`import { ${v}UncheckedUpdateInputObjectSchema } from './objects/${v}UncheckedUpdateInput.schema'`];await Z(f.default.join(e.outputPath,`schemas/${m}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}Upsert`,`z.object({ ${x} ${S} where: ${v}WhereUniqueInputObjectSchema, create: z.union([ ${v}CreateInputObjectSchema, ${v}UncheckedCreateInputObjectSchema ]), update: z.union([ ${v}UpdateInputObjectSchema, ${v}UncheckedUpdateInputObjectSchema ]) })`)}`)}if(h){let t=[T,`import { ${v}WhereInputObjectSchema } from './objects/${v}WhereInput.schema'`,`import { ${v}WhereUniqueInputObjectSchema } from './objects/${v}WhereUniqueInput.schema'`],n=[];this.aggregateOperationSupport[v]&&(this.aggregateOperationSupport[v].count&&(t.push(`import { ${v}CountAggregateInputObjectSchema } from './objects/${v}CountAggregateInput.schema'`),n.push(`_count: z.union([ z.literal(true), ${v}CountAggregateInputObjectSchema ]).optional()`)),this.aggregateOperationSupport[v].min&&(t.push(`import { ${v}MinAggregateInputObjectSchema } from './objects/${v}MinAggregateInput.schema'`),n.push(`_min: ${v}MinAggregateInputObjectSchema.optional()`)),this.aggregateOperationSupport[v].max&&(t.push(`import { ${v}MaxAggregateInputObjectSchema } from './objects/${v}MaxAggregateInput.schema'`),n.push(`_max: ${v}MaxAggregateInputObjectSchema.optional()`)),this.aggregateOperationSupport[v].avg&&(t.push(`import { ${v}AvgAggregateInputObjectSchema } from './objects/${v}AvgAggregateInput.schema'`),n.push(`_avg: ${v}AvgAggregateInputObjectSchema.optional()`)),this.aggregateOperationSupport[v].sum&&(t.push(`import { ${v}SumAggregateInputObjectSchema } from './objects/${v}SumAggregateInput.schema'`),n.push(`_sum: ${v}SumAggregateInputObjectSchema.optional()`))),await Z(f.default.join(e.outputPath,`schemas/${h}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}Aggregate`,`z.object({ ${E} where: ${v}WhereInputObjectSchema.optional(), cursor: ${v}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), ${n.join(`, `)} })`)}`)}if(g){let t=[`import { ${v}WhereInputObjectSchema } from './objects/${v}WhereInput.schema'`,`import { ${v}OrderByWithAggregationInputObjectSchema } from './objects/${v}OrderByWithAggregationInput.schema'`,`import { ${v}ScalarWhereWithAggregatesInputObjectSchema } from './objects/${v}ScalarWhereWithAggregatesInput.schema'`,`import { ${v}ScalarFieldEnumSchema } from './enums/${v}ScalarFieldEnum.schema'`];await Z(f.default.join(e.outputPath,`schemas/${g}.schema.ts`),`${this.generateImportStatements(t)}${this.generateExportSchemaStatement(`${v}GroupBy`,`z.object({ where: ${v}WhereInputObjectSchema.optional(), orderBy: z.union([${v}OrderByWithAggregationInputObjectSchema, ${v}OrderByWithAggregationInputObjectSchema.array()]).optional(), having: ${v}ScalarWhereWithAggregatesInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), by: z.array(${v}ScalarFieldEnumSchema) })`)}`)}}}generateImportStatements(e){let t=this.generateImportZodStatement();return t+=e?.filter(e=>!!e).join(`;\r
|
|
106
|
-
`)??``,t+=`
|
|
107
|
-
|
|
108
|
-
`,t}resolveSelectIncludeImportAndZodSchemaLine(t){let{name:n}=t,r=R(t),i=e.isGenerateSelect?`import { ${C(n)}SelectObjectSchema } from './objects/${C(n)}Select.schema'`:``,a=e.isGenerateInclude&&r?`import { ${C(n)}IncludeObjectSchema } from './objects/${C(n)}Include.schema'`:``,o=``,s=``,c=``,l=``;if(e.isGenerateSelect){let e=`${C(n)}SelectObjectSchema.optional()`;o=`select: ${e},`,c=`select: z.lazy(() => ${e}),`}if(e.isGenerateInclude&&r){let e=`${C(n)}IncludeObjectSchema.optional()`;s=`include: ${e},`,l=`include: z.lazy(() => ${e}),`}return{selectImport:i,includeImport:a,selectZodSchemaLine:o,includeZodSchemaLine:s,selectZodSchemaLineLazy:c,includeZodSchemaLineLazy:l}}resolveOrderByWithRelationImportAndZodSchemaLine(t){let{name:n}=t,r=``;return r=[`postgresql`,`mysql`].includes(e.provider)&&e.previewFeatures?.includes(`fullTextSearch`)?`${C(n)}OrderByWithRelationAndSearchRelevanceInput`:`${C(n)}OrderByWithRelationInput`,{orderByImport:`import { ${r}ObjectSchema } from './objects/${r}.schema'`,orderByZodSchemaLine:`orderBy: z.union([${r}ObjectSchema, ${r}ObjectSchema.array()]).optional(),`}}};async function lt(e,t){let n=[...e,...t];$.enumNames=n.map(e=>e.name)??[],await new $({enumTypes:n}).generateEnumSchemas()}async function ut(e){for(let t=0;t<e.length;t+=1){let n=e[t]?.fields,r=e[t]?.name;await new $({name:r,fields:n}).generateObjectSchema()}}async function dt(e,t,n){await new $({models:e,modelOperations:t,aggregateOperationSupport:n}).generateModelSchemas()}async function ft(){await $.generateIndex()}function pt(e,t,n){let r=mt(t,n);for(let t of r)e.push(t)}function mt(e,t){let n=[];for(let r of e){let{name:e,fields:i}=r,a=[];for(let e of i){let{name:t,isList:n,type:r}=e;if(B(e)){let e={name:t,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`Boolean`,location:`scalar`},{isList:!1,type:n?`${r}FindManyArgs`:`${r}DefaultArgs`,location:`inputObjectTypes`,namespace:`prisma`}]};a.push(e)}}if(!R(r))continue;if(z(r)){let n=[{isList:!1,type:`Boolean`,location:`scalar`}];t&&n.push({isList:!1,type:`${e}CountOutputTypeDefaultArgs`,location:`inputObjectTypes`,namespace:`prisma`});let r={name:`_count`,isRequired:!1,isNullable:!1,inputTypes:n};a.push(r)}let o={name:`${e}Include`,constraints:{maxNumFields:null,minNumFields:null},fields:a};n.push(o)}return n}function ht(e,t,n,r){let i=gt(t,n,r);for(let t of i)e.push(t)}function gt(e,t,n){let r=[];for(let i of e){let{name:e}=i,a=[];if(t){let t={name:`select`,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`${e}Select`,location:`inputObjectTypes`,namespace:`prisma`}]};a.push(t)}let o=R(i);if(n&&o){let t={name:`include`,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`${e}Include`,location:`inputObjectTypes`,namespace:`prisma`}]};a.push(t)}let s={name:`${e}DefaultArgs`,constraints:{maxNumFields:null,minNumFields:null},fields:a};r.push(s)}return r}function _t(e,t,n){let r=vt(t),i=[yt(r),bt(r),xt(n)].flat();for(let t of i)e.push(t)}function vt(e){return e.filter(({name:e})=>e.includes(`CountOutputType`))}function yt(e){let t=[];for(let n of e){let{name:e,fields:r}=n,i={name:`${e}Select`,constraints:{maxNumFields:null,minNumFields:null},fields:r.map(({name:e})=>({name:e,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`Boolean`,location:`scalar`}]}))};t.push(i)}return t}function bt(e){let t=[];for(let n of e){let{name:e}=n,r={name:`${e}DefaultArgs`,constraints:{maxNumFields:null,minNumFields:null},fields:[{name:`select`,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`${e}Select`,location:`inputObjectTypes`,namespace:`prisma`}]}]};t.push(r)}return t}function xt(e){let t=[];for(let n of e){let{name:e,fields:r}=n,i=[];for(let e of r){let{name:t,isList:n,type:r}=e,a=B(e),o={name:t,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`Boolean`,location:`scalar`}]};if(a){let e={isList:!1,type:n?`${r}FindManyArgs`:`${r}DefaultArgs`,location:`inputObjectTypes`,namespace:`prisma`};o.inputTypes.push(e)}i.push(o)}if(z(n)){let t={name:`_count`,isRequired:!1,isNullable:!1,inputTypes:[{isList:!1,type:`Boolean`,location:`scalar`},{isList:!1,type:`${e}CountOutputTypeDefaultArgs`,location:`inputObjectTypes`,namespace:`prisma`}]};i.push(t)}let a={name:`${e}Select`,constraints:{maxNumFields:null,minNumFields:null},fields:i};t.push(a)}return t}function St(e){e.map(e=>(e.name.includes(`WhereUniqueInput`)&&e.constraints.fields?.length>0&&(e.fields=e.fields.map(t=>(e.constraints.fields?.includes(t.name)&&(t.isRequired=!0),t))),e))}function Ct(e,t,n,r,i,a){i===`mongodb`&&it(r,t,e),qe(e,t),a.isGenerateSelect&&(_t(e,t,n),$.setIsGenerateSelect(!0)),(a.isGenerateSelect||a.isGenerateInclude)&&ht(e,n,a.isGenerateSelect,a.isGenerateInclude),a.isGenerateInclude&&(pt(e,n,a.isGenerateSelect),$.setIsGenerateInclude(!0)),St(e)}async function wt(e){console.log(`[STORM]: Running the Storm Software - Prisma tRPC generator
|
|
109
|
-
`);let t=await F();console.log(`[STORM]: Validating configuration options
|
|
110
|
-
`);let n=t.parseEnvValue(e.generator.output),r=await te.safeParseAsync(e.generator.config);if(!r.success)throw Error(`Invalid options passed`);let i=r.data,a=e=>{i.debug&&console.log(`[STORM]: ${e} \n`)};a(`Using configuration parameters: \n${JSON.stringify(i)}`),a(`Preparing output directory: ${n}`),await(0,u.removeDirectory)(n),await(0,u.createDirectory)(n),a(`Finding Prisma Client generator`);let o=e.otherGenerators.find(e=>t.parseEnvValue(e.provider)===`prisma-client-js`);if(!o)throw Error("No Prisma Client generator found. Please add `prisma-client-js` to your generator list.");a(`Generating Prisma Client DMMF`);let s=await t.getDMMF({datamodel:e.datamodel,previewFeatures:o?.previewFeatures}),c=s.mappings.modelOperations,p=s.schema.inputObjectTypes.prisma,m=s.schema.outputObjectTypes.prisma,h=s.schema.enumTypes,g=s.datamodel.models,_=[],v=[];if(i.withZod!==!1){a(`Generating Zod schemas`);let n=t.parseEnvValue(e.generator.output);await(0,u.createDirectory)(n),$.setOutputPath(n),o?.isCustomOutput&&$.setPrismaClientOutputPath(o.output?.value),await He(g,(0,d.joinPaths)(n,`schemas`,`models`),i,e),Qe(g,c,h,_,v),await lt(h.prisma,h.model);let r=e.datasources?.[0];if(!r)throw Error(`No datasource found`);let s=o?.previewFeatures;$.provider=r.provider,$.previewFeatures=s,Ct(p,m,g,c,r.provider,{isGenerateSelect:!0,isGenerateInclude:!0});let l=Je(p);rt(p,_,v),await ut(p),await dt(g,c,l),await ft()}else a(`Skipping Zod schemas generation`);let y=[],b=[],x=[];s.mappings.modelOperations.forEach(e=>{let{model:t,plural:n,...r}=e;for(let[e,t]of Object.entries(r))[`findUnique`,`findUniqueOrThrow`,`findFirst`,`findFirstOrThrow`,`findRaw`,`findMany`,`aggregateRaw`,`count`,`aggregate`,`groupBy`].includes(e)&&y.push(t),[`createOne`,`createMany`,`createManyAndReturn`,`deleteOne`,`deleteMany`,`updateOne`,`updateMany`,`updateManyAndReturn`,`upsertOne`].includes(e)&&b.push(t)}),y.sort(),b.sort(),x.sort(),i.withShield&&!(typeof i.withShield==`string`&&((0,l.existsSync)((0,d.joinPaths)(n,i.withShield))||(0,l.existsSync)((0,d.joinPaths)(n,`./${i.withShield}.ts`))||(0,l.existsSync)((0,d.joinPaths)(n,i.withShield,`./shield.ts`))))?(a(`Generating tRPC Shield source file to ${n}`),await Z((0,d.joinPaths)(n,`./shield.ts`),await Be({queries:y,mutations:b,subscriptions:x},i,e,n))):a(`Skipping tRPC Shield generation`),a(`Generating tRPC source code for ${g.length} models`),i.trpcOptions&&typeof i.trpcOptions==`boolean`&&(a(`Generating tRPC options source file to ${n}`),await Z((0,d.joinPaths)(n,`./options.ts`),Ve(i,e,n))),Le(g,_),a(`Generating tRPC export file`),await Me(O.createSourceFile(f.default.resolve(n,`trpc.ts`),void 0,{overwrite:!0}),i,e,n),a(`Generating tRPC app router`);let S=O.createSourceFile(f.default.resolve(n,`routers`,`index.ts`),void 0,{overwrite:!0});a(`Generating tRPC router imports`),K({sourceFile:S});let w=[];for(let e of c){let{model:t,...r}=e;if(_.includes(t)){a(`Skipping model ${t} as it is hidden`);continue}if(!t){a(`Skipping model ${t} as it is not defined`);continue}let o=Object.keys(r).filter(e=>i.generateModelActions.some(t=>t===e.replace(`One`,``)));if(!o.length){a(`Skipping model ${t} as it has no actions to generate`);continue}let s=(0,ee.default)(C(t));a(`Generating tRPC router for model ${t}`),je(S,s,t);let c=O.createSourceFile(f.default.resolve(n,`routers`,`${C(t)}.router.ts`),void 0,{overwrite:!0});K({sourceFile:c,config:i}),i.withZod&&(a(`Generating Zod schemas imports`),Pe(c,t,o)),c.addStatements(`
|
|
111
|
-
export const ${s}Router = t.router({`);for(let e of o){let n=r[e];if(n){let r=e.replace(`OrThrow`,``);Ne(c,n,q(r,t),t,e,r,i)}}c.addStatements(`
|
|
112
|
-
})`),c.formatText({indentSize:2}),w.push(`
|
|
113
|
-
${C(t)}: ${s}Router`),a(`Generated tRPC router for model ${t} with ${o.length} actions`)}a(`Generating tRPC app router`),S.addStatements(`
|
|
114
|
-
export const appRouter = t.router({${w.join()}});
|
|
115
|
-
|
|
116
|
-
export type AppRouter = typeof appRouter;`),S.formatText({indentSize:2}),a(`Saving tRPC router source files to disk`),await O.save(),a(`Storm Software - Prisma tRPC generator completed successfully`)}ve().then(e=>{e.generatorHandler({onManifest:()=>({defaultOutput:`./generated`,prettyName:`Storm Software - Prisma tRPC Generator`,requiresGenerators:[`prisma-client-js`]}),onGenerate:wt})}).catch(e=>{console.error(`An error occured while generating prisma tRPC source code: ${e}`)});
|
|
1
|
+
const e=require(`./utils/get-prisma-internals.cjs`),t=require(`./prisma-generator.cjs`);e.getPrismaGeneratorHelper().then(e=>{e.generatorHandler({onManifest:()=>({defaultOutput:`./generated`,prettyName:`Storm Software - Prisma tRPC Generator`,requiresGenerators:[`prisma-client-js`]}),onGenerate:t.generate})}).catch(e=>{console.error(`An error occured while generating prisma tRPC source code: ${e}`)});
|