@backmatter/core 0.0.56 → 0.0.58

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.56",
3
+ "version": "0.0.58",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/fields.ts CHANGED
@@ -25,13 +25,51 @@ function isMarkdownFormat(value: unknown): value is MarkdownFormat {
25
25
  return MARKDOWN_FORMATS.includes(value as MarkdownFormat);
26
26
  }
27
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;
28
+ /** Allowed formats in toolbar order, without repeats; null when unknown, or empty unless `empty`. */
29
+ function normalizeAllow(value: unknown, empty = false): MarkdownFormat[] | null {
30
+ if (!Array.isArray(value) || (value.length === 0 && !empty)) return null;
31
31
  if (!value.every(isMarkdownFormat)) return null;
32
32
  return MARKDOWN_FORMATS.filter((format) => value.includes(format));
33
33
  }
34
34
 
35
+ /** A named inline style a markdown field declares; the site styles it (ADR 0008). */
36
+ export type MarkdownMark = {
37
+ /** Studio's button text. */
38
+ label: string;
39
+ /** When to use it, for editors and the AI. */
40
+ description?: string;
41
+ };
42
+
43
+ export type MarkdownMarkInput = { label?: string; description?: string };
44
+
45
+ const MARK_NAME = /^[a-z][a-z0-9-]*$/;
46
+
47
+ function markLabel(name: string): string {
48
+ const words = name.replace(/-/g, " ");
49
+ return words.charAt(0).toUpperCase() + words.slice(1);
50
+ }
51
+
52
+ /** Marks with labels filled in; null when a name or value is invalid or there are none. */
53
+ function normalizeMarks(value: unknown, onBadName?: (name: string) => never): Record<string, MarkdownMark> | null {
54
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
55
+ const out: Record<string, MarkdownMark> = {};
56
+ for (const [name, raw] of Object.entries(value as Record<string, unknown>)) {
57
+ if (!MARK_NAME.test(name)) {
58
+ onBadName?.(name);
59
+ return null;
60
+ }
61
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
62
+ const { label, description } = raw as Record<string, unknown>;
63
+ if (label !== undefined && typeof label !== "string") return null;
64
+ if (description !== undefined && typeof description !== "string") return null;
65
+ out[name] = {
66
+ label: label?.trim() || markLabel(name),
67
+ ...(description?.trim() ? { description: description.trim() } : {}),
68
+ };
69
+ }
70
+ return Object.keys(out).length > 0 ? out : null;
71
+ }
72
+
35
73
  /** Equality filter on scalar frontmatter keys for a file-backed relation target. */
36
74
  export type RelationWhere = Record<string, string | number | boolean>;
37
75
 
@@ -75,6 +113,8 @@ export type FieldDef<
75
113
  picker?: BlockPickerView;
76
114
  /** For markdown fields: the formatting the stored markdown may use. */
77
115
  allow?: readonly MarkdownFormat[];
116
+ /** For markdown fields: the marks it declares, by name. */
117
+ marks?: Readonly<Record<string, MarkdownMark>>;
78
118
  /** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
79
119
  description?: string;
80
120
  };
@@ -109,6 +149,7 @@ export type FieldSnapshot = {
109
149
  accept?: MediaKind[];
110
150
  picker?: BlockPickerView;
111
151
  allow?: MarkdownFormat[];
152
+ marks?: Record<string, MarkdownMark>;
112
153
  description?: string;
113
154
  };
114
155
 
@@ -517,15 +558,30 @@ const constructors = {
517
558
  }) as TextFieldDef<R, O>;
518
559
  },
519
560
  markdown: <const R extends boolean = false>(
520
- opts?: Opts<R> & { allow?: readonly MarkdownFormat[] },
561
+ opts?: Opts<R> & {
562
+ allow?: readonly MarkdownFormat[];
563
+ /** Named inline styles the site defines, e.g. `{ muted: { label: "Muted" } }` (ADR 0008). */
564
+ marks?: Readonly<Record<string, MarkdownMarkInput>>;
565
+ },
521
566
  ): FieldDef<"markdown", R> => {
522
- const allow = opts?.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(opts.allow);
567
+ const marks =
568
+ opts?.marks === undefined
569
+ ? null
570
+ : normalizeMarks(opts.marks, (name) => {
571
+ throw new Error(`field.markdown mark "${name}" must be lowercase letters, digits and dashes`);
572
+ });
573
+ if (opts?.marks !== undefined && !marks) throw new Error("field.markdown marks must declare a mark");
574
+ const allow = opts?.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(opts.allow, marks !== null);
523
575
  if (!allow) {
524
576
  throw new Error(
525
577
  'field.markdown allow must list "bold", "italic", "link", "heading" and/or "list"',
526
578
  );
527
579
  }
528
- return { ...base("markdown", { required: opts?.required, input: opts?.input }), allow };
580
+ return {
581
+ ...base("markdown", { required: opts?.required, input: opts?.input }),
582
+ allow,
583
+ ...(marks ? { marks } : {}),
584
+ };
529
585
  },
530
586
  image: <const R extends boolean = false>(opts?: Opts<R>) => base("image", opts),
531
587
  media: <const R extends boolean = false, const M extends boolean = false>(
@@ -590,6 +646,7 @@ export function serializeField(def: FieldDef): FieldSnapshot {
590
646
  ...(def.accept ? { accept: [...def.accept] } : {}),
591
647
  ...(def.picker ? { picker: def.picker } : {}),
592
648
  ...(def.allow ? { allow: [...def.allow] } : {}),
649
+ ...(def.marks ? { marks: structuredClone(def.marks) as Record<string, MarkdownMark> } : {}),
593
650
  ...(def.description?.trim() ? { description: def.description.trim() } : {}),
594
651
  };
595
652
  if (def.fields) {
@@ -681,9 +738,13 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
681
738
  }
682
739
  if (isPickerView(value.picker)) snap.picker = value.picker;
683
740
  if (snap.kind === "markdown") {
684
- const allow = value.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(value.allow);
741
+ const marks = value.marks === undefined ? null : normalizeMarks(value.marks);
742
+ if (value.marks !== undefined && !marks) throw new Error("invalid field.marks");
743
+ const allow =
744
+ value.allow === undefined ? [...DEFAULT_MARKDOWN_ALLOW] : normalizeAllow(value.allow, marks !== null);
685
745
  if (!allow) throw new Error("invalid field.allow");
686
746
  snap.allow = allow;
747
+ if (marks) snap.marks = marks;
687
748
  }
688
749
  if (typeof value.description === "string" && value.description.trim()) {
689
750
  snap.description = value.description.trim();
package/src/index.ts CHANGED
@@ -8,6 +8,8 @@ export type {
8
8
  FieldSnapshot,
9
9
  BlockPickerView,
10
10
  MarkdownFormat,
11
+ MarkdownMark,
12
+ MarkdownMarkInput,
11
13
  } from "./fields";
12
14
  export {
13
15
  field,
@@ -129,12 +129,16 @@ function flatten(nodes: MarkdownInline[]): string {
129
129
  .join("");
130
130
  }
131
131
 
132
+ /** Something that may be a mark (ADR 0008), which page editing would drop. */
133
+ const MARK_LIKE = /(^|[^:\\]):[a-z][a-z0-9-]*\[/;
134
+
132
135
  /**
133
136
  * The text a markdown value shows when it renders as one paragraph, line breaks
134
- * as `\n`. Null for anything else (headings, lists, several paragraphs): those
135
- * are edited in the form, not on the page.
137
+ * as `\n`. Null for anything else (headings, lists, several paragraphs, marks):
138
+ * those are edited in the form, not on the page.
136
139
  */
137
140
  export function inlineMarkdownText(source: string, allow: readonly MarkdownFormat[]): string | null {
141
+ if (MARK_LIKE.test(source)) return null;
138
142
  const { blocks } = parseMarkdownField(source, allow);
139
143
  const only = blocks[0];
140
144
  if (blocks.length !== 1 || only?.type !== "paragraph") return null;
@@ -1,6 +1,7 @@
1
1
  // packages/core/src/markdown-field.ts
2
2
  // The markdown a markdown field stores, read into a small tree a host renders.
3
3
  // It is a subset on purpose: the block owns the layout around it (ADR 0007).
4
+ // A mark the field declares is a text directive, `:name[text]` (ADR 0008).
4
5
  import type { MarkdownFormat } from "./fields";
5
6
 
6
7
  export type MarkdownInline =
@@ -8,7 +9,8 @@ export type MarkdownInline =
8
9
  | { type: "break" }
9
10
  | { type: "strong"; children: MarkdownInline[] }
10
11
  | { type: "emphasis"; children: MarkdownInline[] }
11
- | { type: "link"; href: string; children: MarkdownInline[] };
12
+ | { type: "link"; href: string; children: MarkdownInline[] }
13
+ | { type: "mark"; name: string; children: MarkdownInline[] };
12
14
 
13
15
  export type MarkdownBlock =
14
16
  | { type: "paragraph"; children: MarkdownInline[] }
@@ -16,7 +18,7 @@ export type MarkdownBlock =
16
18
  | { type: "list"; ordered: boolean; items: MarkdownInline[][] };
17
19
 
18
20
  /** Markdown the value uses that renders as text: not allowed by the field, or never allowed. */
19
- export type MarkdownOutside = MarkdownFormat | "image" | "html" | "code";
21
+ export type MarkdownOutside = MarkdownFormat | "mark" | "image" | "html" | "code";
20
22
 
21
23
  export type ParsedMarkdownField = {
22
24
  blocks: MarkdownBlock[];
@@ -32,9 +34,11 @@ const ESCAPABLE = /[!-/:-@[-`{-~]/;
32
34
  const WORD = /[\p{L}\p{N}]/u;
33
35
  const SCHEME = /^([a-z][a-z0-9+.-]*):/i;
34
36
  const SAFE_SCHEMES = new Set(["http", "https", "mailto", "tel"]);
37
+ const MARK_NAME = /^[a-z][a-z0-9-]*/;
35
38
 
36
39
  type Context = {
37
40
  allow: ReadonlySet<MarkdownFormat>;
41
+ marks: ReadonlySet<string>;
38
42
  outside: MarkdownOutside[];
39
43
  };
40
44
 
@@ -46,12 +50,14 @@ function report(ctx: Context, kind: MarkdownOutside): void {
46
50
  * Read a markdown field's value. A single newline is a line break, a blank line
47
51
  * starts a paragraph. Formatting outside `allow`, and images, HTML and code
48
52
  * always, stay as the text that was written and are listed in `outside`.
53
+ * `marks` are the mark names the field declares; any other `:name[text]` is text.
49
54
  */
50
55
  export function parseMarkdownField(
51
56
  source: string,
52
57
  allow: readonly MarkdownFormat[],
58
+ marks: readonly string[] = [],
53
59
  ): ParsedMarkdownField {
54
- const ctx: Context = { allow: new Set(allow), outside: [] };
60
+ const ctx: Context = { allow: new Set(allow), marks: new Set(marks), outside: [] };
55
61
  const blocks: MarkdownBlock[] = [];
56
62
  let paragraph: string[] = [];
57
63
  let list: { ordered: boolean; items: string[] } | null = null;
@@ -183,18 +189,34 @@ function findClose(src: string, from: number, delim: string): number {
183
189
 
184
190
  type LinkMatch = { text: string; href: string; end: number };
185
191
 
186
- /** A `[text](href)` starting at `index`, where `src[index]` is `[`. */
187
- function matchLink(src: string, index: number): LinkMatch | null {
192
+ /** Index of the `]` that closes the `[` at `index`, or -1. */
193
+ function closeBracket(src: string, index: number): number {
188
194
  let depth = 0;
189
- let close = -1;
190
195
  for (let j = index; j < src.length; j++) {
191
196
  if (isEscaped(src, j)) continue;
192
197
  if (src[j] === "[") depth++;
193
- else if (src[j] === "]" && --depth === 0) {
194
- close = j;
195
- break;
196
- }
198
+ else if (src[j] === "]" && --depth === 0) return j;
197
199
  }
200
+ return -1;
201
+ }
202
+
203
+ type MarkMatch = { name: string; text: string; end: number };
204
+
205
+ /** A `:name[text]` starting at `index`, where `src[index]` is `:`. Not after or before another `:`. */
206
+ function matchMark(src: string, index: number): MarkMatch | null {
207
+ if (src[index - 1] === ":" || src[index + 1] === ":") return null;
208
+ const name = MARK_NAME.exec(src.slice(index + 1))?.[0];
209
+ if (!name) return null;
210
+ const open = index + 1 + name.length;
211
+ if (src[open] !== "[") return null;
212
+ const close = closeBracket(src, open);
213
+ if (close < 0) return null;
214
+ return { name, text: src.slice(open + 1, close), end: close + 1 };
215
+ }
216
+
217
+ /** A `[text](href)` starting at `index`, where `src[index]` is `[`. */
218
+ function matchLink(src: string, index: number): LinkMatch | null {
219
+ const close = closeBracket(src, index);
198
220
  if (close < 0 || src[close + 1] !== "(") return null;
199
221
  let parens = 0;
200
222
  for (let j = close + 1; j < src.length; j++) {
@@ -257,6 +279,20 @@ function parseInline(src: string, ctx: Context): MarkdownInline[] {
257
279
  }
258
280
  }
259
281
 
282
+ if (char === ":") {
283
+ const mark = matchMark(src, i);
284
+ if (mark) {
285
+ if (ctx.marks.has(mark.name)) {
286
+ out.push({ type: "mark", name: mark.name, children: parseInline(mark.text, ctx) });
287
+ i = mark.end;
288
+ continue;
289
+ }
290
+ // Only a mark the field declares is one, but a name it lacks is a
291
+ // mistake worth a warning when the field declares any.
292
+ if (ctx.marks.size > 0) report(ctx, "mark");
293
+ }
294
+ }
295
+
260
296
  if (char === "[") {
261
297
  const link = matchLink(src, i);
262
298
  if (link) {