@zenstackhq/zod 3.5.0-beta.4 → 3.5.0-beta.5

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/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { SchemaDef, GetModels, GetModelFields, GetModelFieldType, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefFieldType, TypeDefFieldIsArray, TypeDefFieldIsOptional, FieldIsArray, ModelFieldIsOptional, FieldIsRelation, FieldHasDefault, FieldIsComputed, FieldIsDelegateDiscriminator, AttributeApplication } from '@zenstackhq/schema';
1
+ import { SchemaDef, GetModels, GetModelFields, GetModelFieldType, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefFieldType, TypeDefFieldIsArray, TypeDefFieldIsOptional, FieldIsArray, ModelFieldIsOptional, FieldIsRelation, FieldHasDefault, FieldIsComputed, FieldIsDelegateDiscriminator, AttributeApplication, Expression } from '@zenstackhq/schema';
2
2
  import z, { z as z$1 } from 'zod';
3
3
  import Decimal from 'decimal.js';
4
4
 
@@ -38,14 +38,145 @@ type ZodOptionalAndNullableIf<T extends z.ZodType, Condition extends boolean> =
38
38
  type ZodOptionalIf<T extends z.ZodType, Condition extends boolean> = Condition extends true ? z.ZodOptional<T> : T;
39
39
  type ZodNullableIf<T extends z.ZodType, Condition extends boolean> = Condition extends true ? z.ZodNullable<T> : T;
40
40
  type ZodArrayIf<T extends z.ZodType, Condition extends boolean> = Condition extends true ? z.ZodArray<T> : T;
41
+ /**
42
+ * The non-relation scalar fields of a model (excludes relation fields and
43
+ * foreign-key fields that back a relation).
44
+ */
45
+ type ScalarModelFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
46
+ [Field in GetModelFields<Schema, Model> as FieldIsRelation<Schema, Model, Field> extends true ? never : Field]: Field;
47
+ };
48
+ /**
49
+ * The relation fields of a model.
50
+ */
51
+ type RelationModelFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
52
+ [Field in GetModelFields<Schema, Model> as FieldIsRelation<Schema, Model, Field> extends true ? Field : never]: Field;
53
+ };
54
+ /**
55
+ * For a relation field, resolve the related model name.
56
+ */
57
+ type RelatedModel<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends GetModels<Schema> ? GetModelFieldType<Schema, Model, Field> : never;
58
+ /**
59
+ * ORM-style query options accepted by `makeModelSchema`.
60
+ *
61
+ * Exactly mirrors the `select` / `include` / `omit` vocabulary:
62
+ * - `select` — pick specific fields (scalars and/or relations). Mutually
63
+ * exclusive with `include` and `omit`.
64
+ * - `include` — start with all scalar fields, then add the named relation
65
+ * fields. Can be combined with `omit`.
66
+ * - `omit` — remove named scalar fields from the default scalar set.
67
+ * Can be combined with `include`, mutually exclusive with
68
+ * `select`.
69
+ */
70
+ type ModelSchemaOptions<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
71
+ /**
72
+ * Pick only the listed fields. Values can be `true` (include with
73
+ * default shape) or a nested options object (for relation fields).
74
+ */
75
+ select: {
76
+ [Field in GetModelFields<Schema, Model>]?: FieldIsRelation<Schema, Model, Field> extends true ? boolean | ModelSchemaOptions<Schema, RelatedModel<Schema, Model, Field>> : boolean;
77
+ };
78
+ include?: never;
79
+ omit?: never;
80
+ } | {
81
+ select?: never;
82
+ /**
83
+ * Add the listed relation fields on top of the scalar fields.
84
+ * Values can be `true` / `{}` (default shape) or a nested options
85
+ * object.
86
+ */
87
+ include?: {
88
+ [Field in keyof RelationModelFields<Schema, Model>]?: Field extends GetModelFields<Schema, Model> ? boolean | ModelSchemaOptions<Schema, RelatedModel<Schema, Model, Field>> : never;
89
+ };
90
+ /**
91
+ * Remove the listed scalar fields from the output.
92
+ */
93
+ omit?: {
94
+ [Field in keyof ScalarModelFields<Schema, Model>]?: boolean;
95
+ };
96
+ };
97
+ /**
98
+ * Narrows `Field` so it can safely index `GetModelFieldsShape`. The mapped
99
+ * type uses a `as`-remapping clause, so TypeScript widens the key set and
100
+ * `Field extends GetModelFields<…>` alone is not enough for indexing.
101
+ */
102
+ type FieldInShape<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = Field & keyof GetModelFieldsShape<Schema, Model>;
103
+ /**
104
+ * Zod shape produced when a relation field is included via `include: { field:
105
+ * true }` or `select: { field: true }` — identical to how the existing
106
+ * `makeModelSchema` (no-options) represents relation fields: optional, carries
107
+ * array-ness and nullability from the field definition.
108
+ */
109
+ type RelationFieldZodDefault<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldsShape<Schema, Model>[FieldInShape<Schema, Model, Field>];
110
+ /**
111
+ * Zod shape for a relation field included with nested options. We recurse
112
+ * into `GetModelSchemaShapeWithOptions` for the related model, then re-apply
113
+ * the same optional/array/nullable wrappers as the default relation field.
114
+ */
115
+ type RelationFieldZodWithOptions<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Options> = RelatedModel<Schema, Model, Field> extends GetModels<Schema> ? ZodNullableIf<z.ZodOptional<ZodArrayIf<z.ZodObject<GetModelSchemaShapeWithOptions<Schema, RelatedModel<Schema, Model, Field>, Options>, z.core.$strict>, FieldIsArray<Schema, Model, Field>>>, ModelFieldIsOptional<Schema, Model, Field>> : never;
116
+ /**
117
+ * Resolve the Zod type for a single field given a select-entry value (`true`
118
+ * or a nested options object).
119
+ */
120
+ type SelectEntryToZod<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Value> = Value extends boolean ? GetModelFieldsShape<Schema, Model>[FieldInShape<Schema, Model, Field>] : Value extends object ? RelationFieldZodWithOptions<Schema, Model, Field, Value> : never;
121
+ /**
122
+ * Build the Zod shape for the `select` branch: only the listed fields,
123
+ * recursing into relations when given nested options.
124
+ */
125
+ type BuildSelectShape<Schema extends SchemaDef, Model extends GetModels<Schema>, S extends Record<string, unknown>> = {
126
+ [Field in keyof S & GetModelFields<Schema, Model> as S[Field] extends false ? never : Field]: SelectEntryToZod<Schema, Model, Field, S[Field]>;
127
+ };
128
+ /**
129
+ * Build the Zod shape for the `include` + `omit` branch:
130
+ * - All scalar fields, minus any that appear in `omit` with value `true`.
131
+ * - Plus the relation fields listed in `include`.
132
+ */
133
+ type BuildIncludeOmitShape<Schema extends SchemaDef, Model extends GetModels<Schema>, I extends Record<string, unknown> | undefined, O extends Record<string, unknown> | undefined> = {
134
+ [Field in GetModelFields<Schema, Model> as FieldIsRelation<Schema, Model, Field> extends true ? never : O extends object ? Field extends keyof O ? O[Field] extends true ? never : Field : Field : Field]: GetModelFieldsShape<Schema, Model>[FieldInShape<Schema, Model, Field>];
135
+ } & (I extends object ? {
136
+ [Field in keyof I & GetModelFields<Schema, Model> as I[Field] extends false ? never : Field]: I[Field] extends object ? RelationFieldZodWithOptions<Schema, Model, Field, I[Field]> : RelationFieldZodDefault<Schema, Model, Field>;
137
+ } : {});
138
+ /**
139
+ * The top-level conditional that maps options → Zod shape.
140
+ *
141
+ * - No options / undefined → existing `GetModelFieldsShape` (no change).
142
+ * - `{ select: S }` → `BuildSelectShape`.
143
+ * - `{ include?, omit? }` → `BuildIncludeOmitShape`.
144
+ */
145
+ type GetModelSchemaShapeWithOptions<Schema extends SchemaDef, Model extends GetModels<Schema>, Options> = Options extends {
146
+ select: infer S extends Record<string, unknown>;
147
+ } ? BuildSelectShape<Schema, Model, S> : Options extends {
148
+ include?: infer I extends Record<string, unknown> | undefined;
149
+ omit?: infer O extends Record<string, unknown> | undefined;
150
+ } ? BuildIncludeOmitShape<Schema, Model, I, O> : GetModelFieldsShape<Schema, Model>;
41
151
 
42
152
  declare function createSchemaFactory<Schema extends SchemaDef>(schema: Schema): SchemaFactory<Schema>;
43
153
  declare class SchemaFactory<Schema extends SchemaDef> {
44
154
  private readonly schema;
45
155
  constructor(_schema: Schema);
46
156
  makeModelSchema<Model extends GetModels<Schema>>(model: Model): z.ZodObject<GetModelFieldsShape<Schema, Model>, z.core.$strict>;
157
+ makeModelSchema<Model extends GetModels<Schema>, Options extends ModelSchemaOptions<Schema, Model>>(model: Model, options: Options): z.ZodObject<GetModelSchemaShapeWithOptions<Schema, Model, Options>, z.core.$strict>;
47
158
  makeModelCreateSchema<Model extends GetModels<Schema>>(model: Model): z.ZodObject<GetModelCreateFieldsShape<Schema, Model>, z.core.$strict>;
48
159
  makeModelUpdateSchema<Model extends GetModels<Schema>>(model: Model): z.ZodObject<GetModelUpdateFieldsShape<Schema, Model>, z.core.$strict>;
160
+ /**
161
+ * Internal loose options shape used at runtime (we've already validated the
162
+ * type-level constraints via the overload signatures).
163
+ */
164
+ private buildFieldsWithOptions;
165
+ /**
166
+ * Returns the set of scalar field names that will be present in the
167
+ * resulting schema after applying `options`. Used by `addCustomValidation`
168
+ * to skip `@@validate` rules that reference an absent field.
169
+ *
170
+ * Only scalar fields matter here because `@@validate` conditions are
171
+ * restricted by the ZModel compiler to scalar fields of the same model.
172
+ */
173
+ private buildPresentFields;
174
+ /**
175
+ * Build the inner Zod schema for a relation field, optionally with nested
176
+ * query options. Does NOT apply cardinality/optional wrappers — the caller
177
+ * does that.
178
+ */
179
+ private makeRelationFieldSchema;
49
180
  private makeScalarFieldSchema;
50
181
  private makeJsonSchema;
51
182
  private applyCardinality;
@@ -62,7 +193,27 @@ declare function addNumberValidation(schema: z$1.ZodNumber, attributes: readonly
62
193
  declare function addBigIntValidation(schema: z$1.ZodBigInt, attributes: readonly AttributeApplication[] | undefined): z$1.ZodSchema;
63
194
  declare function addDecimalValidation(schema: z$1.ZodType<Decimal> | z$1.ZodString, attributes: readonly AttributeApplication[] | undefined, addExtraValidation: boolean): z$1.ZodSchema;
64
195
  declare function addListValidation(schema: z$1.ZodArray<any>, attributes: readonly AttributeApplication[] | undefined): z$1.ZodSchema;
65
- declare function addCustomValidation(schema: z$1.ZodSchema, attributes: readonly AttributeApplication[] | undefined): z$1.ZodSchema;
196
+ /**
197
+ * Recursively collects all field names referenced by `kind: 'field'` nodes
198
+ * inside an expression tree.
199
+ */
200
+ declare function collectFieldRefs(expr: Expression): Set<string>;
201
+ /**
202
+ * Applies `@@validate` rules from `attributes` to `schema` as Zod refinements.
203
+ *
204
+ * When `presentFields` is provided, only rules whose every field reference is
205
+ * present in the set are applied. Rules that reference a field absent from the
206
+ * set are silently skipped — they cannot be evaluated correctly against a
207
+ * partial payload (e.g. when `select` or `omit` has been used).
208
+ *
209
+ * Omit `presentFields` (or pass `undefined`) to apply all rules
210
+ * unconditionally, which is the correct behaviour for full-model schemas.
211
+ *
212
+ * Note: `@@validate` conditions are restricted by the ZModel compiler to
213
+ * scalar fields of the same model only — relation fields are a compile error.
214
+ * A flat field-name set is therefore sufficient.
215
+ */
216
+ declare function addCustomValidation(schema: z$1.ZodSchema, attributes: readonly AttributeApplication[] | undefined, presentFields?: ReadonlySet<string>): z$1.ZodSchema;
66
217
 
67
218
  declare const utils_addBigIntValidation: typeof addBigIntValidation;
68
219
  declare const utils_addCustomValidation: typeof addCustomValidation;
@@ -70,8 +221,9 @@ declare const utils_addDecimalValidation: typeof addDecimalValidation;
70
221
  declare const utils_addListValidation: typeof addListValidation;
71
222
  declare const utils_addNumberValidation: typeof addNumberValidation;
72
223
  declare const utils_addStringValidation: typeof addStringValidation;
224
+ declare const utils_collectFieldRefs: typeof collectFieldRefs;
73
225
  declare namespace utils {
74
- export { utils_addBigIntValidation as addBigIntValidation, utils_addCustomValidation as addCustomValidation, utils_addDecimalValidation as addDecimalValidation, utils_addListValidation as addListValidation, utils_addNumberValidation as addNumberValidation, utils_addStringValidation as addStringValidation };
226
+ export { utils_addBigIntValidation as addBigIntValidation, utils_addCustomValidation as addCustomValidation, utils_addDecimalValidation as addDecimalValidation, utils_addListValidation as addListValidation, utils_addNumberValidation as addNumberValidation, utils_addStringValidation as addStringValidation, utils_collectFieldRefs as collectFieldRefs };
75
227
  }
76
228
 
77
- export { utils as ZodUtils, createSchemaFactory };
229
+ export { type GetModelSchemaShapeWithOptions, type ModelSchemaOptions, utils as ZodUtils, createSchemaFactory };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SchemaDef, GetModels, GetModelFields, GetModelFieldType, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefFieldType, TypeDefFieldIsArray, TypeDefFieldIsOptional, FieldIsArray, ModelFieldIsOptional, FieldIsRelation, FieldHasDefault, FieldIsComputed, FieldIsDelegateDiscriminator, AttributeApplication } from '@zenstackhq/schema';
1
+ import { SchemaDef, GetModels, GetModelFields, GetModelFieldType, GetEnums, GetEnum, GetTypeDefs, GetTypeDefFields, GetTypeDefFieldType, TypeDefFieldIsArray, TypeDefFieldIsOptional, FieldIsArray, ModelFieldIsOptional, FieldIsRelation, FieldHasDefault, FieldIsComputed, FieldIsDelegateDiscriminator, AttributeApplication, Expression } from '@zenstackhq/schema';
2
2
  import z, { z as z$1 } from 'zod';
3
3
  import Decimal from 'decimal.js';
4
4
 
@@ -38,14 +38,145 @@ type ZodOptionalAndNullableIf<T extends z.ZodType, Condition extends boolean> =
38
38
  type ZodOptionalIf<T extends z.ZodType, Condition extends boolean> = Condition extends true ? z.ZodOptional<T> : T;
39
39
  type ZodNullableIf<T extends z.ZodType, Condition extends boolean> = Condition extends true ? z.ZodNullable<T> : T;
40
40
  type ZodArrayIf<T extends z.ZodType, Condition extends boolean> = Condition extends true ? z.ZodArray<T> : T;
41
+ /**
42
+ * The non-relation scalar fields of a model (excludes relation fields and
43
+ * foreign-key fields that back a relation).
44
+ */
45
+ type ScalarModelFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
46
+ [Field in GetModelFields<Schema, Model> as FieldIsRelation<Schema, Model, Field> extends true ? never : Field]: Field;
47
+ };
48
+ /**
49
+ * The relation fields of a model.
50
+ */
51
+ type RelationModelFields<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
52
+ [Field in GetModelFields<Schema, Model> as FieldIsRelation<Schema, Model, Field> extends true ? Field : never]: Field;
53
+ };
54
+ /**
55
+ * For a relation field, resolve the related model name.
56
+ */
57
+ type RelatedModel<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends GetModels<Schema> ? GetModelFieldType<Schema, Model, Field> : never;
58
+ /**
59
+ * ORM-style query options accepted by `makeModelSchema`.
60
+ *
61
+ * Exactly mirrors the `select` / `include` / `omit` vocabulary:
62
+ * - `select` — pick specific fields (scalars and/or relations). Mutually
63
+ * exclusive with `include` and `omit`.
64
+ * - `include` — start with all scalar fields, then add the named relation
65
+ * fields. Can be combined with `omit`.
66
+ * - `omit` — remove named scalar fields from the default scalar set.
67
+ * Can be combined with `include`, mutually exclusive with
68
+ * `select`.
69
+ */
70
+ type ModelSchemaOptions<Schema extends SchemaDef, Model extends GetModels<Schema>> = {
71
+ /**
72
+ * Pick only the listed fields. Values can be `true` (include with
73
+ * default shape) or a nested options object (for relation fields).
74
+ */
75
+ select: {
76
+ [Field in GetModelFields<Schema, Model>]?: FieldIsRelation<Schema, Model, Field> extends true ? boolean | ModelSchemaOptions<Schema, RelatedModel<Schema, Model, Field>> : boolean;
77
+ };
78
+ include?: never;
79
+ omit?: never;
80
+ } | {
81
+ select?: never;
82
+ /**
83
+ * Add the listed relation fields on top of the scalar fields.
84
+ * Values can be `true` / `{}` (default shape) or a nested options
85
+ * object.
86
+ */
87
+ include?: {
88
+ [Field in keyof RelationModelFields<Schema, Model>]?: Field extends GetModelFields<Schema, Model> ? boolean | ModelSchemaOptions<Schema, RelatedModel<Schema, Model, Field>> : never;
89
+ };
90
+ /**
91
+ * Remove the listed scalar fields from the output.
92
+ */
93
+ omit?: {
94
+ [Field in keyof ScalarModelFields<Schema, Model>]?: boolean;
95
+ };
96
+ };
97
+ /**
98
+ * Narrows `Field` so it can safely index `GetModelFieldsShape`. The mapped
99
+ * type uses a `as`-remapping clause, so TypeScript widens the key set and
100
+ * `Field extends GetModelFields<…>` alone is not enough for indexing.
101
+ */
102
+ type FieldInShape<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = Field & keyof GetModelFieldsShape<Schema, Model>;
103
+ /**
104
+ * Zod shape produced when a relation field is included via `include: { field:
105
+ * true }` or `select: { field: true }` — identical to how the existing
106
+ * `makeModelSchema` (no-options) represents relation fields: optional, carries
107
+ * array-ness and nullability from the field definition.
108
+ */
109
+ type RelationFieldZodDefault<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldsShape<Schema, Model>[FieldInShape<Schema, Model, Field>];
110
+ /**
111
+ * Zod shape for a relation field included with nested options. We recurse
112
+ * into `GetModelSchemaShapeWithOptions` for the related model, then re-apply
113
+ * the same optional/array/nullable wrappers as the default relation field.
114
+ */
115
+ type RelationFieldZodWithOptions<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Options> = RelatedModel<Schema, Model, Field> extends GetModels<Schema> ? ZodNullableIf<z.ZodOptional<ZodArrayIf<z.ZodObject<GetModelSchemaShapeWithOptions<Schema, RelatedModel<Schema, Model, Field>, Options>, z.core.$strict>, FieldIsArray<Schema, Model, Field>>>, ModelFieldIsOptional<Schema, Model, Field>> : never;
116
+ /**
117
+ * Resolve the Zod type for a single field given a select-entry value (`true`
118
+ * or a nested options object).
119
+ */
120
+ type SelectEntryToZod<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>, Value> = Value extends boolean ? GetModelFieldsShape<Schema, Model>[FieldInShape<Schema, Model, Field>] : Value extends object ? RelationFieldZodWithOptions<Schema, Model, Field, Value> : never;
121
+ /**
122
+ * Build the Zod shape for the `select` branch: only the listed fields,
123
+ * recursing into relations when given nested options.
124
+ */
125
+ type BuildSelectShape<Schema extends SchemaDef, Model extends GetModels<Schema>, S extends Record<string, unknown>> = {
126
+ [Field in keyof S & GetModelFields<Schema, Model> as S[Field] extends false ? never : Field]: SelectEntryToZod<Schema, Model, Field, S[Field]>;
127
+ };
128
+ /**
129
+ * Build the Zod shape for the `include` + `omit` branch:
130
+ * - All scalar fields, minus any that appear in `omit` with value `true`.
131
+ * - Plus the relation fields listed in `include`.
132
+ */
133
+ type BuildIncludeOmitShape<Schema extends SchemaDef, Model extends GetModels<Schema>, I extends Record<string, unknown> | undefined, O extends Record<string, unknown> | undefined> = {
134
+ [Field in GetModelFields<Schema, Model> as FieldIsRelation<Schema, Model, Field> extends true ? never : O extends object ? Field extends keyof O ? O[Field] extends true ? never : Field : Field : Field]: GetModelFieldsShape<Schema, Model>[FieldInShape<Schema, Model, Field>];
135
+ } & (I extends object ? {
136
+ [Field in keyof I & GetModelFields<Schema, Model> as I[Field] extends false ? never : Field]: I[Field] extends object ? RelationFieldZodWithOptions<Schema, Model, Field, I[Field]> : RelationFieldZodDefault<Schema, Model, Field>;
137
+ } : {});
138
+ /**
139
+ * The top-level conditional that maps options → Zod shape.
140
+ *
141
+ * - No options / undefined → existing `GetModelFieldsShape` (no change).
142
+ * - `{ select: S }` → `BuildSelectShape`.
143
+ * - `{ include?, omit? }` → `BuildIncludeOmitShape`.
144
+ */
145
+ type GetModelSchemaShapeWithOptions<Schema extends SchemaDef, Model extends GetModels<Schema>, Options> = Options extends {
146
+ select: infer S extends Record<string, unknown>;
147
+ } ? BuildSelectShape<Schema, Model, S> : Options extends {
148
+ include?: infer I extends Record<string, unknown> | undefined;
149
+ omit?: infer O extends Record<string, unknown> | undefined;
150
+ } ? BuildIncludeOmitShape<Schema, Model, I, O> : GetModelFieldsShape<Schema, Model>;
41
151
 
42
152
  declare function createSchemaFactory<Schema extends SchemaDef>(schema: Schema): SchemaFactory<Schema>;
43
153
  declare class SchemaFactory<Schema extends SchemaDef> {
44
154
  private readonly schema;
45
155
  constructor(_schema: Schema);
46
156
  makeModelSchema<Model extends GetModels<Schema>>(model: Model): z.ZodObject<GetModelFieldsShape<Schema, Model>, z.core.$strict>;
157
+ makeModelSchema<Model extends GetModels<Schema>, Options extends ModelSchemaOptions<Schema, Model>>(model: Model, options: Options): z.ZodObject<GetModelSchemaShapeWithOptions<Schema, Model, Options>, z.core.$strict>;
47
158
  makeModelCreateSchema<Model extends GetModels<Schema>>(model: Model): z.ZodObject<GetModelCreateFieldsShape<Schema, Model>, z.core.$strict>;
48
159
  makeModelUpdateSchema<Model extends GetModels<Schema>>(model: Model): z.ZodObject<GetModelUpdateFieldsShape<Schema, Model>, z.core.$strict>;
160
+ /**
161
+ * Internal loose options shape used at runtime (we've already validated the
162
+ * type-level constraints via the overload signatures).
163
+ */
164
+ private buildFieldsWithOptions;
165
+ /**
166
+ * Returns the set of scalar field names that will be present in the
167
+ * resulting schema after applying `options`. Used by `addCustomValidation`
168
+ * to skip `@@validate` rules that reference an absent field.
169
+ *
170
+ * Only scalar fields matter here because `@@validate` conditions are
171
+ * restricted by the ZModel compiler to scalar fields of the same model.
172
+ */
173
+ private buildPresentFields;
174
+ /**
175
+ * Build the inner Zod schema for a relation field, optionally with nested
176
+ * query options. Does NOT apply cardinality/optional wrappers — the caller
177
+ * does that.
178
+ */
179
+ private makeRelationFieldSchema;
49
180
  private makeScalarFieldSchema;
50
181
  private makeJsonSchema;
51
182
  private applyCardinality;
@@ -62,7 +193,27 @@ declare function addNumberValidation(schema: z$1.ZodNumber, attributes: readonly
62
193
  declare function addBigIntValidation(schema: z$1.ZodBigInt, attributes: readonly AttributeApplication[] | undefined): z$1.ZodSchema;
63
194
  declare function addDecimalValidation(schema: z$1.ZodType<Decimal> | z$1.ZodString, attributes: readonly AttributeApplication[] | undefined, addExtraValidation: boolean): z$1.ZodSchema;
64
195
  declare function addListValidation(schema: z$1.ZodArray<any>, attributes: readonly AttributeApplication[] | undefined): z$1.ZodSchema;
65
- declare function addCustomValidation(schema: z$1.ZodSchema, attributes: readonly AttributeApplication[] | undefined): z$1.ZodSchema;
196
+ /**
197
+ * Recursively collects all field names referenced by `kind: 'field'` nodes
198
+ * inside an expression tree.
199
+ */
200
+ declare function collectFieldRefs(expr: Expression): Set<string>;
201
+ /**
202
+ * Applies `@@validate` rules from `attributes` to `schema` as Zod refinements.
203
+ *
204
+ * When `presentFields` is provided, only rules whose every field reference is
205
+ * present in the set are applied. Rules that reference a field absent from the
206
+ * set are silently skipped — they cannot be evaluated correctly against a
207
+ * partial payload (e.g. when `select` or `omit` has been used).
208
+ *
209
+ * Omit `presentFields` (or pass `undefined`) to apply all rules
210
+ * unconditionally, which is the correct behaviour for full-model schemas.
211
+ *
212
+ * Note: `@@validate` conditions are restricted by the ZModel compiler to
213
+ * scalar fields of the same model only — relation fields are a compile error.
214
+ * A flat field-name set is therefore sufficient.
215
+ */
216
+ declare function addCustomValidation(schema: z$1.ZodSchema, attributes: readonly AttributeApplication[] | undefined, presentFields?: ReadonlySet<string>): z$1.ZodSchema;
66
217
 
67
218
  declare const utils_addBigIntValidation: typeof addBigIntValidation;
68
219
  declare const utils_addCustomValidation: typeof addCustomValidation;
@@ -70,8 +221,9 @@ declare const utils_addDecimalValidation: typeof addDecimalValidation;
70
221
  declare const utils_addListValidation: typeof addListValidation;
71
222
  declare const utils_addNumberValidation: typeof addNumberValidation;
72
223
  declare const utils_addStringValidation: typeof addStringValidation;
224
+ declare const utils_collectFieldRefs: typeof collectFieldRefs;
73
225
  declare namespace utils {
74
- export { utils_addBigIntValidation as addBigIntValidation, utils_addCustomValidation as addCustomValidation, utils_addDecimalValidation as addDecimalValidation, utils_addListValidation as addListValidation, utils_addNumberValidation as addNumberValidation, utils_addStringValidation as addStringValidation };
226
+ export { utils_addBigIntValidation as addBigIntValidation, utils_addCustomValidation as addCustomValidation, utils_addDecimalValidation as addDecimalValidation, utils_addListValidation as addListValidation, utils_addNumberValidation as addNumberValidation, utils_addStringValidation as addStringValidation, utils_collectFieldRefs as collectFieldRefs };
75
227
  }
76
228
 
77
- export { utils as ZodUtils, createSchemaFactory };
229
+ export { type GetModelSchemaShapeWithOptions, type ModelSchemaOptions, utils as ZodUtils, createSchemaFactory };
package/dist/index.js CHANGED
@@ -28,7 +28,8 @@ __export(utils_exports, {
28
28
  addDecimalValidation: () => addDecimalValidation,
29
29
  addListValidation: () => addListValidation,
30
30
  addNumberValidation: () => addNumberValidation,
31
- addStringValidation: () => addStringValidation
31
+ addStringValidation: () => addStringValidation,
32
+ collectFieldRefs: () => collectFieldRefs
32
33
  });
33
34
  import { ExpressionUtils } from "@zenstackhq/schema";
34
35
  import Decimal from "decimal.js";
@@ -252,7 +253,37 @@ function addListValidation(schema, attributes) {
252
253
  return result;
253
254
  }
254
255
  __name(addListValidation, "addListValidation");
255
- function addCustomValidation(schema, attributes) {
256
+ function collectFieldRefs(expr) {
257
+ const refs = /* @__PURE__ */ new Set();
258
+ function walk(e) {
259
+ switch (e.kind) {
260
+ case "field":
261
+ refs.add(e.field);
262
+ break;
263
+ case "unary":
264
+ walk(e.operand);
265
+ break;
266
+ case "binary":
267
+ walk(e.left);
268
+ walk(e.right);
269
+ break;
270
+ case "call":
271
+ e.args?.forEach(walk);
272
+ break;
273
+ case "array":
274
+ e.items.forEach(walk);
275
+ break;
276
+ case "member":
277
+ walk(e.receiver);
278
+ break;
279
+ }
280
+ }
281
+ __name(walk, "walk");
282
+ walk(expr);
283
+ return refs;
284
+ }
285
+ __name(collectFieldRefs, "collectFieldRefs");
286
+ function addCustomValidation(schema, attributes, presentFields) {
256
287
  const attrs = attributes?.filter((a) => a.name === "@@validate");
257
288
  if (!attrs || attrs.length === 0) {
258
289
  return schema;
@@ -263,6 +294,14 @@ function addCustomValidation(schema, attributes) {
263
294
  if (!expr) {
264
295
  continue;
265
296
  }
297
+ if (presentFields !== void 0) {
298
+ const refs = collectFieldRefs(expr);
299
+ if ([
300
+ ...refs
301
+ ].some((ref) => !presentFields.has(ref))) {
302
+ continue;
303
+ }
304
+ }
266
305
  const message = getArgValue(attr.args?.[1]?.value);
267
306
  const pathExpr = attr.args?.[2]?.value;
268
307
  let path = void 0;
@@ -477,6 +516,30 @@ function createSchemaFactory(schema) {
477
516
  return new SchemaFactory(schema);
478
517
  }
479
518
  __name(createSchemaFactory, "createSchemaFactory");
519
+ var rawOptionsSchema = z2.lazy(() => z2.object({
520
+ select: z2.record(z2.string(), z2.union([
521
+ z2.boolean(),
522
+ rawOptionsSchema
523
+ ])).optional(),
524
+ include: z2.record(z2.string(), z2.union([
525
+ z2.boolean(),
526
+ rawOptionsSchema
527
+ ])).optional(),
528
+ omit: z2.record(z2.string(), z2.boolean()).optional()
529
+ }).superRefine((val, ctx) => {
530
+ if (val.select && val.include) {
531
+ ctx.addIssue({
532
+ code: "custom",
533
+ message: "`select` and `include` cannot be used together"
534
+ });
535
+ }
536
+ if (val.select && val.omit) {
537
+ ctx.addIssue({
538
+ code: "custom",
539
+ message: "`select` and `omit` cannot be used together"
540
+ });
541
+ }
542
+ }));
480
543
  var SchemaFactory = class SchemaFactory2 {
481
544
  static {
482
545
  __name(this, "SchemaFactory");
@@ -485,20 +548,28 @@ var SchemaFactory = class SchemaFactory2 {
485
548
  constructor(_schema) {
486
549
  this.schema = new SchemaAccessor(_schema);
487
550
  }
488
- makeModelSchema(model) {
551
+ makeModelSchema(model, options) {
489
552
  const modelDef = this.schema.requireModel(model);
490
- const fields = {};
491
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
492
- if (fieldDef.relation) {
493
- const relatedModelName = fieldDef.type;
494
- const lazySchema = z2.lazy(() => this.makeModelSchema(relatedModelName));
495
- fields[fieldName] = this.applyDescription(this.applyCardinality(lazySchema, fieldDef).optional(), fieldDef.attributes);
496
- } else {
497
- fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
553
+ if (!options) {
554
+ const fields2 = {};
555
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
556
+ if (fieldDef.relation) {
557
+ const relatedModelName = fieldDef.type;
558
+ const lazySchema = z2.lazy(() => this.makeModelSchema(relatedModelName));
559
+ fields2[fieldName] = this.applyDescription(this.applyCardinality(lazySchema, fieldDef).optional(), fieldDef.attributes);
560
+ } else {
561
+ fields2[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
562
+ }
498
563
  }
564
+ const shape2 = z2.strictObject(fields2);
565
+ return this.applyDescription(addCustomValidation(shape2, modelDef.attributes), modelDef.attributes);
499
566
  }
567
+ const rawOptions = rawOptionsSchema.parse(options);
568
+ const fields = this.buildFieldsWithOptions(model, rawOptions);
500
569
  const shape = z2.strictObject(fields);
501
- return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
570
+ const presentFields = this.buildPresentFields(model, rawOptions);
571
+ const withValidation = addCustomValidation(shape, modelDef.attributes, presentFields);
572
+ return this.applyDescription(withValidation, modelDef.attributes);
502
573
  }
503
574
  makeModelCreateSchema(model) {
504
575
  const modelDef = this.schema.requireModel(model);
@@ -530,6 +601,111 @@ var SchemaFactory = class SchemaFactory2 {
530
601
  const shape = z2.strictObject(fields);
531
602
  return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
532
603
  }
604
+ // -------------------------------------------------------------------------
605
+ // Options-aware field building
606
+ // -------------------------------------------------------------------------
607
+ /**
608
+ * Internal loose options shape used at runtime (we've already validated the
609
+ * type-level constraints via the overload signatures).
610
+ */
611
+ buildFieldsWithOptions(model, options) {
612
+ const { select, include, omit } = options;
613
+ const modelDef = this.schema.requireModel(model);
614
+ const fields = {};
615
+ if (select) {
616
+ for (const [key, value] of Object.entries(select)) {
617
+ if (!value) continue;
618
+ const fieldDef = modelDef.fields[key];
619
+ if (!fieldDef) {
620
+ throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
621
+ }
622
+ if (fieldDef.relation) {
623
+ const subOptions = typeof value === "object" ? value : void 0;
624
+ const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
625
+ fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
626
+ } else {
627
+ if (typeof value === "object") {
628
+ throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a scalar field and cannot have nested options`);
629
+ }
630
+ fields[key] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
631
+ }
632
+ }
633
+ } else {
634
+ if (omit) {
635
+ for (const key of Object.keys(omit)) {
636
+ const fieldDef = modelDef.fields[key];
637
+ if (!fieldDef) {
638
+ throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
639
+ }
640
+ if (fieldDef.relation) {
641
+ throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a relation field and cannot be used in "omit"`);
642
+ }
643
+ }
644
+ }
645
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
646
+ if (fieldDef.relation) continue;
647
+ if (omit?.[fieldName] === true) continue;
648
+ fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
649
+ }
650
+ if (include) {
651
+ for (const [key, value] of Object.entries(include)) {
652
+ if (!value) continue;
653
+ const fieldDef = modelDef.fields[key];
654
+ if (!fieldDef) {
655
+ throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
656
+ }
657
+ if (!fieldDef.relation) {
658
+ throw new SchemaFactoryError(`Field "${key}" on model "${model}" is not a relation field and cannot be used in "include"`);
659
+ }
660
+ const subOptions = typeof value === "object" ? value : void 0;
661
+ const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
662
+ fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
663
+ }
664
+ }
665
+ }
666
+ return fields;
667
+ }
668
+ /**
669
+ * Returns the set of scalar field names that will be present in the
670
+ * resulting schema after applying `options`. Used by `addCustomValidation`
671
+ * to skip `@@validate` rules that reference an absent field.
672
+ *
673
+ * Only scalar fields matter here because `@@validate` conditions are
674
+ * restricted by the ZModel compiler to scalar fields of the same model.
675
+ */
676
+ buildPresentFields(model, options) {
677
+ const { select, omit } = options;
678
+ const modelDef = this.schema.requireModel(model);
679
+ const fields = /* @__PURE__ */ new Set();
680
+ if (select) {
681
+ for (const [key, value] of Object.entries(select)) {
682
+ if (!value) continue;
683
+ const fieldDef = modelDef.fields[key];
684
+ if (fieldDef && !fieldDef.relation) {
685
+ fields.add(key);
686
+ }
687
+ }
688
+ } else {
689
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
690
+ if (fieldDef.relation) continue;
691
+ if (omit?.[fieldName] === true) continue;
692
+ fields.add(fieldName);
693
+ }
694
+ }
695
+ return fields;
696
+ }
697
+ /**
698
+ * Build the inner Zod schema for a relation field, optionally with nested
699
+ * query options. Does NOT apply cardinality/optional wrappers — the caller
700
+ * does that.
701
+ */
702
+ makeRelationFieldSchema(fieldDef, subOptions) {
703
+ const relatedModelName = fieldDef.type;
704
+ if (subOptions) {
705
+ return this.makeModelSchema(relatedModelName, subOptions);
706
+ }
707
+ return z2.lazy(() => this.makeModelSchema(relatedModelName));
708
+ }
533
709
  makeScalarFieldSchema(fieldDef) {
534
710
  const { type, attributes } = fieldDef;
535
711
  const enumDef = this.schema.getEnum(type);