@wemake4u/dmn-core
v1.0.2
Published
DMN 1.5 model, dmn-moddle adapter, store and commands
Maintainers
Readme
@wemake4u/dmn-core
The model layer of the @wemake4u DMN editor, with no user interface:
- XML: reads DMN 1.2–1.5 with DMNDI (namespaces mapped to 1.5) and writes DMN 1.5, without
losing vendor extensions, styles or elements unknown to the editor. It uses
moddlewith its own DMN 1.5 / DMNDI 1.5 schema (thedmn-moddlepackage only knows DMN 1.3). The 156 models of the DMN TCK are read and written back without differences. - Model: immutable snapshots of the semantic model (DRG elements, requirements, expressions, item definitions) and of the diagrams (shapes, edges, waypoints).
- Store:
DmnStore, one per open file, based on Angular signals, with undo/redo, dirty state and a read-only mode. - Commands: every change is a reversible command executed on the store (create, move, connect, rename, delete elements; edit every kind of expression; data types; decision services; edge routing).
- Scope, validation and analysis: names visible in the FEEL expressions of an element, model validation, gaps and overlaps of decision tables.
Installation
npm install @wemake4u/dmn-corePeer dependencies: @angular/core and @angular/common 22.2.x (only signal and computed
are used: the store works in any Angular application, also without zone.js).
Installed with the package: dmn-moddle (^12.2.1, the XML reader and writer) and tslib.
Usage
import {
analyzeDecisionTable,
connect,
createElement,
DmnStore,
setExpressionKind,
setExpressionText,
validateModel,
type Decision,
type DecisionTable,
} from '@wemake4u/dmn-core';
const store = await DmnStore.open(xml); // or DmnStore.create('Nuovo modello')
// commands return their result (here the id of the new element) and can be undone
const income = store.execute(
createElement({ kind: 'inputData', name: 'Reddito', bounds: { x: 80, y: 320 } }),
);
const decision = store.execute(
createElement({ kind: 'decision', name: 'Fascia', bounds: { x: 80, y: 120 } }),
);
store.execute(connect({ sourceId: income, targetId: decision }));
// a decision table, then the text of its first input entry
const logic = { elementId: decision, path: ['decisionLogic'] };
store.execute(setExpressionKind({ ...logic, kind: 'decisionTable' }));
store.execute(
setExpressionText({
...logic,
path: ['decisionLogic', 'rule', 0, 'inputEntry', 0],
text: '< 1000',
}),
);
const model = store.model(); // signal: the current snapshot
const table = (store.elementsById().get(decision) as Decision).decisionLogic as DecisionTable;
analyzeDecisionTable(table, model).gaps; // [{ entries: ['>= 1000'] }]
validateModel(model); // ModelIssue[]: code, severity, elementId, message
store.undo();
store.redo();
const saved = await store.save(); // DMN 1.5 XML; isDirty() becomes false
// a save that may fail or take time: mark it as saved only when it succeeds
const { xml, savePoint } = await store.snapshot();
await upload(xml);
store.markSaved(savePoint); // changes made during the upload stay unsavedExpression paths
Expressions are addressed by the element and a path of properties and indexes from it, as in
the XML: ['decisionLogic'], ['encapsulatedLogic', 'body'],
['decisionLogic', 'contextEntry', 2, 'value'],
['decisionLogic', 'rule', 0, 'outputEntry', 1], ['decisionLogic', 'then', 'expression'].
setExpressionKind creates an empty expression of any kind at a path (literal,
decisionTable, context, relation, list, invocation, functionDefinition,
conditional, filter, for, some, every), also nested.
Read-only mode
store.readOnly.set(true);
store.execute(command); // throws DmnCommandError: the model is not changedImported models
describeImportedModel(model) describes a DMN model (its decisions, input data, business
knowledge models with parameters, decision services and item definitions) as an
ImportedModel, the format an ImportResolver returns. store.resolveImports(resolver)
records the result of each import in store.importResolutions (loading, resolved,
unresolved, error), and importedScope gives the names they add to the FEEL expressions.
ImportCatalogInfo, ImportCatalogList, ImportLibraryInfo, ImportLibraryList,
ImportQuery, ImportSearch, ImportCandidate, searchKeywords and
suggestedPrefix support the search in the catalogs
of importable models; handlerResult turns the result of any handler (value, promise or
observable) into a promise. The commands addImport, setImport and removeImport edit the
imports;
addImportedShape shows an imported element in the diagram (shape ref prefix:id), which
connect (with sourceKind), moveElements and deleteElements accept like a local id.
Evaluation
FeelEvaluator, EvaluationRequest and EvaluationResult are the contract of the "Prova"
panels with the FEEL service of the host. evaluationInputs(model, elementId, resolutions?) lists the inputs
of a decision, BKM or decision service (with an example FEEL value for each type; with the
resolutions of the imports, also the imported decisions and input data of a decision, named
prefix.name),
evaluationRequest(store, elementId, values) builds the request with the model XML, and
evaluationSucceeded / evaluationText read the result. TraceStep and TraceDetail describe the
trace of an evaluation for the diagnostics; traceElements (the DRG elements in evaluation
order, with the calls of the BKMs), logicStep, requiredSteps, flattenTrace, traceMessages, readTraceDocument (reads the
JSON of "Esporta traccia", a result or a trace step), traceMismatches and
expressionAtPath(model, elementId, path) (the part of an element a step refers to) help to
read it; nestedElementSteps, ownDuration and elementTimings (own and total time of each
element, a BKM summed over its calls) read the durations of the steps.
The steps of the imported models come when the request asks for them (trace: { imported: true }):
TraceStep.model names the imported model of a step (its elementId and path are those of that
model), EvaluationResult.models describes the models met by their key (TraceModel: the names of
the imports from the evaluated model, name, namespace, version, access and, added by the host, the
XML), EvaluationMessage.model the model of a message. traceElements(root, model?) and
elementTimings(root, model?) work on the elements of one model, the imported elements it called
following with their model and a key of their own (traceElementKey); traceModelPath gives
the path of an imported model and traceCallers the elements that called some steps.
explainEvaluation(model, result, { request, resolutions, at, messages, locale }) writes the
explanation of an evaluation for people who do not know DMN (Explanation: the outcome, the data
used, a step for each decision with sentences, reasons, formula and alternatives, the warnings),
explanationHtml(explanation, { level, messages, locale }) writes it as a page to print or save
(level "summary" or "full"); explanationReportHtml(report, options) puts several explanations
in one page (ExplanationReport: a heading with the overall outcome, the facts and a table given
by the host, a section for each evaluation), e.g. the checks of a request; unaryTestText writes
the condition of a column in words and explanationValue a FEEL value for a person.
analyzePerformance(trace, { thresholds }) says where the time of an evaluation went
(PerformanceAnalysis: the time by kind of work, the external functions with their calls, the
critical path, the elements by own time, the points of attention); the values a session
evaluation took from other evaluations count once, with the time they took then.
documentPerformance(document, { evaluationId }) does it from a trace as «Esporta traccia» writes
it (an evaluation, one evaluation of a session, or the whole run with sessionPerformanceRows),
without the model, and performanceDocumentHtml(document, { locale, arguments, thresholds })
writes the report as a page to print or save, also outside the editor (e.g. a list of runs
that offers the report of each). The external functions are the calls the service marks
(TraceStep.externalCalls); a trace without marks has the bodies of the invoked functions
that ran no step of their own. maskedFeel hides personal data in the arguments.
Languages
DmnI18n (signals) gives the texts of the editor in the chosen language: messages() (typed
dictionary, DmnMessages), locale(), time, dateTime, number, plural.
provideDmnLocale(locale, { dictionaries, messages }) sets the language of an application (also
a signal), a component may provide its own DmnI18n and connect it to its inputs.
IT_MESSAGES is the reference dictionary, EN_MESSAGES has the same keys (a missing key is a
compile error); mergeMessages applies corrections (DmnMessagesOverride). The issues of
validateModel have code, args and source: 'client': issueText(issue, messages) writes
them, and those of the validator of the host, in a language (the host's issues stay in English
when the language has no template for them).
Validation
validateModel(model) returns the ModelIssue[] of the editor's own checks. For a validator of
the host, ModelValidator ({ xml, namespace } => HandlerResult<ModelIssue[]>) is the contract,
validationSettings(settings, hasValidator) fills in the defaults of ValidationSettings,
placeIssues(model, issues) moves issues reported on a shape to its element and
mergeIssues(client, server) merges both lists (the issue of the editor wins when both report the
same code on the same element). issueText(issue, messages) writes an issue in a language (English by default) from its code and
args (the codes of the .NET DmnModelValidator), falling back to message;
translatedIssueCodes() lists the codes it knows.
Properties of the host
DmnExtension describes properties of the host for the elements of the diagram, saved in its own
namespace (see the README of dmn-editor). extensionValues(model, element, extension) reads them,
setExtensionValue({ elementId, namespace, prefix, field, value }) writes one (an attribute or the
children of extensionElements, declaring the namespace when needed) and
validateExtensions(model, extensions, locale) gives the extension-invalid issues. The
elements of the diagram have the content of other namespaces in extensions (attributes and
extension elements).
The catalogs of an extension (DmnExtension.catalogs, see the README of dmn-editor) are read
with readCatalog(model, extension, catalog) (CatalogContent: links and entries, each with
values, links and children) and written whole with setCatalogContent({ extension, catalog,
content }), one command that keeps what the declaration does not describe.
catalogLinkUses(model, extensions) lists the uses of the elements with their role,
validateCatalogs(model, extensions, locale) gives the catalog-* issues. For a catalog with
evaluation, catalogEvaluationInputs and catalogEvaluationRequest give the fields and the
request of «Prova», catalogOutcomes(catalog, content, document) the outcome of each entry from
the session returned. The other elements of
the extensionElements of the definitions are in DmnModel.extensionNodes.
Automatic layout
autoLayout({ elementIds?, direction?, onlyMissing? }) is a command that arranges the diagram
(computeLayout gives the positions without changing the model): layers along the information
requirements (direction up, the default, puts the input data at the bottom; down,
right), knowledge models on the right of the element that uses them, knowledge sources on the
left, annotations beside their element, a decision service as one block (output decisions above
the divider line), groups around their elements, everything on a 16 px grid. It creates the
missing shapes and edges (a file without DMNDI gets a diagram) and routes the edges again.
onlyMissing places only the elements without a shape, next to their neighbors.
hasNoDiagram(model) and hasElementsWithoutShape(model) tell when it is needed.
Errors
Commands throw DmnCommandError when a change is not allowed, for example a connection that DMN
does not admit or a duplicate name; the store is not changed in that case. The error has a
code and args (e.g. context-entry-duplicate, { name: 'rata' }) and its message is
the text in the default language (English, DEFAULT_DMN_MESSAGES); errorText(error, messages) or commandErrorText(messages, code, args) write
it in another language. connectionProblem gives the code of a refused connection,
connectionError its text (English unless messages are given).
License
MIT. The DMN 1.5 / DMNDI 1.5 schema descriptors are derived from those of dmn-moddle (MIT, © camunda
Services GmbH): its notice and the licenses of the dependencies are in THIRD_PARTY_NOTICES.txt.
