Skip to content

Commit

Permalink
Fix issues with failure handling for CSS loading
Browse files Browse the repository at this point in the history
• Only push `file` for promises that succeed to load.
• Use `Promise.allSettled` to ensure all work has been done
  at the end of given recursion.
• Pass any errors directly with `await` on the first promise that were
  rejected (in matter of index than time).
  • Loading branch information
SpacingBat3 committed Mar 18, 2024
1 parent 60faa5a commit 92a6302
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions sources/code/main/modules/extensions.ts
Expand Up @@ -22,7 +22,7 @@ async function fetchOrRead(file:string, signal?:AbortSignal) {
async function parseImports(cssString: string, importCalls:string[], maxTries=5):Promise<string> {
const anyImport = /^@import .+?$/gm;
if(!anyImport.test(cssString)) return cssString;
const promises:Promise<string>[] = [];
const promises:Promise<unknown>[] = [];
cssString.match(anyImport)?.forEach(singleImport => {
const matches = /^@import (?:(?:url\()?["']?([^"';)]*)["']?)\)?;?/m.exec(singleImport);
if(matches?.[0] === undefined || matches[1] === undefined) return;
Expand All @@ -31,7 +31,6 @@ async function parseImports(cssString: string, importCalls:string[], maxTries=5)
promises.push(Promise.reject(new Error("Circular reference in CSS imports are disallowed!")));
return;
}
importCalls.push(file);
promises.push(fetchOrRead(file)
.then(data => {
if (data.download)
Expand All @@ -40,19 +39,17 @@ async function parseImports(cssString: string, importCalls:string[], maxTries=5)
return data.read.then(data => data.toString());
})
.then(content => cssString = cssString.replace(singleImport, content))
.then(() => importCalls.push(file))
);
});
try {
await Promise.all(promises);
} catch(error) {
const result = await Promise.allSettled(promises);
const rejection = result.findIndex(({status})=> status === "rejected");
if(rejection >= 0) {
if(maxTries > 0) {
console.warn("Couldn't resolve CSS theme imports, retrying again...");
maxTries--;
}
else if(error instanceof Error)
throw error;
else
throw new Error("Couldn't resolve CSS theme imports, aborting...");
else await promises[rejection];
}
if(anyImport.test(cssString)) {
return parseImports(cssString, importCalls, maxTries);
Expand Down

0 comments on commit 92a6302

Please sign in to comment.