@tschk/moonshine-astro 0.4.4 → 0.4.80

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/content.ts ADDED
@@ -0,0 +1,1523 @@
1
+ /** Independent host-free Astro Content Collections, Live Content Layer, and Zod-compatible schema runtime (`astro:content`). */
2
+ import type { ActionInputIssue, SchemaValidator } from "./actions";
3
+
4
+ export interface ZodIssue extends ActionInputIssue {
5
+ code: string;
6
+ path: (string | number)[];
7
+ message: string;
8
+ }
9
+
10
+ export class ZodError extends Error {
11
+ readonly issues: ZodIssue[];
12
+
13
+ constructor(issues: ZodIssue[]) {
14
+ super(
15
+ issues.length > 0
16
+ ? issues
17
+ .map((i) =>
18
+ i.path.length > 0
19
+ ? `${i.path.join(".")}: ${i.message}`
20
+ : i.message,
21
+ )
22
+ .join("; ")
23
+ : "Validation failed",
24
+ );
25
+ this.name = "ZodError";
26
+ this.issues = issues;
27
+ }
28
+
29
+ get errors(): ZodIssue[] {
30
+ return this.issues;
31
+ }
32
+ }
33
+
34
+ export type SafeParseResult<T> =
35
+ | { success: true; data: T; error?: undefined }
36
+ | { success: false; data?: undefined; error: ZodError };
37
+
38
+ export class ZodType<Output = any, Input = Output> {
39
+ declare readonly _output: Output;
40
+ declare readonly _input: Input;
41
+ private readonly validator: (
42
+ value: unknown,
43
+ path: (string | number)[],
44
+ ) => { ok: true; value: Output } | { ok: false; issues: ZodIssue[] };
45
+
46
+ constructor(
47
+ validator: (
48
+ value: unknown,
49
+ path: (string | number)[],
50
+ ) => { ok: true; value: Output } | { ok: false; issues: ZodIssue[] },
51
+ ) {
52
+ this.validator = validator;
53
+ }
54
+
55
+ /** Internal path-aware validation helper. */
56
+ _validate(
57
+ value: unknown,
58
+ path: (string | number)[],
59
+ ): { ok: true; value: Output } | { ok: false; issues: ZodIssue[] } {
60
+ return this.validator(value, path);
61
+ }
62
+
63
+ safeParse(value: unknown): SafeParseResult<Output> {
64
+ const res = this.validator(value, []);
65
+ if (res.ok) {
66
+ return { success: true, data: res.value };
67
+ }
68
+ return { success: false, error: new ZodError(res.issues) };
69
+ }
70
+
71
+ parse(value: unknown): Output {
72
+ const res = this.safeParse(value);
73
+ if (!res.success) {
74
+ throw res.error;
75
+ }
76
+ return res.data;
77
+ }
78
+
79
+ optional(): ZodType<Output | undefined, Input | undefined> {
80
+ return new ZodType<Output | undefined, Input | undefined>((val, path) => {
81
+ if (val === undefined) return { ok: true, value: undefined };
82
+ return this._validate(val, path);
83
+ });
84
+ }
85
+
86
+ nullable(): ZodType<Output | null, Input | null> {
87
+ return new ZodType<Output | null, Input | null>((val, path) => {
88
+ if (val === null) return { ok: true, value: null };
89
+ return this._validate(val, path);
90
+ });
91
+ }
92
+
93
+ nullish(): ZodType<Output | null | undefined, Input | null | undefined> {
94
+ return new ZodType<Output | null | undefined, Input | null | undefined>(
95
+ (val, path) => {
96
+ if (val === undefined || val === null) {
97
+ return { ok: true, value: val };
98
+ }
99
+ return this._validate(val, path);
100
+ },
101
+ );
102
+ }
103
+
104
+ default(
105
+ defaultValue: Output | (() => Output),
106
+ ): ZodType<Output, Input | undefined> {
107
+ return new ZodType<Output, Input | undefined>((val, path) => {
108
+ if (val === undefined) {
109
+ const resolved =
110
+ typeof defaultValue === "function"
111
+ ? (defaultValue as () => Output)()
112
+ : defaultValue;
113
+ return { ok: true, value: resolved };
114
+ }
115
+ return this._validate(val, path);
116
+ });
117
+ }
118
+
119
+ transform<NewOut>(fn: (val: Output) => NewOut): ZodType<NewOut, Input> {
120
+ return new ZodType<NewOut, Input>((val, path) => {
121
+ const base = this._validate(val, path);
122
+ if (!base.ok) return base;
123
+ try {
124
+ return { ok: true, value: fn(base.value) };
125
+ } catch (err) {
126
+ return {
127
+ ok: false,
128
+ issues: [
129
+ {
130
+ code: "custom",
131
+ path,
132
+ message: err instanceof Error ? err.message : String(err),
133
+ },
134
+ ],
135
+ };
136
+ }
137
+ });
138
+ }
139
+
140
+ refine(
141
+ check: (val: Output) => boolean,
142
+ messageOrOpts?: string | { message?: string; path?: (string | number)[] },
143
+ ): ZodType<Output, Input> {
144
+ return new ZodType<Output, Input>((val, path) => {
145
+ const base = this._validate(val, path);
146
+ if (!base.ok) return base;
147
+ if (!check(base.value)) {
148
+ const msg =
149
+ typeof messageOrOpts === "string"
150
+ ? messageOrOpts
151
+ : (messageOrOpts?.message ?? "Invalid input");
152
+ const extraPath =
153
+ typeof messageOrOpts === "object" && messageOrOpts?.path
154
+ ? messageOrOpts.path
155
+ : [];
156
+ return {
157
+ ok: false,
158
+ issues: [
159
+ {
160
+ code: "custom",
161
+ path: [...path, ...extraPath],
162
+ message: msg,
163
+ },
164
+ ],
165
+ };
166
+ }
167
+ return base;
168
+ });
169
+ }
170
+
171
+ or<Other extends ZodType<any, any>>(
172
+ other: Other,
173
+ ): ZodType<Output | Other["_output"], Input | Other["_input"]> {
174
+ return new ZodType((val, path) => {
175
+ const first = this._validate(val, path);
176
+ if (first.ok) return first;
177
+ const second = other._validate(val, path);
178
+ if (second.ok) return second;
179
+ return { ok: false, issues: [...first.issues, ...second.issues] };
180
+ });
181
+ }
182
+
183
+ array(): ZodArray<ZodType<Output, Input>> {
184
+ return new ZodArray<ZodType<Output, Input>>(this);
185
+ }
186
+ }
187
+
188
+ export class ZodString extends ZodType<string, string> {
189
+ constructor(
190
+ checks: Array<
191
+ | { kind: "transform"; fn: (val: string) => string }
192
+ | { kind: "check"; fn: (val: string) => string | undefined }
193
+ > = [],
194
+ coerce = false,
195
+ ) {
196
+ super((val, path) => {
197
+ let current: unknown = val;
198
+ if (coerce && current !== undefined && current !== null) {
199
+ current = String(current);
200
+ }
201
+ if (typeof current !== "string") {
202
+ return {
203
+ ok: false,
204
+ issues: [
205
+ {
206
+ code: "invalid_type",
207
+ path,
208
+ message: `Expected string, received ${typeof current}`,
209
+ },
210
+ ],
211
+ };
212
+ }
213
+ let str = current;
214
+ const issues: ZodIssue[] = [];
215
+ for (const step of checks) {
216
+ if (step.kind === "transform") {
217
+ str = step.fn(str);
218
+ } else {
219
+ const err = step.fn(str);
220
+ if (err) {
221
+ issues.push({ code: "invalid_string", path, message: err });
222
+ }
223
+ }
224
+ }
225
+ if (issues.length > 0) return { ok: false, issues };
226
+ return { ok: true, value: str };
227
+ });
228
+ this.checks = checks;
229
+ this.coerce = coerce;
230
+ }
231
+
232
+ private readonly checks: Array<
233
+ | { kind: "transform"; fn: (val: string) => string }
234
+ | { kind: "check"; fn: (val: string) => string | undefined }
235
+ >;
236
+ private readonly coerce: boolean;
237
+
238
+ private addCheck(fn: (val: string) => string | undefined): ZodString {
239
+ return new ZodString([...this.checks, { kind: "check", fn }], this.coerce);
240
+ }
241
+
242
+ private addTransform(fn: (val: string) => string): ZodString {
243
+ return new ZodString(
244
+ [...this.checks, { kind: "transform", fn }],
245
+ this.coerce,
246
+ );
247
+ }
248
+
249
+ min(length: number, message?: string): ZodString {
250
+ return this.addCheck((s) =>
251
+ s.length >= length
252
+ ? undefined
253
+ : (message ?? `String must contain at least ${length} character(s)`),
254
+ );
255
+ }
256
+
257
+ max(length: number, message?: string): ZodString {
258
+ return this.addCheck((s) =>
259
+ s.length <= length
260
+ ? undefined
261
+ : (message ?? `String must contain at most ${length} character(s)`),
262
+ );
263
+ }
264
+
265
+ length(len: number, message?: string): ZodString {
266
+ return this.addCheck((s) =>
267
+ s.length === len
268
+ ? undefined
269
+ : (message ?? `String must contain exactly ${len} character(s)`),
270
+ );
271
+ }
272
+
273
+ nonempty(message?: string): ZodString {
274
+ return this.min(1, message ?? "String cannot be empty");
275
+ }
276
+
277
+ email(message?: string): ZodString {
278
+ return this.addCheck((s) =>
279
+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)
280
+ ? undefined
281
+ : (message ?? "Invalid email"),
282
+ );
283
+ }
284
+
285
+ url(message?: string): ZodString {
286
+ return this.addCheck((s) => {
287
+ try {
288
+ const parsed = new URL(s);
289
+ return parsed.href ? undefined : (message ?? "Invalid url");
290
+ } catch {
291
+ return message ?? "Invalid url";
292
+ }
293
+ });
294
+ }
295
+
296
+ regex(re: RegExp, message?: string): ZodString {
297
+ return this.addCheck((s) =>
298
+ re.test(s) ? undefined : (message ?? "Invalid"),
299
+ );
300
+ }
301
+
302
+ startsWith(prefix: string, message?: string): ZodString {
303
+ return this.addCheck((s) =>
304
+ s.startsWith(prefix)
305
+ ? undefined
306
+ : (message ?? `Invalid input: must start with "${prefix}"`),
307
+ );
308
+ }
309
+
310
+ endsWith(suffix: string, message?: string): ZodString {
311
+ return this.addCheck((s) =>
312
+ s.endsWith(suffix)
313
+ ? undefined
314
+ : (message ?? `Invalid input: must end with "${suffix}"`),
315
+ );
316
+ }
317
+
318
+ includes(substring: string, message?: string): ZodString {
319
+ return this.addCheck((s) =>
320
+ s.includes(substring)
321
+ ? undefined
322
+ : (message ?? `Invalid input: must include "${substring}"`),
323
+ );
324
+ }
325
+
326
+ trim(): ZodString {
327
+ return this.addTransform((s) => s.trim());
328
+ }
329
+
330
+ toLowerCase(): ZodString {
331
+ return this.addTransform((s) => s.toLowerCase());
332
+ }
333
+
334
+ toUpperCase(): ZodString {
335
+ return this.addTransform((s) => s.toUpperCase());
336
+ }
337
+ }
338
+
339
+ export class ZodNumber extends ZodType<number, number> {
340
+ private readonly checks: Array<(val: number) => string | undefined>;
341
+ private readonly coerce: boolean;
342
+
343
+ constructor(
344
+ checks: Array<(val: number) => string | undefined> = [],
345
+ coerce = false,
346
+ ) {
347
+ super((val, path) => {
348
+ const current = coerce ? Number(val) : val;
349
+ if (typeof current !== "number" || Number.isNaN(current)) {
350
+ return {
351
+ ok: false,
352
+ issues: [
353
+ {
354
+ code: "invalid_type",
355
+ path,
356
+ message: `Expected number, received ${typeof val}`,
357
+ },
358
+ ],
359
+ };
360
+ }
361
+ const issues: ZodIssue[] = [];
362
+ for (const check of checks) {
363
+ const err = check(current);
364
+ if (err) {
365
+ issues.push({ code: "invalid_number", path, message: err });
366
+ }
367
+ }
368
+ if (issues.length > 0) return { ok: false, issues };
369
+ return { ok: true, value: current };
370
+ });
371
+ this.checks = checks;
372
+ this.coerce = coerce;
373
+ }
374
+
375
+ private addCheck(fn: (val: number) => string | undefined): ZodNumber {
376
+ return new ZodNumber([...this.checks, fn], this.coerce);
377
+ }
378
+
379
+ min(value: number, message?: string): ZodNumber {
380
+ return this.addCheck((n) =>
381
+ n >= value
382
+ ? undefined
383
+ : (message ?? `Number must be greater than or equal to ${value}`),
384
+ );
385
+ }
386
+
387
+ max(value: number, message?: string): ZodNumber {
388
+ return this.addCheck((n) =>
389
+ n <= value
390
+ ? undefined
391
+ : (message ?? `Number must be less than or equal to ${value}`),
392
+ );
393
+ }
394
+
395
+ int(message?: string): ZodNumber {
396
+ return this.addCheck((n) =>
397
+ Number.isInteger(n)
398
+ ? undefined
399
+ : (message ?? "Expected integer, received float"),
400
+ );
401
+ }
402
+
403
+ positive(message?: string): ZodNumber {
404
+ return this.addCheck((n) =>
405
+ n > 0 ? undefined : (message ?? "Number must be greater than 0"),
406
+ );
407
+ }
408
+
409
+ nonnegative(message?: string): ZodNumber {
410
+ return this.addCheck((n) =>
411
+ n >= 0
412
+ ? undefined
413
+ : (message ?? "Number must be greater than or equal to 0"),
414
+ );
415
+ }
416
+
417
+ negative(message?: string): ZodNumber {
418
+ return this.addCheck((n) =>
419
+ n < 0 ? undefined : (message ?? "Number must be less than 0"),
420
+ );
421
+ }
422
+
423
+ nonpositive(message?: string): ZodNumber {
424
+ return this.addCheck((n) =>
425
+ n <= 0
426
+ ? undefined
427
+ : (message ?? "Number must be less than or equal to 0"),
428
+ );
429
+ }
430
+
431
+ finite(message?: string): ZodNumber {
432
+ return this.addCheck((n) =>
433
+ Number.isFinite(n) ? undefined : (message ?? "Number must be finite"),
434
+ );
435
+ }
436
+ }
437
+
438
+ export class ZodBoolean extends ZodType<boolean, boolean> {
439
+ constructor(coerce = false) {
440
+ super((val, path) => {
441
+ const current = coerce ? Boolean(val) : val;
442
+ if (typeof current !== "boolean") {
443
+ return {
444
+ ok: false,
445
+ issues: [
446
+ {
447
+ code: "invalid_type",
448
+ path,
449
+ message: `Expected boolean, received ${typeof val}`,
450
+ },
451
+ ],
452
+ };
453
+ }
454
+ return { ok: true, value: current };
455
+ });
456
+ }
457
+ }
458
+
459
+ export class ZodDate extends ZodType<Date, Date | string | number> {
460
+ private readonly checks: Array<(val: Date) => string | undefined>;
461
+ private readonly coerce: boolean;
462
+
463
+ constructor(
464
+ checks: Array<(val: Date) => string | undefined> = [],
465
+ coerce = false,
466
+ ) {
467
+ super((val, path) => {
468
+ const current =
469
+ coerce && (typeof val === "string" || typeof val === "number")
470
+ ? new Date(val)
471
+ : val;
472
+ if (!(current instanceof Date) || Number.isNaN(current.getTime())) {
473
+ return {
474
+ ok: false,
475
+ issues: [
476
+ {
477
+ code: "invalid_date",
478
+ path,
479
+ message: "Invalid date",
480
+ },
481
+ ],
482
+ };
483
+ }
484
+ const issues: ZodIssue[] = [];
485
+ for (const check of checks) {
486
+ const err = check(current);
487
+ if (err) {
488
+ issues.push({ code: "invalid_date", path, message: err });
489
+ }
490
+ }
491
+ if (issues.length > 0) return { ok: false, issues };
492
+ return { ok: true, value: current };
493
+ });
494
+ this.checks = checks;
495
+ this.coerce = coerce;
496
+ }
497
+
498
+ min(minDate: Date, message?: string): ZodDate {
499
+ return new ZodDate(
500
+ [
501
+ ...this.checks,
502
+ (d) =>
503
+ d.getTime() >= minDate.getTime()
504
+ ? undefined
505
+ : (message ??
506
+ `Date must be greater than or equal to ${minDate.toISOString()}`),
507
+ ],
508
+ this.coerce,
509
+ );
510
+ }
511
+
512
+ max(maxDate: Date, message?: string): ZodDate {
513
+ return new ZodDate(
514
+ [
515
+ ...this.checks,
516
+ (d) =>
517
+ d.getTime() <= maxDate.getTime()
518
+ ? undefined
519
+ : (message ??
520
+ `Date must be smaller than or equal to ${maxDate.toISOString()}`),
521
+ ],
522
+ this.coerce,
523
+ );
524
+ }
525
+ }
526
+
527
+ export class ZodArray<Item extends ZodType<any, any>> extends ZodType<
528
+ Item["_output"][],
529
+ Item["_input"][]
530
+ > {
531
+ readonly element: Item;
532
+ private readonly checks: Array<
533
+ (arr: Item["_output"][]) => string | undefined
534
+ >;
535
+
536
+ constructor(
537
+ element: Item,
538
+ checks: Array<(arr: Item["_output"][]) => string | undefined> = [],
539
+ ) {
540
+ super((val, path) => {
541
+ if (!Array.isArray(val)) {
542
+ return {
543
+ ok: false,
544
+ issues: [
545
+ {
546
+ code: "invalid_type",
547
+ path,
548
+ message: `Expected array, received ${typeof val}`,
549
+ },
550
+ ],
551
+ };
552
+ }
553
+ const out: Item["_output"][] = [];
554
+ const issues: ZodIssue[] = [];
555
+ for (let i = 0; i < val.length; i++) {
556
+ const itemRes = element._validate(val[i], [...path, i]);
557
+ if (itemRes.ok) {
558
+ out.push(itemRes.value);
559
+ } else {
560
+ issues.push(...itemRes.issues);
561
+ }
562
+ }
563
+ if (issues.length > 0) return { ok: false, issues };
564
+ for (const check of checks) {
565
+ const err = check(out);
566
+ if (err) {
567
+ issues.push({ code: "invalid_array", path, message: err });
568
+ }
569
+ }
570
+ if (issues.length > 0) return { ok: false, issues };
571
+ return { ok: true, value: out };
572
+ });
573
+ this.element = element;
574
+ this.checks = checks;
575
+ }
576
+
577
+ private addCheck(
578
+ fn: (arr: Item["_output"][]) => string | undefined,
579
+ ): ZodArray<Item> {
580
+ return new ZodArray(this.element, [...this.checks, fn]);
581
+ }
582
+
583
+ min(length: number, message?: string): ZodArray<Item> {
584
+ return this.addCheck((arr) =>
585
+ arr.length >= length
586
+ ? undefined
587
+ : (message ?? `Array must contain at least ${length} element(s)`),
588
+ );
589
+ }
590
+
591
+ max(length: number, message?: string): ZodArray<Item> {
592
+ return this.addCheck((arr) =>
593
+ arr.length <= length
594
+ ? undefined
595
+ : (message ?? `Array must contain at most ${length} element(s)`),
596
+ );
597
+ }
598
+
599
+ length(len: number, message?: string): ZodArray<Item> {
600
+ return this.addCheck((arr) =>
601
+ arr.length === len
602
+ ? undefined
603
+ : (message ?? `Array must contain exactly ${len} element(s)`),
604
+ );
605
+ }
606
+
607
+ nonempty(message?: string): ZodArray<Item> {
608
+ return this.min(1, message ?? "Array cannot be empty");
609
+ }
610
+ }
611
+
612
+ export type ZodRawShape = Record<string, ZodType<any, any>>;
613
+
614
+ type OptionalKeys<S extends ZodRawShape> = {
615
+ [K in keyof S]: undefined extends S[K]["_output"] ? K : never;
616
+ }[keyof S];
617
+
618
+ type RequiredKeys<S extends ZodRawShape> = Exclude<keyof S, OptionalKeys<S>>;
619
+
620
+ export type InferObjectOutput<S extends ZodRawShape> = {
621
+ [K in RequiredKeys<S>]: S[K]["_output"];
622
+ } & {
623
+ [K in OptionalKeys<S>]?: S[K]["_output"];
624
+ };
625
+
626
+ export class ZodObject<Shape extends ZodRawShape> extends ZodType<
627
+ InferObjectOutput<Shape>,
628
+ InferObjectOutput<Shape>
629
+ > {
630
+ readonly shape: Shape;
631
+ private readonly mode: "strip" | "passthrough" | "strict";
632
+
633
+ constructor(
634
+ shape: Shape,
635
+ mode: "strip" | "passthrough" | "strict" = "strip",
636
+ ) {
637
+ super((val, path) => {
638
+ if (typeof val !== "object" || val === null || Array.isArray(val)) {
639
+ return {
640
+ ok: false,
641
+ issues: [
642
+ {
643
+ code: "invalid_type",
644
+ path,
645
+ message: `Expected object, received ${val === null ? "null" : typeof val}`,
646
+ },
647
+ ],
648
+ };
649
+ }
650
+ const record = val as Record<string, unknown>;
651
+ const out: Record<string, unknown> = {};
652
+ const issues: ZodIssue[] = [];
653
+
654
+ for (const [key, fieldSchema] of Object.entries(shape)) {
655
+ const res = fieldSchema._validate(record[key], [...path, key]);
656
+ if (res.ok) {
657
+ if (res.value !== undefined || key in record) {
658
+ out[key] = res.value;
659
+ }
660
+ } else {
661
+ issues.push(...res.issues);
662
+ }
663
+ }
664
+
665
+ if (mode !== "strip") {
666
+ for (const key of Object.keys(record)) {
667
+ if (!(key in shape)) {
668
+ if (mode === "strict") {
669
+ issues.push({
670
+ code: "unrecognized_keys",
671
+ path: [...path, key],
672
+ message: `Unrecognized key in object: '${key}'`,
673
+ });
674
+ } else {
675
+ out[key] = record[key];
676
+ }
677
+ }
678
+ }
679
+ }
680
+
681
+ if (issues.length > 0) return { ok: false, issues };
682
+ return { ok: true, value: out as InferObjectOutput<Shape> };
683
+ });
684
+ this.shape = shape;
685
+ this.mode = mode;
686
+ }
687
+
688
+ passthrough(): ZodObject<Shape> {
689
+ return new ZodObject(this.shape, "passthrough");
690
+ }
691
+
692
+ strict(): ZodObject<Shape> {
693
+ return new ZodObject(this.shape, "strict");
694
+ }
695
+
696
+ partial(): ZodObject<{
697
+ [K in keyof Shape]: ZodType<
698
+ Shape[K]["_output"] | undefined,
699
+ Shape[K]["_input"] | undefined
700
+ >;
701
+ }> {
702
+ const nextShape: Record<string, ZodType<any, any>> = {};
703
+ for (const [k, v] of Object.entries(this.shape)) {
704
+ nextShape[k] = v.optional();
705
+ }
706
+ return new ZodObject(nextShape as any, this.mode);
707
+ }
708
+
709
+ extend<Extra extends ZodRawShape>(extra: Extra): ZodObject<Shape & Extra> {
710
+ return new ZodObject({ ...this.shape, ...extra }, this.mode);
711
+ }
712
+
713
+ merge<Other extends ZodRawShape>(
714
+ other: ZodObject<Other>,
715
+ ): ZodObject<Shape & Other> {
716
+ return this.extend(other.shape);
717
+ }
718
+
719
+ pick<K extends keyof Shape>(
720
+ keys: Record<K, true>,
721
+ ): ZodObject<Pick<Shape, K>> {
722
+ const picked: Record<string, ZodType<any, any>> = {};
723
+ for (const k of Object.keys(keys)) {
724
+ if (k in this.shape) {
725
+ picked[k] = this.shape[k]!;
726
+ }
727
+ }
728
+ return new ZodObject(picked as Pick<Shape, K>, this.mode);
729
+ }
730
+
731
+ omit<K extends keyof Shape>(
732
+ keys: Record<K, true>,
733
+ ): ZodObject<Omit<Shape, K>> {
734
+ const omitted: Record<string, ZodType<any, any>> = {};
735
+ for (const [k, v] of Object.entries(this.shape)) {
736
+ if (!(k in keys)) {
737
+ omitted[k] = v;
738
+ }
739
+ }
740
+ return new ZodObject(omitted as Omit<Shape, K>, this.mode);
741
+ }
742
+ }
743
+
744
+ export const z = {
745
+ ZodError,
746
+ ZodType,
747
+ string(): ZodString {
748
+ return new ZodString();
749
+ },
750
+ number(): ZodNumber {
751
+ return new ZodNumber();
752
+ },
753
+ boolean(): ZodBoolean {
754
+ return new ZodBoolean();
755
+ },
756
+ date(): ZodDate {
757
+ return new ZodDate();
758
+ },
759
+ any(): ZodType<any, any> {
760
+ return new ZodType((val) => ({ ok: true, value: val }));
761
+ },
762
+ unknown(): ZodType<unknown, unknown> {
763
+ return new ZodType((val) => ({ ok: true, value: val }));
764
+ },
765
+ literal<T extends string | number | boolean | null | undefined>(
766
+ expected: T,
767
+ ): ZodType<T, T> {
768
+ return new ZodType((val, path) =>
769
+ Object.is(val, expected)
770
+ ? { ok: true, value: expected }
771
+ : {
772
+ ok: false,
773
+ issues: [
774
+ {
775
+ code: "invalid_literal",
776
+ path,
777
+ message: `Invalid literal value, expected ${JSON.stringify(expected)}`,
778
+ },
779
+ ],
780
+ },
781
+ );
782
+ },
783
+ enum<const T extends readonly [string, ...string[]]>(
784
+ values: T,
785
+ ): ZodType<T[number], T[number]> & {
786
+ readonly options: T;
787
+ readonly enum: { [K in T[number]]: K };
788
+ } {
789
+ const set = new Set<string>(values);
790
+ const schema = new ZodType<T[number], T[number]>((val, path) =>
791
+ typeof val === "string" && set.has(val)
792
+ ? { ok: true, value: val as T[number] }
793
+ : {
794
+ ok: false,
795
+ issues: [
796
+ {
797
+ code: "invalid_enum_value",
798
+ path,
799
+ message: `Invalid enum value. Expected ${values.map((v) => `'${v}'`).join(" | ")}, received ${JSON.stringify(val)}`,
800
+ },
801
+ ],
802
+ },
803
+ ) as ZodType<T[number], T[number]> & {
804
+ options: T;
805
+ enum: { [K in T[number]]: K };
806
+ };
807
+ const enumObj = {} as { [K in T[number]]: K };
808
+ for (const v of values) {
809
+ (enumObj as Record<string, string>)[v] = v;
810
+ }
811
+ schema.options = values;
812
+ schema.enum = enumObj;
813
+ return schema;
814
+ },
815
+ array<Item extends ZodType<any, any>>(item: Item): ZodArray<Item> {
816
+ return new ZodArray(item);
817
+ },
818
+ object<Shape extends ZodRawShape>(shape: Shape): ZodObject<Shape> {
819
+ return new ZodObject(shape);
820
+ },
821
+ record<V extends ZodType<any, any>>(
822
+ keyOrValue: ZodType<string, any> | V,
823
+ maybeValue?: V,
824
+ ): ZodType<Record<string, V["_output"]>, Record<string, V["_input"]>> {
825
+ const keySchema = maybeValue
826
+ ? (keyOrValue as ZodType<string, any>)
827
+ : undefined;
828
+ const valSchema = (maybeValue ?? keyOrValue) as V;
829
+ return new ZodType((val, path) => {
830
+ if (typeof val !== "object" || val === null || Array.isArray(val)) {
831
+ return {
832
+ ok: false,
833
+ issues: [
834
+ {
835
+ code: "invalid_type",
836
+ path,
837
+ message: `Expected object record, received ${typeof val}`,
838
+ },
839
+ ],
840
+ };
841
+ }
842
+ const out: Record<string, V["_output"]> = {};
843
+ const issues: ZodIssue[] = [];
844
+ for (const [k, v] of Object.entries(val as Record<string, unknown>)) {
845
+ if (keySchema) {
846
+ const kRes = keySchema._validate(k, [...path, k]);
847
+ if (!kRes.ok) {
848
+ issues.push(...kRes.issues);
849
+ continue;
850
+ }
851
+ }
852
+ const vRes = valSchema._validate(v, [...path, k]);
853
+ if (vRes.ok) {
854
+ out[k] = vRes.value;
855
+ } else {
856
+ issues.push(...vRes.issues);
857
+ }
858
+ }
859
+ if (issues.length > 0) return { ok: false, issues };
860
+ return { ok: true, value: out };
861
+ });
862
+ },
863
+ union<const T extends readonly [ZodType<any, any>, ...ZodType<any, any>[]]>(
864
+ schemas: T,
865
+ ): ZodType<T[number]["_output"], T[number]["_input"]> {
866
+ return new ZodType((val, path) => {
867
+ const allIssues: ZodIssue[] = [];
868
+ for (const s of schemas) {
869
+ const res = s._validate(val, path);
870
+ if (res.ok) return res;
871
+ allIssues.push(...res.issues);
872
+ }
873
+ return {
874
+ ok: false,
875
+ issues:
876
+ allIssues.length > 0
877
+ ? allIssues
878
+ : [{ code: "invalid_union", path, message: "Invalid input" }],
879
+ };
880
+ });
881
+ },
882
+ discriminatedUnion<
883
+ Discriminator extends string,
884
+ const T extends readonly [ZodObject<any>, ...ZodObject<any>[]],
885
+ >(
886
+ discriminator: Discriminator,
887
+ schemas: T,
888
+ ): ZodType<T[number]["_output"], T[number]["_input"]> {
889
+ return z.union(schemas);
890
+ },
891
+ tuple<const T extends readonly [ZodType<any, any>, ...ZodType<any, any>[]]>(
892
+ schemas: T,
893
+ ): ZodType<
894
+ { [K in keyof T]: T[K] extends ZodType<infer O, any> ? O : never },
895
+ { [K in keyof T]: T[K] extends ZodType<any, infer I> ? I : never }
896
+ > {
897
+ return new ZodType((val, path) => {
898
+ if (!Array.isArray(val) || val.length !== schemas.length) {
899
+ return {
900
+ ok: false,
901
+ issues: [
902
+ {
903
+ code: "invalid_tuple",
904
+ path,
905
+ message: `Expected tuple of length ${schemas.length}`,
906
+ },
907
+ ],
908
+ };
909
+ }
910
+ const out: unknown[] = [];
911
+ const issues: ZodIssue[] = [];
912
+ for (let i = 0; i < schemas.length; i++) {
913
+ const res = schemas[i]!._validate(val[i], [...path, i]);
914
+ if (res.ok) out.push(res.value);
915
+ else issues.push(...res.issues);
916
+ }
917
+ if (issues.length > 0) return { ok: false, issues };
918
+ return { ok: true, value: out as any };
919
+ });
920
+ },
921
+ optional<T extends ZodType<any, any>>(
922
+ schema: T,
923
+ ): ZodType<T["_output"] | undefined, T["_input"] | undefined> {
924
+ return schema.optional();
925
+ },
926
+ nullable<T extends ZodType<any, any>>(
927
+ schema: T,
928
+ ): ZodType<T["_output"] | null, T["_input"] | null> {
929
+ return schema.nullable();
930
+ },
931
+ coerce: {
932
+ string(): ZodString {
933
+ return new ZodString([], true);
934
+ },
935
+ number(): ZodNumber {
936
+ return new ZodNumber([], true);
937
+ },
938
+ boolean(): ZodBoolean {
939
+ return new ZodBoolean(true);
940
+ },
941
+ date(): ZodDate {
942
+ return new ZodDate([], true);
943
+ },
944
+ },
945
+ };
946
+
947
+ export namespace z {
948
+ export type infer<T extends SchemaValidator<any>> =
949
+ T extends ZodType<infer O, any>
950
+ ? O
951
+ : T extends SchemaValidator<infer O>
952
+ ? O
953
+ : unknown;
954
+ }
955
+
956
+ export interface ImageMetadata {
957
+ src: string;
958
+ width?: number;
959
+ height?: number;
960
+ format?: string;
961
+ }
962
+
963
+ export interface SchemaContext {
964
+ image: () => ZodType<ImageMetadata | string, ImageMetadata | string>;
965
+ }
966
+
967
+ export function createSchemaContext(): SchemaContext {
968
+ return {
969
+ image: () =>
970
+ z
971
+ .object({
972
+ src: z.string(),
973
+ width: z.number().optional(),
974
+ height: z.number().optional(),
975
+ format: z.string().optional(),
976
+ })
977
+ .or(z.string()),
978
+ };
979
+ }
980
+
981
+ export interface MarkdownHeading {
982
+ depth: number;
983
+ slug: string;
984
+ text: string;
985
+ }
986
+
987
+ export interface RenderedContent {
988
+ html: string;
989
+ metadata?: {
990
+ headings?: MarkdownHeading[];
991
+ frontmatter?: Record<string, any>;
992
+ imagePaths?: string[];
993
+ [key: string]: any;
994
+ };
995
+ }
996
+
997
+ export interface LoaderStoreEntry {
998
+ id: string;
999
+ data: Record<string, any>;
1000
+ body?: string;
1001
+ filePath?: string;
1002
+ digest?: string;
1003
+ rendered?: RenderedContent;
1004
+ }
1005
+
1006
+ export interface LoaderStore {
1007
+ get: (id: string) => LoaderStoreEntry | undefined;
1008
+ set: (entry: LoaderStoreEntry) => boolean;
1009
+ entries: () => Array<[string, LoaderStoreEntry]>;
1010
+ values: () => LoaderStoreEntry[];
1011
+ keys: () => string[];
1012
+ delete: (id: string) => boolean;
1013
+ clear: () => void;
1014
+ has: (id: string) => boolean;
1015
+ }
1016
+
1017
+ export interface LoaderContext {
1018
+ collection: string;
1019
+ store: LoaderStore;
1020
+ parseData: <TData = Record<string, any>>(props: {
1021
+ id: string;
1022
+ data: Record<string, any>;
1023
+ filePath?: string;
1024
+ }) => Promise<TData>;
1025
+ generateDigest: (data: Record<string, unknown> | string) => string;
1026
+ }
1027
+
1028
+ export interface ContentLoader {
1029
+ name: string;
1030
+ load: (context: LoaderContext) => void | Promise<void>;
1031
+ schema?:
1032
+ SchemaValidator<any> | ((context: SchemaContext) => SchemaValidator<any>);
1033
+ }
1034
+
1035
+ export type CollectionLoader =
1036
+ | ContentLoader
1037
+ | (() =>
1038
+ | Array<{ id?: string; slug?: string; [key: string]: any }>
1039
+ | Record<string, Record<string, any>>
1040
+ | Promise<
1041
+ | Array<{ id?: string; slug?: string; [key: string]: any }>
1042
+ | Record<string, Record<string, any>>
1043
+ >);
1044
+
1045
+ export interface CollectionConfig<S = any> {
1046
+ type?: "content" | "data" | "content_layer";
1047
+ schema?: S;
1048
+ loader?: CollectionLoader;
1049
+ }
1050
+
1051
+ export type InferCollectionSchema<C> =
1052
+ C extends CollectionConfig<infer S>
1053
+ ? S extends (context: SchemaContext) => SchemaValidator<infer O>
1054
+ ? O
1055
+ : S extends SchemaValidator<infer O>
1056
+ ? O
1057
+ : Record<string, any>
1058
+ : Record<string, any>;
1059
+
1060
+ export interface CollectionEntry<
1061
+ C extends string = string,
1062
+ Data = Record<string, any>,
1063
+ > {
1064
+ id: string;
1065
+ slug: string;
1066
+ collection: C;
1067
+ data: Data;
1068
+ body?: string;
1069
+ filePath?: string;
1070
+ rendered?: RenderedContent;
1071
+ render: () => Promise<RenderResult>;
1072
+ }
1073
+
1074
+ export interface ReferenceEntry<C extends string = string> {
1075
+ collection: C;
1076
+ id: string;
1077
+ }
1078
+
1079
+ export function defineCollection<S = any>(
1080
+ config: CollectionConfig<S>,
1081
+ ): CollectionConfig<S> {
1082
+ return {
1083
+ ...config,
1084
+ type: config.type ?? (config.loader ? "content_layer" : "content"),
1085
+ };
1086
+ }
1087
+
1088
+ export function reference<C extends string>(
1089
+ collection: C,
1090
+ ): ZodType<
1091
+ ReferenceEntry<C>,
1092
+ string | { collection?: C; id?: string; slug?: string }
1093
+ > {
1094
+ return new ZodType((val, path) => {
1095
+ if (typeof val === "string" && val.length > 0) {
1096
+ return { ok: true, value: { collection, id: val } };
1097
+ }
1098
+ if (typeof val === "object" && val !== null) {
1099
+ const obj = val as { collection?: string; id?: string; slug?: string };
1100
+ const id = obj.id ?? obj.slug;
1101
+ if (
1102
+ typeof id === "string" &&
1103
+ id.length > 0 &&
1104
+ (obj.collection === undefined || obj.collection === collection)
1105
+ ) {
1106
+ return { ok: true, value: { collection, id } };
1107
+ }
1108
+ }
1109
+ return {
1110
+ ok: false,
1111
+ issues: [
1112
+ {
1113
+ code: "invalid_reference",
1114
+ path,
1115
+ message: `Invalid reference for collection "${collection}"`,
1116
+ },
1117
+ ],
1118
+ };
1119
+ });
1120
+ }
1121
+
1122
+ type InternalCollectionRecord = {
1123
+ config: CollectionConfig<any>;
1124
+ rawEntries: Map<string, LoaderStoreEntry>;
1125
+ loaded: boolean;
1126
+ };
1127
+
1128
+ const collectionRegistry = new Map<string, InternalCollectionRecord>();
1129
+
1130
+ function ensureCollectionRecord(name: string): InternalCollectionRecord {
1131
+ let rec = collectionRegistry.get(name);
1132
+ if (!rec) {
1133
+ rec = {
1134
+ config: { type: "content" },
1135
+ rawEntries: new Map(),
1136
+ loaded: false,
1137
+ };
1138
+ collectionRegistry.set(name, rec);
1139
+ }
1140
+ return rec;
1141
+ }
1142
+
1143
+ export function registerCollections(
1144
+ collections: Record<string, CollectionConfig<any>>,
1145
+ ): void {
1146
+ for (const [name, config] of Object.entries(collections)) {
1147
+ const existing = collectionRegistry.get(name);
1148
+ collectionRegistry.set(name, {
1149
+ config,
1150
+ rawEntries: existing?.rawEntries ?? new Map(),
1151
+ loaded: false,
1152
+ });
1153
+ }
1154
+ }
1155
+
1156
+ export interface SeedEntryInput {
1157
+ id: string;
1158
+ slug?: string;
1159
+ data: Record<string, any>;
1160
+ body?: string;
1161
+ filePath?: string;
1162
+ rendered?: RenderedContent;
1163
+ }
1164
+
1165
+ export function seedCollection(
1166
+ collection: string,
1167
+ entries: SeedEntryInput[] | Record<string, Omit<SeedEntryInput, "id">>,
1168
+ ): void {
1169
+ const rec = ensureCollectionRecord(collection);
1170
+ const list: SeedEntryInput[] = Array.isArray(entries)
1171
+ ? entries
1172
+ : Object.entries(entries).map(([id, item]) => ({ id, ...item }));
1173
+ for (const item of list) {
1174
+ rec.rawEntries.set(item.id, {
1175
+ id: item.id,
1176
+ data: { ...item.data },
1177
+ body: item.body,
1178
+ filePath: item.filePath,
1179
+ rendered: item.rendered,
1180
+ });
1181
+ }
1182
+ }
1183
+
1184
+ export function clearCollections(): void {
1185
+ collectionRegistry.clear();
1186
+ }
1187
+
1188
+ function resolveSchemaValidator(
1189
+ config: CollectionConfig<any>,
1190
+ ): SchemaValidator<any> | undefined {
1191
+ const rawSchema =
1192
+ config.schema ??
1193
+ (typeof config.loader === "object" && config.loader !== null
1194
+ ? config.loader.schema
1195
+ : undefined);
1196
+ if (!rawSchema) return undefined;
1197
+ if (typeof rawSchema === "function") {
1198
+ return rawSchema(createSchemaContext());
1199
+ }
1200
+ return rawSchema;
1201
+ }
1202
+
1203
+ function validateEntryData(
1204
+ collection: string,
1205
+ entryId: string,
1206
+ data: Record<string, any>,
1207
+ validator?: SchemaValidator<any>,
1208
+ ): Record<string, any> {
1209
+ if (!validator) return data;
1210
+ if ("safeParse" in validator && typeof validator.safeParse === "function") {
1211
+ const res = validator.safeParse(data);
1212
+ if (!res.success) {
1213
+ const msg =
1214
+ res.error instanceof Error
1215
+ ? res.error.message
1216
+ : (res.error?.issues
1217
+ ?.map((i: ActionInputIssue) => i.message)
1218
+ .join("; ") ?? "Invalid collection entry data");
1219
+ throw new Error(
1220
+ `[${collection}] "${entryId}" data does not match collection schema: ${msg}`,
1221
+ );
1222
+ }
1223
+ return res.data as Record<string, any>;
1224
+ }
1225
+ if ("parse" in validator && typeof validator.parse === "function") {
1226
+ return validator.parse(data) as Record<string, any>;
1227
+ }
1228
+ return data;
1229
+ }
1230
+
1231
+ function computeSlug(id: string, data?: Record<string, any>): string {
1232
+ if (typeof data?.slug === "string" && data.slug.length > 0) {
1233
+ return data.slug;
1234
+ }
1235
+ return id.replace(/\.(md|mdx|markdown|json|yaml|yml|toml)$/i, "");
1236
+ }
1237
+
1238
+ async function runCollectionLoaderIfNeeded(
1239
+ collection: string,
1240
+ rec: InternalCollectionRecord,
1241
+ ): Promise<void> {
1242
+ if (rec.loaded || !rec.config.loader) return;
1243
+ rec.loaded = true;
1244
+ const loader = rec.config.loader;
1245
+ const validator = resolveSchemaValidator(rec.config);
1246
+
1247
+ const store: LoaderStore = {
1248
+ get: (id) => rec.rawEntries.get(id),
1249
+ set: (entry) => {
1250
+ rec.rawEntries.set(entry.id, entry);
1251
+ return true;
1252
+ },
1253
+ entries: () => Array.from(rec.rawEntries.entries()),
1254
+ values: () => Array.from(rec.rawEntries.values()),
1255
+ keys: () => Array.from(rec.rawEntries.keys()),
1256
+ delete: (id) => rec.rawEntries.delete(id),
1257
+ clear: () => rec.rawEntries.clear(),
1258
+ has: (id) => rec.rawEntries.has(id),
1259
+ };
1260
+
1261
+ if (typeof loader === "function") {
1262
+ const rawResult = await loader();
1263
+ if (Array.isArray(rawResult)) {
1264
+ for (const item of rawResult) {
1265
+ const id = String(item.id ?? item.slug ?? "");
1266
+ if (!id) continue;
1267
+ const { id: _id, body, rendered, filePath, ...rest } = item;
1268
+ const payload =
1269
+ "data" in item &&
1270
+ typeof item.data === "object" &&
1271
+ item.data !== null &&
1272
+ Object.keys(rest).length <= 2
1273
+ ? (item.data as Record<string, any>)
1274
+ : rest;
1275
+ const parsed = validateEntryData(collection, id, payload, validator);
1276
+ rec.rawEntries.set(id, {
1277
+ id,
1278
+ data: parsed,
1279
+ body: typeof body === "string" ? body : undefined,
1280
+ filePath: typeof filePath === "string" ? filePath : undefined,
1281
+ rendered: rendered as RenderedContent | undefined,
1282
+ });
1283
+ }
1284
+ } else if (typeof rawResult === "object" && rawResult !== null) {
1285
+ for (const [id, item] of Object.entries(rawResult)) {
1286
+ const parsed = validateEntryData(collection, id, item, validator);
1287
+ rec.rawEntries.set(id, { id, data: parsed });
1288
+ }
1289
+ }
1290
+ return;
1291
+ }
1292
+
1293
+ await loader.load({
1294
+ collection,
1295
+ store,
1296
+ parseData: async ({ id, data }) =>
1297
+ validateEntryData(collection, id, data, validator) as any,
1298
+ generateDigest: (input) => {
1299
+ const str = typeof input === "string" ? input : JSON.stringify(input);
1300
+ let hash = 5381;
1301
+ for (let i = 0; i < str.length; i++) {
1302
+ hash = (hash * 33) ^ str.charCodeAt(i);
1303
+ }
1304
+ return (hash >>> 0).toString(16);
1305
+ },
1306
+ });
1307
+ }
1308
+
1309
+ function materializeCollectionEntry<C extends string>(
1310
+ collection: C,
1311
+ raw: LoaderStoreEntry,
1312
+ validator?: SchemaValidator<any>,
1313
+ ): CollectionEntry<C> {
1314
+ const validatedData = validateEntryData(
1315
+ collection,
1316
+ raw.id,
1317
+ raw.data,
1318
+ validator,
1319
+ );
1320
+ const slug = computeSlug(raw.id, validatedData);
1321
+ const entry: CollectionEntry<C> = {
1322
+ id: raw.id,
1323
+ slug,
1324
+ collection,
1325
+ data: validatedData,
1326
+ ...(raw.body !== undefined ? { body: raw.body } : {}),
1327
+ ...(raw.filePath !== undefined ? { filePath: raw.filePath } : {}),
1328
+ ...(raw.rendered !== undefined ? { rendered: raw.rendered } : {}),
1329
+ render: () => render(entry),
1330
+ };
1331
+ return entry;
1332
+ }
1333
+
1334
+ export async function getCollection<
1335
+ C extends string = string,
1336
+ E extends CollectionEntry<C> = CollectionEntry<C>,
1337
+ >(
1338
+ collection: C,
1339
+ filter?: (entry: CollectionEntry<C>) => unknown,
1340
+ ): Promise<E[]> {
1341
+ const rec = ensureCollectionRecord(collection);
1342
+ await runCollectionLoaderIfNeeded(collection, rec);
1343
+ const validator = resolveSchemaValidator(rec.config);
1344
+ const results: E[] = [];
1345
+ for (const raw of rec.rawEntries.values()) {
1346
+ const entry = materializeCollectionEntry(collection, raw, validator);
1347
+ if (!filter || Boolean(filter(entry))) {
1348
+ results.push(entry as E);
1349
+ }
1350
+ }
1351
+ return results;
1352
+ }
1353
+
1354
+ export async function getEntry<
1355
+ C extends string = string,
1356
+ E extends CollectionEntry<C> = CollectionEntry<C>,
1357
+ >(
1358
+ collectionOrRef: C | { collection: C; id?: string; slug?: string },
1359
+ maybeIdOrSlug?: string,
1360
+ ): Promise<E | undefined> {
1361
+ const collection =
1362
+ typeof collectionOrRef === "string"
1363
+ ? collectionOrRef
1364
+ : collectionOrRef.collection;
1365
+ const targetKey =
1366
+ typeof collectionOrRef === "string"
1367
+ ? maybeIdOrSlug
1368
+ : (collectionOrRef.id ?? collectionOrRef.slug);
1369
+ if (!targetKey) return undefined;
1370
+
1371
+ const entries = await getCollection<C, E>(collection);
1372
+ return entries.find((e) => e.id === targetKey || e.slug === targetKey);
1373
+ }
1374
+
1375
+ export async function getEntries<
1376
+ C extends string = string,
1377
+ E extends CollectionEntry<C> = CollectionEntry<C>,
1378
+ >(
1379
+ references: ReadonlyArray<{ collection: C; id?: string; slug?: string }>,
1380
+ ): Promise<E[]> {
1381
+ const out: E[] = [];
1382
+ for (const ref of references) {
1383
+ const found = await getEntry<C, E>(ref);
1384
+ if (found) out.push(found);
1385
+ }
1386
+ return out;
1387
+ }
1388
+
1389
+ export async function getLiveCollection<
1390
+ C extends string = string,
1391
+ E extends CollectionEntry<C> = CollectionEntry<C>,
1392
+ >(
1393
+ collection: C,
1394
+ filter?: (entry: CollectionEntry<C>) => unknown,
1395
+ ): Promise<{ entries?: E[]; error?: Error }> {
1396
+ try {
1397
+ const rec = ensureCollectionRecord(collection);
1398
+ rec.loaded = false;
1399
+ const entries = await getCollection<C, E>(collection, filter);
1400
+ return { entries };
1401
+ } catch (err) {
1402
+ return {
1403
+ error: err instanceof Error ? err : new Error(String(err)),
1404
+ };
1405
+ }
1406
+ }
1407
+
1408
+ export async function getLiveEntry<
1409
+ C extends string = string,
1410
+ E extends CollectionEntry<C> = CollectionEntry<C>,
1411
+ >(
1412
+ collection: C,
1413
+ idOrFilter: string | { id?: string; slug?: string },
1414
+ ): Promise<{ entry?: E; error?: Error }> {
1415
+ try {
1416
+ const rec = ensureCollectionRecord(collection);
1417
+ rec.loaded = false;
1418
+ const target =
1419
+ typeof idOrFilter === "string"
1420
+ ? idOrFilter
1421
+ : (idOrFilter.id ?? idOrFilter.slug);
1422
+ const entry = await getEntry<C, E>(collection, target);
1423
+ return { entry };
1424
+ } catch (err) {
1425
+ return {
1426
+ error: err instanceof Error ? err : new Error(String(err)),
1427
+ };
1428
+ }
1429
+ }
1430
+
1431
+ export function slugifyHeading(text: string): string {
1432
+ return text
1433
+ .trim()
1434
+ .toLowerCase()
1435
+ .replace(/[`*_~[\]()!<>]/g, "")
1436
+ .replace(/[^\w\s-]/g, "")
1437
+ .replace(/\s+/g, "-")
1438
+ .replace(/-+/g, "-");
1439
+ }
1440
+
1441
+ export function extractMarkdownHeadings(markdown: string): MarkdownHeading[] {
1442
+ const headings: MarkdownHeading[] = [];
1443
+ const lines = markdown.split(/\r?\n/);
1444
+ let inFence = false;
1445
+ for (const line of lines) {
1446
+ if (/^```|^~~~/.test(line.trim())) {
1447
+ inFence = !inFence;
1448
+ continue;
1449
+ }
1450
+ if (inFence) continue;
1451
+ const match = /^(#{1,6})\s+(.+?)\s*#*$/.exec(line);
1452
+ if (match) {
1453
+ const depth = match[1]!.length;
1454
+ const text = match[2]!.trim();
1455
+ headings.push({
1456
+ depth,
1457
+ slug: slugifyHeading(text),
1458
+ text,
1459
+ });
1460
+ }
1461
+ }
1462
+ return headings;
1463
+ }
1464
+
1465
+ export function renderSimpleMarkdownToHtml(markdown: string): string {
1466
+ const blocks = markdown.trim().split(/\n{2,}/);
1467
+ const htmlParts: string[] = [];
1468
+ for (const block of blocks) {
1469
+ const trimmed = block.trim();
1470
+ if (!trimmed) continue;
1471
+ const headingMatch = /^(#{1,6})\s+(.+?)\s*#*$/.exec(trimmed);
1472
+ if (headingMatch) {
1473
+ const level = headingMatch[1]!.length;
1474
+ const text = headingMatch[2]!.trim();
1475
+ const slug = slugifyHeading(text);
1476
+ htmlParts.push(`<h${level} id="${slug}">${text}</h${level}>`);
1477
+ } else {
1478
+ htmlParts.push(`<p>${trimmed}</p>`);
1479
+ }
1480
+ }
1481
+ return htmlParts.join("\n");
1482
+ }
1483
+
1484
+ export interface RenderResult {
1485
+ Content: (props?: Record<string, any>) => string;
1486
+ headings: MarkdownHeading[];
1487
+ remarkPluginFrontmatter: Record<string, any>;
1488
+ }
1489
+
1490
+ export async function render(
1491
+ entry: Pick<CollectionEntry<any>, "body" | "data" | "rendered">,
1492
+ ): Promise<RenderResult> {
1493
+ const rawBody = entry.body ?? "";
1494
+ const headings =
1495
+ entry.rendered?.metadata?.headings ?? extractMarkdownHeadings(rawBody);
1496
+ const html =
1497
+ entry.rendered?.html ??
1498
+ (rawBody ? renderSimpleMarkdownToHtml(rawBody) : "");
1499
+ const remarkPluginFrontmatter: Record<string, any> = {
1500
+ ...entry.data,
1501
+ ...entry.rendered?.metadata?.frontmatter,
1502
+ };
1503
+
1504
+ return {
1505
+ Content: () => html,
1506
+ headings,
1507
+ remarkPluginFrontmatter,
1508
+ };
1509
+ }
1510
+
1511
+ export {
1512
+ file,
1513
+ glob,
1514
+ matchGlobPattern,
1515
+ parseFrontmatter,
1516
+ parseSimpleCsv,
1517
+ parseSimpleToml,
1518
+ parseSimpleYaml,
1519
+ type FileLoaderOptions,
1520
+ type FrontmatterParseResult,
1521
+ type GenerateIdOptions,
1522
+ type GlobLoaderOptions,
1523
+ } from "./loaders";