-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonCommentWriterBase.ts
255 lines (237 loc) · 11.3 KB
/
jsonCommentWriterBase.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
import * as wrap from 'word-wrap';
import {
IJSONComment, IJSONCommentConfiguration, IReplacer
} from './types';
/**
* Base writer to add comments to stringified JSON.
* JSON stringify implementation is based on the following code:
* https://github.com/douglascrockford/JSON-js/blob/2a76286e00cdc1e98fbc9e9ec6589563a3a4c3bb/json2.js
*
* @param CommentDataNodeType Subclasses should use this type of node to track current node and related data.
*/
export abstract class JSONCommentWriterBase<CommentDataNodeType> {
private static readonly defaultConfiguration: IJSONCommentConfiguration = {
emptyLineBeforeComments: true,
spaceAroundCommentSymbol: true,
styledBlockComment: true,
maxLineLength: 80
};
private readonly configuration: IJSONCommentConfiguration;
private indent: string = '';
private replacer: IReplacer | undefined;
private path: (string | number)[] = [];
/**
* Construct a new JSONCommentWriter.
* @param configuration Styling configuration for comments.
*/
public constructor(configuration?: Partial<IJSONCommentConfiguration>) {
this.configuration = { ...JSONCommentWriterBase.defaultConfiguration, ...configuration };
}
/**
* Convert the given object to a JSON string with comments specified eariler.
* @param object The root object to convert to JSON string.
* @param replacer A function that alters the behavior of the stringification process,
* or an array of String and Number objects that serve as a whitelist for
* selecting/filtering the properties of the value object to be included in the JSON string.
*
* If this value is null or not provided,
* all properties of the object are included in the resulting JSON string.
* @param space A String or Number object that's used to insert white space into
* the output JSON string for readability purposes.
*
* If this is a Number, it indicates the number of space characters to use as white space;
* this number is capped at 10 (if it is greater, the value is just 10).
* Values less than 1 indicate that no space should be used.
*
* If this is a String, the string is used as white space.
* If this parameter is not provided (or is null), no white space is used.
*
* @returns The JSON string, or `undefined` if object is `undefined`.
*/
public stringify(object: any, replacer?: IReplacer, space?: number | string): string | undefined {
this.indent = '';
if (typeof space === 'number') {
for (let i: number = 0; i < space; i++) {
this.indent += ' ';
}
} else if (typeof space === 'string') {
this.indent = space;
}
this.replacer = replacer;
if (replacer && typeof replacer !== 'function' && !Array.isArray(replacer)) {
throw new Error('Argument `replacer` is expected to be a function or an array');
}
this.path = [];
const { comments: parts, childJSON, lineEndComment } = this.getChildJSON({ '': object }, '', '', this.root);
if (childJSON === undefined) {
return undefined;
}
parts.push(childJSON + (lineEndComment || ''));
return parts.join('\n');
}
protected abstract get root(): Readonly<CommentDataNodeType>;
protected abstract nextNode(currentNode: Readonly<CommentDataNodeType>, key: string | number)
: Readonly<CommentDataNodeType> | undefined;
protected abstract getComments(currentNode: Readonly<CommentDataNodeType>): IJSONComment[];
private renderComment(gap: string, path: (string | number)[], comment: IJSONComment): string | undefined {
if (typeof comment === 'string') {
comment = { type: 'block', content: comment };
}
let content: string | undefined = typeof comment.content === 'function' ? comment.content(path.slice(1)) : comment.content;
if (content === undefined) {
return undefined;
}
// If there's indent or is root level
if (gap || this.path.length === 1) {
if (this.configuration.maxLineLength > 0) {
content = wrap(content, { width: this.configuration.maxLineLength, indent: '', trim: true });
}
if (comment.type === 'block') {
content = content.replace(/\*\//g, '*\/');
if (this.configuration.styledBlockComment) {
return `/**
${gap} * ${content.replace(/\n/g, `\n${gap} * `)}
${gap} */`;
} else if (this.configuration.spaceAroundCommentSymbol) {
return `/* ${content.replace(/\n/g, `\n${gap}`)} */`;
} else {
return `/*${content.replace(/\n/g, `\n${gap}`)}*/`;
}
} else {
if (comment.type === 'end' && content.includes('\n')) {
throw new Error('Comment of type `end` is expected to be single-line');
}
if (this.configuration.spaceAroundCommentSymbol) {
return `// ${content.replace(/\n/g, `\n${gap}// `)}`;
} else {
return `//${content.replace(/\n/g, `\n${gap}//`)}`;
}
}
} else {
if (comment.type === 'block') {
if (content.includes('\n')) {
throw new Error('Comment is expected to be single-line when space is 0');
}
content = content.replace(/\*\//g, '*\/');
if (this.configuration.spaceAroundCommentSymbol) {
return `/* ${content} */`;
} else {
return `/*${content}*/`;
}
} else {
return undefined;
}
}
}
private getChildJSON(value: any, nextKey: string | number, gap: string, node: CommentDataNodeType | undefined)
: { comments: string[], childJSON: string | undefined, lineEndComment: string | undefined } {
const nextNode: CommentDataNodeType | undefined = node && this.nextNode(node, nextKey);
const parts: string[] = [];
let lineEndComment: string | undefined;
this.path.push(nextKey);
if (nextNode) {
for (const comment of this.getComments(nextNode)) {
if (typeof comment === 'object' && comment.type === 'end' && lineEndComment !== undefined) {
throw new Error('Comment of type `end` is expected to be unique for each field');
}
const commentString: string | undefined = this.renderComment(gap, this.path, comment);
if (typeof comment === 'object' && comment.type === 'end') {
lineEndComment = commentString;
} else if (commentString !== undefined) {
parts.push(commentString);
}
}
}
const childJSON: string | undefined = this.objToJSON(nextKey, value, gap, nextNode);
this.path.pop();
if (lineEndComment !== undefined && this.configuration.spaceAroundCommentSymbol) {
lineEndComment = ' ' + lineEndComment;
}
return { comments: parts, childJSON, lineEndComment };
}
/**
* Convert holder[key] to JSON.
* @param key The key of the item to be serialized.
* Note that it accepts number to allow for JS engine optimization.
* @param holder The object holding the item.
* @param gap Accumulated indent.
* @param nodes Selecter tree nodes matched for the item
* @returns JSON representation of the item.
* `undefined` if the item is `undefined`.
*/
// tslint:disable-next-line
private objToJSON(key: string | number, holder: any, gap: string, node: CommentDataNodeType | undefined): string | undefined {
let value: any = holder[key];
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
if (typeof this.replacer === 'function') {
value = this.replacer.call(holder, key, value);
}
if (typeof value === 'object') {
if (!value) {
return 'null';
}
const currGap: string = gap + this.indent;
const lineBreakCurrGap: string = currGap ? '\n' + currGap : '';
const lineEndComments: { [index: number]: string } = {};
const partial: string[] = [];
const fnPartialToLine: (value: string, i: number) => string =
(p, i) => `${p}${i < partial.length - 1 ? ',' : ''}${lineEndComments[i] || ''}`;
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]';
}
for (let i: number = 0; i < value.length; i++) {
const { comments: parts, childJSON, lineEndComment } = this.getChildJSON(value, i, currGap, node);
if (lineEndComment !== undefined) {
lineEndComments[i] = lineEndComment;
}
parts.push(childJSON || 'null');
const currentItemWithComments: string = parts.join(lineBreakCurrGap);
if (this.configuration.emptyLineBeforeComments && i > 0 && parts.length > 1 && currGap) {
// Not the first item in array && has comment && spaces != 0
// Add a empty line
partial.push(lineBreakCurrGap + currentItemWithComments);
} else {
partial.push(currGap + currentItemWithComments);
}
}
return currGap
? `[
${partial.map(fnPartialToLine).join('\n')}
${gap}]`
: `[${partial.join(',')}]`;
} else {
const keys: (string | number)[] = Array.isArray(this.replacer) ? this.replacer : Object.keys(value);
if (keys.length === 0) {
return '{}';
}
for (const k of keys) {
const { comments: parts, childJSON, lineEndComment } = this.getChildJSON(value, k, currGap, node);
if (childJSON) {
if (lineEndComment !== undefined) {
lineEndComments[partial.length] = lineEndComment;
}
parts.push(JSON.stringify(k) + (currGap ? ': ' : ':') + childJSON);
const currentKVPairWithComments: string = parts.join(lineBreakCurrGap);
if (this.configuration.emptyLineBeforeComments && partial.length > 0 && parts.length > 1 && currGap) {
// Not the first key-value pair in object && has comment && spaces != 0
// Add a empty line
partial.push(lineBreakCurrGap + currentKVPairWithComments);
} else {
partial.push(currGap + currentKVPairWithComments);
}
}
}
return currGap
? `{
${partial.map(fnPartialToLine).join('\n')}
${gap}}`
: `{${partial.join(',')}}`;
}
} else {
return JSON.stringify(value);
}
}
}