UNPKG

973 BPlain TextView Raw
1/** We don't normalize anything, so it is just strings and strings. */
2export type Data = Record<string, string>
3
4/** We typecast the value as a string so that it is compatible with envfiles. */
5export type Input = Record<string, any>
6
7// perhaps in the future we can use @bevry/json's toJSON and parseJSON and JSON.stringify to support more advanced types
8
9/** Parse an envfile string. */
10export function parse(src: string): Data {
11 const result: Data = {}
12 const lines = src.toString().split('\n')
13 for (const line of lines) {
14 const match = line.match(/^([^=:#]+?)[=:](.*)/)
15 if (match) {
16 const key = match[1].trim()
17 const value = match[2].trim()
18 result[key] = value
19 }
20 }
21 return result
22}
23
24/** Turn an object into an envfile string. */
25export function stringify(obj: Input): string {
26 let result = ''
27 for (const [key, value] of Object.entries(obj)) {
28 if (key) {
29 const line = `${key}=${String(value)}`
30 result += line + '\n'
31 }
32 }
33 return result
34}