Skip to content

Commit

Permalink
fix: prevent deleting files importes for side-effect
Browse files Browse the repository at this point in the history
  • Loading branch information
FredericEspiau committed Dec 17, 2024
1 parent 6ed047a commit 05f7774
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
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

0 comments on commit 05f7774

Please sign in to comment.