@backmatter/core 0.0.33 → 0.0.35

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.
@@ -0,0 +1,189 @@
1
+ // packages/core/src/relation-problems.ts
2
+ import type { BlockInstance } from "./block";
3
+ import type { FieldSnapshot } from "./fields";
4
+ import { matchesWhere } from "./relation-match";
5
+ import type { ModelSnapshot, SchemaSnapshot } from "./model";
6
+
7
+ type DocEntry = { slug: string; frontmatter: Record<string, unknown> };
8
+
9
+ function docKey(type: string, slug: string): string {
10
+ return `${type}/${slug}`;
11
+ }
12
+
13
+ function isBlankRelationValue(value: unknown): boolean {
14
+ return typeof value !== "string" || value.trim() === "";
15
+ }
16
+
17
+ function inlineFields(field: FieldSnapshot): Record<string, FieldSnapshot> | undefined {
18
+ if (!field.fields || Object.keys(field.fields).length === 0) return undefined;
19
+ return field.fields;
20
+ }
21
+
22
+ function objectFieldsFor(
23
+ schema: SchemaSnapshot,
24
+ field: FieldSnapshot,
25
+ ): Record<string, FieldSnapshot> | undefined {
26
+ const inline = inlineFields(field);
27
+ if (inline) return inline;
28
+ if ((field.kind === "object" || field.kind === "array") && field.object) {
29
+ const def = schema.objects?.find((o) => o.name === field.object);
30
+ return def?.fields;
31
+ }
32
+ return undefined;
33
+ }
34
+
35
+ function joinPath(prefix: string, segment: string): string {
36
+ return prefix ? `${prefix}.${segment}` : segment;
37
+ }
38
+
39
+ function checkRelationValue(
40
+ path: string,
41
+ field: FieldSnapshot,
42
+ value: unknown,
43
+ modelsByType: Map<string, ModelSnapshot>,
44
+ docMap: Map<string, DocEntry>,
45
+ errors: string[],
46
+ ): void {
47
+ if (field.kind !== "relation" || !field.relationTo) return;
48
+ if (isBlankRelationValue(value)) return;
49
+ const targetModel = modelsByType.get(field.relationTo);
50
+ if (!targetModel || targetModel.external) return;
51
+
52
+ const targetSlug = value as string;
53
+ const target = docMap.get(docKey(field.relationTo, targetSlug));
54
+ if (!target) {
55
+ errors.push(`${path} must name a ${field.relationTo} document`);
56
+ return;
57
+ }
58
+ if (!matchesWhere(target, field.where)) {
59
+ errors.push(`${path} must match the field's filter`);
60
+ }
61
+ }
62
+
63
+ function asBlockList(value: unknown): BlockInstance[] {
64
+ if (!Array.isArray(value)) return [];
65
+ return value.filter((item): item is BlockInstance => {
66
+ if (!item || typeof item !== "object") return false;
67
+ const row = item as Record<string, unknown>;
68
+ return typeof row.id === "string" && typeof row.type === "string";
69
+ });
70
+ }
71
+
72
+ function walkFields(
73
+ schema: SchemaSnapshot,
74
+ pathPrefix: string,
75
+ fields: Record<string, FieldSnapshot>,
76
+ data: Record<string, unknown>,
77
+ modelsByType: Map<string, ModelSnapshot>,
78
+ docMap: Map<string, DocEntry>,
79
+ errors: string[],
80
+ ): void {
81
+ for (const [name, field] of Object.entries(fields)) {
82
+ const path = joinPath(pathPrefix, name);
83
+ const value = data[name];
84
+
85
+ if (field.kind === "relation") {
86
+ checkRelationValue(path, field, value, modelsByType, docMap, errors);
87
+ continue;
88
+ }
89
+
90
+ if (field.kind === "blocks") {
91
+ walkBlockInstances(schema, name, value, modelsByType, docMap, errors);
92
+ continue;
93
+ }
94
+
95
+ const nested = objectFieldsFor(schema, field);
96
+ if (!nested) continue;
97
+
98
+ if (field.kind === "array" && Array.isArray(value)) {
99
+ value.forEach((item, index) => {
100
+ if (!item || typeof item !== "object") return;
101
+ walkFields(
102
+ schema,
103
+ `${path}.${index}`,
104
+ nested,
105
+ item as Record<string, unknown>,
106
+ modelsByType,
107
+ docMap,
108
+ errors,
109
+ );
110
+ });
111
+ } else if (field.kind === "object" && value && typeof value === "object") {
112
+ walkFields(
113
+ schema,
114
+ path,
115
+ nested,
116
+ value as Record<string, unknown>,
117
+ modelsByType,
118
+ docMap,
119
+ errors,
120
+ );
121
+ }
122
+ }
123
+ }
124
+
125
+ function walkBlockInstances(
126
+ schema: SchemaSnapshot,
127
+ prefix: string,
128
+ blocks: unknown,
129
+ modelsByType: Map<string, ModelSnapshot>,
130
+ docMap: Map<string, DocEntry>,
131
+ errors: string[],
132
+ ): void {
133
+ const catalog = schema.blocks ?? [];
134
+ const byName = new Map(catalog.map((b) => [b.name, b]));
135
+ asBlockList(blocks).forEach((block, index) => {
136
+ const def = byName.get(block.type);
137
+ if (!def) return;
138
+ const props =
139
+ block.props && typeof block.props === "object"
140
+ ? (block.props as Record<string, unknown>)
141
+ : {};
142
+ walkFields(
143
+ schema,
144
+ `${prefix}[${index}]`,
145
+ def.fields,
146
+ props,
147
+ modelsByType,
148
+ docMap,
149
+ errors,
150
+ );
151
+ });
152
+ }
153
+
154
+ function walkDocument(
155
+ schema: SchemaSnapshot,
156
+ model: ModelSnapshot,
157
+ frontmatter: Record<string, unknown>,
158
+ modelsByType: Map<string, ModelSnapshot>,
159
+ docMap: Map<string, DocEntry>,
160
+ errors: string[],
161
+ ): void {
162
+ walkFields(schema, "", model.fields, frontmatter, modelsByType, docMap, errors);
163
+ }
164
+
165
+ export function relationProblems(input: {
166
+ schema: SchemaSnapshot;
167
+ docs: Array<{ type: string; slug: string; frontmatter: Record<string, unknown> }>;
168
+ }): Array<{ type: string; slug: string; errors: string[] }> {
169
+ const modelsByType = new Map(input.schema.models.map((m) => [m.type, m]));
170
+ const docMap = new Map<string, DocEntry>();
171
+ for (const doc of input.docs) {
172
+ docMap.set(docKey(doc.type, doc.slug), {
173
+ slug: doc.slug,
174
+ frontmatter: doc.frontmatter,
175
+ });
176
+ }
177
+
178
+ const rows: Array<{ type: string; slug: string; errors: string[] }> = [];
179
+ for (const doc of input.docs) {
180
+ const model = modelsByType.get(doc.type);
181
+ if (!model) continue;
182
+ const errors: string[] = [];
183
+ walkDocument(input.schema, model, doc.frontmatter, modelsByType, docMap, errors);
184
+ if (errors.length > 0) {
185
+ rows.push({ type: doc.type, slug: doc.slug, errors });
186
+ }
187
+ }
188
+ return rows;
189
+ }
@@ -0,0 +1,260 @@
1
+ // packages/core/src/schema-check.ts
2
+ import type { FieldSnapshot } from "./fields";
3
+ import type { ModelSnapshot, SchemaSnapshot } from "./model";
4
+
5
+ type ScalarKind = "text" | "number" | "boolean";
6
+
7
+ function isScalarKind(kind: string): kind is ScalarKind {
8
+ return kind === "text" || kind === "number" || kind === "boolean";
9
+ }
10
+
11
+ function scalarJsonType(kind: ScalarKind): "string" | "number" | "boolean" {
12
+ if (kind === "number") return "number";
13
+ if (kind === "boolean") return "boolean";
14
+ return "string";
15
+ }
16
+
17
+ function fieldPath(owner: string, segments: string[]): string {
18
+ return `${owner}.${segments.join(".")}`;
19
+ }
20
+
21
+ function modelMap(models: ModelSnapshot[]): Map<string, ModelSnapshot> {
22
+ return new Map(models.map((model) => [model.type, model]));
23
+ }
24
+
25
+ function objectExists(schema: SchemaSnapshot, name: string): boolean {
26
+ return schema.objects?.some((object) => object.name === name) ?? false;
27
+ }
28
+
29
+ function inlineFields(field: FieldSnapshot): Record<string, FieldSnapshot> | undefined {
30
+ if (!field.fields || Object.keys(field.fields).length === 0) {
31
+ return undefined;
32
+ }
33
+ return field.fields;
34
+ }
35
+
36
+ function resolveNamedObjectFields(
37
+ schema: SchemaSnapshot,
38
+ objectName: string,
39
+ visiting: Set<string>,
40
+ ): Record<string, FieldSnapshot> | undefined {
41
+ if (visiting.has(objectName)) {
42
+ return {};
43
+ }
44
+ const object = schema.objects?.find((entry) => entry.name === objectName);
45
+ if (!object) {
46
+ return undefined;
47
+ }
48
+ visiting.add(objectName);
49
+ return object.fields;
50
+ }
51
+
52
+ function nestedFieldsToWalk(
53
+ schema: SchemaSnapshot,
54
+ field: FieldSnapshot,
55
+ visiting: Set<string>,
56
+ ): Record<string, FieldSnapshot> | undefined {
57
+ const inline = inlineFields(field);
58
+ if (inline) {
59
+ return inline;
60
+ }
61
+ if ((field.kind === "object" || field.kind === "array") && field.object) {
62
+ return resolveNamedObjectFields(schema, field.object, visiting);
63
+ }
64
+ return undefined;
65
+ }
66
+
67
+ function checkWhereOnModel(
68
+ path: string,
69
+ where: NonNullable<FieldSnapshot["where"]>,
70
+ target: ModelSnapshot,
71
+ problems: string[],
72
+ ): void {
73
+ for (const [key, value] of Object.entries(where)) {
74
+ if (key === "slug") {
75
+ if (typeof value !== "string") {
76
+ problems.push(`${path} where.slug must be a string`);
77
+ }
78
+ continue;
79
+ }
80
+ const targetField = target.fields[key];
81
+ if (!targetField || !isScalarKind(targetField.kind)) {
82
+ problems.push(`${path} where.${key} is not a scalar field of ${target.type}`);
83
+ continue;
84
+ }
85
+ const expected = scalarJsonType(targetField.kind);
86
+ if (typeof value !== expected) {
87
+ problems.push(`${path} where.${key} must be a ${expected}`);
88
+ }
89
+ }
90
+ }
91
+
92
+ function checkLinkField(
93
+ path: string,
94
+ field: FieldSnapshot,
95
+ modelsByType: Map<string, ModelSnapshot>,
96
+ problems: string[],
97
+ ): void {
98
+ if (field.kind !== "link") {
99
+ return;
100
+ }
101
+ if (field.to === "external") {
102
+ if ((field.models && field.models.length > 0) || field.where) {
103
+ problems.push(`${path} to external cannot set models or where`);
104
+ }
105
+ return;
106
+ }
107
+ if (field.models) {
108
+ const seen = new Set<string>();
109
+ for (const name of field.models) {
110
+ if (seen.has(name)) {
111
+ problems.push(`${path} models repeats ${name}`);
112
+ continue;
113
+ }
114
+ seen.add(name);
115
+ const target = modelsByType.get(name);
116
+ if (!target) {
117
+ problems.push(`${path} models "${name}" names no model`);
118
+ continue;
119
+ }
120
+ if (target.external) {
121
+ problems.push(`${path} models names external model "${name}"`);
122
+ continue;
123
+ }
124
+ if (target.route === false) {
125
+ problems.push(`${path} models "${name}" route is false`);
126
+ }
127
+ }
128
+ }
129
+ if (!field.where) {
130
+ return;
131
+ }
132
+ if (field.models?.length !== 1) {
133
+ problems.push(`${path} where requires one model`);
134
+ return;
135
+ }
136
+ const target = modelsByType.get(field.models[0]!);
137
+ if (!target) {
138
+ return;
139
+ }
140
+ checkWhereOnModel(path, field.where, target, problems);
141
+ }
142
+
143
+ function checkRelationField(
144
+ path: string,
145
+ field: FieldSnapshot,
146
+ modelsByType: Map<string, ModelSnapshot>,
147
+ problems: string[],
148
+ ): void {
149
+ if (!field.relationTo) {
150
+ return;
151
+ }
152
+ const target = modelsByType.get(field.relationTo);
153
+ if (!target) {
154
+ problems.push(`${path} relationTo "${field.relationTo}" names no model`);
155
+ return;
156
+ }
157
+ if (!field.where) {
158
+ return;
159
+ }
160
+ if (target.external) {
161
+ problems.push(`${path} where is set on external model "${target.type}"`);
162
+ return;
163
+ }
164
+ checkWhereOnModel(path, field.where, target, problems);
165
+ }
166
+
167
+ function checkObjectReference(
168
+ schema: SchemaSnapshot,
169
+ path: string,
170
+ field: FieldSnapshot,
171
+ problems: string[],
172
+ ): void {
173
+ if (field.kind !== "object" && field.kind !== "array") {
174
+ return;
175
+ }
176
+ if (!field.object || inlineFields(field)) {
177
+ return;
178
+ }
179
+ if (!objectExists(schema, field.object)) {
180
+ problems.push(`${path} object "${field.object}" names no object`);
181
+ }
182
+ }
183
+
184
+ function walkFields(
185
+ schema: SchemaSnapshot,
186
+ owner: string,
187
+ segments: string[],
188
+ fields: Record<string, FieldSnapshot>,
189
+ modelsByType: Map<string, ModelSnapshot>,
190
+ visitingObjects: Set<string>,
191
+ problems: string[],
192
+ ): void {
193
+ for (const [name, field] of Object.entries(fields)) {
194
+ const path = fieldPath(owner, [...segments, name]);
195
+ checkObjectReference(schema, path, field, problems);
196
+ checkRelationField(path, field, modelsByType, problems);
197
+ checkLinkField(path, field, modelsByType, problems);
198
+ const nested = nestedFieldsToWalk(schema, field, visitingObjects);
199
+ if (nested) {
200
+ walkFields(schema, owner, [...segments, name], nested, modelsByType, visitingObjects, problems);
201
+ }
202
+ }
203
+ }
204
+
205
+ export function assertSchema(schema: SchemaSnapshot): void {
206
+ const modelsByType = modelMap(schema.models);
207
+ const problems: string[] = [];
208
+
209
+ for (const model of schema.models) {
210
+ walkFields(
211
+ schema,
212
+ `model ${model.type}`,
213
+ [],
214
+ model.fields,
215
+ modelsByType,
216
+ new Set<string>(),
217
+ problems,
218
+ );
219
+ }
220
+
221
+ for (const block of schema.blocks ?? []) {
222
+ walkFields(
223
+ schema,
224
+ `block ${block.name}`,
225
+ [],
226
+ block.fields,
227
+ modelsByType,
228
+ new Set<string>(),
229
+ problems,
230
+ );
231
+ }
232
+
233
+ for (const block of schema.richtext ?? []) {
234
+ walkFields(
235
+ schema,
236
+ `richtext ${block.name}`,
237
+ [],
238
+ block.fields,
239
+ modelsByType,
240
+ new Set<string>(),
241
+ problems,
242
+ );
243
+ }
244
+
245
+ for (const object of schema.objects ?? []) {
246
+ walkFields(
247
+ schema,
248
+ `object ${object.name}`,
249
+ [],
250
+ object.fields,
251
+ modelsByType,
252
+ new Set<string>(),
253
+ problems,
254
+ );
255
+ }
256
+
257
+ if (problems.length > 0) {
258
+ throw new Error(problems.join("\n"));
259
+ }
260
+ }
@@ -4,6 +4,7 @@ import {
4
4
  type ModelDef,
5
5
  type ModelSnapshot,
6
6
  } from "./model";
7
+ import { assertSchema } from "./schema-check";
7
8
  import type { BlockDef } from "./block";
8
9
  import type { ObjectDef } from "./object";
9
10
 
@@ -38,6 +39,7 @@ export async function syncSchema(options: SyncSchemaOptions): Promise<void> {
38
39
  options.objects,
39
40
  options.richtext,
40
41
  );
42
+ assertSchema(payload);
41
43
  const body: {
42
44
  payload: ReturnType<typeof serializeSchema>;
43
45
  branch: string;