@markdoc/markdoc 0.5.6 → 0.5.7

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/validator.ts CHANGED
@@ -3,10 +3,12 @@ import Ast from './ast/index';
3
3
  import { isPromise } from './utils';
4
4
 
5
5
  import type {
6
+ Location,
6
7
  Node,
7
8
  Function,
8
9
  Config,
9
10
  SchemaAttribute,
11
+ ValidateError,
10
12
  ValidationError,
11
13
  Value,
12
14
  } from './types';
@@ -303,9 +305,35 @@ export function* walkWithParents(
303
305
  yield* walkWithParents(child, [...parents, node]);
304
306
  }
305
307
 
308
+ function hasValidLocation(
309
+ error: ValidationError
310
+ ): error is ValidationError & { location: Location } {
311
+ const loc = error.location;
312
+ return (
313
+ loc != null &&
314
+ typeof loc.start?.line === 'number' &&
315
+ typeof loc.end?.line === 'number' &&
316
+ (loc.file === undefined || typeof loc.file === 'string')
317
+ );
318
+ }
319
+
320
+ function toValidateError(
321
+ node: { type: string; lines: number[]; location?: Location },
322
+ error: ValidationError
323
+ ): ValidateError {
324
+ if (hasValidLocation(error)) {
325
+ return {
326
+ type: node.type,
327
+ lines: [error.location.start.line, error.location.end.line],
328
+ location: { file: node.location?.file, ...error.location },
329
+ error,
330
+ };
331
+ }
332
+ return { type: node.type, lines: node.lines, location: node.location, error };
333
+ }
334
+
306
335
  export function validateTree(content: Node, config: Config) {
307
336
  const output = [...walkWithParents(content)].map(([node, parents]) => {
308
- const { type, lines, location } = node;
309
337
  const updatedConfig = {
310
338
  ...config,
311
339
  validation: { ...config.validation, parents },
@@ -313,12 +341,10 @@ export function validateTree(content: Node, config: Config) {
313
341
  const errors = validator(node, updatedConfig);
314
342
 
315
343
  if (isPromise(errors)) {
316
- return errors.then((e) =>
317
- e.map((error) => ({ type, lines, location, error }))
318
- );
344
+ return errors.then((e) => e.map((error) => toValidateError(node, error)));
319
345
  }
320
346
 
321
- return errors.map((error) => ({ type, lines, location, error }));
347
+ return errors.map((error) => toValidateError(node, error));
322
348
  });
323
349
 
324
350
  if (output.some(isPromise)) {