( css: string, cssFileDir: string, projectDir: string, visited: Set<string> = new Set(), )
| 129 | } |
| 130 | |
| 131 | function inlineCssFile( |
| 132 | css: string, |
| 133 | cssFileDir: string, |
| 134 | projectDir: string, |
| 135 | visited: Set<string> = new Set(), |
| 136 | ): string { |
| 137 | const { result: strippedCss, restore: restoreComments } = withCommentsStripped(css, (s) => s); |
| 138 | const importPlaceholders: string[] = []; |
| 139 | const withPlaceholders = strippedCss.replace( |
| 140 | CSS_IMPORT_RE, |
| 141 | (full, _q1, urlPath, _q2, barePath, mediaQuery) => { |
| 142 | const importPath = urlPath ?? barePath; |
| 143 | if (!importPath || !isRelativeUrl(importPath)) return full; |
| 144 | const resolved = resolve(cssFileDir, importPath); |
| 145 | // @import is resolved relative to the CSS file, but must stay within the |
| 146 | // project root; isSafePath also blocks symlink escapes (content is inlined). |
| 147 | if (!isSafePath(projectDir, resolved)) return full; |
| 148 | if (visited.has(resolved)) return ""; |
| 149 | const content = safeReadFile(resolved); |
| 150 | if (content == null) return full; |
| 151 | visited.add(resolved); |
| 152 | const inlined = inlineCssFile(content, dirname(resolved), projectDir, visited); |
| 153 | const trimmedMedia = (mediaQuery || "").trim(); |
| 154 | const block = trimmedMedia ? `@media ${trimmedMedia} {\n${inlined}\n}\n` : inlined + "\n"; |
| 155 | const idx = importPlaceholders.length; |
| 156 | importPlaceholders.push(block); |
| 157 | return `/*__hf_import_${idx}__*/`; |
| 158 | }, |
| 159 | ); |
| 160 | let rebased = rebaseCssUrls(withPlaceholders, cssFileDir, projectDir); |
| 161 | rebased = restoreComments(rebased); |
| 162 | for (let i = 0; i < importPlaceholders.length; i++) { |
| 163 | rebased = rebased.replace(`/*__hf_import_${i}__*/`, importPlaceholders[i]!); |
| 164 | } |
| 165 | return rebased; |
| 166 | } |
| 167 | |
| 168 | function safeReadFileBuffer(filePath: string): Buffer | null { |
| 169 | if (!existsSync(filePath)) return null; |
no test coverage detected