Skip to content

Commit

Permalink
🚸 Display error toast when script or set vari…
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Jun 11, 2024
1 parent d80b3ea commit 233ff91
Show file tree
Hide file tree
Showing 15 changed files with 151 additions and 50 deletions.
13 changes: 9 additions & 4 deletions apps/builder/src/components/inputs/RadioButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ type Props<T extends string> = {
value?: T
defaultValue?: T
direction?: 'row' | 'column'
size?: 'md' | 'sm'
onSelect: (newValue: T) => void
}
export const RadioButtons = <T extends string>({
options,
value,
defaultValue,
direction = 'row',
size = 'md',
onSelect,
}: Props<T>) => {
const { getRootProps, getRadioProps } = useRadioGroup({
Expand All @@ -36,7 +38,7 @@ export const RadioButtons = <T extends string>({
{options.map((item) => {
const radio = getRadioProps({ value: parseValue(item) })
return (
<RadioCard key={parseValue(item)} {...radio}>
<RadioCard key={parseValue(item)} {...radio} size={size}>
{parseLabel(item)}
</RadioCard>
)
Expand All @@ -45,7 +47,9 @@ export const RadioButtons = <T extends string>({
)
}

export const RadioCard = (props: UseRadioProps & { children: ReactNode }) => {
export const RadioCard = (
props: UseRadioProps & { children: ReactNode; size?: 'md' | 'sm' }
) => {
const { getInputProps, getCheckboxProps } = useRadio(props)

const input = getInputProps()
Expand All @@ -68,10 +72,11 @@ export const RadioCard = (props: UseRadioProps & { children: ReactNode }) => {
_active={{
bgColor: useColorModeValue('gray.200', 'gray.600'),
}}
px={5}
py={2}
px={props.size === 'sm' ? 3 : 5}
py={props.size === 'sm' ? 1 : 2}
transition="background-color 150ms, color 150ms, border 150ms"
justifyContent="center"
fontSize={props.size === 'sm' ? 'sm' : undefined}
>
{props.children}
</Flex>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { TextInput, Textarea } from '@/components/inputs'
import { isDefined } from '@typebot.io/lib'
import { useTypebot } from '@/features/editor/providers/TypebotProvider'
import { isInputBlock } from '@typebot.io/schemas/helpers'
import { RadioButtons } from '@/components/inputs/RadioButtons'

type Props = {
options: SetVariableBlock['options']
Expand Down Expand Up @@ -172,6 +173,14 @@ const SetVariableValue = ({
})
}

const updateIsCode = (radio: 'Text' | 'Code') => {
if (options?.type && options.type !== 'Custom') return
onOptionsChange({
...options,
isCode: radio === 'Code',
})
}

switch (options?.type) {
case 'Custom':
case undefined:
Expand All @@ -186,11 +195,31 @@ const SetVariableValue = ({
}
onCheckChange={updateClientExecution}
/>
<CodeEditor
defaultValue={options?.expressionToEvaluate ?? ''}
onChange={updateExpression}
lang="javascript"
/>
<Stack>
<RadioButtons
size="sm"
options={['Text', 'Code']}
defaultValue={
options?.isCode ?? defaultSetVariableOptions.isCode
? 'Code'
: 'Text'
}
onSelect={updateIsCode}
/>
{options?.isCode === undefined || options.isCode ? (
<CodeEditor
defaultValue={options?.expressionToEvaluate ?? ''}
onChange={updateExpression}
lang="javascript"
/>
) : (
<Textarea
defaultValue={options?.expressionToEvaluate ?? ''}
onChange={updateExpression}
width="full"
/>
)}
</Stack>
</>
)
case 'Map item with same index': {
Expand Down
9 changes: 9 additions & 0 deletions apps/docs/openapi/viewer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12396,6 +12396,9 @@
"content": {
"type": "string"
},
"isCode": {
"type": "boolean"
},
"args": {
"type": "array",
"items": {
Expand Down Expand Up @@ -12509,6 +12512,9 @@
"content": {
"type": "string"
},
"isCode": {
"type": "boolean"
},
"args": {
"type": "array",
"items": {
Expand Down Expand Up @@ -12677,6 +12683,9 @@
"content": {
"type": "string"
},
"isCode": {
"type": "boolean"
},
"args": {
"type": "array",
"items": {
Expand Down
53 changes: 40 additions & 13 deletions packages/bot-engine/blocks/logic/setVariable/executeSetVariable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ import {
parseTranscriptMessageText,
} from '@typebot.io/logic/computeResultTranscript'
import prisma from '@typebot.io/lib/prisma'
import { sessionOnlySetVariableOptions } from '@typebot.io/schemas/features/blocks/logic/setVariable/constants'
import {
defaultSetVariableOptions,
sessionOnlySetVariableOptions,
} from '@typebot.io/schemas/features/blocks/logic/setVariable/constants'
import { createCodeRunner } from '@typebot.io/variables/codeRunners'
import { stringifyError } from '@typebot.io/lib/stringifyError'

export const executeSetVariable = async (
state: SessionState,
Expand All @@ -34,6 +38,9 @@ export const executeSetVariable = async (
block.id
)
const isCustomValue = !block.options.type || block.options.type === 'Custom'
const isCode =
(!block.options.type || block.options.type === 'Custom') &&
(block.options.isCode ?? defaultSetVariableOptions.isCode)
if (
expressionToEvaluate &&
!state.whatsApp &&
Expand All @@ -50,21 +57,25 @@ export const executeSetVariable = async (
{
type: 'setVariable',
setVariable: {
scriptToExecute,
scriptToExecute: {
...scriptToExecute,
isCode,
},
},
expectsDedicatedReply: true,
},
],
}
}
const evaluatedExpression = expressionToEvaluate
? evaluateSetVariableExpression(variables)(expressionToEvaluate)
: undefined
const { value, error } =
(expressionToEvaluate
? evaluateSetVariableExpression(variables)(expressionToEvaluate)
: undefined) ?? {}
const existingVariable = variables.find(byId(block.options.variableId))
if (!existingVariable) return { outgoingEdgeId: block.outgoingEdgeId }
const newVariable = {
...existingVariable,
value: evaluatedExpression,
value,
}
const { newSetVariableHistory, updatedState } = updateVariablesInSession({
state,
Expand All @@ -85,24 +96,40 @@ export const executeSetVariable = async (
outgoingEdgeId: block.outgoingEdgeId,
newSessionState: updatedState,
newSetVariableHistory,
logs:
error && isCode
? [
{
status: 'error',
description: 'Error evaluating Set variable code',
details: error,
},
]
: undefined,
}
}

const evaluateSetVariableExpression =
(variables: Variable[]) =>
(str: string): unknown => {
(str: string): { value: unknown; error?: string } => {
const isSingleVariable =
str.startsWith('{{') && str.endsWith('}}') && str.split('{{').length === 2
if (isSingleVariable) return parseVariables(variables)(str)
if (isSingleVariable) return { value: parseVariables(variables)(str) }
// To avoid octal number evaluation
if (!isNaN(str as unknown as number) && /0[^.].+/.test(str)) return str
if (!isNaN(str as unknown as number) && /0[^.].+/.test(str))
return { value: str }
try {
const body = parseVariables(variables, { fieldToParse: 'id' })(str)
return createCodeRunner({ variables })(
body.includes('return ') ? body : `return ${body}`
)
return {
value: createCodeRunner({ variables })(
body.includes('return ') ? body : `return ${body}`
),
}
} catch (err) {
return parseVariables(variables)(str)
return {
value: parseVariables(variables)(str),
error: stringifyError(err),
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/embeds/js/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@typebot.io/js",
"version": "0.2.86",
"version": "0.2.87",
"description": "Javascript library to display typebots on your website",
"type": "module",
"main": "dist/index.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,18 +131,18 @@ export const ConversationContainer = (props: Props) => {
)
})

const sendMessage = async (
message: string | undefined,
clientLogs?: ChatLog[]
) => {
if (clientLogs) {
props.onNewLogs?.(clientLogs)
await saveClientLogsQuery({
apiHost: props.context.apiHost,
sessionId: props.initialChatReply.sessionId,
clientLogs,
})
}
const saveLogs = async (clientLogs?: ChatLog[]) => {
if (!clientLogs) return
props.onNewLogs?.(clientLogs)
if (props.context.isPreview) return
await saveClientLogsQuery({
apiHost: props.context.apiHost,
sessionId: props.initialChatReply.sessionId,
clientLogs,
})
}

const sendMessage = async (message: string | undefined) => {
setHasError(false)
const currentInputBlock = [...chatChunks()].pop()?.input
if (currentInputBlock?.id && props.onAnswer && message)
Expand Down Expand Up @@ -288,9 +288,10 @@ export const ConversationContainer = (props: Props) => {
},
onMessageStream: streamMessage,
})
if (response && 'logs' in response) saveLogs(response.logs)
if (response && 'replyToSend' in response) {
setIsSending(false)
sendMessage(response.replyToSend, response.logs)
sendMessage(response.replyToSend)
return
}
if (response && 'blockedPopupUrl' in response)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
import type { ScriptToExecute } from '@typebot.io/schemas'
import { stringifyError } from '@typebot.io/lib/stringifyError'
import type { ChatLog, ScriptToExecute } from '@typebot.io/schemas'

// eslint-disable-next-line @typescript-eslint/no-empty-function
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor

export const executeScript = async ({ content, args }: ScriptToExecute) => {
export const executeScript = async ({
content,
args,
}: ScriptToExecute): Promise<void | { logs: ChatLog[] }> => {
try {
const func = AsyncFunction(
...args.map((arg) => arg.id),
parseContent(content)
)
await func(...args.map((arg) => arg.value))
} catch (err) {
console.warn('Script threw an error:', err)
return {
logs: [
{
status: 'error',
description: 'Script block failed to execute',
details: stringifyError(err),
},
],
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import type { ScriptToExecute } from '@typebot.io/schemas'
import type { ChatLog, ScriptToExecute } from '@typebot.io/schemas'
import { safeStringify } from '@typebot.io/lib/safeStringify'
import { stringifyError } from '@typebot.io/lib/stringifyError'

// eslint-disable-next-line @typescript-eslint/no-empty-function
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor

export const executeSetVariable = async ({
content,
args,
}: ScriptToExecute): Promise<{ replyToSend: string | undefined }> => {
isCode,
}: ScriptToExecute): Promise<{
replyToSend: string | undefined
logs?: ChatLog[]
}> => {
try {
// To avoid octal number evaluation
if (!isNaN(content as unknown as number) && /0[^.].+/.test(content))
Expand All @@ -26,6 +31,15 @@ export const executeSetVariable = async ({
console.error(err)
return {
replyToSend: safeStringify(content) ?? undefined,
logs: isCode
? [
{
status: 'error',
description: 'Failed to execute Set Variable code',
details: stringifyError(err),
},
]
: undefined,
}
}
}
1 change: 1 addition & 0 deletions packages/embeds/js/src/utils/executeClientSideActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const executeClientSideAction = async ({
}: Props): Promise<
| { blockedPopupUrl: string }
| { replyToSend: string | undefined; logs?: ChatLog[] }
| { logs: ChatLog[] }
| void
> => {
if ('chatwoot' in clientSideAction) {
Expand Down
2 changes: 1 addition & 1 deletion packages/embeds/nextjs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@typebot.io/nextjs",
"version": "0.2.86",
"version": "0.2.87",
"description": "Convenient library to display typebots on your Next.js website",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
2 changes: 1 addition & 1 deletion packages/embeds/react/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@typebot.io/react",
"version": "0.2.86",
"version": "0.2.87",
"description": "Convenient library to display typebots on your React app",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
6 changes: 6 additions & 0 deletions packages/lib/stringifyError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const stringifyError = (err: unknown): string =>
typeof err === 'string'
? err
: err instanceof Error
? err.name + ': ' + err.message
: JSON.stringify(err)
Loading

0 comments on commit 233ff91

Please sign in to comment.