UNPKG

14.3 kBTypeScriptView Raw
1/**
2 * Creates a JSON scanner on the given text.
3 * If ignoreTrivia is set, whitespaces or comments are ignored.
4 */
5export declare const createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner;
6export 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}
15export 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 */
37export 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 */
82export 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 */
87export 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 */
91export 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 */
95export 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 */
99export declare const findNodeAtOffset: (root: Node, offset: number, includeRightBound?: boolean) => Node | undefined;
100/**
101 * Gets the JSON path of the given JSON DOM node
102 */
103export declare const getNodePath: (node: Node) => JSONPath;
104/**
105 * Evaluates the JavaScript object of the given JSON DOM node
106 */
107export 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 */
111export 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 */
117export declare const stripComments: (text: string, replaceCh?: string) => string;
118export interface ParseError {
119 error: ParseErrorCode;
120 offset: number;
121 length: number;
122}
123export 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}
141export declare function printParseErrorCode(code: ParseErrorCode): "InvalidSymbol" | "InvalidNumberFormat" | "PropertyNameExpected" | "ValueExpected" | "ColonExpected" | "CommaExpected" | "CloseBraceExpected" | "CloseBracketExpected" | "EndOfFileExpected" | "InvalidCommentToken" | "UnexpectedEndOfComment" | "UnexpectedEndOfString" | "UnexpectedEndOfNumber" | "InvalidUnicode" | "InvalidEscapeCharacter" | "InvalidCharacter" | "<unknown ParseErrorCode>";
142export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';
143export 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 */
156export type Segment = string | number;
157export type JSONPath = Segment[];
158export 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}
179export 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 */
195export 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 */
199 onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
200 /**
201 * Invoked when a property is encountered. The offset and length represent the location of the property name.
202 * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the
203 * property name yet.
204 */
205 onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
206 /**
207 * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
208 */
209 onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
210 /**
211 * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
212 */
213 onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
214 /**
215 * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
216 */
217 onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
218 /**
219 * Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
220 */
221 onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
222 /**
223 * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
224 */
225 onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void;
226 /**
227 * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
228 */
229 onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
230 /**
231 * Invoked on an error.
232 */
233 onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;
234}
235/**
236 * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation.
237 * It consist of one or more edits describing insertions, replacements or removals of text segments.
238 * * The offsets of the edits refer to the original state of the document.
239 * * No two edits change or remove the same range of text in the original document.
240 * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace.
241 * * The order in the array defines which edit is applied first.
242 * To apply an edit result use {@linkcode applyEdits}.
243 * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data.
244 */
245export type EditResult = Edit[];
246/**
247 * Represents a text modification
248 */
249export interface Edit {
250 /**
251 * The start offset of the modification.
252 */
253 offset: number;
254 /**
255 * The length of the modification. Must not be negative. Empty length represents an *insert*.
256 */
257 length: number;
258 /**
259 * The new content. Empty content represents a *remove*.
260 */
261 content: string;
262}
263/**
264 * A text range in the document
265*/
266export interface Range {
267 /**
268 * The start offset of the range.
269 */
270 offset: number;
271 /**
272 * The length of the range. Must not be negative.
273 */
274 length: number;
275}
276/**
277 * Options used by {@linkcode format} when computing the formatting edit operations
278 */
279export interface FormattingOptions {
280 /**
281 * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent.
282 */
283 tabSize?: number;
284 /**
285 * Is indentation based on spaces?
286 */
287 insertSpaces?: boolean;
288 /**
289 * The default 'end of line' character. If not set, '\n' is used as default.
290 */
291 eol?: string;
292 /**
293 * If set, will add a new line at the end of the document.
294 */
295 insertFinalNewline?: boolean;
296 /**
297 * If true, will keep line positions as is in the formatting
298 */
299 keepLines?: boolean;
300}
301/**
302 * Computes the edit operations needed to format a JSON document.
303 *
304 * @param documentText The input text
305 * @param range The range to format or `undefined` to format the full content
306 * @param options The formatting options
307 * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.
308 * To apply the edit operations to the input, use {@linkcode applyEdits}.
309 */
310export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): EditResult;
311/**
312 * Options used by {@linkcode modify} when computing the modification edit operations
313 */
314export interface ModificationOptions {
315 /**
316 * Formatting options. If undefined, the newly inserted code will be inserted unformatted.
317 */
318 formattingOptions?: FormattingOptions;
319 /**
320 * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then
321 * {@linkcode modify} will insert a new item at that location instead of overwriting its contents.
322 */
323 isArrayInsertion?: boolean;
324 /**
325 * Optional function to define the insertion index given an existing list of properties.
326 */
327 getInsertionIndex?: (properties: string[]) => number;
328}
329/**
330 * Computes the edit operations needed to modify a value in the JSON document.
331 *
332 * @param documentText The input text
333 * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
334 * If the path points to an non-existing property or item, it will be created.
335 * @param value The new value for the specified property or item. If the value is undefined,
336 * the property or item will be removed.
337 * @param options Options
338 * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
339 * To apply the edit operations to the input, use {@linkcode applyEdits}.
340 */
341export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;
342/**
343 * Applies edits to an input string.
344 * @param text The input text
345 * @param edits Edit operations following the format described in {@linkcode EditResult}.
346 * @returns The text with the applied edits.
347 * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
348 */
349export declare function applyEdits(text: string, edits: EditResult): string;