Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expressions: Engine #561

Merged
merged 4 commits into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/altinn-app-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"terser-webpack-plugin": "5.3.6",
"ts-jest": "29.0.3",
"ts-loader": "9.4.1",
"utility-types": "^3.10.0",
"webpack": "5.74.0",
"webpack-cli": "4.10.0",
"webpack-dev-server": "4.11.1"
Expand Down
171 changes: 171 additions & 0 deletions src/altinn-app-frontend/src/features/expressions/ExprContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import dot from 'dot-object';

import {
ExprRuntimeError,
NodeNotFound,
NodeNotFoundWithoutContext,
} from 'src/features/expressions/errors';
import {
prettyErrors,
prettyErrorsToConsole,
} from 'src/features/expressions/prettyErrors';
import type { Expression } from 'src/features/expressions/types';
import type { IFormData } from 'src/features/form/data';
import type { LayoutNode, LayoutRootNode } from 'src/utils/layout/hierarchy';

import type {
IApplicationSettings,
IInstanceContext,
} from 'altinn-shared/types';

export interface ContextDataSources {
instanceContext: IInstanceContext;
applicationSettings: IApplicationSettings;
formData: IFormData;
}

export interface PrettyErrorsOptions {
defaultValue?: any;
introText?: string;
}

/**
* The expression context object is passed around when executing/evaluating a expression, and is
* a toolbox for expressions to resolve lookups in data sources, getting the current node, etc.
*/
export class ExprContext {
public path: string[] = [];

private constructor(
public expr: Expression,
public node:
| LayoutNode<any>
| LayoutRootNode<any>
| NodeNotFoundWithoutContext,
public dataSources: ContextDataSources,
) {}

/**
* Start a new context with a blank path (i.e. with a pointer at the top-level of an expression)
*/
public static withBlankPath(
expr: Expression,
node: LayoutNode<any> | LayoutRootNode<any> | NodeNotFoundWithoutContext,
dataSources: ContextDataSources,
): ExprContext {
return new ExprContext(expr, node, dataSources);
}

/**
* Reference a previous instance, but move our path pointer to a new path (meaning the context is working on an
* inner part of the expression)
*/
public static withPath(prevInstance: ExprContext, newPath: string[]) {
const newInstance = new ExprContext(
prevInstance.expr,
prevInstance.node,
prevInstance.dataSources,
);
newInstance.path = newPath;

return newInstance;
}

/**
* Utility function used to get the LayoutNode for this context, or fail if the node was not found
*/
public failWithoutNode(): LayoutNode<any> | LayoutRootNode<any> {
if (this.node instanceof NodeNotFoundWithoutContext) {
throw new NodeNotFound(this, this.node);
}
return this.node;
}

/**
* Get the expression for the current path
*/
public getExpr(): Expression {
if (this.path.length === 0) {
return this.expr;
}

// For some reason dot.pick wants to use the format '0[1][2]' for arrays instead of '[0][1][2]', so we'll rewrite
const [firstKey, ...restKeys] = this.path;
const stringPath =
firstKey.replace('[', '').replace(']', '') + restKeys.join('');

return dot.pick(stringPath, this.expr, false);
}

/**
* Create a string representation of the full expression, using the path pointer to point out where the expression
* failed (with a message).
*/
public trace(err: Error, options?: PrettyErrorsOptions) {
if (!(err instanceof ExprRuntimeError)) {
console.error(err);
return;
}

// eslint-disable-next-line no-console
console.log(...this.prettyErrorConsole(err, options));
}

public prettyError(err: Error, options?: PrettyErrorsOptions): string {
if (err instanceof ExprRuntimeError) {
const prettyPrinted = prettyErrors({
input: this.expr,
errors: { [this.path.join('')]: [err.message] },
indentation: 1,
});

const introText =
options && 'introText' in options
? options.introText
: 'Evaluated expression';

const extra =
options && 'defaultValue' in options
? ['Using default value instead:', ` ${options.defaultValue}`]
: [];

return [`${introText}:`, prettyPrinted, ...extra].join('\n');
}

return err.message;
}

public prettyErrorConsole(
err: Error,
options?: PrettyErrorsOptions,
): string[] {
if (err instanceof ExprRuntimeError) {
const prettyPrinted = prettyErrorsToConsole({
input: this.expr,
errors: { [this.path.join('')]: [err.message] },
indentation: 1,
defaultStyle: '',
});

const introText =
options && 'introText' in options
? options.introText
: 'Evaluated expression:';

const extra =
options && 'defaultValue' in options
? `\n%cUsing default value instead:\n %c${options.defaultValue}%c`
: '';
const extraCss =
options && 'defaultValue' in options ? ['', 'color: red;', ''] : [];

return [
`${introText}:\n${prettyPrinted.lines}${extra}`,
...prettyPrinted.css,
...extraCss,
];
}

return [err.message];
}
}
52 changes: 52 additions & 0 deletions src/altinn-app-frontend/src/features/expressions/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { ExprContext } from 'src/features/expressions/ExprContext';

export class ExprRuntimeError extends Error {
public constructor(public context: ExprContext, message: string) {
super(message);
}
}

export class LookupNotFound extends ExprRuntimeError {
public constructor(context: ExprContext, message: string) {
super(context, message);
}
}

export class UnknownTargetType extends ExprRuntimeError {
public constructor(context: ExprContext, type: string) {
super(context, `Cannot cast to unknown type '${type}'`);
}
}

export class UnknownSourceType extends ExprRuntimeError {
public constructor(context: ExprContext, type: string, supported: string) {
super(
context,
`Received unsupported type '${type}, only ${supported} are supported'`,
);
}
}

export class UnexpectedType extends ExprRuntimeError {
public constructor(context: ExprContext, expected: string, actual: any) {
super(context, `Expected ${expected}, got value ${JSON.stringify(actual)}`);
}
}

export class NodeNotFound extends ExprRuntimeError {
public constructor(
context: ExprContext,
original: NodeNotFoundWithoutContext,
) {
super(
context,
`Unable to evaluate expressions in context of the ${JSON.stringify(
original.nodeId,
)} component (it could not be found)`,
);
}
}

export class NodeNotFoundWithoutContext {
public constructor(public nodeId: string) {}
}
20 changes: 20 additions & 0 deletions src/altinn-app-frontend/src/features/expressions/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { NodeNotFoundWithoutContext } from 'src/features/expressions/errors';
import { evalExpr } from 'src/features/expressions/index';
import type { ContextDataSources } from 'src/features/expressions/ExprContext';

describe('Expressions', () => {
it('should return default value if expression evaluates to null', () => {
expect(
evalExpr(
['frontendSettings', 'whatever'],
new NodeNotFoundWithoutContext('test'),
{
applicationSettings: {},
} as ContextDataSources,
{
defaultValue: 'hello world',
},
),
).toEqual('hello world');
});
});
Loading