Skip to content

Commit

Permalink
feat: callback on file
Browse files Browse the repository at this point in the history
  • Loading branch information
AndersDJohnson committed Jul 17, 2022
1 parent eb563d9 commit 7e65236
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
15 changes: 14 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ module.exports = (src, options = {}) => {

const walker = new Walker(walkerOptions);

walker.walk(src, (node) => {
// Pre-parse the source to get the AST to pass to `onFile`,
// then re-use that AST in our walker walk below.
const ast = typeof src === 'string' ? walker.parse(src) : src;

if (options.onFile) {
options.onFile({ options, src, ast, walker });
}

walker.walk(ast, (node) => {
switch (node.type) {
case 'ImportExpression':
if (!options.skipAsyncImports && node.source && node.source.value) {
Expand Down Expand Up @@ -83,6 +91,11 @@ module.exports = (src, options = {}) => {
}
});


if (options.onAfterFile) {
options.onAfterFile({ options, src, ast, walker, dependencies });
}

return dependencies;
};

Expand Down
42 changes: 42 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,48 @@ describe('detective-typescript', () => {
assert.equal(deps[0], 'mylib');
});

it('calls onFile callback', () => {
let onFileCalledArgs;
const onFile = (...args) => {
onFileCalledArgs = args;
}

const src = 'import {foo, bar} from "mylib";'

detective(src, { onFile });

assert.ok(onFileCalledArgs);
assert.ok(onFileCalledArgs[0]);
assert.equal(onFileCalledArgs[0].src, src);
assert.ok(typeof onFileCalledArgs[0].ast === 'object');
assert.ok(typeof onFileCalledArgs[0].walker === 'object');

assert.ok(typeof onFileCalledArgs[0].options === 'object');
assert.equal(onFileCalledArgs[0].options.onFile, onFile);
});

it('calls onAfterFile callback', () => {
let onAfterFileCalledArgs;
const onAfterFile = (...args) => {
onAfterFileCalledArgs = args;
}

const src = 'import {foo, bar} from "mylib";'

detective(src, { onAfterFile });

assert.ok(onAfterFileCalledArgs);
assert.ok(onAfterFileCalledArgs[0]);
assert.equal(onAfterFileCalledArgs[0].src, src);
assert.ok(typeof onAfterFileCalledArgs[0].ast === 'object');
assert.ok(typeof onAfterFileCalledArgs[0].walker === 'object');
assert.ok(Array.isArray(onAfterFileCalledArgs[0].dependencies));

assert.ok(typeof onAfterFileCalledArgs[0].options === 'object');
assert.equal(onAfterFileCalledArgs[0].options.onAfterFile, onAfterFile);
});


it('retrieves the re-export dependencies of modules', () => {
const deps = detective('export {foo, bar} from "mylib";');
assert.equal(deps.length, 1);
Expand Down

0 comments on commit 7e65236

Please # to comment.