Underground-Digital/Workflow-Engine
0
1import { MAX_VAR_KEY_LENGTH, VAR_ITEM_TEMPLATE, VAR_ITEM_TEMPLATE_IN_WORKFLOW, getMaxVarNameLength } from '@/config'2import { CONTEXT_PLACEHOLDER_TEXT, HISTORY_PLACEHOLDER_TEXT, PRE_PROMPT_PLACEHOLDER_TEXT, QUERY_PLACEHOLDER_TEXT } from '@/app/components/base/prompt-editor/constants'3import { InputVarType } from '@/app/components/workflow/types'4 5const otherAllowedRegex = /^[a-zA-Z0-9_]+$/6 7export const getNewVar = (key: string, type: string) => {8 const { max_length, ...rest } = VAR_ITEM_TEMPLATE9 if (type !== 'string') {10 return {11 ...rest,12 type: type || 'string',13 key,14 name: key.slice(0, getMaxVarNameLength(key)),15 }16 }17 return {18 ...VAR_ITEM_TEMPLATE,19 type: type || 'string',20 key,21 name: key.slice(0, getMaxVarNameLength(key)),22 }23}24 25export const getNewVarInWorkflow = (key: string, type = InputVarType.textInput) => {26 const { max_length, ...rest } = VAR_ITEM_TEMPLATE_IN_WORKFLOW27 if (type !== InputVarType.textInput) {28 return {29 ...rest,30 type,31 variable: key,32 label: key.slice(0, getMaxVarNameLength(key)),33 }34 }35 return {36 ...VAR_ITEM_TEMPLATE_IN_WORKFLOW,37 type,38 variable: key,39 label: key.slice(0, getMaxVarNameLength(key)),40 }41}42 43export const checkKey = (key: string, canBeEmpty?: boolean) => {44 if (key.length === 0 && !canBeEmpty)45 return 'canNoBeEmpty'46 47 if (canBeEmpty && key === '')48 return true49 50 if (key.length > MAX_VAR_KEY_LENGTH)51 return 'tooLong'52 53 if (otherAllowedRegex.test(key)) {54 if (/[0-9]/.test(key[0]))55 return 'notStartWithNumber'56 57 return true58 }59 return 'notValid'60}61 62export const checkKeys = (keys: string[], canBeEmpty?: boolean) => {63 let isValid = true64 let errorKey = ''65 let errorMessageKey = ''66 keys.forEach((key) => {67 if (!isValid)68 return69 70 const res = checkKey(key, canBeEmpty)71 if (res !== true) {72 isValid = false73 errorKey = key74 errorMessageKey = res75 }76 })77 return { isValid, errorKey, errorMessageKey }78}79 80const varRegex = /\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g81export const getVars = (value: string) => {82 if (!value)83 return []84 85 const keys = value.match(varRegex)?.filter((item) => {86 return ![CONTEXT_PLACEHOLDER_TEXT, HISTORY_PLACEHOLDER_TEXT, QUERY_PLACEHOLDER_TEXT, PRE_PROMPT_PLACEHOLDER_TEXT].includes(item)87 }).map((item) => {88 return item.replace('{{', '').replace('}}', '')89 }).filter(key => key.length <= MAX_VAR_KEY_LENGTH) || []90 const keyObj: Record<string, boolean> = {}91 // remove duplicate keys92 const res: string[] = []93 keys.forEach((key) => {94 if (keyObj[key])95 return96 97 keyObj[key] = true98 res.push(key)99 })100 return res101}102 