Skip to content

Commit

Permalink
fix: only try to load external files with relative paths (#487)
Browse files Browse the repository at this point in the history
* fix: only try to load external files with relative paths

* refactor: remove redundant check
  • Loading branch information
kaisermann committed Feb 23, 2022
1 parent 484b26e commit 80d87ed
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -74,6 +74,8 @@ _Vue-like_ support for defining your markup between a specific tag. The default
<style src="./style.css"></style>
```

> Note: using a relative path starting with `.` is important. Otherwise `svelte-preprocess` will ignore the `src` attribute.
### Global style

#### `global` attribute
Expand Down
9 changes: 1 addition & 8 deletions src/modules/utils.ts
Expand Up @@ -60,15 +60,8 @@ export async function hasDepInstalled(dep: string) {
return (depCheckCache[dep] = result);
}

const REMOTE_SRC_PATTERN = /^(https?:)?\/\//;

export function isValidLocalPath(path: string) {
return (
path.match(REMOTE_SRC_PATTERN) == null &&
// only literal strings allowed
!path.startsWith('{') &&
!path.endsWith('}')
);
return path.startsWith('.');
}

// finds a existing path up the tree
Expand Down
25 changes: 21 additions & 4 deletions test/autoProcess/externalFiles.test.ts
Expand Up @@ -68,23 +68,40 @@ describe('external files', () => {
expect(markup.code).toContain(getFixtureContent('template.html'));
});

it("warns if local file don't exist", async () => {
const input = `<style src="./missing-potato"></style>`;

await preprocess(input, sveltePreprocess());

expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('was not found'),
);
});

REMOTE_JS.forEach((url) => {
it(`should not attempt to locally resolve ${url}`, async () => {
it(`ignores remote path "${url}"`, async () => {
const input = `<div></div><script src="${url}"></script>`;

const preprocessed = await preprocess(input, sveltePreprocess());

expect(preprocessed.toString?.()).toContain(input);
expect(preprocessed.dependencies).toHaveLength(0);
expect(warnSpy).not.toHaveBeenCalledWith(
expect.stringContaining('was not found'),
);
});
});

it("should warn if local file don't exist", async () => {
const input = `<style src="./missing-potato"></style>`;
it('ignores external source if path is not relative', async () => {
const input = `<style src="/root-potato"></style>`;

await preprocess(input, sveltePreprocess());

expect(warnSpy).toHaveBeenCalledWith(
const preprocessed = await preprocess(input, sveltePreprocess());

expect(preprocessed.toString?.()).toContain(input);
expect(preprocessed.dependencies).toHaveLength(0);
expect(warnSpy).not.toHaveBeenCalledWith(
expect.stringContaining('was not found'),
);
});
Expand Down

0 comments on commit 80d87ed

Please sign in to comment.