| 2023 | deps: Set<string> |
| 2024 | logger: Logger |
| 2025 | }> = (opts) => { |
| 2026 | if (!opts) { |
| 2027 | throw new Error('base or replace is required') |
| 2028 | } |
| 2029 | |
| 2030 | return { |
| 2031 | postcssPlugin: 'vite-url-rewrite', |
| 2032 | Once(root) { |
| 2033 | const promises: Promise<void>[] = [] |
| 2034 | root.walkDecls((declaration) => { |
| 2035 | const importer = declaration.source?.input.file |
| 2036 | if (!importer) { |
| 2037 | opts.logger.warnOnce( |
| 2038 | '\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. ' + |
| 2039 | 'This may cause imported assets to be incorrectly transformed. ' + |
| 2040 | "If you've recently added a PostCSS plugin that raised this warning, " + |
| 2041 | 'please contact the package author to fix the issue.', |
| 2042 | ) |
| 2043 | } |
| 2044 | const isCssUrl = cssUrlRE.test(declaration.value) |
| 2045 | const isCssImageSet = cssImageSetRE.test(declaration.value) |
| 2046 | if (isCssUrl || isCssImageSet) { |
| 2047 | const replacerForDeclaration = async (rawUrl: string) => { |
| 2048 | const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer) |
| 2049 | if (resolvedId) { |
| 2050 | opts.deps.add(resolvedId) |
| 2051 | } |
| 2052 | return newUrl |
| 2053 | } |
| 2054 | if (isCssUrl && isCssImageSet) { |
| 2055 | promises.push( |
| 2056 | rewriteCssUrls(declaration.value, replacerForDeclaration) |
| 2057 | .then((url) => rewriteCssImageSet(url, replacerForDeclaration)) |
| 2058 | .then((url) => { |
| 2059 | declaration.value = url |
| 2060 | }), |
| 2061 | ) |
| 2062 | } else { |
| 2063 | const rewriterToUse = isCssImageSet |
| 2064 | ? rewriteCssImageSet |
| 2065 | : rewriteCssUrls |
| 2066 | promises.push( |
| 2067 | rewriterToUse(declaration.value, replacerForDeclaration).then( |
| 2068 | (url) => { |
| 2069 | declaration.value = url |
| 2070 | }, |
| 2071 | ), |
| 2072 | ) |
| 2073 | } |
| 2074 | } |
| 2075 | }) |
| 2076 | if (promises.length) { |
| 2077 | return Promise.all(promises) as any |
| 2078 | } |
| 2079 | }, |
| 2080 | } |
| 2081 | } |
| 2082 | UrlRewritePostcssPlugin.postcss = true |