@backmatter/core 0.0.33 → 0.0.34

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/src/zod.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  // packages/core/src/zod.ts
2
2
  import { z } from "zod";
3
+ import { isColorString } from "./color";
3
4
  import type { FieldKind, FieldSnapshot } from "./fields";
4
5
  import { mediaIdFromUrl } from "./media-url";
5
6
  import type { Frontmatter } from "./mdx";
6
7
  import type { ModelSnapshot } from "./model";
8
+ import type { ObjectSnapshot } from "./object";
9
+
10
+ const STEP_EPS = 1e-9;
7
11
 
8
12
  /** Primitive a field kind is stored as in frontmatter; used in error messages. */
9
13
  export function expectedTypeFor(
@@ -58,16 +62,90 @@ export function exampleValueFor(kind: FieldKind): unknown {
58
62
  }
59
63
  }
60
64
 
61
- function objectZod(field: FieldSnapshot): z.ZodType {
62
- if (!field.fields) return z.record(z.string(), z.unknown());
65
+ type ZodBuildContext = {
66
+ objects: ObjectSnapshot[];
67
+ objectSchemas: Map<string, z.ZodType>;
68
+ };
69
+
70
+ function objectFieldsFor(field: FieldSnapshot, ctx: ZodBuildContext): Record<string, FieldSnapshot> | undefined {
71
+ if (field.fields) return field.fields;
72
+ if (!field.object) return undefined;
73
+ const def = ctx.objects.find((o) => o.name === field.object);
74
+ return def?.fields;
75
+ }
76
+
77
+ function objectZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
78
+ const nested = objectFieldsFor(field, ctx);
79
+ if (!nested) return z.record(z.string(), z.unknown());
80
+ if (field.object && !field.fields) {
81
+ return namedObjectZod(field.object, nested, ctx);
82
+ }
63
83
  const shape: Record<string, z.ZodType> = {};
64
- for (const [name, nested] of Object.entries(field.fields)) {
65
- shape[name] = fieldZod(nested);
84
+ for (const [name, child] of Object.entries(nested)) {
85
+ shape[name] = fieldZod(child, ctx);
66
86
  }
67
87
  return z.looseObject(shape);
68
88
  }
69
89
 
70
- function fieldZod(field: FieldSnapshot): z.ZodType {
90
+ function namedObjectZod(
91
+ name: string,
92
+ fields: Record<string, FieldSnapshot>,
93
+ ctx: ZodBuildContext,
94
+ ): z.ZodType {
95
+ const cached = ctx.objectSchemas.get(name);
96
+ if (cached) return cached;
97
+ const schema = z.lazy(() => {
98
+ const shape: Record<string, z.ZodType> = {};
99
+ for (const [key, nested] of Object.entries(fields)) {
100
+ shape[key] = fieldZod(nested, ctx);
101
+ }
102
+ return z.looseObject(shape);
103
+ });
104
+ ctx.objectSchemas.set(name, schema);
105
+ return schema;
106
+ }
107
+
108
+ function applyNumberConstraints(field: FieldSnapshot, base: z.ZodNumber): z.ZodType {
109
+ const { min, max, step } = field;
110
+ if (typeof min !== "number" || typeof max !== "number") return base;
111
+ return base.superRefine((value, ctx) => {
112
+ if (!Number.isFinite(value) || value < min || value > max) {
113
+ ctx.addIssue({ code: "custom", message: `must be between ${min} and ${max}` });
114
+ return;
115
+ }
116
+ if (step !== undefined) {
117
+ const offset = (value - min) / step;
118
+ const n = Math.round(offset);
119
+ if (Math.abs(offset - n) > STEP_EPS || n < 0) {
120
+ ctx.addIssue({ code: "custom", message: `must be a step of ${step} from ${min}` });
121
+ }
122
+ }
123
+ });
124
+ }
125
+
126
+ function applyStringConstraints(field: FieldSnapshot, base: z.ZodString): z.ZodType {
127
+ let out: z.ZodType = base;
128
+ if (field.options && field.options.length > 0) {
129
+ const options = field.options;
130
+ out = out.superRefine((value, ctx) => {
131
+ if (typeof value !== "string" || value.trim() === "") return;
132
+ if (!options.includes(value)) {
133
+ ctx.addIssue({ code: "custom", message: `must be one of ${options.join(", ")}` });
134
+ }
135
+ });
136
+ }
137
+ if (field.input === "color") {
138
+ out = out.superRefine((value, ctx) => {
139
+ if (typeof value !== "string" || value.trim() === "") return;
140
+ if (!isColorString(value.trim())) {
141
+ ctx.addIssue({ code: "custom", message: "must be a color" });
142
+ }
143
+ });
144
+ }
145
+ return out;
146
+ }
147
+
148
+ function fieldZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
71
149
  if (field.kind === "blocks") {
72
150
  const item = z.object({
73
151
  id: z.string().min(1),
@@ -78,11 +156,11 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
78
156
  return arr;
79
157
  }
80
158
  if (field.kind === "object") {
81
- const obj = objectZod(field);
159
+ const obj = objectZod(field, ctx);
82
160
  return field.required ? obj : obj.optional();
83
161
  }
84
162
  if (field.kind === "array") {
85
- const arr = z.array(objectZod(field));
163
+ const arr = z.array(objectZod(field, ctx));
86
164
  return field.required ? arr : arr.optional();
87
165
  }
88
166
  if (field.kind === "media") {
@@ -97,7 +175,7 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
97
175
  let base: z.ZodType;
98
176
  switch (expectedTypeFor(field.kind)) {
99
177
  case "number":
100
- base = z.number();
178
+ base = applyNumberConstraints(field, z.number());
101
179
  break;
102
180
  case "boolean":
103
181
  base = z.boolean();
@@ -105,6 +183,7 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
105
183
  default:
106
184
  // Required strings must be non-blank; trim happens before min(1).
107
185
  base = field.required ? z.string().trim().min(1) : z.string();
186
+ base = applyStringConstraints(field, base as z.ZodString);
108
187
  }
109
188
  return field.required ? base : base.optional();
110
189
  }
@@ -113,10 +192,14 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
113
192
  * Zod object for a model's frontmatter.
114
193
  * Loose: keys not in the model pass through untouched (drift is not an error).
115
194
  */
116
- export function frontmatterZod(model: Pick<ModelSnapshot, "fields">) {
195
+ export function frontmatterZod(
196
+ model: Pick<ModelSnapshot, "fields">,
197
+ objects: ObjectSnapshot[] = [],
198
+ ) {
199
+ const ctx: ZodBuildContext = { objects, objectSchemas: new Map() };
117
200
  const shape: Record<string, z.ZodType> = {};
118
201
  for (const [name, field] of Object.entries(model.fields)) {
119
- shape[name] = fieldZod(field);
202
+ shape[name] = fieldZod(field, ctx);
120
203
  }
121
204
  return z.looseObject(shape);
122
205
  }
@@ -141,3 +224,37 @@ export function frontmatterJsonSchema(model: ModelSnapshot): FrontmatterJsonSche
141
224
  });
142
225
  return { ...schema, title: model.type };
143
226
  }
227
+
228
+ /** Resolve the field definition for a Zod issue path (for error messages). */
229
+ export function fieldAtPath(
230
+ rootFields: Record<string, FieldSnapshot>,
231
+ path: PropertyKey[],
232
+ objects: ObjectSnapshot[],
233
+ ): FieldSnapshot | undefined {
234
+ let fields = rootFields;
235
+ let current: FieldSnapshot | undefined;
236
+ for (let i = 0; i < path.length; i++) {
237
+ const seg = path[i];
238
+ if (typeof seg === "number") continue;
239
+ current = fields[String(seg)];
240
+ if (!current) return undefined;
241
+ if (i === path.length - 1) return current;
242
+ const next = path[i + 1];
243
+ if (typeof next === "number") {
244
+ if (current.kind !== "array") return undefined;
245
+ const itemFields = objectFieldsFor(current, { objects, objectSchemas: new Map() });
246
+ if (!itemFields) return undefined;
247
+ fields = itemFields;
248
+ i += 1;
249
+ continue;
250
+ }
251
+ if (current.kind === "object" || current.kind === "array") {
252
+ const nested = objectFieldsFor(current, { objects, objectSchemas: new Map() });
253
+ if (!nested) return undefined;
254
+ fields = nested;
255
+ } else {
256
+ return undefined;
257
+ }
258
+ }
259
+ return current;
260
+ }