MCPcopy Create free account
hub / github.com/Effect-TS/effect / interpolate

Function interpolate

packages/effect/src/ConfigProvider.ts:1106–1145  ·  view source on GitHub ↗
(envValue: string, parsed: Record<string, string>)

Source from the content-addressed store, hash-verified

1104}
1105
1106function interpolate(envValue: string, parsed: Record<string, string>): string {
1107 // find the last unescaped dollar sign in the
1108 // value so that we can evaluate it
1109 const lastUnescapedDollarSignIndex = searchLast(envValue, /(?!(?<=\\))\$/g)
1110
1111 // If we couldn't match any unescaped dollar sign
1112 // let's return the string as is
1113 if (lastUnescapedDollarSignIndex === -1) return envValue
1114
1115 // This is the right-most group of variables in the string
1116 const rightMostGroup = envValue.slice(lastUnescapedDollarSignIndex)
1117
1118 /**
1119 * This finds the inner most variable/group divided
1120 * by variable name and default value (if present)
1121 * (
1122 * (?!(?<=\\))\$ // only match dollar signs that are not escaped
1123 * {? // optional opening curly brace
1124 * ([\w]+) // match the variable name
1125 * (?::-([^}\\]*))? // match an optional default value
1126 * }? // optional closing curly brace
1127 * )
1128 */
1129 const matchGroup = /((?!(?<=\\))\${?([\w]+)(?::-([^}\\]*))?}?)/
1130 const match = rightMostGroup.match(matchGroup)
1131
1132 if (match !== null) {
1133 const [_, group, variableName, defaultValue] = match
1134 const value = Object.hasOwn(parsed, variableName) && parsed[variableName] !== ""
1135 ? parsed[variableName]
1136 : defaultValue ?? ""
1137
1138 return interpolate(
1139 envValue.replace(group, value),
1140 parsed
1141 )
1142 }
1143
1144 return envValue
1145}
1146
1147function searchLast(str: string, rgx: RegExp): number {
1148 const matches = Array.from(str.matchAll(rgx))

Callers 1

dotEnvExpandFunction · 0.85

Calls 2

searchLastFunction · 0.85
replaceMethod · 0.45

Tested by

no test coverage detected