@markdoc/markdoc 0.2.2 → 0.3.1

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 (46) hide show
  1. package/dist/index.d.ts +21 -4
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +154 -58
  4. package/dist/index.js.map +3 -3
  5. package/dist/index.mjs +154 -58
  6. package/dist/index.mjs.map +3 -3
  7. package/dist/src/ast/index.d.ts +1 -0
  8. package/dist/src/ast/index.d.ts.map +1 -1
  9. package/dist/src/ast/node.d.ts +1 -0
  10. package/dist/src/ast/node.d.ts.map +1 -1
  11. package/dist/src/formatter.d.ts.map +1 -1
  12. package/dist/src/parser.d.ts +2 -1
  13. package/dist/src/parser.d.ts.map +1 -1
  14. package/dist/src/schema-types/class.d.ts +2 -2
  15. package/dist/src/schema-types/class.d.ts.map +1 -1
  16. package/dist/src/schema.d.ts.map +1 -1
  17. package/dist/src/tags/index.d.ts +17 -2
  18. package/dist/src/tags/index.d.ts.map +1 -1
  19. package/dist/src/tags/slot.d.ts +3 -0
  20. package/dist/src/tags/slot.d.ts.map +1 -0
  21. package/dist/src/tokenizer/plugins/annotations.d.ts.map +1 -1
  22. package/dist/src/transformer.d.ts.map +1 -1
  23. package/dist/src/types.d.ts +14 -1
  24. package/dist/src/types.d.ts.map +1 -1
  25. package/dist/src/validator.d.ts +23 -1
  26. package/dist/src/validator.d.ts.map +1 -1
  27. package/index.ts +9 -24
  28. package/package.json +1 -1
  29. package/src/ast/node.test.ts +47 -0
  30. package/src/ast/node.ts +3 -1
  31. package/src/formatter.test.ts +99 -8
  32. package/src/formatter.ts +39 -16
  33. package/src/parser.test.ts +276 -2
  34. package/src/parser.ts +37 -11
  35. package/src/renderers/html.test.ts +7 -0
  36. package/src/renderers/html.ts +1 -1
  37. package/src/schema-types/class.ts +7 -3
  38. package/src/schema.ts +12 -2
  39. package/src/tags/index.ts +3 -1
  40. package/src/tags/slot.ts +7 -0
  41. package/src/tokenizer/plugins/annotations.test.ts +44 -22
  42. package/src/tokenizer/plugins/annotations.ts +3 -1
  43. package/src/transformer.ts +7 -0
  44. package/src/types.ts +16 -1
  45. package/src/validator.test.ts +202 -0
  46. package/src/validator.ts +73 -7
@@ -111,6 +111,29 @@ describe('MarkdownIt Annotations plugin', function () {
111
111
  });
112
112
 
113
113
  describe('multiline', function () {
114
+ const basicExample = [
115
+ {
116
+ type: 'tag_open',
117
+ nesting: 1,
118
+ meta: {
119
+ attributes: [
120
+ { type: 'attribute', name: 'id', value: 'foo' },
121
+ { type: 'class', name: 'bar', value: true },
122
+ { type: 'attribute', name: 'baz', value: 1 },
123
+ ],
124
+ tag: 'test',
125
+ },
126
+ },
127
+ { type: 'paragraph_open', tag: 'p', nesting: 1 },
128
+ {
129
+ type: 'inline',
130
+ nesting: 0,
131
+ children: [{ type: 'text', nesting: 0, content: 'This is a test' }],
132
+ },
133
+ { type: 'paragraph_close', tag: 'p', nesting: -1 },
134
+ { type: 'tag_close', nesting: -1, meta: { tag: 'test' } },
135
+ ];
136
+
114
137
  it('basic', function () {
115
138
  const example = parse(`
116
139
  {% test #foo .bar
@@ -119,29 +142,28 @@ describe('MarkdownIt Annotations plugin', function () {
119
142
  {% /test %}
120
143
  `);
121
144
 
122
- expect(example).toDeepEqualSubset([
123
- {
124
- type: 'tag_open',
125
- nesting: 1,
126
- meta: {
127
- attributes: [
128
- { type: 'attribute', name: 'id', value: 'foo' },
129
- { type: 'class', name: 'bar', value: true },
130
- { type: 'attribute', name: 'baz', value: 1 },
131
- ],
132
- tag: 'test',
133
- },
134
- },
135
- { type: 'paragraph_open', tag: 'p', nesting: 1 },
136
- {
137
- type: 'inline',
138
- nesting: 0,
139
- children: [{ type: 'text', nesting: 0, content: 'This is a test' }],
140
- },
141
- { type: 'paragraph_close', tag: 'p', nesting: -1 },
142
- { type: 'tag_close', nesting: -1, meta: { tag: 'test' } },
143
- ]);
145
+ expect(example).toDeepEqualSubset(basicExample);
146
+ expect(example[0].map).toDeepEqual([0, 2]);
147
+ expect(example[1].map).toDeepEqual([2, 3]);
148
+ expect(example[4].map).toDeepEqual([3, 4]);
149
+ expect(example.length).toEqual(5);
150
+ expect(example[2].children.length).toEqual(1);
151
+ });
152
+
153
+ it('basic with symbols on separate lines', function () {
154
+ const example = parse(`
155
+ {%
156
+ test #foo .bar
157
+ baz=1
158
+ %}
159
+ This is a test
160
+ {% /test %}
161
+ `);
144
162
 
163
+ expect(example).toDeepEqualSubset(basicExample);
164
+ expect(example[0].map).toDeepEqual([0, 4]);
165
+ expect(example[2].map).toDeepEqual([4, 5]);
166
+ expect(example[4].map).toDeepEqual([5, 6]);
145
167
  expect(example.length).toEqual(5);
146
168
  expect(example[2].children.length).toEqual(1);
147
169
  });
@@ -66,7 +66,9 @@ function block(
66
66
 
67
67
  const contentStart = start + OPEN.length;
68
68
  const content = state.src.slice(contentStart, tagEnd).trim();
69
- const lines = content.split('\n').length;
69
+ const lines = state.src
70
+ .slice(start, tagEnd + CLOSE.length)
71
+ .split('\n').length;
70
72
 
71
73
  if (content[0] === '$') return false;
72
74
 
@@ -47,6 +47,13 @@ export default {
47
47
  output[name] = value;
48
48
  }
49
49
 
50
+ if (schema.slots) {
51
+ for (const [key, slot] of Object.entries(schema.slots)) {
52
+ const name = typeof slot.render === 'string' ? slot.render : key;
53
+ if (node.slots[key]) output[name] = this.node(node.slots[key], config);
54
+ }
55
+ }
56
+
50
57
  return output;
51
58
  },
52
59
 
package/src/types.ts CHANGED
@@ -29,6 +29,7 @@ export type ConfigType = Partial<{
29
29
  functions: Record<string, ConfigFunction>;
30
30
  partials: Record<string, any>;
31
31
  validation?: {
32
+ parents?: Node[];
32
33
  validateFunctions?: boolean;
33
34
  };
34
35
  }>;
@@ -42,7 +43,7 @@ export type ConfigFunction = {
42
43
 
43
44
  export interface CustomAttributeTypeInterface {
44
45
  transform?(value: any, config: Config): Scalar;
45
- validate?(value: any, config: Config): ValidationError[];
46
+ validate?(value: any, config: Config, name: string): ValidationError[];
46
47
  }
47
48
 
48
49
  export interface CustomAttributeType {
@@ -102,10 +103,12 @@ export type Schema<C extends Config = Config, R = string> = {
102
103
  render?: R;
103
104
  children?: string[];
104
105
  attributes?: Record<string, SchemaAttribute>;
106
+ slots?: Record<string, SchemaSlot>;
105
107
  selfClosing?: boolean;
106
108
  inline?: boolean;
107
109
  transform?(node: Node, config: C): MaybePromise<RenderableTreeNodes>;
108
110
  validate?(node: Node, config: C): MaybePromise<ValidationError[]>;
111
+ description?: string;
109
112
  };
110
113
 
111
114
  export type SchemaAttribute = {
@@ -114,11 +117,18 @@ export type SchemaAttribute = {
114
117
  default?: any;
115
118
  required?: boolean;
116
119
  matches?: SchemaMatches | ((config: Config) => SchemaMatches);
120
+ validate?(value: any, config: Config, name: string): ValidationError[];
117
121
  errorLevel?: ValidationError['level'];
122
+ description?: string;
118
123
  };
119
124
 
120
125
  export type SchemaMatches = RegExp | string[] | null;
121
126
 
127
+ export type SchemaSlot = {
128
+ render?: boolean | string;
129
+ required?: boolean;
130
+ };
131
+
122
132
  export interface Transformer {
123
133
  findSchema(node: Node, config: Config): Schema | undefined;
124
134
  node(node: Node, config: Config): MaybePromise<RenderableTreeNodes>;
@@ -154,3 +164,8 @@ export type ValidationType =
154
164
  | 'Array';
155
165
 
156
166
  export type Value = AstType | Scalar;
167
+
168
+ export type ParserArgs = {
169
+ file?: string;
170
+ slots?: boolean;
171
+ };
@@ -289,6 +289,44 @@ bar
289
289
  });
290
290
 
291
291
  describe('attribute validation', () => {
292
+ describe('with a validate function', () => {
293
+ it('using simple conditional', () => {
294
+ const schema = {
295
+ tags: {
296
+ foo: {
297
+ attributes: {
298
+ bar: {
299
+ type: Number,
300
+ validate(value, _config) {
301
+ return value > 10
302
+ ? []
303
+ : [
304
+ {
305
+ id: 'attribute-should-be-greater-than-ten',
306
+ message:
307
+ 'Attribute "bar" must have value greater than 10.',
308
+ },
309
+ ];
310
+ },
311
+ },
312
+ },
313
+ },
314
+ },
315
+ };
316
+
317
+ expect(validate(`{% foo bar=20 /%}`, schema)).toEqual([]);
318
+ expect(validate(`{% foo bar=5 /%}`, schema)).toDeepEqualSubset([
319
+ {
320
+ type: 'tag',
321
+ error: {
322
+ id: 'attribute-should-be-greater-than-ten',
323
+ message: 'Attribute "bar" must have value greater than 10.',
324
+ },
325
+ },
326
+ ]);
327
+ });
328
+ });
329
+
292
330
  it('should return error on failure to match array', () => {
293
331
  const example = '{% foo jawn="cat" /%}';
294
332
  const schema = {
@@ -315,6 +353,33 @@ bar
315
353
  ]);
316
354
  });
317
355
 
356
+ it('Elides excess values in matches check', () => {
357
+ const example = '{% foo jawn="cat" /%}';
358
+ const schema = {
359
+ tags: {
360
+ foo: {
361
+ attributes: {
362
+ jawn: {
363
+ type: String,
364
+ matches: Array.from('foobarbazqux'),
365
+ },
366
+ },
367
+ },
368
+ },
369
+ };
370
+
371
+ const output = validate(example, schema);
372
+ expect(output).toDeepEqualSubset([
373
+ {
374
+ type: 'tag',
375
+ error: {
376
+ id: 'attribute-value-invalid',
377
+ message: `Attribute 'jawn' must match one of ["f","o","o","b","a","r","b","a", ... 4 more]. Got 'cat' instead.`,
378
+ },
379
+ },
380
+ ]);
381
+ });
382
+
318
383
  // https://github.com/markdoc/markdoc/issues/122
319
384
  it('should validate partial file attributes', () => {
320
385
  const example = `{% partial file="non-existent.md" /%}`;
@@ -479,4 +544,141 @@ bar
479
544
  ]);
480
545
  });
481
546
  });
547
+
548
+ describe('attribute validation key', () => {
549
+ it('simple case', () => {
550
+ const example = `{% foo bar={baz: 3} /%}`;
551
+
552
+ function validator(value, config, name) {
553
+ return value.baz < 5
554
+ ? [
555
+ {
556
+ id: 'invalid-foo-bar',
557
+ level: 'error',
558
+ message: `The value of '${name}.baz' must be less than five`,
559
+ },
560
+ ]
561
+ : [];
562
+ }
563
+
564
+ const config = {
565
+ tags: {
566
+ foo: {
567
+ attributes: {
568
+ bar: {
569
+ type: Object,
570
+ validate: validator,
571
+ },
572
+ blah: {
573
+ type: Object,
574
+ validate: validator,
575
+ },
576
+ },
577
+ },
578
+ },
579
+ };
580
+
581
+ const errs = validate(example, config);
582
+ expect(errs[0].error.message).toEqual(
583
+ "The value of 'bar.baz' must be less than five"
584
+ );
585
+ });
586
+
587
+ it('custom attribute type', () => {
588
+ const example = `{% foo bar={baz: 3} /%}`;
589
+
590
+ class CustomType {
591
+ validate(value, config, name) {
592
+ return value.baz < 5
593
+ ? [
594
+ {
595
+ id: 'invalid-foo-bar',
596
+ level: 'error',
597
+ message: `The value of '${name}.baz' must be less than five`,
598
+ },
599
+ ]
600
+ : [];
601
+ }
602
+ }
603
+
604
+ const config = {
605
+ tags: {
606
+ foo: {
607
+ attributes: {
608
+ bar: {
609
+ type: CustomType,
610
+ },
611
+ blah: {
612
+ type: CustomType,
613
+ },
614
+ },
615
+ },
616
+ },
617
+ };
618
+
619
+ const errs = validate(example, config);
620
+ expect(errs[0].error.message).toEqual(
621
+ "The value of 'bar.baz' must be less than five"
622
+ );
623
+ });
624
+ });
625
+
626
+ describe('parent validation', () => {
627
+ it('for deep nesting', () => {
628
+ const doc = `
629
+ {% foo %}
630
+ {% bar %}
631
+ {% baz %}
632
+ # testing
633
+ {% /baz %}
634
+ {% /bar %}
635
+ {% /foo %}
636
+ `;
637
+
638
+ const doc2 = `
639
+ {% foo %}
640
+ {% bar %}
641
+ {% /bar %}
642
+ {% /foo %}
643
+
644
+ {% bar %}
645
+ {% baz %}
646
+ # testing
647
+ {% /baz %}
648
+ {% /bar %}
649
+ `;
650
+
651
+ const config = {
652
+ tags: {
653
+ foo: {},
654
+ bar: {},
655
+ baz: {},
656
+ },
657
+ nodes: {
658
+ heading: {
659
+ ...Markdoc.nodes.heading,
660
+ validate(node, config) {
661
+ if (config.validation.parents.find((p) => p.tag === 'foo'))
662
+ return [
663
+ {
664
+ id: 'heading-in-foo',
665
+ level: 'error',
666
+ message: "Can't nest a heading in tag 'foo'",
667
+ },
668
+ ];
669
+
670
+ return [];
671
+ },
672
+ },
673
+ },
674
+ };
675
+
676
+ const errors = validate(doc, config);
677
+ expect(errors.length).toEqual(1);
678
+ expect(errors[0].error.id).toEqual('heading-in-foo');
679
+
680
+ const errors2 = validate(doc2, config);
681
+ expect(errors2.length).toEqual(0);
682
+ });
683
+ });
482
684
  });
package/src/validator.ts CHANGED
@@ -24,7 +24,8 @@ type TypeParam = NonNullable<SchemaAttribute['type']>;
24
24
  export function validateType(
25
25
  type: TypeParam,
26
26
  value: Value,
27
- config: Config
27
+ config: Config,
28
+ key: string
28
29
  ): boolean | ValidationError[] {
29
30
  if (!type) return true;
30
31
 
@@ -40,14 +41,14 @@ export function validateType(
40
41
  if (Ast.isAst(value)) return true;
41
42
 
42
43
  if (Array.isArray(type))
43
- return type.some((t) => validateType(t, value, config));
44
+ return type.some((t) => validateType(t, value, config, key));
44
45
 
45
46
  if (typeof type === 'string') type = TypeMappings[type];
46
47
 
47
48
  if (typeof type === 'function') {
48
49
  const instance: any = new type();
49
50
  if (instance.validate) {
50
- return instance.validate(value, config);
51
+ return instance.validate(value, config, key);
51
52
  }
52
53
  }
53
54
 
@@ -94,7 +95,7 @@ function validateFunction(fn: Function, config: Config): ValidationError[] {
94
95
  if (Ast.isAst(value) && !Ast.isFunction(value)) continue;
95
96
 
96
97
  if (param.type) {
97
- const valid = validateType(param.type, value, config);
98
+ const valid = validateType(param.type, value, config, key);
98
99
  if (valid === false) {
99
100
  errors.push({
100
101
  id: 'parameter-type-invalid',
@@ -121,6 +122,12 @@ function validateFunction(fn: Function, config: Config): ValidationError[] {
121
122
  return errors;
122
123
  }
123
124
 
125
+ function displayMatches(matches: any[], n: number) {
126
+ if (matches.length <= n) return JSON.stringify(matches);
127
+ const items = matches.slice(0, n).map((item) => JSON.stringify(item));
128
+ return `[${items.join(',')}, ... ${matches.length - n} more]`;
129
+ }
130
+
124
131
  export default function validator(node: Node, config: Config) {
125
132
  const schema = node.findSchema(config);
126
133
  const errors: ValidationError[] = [...(node.errors || [])];
@@ -158,6 +165,16 @@ export default function validator(node: Node, config: Config) {
158
165
  ...schema.attributes,
159
166
  };
160
167
 
168
+ for (const key of Object.keys(node.slots)) {
169
+ const slot = schema.slots?.[key];
170
+ if (!slot)
171
+ errors.push({
172
+ id: 'slot-undefined',
173
+ level: 'error',
174
+ message: `Invalid slot: '${key}'`,
175
+ });
176
+ }
177
+
161
178
  for (let [key, value] of Object.entries(node.attributes)) {
162
179
  const attrib = attributes[key];
163
180
 
@@ -201,7 +218,7 @@ export default function validator(node: Node, config: Config) {
201
218
  value = value as string;
202
219
 
203
220
  if (type) {
204
- const valid = validateType(type, value, config);
221
+ const valid = validateType(type, value, config, key);
205
222
  if (valid === false) {
206
223
  errors.push({
207
224
  id: 'attribute-type-invalid',
@@ -220,8 +237,9 @@ export default function validator(node: Node, config: Config) {
220
237
  errors.push({
221
238
  id: 'attribute-value-invalid',
222
239
  level: errorLevel || 'error',
223
- message: `Attribute '${key}' must match one of ${JSON.stringify(
224
- matches
240
+ message: `Attribute '${key}' must match one of ${displayMatches(
241
+ matches,
242
+ 8
225
243
  )}. Got '${value}' instead.`,
226
244
  });
227
245
 
@@ -231,6 +249,11 @@ export default function validator(node: Node, config: Config) {
231
249
  level: errorLevel || 'error',
232
250
  message: `Attribute '${key}' must match ${matches}. Got '${value}' instead.`,
233
251
  });
252
+
253
+ if (typeof attrib.validate === 'function') {
254
+ const attribErrors = attrib.validate(value, config, key);
255
+ if (Array.isArray(attribErrors)) errors.push(...attribErrors);
256
+ }
234
257
  }
235
258
 
236
259
  for (const [key, { required }] of Object.entries(attributes))
@@ -241,6 +264,15 @@ export default function validator(node: Node, config: Config) {
241
264
  message: `Missing required attribute: '${key}'`,
242
265
  });
243
266
 
267
+ if (schema.slots)
268
+ for (const [key, { required }] of Object.entries(schema.slots))
269
+ if (required && node.slots[key] === undefined)
270
+ errors.push({
271
+ id: 'slot-missing-required',
272
+ level: 'error',
273
+ message: `Missing required slot: '${key}'`,
274
+ });
275
+
244
276
  for (const { type } of node.children) {
245
277
  if (schema.children && type !== 'error' && !schema.children.includes(type))
246
278
  errors.push({
@@ -261,3 +293,37 @@ export default function validator(node: Node, config: Config) {
261
293
 
262
294
  return errors;
263
295
  }
296
+
297
+ export function* walkWithParents(
298
+ node: Node,
299
+ parents: Node[] = []
300
+ ): Generator<[Node, Node[]]> {
301
+ yield [node, parents];
302
+ for (const child of [...Object.values(node.slots), ...node.children])
303
+ yield* walkWithParents(child, [...parents, node]);
304
+ }
305
+
306
+ export function validateTree(content: Node, config: Config) {
307
+ const output = [...walkWithParents(content)].map(([node, parents]) => {
308
+ const { type, lines, location } = node;
309
+ const updatedConfig = {
310
+ validation: { ...config.validation, parents },
311
+ ...config,
312
+ };
313
+ const errors = validator(node, updatedConfig);
314
+
315
+ if (isPromise(errors)) {
316
+ return errors.then((e) =>
317
+ e.map((error) => ({ type, lines, location, error }))
318
+ );
319
+ }
320
+
321
+ return errors.map((error) => ({ type, lines, location, error }));
322
+ });
323
+
324
+ if (output.some(isPromise)) {
325
+ return Promise.all(output).then((o) => o.flat());
326
+ }
327
+
328
+ return output.flat();
329
+ }