-
-
Notifications
You must be signed in to change notification settings - Fork 269
/
styles.ts
378 lines (352 loc) · 11.5 KB
/
styles.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import type { ReactNode } from 'react'
import type { Format } from './format.js'
import reactElementToJsxString from './react-element-to-jsx-string.js'
// can't use buf.toString('ascii') because that unmasks high bytes
const bufToAscii = (buf: Buffer) =>
buf
.map(c => (c <= 0x20 || c >= 0x7f ? '.'.charCodeAt(0) : c))
.toString()
export type StyleType = 'pretty' | 'js' | 'tight'
/**
* A set of functions defining how various sorts of things get converted
* into strings.
*/
export interface Style {
/** a function, optionally with a class name */
fn: (fn: Function | ((...a: any[]) => any), cls: string) => string
/** an empty `Set` */
setEmpty: (cls: string) => string
/** start of a `Set` */
setHead: (cls: string) => string
/** end of a `Set` */
setTail: (indent: string) => string
/** separator between entries in a `Set` */
setEntrySep: () => string
/** an empty `Map` */
mapEmpty: (cls: string) => string
/** start of a `Map` */
mapHead: (cls: string) => string
/** end of a `Map` */
mapTail: (indent: string) => string
/** start of a key in a `Map` */
mapKeyStart: () => string
/** separator between key and value in a `Map` */
mapKeyValSep: () => string
/** separator between entries in a `Map` */
mapEntrySep: () => string
/** what to print when we encounter a circular reference */
circular: (node: Format) => string
/** how to print node identifiers for circular references */
nodeId: (id: number) => string
/** an empty `Error` object */
errorEmpty: (er: Error, cls: string) => string
/** start of an `Error` object */
errorHead: (
er: (Error | { name?: string; message?: string }) & {
generatedMessage?: string
},
cls: string,
) => string
/** end of an `Error` object */
errorTail: (indent: string) => string
/** empty JavaScript object */
pojoEmpty: (cls: string) => string
/** start of a JavaScript object */
pojoHead: (cls: string) => string
/** end of a JavaScript object */
pojoTail: (indent: string) => string
/** separator between key and value in a JavaScript object */
pojoKeyValSep: () => string
/** separator between entries in a JavaScript object */
pojoEntrySep: () => string
/** an empty `Array` */
arrayEmpty: (cls: string) => string
/** start of an `Array` */
arrayHead: (cls: string) => string
/** end of an `Array` */
arrayTail: (indent: string) => string
/** separator between entries in an `Array` */
arrayEntrySep: () => string
/**
* how many bytes of a `Buffer` to show per line. can be overridden by
* the Format constructor options.
* */
bufferChunkSize: number
/** an empty `Buffer` */
bufferEmpty: () => string
/** start of a short `Buffer` */
bufferStart: () => string
/** contents of a short `Buffer` */
bufferBody: (buf: Buffer) => string
/** end of a short `Buffer` */
bufferEnd: (buf: Buffer) => string
/** start of a long `Buffer` */
bufferHead: () => string
// show line numbers as offset 0x0000 through 0xffff as zero-padded hex
// this will wrap around if you have more than 64kb buffer, but that's
// (a) highly unusual for the use cases tcompare works in, and (b) fine.
/** line numbers to print for lines in a long `Buffer` */
bufferKey: (i: number) => string
/** line of bytes in a long `Buffer` */
bufferLine: (buf: Buffer, chunkSize: number) => string
/** separator between lines in a long `Buffer` */
bufferLineSep: () => string
/** end of a long `Buffer` */
bufferTail: (indent: string) => string
/** separator between line number and contents of a long `Buffer` */
bufferKeySep: () => string
/** a react element */
reactElement?: (node: ReactNode) => string
/** an empty string */
stringEmpty: () => string
/** a string that fits on one line */
stringOneLine: (str: string) => string
/** start of a long string */
stringHead: () => string
/** separator between lines of a long string */
stringLineSep: () => string
/** each line of a long string */
stringLine: (str: string) => string
/** end of a long string */
stringTail: (indent: string) => string
/** printing symbols */
symbol: (method: string, key: string) => string
/** indicator as to whether this style is suitable for use in diffs */
diffable: boolean
/** beginning of a thing being printed */
start: (indent: string, key: string, sep: string) => string
}
/**
* The default style, suitable for diffs, and optimized for human
* readability.
*/
const pretty: Style = {
fn: (fn, cls) => {
const name = fn.name
const args = fn
.toString?.()
.split('{')[0]
?.split('=>')[0]
?.replace(/[\n\r\s\t]+/g, '')
.replace(/^[^\(]*\( */, '')
.replace(/ *\).*/g, '')
.split(',')
.join(', ')
.trim()
return `${cls} ${name || ''}(${args})`
},
setEmpty: cls => `${cls} \{\}`,
setHead: cls => `${cls} \{\n`,
setTail: indent => `${indent}}`,
setEntrySep: () => ',\n',
mapEmpty: cls => `${cls} \{\}`,
mapHead: cls => `${cls} \{\n`,
mapTail: indent => `${indent}}`,
mapKeyStart: () => '',
mapKeyValSep: () => ' => ',
mapEntrySep: () => ',\n',
circular: node => `<*ref_${node.id}>`,
nodeId: id => `&ref_${id} `,
errorEmpty: er =>
!(er instanceof Error) ?
`${(er as Error).name || '(no name)'}: ${
(er as Error).message || '(no message)'
}`
: `${er.toString()}`,
errorHead: (er, cls) => {
// assertion errors sometimes generate WACKY stuff
return (
cls === 'AssertionError' && er.generatedMessage ?
er.name + ' {\n'
: !(er instanceof Error) ?
`${(er as Error).name || '(no name)'}: ${
(er as Error).message || '(no message)'
} \{\n`
: `${er.toString()} \{\n`
)
},
errorTail: indent => `${indent}}`,
pojoEmpty: cls => `${cls} \{\}`,
pojoHead: cls => `${cls} \{\n`,
pojoTail: indent => `${indent}}`,
pojoKeyValSep: () => ': ',
pojoEntrySep: () => ',\n',
arrayEmpty: cls => `${cls} []`,
arrayHead: cls => `${cls} [\n`,
arrayTail: indent => `${indent}]`,
arrayEntrySep: () => ',\n',
bufferChunkSize: 32,
bufferEmpty: () => 'Buffer <>',
bufferStart: () => 'Buffer <',
bufferBody: buf =>
buf
.toString('hex')
.replace(/(....)/g, '$1 ')
.trim(),
bufferEnd: buf => ' ' + bufToAscii(buf) + '>',
bufferHead: () => 'Buffer <\n',
// show line numbers as offset 0x0000 through 0xffff as zero-padded hex
// this will wrap around if you have more than 64kb buffer, but that's
// (a) highly unusual for the use cases tcompare works in, and (b) fine.
bufferKey: i => (i + 0x10000).toString(16).slice(-4),
bufferLine: (buf, chunkSize) => {
const hex = buf
.toString('hex')
.replace(/(....)/g, '$1 ')
.trim()
// double for hex, then add 25% for the spaces between every 4 hexits
const l = Math.ceil(chunkSize * 2 * 1.25)
const pad = ' '.repeat(l - hex.length + 1)
return hex + pad + bufToAscii(buf)
},
bufferLineSep: () => '\n',
bufferTail: indent => `\n${indent}>`,
bufferKeySep: () => ': ',
reactElement: (el: ReactNode) =>
reactElementToJsxString(el, {
showDefaultProps: true,
showFunctions: true,
useBooleanShorthandSyntax: true,
sortProps: true,
useFragmentShortSyntax: true,
}),
stringEmpty: () => '""',
stringOneLine: str => JSON.stringify(str),
stringHead: () => 'String(\n',
stringLineSep: () => '\n',
stringLine: str =>
JSON.stringify(str.replace(/\n$/, ''))
.slice(1, -1)
.replace(/\\"/g, '"'),
stringTail: indent => `\n${indent})`,
symbol: (method, key) => `${method}(${key})`,
diffable: true,
start: (indent, key, sep) => `${indent}${key}${sep}`,
}
/**
* A style that can (mostly) be copy-pasted into a JS program
* and used as-is.
*
* Of course, object and function identities won't really work,
* and if there are circular references, then the results won't
* be valid JavaScript.
*/
const js: Style = {
fn: (fn, _) => fn.toString(),
setEmpty: cls => `new ${cls}()`,
setHead: cls => `new ${cls}([\n`,
setTail: indent => `${indent}])`,
setEntrySep: () => ',\n',
mapEmpty: cls => `new ${cls}()`,
mapHead: cls => `new ${cls}([\n`,
mapTail: indent => `${indent}])`,
mapKeyStart: () => '[',
mapKeyValSep: () => ', ',
mapEntrySep: () => '],\n',
circular: node => `*ref_${node.id}`,
nodeId: id => `&ref_${id} `,
errorEmpty: (er, cls) =>
`new ${cls}(${er.message ? JSON.stringify(er.message) : ''})`,
errorHead: (er, cls) =>
`Object.assign(new ${cls}(${
er.message ? JSON.stringify(er.message) : ''
}), {\n`,
errorTail: indent => `${indent}})`,
pojoEmpty: _ => '{}',
pojoHead: _ => `\{\n`,
pojoTail: indent => `${indent}}`,
pojoKeyValSep: () => ': ',
pojoEntrySep: () => ',\n',
arrayEmpty: _ => `[]`,
arrayHead: _ => `[\n`,
arrayTail: indent => `${indent}]`,
arrayEntrySep: () => ',\n',
bufferChunkSize: 32,
bufferEmpty: () => 'Buffer.alloc(0)',
bufferStart: () => 'Buffer.from("',
bufferBody: buf => buf.toString('hex'),
bufferEnd: buf => '", "hex") /* ' + bufToAscii(buf) + ' */',
bufferHead: () => 'Buffer.from(\n',
bufferKey: () => '',
bufferLine: (buf, chunkSize) =>
JSON.stringify(buf.toString('hex')) +
' '.repeat((chunkSize + 1) * 2 - buf.length * 2) +
'/* ' +
bufToAscii(buf) +
' */',
bufferTail: indent => `\n${indent}, "hex")`,
bufferLineSep: () => ' +\n',
bufferKeySep: () => '',
stringEmpty: () => '""',
stringLineSep: () => ' +\n',
stringLine: str => JSON.stringify(str),
stringOneLine: str => JSON.stringify(str),
stringHead: () => 'String(\n',
stringTail: indent => `\n${indent})`,
symbol: (method, key) => `${method}(${JSON.stringify(key)})`,
diffable: true,
start: (indent, key, sep) => `${indent}${key}${sep}`,
}
/**
* same as the {@link tcompare!styles.js} style, but no indentation or \n
*
* Not suitable for diffs, as everything is printed on one line.
*/
const tight: Style = {
fn: (fn, _) => fn.toString(),
setEmpty: cls => `new ${cls}()`,
setHead: cls => `new ${cls}([`,
setTail: _ => '])',
setEntrySep: () => ',',
mapEmpty: cls => `new ${cls}()`,
mapHead: cls => `new ${cls}([`,
mapTail: _ => '])',
mapKeyStart: () => '[',
mapKeyValSep: () => ',',
mapEntrySep: () => '],',
circular: node => `*${node.id}`,
nodeId: id => `&${id} `,
errorEmpty: (er, cls) =>
`new ${cls}(${JSON.stringify(er.message)})`,
errorHead: (er, cls) =>
`Object.assign(new ${cls}(${
er.message ? JSON.stringify(er.message) : ''
}), {`,
errorTail: _ => '})',
pojoEmpty: _ => '{}',
pojoHead: _ => `\{`,
pojoTail: _ => '}',
pojoKeyValSep: () => ':',
pojoEntrySep: () => ',',
arrayEmpty: _ => `[]`,
arrayHead: _ => `[`,
arrayTail: () => ']',
arrayEntrySep: () => ',',
// tight style doesn't need buffer head/tail/body, because it's
// always printed as one base64 line.
bufferChunkSize: Infinity,
bufferEmpty: () => 'Buffer.alloc(0)',
bufferStart: () => 'Buffer.from("',
bufferBody: buf => buf.toString('base64'),
bufferEnd: () => '","base64")',
stringEmpty: () => '""',
stringLineSep: () => '+',
stringLine: str => JSON.stringify(str),
stringOneLine: str => JSON.stringify(str),
stringHead: () => '',
stringTail: _ => '',
symbol: (method, key) => `${method}(${JSON.stringify(key)})`,
bufferHead: js.bufferHead,
bufferKey: js.bufferKey,
bufferLine: js.bufferLine,
bufferLineSep: js.bufferLineSep,
bufferTail: js.bufferTail,
bufferKeySep: js.bufferKeySep,
diffable: false,
start: (_indent, key, sep) => `${key}${sep}`,
}
export const styles: { [style in StyleType]: Style } = {
pretty,
js,
tight,
}