@markdoc/markdoc 0.5.13 → 0.6.0

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.
Files changed (88) hide show
  1. package/README.md +29 -1
  2. package/dist/index.d.ts +4 -4
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1228 -1143
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.mjs +1228 -1143
  7. package/dist/index.mjs.map +4 -4
  8. package/dist/react.js +1 -1
  9. package/dist/react.js.map +2 -2
  10. package/dist/src/ast/base.d.ts +1 -1
  11. package/dist/src/ast/base.d.ts.map +1 -1
  12. package/dist/src/ast/function.d.ts +1 -1
  13. package/dist/src/ast/function.d.ts.map +1 -1
  14. package/dist/src/ast/index.d.ts +2 -2
  15. package/dist/src/ast/index.d.ts.map +1 -1
  16. package/dist/src/ast/node.d.ts.map +1 -1
  17. package/dist/src/ast/variable.d.ts +1 -1
  18. package/dist/src/ast/variable.d.ts.map +1 -1
  19. package/dist/src/formatter.d.ts.map +1 -1
  20. package/dist/src/functions/index.d.ts.map +1 -1
  21. package/dist/src/parser.d.ts.map +1 -1
  22. package/dist/src/renderers/html.d.ts.map +1 -1
  23. package/dist/src/renderers/react/react.d.ts +3 -3
  24. package/dist/src/renderers/react/react.d.ts.map +1 -1
  25. package/dist/src/renderers/react/static.d.ts +1 -1
  26. package/dist/src/renderers/react/static.d.ts.map +1 -1
  27. package/dist/src/schema-types/class.d.ts +1 -1
  28. package/dist/src/schema-types/class.d.ts.map +1 -1
  29. package/dist/src/schema-types/conditional.d.ts +1 -1
  30. package/dist/src/schema-types/conditional.d.ts.map +1 -1
  31. package/dist/src/schema.d.ts.map +1 -1
  32. package/dist/src/tags/conditional.d.ts +1 -1
  33. package/dist/src/tags/conditional.d.ts.map +1 -1
  34. package/dist/src/tokenizer/index.d.ts.map +1 -1
  35. package/dist/src/tokenizer/plugins/annotations.d.ts.map +1 -1
  36. package/dist/src/transformer.d.ts.map +1 -1
  37. package/dist/src/validator.d.ts +1 -1
  38. package/dist/src/validator.d.ts.map +1 -1
  39. package/index.ts +21 -22
  40. package/package.json +9 -14
  41. package/spec/support/matchers.d.ts +6 -4
  42. package/src/ast/base.test.ts +120 -0
  43. package/src/ast/base.ts +14 -9
  44. package/src/ast/function.ts +1 -1
  45. package/src/ast/index.ts +3 -4
  46. package/src/ast/node.test.ts +140 -45
  47. package/src/ast/node.ts +32 -13
  48. package/src/ast/variable.test.ts +5 -4
  49. package/src/ast/variable.ts +1 -1
  50. package/src/ast/walk.test.ts +283 -0
  51. package/src/formatter.test.ts +31 -3
  52. package/src/formatter.ts +12 -12
  53. package/src/functions/index.test.ts +8 -7
  54. package/src/functions/index.ts +1 -1
  55. package/src/grammar/tag.d.ts +1 -1
  56. package/src/grammar/tag.js +208 -285
  57. package/src/grammar/tag.pegjs +4 -4
  58. package/src/grammar/tag.test.ts +56 -52
  59. package/src/parser.test.ts +93 -70
  60. package/src/parser.ts +19 -6
  61. package/src/renderers/html.test.ts +56 -16
  62. package/src/renderers/html.ts +10 -2
  63. package/src/renderers/react/react.test.ts +49 -28
  64. package/src/renderers/react/react.ts +8 -9
  65. package/src/renderers/react/static.ts +7 -12
  66. package/src/schema-types/class.ts +1 -1
  67. package/src/schema-types/conditional.ts +1 -1
  68. package/src/schema.ts +13 -6
  69. package/src/tag.test.ts +2 -1
  70. package/src/tag.ts +1 -1
  71. package/src/tags/conditional.ts +4 -4
  72. package/src/tags/index.ts +2 -2
  73. package/src/tags/partial.ts +1 -1
  74. package/src/tokenizer/index.ts +6 -5
  75. package/src/tokenizer/plugins/annotations.test.ts +29 -28
  76. package/src/tokenizer/plugins/annotations.ts +12 -12
  77. package/src/tokenizer/plugins/comments.test.ts +11 -10
  78. package/src/tokenizer/plugins/comments.ts +2 -2
  79. package/src/tokenizer/plugins/frontmatter.test.ts +7 -6
  80. package/src/tokenizer/plugins/frontmatter.ts +2 -2
  81. package/src/tokenizer/plugins/link.test.ts +14 -13
  82. package/src/transformer.ts +7 -5
  83. package/src/transforms/table.test.ts +18 -17
  84. package/src/transforms/table.ts +1 -1
  85. package/src/utils.test.ts +23 -22
  86. package/src/utils.ts +3 -3
  87. package/src/validator.test.ts +60 -59
  88. package/src/validator.ts +43 -14
@@ -0,0 +1,283 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import Markdoc from '../../index';
3
+ import { walkWithParents } from '../validator';
4
+ import Node from './node';
5
+
6
+ function expectNodes(actual: Node[], expected: Node[]) {
7
+ expect(actual).toHaveLength(expected.length);
8
+ for (const [index, node] of expected.entries())
9
+ expect(actual[index]).toBe(node);
10
+ }
11
+
12
+ function expectVisit(
13
+ actual: [Node, Node[]] | undefined,
14
+ expected: [Node, Node[]],
15
+ ) {
16
+ expect(actual).toBeDefined();
17
+ expect(actual![0]).toBe(expected[0]);
18
+ expectNodes(actual![1], expected[1]);
19
+ }
20
+
21
+ function expectVisits(actual: [Node, Node[]][], expected: [Node, Node[]][]) {
22
+ expect(actual).toHaveLength(expected.length);
23
+ for (const [index, entry] of expected.entries())
24
+ expectVisit(actual[index], entry);
25
+ }
26
+
27
+ describe('Node.walk', () => {
28
+ it('visits slots before children in preorder, including repeated nodes', () => {
29
+ const shared = new Node();
30
+ const slot = new Node('slot', {}, [shared]);
31
+ const child = new Node('paragraph', {}, [shared]);
32
+ const childSlot = new Node('slot');
33
+ child.slots.title = childSlot;
34
+ const root = new Node('document', {}, [child]);
35
+ root.slots.title = slot;
36
+
37
+ expectNodes([...root.walk()], [slot, shared, child, childSlot, shared]);
38
+ });
39
+
40
+ it('snapshots siblings but reads descendants after yielding their parent', () => {
41
+ const first = new Node();
42
+ const second = new Node();
43
+ const root = new Node('document', {}, [first, second]);
44
+ const iter = root.walk();
45
+ const beforeStart = new Node();
46
+ root.children.push(beforeStart);
47
+ expect(iter.next().value).toBe(first);
48
+
49
+ root.children = [];
50
+ const descendant = new Node();
51
+ first.slots.title = descendant;
52
+ expect(iter.next().value).toBe(descendant);
53
+
54
+ first.children.push(new Node());
55
+ const laterDescendant = new Node();
56
+ second.children.push(laterDescendant);
57
+ expectNodes([...iter], [second, laterDescendant, beforeStart]);
58
+ });
59
+
60
+ it('delegates to custom child walkers with the child as receiver', () => {
61
+ const replacement = new Node();
62
+ class CustomNode extends Node {
63
+ *walk() {
64
+ expect(this).toBe(custom);
65
+ yield replacement;
66
+ }
67
+ }
68
+ const custom = new CustomNode('node', {}, [new Node()]);
69
+ Object.defineProperty(custom.walk, 'call', { value: undefined });
70
+ const sibling = new Node();
71
+ const root = new Node('document', {}, [custom, sibling]);
72
+
73
+ expectNodes([...root.walk()], [custom, replacement, sibling]);
74
+ });
75
+
76
+ it('reads a child walker after yielding the child', () => {
77
+ const child = new Node();
78
+ const replacement = new Node();
79
+ const iter = new Node('document', {}, [child]).walk();
80
+ expect(iter.next().value).toBe(child);
81
+ child.walk = function* () {
82
+ yield replacement;
83
+ };
84
+
85
+ expectNodes([...iter], [replacement]);
86
+ });
87
+
88
+ it('honors prototype walker replacements during iteration', () => {
89
+ const child = new Node();
90
+ const replacement = new Node();
91
+ const iter = new Node('document', {}, [child]).walk();
92
+ expect(iter.next().value).toBe(child);
93
+ const original = Node.prototype.walk;
94
+ try {
95
+ Node.prototype.walk = function* () {
96
+ yield replacement;
97
+ };
98
+ expectNodes([...iter], [replacement]);
99
+ } finally {
100
+ Node.prototype.walk = original;
101
+ }
102
+ });
103
+
104
+ it('closes a delegated child walker when iteration stops', () => {
105
+ let closed = false;
106
+ const child = new Node();
107
+ child.walk = function* () {
108
+ try {
109
+ yield new Node();
110
+ } finally {
111
+ closed = true;
112
+ }
113
+ };
114
+ const iter = new Node('document', {}, [child]).walk();
115
+ iter.next();
116
+ iter.next();
117
+ iter.return();
118
+
119
+ expect(closed).toBe(true);
120
+ });
121
+
122
+ it('walks deeply nested trees without recursive generator calls', () => {
123
+ let root = new Node();
124
+ for (let index = 0; index < 4000; index++)
125
+ root = new Node('node', {}, [root]);
126
+
127
+ let count = 0;
128
+ for (const _node of root.walk()) count++;
129
+ expect(count).toBe(4000);
130
+ });
131
+ });
132
+
133
+ describe('walkWithParents', () => {
134
+ it('includes the root and visits slots before children with fresh parent arrays', () => {
135
+ const leaf = new Node();
136
+ const slot = new Node('slot', {}, [leaf]);
137
+ const child = new Node();
138
+ const root = new Node('document', {}, [child]);
139
+ root.slots.title = slot;
140
+ const entries = [...walkWithParents(root)];
141
+
142
+ expectVisits(entries, [
143
+ [root, []],
144
+ [slot, [root]],
145
+ [leaf, [root, slot]],
146
+ [child, [root]],
147
+ ]);
148
+ expect(new Set(entries.map(([, parents]) => parents)).size).toBe(4);
149
+ });
150
+
151
+ it('reads descendants after yielding and snapshots each sibling list', () => {
152
+ const first = new Node();
153
+ const second = new Node();
154
+ const root = new Node('document', {}, [first]);
155
+ const iter = walkWithParents(root);
156
+ expectVisit(iter.next().value, [root, []]);
157
+ root.children.push(second);
158
+ expectVisit(iter.next().value, [first, [root]]);
159
+
160
+ root.children = [];
161
+ const descendant = new Node();
162
+ first.slots.title = descendant;
163
+ expectVisit(iter.next().value, [descendant, [root, first]]);
164
+ first.children.push(new Node());
165
+ expectVisits([...iter], [[second, [root]]]);
166
+ });
167
+
168
+ it('copies the current parent array separately when each child is reached', () => {
169
+ const grandchild = new Node();
170
+ const first = new Node('node', {}, [grandchild]);
171
+ const second = new Node();
172
+ const root = new Node('document', {}, [first, second]);
173
+ const ancestor = new Node();
174
+ const parents = [ancestor];
175
+ const iter = walkWithParents(root, parents);
176
+ const rootEntry = iter.next().value as [Node, Node[]];
177
+ expectVisit(rootEntry, [root, parents]);
178
+ expect(rootEntry[1]).toBe(parents);
179
+ const before = new Node();
180
+ parents.push(before);
181
+ const firstEntry = iter.next().value as [Node, Node[]];
182
+ expectVisit(firstEntry, [first, [ancestor, before, root]]);
183
+
184
+ const local = new Node();
185
+ firstEntry[1].push(local);
186
+ const later = new Node();
187
+ parents.push(later);
188
+ expectVisit(iter.next().value, [
189
+ grandchild,
190
+ [ancestor, before, root, local, first],
191
+ ]);
192
+ const secondEntry = iter.next().value as [Node, Node[]];
193
+ expectVisit(secondEntry, [second, [ancestor, before, later, root]]);
194
+ expect(secondEntry[1]).not.toBe(firstEntry[1]);
195
+ });
196
+
197
+ it('does not use replacements made to the yielded tuple', () => {
198
+ const child = new Node();
199
+ const root = new Node('document', {}, [child]);
200
+ const iter = walkWithParents(root);
201
+ const entry = iter.next().value as [Node, Node[]];
202
+ entry[0] = new Node();
203
+ entry[1] = [new Node()];
204
+
205
+ expectVisits([...iter], [[child, [root]]]);
206
+ });
207
+
208
+ it('walks deeply nested trees without recursive generator calls', () => {
209
+ let root = new Node();
210
+ for (let index = 0; index < 4000; index++)
211
+ root = new Node('node', {}, [root]);
212
+
213
+ let count = 0;
214
+ let depth = 0;
215
+ for (const [, parents] of walkWithParents(root)) {
216
+ count++;
217
+ depth = parents.length;
218
+ }
219
+ expect(count).toBe(4001);
220
+ expect(depth).toBe(4000);
221
+ });
222
+ });
223
+
224
+ describe('validation traversal', () => {
225
+ it('snapshots the tree and gives each validation hook its own parent array', () => {
226
+ const first = new Node();
227
+ const second = new Node();
228
+ const root = new Node('node', {}, [first, second]);
229
+ const seen: [Node, Node[]][] = [];
230
+ const parentArrays: Node[][] = [];
231
+ const poison = new Node();
232
+
233
+ expect(
234
+ Markdoc.validate(root, {
235
+ nodes: {
236
+ node: {
237
+ validate(node, config) {
238
+ const parents = config.validation!.parents!;
239
+ seen.push([node, [...parents]]);
240
+ parentArrays.push(parents);
241
+ parents.push(poison);
242
+ if (node === root) root.children = [new Node()];
243
+ return [];
244
+ },
245
+ },
246
+ },
247
+ }),
248
+ ).toEqual([]);
249
+
250
+ expectVisits(seen, [
251
+ [root, []],
252
+ [first, [root]],
253
+ [second, [root]],
254
+ ]);
255
+ expect(new Set(parentArrays).size).toBe(3);
256
+ });
257
+
258
+ it('keeps parent arrays stable for asynchronous validation hooks', async () => {
259
+ const first = new Node();
260
+ const second = new Node();
261
+ const root = new Node('node', {}, [first, second]);
262
+ const seen: [Node, Node[]][] = [];
263
+
264
+ await Markdoc.validate(root, {
265
+ nodes: {
266
+ node: {
267
+ async validate(node, config) {
268
+ await Promise.resolve();
269
+ seen.push([node, [...config.validation!.parents!]]);
270
+ config.validation!.parents!.push(new Node());
271
+ return [];
272
+ },
273
+ },
274
+ },
275
+ });
276
+
277
+ expectVisits(seen, [
278
+ [root, []],
279
+ [first, [root]],
280
+ [second, [root]],
281
+ ]);
282
+ });
283
+ });
@@ -1,4 +1,5 @@
1
1
  import { diff } from 'jest-diff';
2
+ import { describe, expect, it } from 'vitest';
2
3
 
3
4
  import Markdoc from '../index';
4
5
  import format from './formatter';
@@ -86,7 +87,7 @@ function check(source, expected, options = {}) {
86
87
  const b = format(Markdoc.parse(tokenizer.tokenize(source)), options);
87
88
  // console.log(a, b);
88
89
  const d = diff(a, b);
89
- if (d && d.includes('Compared values have no visual difference.')) return;
90
+ if (d?.includes('Compared values have no visual difference.')) return;
90
91
  throw d;
91
92
  }
92
93
 
@@ -185,6 +186,33 @@ paragraph 2
185
186
  stable(source);
186
187
  });
187
188
 
189
+ it('escapes only the first run of heading marks', () => {
190
+ const examples = {
191
+ 'a ## b': 'a \\## b',
192
+ 'C# and C# again': 'C\\# and C# again',
193
+ '##x ## y': '##x \\## y',
194
+ 'Issue #': 'Issue #',
195
+ };
196
+
197
+ for (const [content, expected] of Object.entries(examples)) {
198
+ const ast = new Markdoc.Ast.Node('paragraph', {}, [
199
+ new Markdoc.Ast.Node('text', { content }),
200
+ ]);
201
+ expect(Markdoc.format(ast).trim()).toEqual(expected);
202
+ }
203
+ });
204
+
205
+ it('escapes long runs of heading marks in linear time', () => {
206
+ const content = '#'.repeat(100_000) + 'x';
207
+ const ast = new Markdoc.Ast.Node('paragraph', {}, [
208
+ new Markdoc.Ast.Node('text', { content }),
209
+ ]);
210
+
211
+ const start = performance.now();
212
+ expect(Markdoc.format(ast).trim()).toEqual(content);
213
+ expect(performance.now() - start).toBeLessThan(500);
214
+ });
215
+
188
216
  it('emphasis marks', () => {
189
217
  const examples = [
190
218
  '*foo* bar baz',
@@ -896,14 +924,14 @@ ${'`'.repeat(4)}
896
924
  validAttribute: true,
897
925
  },
898
926
  [],
899
- 'tag'
927
+ 'tag',
900
928
  );
901
929
 
902
930
  const expected = `{% tag validAttribute=true /%}`;
903
931
 
904
932
  const b = format(sourceNode);
905
933
  const d = diff(expected, b.trim());
906
- if (d && d.includes('Compared values have no visual difference.')) return;
934
+ if (d?.includes('Compared values have no visual difference.')) return;
907
935
  });
908
936
 
909
937
  it('makes sure fences are formatted correctly if content has no ending newline', () => {
package/src/formatter.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import Ast from './ast';
2
- import { OPEN, CLOSE, isIdentifier } from './utils';
3
2
  import type { AttributeValue, Function, Node, Value, Variable } from './types';
3
+ import { CLOSE, isIdentifier, OPEN } from './utils';
4
4
 
5
5
  type Options = {
6
6
  allowIndentation?: boolean;
@@ -59,7 +59,7 @@ function formatScalar(v: Value): string | undefined {
59
59
  Object.entries(v)
60
60
  .map(
61
61
  ([key, value]) =>
62
- `${isIdentifier(key) ? key : `"${key}"`}: ${formatScalar(value)}`
62
+ `${isIdentifier(key) ? key : `"${key}"`}: ${formatScalar(value)}`,
63
63
  )
64
64
  .join(SEP) +
65
65
  '}'
@@ -122,7 +122,7 @@ function* formatFunction(f: Function) {
122
122
  }
123
123
 
124
124
  function* trimStart(g: Generator<string>) {
125
- let n;
125
+ let n: string;
126
126
  do {
127
127
  const { value, done } = g.next();
128
128
  if (done) return;
@@ -137,7 +137,7 @@ function* escapeMarkdownCharacters(s: string, characters: RegExp) {
137
137
  .replace(characters, '\\$&')
138
138
  // TODO keep &nbsp; as entity in the AST?
139
139
  // Non-breaking space (0xA0)
140
- .replace(new RegExp('\xa0', 'g'), '&nbsp;');
140
+ .replace(/\xa0/g, '&nbsp;');
141
141
  }
142
142
 
143
143
  function* formatNode(n: Node, o: Options = {}) {
@@ -146,7 +146,7 @@ function* formatNode(n: Node, o: Options = {}) {
146
146
 
147
147
  switch (n.type) {
148
148
  case 'document': {
149
- if (n.attributes.frontmatter && n.attributes.frontmatter.length) {
149
+ if (n.attributes.frontmatter?.length) {
150
150
  yield '---' + NL + n.attributes.frontmatter + NL + '---' + NL + NL;
151
151
  }
152
152
  yield* trimStart(formatChildren(n, no));
@@ -224,7 +224,7 @@ function* formatNode(n: Node, o: Options = {}) {
224
224
  yield* escapeMarkdownCharacters(content, /[*_~]/g);
225
225
  } else {
226
226
  // Escape > blockquote, * list item, and heading
227
- yield* escapeMarkdownCharacters(content, /^\*|#+\s|^>/);
227
+ yield* escapeMarkdownCharacters(content, /^\*|(?<!#)#+\s|^>/);
228
228
  }
229
229
  }
230
230
 
@@ -279,7 +279,7 @@ function* formatNode(n: Node, o: Options = {}) {
279
279
  }
280
280
  const open = OPEN + SPACE;
281
281
  const attributes = [...formatAttributes(n)].filter(
282
- (v) => v !== undefined
282
+ (v) => v !== undefined,
283
283
  );
284
284
  const tag = [open + n.tag, ...attributes];
285
285
  const inlineTag = tag.join(SPACE);
@@ -311,7 +311,7 @@ function* formatNode(n: Node, o: Options = {}) {
311
311
  }
312
312
  case 'list': {
313
313
  const isLoose = n.children.some((n) =>
314
- n.children.some((c) => c.type === 'paragraph')
314
+ n.children.some((c) => c.type === 'paragraph'),
315
315
  );
316
316
 
317
317
  for (let i = 0; i < n.children.length; i++) {
@@ -418,14 +418,14 @@ function* formatNode(n: Node, o: Options = {}) {
418
418
 
419
419
  yield NL;
420
420
  yield* formatTableRow(
421
- head.map((cell, i) => cell + SPACE.repeat(widths[i] - cell.length))
421
+ head.map((cell, i) => cell + SPACE.repeat(widths[i] - cell.length)),
422
422
  );
423
423
  yield NL;
424
- yield* formatTableRow(head.map((cell, i) => '-'.repeat(widths[i])));
424
+ yield* formatTableRow(head.map((_cell, i) => '-'.repeat(widths[i])));
425
425
  yield NL;
426
426
  for (const row of rows) {
427
427
  yield* formatTableRow(
428
- row.map((cell, i) => cell + SPACE.repeat(widths[i] - cell.length))
428
+ row.map((cell, i) => cell + SPACE.repeat(widths[i] - cell.length)),
429
429
  );
430
430
  yield NL;
431
431
  }
@@ -462,7 +462,7 @@ function* formatNode(n: Node, o: Options = {}) {
462
462
 
463
463
  function* formatValue(
464
464
  v: Value | Value[],
465
- o: Options = {}
465
+ o: Options = {},
466
466
  ): Generator<string, void, unknown> {
467
467
  switch (typeof v) {
468
468
  case 'undefined':
@@ -1,9 +1,10 @@
1
- import functions from './index';
1
+ import { describe, expect, it } from 'vitest';
2
2
  import Ast from '../ast';
3
+ import functions from './index';
3
4
 
4
- describe('built-in functions', function () {
5
- describe('equals function', function () {
6
- it('true match with variable', function () {
5
+ describe('built-in functions', () => {
6
+ describe('equals function', () => {
7
+ it('true match with variable', () => {
7
8
  const example = new Ast.Function('equals', {
8
9
  0: new Ast.Variable(['foo']),
9
10
  1: 'bar',
@@ -14,10 +15,10 @@ describe('built-in functions', function () {
14
15
  variables: { foo: 'bar' },
15
16
  });
16
17
 
17
- expect(output).toBeTrue();
18
+ expect(output).toBe(true);
18
19
  });
19
20
 
20
- it('false match with variable', function () {
21
+ it('false match with variable', () => {
21
22
  const example = new Ast.Function('equals', {
22
23
  0: new Ast.Variable(['foo']),
23
24
  1: 'bar',
@@ -28,7 +29,7 @@ describe('built-in functions', function () {
28
29
  variables: { foo: 'baz' },
29
30
  });
30
31
 
31
- expect(output).toBeFalse();
32
+ expect(output).toBe(false);
32
33
  });
33
34
  });
34
35
  });
@@ -1,5 +1,5 @@
1
- import type { ConfigFunction } from '../types';
2
1
  import { truthy } from '../tags/conditional';
2
+ import type { ConfigFunction } from '../types';
3
3
 
4
4
  const and: ConfigFunction = {
5
5
  transform(parameters) {
@@ -1,6 +1,6 @@
1
1
  import type { Token } from 'markdown-it';
2
- import type AstVariable from '../ast/variable';
3
2
  import type AstFunction from '../ast/function';
3
+ import type AstVariable from '../ast/variable';
4
4
 
5
5
  type astTypes = {
6
6
  Variable?: typeof AstVariable;