@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 205 lines 7.6 KB
Raw
1 import type { Contract, ContractField, ContractModel } from "@prisma/orm-postgres/contract/types";
2 import type { SqlStorage } from "@prisma/orm-postgres/family-contract/types";
3 import type { DefaultModelRow } from "@prisma/orm-postgres/orm-client";
4 import * as Data from "effect/Data";
5 import * as Schema from "effect/Schema";
6
7 /** An unsupported contract field requires an explicit codec mapping. */
8 export class SchemaError extends Data.TaggedError("Prisma.SchemaError")<{
9 readonly field: string;
10 readonly message: string;
11 }> {}
12
13 /** A custom codec's row validator and its standalone TypeScript expression. */
14 export interface CodecSchema {
15 readonly schema: Schema.Codec<unknown, unknown>;
16 /** Expression using `Schema` or names declared by `imports`. */
17 readonly expression: string;
18 /** Import declarations copied into standalone schema modules. */
19 readonly imports?: readonly string[];
20 }
21
22 export interface SchemaOptions {
23 readonly codecs?: Readonly<Record<string, CodecSchema>>;
24 }
25
26 export type ModelSchemas<C extends Contract<SqlStorage>> = {
27 readonly [Ns in keyof C["domain"]["namespaces"] & string]: {
28 readonly [M in keyof C["domain"]["namespaces"][Ns]["models"] & string]: Schema.Codec<
29 DefaultModelRow<C, M, Ns>,
30 unknown
31 >;
32 };
33 };
34
35 const builtin = (schema: Schema.Codec<unknown, unknown>, expression: string): CodecSchema => ({
36 schema,
37 expression,
38 });
39 const text = builtin(Schema.String, "Schema.String");
40 const int = builtin(Schema.Int, "Schema.Int");
41 const float = builtin(Schema.Number, "Schema.Number");
42 const bigint = builtin(Schema.BigInt, "Schema.BigInt");
43 const codecs: Readonly<Record<string, CodecSchema>> = {
44 "pg/text@1": text,
45 "sql/text@1": text,
46 "pg/date-string@1": text,
47 "pg/timestamp-string@1": text,
48 "pg/timestamptz-string@1": text,
49 "pg/time-string@1": text,
50 "pg/char@1": text,
51 "pg/varchar@1": text,
52 "sql/char@1": text,
53 "sql/varchar@1": text,
54 "pg/inet@1": text,
55 "pg/interval@1": text,
56 "pg/timetz@1": text,
57 "pg/bit@1": text,
58 "pg/varbit@1": text,
59 "pg/int@1": int,
60 "sql/int@1": int,
61 "pg/int4@1": int,
62 "pg/int2@1": int,
63 "pg/int8number@1": int,
64 "pg/int8@1": bigint,
65 "pg/unboundedint@1": bigint,
66 "pg/float@1": float,
67 "sql/float@1": float,
68 "pg/float4@1": float,
69 "pg/float8@1": float,
70 "pg/bool@1": builtin(Schema.Boolean, "Schema.Boolean"),
71 "pg/bytea@1": builtin(Schema.Uint8Array, "Schema.Uint8Array"),
72 "pg/uuid@1": builtin(
73 Schema.String.check(Schema.isGUID()),
74 "Schema.String.check(Schema.isGUID())",
75 ),
76 "pg/numeric@1": builtin(
77 Schema.String.check(
78 Schema.isPattern(
79 /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$|^(?:NaN|Infinity|-Infinity)$/,
80 ),
81 ),
82 "Schema.String.check(Schema.isPattern(/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$|^(?:NaN|Infinity|-Infinity)$/))",
83 ),
84 "pg/json@1": builtin(Schema.Json, "Schema.Json"),
85 "pg/jsonb@1": builtin(Schema.Json, "Schema.Json"),
86 };
87
88 function fieldSchema(
89 contract: Contract<SqlStorage>,
90 field: ContractField,
91 name: string,
92 options: SchemaOptions,
93 ): CodecSchema {
94 const fail = (message: string): never => {
95 throw new SchemaError({ field: name, message: `${name}: ${message}` });
96 };
97 if (field.type.kind !== "scalar")
98 return fail(`unsupported ${field.type.kind} field; use an explicit application schema`);
99 const codec = field.type.codecId;
100 let value: CodecSchema | undefined =
101 options.codecs && Object.hasOwn(options.codecs, codec) ? options.codecs[codec] : undefined;
102 if (!value && field.valueSet) {
103 const ref = field.valueSet;
104 if (ref.spaceId || ref.entityKind !== "enum")
105 return fail("external value sets require an explicit codec mapping");
106 const enumeration = contract.domain.namespaces[ref.namespaceId]?.enum?.[ref.entityName];
107 if (!enumeration) return fail(`enum ${ref.namespaceId}.${ref.entityName} is missing`);
108 const literals = enumeration.members.map((member) => member.value);
109 if (
110 !literals.every(
111 (literal): literal is string | number | boolean =>
112 typeof literal === "string" ||
113 typeof literal === "number" ||
114 typeof literal === "boolean",
115 )
116 ) {
117 return fail("non-primitive enum values require an explicit codec mapping");
118 }
119 value = builtin(Schema.Literals(literals), `Schema.Literals(${JSON.stringify(literals)})`);
120 }
121 value ??= Object.hasOwn(codecs, codec) ? codecs[codec] : undefined;
122 if (!value)
123 return fail(
124 `unsupported codec ${codec}; supply options.codecs[${JSON.stringify(codec)}] with a schema and standalone expression`,
125 );
126 let { schema, expression } = value;
127 if (field.many) {
128 schema = Schema.Array(schema);
129 expression = `Schema.Array(${expression})`;
130 }
131 if (field.dict) {
132 schema = Schema.Record(Schema.String, schema);
133 expression = `Schema.Record(Schema.String, ${expression})`;
134 }
135 if (field.nullable) {
136 schema = Schema.NullOr(schema);
137 expression = `Schema.NullOr(${expression})`;
138 }
139 return { ...value, schema, expression };
140 }
141
142 function rowFields(model: ContractModel, name: string) {
143 if (model.base || model.variants || model.discriminator) {
144 throw new SchemaError({
145 field: name,
146 message: `${name}: variant and inherited models require an explicit application schema`,
147 });
148 }
149 return model.fields;
150 }
151
152 /**
153 * Derive scalar row validators without opening a database connection.
154 * Relations and mutation defaults are not row fields. These are database row
155 * schemas, not create/update inputs or public API response definitions.
156 */
157 export function makeSchemas<C extends Contract<SqlStorage>>(
158 contract: C,
159 options: SchemaOptions = {},
160 ): ModelSchemas<C> {
161 return Object.fromEntries(
162 Object.entries(contract.domain.namespaces).map(([ns, namespace]) => [
163 ns,
164 Object.fromEntries(
165 Object.entries(namespace.models).map(([model, definition]) => [
166 model,
167 Schema.Struct(
168 Object.fromEntries(
169 Object.entries(rowFields(definition, `${ns}.${model}`)).map(([name, field]) => [
170 name,
171 fieldSchema(contract, field, `${ns}.${model}.${name}`, options).schema,
172 ]),
173 ),
174 ),
175 ]),
176 ),
177 ]),
178 ) as unknown as ModelSchemas<C>;
179 }
180
181 const propertyKey = (name: string) =>
182 name === "__proto__" ? '["__proto__"]' : JSON.stringify(name);
183
184 /** Emit a standalone module importing only Effect and explicit custom mappings. */
185 export function emitSchemas(contract: Contract<SqlStorage>, options: SchemaOptions = {}): string {
186 const imports = new Set<string>();
187 const namespaces = Object.entries(contract.domain.namespaces)
188 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
189 .map(([ns, namespace]) => {
190 const models = Object.entries(namespace.models)
191 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
192 .map(([model, definition]) => {
193 const fields = Object.entries(rowFields(definition, `${ns}.${model}`))
194 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
195 .map(([name, field]) => {
196 const mapped = fieldSchema(contract, field, `${ns}.${model}.${name}`, options);
197 for (const statement of mapped.imports ?? []) imports.add(statement);
198 return ` ${propertyKey(name)}: ${mapped.expression},`;
199 });
200 return ` ${propertyKey(model)}: Schema.Struct({\n${fields.join("\n")}\n }),`;
201 });
202 return ` ${propertyKey(ns)}: {\n${models.join("\n")}\n },`;
203 });
204 return `// Generated by alchemy prisma generate.\nimport * as Schema from "effect/Schema";\n${[...imports].sort().join("\n")}\nexport const schemas = {\n${namespaces.join("\n")}\n} as const;\n`;
205 }