@backmatter/core 0.0.52 → 0.0.54

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/core",
3
- "version": "0.0.52",
3
+ "version": "0.0.54",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/block.ts CHANGED
@@ -135,7 +135,7 @@ function humanize(name: string): string {
135
135
  }
136
136
 
137
137
  /**
138
- * Stand-in props for a block without examples: a label for text, the first
138
+ * Stand-in props for a block without examples: a label for text and markdown, the first
139
139
  * option, the minimum, false. Richer fields stay unset.
140
140
  */
141
141
  export function placeholderBlockProps(
@@ -144,6 +144,7 @@ export function placeholderBlockProps(
144
144
  const props: Record<string, unknown> = {};
145
145
  for (const [name, field] of Object.entries(fields)) {
146
146
  if (field.kind === "text") props[name] = field.options?.[0] ?? humanize(name);
147
+ else if (field.kind === "markdown") props[name] = humanize(name);
147
148
  else if (field.kind === "number") props[name] = field.min ?? 0;
148
149
  else if (field.kind === "boolean") props[name] = false;
149
150
  }
package/src/fields.ts CHANGED
@@ -3,6 +3,7 @@ import { MEDIA_KINDS, isMediaKind, type MediaKind } from "./media-url";
3
3
 
4
4
  export type FieldKind =
5
5
  | "text"
6
+ | "markdown"
6
7
  | "image"
7
8
  | "media"
8
9
  | "relation"
@@ -13,6 +14,24 @@ export type FieldKind =
13
14
  | "object"
14
15
  | "array";
15
16
 
17
+ /** Formatting a markdown field may allow, in the order Studio's toolbar shows it. */
18
+ export const MARKDOWN_FORMATS = ["bold", "italic", "link", "heading", "list"] as const;
19
+ export type MarkdownFormat = (typeof MARKDOWN_FORMATS)[number];
20
+
21
+ /** What a markdown field allows when it lists nothing. */
22
+ export const DEFAULT_MARKDOWN_ALLOW: readonly MarkdownFormat[] = ["bold", "italic", "link"];
23
+
24
+ function isMarkdownFormat(value: unknown): value is MarkdownFormat {
25
+ return MARKDOWN_FORMATS.includes(value as MarkdownFormat);
26
+ }
27
+
28
+ /** Allowed formats in toolbar order, without repeats; null when empty or unknown. */
29
+ function normalizeAllow(value: unknown): MarkdownFormat[] | null {
30
+ if (!Array.isArray(value) || value.length === 0) return null;
31
+ if (!value.every(isMarkdownFormat)) return null;
32
+ return MARKDOWN_FORMATS.filter((format) => value.includes(format));
33
+ }
34
+
16
35
  /** Equality filter on scalar frontmatter keys for a file-backed relation target. */
17
36
  export type RelationWhere = Record<string, string | number | boolean>;
18
37
 
@@ -54,6 +73,8 @@ export type FieldDef<
54
73
  accept?: readonly MediaKind[];
55
74
  /** For blocks fields: how Studio's "Add block" picker lays out the blocks. */
56
75
  picker?: BlockPickerView;
76
+ /** For markdown fields: the formatting the stored markdown may use. */
77
+ allow?: readonly MarkdownFormat[];
57
78
  /** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
58
79
  description?: string;
59
80
  };
@@ -87,6 +108,7 @@ export type FieldSnapshot = {
87
108
  multiple?: true;
88
109
  accept?: MediaKind[];
89
110
  picker?: BlockPickerView;
111
+ allow?: MarkdownFormat[];
90
112
  description?: string;
91
113
  };
92
114
 
@@ -494,6 +516,17 @@ const constructors = {
494
516
  ...(opts?.input ? { input: opts.input } : {}),
495
517
  }) as TextFieldDef<R, O>;
496
518
  },
519
+ markdown: <const R extends boolean = false>(
520
+ opts?: Opts<R> & { allow?: readonly MarkdownFormat[] },
521
+ ): FieldDef<"markdown", R> => {
522
+ const allow = opts?.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(opts.allow);
523
+ if (!allow) {
524
+ throw new Error(
525
+ 'field.markdown allow must list "bold", "italic", "link", "heading" and/or "list"',
526
+ );
527
+ }
528
+ return { ...base("markdown", { required: opts?.required, input: opts?.input }), allow };
529
+ },
497
530
  image: <const R extends boolean = false>(opts?: Opts<R>) => base("image", opts),
498
531
  media: <const R extends boolean = false, const M extends boolean = false>(
499
532
  opts?: Opts<R> & { multiple?: M; accept?: readonly MediaKind[] },
@@ -527,6 +560,7 @@ const constructors = {
527
560
 
528
561
  export const field = {
529
562
  text: described(constructors.text, 0),
563
+ markdown: described(constructors.markdown, 0),
530
564
  image: described(constructors.image, 0),
531
565
  media: described(constructors.media, 0),
532
566
  number: described(constructors.number, 0),
@@ -555,6 +589,7 @@ export function serializeField(def: FieldDef): FieldSnapshot {
555
589
  ...(def.multiple ? { multiple: true as const } : {}),
556
590
  ...(def.accept ? { accept: [...def.accept] } : {}),
557
591
  ...(def.picker ? { picker: def.picker } : {}),
592
+ ...(def.allow ? { allow: [...def.allow] } : {}),
558
593
  ...(def.description?.trim() ? { description: def.description.trim() } : {}),
559
594
  };
560
595
  if (def.fields) {
@@ -575,6 +610,7 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
575
610
  const kind = value.kind;
576
611
  const allowed: FieldKind[] = [
577
612
  "text",
613
+ "markdown",
578
614
  "image",
579
615
  "media",
580
616
  "relation",
@@ -644,6 +680,11 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
644
680
  snap.where = where;
645
681
  }
646
682
  if (isPickerView(value.picker)) snap.picker = value.picker;
683
+ if (snap.kind === "markdown") {
684
+ const allow = value.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(value.allow);
685
+ if (!allow) throw new Error("invalid field.allow");
686
+ snap.allow = allow;
687
+ }
647
688
  if (typeof value.description === "string" && value.description.trim()) {
648
689
  snap.description = value.description.trim();
649
690
  }
package/src/index.ts CHANGED
@@ -7,8 +7,22 @@ export type {
7
7
  FieldKind,
8
8
  FieldSnapshot,
9
9
  BlockPickerView,
10
+ MarkdownFormat,
10
11
  } from "./fields";
11
- export { field, serializeField, parseFieldSnapshot } from "./fields";
12
+ export {
13
+ field,
14
+ serializeField,
15
+ parseFieldSnapshot,
16
+ MARKDOWN_FORMATS,
17
+ DEFAULT_MARKDOWN_ALLOW,
18
+ } from "./fields";
19
+ export type {
20
+ MarkdownBlock,
21
+ MarkdownInline,
22
+ MarkdownOutside,
23
+ ParsedMarkdownField,
24
+ } from "./markdown-field";
25
+ export { parseMarkdownField } from "./markdown-field";
12
26
  export {
13
27
  MAX_MEDIA_BYTES,
14
28
  MAX_MEDIA_TEXT,
@@ -0,0 +1,305 @@
1
+ // packages/core/src/markdown-field.ts
2
+ // The markdown a markdown field stores, read into a small tree a host renders.
3
+ // It is a subset on purpose: the block owns the layout around it (ADR 0007).
4
+ import type { MarkdownFormat } from "./fields";
5
+
6
+ export type MarkdownInline =
7
+ | { type: "text"; value: string }
8
+ | { type: "break" }
9
+ | { type: "strong"; children: MarkdownInline[] }
10
+ | { type: "emphasis"; children: MarkdownInline[] }
11
+ | { type: "link"; href: string; children: MarkdownInline[] };
12
+
13
+ export type MarkdownBlock =
14
+ | { type: "paragraph"; children: MarkdownInline[] }
15
+ | { type: "heading"; level: 3 | 4; children: MarkdownInline[] }
16
+ | { type: "list"; ordered: boolean; items: MarkdownInline[][] };
17
+
18
+ /** Markdown the value uses that renders as text: not allowed by the field, or never allowed. */
19
+ export type MarkdownOutside = MarkdownFormat | "image" | "html" | "code";
20
+
21
+ export type ParsedMarkdownField = {
22
+ blocks: MarkdownBlock[];
23
+ /** Each kind once, in the order it first appears. Studio warns about these. */
24
+ outside: MarkdownOutside[];
25
+ };
26
+
27
+ const HEADING = /^(#{1,6})\s+(.*)$/;
28
+ const BULLET = /^[-*+]\s+(.*)$/;
29
+ const NUMBERED = /^\d{1,9}[.)]\s+(.*)$/;
30
+ const HTML_TAG = /^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?\/?>/;
31
+ const ESCAPABLE = /[!-/:-@[-`{-~]/;
32
+ const WORD = /[\p{L}\p{N}]/u;
33
+ const SCHEME = /^([a-z][a-z0-9+.-]*):/i;
34
+ const SAFE_SCHEMES = new Set(["http", "https", "mailto", "tel"]);
35
+
36
+ type Context = {
37
+ allow: ReadonlySet<MarkdownFormat>;
38
+ outside: MarkdownOutside[];
39
+ };
40
+
41
+ function report(ctx: Context, kind: MarkdownOutside): void {
42
+ if (!ctx.outside.includes(kind)) ctx.outside.push(kind);
43
+ }
44
+
45
+ /**
46
+ * Read a markdown field's value. A single newline is a line break, a blank line
47
+ * starts a paragraph. Formatting outside `allow`, and images, HTML and code
48
+ * always, stay as the text that was written and are listed in `outside`.
49
+ */
50
+ export function parseMarkdownField(
51
+ source: string,
52
+ allow: readonly MarkdownFormat[],
53
+ ): ParsedMarkdownField {
54
+ const ctx: Context = { allow: new Set(allow), outside: [] };
55
+ const blocks: MarkdownBlock[] = [];
56
+ let paragraph: string[] = [];
57
+ let list: { ordered: boolean; items: string[] } | null = null;
58
+
59
+ const flushParagraph = () => {
60
+ if (paragraph.length === 0) return;
61
+ const children: MarkdownInline[] = [];
62
+ paragraph.forEach((line, index) => {
63
+ if (index > 0) children.push({ type: "break" });
64
+ appendAll(children, parseInline(line, ctx));
65
+ });
66
+ blocks.push({ type: "paragraph", children });
67
+ paragraph = [];
68
+ };
69
+ const flushList = () => {
70
+ if (!list) return;
71
+ const { ordered, items } = list;
72
+ blocks.push({ type: "list", ordered, items: items.map((item) => parseInline(item, ctx)) });
73
+ list = null;
74
+ };
75
+
76
+ for (const raw of source.replace(/\r\n?/g, "\n").split("\n")) {
77
+ const line = raw.trim();
78
+ if (line === "") {
79
+ flushParagraph();
80
+ flushList();
81
+ continue;
82
+ }
83
+
84
+ const heading = HEADING.exec(line);
85
+ if (heading) {
86
+ const level = heading[1]!.length;
87
+ if (ctx.allow.has("heading") && (level === 3 || level === 4)) {
88
+ flushParagraph();
89
+ flushList();
90
+ blocks.push({ type: "heading", level, children: parseInline(heading[2]!.trim(), ctx) });
91
+ continue;
92
+ }
93
+ report(ctx, "heading");
94
+ }
95
+
96
+ const bullet = BULLET.exec(line);
97
+ const numbered = bullet ? null : NUMBERED.exec(line);
98
+ const item = bullet ?? numbered;
99
+ if (item) {
100
+ if (ctx.allow.has("list")) {
101
+ const ordered = numbered !== null;
102
+ flushParagraph();
103
+ if (list && list.ordered !== ordered) flushList();
104
+ list ??= { ordered, items: [] };
105
+ list.items.push(item[1]!.trim());
106
+ continue;
107
+ }
108
+ report(ctx, "list");
109
+ }
110
+
111
+ flushList();
112
+ paragraph.push(line);
113
+ }
114
+ flushParagraph();
115
+ flushList();
116
+ return { blocks, outside: ctx.outside };
117
+ }
118
+
119
+ function appendText(out: MarkdownInline[], value: string): void {
120
+ if (value === "") return;
121
+ const last = out[out.length - 1];
122
+ if (last?.type === "text") last.value += value;
123
+ else out.push({ type: "text", value });
124
+ }
125
+
126
+ function appendAll(out: MarkdownInline[], nodes: MarkdownInline[]): void {
127
+ for (const node of nodes) {
128
+ if (node.type === "text") appendText(out, node.value);
129
+ else out.push(node);
130
+ }
131
+ }
132
+
133
+ function isEscaped(src: string, index: number): boolean {
134
+ let slashes = 0;
135
+ for (let i = index - 1; i >= 0 && src[i] === "\\"; i--) slashes++;
136
+ return slashes % 2 === 1;
137
+ }
138
+
139
+ function isSpace(char: string | undefined): boolean {
140
+ return char === undefined || /\s/.test(char);
141
+ }
142
+
143
+ function isWord(char: string | undefined): boolean {
144
+ return char !== undefined && WORD.test(char);
145
+ }
146
+
147
+ function runLength(src: string, index: number, char: string): number {
148
+ let n = 0;
149
+ while (src[index + n] === char) n++;
150
+ return n;
151
+ }
152
+
153
+ /** Where `delim` (one or two of `*` or `_`) can open at `index`. */
154
+ function canOpen(src: string, index: number, delim: string): boolean {
155
+ const after = src[index + delim.length];
156
+ if (isSpace(after)) return false;
157
+ if (delim[0] === "_" && isWord(src[index - 1])) return false;
158
+ return true;
159
+ }
160
+
161
+ /** Index of the delimiter that closes one opened before `from`, or -1. */
162
+ function findClose(src: string, from: number, delim: string): number {
163
+ const char = delim[0]!;
164
+ let j = from;
165
+ while (j < src.length) {
166
+ if (src[j] !== char || isEscaped(src, j)) {
167
+ j++;
168
+ continue;
169
+ }
170
+ const run = runLength(src, j, char);
171
+ const closesHere =
172
+ !isSpace(src[j - 1]) && (char !== "_" || !isWord(src[j + run]));
173
+ if (closesHere) {
174
+ // "***" ends both an emphasis and a strong: a single closes on its first
175
+ // star, a double on its last two.
176
+ if (delim.length === 1 && run !== 2) return j;
177
+ if (delim.length === 2 && run >= 2) return j + run - 2;
178
+ }
179
+ j += run;
180
+ }
181
+ return -1;
182
+ }
183
+
184
+ type LinkMatch = { text: string; href: string; end: number };
185
+
186
+ /** A `[text](href)` starting at `index`, where `src[index]` is `[`. */
187
+ function matchLink(src: string, index: number): LinkMatch | null {
188
+ let depth = 0;
189
+ let close = -1;
190
+ for (let j = index; j < src.length; j++) {
191
+ if (isEscaped(src, j)) continue;
192
+ if (src[j] === "[") depth++;
193
+ else if (src[j] === "]" && --depth === 0) {
194
+ close = j;
195
+ break;
196
+ }
197
+ }
198
+ if (close < 0 || src[close + 1] !== "(") return null;
199
+ let parens = 0;
200
+ for (let j = close + 1; j < src.length; j++) {
201
+ const char = src[j]!;
202
+ if (/\s/.test(char)) return null;
203
+ if (char === "(") parens++;
204
+ else if (char === ")" && --parens === 0) {
205
+ const href = src.slice(close + 2, j);
206
+ if (href === "") return null;
207
+ return { text: src.slice(index + 1, close), href, end: j + 1 };
208
+ }
209
+ }
210
+ return null;
211
+ }
212
+
213
+ function isSafeHref(href: string): boolean {
214
+ const scheme = SCHEME.exec(href);
215
+ return !scheme || SAFE_SCHEMES.has(scheme[1]!.toLowerCase());
216
+ }
217
+
218
+ function parseInline(src: string, ctx: Context): MarkdownInline[] {
219
+ const out: MarkdownInline[] = [];
220
+ let i = 0;
221
+ while (i < src.length) {
222
+ const char = src[i]!;
223
+
224
+ if (char === "\\" && i + 1 < src.length && ESCAPABLE.test(src[i + 1]!)) {
225
+ appendText(out, src[i + 1]!);
226
+ i += 2;
227
+ continue;
228
+ }
229
+
230
+ if (char === "`") {
231
+ const close = src.indexOf("`", i + 1);
232
+ if (close > i + 1) {
233
+ report(ctx, "code");
234
+ appendText(out, src.slice(i, close + 1));
235
+ i = close + 1;
236
+ continue;
237
+ }
238
+ }
239
+
240
+ if (char === "!" && src[i + 1] === "[") {
241
+ const image = matchLink(src, i + 1);
242
+ if (image) {
243
+ report(ctx, "image");
244
+ appendText(out, src.slice(i, image.end));
245
+ i = image.end;
246
+ continue;
247
+ }
248
+ }
249
+
250
+ if (char === "<") {
251
+ const tag = HTML_TAG.exec(src.slice(i));
252
+ if (tag) {
253
+ report(ctx, "html");
254
+ appendText(out, tag[0]);
255
+ i += tag[0].length;
256
+ continue;
257
+ }
258
+ }
259
+
260
+ if (char === "[") {
261
+ const link = matchLink(src, i);
262
+ if (link) {
263
+ const children = parseInline(link.text, ctx);
264
+ if (ctx.allow.has("link") && isSafeHref(link.href)) {
265
+ out.push({ type: "link", href: link.href, children });
266
+ } else {
267
+ report(ctx, "link");
268
+ appendText(out, "[");
269
+ appendAll(out, children);
270
+ appendText(out, `](${link.href})`);
271
+ }
272
+ i = link.end;
273
+ continue;
274
+ }
275
+ }
276
+
277
+ if (char === "*" || char === "_") {
278
+ const delim = src[i + 1] === char ? char + char : char;
279
+ if (canOpen(src, i, delim)) {
280
+ const close = findClose(src, i + delim.length, delim);
281
+ if (close > i + delim.length) {
282
+ const format: MarkdownFormat = delim.length === 2 ? "bold" : "italic";
283
+ const children = parseInline(src.slice(i + delim.length, close), ctx);
284
+ if (ctx.allow.has(format)) {
285
+ out.push({ type: format === "bold" ? "strong" : "emphasis", children });
286
+ } else {
287
+ report(ctx, format);
288
+ appendText(out, delim);
289
+ appendAll(out, children);
290
+ appendText(out, delim);
291
+ }
292
+ i = close + delim.length;
293
+ continue;
294
+ }
295
+ }
296
+ appendText(out, delim);
297
+ i += delim.length;
298
+ continue;
299
+ }
300
+
301
+ appendText(out, char);
302
+ i++;
303
+ }
304
+ return out;
305
+ }
package/src/zod.ts CHANGED
@@ -24,6 +24,7 @@ export function expectedTypeFor(
24
24
  case "object":
25
25
  return "object";
26
26
  case "text":
27
+ case "markdown":
27
28
  case "image":
28
29
  case "media":
29
30
  case "relation":
@@ -57,6 +58,7 @@ export function exampleValueFor(kind: FieldKind): unknown {
57
58
  case "link":
58
59
  return "/page";
59
60
  case "text":
61
+ case "markdown":
60
62
  return "";
61
63
  default: {
62
64
  const _exhaustive: never = kind;