PromucFlow_constructor/app/client/src/sagas/PostEvaluationSagas.ts
Apeksha Bhosale 09eea59330
feat: JS Editor (#6003)
* Changes to add js plugin

* routes+reducer+create template

* added debugger to js editor page

* entity explorer changes

* create js function

* added copy, move and delete action

* added js plugin

* added existing js functions to data tree

* removed actionconfig for js collection

* new js function added to data tree and entity as well

* parsing flow added

* changes to data tree

* parse and update js functions

* small changes for def creator for js action

* create delete modified

* small changes for update

* update flow change

* entity properties added

* removed linting errors

* small changes in entity explorer

* changes for update

* move, copy implementation

* conflict resolved

* changes for dependecy map creation

* Only make the variables the binding paths

* Basic eval sync working

* Minor fixes

* removed unwanted code

* entity props and autocomplete

* saving in progress show

* redirection fix after delete js action

* removed unnecessary line

* Fixing merge conflict

* added sample body

* removed dummy data and added plugin Type

* few PR comments fixed

* automplete fix

* few more PR comments fix

* PR commnets fix

* move and copy api change

* js colleciton name refactor & 'move to page' changes & search

* view changes

* autocomplete added for js collections

* removing till async is implemented

* small changes

* separate js pane response view

* Executing functions

* js collection to js objects

* entity explorer issue and resolve action on page switch

* removed unused line

* small color fix

* js file icon added

* added js action to property pane

* Property pane changes for actions

* property pane changes for js functions

* showing syntax error for now

* actions sorted in response tab

* added js objects to slash and recent entitties

* enabling this to be used inside of function

* eval fix

* feature flag changes for entity explorer and property pane

* debugger changes

* copy bug fix

* small changes for eval

* debugger bug fix

* chnaged any to specific types

* error in console fix

* icons update

* fixed test case

* test case fix

* non empty check for functions

* evaluate test case fix

* added new icons

* text change

* updated time for debounce for trial

* after release mereg

* changed icon

* after merge

* PR comments simple

* fixed PR comments - redux form, settings remove

* js object interface changes

* name refactor

* export default change

* delete resolve actions chnage

* after merge

* adding execute fn as 3rd option and removed create new js function

* issue 7054 fixed - app crash

* execute function on response tab changes

* refactor function name part 1

* refactor of js function name

* try catch added refactor

* test fix

* not used line removed

* test cases locator fixed

Co-authored-by: Nidhi <nidhi.nair93@gmail.com>
Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 23:02:22 +05:30

358 lines
11 KiB
TypeScript

import { ENTITY_TYPE, Log, Severity } from "entities/AppsmithConsole";
import { DataTree } from "entities/DataTree/dataTreeFactory";
import {
DataTreeDiff,
DataTreeDiffEvent,
getEntityNameAndPropertyPath,
isAction,
isWidget,
} from "workers/evaluationUtils";
import {
EvalError,
EvalErrorTypes,
EvaluationError,
getEvalErrorPath,
getEvalValuePath,
PropertyEvaluationErrorType,
} from "utils/DynamicBindingUtils";
import { find, get, some } from "lodash";
import LOG_TYPE from "../entities/AppsmithConsole/logtype";
import { put, select } from "redux-saga/effects";
import {
ReduxAction,
ReduxActionWithoutPayload,
} from "constants/ReduxActionConstants";
import { Toaster } from "components/ads/Toast";
import { Variant } from "components/ads/common";
import AppsmithConsole from "../utils/AppsmithConsole";
import * as Sentry from "@sentry/react";
import AnalyticsUtil from "../utils/AnalyticsUtil";
import {
createMessage,
ERROR_EVAL_ERROR_GENERIC,
ERROR_EVAL_TRIGGER,
PARSE_JS_FUNCTION_ERROR,
VALUE_IS_INVALID,
} from "constants/messages";
import log from "loglevel";
import { AppState } from "reducers";
import { getAppMode } from "selectors/applicationSelectors";
import { APP_MODE } from "entities/App";
import { dataTreeTypeDefCreator } from "utils/autocomplete/dataTreeTypeDefCreator";
import TernServer from "utils/autocomplete/TernServer";
import getFeatureFlags from "utils/featureFlags";
import { TriggerEvaluationError } from "sagas/ActionExecution/ActionExecutionSagas";
const getDebuggerErrors = (state: AppState) => state.ui.debugger.errors;
/**
* Errors in this array will not be shown in the debugger.
* We do this to avoid same error showing multiple times.
*
* Errors ignored:
* W117: `x` is undefined
*/
const errorCodesToIgnoreInDebugger = ["W117"];
function logLatestEvalPropertyErrors(
currentDebuggerErrors: Record<string, Log>,
dataTree: DataTree,
evaluationOrder: Array<string>,
) {
const updatedDebuggerErrors: Record<string, Log> = {
...currentDebuggerErrors,
};
for (const evaluatedPath of evaluationOrder) {
const { entityName, propertyPath } = getEntityNameAndPropertyPath(
evaluatedPath,
);
const entity = dataTree[entityName];
if (isWidget(entity) || isAction(entity)) {
if (propertyPath in entity.logBlackList) {
continue;
}
let allEvalErrors: EvaluationError[] = get(
entity,
getEvalErrorPath(evaluatedPath, false),
[],
);
// If linting flag is not own, filter out all lint errors
if (!getFeatureFlags().LINTING) {
allEvalErrors = allEvalErrors.filter(
(err) => err.errorType !== PropertyEvaluationErrorType.LINT,
);
}
const evaluatedValue = get(
entity,
getEvalValuePath(evaluatedPath, false),
);
const evalErrors: EvaluationError[] = [];
const evalWarnings: EvaluationError[] = [];
for (const err of allEvalErrors) {
if (
err.severity === Severity.WARNING &&
!errorCodesToIgnoreInDebugger.includes(err.code || "")
) {
evalWarnings.push(err);
}
if (err.severity === Severity.ERROR) {
evalErrors.push(err);
}
}
const idField = isWidget(entity) ? entity.widgetId : entity.actionId;
const nameField = isWidget(entity) ? entity.widgetName : entity.name;
const entityType = isWidget(entity)
? ENTITY_TYPE.WIDGET
: ENTITY_TYPE.ACTION;
const debuggerKeys = [
{
key: `${idField}-${propertyPath}`,
errors: evalErrors,
},
{
key: `${idField}-${propertyPath}-warning`,
errors: evalWarnings,
isWarning: true,
},
];
for (const { errors, isWarning, key: debuggerKey } of debuggerKeys) {
// if dataTree has error but debugger does not -> add
// if debugger has error and data tree has error -> update error
// if debugger has error but data tree does not -> remove
// if debugger or data tree does not have an error -> no change
if (errors.length) {
// TODO Rank and set the most critical error
// const error = evalErrors[0];
// Reformatting eval errors here to a format usable by the debugger
const errorMessages = errors.map((e) => {
// Error format required for the debugger
return {
message: e.errorMessage,
type: e.errorType,
};
});
const analyticsData = isWidget(entity)
? {
widgetType: entity.type,
}
: {};
// Add or update
AppsmithConsole.addError(
{
id: debuggerKey,
logType: isWarning ? LOG_TYPE.EVAL_WARNING : LOG_TYPE.EVAL_ERROR,
// Unless the intention is to change the message shown in the debugger please do not
// change the text shown here
text: createMessage(VALUE_IS_INVALID, propertyPath),
messages: errorMessages,
source: {
id: idField,
name: nameField,
type: entityType,
propertyPath: propertyPath,
},
state: {
[propertyPath]: evaluatedValue,
},
analytics: analyticsData,
},
isWarning ? Severity.WARNING : Severity.ERROR,
);
} else if (debuggerKey in updatedDebuggerErrors) {
AppsmithConsole.deleteError(debuggerKey);
}
}
}
}
}
export function* evalErrorHandler(
errors: EvalError[],
dataTree?: DataTree,
evaluationOrder?: Array<string>,
): any {
if (dataTree && evaluationOrder) {
const currentDebuggerErrors: Record<string, Log> = yield select(
getDebuggerErrors,
);
// Update latest errors to the debugger
logLatestEvalPropertyErrors(
currentDebuggerErrors,
dataTree,
evaluationOrder,
);
}
errors.forEach((error) => {
switch (error.type) {
case EvalErrorTypes.CYCLICAL_DEPENDENCY_ERROR: {
if (error.context) {
// Add more info about node for the toast
const { dependencyMap, diffs, entityType, node } = error.context;
Toaster.show({
text: `${error.message} Node was: ${node}`,
variant: Variant.danger,
});
AppsmithConsole.error({
text: `${error.message} Node was: ${node}`,
});
// Send the generic error message to sentry for better grouping
Sentry.captureException(new Error(error.message), {
tags: {
node,
entityType,
},
extra: {
dependencyMap,
diffs,
},
// Level is warning because it could be a user error
level: Sentry.Severity.Warning,
});
// Log an analytics event for cyclical dep errors
AnalyticsUtil.logEvent("CYCLICAL_DEPENDENCY_ERROR", {
node,
entityType,
// Level is warning because it could be a user error
level: Sentry.Severity.Warning,
});
}
break;
}
case EvalErrorTypes.EVAL_TREE_ERROR: {
Toaster.show({
text: createMessage(ERROR_EVAL_ERROR_GENERIC),
variant: Variant.danger,
});
break;
}
case EvalErrorTypes.BAD_UNEVAL_TREE_ERROR: {
Sentry.captureException(error);
break;
}
case EvalErrorTypes.EVAL_TRIGGER_ERROR: {
log.error(error);
const message = createMessage(ERROR_EVAL_TRIGGER, error.message);
Toaster.show({
text: message,
variant: Variant.danger,
showDebugButton: true,
});
AppsmithConsole.error({
text: message,
});
throw new TriggerEvaluationError(message);
}
case EvalErrorTypes.EVAL_PROPERTY_ERROR: {
log.debug(error);
break;
}
case EvalErrorTypes.PARSE_JS_ERROR: {
AppsmithConsole.addError({
id: error?.context?.id,
logType: LOG_TYPE.JS_PARSE_ERROR,
text: createMessage(PARSE_JS_FUNCTION_ERROR, error.message),
source: {
type: ENTITY_TYPE.JSACTION,
name: error?.context?.name,
id: error?.context?.id,
},
});
break;
}
default: {
Sentry.captureException(error);
log.debug(error);
}
}
});
}
export function* logSuccessfulBindings(
unEvalTree: DataTree,
dataTree: DataTree,
evaluationOrder: string[],
) {
const appMode = yield select(getAppMode);
if (appMode === APP_MODE.PUBLISHED) return;
if (!evaluationOrder) return;
evaluationOrder.forEach((evaluatedPath) => {
const { entityName, propertyPath } = getEntityNameAndPropertyPath(
evaluatedPath,
);
const entity = dataTree[entityName];
if (isAction(entity) || isWidget(entity)) {
const unevalValue = get(unEvalTree, evaluatedPath);
const entityType = isAction(entity) ? entity.pluginType : entity.type;
const isABinding = find(entity.dynamicBindingPathList, {
key: propertyPath,
});
const logBlackList = entity.logBlackList;
const errors: EvaluationError[] = get(
dataTree,
getEvalErrorPath(evaluatedPath),
[],
) as EvaluationError[];
const criticalErrors = errors.filter(
(error) => error.errorType !== PropertyEvaluationErrorType.LINT,
);
const hasErrors = criticalErrors.length > 0;
if (isABinding && !hasErrors && !(propertyPath in logBlackList)) {
AnalyticsUtil.logEvent("BINDING_SUCCESS", {
unevalValue,
entityType,
propertyPath,
});
}
}
});
}
export function* postEvalActionDispatcher(
actions: Array<ReduxAction<unknown> | ReduxActionWithoutPayload>,
) {
for (const action of actions) {
yield put(action);
}
}
// We update the data tree definition after every eval so that autocomplete
// is accurate
export function* updateTernDefinitions(
dataTree: DataTree,
updates?: DataTreeDiff[],
) {
let shouldUpdate: boolean;
// No updates means it was a first Eval
if (!updates) {
shouldUpdate = true;
} else if (updates.length === 0) {
// update length is 0 means no significant updates
shouldUpdate = false;
} else {
// Only when new field is added or deleted, we want to re create the def
shouldUpdate = some(updates, (update) => {
return (
update.event === DataTreeDiffEvent.NEW ||
update.event === DataTreeDiffEvent.DELETE
);
});
}
if (shouldUpdate) {
const start = performance.now();
const { def, entityInfo } = dataTreeTypeDefCreator(dataTree);
TernServer.updateDef("DATA_TREE", def, entityInfo);
const end = performance.now();
log.debug("Tern", { updates });
log.debug("Tern definitions updated took ", (end - start).toFixed(2));
}
}