(cssText: string)
| 13 | } |
| 14 | |
| 15 | export function processBackgroundUrls(cssText: string): string { |
| 16 | if (isBlank(cssText)) { |
| 17 | return null; |
| 18 | } |
| 19 | cssText = cssText.trim(); |
| 20 | if (cssText.endsWith(";")) { |
| 21 | cssText = cssText.slice(0, -1); |
| 22 | } |
| 23 | const attrRe = /^background(-image)?\s*:\s*/i; |
| 24 | cssText = cssText.replace(attrRe, ""); |
| 25 | const ast = parseCSS("background: " + cssText, { |
| 26 | context: "declaration", |
| 27 | }); |
| 28 | let hasUnsafeUrl = false; |
| 29 | walkCSS(ast, { |
| 30 | visit: "Url", |
| 31 | enter(node) { |
| 32 | const originalUrl = node.value.trim(); |
| 33 | if ( |
| 34 | originalUrl.startsWith("http:") || |
| 35 | originalUrl.startsWith("https:") || |
| 36 | originalUrl.startsWith("data:") |
| 37 | ) { |
| 38 | return; |
| 39 | } |
| 40 | // allow file:/// urls (if they are absolute) |
| 41 | if (originalUrl.startsWith("file://")) { |
| 42 | const path = originalUrl.slice(7); |
| 43 | if (!path.startsWith("/")) { |
| 44 | console.log(`Invalid background, contains a non-absolute file URL: ${originalUrl}`); |
| 45 | hasUnsafeUrl = true; |
| 46 | return; |
| 47 | } |
| 48 | const newUrl = encodeFileURL(path); |
| 49 | node.value = newUrl; |
| 50 | return; |
| 51 | } |
| 52 | // allow absolute paths |
| 53 | if (originalUrl.startsWith("/") || originalUrl.startsWith("~/") || /^[a-zA-Z]:(\/|\\)/.test(originalUrl)) { |
| 54 | const newUrl = encodeFileURL(originalUrl); |
| 55 | node.value = newUrl; |
| 56 | return; |
| 57 | } |
| 58 | hasUnsafeUrl = true; |
| 59 | console.log(`Invalid background, contains an unsafe URL scheme: ${originalUrl}`); |
| 60 | }, |
| 61 | }); |
| 62 | if (hasUnsafeUrl) { |
| 63 | return null; |
| 64 | } |
| 65 | const rtnStyle = generateCSS(ast); |
| 66 | if (rtnStyle == null) { |
| 67 | return null; |
| 68 | } |
| 69 | return rtnStyle.replace(/^background:\s*/, ""); |
| 70 | } |
| 71 | |
| 72 | export function computeBgStyleFromMeta(meta: Omit<BackgroundConfigType, "display:name">, defaultOpacity: number = null): React.CSSProperties { |
no test coverage detected