2
0

♻️ Introduce typebot v6 with events (#1013)

Closes #885
This commit is contained in:
Baptiste Arnaud
2023-11-08 15:34:16 +01:00
committed by GitHub
parent 68e4fc71fb
commit 35300eaf34
634 changed files with 58971 additions and 31449 deletions

View File

@ -1,6 +1,7 @@
import { Prisma, PrismaClient } from '@typebot.io/prisma'
import { InputBlockType, Typebot } from '@typebot.io/schemas'
import { Block, Typebot } from '@typebot.io/schemas'
import { deleteFilesFromBucket } from '../../s3/deleteFilesFromBucket'
import { InputBlockType } from '@typebot.io/schemas/features/blocks/inputs/constants'
type ArchiveResultsProps = {
typebot: Pick<Typebot, 'groups'>
@ -14,7 +15,7 @@ export const archiveResults =
async ({ typebot, resultsFilter }: ArchiveResultsProps) => {
const batchSize = 100
const fileUploadBlockIds = typebot.groups
.flatMap((group) => group.blocks)
.flatMap<Block>((group) => group.blocks)
.filter((block) => block.type === InputBlockType.FILE)
.map((block) => block.id)

View File

@ -0,0 +1,24 @@
import { Block, Group } from '@typebot.io/schemas'
export const getBlockById = (
blockId: string,
groups: Group[]
): { block: Block; group: Group; blockIndex: number; groupIndex: number } => {
for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
for (
let blockIndex = 0;
blockIndex < groups[groupIndex].blocks.length;
blockIndex++
) {
if (groups[groupIndex].blocks[blockIndex].id === blockId) {
return {
block: groups[groupIndex].blocks[blockIndex],
group: groups[groupIndex],
blockIndex,
groupIndex,
}
}
}
}
throw new Error(`Block with id ${blockId} was not found`)
}

View File

@ -0,0 +1,15 @@
import { PublicTypebot, PublicTypebotV6 } from '@typebot.io/schemas'
import { migrateTypebotFromV3ToV4 } from './migrateTypebotFromV3ToV4'
import { migrateTypebotFromV5ToV6 } from './migrateTypebotFromV5ToV6'
export const migrateTypebot = async (
typebot: PublicTypebot
): Promise<PublicTypebotV6> => {
if (typebot.version === '6') return typebot
let migratedTypebot: any = typebot
if (migratedTypebot.version === '3')
migratedTypebot = await migrateTypebotFromV3ToV4(typebot)
if (migratedTypebot.version === '4' || migratedTypebot.version === '5')
migratedTypebot = migrateTypebotFromV5ToV6(migratedTypebot)
return migratedTypebot
}

View File

@ -0,0 +1,30 @@
import {
PublicTypebot,
PublicTypebotV6,
Typebot,
TypebotV6,
} from '@typebot.io/schemas'
import { migrateTypebotFromV3ToV4 } from './migrateTypebotFromV3ToV4'
import { migrateTypebotFromV5ToV6 } from './migrateTypebotFromV5ToV6'
export const migrateTypebot = async (typebot: Typebot): Promise<TypebotV6> => {
if (typebot.version === '6') return typebot
let migratedTypebot: any = typebot
if (migratedTypebot.version === '3')
migratedTypebot = await migrateTypebotFromV3ToV4(typebot)
if (migratedTypebot.version === '4' || migratedTypebot.version === '5')
migratedTypebot = migrateTypebotFromV5ToV6(migratedTypebot)
return migratedTypebot
}
export const migratePublicTypebot = async (
typebot: PublicTypebot
): Promise<PublicTypebotV6> => {
if (typebot.version === '6') return typebot
let migratedTypebot: any = typebot
if (migratedTypebot.version === '3')
migratedTypebot = await migrateTypebotFromV3ToV4(typebot)
if (migratedTypebot.version === '4' || migratedTypebot.version === '5')
migratedTypebot = migrateTypebotFromV5ToV6(migratedTypebot)
return migratedTypebot
}

View File

@ -1,43 +1,48 @@
import { PrismaClient, Webhook as WebhookFromDb } from '@typebot.io/prisma'
import { Webhook as WebhookFromDb } from '@typebot.io/prisma'
import {
Block,
Typebot,
BlockV5,
PublicTypebotV5,
TypebotV5,
Webhook,
defaultWebhookAttributes,
} from '@typebot.io/schemas'
import { isWebhookBlock } from '../utils'
import { HttpMethod } from '@typebot.io/schemas/features/blocks/integrations/webhook/enums'
import { isWebhookBlock, isDefined } from '../utils'
import prisma from '../prisma'
import {
HttpMethod,
defaultWebhookAttributes,
} from '@typebot.io/schemas/features/blocks/integrations/webhook/constants'
export const migrateTypebotFromV3ToV4 =
(prisma: PrismaClient) =>
async (
typebot: Typebot
): Promise<Omit<Typebot, 'version'> & { version: '4' }> => {
if (typebot.version === '4')
return typebot as Omit<Typebot, 'version'> & { version: '4' }
const webhookBlocks = typebot.groups
.flatMap((group) => group.blocks)
.filter(isWebhookBlock)
const webhooks = await prisma.webhook.findMany({
where: {
id: {
in: webhookBlocks.map((block) => block.webhookId as string),
},
export const migrateTypebotFromV3ToV4 = async (
typebot: TypebotV5 | PublicTypebotV5
): Promise<Omit<TypebotV5 | PublicTypebotV5, 'version'> & { version: '4' }> => {
if (typebot.version === '4')
return typebot as Omit<TypebotV5, 'version'> & { version: '4' }
const webhookBlocks = typebot.groups
.flatMap((group) => group.blocks)
.filter(isWebhookBlock)
const webhooks = await prisma.webhook.findMany({
where: {
id: {
in: webhookBlocks
.map((block) => ('webhookId' in block ? block.webhookId : undefined))
.filter(isDefined),
},
})
return {
...typebot,
version: '4',
groups: typebot.groups.map((group) => ({
...group,
blocks: group.blocks.map(migrateWebhookBlock(webhooks)),
})),
}
},
})
return {
...typebot,
version: '4',
groups: typebot.groups.map((group) => ({
...group,
blocks: group.blocks.map(migrateWebhookBlock(webhooks)),
})),
}
}
const migrateWebhookBlock =
(webhooks: WebhookFromDb[]) =>
(block: Block): Block => {
(block: BlockV5): BlockV5 => {
if (!isWebhookBlock(block)) return block
const webhook = webhooks.find((webhook) => webhook.id === block.webhookId)
return {
@ -56,7 +61,7 @@ const migrateWebhookBlock =
}
: {
...defaultWebhookAttributes,
id: block.webhookId ?? '',
id: 'webhookId' in block ? block.webhookId ?? '' : '',
},
},
}

View File

@ -0,0 +1,125 @@
import {
BlockV5,
BlockV6,
GoogleSheetsBlockV5,
GoogleSheetsBlockV6,
PublicTypebotV5,
PublicTypebotV6,
TypebotV5,
TypebotV6,
} from '@typebot.io/schemas'
import { IntegrationBlockType } from '@typebot.io/schemas/features/blocks/integrations/constants'
import { GoogleSheetsAction } from '@typebot.io/schemas/features/blocks/integrations/googleSheets/constants'
import { ComparisonOperators } from '@typebot.io/schemas/features/blocks/logic/condition/constants'
import { createId } from '@paralleldrive/cuid2'
import { EventType } from '@typebot.io/schemas/features/events/constants'
import { byId } from '../utils'
export const migrateTypebotFromV5ToV6 = async (
typebot: TypebotV5 | PublicTypebotV5
): Promise<TypebotV6 | PublicTypebotV6> => {
const startGroup = typebot.groups.find((group) =>
group.blocks.some((b) => b.type === 'start')
)
if (!startGroup) throw new Error('Start group not found')
const startBlock = startGroup?.blocks.find((b) => b.type === 'start')
if (!startBlock) throw new Error('Start block not found')
const startOutgoingEdge = typebot.edges.find(byId(startBlock.outgoingEdgeId))
return {
...typebot,
groups: migrateGroups(
typebot.groups.filter((g) => g.blocks.some((b) => b.type !== 'start'))
),
version: '6',
events: [
{
id: startGroup.id,
type: EventType.START,
graphCoordinates: startGroup.graphCoordinates,
outgoingEdgeId: startBlock.outgoingEdgeId,
},
],
edges: startOutgoingEdge
? [
{
...startOutgoingEdge,
from: {
eventId: startGroup.id,
},
},
...typebot.edges.filter((e) => e.id !== startOutgoingEdge.id),
]
: typebot.edges,
}
}
const migrateGroups = (groups: TypebotV5['groups']): TypebotV6['groups'] =>
groups.map((group) => ({
...group,
blocks: migrateBlocksFromV1ToV2(group.blocks),
}))
const migrateBlocksFromV1ToV2 = (
blocks: TypebotV5['groups'][0]['blocks']
): BlockV6[] =>
(
blocks.filter((block) => block.type !== 'start') as Exclude<
BlockV5,
{ type: 'start' }
>[]
).map((block) => {
if (block.type === IntegrationBlockType.GOOGLE_SHEETS) {
return {
...block,
options: migrateGoogleSheetsOptions(block.options),
}
}
return block
})
const migrateGoogleSheetsOptions = (
options: GoogleSheetsBlockV5['options']
): GoogleSheetsBlockV6['options'] => {
if (!options) return
if (options.action === GoogleSheetsAction.GET) {
if (options.filter || !options.referenceCell) return options
return {
...options,
filter: {
comparisons: [
{
id: createId(),
column: options.referenceCell?.column,
comparisonOperator: ComparisonOperators.EQUAL,
value: options.referenceCell?.value,
},
],
},
}
}
if (options.action === GoogleSheetsAction.INSERT_ROW) {
return options
}
if (options.action === GoogleSheetsAction.UPDATE_ROW) {
if (options.filter || !options.referenceCell) return options
return {
...options,
filter: {
comparisons: [
{
id: createId(),
column: options.referenceCell?.column,
comparisonOperator: ComparisonOperators.EQUAL,
value: options.referenceCell?.value,
},
],
},
}
}
return options
}

View File

@ -15,7 +15,7 @@
"@types/nodemailer": "6.4.8",
"next": "13.5.4",
"nodemailer": "6.9.3",
"typescript": "5.1.6"
"typescript": "5.2.2"
},
"peerDependencies": {
"next": "13.0.0",

View File

@ -1,4 +1,4 @@
import { VideoBubbleContentType } from '@typebot.io/schemas/features/blocks/bubbles/video/enums'
import { VideoBubbleContentType } from '@typebot.io/schemas/features/blocks/bubbles/video/constants'
const vimeoRegex = /vimeo\.com\/(\d+)/
const youtubeRegex =

View File

@ -7,7 +7,7 @@ import {
WorkspaceRole,
} from '@typebot.io/prisma'
import { createId } from '@paralleldrive/cuid2'
import { Typebot, Webhook } from '@typebot.io/schemas'
import { Typebot, TypebotV6, Webhook } from '@typebot.io/schemas'
import { readFileSync } from 'fs'
import { proWorkspaceId, userId } from './databaseSetup'
import {
@ -74,20 +74,24 @@ export const importTypebotInDatabase = async (
path: string,
updates?: Partial<Typebot>
) => {
const typebot: Typebot = {
...JSON.parse(readFileSync(path).toString()),
const typebotFile = JSON.parse(readFileSync(path).toString())
const typebot = {
events: null,
...typebotFile,
workspaceId: proWorkspaceId,
...updates,
version: '3',
}
await prisma.typebot.create({
data: parseCreateTypebot(typebot),
})
return prisma.publicTypebot.create({
data: parseTypebotToPublicTypebot(
updates?.id ? `${updates?.id}-public` : 'publicBot',
typebot
),
data: {
...parseTypebotToPublicTypebot(
updates?.id ? `${updates?.id}-public` : 'publicBot',
typebot
),
events: typebot.events === null ? Prisma.DbNull : typebot.events,
},
})
}
@ -165,7 +169,7 @@ export const createWebhook = async (
})
}
export const createTypebots = async (partialTypebots: Partial<Typebot>[]) => {
export const createTypebots = async (partialTypebots: Partial<TypebotV6>[]) => {
const typebotsWithId = partialTypebots.map((typebot) => {
const typebotId = typebot.id ?? createId()
return {
@ -178,9 +182,9 @@ export const createTypebots = async (partialTypebots: Partial<Typebot>[]) => {
data: typebotsWithId.map(parseTestTypebot).map(parseCreateTypebot),
})
return prisma.publicTypebot.createMany({
data: typebotsWithId.map((t) =>
parseTypebotToPublicTypebot(t.publicId, parseTestTypebot(t))
),
data: typebotsWithId.map((t) => ({
...parseTypebotToPublicTypebot(t.publicId, parseTestTypebot(t)),
})) as any,
})
}
@ -193,7 +197,11 @@ export const updateTypebot = async (
})
return prisma.publicTypebot.updateMany({
where: { typebotId: partialTypebot.id },
data: partialTypebot,
data: {
...partialTypebot,
events:
partialTypebot.events === null ? Prisma.DbNull : partialTypebot.events,
},
})
}
@ -213,6 +221,7 @@ export const parseCreateTypebot = (typebot: Typebot) => ({
typebot.resultsTablePreferences === null
? Prisma.DbNull
: typebot.resultsTablePreferences,
events: typebot.events === null ? Prisma.DbNull : typebot.events,
})
const parseUpdateTypebot = (typebot: Partial<Typebot>) => ({
@ -221,4 +230,5 @@ const parseUpdateTypebot = (typebot: Partial<Typebot>) => ({
typebot.resultsTablePreferences === null
? Prisma.DbNull
: typebot.resultsTablePreferences,
events: typebot.events === null ? Prisma.DbNull : typebot.events,
})

View File

@ -1,64 +1,78 @@
import { createId } from '@paralleldrive/cuid2'
import {
Block,
defaultChoiceInputOptions,
defaultSettings,
defaultTheme,
InputBlockType,
ItemType,
BlockV5,
BlockV6,
Group,
PublicTypebot,
Typebot,
TypebotV6,
} from '@typebot.io/schemas'
import { isDefined } from '../utils'
import { proWorkspaceId } from './databaseSetup'
import { InputBlockType } from '@typebot.io/schemas/features/blocks/inputs/constants'
import { EventType } from '@typebot.io/schemas/features/events/constants'
export const parseTestTypebot = (
partialTypebot: Partial<Typebot>
): Typebot => ({
id: createId(),
version: '3',
workspaceId: proWorkspaceId,
folderId: null,
name: 'My typebot',
theme: defaultTheme,
settings: defaultSettings({ isBrandingEnabled: true }),
publicId: null,
updatedAt: new Date(),
createdAt: new Date(),
customDomain: null,
icon: null,
selectedThemeTemplateId: null,
isArchived: false,
isClosed: false,
resultsTablePreferences: null,
whatsAppCredentialsId: null,
variables: [{ id: 'var1', name: 'var1' }],
...partialTypebot,
edges: [
{
id: 'edge1',
from: { groupId: 'group0', blockId: 'block0' },
to: { groupId: 'group1' },
},
],
groups: [
{
id: 'group0',
title: 'Group #0',
blocks: [
{
id: 'block0',
type: 'start',
groupId: 'group0',
label: 'Start',
outgoingEdgeId: 'edge1',
},
],
graphCoordinates: { x: 0, y: 0 },
},
...(partialTypebot.groups ?? []),
],
})
export const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => {
const version = partialTypebot.version ?? ('3' as any)
return {
id: createId(),
version,
workspaceId: proWorkspaceId,
folderId: null,
name: 'My typebot',
theme: {},
settings: {},
publicId: null,
updatedAt: new Date(),
createdAt: new Date(),
customDomain: null,
icon: null,
selectedThemeTemplateId: null,
isArchived: false,
isClosed: false,
resultsTablePreferences: null,
whatsAppCredentialsId: null,
events:
version === '6'
? [
{
id: 'group1',
type: EventType.START,
graphCoordinates: { x: 0, y: 0 },
outgoingEdgeId: 'edge1',
},
]
: null,
variables: [{ id: 'var1', name: 'var1' }],
...partialTypebot,
edges: [
{
id: 'edge1',
from: { blockId: 'block0' },
to: { groupId: 'group1' },
},
],
groups: (version === '6'
? partialTypebot.groups ?? []
: [
{
id: 'group0',
title: 'Group #0',
blocks: [
{
id: 'block0',
type: 'start',
label: 'Start',
outgoingEdgeId: 'edge1',
},
],
graphCoordinates: { x: 0, y: 0 },
},
...(partialTypebot.groups ?? []),
]) as any[],
}
}
export const parseTypebotToPublicTypebot = (
id: string,
@ -72,6 +86,7 @@ export const parseTypebotToPublicTypebot = (
settings: typebot.settings,
variables: typebot.variables,
edges: typebot.edges,
events: typebot.events,
})
type Options = {
@ -79,9 +94,9 @@ type Options = {
}
export const parseDefaultGroupWithBlock = (
block: Partial<Block>,
block: Partial<BlockV6>,
options?: Options
): Pick<Typebot, 'groups'> => ({
): Pick<TypebotV6, 'groups'> => ({
groups: [
{
graphCoordinates: { x: 200, y: 200 },
@ -96,19 +111,17 @@ export const parseDefaultGroupWithBlock = (
{
id: 'item1',
blockId: 'block1',
type: ItemType.BUTTON,
content: 'Go',
},
],
options: defaultChoiceInputOptions,
options: {},
}
: undefined,
{
id: 'block2',
groupId: 'group1',
...block,
} as Block,
].filter(isDefined) as Block[],
} as BlockV5,
].filter(isDefined) as BlockV6[],
title: 'Group #1',
},
],

View File

@ -6,10 +6,10 @@ import {
VariableWithValue,
Typebot,
ResultWithAnswers,
InputBlockType,
AnswerInSessionState,
} from '@typebot.io/schemas'
import { isInputBlock, isDefined, byId, isNotEmpty, isEmpty } from './utils'
import { InputBlockType } from '@typebot.io/schemas/features/blocks/inputs/constants'
export const parseResultHeader = (
typebot: Pick<Typebot, 'groups' | 'variables'>,
@ -18,7 +18,9 @@ export const parseResultHeader = (
): ResultHeaderCell[] => {
const parsedGroups = [
...typebot.groups,
...(linkedTypebots ?? []).flatMap((linkedTypebot) => linkedTypebot.groups),
...(linkedTypebots ?? []).flatMap(
(linkedTypebot) => linkedTypebot.groups as Group[]
),
]
const parsedVariables = [
...typebot.variables,
@ -55,69 +57,71 @@ const parseInputsResultHeader = ({
group.blocks.map((block) => ({
...block,
groupTitle: group.title,
groupId: group.id,
}))
)
.filter((block) => isInputBlock(block)) as (InputBlock & {
groupId: string
groupTitle: string
})[]
).reduce<ResultHeaderCellWithBlock[]>((existingHeaders, inputBlock) => {
if (
existingHeaders.some(
(existingHeader) =>
inputBlock.options.variableId &&
inputBlock.options?.variableId &&
existingHeader.variableIds?.includes(inputBlock.options.variableId)
)
)
return existingHeaders
const matchedVariableName =
inputBlock.options.variableId &&
inputBlock.options?.variableId &&
variables.find(byId(inputBlock.options.variableId))?.name
let label = matchedVariableName ?? inputBlock.groupTitle
const existingHeader = existingHeaders.find((h) => h.label === label)
if (existingHeader) {
if (
existingHeader.blocks?.some(
(block) => block.groupId === inputBlock.groupId
) ||
existingHeader.label.includes('Untitled')
) {
const totalPrevious = existingHeaders.filter((h) =>
h.label.includes(label)
).length
const newHeaderCell: ResultHeaderCellWithBlock = {
id: inputBlock.id,
label: label + ` (${totalPrevious})`,
blocks: [
{
id: inputBlock.id,
groupId: inputBlock.groupId,
},
],
blockType: inputBlock.type,
variableIds: inputBlock.options.variableId
? [inputBlock.options.variableId]
: undefined,
const headerWithSameLabel = existingHeaders.find((h) => h.label === label)
if (headerWithSameLabel) {
const shouldMerge = headerWithSameLabel.blocks?.some(
(block) => block.id === inputBlock.id
)
if (shouldMerge) {
const updatedHeaderCell: ResultHeaderCellWithBlock = {
...headerWithSameLabel,
variableIds:
headerWithSameLabel.variableIds && inputBlock.options?.variableId
? headerWithSameLabel.variableIds.concat([
inputBlock.options.variableId,
])
: undefined,
blocks: headerWithSameLabel.blocks.concat({
id: inputBlock.id,
groupId: inputBlock.groupId,
}),
}
return [...existingHeaders, newHeaderCell]
return [
...existingHeaders.filter(
(existingHeader) => existingHeader.label !== label
),
updatedHeaderCell,
]
}
const updatedHeaderCell: ResultHeaderCellWithBlock = {
...existingHeader,
variableIds:
existingHeader.variableIds && inputBlock.options.variableId
? existingHeader.variableIds.concat([inputBlock.options.variableId])
: undefined,
blocks: existingHeader.blocks.concat({
id: inputBlock.id,
groupId: inputBlock.groupId,
}),
const totalPrevious = existingHeaders.filter((h) =>
h.label.includes(label)
).length
const newHeaderCell: ResultHeaderCellWithBlock = {
id: inputBlock.id,
label: label + ` (${totalPrevious})`,
blocks: [
{
id: inputBlock.id,
groupId: inputBlock.groupId,
},
],
blockType: inputBlock.type,
variableIds: inputBlock.options?.variableId
? [inputBlock.options.variableId]
: undefined,
}
return [
...existingHeaders.filter(
(existingHeader) => existingHeader.label !== label
),
updatedHeaderCell,
]
return [...existingHeaders, newHeaderCell]
}
const newHeaderCell: ResultHeaderCellWithBlock = {
@ -130,7 +134,7 @@ const parseInputsResultHeader = ({
},
],
blockType: inputBlock.type,
variableIds: inputBlock.options.variableId
variableIds: inputBlock.options?.variableId
? [inputBlock.options.variableId]
: undefined,
}

View File

@ -9,16 +9,16 @@ import type {
TextInputBlock,
TextBubbleBlock,
WebhookBlock,
BlockType,
ImageBubbleBlock,
VideoBubbleBlock,
BlockWithOptionsType,
} from '@typebot.io/schemas'
import { InputBlockType } from '@typebot.io/schemas/features/blocks/inputs/enums'
import { BubbleBlockType } from '@typebot.io/schemas/features/blocks/bubbles/enums'
import { LogicBlockType } from '@typebot.io/schemas/features/blocks/logic/enums'
import { IntegrationBlockType } from '@typebot.io/schemas/features/blocks/integrations/enums'
import { BubbleBlockType } from '@typebot.io/schemas/features/blocks/bubbles/constants'
import { InputBlockType } from '@typebot.io/schemas/features/blocks/inputs/constants'
import { PictureChoiceBlock } from '@typebot.io/schemas/features/blocks/inputs/pictureChoice'
import { IntegrationBlockType } from '@typebot.io/schemas/features/blocks/integrations/constants'
import { LogicBlockType } from '@typebot.io/schemas/features/blocks/logic/constants'
import { defaultChoiceInputOptions } from '@typebot.io/schemas/features/blocks/inputs/choice/constants'
export const sendRequest = async <ResponseData>(
params:
@ -100,7 +100,10 @@ export const isPictureChoiceInput = (
export const isSingleChoiceInput = (block: Block): block is ChoiceInputBlock =>
block.type === InputBlockType.CHOICE &&
'options' in block &&
!block.options.isMultipleChoice
!(
block.options?.isMultipleChoice ??
defaultChoiceInputOptions.isMultipleChoice
)
export const isConditionBlock = (block: Block): block is ConditionBlock =>
block.type === LogicBlockType.CONDITION
@ -116,11 +119,13 @@ export const isWebhookBlock = (block: Block): block is WebhookBlock =>
IntegrationBlockType.MAKE_COM,
].includes(block.type as IntegrationBlockType)
export const isBubbleBlockType = (type: BlockType): type is BubbleBlockType =>
export const isBubbleBlockType = (
type: Block['type']
): type is BubbleBlockType =>
(Object.values(BubbleBlockType) as string[]).includes(type)
export const blockTypeHasOption = (
type: BlockType
type: Block['type']
): type is BlockWithOptionsType =>
(Object.values(InputBlockType) as string[])
.concat(Object.values(LogicBlockType))
@ -128,7 +133,7 @@ export const blockTypeHasOption = (
.includes(type)
export const blockTypeHasItems = (
type: BlockType
type: Block['type']
): type is
| LogicBlockType.CONDITION
| InputBlockType.CHOICE