-
Notifications
You must be signed in to change notification settings - Fork 44
/
stringify.js
270 lines (245 loc) · 7.44 KB
/
stringify.js
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
'use strict'
module.exports = stringify
module.exports.value = stringifyInline
function stringify (obj) {
if (obj === null) throw typeError('null')
if (obj === void (0)) throw typeError('undefined')
if (typeof obj !== 'object') throw typeError(typeof obj)
if (typeof obj.toJSON === 'function') obj = obj.toJSON()
if (obj == null) return null
const type = tomlType(obj)
if (type !== 'table') throw typeError(type)
return stringifyObject('', '', obj)
}
function typeError (type) {
return new Error('Can only stringify objects, not ' + type)
}
function getInlineKeys (obj) {
return Object.keys(obj).filter(key => isInline(obj[key]))
}
function getComplexKeys (obj) {
return Object.keys(obj).filter(key => !isInline(obj[key]))
}
function toJSON (obj) {
let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {}
for (let prop of Object.keys(obj)) {
if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) {
nobj[prop] = obj[prop].toJSON()
} else {
nobj[prop] = obj[prop]
}
}
return nobj
}
function stringifyObject (prefix, indent, obj) {
obj = toJSON(obj)
let inlineKeys
let complexKeys
inlineKeys = getInlineKeys(obj)
complexKeys = getComplexKeys(obj)
const result = []
const inlineIndent = indent || ''
inlineKeys.forEach(key => {
var type = tomlType(obj[key])
if (type !== 'undefined' && type !== 'null') {
result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true))
}
})
if (result.length > 0) result.push('')
const complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : ''
complexKeys.forEach(key => {
result.push(stringifyComplex(prefix, complexIndent, key, obj[key]))
})
return result.join('\n')
}
function isInline (value) {
switch (tomlType(value)) {
case 'undefined':
case 'null':
case 'integer':
case 'nan':
case 'float':
case 'boolean':
case 'string':
case 'datetime':
return true
case 'array':
return value.length === 0 || tomlType(value[0]) !== 'table'
case 'table':
return Object.keys(value).length === 0
/* istanbul ignore next */
default:
return false
}
}
function tomlType (value) {
if (value === undefined) {
return 'undefined'
} else if (value === null) {
return 'null'
/* eslint-disable valid-typeof */
} else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) {
return 'integer'
} else if (typeof value === 'number') {
return 'float'
} else if (typeof value === 'boolean') {
return 'boolean'
} else if (typeof value === 'string') {
return 'string'
} else if ('toISOString' in value) {
return isNaN(value) ? 'undefined' : 'datetime'
} else if (Array.isArray(value)) {
return 'array'
} else {
return 'table'
}
}
function stringifyKey (key) {
const keyStr = String(key)
if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {
return keyStr
} else {
return stringifyBasicString(keyStr)
}
}
function stringifyBasicString (str) {
return '"' + escapeString(str).replace(/"/g, '\\"') + '"'
}
function stringifyLiteralString (str) {
return "'" + str + "'"
}
function numpad (num, str) {
while (str.length < num) str = '0' + str
return str
}
function escapeString (str) {
return str.replace(/\\/g, '\\\\')
.replace(/[\b]/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
/* eslint-disable no-control-regex */
.replace(/([\u0000-\u001f\u007f])/, c => '\\u' + numpad(4, c.codePointAt(0).toString(16)))
/* eslint-enable no-control-regex */
}
function stringifyMultilineString (str) {
let escaped = str.split(/\n/).map(str => {
return escapeString(str).replace(/"(?="")/g, '\\"')
}).join('\n')
if (escaped.slice(-1) === '"') escaped += '\\\n'
return '"""\n' + escaped + '"""'
}
function stringifyAnyInline (value, multilineOk) {
let type = tomlType(value)
if (type === 'string') {
if (multilineOk && /\n/.test(value)) {
type = 'string-multiline'
} else if (!/[\b\t\n\f\r']/.test(value) && /"/.test(value)) {
type = 'string-literal'
}
}
return stringifyInline(value, type)
}
function stringifyInline (value, type) {
/* istanbul ignore if */
if (!type) type = tomlType(value)
switch (type) {
case 'string-multiline':
return stringifyMultilineString(value)
case 'string':
return stringifyBasicString(value)
case 'string-literal':
return stringifyLiteralString(value)
case 'integer':
return stringifyInteger(value)
case 'float':
return stringifyFloat(value)
case 'boolean':
return stringifyBoolean(value)
case 'datetime':
return stringifyDatetime(value)
case 'array':
return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan'))
case 'table':
return stringifyInlineTable(value)
/* istanbul ignore next */
default:
throw typeError(type)
}
}
function stringifyInteger (value) {
/* eslint-disable security/detect-unsafe-regex */
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, '_')
}
function stringifyFloat (value) {
if (value === Infinity) {
return 'inf'
} else if (value === -Infinity) {
return '-inf'
} else if (Object.is(value, NaN)) {
return 'nan'
} else if (Object.is(value, -0)) {
return '-0.0'
}
const [int, dec] = String(value).split('.')
return stringifyInteger(int) + '.' + dec
}
function stringifyBoolean (value) {
return String(value)
}
function stringifyDatetime (value) {
return value.toISOString()
}
function stringifyInlineArray (values) {
values = toJSON(values)
let result = '['
const stringified = values.map(_ => stringifyInline(_))
if (stringified.join(', ').length > 60 || /\n/.test(stringified)) {
result += '\n ' + stringified.join(',\n ') + '\n'
} else {
result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '')
}
return result + ']'
}
function stringifyInlineTable (value) {
value = toJSON(value)
const result = []
Object.keys(value).forEach(key => {
result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false))
})
return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}'
}
function stringifyComplex (prefix, indent, key, value) {
const valueType = tomlType(value)
/* istanbul ignore else */
if (valueType === 'array') {
return stringifyArrayOfTables(prefix, indent, key, value)
} else if (valueType === 'table') {
return stringifyComplexTable(prefix, indent, key, value)
} else {
throw typeError(valueType)
}
}
function stringifyArrayOfTables (prefix, indent, key, values) {
values = toJSON(values)
const firstValueType = tomlType(values[0])
/* istanbul ignore if */
if (firstValueType !== 'table') throw typeError(firstValueType)
const fullKey = prefix + stringifyKey(key)
let result = ''
values.forEach(table => {
if (result.length > 0) result += '\n'
result += indent + '[[' + fullKey + ']]\n'
result += stringifyObject(fullKey + '.', indent, table)
})
return result
}
function stringifyComplexTable (prefix, indent, key, value) {
const fullKey = prefix + stringifyKey(key)
let result = ''
if (getInlineKeys(value).length > 0) {
result += indent + '[' + fullKey + ']\n'
}
return result + stringifyObject(fullKey + '.', indent, value)
}