Skip to content

Commit

Permalink
Fix build failure when image file name includes special characters (#…
Browse files Browse the repository at this point in the history
…9781)

The latest version of `vite-plugin-markdown` uses a regular
expression that includes the file path via string concatenation.
However the file path is not escaped for use in a regular
expressions. So if a markdown document includes a reference to an
image file name which includes certain special characters it will
cause the build to fail.

This patch escapes regex special characters in the file path string
being injected into the regular expression. While I found that not
all special characters will cause this problem, it seems safer to
simply escape all regex specials. I also added test to verify this.

Related to: Commit 165cfc1

Co-authored-by: Erika <[email protected]>
  • Loading branch information
stevenbenner and Princesseuh authored Jan 23, 2024
1 parent 5e466ef commit ccc05d5
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/weak-plums-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Fix build failure when image file name includes special characters
2 changes: 1 addition & 1 deletion packages/astro/src/vite-plugin-markdown/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function getMarkdownCodeForImages(imagePaths: MarkdownImagePath[], html:
.map((entry) => {
const rawUrl = JSON.stringify(entry.raw);
return `{
const regex = new RegExp('__ASTRO_IMAGE_="([^"]*' + ${rawUrl} + '[^"]*)"', 'g');
const regex = new RegExp('__ASTRO_IMAGE_="([^"]*' + ${rawUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\\\$&')} + '[^"]*)"', 'g');
let match;
let occurrenceCounter = 0;
while ((match = regex.exec(html)) !== null) {
Expand Down
9 changes: 9 additions & 0 deletions packages/astro/test/core-image.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,15 @@ describe('astro:image', () => {
expect($img.attr('src').startsWith('/_image')).to.equal(true);
});

it('Supports special characters in file name', async () => {
let res = await fixture.fetch('/specialChars');
let html = await res.text();
$ = cheerio.load(html);

let $img = $('img');
expect($img.attr('src').startsWith('/_image')).to.equal(true);
});

it('properly handles remote images', async () => {
let res = await fixture.fetch('/httpImage');
let html = await res.text();
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
![C++](../assets/c++.png)

Image with special characters in file name worked.

0 comments on commit ccc05d5

Please sign in to comment.