ini.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. const { hasOwnProperty } = Object.prototype
  2. /* istanbul ignore next */
  3. const eol = typeof process !== 'undefined' &&
  4. process.platform === 'win32' ? '\r\n' : '\n'
  5. const encode = (obj, opt) => {
  6. const children = []
  7. let out = ''
  8. if (typeof opt === 'string') {
  9. opt = {
  10. section: opt,
  11. whitespace: false,
  12. }
  13. } else {
  14. opt = opt || Object.create(null)
  15. opt.whitespace = opt.whitespace === true
  16. }
  17. const separator = opt.whitespace ? ' = ' : '='
  18. for (const k of Object.keys(obj)) {
  19. const val = obj[k]
  20. if (val && Array.isArray(val)) {
  21. for (const item of val) {
  22. out += safe(k + '[]') + separator + safe(item) + eol
  23. }
  24. } else if (val && typeof val === 'object') {
  25. children.push(k)
  26. } else {
  27. out += safe(k) + separator + safe(val) + eol
  28. }
  29. }
  30. if (opt.section && out.length) {
  31. out = '[' + safe(opt.section) + ']' + eol + out
  32. }
  33. for (const k of children) {
  34. const nk = dotSplit(k).join('\\.')
  35. const section = (opt.section ? opt.section + '.' : '') + nk
  36. const { whitespace } = opt
  37. const child = encode(obj[k], {
  38. section,
  39. whitespace,
  40. })
  41. if (out.length && child.length) {
  42. out += eol
  43. }
  44. out += child
  45. }
  46. return out
  47. }
  48. const dotSplit = str =>
  49. str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
  50. .replace(/\\\./g, '\u0001')
  51. .split(/\./)
  52. .map(part =>
  53. part.replace(/\1/g, '\\.')
  54. .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'))
  55. const decode = str => {
  56. const out = Object.create(null)
  57. let p = out
  58. let section = null
  59. // section |key = value
  60. const re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
  61. const lines = str.split(/[\r\n]+/g)
  62. for (const line of lines) {
  63. if (!line || line.match(/^\s*[;#]/)) {
  64. continue
  65. }
  66. const match = line.match(re)
  67. if (!match) {
  68. continue
  69. }
  70. if (match[1] !== undefined) {
  71. section = unsafe(match[1])
  72. if (section === '__proto__') {
  73. // not allowed
  74. // keep parsing the section, but don't attach it.
  75. p = Object.create(null)
  76. continue
  77. }
  78. p = out[section] = out[section] || Object.create(null)
  79. continue
  80. }
  81. const keyRaw = unsafe(match[2])
  82. const isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'
  83. const key = isArray ? keyRaw.slice(0, -2) : keyRaw
  84. if (key === '__proto__') {
  85. continue
  86. }
  87. const valueRaw = match[3] ? unsafe(match[4]) : true
  88. const value = valueRaw === 'true' ||
  89. valueRaw === 'false' ||
  90. valueRaw === 'null' ? JSON.parse(valueRaw)
  91. : valueRaw
  92. // Convert keys with '[]' suffix to an array
  93. if (isArray) {
  94. if (!hasOwnProperty.call(p, key)) {
  95. p[key] = []
  96. } else if (!Array.isArray(p[key])) {
  97. p[key] = [p[key]]
  98. }
  99. }
  100. // safeguard against resetting a previously defined
  101. // array by accidentally forgetting the brackets
  102. if (Array.isArray(p[key])) {
  103. p[key].push(value)
  104. } else {
  105. p[key] = value
  106. }
  107. }
  108. // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  109. // use a filter to return the keys that have to be deleted.
  110. const remove = []
  111. for (const k of Object.keys(out)) {
  112. if (!hasOwnProperty.call(out, k) ||
  113. typeof out[k] !== 'object' ||
  114. Array.isArray(out[k])) {
  115. continue
  116. }
  117. // see if the parent section is also an object.
  118. // if so, add it to that, and mark this one for deletion
  119. const parts = dotSplit(k)
  120. p = out
  121. const l = parts.pop()
  122. const nl = l.replace(/\\\./g, '.')
  123. for (const part of parts) {
  124. if (part === '__proto__') {
  125. continue
  126. }
  127. if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') {
  128. p[part] = Object.create(null)
  129. }
  130. p = p[part]
  131. }
  132. if (p === out && nl === l) {
  133. continue
  134. }
  135. p[nl] = out[k]
  136. remove.push(k)
  137. }
  138. for (const del of remove) {
  139. delete out[del]
  140. }
  141. return out
  142. }
  143. const isQuoted = val => {
  144. return (val.startsWith('"') && val.endsWith('"')) ||
  145. (val.startsWith("'") && val.endsWith("'"))
  146. }
  147. const safe = val => {
  148. if (
  149. typeof val !== 'string' ||
  150. val.match(/[=\r\n]/) ||
  151. val.match(/^\[/) ||
  152. (val.length > 1 && isQuoted(val)) ||
  153. val !== val.trim()
  154. ) {
  155. return JSON.stringify(val)
  156. }
  157. return val.split(';').join('\\;').split('#').join('\\#')
  158. }
  159. const unsafe = (val, doUnesc) => {
  160. val = (val || '').trim()
  161. if (isQuoted(val)) {
  162. // remove the single quotes before calling JSON.parse
  163. if (val.charAt(0) === "'") {
  164. val = val.slice(1, -1)
  165. }
  166. try {
  167. val = JSON.parse(val)
  168. } catch {
  169. // ignore errors
  170. }
  171. } else {
  172. // walk the val to find the first not-escaped ; character
  173. let esc = false
  174. let unesc = ''
  175. for (let i = 0, l = val.length; i < l; i++) {
  176. const c = val.charAt(i)
  177. if (esc) {
  178. if ('\\;#'.indexOf(c) !== -1) {
  179. unesc += c
  180. } else {
  181. unesc += '\\' + c
  182. }
  183. esc = false
  184. } else if (';#'.indexOf(c) !== -1) {
  185. break
  186. } else if (c === '\\') {
  187. esc = true
  188. } else {
  189. unesc += c
  190. }
  191. }
  192. if (esc) {
  193. unesc += '\\'
  194. }
  195. return unesc.trim()
  196. }
  197. return val
  198. }
  199. module.exports = {
  200. parse: decode,
  201. decode,
  202. stringify: encode,
  203. encode,
  204. safe,
  205. unsafe,
  206. }