import { REGEX_VAR, REGEX_VAR_ALT } from "@polymech/core/constants" import { DEFAULT_ROOTS } from './config.js' 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 = {}, keep = false) => substitute(alt, path, DEFAULT_VARS(vars), keep) export const resolve = (path: string, alt: boolean = false, vars: Record = {}, keep = false) => resolveVariables(path, alt, vars, keep) export const template = ( path: string, vars: Record = {}, keep: boolean = false, depth: number = 3 ): string => { const map = DEFAULT_VARS(vars) let oldValue = path let newValue = resolve(oldValue, false, map) let iterationCount = 0 while (newValue !== oldValue && iterationCount < depth) { iterationCount++ oldValue = newValue newValue = resolve(oldValue, false, map, keep) } return newValue }