Skip to content

Commit

Permalink
Merge pull request #3 from Agoric/2-explicit-module-rewrites
Browse files Browse the repository at this point in the history
require transforms to handle modules explicitly
  • Loading branch information
michaelfig authored Aug 7, 2019
2 parents 88aa90f + 29f5b6f commit 6b85e50
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,20 @@ export const makeEvaluators = (makerOptions = {}) => {
staticOptions,
);

const moduleOptions =
sourceType === 'module' ? { moduleRewritten: false } : {};
const sourceState = fullTransforms.reduce(
(ss, transform) => (transform.rewrite ? transform.rewrite(ss) : ss),
{ ...staticOptions, src: source },
{ ...staticOptions, ...moduleOptions, src: source },
);

if (sourceType === 'module' && !sourceState.moduleRewritten) {
throw SyntaxError(`Module source was not explicitly rewritten`);
}
if (sourceType !== 'module' && sourceState.moduleRewritten) {
throw SyntaxError(`Non-module source was explicitly rewritten as module`);
}

// Work around Babel appending semicolons.
// TODO: This belongs only in the individual transforms.
const maybeSource = sourceState.src;
Expand Down
56 changes: 56 additions & 0 deletions test/test-evaluate.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,59 @@ test('options.transforms', t => {
t.end();
}
});

test('evaluateModule needs explicit enabling', async t => {
try {
const {
evaluateModule: defaultModule,
evaluateProgram: defaultProgram,
} = makeEvaluators();

t.equal(defaultProgram('123; 456'), 456, 'default program works');
t.throws(
() => defaultModule('123; 456'),
SyntaxError,
'default module fails',
);

let rewriteAll = false;
const moduleTransform = {
rewrite(ss) {
if (rewriteAll || ss.sourceType === 'module') {
return {
...ss,
src: 'Promise.resolve({default: 123})',
moduleRewritten: true,
};
}
return ss;
},
};

const {
evaluateModule: myModule,
evaluateProgram: myProgram,
} = makeEvaluators({
transforms: [moduleTransform],
});

t.equal(myProgram('123; 456'), 456, 'my program works');
t.deepEqual(
await myModule('export default 345;'),
{ default: 123 },
'module rewrites',
);

rewriteAll = true;
t.throws(
() => myProgram('123; 456'),
SyntaxError,
'module rewrite in program context fails',
);
} catch (e) {
console.log('unexpected exception', e);
t.assert(false, e);
} finally {
t.end();
}
});

0 comments on commit 6b85e50

Please sign in to comment.