Skip to content

Commit

Permalink
Merge pull request #191 from divriots/featCustomCallbackExternalImages
Browse files Browse the repository at this point in the history
feat(external): add custom processing external images callback
  • Loading branch information
georges-gomes authored Sep 11, 2024
2 parents 63c10d7 + 0e97a88 commit 7a1322e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 27 deletions.
3 changes: 2 additions & 1 deletion src/config-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ export type Options = {
external: {
process:
| 'off' // Default
| 'download'; // Experimental
| 'download' // Experimental
| ((attrib_src: string) => Promise<string>); // Experimental
src_include: RegExp;
src_exclude: RegExp | null;
};
Expand Down
55 changes: 29 additions & 26 deletions src/optimize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,35 @@ async function processImage(
/*
* Check for external images
*/

if (
!isLocal(attrib_src) &&
isIncluded(
attrib_src,
config.image.external.src_include,
config.image.external.src_exclude
)
) {
// Don't process external images
if (config.image.external.process === 'off') return;
try {
if (config.image.external.process === 'download') {
// Download external image for local processing
attrib_src = await downloadExternalImage(state, htmlfile, attrib_src);
} else if (typeof config.image.external.process === 'function') {
// Custom processing for external image
attrib_src = await config.image.external.process(attrib_src);
}
img.attr('src', attrib_src);
} catch (e: any) {
state.reportIssue(htmlfile, {
type: 'warn',
msg: `Failed to process external image: ${attrib_src} - ${e.message}`,
});
return; // No more processing
}
}

switch (config.image.cdn.process) {
case 'off':
break;
Expand Down Expand Up @@ -404,32 +433,6 @@ async function processImage(
}
return;
}
if (!isLocal(attrib_src)) {
switch (config.image.external.process) {
case 'off': // Don't process external images
return;
case 'download': // Download external image for local processing
if (
!isIncluded(
attrib_src,
config.image.external.src_include,
config.image.external.src_exclude
)
)
break;
try {
attrib_src = await downloadExternalImage(state, htmlfile, attrib_src);
img.attr('src', attrib_src);
} catch (e: any) {
state.reportIssue(htmlfile, {
type: 'warn',
msg: `Failed to download image: ${attrib_src} - ${e.message}`,
});
return; // No more processing
}
break;
}
}

/*
* Loading image
Expand Down

0 comments on commit 7a1322e

Please sign in to comment.