Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent deleting files importes for side-effect #110

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/util/edit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2103,4 +2103,22 @@ export const a = 'a';`,
);
});
});

describe('side effect import', () => {
it('should not remove file if it is used for side effects', () => {
const fileService = new MemoryFileService();
fileService.set('/app/main.ts', `import './a';`);
fileService.set('/app/a.ts', `console.log('a');`);

edit({
fileService,
recursive,
deleteUnusedFile: true,
entrypoints: ['/app/main.ts'],
});

assert.equal(fileService.get('/app/main.ts'), `import './a';`);
assert.equal(fileService.get('/app/a.ts'), `console.log('a');`);
});
});
});
21 changes: 21 additions & 0 deletions lib/util/findFileUsage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,25 @@ describe('findFileUsage', () => {
// but for now this is the expected behavior
assert.deepEqual(result, new Set(['glob', 'cwd']));
});

it('should handle files imported only for side effects', () => {
const fileService = new MemoryFileService();
fileService.set('/app/main.ts', `import './a';`);
fileService.set('/app/a.ts', `console.log('a');`);

const graph = createDependencyGraph({
fileService,
options,
entrypoints: ['/app/main.ts'],
});
const result = findFileUsage({
targetFile: '/app/a.ts',
vertexes: graph.eject(),
files: fileService.eject(),
fileNames: fileService.getFileNames(),
options: {},
});

assert.deepEqual(result, new Set(['#side-effect']));
});
});
5 changes: 4 additions & 1 deletion lib/util/findFileUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ export const findFileUsage = ({
}

return new Set(
result.filter((it) => exportsOfTargetFile.has(it) || it === '*'),
result.filter(
(it) =>
exportsOfTargetFile.has(it) || it === '*' || it === '#side-effect',
),
);
};
7 changes: 7 additions & 0 deletions lib/util/parseFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,13 @@ const fn = ({
imports[resolved]?.push('default');
}

// side effect import
if (!node.importClause) {
imports[resolved] ||= [];
// using a special symbol that can't be a valid identifier
imports[resolved]?.push('#side-effect');
}

return;
}

Expand Down
Loading