Skip to content

Commit

Permalink
added methood (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
geoffhendrey authored Feb 12, 2025
1 parent 34dde19 commit ef81662
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "stated-js",
"version": "0.1.52",
"version": "0.1.53",
"license": "Apache-2.0",
"description": "JSONata embedded in JSON",
"main": "./dist/src/index.js",
Expand Down
24 changes: 24 additions & 0 deletions src/TemplateProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1458,6 +1458,7 @@ export default class TemplateProcessor {
this.planStepFunctionGenerators.set("set", this.generateSet);
this.planStepFunctionGenerators.set("setInterval", this.timerManager.generateSetInterval);
this.planStepFunctionGenerators.set("clearInterval", this.timerManager.generateClearInterval);
this.planStepFunctionGenerators.set("change", this.generateChange);
}

/**
Expand Down Expand Up @@ -1914,11 +1915,34 @@ export default class TemplateProcessor {
if(!isInsideFork){
return this.setData
}
//fixme -- bro...this cannot possibly be right...and there are not any tests for it. How can we generate
//a function that ignores its arguments
return async (jsonPtr: JsonPointerString, data:any, op:Op='set')=>{
this.setDataForked(planStep); //behaves like setData, except operates on the forked output
}
}

private generateChange = (planStep: PlanStep) => {
const isInsideFork = planStep.forkStack.length > 0;

return async (jsonPtr:JsonPointerString, {mutator, defaultVal=0}:{mutator:(v:any)=>Promise<any>, defaultVal:any}):Promise<any> =>{
let data;
if(jp.has(this.output, jsonPtr)) {
data = jp.get(this.output, jsonPtr);
data = await mutator(data);
}else{
data = await mutator(defaultVal);
}
if(!isInsideFork) {
return await this.setData(jsonPtr, data);
}else{
//have not tested this
return await this.setDataForked({...planStep, data});
}
}

}

/**
* The $joined(/foo, data) function pops the forkstack and can return us to ordinary
* non-forked operation if the pop operation empties the fork stack
Expand Down
2 changes: 0 additions & 2 deletions src/test/StatedREPL.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,12 @@ if(typeof Bun === "undefined") { //run on node, not bun
// we call restore on the repl, which will expect it to be defined in CliCore.
await repl.cli('restore', '-f example/restoreSnapshot.json');

console.log(stringify(repl.cliCore.templateProcessor.output));
expect(repl.cliCore.templateProcessor.output).toBeDefined();
expect(repl.cliCore.templateProcessor.output.count).toBeGreaterThanOrEqual(3); // should be 3 or more right after restoring from the snapshot
expect(repl.cliCore.templateProcessor.output.count).toBeLessThan(10); // ... but less than 10


while (repl.cliCore.templateProcessor.output.count < 10) { // validates that templateProcessor picks up where it was left in the snapshot.
console.log("waiting for output.count to reach 10")
await new Promise(resolve => setTimeout(resolve, 50));
}
expect(repl.cliCore.templateProcessor.output.count).toBe(10);
Expand Down
41 changes: 34 additions & 7 deletions src/test/TemplateProcessor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1440,10 +1440,9 @@ test("local import with non-absolute --importPath", async () => {

// Use jest.fn() to track calls
const mockCallback = jest.fn((ptr, data)=>{
console.log(data);
//console.log(data);
});
tp.setDataChangeCallback("/once", mockCallback);
tp.logger.level = "debug";
await tp.initialize();

// Corrected assertion: Use toMatchObject instead of toContain for object comparison
Expand Down Expand Up @@ -3657,13 +3656,13 @@ test("repetitive snapshots stopped in random execution time", async () => {
//we are expecting the homeworlds to not be set yet
expect(snapshotObject.output.homeworlds.length).toEqual(0);

console.log(`restoring snapshot ${snapshot}`);
//console.log(`restoring snapshot ${snapshot}`);
// Restore from snapshot
const restoredTp = new TemplateProcessor();

const convergencePromise = new Promise(resolve => {
restoredTp.setDataChangeCallback('/homeworlds', (homeworlds) => {
console.log(`${restoredTp.uniqueId} ${homeworlds}`);
//console.log(`${restoredTp.uniqueId} ${homeworlds}`);
if (homeworlds.length === 10) { //both original template, and snapshot are pumping 5 items, for total of 10
resolve();
}
Expand All @@ -3672,11 +3671,11 @@ test("repetitive snapshots stopped in random execution time", async () => {
}
});
});
console.log(`restoring ${i}`)
//console.log(`restoring ${i}`)
await restoredTp.restore(snapshot);
await convergencePromise;
await restoredTp?.close();
console.log(`restored ${i}`)
//console.log(`restored ${i}`)

await convergencePromise;
const expectedHomeworlds = [
Expand Down Expand Up @@ -5743,7 +5742,6 @@ test("test resourceMapperB example", async () => {
"entities": "${ BEntities?BEntities:resourceMapperAFn(input)}"
};
const tp = new TemplateProcessor(o);
tp.logger.level = "debug";
await tp.initialize();
await new Promise(resolve => setTimeout(resolve, 1000));
expect(tp.output.entities).toStrictEqual( [
Expand All @@ -5755,6 +5753,35 @@ test("test resourceMapperB example", async () => {
]);
});

test("change with defaultVal", async () => {
let template = {
"mutateOpts": {
"mutator":"${function($v){$v+1}}",
"defaultVal": 42
},
"foo": "${$change('/bar', $$.mutateOpts)}",
"baz": 0,
"mutateOpts2": {
"mutator":"${function($v){$v+1}}",
"defaultVal": -100,
},
"zap": "${$change('/baz', $$.mutateOpts2)}",
};
let tp = new TemplateProcessor(template);
try {
await tp.initialize();
expect(tp.output.foo).toStrictEqual([
"/bar"
]);
expect(tp.output.bar).toBe(43);
expect(tp.output.baz).toBe(1);
}finally{
await tp.close();
}
});






Expand Down

0 comments on commit ef81662

Please sign in to comment.