Private
changefor every json pointer, we have multiple callbacks that are stored in a Set
Contextual data for the template processing.
Debugger utility for the template processor.
Contains any errors encountered during template processing.
Private
executionExecution plans 'from' a given JSON Pointer. So key is JSON Pointer and value is array of JSON pointers (a plan)
Private
Readonly
executionA queue of execution plans awaiting processing.
function generators can be provided by a caller when functions need to be created in such a way that they are somehow 'responsive' or dependent on their location inside the template. Both the generator function, and the function it generates are asynchronous functions (ie they return a promise). $import is an example of this kind of behavior. When $import('http://mytemplate.com/foo.json') is called, the import function is actually generated on the fly, using knowledge of the json path that it was called at, to replace the content of the template at that path with the downloaded content.
Private
generatorRepresents the raw input for the template processor.
Private
isFlag indicating if the template processor is currently initializing.
Readonly
lifecycleRepresents the logger used within the template processor.
Maps JSON pointers of import paths to their associated meta information. So, for example the key "/" -> MetaInfo[]. the MetaInfo are in no particular order HOWEVER the individual MetaInfo objects are the same objects as memory as those in the templateMeta tree. Therefore, from any MetaInfo, you can navigate to it children as its children are simply field of the object that don't end in "". This explains why we name the MetaInfo fields with "" suffix, so they can be differentiated from 'real' fields of the template output nodes.
Readonly
onAllows caller to set a callback to propagate initialization into their framework
use lifecycleManager instead
Configuration options for the template processor.
Contains the processed output after template processing.
An instance of the Planner
interface used to manage execution plans.
The planner
is responsible for generating and executing ExecutionPlan
s,
which define the steps necessary to process templates. It provides methods
to initialize plans based on metadata and execute those plans. The planner
can be replaced by any valid Planner. We have SerialPlanner and ParallelPlanner
Allows a caller to receive a callback after the template is evaluated, but before any temporary variables are removed. This function is slated to be replaced with a map of functions like onInitialize
Allows a caller to receive a callback after the template is evaluated, but before any temporary variables are removed. This function is slated to be replaced with a map of functions like onInitialize
use lifecycleManager instead
use lifecycleManager instead
A set of tags associated with the template.
Private
tempThis object mirrors the template output in structure but where the output contains actual data, this object contains MetaInfo nodes that track metadata on the actual nodes
A unique string identifier for the template processor instance like '3b12f1df-5232-4e1f-9c1b-3c6fc5ac7d3f'.
List of warnings generated during template processing.
Static
DEFAULT_Default set of functions provided for the template processor.
Debounces a function, ensuring that it is only called once after a specified time has elapsed since the last call.
The function to debounce.
The number of milliseconds to wait before invoking the function.
A debounced function with the same type as the original function.
// Example usage:
function myFunction(value: string) {
console.log('Value:', value);
}
const debouncedFunction = debounce(myFunction, 500);
debouncedFunction('First call');
debouncedFunction('Second call');
debouncedFunction('Third call');
Optional
defaultValue: stringPerforms a fetch request and enhances error handling.
If the response is not ok, it rejects with a custom error object that includes a .json()
method.
This .json()
method, when called, returns the error object itself, facilitating error handling
for scenarios where the caller expects to call .json()
on the response.
The URL to fetch.
Optional
opts: objectOptional fetch options.
A promise that resolves to the fetch response. If the response is not ok, it rejects with a custom error object consistent with Stated template-level error handling e.g. {error:{message:"..."}}.
The custom error object with a .json()
method if the response is not ok. The error
object structure is: { error: { message: string } }.
These functions are commonly used utilities available for usage within the template processor's context. You can replace set this to determine which functions are available from templates
Static
NOOPStatic
Private
_isPrivate
_evaluatePrivate
_evaluatePrivate
_setPrivate
_strictPrivate
adjustPrivate
Sometimes we need to import a simple expression string that is not nested in an object. for example if we {"msg":"$import('${'hello ' & to }')"), then we are importing an expression directly into the parent, not nesting in an object. In this case we must slice off the last element of the rootJsonPointer, because to not slice it off would imply that the target of the expression is inside the msg field, but the intention when we import a simple expression is target the parent object which holds the msg field.
either the original rootJsonPointer, or one that has been trimmed to point to the parent of rootJsonPtr
Private
allPrivate
applyPrivate
Applies a transaction by processing each mutation within the transaction.
For each mutation, this method applies the specified operation (set
or delete
)
to the output
object based on the jsonPtr
(JSON pointer).
It also triggers data change callbacks after each mutation.
The transaction object containing a list of mutations to apply.
If the operation (op
) is neither "set"
nor "delete"
.
The transaction is processed as follows:
"set"
: Sets the value at the location specified by jsonPtr
using jp.set
."delete"
: Removes the value at the location specified by jsonPtr
using jp.remove
.After each mutation, callDataChangeCallbacks
is called to notify of the change.
Finally, a batch data change callback is triggered for all affected JSON pointers.
Private
cachePrivate
compilePrivate
createPrivate
drainPrivate
extractPrivate
fetchControls the flow of data and retrieves root nodes based on the specified level.
The level specifying the granularity of the data flow.
An array of root nodes that are computed based on the specified level.
Private
generatePrivate
generatePrivate
generatePrivate
When $forked is called, it must push the current output onto the forkStack so it can be restored on $joined, and it must replace the output with a copy of the output.
Private
generatePrivate
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
Private
generatePrivate
The $set(/foo, data) command may be operating inside the context of a $forked. If this is the case then $setData is intercepted here and we use the setDataForked function which applies changes to forked output
Private
getOptional
mergeMe: objectRetrieves the metadata information for a given JSON Pointer string.
The JSON Pointer string that identifies the template node.
The MetaInfo
object corresponding to the provided JSON Pointer.
If the JSON Pointer does not exist in the templateMeta
.
Template processor initialize can be called from 2 major use cases
the object representing the importedSubtemplate
defaults to "/" which is to say, this importedSubtemplate is the root importedSubtemplate. When we $import a importedSubtemplate inside an existing importedSubtemplate, then we must provide a path other than root to import into. Typically, we would use the json pointer of the expression where the $import function is used.
Private
isPrivate
isPrivate
temp vars are in scope if all tags are present OR the expression's fieldname ends in !, which makes it an absolutely temporary variable since.
Private
localPrivate
logPrivate
makePrivate
parseURLPrivate
populatePrivate
Certain functions callable in a JSONata expression must be dynamically generated. They cannot be static generated because the function instance needs to hold a reference to some kind of runtime state, either a MetaInfo or a PlanStep (see FunctionGenerator type). This method, for a given list of function names, generates the function by finding and calling the corresponding FunctionGenerator.
Private
populatePrivate
populatePrivate
propagatePrivate
queueOptional
cbFn: DataChangeCallbackPrivate
removePrivate
removeRemoves a previously registered transaction callback.
This method removes the callback that was registered with setTransactionCallback
for the root path '/'
.
The callback function to remove, which should match the previously registered callback.
Private
resetPrivate
restorePrivate
setSets or deletes data based on the specified operation.
The JSON pointer indicating where to apply the operation.
Optional
data: any = nullThe data to be used with the set or setDeferred operation.
Optional
op: Op = "set"The operation to perform - setDeferred is for internal use
A promise with the list of json pointers touched by the plan
Sets a data change callback function that will be called whenever the value at the json pointer has changed
of form (data, ptr:JsonPointerString, removed?:boolean)=>void
Calling setDataForked allows the mutation and its reaction (fromPlan) to begin executing immediately without queuing/seriealizing/blocking on other plans. This is possible because a forked planStep contains a write-safe copy of this.output (essentially a 'snapshot' in MVCC terminology) and therefore the mutation and propagation of the fromPlan are isolated, just like snapshot isolation levels on Postres or other MVCC databases. So, do not await this method. Just let 'er rip.
Private
setRegisters a transaction callback to handle batched data changes.
When setData is called, a set of changes (a DAG) is calculated and the changes are sequentially applied. These changes can be 'bundled' into a single Transaction for the purpose of capturing a single set of changes that if atomically applied, has the exact same effect as the DAG propagation. Therefore, a Transaction can be a less chatty way to capture and apply changes from one template instance A to template instance B without incurring the cost of for B to compute the change DAG.
A callback function that handles a Transaction
object. The callback is expected
to return a Promise<void>
.
If the callback is registered for any path other than '/'
.
Private
setPrivate
setupPrivate
setupCreates a stringified snapshot of the current state of the TemplateProcessor instance, including its execution status, input, output, and options.
A JSON string representing the snapshot of the TemplateProcessor's current state, including template input, processed output, and options.
const tp = new TemplateProcessor(template, context, options);
const snapshotString = await tp.snapshot();
// snapshotString contains a JSON string with the execution plans, mvcc, template, output, and options of the
TemplateProcessor
Private
sortPrivate
validatePrivate
withStatic
Private
compileStatic
constructConstructs a new TemplateProcessor instance from a given snapshot object, but does NOT initialize it. This method allows the caller the opportunity to register dataChangeCallbacks and so forth before template evaluation begins, providing more control over the initialization process.
A snapshot object containing template, options, and output data for initializing the TemplateProcessor.
Optional
context: {} = {}An optional context object to be used by the TemplateProcessor.
A new TemplateProcessor instance constructed from the snapshot data, not yet initialized.
const snapshot = {"template":"...", "options":{}, "output":"..."};
const tp = TemplateProcessor.constructFromSnapshot(snapshot);
// Register callbacks or perform other setup operations here
await tp.initialize();
Static
Private
deepStatic
Private
dependsStatic
fromStatic
fromStatic
loadLoads a template and initializes a new template processor instance.
The template data to be processed.
Optional
context: {} = {}Optional context data for the template.
Returns an initialized instance of TemplateProcessor
.
Static
simpleStatic
wrapGenerated using TypeDoc
This is the main TemplateProcessor class.
Remarks
The TemplateProcessor class is responsible for processing templates and interfacing with your program that may provide changing inputs over time and react to changes with callbacks. Many examples can be found in
src/test/TemplateProcessor.test.js
Example: Initialize a simple template stored in local object 'o'
Example: Pass the TemplateProcessor a context containing a function named `nozzle` and a variable named `ZOINK`
Example: Parse template from JSON or YAML
Example: React to changes using data change callbacks on various locations in the template