( node: DefaultTreeAdapterMap['element'], additionalAssetSources?: Record<string, HtmlAssetSource>, )
| 121 | * Given a HTML node, find all attributes that references an asset to be processed |
| 122 | */ |
| 123 | export function getNodeAssetAttributes( |
| 124 | node: DefaultTreeAdapterMap['element'], |
| 125 | additionalAssetSources?: Record<string, HtmlAssetSource>, |
| 126 | ): HtmlAssetAttribute[] { |
| 127 | const defaults = DEFAULT_HTML_ASSET_SOURCES[node.nodeName] |
| 128 | const additional = additionalAssetSources?.[node.nodeName] |
| 129 | |
| 130 | if (!defaults && !additional) return [] |
| 131 | |
| 132 | const attributes: Record<string, string> = {} |
| 133 | for (const attr of node.attrs) { |
| 134 | attributes[getAttrKey(attr)] = attr.value |
| 135 | } |
| 136 | |
| 137 | // If the node has a `vite-ignore` attribute, remove the attribute and early out |
| 138 | // to skip processing any attributes |
| 139 | if ('vite-ignore' in attributes) { |
| 140 | return [ |
| 141 | { |
| 142 | type: 'remove', |
| 143 | key: 'vite-ignore', |
| 144 | value: '', |
| 145 | attributes, |
| 146 | location: node.sourceCodeLocation!.attrs!['vite-ignore'], |
| 147 | }, |
| 148 | ] |
| 149 | } |
| 150 | |
| 151 | const actions: HtmlAssetAttribute[] = [] |
| 152 | function handleAttributeKey( |
| 153 | key: string, |
| 154 | type: 'src' | 'srcset', |
| 155 | filter?: (data: HtmlAssetSourceFilterData) => boolean, |
| 156 | ) { |
| 157 | const value = attributes[key] |
| 158 | if (!value) return |
| 159 | if (filter && !filter({ key, value, attributes })) return |
| 160 | const location = node.sourceCodeLocation!.attrs![key] |
| 161 | actions.push({ type, key, value, attributes, location }) |
| 162 | } |
| 163 | |
| 164 | // Run matching for default asset sources |
| 165 | if (defaults) { |
| 166 | defaults.srcAttributes?.forEach((key) => |
| 167 | handleAttributeKey(key, 'src', defaults.filter), |
| 168 | ) |
| 169 | defaults.srcsetAttributes?.forEach((key) => |
| 170 | handleAttributeKey(key, 'srcset', defaults.filter), |
| 171 | ) |
| 172 | } |
| 173 | |
| 174 | // Run matching for additional asset sources |
| 175 | if (additional) { |
| 176 | additional.srcAttributes?.forEach((key) => |
| 177 | handleAttributeKey(key, 'src', additional.filter), |
| 178 | ) |
| 179 | additional.srcsetAttributes?.forEach((key) => |
| 180 | handleAttributeKey(key, 'srcset', additional.filter), |
no test coverage detected