@backmatter/core 0.0.32 → 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/query.ts CHANGED
@@ -1,6 +1,6 @@
1
- // packages/core/src/query.ts
1
+ import type { BlockDef } from "./block";
2
2
  import type { BackmatterDoc, BackmatterDocSummary } from "./doc";
3
- import type { FieldKind } from "./fields";
3
+ import type { FieldDef, FieldKind } from "./fields";
4
4
  import { IMPLICIT_SINGLETON_SLUG, type InferFrontmatter, type ModelDef } from "./model";
5
5
  import { normalizeFrontmatter } from "./zod";
6
6
 
@@ -10,11 +10,6 @@ export type DocLoader = {
10
10
  getDoc(type: string, slug: string): Promise<BackmatterDoc | null>;
11
11
  };
12
12
 
13
- export type TypedDoc<M extends ModelDef> = Omit<BackmatterDoc, "type" | "frontmatter"> & {
14
- type: M["type"];
15
- frontmatter: InferFrontmatter<M>;
16
- };
17
-
18
13
  type KeysOfKind<M extends ModelDef, K extends FieldKind> = {
19
14
  [N in keyof M["fields"]]: M["fields"][N]["kind"] extends K ? N : never;
20
15
  }[keyof M["fields"]];
@@ -29,52 +24,419 @@ export type Where<M extends ModelDef> = Partial<
29
24
  >
30
25
  >;
31
26
 
32
- /** Relation fields that may be resolved (depth 1). */
33
- export type Include<M extends ModelDef> = Partial<Record<KeysOfKind<M, "relation">, true>>;
27
+ type Simplify<T> = { -readonly [K in keyof T]: T[K] } & {};
28
+
29
+ type IsRequired<F> = F extends { required?: infer R }
30
+ ? [Exclude<R, undefined>] extends [true]
31
+ ? true
32
+ : false
33
+ : false;
34
+
35
+ type RelationMode = "load" | "slug";
36
+
37
+ type ModelByType<Models extends readonly ModelDef[], Type extends string> = Extract<
38
+ Models[number],
39
+ { type: Type }
40
+ >;
41
+
42
+ /** `true` selects the stored field. An object on an object or array field is a cut. A relation object is one hop. A blocks field is only `true`. */
43
+ type FieldChoice<Models extends readonly ModelDef[], F, Mode extends RelationMode> = F extends {
44
+ kind: "blocks";
45
+ }
46
+ ? true
47
+ : F extends {
48
+ kind: "object" | "array";
49
+ fields: infer Fields;
50
+ }
51
+ ? true | NestedSelect<Models, Fields, Mode>
52
+ : F extends { kind: "relation" }
53
+ ? RelationChoice<Models, F, Mode>
54
+ : true;
55
+
56
+ type NestedSelect<Models extends readonly ModelDef[], Fields, Mode extends RelationMode> = {
57
+ [K in keyof Fields]?: FieldChoice<Models, Fields[K], Mode>;
58
+ };
59
+
60
+ /** `relationTo` is optional on `FieldDef`, so a direct `{ relationTo: infer To extends string }` does not match. */
61
+ type RelationToOf<F> = F extends { relationTo?: infer To } ? Extract<To, string> : never;
62
+
63
+ type RelationTargetChoice<Models extends readonly ModelDef[], To extends string> =
64
+ ModelByType<Models, To> extends infer Target
65
+ ? [Target] extends [never]
66
+ ? true
67
+ : Target extends { external: true }
68
+ ? true
69
+ : Target extends ModelDef
70
+ ? true | SelectShape<Models, Target, "slug">
71
+ : true
72
+ : true;
73
+
74
+ type RelationChoice<Models extends readonly ModelDef[], F, Mode extends RelationMode> = Mode extends "slug"
75
+ ? true
76
+ : RelationToOf<F> extends infer To
77
+ ? [To] extends [never]
78
+ ? true
79
+ : To extends string
80
+ ? RelationTargetChoice<Models, To>
81
+ : true
82
+ : true;
34
83
 
35
- type RelationTarget<
84
+ type SelectShape<
85
+ Models extends readonly ModelDef[],
36
86
  M extends ModelDef,
37
- N extends keyof M["fields"],
87
+ Mode extends RelationMode = "load",
88
+ > = Simplify<
89
+ {
90
+ [K in keyof M["fields"]]?: FieldChoice<Models, M["fields"][K], Mode>;
91
+ } & (M extends { format: "page" } ? object : { body?: true })
92
+ >;
93
+
94
+ type SelectValue<
38
95
  Models extends readonly ModelDef[],
39
- > = M["fields"][N] extends { relationTo?: infer To }
40
- ? Extract<Models[number], { type: Exclude<To, undefined> }>
41
- : never;
96
+ M extends ModelDef,
97
+ P extends PropertyKey,
98
+ Mode extends RelationMode = "load",
99
+ > = P extends "body"
100
+ ? true
101
+ : P extends keyof M["fields"]
102
+ ? FieldChoice<Models, M["fields"][P], Mode>
103
+ : never;
42
104
 
43
- export type Resolved<
105
+ /** One or more known keys. An empty object is `never`. */
106
+ type SelectArg<
107
+ Models extends readonly ModelDef[],
44
108
  M extends ModelDef,
109
+ K extends PropertyKey,
110
+ Mode extends RelationMode = "load",
111
+ > = [K] extends [never] ? never : { [P in K]: SelectValue<Models, M, P, Mode> };
112
+
113
+ type StoredOf<F, Blocks extends readonly BlockDef[]> = F extends { kind: "number" }
114
+ ? number
115
+ : F extends { kind: "boolean" }
116
+ ? boolean
117
+ : F extends { kind: "blocks" }
118
+ ? BlockValue<Blocks>
119
+ : F extends { kind: "object"; fields: infer Fields }
120
+ ? ObjectShape<Fields, Blocks>
121
+ : F extends { kind: "array"; fields: infer Fields }
122
+ ? ObjectShape<Fields, Blocks>[]
123
+ : F extends { options: infer O extends readonly [string, ...string[]] }
124
+ ? O[number]
125
+ : string;
126
+
127
+ type ObjectShape<Fields, Blocks extends readonly BlockDef[]> = Simplify<
128
+ {
129
+ [K in keyof Fields as IsRequired<Fields[K]> extends true ? K : never]: StoredOf<Fields[K], Blocks>;
130
+ } & {
131
+ [K in keyof Fields as IsRequired<Fields[K]> extends true ? never : K]?: StoredOf<Fields[K], Blocks>;
132
+ }
133
+ >;
134
+
135
+ /** One stored block. An empty `Blocks` has no members, so the value is `never[]`. */
136
+ type BlockValue<Blocks extends readonly BlockDef[]> = [Blocks[number]] extends [never]
137
+ ? never[]
138
+ : Array<
139
+ Blocks[number] extends infer B
140
+ ? B extends { name: infer Name extends string; fields: infer Fields }
141
+ ? { id: string; type: Name; props: ObjectShape<Fields, Blocks> }
142
+ : never
143
+ : never
144
+ >;
145
+
146
+ /** A relation object is always present: the loaded cut, or `null` when the slug cannot be loaded. */
147
+ type RelationObject<F, Sel> = F extends { kind: "relation" }
148
+ ? Sel extends true
149
+ ? false
150
+ : Sel extends readonly unknown[]
151
+ ? false
152
+ : Sel extends object
153
+ ? true
154
+ : false
155
+ : false;
156
+
157
+ type KeyRequired<F, Sel> = RelationObject<F, Sel> extends true ? true : IsRequired<F>;
158
+
159
+ type RelationLoaded<Models extends readonly ModelDef[], F, Sel, Blocks extends readonly BlockDef[]> =
160
+ RelationToOf<F> extends infer To
161
+ ? [To] extends [never]
162
+ ? null
163
+ : To extends string
164
+ ? ModelByType<Models, To> extends infer Target
165
+ ? [Target] extends [never]
166
+ ? null
167
+ : Target extends { external: true }
168
+ ? null
169
+ : Target extends ModelDef
170
+ ? SelectionOf<Models, Target, Sel, "slug", Blocks> | null
171
+ : null
172
+ : null
173
+ : null
174
+ : null;
175
+
176
+ type ValueAt<
177
+ Models extends readonly ModelDef[],
178
+ F,
179
+ Sel,
180
+ Mode extends RelationMode,
181
+ Blocks extends readonly BlockDef[],
182
+ > = Sel extends true
183
+ ? StoredOf<F, Blocks>
184
+ : Sel extends readonly unknown[]
185
+ ? never
186
+ : Sel extends object
187
+ ? F extends { kind: "object"; fields: infer Fields }
188
+ ? CutShape<Models, Fields, Sel, Mode, Blocks>
189
+ : F extends { kind: "array"; fields: infer Fields }
190
+ ? CutShape<Models, Fields, Sel, Mode, Blocks>[]
191
+ : F extends { kind: "relation" }
192
+ ? Mode extends "slug"
193
+ ? never
194
+ : RelationLoaded<Models, F, Sel, Blocks>
195
+ : never
196
+ : never;
197
+
198
+ type CutShape<
45
199
  Models extends readonly ModelDef[],
46
- I extends Include<M>,
200
+ Fields,
201
+ Sel,
202
+ Mode extends RelationMode,
203
+ Blocks extends readonly BlockDef[],
204
+ > = Simplify<
205
+ {
206
+ [K in keyof Sel & keyof Fields as KeyRequired<Fields[K], Sel[K]> extends true ? K : never]: ValueAt<
207
+ Models,
208
+ Fields[K],
209
+ Sel[K],
210
+ Mode,
211
+ Blocks
212
+ >;
213
+ } & {
214
+ [K in keyof Sel & keyof Fields as KeyRequired<Fields[K], Sel[K]> extends true ? never : K]?: ValueAt<
215
+ Models,
216
+ Fields[K],
217
+ Sel[K],
218
+ Mode,
219
+ Blocks
220
+ >;
221
+ }
222
+ >;
223
+
224
+ type SelectionOf<
225
+ Models extends readonly ModelDef[],
226
+ M extends ModelDef,
227
+ Sel,
228
+ Mode extends RelationMode = "load",
229
+ Blocks extends readonly BlockDef[] = [],
230
+ > = Simplify<
231
+ { slug: string } &
232
+ ("body" extends keyof Sel ? (M extends { format: "page" } ? object : { body: string }) : object) &
233
+ CutShape<Models, M["fields"], Sel, Mode, Blocks>
234
+ >;
235
+
236
+ type SelectFor<
237
+ Models extends readonly ModelDef[],
238
+ M extends ModelDef,
239
+ K extends PropertyKey,
240
+ Mode extends RelationMode = "load",
47
241
  > = {
48
- [N in keyof I as I[N] extends true ? N : never]: N extends keyof M["fields"]
49
- ? TypedDoc<RelationTarget<M, N, Models>> | null
50
- : never;
242
+ [P in K]: SelectValue<Models, M, P, Mode>;
51
243
  };
52
244
 
53
- type ModelGet<M extends ModelDef> = M["singleton"] extends true
54
- ? () => Promise<TypedDoc<M> | null>
55
- : (slug: string) => Promise<TypedDoc<M> | null>;
245
+ type ModelGet<Models extends readonly ModelDef[], M extends ModelDef, Blocks extends readonly BlockDef[]> =
246
+ M["singleton"] extends true
247
+ ? <const K extends keyof SelectShape<Models, M>, const S extends SelectArg<Models, M, K>>(
248
+ select: SelectFor<Models, M, K> & S,
249
+ ) => Promise<SelectionOf<Models, M, S, "load", Blocks> | null>
250
+ : <const K extends keyof SelectShape<Models, M>, const S extends SelectArg<Models, M, K>>(
251
+ slug: string,
252
+ select: SelectFor<Models, M, K> & S,
253
+ ) => Promise<SelectionOf<Models, M, S, "load", Blocks> | null>;
56
254
 
57
- export type ModelQuery<M extends ModelDef, Models extends readonly ModelDef[]> = {
58
- get: ModelGet<M>;
59
- findMany<I extends Include<M> = {}>(opts?: {
255
+ export type ModelQuery<
256
+ M extends ModelDef,
257
+ Models extends readonly ModelDef[] = readonly [M],
258
+ Blocks extends readonly BlockDef[] = [],
259
+ > = {
260
+ get: ModelGet<Models, M, Blocks>;
261
+ findMany<const K extends keyof SelectShape<Models, M>, const S extends SelectArg<Models, M, K>>(opts: {
60
262
  where?: Where<M>;
61
- include?: I;
62
- }): Promise<Array<TypedDoc<M> & Resolved<M, Models, I>>>;
263
+ select: SelectFor<Models, M, K> & S;
264
+ }): Promise<Array<SelectionOf<Models, M, S, "load", Blocks>>>;
63
265
  };
64
266
 
65
- export type Query<Models extends readonly ModelDef[]> = {
66
- [M in Models[number] as M["type"]]: ModelQuery<M, Models>;
267
+ export type Query<Models extends readonly ModelDef[], Blocks extends readonly BlockDef[] = []> = {
268
+ [M in Models[number] as M["type"]]: ModelQuery<M, Models, Blocks>;
67
269
  };
68
270
 
69
271
  type RawOpts = {
70
272
  where?: Record<string, unknown>;
71
- include?: Record<string, boolean | undefined>;
273
+ select: Record<string, unknown>;
72
274
  };
73
275
 
74
- export function createQuery<const Models extends readonly ModelDef[]>(
75
- models: Models,
76
- loader: DocLoader,
77
- ): Query<Models> {
276
+ function isRecord(value: unknown): value is Record<string, unknown> {
277
+ return typeof value === "object" && value !== null && !Array.isArray(value);
278
+ }
279
+
280
+ function withoutBody(select: Record<string, unknown>): Record<string, unknown> {
281
+ if (!("body" in select)) return select;
282
+ const rest = { ...select };
283
+ delete rest.body;
284
+ return rest;
285
+ }
286
+
287
+ /** A blocks `true` keeps the stored array and does not walk `props`. Anything else is omitted. */
288
+ function storedBlockArray(value: unknown): unknown[] | undefined {
289
+ return Array.isArray(value) ? value : undefined;
290
+ }
291
+
292
+ type LoadDoc = (type: string, slug: string) => Promise<BackmatterDoc | null>;
293
+
294
+ /** One file-backed hop. A missing slug or file is `null`. A hopped relation is not loaded. */
295
+ function queueRelation(
296
+ out: Record<string, unknown>,
297
+ loads: Promise<void>[],
298
+ key: string,
299
+ field: FieldDef,
300
+ storedValue: unknown,
301
+ wanted: Record<string, unknown>,
302
+ load: LoadDoc,
303
+ models: Map<string, ModelDef>,
304
+ ) {
305
+ const slug = relationSlug(storedValue);
306
+ const relationTo = field.relationTo;
307
+ const target = relationTo ? models.get(relationTo) : undefined;
308
+ if (!slug || !relationTo || !target || target.external === true) {
309
+ out[key] = null;
310
+ return;
311
+ }
312
+ loads.push(
313
+ load(relationTo, slug).then(async (related) => {
314
+ out[key] = related ? await selected(target, related, wanted, load, models, true) : null;
315
+ }),
316
+ );
317
+ }
318
+
319
+ /** Cut `stored` to `select`. A missing value or an empty cut is omitted. `true` copies the stored leaf. */
320
+ async function cutFields(
321
+ fields: Record<string, FieldDef> | undefined,
322
+ stored: Record<string, unknown>,
323
+ select: Record<string, unknown>,
324
+ load: LoadDoc,
325
+ models: Map<string, ModelDef>,
326
+ hopped: boolean,
327
+ ): Promise<Record<string, unknown> | undefined> {
328
+ const out: Record<string, unknown> = {};
329
+ const loads: Promise<void>[] = [];
330
+ for (const [key, wanted] of Object.entries(select)) {
331
+ const field = fields?.[key];
332
+ if (!field) continue;
333
+ if (wanted === true) {
334
+ if (!(key in stored)) continue;
335
+ if (field.kind === "blocks") {
336
+ const value = storedBlockArray(stored[key]);
337
+ if (value) out[key] = value;
338
+ } else {
339
+ out[key] = stored[key];
340
+ }
341
+ continue;
342
+ }
343
+ if (!isRecord(wanted)) continue;
344
+ if (field.kind === "relation") {
345
+ if (hopped) continue;
346
+ queueRelation(out, loads, key, field, stored[key], wanted, load, models);
347
+ continue;
348
+ }
349
+ if (field.kind !== "object" && field.kind !== "array") continue;
350
+ if (!(key in stored)) continue;
351
+ loads.push(
352
+ cutComposite(field, stored[key], wanted, load, models, hopped).then((cut) => {
353
+ if (cut !== undefined) out[key] = cut;
354
+ }),
355
+ );
356
+ }
357
+ if (loads.length > 0) await Promise.all(loads);
358
+ return Object.keys(out).length === 0 ? undefined : out;
359
+ }
360
+
361
+ async function cutComposite(
362
+ field: FieldDef,
363
+ stored: unknown,
364
+ select: Record<string, unknown>,
365
+ load: LoadDoc,
366
+ models: Map<string, ModelDef>,
367
+ hopped: boolean,
368
+ ): Promise<unknown> {
369
+ if (stored == null) return undefined;
370
+ if (field.kind === "array") {
371
+ if (!Array.isArray(stored)) return undefined;
372
+ const items = await Promise.all(
373
+ stored.map(async (item) => {
374
+ if (!isRecord(item)) return undefined;
375
+ return cutFields(field.fields, item, select, load, models, hopped);
376
+ }),
377
+ );
378
+ return items.filter((item): item is Record<string, unknown> => item !== undefined);
379
+ }
380
+ if (field.kind === "object") {
381
+ if (!isRecord(stored)) return undefined;
382
+ return cutFields(field.fields, stored, select, load, models, hopped);
383
+ }
384
+ return undefined;
385
+ }
386
+
387
+ function relationSlug(value: unknown): string | null {
388
+ if (typeof value !== "string" || value.trim() === "") return null;
389
+ return value;
390
+ }
391
+
392
+ async function selected(
393
+ model: ModelDef,
394
+ doc: { slug: string; frontmatter: Record<string, unknown>; body: string },
395
+ select: Record<string, unknown>,
396
+ load: LoadDoc,
397
+ models: Map<string, ModelDef>,
398
+ hopped: boolean,
399
+ ) {
400
+ const out: Record<string, unknown> = { slug: doc.slug };
401
+ const loads: Promise<void>[] = [];
402
+ for (const [key, wanted] of Object.entries(select)) {
403
+ if (key === "body") {
404
+ if (model.format !== "page" && wanted === true) out.body = doc.body;
405
+ continue;
406
+ }
407
+ const field = model.fields[key];
408
+ if (field?.kind === "blocks") {
409
+ if (wanted === true) {
410
+ const value = storedBlockArray(doc.frontmatter[key]);
411
+ if (value) out[key] = value;
412
+ }
413
+ continue;
414
+ }
415
+ if (field?.kind === "relation" && isRecord(wanted)) {
416
+ if (hopped) continue;
417
+ queueRelation(out, loads, key, field, doc.frontmatter[key], wanted, load, models);
418
+ continue;
419
+ }
420
+ if (wanted === true) {
421
+ if (key in doc.frontmatter) out[key] = doc.frontmatter[key];
422
+ continue;
423
+ }
424
+ if (!field || !isRecord(wanted) || (field.kind !== "object" && field.kind !== "array")) continue;
425
+ if (!(key in doc.frontmatter)) continue;
426
+ loads.push(
427
+ cutComposite(field, doc.frontmatter[key], wanted, load, models, hopped).then((cut) => {
428
+ if (cut !== undefined) out[key] = cut;
429
+ }),
430
+ );
431
+ }
432
+ if (loads.length > 0) await Promise.all(loads);
433
+ return out;
434
+ }
435
+
436
+ export function createQuery<
437
+ const Models extends readonly ModelDef[],
438
+ const Blocks extends readonly BlockDef[] = [],
439
+ >(models: Models, loader: DocLoader, blocks?: Blocks): Query<Models, Blocks> {
78
440
  const byType = new Map<string, ModelDef>(models.map((m) => [m.type, m]));
79
441
 
80
442
  function slugForGet(type: string, arg?: string): string {
@@ -92,6 +454,27 @@ export function createQuery<const Models extends readonly ModelDef[]>(
92
454
  return { ...doc, frontmatter: normalizeFrontmatter(doc.frontmatter) };
93
455
  }
94
456
 
457
+ function loadCached(
458
+ cache: Map<string, Promise<BackmatterDoc | null>>,
459
+ type: string,
460
+ slug: string,
461
+ ): Promise<BackmatterDoc | null> {
462
+ const key = `${type}:${slug}`;
463
+ const hit = cache.get(key);
464
+ if (hit) return hit;
465
+ const pending = get(type, slug);
466
+ cache.set(key, pending);
467
+ return pending;
468
+ }
469
+
470
+ async function read(type: string, slug: string, select: Record<string, unknown>) {
471
+ const model = byType.get(type);
472
+ const doc = await get(type, slug);
473
+ if (!doc || !model) return null;
474
+ const cache = new Map<string, Promise<BackmatterDoc | null>>();
475
+ return selected(model, doc, select, (rel, id) => loadCached(cache, rel, id), byType, false);
476
+ }
477
+
95
478
  function matchesWhere(doc: BackmatterDoc, where: Record<string, unknown>): boolean {
96
479
  for (const [key, expected] of Object.entries(where)) {
97
480
  if (expected === undefined) continue;
@@ -101,71 +484,67 @@ export function createQuery<const Models extends readonly ModelDef[]>(
101
484
  return true;
102
485
  }
103
486
 
104
- async function findMany(type: string, opts?: RawOpts): Promise<BackmatterDoc[]> {
487
+ async function findMany(type: string, opts: RawOpts) {
105
488
  const model = byType.get(type);
106
- const whereSlug = opts?.where?.slug;
489
+ if (!model) return [];
490
+ const whereSlug = opts.where?.slug;
107
491
 
108
- let docs: BackmatterDoc[];
492
+ let docs: Array<BackmatterDoc & { bodyLoaded: boolean }>;
109
493
  if (typeof whereSlug === "string") {
110
494
  const doc = await get(type, whereSlug);
111
- docs = doc ? [doc] : [];
495
+ docs = doc ? [{ ...doc, bodyLoaded: true }] : [];
112
496
  } else {
113
497
  const summaries = await loader.listDocs({ type });
114
498
  const fromList = summaries.filter((s) => s.frontmatter != null);
115
499
  const missing = summaries.filter((s) => s.frontmatter == null);
116
500
  const loaded = await Promise.all(missing.map((s) => get(type, s.slug)));
117
501
  docs = [
118
- ...fromList.map((s) => ({
119
- type: s.type,
120
- slug: s.slug,
121
- source: "head" as const,
122
- frontmatter: normalizeFrontmatter(s.frontmatter ?? {}),
123
- body: "",
124
- raw: "",
125
- })),
126
- ...loaded.filter((d): d is BackmatterDoc => d !== null),
502
+ ...fromList.map((s) => {
503
+ const body = s.body;
504
+ const bodyLoaded = typeof body === "string";
505
+ return {
506
+ type: s.type,
507
+ slug: s.slug,
508
+ source: "head" as const,
509
+ frontmatter: normalizeFrontmatter(s.frontmatter ?? {}),
510
+ body: bodyLoaded ? body : "",
511
+ raw: "",
512
+ bodyLoaded,
513
+ };
514
+ }),
515
+ ...loaded.flatMap((doc) => (doc ? [{ ...doc, bodyLoaded: true }] : [])),
127
516
  ];
128
517
  }
129
518
 
130
- const filtered = opts?.where ? docs.filter((d) => matchesWhere(d, opts.where!)) : docs;
131
- const include = opts?.include;
132
- if (!include || !model) return filtered;
133
-
134
- const relationCache = new Map<string, Promise<BackmatterDoc | null>>();
135
- const getCached = (target: string, slug: string) => {
136
- const key = `${target}:${slug}`;
137
- let promise = relationCache.get(key);
138
- if (!promise) {
139
- promise = get(target, slug);
140
- relationCache.set(key, promise);
141
- }
142
- return promise;
143
- };
144
-
519
+ const filtered = opts.where ? docs.filter((d) => matchesWhere(d, opts.where!)) : docs;
520
+ const wantsBody = opts.select.body === true && model.format !== "page";
521
+ const cache = new Map<string, Promise<BackmatterDoc | null>>();
522
+ const load = (rel: string, id: string) => loadCached(cache, rel, id);
145
523
  return Promise.all(
146
524
  filtered.map(async (doc) => {
147
- const extra: Record<string, BackmatterDoc | null> = {};
148
- for (const [name, on] of Object.entries(include)) {
149
- if (!on) continue;
150
- const field = model.fields[name];
151
- const target = field?.kind === "relation" ? field.relationTo : undefined;
152
- const relatedSlug = doc.frontmatter[name];
153
- extra[name] =
154
- target && typeof relatedSlug === "string" && relatedSlug.length > 0
155
- ? await getCached(target, relatedSlug)
156
- : null;
525
+ if (!wantsBody || doc.bodyLoaded) {
526
+ return selected(model, doc, opts.select, load, byType, false);
157
527
  }
158
- return { ...doc, ...extra };
528
+ const loaded = await get(type, doc.slug);
529
+ const select = loaded ? opts.select : withoutBody(opts.select);
530
+ return selected(model, loaded ?? doc, select, load, byType, false);
159
531
  }),
160
532
  );
161
533
  }
162
534
 
163
535
  const query: Record<string, unknown> = {};
164
536
  for (const m of models) {
165
- query[m.type] = {
166
- get: (arg?: string) => get(m.type, slugForGet(m.type, arg)),
167
- findMany: (opts?: RawOpts) => findMany(m.type, opts),
168
- };
537
+ query[m.type] =
538
+ m.singleton === true
539
+ ? {
540
+ get: (select: Record<string, unknown>) => read(m.type, slugForGet(m.type), select),
541
+ findMany: (opts: RawOpts) => findMany(m.type, opts),
542
+ }
543
+ : {
544
+ get: (slug: string, select: Record<string, unknown>) =>
545
+ read(m.type, slugForGet(m.type, slug), select),
546
+ findMany: (opts: RawOpts) => findMany(m.type, opts),
547
+ };
169
548
  }
170
- return query as Query<Models>;
549
+ return query as Query<Models, Blocks>;
171
550
  }
@@ -0,0 +1,12 @@
1
+ // packages/core/src/relation-match.ts
2
+ export function matchesWhere(
3
+ doc: { slug: string; frontmatter: Record<string, unknown> },
4
+ where: Record<string, string | number | boolean> | undefined,
5
+ ): boolean {
6
+ if (where === undefined) return true;
7
+ for (const [key, expected] of Object.entries(where)) {
8
+ const actual = key === "slug" ? doc.slug : doc.frontmatter[key];
9
+ if (actual !== expected) return false;
10
+ }
11
+ return true;
12
+ }