@botpress/sdk 2.3.1 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +3 -3
- package/dist/index.js.map +2 -2
- package/package.json +3 -3
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
|
|
2
|
-
> @botpress/sdk@2.
|
|
2
|
+
> @botpress/sdk@2.4.1 build /home/runner/work/botpress/botpress/packages/sdk
|
|
3
3
|
> pnpm build:type && pnpm build:node
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @botpress/sdk@2.
|
|
6
|
+
> @botpress/sdk@2.4.1 build:type /home/runner/work/botpress/botpress/packages/sdk
|
|
7
7
|
> tsc --emitDeclarationOnly --declaration
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
> @botpress/sdk@2.
|
|
10
|
+
> @botpress/sdk@2.4.1 build:node /home/runner/work/botpress/botpress/packages/sdk
|
|
11
11
|
> ts-node -T build.ts
|
|
12
12
|
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/utils/record-utils.ts", "../src/utils/array-utils.ts", "../src/integration/definition/branded-schema.ts", "../src/integration/definition/index.ts", "../src/integration/server/index.ts", "../src/retry.ts", "../src/integration/client/index.ts", "../src/integration/server/action-metadata.ts", "../src/integration/server/context.ts", "../src/base-logger.ts", "../src/integration/server/integration-logger.ts", "../src/integration/implementation.ts", "../src/bot/definition.ts", "../src/bot/merge-bots.ts", "../src/bot/server/index.ts", "../src/bot/bot-logger.ts", "../src/bot/client/index.ts", "../src/bot/server/context.ts", "../src/bot/implementation.ts", "../src/interface/definition.ts", "../src/plugin/definition.ts", "../src/plugin/implementation.ts"],
|
|
4
|
-
"sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n //\n isApiError,\n RuntimeError,\n} from '@botpress/client'\n\nexport {\n DefaultIntegration,\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationLogger,\n IntegrationSpecificClient,\n TagDefinition,\n ConfigurationDefinition,\n AdditionalConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport {\n /**\n * @deprecated use Context exported from '.botpress' instead\n */\n IntegrationContext,\n} from './integration/server'\n\nexport {\n DefaultBot,\n BotDefinition,\n BotDefinitionProps,\n BotImplementation as Bot,\n BotImplementationProps as BotProps,\n BotSpecificClient,\n BotHandlers,\n TagDefinition as BotTagDefinition,\n StateType as BotStateType,\n StateDefinition as BotStateDefinition,\n RecurringEventDefinition as BotRecurringEventDefinition,\n EventDefinition as BotEventDefinition,\n ConfigurationDefinition as BotConfigurationDefinition,\n UserDefinition as BotUserDefinition,\n ConversationDefinition as BotConversationDefinition,\n MessageDefinition as BotMessageDefinition,\n ActionDefinition as BotActionDefinition,\n BotLogger,\n} from './bot'\n\nexport {\n //\n InterfaceDefinition,\n InterfaceDefinitionProps,\n} from './interface'\n\nexport {\n //\n DefaultPlugin,\n PluginDefinition,\n PluginImplementation as Plugin,\n} from './plugin'\n\nexport {\n //\n IntegrationPackage,\n InterfacePackage,\n PluginPackage,\n Package,\n} from './package'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nconst blocSchema = z.union([\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n z.object({ type: z.literal('image'), payload: imageMessageSchema }),\n z.object({ type: z.literal('audio'), payload: audioMessageSchema }),\n z.object({ type: z.literal('video'), payload: videoMessageSchema }),\n z.object({ type: z.literal('file'), payload: fileMessageSchema }),\n z.object({ type: z.literal('location'), payload: locationMessageSchema }),\n])\n\nconst blocsSchema = z.object({\n items: z.array(blocSchema),\n})\n\n/**\n * @deprecated use `text` instead\n */\nexport const markdown = { schema: markdownMessageSchema }\nexport const defaults = {\n text: { schema: textMessageSchema },\n image: { schema: imageMessageSchema },\n audio: { schema: audioMessageSchema },\n video: { schema: videoMessageSchema },\n file: { schema: fileMessageSchema },\n location: { schema: locationMessageSchema },\n carousel: { schema: carouselSchema },\n card: { schema: cardSchema },\n dropdown: { schema: choiceSchema },\n choice: { schema: choiceSchema },\n bloc: { schema: blocsSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import { z } from '@bpinternal/zui'\n\nexport * from '@bpinternal/zui'\n\nexport type GenericZuiSchema<\n A extends Record<string, z.ZodTypeAny> = Record<string, z.ZodTypeAny>,\n R extends z.ZodTypeAny = z.ZodTypeAny\n> = (typeArguments: A) => R\n\nexport type ZuiObjectSchema = z.ZodObject | z.ZodRecord\n\nexport default z\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationTypeHeader = 'x-bp-configuration-type'\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "export const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, V][]\nexport const values = <K extends string, V>(obj: Record<K, V>) => Object.values(obj) as V[]\nexport const mapValues = <K extends string, V, R>(obj: Record<K, V>, fn: (value: V, key: K) => R): Record<K, R> =>\n Object.fromEntries(pairs(obj).map(([key, value]) => [key, fn(value, key)])) as Record<K, R>\n", "export const safePush = <T>(arr: T[] | undefined, ...values: T[]): T[] => (arr ? [...arr, ...values] : [...values])\n", "import * as utils from '../../utils'\nimport { z } from '../../zui'\n\nconst schemaName = Symbol('schemaName')\n\ntype BaseSchemas = Record<string, z.ZodSchema>\n\nexport type SchemaStoreProps<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: {\n schema: TSchemas[K]\n }\n}\n\nexport type BrandedSchema<TSchema extends BaseSchemas[string] = BaseSchemas[string]> = {\n schema: TSchema\n [schemaName]: string\n}\n\nexport type SchemaStore<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: BrandedSchema<TSchemas[K]>\n}\n\nexport const createStore = <TSchemas extends BaseSchemas>(\n props: SchemaStoreProps<TSchemas> | undefined\n): SchemaStore<TSchemas> => {\n if (!props) {\n return {} as SchemaStore<TSchemas>\n }\n const store: SchemaStore<BaseSchemas> = utils.records.mapValues(props, (e, k) => ({ ...e, [schemaName]: k }))\n return store as SchemaStore<TSchemas>\n}\n\nexport const isBranded = (schema: BrandedSchema | { schema: z.ZodSchema }): schema is BrandedSchema => {\n return schemaName in schema && schema[schemaName] !== undefined\n}\n\nexport const getName = (schema: BrandedSchema): string => {\n return schema[schemaName]\n}\n", "import { InterfacePackage } from '../../package'\nimport * as utils from '../../utils'\nimport { z } from '../../zui'\nimport { SchemaStore, BrandedSchema, createStore, isBranded, getName } from './branded-schema'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities, BaseConfigs } from './generic'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n AdditionalConfigurationDefinition,\n} from './types'\n\nexport * from './types'\n\nexport type InterfaceExtension = InterfacePackage & {\n entities: Record<\n string,\n {\n name: string\n schema: z.AnyZodObject\n }\n >\n}\n\nexport type IntegrationDefinitionProps<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: TName\n version: TVersion\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n configurations?: {\n [K in keyof TConfigs]: AdditionalConfigurationDefinition<TConfigs[K]>\n }\n\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n interfaces?: Record<string, InterfaceExtension>\n}\n\ntype EntitiesOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['entities']]: NonNullable<TPackage['definition']['entities']>[K]['schema']\n}\n\ntype ExtensionBuilderInput<TIntegrationEntities extends BaseEntities> = SchemaStore<TIntegrationEntities>\n\ntype ExtensionBuilderOutput<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: ExtensionBuilderInput<TIntegrationEntities>\n) => ExtensionBuilderOutput<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly configurations: this['props']['configurations']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n public readonly interfaces: this['props']['interfaces']\n public constructor(\n public readonly props: IntegrationDefinitionProps<\n TName,\n TVersion,\n TConfig,\n TConfigs,\n TEvents,\n TActions,\n TChannels,\n TStates,\n TEntities\n >\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.configurations = props.configurations\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n this.interfaces = props.interfaces\n }\n\n public extend<P extends InterfacePackage>(\n interfacePkg: P,\n builder: ExtensionBuilder<TEntities, EntitiesOfPackage<P>>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities))\n const unbrandedEntity = utils.records.pairs(extensionBuilderOutput).find(([_k, e]) => !isBranded(e))\n if (unbrandedEntity) {\n // this means the user tried providing a plain schema without referencing an entity from the integration\n throw new Error(\n `Cannot extend interface \"${interfacePkg.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const self = this as utils.types.Writable<IntegrationDefinition>\n self.interfaces ??= {}\n\n const interfaceTypeArguments = utils.records.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema as z.AnyZodObject,\n }))\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n\n const key = entityNames.length === 0 ? interfacePkg.name : `${interfacePkg.name}<${entityNames.join(',')}>`\n\n self.interfaces[key] = {\n ...interfacePkg,\n entities: interfaceTypeArguments,\n }\n\n return this\n }\n}\n", "import { isApiError, Client, RuntimeError } from '@botpress/client'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody } from '../../serve'\nimport { IntegrationSpecificClient } from '../client'\nimport { BaseIntegration } from '../types'\nimport { ActionMetadataStore } from './action-metadata'\nimport { extractContext } from './context'\nimport { IntegrationLogger } from './integration-logger'\nimport {\n CommonHandlerProps,\n IntegrationHandlers,\n WebhookPayload,\n ActionPayload,\n MessagePayload,\n RegisterPayload,\n CreateUserPayload,\n UnregisterPayload,\n CreateConversationPayload,\n} from './types'\n\nexport * from './types'\nexport * from './integration-logger'\n\ntype ServerProps = CommonHandlerProps<BaseIntegration> & {\n req: Request\n instance: IntegrationHandlers<BaseIntegration>\n}\n\nexport const integrationHandler =\n (instance: IntegrationHandlers<BaseIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n retry: retryConfig,\n })\n const client = new IntegrationSpecificClient<BaseIntegration>(vanillaClient)\n const logger = new IntegrationLogger()\n\n const props = {\n ctx,\n req,\n client,\n logger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook(props)\n break\n case 'register':\n response = await onRegister(props)\n break\n case 'unregister':\n response = await onUnregister(props)\n break\n case 'message_created':\n response = await onMessageCreated(props)\n break\n case 'action_triggered':\n response = await onActionTriggered(props)\n break\n case 'ping':\n response = await onPing(props)\n break\n case 'create_user':\n response = await onCreateUser(props)\n break\n case 'create_conversation':\n response = await onCreateConversation(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (error) {\n if (isApiError(error)) {\n const runtimeError = error.type === 'Runtime' ? error : new RuntimeError(error.message, error)\n logger.forBot().error(runtimeError.message)\n\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n\n // prints the error in the integration logs\n console.error(error)\n\n const runtimeError = new RuntimeError(\n 'An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.'\n )\n logger.forBot().error(runtimeError.message)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n }\n\nconst onPing = async (_: ServerProps) => {}\n\nconst onWebhook = async ({ client, ctx, req: incomingRequest, logger, instance }: ServerProps) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<BaseIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<BaseIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async ({ ctx, req, client, logger, instance }: ServerProps) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<BaseIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async ({ req, ctx, client, logger, instance }: ServerProps) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const metadata = new ActionMetadataStore()\n const output = await action({ ctx, input, client, type, logger, metadata })\n\n const response = { output, meta: metadata.toJSON() }\n return {\n body: JSON.stringify(response),\n }\n}\n", "import { RetryConfig, axiosRetry } from '@botpress/client'\n\nexport const retryConfig: RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount) => retryCount * 1000,\n}\n", "/* eslint-disable brace-style */\nimport * as client from '@botpress/client'\nimport * as common from '../types'\nimport * as types from './types'\n\nexport * from './types'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends common.BaseIntegration>\n implements types.ClientOperations<TIntegration>\n{\n public constructor(private readonly _client: client.Client) {}\n\n public createConversation: types.CreateConversation<TIntegration> = ((x) =>\n this._client.createConversation(x)) as types.CreateConversation<TIntegration>\n public getConversation: types.GetConversation<TIntegration> = ((x) =>\n this._client.getConversation(x)) as types.GetConversation<TIntegration>\n public listConversations: types.ListConversations<TIntegration> = ((x) =>\n this._client.listConversations(x)) as types.ListConversations<TIntegration>\n public getOrCreateConversation: types.GetOrCreateConversation<TIntegration> = ((x) =>\n this._client.getOrCreateConversation(x)) as types.GetOrCreateConversation<TIntegration>\n public updateConversation: types.UpdateConversation<TIntegration> = ((x) =>\n this._client.updateConversation(x)) as types.UpdateConversation<TIntegration>\n public deleteConversation: types.DeleteConversation<TIntegration> = ((x) =>\n this._client.deleteConversation(x)) as types.DeleteConversation<TIntegration>\n\n public listParticipants: types.ListParticipants<TIntegration> = ((x) =>\n this._client.listParticipants(x)) as types.ListParticipants<TIntegration>\n public addParticipant: types.AddParticipant<TIntegration> = ((x) =>\n this._client.addParticipant(x)) as types.AddParticipant<TIntegration>\n public getParticipant: types.GetParticipant<TIntegration> = ((x) =>\n this._client.getParticipant(x)) as types.GetParticipant<TIntegration>\n public removeParticipant: types.RemoveParticipant<TIntegration> = ((x) =>\n this._client.removeParticipant(x)) as types.RemoveParticipant<TIntegration>\n\n public createEvent: types.CreateEvent<TIntegration> = ((x) =>\n this._client.createEvent(x)) as types.CreateEvent<TIntegration>\n public getEvent: types.GetEvent<TIntegration> = ((x) => this._client.getEvent(x)) as types.GetEvent<TIntegration>\n public listEvents: types.ListEvents<TIntegration> = ((x) =>\n this._client.listEvents(x)) as types.ListEvents<TIntegration>\n\n public createMessage: types.CreateMessage<TIntegration> = ((x) =>\n this._client.createMessage(x)) as types.CreateMessage<TIntegration>\n public getOrCreateMessage: types.GetOrCreateMessage<TIntegration> = ((x) =>\n this._client.getOrCreateMessage(x)) as types.GetOrCreateMessage<TIntegration>\n public getMessage: types.GetMessage<TIntegration> = ((x) =>\n this._client.getMessage(x)) as types.GetMessage<TIntegration>\n public updateMessage: types.UpdateMessage<TIntegration> = ((x) =>\n this._client.updateMessage(x)) as types.UpdateMessage<TIntegration>\n public listMessages: types.ListMessages<TIntegration> = ((x) =>\n this._client.listMessages(x)) as types.ListMessages<TIntegration>\n public deleteMessage: types.DeleteMessage<TIntegration> = ((x) =>\n this._client.deleteMessage(x)) as types.DeleteMessage<TIntegration>\n\n public createUser: types.CreateUser<TIntegration> = ((x) =>\n this._client.createUser(x)) as types.CreateUser<TIntegration>\n public getUser: types.GetUser<TIntegration> = ((x) => this._client.getUser(x)) as types.GetUser<TIntegration>\n public listUsers: types.ListUsers<TIntegration> = (x) => this._client.listUsers(x)\n public getOrCreateUser: types.GetOrCreateUser<TIntegration> = ((x) =>\n this._client.getOrCreateUser(x)) as types.GetOrCreateUser<TIntegration>\n public updateUser: types.UpdateUser<TIntegration> = ((x) =>\n this._client.updateUser(x)) as types.UpdateUser<TIntegration>\n public deleteUser: types.DeleteUser<TIntegration> = (x) => this._client.deleteUser(x)\n\n public getState: types.GetState<TIntegration> = ((x) => this._client.getState(x)) as types.GetState<TIntegration>\n public setState: types.SetState<TIntegration> = ((x) => this._client.setState(x)) as types.SetState<TIntegration>\n public getOrSetState: types.GetOrSetState<TIntegration> = ((x) =>\n this._client.getOrSetState(x)) as types.GetOrSetState<TIntegration>\n public patchState: types.PatchState<TIntegration> = ((x) =>\n this._client.patchState(x)) as types.PatchState<TIntegration>\n\n public configureIntegration: types.ConfigureIntegration<TIntegration> = (x) => this._client.configureIntegration(x)\n\n public uploadFile: types.UploadFile<TIntegration> = (x) => this._client.uploadFile(x)\n public upsertFile: types.UpsertFile<TIntegration> = (x) => this._client.upsertFile(x)\n public deleteFile: types.DeleteFile<TIntegration> = (x) => this._client.deleteFile(x)\n public listFiles: types.ListFiles<TIntegration> = (x) => this._client.listFiles(x)\n public getFile: types.GetFile<TIntegration> = (x) => this._client.getFile(x)\n public updateFileMetadata: types.UpdateFileMetadata<TIntegration> = (x) => this._client.updateFileMetadata(x)\n}\n", "export type ActionMetadata = {\n cost: number\n}\n\nexport class ActionMetadataStore {\n private _cost: number = 0\n\n public get cost(): number {\n return this._cost\n }\n\n public setCost(cost: number): void {\n this._cost = cost\n }\n\n public toJSON(): ActionMetadata {\n return {\n cost: this.cost,\n }\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n configurationTypeHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../../const'\nimport { IntegrationContext } from './types'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const configurationType = headers[configurationTypeHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configurationType: configurationType ?? null,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import util from 'util'\n\ntype LogLevel = 'info' | 'debug' | 'warn' | 'error'\n\nexport abstract class BaseLogger<TOptions extends object> {\n protected defaultOptions: TOptions\n\n protected constructor(defaultOptions: TOptions) {\n this.defaultOptions = defaultOptions\n }\n\n public abstract with(options: TOptions): BaseLogger<TOptions>\n\n public info(...args: Parameters<typeof console.info>) {\n this._log('info', args)\n }\n\n public debug(...args: Parameters<typeof console.debug>) {\n this._log('debug', args)\n }\n\n public warn(...args: Parameters<typeof console.warn>) {\n this._log('warn', args)\n }\n\n public error(...args: Parameters<typeof console.error>) {\n this._log('error', args)\n }\n\n private _log(level: LogLevel, args: Parameters<typeof console.info>) {\n this._getConsoleMethod(level)(this._serializeMessage(args))\n }\n\n private _serializeMessage(args: Parameters<typeof console.info>) {\n const msg = util.format(...args)\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return this.getJsonMessage(msg)\n } else {\n return msg\n }\n }\n\n protected getJsonMessage(msg: string) {\n return JSON.stringify({ msg, options: this.defaultOptions })\n }\n\n private _getConsoleMethod(level: LogLevel): (...args: any[]) => void {\n switch (level) {\n case 'debug':\n return console.debug\n case 'warn':\n return console.warn\n case 'error':\n return console.error\n default:\n return console.info\n }\n }\n}\n", "import { BaseLogger } from '../../base-logger'\n\ntype IntegrationLogOptions = {\n userId?: string\n conversationId?: string\n visibleToBotOwners?: boolean\n}\n\nexport class IntegrationLogger extends BaseLogger<IntegrationLogOptions> {\n public constructor(options?: IntegrationLogOptions) {\n super({\n visibleToBotOwners: true,\n ...options,\n })\n }\n\n public override with(options: IntegrationLogOptions) {\n return new IntegrationLogger({ ...this.defaultOptions, ...options })\n }\n\n public withUserId(userId: string) {\n return this.with({\n userId,\n })\n }\n\n public withConversationId(conversationId: string) {\n return this.with({\n conversationId,\n })\n }\n\n public withVisibleToBotOwners(visibleToBotOwners: boolean) {\n return this.with({\n visibleToBotOwners,\n })\n }\n\n public forBot() {\n return this.withVisibleToBotOwners(true)\n }\n\n protected override getJsonMessage(msg: string) {\n return JSON.stringify({\n msg,\n //We need to have snake case 'visible_to_bot_owner' since that is how we used to differentiate between bot and integration logs\n visible_to_bot_owner: this.defaultOptions.visibleToBotOwners,\n options: this.defaultOptions,\n })\n }\n}\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport {\n RegisterHandler as RegisterFunction,\n UnregisterHandler as UnregisterFunction,\n WebhookHandler as WebhookFunction,\n CreateUserHandler as CreateUserFunction,\n CreateConversationHandler as CreateConversationFunction,\n ActionHandlers as ActionFunctions,\n ChannelHandlers as ChannelFunctions,\n integrationHandler,\n} from './server'\nimport { BaseIntegration } from './types'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(public readonly props: IntegrationImplementationProps<TIntegration>) {\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler(this as IntegrationImplementation<any>)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { IntegrationPackage, PluginPackage } from '../package'\nimport { SchemaDefinition } from '../schema'\nimport { ValueOf, Writable } from '../utils/type-utils'\nimport z, { ZuiObjectSchema } from '../zui'\n\ntype BaseConfig = ZuiObjectSchema\ntype BaseStates = Record<string, ZuiObjectSchema>\ntype BaseEvents = Record<string, ZuiObjectSchema>\ntype BaseActions = Record<string, ZuiObjectSchema>\n\nexport type TagDefinition = {\n title?: string\n description?: string\n}\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\nexport type RecurringEventDefinition<TEvents extends BaseEvents = BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\nexport type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = SchemaDefinition<TEvent>\n\nexport type ConfigurationDefinition<TConfig extends BaseConfig = BaseConfig> = SchemaDefinition<TConfig>\n\nexport type UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type ActionDefinition<TAction extends BaseActions[string] = BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<ZuiObjectSchema> // cannot infer both input and output types (typescript limitation)\n}\n\nexport type IntegrationConfigInstance<I extends IntegrationPackage = IntegrationPackage> = {\n enabled: boolean\n} & (\n | {\n configurationType?: null\n configuration: z.infer<NonNullable<I['definition']['configuration']>['schema']>\n }\n | ValueOf<{\n [K in keyof NonNullable<I['definition']['configurations']>]: {\n configurationType: K\n configuration: z.infer<NonNullable<I['definition']['configurations']>[K]['schema']>\n }\n }>\n)\n\nexport type PluginConfigInstance<P extends PluginPackage = PluginPackage> = {\n configuration: z.infer<NonNullable<P['definition']['configuration']>['schema']>\n interfaces: {\n // TODO: this configuration should be strongly typed so that only the integrations that implement the interface are allowed\n [I in keyof NonNullable<P['definition']['interfaces']>]: { name: string; version: string }\n }\n}\n\nexport type IntegrationInstance = IntegrationPackage & IntegrationConfigInstance\nexport type PluginInstance = PluginPackage & PluginConfigInstance\n\nexport type BotDefinitionProps<\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions\n> = {\n integrations?: {\n [K: string]: IntegrationInstance\n }\n plugins?: {\n [K: string]: PluginInstance\n }\n user?: UserDefinition\n conversation?: ConversationDefinition\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n}\n\nexport class BotDefinition<\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions\n> {\n public readonly integrations: this['props']['integrations']\n public readonly plugins: this['props']['plugins']\n public readonly user: this['props']['user']\n public readonly conversation: this['props']['conversation']\n public readonly message: this['props']['message']\n public readonly states: this['props']['states']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly recurringEvents: this['props']['recurringEvents']\n public readonly actions: this['props']['actions']\n public constructor(public readonly props: BotDefinitionProps<TStates, TEvents, TActions>) {\n this.integrations = props.integrations\n this.plugins = props.plugins\n this.user = props.user\n this.conversation = props.conversation\n this.message = props.message\n this.states = props.states\n this.configuration = props.configuration\n this.events = props.events\n this.recurringEvents = props.recurringEvents\n this.actions = props.actions\n }\n\n public addIntegration<I extends IntegrationPackage>(integrationPkg: I, config: IntegrationConfigInstance<I>): this {\n const self = this as Writable<BotDefinition>\n if (!self.integrations) {\n self.integrations = {}\n }\n\n self.integrations[integrationPkg.name] = {\n enabled: config.enabled,\n ...integrationPkg,\n configurationType: config.configurationType as string,\n configuration: config.configuration,\n }\n return this\n }\n\n public addPlugin<P extends PluginPackage>(pluginPkg: P, config: PluginConfigInstance<P>): this {\n const self = this as Writable<BotDefinition>\n if (!self.plugins) {\n self.plugins = {}\n }\n\n self.plugins[pluginPkg.name] = {\n ...pluginPkg,\n configuration: config.configuration,\n interfaces: config.interfaces,\n }\n\n self.user = this._mergeUser(self.user, pluginPkg.definition.user)\n self.conversation = this._mergeConversation(self.conversation, pluginPkg.definition.conversation)\n self.message = this._mergeMessage(self.message, pluginPkg.definition.message)\n self.states = this._mergeStates(self.states, pluginPkg.definition.states)\n self.events = this._mergeEvents(self.events, pluginPkg.definition.events)\n self.recurringEvents = this._mergeRecurringEvents(self.recurringEvents, pluginPkg.definition.recurringEvents)\n self.actions = this._mergeActions(self.actions, pluginPkg.definition.actions)\n\n return this\n }\n\n private _mergeUser = (\n user1: BotDefinitionProps['user'],\n user2: BotDefinitionProps['user']\n ): BotDefinitionProps['user'] => {\n return {\n tags: {\n ...user1?.tags,\n ...user2?.tags,\n },\n }\n }\n\n private _mergeConversation = (\n conversation1: BotDefinitionProps['conversation'],\n conversation2: BotDefinitionProps['conversation']\n ): BotDefinitionProps['conversation'] => {\n return {\n tags: {\n ...conversation1?.tags,\n ...conversation2?.tags,\n },\n }\n }\n\n private _mergeMessage = (\n message1: BotDefinitionProps['message'],\n message2: BotDefinitionProps['message']\n ): BotDefinitionProps['message'] => {\n return {\n tags: {\n ...message1?.tags,\n ...message2?.tags,\n },\n }\n }\n\n private _mergeStates = (\n states1: BotDefinitionProps['states'],\n states2: BotDefinitionProps['states']\n ): BotDefinitionProps['states'] => {\n return {\n ...states1,\n ...states2,\n }\n }\n\n private _mergeEvents = (\n events1: BotDefinitionProps['events'],\n events2: BotDefinitionProps['events']\n ): BotDefinitionProps['events'] => {\n return {\n ...events1,\n ...events2,\n }\n }\n\n private _mergeRecurringEvents = (\n recurringEvents1: BotDefinitionProps['recurringEvents'],\n recurringEvents2: BotDefinitionProps['recurringEvents']\n ): BotDefinitionProps['recurringEvents'] => {\n return {\n ...recurringEvents1,\n ...recurringEvents2,\n }\n }\n\n private _mergeActions = (\n actions1: BotDefinitionProps['actions'],\n actions2: BotDefinitionProps['actions']\n ): BotDefinitionProps['actions'] => {\n return {\n ...actions1,\n ...actions2,\n }\n }\n}\n", "import * as utils from '../utils'\nimport { BotHandlers } from './server'\n\nexport const mergeBots = (dest: BotHandlers<any>, src: BotHandlers<any>) => {\n for (const [type, actionHandler] of Object.entries(src.actionHandlers)) {\n dest.actionHandlers[type] = actionHandler\n }\n\n for (const [type, handlers] of Object.entries(src.eventHandlers)) {\n if (!handlers) {\n continue\n }\n dest.eventHandlers[type] = utils.arrays.safePush(dest.eventHandlers[type], ...handlers)\n }\n\n for (const [type, handlers] of Object.entries(src.messageHandlers)) {\n if (!handlers) {\n continue\n }\n dest.messageHandlers[type] = utils.arrays.safePush(dest.messageHandlers[type], ...handlers)\n }\n\n for (const [type, handlers] of Object.entries(src.stateExpiredHandlers)) {\n if (!handlers) {\n continue\n }\n // TODO: address this type issue\n // @ts-ignore\n dest.stateExpiredHandlers[type] = utils.arrays.safePush(dest.stateExpiredHandlers[type], ...handlers)\n }\n\n for (const [hook, types] of Object.entries(src.hookHandlers)) {\n for (const [type, handlers] of Object.entries(types)) {\n if (!handlers) {\n continue\n }\n // TODO: address this type issue\n // @ts-ignore\n dest.hookHandlers[hook]![type] = utils.arrays.safePush(dest.hookHandlers[hook]![type], ...handlers)\n }\n }\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../../log'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody } from '../../serve'\nimport * as utils from '../../utils/type-utils'\nimport { BotLogger } from '../bot-logger'\nimport { BotSpecificClient } from '../client'\nimport * as common from '../types'\nimport { extractContext } from './context'\nimport * as types from './types'\n\nexport * from './types'\n\ntype ServerProps = types.CommonHandlerProps<common.BaseBot> & {\n req: Request\n self: types.BotHandlers<common.BaseBot>\n}\n\nconst SUCCESS_RESPONSE = { status: 200 }\n\nexport const botHandler =\n (bot: types.BotHandlers<common.BaseBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n const logger = new BotLogger()\n\n const vanillaClient = new client.Client({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<common.BaseBot>(vanillaClient, {\n before: {\n createMessage: async (req) => {\n const specificBeforeOutgoingMessageHooks = bot.hookHandlers.before_outgoing_message[req.type] ?? []\n const globalBeforeOutgoingMessageHooks = bot.hookHandlers.before_outgoing_message['*'] ?? []\n const beforeOutgoingMessageHooks = [\n ...specificBeforeOutgoingMessageHooks,\n ...globalBeforeOutgoingMessageHooks,\n ]\n for (const handler of beforeOutgoingMessageHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: req,\n })\n req = hookOutput?.data ?? req\n }\n return req\n },\n callAction: async (req) => {\n const specificBeforeOutgoingCallActionHooks = bot.hookHandlers.before_outgoing_call_action[req.type] ?? []\n const globalBeforeOutgoingCallActionHooks = bot.hookHandlers.before_outgoing_call_action['*'] ?? []\n const beforeOutgoingCallActionHooks = [\n ...specificBeforeOutgoingCallActionHooks,\n ...globalBeforeOutgoingCallActionHooks,\n ]\n for (const handler of beforeOutgoingCallActionHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: req,\n })\n req = hookOutput?.data ?? req\n }\n return req\n },\n },\n after: {\n createMessage: async (res) => {\n const specificAfterOutgoingMessageHooks = bot.hookHandlers.after_outgoing_message[res.message.type] ?? []\n const globalAfterOutgoingMessageHooks = bot.hookHandlers.after_outgoing_message['*'] ?? []\n const afterOutgoingMessageHooks = [...specificAfterOutgoingMessageHooks, ...globalAfterOutgoingMessageHooks]\n for (const handler of afterOutgoingMessageHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: res,\n })\n res = hookOutput?.data ?? res\n }\n return res\n },\n callAction: async (res) => {\n const specificAfterOutgoingCallActionHooks =\n bot.hookHandlers.after_outgoing_call_action[res.output.type] ?? []\n const globalAfterOutgoingCallActionHooks = bot.hookHandlers.after_outgoing_call_action['*'] ?? []\n const afterOutgoingCallActionHooks = [\n ...specificAfterOutgoingCallActionHooks,\n ...globalAfterOutgoingCallActionHooks,\n ]\n for (const handler of afterOutgoingCallActionHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: res,\n })\n res = hookOutput?.data ?? res\n }\n return res\n },\n },\n })\n\n const props: ServerProps = {\n req,\n ctx,\n logger,\n client: botClient,\n self: bot,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n return await onActionTriggered(props)\n case 'event_received':\n return await onEventReceived(props)\n case 'register':\n return await onRegister(props)\n case 'unregister':\n return await onUnregister(props)\n case 'ping':\n return await onPing(props)\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n }\n\nconst onPing = async ({ ctx }: ServerProps): Promise<Response> => {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n return SUCCESS_RESPONSE\n}\n\nconst onRegister = async (_: ServerProps): Promise<Response> => SUCCESS_RESPONSE\n\nconst onUnregister = async (_: ServerProps): Promise<Response> => SUCCESS_RESPONSE\n\nconst onEventReceived = async ({ ctx, logger, req, client, self }: ServerProps): Promise<Response> => {\n log.debug(`Received event ${ctx.type}`)\n\n type AnyEventPayload = utils.ValueOf<types.EventPayloads<common.BaseBot>>\n const body = parseBody<AnyEventPayload>(req)\n\n if (ctx.type === 'message_created') {\n const event = body.event\n let message: client.Message = event.payload.message\n const specificBeforeIncomingMessageHooks = self.hookHandlers.before_incoming_message[message.type] ?? []\n const globalBeforeIncomingMessageHooks = self.hookHandlers.before_incoming_message['*'] ?? []\n const beforeIncomingMessageHooks = [...specificBeforeIncomingMessageHooks, ...globalBeforeIncomingMessageHooks]\n for (const handler of beforeIncomingMessageHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n logger,\n data: message,\n })\n message = hookOutput?.data ?? message\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n const messagePayload: utils.ValueOf<types.MessagePayloads<common.BaseBot>> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n states: event.payload.states,\n message,\n event,\n }\n\n const specificMessageHandlers = self.messageHandlers[message.type] ?? []\n const globalMessageHandlers = self.messageHandlers['*'] ?? []\n const messageHandlers = [...specificMessageHandlers, ...globalMessageHandlers]\n\n for (const handler of messageHandlers) {\n await handler({\n ...messagePayload,\n client,\n ctx,\n logger,\n })\n }\n\n const specificAfterIncomingMessageHooks = self.hookHandlers.after_incoming_message[message.type] ?? []\n const globalAfterIncomingMessageHooks = self.hookHandlers.after_incoming_message['*'] ?? []\n const afterIncomingMessageHooks = [...specificAfterIncomingMessageHooks, ...globalAfterIncomingMessageHooks]\n for (const handler of afterIncomingMessageHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n data: message,\n logger,\n })\n message = hookOutput?.data ?? message\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n return SUCCESS_RESPONSE\n }\n\n if (ctx.type === 'state_expired') {\n const event = body.event\n const state: client.State = event.payload.state\n const statePayload: utils.ValueOf<types.StateExpiredPayloads<common.BaseBot>> = { state }\n\n const stateHandlers = self.stateExpiredHandlers['*'] ?? []\n for (const handler of stateHandlers) {\n await handler({\n ...statePayload,\n client,\n ctx,\n logger,\n })\n }\n return SUCCESS_RESPONSE\n }\n\n let event = body.event\n const sepcificBeforeIncomingEventHooks = self.hookHandlers.before_incoming_event[event.type] ?? []\n const globalBeforeIncomingEventHooks = self.hookHandlers.before_incoming_event['*'] ?? []\n const beforeIncomingEventHooks = [...sepcificBeforeIncomingEventHooks, ...globalBeforeIncomingEventHooks]\n for (const handler of beforeIncomingEventHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n data: event,\n logger,\n })\n event = hookOutput?.data ?? event\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n const eventPayload = { event }\n\n const specificEventHandlers = self.eventHandlers[event.type] ?? []\n const globalEventHandlers = self.eventHandlers['*'] ?? []\n const eventHandlers = [...specificEventHandlers, ...globalEventHandlers]\n for (const handler of eventHandlers) {\n await handler({\n ...eventPayload,\n client,\n ctx,\n logger,\n })\n }\n\n const specificAfterIncomingEventHooks = self.hookHandlers.after_incoming_event[event.type] ?? []\n const globalAfterIncomingEventHooks = self.hookHandlers.after_incoming_event['*'] ?? []\n const afterIncomingEventHooks = [...specificAfterIncomingEventHooks, ...globalAfterIncomingEventHooks]\n for (const handler of afterIncomingEventHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n data: event,\n logger,\n })\n event = hookOutput?.data ?? event\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n return SUCCESS_RESPONSE\n}\n\nconst onActionTriggered = async ({ ctx, logger, req, client, self }: ServerProps): Promise<Response> => {\n type AnyActionPayload = utils.ValueOf<types.ActionHandlerPayloads<common.BaseBot>>\n const { input, type } = parseBody<AnyActionPayload>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = self.actionHandlers[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, logger, input, client, type })\n\n const response = { output }\n return {\n status: 200,\n body: JSON.stringify(response),\n }\n}\n", "import { BaseLogger } from '../base-logger'\n\ntype BotLogOptions = {\n userId?: string\n conversationId?: string\n workflowId?: string\n}\n\nexport class BotLogger extends BaseLogger<BotLogOptions> {\n public constructor(options?: BotLogOptions) {\n super({\n ...options,\n })\n }\n\n public override with(options: BotLogOptions) {\n return new BotLogger({ ...this.defaultOptions, ...options })\n }\n\n public withUserId(userId: string) {\n return this.with({\n userId,\n })\n }\n\n public withConversationId(conversationId: string) {\n return this.with({\n conversationId,\n })\n }\n\n public withWorkflowId(workflowId: string) {\n return this.with({\n workflowId,\n })\n }\n}\n", "import * as client from '@botpress/client'\nimport * as common from '../types'\nimport * as types from './types'\n\nexport * from './types'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends common.BaseBot> implements types.ClientOperations<TBot> {\n public constructor(private _client: client.Client, private _hooks: types.ClientHooks = { before: {}, after: {} }) {}\n\n public getConversation: types.GetConversation<TBot> = ((x) =>\n this._run('getConversation', x)) as types.GetConversation<TBot>\n public listConversations: types.ListConversations<TBot> = ((x) =>\n this._run('listConversations', x)) as types.ListConversations<TBot>\n public updateConversation: types.UpdateConversation<TBot> = ((x) =>\n this._run('updateConversation', x)) as types.UpdateConversation<TBot>\n public deleteConversation: types.DeleteConversation<TBot> = ((x) =>\n this._run('deleteConversation', x)) as types.DeleteConversation<TBot>\n public listParticipants: types.ListParticipants<TBot> = ((x) =>\n this._run('listParticipants', x)) as types.ListParticipants<TBot>\n public addParticipant: types.AddParticipant<TBot> = ((x) =>\n this._run('addParticipant', x)) as types.AddParticipant<TBot>\n public getParticipant: types.GetParticipant<TBot> = ((x) =>\n this._run('getParticipant', x)) as types.GetParticipant<TBot>\n public removeParticipant: types.RemoveParticipant<TBot> = ((x) =>\n this._run('removeParticipant', x)) as types.RemoveParticipant<TBot>\n public getEvent: types.GetEvent<TBot> = ((x) => this._run('getEvent', x)) as types.GetEvent<TBot>\n public listEvents: types.ListEvents<TBot> = ((x) => this._run('listEvents', x)) as types.ListEvents<TBot>\n public createMessage: types.CreateMessage<TBot> = ((x) => this._run('createMessage', x)) as types.CreateMessage<TBot>\n public getOrCreateMessage: types.GetOrCreateMessage<TBot> = ((x) =>\n this._run('getOrCreateMessage', x)) as types.GetOrCreateMessage<TBot>\n public getMessage: types.GetMessage<TBot> = ((x) => this._run('getMessage', x)) as types.GetMessage<TBot>\n public updateMessage: types.UpdateMessage<TBot> = ((x) => this._run('updateMessage', x)) as types.UpdateMessage<TBot>\n public listMessages: types.ListMessages<TBot> = ((x) => this._run('listMessages', x)) as types.ListMessages<TBot>\n public deleteMessage: types.DeleteMessage<TBot> = ((x) => this._run('deleteMessage', x)) as types.DeleteMessage<TBot>\n public getUser: types.GetUser<TBot> = ((x) => this._run('getUser', x)) as types.GetUser<TBot>\n public listUsers: types.ListUsers<TBot> = ((x) => this._run('listUsers', x)) as types.ListUsers<TBot>\n public updateUser: types.UpdateUser<TBot> = ((x) => this._run('updateUser', x)) as types.UpdateUser<TBot>\n public deleteUser: types.DeleteUser<TBot> = ((x) => this._run('deleteUser', x)) as types.DeleteUser<TBot>\n public getState: types.GetState<TBot> = ((x) => this._run('getState', x)) as types.GetState<TBot>\n public setState: types.SetState<TBot> = ((x) => this._run('setState', x)) as types.SetState<TBot>\n public getOrSetState: types.GetOrSetState<TBot> = ((x) => this._run('getOrSetState', x)) as types.GetOrSetState<TBot>\n public patchState: types.PatchState<TBot> = ((x) => this._run('patchState', x)) as types.PatchState<TBot>\n public callAction: types.CallAction<TBot> = ((x) => this._run('callAction', x)) as types.CallAction<TBot>\n public uploadFile: types.UploadFile<TBot> = ((x) => this._run('uploadFile', x)) as types.UploadFile<TBot>\n public upsertFile: types.UpsertFile<TBot> = ((x) => this._run('upsertFile', x)) as types.UpsertFile<TBot>\n public deleteFile: types.DeleteFile<TBot> = ((x) => this._run('deleteFile', x)) as types.DeleteFile<TBot>\n public listFiles: types.ListFiles<TBot> = ((x) => this._run('listFiles', x)) as types.ListFiles<TBot>\n public getFile: types.GetFile<TBot> = ((x) => this._run('getFile', x)) as types.GetFile<TBot>\n public updateFileMetadata: types.UpdateFileMetadata<TBot> = ((x) =>\n this._run('updateFileMetadata', x)) as types.UpdateFileMetadata<TBot>\n public searchFiles: types.SearchFiles<TBot> = ((x) => this._run('searchFiles', x)) as types.SearchFiles<TBot>\n public trackAnalytics: types.TrackAnalytics<TBot> = ((x) =>\n this._run('trackAnalytics', x)) as types.TrackAnalytics<TBot>\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: types.CreateConversation<TBot> = (x) => this._client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: types.GetOrCreateConversation<TBot> = (x) => this._client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: types.CreateUser<TBot> = (x) => this._client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: types.GetOrCreateUser<TBot> = (x) => this._client.getOrCreateUser(x)\n\n private _run = async <K extends client.Operation>(\n operation: K,\n req: client.ClientInputs[K]\n ): Promise<client.ClientOutputs[K]> => {\n const before = this._hooks.before[operation]\n if (before) {\n req = await before(req)\n }\n\n let res = (await this._client[operation](req as any)) as client.ClientOutputs[K]\n\n const after = this._hooks.after[operation]\n if (after) {\n res = await after(res)\n }\n\n return res\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../../const'\nimport { BotContext } from './types'\n\nconst botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import type { Server } from 'node:http'\nimport { BasePlugin, PluginImplementation } from '../plugin'\nimport { serve } from '../serve'\nimport * as utils from '../utils'\nimport { mergeBots } from './merge-bots'\nimport {\n botHandler,\n MessageHandlersMap,\n MessageHandlers,\n EventHandlersMap,\n EventHandlers,\n StateExpiredHandlersMap,\n StateExpiredHandlers,\n HookHandlersMap,\n HookData,\n HookHandlers,\n ActionHandlers,\n BotHandlers,\n UnimplementedActionHandlers,\n} from './server'\nimport { BaseBot } from './types'\n\nexport type BotImplementationProps<TBot extends BaseBot = BaseBot, TPlugins extends Record<string, BasePlugin> = {}> = {\n actions: UnimplementedActionHandlers<TBot, TPlugins>\n plugins: {\n [K in keyof TPlugins]: PluginImplementation<TPlugins[K]>\n }\n}\n\nexport class BotImplementation<TBot extends BaseBot = BaseBot, TPlugins extends Record<string, BasePlugin> = {}>\n implements BotHandlers<TBot>\n{\n public readonly actionHandlers: ActionHandlers<TBot>\n public readonly messageHandlers: MessageHandlersMap<TBot> = {}\n public readonly eventHandlers: EventHandlersMap<TBot> = {}\n public readonly stateExpiredHandlers: StateExpiredHandlersMap<TBot> = {}\n public readonly hookHandlers: HookHandlersMap<TBot> = {\n before_incoming_event: {},\n before_incoming_message: {},\n before_outgoing_message: {},\n before_outgoing_call_action: {},\n after_incoming_event: {},\n after_incoming_message: {},\n after_outgoing_message: {},\n after_outgoing_call_action: {},\n }\n\n /**\n * alias for actionHandlers\n */\n public get actions() {\n return this.actionHandlers\n }\n\n public constructor(public readonly props: BotImplementationProps<TBot, TPlugins>) {\n this.actionHandlers = props.actions as ActionHandlers<TBot>\n const plugins = utils.records.values(props.plugins)\n for (const plugin of plugins) {\n this._use(plugin as BotHandlers<any>)\n }\n }\n\n public readonly on = {\n message: <T extends keyof MessageHandlersMap<TBot>>(type: T, handler: MessageHandlers<TBot>[T]): void => {\n this.messageHandlers[type] = utils.arrays.safePush(this.messageHandlers[type], handler)\n },\n event: <T extends keyof EventHandlersMap<TBot>>(type: T, handler: EventHandlers<TBot>[T]): void => {\n this.eventHandlers[type] = utils.arrays.safePush(this.eventHandlers[type], handler)\n },\n stateExpired: <T extends keyof StateExpiredHandlersMap<TBot>>(\n type: T,\n handler: StateExpiredHandlers<TBot>[T]\n ): void => {\n this.stateExpiredHandlers[type] = utils.arrays.safePush(this.stateExpiredHandlers[type], handler)\n },\n beforeIncomingEvent: <T extends keyof HookData<TBot>['before_incoming_event']>(\n type: T,\n handler: HookHandlers<TBot>['before_incoming_event'][T]\n ) => {\n this.hookHandlers.before_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_event[type],\n handler\n )\n },\n beforeIncomingMessage: <T extends keyof HookData<TBot>['before_incoming_message']>(\n type: T,\n handler: HookHandlers<TBot>['before_incoming_message'][T]\n ) => {\n this.hookHandlers.before_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_message[type],\n handler\n )\n },\n beforeOutgoingMessage: <T extends keyof HookData<TBot>['before_outgoing_message']>(\n type: T,\n handler: HookHandlers<TBot>['before_outgoing_message'][T]\n ) => {\n this.hookHandlers.before_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_message[type],\n handler\n )\n },\n beforeOutgoingCallAction: <T extends keyof HookData<TBot>['before_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TBot>['before_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.before_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_call_action[type],\n handler\n )\n },\n afterIncomingEvent: <T extends keyof HookData<TBot>['after_incoming_event']>(\n type: T,\n handler: HookHandlers<TBot>['after_incoming_event'][T]\n ) => {\n this.hookHandlers.after_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_event[type],\n handler\n )\n },\n afterIncomingMessage: <T extends keyof HookData<TBot>['after_incoming_message']>(\n type: T,\n handler: HookHandlers<TBot>['after_incoming_message'][T]\n ) => {\n this.hookHandlers.after_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_message[type],\n handler\n )\n },\n afterOutgoingMessage: <T extends keyof HookData<TBot>['after_outgoing_message']>(\n type: T,\n handler: HookHandlers<TBot>['after_outgoing_message'][T]\n ) => {\n this.hookHandlers.after_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_message[type],\n handler\n )\n },\n afterOutgoingCallAction: <T extends keyof HookData<TBot>['after_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TBot>['after_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.after_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_call_action[type],\n handler\n )\n },\n }\n\n private readonly _use = (botLike: BotHandlers<any>): void => {\n mergeBots(this as BotHandlers<any>, botLike)\n }\n\n public readonly handler = botHandler(this as BotHandlers<any>)\n\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { ActionDefinition, ChannelDefinition, EntityDefinition, EventDefinition } from '../integration/definition'\nimport * as utils from '../utils'\nimport z, { ZuiObjectSchema, GenericZuiSchema, ZodRef } from '../zui'\n\ntype BaseEvents = Record<string, ZuiObjectSchema>\ntype BaseActions = Record<string, ZuiObjectSchema>\ntype BaseMessages = Record<string, ZuiObjectSchema>\ntype BaseChannels = Record<string, BaseMessages>\ntype BaseEntities = Record<string, ZuiObjectSchema>\n\ntype EntityReferences<TEntities extends BaseEntities> = {\n [K in keyof TEntities]: ZodRef\n}\n\ntype GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TEvent>\n}\n\ntype GenericChannelDefinition<\n TEntities extends BaseEntities,\n TChannel extends BaseChannels[string] = BaseChannels[string]\n> = {\n messages: {\n [K in keyof TChannel]: {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>\n }\n }\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\n title?: string\n description?: string\n billable?: boolean\n cacheable?: boolean\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, ZuiObjectSchema> }\n}\n\nexport type InterfaceDefinitionProps<\n TName extends string = string,\n TVersion extends string = string,\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities,\n TChannels extends BaseChannels = BaseChannels\n> = {\n name: TName\n version: TVersion\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n events?: { [K in keyof TEvents]: GenericEventDefinition<TEntities, TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: GenericActionDefinition<TEntities, TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>\n }\n\n templateName?: string\n}\n\nexport class InterfaceDefinition<\n TName extends string = string,\n TVersion extends string = string,\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents,\n TChannels extends BaseChannels = BaseChannels\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\n public readonly entities: { [K in keyof TEntities]: EntityDefinition<TEntities[K]> }\n public readonly events: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n public readonly actions: { [K in keyof TActions]: ActionDefinition<TActions[K]> }\n public readonly channels: { [K in keyof TChannels]: ChannelDefinition<TChannels[K]> }\n\n public readonly templateName: this['props']['templateName']\n\n public constructor(\n public readonly props: InterfaceDefinitionProps<TName, TVersion, TEntities, TActions, TEvents, TChannels>\n ) {\n this.name = props.name\n this.version = props.version\n this.entities = props.entities ?? ({} as this['entities'])\n this.templateName = props.templateName\n\n const entityReferences = this._getEntityReference(this.entities)\n\n const events: Record<string, EventDefinition> =\n props.events === undefined\n ? {}\n : utils.records.mapValues(\n props.events,\n (event): EventDefinition => ({\n ...event,\n schema: event.schema(entityReferences),\n })\n )\n\n const actions: Record<string, ActionDefinition> =\n props.actions === undefined\n ? {}\n : utils.records.mapValues(\n props.actions,\n (action): ActionDefinition => ({\n ...action,\n input: {\n ...action.input,\n schema: action.input.schema(entityReferences),\n },\n output: {\n ...action.output,\n schema: action.output.schema(entityReferences),\n },\n })\n )\n\n const channels: Record<string, ChannelDefinition> =\n props.channels === undefined\n ? {}\n : utils.records.mapValues(\n props.channels,\n (channel): ChannelDefinition => ({\n ...channel,\n messages: utils.records.mapValues(channel.messages, (message) => ({\n ...message,\n schema: message.schema(entityReferences),\n })),\n })\n )\n\n this.events = events as this['events']\n this.actions = actions as this['actions']\n this.channels = channels as this['channels']\n }\n\n private _getEntityReference = (entities: Record<string, EntityDefinition>): EntityReferences<TEntities> => {\n const entityReferences: Record<string, ZodRef> = {} as EntityReferences<TEntities>\n for (const [entityName, entityDef] of Object.entries(entities)) {\n const title = entityDef.schema._def['x-zui']?.title\n const description = entityDef.schema._def.description\n\n const refSchema = z.ref(entityName)\n if (title) {\n refSchema.title(title)\n }\n if (description) {\n refSchema.describe(description)\n }\n\n entityReferences[entityName] = refSchema\n }\n return entityReferences as EntityReferences<TEntities>\n }\n}\n", "import {\n StateDefinition,\n RecurringEventDefinition,\n EventDefinition,\n ConfigurationDefinition,\n UserDefinition,\n ConversationDefinition,\n MessageDefinition,\n ActionDefinition,\n} from '../bot/definition'\nimport { IntegrationPackage, InterfacePackage } from '../package'\nimport { ZuiObjectSchema } from '../zui'\n\nexport {\n StateDefinition,\n RecurringEventDefinition,\n EventDefinition,\n ConfigurationDefinition,\n UserDefinition,\n ConversationDefinition,\n MessageDefinition,\n ActionDefinition,\n IntegrationConfigInstance,\n} from '../bot/definition'\n\ntype BaseConfig = ZuiObjectSchema\ntype BaseStates = Record<string, ZuiObjectSchema>\ntype BaseEvents = Record<string, ZuiObjectSchema>\ntype BaseActions = Record<string, ZuiObjectSchema>\ntype BaseInterfaces = Record<string, any>\ntype BaseIntegrations = Record<string, any>\n\nexport type PluginDefinitionProps<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TInterfaces extends BaseInterfaces = BaseInterfaces,\n TIntegrations extends BaseIntegrations = BaseIntegrations\n> = {\n name: TName\n version: TVersion\n integrations?: {\n [K in keyof TIntegrations]: IntegrationPackage\n }\n interfaces?: {\n [K in keyof TInterfaces]: InterfacePackage\n }\n user?: UserDefinition\n conversation?: ConversationDefinition\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition<TConfig>\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n}\n\nexport class PluginDefinition<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TInterfaces extends BaseInterfaces = BaseInterfaces,\n TIntegrations extends BaseIntegrations = BaseIntegrations\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\n public readonly integrations: this['props']['integrations']\n public readonly interfaces: this['props']['interfaces']\n\n public readonly user: this['props']['user']\n public readonly conversation: this['props']['conversation']\n public readonly message: this['props']['message']\n public readonly states: this['props']['states']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly recurringEvents: this['props']['recurringEvents']\n public readonly actions: this['props']['actions']\n\n public constructor(\n public readonly props: PluginDefinitionProps<\n TName,\n TVersion,\n TConfig,\n TStates,\n TEvents,\n TActions,\n TInterfaces,\n TIntegrations\n >\n ) {\n this.name = props.name\n this.version = props.version\n this.integrations = props.integrations\n this.interfaces = props.interfaces\n this.user = props.user\n this.conversation = props.conversation\n this.message = props.message\n this.states = props.states\n this.configuration = props.configuration\n this.events = props.events\n this.recurringEvents = props.recurringEvents\n this.actions = props.actions\n }\n}\n", "import * as utils from '../utils'\nimport {\n MessageHandlersMap,\n MessageHandlers,\n EventHandlersMap,\n EventHandlers,\n StateExpiredHandlersMap,\n StateExpiredHandlers,\n HookHandlersMap,\n HookData,\n HookHandlers,\n ActionHandlers,\n BotHandlers,\n} from './server/types'\nimport { BasePlugin } from './types/generic'\n\nexport type PluginImplementationProps<TPlugin extends BasePlugin = BasePlugin> = {\n actions: ActionHandlers<TPlugin>\n}\n\nexport type PluginRuntimeProps<TPlugin extends BasePlugin = BasePlugin> = {\n configuration: TPlugin['configuration']\n interfaces: {\n [K in keyof TPlugin['interfaces']]: { name: string; version: string }\n }\n}\n\nexport class PluginImplementation<TPlugin extends BasePlugin = BasePlugin> implements BotHandlers<TPlugin> {\n private _runtimeProps: PluginRuntimeProps<TPlugin> | undefined\n\n public readonly actionHandlers: ActionHandlers<TPlugin>\n public readonly messageHandlers: MessageHandlersMap<TPlugin> = {}\n public readonly eventHandlers: EventHandlersMap<TPlugin> = {}\n public readonly stateExpiredHandlers: StateExpiredHandlersMap<TPlugin> = {}\n public readonly hookHandlers: HookHandlersMap<TPlugin> = {\n before_incoming_event: {},\n before_incoming_message: {},\n before_outgoing_message: {},\n before_outgoing_call_action: {},\n after_incoming_event: {},\n after_incoming_message: {},\n after_outgoing_message: {},\n after_outgoing_call_action: {},\n }\n\n public constructor(public readonly props: PluginImplementationProps<TPlugin>) {\n this.actionHandlers = props.actions\n }\n\n public initialize(config: PluginRuntimeProps<TPlugin>): this {\n this._runtimeProps = config\n return this\n }\n\n public get config(): PluginRuntimeProps<TPlugin> {\n if (!this._runtimeProps) {\n throw new Error(\n 'Plugin not correctly initialized. This is likely because you access your plugin config outside of an handler.'\n )\n }\n return this._runtimeProps\n }\n\n public readonly on = {\n message: <T extends keyof MessageHandlersMap<TPlugin>>(type: T, handler: MessageHandlers<TPlugin>[T]): void => {\n this.messageHandlers[type] = utils.arrays.safePush(this.messageHandlers[type], handler)\n },\n event: <T extends keyof EventHandlersMap<TPlugin>>(type: T, handler: EventHandlers<TPlugin>[T]): void => {\n this.eventHandlers[type] = utils.arrays.safePush(this.eventHandlers[type], handler)\n },\n stateExpired: <T extends keyof StateExpiredHandlersMap<TPlugin>>(\n type: T,\n handler: StateExpiredHandlers<TPlugin>[T]\n ): void => {\n this.stateExpiredHandlers[type] = utils.arrays.safePush(this.stateExpiredHandlers[type], handler)\n },\n beforeIncomingEvent: <T extends keyof HookData<TPlugin>['before_incoming_event']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_incoming_event'][T]\n ) => {\n this.hookHandlers.before_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_event[type],\n handler\n )\n },\n beforeIncomingMessage: <T extends keyof HookData<TPlugin>['before_incoming_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_incoming_message'][T]\n ) => {\n this.hookHandlers.before_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_message[type],\n handler\n )\n },\n beforeOutgoingMessage: <T extends keyof HookData<TPlugin>['before_outgoing_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_outgoing_message'][T]\n ) => {\n this.hookHandlers.before_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_message[type],\n handler\n )\n },\n beforeOutgoingCallAction: <T extends keyof HookData<TPlugin>['before_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.before_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_call_action[type],\n handler\n )\n },\n afterIncomingEvent: <T extends keyof HookData<TPlugin>['after_incoming_event']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_incoming_event'][T]\n ) => {\n this.hookHandlers.after_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_event[type],\n handler\n )\n },\n afterIncomingMessage: <T extends keyof HookData<TPlugin>['after_incoming_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_incoming_message'][T]\n ) => {\n this.hookHandlers.after_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_message[type],\n handler\n )\n },\n afterOutgoingMessage: <T extends keyof HookData<TPlugin>['after_outgoing_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_outgoing_message'][T]\n ) => {\n this.hookHandlers.after_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_message[type],\n handler\n )\n },\n afterOutgoingCallAction: <T extends keyof HookData<TPlugin>['after_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.after_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_call_action[type],\n handler\n )\n },\n }\n}\n"],
|
|
5
|
-
"mappings": "onBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,kBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,sBAAAC,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,WAAAC,EAAA,qBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,GAAA,wBAAAC,EAAA,4BAAAC,GAAA,wBAAAC,GAAA,yCAAAC,GAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,GAAA,oBAAAC,KAAA,eAAAC,GAAAxB,GCAA,IAAAyB,GAAA,GAAAC,EAAAD,GAAA,cAAAE,GAAA,aAAAC,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,KAAA,IAAAC,GAAkB,2BAElBC,EAAAJ,EAAc,4BASd,IAAOE,GAAQ,KDTf,IAAMG,EAA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,IACG,CACH,KAAK,aAAa,uBAAuBD,CAAI,EAAUE,EAAO,SAC5D,KAAK,aAAa,uBAAuBF,CAAI,EAC7CC,CACF,CACF,EACA,qBAAsB,CACpBD,EACAC,IACG,CACH,KAAK,aAAa,uBAAuBD,CAAI,EAAUE,EAAO,SAC5D,KAAK,aAAa,uBAAuBF,CAAI,EAC7CC,CACF,CACF,EACA,wBAAyB,CACvBD,EACAC,IACG,CACH,KAAK,aAAa,2BAA2BD,CAAI,EAAUE,EAAO,SAChE,KAAK,aAAa,2BAA2BF,CAAI,EACjDC,CACF,CACF,CACF,CACF",
|
|
4
|
+
"sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n //\n isApiError,\n RuntimeError,\n} from '@botpress/client'\n\nexport {\n DefaultIntegration,\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationLogger,\n IntegrationSpecificClient,\n TagDefinition,\n ConfigurationDefinition,\n AdditionalConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport {\n /**\n * @deprecated use Context exported from '.botpress' instead\n */\n IntegrationContext,\n} from './integration/server'\n\nexport {\n DefaultBot,\n BotDefinition,\n BotDefinitionProps,\n BotImplementation as Bot,\n BotImplementationProps as BotProps,\n BotSpecificClient,\n BotHandlers,\n TagDefinition as BotTagDefinition,\n StateType as BotStateType,\n StateDefinition as BotStateDefinition,\n RecurringEventDefinition as BotRecurringEventDefinition,\n EventDefinition as BotEventDefinition,\n ConfigurationDefinition as BotConfigurationDefinition,\n UserDefinition as BotUserDefinition,\n ConversationDefinition as BotConversationDefinition,\n MessageDefinition as BotMessageDefinition,\n ActionDefinition as BotActionDefinition,\n BotLogger,\n} from './bot'\n\nexport {\n //\n InterfaceDefinition,\n InterfaceDefinitionProps,\n} from './interface'\n\nexport {\n //\n DefaultPlugin,\n PluginDefinition,\n PluginImplementation as Plugin,\n} from './plugin'\n\nexport {\n //\n IntegrationPackage,\n InterfacePackage,\n PluginPackage,\n Package,\n} from './package'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nconst blocSchema = z.union([\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n z.object({ type: z.literal('image'), payload: imageMessageSchema }),\n z.object({ type: z.literal('audio'), payload: audioMessageSchema }),\n z.object({ type: z.literal('video'), payload: videoMessageSchema }),\n z.object({ type: z.literal('file'), payload: fileMessageSchema }),\n z.object({ type: z.literal('location'), payload: locationMessageSchema }),\n])\n\nconst blocsSchema = z.object({\n items: z.array(blocSchema),\n})\n\n/**\n * @deprecated use `text` instead\n */\nexport const markdown = { schema: markdownMessageSchema }\nexport const defaults = {\n text: { schema: textMessageSchema },\n image: { schema: imageMessageSchema },\n audio: { schema: audioMessageSchema },\n video: { schema: videoMessageSchema },\n file: { schema: fileMessageSchema },\n location: { schema: locationMessageSchema },\n carousel: { schema: carouselSchema },\n card: { schema: cardSchema },\n dropdown: { schema: choiceSchema },\n choice: { schema: choiceSchema },\n bloc: { schema: blocsSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import { z } from '@bpinternal/zui'\n\nexport * from '@bpinternal/zui'\n\nexport type GenericZuiSchema<\n A extends Record<string, z.ZodTypeAny> = Record<string, z.ZodTypeAny>,\n R extends z.ZodTypeAny = z.ZodTypeAny,\n> = (typeArguments: A) => R\n\nexport type ZuiObjectSchema = z.ZodObject | z.ZodRecord\n\nexport default z\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationTypeHeader = 'x-bp-configuration-type'\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "export const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, V][]\nexport const values = <K extends string, V>(obj: Record<K, V>) => Object.values(obj) as V[]\nexport const mapValues = <K extends string, V, R>(obj: Record<K, V>, fn: (value: V, key: K) => R): Record<K, R> =>\n Object.fromEntries(pairs(obj).map(([key, value]) => [key, fn(value, key)])) as Record<K, R>\n", "export const safePush = <T>(arr: T[] | undefined, ...values: T[]): T[] => (arr ? [...arr, ...values] : [...values])\n", "import * as utils from '../../utils'\nimport { z } from '../../zui'\n\nconst schemaName = Symbol('schemaName')\n\ntype BaseSchemas = Record<string, z.ZodSchema>\n\nexport type SchemaStoreProps<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: {\n schema: TSchemas[K]\n }\n}\n\nexport type BrandedSchema<TSchema extends BaseSchemas[string] = BaseSchemas[string]> = {\n schema: TSchema\n [schemaName]: string\n}\n\nexport type SchemaStore<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: BrandedSchema<TSchemas[K]>\n}\n\nexport const createStore = <TSchemas extends BaseSchemas>(\n props: SchemaStoreProps<TSchemas> | undefined\n): SchemaStore<TSchemas> => {\n if (!props) {\n return {} as SchemaStore<TSchemas>\n }\n const store: SchemaStore<BaseSchemas> = utils.records.mapValues(props, (e, k) => ({ ...e, [schemaName]: k }))\n return store as SchemaStore<TSchemas>\n}\n\nexport const isBranded = (schema: BrandedSchema | { schema: z.ZodSchema }): schema is BrandedSchema => {\n return schemaName in schema && schema[schemaName] !== undefined\n}\n\nexport const getName = (schema: BrandedSchema): string => {\n return schema[schemaName]\n}\n", "import { InterfacePackage } from '../../package'\nimport * as utils from '../../utils'\nimport { z } from '../../zui'\nimport { SchemaStore, BrandedSchema, createStore, isBranded, getName } from './branded-schema'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities, BaseConfigs } from './generic'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n AdditionalConfigurationDefinition,\n} from './types'\n\nexport * from './types'\n\nexport type InterfaceExtension = InterfacePackage & {\n entities: Record<\n string,\n {\n name: string\n schema: z.AnyZodObject\n }\n >\n}\n\nexport type IntegrationDefinitionProps<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities,\n> = {\n name: TName\n version: TVersion\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n configurations?: {\n [K in keyof TConfigs]: AdditionalConfigurationDefinition<TConfigs[K]>\n }\n\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n interfaces?: Record<string, InterfaceExtension>\n}\n\ntype EntitiesOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['entities']]: NonNullable<TPackage['definition']['entities']>[K]['schema']\n}\n\ntype ExtensionBuilderInput<TIntegrationEntities extends BaseEntities> = SchemaStore<TIntegrationEntities>\n\ntype ExtensionBuilderOutput<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: ExtensionBuilderInput<TIntegrationEntities>\n) => ExtensionBuilderOutput<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities,\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly configurations: this['props']['configurations']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n public readonly interfaces: this['props']['interfaces']\n public constructor(\n public readonly props: IntegrationDefinitionProps<\n TName,\n TVersion,\n TConfig,\n TConfigs,\n TEvents,\n TActions,\n TChannels,\n TStates,\n TEntities\n >\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.configurations = props.configurations\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n this.interfaces = props.interfaces\n }\n\n public extend<P extends InterfacePackage>(\n interfacePkg: P,\n builder: ExtensionBuilder<TEntities, EntitiesOfPackage<P>>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities))\n const unbrandedEntity = utils.records.pairs(extensionBuilderOutput).find(([_k, e]) => !isBranded(e))\n if (unbrandedEntity) {\n // this means the user tried providing a plain schema without referencing an entity from the integration\n throw new Error(\n `Cannot extend interface \"${interfacePkg.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const self = this as utils.types.Writable<IntegrationDefinition>\n self.interfaces ??= {}\n\n const interfaceTypeArguments = utils.records.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema as z.AnyZodObject,\n }))\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n\n const key = entityNames.length === 0 ? interfacePkg.name : `${interfacePkg.name}<${entityNames.join(',')}>`\n\n self.interfaces[key] = {\n ...interfacePkg,\n entities: interfaceTypeArguments,\n }\n\n return this\n }\n}\n", "import { isApiError, Client, RuntimeError } from '@botpress/client'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody } from '../../serve'\nimport { IntegrationSpecificClient } from '../client'\nimport { BaseIntegration } from '../types'\nimport { ActionMetadataStore } from './action-metadata'\nimport { extractContext } from './context'\nimport { IntegrationLogger } from './integration-logger'\nimport {\n CommonHandlerProps,\n IntegrationHandlers,\n WebhookPayload,\n ActionPayload,\n MessagePayload,\n RegisterPayload,\n CreateUserPayload,\n UnregisterPayload,\n CreateConversationPayload,\n} from './types'\n\nexport * from './types'\nexport * from './integration-logger'\n\ntype ServerProps = CommonHandlerProps<BaseIntegration> & {\n req: Request\n instance: IntegrationHandlers<BaseIntegration>\n}\n\nexport const integrationHandler =\n (instance: IntegrationHandlers<BaseIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n retry: retryConfig,\n })\n const client = new IntegrationSpecificClient<BaseIntegration>(vanillaClient)\n const logger = new IntegrationLogger()\n\n const props = {\n ctx,\n req,\n client,\n logger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook(props)\n break\n case 'register':\n response = await onRegister(props)\n break\n case 'unregister':\n response = await onUnregister(props)\n break\n case 'message_created':\n response = await onMessageCreated(props)\n break\n case 'action_triggered':\n response = await onActionTriggered(props)\n break\n case 'ping':\n response = await onPing(props)\n break\n case 'create_user':\n response = await onCreateUser(props)\n break\n case 'create_conversation':\n response = await onCreateConversation(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (error) {\n if (isApiError(error)) {\n const runtimeError = error.type === 'Runtime' ? error : new RuntimeError(error.message, error)\n logger.forBot().error(runtimeError.message)\n\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n\n // prints the error in the integration logs\n console.error(error)\n\n const runtimeError = new RuntimeError(\n 'An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.'\n )\n logger.forBot().error(runtimeError.message)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n }\n\nconst onPing = async (_: ServerProps) => {}\n\nconst onWebhook = async ({ client, ctx, req: incomingRequest, logger, instance }: ServerProps) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<BaseIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async ({ client, ctx, req, logger, instance }: ServerProps) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<BaseIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async ({ ctx, req, client, logger, instance }: ServerProps) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<BaseIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async ({ req, ctx, client, logger, instance }: ServerProps) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const metadata = new ActionMetadataStore()\n const output = await action({ ctx, input, client, type, logger, metadata })\n\n const response = { output, meta: metadata.toJSON() }\n return {\n body: JSON.stringify(response),\n }\n}\n", "import { RetryConfig, axiosRetry } from '@botpress/client'\n\nexport const retryConfig: RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount) => retryCount * 1000,\n}\n", "import * as client from '@botpress/client'\nimport * as common from '../types'\nimport * as types from './types'\n\nexport * from './types'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends common.BaseIntegration>\n implements types.ClientOperations<TIntegration>\n{\n public constructor(private readonly _client: client.Client) {}\n\n public createConversation: types.CreateConversation<TIntegration> = ((x) =>\n this._client.createConversation(x)) as types.CreateConversation<TIntegration>\n public getConversation: types.GetConversation<TIntegration> = ((x) =>\n this._client.getConversation(x)) as types.GetConversation<TIntegration>\n public listConversations: types.ListConversations<TIntegration> = ((x) =>\n this._client.listConversations(x)) as types.ListConversations<TIntegration>\n public getOrCreateConversation: types.GetOrCreateConversation<TIntegration> = ((x) =>\n this._client.getOrCreateConversation(x)) as types.GetOrCreateConversation<TIntegration>\n public updateConversation: types.UpdateConversation<TIntegration> = ((x) =>\n this._client.updateConversation(x)) as types.UpdateConversation<TIntegration>\n public deleteConversation: types.DeleteConversation<TIntegration> = ((x) =>\n this._client.deleteConversation(x)) as types.DeleteConversation<TIntegration>\n\n public listParticipants: types.ListParticipants<TIntegration> = ((x) =>\n this._client.listParticipants(x)) as types.ListParticipants<TIntegration>\n public addParticipant: types.AddParticipant<TIntegration> = ((x) =>\n this._client.addParticipant(x)) as types.AddParticipant<TIntegration>\n public getParticipant: types.GetParticipant<TIntegration> = ((x) =>\n this._client.getParticipant(x)) as types.GetParticipant<TIntegration>\n public removeParticipant: types.RemoveParticipant<TIntegration> = ((x) =>\n this._client.removeParticipant(x)) as types.RemoveParticipant<TIntegration>\n\n public createEvent: types.CreateEvent<TIntegration> = ((x) =>\n this._client.createEvent(x)) as types.CreateEvent<TIntegration>\n public getEvent: types.GetEvent<TIntegration> = ((x) => this._client.getEvent(x)) as types.GetEvent<TIntegration>\n public listEvents: types.ListEvents<TIntegration> = ((x) =>\n this._client.listEvents(x)) as types.ListEvents<TIntegration>\n\n public createMessage: types.CreateMessage<TIntegration> = ((x) =>\n this._client.createMessage(x)) as types.CreateMessage<TIntegration>\n public getOrCreateMessage: types.GetOrCreateMessage<TIntegration> = ((x) =>\n this._client.getOrCreateMessage(x)) as types.GetOrCreateMessage<TIntegration>\n public getMessage: types.GetMessage<TIntegration> = ((x) =>\n this._client.getMessage(x)) as types.GetMessage<TIntegration>\n public updateMessage: types.UpdateMessage<TIntegration> = ((x) =>\n this._client.updateMessage(x)) as types.UpdateMessage<TIntegration>\n public listMessages: types.ListMessages<TIntegration> = ((x) =>\n this._client.listMessages(x)) as types.ListMessages<TIntegration>\n public deleteMessage: types.DeleteMessage<TIntegration> = ((x) =>\n this._client.deleteMessage(x)) as types.DeleteMessage<TIntegration>\n\n public createUser: types.CreateUser<TIntegration> = ((x) =>\n this._client.createUser(x)) as types.CreateUser<TIntegration>\n public getUser: types.GetUser<TIntegration> = ((x) => this._client.getUser(x)) as types.GetUser<TIntegration>\n public listUsers: types.ListUsers<TIntegration> = (x) => this._client.listUsers(x)\n public getOrCreateUser: types.GetOrCreateUser<TIntegration> = ((x) =>\n this._client.getOrCreateUser(x)) as types.GetOrCreateUser<TIntegration>\n public updateUser: types.UpdateUser<TIntegration> = ((x) =>\n this._client.updateUser(x)) as types.UpdateUser<TIntegration>\n public deleteUser: types.DeleteUser<TIntegration> = (x) => this._client.deleteUser(x)\n\n public getState: types.GetState<TIntegration> = ((x) => this._client.getState(x)) as types.GetState<TIntegration>\n public setState: types.SetState<TIntegration> = ((x) => this._client.setState(x)) as types.SetState<TIntegration>\n public getOrSetState: types.GetOrSetState<TIntegration> = ((x) =>\n this._client.getOrSetState(x)) as types.GetOrSetState<TIntegration>\n public patchState: types.PatchState<TIntegration> = ((x) =>\n this._client.patchState(x)) as types.PatchState<TIntegration>\n\n public configureIntegration: types.ConfigureIntegration<TIntegration> = (x) => this._client.configureIntegration(x)\n\n public uploadFile: types.UploadFile<TIntegration> = (x) => this._client.uploadFile(x)\n public upsertFile: types.UpsertFile<TIntegration> = (x) => this._client.upsertFile(x)\n public deleteFile: types.DeleteFile<TIntegration> = (x) => this._client.deleteFile(x)\n public listFiles: types.ListFiles<TIntegration> = (x) => this._client.listFiles(x)\n public getFile: types.GetFile<TIntegration> = (x) => this._client.getFile(x)\n public updateFileMetadata: types.UpdateFileMetadata<TIntegration> = (x) => this._client.updateFileMetadata(x)\n}\n", "export type ActionMetadata = {\n cost: number\n}\n\nexport class ActionMetadataStore {\n private _cost: number = 0\n\n public get cost(): number {\n return this._cost\n }\n\n public setCost(cost: number): void {\n this._cost = cost\n }\n\n public toJSON(): ActionMetadata {\n return {\n cost: this.cost,\n }\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n configurationTypeHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../../const'\nimport { IntegrationContext } from './types'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const configurationType = headers[configurationTypeHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configurationType: configurationType ?? null,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import util from 'util'\n\ntype LogLevel = 'info' | 'debug' | 'warn' | 'error'\n\nexport abstract class BaseLogger<TOptions extends object> {\n protected defaultOptions: TOptions\n\n protected constructor(defaultOptions: TOptions) {\n this.defaultOptions = defaultOptions\n }\n\n public abstract with(options: TOptions): BaseLogger<TOptions>\n\n public info(...args: Parameters<typeof console.info>) {\n this._log('info', args)\n }\n\n public debug(...args: Parameters<typeof console.debug>) {\n this._log('debug', args)\n }\n\n public warn(...args: Parameters<typeof console.warn>) {\n this._log('warn', args)\n }\n\n public error(...args: Parameters<typeof console.error>) {\n this._log('error', args)\n }\n\n private _log(level: LogLevel, args: Parameters<typeof console.info>) {\n this._getConsoleMethod(level)(this._serializeMessage(args))\n }\n\n private _serializeMessage(args: Parameters<typeof console.info>) {\n const msg = util.format(...args)\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return this.getJsonMessage(msg)\n } else {\n return msg\n }\n }\n\n protected getJsonMessage(msg: string) {\n return JSON.stringify({ msg, options: this.defaultOptions })\n }\n\n private _getConsoleMethod(level: LogLevel): (...args: any[]) => void {\n switch (level) {\n case 'debug':\n return console.debug\n case 'warn':\n return console.warn\n case 'error':\n return console.error\n default:\n return console.info\n }\n }\n}\n", "import { BaseLogger } from '../../base-logger'\n\ntype IntegrationLogOptions = {\n userId?: string\n conversationId?: string\n visibleToBotOwners?: boolean\n}\n\nexport class IntegrationLogger extends BaseLogger<IntegrationLogOptions> {\n public constructor(options?: IntegrationLogOptions) {\n super({\n visibleToBotOwners: true,\n ...options,\n })\n }\n\n public override with(options: IntegrationLogOptions) {\n return new IntegrationLogger({ ...this.defaultOptions, ...options })\n }\n\n public withUserId(userId: string) {\n return this.with({\n userId,\n })\n }\n\n public withConversationId(conversationId: string) {\n return this.with({\n conversationId,\n })\n }\n\n public withVisibleToBotOwners(visibleToBotOwners: boolean) {\n return this.with({\n visibleToBotOwners,\n })\n }\n\n public forBot() {\n return this.withVisibleToBotOwners(true)\n }\n\n protected override getJsonMessage(msg: string) {\n return JSON.stringify({\n msg,\n //We need to have snake case 'visible_to_bot_owner' since that is how we used to differentiate between bot and integration logs\n visible_to_bot_owner: this.defaultOptions.visibleToBotOwners,\n options: this.defaultOptions,\n })\n }\n}\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport {\n RegisterHandler as RegisterFunction,\n UnregisterHandler as UnregisterFunction,\n WebhookHandler as WebhookFunction,\n CreateUserHandler as CreateUserFunction,\n CreateConversationHandler as CreateConversationFunction,\n ActionHandlers as ActionFunctions,\n ChannelHandlers as ChannelFunctions,\n integrationHandler,\n} from './server'\nimport { BaseIntegration } from './types'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(public readonly props: IntegrationImplementationProps<TIntegration>) {\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler(this as IntegrationImplementation<any>)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { IntegrationPackage, PluginPackage } from '../package'\nimport { SchemaDefinition } from '../schema'\nimport { ValueOf, Writable } from '../utils/type-utils'\nimport z, { ZuiObjectSchema } from '../zui'\n\ntype BaseConfig = ZuiObjectSchema\ntype BaseStates = Record<string, ZuiObjectSchema>\ntype BaseEvents = Record<string, ZuiObjectSchema>\ntype BaseActions = Record<string, ZuiObjectSchema>\n\nexport type TagDefinition = {\n title?: string\n description?: string\n}\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\nexport type RecurringEventDefinition<TEvents extends BaseEvents = BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\nexport type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = SchemaDefinition<TEvent>\n\nexport type ConfigurationDefinition<TConfig extends BaseConfig = BaseConfig> = SchemaDefinition<TConfig>\n\nexport type UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type ActionDefinition<TAction extends BaseActions[string] = BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<ZuiObjectSchema> // cannot infer both input and output types (typescript limitation)\n}\n\nexport type IntegrationConfigInstance<I extends IntegrationPackage = IntegrationPackage> = {\n enabled: boolean\n} & (\n | {\n configurationType?: null\n configuration: z.infer<NonNullable<I['definition']['configuration']>['schema']>\n }\n | ValueOf<{\n [K in keyof NonNullable<I['definition']['configurations']>]: {\n configurationType: K\n configuration: z.infer<NonNullable<I['definition']['configurations']>[K]['schema']>\n }\n }>\n)\n\nexport type PluginConfigInstance<P extends PluginPackage = PluginPackage> = {\n configuration: z.infer<NonNullable<P['definition']['configuration']>['schema']>\n interfaces: {\n // TODO: this configuration should be strongly typed so that only the integrations that implement the interface are allowed\n [I in keyof NonNullable<P['definition']['interfaces']>]: { name: string; version: string }\n }\n}\n\nexport type IntegrationInstance = IntegrationPackage & IntegrationConfigInstance\nexport type PluginInstance = PluginPackage & PluginConfigInstance\n\nexport type BotDefinitionProps<\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n> = {\n integrations?: {\n [K: string]: IntegrationInstance\n }\n plugins?: {\n [K: string]: PluginInstance\n }\n user?: UserDefinition\n conversation?: ConversationDefinition\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n}\n\nexport class BotDefinition<\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n> {\n public readonly integrations: this['props']['integrations']\n public readonly plugins: this['props']['plugins']\n public readonly user: this['props']['user']\n public readonly conversation: this['props']['conversation']\n public readonly message: this['props']['message']\n public readonly states: this['props']['states']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly recurringEvents: this['props']['recurringEvents']\n public readonly actions: this['props']['actions']\n public constructor(public readonly props: BotDefinitionProps<TStates, TEvents, TActions>) {\n this.integrations = props.integrations\n this.plugins = props.plugins\n this.user = props.user\n this.conversation = props.conversation\n this.message = props.message\n this.states = props.states\n this.configuration = props.configuration\n this.events = props.events\n this.recurringEvents = props.recurringEvents\n this.actions = props.actions\n }\n\n public addIntegration<I extends IntegrationPackage>(integrationPkg: I, config: IntegrationConfigInstance<I>): this {\n const self = this as Writable<BotDefinition>\n if (!self.integrations) {\n self.integrations = {}\n }\n\n self.integrations[integrationPkg.name] = {\n enabled: config.enabled,\n ...integrationPkg,\n configurationType: config.configurationType as string,\n configuration: config.configuration,\n }\n return this\n }\n\n public addPlugin<P extends PluginPackage>(pluginPkg: P, config: PluginConfigInstance<P>): this {\n const self = this as Writable<BotDefinition>\n if (!self.plugins) {\n self.plugins = {}\n }\n\n self.plugins[pluginPkg.name] = {\n ...pluginPkg,\n configuration: config.configuration,\n interfaces: config.interfaces,\n }\n\n self.user = this._mergeUser(self.user, pluginPkg.definition.user)\n self.conversation = this._mergeConversation(self.conversation, pluginPkg.definition.conversation)\n self.message = this._mergeMessage(self.message, pluginPkg.definition.message)\n self.states = this._mergeStates(self.states, pluginPkg.definition.states)\n self.events = this._mergeEvents(self.events, pluginPkg.definition.events)\n self.recurringEvents = this._mergeRecurringEvents(self.recurringEvents, pluginPkg.definition.recurringEvents)\n self.actions = this._mergeActions(self.actions, pluginPkg.definition.actions)\n\n return this\n }\n\n private _mergeUser = (\n user1: BotDefinitionProps['user'],\n user2: BotDefinitionProps['user']\n ): BotDefinitionProps['user'] => {\n return {\n tags: {\n ...user1?.tags,\n ...user2?.tags,\n },\n }\n }\n\n private _mergeConversation = (\n conversation1: BotDefinitionProps['conversation'],\n conversation2: BotDefinitionProps['conversation']\n ): BotDefinitionProps['conversation'] => {\n return {\n tags: {\n ...conversation1?.tags,\n ...conversation2?.tags,\n },\n }\n }\n\n private _mergeMessage = (\n message1: BotDefinitionProps['message'],\n message2: BotDefinitionProps['message']\n ): BotDefinitionProps['message'] => {\n return {\n tags: {\n ...message1?.tags,\n ...message2?.tags,\n },\n }\n }\n\n private _mergeStates = (\n states1: BotDefinitionProps['states'],\n states2: BotDefinitionProps['states']\n ): BotDefinitionProps['states'] => {\n return {\n ...states1,\n ...states2,\n }\n }\n\n private _mergeEvents = (\n events1: BotDefinitionProps['events'],\n events2: BotDefinitionProps['events']\n ): BotDefinitionProps['events'] => {\n return {\n ...events1,\n ...events2,\n }\n }\n\n private _mergeRecurringEvents = (\n recurringEvents1: BotDefinitionProps['recurringEvents'],\n recurringEvents2: BotDefinitionProps['recurringEvents']\n ): BotDefinitionProps['recurringEvents'] => {\n return {\n ...recurringEvents1,\n ...recurringEvents2,\n }\n }\n\n private _mergeActions = (\n actions1: BotDefinitionProps['actions'],\n actions2: BotDefinitionProps['actions']\n ): BotDefinitionProps['actions'] => {\n return {\n ...actions1,\n ...actions2,\n }\n }\n}\n", "import * as utils from '../utils'\nimport { BotHandlers } from './server'\n\nexport const mergeBots = (dest: BotHandlers<any>, src: BotHandlers<any>) => {\n for (const [type, actionHandler] of Object.entries(src.actionHandlers)) {\n dest.actionHandlers[type] = actionHandler\n }\n\n for (const [type, handlers] of Object.entries(src.eventHandlers)) {\n if (!handlers) {\n continue\n }\n dest.eventHandlers[type] = utils.arrays.safePush(dest.eventHandlers[type], ...handlers)\n }\n\n for (const [type, handlers] of Object.entries(src.messageHandlers)) {\n if (!handlers) {\n continue\n }\n dest.messageHandlers[type] = utils.arrays.safePush(dest.messageHandlers[type], ...handlers)\n }\n\n for (const [type, handlers] of Object.entries(src.stateExpiredHandlers)) {\n if (!handlers) {\n continue\n }\n // TODO: address this type issue\n // @ts-ignore\n dest.stateExpiredHandlers[type] = utils.arrays.safePush(dest.stateExpiredHandlers[type], ...handlers)\n }\n\n for (const [hook, types] of Object.entries(src.hookHandlers)) {\n for (const [type, handlers] of Object.entries(types)) {\n if (!handlers) {\n continue\n }\n // TODO: address this type issue\n // @ts-ignore\n dest.hookHandlers[hook]![type] = utils.arrays.safePush(dest.hookHandlers[hook]![type], ...handlers)\n }\n }\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../../log'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody } from '../../serve'\nimport * as utils from '../../utils/type-utils'\nimport { BotLogger } from '../bot-logger'\nimport { BotSpecificClient } from '../client'\nimport * as common from '../types'\nimport { extractContext } from './context'\nimport * as types from './types'\n\nexport * from './types'\n\ntype ServerProps = types.CommonHandlerProps<common.BaseBot> & {\n req: Request\n self: types.BotHandlers<common.BaseBot>\n}\n\nconst SUCCESS_RESPONSE = { status: 200 }\n\nexport const botHandler =\n (bot: types.BotHandlers<common.BaseBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n const logger = new BotLogger()\n\n const vanillaClient = new client.Client({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<common.BaseBot>(vanillaClient, {\n before: {\n createMessage: async (req) => {\n const specificBeforeOutgoingMessageHooks = bot.hookHandlers.before_outgoing_message[req.type] ?? []\n const globalBeforeOutgoingMessageHooks = bot.hookHandlers.before_outgoing_message['*'] ?? []\n const beforeOutgoingMessageHooks = [\n ...specificBeforeOutgoingMessageHooks,\n ...globalBeforeOutgoingMessageHooks,\n ]\n for (const handler of beforeOutgoingMessageHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: req,\n })\n req = hookOutput?.data ?? req\n }\n return req\n },\n callAction: async (req) => {\n const specificBeforeOutgoingCallActionHooks = bot.hookHandlers.before_outgoing_call_action[req.type] ?? []\n const globalBeforeOutgoingCallActionHooks = bot.hookHandlers.before_outgoing_call_action['*'] ?? []\n const beforeOutgoingCallActionHooks = [\n ...specificBeforeOutgoingCallActionHooks,\n ...globalBeforeOutgoingCallActionHooks,\n ]\n for (const handler of beforeOutgoingCallActionHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: req,\n })\n req = hookOutput?.data ?? req\n }\n return req\n },\n },\n after: {\n createMessage: async (res) => {\n const specificAfterOutgoingMessageHooks = bot.hookHandlers.after_outgoing_message[res.message.type] ?? []\n const globalAfterOutgoingMessageHooks = bot.hookHandlers.after_outgoing_message['*'] ?? []\n const afterOutgoingMessageHooks = [...specificAfterOutgoingMessageHooks, ...globalAfterOutgoingMessageHooks]\n for (const handler of afterOutgoingMessageHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: res,\n })\n res = hookOutput?.data ?? res\n }\n return res\n },\n callAction: async (res) => {\n const specificAfterOutgoingCallActionHooks =\n bot.hookHandlers.after_outgoing_call_action[res.output.type] ?? []\n const globalAfterOutgoingCallActionHooks = bot.hookHandlers.after_outgoing_call_action['*'] ?? []\n const afterOutgoingCallActionHooks = [\n ...specificAfterOutgoingCallActionHooks,\n ...globalAfterOutgoingCallActionHooks,\n ]\n for (const handler of afterOutgoingCallActionHooks) {\n const hookOutput = await handler({\n client: new BotSpecificClient(vanillaClient),\n ctx,\n logger,\n data: res,\n })\n res = hookOutput?.data ?? res\n }\n return res\n },\n },\n })\n\n const props: ServerProps = {\n req,\n ctx,\n logger,\n client: botClient,\n self: bot,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n return await onActionTriggered(props)\n case 'event_received':\n return await onEventReceived(props)\n case 'register':\n return await onRegister(props)\n case 'unregister':\n return await onUnregister(props)\n case 'ping':\n return await onPing(props)\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n }\n\nconst onPing = async ({ ctx }: ServerProps): Promise<Response> => {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n return SUCCESS_RESPONSE\n}\n\nconst onRegister = async (_: ServerProps): Promise<Response> => SUCCESS_RESPONSE\n\nconst onUnregister = async (_: ServerProps): Promise<Response> => SUCCESS_RESPONSE\n\nconst onEventReceived = async ({ ctx, logger, req, client, self }: ServerProps): Promise<Response> => {\n log.debug(`Received event ${ctx.type}`)\n\n type AnyEventPayload = utils.ValueOf<types.EventPayloads<common.BaseBot>>\n const body = parseBody<AnyEventPayload>(req)\n\n if (ctx.type === 'message_created') {\n const event = body.event\n let message: client.Message = event.payload.message\n const specificBeforeIncomingMessageHooks = self.hookHandlers.before_incoming_message[message.type] ?? []\n const globalBeforeIncomingMessageHooks = self.hookHandlers.before_incoming_message['*'] ?? []\n const beforeIncomingMessageHooks = [...specificBeforeIncomingMessageHooks, ...globalBeforeIncomingMessageHooks]\n for (const handler of beforeIncomingMessageHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n logger,\n data: message,\n })\n message = hookOutput?.data ?? message\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n const messagePayload: utils.ValueOf<types.MessagePayloads<common.BaseBot>> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n states: event.payload.states,\n message,\n event,\n }\n\n const specificMessageHandlers = self.messageHandlers[message.type] ?? []\n const globalMessageHandlers = self.messageHandlers['*'] ?? []\n const messageHandlers = [...specificMessageHandlers, ...globalMessageHandlers]\n\n for (const handler of messageHandlers) {\n await handler({\n ...messagePayload,\n client,\n ctx,\n logger,\n })\n }\n\n const specificAfterIncomingMessageHooks = self.hookHandlers.after_incoming_message[message.type] ?? []\n const globalAfterIncomingMessageHooks = self.hookHandlers.after_incoming_message['*'] ?? []\n const afterIncomingMessageHooks = [...specificAfterIncomingMessageHooks, ...globalAfterIncomingMessageHooks]\n for (const handler of afterIncomingMessageHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n data: message,\n logger,\n })\n message = hookOutput?.data ?? message\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n return SUCCESS_RESPONSE\n }\n\n if (ctx.type === 'state_expired') {\n const event = body.event\n const state: client.State = event.payload.state\n const statePayload: utils.ValueOf<types.StateExpiredPayloads<common.BaseBot>> = { state }\n\n const stateHandlers = self.stateExpiredHandlers['*'] ?? []\n for (const handler of stateHandlers) {\n await handler({\n ...statePayload,\n client,\n ctx,\n logger,\n })\n }\n return SUCCESS_RESPONSE\n }\n\n let event = body.event\n const sepcificBeforeIncomingEventHooks = self.hookHandlers.before_incoming_event[event.type] ?? []\n const globalBeforeIncomingEventHooks = self.hookHandlers.before_incoming_event['*'] ?? []\n const beforeIncomingEventHooks = [...sepcificBeforeIncomingEventHooks, ...globalBeforeIncomingEventHooks]\n for (const handler of beforeIncomingEventHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n data: event,\n logger,\n })\n event = hookOutput?.data ?? event\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n const eventPayload = { event }\n\n const specificEventHandlers = self.eventHandlers[event.type] ?? []\n const globalEventHandlers = self.eventHandlers['*'] ?? []\n const eventHandlers = [...specificEventHandlers, ...globalEventHandlers]\n for (const handler of eventHandlers) {\n await handler({\n ...eventPayload,\n client,\n ctx,\n logger,\n })\n }\n\n const specificAfterIncomingEventHooks = self.hookHandlers.after_incoming_event[event.type] ?? []\n const globalAfterIncomingEventHooks = self.hookHandlers.after_incoming_event['*'] ?? []\n const afterIncomingEventHooks = [...specificAfterIncomingEventHooks, ...globalAfterIncomingEventHooks]\n for (const handler of afterIncomingEventHooks) {\n const hookOutput = await handler({\n client,\n ctx,\n data: event,\n logger,\n })\n event = hookOutput?.data ?? event\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n return SUCCESS_RESPONSE\n}\n\nconst onActionTriggered = async ({ ctx, logger, req, client, self }: ServerProps): Promise<Response> => {\n type AnyActionPayload = utils.ValueOf<types.ActionHandlerPayloads<common.BaseBot>>\n const { input, type } = parseBody<AnyActionPayload>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = self.actionHandlers[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, logger, input, client, type })\n\n const response = { output }\n return {\n status: 200,\n body: JSON.stringify(response),\n }\n}\n", "import { BaseLogger } from '../base-logger'\n\ntype BotLogOptions = {\n userId?: string\n conversationId?: string\n workflowId?: string\n}\n\nexport class BotLogger extends BaseLogger<BotLogOptions> {\n public constructor(options?: BotLogOptions) {\n super({\n ...options,\n })\n }\n\n public override with(options: BotLogOptions) {\n return new BotLogger({ ...this.defaultOptions, ...options })\n }\n\n public withUserId(userId: string) {\n return this.with({\n userId,\n })\n }\n\n public withConversationId(conversationId: string) {\n return this.with({\n conversationId,\n })\n }\n\n public withWorkflowId(workflowId: string) {\n return this.with({\n workflowId,\n })\n }\n}\n", "import * as client from '@botpress/client'\nimport * as common from '../types'\nimport * as types from './types'\n\nexport * from './types'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends common.BaseBot> implements types.ClientOperations<TBot> {\n public constructor(\n private _client: client.Client,\n private _hooks: types.ClientHooks = { before: {}, after: {} }\n ) {}\n\n public getConversation: types.GetConversation<TBot> = ((x) =>\n this._run('getConversation', x)) as types.GetConversation<TBot>\n public listConversations: types.ListConversations<TBot> = ((x) =>\n this._run('listConversations', x)) as types.ListConversations<TBot>\n public updateConversation: types.UpdateConversation<TBot> = ((x) =>\n this._run('updateConversation', x)) as types.UpdateConversation<TBot>\n public deleteConversation: types.DeleteConversation<TBot> = ((x) =>\n this._run('deleteConversation', x)) as types.DeleteConversation<TBot>\n public listParticipants: types.ListParticipants<TBot> = ((x) =>\n this._run('listParticipants', x)) as types.ListParticipants<TBot>\n public addParticipant: types.AddParticipant<TBot> = ((x) =>\n this._run('addParticipant', x)) as types.AddParticipant<TBot>\n public getParticipant: types.GetParticipant<TBot> = ((x) =>\n this._run('getParticipant', x)) as types.GetParticipant<TBot>\n public removeParticipant: types.RemoveParticipant<TBot> = ((x) =>\n this._run('removeParticipant', x)) as types.RemoveParticipant<TBot>\n public getEvent: types.GetEvent<TBot> = ((x) => this._run('getEvent', x)) as types.GetEvent<TBot>\n public listEvents: types.ListEvents<TBot> = ((x) => this._run('listEvents', x)) as types.ListEvents<TBot>\n public createMessage: types.CreateMessage<TBot> = ((x) => this._run('createMessage', x)) as types.CreateMessage<TBot>\n public getOrCreateMessage: types.GetOrCreateMessage<TBot> = ((x) =>\n this._run('getOrCreateMessage', x)) as types.GetOrCreateMessage<TBot>\n public getMessage: types.GetMessage<TBot> = ((x) => this._run('getMessage', x)) as types.GetMessage<TBot>\n public updateMessage: types.UpdateMessage<TBot> = ((x) => this._run('updateMessage', x)) as types.UpdateMessage<TBot>\n public listMessages: types.ListMessages<TBot> = ((x) => this._run('listMessages', x)) as types.ListMessages<TBot>\n public deleteMessage: types.DeleteMessage<TBot> = ((x) => this._run('deleteMessage', x)) as types.DeleteMessage<TBot>\n public getUser: types.GetUser<TBot> = ((x) => this._run('getUser', x)) as types.GetUser<TBot>\n public listUsers: types.ListUsers<TBot> = ((x) => this._run('listUsers', x)) as types.ListUsers<TBot>\n public updateUser: types.UpdateUser<TBot> = ((x) => this._run('updateUser', x)) as types.UpdateUser<TBot>\n public deleteUser: types.DeleteUser<TBot> = ((x) => this._run('deleteUser', x)) as types.DeleteUser<TBot>\n public getState: types.GetState<TBot> = ((x) => this._run('getState', x)) as types.GetState<TBot>\n public setState: types.SetState<TBot> = ((x) => this._run('setState', x)) as types.SetState<TBot>\n public getOrSetState: types.GetOrSetState<TBot> = ((x) => this._run('getOrSetState', x)) as types.GetOrSetState<TBot>\n public patchState: types.PatchState<TBot> = ((x) => this._run('patchState', x)) as types.PatchState<TBot>\n public callAction: types.CallAction<TBot> = ((x) => this._run('callAction', x)) as types.CallAction<TBot>\n public uploadFile: types.UploadFile<TBot> = ((x) => this._run('uploadFile', x)) as types.UploadFile<TBot>\n public upsertFile: types.UpsertFile<TBot> = ((x) => this._run('upsertFile', x)) as types.UpsertFile<TBot>\n public deleteFile: types.DeleteFile<TBot> = ((x) => this._run('deleteFile', x)) as types.DeleteFile<TBot>\n public listFiles: types.ListFiles<TBot> = ((x) => this._run('listFiles', x)) as types.ListFiles<TBot>\n public getFile: types.GetFile<TBot> = ((x) => this._run('getFile', x)) as types.GetFile<TBot>\n public updateFileMetadata: types.UpdateFileMetadata<TBot> = ((x) =>\n this._run('updateFileMetadata', x)) as types.UpdateFileMetadata<TBot>\n public searchFiles: types.SearchFiles<TBot> = ((x) => this._run('searchFiles', x)) as types.SearchFiles<TBot>\n public trackAnalytics: types.TrackAnalytics<TBot> = ((x) =>\n this._run('trackAnalytics', x)) as types.TrackAnalytics<TBot>\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: types.CreateConversation<TBot> = (x) => this._client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: types.GetOrCreateConversation<TBot> = (x) => this._client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: types.CreateUser<TBot> = (x) => this._client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: types.GetOrCreateUser<TBot> = (x) => this._client.getOrCreateUser(x)\n\n private _run = async <K extends client.Operation>(\n operation: K,\n req: client.ClientInputs[K]\n ): Promise<client.ClientOutputs[K]> => {\n const before = this._hooks.before[operation]\n if (before) {\n req = await before(req)\n }\n\n let res = (await this._client[operation](req as any)) as client.ClientOutputs[K]\n\n const after = this._hooks.after[operation]\n if (after) {\n res = await after(res)\n }\n\n return res\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../../const'\nimport { BotContext } from './types'\n\nconst botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import type { Server } from 'node:http'\nimport { BasePlugin, PluginImplementation } from '../plugin'\nimport { serve } from '../serve'\nimport * as utils from '../utils'\nimport { mergeBots } from './merge-bots'\nimport {\n botHandler,\n MessageHandlersMap,\n MessageHandlers,\n EventHandlersMap,\n EventHandlers,\n StateExpiredHandlersMap,\n StateExpiredHandlers,\n HookHandlersMap,\n HookData,\n HookHandlers,\n ActionHandlers,\n BotHandlers,\n UnimplementedActionHandlers,\n} from './server'\nimport { BaseBot } from './types'\n\nexport type BotImplementationProps<TBot extends BaseBot = BaseBot, TPlugins extends Record<string, BasePlugin> = {}> = {\n actions: UnimplementedActionHandlers<TBot, TPlugins>\n plugins: {\n [K in keyof TPlugins]: PluginImplementation<TPlugins[K]>\n }\n}\n\nexport class BotImplementation<TBot extends BaseBot = BaseBot, TPlugins extends Record<string, BasePlugin> = {}>\n implements BotHandlers<TBot>\n{\n public readonly actionHandlers: ActionHandlers<TBot>\n public readonly messageHandlers: MessageHandlersMap<TBot> = {}\n public readonly eventHandlers: EventHandlersMap<TBot> = {}\n public readonly stateExpiredHandlers: StateExpiredHandlersMap<TBot> = {}\n public readonly hookHandlers: HookHandlersMap<TBot> = {\n before_incoming_event: {},\n before_incoming_message: {},\n before_outgoing_message: {},\n before_outgoing_call_action: {},\n after_incoming_event: {},\n after_incoming_message: {},\n after_outgoing_message: {},\n after_outgoing_call_action: {},\n }\n\n /**\n * alias for actionHandlers\n */\n public get actions() {\n return this.actionHandlers\n }\n\n public constructor(public readonly props: BotImplementationProps<TBot, TPlugins>) {\n this.actionHandlers = props.actions as ActionHandlers<TBot>\n const plugins = utils.records.values(props.plugins)\n for (const plugin of plugins) {\n this._use(plugin as BotHandlers<any>)\n }\n }\n\n public readonly on = {\n message: <T extends keyof MessageHandlersMap<TBot>>(type: T, handler: MessageHandlers<TBot>[T]): void => {\n this.messageHandlers[type] = utils.arrays.safePush(this.messageHandlers[type], handler)\n },\n event: <T extends keyof EventHandlersMap<TBot>>(type: T, handler: EventHandlers<TBot>[T]): void => {\n this.eventHandlers[type] = utils.arrays.safePush(this.eventHandlers[type], handler)\n },\n stateExpired: <T extends keyof StateExpiredHandlersMap<TBot>>(\n type: T,\n handler: StateExpiredHandlers<TBot>[T]\n ): void => {\n this.stateExpiredHandlers[type] = utils.arrays.safePush(this.stateExpiredHandlers[type], handler)\n },\n beforeIncomingEvent: <T extends keyof HookData<TBot>['before_incoming_event']>(\n type: T,\n handler: HookHandlers<TBot>['before_incoming_event'][T]\n ) => {\n this.hookHandlers.before_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_event[type],\n handler\n )\n },\n beforeIncomingMessage: <T extends keyof HookData<TBot>['before_incoming_message']>(\n type: T,\n handler: HookHandlers<TBot>['before_incoming_message'][T]\n ) => {\n this.hookHandlers.before_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_message[type],\n handler\n )\n },\n beforeOutgoingMessage: <T extends keyof HookData<TBot>['before_outgoing_message']>(\n type: T,\n handler: HookHandlers<TBot>['before_outgoing_message'][T]\n ) => {\n this.hookHandlers.before_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_message[type],\n handler\n )\n },\n beforeOutgoingCallAction: <T extends keyof HookData<TBot>['before_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TBot>['before_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.before_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_call_action[type],\n handler\n )\n },\n afterIncomingEvent: <T extends keyof HookData<TBot>['after_incoming_event']>(\n type: T,\n handler: HookHandlers<TBot>['after_incoming_event'][T]\n ) => {\n this.hookHandlers.after_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_event[type],\n handler\n )\n },\n afterIncomingMessage: <T extends keyof HookData<TBot>['after_incoming_message']>(\n type: T,\n handler: HookHandlers<TBot>['after_incoming_message'][T]\n ) => {\n this.hookHandlers.after_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_message[type],\n handler\n )\n },\n afterOutgoingMessage: <T extends keyof HookData<TBot>['after_outgoing_message']>(\n type: T,\n handler: HookHandlers<TBot>['after_outgoing_message'][T]\n ) => {\n this.hookHandlers.after_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_message[type],\n handler\n )\n },\n afterOutgoingCallAction: <T extends keyof HookData<TBot>['after_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TBot>['after_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.after_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_call_action[type],\n handler\n )\n },\n }\n\n private readonly _use = (botLike: BotHandlers<any>): void => {\n mergeBots(this as BotHandlers<any>, botLike)\n }\n\n public readonly handler = botHandler(this as BotHandlers<any>)\n\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { ActionDefinition, ChannelDefinition, EntityDefinition, EventDefinition } from '../integration/definition'\nimport * as utils from '../utils'\nimport z, { ZuiObjectSchema, GenericZuiSchema, ZodRef } from '../zui'\n\ntype BaseEvents = Record<string, ZuiObjectSchema>\ntype BaseActions = Record<string, ZuiObjectSchema>\ntype BaseMessages = Record<string, ZuiObjectSchema>\ntype BaseChannels = Record<string, BaseMessages>\ntype BaseEntities = Record<string, ZuiObjectSchema>\n\ntype EntityReferences<TEntities extends BaseEntities> = {\n [K in keyof TEntities]: ZodRef\n}\n\ntype GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TEvent>\n}\n\ntype GenericChannelDefinition<\n TEntities extends BaseEntities,\n TChannel extends BaseChannels[string] = BaseChannels[string],\n> = {\n messages: {\n [K in keyof TChannel]: {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>\n }\n }\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string],\n> = {\n title?: string\n description?: string\n billable?: boolean\n cacheable?: boolean\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, ZuiObjectSchema> }\n}\n\nexport type InterfaceDefinitionProps<\n TName extends string = string,\n TVersion extends string = string,\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities,\n TChannels extends BaseChannels = BaseChannels,\n> = {\n name: TName\n version: TVersion\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n events?: { [K in keyof TEvents]: GenericEventDefinition<TEntities, TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: GenericActionDefinition<TEntities, TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>\n }\n\n templateName?: string\n}\n\nexport class InterfaceDefinition<\n TName extends string = string,\n TVersion extends string = string,\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents,\n TChannels extends BaseChannels = BaseChannels,\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\n public readonly entities: { [K in keyof TEntities]: EntityDefinition<TEntities[K]> }\n public readonly events: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n public readonly actions: { [K in keyof TActions]: ActionDefinition<TActions[K]> }\n public readonly channels: { [K in keyof TChannels]: ChannelDefinition<TChannels[K]> }\n\n public readonly templateName: this['props']['templateName']\n\n public constructor(\n public readonly props: InterfaceDefinitionProps<TName, TVersion, TEntities, TActions, TEvents, TChannels>\n ) {\n this.name = props.name\n this.version = props.version\n this.entities = props.entities ?? ({} as this['entities'])\n this.templateName = props.templateName\n\n const entityReferences = this._getEntityReference(this.entities)\n\n const events: Record<string, EventDefinition> =\n props.events === undefined\n ? {}\n : utils.records.mapValues(\n props.events,\n (event): EventDefinition => ({\n ...event,\n schema: event.schema(entityReferences),\n })\n )\n\n const actions: Record<string, ActionDefinition> =\n props.actions === undefined\n ? {}\n : utils.records.mapValues(\n props.actions,\n (action): ActionDefinition => ({\n ...action,\n input: {\n ...action.input,\n schema: action.input.schema(entityReferences),\n },\n output: {\n ...action.output,\n schema: action.output.schema(entityReferences),\n },\n })\n )\n\n const channels: Record<string, ChannelDefinition> =\n props.channels === undefined\n ? {}\n : utils.records.mapValues(\n props.channels,\n (channel): ChannelDefinition => ({\n ...channel,\n messages: utils.records.mapValues(channel.messages, (message) => ({\n ...message,\n schema: message.schema(entityReferences),\n })),\n })\n )\n\n this.events = events as this['events']\n this.actions = actions as this['actions']\n this.channels = channels as this['channels']\n }\n\n private _getEntityReference = (entities: Record<string, EntityDefinition>): EntityReferences<TEntities> => {\n const entityReferences: Record<string, ZodRef> = {} as EntityReferences<TEntities>\n for (const [entityName, entityDef] of Object.entries(entities)) {\n const title = entityDef.schema._def['x-zui']?.title\n const description = entityDef.schema._def.description\n\n const refSchema = z.ref(entityName)\n if (title) {\n refSchema.title(title)\n }\n if (description) {\n refSchema.describe(description)\n }\n\n entityReferences[entityName] = refSchema\n }\n return entityReferences as EntityReferences<TEntities>\n }\n}\n", "import {\n StateDefinition,\n RecurringEventDefinition,\n EventDefinition,\n ConfigurationDefinition,\n UserDefinition,\n ConversationDefinition,\n MessageDefinition,\n ActionDefinition,\n} from '../bot/definition'\nimport { IntegrationPackage, InterfacePackage } from '../package'\nimport { ZuiObjectSchema } from '../zui'\n\nexport {\n StateDefinition,\n RecurringEventDefinition,\n EventDefinition,\n ConfigurationDefinition,\n UserDefinition,\n ConversationDefinition,\n MessageDefinition,\n ActionDefinition,\n IntegrationConfigInstance,\n} from '../bot/definition'\n\ntype BaseConfig = ZuiObjectSchema\ntype BaseStates = Record<string, ZuiObjectSchema>\ntype BaseEvents = Record<string, ZuiObjectSchema>\ntype BaseActions = Record<string, ZuiObjectSchema>\ntype BaseInterfaces = Record<string, any>\ntype BaseIntegrations = Record<string, any>\n\nexport type PluginDefinitionProps<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TInterfaces extends BaseInterfaces = BaseInterfaces,\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n> = {\n name: TName\n version: TVersion\n integrations?: {\n [K in keyof TIntegrations]: IntegrationPackage\n }\n interfaces?: {\n [K in keyof TInterfaces]: InterfacePackage\n }\n user?: UserDefinition\n conversation?: ConversationDefinition\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition<TConfig>\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n}\n\nexport class PluginDefinition<\n TName extends string = string,\n TVersion extends string = string,\n TConfig extends BaseConfig = BaseConfig,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TInterfaces extends BaseInterfaces = BaseInterfaces,\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\n public readonly integrations: this['props']['integrations']\n public readonly interfaces: this['props']['interfaces']\n\n public readonly user: this['props']['user']\n public readonly conversation: this['props']['conversation']\n public readonly message: this['props']['message']\n public readonly states: this['props']['states']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly recurringEvents: this['props']['recurringEvents']\n public readonly actions: this['props']['actions']\n\n public constructor(\n public readonly props: PluginDefinitionProps<\n TName,\n TVersion,\n TConfig,\n TStates,\n TEvents,\n TActions,\n TInterfaces,\n TIntegrations\n >\n ) {\n this.name = props.name\n this.version = props.version\n this.integrations = props.integrations\n this.interfaces = props.interfaces\n this.user = props.user\n this.conversation = props.conversation\n this.message = props.message\n this.states = props.states\n this.configuration = props.configuration\n this.events = props.events\n this.recurringEvents = props.recurringEvents\n this.actions = props.actions\n }\n}\n", "import * as utils from '../utils'\nimport {\n MessageHandlersMap,\n MessageHandlers,\n EventHandlersMap,\n EventHandlers,\n StateExpiredHandlersMap,\n StateExpiredHandlers,\n HookHandlersMap,\n HookData,\n HookHandlers,\n ActionHandlers,\n BotHandlers,\n} from './server/types'\nimport { BasePlugin } from './types/generic'\n\nexport type PluginImplementationProps<TPlugin extends BasePlugin = BasePlugin> = {\n actions: ActionHandlers<TPlugin>\n}\n\nexport type PluginRuntimeProps<TPlugin extends BasePlugin = BasePlugin> = {\n configuration: TPlugin['configuration']\n interfaces: {\n [K in keyof TPlugin['interfaces']]: { name: string; version: string }\n }\n}\n\nexport class PluginImplementation<TPlugin extends BasePlugin = BasePlugin> implements BotHandlers<TPlugin> {\n private _runtimeProps: PluginRuntimeProps<TPlugin> | undefined\n\n public readonly actionHandlers: ActionHandlers<TPlugin>\n public readonly messageHandlers: MessageHandlersMap<TPlugin> = {}\n public readonly eventHandlers: EventHandlersMap<TPlugin> = {}\n public readonly stateExpiredHandlers: StateExpiredHandlersMap<TPlugin> = {}\n public readonly hookHandlers: HookHandlersMap<TPlugin> = {\n before_incoming_event: {},\n before_incoming_message: {},\n before_outgoing_message: {},\n before_outgoing_call_action: {},\n after_incoming_event: {},\n after_incoming_message: {},\n after_outgoing_message: {},\n after_outgoing_call_action: {},\n }\n\n public constructor(public readonly props: PluginImplementationProps<TPlugin>) {\n this.actionHandlers = props.actions\n }\n\n public initialize(config: PluginRuntimeProps<TPlugin>): this {\n this._runtimeProps = config\n return this\n }\n\n public get config(): PluginRuntimeProps<TPlugin> {\n if (!this._runtimeProps) {\n throw new Error(\n 'Plugin not correctly initialized. This is likely because you access your plugin config outside of an handler.'\n )\n }\n return this._runtimeProps\n }\n\n public readonly on = {\n message: <T extends keyof MessageHandlersMap<TPlugin>>(type: T, handler: MessageHandlers<TPlugin>[T]): void => {\n this.messageHandlers[type] = utils.arrays.safePush(this.messageHandlers[type], handler)\n },\n event: <T extends keyof EventHandlersMap<TPlugin>>(type: T, handler: EventHandlers<TPlugin>[T]): void => {\n this.eventHandlers[type] = utils.arrays.safePush(this.eventHandlers[type], handler)\n },\n stateExpired: <T extends keyof StateExpiredHandlersMap<TPlugin>>(\n type: T,\n handler: StateExpiredHandlers<TPlugin>[T]\n ): void => {\n this.stateExpiredHandlers[type] = utils.arrays.safePush(this.stateExpiredHandlers[type], handler)\n },\n beforeIncomingEvent: <T extends keyof HookData<TPlugin>['before_incoming_event']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_incoming_event'][T]\n ) => {\n this.hookHandlers.before_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_event[type],\n handler\n )\n },\n beforeIncomingMessage: <T extends keyof HookData<TPlugin>['before_incoming_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_incoming_message'][T]\n ) => {\n this.hookHandlers.before_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_incoming_message[type],\n handler\n )\n },\n beforeOutgoingMessage: <T extends keyof HookData<TPlugin>['before_outgoing_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_outgoing_message'][T]\n ) => {\n this.hookHandlers.before_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_message[type],\n handler\n )\n },\n beforeOutgoingCallAction: <T extends keyof HookData<TPlugin>['before_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TPlugin>['before_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.before_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.before_outgoing_call_action[type],\n handler\n )\n },\n afterIncomingEvent: <T extends keyof HookData<TPlugin>['after_incoming_event']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_incoming_event'][T]\n ) => {\n this.hookHandlers.after_incoming_event[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_event[type],\n handler\n )\n },\n afterIncomingMessage: <T extends keyof HookData<TPlugin>['after_incoming_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_incoming_message'][T]\n ) => {\n this.hookHandlers.after_incoming_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_incoming_message[type],\n handler\n )\n },\n afterOutgoingMessage: <T extends keyof HookData<TPlugin>['after_outgoing_message']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_outgoing_message'][T]\n ) => {\n this.hookHandlers.after_outgoing_message[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_message[type],\n handler\n )\n },\n afterOutgoingCallAction: <T extends keyof HookData<TPlugin>['after_outgoing_call_action']>(\n type: T,\n handler: HookHandlers<TPlugin>['after_outgoing_call_action'][T]\n ) => {\n this.hookHandlers.after_outgoing_call_action[type] = utils.arrays.safePush(\n this.hookHandlers.after_outgoing_call_action[type],\n handler\n )\n },\n }\n}\n"],
|
|
5
|
+
"mappings": "onBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,kBAAAC,EAAA,cAAAC,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,sBAAAC,EAAA,8BAAAC,EAAA,wBAAAC,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G,CACH,KAAK,aAAa,wBAAwBD,CAAI,EAAUE,EAAO,SAC7D,KAAK,aAAa,wBAAwBF,CAAI,EAC9CC,CACF,CACF,EACA,yBAA0B,CACxBD,EACAC,IACG,CACH,KAAK,aAAa,4BAA4BD,CAAI,EAAUE,EAAO,SACjE,KAAK,aAAa,4BAA4BF,CAAI,EAClDC,CACF,CACF,EACA,mBAAoB,CAClBD,EACAC,IACG,CACH,KAAK,aAAa,qBAAqBD,CAAI,EAAUE,EAAO,SAC1D,KAAK,aAAa,qBAAqBF,CAAI,EAC3CC,CACF,CACF,EACA,qBAAsB,CACpBD,EACAC,IACG,CACH,KAAK,aAAa,uBAAuBD,CAAI,EAAUE,EAAO,SAC5D,KAAK,aAAa,uBAAuBF,CAAI,EAC7CC,CACF,CACF,EACA,qBAAsB,CACpBD,EACAC,IACG,CACH,KAAK,aAAa,uBAAuBD,CAAI,EAAUE,EAAO,SAC5D,KAAK,aAAa,uBAAuBF,CAAI,EAC7CC,CACF,CACF,EACA,wBAAyB,CACvBD,EACAC,IACG,CACH,KAAK,aAAa,2BAA2BD,CAAI,EAAUE,EAAO,SAChE,KAAK,aAAa,2BAA2BF,CAAI,EACjDC,CACF,CACF,CACF,CACF",
|
|
6
6
|
"names": ["src_exports", "__export", "BotImplementation", "BotDefinition", "BotLogger", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationLogger", "IntegrationSpecificClient", "InterfaceDefinition", "PluginImplementation", "PluginDefinition", "botIdHeader", "botUserIdHeader", "configurationHeader", "configurationTypeHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "markdown", "zui_exports", "__export", "zui_default", "import_zui", "__reExport", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "markdown", "defaults", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationTypeHeader", "configurationHeader", "operationHeader", "typeHeader", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "__reExport", "src_exports", "zui_exports", "import_client", "record_utils_exports", "__export", "mapValues", "pairs", "values", "obj", "fn", "key", "value", "array_utils_exports", "__export", "safePush", "arr", "values", "schemaName", "createStore", "props", "record_utils_exports", "e", "k", "isBranded", "schema", "getName", "IntegrationDefinition", "props", "interfacePkg", "builder", "extensionBuilderOutput", "createStore", "unbrandedEntity", "record_utils_exports", "_k", "e", "isBranded", "self", "interfaceTypeArguments", "getName", "entityNames", "key", "import_client", "import_client", "retryConfig", "err", "retryCount", "IntegrationSpecificClient", "_client", "x", "ActionMetadataStore", "cost", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "configurationType", "configurationTypeHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "import_util", "BaseLogger", "defaultOptions", "args", "level", "msg", "util", "IntegrationLogger", "BaseLogger", "options", "userId", "conversationId", "visibleToBotOwners", "msg", "integrationHandler", "instance", "req", "ctx", "extractContext", "vanillaClient", "retryConfig", "client", "IntegrationSpecificClient", "logger", "IntegrationLogger", "props", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "error", "runtimeError", "_", "incomingRequest", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "metadata", "ActionMetadataStore", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "BotDefinition", "props", "integrationPkg", "config", "self", "pluginPkg", "user1", "user2", "conversation1", "conversation2", "message1", "message2", "states1", "states2", "events1", "events2", "recurringEvents1", "recurringEvents2", "actions1", "actions2", "mergeBots", "dest", "src", "type", "actionHandler", "handlers", "array_utils_exports", "hook", "types", "client", "BotLogger", "BaseLogger", "options", "userId", "conversationId", "workflowId", "BotSpecificClient", "_client", "_hooks", "x", "operation", "req", "before", "res", "after", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "SUCCESS_RESPONSE", "botHandler", "bot", "req", "ctx", "extractContext", "logger", "BotLogger", "vanillaClient", "retryConfig", "botClient", "BotSpecificClient", "specificBeforeOutgoingMessageHooks", "globalBeforeOutgoingMessageHooks", "beforeOutgoingMessageHooks", "handler", "specificBeforeOutgoingCallActionHooks", "globalBeforeOutgoingCallActionHooks", "beforeOutgoingCallActionHooks", "res", "specificAfterOutgoingMessageHooks", "globalAfterOutgoingMessageHooks", "afterOutgoingMessageHooks", "specificAfterOutgoingCallActionHooks", "globalAfterOutgoingCallActionHooks", "afterOutgoingCallActionHooks", "props", "onActionTriggered", "onEventReceived", "onRegister", "onUnregister", "onPing", "log", "_", "client", "self", "body", "parseBody", "event", "message", "specificBeforeIncomingMessageHooks", "globalBeforeIncomingMessageHooks", "beforeIncomingMessageHooks", "hookOutput", "messagePayload", "specificMessageHandlers", "globalMessageHandlers", "messageHandlers", "specificAfterIncomingMessageHooks", "globalAfterIncomingMessageHooks", "afterIncomingMessageHooks", "statePayload", "stateHandlers", "sepcificBeforeIncomingEventHooks", "globalBeforeIncomingEventHooks", "beforeIncomingEventHooks", "eventPayload", "specificEventHandlers", "globalEventHandlers", "eventHandlers", "specificAfterIncomingEventHooks", "globalAfterIncomingEventHooks", "afterIncomingEventHooks", "input", "type", "action", "response", "BotImplementation", "props", "plugins", "record_utils_exports", "plugin", "type", "handler", "array_utils_exports", "botLike", "mergeBots", "botHandler", "port", "serve", "InterfaceDefinition", "props", "entityReferences", "events", "record_utils_exports", "event", "actions", "action", "channels", "channel", "message", "entities", "entityName", "entityDef", "title", "description", "refSchema", "zui_default", "PluginDefinition", "props", "PluginImplementation", "props", "config", "type", "handler", "array_utils_exports"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botpress/sdk",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.1",
|
|
4
4
|
"description": "Botpress SDK",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
"author": "",
|
|
15
15
|
"license": "MIT",
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@botpress/client": "0.
|
|
18
|
-
"@bpinternal/zui": "0.
|
|
17
|
+
"@botpress/client": "0.41.0",
|
|
18
|
+
"@bpinternal/zui": "0.13.4"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
21
|
"esbuild": "^0.16.12",
|