|
| 1 | +import type { DependencyInfo, Extractor } from '#types/extractor' |
| 2 | +import type { Node } from 'jsonc-parser' |
| 3 | +import type { TextDocument } from 'vscode' |
| 4 | +import { createCachedParse } from '#utils/data' |
| 5 | +import { findNodeAtLocation, findNodeAtOffset, parseTree } from 'jsonc-parser' |
| 6 | +import { Range } from 'vscode' |
| 7 | + |
| 8 | +const DEP_SECTIONS = [ |
| 9 | + 'dependencies', |
| 10 | + 'devDependencies', |
| 11 | + 'peerDependencies', |
| 12 | + 'optionalDependencies', |
| 13 | +] |
| 14 | + |
| 15 | +export class JsonExtractor implements Extractor<Node> { |
| 16 | + parse = createCachedParse(parseTree) |
| 17 | + |
| 18 | + getNodeRange(doc: TextDocument, node: Node) { |
| 19 | + const start = doc.positionAt(node.offset + 1) |
| 20 | + const end = doc.positionAt( |
| 21 | + node.offset + node.length - 1, |
| 22 | + ) |
| 23 | + |
| 24 | + return new Range(start, end) |
| 25 | + } |
| 26 | + |
| 27 | + inDependencySection(root: Node, node: Node) { |
| 28 | + return DEP_SECTIONS.some((section) => { |
| 29 | + const dep = findNodeAtLocation(root, [section]) |
| 30 | + if (!dep || !dep.parent) |
| 31 | + return false |
| 32 | + |
| 33 | + const { offset, length } = dep.parent.children![1] |
| 34 | + |
| 35 | + return node.offset > offset && node.offset < offset + length |
| 36 | + }) |
| 37 | + } |
| 38 | + |
| 39 | + getDependenciesInfo(root: Node) { |
| 40 | + const info: DependencyInfo<Node>[] = [] |
| 41 | + |
| 42 | + DEP_SECTIONS.forEach((section) => { |
| 43 | + const node = findNodeAtLocation(root, [section]) |
| 44 | + if (!node || !node.children) |
| 45 | + return |
| 46 | + |
| 47 | + for (const dep of node.children) { |
| 48 | + const keyNode = dep.children?.[0] |
| 49 | + if (!keyNode || typeof keyNode.value !== 'string') |
| 50 | + continue |
| 51 | + |
| 52 | + info.push({ |
| 53 | + node: keyNode, |
| 54 | + name: keyNode.value, |
| 55 | + version: '', |
| 56 | + }) |
| 57 | + } |
| 58 | + }) |
| 59 | + |
| 60 | + return info |
| 61 | + } |
| 62 | + |
| 63 | + getDependencyInfoByOffset(root: Node, offset: number) { |
| 64 | + const node = findNodeAtOffset(root, offset) |
| 65 | + if (!node || node.type !== 'string' || !this.inDependencySection(root, node)) |
| 66 | + return |
| 67 | + |
| 68 | + return { |
| 69 | + node, |
| 70 | + name: node.parent!.children![0].value as string, |
| 71 | + version: node.value as string, |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments