|
5 | 5 | * @typedef {import('vfile').VFileValue} VFileValue |
6 | 6 | */ |
7 | 7 |
|
| 8 | +/** |
| 9 | + * @typedef NodeLike |
| 10 | + * @property {string} type |
| 11 | + * @property {PositionLike | null | undefined} [position] |
| 12 | + * |
| 13 | + * @typedef PositionLike |
| 14 | + * @property {PointLike | null | undefined} [start] |
| 15 | + * @property {PointLike | null | undefined} [end] |
| 16 | + * |
| 17 | + * @typedef PointLike |
| 18 | + * @property {number | null | undefined} [line] |
| 19 | + * @property {number | null | undefined} [column] |
| 20 | + * @property {number | null | undefined} [offset] |
| 21 | + */ |
| 22 | + |
8 | 23 | import {location} from 'vfile-location' |
9 | 24 |
|
10 | 25 | const search = /\r?\n|\r/g |
11 | 26 |
|
12 | 27 | /** |
13 | 28 | * Get the source of a node or at a position. |
14 | 29 | * |
15 | | - * @param {Node|Position} value |
| 30 | + * @param {Node | NodeLike | Position | PositionLike | null | undefined} value |
16 | 31 | * Value to get. |
17 | | - * @param {VFile|VFileValue} file |
| 32 | + * @param {VFile | VFileValue} file |
18 | 33 | * File in which `value` exists. |
19 | | - * @returns {string|null} |
| 34 | + * @returns {string | null} |
20 | 35 | * Source of `value` in `doc`, if available. |
21 | 36 | */ |
22 | 37 | export function source(value, file) { |
23 | 38 | const doc = String(file) |
24 | 39 | const loc = location(file) |
25 | | - /** @type {import('unist').Position} */ |
26 | | - // @ts-expect-error Looks like a node. |
27 | | - const position = (value && value.position) || value || {} |
| 40 | + const position = |
| 41 | + value && typeof value === 'object' |
| 42 | + ? 'type' in value |
| 43 | + ? value.position |
| 44 | + : value |
| 45 | + : undefined |
| 46 | + |
| 47 | + if (!position || !position.start || !position.end) { |
| 48 | + return null |
| 49 | + } |
| 50 | + |
| 51 | + // @ts-expect-error: To do: add `PointLike` to `vfile-location` |
28 | 52 | const endOffset = loc.toOffset(position.end) |
| 53 | + // @ts-expect-error: To do: add `PointLike` to `vfile-location` |
29 | 54 | let startOffset = loc.toOffset(position.start) |
30 | 55 |
|
31 | 56 | if (endOffset === -1 || startOffset === -1) { |
|
0 commit comments