import { REGEX_VAR, REGEX_VAR_ALT } from "@plastichub/core/constants" import { DEFAULT_ROOTS } from './config' export const DATE_VARS = () => { return { YYYY: new Date(Date.now()).getFullYear(), MM: new Date(Date.now()).getMonth() + 1, DD: new Date(Date.now()).getDate(), HH: new Date(Date.now()).getHours(), SS: new Date(Date.now()).getSeconds() } } export const _substitute = (template, map: Record, keep: boolean = true, alt: boolean = false) => { const transform = (k) => k || '' return template.replace(alt ? REGEX_VAR_ALT : REGEX_VAR, (match, key, format) => { if (map[key]) { return transform(map[key]).toString() } else if (map[key.replace(/-/g, '_')]) { return transform(map[key.replace(/-/g, '_')]).toString() } else if (keep) { return "${" + key + "}" } else { return "" } }) } export const substitute = (alt: boolean, template: string, vars: Record = {}, keep: boolean = true) => alt ? _substitute(template, vars, keep, alt) : _substitute(template, vars, keep, alt) export const DEFAULT_VARS = (vars: any) => { return { ...DEFAULT_ROOTS, ...DATE_VARS(), ...vars } } export const resolveVariables = (_path: string, alt: boolean = false, vars: Record = {}) => substitute(alt, _path, DEFAULT_VARS(vars)) export const resolve = (_path: string, alt: boolean = false, vars: Record = {}) => resolveVariables(_path, alt, vars)