@holocronlab/botruntime-sdk 6.13.3
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/LICENSE +8 -0
- package/dist/base-logger.d.ts +34 -0
- package/dist/base-logger.test.d.ts +1 -0
- package/dist/bot/bot-logger.d.ts +18 -0
- package/dist/bot/client/index.d.ts +80 -0
- package/dist/bot/client/types.d.ts +254 -0
- package/dist/bot/client/types.test.d.ts +1 -0
- package/dist/bot/common/generic.d.ts +41 -0
- package/dist/bot/common/generic.test.d.ts +1 -0
- package/dist/bot/common/index.d.ts +2 -0
- package/dist/bot/common/types.d.ts +54 -0
- package/dist/bot/common/types.test.d.ts +1 -0
- package/dist/bot/definition.d.ts +214 -0
- package/dist/bot/definition.test.d.ts +1 -0
- package/dist/bot/implementation.d.ts +72 -0
- package/dist/bot/implementation.test.d.ts +1 -0
- package/dist/bot/index.d.ts +6 -0
- package/dist/bot/server/context.d.ts +2 -0
- package/dist/bot/server/index.d.ts +5 -0
- package/dist/bot/server/responses.d.ts +3 -0
- package/dist/bot/server/types.d.ts +423 -0
- package/dist/bot/server/types.test.d.ts +1 -0
- package/dist/bot/server/workflows/update-handler.d.ts +3 -0
- package/dist/bot/server/workflows/update-type-conv.d.ts +2 -0
- package/dist/bot/workflow-proxy/index.d.ts +2 -0
- package/dist/bot/workflow-proxy/proxy.d.ts +17 -0
- package/dist/bot/workflow-proxy/types.d.ts +80 -0
- package/dist/bot/workflow-proxy/types.test.d.ts +1 -0
- package/dist/common/index.d.ts +1 -0
- package/dist/common/recurring-events.d.ts +9 -0
- package/dist/common/recurring-events.test.d.ts +1 -0
- package/dist/common/types.d.ts +8 -0
- package/dist/consts.d.ts +11 -0
- package/dist/errors.d.ts +19 -0
- package/dist/fixtures.d.ts +357 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +7 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.mjs +34 -0
- package/dist/index.mjs.map +7 -0
- package/dist/integration/client/index.d.ts +55 -0
- package/dist/integration/client/sub-types.d.ts +27 -0
- package/dist/integration/client/sub-types.test.d.ts +1 -0
- package/dist/integration/client/types.d.ts +209 -0
- package/dist/integration/client/types.test.d.ts +1 -0
- package/dist/integration/common/generic.d.ts +57 -0
- package/dist/integration/common/generic.test.d.ts +1 -0
- package/dist/integration/common/index.d.ts +1 -0
- package/dist/integration/definition/branded-schema.d.ts +21 -0
- package/dist/integration/definition/definition.test.d.ts +1 -0
- package/dist/integration/definition/generic.d.ts +9 -0
- package/dist/integration/definition/index.d.ts +130 -0
- package/dist/integration/definition/types.d.ts +119 -0
- package/dist/integration/implementation.d.ts +37 -0
- package/dist/integration/index.d.ts +5 -0
- package/dist/integration/server/action-metadata.d.ts +9 -0
- package/dist/integration/server/context.d.ts +4 -0
- package/dist/integration/server/index.d.ts +6 -0
- package/dist/integration/server/integration-logger.d.ts +36 -0
- package/dist/integration/server/types.d.ts +108 -0
- package/dist/interface/common/generic.d.ts +34 -0
- package/dist/interface/common/generic.test.d.ts +1 -0
- package/dist/interface/common/index.d.ts +1 -0
- package/dist/interface/definition.d.ts +87 -0
- package/dist/interface/index.d.ts +2 -0
- package/dist/interface/resolve.d.ts +18 -0
- package/dist/log.d.ts +7 -0
- package/dist/message.d.ts +742 -0
- package/dist/package.d.ts +64 -0
- package/dist/plugin/action-proxy/index.d.ts +2 -0
- package/dist/plugin/action-proxy/proxy.d.ts +5 -0
- package/dist/plugin/action-proxy/types.d.ts +14 -0
- package/dist/plugin/action-proxy/types.test.d.ts +1 -0
- package/dist/plugin/common/generic.d.ts +63 -0
- package/dist/plugin/common/generic.test.d.ts +1 -0
- package/dist/plugin/common/index.d.ts +2 -0
- package/dist/plugin/common/types.d.ts +59 -0
- package/dist/plugin/conversation-proxy/index.d.ts +2 -0
- package/dist/plugin/conversation-proxy/proxy.d.ts +13 -0
- package/dist/plugin/conversation-proxy/types.d.ts +54 -0
- package/dist/plugin/conversation-proxy/types.test.d.ts +1 -0
- package/dist/plugin/definition.d.ts +152 -0
- package/dist/plugin/definition.test.d.ts +1 -0
- package/dist/plugin/event-proxy/index.d.ts +2 -0
- package/dist/plugin/event-proxy/proxy.d.ts +5 -0
- package/dist/plugin/event-proxy/types.d.ts +19 -0
- package/dist/plugin/event-proxy/types.test.d.ts +1 -0
- package/dist/plugin/implementation.d.ts +71 -0
- package/dist/plugin/implementation.test.d.ts +1 -0
- package/dist/plugin/index.d.ts +4 -0
- package/dist/plugin/message-proxy/index.d.ts +2 -0
- package/dist/plugin/message-proxy/proxy.d.ts +13 -0
- package/dist/plugin/message-proxy/types.d.ts +22 -0
- package/dist/plugin/server/index.d.ts +1 -0
- package/dist/plugin/server/types.d.ts +505 -0
- package/dist/plugin/server/types.test.d.ts +1 -0
- package/dist/plugin/state-proxy/index.d.ts +2 -0
- package/dist/plugin/state-proxy/proxy.d.ts +5 -0
- package/dist/plugin/state-proxy/types.d.ts +29 -0
- package/dist/plugin/state-proxy/types.test.d.ts +1 -0
- package/dist/plugin/tag-prefixer.d.ts +10 -0
- package/dist/plugin/tag-prefixer.test.d.ts +1 -0
- package/dist/plugin/user-proxy/index.d.ts +2 -0
- package/dist/plugin/user-proxy/proxy.d.ts +14 -0
- package/dist/plugin/user-proxy/types.d.ts +30 -0
- package/dist/public-consts.d.ts +9 -0
- package/dist/retry.d.ts +2 -0
- package/dist/retry.test.d.ts +1 -0
- package/dist/schema.d.ts +18 -0
- package/dist/serve.d.ts +38 -0
- package/dist/utils/api-paging-utils.d.ts +43 -0
- package/dist/utils/api-paging-utils.test.d.ts +1 -0
- package/dist/utils/array-utils.d.ts +2 -0
- package/dist/utils/error-utils.d.ts +4 -0
- package/dist/utils/function-utils.d.ts +2 -0
- package/dist/utils/function-utils.test.d.ts +1 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/record-utils.d.ts +6 -0
- package/dist/utils/record-utils.test.d.ts +1 -0
- package/dist/utils/type-utils.d.ts +63 -0
- package/dist/utils/type-utils.test.d.ts +1 -0
- package/dist/version-utils.d.ts +18 -0
- package/dist/version.d.ts +1 -0
- package/dist/zui.d.ts +9 -0
- package/package.json +59 -0
- package/readme.md +11 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/public-consts.ts", "../src/serve.ts", "../src/log.ts", "../src/errors.ts", "../src/utils/record-utils.ts", "../src/utils/array-utils.ts", "../src/utils/function-utils.ts", "../src/interface/resolve.ts", "../package.json", "../src/version.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/consts.ts", "../src/utils/error-utils.ts", "../src/base-logger.ts", "../src/integration/server/integration-logger.ts", "../src/integration/implementation.ts", "../src/common/recurring-events.ts", "../src/bot/definition.ts", "../src/bot/server/index.ts", "../src/bot/bot-logger.ts", "../src/bot/client/index.ts", "../src/bot/server/context.ts", "../src/bot/server/responses.ts", "../src/bot/server/workflows/update-type-conv.ts", "../src/bot/server/workflows/update-handler.ts", "../src/plugin/tag-prefixer.ts", "../src/utils/api-paging-utils.ts", "../src/bot/workflow-proxy/proxy.ts", "../src/bot/implementation.ts", "../src/interface/definition.ts", "../src/plugin/definition.ts", "../src/plugin/action-proxy/proxy.ts", "../src/plugin/message-proxy/proxy.ts", "../src/plugin/user-proxy/proxy.ts", "../src/plugin/conversation-proxy/proxy.ts", "../src/plugin/event-proxy/proxy.ts", "../src/plugin/state-proxy/proxy.ts", "../src/plugin/implementation.ts", "../src/version-utils.ts"],
|
|
4
|
+
"sourcesContent": ["export * as messages from './message'\nexport * from './public-consts'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n //\n isApiError,\n RuntimeError,\n} from '@holocronlab/botruntime-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 IntegrationNetworkDefinition,\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 // NOTE: BotHandlers is needed by the Studio, and InjectedBotHandlers is\n // needed for the code generation in the CLI\n BotHandlers,\n InjectedBotHandlers,\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 TableDefinition as BotTableDefinition,\n WorkflowDefinition as BotWorkflowDefinition,\n BotLogger,\n} from './bot'\n\nexport {\n //\n InterfaceDefinition,\n InterfaceDefinitionProps,\n} from './interface'\n\nexport {\n //\n DefaultPlugin,\n PluginDefinition,\n PluginDefinitionProps,\n PluginImplementation as Plugin,\n PluginImplementationProps as PluginProps,\n PluginRuntimeProps,\n PluginHandlers,\n InjectedPluginHandlers,\n} from './plugin'\n\nexport * as version from './version-utils'\n\nexport * as errors from './errors'\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\n/**\n * @deprecated\n */\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n title: NonEmptyString.optional(),\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 blocItemSchema = z.union([\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\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 blocSchema = z.object({\n items: z.array(blocItemSchema),\n})\n\n/**\n * @deprecated use `text` instead\n */\nexport const markdown = {\n schema: markdownMessageSchema,\n}\n\n/**\n * Bloc message that still includes markdown as an item\n *\n * @deprecated use `bloc` instead\n */\nexport const markdownBloc = {\n schema: z.object({\n items: z.array(\n // TODO: replace by a discriminated union\n z.union([\n //\n ...blocItemSchema.options,\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n ])\n ),\n }),\n}\n\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: blocSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import '@holocronlab/botruntime-zui'\n\ndeclare module '@holocronlab/botruntime-zui' {\n export namespace z {\n export type GenericZuiSchema<\n A extends Record<string, z.ZodType> = Record<string, z.ZodType>,\n R extends z.ZodType = z.ZodType,\n > = (typeArguments: A) => R\n\n export type ZuiObjectSchema = z.ZodObject | z.ZodRecord\n export type ZuiObjectOrRefSchema = ZuiObjectSchema | z.ZodRef\n }\n}\n\nexport { z } from '@holocronlab/botruntime-zui'\n", "// This file contains constants that are exported for public use.\n\nexport const WELL_KNOWN_ATTRIBUTES = {\n HIDDEN_IN_STUDIO: { bpActionHiddenInStudio: 'true' },\n AWAIT_RETURN: { bpActionAwaitReturn: 'true' },\n} as const\n\nexport const OAUTH_IDENTIFIER_HEADER = 'x-bp-integration-identifier'\n", "import { InvalidPayloadError, isApiError, RuntimeError } from '@holocronlab/botruntime-client'\nimport { isNode } from 'browser-or-node'\nimport * as http 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 InvalidPayloadError('Missing body')\n }\n\n try {\n return JSON.parse(req.body)\n } catch (thrown: unknown) {\n throw new InvalidPayloadError(thrown instanceof Error ? thrown.message : String(thrown))\n }\n}\n\n/**\n * Maps a thrown handler error to an HTTP response.\n *\n * A deliberately thrown `RuntimeError` indicates a handled, user-facing failure,\n * and an `InvalidPayloadError` indicates a malformed request. Both preserve\n * their original 4xx status so callers do not retry them.\n *\n * Any other error is treated as unhandled and returned as a 500 response so\n * callers can consider it transient.\n */\nexport const handlerErrorToHttpResponse = ({\n thrown,\n unexpectedErrorMessage,\n}: {\n thrown: unknown\n unexpectedErrorMessage: string\n}): { status: number; body: string; error: Error } => {\n const error = thrown instanceof Error ? thrown : new Error(String(thrown))\n\n if (isApiError(error) && (error.type === 'Runtime' || error.type === 'InvalidPayload')) {\n return { status: error.code, body: JSON.stringify(error.toJSON()), error }\n }\n\n const runtimeError = isApiError(error)\n ? new RuntimeError(error.message, error)\n : new RuntimeError(unexpectedErrorMessage, error)\n\n return { status: 500, body: JSON.stringify(runtimeError.toJSON()), error: runtimeError }\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<http.Server> {\n if (!isNode) {\n throw new Error('This function can only be called in Node.js')\n }\n\n const httpModule = require('http') as typeof http\n\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = httpModule.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 (thrown: unknown) {\n const error: string = thrown instanceof Error ? thrown.message : String(thrown)\n log.error('Error while handling request', { error: error ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: error ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: http.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 // The base is only needed so `new URL()` can resolve a relative request URL; only\n // `url.pathname` / `url.search` are read below \u2014 the host is never used. So the no-host\n // case uses a neutral, non-routable placeholder (not a real endpoint): this is a\n // URL()-parsing requirement, not a silent fallback to some default cloud host.\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://localhost'\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: http.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?: unknown): void\n info(message: string, metadata?: unknown): void\n warn(message: string, metadata?: unknown): void\n error(message: string, metadata?: unknown): void\n}\nexport const log: Logger = console\n", "/**\n * Thrown by SDK definition classes (BotDefinition, IntegrationDefinition, PluginDefinition, etc.)\n * for intentional validation errors whose message is already clear.\n *\n * The CLI detects this class to suppress the \"Offending code:\" section that it normally\n * appends to errors thrown during definition file evaluation.\n */\nexport class DefinitionError extends Error {\n /** @internal Marker used by {@link isDefinitionError} to survive esbuild bundle boundaries. */\n public readonly __IS_SDK_ERROR__ = true as const\n public readonly type = 'definition_error' as const\n}\n\n/**\n * Type guard to detect {@link DefinitionError} across esbuild bundle boundaries.\n *\n * Tries `instanceof` first (same bundle), then falls back to the `__IS_SDK_ERROR__` marker\n * and `type` field for cross-bundle cases where esbuild inlines a separate copy of the SDK class.\n */\nexport const isDefinitionError = (error: unknown): error is DefinitionError =>\n error instanceof DefinitionError ||\n (typeof error === 'object' &&\n error !== null &&\n '__IS_SDK_ERROR__' in error &&\n error.__IS_SDK_ERROR__ === true &&\n 'type' in error &&\n error.type === 'definition_error')\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>\nexport const mapKeys = <K1 extends string, K2 extends string, V>(\n obj: Record<K1, V>,\n fn: (key: K1) => K2\n): Record<K2, V> => Object.fromEntries(pairs(obj).map(([key, value]) => [fn(key), value])) as Record<K2, V>\nexport const stripUndefinedProps = <K extends string, V>(obj: Record<K, V | undefined>): Record<K, V> =>\n Object.fromEntries(pairs(obj).filter(([, value]) => value !== undefined)) as Record<K, V>\n\nexport const mergeRecords = <K extends string, V>(\n a: Record<K, V>,\n b: Record<K, V>,\n merge: (v1: V, v2: V) => V\n): Record<K, V> => {\n const allKeys = [...Object.keys(a), ...Object.keys(b)] as K[]\n const uniqueKeys = [...new Set(allKeys)]\n const result: Record<K, V> = {} as Record<K, V>\n for (const key of uniqueKeys) {\n const aValue = a[key]\n const bValue = b[key]\n if (aValue && bValue) {\n result[key] = merge(aValue, bValue)\n } else if (aValue) {\n result[key] = aValue\n } else if (bValue) {\n result[key] = bValue\n }\n }\n return result\n}\n", "export const safePush = <T>(arr: T[] | undefined, ...values: T[]): T[] => (arr ? [...arr, ...values] : [...values])\n\nexport const unique = <T>(arr: T[]): T[] => Array.from(new Set(arr))\n", "export type Func<X extends any[], Y> = (...args: X) => Y\n\nexport const setName = <X extends any[], Y>(f: Func<X, Y>, name: string): Func<X, Y> => {\n Object.defineProperty(f, 'name', { value: name })\n return f\n}\n", "import {\n ActionOverrideProps,\n ChannelOverrideProps,\n EventOverrideProps,\n InterfaceExtension,\n ResolvedInterface,\n} from '../integration'\nimport { InterfacePackage } from '../package'\nimport * as utils from '../utils'\nimport { z } from '../zui'\n\ntype ResolveInterfaceInput = InterfacePackage & {\n entities: Record<string, { name: string; schema: z.ZuiObjectSchema }>\n actions: Record<string, ActionOverrideProps>\n events: Record<string, EventOverrideProps>\n channels: Record<string, ChannelOverrideProps>\n}\n\ntype ResolveInterfaceOutput = {\n resolved: ResolvedInterface\n statement: InterfaceExtension\n}\n\nexport const resolveInterface = (intrface: ResolveInterfaceInput): ResolveInterfaceOutput => {\n const { name, version } = intrface\n\n const resolved: ResolvedInterface = { actions: {}, events: {}, channels: {} }\n const statement: InterfaceExtension = {\n name,\n version,\n entities: utils.records.mapValues(intrface.entities, (entity) => ({ name: entity.name })), // { item: { name: 'issue' } },\n actions: {},\n events: {},\n channels: {},\n }\n\n const entitySchemas = utils.records.mapValues(intrface.entities, (entity) => entity.schema)\n\n // dereference actions\n for (const [actionName, action] of Object.entries(intrface.definition.actions ?? {})) {\n const resolvedInputSchema = action.input.schema.dereference(entitySchemas) as z.AnyZodObject\n const resolvedOutputSchema = action.output.schema.dereference(entitySchemas) as z.AnyZodObject\n\n const newActionName = intrface.actions?.[actionName]?.name ?? actionName\n resolved.actions[newActionName] = {\n ...action,\n ...(intrface.actions?.[actionName] ?? {}),\n input: { schema: resolvedInputSchema },\n output: { schema: resolvedOutputSchema },\n }\n statement.actions[actionName] = { name: newActionName }\n }\n\n // dereference events\n for (const [eventName, event] of Object.entries(intrface.definition.events ?? {})) {\n const resolvedEventSchema = event.schema.dereference(entitySchemas) as z.AnyZodObject\n const newEventName = intrface.events?.[eventName]?.name ?? eventName\n resolved.events[newEventName] = {\n ...event,\n ...(intrface.events?.[eventName] ?? {}),\n schema: resolvedEventSchema,\n }\n statement.events[eventName] = { name: newEventName }\n }\n\n // dereference channels\n for (const [channelName, channel] of Object.entries(intrface.definition.channels ?? {})) {\n const messages: Record<string, { schema: z.AnyZodObject }> = {}\n for (const [messageName, message] of Object.entries(channel.messages)) {\n const resolvedMessageSchema = message.schema.dereference(entitySchemas) as z.AnyZodObject\n // no renaming for messages as they are already contained within a channel that acts as a namespace\n messages[messageName] = { ...message, schema: resolvedMessageSchema }\n }\n const newChannelName = intrface.channels?.[channelName]?.name ?? channelName\n resolved.channels[newChannelName] = {\n ...channel,\n ...(intrface.channels?.[channelName] ?? {}),\n message: {\n ...(channel.message ?? {}),\n tags: {\n ...(channel.message?.tags ?? {}),\n ...(intrface.channels?.[channelName]?.message?.tags ?? {}),\n },\n },\n conversation: {\n ...(channel.conversation ?? {}),\n tags: {\n ...(channel.conversation?.tags ?? {}),\n ...(intrface.channels?.[channelName]?.conversation?.tags ?? {}),\n },\n },\n messages,\n }\n statement.channels[channelName] = { name: newChannelName }\n }\n\n return { resolved, statement }\n}\n", "{\n \"name\": \"@holocronlab/botruntime-sdk\",\n \"version\": \"6.13.3\",\n \"description\": \"SDK for building bots and integrations on botruntime\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"files\": [\n \"dist\",\n \"readme.md\",\n \"LICENSE\"\n ],\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/HolocronLab/botruntime-packages\",\n \"directory\": \"packages/botruntime-sdk\"\n },\n \"scripts\": {\n \"check:type\": \"tsc -p ./tsconfig.json --noEmit\",\n \"build:type\": \"tsc -p ./tsconfig.package.json --emitDeclarationOnly --declaration\",\n \"build:browser\": \"ts-node -T ./build.ts --browser\",\n \"build:node\": \"ts-node -T ./build.ts --node\",\n \"build\": \"npm run build:type && npm run build:node && npm run build:browser\",\n \"test\": \"vitest --run\"\n },\n \"keywords\": [],\n \"author\": \"HolocronLab\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@holocronlab/botruntime-client\": \"file:../botruntime-client\",\n \"@holocronlab/botruntime-zui\": \"file:../botruntime-zui\",\n \"browser-or-node\": \"^2.1.1\",\n \"semver\": \"^7.3.8\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^22.16.4\",\n \"@types/semver\": \"^7.3.11\",\n \"esbuild\": \"^0.25.10\",\n \"esbuild-plugin-polyfill-node\": \"^0.3.0\",\n \"ts-node\": \"^10.9.2\",\n \"typescript\": \"^6.0.3\",\n \"vitest\": \"^2.1.8\"\n },\n \"peerDependencies\": {\n \"esbuild\": \"^0.16.12\"\n },\n \"peerDependenciesMeta\": {\n \"esbuild\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}\n", "import { version } from '../package.json'\n\nexport const SDK_VERSION = version\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 type * as esbuild from 'esbuild'\nimport { SchemaTransformOptions } from '../../common/types'\nimport { DefinitionError } from '../../errors'\nimport { resolveInterface } from '../../interface/resolve'\nimport { InterfacePackage } from '../../package'\nimport * as utils from '../../utils'\nimport { SDK_VERSION } from '../../version'\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 MessageDefinition,\n InterfaceExtension,\n IntegrationNetworkDefinition,\n} from './types'\n\nexport * from './types'\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 attributes?: Record<string, string>\n\n network?: IntegrationNetworkDefinition\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 __advanced?: SchemaTransformOptions & {\n esbuild?: Partial<esbuild.BuildOptions>\n extraOperations?: Record<string, { enabled: boolean }>\n }\n}\n\ntype EntitiesOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['entities']]: NonNullable<TPackage['definition']['entities']>[K]['schema']\n}\n\ntype ActionsOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['actions']]: NonNullable<TPackage['definition']['actions']>[K]['input']['schema']\n}\n\ntype EventsOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['events']]: NonNullable<TPackage['definition']['events']>[K]['schema']\n}\n\ntype ChannelsOfPackage<TPackage extends InterfacePackage> = {\n [K in keyof TPackage['definition']['channels']]: {\n [M in keyof NonNullable<TPackage['definition']['channels']>[K]['messages']]: NonNullable<\n NonNullable<TPackage['definition']['channels']>[K]['messages']\n >[M]['schema']\n }\n}\n\nexport type ActionOverrideProps = utils.types.AtLeastOneProperty<\n Pick<Required<ActionDefinition>, 'title' | 'description' | 'billable' | 'cacheable' | 'attributes'> & {\n name: string\n }\n>\nexport type EventOverrideProps = utils.types.AtLeastOneProperty<\n Pick<Required<EventDefinition>, 'title' | 'description' | 'attributes'> & {\n name: string\n }\n>\nexport type ChannelOverrideProps = utils.types.AtLeastOneProperty<\n Pick<Required<ChannelDefinition>, 'title' | 'description'> & {\n name: string\n message: {\n tags: Required<Required<ChannelDefinition>['message']>['tags']\n }\n conversation: {\n tags: Required<Required<ChannelDefinition>['conversation']>['tags']\n }\n }\n>\n\ntype ActionOverrides<TInterfaceActionNames extends string = string> = utils.types.AtLeastOneProperty<\n Record<TInterfaceActionNames, ActionOverrideProps>\n>\ntype EventOverrides<TInterfaceEventNames extends string = string> = utils.types.AtLeastOneProperty<\n Record<TInterfaceEventNames, EventOverrideProps>\n>\ntype ChannelOverrides<TInterfaceChannelNames extends string = string> = utils.types.AtLeastOneProperty<\n Record<TInterfaceChannelNames, ChannelOverrideProps>\n>\n\ntype ExtensionBuilderInput<\n TIntegrationEntities extends BaseEntities,\n _TIntegrationActions extends BaseActions,\n _TIntegrationEvents extends BaseEvents,\n _TIntegrationChannels extends BaseChannels,\n> = {\n entities: SchemaStore<TIntegrationEntities>\n}\n\ntype ExtensionBuilderOutput<\n TInterfaceEntities extends BaseEntities,\n TInterfaceActions extends BaseActions,\n TInterfaceEvents extends BaseEvents,\n TInterfaceChannels extends BaseChannels,\n> = {\n entities: {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n }\n actions?: ActionOverrides<Extract<keyof TInterfaceActions, string>>\n events?: EventOverrides<Extract<keyof TInterfaceEvents, string>>\n channels?: ChannelOverrides<Extract<keyof TInterfaceChannels, string>>\n}\n\ntype ExtensionBuilder<\n TIntegrationEntities extends BaseEntities,\n TIntegrationActions extends BaseActions,\n TIntegrationEvents extends BaseEvents,\n TIntegrationChannels extends BaseChannels,\n TInterfaceEntities extends BaseEntities,\n TInterfaceActions extends BaseActions,\n TInterfaceEvents extends BaseEvents,\n TInterfaceChannels extends BaseChannels,\n> = (\n input: ExtensionBuilderInput<TIntegrationEntities, TIntegrationActions, TIntegrationEvents, TIntegrationChannels>\n) => ExtensionBuilderOutput<TInterfaceEntities, TInterfaceActions, TInterfaceEvents, TInterfaceChannels>\n\ntype TypeArgument = { name: string; schema: z.AnyZodObject }\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 readonly __advanced: this['props']['__advanced']\n public readonly attributes: this['props']['attributes']\n public readonly network: this['props']['network']\n\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 this.__advanced = props.__advanced\n this.attributes = props.attributes\n this.network = props.network\n }\n\n public get metadata() {\n return { sdkVersion: SDK_VERSION } as const\n }\n\n public readonly clone?: (overrides?: Partial<IntegrationDefinitionProps>) => IntegrationDefinition = (overrides?) => {\n // TODO: make non-optional on next major (CLI and SDK share the same major, so the CLI can always rely on clone being present)\n return new IntegrationDefinition({\n ...this.props,\n actions: this.actions,\n events: this.events,\n channels: this.channels,\n interfaces: this.interfaces,\n ...overrides,\n } as IntegrationDefinitionProps)\n }\n\n public extend<P extends InterfacePackage>(\n interfacePkg: P,\n builder: ExtensionBuilder<\n TEntities,\n TActions,\n TEvents,\n TChannels,\n EntitiesOfPackage<P>,\n ActionsOfPackage<P>,\n EventsOfPackage<P>,\n ChannelsOfPackage<P>\n >\n ): this {\n const { entities, actions, events, channels } = this._callBuilder(interfacePkg, builder)\n\n const self = this as utils.types.Writable<IntegrationDefinition>\n self.interfaces ??= {}\n\n const entityNames = Object.values(entities).map((e) => e.name)\n\n const key = entityNames.length === 0 ? interfacePkg.name : `${interfacePkg.name}<${entityNames.join(',')}>`\n\n const { resolved, statement } = resolveInterface({\n ...interfacePkg,\n entities,\n actions: utils.records.stripUndefinedProps(actions),\n events: utils.records.stripUndefinedProps(events),\n channels: utils.records.stripUndefinedProps(channels),\n })\n\n /**\n * If an action is defined both in the integration and the interface; we merge both.\n * This allows setting more specific properties in the integration, while staying compatible with the interface.\n * Same goes for channels and events.\n */\n self.actions = utils.records.mergeRecords(self.actions ?? {}, resolved.actions, this._mergeActions)\n self.channels = utils.records.mergeRecords(self.channels ?? {}, resolved.channels, this._mergeChannels)\n self.events = utils.records.mergeRecords(self.events ?? {}, resolved.events, this._mergeEvents)\n\n self.interfaces[key] = {\n id: interfacePkg.id,\n ...statement,\n }\n\n return this\n }\n\n private _callBuilder<P extends InterfacePackage>(\n interfacePkg: P,\n builder: ExtensionBuilder<\n TEntities,\n TActions,\n TEvents,\n TChannels,\n EntitiesOfPackage<P>,\n ActionsOfPackage<P>,\n EventsOfPackage<P>,\n ChannelsOfPackage<P>\n >\n ): {\n entities: Record<string, TypeArgument>\n actions: ActionOverrides\n events: EventOverrides\n channels: ChannelOverrides\n } {\n const entityStore = createStore(this.entities)\n const extensionBuilderInput: ExtensionBuilderInput<TEntities, TActions, TEvents, TChannels> = {\n entities: entityStore,\n }\n const extensionBuilderOutput = builder(extensionBuilderInput)\n const unbrandedEntity = utils.records.pairs(extensionBuilderOutput.entities).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 DefinitionError(\n `Cannot extend interface \"${interfacePkg.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n const entities = utils.records.mapValues(extensionBuilderOutput.entities, (e) => ({\n name: getName(e),\n schema: e.schema as z.AnyZodObject,\n }))\n return {\n entities,\n actions: extensionBuilderOutput.actions ?? {},\n events: extensionBuilderOutput.events ?? {},\n channels: extensionBuilderOutput.channels ?? {},\n }\n }\n\n private _mergeActions = (a: ActionDefinition, b: ActionDefinition): ActionDefinition => {\n return {\n ...a,\n ...b,\n input: {\n schema: this._mergeObjectSchemas(a.input.schema, b.input.schema),\n },\n output: {\n schema: this._mergeObjectSchemas(a.output.schema, b.output.schema),\n },\n }\n }\n\n private _mergeEvents = (a: EventDefinition, b: EventDefinition): EventDefinition => {\n return {\n ...a,\n ...b,\n schema: this._mergeObjectSchemas(a.schema, b.schema),\n }\n }\n\n private _mergeChannels = (a: ChannelDefinition, b: ChannelDefinition): ChannelDefinition => {\n const messages = utils.records.mergeRecords(a.messages, b.messages, this._mergeMessage)\n\n let conversation: ChannelDefinition['conversation'] = undefined\n if (a.conversation || b.conversation) {\n conversation = {\n tags: {\n ...a.conversation?.tags,\n ...b.conversation?.tags,\n },\n }\n }\n\n let message: ChannelDefinition['message'] = undefined\n if (a.message || b.message) {\n message = {\n tags: {\n ...a.message?.tags,\n ...b.message?.tags,\n },\n }\n }\n\n return {\n ...a,\n ...b,\n messages,\n conversation,\n message,\n }\n }\n\n private _mergeMessage = (a: MessageDefinition, b: MessageDefinition): MessageDefinition => {\n return {\n schema: this._mergeObjectSchemas(a.schema, b.schema),\n }\n }\n\n private _mergeObjectSchemas = (a: z.ZuiObjectSchema, b: z.ZuiObjectSchema): z.ZuiObjectSchema => {\n const aDef = a._def\n const bDef = b._def\n\n if (aDef.typeName === 'ZodObject' && bDef.typeName === 'ZodObject') {\n const aShape = aDef.shape()\n const bShape = bDef.shape()\n return z.object({ ...aShape, ...bShape })\n }\n if (aDef.typeName === 'ZodRecord' && bDef.typeName === 'ZodRecord') {\n return z.record(z.intersection(aDef.valueType, bDef.valueType))\n }\n // TODO: adress this case\n throw new Error('Cannot merge object schemas with record schemas')\n }\n}\n", "import { Client, InvalidPayloadError } from '@holocronlab/botruntime-client'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody, handlerErrorToHttpResponse } from '../../serve'\nimport { IntegrationSpecificClient } from '../client'\nimport { BaseIntegration } from '../common'\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 IntegrationContext,\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\nconst extractTracingHeaders = (headers: Record<string, string | undefined>) => {\n return ['traceparent', 'tracestate'].reduce<Record<string, string>>((acc, header) => {\n if (headers[header]) {\n acc[header] = headers[header]\n }\n return acc\n }, {})\n}\n\nconst getServerProps = (\n ctx: IntegrationContext,\n req: Request,\n instance: IntegrationHandlers<BaseIntegration>\n): ServerProps => {\n const [, traceId] = (req.headers['traceparent'] || '').split('-')\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n integrationAlias: ctx.integrationAlias,\n retry: retryConfig,\n headers: instance.managesOwnTracePropagation ? {} : extractTracingHeaders(req.headers),\n })\n const client = new IntegrationSpecificClient<BaseIntegration>(vanillaClient)\n const logger = new IntegrationLogger({\n traceId,\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n integrationAlias: ctx.integrationAlias,\n })\n\n return {\n ctx,\n req,\n client,\n logger,\n instance,\n }\n}\n\nconst handleOperation = async (props: ServerProps) => {\n const { ctx } = props\n switch (ctx.operation) {\n case 'webhook_received':\n return await onWebhook(props)\n case 'register':\n return await onRegister(props)\n case 'unregister':\n return await onUnregister(props)\n case 'message_created':\n return await onMessageCreated(props)\n case 'action_triggered':\n return await onActionTriggered(props)\n case 'ping':\n return await onPing(props)\n case 'create_user':\n return await onCreateUser(props)\n case 'create_conversation':\n return await onCreateConversation(props)\n default:\n throw new InvalidPayloadError(`Unknown operation ${ctx.operation}`)\n }\n}\n\nexport const integrationHandler =\n (instance: IntegrationHandlers<BaseIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n const props = getServerProps(ctx, req, instance)\n const { logger } = props\n\n try {\n let response: Response | void\n response = await onUnknownOperationHandler(props)\n if (response) {\n return { ...response, status: response.status ?? 200 }\n }\n\n response = await handleOperation(props)\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (thrown: unknown) {\n const { status, body, error } = handlerErrorToHttpResponse({\n thrown,\n unexpectedErrorMessage:\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\n if (status >= 500) {\n // prints the error in the integration logs\n console.error(thrown)\n }\n\n logger.forBot().error(error.message)\n return { status, body }\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 InvalidPayloadError(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new InvalidPayloadError(`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 InvalidPayloadError('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new InvalidPayloadError(`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\nconst onUnknownOperationHandler = async ({\n instance,\n client,\n ctx,\n logger,\n req,\n}: ServerProps): Promise<Response | void> => {\n const handler = instance.unknownOperationHandler\n if (!handler) {\n return\n }\n return await handler({\n client,\n ctx,\n logger,\n req,\n })\n}\n", "import * as client from '@holocronlab/botruntime-client'\n\nexport const retryConfig: client.RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n client.axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount, axiosError) => {\n const retryAfterSeconds = _getRetryAfterSeconds(axiosError.response?.headers ?? {})\n return (retryAfterSeconds ?? retryCount) * 1000\n },\n}\n\nconst _getRetryAfterSeconds = (headers: client.axios.RawAxiosResponseHeaders) => {\n const headerNames = [\n // Standard rate limiting headers:\n 'RateLimit-Reset',\n 'X-RateLimit-Reset',\n 'Retry-After',\n\n // Lowercase variants:\n 'ratelimit-reset',\n 'x-ratelimit-reset',\n 'retry-after',\n ] as const\n\n for (const headerName of headerNames) {\n const headerValue: unknown = headers[headerName]\n\n if (headerValue === undefined) {\n continue\n }\n\n return _parseHeaderToSeconds(String(headerValue))\n }\n\n return\n}\n\nconst _parseHeaderToSeconds = (headerValue: string): number | undefined => {\n // NOTE: retry-after can be either a number of seconds or a date string:\n const secondsDiff = _isDateString(headerValue)\n ? _parseDateToSeconds(headerValue)\n : headerValue.length > 0\n ? parseInt(headerValue, 10)\n : undefined\n\n return secondsDiff === undefined || isNaN(secondsDiff) ? undefined : secondsDiff\n}\n\nconst _isDateString = (headerValue: string): boolean => headerValue.includes(' ')\n\nconst _parseDateToSeconds = (headerValue: string): number | undefined => {\n const futureDate = _parseDateString(headerValue)\n if (!futureDate) {\n return\n }\n\n const currentDate = new Date()\n return Math.max(0, Math.floor((futureDate.getTime() - currentDate.getTime()) / 1000))\n}\n\nconst _parseDateString = (headerValue: string): Date | undefined => {\n const date = new Date(headerValue)\n return isNaN(date.getTime()) ? undefined : date\n}\n", "import * as client from '@holocronlab/botruntime-client'\nimport * as common from '../common'\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 /**\n * Access the underlying Botpress client.\n * This is useful for operations that are not available in the IntegrationSpecificClient.\n * You probably shouldn't use this directly if you don't know what you're doing.\n */\n public get _inner(): client.Client {\n return this._client\n }\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).then((r) => r)) as types.GetMessage<TIntegration>\n public updateMessage: types.UpdateMessage<TIntegration> = ((x) =>\n this._client.updateMessage(x).then((r) => r)) 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 public initializeIncomingMessage: types.InitializeIncomingMessage<TIntegration> = ((x) =>\n this._client.initializeIncomingMessage(x)) as types.InitializeIncomingMessage<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 public trackAnalytics: types.TrackAnalytics<TIntegration> = (x) => this._client.trackAnalytics(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 '@holocronlab/botruntime-zui'\nimport {\n BOT_ID_HEADER,\n BOT_USER_ID_HEADER,\n CONFIGURATION_PAYLOAD_HEADER,\n CONFIGURATION_TYPE_HEADER,\n INTEGRATION_ALIAS_HEADER,\n INTEGRATION_ID_HEADER,\n OPERATION_TYPE_HEADER,\n WEBHOOK_ID_HEADER,\n} from '../../consts'\nimport { throwError } from '../../utils/error-utils'\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 botId: headers[BOT_ID_HEADER] || throwError('Missing bot header'),\n botUserId: headers[BOT_USER_ID_HEADER] || throwError('Missing bot user header'),\n integrationId: headers[INTEGRATION_ID_HEADER] || throwError('Missing integration header'),\n integrationAlias: headers[INTEGRATION_ALIAS_HEADER] || throwError('Missing integration alias header'),\n webhookId: headers[WEBHOOK_ID_HEADER] || throwError('Missing webhook header'),\n operation: headers[OPERATION_TYPE_HEADER] || throwError('Missing operation header'),\n configurationType: headers[CONFIGURATION_TYPE_HEADER] ?? null,\n configuration: JSON.parse(\n Buffer.from(headers[CONFIGURATION_PAYLOAD_HEADER] || throwError('Missing configuration header'), 'base64').toString(\n 'utf-8'\n )\n ),\n})\n", "export * from './public-consts'\n\n// This file contains constants that are not exported for public use.\n// They are used internally in the SDK and should not be used outside of it.\n\n// To export a constant, add it to the public-consts.ts file instead.\n\nexport const PLUGIN_PREFIX_SEPARATOR = '#'\n\nexport const BOT_ID_HEADER = 'x-bot-id'\nexport const BOT_USER_ID_HEADER = 'x-bot-user-id'\nexport const INTEGRATION_ID_HEADER = 'x-integration-id'\nexport const INTEGRATION_ALIAS_HEADER = 'x-integration-alias'\nexport const WEBHOOK_ID_HEADER = 'x-webhook-id'\n\nexport const CONFIGURATION_TYPE_HEADER = 'x-bp-configuration-type'\nexport const CONFIGURATION_PAYLOAD_HEADER = 'x-bp-configuration'\nexport const OPERATION_TYPE_HEADER = 'x-bp-operation'\nexport const OPERATION_SUBTYPE_HEADER = 'x-bp-type'\n", "/**\n * Utility to throw an error in ternary or nullish coalescing expressions\n */\nexport const throwError = (thrown: string | Error): never => {\n const error = thrown instanceof Error ? thrown : new Error(thrown)\n throw error\n}\n", "import util from 'util'\n\nexport type LogLevel = 'info' | 'debug' | 'warn' | 'error'\n\nexport type IssueLogEvent = {\n type: 'issue'\n code: string\n category: 'user_code' | 'limits' | 'configuration' | 'other'\n title: string\n description: string\n data: Record<string, { raw: string; pretty?: string }>\n /** This groups by data fields */\n groupBy: string[]\n traceId?: string\n}\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 public issue(args: IssueLogEvent) {\n console.info(JSON.stringify({ ...args, ...this.getIssueContext() }))\n }\n\n /**\n * Identity fields merged into every issue line so downstream ingestion can\n * attribute and validate the issue without out-of-band context.\n */\n protected getIssueContext(): Record<string, string> {\n return {}\n }\n\n private _log(level: LogLevel, args: Parameters<typeof console.info>) {\n this._getConsoleMethod(level)(this._serializeMessage(level, args))\n }\n\n private _serializeMessage(level: LogLevel, args: Parameters<typeof console.info>) {\n const msg = util.format(...args)\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return this.getJsonMessage(level, msg)\n } else {\n return msg\n }\n }\n\n protected getJsonMessage(level: LogLevel, msg: string) {\n return JSON.stringify({ msg, level, options: this.defaultOptions })\n }\n\n private _getConsoleMethod(level: LogLevel): (...args: unknown[]) => 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, type LogLevel } from '../../base-logger'\n\ntype IntegrationLogOptions = {\n botId?: string\n integrationId?: string\n integrationAlias?: string\n userId?: string\n conversationId?: string\n traceId?: string\n visibleToBotOwners?: boolean\n hiddenToIntegrationOwners?: boolean\n}\n\nexport class IntegrationLogger extends BaseLogger<IntegrationLogOptions> {\n public constructor(options?: IntegrationLogOptions) {\n super({\n visibleToBotOwners: false,\n hiddenToIntegrationOwners: false,\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 /**\n * Used send the log to the bot owner\n */\n public withVisibleToBotOwners(visibleToBotOwners: boolean) {\n return this.with({\n visibleToBotOwners,\n })\n }\n\n /**\n * Used to *hide* the log from the integration owner\n */\n public withHiddenToIntegrationOwners(hiddenToIntegrationOwners: boolean) {\n return this.with({\n hiddenToIntegrationOwners,\n })\n }\n\n /**\n * Used to send the log to the bot owner _**and**_ the integration owner\n */\n public forBot() {\n return this.with({\n hiddenToIntegrationOwners: false,\n visibleToBotOwners: true,\n })\n }\n\n /**\n * Used to send the log _**only**_ to the bot owner and _**not**_ the integration owner\n */\n public forBotOnly() {\n return this.with({\n hiddenToIntegrationOwners: true,\n visibleToBotOwners: true,\n })\n }\n\n protected override getJsonMessage(level: LogLevel, msg: string) {\n return JSON.stringify({\n msg,\n level,\n botId: this.defaultOptions.botId,\n integrationId: this.defaultOptions.integrationId,\n integrationAlias: this.defaultOptions.integrationAlias,\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 hidden_to_integration_owner: this.defaultOptions.hiddenToIntegrationOwners,\n options: this.defaultOptions,\n })\n }\n\n protected override getIssueContext(): Record<string, string> {\n const { botId, integrationId, integrationAlias } = this.defaultOptions\n return {\n ...(botId && { botId }),\n ...(integrationId && { integrationId }),\n ...(integrationAlias && { integrationAlias }),\n }\n }\n}\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './common'\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 UnknownOperationHandler as UnknownOperationFunction,\n integrationHandler,\n} from './server'\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 __advanced?: {\n unknownOperationHandler?: UnknownOperationFunction<TIntegration>\n managesOwnTracePropagation?: boolean\n }\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 public readonly unknownOperationHandler: NonNullable<\n IntegrationImplementationProps<TIntegration>['__advanced']\n >['unknownOperationHandler']\n public readonly managesOwnTracePropagation: NonNullable<\n IntegrationImplementationProps<TIntegration>['__advanced']\n >['managesOwnTracePropagation']\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 this.unknownOperationHandler = props.__advanced?.unknownOperationHandler\n this.managesOwnTracePropagation = props.__advanced?.managesOwnTracePropagation\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 { BotDefinitionProps, EventDefinition, RecurringEventDefinition } from '../bot/definition'\nimport { SafeOmit } from '../utils/type-utils'\n\ntype StrippedEvents<TEvents extends Record<string, EventDefinition>> = {\n [K in keyof TEvents]: SafeOmit<TEvents[K], 'recurrence'>\n}\n\nexport function stripRecurringFromEvents<TEvents extends Record<string, EventDefinition>>(\n events: TEvents\n): StrippedEvents<TEvents>\nexport function stripRecurringFromEvents<TEvents extends Record<string, EventDefinition>>(\n events: TEvents | undefined\n): StrippedEvents<TEvents> | undefined\nexport function stripRecurringFromEvents<TEvents extends Record<string, EventDefinition>>(\n events: TEvents | undefined\n): StrippedEvents<TEvents> | undefined {\n if (!events) return undefined\n return Object.fromEntries(\n Object.entries(events).map(([key, { recurrence: _, ...rest }]) => [key, rest])\n ) as StrippedEvents<TEvents>\n}\n\nexport function resolveRecurringEvents(\n events: Record<string, EventDefinition> | undefined,\n explicitRecurringEvents: BotDefinitionProps['recurringEvents']\n): BotDefinitionProps['recurringEvents'] {\n const derived: NonNullable<BotDefinitionProps['recurringEvents']> = Object.fromEntries(\n Object.entries(events ?? {})\n .map(([eventName, event]): [string, RecurringEventDefinition] | null =>\n event.recurrence\n ? [\n eventName,\n { type: eventName, payload: event.recurrence.payload, schedule: { cron: event.recurrence.cron } },\n ]\n : null\n )\n .filter((x) => x !== null)\n )\n const merged = { ...derived, ...explicitRecurringEvents }\n return Object.keys(merged).length ? merged : undefined\n}\n", "import { Table } from '@holocronlab/botruntime-client'\nimport { stripRecurringFromEvents, resolveRecurringEvents } from '../common/recurring-events'\nimport { SchemaTransformOptions } from '../common/types'\nimport * as consts from '../consts'\nimport { DefinitionError } from '../errors'\nimport { IntegrationPackage, PluginPackage } from '../package'\nimport { PluginInterfaceExtension, PluginIntegrationExtension } from '../plugin'\nimport { SchemaDefinition } from '../schema'\nimport * as utils from '../utils'\nimport { ValueOf, Writable, Merge, StringKeys } from '../utils/type-utils'\nimport { SDK_VERSION } from '../version'\nimport { z } from '../zui'\n\ntype BaseConfig = z.ZuiObjectSchema\ntype BaseStates = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseEvents = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseActions = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseTables = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseWorkflows = Record<string, z.ZuiObjectSchema>\n\nexport type TagDefinition = {\n title?: string\n description?: string\n}\n\nexport type StateType = 'conversation' | 'user' | 'bot' | 'workflow'\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\n/*\n * @deprecate\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 recurrence?: {\n cron: string\n payload: z.input<TEvent>\n }\n attributes?: Record<string, string>\n}\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 SecretDefinition = {\n optional?: boolean\n description?: string\n}\n\nexport type ActionDefinition<TAction extends BaseActions[string] = BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<z.ZuiObjectOrRefSchema> // cannot infer both input and output types (typescript limitation)\n attributes?: Record<string, string>\n}\n\nexport type WorkflowDefinition<TWorkflow extends BaseWorkflows[string] = BaseWorkflows[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TWorkflow>\n output: SchemaDefinition<z.ZuiObjectSchema> // cannot infer both input and output types (typescript limitation)\n tags?: Record<string, TagDefinition>\n}\n\nexport type TableDefinition<TTable extends BaseTables[string] = BaseTables[string]> = Merge<\n Omit<Table, 'id' | 'createdAt' | 'updatedAt' | 'name'>,\n {\n schema: TTable\n }\n>\n\nexport type ResolvedIntegrationConfigInstance<I extends IntegrationPackage = IntegrationPackage> = {\n enabled?: boolean\n alias: string\n disabledChannels?: StringKeys<NonNullable<I['definition']['channels']>>[]\n} & (\n | {\n configurationType?: null\n configuration: z.input<NonNullable<I['definition']['configuration']>['schema']>\n }\n | ValueOf<{\n [K in StringKeys<NonNullable<I['definition']['configurations']>>]: {\n configurationType: K\n configuration: z.input<NonNullable<I['definition']['configurations']>[K]['schema']>\n }\n }>\n)\n\ntype IntegrationConfigInstance<I extends IntegrationPackage = IntegrationPackage> = Omit<\n ResolvedIntegrationConfigInstance<I>,\n 'alias'\n> & { alias?: string }\n\ntype _ResolvedPluginConfigInstance<P extends PluginPackage = PluginPackage> = {\n alias: string\n configuration: z.input<NonNullable<P['definition']['configuration']>['schema']>\n interfaces: {\n [I in keyof NonNullable<P['definition']['interfaces']>]: PluginInterfaceExtension\n }\n integrations: {\n [I in keyof NonNullable<P['definition']['integrations']>]: PluginIntegrationExtension\n }\n}\n\ntype PluginConfigInstance<P extends PluginPackage = PluginPackage> = Omit<\n _ResolvedPluginConfigInstance<P>,\n 'alias' | 'integrations' | 'interfaces'\n> & {\n alias?: string\n /** Backing integrations for the plugin's dependencies */\n dependencies: {\n [K in StringKeys<NonNullable<P['definition']['interfaces']>>]: {\n /**\n * Alias of the integration to use to fullfil this dependency.\n *\n * This is the alias given when adding the integration to the bot\n * via `addIntegration()`.\n */\n integrationAlias: string\n /**\n * Alias of the interface within the integration.\n *\n * This is the alias defined by the integration package for the\n * interface it implements.\n */\n integrationInterfaceAlias: string\n }\n } & {\n [K in StringKeys<NonNullable<P['definition']['integrations']>>]: {\n /**\n * Alias of the integration to use to fullfil this dependency.\n *\n * This is the alias given when adding the integration to the bot\n * via `addIntegration()`.\n */\n integrationAlias: string\n }\n }\n}\n\nexport type IntegrationInstance = IntegrationPackage & ResolvedIntegrationConfigInstance\nexport type PluginInstance = PluginPackage & _ResolvedPluginConfigInstance\n\nexport type BotDefinitionProps<\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TTables extends BaseTables = BaseTables,\n TWorkflows extends BaseWorkflows = BaseWorkflows,\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 /** @deprecated Use the `recurrence` field on each event in `events` instead. */\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n tables?: {\n [K in keyof TTables]: TableDefinition<TTables[K]>\n }\n\n secrets?: Record<string, SecretDefinition>\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflows?: {\n [K in keyof TWorkflows]: WorkflowDefinition<TWorkflows[K]>\n }\n\n attributes?: Record<string, string>\n\n __advanced?: SchemaTransformOptions\n}\n\nexport class BotDefinition<\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TTables extends BaseTables = BaseTables,\n TWorkflows extends BaseWorkflows = BaseWorkflows,\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 readonly tables: this['props']['tables']\n public readonly secrets: this['props']['secrets']\n public readonly workflows: this['props']['workflows']\n public readonly attributes: this['props']['attributes']\n public readonly __advanced: this['props']['__advanced']\n\n /** Bot definition with plugins merged into it */\n public readonly withPlugins: Pick<\n this['props'],\n 'user' | 'conversation' | 'message' | 'states' | 'events' | 'recurringEvents' | 'actions' | 'tables' | 'workflows'\n >\n\n public constructor(public readonly props: BotDefinitionProps<TStates, TEvents, TActions, TTables, TWorkflows>) {\n const events = stripRecurringFromEvents(\n props.events as Record<string, EventDefinition> | undefined\n ) as this['props']['events']\n const recurringEvents = resolveRecurringEvents(\n props.events as Record<string, EventDefinition>,\n props.recurringEvents as BotDefinitionProps['recurringEvents']\n )\n\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 = events\n this.recurringEvents = recurringEvents\n this.actions = props.actions\n this.tables = props.tables\n this.secrets = props.secrets\n this.workflows = props.workflows\n this.attributes = props.attributes\n this.__advanced = props.__advanced\n\n this.withPlugins = {\n user: props.user,\n conversation: props.conversation,\n message: props.message,\n states: props.states,\n events,\n recurringEvents,\n actions: props.actions,\n tables: props.tables,\n workflows: props.workflows,\n }\n }\n\n public get metadata() {\n return { sdkVersion: SDK_VERSION } as const\n }\n\n public readonly clone?: (overrides?: Partial<BotDefinitionProps>) => BotDefinition = (overrides?) => {\n // TODO: make non-optional on next major (CLI and SDK share the same major, so the CLI can always rely on clone being present)\n return new BotDefinition({\n ...this.props,\n integrations: this.integrations,\n plugins: this.plugins,\n ...overrides,\n } as BotDefinitionProps)\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 const integrationAlias = config?.alias ?? integrationPkg.name\n\n if (self.integrations[integrationAlias]) {\n throw new DefinitionError(`Another integration with alias \"${integrationAlias}\" is already installed in the bot`)\n }\n\n const configurationType = config && 'configurationType' in config ? config.configurationType : undefined\n const rawConfiguration = config && 'configuration' in config ? (config.configuration ?? {}) : {}\n\n const configSchema = configurationType\n ? integrationPkg.definition.configurations?.[configurationType]?.schema\n : integrationPkg.definition.configuration?.schema\n\n // Use safeParse to avoid throwing on validation errors at definition time (e.g. genenv placeholders\n // or extra keys in catchall(z.never()) schemas). Spread rawConfiguration first to preserve unknown\n // keys, then overlay the parsed result so that z.default() values are applied for omitted fields.\n const parseResult = configSchema ? configSchema.safeParse(rawConfiguration) : null\n const configuration = parseResult?.success ? { ...rawConfiguration, ...parseResult.data } : rawConfiguration\n\n self.integrations[integrationAlias] = {\n ...integrationPkg,\n alias: integrationAlias,\n enabled: config?.enabled,\n configurationType,\n configuration,\n disabledChannels: config?.disabledChannels,\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 const pluginAlias = config.alias ?? pluginPkg.name\n\n if (self.plugins[pluginAlias]) {\n throw new DefinitionError(`Another plugin with alias \"${pluginAlias}\" is already installed in the bot`)\n }\n // Resolve backing integrations for plugin interfaces:\n const interfaces: Record<string, PluginInterfaceExtension> = Object.fromEntries(\n Object.entries(config.dependencies ?? {})\n .filter(([_, dep]) => 'integrationInterfaceAlias' in dep)\n .map(([pluginIfaceAlias, pluginIfaceConfig]) => {\n const integrationInstance = this.integrations?.[pluginIfaceConfig.integrationAlias]\n\n if (!integrationInstance) {\n const availableIntegrations = Object.keys(this.integrations ?? {}).join(', ') || '(none)'\n\n throw new DefinitionError(\n `Interface with alias \"${pluginIfaceAlias}\" of plugin with alias \"${pluginAlias}\" ` +\n `references integration with alias \"${pluginIfaceConfig.integrationAlias}\" which is not installed. ` +\n 'Please make sure to add the integration via addIntegration() before calling addPlugin().\\n' +\n `Available integration aliases: ${availableIntegrations}`\n )\n }\n\n const integrationInterfaceExtension =\n integrationInstance.definition.interfaces?.[pluginIfaceConfig.integrationInterfaceAlias]\n\n if (!integrationInterfaceExtension) {\n const availableInterfaces =\n Object.keys(integrationInstance.definition.interfaces ?? {}).join(', ') || '(none)'\n\n throw new DefinitionError(\n `Interface with alias \"${pluginIfaceConfig.integrationInterfaceAlias}\" does not exist in integration ` +\n `\"${integrationInstance.name}\" referenced by interface with alias \"${pluginIfaceAlias}\" of plugin ` +\n `with alias \"${pluginAlias}\".\\nAvailable interface aliases: ${availableInterfaces}`\n )\n }\n\n return [\n pluginIfaceAlias,\n {\n ...integrationInterfaceExtension,\n id: integrationInstance.id,\n name: integrationInstance.name,\n version: integrationInstance.version,\n ...pluginIfaceConfig,\n } satisfies PluginInterfaceExtension,\n ]\n })\n )\n\n // Resolve backing integrations for plugin integrations:\n const integrations: Record<string, PluginIntegrationExtension> = Object.fromEntries(\n Object.entries(config.dependencies ?? {})\n .filter(([_, dep]) => !('integrationInterfaceAlias' in dep))\n .map(([pluginIntegAlias, pluginIntegConfig]) => {\n const integrationInstance = this.integrations?.[pluginIntegConfig.integrationAlias]\n\n if (!integrationInstance) {\n const availableIntegrations = Object.keys(this.integrations ?? {}).join(', ') || '(none)'\n\n throw new Error(\n `Integration with alias \"${pluginIntegAlias}\" of plugin with alias \"${pluginAlias}\" ` +\n `references integration with alias \"${pluginIntegConfig.integrationAlias}\" which is not installed. ` +\n 'Please make sure to add the integration via addIntegration() before calling addPlugin().\\n' +\n `Available integration aliases: ${availableIntegrations}`\n )\n }\n\n return [\n pluginIntegAlias,\n { ...integrationInstance, ...pluginIntegConfig } satisfies PluginIntegrationExtension,\n ]\n })\n )\n\n const rawPluginConfiguration = config.configuration ?? {}\n const pluginConfigSchema = pluginPkg.definition.configuration?.schema\n // Use safeParse to avoid throwing on validation errors at definition time (e.g. genenv placeholders\n // or extra keys in catchall(z.never()) schemas). Spread rawPluginConfiguration first to preserve\n // unknown keys, then overlay the parsed result so that z.default() values are applied for omitted fields.\n const pluginParseResult = pluginConfigSchema ? pluginConfigSchema.safeParse(rawPluginConfiguration) : null\n const pluginConfiguration = pluginParseResult?.success\n ? { ...rawPluginConfiguration, ...pluginParseResult.data }\n : rawPluginConfiguration\n\n self.plugins[pluginAlias] = {\n ...pluginPkg,\n alias: pluginAlias,\n configuration: pluginConfiguration,\n interfaces,\n integrations,\n }\n\n self.withPlugins.user = this._mergeUser(self.withPlugins.user, pluginPkg.definition.user)\n self.withPlugins.conversation = this._mergeConversation(\n self.withPlugins.conversation,\n pluginPkg.definition.conversation\n )\n self.withPlugins.message = this._mergeMessage(self.withPlugins.message, pluginPkg.definition.message)\n self.withPlugins.recurringEvents = this._mergeRecurringEvents(\n self.withPlugins.recurringEvents,\n pluginPkg.definition.recurringEvents\n )\n self.withPlugins.tables = this._mergeTables(self.withPlugins.tables, pluginPkg.definition.tables)\n self.withPlugins.workflows = this._mergeWorkflows(self.withPlugins.workflows, pluginPkg.definition.workflows)\n\n self.withPlugins.states = this._mergeStates(\n self.withPlugins.states,\n this._prefixKeysWithPluginAlias(pluginPkg.definition.states, pluginAlias)\n )\n self.withPlugins.events = this._mergeEvents(\n self.withPlugins.events,\n this._prefixKeysWithPluginAlias(pluginPkg.definition.events, pluginAlias)\n )\n self.withPlugins.actions = this._mergeActions(\n self.withPlugins.actions,\n this._prefixKeysWithPluginAlias(pluginPkg.definition.actions, pluginAlias)\n )\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 private _mergeTables = (\n tables1: BotDefinitionProps['tables'],\n tables2: BotDefinitionProps['tables']\n ): BotDefinitionProps['tables'] => {\n return {\n ...tables1,\n ...tables2,\n }\n }\n\n private _mergeWorkflows = (\n workflows1: BotDefinitionProps['workflows'],\n workflows2: BotDefinitionProps['workflows']\n ): BotDefinitionProps['workflows'] => {\n return {\n ...workflows1,\n ...workflows2,\n }\n }\n\n private _prefixKeysWithPluginAlias = <TRecord extends Record<string, unknown>>(\n obj: TRecord | undefined,\n pluginAlias: string\n ): TRecord =>\n utils.records.mapKeys(obj ?? {}, (key) => `${pluginAlias}${consts.PLUGIN_PREFIX_SEPARATOR}${key}`) as TRecord\n\n /**\n * Returns a copy of the bot definition where all interface entity references\n * are resolved to the base entity schema as extended by the backing\n * integration.\n */\n public dereferencePluginEntities(): this {\n const zuiReferenceMap = this._buildZuiReferenceMap()\n\n return {\n ...this,\n withPlugins: {\n ...this.withPlugins,\n events: this._dereferenceDefinitionSchemas(this.withPlugins.events, zuiReferenceMap),\n states: this._dereferenceDefinitionSchemas(this.withPlugins.states, zuiReferenceMap),\n tables: this._dereferenceDefinitionSchemas(this.withPlugins.tables, zuiReferenceMap),\n actions: this._dereferenceActionDefinitionSchemas(this.withPlugins.actions, zuiReferenceMap),\n },\n plugins: Object.fromEntries(\n (Object.entries(this.plugins ?? {}) as [pluginAlias: string, PluginInstance][]).map(\n ([pluginAlias, pluginInstance]) => [\n pluginAlias,\n {\n ...pluginInstance,\n definition: {\n ...pluginInstance.definition,\n configuration: this._dereferenceDefinitionSchema(\n pluginInstance.definition.configuration,\n zuiReferenceMap\n ),\n events: this._dereferenceDefinitionSchemas(pluginInstance.definition.events, zuiReferenceMap),\n states: this._dereferenceDefinitionSchemas(pluginInstance.definition.states, zuiReferenceMap),\n tables: this._dereferenceDefinitionSchemas(pluginInstance.definition.tables, zuiReferenceMap),\n actions: this._dereferenceActionDefinitionSchemas(pluginInstance.definition.actions, zuiReferenceMap),\n },\n },\n ]\n )\n ),\n } as typeof this\n }\n\n private _buildZuiReferenceMap(): Record<string, z.ZodTypeAny> {\n const zuiReferenceMap: Record<string, z.ZodTypeAny> = {}\n\n const installedPlugins = Object.entries(this.plugins ?? {}) as [pluginAlias: string, PluginInstance][]\n\n for (const [pluginAlias, pluginInstance] of installedPlugins) {\n const pluginInterfaceExtensions = Object.entries(pluginInstance.interfaces ?? {}) as [\n interfaceAlias: string,\n PluginInterfaceExtension,\n ][]\n\n for (const [interfaceAlias, pluginInterfaceExtension] of pluginInterfaceExtensions) {\n const backingIntegration = this.integrations?.[pluginInterfaceExtension.integrationAlias]\n\n if (!backingIntegration) {\n throw new DefinitionError(\n `Interface with alias \"${interfaceAlias}\" of plugin with alias \"${pluginAlias}\" references integration \"${pluginInterfaceExtension.name}\" which is not installed`\n )\n }\n\n const entityExtensions = Object.entries(pluginInterfaceExtension.entities ?? {}) as [\n entityAlias: string,\n {\n name: string\n },\n ][]\n\n for (const [entityAlias, { name: interfaceEntityName }] of entityExtensions) {\n const entitySchema = backingIntegration.definition.entities?.[interfaceEntityName]?.schema\n\n if (!entitySchema) {\n // This should never happen\n throw new Error(\n `Interface entity \"${interfaceEntityName}\" does not exist in integration \"${backingIntegration.name}\"`\n )\n }\n\n zuiReferenceMap[`interface:${interfaceAlias}/entities/${entityAlias}`] = entitySchema\n }\n }\n }\n\n return zuiReferenceMap\n }\n\n private _dereferenceZuiSchema(\n schema: z.ZuiObjectOrRefSchema,\n zuiReferenceMap: Record<string, z.ZodTypeAny>\n ): z.ZuiObjectSchema {\n return schema.dereference(zuiReferenceMap) as z.ZuiObjectSchema\n }\n\n private _dereferenceDefinitionSchemas<TDefinitionRecord extends Record<string, { schema: z.ZuiObjectOrRefSchema }>>(\n definitions: TDefinitionRecord | undefined,\n zuiReferenceMap: Record<string, z.ZodTypeAny>\n ): TDefinitionRecord {\n return Object.fromEntries(\n Object.entries(definitions ?? {}).map(([key, definition]) => [\n key,\n this._dereferenceDefinitionSchema(definition, zuiReferenceMap),\n ])\n ) as TDefinitionRecord\n }\n\n private _dereferenceDefinitionSchema<TDefinition extends { schema: z.ZuiObjectOrRefSchema } | undefined>(\n definition: TDefinition,\n zuiReferenceMap: Record<string, z.ZodTypeAny>\n ): TDefinition {\n return definition\n ? { ...definition, schema: this._dereferenceZuiSchema(definition.schema, zuiReferenceMap) }\n : definition\n }\n\n private _dereferenceActionDefinitionSchemas<\n TDefinitionRecord extends Record<\n string,\n { input: { schema: z.ZuiObjectOrRefSchema }; output: { schema: z.ZuiObjectOrRefSchema } }\n >,\n >(definitions: TDefinitionRecord | undefined, zuiReferenceMap: Record<string, z.ZodTypeAny>): TDefinitionRecord {\n return Object.fromEntries(\n Object.entries(definitions ?? {}).map(([key, definition]) => [\n key,\n {\n ...definition,\n input: { schema: this._dereferenceZuiSchema(definition.input.schema, zuiReferenceMap) },\n output: { schema: this._dereferenceZuiSchema(definition.output.schema, zuiReferenceMap) },\n },\n ])\n ) as TDefinitionRecord\n }\n}\n", "import { Client, InvalidPayloadError, Message, State, User, Conversation } from '@holocronlab/botruntime-client'\nimport { retryConfig } from '../../retry'\nimport { Request, Response, parseBody, handlerErrorToHttpResponse } from '../../serve'\nimport * as utils from '../../utils/type-utils'\nimport { BotLogger } from '../bot-logger'\nimport { BotSpecificClient } from '../client'\nimport * as common from '../common'\nimport { extractContext } from './context'\nimport { SUCCESS_RESPONSE } from './responses'\nimport * as types from './types'\nimport { handleWorkflowUpdateEvent } from './workflows/update-handler'\n\nexport * from './types'\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({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<common.BaseBot>(vanillaClient, {\n before: {\n createMessage: async (req) => {\n const beforeOutgoingMessageHooks = bot.hookHandlers.before_outgoing_message[req.type] ?? []\n for (const handler of beforeOutgoingMessageHooks) {\n const client = new BotSpecificClient(vanillaClient)\n const hookOutput = await handler({\n client,\n ctx,\n logger: logger.with({ conversationId: req.conversationId, userId: req.userId }),\n data: req,\n })\n req = hookOutput?.data ?? req\n }\n return req\n },\n callAction: async (req) => {\n const beforeOutgoingCallActionHooks = bot.hookHandlers.before_outgoing_call_action[req.type] ?? []\n for (const handler of beforeOutgoingCallActionHooks) {\n const client = new BotSpecificClient(vanillaClient)\n const hookOutput = await handler({\n client,\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 afterOutgoingMessageHooks = bot.hookHandlers.after_outgoing_message[res.message.type] ?? []\n for (const handler of afterOutgoingMessageHooks) {\n const client = new BotSpecificClient(vanillaClient)\n const hookOutput = await handler({\n client,\n ctx,\n logger: logger.with({\n messageId: res.message.id,\n conversationId: res.message.conversationId,\n userId: res.message.userId,\n }),\n data: res,\n })\n res = hookOutput?.data ?? res\n }\n return res\n },\n callAction: async (res, req) => {\n const { type } = req\n const afterOutgoingCallActionHooks = bot.hookHandlers.after_outgoing_call_action[type] ?? []\n for (const handler of afterOutgoingCallActionHooks) {\n const client = new BotSpecificClient(vanillaClient)\n const hookOutput = await handler({\n client,\n ctx,\n logger,\n data: {\n type,\n ...res,\n },\n })\n res = hookOutput?.data ?? res\n }\n return res\n },\n },\n })\n\n const props: types.ServerProps = {\n req,\n ctx,\n logger,\n client: botClient,\n self: bot,\n }\n\n try {\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 InvalidPayloadError(`Unknown operation ${ctx.operation}`)\n }\n } catch (thrown: unknown) {\n const { status, body, error } = handlerErrorToHttpResponse({\n thrown,\n unexpectedErrorMessage: 'An unexpected error occurred in the bot.',\n })\n\n status >= 500 ? logger.error(error.message, thrown) : logger.error(error.message)\n return { status, body }\n }\n }\n\nconst onPing = async (_: types.ServerProps): Promise<Response> => {\n return SUCCESS_RESPONSE\n}\n\nconst onRegister = async (serverProps: types.ServerProps): Promise<Response> => {\n await serverProps.self.registerHandler?.({\n client: serverProps.client,\n ctx: serverProps.ctx,\n logger: serverProps.logger,\n })\n return SUCCESS_RESPONSE\n}\n\nconst onUnregister = async (_: types.ServerProps): Promise<Response> => {\n // this is currently never called\n return SUCCESS_RESPONSE\n}\n\nconst onEventReceived = async (serverProps: types.ServerProps): Promise<Response> => {\n const { ctx, logger, req, client, self } = serverProps\n const common: types.CommonHandlerProps<common.BaseBot> = { client, ctx, logger }\n\n type AnyEventPayload = utils.ValueOf<types.EventPayloads<common.BaseBot>>\n const body = parseBody<AnyEventPayload>(req)\n\n common.logger = common.logger.with({\n eventId: body.event.id,\n messageId: body.event.messageId,\n conversationId: body.event.conversationId,\n userId: body.event.userId,\n })\n\n if (ctx.type === 'workflow_update') {\n return await handleWorkflowUpdateEvent(serverProps, body.event as types.WorkflowUpdateEvent)\n }\n\n if (ctx.type === 'message_created') {\n const event = body.event\n let message: Message = event.payload.message\n const user: User = event.payload.user\n const conversation: Conversation = event.payload.conversation\n\n common.logger = common.logger.with({\n messageId: message.id,\n conversationId: message.conversationId,\n userId: message.userId,\n })\n\n const beforeIncomingMessageHooks = self.hookHandlers.before_incoming_message[message.type] ?? []\n for (const handler of beforeIncomingMessageHooks) {\n const hookOutput = await handler({\n ...common,\n user,\n conversation,\n data: message,\n })\n message = hookOutput?.data ?? message\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n const messagePayload: Parameters<(typeof messageHandlers)[number]>[0] = {\n ...common,\n user,\n conversation,\n message,\n event,\n }\n const messageHandlers = self.messageHandlers[message.type] ?? []\n for (const handler of messageHandlers) {\n await handler(messagePayload)\n }\n\n const afterIncomingMessageHooks = self.hookHandlers.after_incoming_message[message.type] ?? []\n for (const handler of afterIncomingMessageHooks) {\n const hookOutput = await handler({\n ...common,\n user,\n conversation,\n data: message,\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: State = event.payload.state\n const statePayload: Parameters<(typeof stateHandlers)[number]>[0] = {\n ...common,\n state: state as types.IncomingStates<common.BaseBot>[string],\n }\n\n const stateHandlers = self.stateExpiredHandlers[state.name] ?? []\n for (const handler of stateHandlers) {\n await handler(statePayload)\n }\n\n return SUCCESS_RESPONSE\n }\n\n let event = body.event\n const beforeIncomingEventHooks = self.hookHandlers.before_incoming_event[event.type] ?? []\n for (const handler of beforeIncomingEventHooks) {\n const hookOutput = await handler({\n ...common,\n data: event,\n })\n event = hookOutput?.data ?? event\n if (hookOutput?.stop) {\n return SUCCESS_RESPONSE\n }\n }\n\n const eventPayload: Parameters<(typeof eventHandlers)[number]>[0] = { ...common, event }\n const eventHandlers = self.eventHandlers[event.type] ?? []\n for (const handler of eventHandlers) {\n await handler(eventPayload)\n }\n\n const afterIncomingEventHooks = self.hookHandlers.after_incoming_event[event.type] ?? []\n for (const handler of afterIncomingEventHooks) {\n const hookOutput = await handler({\n ...common,\n data: event,\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 }: types.ServerProps): Promise<Response> => {\n type AnyActionPayload = utils.ValueOf<types.ActionHandlerPayloads<common.BaseBot>>\n let { input, type } = parseBody<AnyActionPayload>(req)\n\n if (!type) {\n throw new InvalidPayloadError('Missing action type')\n }\n\n // TODO: this should probably run even if the action is called in memory\n const beforeIncomingCallActionHooks = self.hookHandlers.before_incoming_call_action[type] ?? []\n for (const handler of beforeIncomingCallActionHooks) {\n const hookOutput = await handler({\n ctx,\n logger,\n client,\n data: {\n type,\n input,\n },\n })\n input = hookOutput?.data?.input ?? input\n type = hookOutput?.data?.type ?? type\n }\n\n const action = self.actionHandlers[type]\n if (!action) {\n throw new InvalidPayloadError(`Action ${type} not found`)\n }\n\n let output = await action({ ctx, logger, input, client, type })\n\n const afterIncomingCallActionHooks = self.hookHandlers.after_incoming_call_action[type] ?? []\n for (const handler of afterIncomingCallActionHooks) {\n const hookOutput = await handler({\n ctx,\n logger,\n client,\n data: {\n type,\n output,\n },\n })\n type = hookOutput?.data?.type ?? type\n output = hookOutput?.data?.output ?? output\n }\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 eventId?: string\n messageId?: 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 public withEventId(eventId: string) {\n return this.with({\n eventId,\n })\n }\n\n public withMessageId(messageId: string) {\n return this.with({\n messageId,\n })\n }\n}\n", "import * as client from '@holocronlab/botruntime-client'\nimport * as common from '../common'\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 /**\n * Access the underlying Botpress client.\n * This is useful for operations that are not available in the BotSpecificClient.\n * You probably shouldn't use this directly if you don't know what you're doing.\n */\n public get _inner(): client.Client {\n return this._client\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 createEvent: types.CreateEvent<TBot> = ((x) => this._run('createEvent', x)) as types.CreateEvent<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 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 public getTableRow: types.GetTableRow<TBot> = ((x) => this._run('getTableRow', x)) as types.GetTableRow<TBot>\n public createTableRows: types.CreateTableRows<TBot> = ((x) =>\n this._run('createTableRows', x)) as types.CreateTableRows<TBot>\n public findTableRows: types.FindTableRows<TBot> = ((x) => this._run('findTableRows', x)) as types.FindTableRows<TBot>\n public deleteTableRows: types.DeleteTableRows<TBot> = ((x) =>\n this._run('deleteTableRows', x)) as types.DeleteTableRows<TBot>\n public updateTableRows: types.UpdateTableRows<TBot> = ((x) =>\n this._run('updateTableRows', x)) as types.UpdateTableRows<TBot>\n public upsertTableRows: types.UpsertTableRows<TBot> = ((x) =>\n this._run('upsertTableRows', x)) as types.UpsertTableRows<TBot>\n public createWorkflow: types.CreateWorkflow<TBot> = ((x) =>\n this._run('createWorkflow', x)) as types.CreateWorkflow<TBot>\n public getOrCreateWorkflow: types.GetOrCreateWorkflow<TBot> = ((x) =>\n this._run('getOrCreateWorkflow', x)) as types.GetOrCreateWorkflow<TBot>\n public getWorkflow: types.GetWorkflow<TBot> = ((x) => this._run('getWorkflow', x)) as types.GetWorkflow<TBot>\n public updateWorkflow: types.UpdateWorkflow<TBot> = ((x) =>\n this._run('updateWorkflow', x)) as types.UpdateWorkflow<TBot>\n public deleteWorkflow: types.DeleteWorkflow<TBot> = ((x) =>\n this._run('deleteWorkflow', x)) as types.DeleteWorkflow<TBot>\n public listWorkflows: types.ListWorkflows<TBot> = ((x) => this._run('listWorkflows', x)) as types.ListWorkflows<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, req)\n }\n\n return res\n }\n}\n", "import { z } from '@holocronlab/botruntime-zui'\nimport {\n BOT_ID_HEADER,\n CONFIGURATION_PAYLOAD_HEADER,\n OPERATION_TYPE_HEADER,\n OPERATION_SUBTYPE_HEADER,\n} from '../../consts'\nimport { throwError } from '../../utils/error-utils'\nimport { BotContext } from './types'\n\nconst botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => ({\n botId: headers[BOT_ID_HEADER] || throwError('Missing bot id header'),\n operation: botOperationSchema.parse(headers[OPERATION_TYPE_HEADER]),\n type: headers[OPERATION_SUBTYPE_HEADER] || throwError('Missing type header'),\n configuration: JSON.parse(\n Buffer.from(headers[CONFIGURATION_PAYLOAD_HEADER] || throwError('Missing configuration header'), 'base64').toString(\n 'utf-8'\n )\n ),\n})\n", "export const SUCCESS_RESPONSE = { status: 200 } as const\n", "import * as types from '../types'\n\nexport const bridgeUpdateTypeToSnakeCase = (updateType: types.BridgeWorkflowUpdateType): types.WorkflowUpdateType => {\n switch (updateType) {\n case 'workflow_continued':\n return 'continued'\n case 'workflow_started':\n return 'started'\n case 'workflow_timedout':\n return 'timed_out'\n default:\n throw new Error(`Unsupported workflow update type: ${updateType}`)\n }\n}\n", "import { Response } from '../../../serve'\nimport { SUCCESS_RESPONSE } from '../responses'\nimport * as types from '../types'\nimport { bridgeUpdateTypeToSnakeCase } from './update-type-conv'\n\nconst WORKFLOW_UPDATE_TYPES = [\n 'child_workflow_deleted',\n 'child_workflow_finished',\n 'workflow_timedout',\n 'workflow_started',\n 'workflow_continued',\n] as const\n\nexport const handleWorkflowUpdateEvent = async (\n rawProps: types.ServerProps,\n event: types.WorkflowUpdateEvent\n): Promise<Response> => {\n if (rawProps.ctx.type !== 'workflow_update' || !WORKFLOW_UPDATE_TYPES.includes(event.payload.type)) {\n throw new Error('Unexpected event type')\n }\n\n const props = { ...rawProps, logger: _attachWorkflowContextToLogger(rawProps, event) }\n\n if (!event.payload.workflow.name) {\n props.logger.warn(\n 'Received workflow update event without a workflow name. Assuming this workflow was not defined by the bot.',\n event.payload.workflow\n )\n return SUCCESS_RESPONSE\n }\n\n switch (event.payload.type) {\n case 'child_workflow_deleted':\n case 'child_workflow_finished':\n props.logger.info(\n `Received child workflow event \"${event.payload.type}\", but child workflows are not yet supported`\n )\n break\n case 'workflow_timedout':\n case 'workflow_started':\n case 'workflow_continued':\n return await _handleWorkflowUpdate(props, event)\n default:\n event.payload.type satisfies never\n }\n\n return SUCCESS_RESPONSE\n}\n\nconst _attachWorkflowContextToLogger = (\n props: types.ServerProps,\n event: types.WorkflowUpdateEvent\n): types.ServerProps['logger'] =>\n props.logger.with({\n eventId: event.id,\n workflowId: event.payload.workflow.id,\n conversationId: event.payload.conversation?.id,\n userId: event.payload.user?.id,\n })\n\nconst _handleWorkflowUpdate = async (props: types.ServerProps, event: types.WorkflowUpdateEvent): Promise<Response> => {\n const updateType = bridgeUpdateTypeToSnakeCase(event.payload.type)\n const handlers = props.self.workflowHandlers[updateType]?.[event.payload.workflow.name]\n\n if (!handlers || handlers.length === 0) {\n props.logger.warn(`No ${updateType} handler found for workflow \"${event.payload.workflow.name}\"`)\n return SUCCESS_RESPONSE\n }\n\n const { updatedWorkflow } = await _dispatchToHandlers(props, event)\n\n if (updatedWorkflow.status === 'pending') {\n props.logger.warn(\n `Workflow \"${event.payload.workflow.name}\" is still in pending status after processing \"${updateType}\" event. ` +\n 'This may indicate that the workflow was not properly acknowledged or terminated by the handler. '\n )\n }\n\n return SUCCESS_RESPONSE\n}\n\ntype WorkflowState = types.WorkflowUpdateEventPayload['workflow']\n\nconst _dispatchToHandlers = async (\n props: types.ServerProps,\n event: types.WorkflowUpdateEvent\n): Promise<{ updatedWorkflow: WorkflowState }> => {\n const updateType = bridgeUpdateTypeToSnakeCase(event.payload.type)\n const handlers = props.self.workflowHandlers[updateType]?.[event.payload.workflow.name]\n\n let currentWorkflowState: WorkflowState = structuredClone(event.payload.workflow)\n\n for (const handler of handlers ?? []) {\n currentWorkflowState = await handler({\n ...props,\n event,\n conversation: event.payload.conversation,\n user: event.payload.user,\n workflow: currentWorkflowState,\n })\n }\n\n return { updatedWorkflow: currentWorkflowState }\n}\n", "import { PLUGIN_PREFIX_SEPARATOR } from '../consts'\n\nexport const unprefixTagsOwnedByPlugin = <T extends {} | { tags?: Record<string, string> }>(\n obj: T,\n { alias }: { alias?: string }\n): T => {\n if (!('tags' in obj) || !alias) {\n return obj\n }\n\n const prefix = `${alias}${PLUGIN_PREFIX_SEPARATOR}` as const\n\n const unprefixedTags = Object.fromEntries(\n Object.entries(obj.tags ?? {}).flatMap(([key, value]) =>\n key.startsWith(prefix) ? [[key.slice(prefix.length), value]] : []\n )\n )\n\n return {\n ...obj,\n tags: unprefixedTags,\n }\n}\n\nexport const prefixTagsIfNeeded = <T extends {} | { tags?: Record<string, string> }>(\n obj: T,\n { alias }: { alias?: string }\n): T => {\n if (!('tags' in obj) || !alias) {\n return obj\n }\n\n const prefix = `${alias}${PLUGIN_PREFIX_SEPARATOR}` as const\n\n const prefixedTags = Object.fromEntries(\n Object.entries(obj.tags ?? {}).map(([key, value]) => [key.startsWith(prefix) ? key : `${prefix}${key}`, value])\n )\n\n return {\n ...obj,\n tags: prefixedTags,\n }\n}\n", "type _PageLister<R> = (t: { nextToken?: string }) => Promise<{ items: R[]; meta: { nextToken?: string } }>\n\nclass AsyncCollection<T> implements AsyncIterableIterator<T> {\n private _nextToken?: string\n private _elementsBuffer: T[] = []\n private _isExhausted = false\n\n public constructor(private _list: _PageLister<T>) {}\n\n // Allows iterating with for-await-of loops:\n public [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n return this\n }\n\n /**\n * Get the next element from the collection and advance the iterator.\n */\n public async next(): Promise<IteratorResult<T, undefined>> {\n if (this._bufferIsEmpty && !this._isExhausted) {\n await this._fetchNextPageIntoBuffer()\n }\n\n if (this._bufferIsEmpty) {\n return { done: true, value: undefined }\n }\n\n return { done: false, value: this._elementsBuffer.shift()! }\n }\n\n /**\n * Take the next n elements from the collection, advancing the iterator, and\n * return them as an array.\n */\n public async take(amount: number): Promise<T[]> {\n const arr: T[] = []\n for (let i = 0; i < amount; ++i) {\n const result = await this.next()\n if (result.done) {\n break\n }\n arr.push(result.value)\n }\n return arr\n }\n\n /**\n * Take the next n pages of elements from the collection, advancing the\n * iterator, and return the elements as an array.\n */\n public async takePage(amount: number): Promise<T[]> {\n for (let i = 0; i < amount; ++i) {\n if (!this._isExhausted) {\n await this._fetchNextPageIntoBuffer()\n }\n }\n\n const elements = [...this._elementsBuffer]\n this._elementsBuffer.length = 0\n\n return elements\n }\n\n /**\n * Take all remaining elements from in collection, moving the iterator to the\n * end, and return them as an array.\n */\n public async takeAll(): Promise<T[]> {\n return this.take(Number.POSITIVE_INFINITY)\n }\n\n /**\n * Returns true if there are no more elements to fetch in the collection.\n */\n public get isExhausted() {\n return this._isExhausted\n }\n\n private async _fetchNextPageIntoBuffer(): Promise<void> {\n const { items, meta } = await this._list({ nextToken: this._nextToken })\n\n this._elementsBuffer.push(...items)\n this._nextToken = meta.nextToken\n\n if (!meta.nextToken) {\n this._isExhausted = true\n }\n }\n\n private get _bufferIsEmpty(): boolean {\n return this._elementsBuffer.length === 0\n }\n}\n\nexport type { AsyncCollection }\nexport const createAsyncCollection = <T>(listFn: _PageLister<T>) => new AsyncCollection<T>(listFn)\n", "import type * as client from '@holocronlab/botruntime-client'\nimport type { BotSpecificClient } from '../../bot'\nimport { prefixTagsIfNeeded, unprefixTagsOwnedByPlugin } from '../../plugin/tag-prefixer'\nimport { createAsyncCollection } from '../../utils/api-paging-utils'\nimport type * as typeUtils from '../../utils/type-utils'\nimport type { BaseBot } from '../common'\nimport * as botServerTypes from '../server/types'\nimport type { WorkflowProxy, ActionableWorkflow } from './types'\n\n// FIXME: Plugin (and bot) workflow definitions are currently being created on\n// the fly at run time. However, they should be part of the bot/plugin\n// definition. The SDK currently gives the illusion that they are defined\n// at deploy time, but in reality they are not. Nothing about the\n// workflows is sent to the backend at deploy time.\n//\n// This is being tracked as https://linear.app/botpress/issue/KKN-292\n//\n// Since currently each workflow definition is unique to a workflow run,\n// the tags are not prefixed by the plugin instance's alias. This is\n// because the backend's input validation prevents us from having a `#`\n// character in the workflow definition's tag definition. The plugin\n// prefix separator should only be present when we merge a plugin's\n// definitions into a bot (ie when installing a plugin in a bot). It\n// should not be allowed when calling the createWorkflow endpoint\n// directly, which is what the CLI currently does.\n//\n// Once we have proper deploy-time workflow definitions, we should\n// prefix/unprefix the tags like we do in the other plugin proxies.\n//\n// This means removing `undefined /* props.pluginAlias */` and replacing\n// it with `props.pluginAlias` in the calls to `prefixTagsIfNeeded()` and\n// `unprefixTagsOwnedByPlugin()`.\n\nexport const proxyWorkflows = <TBot extends BaseBot>(props: {\n client: BotSpecificClient<TBot> | client.Client\n pluginAlias?: string\n}): WorkflowProxy<TBot> =>\n new Proxy({} as WorkflowProxy<TBot>, {\n get: <TWorkflowName extends typeUtils.StringKeys<TBot['workflows']>>(_: unknown, workflowName: TWorkflowName) =>\n ({\n listInstances: (input) =>\n createAsyncCollection(({ nextToken }) =>\n props.client\n .listWorkflows({\n ...input,\n name: workflowName as typeUtils.Cast<TWorkflowName, string>,\n nextToken,\n })\n .then(({ meta, workflows }) => ({\n meta,\n items: workflows.map((workflow) => wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow })),\n }))\n ),\n startNewInstance: async (input) => {\n const { workflow } = await props.client.createWorkflow({\n name: workflowName as typeUtils.Cast<TWorkflowName, string>,\n status: 'pending',\n ...prefixTagsIfNeeded(input, { alias: undefined /* props.pluginAlias */ }),\n })\n return { workflow: wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow }) }\n },\n }) satisfies WorkflowProxy<TBot>[TWorkflowName],\n })\n\nexport const wrapWorkflowInstance = <\n TBot extends BaseBot,\n TWorkflowName extends typeUtils.StringKeys<TBot['workflows']>,\n>(props: {\n client: BotSpecificClient<TBot> | client.Client\n workflow: client.Workflow\n event?: botServerTypes.WorkflowUpdateEvent\n onWorkflowUpdate?: (newState: client.Workflow) => Promise<void> | void\n pluginAlias?: string\n}): ActionableWorkflow<TBot, TWorkflowName> => {\n let isAcknowledged = false\n\n return {\n ...(unprefixTagsOwnedByPlugin(props.workflow, { alias: undefined /* props.pluginAlias */ }) as ActionableWorkflow<\n TBot,\n TWorkflowName\n >),\n\n async update(x) {\n const { workflow } = await props.client.updateWorkflow({\n id: props.workflow.id,\n ...prefixTagsIfNeeded(x, { alias: undefined /* props.pluginAlias */ }),\n })\n await props.onWorkflowUpdate?.(workflow)\n\n return { workflow: wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow }) }\n },\n\n async acknowledgeStartOfProcessing() {\n if (!props.event || props.workflow.status !== 'pending' || isAcknowledged) {\n return {\n workflow: wrapWorkflowInstance<TBot, TWorkflowName>(props),\n }\n }\n\n const { workflow } = await props.client.updateWorkflow({\n id: props.workflow.id,\n status: 'in_progress',\n eventId: props.event.id,\n })\n isAcknowledged = true\n\n await props.onWorkflowUpdate?.(workflow)\n\n return { workflow: wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow }) }\n },\n\n async setFailed({ failureReason }) {\n const { workflow } = await props.client.updateWorkflow({\n id: props.workflow.id,\n status: 'failed',\n failureReason,\n })\n\n await props.onWorkflowUpdate?.(workflow)\n\n return { workflow: wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow }) }\n },\n\n async setCompleted({ output } = {}) {\n const { workflow } = await props.client.updateWorkflow({ id: props.workflow.id, status: 'completed', output })\n await props.onWorkflowUpdate?.(workflow)\n\n return { workflow: wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow }) }\n },\n\n async cancel() {\n const { workflow } = await props.client.updateWorkflow({ id: props.workflow.id, status: 'cancelled' })\n await props.onWorkflowUpdate?.(workflow)\n\n return { workflow: wrapWorkflowInstance<TBot, TWorkflowName>({ ...props, workflow }) }\n },\n }\n}\n", "import { Workflow } from '@holocronlab/botruntime-client'\nimport type { Server } from 'node:http'\nimport { PLUGIN_PREFIX_SEPARATOR } from '../consts'\nimport { BasePlugin, PluginImplementation } from '../plugin'\nimport { serve } from '../serve'\nimport * as utils from '../utils'\nimport { BaseBot } from './common'\nimport {\n botHandler,\n ActionHandlers,\n MessageHandlers,\n EventHandlers,\n StateExpiredHandlers,\n HookHandlers,\n WorkflowHandlers,\n MessageHandlersMap,\n EventHandlersMap,\n StateExpiredHandlersMap,\n HookHandlersMap,\n WorkflowHandlersMap,\n OrderedMessageHandlersMap,\n OrderedEventHandlersMap,\n OrderedStateExpiredHandlersMap,\n OrderedHookHandlersMap,\n OrderedWorkflowHandlersMap,\n BotHandlers,\n UnimplementedActionHandlers,\n WorkflowUpdateType,\n InjectedHandlerProps,\n InjectedBotHandlers,\n RegisterHandler,\n} from './server'\nimport { proxyWorkflows, wrapWorkflowInstance } from './workflow-proxy'\n\nexport type BotImplementationProps<TBot extends BaseBot = BaseBot, TPlugins extends Record<string, BasePlugin> = {}> = {\n register?: RegisterHandler<TBot>\n actions: UnimplementedActionHandlers<TBot, TPlugins>\n plugins: {\n [K in utils.types.StringKeys<TPlugins>]: PluginImplementation<TPlugins[K]>\n }\n}\n\nexport class BotImplementation<TBot extends BaseBot = BaseBot, TPlugins extends Record<string, BasePlugin> = {}>\n implements InjectedBotHandlers<TBot>\n{\n private _registerHandler: RegisterHandler<TBot> | undefined\n private _actionHandlers: ActionHandlers<any>\n private _messageHandlers: OrderedMessageHandlersMap<any> = {}\n private _eventHandlers: OrderedEventHandlersMap<any> = {}\n private _stateExpiredHandlers: OrderedStateExpiredHandlersMap<any> = {}\n private _hookHandlers: OrderedHookHandlersMap<any> = {\n before_incoming_event: {},\n before_incoming_message: {},\n before_outgoing_message: {},\n before_outgoing_call_action: {},\n before_incoming_call_action: {},\n after_incoming_event: {},\n after_incoming_message: {},\n after_outgoing_message: {},\n after_outgoing_call_action: {},\n after_incoming_call_action: {},\n }\n private _workflowHandlers: OrderedWorkflowHandlersMap<any> = {\n started: {},\n continued: {},\n timed_out: {},\n }\n\n private _plugins: Record<string, PluginImplementation<any>> = {}\n\n private _registerOrder: number = 0\n\n public constructor(public readonly props: BotImplementationProps<TBot, TPlugins>) {\n this._registerHandler = props.register\n this._actionHandlers = props.actions as ActionHandlers<TBot>\n this._plugins = props.plugins\n }\n\n public get registerHandler(): RegisterHandler<TBot> | undefined {\n return this._registerHandler\n }\n\n public get actionHandlers(): InjectedBotHandlers<TBot>['actionHandlers'] {\n return new Proxy(\n {},\n {\n get: (_, actionName: string) => {\n const action = this._actionHandlers[actionName]\n if (action) {\n return utils.functions.setName(\n (props: Omit<Parameters<typeof action>[0], keyof InjectedHandlerProps<TBot>>) =>\n action({ ...props, workflows: proxyWorkflows(props) }),\n action.name\n )\n }\n\n for (const [pluginAlias, plugin] of Object.entries(this._plugins)) {\n const [actionPrefix, nameWithoutPrefix] = actionName.split(PLUGIN_PREFIX_SEPARATOR)\n if (actionPrefix !== pluginAlias || !nameWithoutPrefix) {\n continue\n }\n return plugin.actionHandlers[nameWithoutPrefix]\n }\n\n return undefined\n },\n }\n ) as InjectedBotHandlers<TBot>['actionHandlers']\n }\n\n public get messageHandlers(): InjectedBotHandlers<TBot>['messageHandlers'] {\n return new Proxy(\n {},\n {\n /** returns both the message handlers for the target type but global as well */\n get: (_, messageName: string) => {\n const pluginHandlers = Object.values(this._plugins).flatMap(\n (plugin) => plugin.messageHandlers[messageName] ?? []\n )\n const selfSpecificHandlers = messageName === '*' ? [] : (this._messageHandlers[messageName] ?? [])\n const selfGlobalHandlers = this._messageHandlers['*'] ?? []\n const selfHandlers = [...selfSpecificHandlers, ...selfGlobalHandlers]\n .sort((a, b) => a.order - b.order)\n .map(({ handler }) =>\n utils.functions.setName(\n (props: Omit<Parameters<typeof handler>[0], keyof InjectedHandlerProps<TBot>>) =>\n handler({ ...props, workflows: proxyWorkflows(props) }),\n handler.name\n )\n )\n\n return utils.arrays.unique([...pluginHandlers, ...selfHandlers])\n },\n }\n ) as InjectedBotHandlers<TBot>['messageHandlers']\n }\n\n public get eventHandlers(): InjectedBotHandlers<TBot>['eventHandlers'] {\n return new Proxy(\n {},\n {\n /** returns both the event handlers for the target type but global as well */\n get: (_, eventName: string) => {\n const pluginHandlers = Object.values(this._plugins).flatMap((plugin) => plugin.eventHandlers[eventName] ?? [])\n\n const selfSpecificHandlers = eventName === '*' ? [] : (this._eventHandlers[eventName] ?? [])\n const selfGlobalHandlers = this._eventHandlers['*'] ?? []\n const selfHandlers = [...selfSpecificHandlers, ...selfGlobalHandlers]\n .sort((a, b) => a.order - b.order)\n .map(({ handler }) =>\n utils.functions.setName(\n (props: Omit<Parameters<typeof handler>[0], keyof InjectedHandlerProps<TBot>>) =>\n handler({ ...props, workflows: proxyWorkflows(props) }),\n handler.name\n )\n )\n\n return utils.arrays.unique([...pluginHandlers, ...selfHandlers])\n },\n }\n ) as InjectedBotHandlers<TBot>['eventHandlers']\n }\n\n public get stateExpiredHandlers(): InjectedBotHandlers<TBot>['stateExpiredHandlers'] {\n return new Proxy(\n {},\n {\n /** returns both the state expired handlers for the target type but global as well */\n get: (_, stateName: string) => {\n const pluginHandlers = Object.values(this._plugins).flatMap(\n (plugin) => plugin.stateExpiredHandlers[stateName] ?? []\n )\n\n const selfSpecificHandlers = stateName === '*' ? [] : (this._stateExpiredHandlers[stateName] ?? [])\n const selfGlobalHandlers = this._stateExpiredHandlers['*'] ?? []\n const selfHandlers = [...selfSpecificHandlers, ...selfGlobalHandlers]\n .sort((a, b) => a.order - b.order)\n .map(({ handler }) =>\n utils.functions.setName(\n (props: Omit<Parameters<typeof handler>[0], keyof InjectedHandlerProps<TBot>>) =>\n handler({ ...props, workflows: proxyWorkflows(props) }),\n handler.name\n )\n )\n\n return utils.arrays.unique([...pluginHandlers, ...selfHandlers])\n },\n }\n ) as InjectedBotHandlers<TBot>['stateExpiredHandlers']\n }\n\n public get hookHandlers(): InjectedBotHandlers<TBot>['hookHandlers'] {\n return new Proxy(\n {},\n {\n get: (_, hookType: utils.types.StringKeys<HookHandlersMap<TBot>>) => {\n const hooks = this._hookHandlers[hookType]\n if (!hooks) {\n return undefined\n }\n\n return new Proxy(\n {},\n {\n get: (_, hookDataName: string) => {\n const pluginHandlers = Object.values(this._plugins).flatMap(\n (plugin) => (plugin.hookHandlers[hookType]?.[hookDataName] ?? []) as typeof selfHandlers\n )\n\n const selfHooks = this._hookHandlers[hookType] ?? {}\n const selfSpecificHandlers = hookDataName === '*' ? [] : (selfHooks[hookDataName] ?? [])\n const selfGlobalHandlers = selfHooks['*'] ?? []\n const selfHandlers = [...selfSpecificHandlers, ...selfGlobalHandlers]\n .sort((a, b) => a.order - b.order)\n .map(({ handler }) =>\n utils.functions.setName(\n (props: any) => handler({ ...props, workflows: proxyWorkflows(props) }),\n handler.name\n )\n )\n\n return utils.arrays.unique([...pluginHandlers, ...selfHandlers])\n },\n }\n )\n },\n }\n ) as InjectedBotHandlers<TBot>['hookHandlers']\n }\n\n public get workflowHandlers(): InjectedBotHandlers<TBot>['workflowHandlers'] {\n return new Proxy(\n {},\n {\n get: (_, updateType: WorkflowUpdateType) => {\n const handlersOfType = this._workflowHandlers[updateType]\n if (!handlersOfType) {\n return undefined\n }\n\n return new Proxy(\n {},\n {\n get: (_, workflowName: string) => {\n const selfHandlers =\n handlersOfType[workflowName]\n ?.sort((a, b) => a.order - b.order)\n .map(({ handler }) =>\n utils.functions.setName(\n async (props: Omit<Parameters<typeof handler>[0], keyof InjectedHandlerProps<TBot>>) => {\n let currentWorkflowState: Workflow = props.workflow\n await handler({\n ...props,\n workflow: wrapWorkflowInstance({\n ...props,\n onWorkflowUpdate(newState) {\n currentWorkflowState = newState\n },\n }),\n workflows: proxyWorkflows(props),\n })\n return currentWorkflowState\n },\n handler.name\n )\n ) ?? []\n\n const pluginHandlers = Object.values(this._plugins).flatMap(\n (plugin) => plugin.workflowHandlers[updateType]?.[workflowName] ?? []\n )\n\n return utils.arrays.unique([...selfHandlers, ...pluginHandlers])\n },\n }\n )\n },\n }\n ) as InjectedBotHandlers<TBot>['workflowHandlers']\n }\n\n public readonly on = {\n message: <T extends utils.types.StringKeys<MessageHandlersMap<TBot>>>(\n type: T,\n handler: MessageHandlers<TBot>[T]\n ): void => {\n this._messageHandlers[type] = utils.arrays.safePush(this._messageHandlers[type], {\n handler: handler as MessageHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n event: <T extends utils.types.StringKeys<EventHandlersMap<TBot>>>(\n type: T,\n handler: EventHandlers<TBot>[T]\n ): void => {\n this._eventHandlers[type] = utils.arrays.safePush(this._eventHandlers[type], {\n handler: handler as EventHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n stateExpired: <T extends utils.types.StringKeys<StateExpiredHandlersMap<TBot>>>(\n type: T,\n handler: StateExpiredHandlers<TBot>[T]\n ): void => {\n this._stateExpiredHandlers[type] = utils.arrays.safePush(this._stateExpiredHandlers[type], {\n handler: handler as StateExpiredHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n beforeIncomingEvent: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['before_incoming_event'][string], order: this._registerOrder++ }\n )\n },\n beforeIncomingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['before_incoming_message'][string], order: this._registerOrder++ }\n )\n },\n beforeOutgoingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['before_outgoing_message'][string], order: this._registerOrder++ }\n )\n },\n beforeOutgoingCallAction: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['before_outgoing_call_action'][string], order: this._registerOrder++ }\n )\n },\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n beforeIncomingCallAction: <T extends utils.types.StringKeys<HookHandlersMap<TBot>['before_incoming_call_action']>>(\n type: T,\n handler: HookHandlers<TBot>['before_incoming_call_action'][T]\n ) => {\n this._hookHandlers.before_incoming_call_action[type] = utils.arrays.safePush(\n this._hookHandlers.before_incoming_call_action[type],\n { handler: handler as HookHandlers<any>['before_incoming_call_action'][string], order: this._registerOrder++ }\n )\n },\n afterIncomingEvent: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['after_incoming_event'][string], order: this._registerOrder++ }\n )\n },\n afterIncomingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['after_incoming_message'][string], order: this._registerOrder++ }\n )\n },\n afterOutgoingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['after_outgoing_message'][string], order: this._registerOrder++ }\n )\n },\n afterOutgoingCallAction: <T extends utils.types.StringKeys<HookHandlersMap<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: handler as HookHandlers<any>['after_outgoing_call_action'][string], order: this._registerOrder++ }\n )\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n afterIncomingCallAction: <T extends utils.types.StringKeys<HookHandlersMap<TBot>['after_incoming_call_action']>>(\n type: T,\n handler: HookHandlers<TBot>['after_incoming_call_action'][T]\n ) => {\n this._hookHandlers.after_incoming_call_action[type] = utils.arrays.safePush(\n this._hookHandlers.after_incoming_call_action[type],\n { handler: handler as HookHandlers<any>['after_incoming_call_action'][string], order: this._registerOrder++ }\n )\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflowStart: <T extends utils.types.StringKeys<WorkflowHandlersMap<TBot>['started']>>(\n type: T,\n handler: WorkflowHandlers<TBot>[T]\n ): void => {\n this._workflowHandlers.started[type] = utils.arrays.safePush(this._workflowHandlers.started[type], {\n handler: handler as WorkflowHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflowContinue: <T extends utils.types.StringKeys<WorkflowHandlersMap<TBot>['continued']>>(\n type: T,\n handler: WorkflowHandlers<TBot>[T]\n ): void => {\n this._workflowHandlers.continued[type] = utils.arrays.safePush(this._workflowHandlers.continued[type], {\n handler: handler as WorkflowHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflowTimeout: <T extends utils.types.StringKeys<WorkflowHandlersMap<TBot>['timed_out']>>(\n type: T,\n handler: WorkflowHandlers<TBot>[T]\n ): void => {\n this._workflowHandlers.timed_out[type] = utils.arrays.safePush(this._workflowHandlers.timed_out[type], {\n handler: handler as WorkflowHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n }\n\n public readonly handler = botHandler(this as unknown as BotHandlers<any>)\n\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { SchemaTransformOptions } from '../common/types'\nimport { ActionDefinition, ChannelDefinition, EntityDefinition, EventDefinition } from '../integration/definition'\nimport * as utils from '../utils'\nimport { SDK_VERSION } from '../version'\nimport { z } from '../zui'\n\ntype BaseEvents = Record<string, z.ZuiObjectSchema>\ntype BaseActions = Record<string, z.ZuiObjectSchema>\ntype BaseMessages = Record<string, z.ZuiObjectSchema>\ntype BaseChannels = Record<string, BaseMessages>\ntype BaseEntities = Record<string, z.ZuiObjectSchema>\n\ntype EntityReferences<TEntities extends BaseEntities> = {\n [K in keyof TEntities]: z.ZodRef\n}\n\ntype GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {\n schema: z.GenericZuiSchema<EntityReferences<TEntities>, TEvent>\n attributes?: Record<string, string>\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: z.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: z.GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: z.GenericZuiSchema<EntityReferences<TEntities>, z.ZuiObjectSchema> }\n attributes?: Record<string, string>\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 title?: string\n description?: string\n icon?: string\n readme?: string\n\n attributes?: Record<string, string>\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 __advanced?: SchemaTransformOptions\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 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 attributes: this['props']['attributes']\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 __advanced: this['props']['__advanced']\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.icon = props.icon\n this.title = props.title\n this.description = props.description\n this.readme = props.readme\n this.entities = props.entities ?? ({} as this['entities'])\n this.attributes = props.attributes\n this.__advanced = props.__advanced\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 public get metadata() {\n return { sdkVersion: SDK_VERSION } as const\n }\n\n public readonly clone?: (overrides?: Partial<InterfaceDefinitionProps>) => InterfaceDefinition = (overrides?) => {\n // TODO: make non-optional on next major (CLI and SDK share the same major, so the CLI can always rely on clone being present)\n return new InterfaceDefinition({ ...this.props, ...overrides } as InterfaceDefinitionProps)\n }\n\n private _getEntityReference = (entities: Record<string, EntityDefinition>): EntityReferences<TEntities> => {\n const entityReferences: Record<string, z.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 BotDefinitionProps,\n StateDefinition as BotStateDefinition,\n EventDefinition as BotEventDefinition,\n ConfigurationDefinition as BotConfigurationDefinition,\n UserDefinition,\n ConversationDefinition,\n MessageDefinition,\n ActionDefinition as BotActionDefinition,\n TableDefinition as BotTableDefinition,\n WorkflowDefinition,\n} from '../bot/definition'\nimport { stripRecurringFromEvents, resolveRecurringEvents } from '../common/recurring-events'\nimport { SchemaTransformOptions } from '../common/types'\nimport { DefinitionError } from '../errors'\nimport { IntegrationPackage, InterfacePackage } from '../package'\nimport * as typeUtils from '../utils/type-utils'\nimport { SDK_VERSION } from '../version'\nimport { z } from '../zui'\n\nexport { UserDefinition, ConversationDefinition, MessageDefinition, WorkflowDefinition } from '../bot/definition'\n\ntype BaseConfig = z.ZuiObjectOrRefSchema\ntype BaseStates = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseEvents = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseActions = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseInterfaces = Record<string, InterfacePackage>\ntype BaseIntegrations = Record<string, IntegrationPackage>\ntype BaseTables = Record<string, z.ZuiObjectOrRefSchema>\ntype BaseWorkflows = Record<string, z.ZuiObjectSchema>\n\nexport type TableDefinition<TTable extends BaseTables[string] = BaseTables[string]> = typeUtils.Merge<\n BotTableDefinition,\n {\n schema: TTable\n }\n>\n\nexport type ConfigurationDefinition<TConfig extends BaseConfig = BaseConfig> = typeUtils.Merge<\n BotConfigurationDefinition,\n {\n schema: TConfig\n }\n>\n\nexport type StateDefinition<TState extends BaseStates[string] = BaseStates[string]> = typeUtils.Merge<\n BotStateDefinition,\n {\n schema: TState\n }\n>\n\nexport type EventDefinition<TEvent extends BaseEvents[string] = BaseEvents[string]> = typeUtils.Merge<\n BotEventDefinition,\n {\n schema: TEvent\n }\n>\n\nexport type ActionDefinition<TAction extends BaseActions[string] = BaseActions[string]> = typeUtils.Merge<\n BotActionDefinition,\n {\n input: { schema: TAction }\n output: { schema: z.ZuiObjectOrRefSchema }\n }\n>\n\n/*\n * @deprecated Use the `recurring` field on `EventDefinition` instead.\n */\nexport type RecurringEventDefinition<TEvents extends BaseEvents = BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: {\n cron: string\n }\n }\n}[keyof TEvents]\n\nexport type ZuiSchemaWithEntityReferences<\n TInterfaces extends BaseInterfaces,\n TReturnType extends z.ZuiObjectOrRefSchema,\n> =\n | ((props: {\n entities: {\n [TInterfaceAlias in keyof TInterfaces]: {\n [TEntityName in keyof TInterfaces[TInterfaceAlias]['definition']['entities']]: z.ZodRef\n }\n }\n }) => TReturnType)\n | TReturnType\n\ntype GenericDefinition<\n TInterfaces extends BaseInterfaces,\n TDefinition extends { schema: z.ZuiObjectOrRefSchema },\n> = typeUtils.Merge<\n TDefinition,\n {\n schema: ZuiSchemaWithEntityReferences<TInterfaces, TDefinition['schema']>\n }\n>\n\ntype GenericNestedDefinition<\n TInterfaces extends BaseInterfaces,\n TDefinition extends { [k: string]: any },\n TKeys extends string,\n> = Omit<TDefinition, TKeys> & {\n [TKey in TKeys]: Omit<TDefinition[TKey], 'schema'> & {\n schema: ZuiSchemaWithEntityReferences<TInterfaces, TDefinition[TKey]['schema']>\n }\n}\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 TTables extends BaseTables = BaseTables,\n TWorkflows extends BaseWorkflows = BaseWorkflows,\n> = {\n name: TName\n version: TVersion\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n attributes?: Record<string, string>\n\n integrations?: TIntegrations\n interfaces?: TInterfaces\n user?: UserDefinition\n conversation?: ConversationDefinition\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: GenericDefinition<TInterfaces, StateDefinition<TStates[K]>>\n }\n configuration?: GenericDefinition<TInterfaces, ConfigurationDefinition<TConfig>>\n events?: {\n [K in keyof TEvents]: GenericDefinition<TInterfaces, EventDefinition<TEvents[K]>>\n }\n /** @deprecated Use the `recurrence` field on each event in `events` instead. */\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n actions?: {\n [K in keyof TActions]: GenericNestedDefinition<TInterfaces, ActionDefinition<TActions[K]>, 'input' | 'output'>\n }\n tables?: {\n [K in keyof TTables]: GenericDefinition<TInterfaces, TableDefinition<TTables[K]>>\n }\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflows?: {\n [K in keyof TWorkflows]: WorkflowDefinition<TWorkflows[K]>\n }\n\n __advanced?: SchemaTransformOptions\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 TTables extends BaseTables = BaseTables,\n TWorkflows extends BaseWorkflows = BaseWorkflows,\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n\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\n public readonly attributes: this['props']['attributes']\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: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n public readonly configuration?: ConfigurationDefinition<TConfig>\n public readonly events: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n public readonly recurringEvents: this['props']['recurringEvents']\n public readonly actions: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n public readonly tables: {\n [K in keyof TTables]: TableDefinition<TTables[K]>\n }\n public readonly workflows: this['props']['workflows']\n public readonly __advanced: this['props']['__advanced']\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 TTables,\n TWorkflows\n >\n ) {\n // entities.<interfaceAlias>.<entityName> -> ZodRef\n const entities = Object.fromEntries(\n Object.entries(props.interfaces ?? {}).map(([interfaceAlias, interfaceDef]) => [\n interfaceAlias,\n Object.fromEntries(\n Object.entries(interfaceDef.definition.entities ?? {}).map(([entityName]) => [\n entityName,\n z.ref(`interface:${interfaceAlias}/entities/${entityName}`),\n ])\n ),\n ])\n ) as {\n [TInterfaceAlias in keyof TInterfaces]: {\n [TEntityName in keyof TInterfaces[TInterfaceAlias]['definition']['entities']]: z.ZodRef\n }\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.description = props.description\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.workflows = props.workflows\n this.attributes = props.attributes\n this.__advanced = props.__advanced\n\n const aliases = new Set<string>()\n\n for (const alias of [...Object.keys(props.integrations ?? {}), ...Object.keys(props.interfaces ?? {})]) {\n if (aliases.has(alias)) {\n throw new DefinitionError(\n `Duplicate interface or integration alias detected in plugin definition: '${alias}'. ` +\n 'Please use unique aliases for each interface and integration.'\n )\n }\n aliases.add(alias)\n }\n\n this.configuration = props.configuration\n ? {\n ...props.configuration,\n schema:\n typeof props.configuration.schema === 'object'\n ? props.configuration.schema\n : props.configuration.schema({ entities }),\n }\n : undefined\n\n this.states = Object.fromEntries(\n Object.entries(props.states ?? {}).map(\n ([stateName, stateDef]: [keyof TStates, NonNullable<(typeof props)['states']>[keyof TStates]]) => [\n stateName,\n {\n ...stateDef,\n schema: typeof stateDef.schema === 'object' ? stateDef.schema : stateDef.schema({ entities }),\n } as StateDefinition<TStates[keyof TStates]>,\n ]\n )\n ) as { [K in keyof TStates]: StateDefinition<TStates[K]> }\n\n const resolvedEvents = Object.fromEntries(\n Object.entries(props.events ?? {}).map(\n ([eventName, eventDef]: [keyof TEvents, NonNullable<(typeof props)['events']>[keyof TEvents]]) => [\n eventName,\n {\n ...eventDef,\n schema: typeof eventDef.schema === 'object' ? eventDef.schema : eventDef.schema({ entities }),\n } as EventDefinition<TEvents[keyof TEvents]>,\n ]\n )\n ) as { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n this.events = stripRecurringFromEvents(resolvedEvents)\n this.recurringEvents = resolveRecurringEvents(\n resolvedEvents as Record<string, EventDefinition>,\n props.recurringEvents as BotDefinitionProps['recurringEvents']\n )\n\n this.actions = Object.fromEntries(\n Object.entries(props.actions ?? {}).map(\n ([actionName, actionDef]: [keyof TActions, NonNullable<(typeof props)['actions']>[keyof TActions]]) => [\n actionName,\n {\n ...actionDef,\n input: {\n ...actionDef.input,\n schema:\n typeof actionDef.input.schema === 'object'\n ? actionDef.input.schema\n : actionDef.input.schema({ entities }),\n },\n output: {\n ...actionDef.output,\n schema:\n typeof actionDef.output.schema === 'object'\n ? actionDef.output.schema\n : actionDef.output.schema({ entities }),\n },\n } as ActionDefinition<TActions[keyof TActions]>,\n ]\n )\n ) as { [K in keyof TActions]: ActionDefinition<TActions[K]> }\n\n this.tables = Object.fromEntries(\n Object.entries(props.tables ?? {}).map(\n ([tableName, tableDef]: [keyof TTables, NonNullable<(typeof props)['tables']>[keyof TTables]]) => [\n tableName,\n {\n ...tableDef,\n schema: typeof tableDef.schema === 'object' ? tableDef.schema : tableDef.schema({ entities }),\n } as TableDefinition<TTables[keyof TTables]>,\n ]\n )\n ) as { [K in keyof TTables]: TableDefinition<TTables[K]> }\n }\n\n public get metadata() {\n return { sdkVersion: SDK_VERSION } as const\n }\n\n public readonly clone?: (overrides?: Partial<PluginDefinitionProps>) => PluginDefinition = (overrides?) => {\n // TODO: make non-optional on next major (CLI and SDK share the same major, so the CLI can always rely on clone being present)\n return new PluginDefinition({ ...this.props, ...overrides } as PluginDefinitionProps)\n }\n\n /**\n * Returns a copy of the plugin definition where all entity references are\n * resolved to the base entity schema defined by the interface. This does not\n * include any additional properties that may be added to the entity by the\n * backing integration.\n *\n * If `intersectWithUnknownRecord` is `true` (default), the entity schemas\n * will be intersected with `z.record(z.string(), z.unknown())` to make it\n * explicit that the backing integration may have added additional properties.\n */\n public dereferenceEntities(\n { intersectWithUnknownRecord }: { intersectWithUnknownRecord?: boolean } = {\n intersectWithUnknownRecord: true,\n }\n ): this {\n const zuiReferenceMap = this._buildZuiReferenceMap(intersectWithUnknownRecord)\n\n return {\n ...this,\n configuration: this.configuration\n ? {\n ...this.configuration,\n schema: this._dereferenceZuiSchema(this.configuration.schema, zuiReferenceMap),\n }\n : undefined,\n events: this._dereferenceDefinitionSchemas(this.events, zuiReferenceMap),\n states: this._dereferenceDefinitionSchemas(this.states, zuiReferenceMap),\n tables: this._dereferenceDefinitionSchemas(this.tables, zuiReferenceMap),\n actions: this._dereferenceActionDefinitionSchemas(this.actions, zuiReferenceMap),\n } as typeof this\n }\n\n private _buildZuiReferenceMap(intersectWithUnknownRecord?: boolean): Record<string, z.ZodTypeAny> {\n return Object.fromEntries(\n (Object.entries(this.interfaces ?? {}) as [string, InterfacePackage][]).flatMap(\n ([interfaceAlias, interfacePackage]) =>\n Object.entries(interfacePackage.definition.entities ?? {}).map(([entityName, entityDefinition]) => [\n `interface:${interfaceAlias}/entities/${entityName}`,\n intersectWithUnknownRecord\n ? entityDefinition.schema.and(z.record(z.string(), z.unknown()))\n : entityDefinition.schema,\n ])\n )\n )\n }\n\n private _dereferenceZuiSchema(\n schema: z.ZuiObjectOrRefSchema,\n zuiReferenceMap: Record<string, z.ZodTypeAny>\n ): z.ZuiObjectSchema {\n return schema.dereference(zuiReferenceMap) as z.ZuiObjectSchema\n }\n\n private _dereferenceDefinitionSchemas<TDefinitionRecord extends Record<string, { schema: z.ZuiObjectOrRefSchema }>>(\n definitions: TDefinitionRecord | undefined,\n zuiReferenceMap: Record<string, z.ZodTypeAny>\n ): TDefinitionRecord {\n return Object.fromEntries(\n Object.entries(definitions ?? {}).map(([key, definition]) => [\n key,\n { ...definition, schema: this._dereferenceZuiSchema(definition.schema, zuiReferenceMap) },\n ])\n ) as TDefinitionRecord\n }\n\n private _dereferenceActionDefinitionSchemas<\n TDefinitionRecord extends Record<\n string,\n { input: { schema: z.ZuiObjectOrRefSchema }; output: { schema: z.ZuiObjectOrRefSchema } }\n >,\n >(definitions: TDefinitionRecord | undefined, zuiReferenceMap: Record<string, z.ZodTypeAny>): TDefinitionRecord {\n return Object.fromEntries(\n Object.entries(definitions ?? {}).map(([key, definition]) => [\n key,\n {\n ...definition,\n input: { schema: this._dereferenceZuiSchema(definition.input.schema, zuiReferenceMap) },\n output: { schema: this._dereferenceZuiSchema(definition.output.schema, zuiReferenceMap) },\n },\n ])\n ) as TDefinitionRecord\n }\n}\n", "import { Client } from '@holocronlab/botruntime-client'\nimport { BotSpecificClient, EnumerateActions } from '../../bot'\nimport type * as typeUtils from '../../utils/type-utils'\nimport { BasePlugin, PluginRuntimeProps } from '../common'\nimport { ActionProxy } from './types'\n\nexport const proxyActions = <TPlugin extends BasePlugin>(\n client: BotSpecificClient<TPlugin> | Client,\n props: PluginRuntimeProps<TPlugin>\n): ActionProxy<TPlugin> =>\n new Proxy<Partial<ActionProxy<TPlugin>>>(\n {},\n {\n get: (_target, integrationOrInterfaceAlias: string) =>\n new Proxy(\n {},\n {\n get: (_target, actionName: string) => (input: Record<string, any>) => {\n const integrationAlias = (\n props.integrations[integrationOrInterfaceAlias] ?? props.interfaces[integrationOrInterfaceAlias]\n )?.integrationAlias\n const actualActionName =\n props.interfaces[integrationOrInterfaceAlias]?.actions?.[actionName]?.name ?? actionName\n\n return client\n .callAction({\n type: `${integrationAlias}:${actualActionName}` as typeUtils.Cast<\n keyof EnumerateActions<TPlugin>,\n string\n >,\n input,\n })\n .then((res) => res.output)\n },\n }\n ),\n }\n ) as ActionProxy<TPlugin>\n", "import type * as client from '@holocronlab/botruntime-client'\nimport type { BotSpecificClient } from '../../bot'\nimport type { commonTypes } from '../../common'\nimport { createAsyncCollection } from '../../utils/api-paging-utils'\nimport type * as typeUtils from '../../utils/type-utils'\n\nimport type { BasePlugin, PluginRuntimeProps } from '../common'\nimport { prefixTagsIfNeeded, unprefixTagsOwnedByPlugin } from '../tag-prefixer'\nimport type { ActionableMessage, AnyPluginMessage, MessageFinder } from './types'\n\nexport const proxyMessages = <TPlugin extends BasePlugin>(props: {\n client: BotSpecificClient<TPlugin> | client.Client\n plugin?: PluginRuntimeProps<TPlugin>\n}): MessageFinder<TPlugin> => ({\n async getById({ id }) {\n const response = await (props.client.getMessage({ id }) as Promise<client.ClientOutputs['getMessage']>)\n return proxyMessage({ ...props, message: response.message as client.Message })\n },\n\n list(listProps) {\n return createAsyncCollection(({ nextToken }) =>\n props.client\n .listMessages({\n ...prefixTagsIfNeeded(listProps ?? {}, { alias: props.plugin?.alias }),\n nextToken,\n })\n .then(({ meta, messages }) => ({\n meta,\n items: messages.map((message) => proxyMessage({ ...props, message })),\n }))\n )\n },\n})\n\nexport const proxyMessage = <\n TPlugin extends BasePlugin,\n TMessage extends client.Message | AnyPluginMessage<TPlugin> = AnyPluginMessage<TPlugin>,\n>(props: {\n client: BotSpecificClient<TPlugin> | client.Client\n plugin?: PluginRuntimeProps<TPlugin>\n message: TMessage\n}): ActionableMessage<TPlugin, TMessage> => ({\n ...(unprefixTagsOwnedByPlugin(props.message, { alias: props.plugin?.alias }) as unknown as typeUtils.Merge<\n TMessage,\n {\n tags: commonTypes.ToTags<typeUtils.StringKeys<TPlugin['conversation']['tags']>>\n }\n >),\n\n async delete() {\n await props.client.deleteMessage({ id: props.message.id })\n },\n\n async update(data) {\n const { message: updatedMessage } = await props.client.updateMessage({\n ...prefixTagsIfNeeded(data, { alias: props.plugin?.alias }),\n id: props.message.id,\n })\n\n return proxyMessage({ ...props, message: updatedMessage as TMessage })\n },\n})\n", "import type * as client from '@holocronlab/botruntime-client'\nimport type { BotSpecificClient } from '../../bot'\nimport type { commonTypes } from '../../common'\nimport { createAsyncCollection } from '../../utils/api-paging-utils'\nimport type * as typeUtils from '../../utils/type-utils'\nimport type { BasePlugin } from '../common'\nimport { prefixTagsIfNeeded, unprefixTagsOwnedByPlugin } from '../tag-prefixer'\nimport type {\n UserFinder,\n ActionableUser,\n BaseActionableUser,\n ActionableUserWithoutConversation,\n ActionableUserWithConversation,\n} from './types'\n\nexport const proxyUsers = <TPlugin extends BasePlugin>(props: {\n client: BotSpecificClient<TPlugin> | client.Client\n pluginAlias?: string\n}): UserFinder<TPlugin> => ({\n list(listProps) {\n return createAsyncCollection(({ nextToken }) =>\n props.client\n .listUsers({\n ...prefixTagsIfNeeded(listProps ?? {}, { alias: props.pluginAlias }),\n nextToken,\n })\n .then(({ meta, users }) => ({\n meta,\n items: users.map((user) => proxyUser({ ...props, conversationId: listProps?.conversationId, user })),\n }))\n )\n },\n\n async getById({ id }) {\n const response = await props.client.getUser({ id })\n return proxyUser({ ...props, user: response.user, conversationId: undefined })\n },\n})\n\nexport const proxyUser = <TPlugin extends BasePlugin, TConversationId extends string | undefined>(props: {\n client: BotSpecificClient<TPlugin> | client.Client\n conversationId?: TConversationId\n pluginAlias?: string\n user: client.User\n}): ActionableUser<TPlugin, TConversationId> => {\n const baseActionableUser = {\n ...(unprefixTagsOwnedByPlugin(props.user, { alias: props.pluginAlias }) as typeUtils.Merge<\n client.User,\n {\n tags: commonTypes.ToTags<typeUtils.StringKeys<TPlugin['user']['tags']>>\n }\n >),\n\n async update(data) {\n const { user: updatedUser } = await props.client.updateUser({\n ...prefixTagsIfNeeded(data, { alias: props.pluginAlias }),\n id: props.user.id,\n })\n\n return proxyUser({ ...props, user: updatedUser })\n },\n } satisfies BaseActionableUser<TPlugin, TConversationId>\n\n return (\n props.conversationId\n ? ({\n ...baseActionableUser,\n async removeFromConversation() {\n await props.client.removeParticipant({ id: props.conversationId!, userId: props.user.id })\n\n return proxyUser({\n ...props,\n conversationId: undefined,\n })\n },\n } satisfies ActionableUserWithConversation<TPlugin, TConversationId>)\n : ({\n ...baseActionableUser,\n async addToConversation({ conversationId }) {\n const { participant } = await props.client.addParticipant({ id: conversationId, userId: props.user.id })\n\n return proxyUser({\n ...props,\n user: participant,\n conversationId,\n })\n },\n } satisfies ActionableUserWithoutConversation<TPlugin, TConversationId>)\n ) as ActionableUser<TPlugin, TConversationId>\n}\n", "import type * as client from '@holocronlab/botruntime-client'\nimport type { BotSpecificClient } from '../../bot'\n\nimport type { commonTypes } from '../../common'\nimport { type AsyncCollection, createAsyncCollection } from '../../utils/api-paging-utils'\nimport type * as typeUtils from '../../utils/type-utils'\nimport type { BasePlugin, PluginRuntimeProps } from '../common'\nimport { proxyMessage } from '../message-proxy/proxy'\nimport { prefixTagsIfNeeded, unprefixTagsOwnedByPlugin } from '../tag-prefixer'\nimport { proxyUser } from '../user-proxy'\nimport type { ActionableConversation, ConversationFinder } from './types'\n\nexport const proxyConversations = <TPlugin extends BasePlugin>(props: {\n client: BotSpecificClient<TPlugin> | client.Client\n plugin?: PluginRuntimeProps<TPlugin>\n}): ConversationFinder<TPlugin> =>\n new Proxy(\n {},\n {\n get: (_target, interfaceOrIntegrationAlias: string) =>\n new Proxy(\n {},\n {\n get: (_target2, channel: string) => {\n return {\n list(listProps): any {\n const integrationName =\n props.plugin?.interfaces[interfaceOrIntegrationAlias]?.integrationAlias ??\n props.plugin?.integrations[interfaceOrIntegrationAlias]?.integrationAlias\n\n const actualChannelName =\n props.plugin?.interfaces[interfaceOrIntegrationAlias]?.channels?.[channel]?.name ?? channel\n\n return createAsyncCollection(({ nextToken }) =>\n props.client\n .listConversations({\n ...prefixTagsIfNeeded(listProps ?? {}, { alias: props.plugin?.alias }),\n channel: actualChannelName === '*' ? undefined : actualChannelName,\n integrationName: integrationName === '*' ? undefined : integrationName,\n nextToken,\n })\n .then(({ meta, conversations }) => ({\n meta,\n items: conversations.map((conversation) => proxyConversation({ ...props, conversation })),\n }))\n ) satisfies AsyncCollection<ActionableConversation<TPlugin>>\n },\n\n async getById({ id }): Promise<any> {\n const response = await props.client.getConversation({ id })\n return proxyConversation({\n ...props,\n conversation: response.conversation,\n }) satisfies ActionableConversation<TPlugin>\n },\n } satisfies ConversationFinder<TPlugin>['*']['*']\n },\n }\n ),\n }\n ) as ConversationFinder<TPlugin>\n\nexport const proxyConversation = <TPlugin extends BasePlugin>(props: {\n client: BotSpecificClient<TPlugin> | client.Client\n plugin?: PluginRuntimeProps<TPlugin>\n conversation: client.Conversation\n}): ActionableConversation<TPlugin> => {\n // Client.GetMessageResponse conflicts with MessageResponse<TPlugin>:\n const vanillaClient = props.client as client.Client\n\n return {\n ...(unprefixTagsOwnedByPlugin(props.conversation, { alias: props.plugin?.alias }) as typeUtils.Merge<\n client.Conversation,\n { tags: commonTypes.ToTags<typeUtils.StringKeys<TPlugin['message']['tags']>> }\n >),\n\n async delete() {\n await vanillaClient.deleteConversation({ id: props.conversation.id })\n },\n\n async update(data) {\n const { conversation: updatedConversation } = await vanillaClient.updateConversation({\n ...prefixTagsIfNeeded(data, { alias: props.plugin?.alias }),\n id: props.conversation.id,\n })\n\n return proxyConversation({ ...props, conversation: updatedConversation })\n },\n\n async getMessage({ id }) {\n const response = await vanillaClient.getMessage({ id })\n return proxyMessage({ ...props, message: response.message })\n },\n\n async getOrCreateMessage(data) {\n const { message } = await vanillaClient.getOrCreateMessage({\n ...prefixTagsIfNeeded(data, { alias: props.plugin?.alias }),\n conversationId: props.conversation.id,\n })\n\n return proxyMessage({ ...props, message })\n },\n\n async createMessage(data) {\n const { message } = await vanillaClient.createMessage({\n ...prefixTagsIfNeeded(data, { alias: props.plugin?.alias }),\n conversationId: props.conversation.id,\n })\n\n return proxyMessage({ ...props, message })\n },\n\n listMessages(listProps) {\n return createAsyncCollection(({ nextToken }) =>\n vanillaClient\n .listMessages({\n ...prefixTagsIfNeeded(listProps ?? {}, { alias: props.plugin?.alias }),\n conversationId: props.conversation.id,\n nextToken,\n })\n .then(({ meta, messages }) => ({\n meta,\n items: messages.map((message) => proxyMessage({ ...props, message })),\n }))\n )\n },\n\n listParticipants() {\n return createAsyncCollection(({ nextToken }) =>\n vanillaClient\n .listParticipants({\n id: props.conversation.id,\n nextToken,\n })\n .then(({ meta, participants }) => ({\n meta,\n items: participants.map((user) =>\n proxyUser<TPlugin, string>({ ...props, user, conversationId: props.conversation.id })\n ),\n }))\n )\n },\n }\n}\n", "import type * as client from '@holocronlab/botruntime-client'\nimport { BotSpecificClient } from '../../bot'\nimport * as consts from '../../consts'\nimport { type AsyncCollection, createAsyncCollection } from '../../utils/api-paging-utils'\nimport { BasePlugin, PluginRuntimeProps } from '../common'\nimport { EventProxy, EventSchedule, EventSender } from './types'\n\ntype _EventSenderProps = {\n client: BotSpecificClient<any> | client.Client\n eventName: string\n conversationId?: string\n userId?: string\n messageId?: string\n}\n\nclass _EventSender implements EventSender<object> {\n public constructor(private _props: _EventSenderProps) {}\n\n public async emit(eventPayload: object): Promise<client.Event> {\n const { conversationId, userId, messageId } = this._props\n const { event } = await this._props.client.createEvent({\n type: this._props.eventName,\n payload: eventPayload,\n conversationId,\n userId,\n messageId,\n })\n return event\n }\n\n public async schedule(eventPayload: object, schedule: EventSchedule): Promise<client.Event> {\n const { conversationId, userId, messageId } = this._props\n const { event } = await this._props.client.createEvent({\n type: this._props.eventName,\n payload: eventPayload,\n conversationId,\n userId,\n messageId,\n schedule,\n })\n return event\n }\n\n public withConversationId(conversationId: string): this {\n return new _EventSender({\n ...this._props,\n conversationId,\n }) as this\n }\n\n public withUserId(userId: string): this {\n return new _EventSender({\n ...this._props,\n userId,\n }) as this\n }\n\n public withMessageId(messageId: string): this {\n return new _EventSender({\n ...this._props,\n messageId,\n }) as this\n }\n\n public async getById(props: { id: string }): Promise<client.Event> {\n const response = await this._props.client.getEvent({ id: props.id })\n return response.event\n }\n\n public list(\n props?: Omit<client.ClientInputs['listEvents'], 'type' | 'nextToken' | 'conversationId' | 'messageId' | 'userId'>\n ): AsyncCollection<client.Event> {\n return createAsyncCollection(({ nextToken }) =>\n this._props.client\n .listEvents({\n ...props,\n type: this._props.eventName,\n conversationId: this._props.conversationId,\n userId: this._props.userId,\n messageId: this._props.messageId,\n nextToken,\n })\n .then(({ meta, events }) => ({\n meta,\n items: events,\n }))\n )\n }\n}\n\nexport const proxyEvents = <TPlugin extends BasePlugin>(\n client: BotSpecificClient<TPlugin> | client.Client,\n props: PluginRuntimeProps<TPlugin>\n): EventProxy<TPlugin> =>\n new Proxy(\n {},\n {\n get: (_target, eventName: string) => {\n const actualName =\n props.alias !== undefined ? `${props.alias}${consts.PLUGIN_PREFIX_SEPARATOR}${eventName}` : eventName\n return new _EventSender({\n client,\n eventName: actualName,\n })\n },\n }\n ) as EventProxy<TPlugin>\n", "import { Client } from '@holocronlab/botruntime-client'\nimport { BotSpecificClient, StateType } from '../../bot'\nimport * as consts from '../../consts'\nimport { BasePlugin, PluginRuntimeProps } from '../common'\nimport { StateProxy, StateRepo } from './types'\n\nclass _StateRepo<TPayload extends object> implements StateRepo<TPayload> {\n public constructor(\n private _client: BotSpecificClient<any> | Client,\n private _stateType: StateType,\n private _stateName: string\n ) {}\n\n public async get(id: string): Promise<TPayload> {\n return await this._client\n .getState({\n type: this._stateType,\n name: this._stateName,\n id,\n })\n .then((r) => r.state.payload)\n }\n\n public async set(id: string, payload: TPayload, options?: { expiryMs: number }): Promise<void> {\n await this._client.setState({\n type: this._stateType,\n name: this._stateName,\n id,\n payload,\n expiry: options?.expiryMs,\n })\n return\n }\n\n public async getOrSet(id: string, payload: TPayload, options?: { expiryMs: number }): Promise<TPayload> {\n return await this._client\n .getOrSetState({\n type: this._stateType,\n name: this._stateName,\n id,\n payload,\n expiry: options?.expiryMs,\n })\n .then((r) => r.state.payload)\n }\n\n public async delete(id: string): Promise<void> {\n await this._client.setState({\n type: this._stateType,\n name: this._stateName,\n id,\n payload: null,\n })\n return\n }\n\n public async patch(id: string, payload: Partial<TPayload>): Promise<void> {\n await this._client.patchState({\n type: this._stateType,\n name: this._stateName,\n id,\n payload,\n })\n return\n }\n}\n\nexport const proxyStates = <TPlugin extends BasePlugin>(\n client: BotSpecificClient<TPlugin> | Client,\n props: PluginRuntimeProps<TPlugin>\n): StateProxy<TPlugin> =>\n new Proxy<Partial<StateProxy<TPlugin>>>(\n {},\n {\n get: (_target, stateType: StateType) => {\n return new Proxy(\n {},\n {\n get: (_target, stateName: string) => {\n const actualName =\n props.alias !== undefined ? `${props.alias}${consts.PLUGIN_PREFIX_SEPARATOR}${stateName}` : stateName\n return new _StateRepo(client, stateType, actualName)\n },\n }\n )\n },\n }\n ) as StateProxy<TPlugin>\n", "import * as client from '@holocronlab/botruntime-client'\nimport type {\n MessageHandlersMap as BotMessageHandlersMap,\n EventHandlersMap as BotEventHandlersMap,\n StateExpiredHandlersMap as BotStateExpiredHandlersMap,\n HookHandlersMap as BotHookHandlersMap,\n WorkflowHandlersMap as BotWorkflowHandlersMap,\n ActionHandlersMap as BotActionHandlersMap,\n BotHandlers,\n BotSpecificClient,\n WorkflowUpdateType,\n} from '../bot'\nimport { WorkflowProxy, proxyWorkflows, wrapWorkflowInstance } from '../bot/workflow-proxy'\nimport * as utils from '../utils'\nimport { ActionProxy, proxyActions } from './action-proxy'\nimport { BasePlugin, PluginRuntimeProps } from './common'\nimport { ConversationFinder, proxyConversation, proxyConversations } from './conversation-proxy'\nimport { EventProxy, proxyEvents } from './event-proxy'\nimport { proxyMessage, proxyMessages } from './message-proxy'\nimport {\n ActionHandlers,\n MessageHandlers,\n EventHandlers,\n StateExpiredHandlers,\n HookHandlers,\n WorkflowHandlers,\n HookHandlersMap,\n WorkflowHandlersMap,\n OrderedMessageHandlersMap,\n OrderedEventHandlersMap,\n OrderedStateExpiredHandlersMap,\n OrderedHookHandlersMap,\n OrderedWorkflowHandlersMap,\n HookInputsWithoutInjectedProps,\n ActionHandlerPayloadsWithoutInjectedProps,\n StateExpiredPayloadsWithoutInjectedProps,\n MessagePayloadsWithoutInjectedProps,\n EventPayloadsWithoutInjectedProps,\n WorkflowPayloadsWithoutInjectedProps,\n InjectedHandlerProps,\n} from './server/types'\nimport { proxyStates, StateProxy } from './state-proxy'\nimport { unprefixTagsOwnedByPlugin } from './tag-prefixer'\nimport { proxyUser, proxyUsers, type UserFinder } from './user-proxy'\n\nexport type PluginImplementationProps<TPlugin extends BasePlugin = BasePlugin> = {\n actions: ActionHandlers<TPlugin>\n}\n\ntype WithMessageContext<T> = T & { user: client.User; conversation: client.Conversation }\n\nconst _hookInputHasMessageContext = <T extends object>(input: T): input is WithMessageContext<T> =>\n 'user' in input && 'conversation' in input\n\ntype Tools<TPlugin extends BasePlugin = BasePlugin> = InjectedHandlerProps<TPlugin>\n\nexport class PluginImplementation<TPlugin extends BasePlugin = BasePlugin> implements BotHandlers<TPlugin> {\n private _runtimeProps: PluginRuntimeProps<TPlugin> | undefined\n\n private _actionHandlers: ActionHandlers<any>\n private _messageHandlers: OrderedMessageHandlersMap = {}\n private _eventHandlers: OrderedEventHandlersMap = {}\n private _stateExpiredHandlers: OrderedStateExpiredHandlersMap = {}\n private _hookHandlers: OrderedHookHandlersMap = {\n before_incoming_event: {},\n before_incoming_message: {},\n before_outgoing_message: {},\n before_outgoing_call_action: {},\n before_incoming_call_action: {},\n after_incoming_event: {},\n after_incoming_message: {},\n after_outgoing_message: {},\n after_outgoing_call_action: {},\n after_incoming_call_action: {},\n }\n private _workflowHandlers: OrderedWorkflowHandlersMap = {\n started: {},\n continued: {},\n timed_out: {},\n }\n\n private _registerOrder: number = 0\n\n public constructor(public readonly props: PluginImplementationProps<TPlugin>) {\n this._actionHandlers = props.actions\n }\n\n public initialize(props: PluginRuntimeProps<TPlugin>): this {\n this._runtimeProps = props\n return this\n }\n\n private get _runtime() {\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 private _getTools(client: BotSpecificClient<any>): Tools {\n const { configuration, interfaces, integrations, alias } = this._runtime\n const actions = proxyActions(client, this._runtime) as ActionProxy<BasePlugin>\n const states = proxyStates(client, this._runtime) as StateProxy<BasePlugin>\n const workflows = proxyWorkflows({ client, pluginAlias: this._runtime.alias }) as WorkflowProxy<BasePlugin>\n const events = proxyEvents(client, this._runtime) as EventProxy<BasePlugin>\n const users = proxyUsers({ client, pluginAlias: this._runtime.alias }) as UserFinder<BasePlugin>\n const conversations = proxyConversations({ client, plugin: this._runtime }) as ConversationFinder<BasePlugin>\n const messages = proxyMessages({ client, plugin: this._runtime })\n\n return {\n configuration,\n interfaces,\n integrations,\n actions,\n states,\n alias,\n workflows,\n events,\n users,\n conversations,\n messages,\n }\n }\n\n public get actionHandlers(): BotActionHandlersMap<TPlugin> {\n return new Proxy(\n {},\n {\n get: (_: unknown, actionName: string) => {\n actionName = this._stripAliasPrefix(actionName)\n const handler = this._actionHandlers[actionName]\n if (!handler) {\n return undefined\n }\n return utils.functions.setName(\n (input: utils.types.ValueOf<ActionHandlerPayloadsWithoutInjectedProps<TPlugin>>) =>\n handler({ ...input, ...this._getTools(input.client) }),\n handler.name\n )\n },\n }\n ) as BotActionHandlersMap<TPlugin>\n }\n\n public get messageHandlers(): BotMessageHandlersMap<TPlugin> {\n return new Proxy(\n {},\n {\n get: (_: unknown, messageName: string) => {\n messageName = this._stripAliasPrefix(messageName as string)\n const specificHandlers = messageName === '*' ? [] : (this._messageHandlers[messageName] ?? [])\n const globalHandlers = this._messageHandlers['*'] ?? []\n const allHandlers = utils.arrays\n .unique([...specificHandlers, ...globalHandlers])\n .sort((a, b) => a.order - b.order)\n return allHandlers.map(({ handler }) =>\n utils.functions.setName(\n (input: utils.types.ValueOf<MessagePayloadsWithoutInjectedProps<TPlugin>>) =>\n handler({\n ...input,\n user: proxyUser({\n ...input,\n conversationId: input.conversation.id,\n pluginAlias: this._runtime.alias,\n }),\n message: proxyMessage<BasePlugin>({\n ...input,\n plugin: this._runtime,\n message: input.message,\n }),\n conversation: proxyConversation({\n ...input,\n plugin: this._runtime,\n conversation: input.conversation,\n }),\n ...this._getTools(input.client),\n }),\n handler.name\n )\n )\n },\n }\n ) as BotMessageHandlersMap<TPlugin>\n }\n\n public get eventHandlers(): BotEventHandlersMap<TPlugin> {\n return new Proxy(\n {},\n {\n get: (_: unknown, eventName: string) => {\n eventName = this._stripAliasPrefix(eventName)\n\n // if prop is \"github:prOpened\", include both \"github:prOpened\" and \"creatable:itemCreated\"\n\n const specificHandlers = eventName === '*' ? [] : (this._eventHandlers[eventName] ?? [])\n\n const interfaceHandlers = Object.entries(this._eventHandlers)\n .filter(([e]) => this._eventResolvesTo(e, eventName))\n .flatMap(([, handlers]) => handlers ?? [])\n\n const globalHandlers = this._eventHandlers['*'] ?? []\n const allHandlers = utils.arrays\n .unique([...specificHandlers, ...interfaceHandlers, ...globalHandlers])\n .sort((a, b) => a.order - b.order)\n\n return allHandlers.map(({ handler }) =>\n utils.functions.setName(\n (input: utils.types.ValueOf<EventPayloadsWithoutInjectedProps<TPlugin>>) =>\n handler({ ...input, ...this._getTools(input.client) }),\n handler.name\n )\n )\n },\n }\n ) as BotEventHandlersMap<TPlugin>\n }\n\n public get stateExpiredHandlers(): BotStateExpiredHandlersMap<TPlugin> {\n return new Proxy(\n {},\n {\n get: (_: unknown, stateName: string) => {\n stateName = this._stripAliasPrefix(stateName)\n\n const specificHandlers = stateName === '*' ? [] : (this._stateExpiredHandlers[stateName] ?? [])\n const globalHandlers = this._stateExpiredHandlers['*'] ?? []\n const allHandlers = utils.arrays\n .unique([...specificHandlers, ...globalHandlers])\n .sort((a, b) => a.order - b.order)\n return allHandlers.map(({ handler }) =>\n utils.functions.setName(\n (input: utils.types.ValueOf<StateExpiredPayloadsWithoutInjectedProps<TPlugin>>) =>\n handler({ ...input, ...this._getTools(input.client) }),\n handler.name\n )\n )\n },\n }\n ) as BotStateExpiredHandlersMap<TPlugin>\n }\n\n public get hookHandlers(): BotHookHandlersMap<TPlugin> {\n return new Proxy(\n {},\n {\n get: (_, hookType: utils.types.StringKeys<HookHandlersMap<TPlugin>>) => {\n const hooks = this._hookHandlers[hookType]\n if (!hooks) {\n return undefined\n }\n return new Proxy(\n {},\n {\n get: (_: unknown, hookDataName: string) => {\n hookDataName = this._stripAliasPrefix(hookDataName)\n\n const specificHandlers = hookDataName === '*' ? [] : (hooks[hookDataName] ?? [])\n\n // for \"before_incoming_event\", \"after_incoming_event\" and other event related hooks\n const interfaceHandlers = Object.entries(hooks)\n .filter(([e]) => this._eventResolvesTo(e, hookDataName))\n .flatMap(([, handlers]) => handlers ?? [])\n\n const globalHandlers = hooks['*'] ?? []\n const handlers = utils.arrays\n .unique([...specificHandlers, ...interfaceHandlers, ...globalHandlers])\n .sort((a, b) => a.order - b.order)\n\n return handlers.map(({ handler }) =>\n utils.functions.setName(\n (input: utils.types.ValueOf<HookInputsWithoutInjectedProps<TPlugin>>['*']) => {\n const data = unprefixTagsOwnedByPlugin(input.data, { alias: this._runtime.alias })\n const tools = this._getTools(input.client)\n\n let extraProps: Record<string, any> = {}\n\n // `before_incoming_message` and `after_incoming_message` carry the raw\n // `user` and `conversation` from the incoming event payload; wrap them\n // as proxies so handlers see the same shape as `plugin.on.message(...)`.\n // Other hook types don't carry these fields, so we just forward.\n if (_hookInputHasMessageContext(input)) {\n const user = proxyUser({\n client: input.client,\n user: input.user,\n conversationId: input.conversation.id,\n pluginAlias: this._runtime.alias,\n })\n\n const conversation = proxyConversation({\n client: input.client,\n plugin: this._runtime,\n conversation: input.conversation,\n })\n\n extraProps = { user, conversation }\n }\n\n return handler({ ...input, data, ...extraProps, ...tools })\n },\n handler.name\n )\n )\n },\n }\n )\n },\n }\n ) as BotHookHandlersMap<TPlugin>\n }\n\n public get workflowHandlers(): BotWorkflowHandlersMap<TPlugin> {\n return new Proxy(\n {},\n {\n get: (_, updateType: WorkflowUpdateType) => {\n const handlersOfType = this._workflowHandlers[updateType]\n if (!handlersOfType) {\n return undefined\n }\n\n return new Proxy(\n {},\n {\n get: (_, workflowName: string) => {\n const selfHandlers = handlersOfType[workflowName]?.sort((a, b) => a.order - b.order) ?? []\n\n return selfHandlers.map(({ handler }) =>\n utils.functions.setName(\n async (input: utils.types.ValueOf<WorkflowPayloadsWithoutInjectedProps<TPlugin>>) => {\n let currentWorkflowState = input.workflow\n await handler({\n ...input,\n workflow: wrapWorkflowInstance({\n ...input,\n workflow: currentWorkflowState,\n onWorkflowUpdate(newState) {\n currentWorkflowState = newState\n },\n pluginAlias: this._runtime.alias,\n }),\n ...this._getTools(input.client),\n })\n return currentWorkflowState\n },\n handler.name\n )\n )\n },\n }\n )\n },\n }\n ) as BotWorkflowHandlersMap<TPlugin>\n }\n\n public readonly on = {\n message: <T extends utils.types.StringKeys<MessageHandlers<TPlugin>>>(\n type: T,\n handler: MessageHandlers<TPlugin>[T]\n ): void => {\n this._messageHandlers[type] = utils.arrays.safePush(this._messageHandlers[type], {\n handler: handler as unknown as MessageHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n event: <T extends utils.types.StringKeys<EventHandlers<TPlugin>>>(\n type: T,\n handler: EventHandlers<TPlugin>[T]\n ): void => {\n this._eventHandlers[type] = utils.arrays.safePush(this._eventHandlers[type], {\n handler: handler as unknown as EventHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n stateExpired: <T extends utils.types.StringKeys<StateExpiredHandlers<TPlugin>>>(\n type: T,\n handler: StateExpiredHandlers<TPlugin>[T]\n ): void => {\n this._stateExpiredHandlers[type] = utils.arrays.safePush(this._stateExpiredHandlers[type], {\n handler: handler as unknown as StateExpiredHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n beforeIncomingEvent: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['before_incoming_event'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n beforeIncomingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['before_incoming_message'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n beforeOutgoingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['before_outgoing_message'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n beforeOutgoingCallAction: <\n T extends utils.types.StringKeys<HookHandlersMap<TPlugin>['before_outgoing_call_action']>,\n >(\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 {\n handler: handler as unknown as HookHandlers<any>['before_outgoing_call_action'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n beforeIncomingCallAction: <\n T extends utils.types.StringKeys<HookHandlersMap<TPlugin>['before_incoming_call_action']>,\n >(\n type: T,\n handler: HookHandlers<TPlugin>['before_incoming_call_action'][T]\n ) => {\n this._hookHandlers.before_incoming_call_action[type] = utils.arrays.safePush(\n this._hookHandlers.before_incoming_call_action[type],\n {\n handler: handler as unknown as HookHandlers<any>['before_incoming_call_action'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n afterIncomingEvent: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['after_incoming_event'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n afterIncomingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['after_incoming_message'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n afterOutgoingMessage: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['after_outgoing_message'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n afterOutgoingCallAction: <T extends utils.types.StringKeys<HookHandlersMap<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 {\n handler: handler as unknown as HookHandlers<any>['after_outgoing_call_action'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n afterIncomingCallAction: <T extends utils.types.StringKeys<HookHandlersMap<TPlugin>['after_incoming_call_action']>>(\n type: T,\n handler: HookHandlers<TPlugin>['after_incoming_call_action'][T]\n ) => {\n this._hookHandlers.after_incoming_call_action[type] = utils.arrays.safePush(\n this._hookHandlers.after_incoming_call_action[type],\n {\n handler: handler as unknown as HookHandlers<any>['after_incoming_call_action'][string],\n order: this._registerOrder++,\n }\n )\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflowStart: <T extends utils.types.StringKeys<WorkflowHandlersMap<TPlugin>['started']>>(\n type: T,\n handler: WorkflowHandlers<TPlugin>[T]\n ): void => {\n this._workflowHandlers.started[type] = utils.arrays.safePush(this._workflowHandlers.started[type], {\n handler: handler as unknown as WorkflowHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflowContinue: <T extends utils.types.StringKeys<WorkflowHandlersMap<TPlugin>['continued']>>(\n type: T,\n handler: WorkflowHandlers<TPlugin>[T]\n ): void => {\n this._workflowHandlers.continued[type] = utils.arrays.safePush(this._workflowHandlers.continued[type], {\n handler: handler as unknown as WorkflowHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n\n /**\n * # EXPERIMENTAL\n * This API is experimental and may change in the future.\n */\n workflowTimeout: <T extends utils.types.StringKeys<WorkflowHandlersMap<TPlugin>['timed_out']>>(\n type: T,\n handler: WorkflowHandlers<TPlugin>[T]\n ): void => {\n this._workflowHandlers.timed_out[type] = utils.arrays.safePush(this._workflowHandlers.timed_out[type], {\n handler: handler as unknown as WorkflowHandlers<any>[string],\n order: this._registerOrder++,\n })\n },\n }\n\n /**\n * checks if the actual event resolves to the target event\n */\n private _eventResolvesTo = (actualEventRef: string, targetEventRef: string) => {\n const NAMESPACE_SEPARATOR = ':'\n const [pluginIfaceOrIntAlias, ifaceOrIntEvent] = actualEventRef.split(NAMESPACE_SEPARATOR)\n if (!pluginIfaceOrIntAlias || !ifaceOrIntEvent) {\n return false\n }\n\n // match '<plugin-iface-alias>:<iface-event>' => '<bot-int-alias>:<int-event>':\n const iface = this._runtime.interfaces[pluginIfaceOrIntAlias]\n\n if (\n iface &&\n targetEventRef === `${iface.integrationAlias}${NAMESPACE_SEPARATOR}${iface?.events?.[ifaceOrIntEvent]?.name}`\n ) {\n return true\n }\n\n const integration = this._runtime.integrations[pluginIfaceOrIntAlias]\n\n // match '<plugin-int-alias>:<int-event>' => '<bot-int-alias>:<int-event>':\n if (integration && targetEventRef === `${integration.integrationAlias}${NAMESPACE_SEPARATOR}${ifaceOrIntEvent}`) {\n return true\n }\n\n return false\n }\n\n private _stripAliasPrefix = (prop: string) => {\n const { alias } = this._runtime\n if (!alias) {\n return prop\n }\n const prefix = `${alias}#`\n return prop.startsWith(prefix) ? prop.slice(prefix.length) : prop\n }\n}\n", "import * as semver from 'semver'\nimport { Package } from './package'\nimport { PluginDefinition } from './plugin/definition'\n\ntype GenericPackage = Exclude<Package, PluginDefinition>\n\n/**\n * Returns the major version range for a given package.\n * Version utility helpers are only intended to be used with plugins.\n **/\nexport function allWithinMajorOf<T extends GenericPackage>(pkg: T): T & { version: string } {\n const major = semver.major(pkg.version)\n return { ...pkg, version: `>=${major}.0.0 <${major + 1}.0.0` }\n}\n\n/**\n * Returns the minor version range for a given package.\n * Version utility helpers are only intended to be used with plugins.\n **/\nexport function allWithinMinorOf<T extends GenericPackage>(pkg: T): T & { version: string } {\n const major = semver.major(pkg.version)\n const minor = semver.minor(pkg.version)\n return {\n ...pkg,\n version: `>=${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,EAAAD,GAAA,sBAAAE,GAAA,qBAAAC,KAAA,IAAAC,EAAwB,sBAUjB,SAASF,GAA2CG,EAAiC,CAC1F,IAAMC,EAAe,QAAMD,EAAI,OAAO,EACtC,MAAO,CAAE,GAAGA,EAAK,QAAS,KAAKC,CAAK,SAASA,EAAQ,CAAC,MAAO,CAC/D,CAMO,SAASH,GAA2CE,EAAiC,CAC1F,IAAMC,EAAe,QAAMD,EAAI,OAAO,EAChCE,EAAe,QAAMF,EAAI,OAAO,EACtC,MAAO,CACL,GAAGA,EACH,QAAS,KAAKC,CAAK,IAAIC,CAAK,OAAOD,CAAK,IAAIC,EAAQ,CAAC,IACvD,CACF",
|
|
6
|
+
"names": ["index_exports", "__export", "BotImplementation", "BotDefinition", "BotLogger", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationLogger", "IntegrationSpecificClient", "InterfaceDefinition", "OAUTH_IDENTIFIER_HEADER", "PluginImplementation", "PluginDefinition", "WELL_KNOWN_ATTRIBUTES", "errors_exports", "handlerErrorToHttpResponse", "message_exports", "parseBody", "serve", "version_utils_exports", "__toCommonJS", "message_exports", "__export", "defaults", "markdown", "markdownBloc", "import_botruntime_zui", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocItemSchema", "blocSchema", "markdown", "markdownBloc", "defaults", "WELL_KNOWN_ATTRIBUTES", "OAUTH_IDENTIFIER_HEADER", "import_botruntime_client", "import_browser_or_node", "log", "parseBody", "req", "thrown", "handlerErrorToHttpResponse", "unexpectedErrorMessage", "error", "runtimeError", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "log", "incoming", "body", "readBody", "headers", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "e", "import_botruntime_client", "errors_exports", "__export", "DefinitionError", "isDefinitionError", "error", "record_utils_exports", "__export", "mapKeys", "mapValues", "mergeRecords", "pairs", "stripUndefinedProps", "values", "obj", "fn", "key", "value", "a", "b", "merge", "allKeys", "uniqueKeys", "result", "aValue", "bValue", "array_utils_exports", "__export", "safePush", "unique", "arr", "values", "function_utils_exports", "__export", "setName", "f", "name", "resolveInterface", "intrface", "name", "version", "resolved", "statement", "record_utils_exports", "entity", "entitySchemas", "actionName", "action", "resolvedInputSchema", "resolvedOutputSchema", "newActionName", "eventName", "event", "resolvedEventSchema", "newEventName", "channelName", "channel", "messages", "messageName", "message", "resolvedMessageSchema", "newChannelName", "version", "SDK_VERSION", "version", "schemaName", "createStore", "props", "record_utils_exports", "e", "k", "isBranded", "schema", "getName", "IntegrationDefinition", "_IntegrationDefinition", "props", "SDK_VERSION", "overrides", "interfacePkg", "builder", "entities", "actions", "events", "channels", "self", "entityNames", "e", "key", "resolved", "statement", "resolveInterface", "record_utils_exports", "extensionBuilderInput", "createStore", "extensionBuilderOutput", "unbrandedEntity", "_k", "isBranded", "DefinitionError", "getName", "a", "b", "messages", "conversation", "message", "aDef", "bDef", "aShape", "bShape", "import_botruntime_client", "client", "retryConfig", "err", "retryCount", "axiosError", "_getRetryAfterSeconds", "headers", "headerNames", "headerName", "headerValue", "_parseHeaderToSeconds", "secondsDiff", "_isDateString", "_parseDateToSeconds", "futureDate", "_parseDateString", "currentDate", "date", "IntegrationSpecificClient", "_client", "x", "r", "ActionMetadataStore", "cost", "import_botruntime_zui", "PLUGIN_PREFIX_SEPARATOR", "BOT_ID_HEADER", "BOT_USER_ID_HEADER", "INTEGRATION_ID_HEADER", "INTEGRATION_ALIAS_HEADER", "WEBHOOK_ID_HEADER", "CONFIGURATION_TYPE_HEADER", "CONFIGURATION_PAYLOAD_HEADER", "OPERATION_TYPE_HEADER", "OPERATION_SUBTYPE_HEADER", "throwError", "thrown", "integrationOperationSchema", "extractContext", "headers", "BOT_ID_HEADER", "throwError", "BOT_USER_ID_HEADER", "INTEGRATION_ID_HEADER", "INTEGRATION_ALIAS_HEADER", "WEBHOOK_ID_HEADER", "OPERATION_TYPE_HEADER", "CONFIGURATION_TYPE_HEADER", "CONFIGURATION_PAYLOAD_HEADER", "import_util", "BaseLogger", "defaultOptions", "args", "level", "msg", "util", "IntegrationLogger", "_IntegrationLogger", "BaseLogger", "options", "userId", "conversationId", "visibleToBotOwners", "hiddenToIntegrationOwners", "level", "msg", "botId", "integrationId", "integrationAlias", "extractTracingHeaders", "headers", "acc", "header", "getServerProps", "ctx", "req", "instance", "traceId", "vanillaClient", "retryConfig", "client", "IntegrationSpecificClient", "logger", "IntegrationLogger", "handleOperation", "props", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "integrationHandler", "extractContext", "response", "onUnknownOperationHandler", "thrown", "status", "body", "error", "handlerErrorToHttpResponse", "_", "incomingRequest", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "metadata", "ActionMetadataStore", "handler", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "stripRecurringFromEvents", "events", "key", "_", "rest", "resolveRecurringEvents", "explicitRecurringEvents", "merged", "eventName", "event", "x", "BotDefinition", "_BotDefinition", "props", "events", "stripRecurringFromEvents", "recurringEvents", "resolveRecurringEvents", "SDK_VERSION", "overrides", "integrationPkg", "config", "self", "integrationAlias", "DefinitionError", "configurationType", "rawConfiguration", "configSchema", "parseResult", "configuration", "pluginPkg", "pluginAlias", "interfaces", "_", "dep", "pluginIfaceAlias", "pluginIfaceConfig", "integrationInstance", "availableIntegrations", "integrationInterfaceExtension", "availableInterfaces", "integrations", "pluginIntegAlias", "pluginIntegConfig", "rawPluginConfiguration", "pluginConfigSchema", "pluginParseResult", "pluginConfiguration", "user1", "user2", "conversation1", "conversation2", "message1", "message2", "states1", "states2", "events1", "events2", "recurringEvents1", "recurringEvents2", "actions1", "actions2", "tables1", "tables2", "workflows1", "workflows2", "obj", "record_utils_exports", "key", "PLUGIN_PREFIX_SEPARATOR", "zuiReferenceMap", "pluginInstance", "installedPlugins", "pluginInterfaceExtensions", "interfaceAlias", "pluginInterfaceExtension", "backingIntegration", "entityExtensions", "entityAlias", "interfaceEntityName", "entitySchema", "schema", "definitions", "definition", "import_botruntime_client", "BotLogger", "_BotLogger", "BaseLogger", "options", "userId", "conversationId", "workflowId", "eventId", "messageId", "BotSpecificClient", "_client", "_hooks", "x", "operation", "req", "before", "res", "after", "import_botruntime_zui", "botOperationSchema", "extractContext", "headers", "BOT_ID_HEADER", "throwError", "OPERATION_TYPE_HEADER", "OPERATION_SUBTYPE_HEADER", "CONFIGURATION_PAYLOAD_HEADER", "SUCCESS_RESPONSE", "bridgeUpdateTypeToSnakeCase", "updateType", "WORKFLOW_UPDATE_TYPES", "handleWorkflowUpdateEvent", "rawProps", "event", "props", "_attachWorkflowContextToLogger", "SUCCESS_RESPONSE", "_handleWorkflowUpdate", "updateType", "bridgeUpdateTypeToSnakeCase", "handlers", "updatedWorkflow", "_dispatchToHandlers", "currentWorkflowState", "handler", "botHandler", "bot", "req", "ctx", "extractContext", "logger", "BotLogger", "vanillaClient", "retryConfig", "botClient", "BotSpecificClient", "beforeOutgoingMessageHooks", "handler", "client", "beforeOutgoingCallActionHooks", "res", "afterOutgoingMessageHooks", "type", "afterOutgoingCallActionHooks", "props", "onActionTriggered", "onEventReceived", "onRegister", "onUnregister", "onPing", "thrown", "status", "body", "error", "handlerErrorToHttpResponse", "_", "SUCCESS_RESPONSE", "serverProps", "self", "common", "parseBody", "handleWorkflowUpdateEvent", "event", "message", "user", "conversation", "beforeIncomingMessageHooks", "hookOutput", "messagePayload", "messageHandlers", "afterIncomingMessageHooks", "state", "statePayload", "stateHandlers", "beforeIncomingEventHooks", "eventPayload", "eventHandlers", "afterIncomingEventHooks", "input", "beforeIncomingCallActionHooks", "action", "output", "afterIncomingCallActionHooks", "unprefixTagsOwnedByPlugin", "obj", "alias", "prefix", "PLUGIN_PREFIX_SEPARATOR", "unprefixedTags", "key", "value", "prefixTagsIfNeeded", "prefixedTags", "AsyncCollection", "_list", "amount", "arr", "i", "result", "elements", "items", "meta", "createAsyncCollection", "listFn", "proxyWorkflows", "props", "_", "workflowName", "input", "createAsyncCollection", "nextToken", "meta", "workflows", "workflow", "wrapWorkflowInstance", "prefixTagsIfNeeded", "isAcknowledged", "unprefixTagsOwnedByPlugin", "x", "failureReason", "output", "BotImplementation", "props", "_", "actionName", "action", "function_utils_exports", "proxyWorkflows", "pluginAlias", "plugin", "actionPrefix", "nameWithoutPrefix", "PLUGIN_PREFIX_SEPARATOR", "messageName", "pluginHandlers", "selfSpecificHandlers", "selfGlobalHandlers", "selfHandlers", "a", "b", "handler", "array_utils_exports", "eventName", "stateName", "hookType", "hookDataName", "selfHooks", "updateType", "handlersOfType", "workflowName", "currentWorkflowState", "wrapWorkflowInstance", "newState", "type", "botHandler", "port", "serve", "InterfaceDefinition", "_InterfaceDefinition", "props", "entityReferences", "events", "record_utils_exports", "event", "actions", "action", "channels", "channel", "message", "SDK_VERSION", "overrides", "entities", "entityName", "entityDef", "title", "description", "refSchema", "PluginDefinition", "_PluginDefinition", "props", "entities", "interfaceAlias", "interfaceDef", "entityName", "aliases", "alias", "DefinitionError", "stateName", "stateDef", "resolvedEvents", "eventName", "eventDef", "stripRecurringFromEvents", "resolveRecurringEvents", "actionName", "actionDef", "tableName", "tableDef", "SDK_VERSION", "overrides", "intersectWithUnknownRecord", "zuiReferenceMap", "interfacePackage", "entityDefinition", "schema", "definitions", "key", "definition", "proxyActions", "client", "props", "_target", "integrationOrInterfaceAlias", "actionName", "input", "integrationAlias", "actualActionName", "res", "proxyMessages", "props", "id", "response", "proxyMessage", "listProps", "createAsyncCollection", "nextToken", "prefixTagsIfNeeded", "meta", "messages", "message", "unprefixTagsOwnedByPlugin", "data", "updatedMessage", "proxyUsers", "props", "listProps", "createAsyncCollection", "nextToken", "prefixTagsIfNeeded", "meta", "users", "user", "proxyUser", "id", "response", "baseActionableUser", "unprefixTagsOwnedByPlugin", "data", "updatedUser", "conversationId", "participant", "proxyConversations", "props", "_target", "interfaceOrIntegrationAlias", "_target2", "channel", "listProps", "integrationName", "actualChannelName", "createAsyncCollection", "nextToken", "prefixTagsIfNeeded", "meta", "conversations", "conversation", "proxyConversation", "id", "response", "vanillaClient", "unprefixTagsOwnedByPlugin", "data", "updatedConversation", "proxyMessage", "message", "messages", "participants", "user", "proxyUser", "_EventSender", "__EventSender", "_props", "eventPayload", "conversationId", "userId", "messageId", "event", "schedule", "props", "createAsyncCollection", "nextToken", "meta", "events", "proxyEvents", "client", "_target", "eventName", "actualName", "PLUGIN_PREFIX_SEPARATOR", "_StateRepo", "_client", "_stateType", "_stateName", "id", "r", "payload", "options", "proxyStates", "client", "props", "_target", "stateType", "stateName", "actualName", "PLUGIN_PREFIX_SEPARATOR", "_hookInputHasMessageContext", "input", "PluginImplementation", "props", "client", "configuration", "interfaces", "integrations", "alias", "actions", "proxyActions", "states", "proxyStates", "workflows", "proxyWorkflows", "events", "proxyEvents", "users", "proxyUsers", "conversations", "proxyConversations", "messages", "proxyMessages", "_", "actionName", "handler", "function_utils_exports", "messageName", "specificHandlers", "globalHandlers", "array_utils_exports", "a", "b", "proxyUser", "proxyMessage", "proxyConversation", "eventName", "interfaceHandlers", "e", "handlers", "stateName", "hookType", "hooks", "hookDataName", "data", "unprefixTagsOwnedByPlugin", "tools", "extraProps", "user", "conversation", "updateType", "handlersOfType", "workflowName", "currentWorkflowState", "wrapWorkflowInstance", "newState", "type", "actualEventRef", "targetEventRef", "pluginIfaceOrIntAlias", "ifaceOrIntEvent", "iface", "integration", "prop", "prefix", "version_utils_exports", "__export", "allWithinMajorOf", "allWithinMinorOf", "semver", "pkg", "major", "minor"]
|
|
7
|
+
}
|