Skip to content

Commit

Permalink
Add undocumented API to hook into when a new frame is created.
Browse files Browse the repository at this point in the history
This is helpful in scenarios where you wish to debug the environment
behavior, or modify the env for advanced scenarios.

As the callback is set via a Symbol, it can not be manipulated
or read inside a query. See jsonata-js/jsonata/jsonata-js#700.
  • Loading branch information
adamscybot committed Jun 8, 2024
1 parent 9eda3c7 commit e233bef
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/jsonata.js
Original file line number Diff line number Diff line change
Expand Up @@ -1837,7 +1837,7 @@ var jsonata = (function() {
*/
function createFrame(enclosingEnvironment) {
var bindings = {};
return {
const newFrame = {
bind: function (name, value) {
bindings[name] = value;
},
Expand All @@ -1857,6 +1857,16 @@ var jsonata = (function() {
ancestry: [ null ]
}
};

if (enclosingEnvironment) {
var framePushCallback = enclosingEnvironment.lookup(Symbol.for('jsonata.__createFrame_push'));
if(framePushCallback) {
framePushCallback(enclosingEnvironment, newFrame);
}
}


return newFrame
}

// Function registration
Expand Down
15 changes: 15 additions & 0 deletions test/implementation-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,21 @@ describe("Tests that include infinite recursion", () => {
});
});

describe("Tests that use internal frame push callbacks", () => {
describe("frame push callback bound to expression", function() {
it("calls callback when new frame created", function(done) {
var expr = jsonata("( )");
expr.assign(Symbol.for('jsonata.__createFrame_push'), function(parentEnv, newEnv) {
expect(parentEnv).to.not.equal(newEnv);
expect(parentEnv).to.include.keys(['lookup', 'bind']);
expect(newEnv).to.include.keys(['lookup', 'bind']);
done();
});
expr.evaluate();
});
});
});

/**
* Protect the process/browser from a runnaway expression
* i.e. Infinite loop (tail recursion), or excessive stack growth
Expand Down

0 comments on commit e233bef

Please sign in to comment.