-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenparser.ts
339 lines (297 loc) · 9.01 KB
/
tokenparser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import TokenType, { TokenTypeToString } from "./utils/types/tokenType.js";
import {
JsonPrimitive,
JsonKey,
JsonObject,
JsonArray,
JsonStruct,
} from "./utils/types/jsonTypes.js";
import { StackElement, TokenParserMode } from "./utils/types/stackElement.js";
import { ParsedTokenInfo } from "./utils/types/parsedTokenInfo.js";
import { ParsedElementInfo } from "./utils/types/parsedElementInfo.js";
// Parser States
const enum TokenParserState {
VALUE,
KEY,
COLON,
COMMA,
ENDED,
ERROR,
SEPARATOR,
}
function TokenParserStateToString(state: TokenParserState): string {
return ["VALUE", "KEY", "COLON", "COMMA", "ENDED", "ERROR", "SEPARATOR"][
state
];
}
export interface TokenParserOptions {
paths?: string[];
keepStack?: boolean;
separator?: string;
}
const defaultOpts: TokenParserOptions = {
paths: undefined,
keepStack: true,
separator: undefined,
};
export class TokenParserError extends Error {
constructor(message: string) {
super(message);
// Typescript is broken. This is a workaround
Object.setPrototypeOf(this, TokenParserError.prototype);
}
}
export default class TokenParser {
private readonly paths?: (string[] | undefined)[];
private readonly keepStack: boolean;
private readonly separator?: string;
private state: TokenParserState = TokenParserState.VALUE;
private mode: TokenParserMode | undefined = undefined;
private key: JsonKey = undefined;
private value: JsonStruct | undefined = undefined;
private stack: StackElement[] = [];
constructor(opts?: TokenParserOptions) {
opts = { ...defaultOpts, ...opts };
if (opts.paths) {
this.paths = opts.paths.map((path) => {
if (path === undefined || path === "$*") return undefined;
if (!path.startsWith("$"))
throw new TokenParserError(
`Invalid selector "${path}". Should start with "$".`
);
const pathParts = path.split(".").slice(1);
if (pathParts.includes(""))
throw new TokenParserError(
`Invalid selector "${path}". ".." syntax not supported.`
);
return pathParts;
});
}
this.keepStack = opts.keepStack || false;
this.separator = opts.separator;
}
private shouldEmit(): boolean {
if (!this.paths) return true;
return this.paths.some((path) => {
if (path === undefined) return true;
if (path.length !== this.stack.length) return false;
for (let i = 0; i < path.length - 1; i++) {
const selector = path[i];
const key = this.stack[i + 1].key;
if (selector === "*") continue;
if (selector !== key) return false;
}
const selector = path[path.length - 1];
if (selector === "*") return true;
return selector === this.key?.toString();
});
}
private push(): void {
this.stack.push({
key: this.key,
value: this.value as JsonStruct,
mode: this.mode,
emit: this.shouldEmit(),
});
}
private pop(): void {
const value = this.value;
let emit;
({
key: this.key,
value: this.value,
mode: this.mode,
emit,
} = this.stack.pop() as StackElement);
this.state =
this.mode !== undefined ? TokenParserState.COMMA : TokenParserState.VALUE;
this.emit(value as JsonPrimitive | JsonStruct, emit);
}
private emit(value: JsonPrimitive | JsonStruct, emit: boolean): void {
if (
!this.keepStack &&
this.value &&
this.stack.every((item) => !item.emit)
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (this.value as JsonStruct as any)[this.key as string | number];
}
if (emit) {
this.onValue({
value: value,
key: this.key,
parent: this.value,
stack: this.stack,
});
}
if (this.stack.length === 0) {
if (this.separator) {
this.state = TokenParserState.SEPARATOR;
} else if (this.separator === undefined) {
this.end();
}
// else if separator === '', expect next JSON object.
}
}
public get isEnded(): boolean {
return this.state === TokenParserState.ENDED;
}
public write({ token, value }: Omit<ParsedTokenInfo, "offset">): void {
try {
if (this.state === TokenParserState.VALUE) {
if (
token === TokenType.STRING ||
token === TokenType.NUMBER ||
token === TokenType.TRUE ||
token === TokenType.FALSE ||
token === TokenType.NULL
) {
if (this.mode === TokenParserMode.OBJECT) {
(this.value as JsonObject)[this.key as string] = value;
this.state = TokenParserState.COMMA;
} else if (this.mode === TokenParserMode.ARRAY) {
(this.value as JsonArray).push(value);
this.state = TokenParserState.COMMA;
}
this.emit(value, this.shouldEmit());
return;
}
if (token === TokenType.LEFT_BRACE) {
this.push();
if (this.mode === TokenParserMode.OBJECT) {
this.value = (this.value as JsonObject)[this.key as string] = {};
} else if (this.mode === TokenParserMode.ARRAY) {
const val = {};
(this.value as JsonArray).push(val);
this.value = val;
} else {
this.value = {};
}
this.mode = TokenParserMode.OBJECT;
this.state = TokenParserState.KEY;
this.key = undefined;
return;
}
if (token === TokenType.LEFT_BRACKET) {
this.push();
if (this.mode === TokenParserMode.OBJECT) {
this.value = (this.value as JsonObject)[this.key as string] = [];
} else if (this.mode === TokenParserMode.ARRAY) {
const val: JsonArray = [];
(this.value as JsonArray).push(val);
this.value = val;
} else {
this.value = [];
}
this.mode = TokenParserMode.ARRAY;
this.state = TokenParserState.VALUE;
this.key = 0;
return;
}
if (
this.mode === TokenParserMode.ARRAY &&
token === TokenType.RIGHT_BRACKET &&
(this.value as JsonArray).length === 0
) {
this.pop();
return;
}
}
if (this.state === TokenParserState.KEY) {
if (token === TokenType.STRING) {
this.key = value as string;
this.state = TokenParserState.COLON;
return;
}
if (
token === TokenType.RIGHT_BRACE &&
Object.keys(this.value as JsonObject).length === 0
) {
this.pop();
return;
}
}
if (this.state === TokenParserState.COLON) {
if (token === TokenType.COLON) {
this.state = TokenParserState.VALUE;
return;
}
}
if (this.state === TokenParserState.COMMA) {
if (token === TokenType.COMMA) {
if (this.mode === TokenParserMode.ARRAY) {
this.state = TokenParserState.VALUE;
(this.key as number) += 1;
return;
}
/* istanbul ignore else */
if (this.mode === TokenParserMode.OBJECT) {
this.state = TokenParserState.KEY;
return;
}
}
if (
(token === TokenType.RIGHT_BRACE &&
this.mode === TokenParserMode.OBJECT) ||
(token === TokenType.RIGHT_BRACKET &&
this.mode === TokenParserMode.ARRAY)
) {
this.pop();
return;
}
}
if (this.state === TokenParserState.SEPARATOR) {
if (token === TokenType.SEPARATOR && value === this.separator) {
this.state = TokenParserState.VALUE;
return;
}
}
throw new TokenParserError(
`Unexpected ${TokenTypeToString(token)} (${JSON.stringify(
value
)}) in state ${TokenParserStateToString(this.state)}`
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
this.error(err);
}
}
public error(err: Error): void {
if (this.state !== TokenParserState.ENDED) {
this.state = TokenParserState.ERROR;
}
this.onError(err);
}
public end(): void {
if (
(this.state !== TokenParserState.VALUE &&
this.state !== TokenParserState.SEPARATOR) ||
this.stack.length > 0
) {
this.error(
new Error(
`Parser ended in mid-parsing (state: ${TokenParserStateToString(
this.state
)}). Either not all the data was received or the data was invalid.`
)
);
} else {
this.state = TokenParserState.ENDED;
this.onEnd();
}
}
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
public onValue(parsedElementInfo: ParsedElementInfo): void {
// Override me
throw new TokenParserError(
'Can\'t emit data before the "onValue" callback has been set up.'
);
}
public onError(err: Error): void {
// Override me
throw err;
}
public onEnd(): void {
// Override me
}
}