* Fetch source content from URL * @param {ReadResource} readResource The read resource function * @param {string} context context directory * @param {string} url source URL * @param {string=} sourceRoot source root directory * @param {boolean=} skipReading whether to skip reading file content
( readResource, context, url, sourceRoot, skipReading = false )
| 146 | * @returns {Promise<{ sourceURL: string, sourceContent?: StringOrBuffer }>} source content promise |
| 147 | */ |
| 148 | async function fetchFromURL( |
| 149 | readResource, |
| 150 | context, |
| 151 | url, |
| 152 | sourceRoot, |
| 153 | skipReading = false |
| 154 | ) { |
| 155 | // 1. It's an absolute url and it is not `windows` path like `C:\dir\file` |
| 156 | if (isURL(url)) { |
| 157 | // eslint-disable-next-line n/no-deprecated-api |
| 158 | const { protocol } = urlUtils.parse(url); |
| 159 | if (protocol === "data:") { |
| 160 | const sourceContent = skipReading ? "" : await readResource(url); |
| 161 | |
| 162 | return { sourceURL: "", sourceContent }; |
| 163 | } |
| 164 | |
| 165 | if (protocol === "file:") { |
| 166 | const pathFromURL = urlUtils.fileURLToPath(url); |
| 167 | const sourceURL = path.normalize(pathFromURL); |
| 168 | const sourceContent = skipReading ? "" : await readResource(sourceURL); |
| 169 | |
| 170 | return { sourceURL, sourceContent }; |
| 171 | } |
| 172 | |
| 173 | const sourceContent = skipReading ? "" : await readResource(url); |
| 174 | return { sourceURL: url, sourceContent }; |
| 175 | } |
| 176 | |
| 177 | // 3. Absolute path |
| 178 | if (isAbsolute(url)) { |
| 179 | let sourceURL = path.normalize(url); |
| 180 | |
| 181 | /** @type {undefined | StringOrBuffer} */ |
| 182 | let sourceContent; |
| 183 | |
| 184 | if (!skipReading) { |
| 185 | /** @type {string[]} */ |
| 186 | const possibleRequests = [sourceURL]; |
| 187 | |
| 188 | if (url.startsWith("/")) { |
| 189 | possibleRequests.push( |
| 190 | getAbsolutePath(context, sourceURL.slice(1), sourceRoot || "") |
| 191 | ); |
| 192 | } |
| 193 | |
| 194 | const result = await fetchPathsFromURL(readResource, possibleRequests); |
| 195 | |
| 196 | sourceURL = result.path; |
| 197 | sourceContent = result.data; |
| 198 | } |
| 199 | |
| 200 | return { sourceURL, sourceContent }; |
| 201 | } |
| 202 | |
| 203 | // 4. Relative path |
| 204 | const sourceURL = getAbsolutePath(context, url, sourceRoot || ""); |
| 205 | /** @type {undefined | StringOrBuffer} */ |
no test coverage detected