main.d.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /**
  2. * Creates a JSON scanner on the given text.
  3. * If ignoreTrivia is set, whitespaces or comments are ignored.
  4. */
  5. export declare const createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner;
  6. export declare const enum ScanError {
  7. None = 0,
  8. UnexpectedEndOfComment = 1,
  9. UnexpectedEndOfString = 2,
  10. UnexpectedEndOfNumber = 3,
  11. InvalidUnicode = 4,
  12. InvalidEscapeCharacter = 5,
  13. InvalidCharacter = 6
  14. }
  15. export declare const enum SyntaxKind {
  16. OpenBraceToken = 1,
  17. CloseBraceToken = 2,
  18. OpenBracketToken = 3,
  19. CloseBracketToken = 4,
  20. CommaToken = 5,
  21. ColonToken = 6,
  22. NullKeyword = 7,
  23. TrueKeyword = 8,
  24. FalseKeyword = 9,
  25. StringLiteral = 10,
  26. NumericLiteral = 11,
  27. LineCommentTrivia = 12,
  28. BlockCommentTrivia = 13,
  29. LineBreakTrivia = 14,
  30. Trivia = 15,
  31. Unknown = 16,
  32. EOF = 17
  33. }
  34. /**
  35. * The scanner object, representing a JSON scanner at a position in the input string.
  36. */
  37. export interface JSONScanner {
  38. /**
  39. * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
  40. */
  41. setPosition(pos: number): void;
  42. /**
  43. * Read the next token. Returns the token code.
  44. */
  45. scan(): SyntaxKind;
  46. /**
  47. * Returns the zero-based current scan position, which is after the last read token.
  48. */
  49. getPosition(): number;
  50. /**
  51. * Returns the last read token.
  52. */
  53. getToken(): SyntaxKind;
  54. /**
  55. * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false.
  56. */
  57. getTokenValue(): string;
  58. /**
  59. * The zero-based start offset of the last read token.
  60. */
  61. getTokenOffset(): number;
  62. /**
  63. * The length of the last read token.
  64. */
  65. getTokenLength(): number;
  66. /**
  67. * The zero-based start line number of the last read token.
  68. */
  69. getTokenStartLine(): number;
  70. /**
  71. * The zero-based start character (column) of the last read token.
  72. */
  73. getTokenStartCharacter(): number;
  74. /**
  75. * An error code of the last scan.
  76. */
  77. getTokenError(): ScanError;
  78. }
  79. /**
  80. * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
  81. */
  82. export declare const getLocation: (text: string, position: number) => Location;
  83. /**
  84. * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  85. * Therefore, always check the errors list to find out if the input was valid.
  86. */
  87. export declare const parse: (text: string, errors?: ParseError[], options?: ParseOptions) => any;
  88. /**
  89. * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
  90. */
  91. export declare const parseTree: (text: string, errors?: ParseError[], options?: ParseOptions) => Node | undefined;
  92. /**
  93. * Finds the node at the given path in a JSON DOM.
  94. */
  95. export declare const findNodeAtLocation: (root: Node, path: JSONPath) => Node | undefined;
  96. /**
  97. * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
  98. */
  99. export declare const findNodeAtOffset: (root: Node, offset: number, includeRightBound?: boolean) => Node | undefined;
  100. /**
  101. * Gets the JSON path of the given JSON DOM node
  102. */
  103. export declare const getNodePath: (node: Node) => JSONPath;
  104. /**
  105. * Evaluates the JavaScript object of the given JSON DOM node
  106. */
  107. export declare const getNodeValue: (node: Node) => any;
  108. /**
  109. * Parses the given text and invokes the visitor functions for each object, array and literal reached.
  110. */
  111. export declare const visit: (text: string, visitor: JSONVisitor, options?: ParseOptions) => any;
  112. /**
  113. * Takes JSON with JavaScript-style comments and remove
  114. * them. Optionally replaces every none-newline character
  115. * of comments with a replaceCharacter
  116. */
  117. export declare const stripComments: (text: string, replaceCh?: string) => string;
  118. export interface ParseError {
  119. error: ParseErrorCode;
  120. offset: number;
  121. length: number;
  122. }
  123. export declare const enum ParseErrorCode {
  124. InvalidSymbol = 1,
  125. InvalidNumberFormat = 2,
  126. PropertyNameExpected = 3,
  127. ValueExpected = 4,
  128. ColonExpected = 5,
  129. CommaExpected = 6,
  130. CloseBraceExpected = 7,
  131. CloseBracketExpected = 8,
  132. EndOfFileExpected = 9,
  133. InvalidCommentToken = 10,
  134. UnexpectedEndOfComment = 11,
  135. UnexpectedEndOfString = 12,
  136. UnexpectedEndOfNumber = 13,
  137. InvalidUnicode = 14,
  138. InvalidEscapeCharacter = 15,
  139. InvalidCharacter = 16
  140. }
  141. export declare function printParseErrorCode(code: ParseErrorCode): "InvalidSymbol" | "InvalidNumberFormat" | "PropertyNameExpected" | "ValueExpected" | "ColonExpected" | "CommaExpected" | "CloseBraceExpected" | "CloseBracketExpected" | "EndOfFileExpected" | "InvalidCommentToken" | "UnexpectedEndOfComment" | "UnexpectedEndOfString" | "UnexpectedEndOfNumber" | "InvalidUnicode" | "InvalidEscapeCharacter" | "InvalidCharacter" | "<unknown ParseErrorCode>";
  142. export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';
  143. export interface Node {
  144. readonly type: NodeType;
  145. readonly value?: any;
  146. readonly offset: number;
  147. readonly length: number;
  148. readonly colonOffset?: number;
  149. readonly parent?: Node;
  150. readonly children?: Node[];
  151. }
  152. /**
  153. * A {@linkcode JSONPath} segment. Either a string representing an object property name
  154. * or a number (starting at 0) for array indices.
  155. */
  156. export type Segment = string | number;
  157. export type JSONPath = Segment[];
  158. export interface Location {
  159. /**
  160. * The previous property key or literal value (string, number, boolean or null) or undefined.
  161. */
  162. previousNode?: Node;
  163. /**
  164. * The path describing the location in the JSON document. The path consists of a sequence of strings
  165. * representing an object property or numbers for array indices.
  166. */
  167. path: JSONPath;
  168. /**
  169. * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
  170. * '*' will match a single segment of any property name or index.
  171. * '**' will match a sequence of segments of any property name or index, or no segment.
  172. */
  173. matches: (patterns: JSONPath) => boolean;
  174. /**
  175. * If set, the location's offset is at a property key.
  176. */
  177. isAtPropertyKey: boolean;
  178. }
  179. export interface ParseOptions {
  180. disallowComments?: boolean;
  181. allowTrailingComma?: boolean;
  182. allowEmptyContent?: boolean;
  183. }
  184. /**
  185. * Visitor called by {@linkcode visit} when parsing JSON.
  186. *
  187. * The visitor functions have the following common parameters:
  188. * - `offset`: Global offset within the JSON document, starting at 0
  189. * - `startLine`: Line number, starting at 0
  190. * - `startCharacter`: Start character (column) within the current line, starting at 0
  191. *
  192. * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the
  193. * current `JSONPath` within the document.
  194. */
  195. export interface JSONVisitor {
  196. /**
  197. * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
  198. * When `false` is returned, the object properties will not be visited.
  199. */
  200. onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => boolean | void;
  201. /**
  202. * Invoked when a property is encountered. The offset and length represent the location of the property name.
  203. * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the
  204. * property name yet.
  205. */
  206. onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
  207. /**
  208. * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
  209. */
  210. onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
  211. /**
  212. * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
  213. * When `false` is returned, the array items will not be visited.
  214. */
  215. onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => boolean | void;
  216. /**
  217. * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
  218. */
  219. onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
  220. /**
  221. * Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
  222. */
  223. onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
  224. /**
  225. * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
  226. */
  227. onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void;
  228. /**
  229. * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
  230. */
  231. onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
  232. /**
  233. * Invoked on an error.
  234. */
  235. onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;
  236. }
  237. /**
  238. * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation.
  239. * It consist of one or more edits describing insertions, replacements or removals of text segments.
  240. * * The offsets of the edits refer to the original state of the document.
  241. * * No two edits change or remove the same range of text in the original document.
  242. * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace.
  243. * * The order in the array defines which edit is applied first.
  244. * To apply an edit result use {@linkcode applyEdits}.
  245. * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data.
  246. */
  247. export type EditResult = Edit[];
  248. /**
  249. * Represents a text modification
  250. */
  251. export interface Edit {
  252. /**
  253. * The start offset of the modification.
  254. */
  255. offset: number;
  256. /**
  257. * The length of the modification. Must not be negative. Empty length represents an *insert*.
  258. */
  259. length: number;
  260. /**
  261. * The new content. Empty content represents a *remove*.
  262. */
  263. content: string;
  264. }
  265. /**
  266. * A text range in the document
  267. */
  268. export interface Range {
  269. /**
  270. * The start offset of the range.
  271. */
  272. offset: number;
  273. /**
  274. * The length of the range. Must not be negative.
  275. */
  276. length: number;
  277. }
  278. /**
  279. * Options used by {@linkcode format} when computing the formatting edit operations
  280. */
  281. export interface FormattingOptions {
  282. /**
  283. * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent.
  284. */
  285. tabSize?: number;
  286. /**
  287. * Is indentation based on spaces?
  288. */
  289. insertSpaces?: boolean;
  290. /**
  291. * The default 'end of line' character. If not set, '\n' is used as default.
  292. */
  293. eol?: string;
  294. /**
  295. * If set, will add a new line at the end of the document.
  296. */
  297. insertFinalNewline?: boolean;
  298. /**
  299. * If true, will keep line positions as is in the formatting
  300. */
  301. keepLines?: boolean;
  302. }
  303. /**
  304. * Computes the edit operations needed to format a JSON document.
  305. *
  306. * @param documentText The input text
  307. * @param range The range to format or `undefined` to format the full content
  308. * @param options The formatting options
  309. * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.
  310. * To apply the edit operations to the input, use {@linkcode applyEdits}.
  311. */
  312. export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): EditResult;
  313. /**
  314. * Options used by {@linkcode modify} when computing the modification edit operations
  315. */
  316. export interface ModificationOptions {
  317. /**
  318. * Formatting options. If undefined, the newly inserted code will be inserted unformatted.
  319. */
  320. formattingOptions?: FormattingOptions;
  321. /**
  322. * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then
  323. * {@linkcode modify} will insert a new item at that location instead of overwriting its contents.
  324. */
  325. isArrayInsertion?: boolean;
  326. /**
  327. * Optional function to define the insertion index given an existing list of properties.
  328. */
  329. getInsertionIndex?: (properties: string[]) => number;
  330. }
  331. /**
  332. * Computes the edit operations needed to modify a value in the JSON document.
  333. *
  334. * @param documentText The input text
  335. * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
  336. * If the path points to an non-existing property or item, it will be created.
  337. * @param value The new value for the specified property or item. If the value is undefined,
  338. * the property or item will be removed.
  339. * @param options Options
  340. * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
  341. * To apply the edit operations to the input, use {@linkcode applyEdits}.
  342. */
  343. export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;
  344. /**
  345. * Applies edits to an input string.
  346. * @param text The input text
  347. * @param edits Edit operations following the format described in {@linkcode EditResult}.
  348. * @returns The text with the applied edits.
  349. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
  350. */
  351. export declare function applyEdits(text: string, edits: EditResult): string;