@botpress/sdk 1.2.1 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +3 -3
- package/dist/bot/client/index.d.ts +42 -41
- package/dist/bot/client/types.d.ts +126 -60
- package/dist/bot/implementation.d.ts +1 -1
- package/dist/bot/index.d.ts +1 -1
- package/dist/bot/server/context.d.ts +2 -0
- package/dist/bot/server/index.d.ts +5 -0
- package/dist/bot/server/types.d.ts +59 -0
- package/dist/bot/types/common.d.ts +56 -0
- package/dist/bot/types/common.test.d.ts +1 -0
- package/dist/bot/{generic.d.ts → types/generic.d.ts} +6 -4
- package/dist/bot/types/index.d.ts +2 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/integration/client/index.d.ts +42 -41
- package/dist/integration/client/types.d.ts +127 -21
- package/dist/integration/implementation.d.ts +2 -2
- package/dist/integration/index.d.ts +1 -2
- package/dist/integration/server/context.d.ts +3 -0
- package/dist/integration/server/index.d.ts +6 -0
- package/dist/integration/server/types.d.ts +102 -0
- package/dist/integration/types/common.d.ts +11 -0
- package/dist/integration/{generic.d.ts → types/generic.d.ts} +7 -1
- package/dist/integration/types/index.d.ts +2 -0
- package/dist/message.d.ts +1 -1
- package/dist/utils/type-utils.d.ts +9 -2
- package/package.json +1 -1
- package/dist/bot/client/routes.d.ts +0 -81
- package/dist/bot/context.d.ts +0 -12
- package/dist/bot/server.d.ts +0 -40
- package/dist/integration/client/routes.d.ts +0 -128
- package/dist/integration/context.d.ts +0 -23
- package/dist/integration/server.d.ts +0 -88
- /package/dist/integration/{action-metadata.d.ts → server/action-metadata.d.ts} +0 -0
- /package/dist/integration/{logger.d.ts → server/logger.d.ts} +0 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
|
|
2
|
-
> @botpress/sdk@1.2.
|
|
2
|
+
> @botpress/sdk@1.2.2 build /home/runner/work/botpress/botpress/packages/sdk
|
|
3
3
|
> pnpm build:type && pnpm build:node
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @botpress/sdk@1.2.
|
|
6
|
+
> @botpress/sdk@1.2.2 build:type /home/runner/work/botpress/botpress/packages/sdk
|
|
7
7
|
> tsc --emitDeclarationOnly --declaration
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
> @botpress/sdk@1.2.
|
|
10
|
+
> @botpress/sdk@1.2.2 build:node /home/runner/work/botpress/botpress/packages/sdk
|
|
11
11
|
> ts-node -T build.ts
|
|
12
12
|
|
|
@@ -1,58 +1,59 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import * as
|
|
1
|
+
import * as client from '@botpress/client';
|
|
2
|
+
import * as common from '../types';
|
|
3
|
+
import * as types from './types';
|
|
4
|
+
export * from './types';
|
|
4
5
|
/**
|
|
5
6
|
* Just like the regular botpress client, but typed with the bot's properties.
|
|
6
7
|
*/
|
|
7
|
-
export declare class BotSpecificClient<TBot extends BaseBot> {
|
|
8
|
+
export declare class BotSpecificClient<TBot extends common.BaseBot> implements types.ClientOperations<TBot> {
|
|
8
9
|
private readonly _client;
|
|
9
|
-
constructor(_client: Client);
|
|
10
|
-
getConversation:
|
|
11
|
-
listConversations:
|
|
12
|
-
updateConversation:
|
|
13
|
-
deleteConversation:
|
|
14
|
-
listParticipants:
|
|
15
|
-
addParticipant:
|
|
16
|
-
getParticipant:
|
|
17
|
-
removeParticipant:
|
|
18
|
-
getEvent:
|
|
19
|
-
listEvents:
|
|
20
|
-
createMessage:
|
|
21
|
-
getOrCreateMessage:
|
|
22
|
-
getMessage:
|
|
23
|
-
updateMessage:
|
|
24
|
-
listMessages:
|
|
25
|
-
deleteMessage:
|
|
26
|
-
getUser:
|
|
27
|
-
listUsers:
|
|
28
|
-
updateUser:
|
|
29
|
-
deleteUser:
|
|
30
|
-
getState:
|
|
31
|
-
setState:
|
|
32
|
-
getOrSetState:
|
|
33
|
-
patchState:
|
|
34
|
-
callAction:
|
|
35
|
-
uploadFile:
|
|
36
|
-
upsertFile:
|
|
37
|
-
deleteFile:
|
|
38
|
-
listFiles:
|
|
39
|
-
getFile:
|
|
40
|
-
updateFileMetadata:
|
|
41
|
-
searchFiles:
|
|
10
|
+
constructor(_client: client.Client);
|
|
11
|
+
getConversation: types.GetConversation<TBot>;
|
|
12
|
+
listConversations: types.ListConversations<TBot>;
|
|
13
|
+
updateConversation: types.UpdateConversation<TBot>;
|
|
14
|
+
deleteConversation: types.DeleteConversation<TBot>;
|
|
15
|
+
listParticipants: types.ListParticipants<TBot>;
|
|
16
|
+
addParticipant: types.AddParticipant<TBot>;
|
|
17
|
+
getParticipant: types.GetParticipant<TBot>;
|
|
18
|
+
removeParticipant: types.RemoveParticipant<TBot>;
|
|
19
|
+
getEvent: types.GetEvent<TBot>;
|
|
20
|
+
listEvents: types.ListEvents<TBot>;
|
|
21
|
+
createMessage: types.CreateMessage<TBot>;
|
|
22
|
+
getOrCreateMessage: types.GetOrCreateMessage<TBot>;
|
|
23
|
+
getMessage: types.GetMessage<TBot>;
|
|
24
|
+
updateMessage: types.UpdateMessage<TBot>;
|
|
25
|
+
listMessages: types.ListMessages<TBot>;
|
|
26
|
+
deleteMessage: types.DeleteMessage<TBot>;
|
|
27
|
+
getUser: types.GetUser<TBot>;
|
|
28
|
+
listUsers: types.ListUsers<TBot>;
|
|
29
|
+
updateUser: types.UpdateUser<TBot>;
|
|
30
|
+
deleteUser: types.DeleteUser<TBot>;
|
|
31
|
+
getState: types.GetState<TBot>;
|
|
32
|
+
setState: types.SetState<TBot>;
|
|
33
|
+
getOrSetState: types.GetOrSetState<TBot>;
|
|
34
|
+
patchState: types.PatchState<TBot>;
|
|
35
|
+
callAction: types.CallAction<TBot>;
|
|
36
|
+
uploadFile: types.UploadFile<TBot>;
|
|
37
|
+
upsertFile: types.UpsertFile<TBot>;
|
|
38
|
+
deleteFile: types.DeleteFile<TBot>;
|
|
39
|
+
listFiles: types.ListFiles<TBot>;
|
|
40
|
+
getFile: types.GetFile<TBot>;
|
|
41
|
+
updateFileMetadata: types.UpdateFileMetadata<TBot>;
|
|
42
|
+
searchFiles: types.SearchFiles<TBot>;
|
|
42
43
|
/**
|
|
43
44
|
* @deprecated Use `callAction` to delegate the conversation creation to an integration.
|
|
44
45
|
*/
|
|
45
|
-
createConversation:
|
|
46
|
+
createConversation: types.CreateConversation<TBot>;
|
|
46
47
|
/**
|
|
47
48
|
* @deprecated Use `callAction` to delegate the conversation creation to an integration.
|
|
48
49
|
*/
|
|
49
|
-
getOrCreateConversation:
|
|
50
|
+
getOrCreateConversation: types.GetOrCreateConversation<TBot>;
|
|
50
51
|
/**
|
|
51
52
|
* @deprecated Use `callAction` to delegate the user creation to an integration.
|
|
52
53
|
*/
|
|
53
|
-
createUser:
|
|
54
|
+
createUser: types.CreateUser<TBot>;
|
|
54
55
|
/**
|
|
55
56
|
* @deprecated Use `callAction` to delegate the user creation to an integration.
|
|
56
57
|
*/
|
|
57
|
-
getOrCreateUser:
|
|
58
|
+
getOrCreateUser: types.GetOrCreateUser<TBot>;
|
|
58
59
|
}
|
|
@@ -1,70 +1,136 @@
|
|
|
1
1
|
import * as client from '@botpress/client';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export type EventDefinition = BaseBot['events'][string];
|
|
8
|
-
export type StateDefinition = BaseBot['states'][string];
|
|
9
|
-
export type IntegrationInstanceDefinition = BaseBot['integrations'][string];
|
|
10
|
-
export type IntegrationInstanceConfigurationDefinition = IntegrationInstanceDefinition['configuration'];
|
|
11
|
-
export type IntegrationInstanceActionDefinition = IntegrationInstanceDefinition['actions'][string];
|
|
12
|
-
export type IntegrationInstanceChannelDefinition = IntegrationInstanceDefinition['channels'][string];
|
|
13
|
-
export type IntegrationInstanceMessageDefinition = IntegrationInstanceChannelDefinition['messages'][string];
|
|
14
|
-
export type IntegrationInstanceEventDefinition = IntegrationInstanceDefinition['events'][string];
|
|
15
|
-
export type IntegrationInstanceStateDefinition = IntegrationInstanceDefinition['states'][string];
|
|
16
|
-
export type IntegrationInstanceUserDefinition = IntegrationInstanceDefinition['user'];
|
|
17
|
-
/**
|
|
18
|
-
* 1. Enumerations
|
|
19
|
-
*/
|
|
20
|
-
type ActionKey<TIntegrationName extends string, TActionName extends string> = string extends TIntegrationName ? string : string extends TActionName ? string : Join<[TIntegrationName, ':', TActionName]>;
|
|
21
|
-
export type EnumerateActions<TBot extends BaseBot> = ToSealedRecord<UnionToIntersection<{
|
|
22
|
-
[TIntegrationName in keyof TBot['integrations']]: {
|
|
23
|
-
[TActionName in keyof TBot['integrations'][TIntegrationName]['actions'] as ActionKey<Cast<TIntegrationName, string>, Cast<TActionName, string>>]: TBot['integrations'][TIntegrationName]['actions'][TActionName];
|
|
24
|
-
};
|
|
25
|
-
}[keyof TBot['integrations']]> & {}>;
|
|
26
|
-
type EventKey<TIntegrationName extends string, TEventName extends string> = string extends TIntegrationName ? string : string extends TEventName ? string : Join<[TIntegrationName, ':', TEventName]>;
|
|
27
|
-
export type EnumerateEvents<TBot extends BaseBot> = ToSealedRecord<UnionToIntersection<{
|
|
28
|
-
[TIntegrationName in keyof TBot['integrations']]: {
|
|
29
|
-
[TEventName in keyof TBot['integrations'][TIntegrationName]['events'] as EventKey<Cast<TIntegrationName, string>, Cast<TEventName, string>>]: TBot['integrations'][TIntegrationName]['events'][TEventName];
|
|
30
|
-
};
|
|
31
|
-
}[keyof TBot['integrations']]> & {
|
|
32
|
-
[TEventName in keyof TBot['events']]: TBot['events'][TEventName];
|
|
33
|
-
}>;
|
|
34
|
-
type ChannelKey<TIntegrationName extends string, TChannelName extends string> = string extends TIntegrationName ? string : string extends TChannelName ? string : Join<[TIntegrationName, ':', TChannelName]>;
|
|
35
|
-
export type EnumerateChannels<TBot extends BaseBot> = ToSealedRecord<UnionToIntersection<{
|
|
36
|
-
[TIntegrationName in keyof TBot['integrations']]: {
|
|
37
|
-
[TChannelName in keyof TBot['integrations'][TIntegrationName]['channels'] as ChannelKey<Cast<TIntegrationName, string>, Cast<TChannelName, string>>]: TBot['integrations'][TIntegrationName]['channels'][TChannelName];
|
|
38
|
-
};
|
|
39
|
-
}[keyof TBot['integrations']]> & {}>;
|
|
40
|
-
type MessageKey<TIntegrationName extends string, TChannelName extends string, TMessageName extends string> = string extends TIntegrationName ? string : string extends TChannelName ? string : string extends TMessageName ? string : Join<[TIntegrationName, ':', TChannelName, ':', TMessageName]>;
|
|
41
|
-
export type EnumerateMessages<TBot extends BaseBot> = ToSealedRecord<UnionToIntersection<{
|
|
42
|
-
[TIntegrationName in keyof TBot['integrations']]: {
|
|
43
|
-
[TChannelName in keyof TBot['integrations'][TIntegrationName]['channels']]: {
|
|
44
|
-
[TMessageName in keyof TBot['integrations'][TIntegrationName]['channels'][TChannelName]['messages'] as MessageKey<Cast<TIntegrationName, string>, Cast<TChannelName, string>, Cast<TMessageName, string>>]: TBot['integrations'][TIntegrationName]['channels'][TChannelName]['messages'][TMessageName];
|
|
45
|
-
};
|
|
46
|
-
}[keyof TBot['integrations'][TIntegrationName]['channels']];
|
|
47
|
-
}[keyof TBot['integrations']]> & {}>;
|
|
48
|
-
export type GetMessages<TBot extends BaseBot> = {
|
|
49
|
-
[K in keyof EnumerateMessages<TBot> as Cast<Split<K, ':'>[2], string>]: EnumerateMessages<TBot>[K];
|
|
50
|
-
};
|
|
51
|
-
/**
|
|
52
|
-
* 2. Responses
|
|
53
|
-
*/
|
|
54
|
-
export type EventResponse<TBot extends BaseBot> = {
|
|
2
|
+
import * as utils from '../../utils/type-utils';
|
|
3
|
+
import * as common from '../types';
|
|
4
|
+
type Arg<F extends (...args: any[]) => any> = Parameters<F>[number];
|
|
5
|
+
type Res<F extends (...args: any[]) => any> = ReturnType<F>;
|
|
6
|
+
type EventResponse<TBot extends common.BaseBot> = {
|
|
55
7
|
event: {
|
|
56
|
-
[K in keyof EnumerateEvents<TBot>]: Merge<client.Event, {
|
|
8
|
+
[K in keyof common.EnumerateEvents<TBot>]: utils.Merge<client.Event, {
|
|
57
9
|
type: K;
|
|
58
|
-
payload: EnumerateEvents<TBot>[K];
|
|
10
|
+
payload: common.EnumerateEvents<TBot>[K];
|
|
59
11
|
}>;
|
|
60
|
-
}[keyof EnumerateEvents<TBot>];
|
|
12
|
+
}[keyof common.EnumerateEvents<TBot>];
|
|
61
13
|
};
|
|
62
|
-
|
|
63
|
-
message: ValueOf<{
|
|
64
|
-
[K in keyof GetMessages<TBot> as K extends TMessage ? K : never]: Merge<client.Message, {
|
|
14
|
+
type MessageResponse<TBot extends common.BaseBot, TMessage extends keyof common.GetMessages<TBot> = keyof common.GetMessages<TBot>> = {
|
|
15
|
+
message: utils.ValueOf<{
|
|
16
|
+
[K in keyof common.GetMessages<TBot> as K extends TMessage ? K : never]: utils.Merge<client.Message, {
|
|
65
17
|
type: K;
|
|
66
|
-
payload: GetMessages<TBot>[K];
|
|
18
|
+
payload: common.GetMessages<TBot>[K];
|
|
67
19
|
}>;
|
|
68
20
|
}>;
|
|
69
21
|
};
|
|
22
|
+
export type CreateConversation<_TBot extends common.BaseBot> = client.Client['createConversation'];
|
|
23
|
+
export type GetConversation<_TBot extends common.BaseBot> = client.Client['getConversation'];
|
|
24
|
+
export type ListConversations<_TBot extends common.BaseBot> = client.Client['listConversations'];
|
|
25
|
+
export type GetOrCreateConversation<_TBot extends common.BaseBot> = client.Client['getOrCreateConversation'];
|
|
26
|
+
export type UpdateConversation<_TBot extends common.BaseBot> = client.Client['updateConversation'];
|
|
27
|
+
export type DeleteConversation<_TBot extends common.BaseBot> = client.Client['deleteConversation'];
|
|
28
|
+
export type ListParticipants<_TBot extends common.BaseBot> = client.Client['listParticipants'];
|
|
29
|
+
export type AddParticipant<_TBot extends common.BaseBot> = client.Client['addParticipant'];
|
|
30
|
+
export type GetParticipant<_TBot extends common.BaseBot> = client.Client['getParticipant'];
|
|
31
|
+
export type RemoveParticipant<_TBot extends common.BaseBot> = client.Client['removeParticipant'];
|
|
32
|
+
export type GetEvent<TBot extends common.BaseBot> = (x: Arg<client.Client['getEvent']>) => Promise<EventResponse<TBot>>;
|
|
33
|
+
export type ListEvents<_TBot extends common.BaseBot> = client.Client['listEvents'];
|
|
34
|
+
export type CreateMessage<TBot extends common.BaseBot> = <TMessage extends keyof common.GetMessages<TBot>>(x: utils.Merge<Arg<client.Client['createMessage']>, {
|
|
35
|
+
type: utils.Cast<TMessage, string>;
|
|
36
|
+
payload: utils.Cast<common.GetMessages<TBot>[TMessage], Record<string, any>>;
|
|
37
|
+
}>) => Promise<MessageResponse<TBot, TMessage>>;
|
|
38
|
+
export type GetOrCreateMessage<TBot extends common.BaseBot> = <TMessage extends keyof common.GetMessages<TBot>>(x: utils.Merge<Arg<client.Client['getOrCreateMessage']>, {
|
|
39
|
+
type: utils.Cast<TMessage, string>;
|
|
40
|
+
payload: utils.Cast<common.GetMessages<TBot>[TMessage], Record<string, any>>;
|
|
41
|
+
}>) => Promise<MessageResponse<TBot, TMessage>>;
|
|
42
|
+
export type GetMessage<TBot extends common.BaseBot> = (x: Arg<client.Client['getMessage']>) => Promise<MessageResponse<TBot>>;
|
|
43
|
+
export type UpdateMessage<TBot extends common.BaseBot> = (x: Arg<client.Client['updateMessage']>) => Promise<MessageResponse<TBot>>;
|
|
44
|
+
export type ListMessages<_TBot extends common.BaseBot> = client.Client['listMessages'];
|
|
45
|
+
export type DeleteMessage<_TBot extends common.BaseBot> = client.Client['deleteMessage'];
|
|
46
|
+
export type CreateUser<_TBot extends common.BaseBot> = client.Client['createUser'];
|
|
47
|
+
export type GetUser<_TBot extends common.BaseBot> = client.Client['getUser'];
|
|
48
|
+
export type ListUsers<_TBot extends common.BaseBot> = client.Client['listUsers'];
|
|
49
|
+
export type GetOrCreateUser<_TBot extends common.BaseBot> = client.Client['getOrCreateUser'];
|
|
50
|
+
export type UpdateUser<_TBot extends common.BaseBot> = client.Client['updateUser'];
|
|
51
|
+
export type DeleteUser<_TBot extends common.BaseBot> = client.Client['deleteUser'];
|
|
52
|
+
export type GetState<TBot extends common.BaseBot> = <TState extends keyof TBot['states']>(x: utils.Merge<Arg<client.Client['getState']>, {
|
|
53
|
+
name: utils.Cast<TState, string>;
|
|
54
|
+
}>) => Promise<{
|
|
55
|
+
state: utils.Merge<Awaited<Res<client.Client['getState']>>['state'], {
|
|
56
|
+
payload: TBot['states'][TState];
|
|
57
|
+
}>;
|
|
58
|
+
}>;
|
|
59
|
+
export type SetState<TBot extends common.BaseBot> = <TState extends keyof TBot['states']>(x: utils.Merge<Arg<client.Client['setState']>, {
|
|
60
|
+
name: utils.Cast<TState, string>;
|
|
61
|
+
payload: TBot['states'][TState] | null;
|
|
62
|
+
}>) => Promise<{
|
|
63
|
+
state: utils.Merge<Awaited<Res<client.Client['setState']>>['state'], {
|
|
64
|
+
payload: TBot['states'][TState];
|
|
65
|
+
}>;
|
|
66
|
+
}>;
|
|
67
|
+
export type GetOrSetState<TBot extends common.BaseBot> = <TState extends keyof TBot['states']>(x: utils.Merge<Arg<client.Client['getOrSetState']>, {
|
|
68
|
+
name: utils.Cast<TState, string>;
|
|
69
|
+
payload: TBot['states'][TState];
|
|
70
|
+
}>) => Promise<{
|
|
71
|
+
state: utils.Merge<Awaited<Res<client.Client['getOrSetState']>>['state'], {
|
|
72
|
+
payload: TBot['states'][TState];
|
|
73
|
+
}>;
|
|
74
|
+
}>;
|
|
75
|
+
export type PatchState<TBot extends common.BaseBot> = <TState extends keyof TBot['states']>(x: utils.Merge<Arg<client.Client['patchState']>, {
|
|
76
|
+
name: utils.Cast<TState, string>;
|
|
77
|
+
payload: Partial<TBot['states'][TState]>;
|
|
78
|
+
}>) => Promise<{
|
|
79
|
+
state: utils.Merge<Awaited<Res<client.Client['patchState']>>['state'], {
|
|
80
|
+
payload: TBot['states'][TState];
|
|
81
|
+
}>;
|
|
82
|
+
}>;
|
|
83
|
+
export type CallAction<TBot extends common.BaseBot> = <ActionType extends keyof common.EnumerateActions<TBot>>(x: utils.Merge<Arg<client.Client['callAction']>, {
|
|
84
|
+
type: utils.Cast<ActionType, string>;
|
|
85
|
+
input: utils.Cast<common.EnumerateActions<TBot>[ActionType], common.IntegrationInstanceActionDefinition>['input'];
|
|
86
|
+
}>) => Promise<{
|
|
87
|
+
output: utils.Cast<common.EnumerateActions<TBot>[ActionType], common.IntegrationInstanceActionDefinition>['output'];
|
|
88
|
+
}>;
|
|
89
|
+
export type UploadFile<_TBot extends common.BaseBot> = client.Client['uploadFile'];
|
|
90
|
+
export type UpsertFile<_TBot extends common.BaseBot> = client.Client['upsertFile'];
|
|
91
|
+
export type DeleteFile<_TBot extends common.BaseBot> = client.Client['deleteFile'];
|
|
92
|
+
export type ListFiles<_TBot extends common.BaseBot> = client.Client['listFiles'];
|
|
93
|
+
export type GetFile<_TBot extends common.BaseBot> = client.Client['getFile'];
|
|
94
|
+
export type UpdateFileMetadata<_TBot extends common.BaseBot> = client.Client['updateFileMetadata'];
|
|
95
|
+
export type SearchFiles<_TBot extends common.BaseBot> = client.Client['searchFiles'];
|
|
96
|
+
export type ClientOperations<TBot extends common.BaseBot> = {
|
|
97
|
+
getConversation: GetConversation<TBot>;
|
|
98
|
+
listConversations: ListConversations<TBot>;
|
|
99
|
+
updateConversation: UpdateConversation<TBot>;
|
|
100
|
+
deleteConversation: DeleteConversation<TBot>;
|
|
101
|
+
listParticipants: ListParticipants<TBot>;
|
|
102
|
+
addParticipant: AddParticipant<TBot>;
|
|
103
|
+
getParticipant: GetParticipant<TBot>;
|
|
104
|
+
removeParticipant: RemoveParticipant<TBot>;
|
|
105
|
+
getEvent: GetEvent<TBot>;
|
|
106
|
+
listEvents: ListEvents<TBot>;
|
|
107
|
+
createMessage: CreateMessage<TBot>;
|
|
108
|
+
getOrCreateMessage: GetOrCreateMessage<TBot>;
|
|
109
|
+
getMessage: GetMessage<TBot>;
|
|
110
|
+
updateMessage: UpdateMessage<TBot>;
|
|
111
|
+
listMessages: ListMessages<TBot>;
|
|
112
|
+
deleteMessage: DeleteMessage<TBot>;
|
|
113
|
+
getUser: GetUser<TBot>;
|
|
114
|
+
listUsers: ListUsers<TBot>;
|
|
115
|
+
updateUser: UpdateUser<TBot>;
|
|
116
|
+
deleteUser: DeleteUser<TBot>;
|
|
117
|
+
getState: GetState<TBot>;
|
|
118
|
+
setState: SetState<TBot>;
|
|
119
|
+
getOrSetState: GetOrSetState<TBot>;
|
|
120
|
+
patchState: PatchState<TBot>;
|
|
121
|
+
callAction: CallAction<TBot>;
|
|
122
|
+
uploadFile: UploadFile<TBot>;
|
|
123
|
+
upsertFile: UpsertFile<TBot>;
|
|
124
|
+
deleteFile: DeleteFile<TBot>;
|
|
125
|
+
listFiles: ListFiles<TBot>;
|
|
126
|
+
getFile: GetFile<TBot>;
|
|
127
|
+
updateFileMetadata: UpdateFileMetadata<TBot>;
|
|
128
|
+
searchFiles: SearchFiles<TBot>;
|
|
129
|
+
};
|
|
130
|
+
export type ClientInputs<TBot extends common.BaseBot> = {
|
|
131
|
+
[K in keyof ClientOperations<TBot>]: Arg<ClientOperations<TBot>[K]>;
|
|
132
|
+
};
|
|
133
|
+
export type ClientOutputs<TBot extends common.BaseBot> = {
|
|
134
|
+
[K in keyof ClientOperations<TBot>]: Awaited<Res<ClientOperations<TBot>[K]>>;
|
|
135
|
+
};
|
|
70
136
|
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Server } from 'node:http';
|
|
2
|
-
import { BaseBot } from './generic';
|
|
3
2
|
import { MessageHandler, EventHandler, StateExpiredHandler } from './server';
|
|
3
|
+
import { BaseBot } from './types';
|
|
4
4
|
export type BotImplementationProps<_TBot extends BaseBot = BaseBot> = {};
|
|
5
5
|
export declare class BotImplementation<TBot extends BaseBot = BaseBot> {
|
|
6
6
|
readonly props: BotImplementationProps<TBot>;
|
package/dist/bot/index.d.ts
CHANGED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { Request, Response } from '../../serve';
|
|
2
|
+
import * as common from '../types';
|
|
3
|
+
import * as types from './types';
|
|
4
|
+
export * from './types';
|
|
5
|
+
export declare const botHandler: <TBot extends common.BaseBot>(instance: types.BotHandlers<TBot>) => (req: Request) => Promise<Response | void>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import * as client from '@botpress/client';
|
|
2
|
+
import * as utils from '../../utils/type-utils';
|
|
3
|
+
import { BotSpecificClient } from '../client';
|
|
4
|
+
import * as types from '../types';
|
|
5
|
+
export type BotOperation = 'event_received' | 'register' | 'unregister' | 'ping' | 'action_triggered';
|
|
6
|
+
export type BotContext = {
|
|
7
|
+
botId: string;
|
|
8
|
+
type: string;
|
|
9
|
+
operation: BotOperation;
|
|
10
|
+
configuration: {
|
|
11
|
+
payload: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
export type EventRequest<TBot extends types.BaseBot> = {
|
|
15
|
+
event: {
|
|
16
|
+
[K in keyof types.EnumerateEvents<TBot>]: utils.Merge<client.Event, {
|
|
17
|
+
type: K;
|
|
18
|
+
payload: types.EnumerateEvents<TBot>[K];
|
|
19
|
+
}>;
|
|
20
|
+
}[keyof types.EnumerateEvents<TBot>];
|
|
21
|
+
};
|
|
22
|
+
export type MessageRequest<TBot extends types.BaseBot, TMessage extends keyof types.GetMessages<TBot> = keyof types.GetMessages<TBot>> = {
|
|
23
|
+
message: utils.ValueOf<{
|
|
24
|
+
[K in keyof types.GetMessages<TBot> as K extends TMessage ? K : never]: utils.Merge<client.Message, {
|
|
25
|
+
type: K;
|
|
26
|
+
payload: types.GetMessages<TBot>[K];
|
|
27
|
+
}>;
|
|
28
|
+
}>;
|
|
29
|
+
};
|
|
30
|
+
export type CommonHandlerProps<TBot extends types.BaseBot> = {
|
|
31
|
+
ctx: BotContext;
|
|
32
|
+
client: BotSpecificClient<TBot>;
|
|
33
|
+
};
|
|
34
|
+
export type MessagePayload<TBot extends types.BaseBot> = MessageRequest<TBot> & {
|
|
35
|
+
user: client.User;
|
|
36
|
+
conversation: client.Conversation;
|
|
37
|
+
event: client.Event;
|
|
38
|
+
states: {
|
|
39
|
+
[TState in keyof TBot['states']]: {
|
|
40
|
+
type: 'user' | 'conversation' | 'bot';
|
|
41
|
+
payload: TBot['states'][TState];
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
export type MessageHandlerProps<TBot extends types.BaseBot> = CommonHandlerProps<TBot> & MessagePayload<TBot>;
|
|
46
|
+
export type MessageHandler<TBot extends types.BaseBot> = (args: MessageHandlerProps<TBot>) => Promise<void>;
|
|
47
|
+
export type EventPayload<TBot extends types.BaseBot> = EventRequest<TBot>;
|
|
48
|
+
export type EventHandlerProps<TBot extends types.BaseBot> = CommonHandlerProps<TBot> & EventPayload<TBot>;
|
|
49
|
+
export type EventHandler<TBot extends types.BaseBot> = (args: EventHandlerProps<TBot>) => Promise<void>;
|
|
50
|
+
export type StateExpiredPayload<_TBot extends types.BaseBot> = {
|
|
51
|
+
state: client.State;
|
|
52
|
+
};
|
|
53
|
+
export type StateExpiredHandlerProps<TBot extends types.BaseBot> = CommonHandlerProps<TBot> & StateExpiredPayload<TBot>;
|
|
54
|
+
export type StateExpiredHandler<TBot extends types.BaseBot> = (args: StateExpiredHandlerProps<TBot>) => Promise<void>;
|
|
55
|
+
export type BotHandlers<TBot extends types.BaseBot> = {
|
|
56
|
+
messageHandlers: MessageHandler<TBot>[];
|
|
57
|
+
eventHandlers: EventHandler<TBot>[];
|
|
58
|
+
stateExpiredHandlers: StateExpiredHandler<TBot>[];
|
|
59
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Join, UnionToIntersection, Split, Cast } from '../../utils/type-utils';
|
|
2
|
+
import { BaseBot } from './generic';
|
|
3
|
+
/**
|
|
4
|
+
* 0. Definitions
|
|
5
|
+
*/
|
|
6
|
+
export type EventDefinition = BaseBot['events'][string];
|
|
7
|
+
export type StateDefinition = BaseBot['states'][string];
|
|
8
|
+
export type IntegrationInstanceDefinition = BaseBot['integrations'][string];
|
|
9
|
+
export type IntegrationInstanceConfigurationDefinition = IntegrationInstanceDefinition['configuration'];
|
|
10
|
+
export type IntegrationInstanceActionDefinition = IntegrationInstanceDefinition['actions'][string];
|
|
11
|
+
export type IntegrationInstanceChannelDefinition = IntegrationInstanceDefinition['channels'][string];
|
|
12
|
+
export type IntegrationInstanceMessageDefinition = IntegrationInstanceChannelDefinition['messages'][string];
|
|
13
|
+
export type IntegrationInstanceEventDefinition = IntegrationInstanceDefinition['events'][string];
|
|
14
|
+
export type IntegrationInstanceStateDefinition = IntegrationInstanceDefinition['states'][string];
|
|
15
|
+
export type IntegrationInstanceUserDefinition = IntegrationInstanceDefinition['user'];
|
|
16
|
+
/**
|
|
17
|
+
* 1. Enumerations
|
|
18
|
+
*/
|
|
19
|
+
type ActionKey<TIntegrationName extends string, TActionName extends string> = string extends TIntegrationName ? string : string extends TActionName ? string : Join<[TIntegrationName, ':', TActionName]>;
|
|
20
|
+
export type EnumerateActions<TBot extends BaseBot> = UnionToIntersection<{
|
|
21
|
+
[TIntegrationName in keyof TBot['integrations']]: {
|
|
22
|
+
[TActionName in keyof TBot['integrations'][TIntegrationName]['actions'] as ActionKey<Cast<TIntegrationName, string>, Cast<TActionName, string>>]: TBot['integrations'][TIntegrationName]['actions'][TActionName];
|
|
23
|
+
};
|
|
24
|
+
}[keyof TBot['integrations']]> & {};
|
|
25
|
+
export type EnumerateActionInputs<TBot extends BaseBot> = {
|
|
26
|
+
[K in keyof EnumerateActions<TBot>]: Cast<EnumerateActions<TBot>[K], IntegrationInstanceActionDefinition>['input'];
|
|
27
|
+
};
|
|
28
|
+
export type EnumerateActionOutputs<TBot extends BaseBot> = {
|
|
29
|
+
[K in keyof EnumerateActions<TBot>]: Cast<EnumerateActions<TBot>[K], IntegrationInstanceActionDefinition>['output'];
|
|
30
|
+
};
|
|
31
|
+
type EventKey<TIntegrationName extends string, TEventName extends string> = string extends TIntegrationName ? string : string extends TEventName ? string : Join<[TIntegrationName, ':', TEventName]>;
|
|
32
|
+
export type EnumerateEvents<TBot extends BaseBot> = UnionToIntersection<{
|
|
33
|
+
[TIntegrationName in keyof TBot['integrations']]: {
|
|
34
|
+
[TEventName in keyof TBot['integrations'][TIntegrationName]['events'] as EventKey<Cast<TIntegrationName, string>, Cast<TEventName, string>>]: TBot['integrations'][TIntegrationName]['events'][TEventName];
|
|
35
|
+
};
|
|
36
|
+
}[keyof TBot['integrations']]> & {
|
|
37
|
+
[TEventName in keyof TBot['events']]: TBot['events'][TEventName];
|
|
38
|
+
};
|
|
39
|
+
type ChannelKey<TIntegrationName extends string, TChannelName extends string> = string extends TIntegrationName ? string : string extends TChannelName ? string : Join<[TIntegrationName, ':', TChannelName]>;
|
|
40
|
+
export type EnumerateChannels<TBot extends BaseBot> = UnionToIntersection<{
|
|
41
|
+
[TIntegrationName in keyof TBot['integrations']]: {
|
|
42
|
+
[TChannelName in keyof TBot['integrations'][TIntegrationName]['channels'] as ChannelKey<Cast<TIntegrationName, string>, Cast<TChannelName, string>>]: TBot['integrations'][TIntegrationName]['channels'][TChannelName];
|
|
43
|
+
};
|
|
44
|
+
}[keyof TBot['integrations']]> & {};
|
|
45
|
+
type MessageKey<TIntegrationName extends string, TChannelName extends string, TMessageName extends string> = string extends TIntegrationName ? string : string extends TChannelName ? string : string extends TMessageName ? string : Join<[TIntegrationName, ':', TChannelName, ':', TMessageName]>;
|
|
46
|
+
export type EnumerateMessages<TBot extends BaseBot> = UnionToIntersection<{
|
|
47
|
+
[TIntegrationName in keyof TBot['integrations']]: {
|
|
48
|
+
[TChannelName in keyof TBot['integrations'][TIntegrationName]['channels']]: {
|
|
49
|
+
[TMessageName in keyof TBot['integrations'][TIntegrationName]['channels'][TChannelName]['messages'] as MessageKey<Cast<TIntegrationName, string>, Cast<TChannelName, string>, Cast<TMessageName, string>>]: TBot['integrations'][TIntegrationName]['channels'][TChannelName]['messages'][TMessageName];
|
|
50
|
+
};
|
|
51
|
+
}[keyof TBot['integrations'][TIntegrationName]['channels']];
|
|
52
|
+
}[keyof TBot['integrations']]> & {};
|
|
53
|
+
export type GetMessages<TBot extends BaseBot> = {
|
|
54
|
+
[K in keyof EnumerateMessages<TBot> as Cast<Split<K, ':'>[2], string>]: EnumerateMessages<TBot>[K];
|
|
55
|
+
};
|
|
56
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { BaseIntegration } from '
|
|
2
|
-
import * as utils from '
|
|
3
|
-
export type BaseIntegrations = Record<string, BaseIntegration>;
|
|
1
|
+
import { BaseIntegration } from '../../integration/types';
|
|
2
|
+
import * as utils from '../../utils/type-utils';
|
|
4
3
|
export type BaseBot = {
|
|
5
|
-
integrations:
|
|
4
|
+
integrations: Record<string, BaseIntegration>;
|
|
6
5
|
events: Record<string, any>;
|
|
7
6
|
states: Record<string, any>;
|
|
8
7
|
};
|
|
8
|
+
/**
|
|
9
|
+
* Usefull for tests, allows to create a bot with only the properties you want to override
|
|
10
|
+
*/
|
|
9
11
|
export type MakeBot<B extends Partial<BaseBot>> = {
|
|
10
12
|
integrations: utils.Default<B['integrations'], BaseBot['integrations']>;
|
|
11
13
|
events: utils.Default<B['events'], BaseBot['events']>;
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,12 @@ export * from './const';
|
|
|
3
3
|
export * from './serve';
|
|
4
4
|
export * from './zui';
|
|
5
5
|
export { isApiError, RuntimeError, } from '@botpress/client';
|
|
6
|
-
export { IntegrationDefinition, IntegrationDefinitionProps, IntegrationImplementation as Integration, IntegrationImplementationProps as IntegrationProps,
|
|
6
|
+
export { IntegrationDefinition, IntegrationDefinitionProps, IntegrationImplementation as Integration, IntegrationImplementationProps as IntegrationProps, IntegrationLogger, IntegrationSpecificClient, TagDefinition, ConfigurationDefinition, AdditionalConfigurationDefinition, EventDefinition, ChannelDefinition, MessageDefinition, ActionDefinition, StateDefinition, UserDefinition, SecretDefinition, EntityDefinition, } from './integration';
|
|
7
|
+
export {
|
|
8
|
+
/**
|
|
9
|
+
* @deprecated use Context exported from '.botpress' instead
|
|
10
|
+
*/
|
|
11
|
+
IntegrationContext, } from './integration/server';
|
|
7
12
|
export { BotDefinition, BotDefinitionProps, BotImplementation as Bot, BotImplementationProps as BotProps, BotSpecificClient, TagDefinition as BotTagDefinition, StateType as BotStateType, StateDefinition as BotStateDefinition, RecurringEventDefinition as BotRecurringEventDefinition, EventDefinition as BotEventDefinition, ConfigurationDefinition as BotConfigurationDefinition, UserDefinition as BotUserDefinition, ConversationDefinition as BotConversationDefinition, MessageDefinition as BotMessageDefinition, } from './bot';
|
|
8
13
|
export { InterfaceDeclaration, InterfaceDeclarationProps, } from './interface';
|
|
9
14
|
export { IntegrationPackage, InterfacePackage, } from './package';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Be=Object.create;var S=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},E=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of be(e))!xe.call(t,r)&&r!==n&&S(t,r,{get:()=>e[r],enumerable:!(o=ve(e,r))||o.enumerable});return t},p=(t,e,n)=>(E(t,e,"default"),n&&E(n,e,"default")),W=(t,e,n)=>(n=t!=null?Be(Ce(t)):{},E(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),Ee=t=>E(S({},"__esModule",{value:!0}),t);var m={};P(m,{Bot:()=>O,BotDefinition:()=>R,BotSpecificClient:()=>B,Integration:()=>_,IntegrationDefinition:()=>A,IntegrationSpecificClient:()=>I,InterfaceDeclaration:()=>H,RuntimeError:()=>F.RuntimeError,botIdHeader:()=>v,botUserIdHeader:()=>j,configurationHeader:()=>b,configurationTypeHeader:()=>Z,integrationIdHeader:()=>N,isApiError:()=>F.isApiError,messages:()=>G,operationHeader:()=>C,parseBody:()=>T,serve:()=>x,typeHeader:()=>z,webhookIdHeader:()=>L});module.exports=Ee(m);var G={};P(G,{defaults:()=>Ae});var i={};P(i,{default:()=>K});var J=require("@bpinternal/zui");p(i,require("@bpinternal/zui"));var K=J.z;var l=i.z.string().min(1),X=i.z.object({text:l}),Y=i.z.object({markdown:l}),ee=i.z.object({imageUrl:l}),te=i.z.object({audioUrl:l}),ne=i.z.object({videoUrl:l}),ie=i.z.object({fileUrl:l,title:l.optional()}),oe=i.z.object({latitude:i.z.number(),longitude:i.z.number(),address:i.z.string().optional(),title:i.z.string().optional()}),se=i.z.object({title:l,subtitle:l.optional(),imageUrl:l.optional(),actions:i.z.array(i.z.object({action:i.z.enum(["postback","url","say"]),label:l,value:l}))}),Q=i.z.object({text:l,options:i.z.array(i.z.object({label:l,value:l}))}),Se=i.z.object({items:i.z.array(se)}),Pe=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("text"),payload:X}),i.z.object({type:i.z.literal("markdown"),payload:Y}),i.z.object({type:i.z.literal("image"),payload:ee}),i.z.object({type:i.z.literal("audio"),payload:te}),i.z.object({type:i.z.literal("video"),payload:ne}),i.z.object({type:i.z.literal("file"),payload:ie}),i.z.object({type:i.z.literal("location"),payload:oe})]),Me=i.z.object({items:i.z.array(Pe)}),Ae={text:{schema:X},markdown:{schema:Y},image:{schema:ee},audio:{schema:te},video:{schema:ne},file:{schema:ie},location:{schema:oe},carousel:{schema:Se},card:{schema:se},dropdown:{schema:Q},choice:{schema:Q},bloc:{schema:Me}};var v="x-bot-id",j="x-bot-user-id",N="x-integration-id",L="x-webhook-id",Z="x-bp-configuration-type",b="x-bp-configuration",C="x-bp-operation",z="x-bp-type";var re=require("node:http");var y=console;function T(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function x(t,e=8072,n=De){let o=(0,re.createServer)(async(r,a)=>{try{let s=await we(r);if(s.path==="/health"){a.writeHead(200).end("ok");return}let c=await t(s);a.writeHead(c?.status??200,c?.headers??{}).end(c?.body??"{}")}catch(s){y.error("Error while handling request",{error:s?.message??"Internal error occured"}),a.writeHead(500).end(JSON.stringify({error:s?.message??"Internal error occured"}))}});return o.listen(e,()=>n(e)),o}async function we(t){let e=await Ue(t),n={};for(let r=0;r<t.rawHeaders.length;r+=2){let a=t.rawHeaders[r].toLowerCase(),s=t.rawHeaders[r+1];n[a]=s}let o=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:o.pathname,query:ke(o.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function ke(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function Ue(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let o="";t.on("data",r=>o+=r.toString()),t.on("error",r=>n(r)),t.on("end",()=>e(o))})}function De(t){y.info(`Listening on port ${t}`)}p(m,i,module.exports);var F=require("@botpress/client");var ae=require("@bpinternal/zui");var _e=ae.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),ce=t=>{let e=t[v],n=t[j],o=t[N],r=t[L],a=t[Z],s=t[b],c=_e.parse(t[C]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!o)throw new Error("Missing integration headers");if(!r)throw new Error("Missing webhook headers");if(!s)throw new Error("Missing configuration headers");if(!c)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:o,webhookId:r,operation:c,configurationType:a??null,configuration:s?JSON.parse(Buffer.from(s,"base64").toString("utf-8")):{}}};var u={};P(u,{mapValues:()=>Re,pairs:()=>ge});var ge=t=>Object.entries(t),Re=(t,e)=>Object.fromEntries(ge(t).map(([n,o])=>[n,e(o,n)]));var M=Symbol("schemaName"),le=t=>t?u.mapValues(t,(n,o)=>({...n,[M]:o})):{},pe=t=>M in t&&t[M]!==void 0,de=t=>t[M];var A=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.configurations=e.configurations,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities,this.interfaces=e.interfaces}name;version;title;description;icon;readme;configuration;configurations;events;actions;channels;states;user;secrets;identifier;entities;interfaces;extend(e,n){let o=n(le(this.entities)),r=u.pairs(o).find(([g,h])=>!pe(h));if(r)throw new Error(`Cannot extend interface "${e.definition.name}" with entity "${r[0]}"; the provided schema is not part of the integration's entities.`);let a=this;a.interfaces??={};let s=u.mapValues(o,g=>({name:de(g),schema:g.schema})),c=Object.values(s).map(g=>g.name),d=c.length===0?e.definition.name:`${e.definition.name}<${c.join(",")}>`;return a.interfaces[d]={...e,entities:s},this}};var f=require("@botpress/client");var ue=require("@botpress/client"),w={retries:3,retryCondition:t=>ue.axiosRetry.isNetworkOrIdempotentRequestError(t)||[429,502].includes(t.response?.status??0),retryDelay:t=>t*1e3};var k=class{_cost=0;get cost(){return this._cost}setCost(e){this._cost=e}toJSON(){return{cost:this.cost}}};var I=class{constructor(e){this._client=e}createConversation=e=>this._client.createConversation(e);getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);createEvent=e=>this._client.createEvent(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);createUser=e=>this._client.createUser(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);getOrCreateUser=e=>this._client.getOrCreateUser(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e);setState=e=>this._client.setState(e);getOrSetState=e=>this._client.getOrSetState(e);patchState=e=>this._client.patchState(e);configureIntegration=e=>this._client.configureIntegration(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e)};var $=W(require("util")),U=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:$.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return $.default.format(`[For Bot Owner] ${e}`,...n)}},D={forBot:()=>({info:(...t)=>{console.info(U(t))},warn:(...t)=>{console.warn(U(t))},error:(...t)=>{console.error(U(t))},debug:(...t)=>{console.debug(U(t))}})};var Te=t=>async e=>{let n=ce(e.headers),o=new f.Client({botId:n.botId,integrationId:n.integrationId,retry:w}),r=new I(o),a={ctx:n,req:e,client:r,logger:D,instance:t};try{let s;switch(n.operation){case"webhook_received":s=await He(a);break;case"register":s=await Fe(a);break;case"unregister":s=await Ke(a);break;case"message_created":s=await Ne(a);break;case"action_triggered":s=await Le(a);break;case"ping":s=await Oe(a);break;case"create_user":s=await Ge(a);break;case"create_conversation":s=await je(a);break;default:throw new Error(`Unknown operation ${n.operation}`)}return s?{...s,status:s.status??200}:{status:200}}catch(s){if((0,f.isApiError)(s)){let d=new f.RuntimeError(s.message,s);return D.forBot().error(d.message),{status:d.code,body:JSON.stringify(d.toJSON())}}console.error(s);let c=new f.RuntimeError("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.");return D.forBot().error(c.message),{status:c.code,body:JSON.stringify(c.toJSON())}}},Oe=async t=>{},He=async({client:t,ctx:e,req:n,logger:o,instance:r})=>{let{req:a}=T(n);return r.webhook({client:t,ctx:e,req:a,logger:o})},Fe=async({client:t,ctx:e,req:n,logger:o,instance:r})=>{if(!r.register)return;let{webhookUrl:a}=T(n);await r.register({client:t,ctx:e,webhookUrl:a,logger:o})},Ke=async({client:t,ctx:e,req:n,logger:o,instance:r})=>{if(!r.unregister)return;let{webhookUrl:a}=T(n);await r.unregister({ctx:e,webhookUrl:a,client:t,logger:o})},Ge=async({client:t,ctx:e,req:n,logger:o,instance:r})=>{if(!r.createUser)return;let{tags:a}=T(n);return await r.createUser({ctx:e,client:t,tags:a,logger:o})},je=async({client:t,ctx:e,req:n,logger:o,instance:r})=>{if(!r.createConversation)return;let{channel:a,tags:s}=T(n);return await r.createConversation({ctx:e,client:t,channel:a,tags:s,logger:o})},Ne=async({ctx:t,req:e,client:n,logger:o,instance:r})=>{let{conversation:a,user:s,type:c,payload:d,message:g}=T(e),h=r.channels[a.channel];if(!h)throw new Error(`Channel ${a.channel} not found`);let V=h.messages[c];if(!V)throw new Error(`Message of type ${c} not found in channel ${a.channel}`);await V({ctx:t,conversation:a,message:g,user:s,type:c,client:n,payload:d,ack:async({tags:Ie})=>{await n.updateMessage({id:g.id,tags:Ie})},logger:o})},Le=async({req:t,ctx:e,client:n,logger:o,instance:r})=>{let{input:a,type:s}=T(t);if(!s)throw new Error("Missing action type");let c=r.actions[s];if(!c)throw new Error(`Action ${s} not found`);let d=new k,h={output:await c({ctx:e,input:a,client:n,type:s,logger:o,metadata:d}),meta:d.toJSON()};return{body:JSON.stringify(h)}};var _=class{constructor(e){this.props=e;this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}actions;channels;register;unregister;createUser;createConversation;webhook;handler=Te(this);start=e=>x(this.handler,e)};var R=class{constructor(e){this.props=e;this.integrations=e.integrations,this.user=e.user,this.conversation=e.conversation,this.message=e.message,this.states=e.states,this.configuration=e.configuration,this.events=e.events,this.recurringEvents=e.recurringEvents}integrations;user;conversation;message;states;configuration;events;recurringEvents;add(e,n){let o=this;return o.integrations||(o.integrations={}),o.integrations[e.definition.name]={enabled:n.enabled,...e,configurationType:n.configurationType,configuration:n.configuration},this}};var he=W(require("@botpress/client"));var B=class{constructor(e){this._client=e}getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this._client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this._client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this._client.patchState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));callAction=e=>this._client.callAction(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e);searchFiles=e=>this._client.searchFiles(e);createConversation=e=>this._client.createConversation(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);createUser=e=>this._client.createUser(e);getOrCreateUser=e=>this._client.getOrCreateUser(e)};var me=require("@bpinternal/zui");var Ze=me.z.enum(["event_received","register","unregister","ping","action_triggered"]),fe=t=>{let e=t[v],n=t[b],o=t[z],r=Ze.parse(t[C]);if(!e)throw new Error("Missing bot headers");if(!o)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!r)throw new Error("Missing operation headers");return{botId:e,operation:r,type:o,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var ye=t=>async e=>{let n=fe(e.headers);n.operation!=="ping"&&y.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let o=new he.Client({botId:n.botId,retry:w}),r=new B(o),a={req:e,ctx:n,client:r,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await Ve(a);break;case"register":await qe(a);break;case"unregister":await $e(a);break;case"ping":await ze(a);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},ze=async t=>{},qe=async t=>{},$e=async t=>{},Ve=async({ctx:t,req:e,client:n,instance:o})=>{y.debug(`Received event ${t.type}`);let r=T(e),a=r.event;switch(t.type){case"message_created":let s={user:a.payload.user,conversation:a.payload.conversation,message:a.payload.message,states:a.payload.states,event:a};await Promise.all(o.messageHandlers.map(g=>g({client:n,ctx:t,...s})));break;case"state_expired":let c={state:a.payload.state};await Promise.all(o.stateExpiredHandlers.map(g=>g({client:n,ctx:t,...c})));break;default:let d={event:r.event};await Promise.all(o.eventHandlers.map(g=>g({client:n,ctx:t,...d})))}};var O=class{constructor(e){this.props=e}_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=ye(this._state);start=e=>x(this.handler,e)};var H=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.entities=e.entities??{},this.templateName=e.templateName;let n=this._getEntityReference(this.entities),o=e.events===void 0?{}:u.mapValues(e.events,s=>({...s,schema:s.schema(n)})),r=e.actions===void 0?{}:u.mapValues(e.actions,s=>({...s,input:{...s.input,schema:s.input.schema(n)},output:{...s.output,schema:s.output.schema(n)}})),a=e.channels===void 0?{}:u.mapValues(e.channels,s=>({...s,messages:u.mapValues(s.messages,c=>({...c,schema:c.schema(n)}))}));this.events=o,this.actions=r,this.channels=a}name;version;entities;events;actions;channels;templateName;_getEntityReference=e=>{let n={};for(let o of Object.keys(e))n[o]=K.ref(o);return n}};0&&(module.exports={Bot,BotDefinition,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,InterfaceDeclaration,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,configurationTypeHeader,integrationIdHeader,isApiError,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
|
|
1
|
+
"use strict";var Be=Object.create;var S=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var P=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},x=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ie(e))!Ee.call(t,a)&&a!==n&&S(t,a,{get:()=>e[a],enumerable:!(s=ve(e,a))||s.enumerable});return t},l=(t,e,n)=>(x(t,e,"default"),n&&x(n,e,"default")),J=(t,e,n)=>(n=t!=null?Be(Ce(t)):{},x(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),xe=t=>x(S({},"__esModule",{value:!0}),t);var m={};P(m,{Bot:()=>O,BotDefinition:()=>A,BotSpecificClient:()=>B,Integration:()=>k,IntegrationDefinition:()=>D,IntegrationSpecificClient:()=>b,InterfaceDeclaration:()=>H,RuntimeError:()=>K.RuntimeError,botIdHeader:()=>v,botUserIdHeader:()=>j,configurationHeader:()=>I,configurationTypeHeader:()=>Z,integrationIdHeader:()=>N,isApiError:()=>K.isApiError,messages:()=>G,operationHeader:()=>C,parseBody:()=>f,serve:()=>E,typeHeader:()=>z,webhookIdHeader:()=>L});module.exports=xe(m);var G={};P(G,{defaults:()=>De});var i={};P(i,{default:()=>F});var W=require("@bpinternal/zui");l(i,require("@bpinternal/zui"));var F=W.z;var g=i.z.string().min(1),X=i.z.object({text:g}),Y=i.z.object({markdown:g}),ee=i.z.object({imageUrl:g}),te=i.z.object({audioUrl:g}),ne=i.z.object({videoUrl:g}),ie=i.z.object({fileUrl:g,title:g.optional()}),se=i.z.object({latitude:i.z.number(),longitude:i.z.number(),address:i.z.string().optional(),title:i.z.string().optional()}),oe=i.z.object({title:g,subtitle:g.optional(),imageUrl:g.optional(),actions:i.z.array(i.z.object({action:i.z.enum(["postback","url","say"]),label:g,value:g}))}),Q=i.z.object({text:g,options:i.z.array(i.z.object({label:g,value:g}))}),Se=i.z.object({items:i.z.array(oe)}),Pe=i.z.union([i.z.object({type:i.z.literal("text"),payload:X}),i.z.object({type:i.z.literal("markdown"),payload:Y}),i.z.object({type:i.z.literal("image"),payload:ee}),i.z.object({type:i.z.literal("audio"),payload:te}),i.z.object({type:i.z.literal("video"),payload:ne}),i.z.object({type:i.z.literal("file"),payload:ie}),i.z.object({type:i.z.literal("location"),payload:se})]),we=i.z.object({items:i.z.array(Pe)}),De={text:{schema:X},markdown:{schema:Y},image:{schema:ee},audio:{schema:te},video:{schema:ne},file:{schema:ie},location:{schema:se},carousel:{schema:Se},card:{schema:oe},dropdown:{schema:Q},choice:{schema:Q},bloc:{schema:we}};var v="x-bot-id",j="x-bot-user-id",N="x-integration-id",L="x-webhook-id",Z="x-bp-configuration-type",I="x-bp-configuration",C="x-bp-operation",z="x-bp-type";var ae=require("node:http");var T=console;function f(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function E(t,e=8072,n=Re){let s=(0,ae.createServer)(async(a,r)=>{try{let o=await _e(a);if(o.path==="/health"){r.writeHead(200).end("ok");return}let c=await t(o);r.writeHead(c?.status??200,c?.headers??{}).end(c?.body??"{}")}catch(o){T.error("Error while handling request",{error:o?.message??"Internal error occured"}),r.writeHead(500).end(JSON.stringify({error:o?.message??"Internal error occured"}))}});return s.listen(e,()=>n(e)),s}async function _e(t){let e=await Ue(t),n={};for(let a=0;a<t.rawHeaders.length;a+=2){let r=t.rawHeaders[a].toLowerCase(),o=t.rawHeaders[a+1];n[r]=o}let s=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:s.pathname,query:Me(s.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function Me(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function Ue(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let s="";t.on("data",a=>s+=a.toString()),t.on("error",a=>n(a)),t.on("end",()=>e(s))})}function Re(t){T.info(`Listening on port ${t}`)}l(m,i,module.exports);var K=require("@botpress/client");var u={};P(u,{mapValues:()=>ke,pairs:()=>re});var re=t=>Object.entries(t),ke=(t,e)=>Object.fromEntries(re(t).map(([n,s])=>[n,e(s,n)]));var w=Symbol("schemaName"),ce=t=>t?u.mapValues(t,(n,s)=>({...n,[w]:s})):{},pe=t=>w in t&&t[w]!==void 0,le=t=>t[w];var D=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.configurations=e.configurations,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities,this.interfaces=e.interfaces}name;version;title;description;icon;readme;configuration;configurations;events;actions;channels;states;user;secrets;identifier;entities;interfaces;extend(e,n){let s=n(ce(this.entities)),a=u.pairs(s).find(([p,h])=>!pe(h));if(a)throw new Error(`Cannot extend interface "${e.definition.name}" with entity "${a[0]}"; the provided schema is not part of the integration's entities.`);let r=this;r.interfaces??={};let o=u.mapValues(s,p=>({name:le(p),schema:p.schema})),c=Object.values(o).map(p=>p.name),d=c.length===0?e.definition.name:`${e.definition.name}<${c.join(",")}>`;return r.interfaces[d]={...e,entities:o},this}};var y=require("@botpress/client");var ge=require("@botpress/client"),_={retries:3,retryCondition:t=>ge.axiosRetry.isNetworkOrIdempotentRequestError(t)||[429,502].includes(t.response?.status??0),retryDelay:t=>t*1e3};var b=class{constructor(e){this._client=e}createConversation=e=>this._client.createConversation(e);getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);createEvent=e=>this._client.createEvent(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);createUser=e=>this._client.createUser(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);getOrCreateUser=e=>this._client.getOrCreateUser(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e);setState=e=>this._client.setState(e);getOrSetState=e=>this._client.getOrSetState(e);patchState=e=>this._client.patchState(e);configureIntegration=e=>this._client.configureIntegration(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e)};var M=class{_cost=0;get cost(){return this._cost}setCost(e){this._cost=e}toJSON(){return{cost:this.cost}}};var de=require("@bpinternal/zui");var Ae=de.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),ue=t=>{let e=t[v],n=t[j],s=t[N],a=t[L],r=t[Z],o=t[I],c=Ae.parse(t[C]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!s)throw new Error("Missing integration headers");if(!a)throw new Error("Missing webhook headers");if(!o)throw new Error("Missing configuration headers");if(!c)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:s,webhookId:a,operation:c,configurationType:r??null,configuration:o?JSON.parse(Buffer.from(o,"base64").toString("utf-8")):{}}};var $=J(require("util")),U=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:$.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return $.default.format(`[For Bot Owner] ${e}`,...n)}},R={forBot:()=>({info:(...t)=>{console.info(U(t))},warn:(...t)=>{console.warn(U(t))},error:(...t)=>{console.error(U(t))},debug:(...t)=>{console.debug(U(t))}})};var me=t=>async e=>{let n=ue(e.headers),s=new y.Client({botId:n.botId,integrationId:n.integrationId,retry:_}),a=new b(s),r={ctx:n,req:e,client:a,logger:R,instance:t};try{let o;switch(n.operation){case"webhook_received":o=await He(r);break;case"register":o=await Ke(r);break;case"unregister":o=await Fe(r);break;case"message_created":o=await Ne(r);break;case"action_triggered":o=await Le(r);break;case"ping":o=await Oe(r);break;case"create_user":o=await Ge(r);break;case"create_conversation":o=await je(r);break;default:throw new Error(`Unknown operation ${n.operation}`)}return o?{...o,status:o.status??200}:{status:200}}catch(o){if((0,y.isApiError)(o)){let d=new y.RuntimeError(o.message,o);return R.forBot().error(d.message),{status:d.code,body:JSON.stringify(d.toJSON())}}console.error(o);let c=new y.RuntimeError("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.");return R.forBot().error(c.message),{status:c.code,body:JSON.stringify(c.toJSON())}}},Oe=async t=>{},He=async({client:t,ctx:e,req:n,logger:s,instance:a})=>{let{req:r}=f(n);return a.webhook({client:t,ctx:e,req:r,logger:s})},Ke=async({client:t,ctx:e,req:n,logger:s,instance:a})=>{if(!a.register)return;let{webhookUrl:r}=f(n);await a.register({client:t,ctx:e,webhookUrl:r,logger:s})},Fe=async({client:t,ctx:e,req:n,logger:s,instance:a})=>{if(!a.unregister)return;let{webhookUrl:r}=f(n);await a.unregister({ctx:e,webhookUrl:r,client:t,logger:s})},Ge=async({client:t,ctx:e,req:n,logger:s,instance:a})=>{if(!a.createUser)return;let{tags:r}=f(n);return await a.createUser({ctx:e,client:t,tags:r,logger:s})},je=async({client:t,ctx:e,req:n,logger:s,instance:a})=>{if(!a.createConversation)return;let{channel:r,tags:o}=f(n);return await a.createConversation({ctx:e,client:t,channel:r,tags:o,logger:s})},Ne=async({ctx:t,req:e,client:n,logger:s,instance:a})=>{let{conversation:r,user:o,type:c,payload:d,message:p}=f(e),h=a.channels[r.channel];if(!h)throw new Error(`Channel ${r.channel} not found`);let V=h.messages[c];if(!V)throw new Error(`Message of type ${c} not found in channel ${r.channel}`);await V({ctx:t,conversation:r,message:p,user:o,type:c,client:n,payload:d,ack:async({tags:be})=>{await n.updateMessage({id:p.id,tags:be})},logger:s})},Le=async({req:t,ctx:e,client:n,logger:s,instance:a})=>{let{input:r,type:o}=f(t);if(!o)throw new Error("Missing action type");let c=a.actions[o];if(!c)throw new Error(`Action ${o} not found`);let d=new M,h={output:await c({ctx:e,input:r,client:n,type:o,logger:s,metadata:d}),meta:d.toJSON()};return{body:JSON.stringify(h)}};var k=class{constructor(e){this.props=e;this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}actions;channels;register;unregister;createUser;createConversation;webhook;handler=me(this);start=e=>E(this.handler,e)};var A=class{constructor(e){this.props=e;this.integrations=e.integrations,this.user=e.user,this.conversation=e.conversation,this.message=e.message,this.states=e.states,this.configuration=e.configuration,this.events=e.events,this.recurringEvents=e.recurringEvents}integrations;user;conversation;message;states;configuration;events;recurringEvents;add(e,n){let s=this;return s.integrations||(s.integrations={}),s.integrations[e.definition.name]={enabled:n.enabled,...e,configurationType:n.configurationType,configuration:n.configuration},this}};var he=J(require("@botpress/client"));var B=class{constructor(e){this._client=e}getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this._client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this._client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this._client.patchState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));callAction=e=>this._client.callAction(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e);searchFiles=e=>this._client.searchFiles(e);createConversation=e=>this._client.createConversation(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);createUser=e=>this._client.createUser(e);getOrCreateUser=e=>this._client.getOrCreateUser(e)};var fe=require("@bpinternal/zui");var Ze=fe.z.enum(["event_received","register","unregister","ping","action_triggered"]),ye=t=>{let e=t[v],n=t[I],s=t[z],a=Ze.parse(t[C]);if(!e)throw new Error("Missing bot headers");if(!s)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!a)throw new Error("Missing operation headers");return{botId:e,operation:a,type:s,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var Te=t=>async e=>{let n=ye(e.headers);n.operation!=="ping"&&T.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let s=new he.Client({botId:n.botId,retry:_}),a=new B(s),r={req:e,ctx:n,client:a,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await Ve(r);break;case"register":await qe(r);break;case"unregister":await $e(r);break;case"ping":await ze(r);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},ze=async t=>{},qe=async t=>{},$e=async t=>{},Ve=async({ctx:t,req:e,client:n,instance:s})=>{T.debug(`Received event ${t.type}`);let a=f(e),r=a.event;switch(t.type){case"message_created":let o={user:r.payload.user,conversation:r.payload.conversation,message:r.payload.message,states:r.payload.states,event:r};await Promise.all(s.messageHandlers.map(p=>p({client:n,ctx:t,...o})));break;case"state_expired":let c={state:r.payload.state};await Promise.all(s.stateExpiredHandlers.map(p=>p({client:n,ctx:t,...c})));break;default:let d={event:a.event};await Promise.all(s.eventHandlers.map(p=>p({client:n,ctx:t,...d})))}};var O=class{constructor(e){this.props=e}_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=Te(this._state);start=e=>E(this.handler,e)};var H=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.entities=e.entities??{},this.templateName=e.templateName;let n=this._getEntityReference(this.entities),s=e.events===void 0?{}:u.mapValues(e.events,o=>({...o,schema:o.schema(n)})),a=e.actions===void 0?{}:u.mapValues(e.actions,o=>({...o,input:{...o.input,schema:o.input.schema(n)},output:{...o.output,schema:o.output.schema(n)}})),r=e.channels===void 0?{}:u.mapValues(e.channels,o=>({...o,messages:u.mapValues(o.messages,c=>({...c,schema:c.schema(n)}))}));this.events=s,this.actions=a,this.channels=r}name;version;entities;events;actions;channels;templateName;_getEntityReference=e=>{let n={};for(let s of Object.keys(e))n[s]=F.ref(s);return n}};0&&(module.exports={Bot,BotDefinition,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,InterfaceDeclaration,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,configurationTypeHeader,integrationIdHeader,isApiError,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|