@botpress/sdk 0.0.16 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,10 +10,9 @@ export type UnregisterBotPayload = {
10
10
  export type EventReceivedBotPayload = {
11
11
  event: Event;
12
12
  };
13
- export type BotDefinitionTags = {
14
- messages?: string[];
15
- conversations?: string[];
16
- users?: string[];
13
+ export type BotDefinitionTag = {
14
+ title?: string;
15
+ description?: string;
17
16
  };
18
17
  export type BotDefinitionStateType = 'conversation' | 'user' | 'bot';
19
18
  export type BotDefinitionState = {
@@ -41,8 +40,19 @@ export type BotDefinitionEvent = {
41
40
  export type BotDefinitionConfiguration = {
42
41
  schema: Record<string, any>;
43
42
  };
43
+ export type BotDefinitionUser = {
44
+ tags?: Record<string, BotDefinitionTag>;
45
+ };
46
+ export type BotDefinitionConversation = {
47
+ tags?: Record<string, BotDefinitionTag>;
48
+ };
49
+ export type BotDefinitionMessage = {
50
+ tags?: Record<string, BotDefinitionTag>;
51
+ };
44
52
  export type BotDefinition = {
45
- tags?: BotDefinitionTags;
53
+ user?: BotDefinitionUser;
54
+ conversation?: BotDefinitionConversation;
55
+ message?: BotDefinitionMessage;
46
56
  states?: Record<string, BotDefinitionState>;
47
57
  integrations?: IntegrationInstance[];
48
58
  configuration?: BotDefinitionConfiguration;
@@ -51,12 +61,7 @@ export type BotDefinition = {
51
61
  };
52
62
  export declare class Bot {
53
63
  private _state;
54
- readonly tags?: BotDefinitionTags;
55
- readonly states?: Record<string, BotDefinitionState>;
56
- readonly integrations?: IntegrationInstance[];
57
- readonly configuration?: BotDefinitionConfiguration;
58
- readonly events?: Record<string, BotDefinitionEvent>;
59
- readonly recurringEvents?: Record<string, BotDefinitionRecurringEvent>;
64
+ readonly definition: BotDefinition;
60
65
  constructor(def?: BotDefinition);
61
66
  register: (_handler: RegisterHandler) => void;
62
67
  unregister: (_handler: UnregisterHandler) => void;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var le=Object.create;var B=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var K=(t,e)=>{for(var n in e)B(t,n,{get:e[n],enumerable:!0})},Z=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ye(e))!he.call(t,o)&&o!==n&&B(t,o,{get:()=>e[o],enumerable:!(r=fe(e,o))||r.enumerable});return t};var _=(t,e,n)=>(n=t!=null?le(me(t)):{},Z(e||!t||!t.__esModule?B(n,"default",{value:t,enumerable:!0}):n,t)),be=t=>Z(B({},"__esModule",{value:!0}),t);var ct={};K(ct,{Bot:()=>H,Integration:()=>M,IntegrationDefinition:()=>A,botIdHeader:()=>d,botUserIdHeader:()=>C,clients:()=>st,configurationHeader:()=>u,integrationIdHeader:()=>I,messages:()=>N,operationHeader:()=>l,serve:()=>h,typeHeader:()=>S,webhookIdHeader:()=>P});module.exports=be(ct);var L=_(require("axios"));var d="x-bot-id",C="x-bot-user-id",I="x-integration-id",P="x-webhook-id",u="x-bp-configuration",l="x-bp-operation",S="x-bp-type";var O=class{axios;constructor(e){this.axios=e??L.default.create({timeout:5e3})}register=e=>z("register",e,this.axios);unregister=e=>z("unregister",e,this.axios);eventReceived=e=>z("event_received",e,this.axios)};function ve(t){return{[S]:t.type,[d]:t.botId,[l]:t.operation,[u]:Buffer.from(typeof t.configuration=="string"?t.configuration:JSON.stringify(t.configuration),"utf-8").toString("base64")}}async function z(t,{url:e,data:n,...r},o){return(await o.post(e,n,{headers:ve({...r,operation:t})})).data}var V=require("node:http");var m=console;async function h(t,e=8072,n=Pe){let r=(0,V.createServer)(async(o,i)=>{try{let s=await xe(o),g=await t(s);i.writeHead(g?.status??200,g?.headers??{}).end(g?.body??"{}")}catch(s){m.error("Error while handling request",{error:s?.message??"Internal error occured"}),i.writeHead(500).end(JSON.stringify({error:s?.message??"Internal error occured"}))}});return r.listen(e,()=>n(e)),r}async function xe(t){let e=await Ie(t),n={};for(let o=0;o<t.rawHeaders.length;o+=2){let i=t.rawHeaders[o].toLowerCase(),s=t.rawHeaders[o+1];n[i]=s}let r=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:r.pathname,query:Ce(r.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function Ce(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function Ie(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let r="";t.on("data",o=>r+=o.toString()),t.on("error",o=>n(o)),t.on("end",()=>e(r))})}function Pe(t){m.info(`Listening on port ${t}`)}var q=require("@botpress/client");var F=require("zod"),W=F.z.enum(["event_received","register","unregister","ping"]);var G=t=>async e=>{let n=Se(e.headers);n.operation!=="ping"&&m.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let r=new q.Client({botId:n.botId}),o={req:e,botState:t,ctx:n,client:r};switch(n.operation){case"event_received":await we(o);break;case"register":await Te(o);break;case"unregister":await Ee(o);break;case"ping":await De(o);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}};function Se(t){let e=t[d],n=t[u],r=t[S],o=W.parse(t[l]);if(!e)throw new Error("Missing bot headers");if(!r)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!o)throw new Error("Missing operation headers");return{botId:e,operation:o,type:r,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}}async function we({botState:t,ctx:e,req:n}){m.debug(`Received event ${e.type}`);let r=new q.Client({botId:e.botId}),o=Be(n);switch(e.type){case"message_created":await Promise.all(t.messageHandlers.map(i=>i({client:r,user:o.event.payload.user,conversation:o.event.payload.conversation,message:o.event.payload.message,event:o.event,ctx:e})));break;case"state_expired":await Promise.all(t.stateExpiredHandlers.map(i=>i({client:r,state:o.event.payload.state,ctx:e})));break;default:await Promise.all(t.eventHandlers.map(i=>i({client:r,event:o.event,ctx:e})))}}async function De(t){}async function Te(t){}async function Ee(t){}function Be(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}var H=class{_state={registerHandlers:[],unregisterHandlers:[],messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};tags;states;integrations;configuration;events;recurringEvents;constructor(e={}){this.tags=e.tags,this.states=e.states,this.integrations=e.integrations,this.configuration=e.configuration,this.events=e.events,this.recurringEvents=e.recurringEvents}register=e=>{};unregister=e=>{};message=(e,n)=>{this._state.messageHandlers.push(n)};conversation=(e,n)=>{};user=(e,n)=>{};event=(e,n)=>{this._state.eventHandlers.push(n)};stateExpired=(e,n)=>{this._state.stateExpiredHandlers.push(n)};handler=G(this._state);start=e=>h(this.handler,e)};var J=require("@botpress/client"),k=_(require("axios"));var X=require("@botpress/client"),w=require("zod"),Q=new X.RuntimeError(""),Y=w.z.object({code:w.z.literal(Q.code),type:w.z.literal(Q.type),message:w.z.string()});var R=class{axios;constructor(e){this.axios=e??k.default.create({timeout:5e3})}actionTriggered=e=>b("action_triggered",e,this.axios);messageCreated=e=>b("message_created",e,this.axios);register=e=>b("register",e,this.axios);unregister=e=>b("unregister",e,this.axios);webhookReceived=e=>Oe("webhook_received",e,this.axios);createUser=e=>b("create_user",e,this.axios);createConversation=e=>b("create_conversation",e,this.axios)};function ee(t){return{[d]:t.botId,[l]:t.operation,[C]:t.botUserId,[I]:t.integrationId,[P]:t.webhookId,[u]:Buffer.from(typeof t.configuration=="string"?t.configuration:JSON.stringify(t.configuration),"utf-8").toString("base64")}}async function Oe(t,{url:e,data:n,...r},o){return await o.post(e,n,{headers:ee({...r,operation:t})}).catch(s=>{if(k.default.isAxiosError(s)&&s.response?.status&&s.response.status<500)return s.response;throw s})}async function b(t,{url:e,data:n,...r},o){try{return await o.post(e,n,{headers:ee({...r,operation:t})})}catch(i){let s=new J.RuntimeError("").code;if(k.default.isAxiosError(i)&&i.response?.status===s){let g=Y.safeParse(i.response.data);if(g.success)throw new J.RuntimeError(g.data.message)}throw i}}var te=require("zod"),ne=te.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]);var v=require("radash"),a=require("zod");var oe=_(require("zod-to-json-schema")),He=t=>t?.type==="object";function f(t){let e=(0,oe.default)(t.schema,{errorMessages:!0});if(!He(e)||!t.ui)return e;for(let[n,r]of Object.entries(t.ui??{})){let o=e.properties?.[n];o&&(r?.title&&(o.title=r.title),r?.examples&&(o.examples=r.examples))}return e}var Re=t=>{let e=a.z.record(t);return{min:n=>e.refine(r=>Object.keys(r).length>=n,{message:`At least ${n} item(s) must be defined`})}},x=a.z.object({}).passthrough(),ke=a.z.object({schema:x}),Ae=a.z.object({schema:x}),Ue=a.z.object({input:a.z.object({schema:x}),output:a.z.object({schema:x})}),Me=a.z.object({schema:x}),re=a.z.object({conversations:a.z.array(a.z.string()).optional(),users:a.z.array(a.z.string()).optional(),messages:a.z.array(a.z.string()).optional()}),je=a.z.object({tags:re.omit({users:!0}).optional(),messages:Re(Me).min(1),conversation:a.z.object({creation:a.z.object({enabled:a.z.boolean(),requiredTags:a.z.array(a.z.string())})}).optional()}),_e=a.z.object({type:a.z.union([a.z.literal("integration"),a.z.literal("conversation"),a.z.literal("user")]),schema:x}),ze="0.2.0",qe="0.0.1",Je=a.z.object({name:a.z.string(),version:a.z.enum([qe,ze]),title:a.z.string().optional(),description:a.z.string().optional(),icon:a.z.string().optional(),readme:a.z.string().optional(),tags:re.pick({users:!0}).optional(),configuration:ke.optional(),events:a.z.record(Ae).optional(),actions:a.z.record(Ue).optional(),channels:a.z.record(je).optional(),states:a.z.record(_e).optional(),user:a.z.object({creation:a.z.object({enabled:a.z.boolean(),requiredTags:a.z.array(a.z.string())})}).optional(),secrets:a.z.array(a.z.string()).optional()});function Ne(t){return{...t,configuration:t.configuration?{...t.configuration,schema:f(t.configuration)}:void 0,events:t.events?(0,v.mapValues)(t.events,e=>({...e,schema:f(e)})):void 0,actions:t.actions?(0,v.mapValues)(t.actions,e=>({...e,input:{...e.input,schema:f(e.input)},output:{...e.output,schema:f(e.output)}})):void 0,channels:t.channels?(0,v.mapValues)(t.channels,e=>({...e,messages:(0,v.mapValues)(e.messages,n=>({...n,schema:f(n)}))})):void 0,states:t.states?(0,v.mapValues)(t.states,e=>({...e,schema:f(e)})):void 0,user:t.user}}var A=class{name;version;icon;readme;title;description;tags;configuration;events;actions;channels;states;user;secrets;constructor(e){let n=Ne(e),r=Je.parse(n),{name:o,version:i,icon:s,readme:g,title:D,description:T,tags:E,configuration:$,events:j,actions:ce,channels:pe,states:ge,user:de,secrets:ue}=r;this.name=o,this.version=i,this.icon=s,this.readme=g,this.title=D,this.description=T,this.tags=E,this.configuration=$,this.events=j,this.actions=ce,this.channels=pe,this.states=ge,this.user=de,this.secrets=ue}};var U=require("@botpress/client");var ie=t=>async e=>{let n=$e(e.headers),r=new U.Client({botId:n.botId,integrationId:n.integrationId}),o={integration:t,ctx:n,req:e,client:r};try{let i;switch(n.operation){case"webhook_received":i=await Ze(o);break;case"register":i=await Le(o);break;case"unregister":i=await Ve(o);break;case"message_created":i=await Ge(o);break;case"action_triggered":i=await Qe(o);break;case"ping":i=await Ke(o);break;case"create_user":i=await Fe(o);break;case"create_conversation":i=await We(o);break;default:throw new Error(`Unknown operation ${n.operation}`)}return i?{...i,status:i.status??200}:{status:200}}catch(i){if(i instanceof U.RuntimeError)return{status:i.code,body:JSON.stringify(i.toJSON())};throw i}};function $e(t){let e=t[d],n=t[C],r=t[I],o=t[P],i=t[u],s=ne.parse(t[l]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!r)throw new Error("Missing integration headers");if(!o)throw new Error("Missing webhook headers");if(!i)throw new Error("Missing configuration headers");if(!s)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:r,webhookId:o,operation:s,configuration:i?JSON.parse(Buffer.from(i,"base64").toString("utf-8")):{}}}function y(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function Ke(t){}async function Ze({client:t,ctx:e,integration:n,req:r}){let{req:o}=y(r);return n.handler({client:t,ctx:e,req:o})}async function Le({client:t,ctx:e,integration:n,req:r}){if(!n.register)return;let{webhookUrl:o}=y(r);await n.register({client:t,ctx:e,webhookUrl:o})}async function Ve({client:t,ctx:e,integration:n,req:r}){if(!n.unregister)return;let{webhookUrl:o}=y(r);await n.unregister({ctx:e,webhookUrl:o,client:t})}async function Fe({client:t,ctx:e,integration:n,req:r}){if(!n.createUser)return;let{tags:o}=y(r);return await n.createUser({ctx:e,client:t,tags:o})}async function We({client:t,ctx:e,integration:n,req:r}){if(!n.createConversation)return;let{channel:o,tags:i}=y(r);return await n.createConversation({ctx:e,client:t,channel:o,tags:i})}async function Ge({ctx:t,integration:e,req:n,client:r}){let{conversation:o,user:i,type:s,payload:g,message:D}=y(n),T=e.channels[o.channel];if(!T)throw new Error(`Channel ${o.channel} not found`);let E=T.messages[s];if(!E)throw new Error(`Message of type ${s} not found in channel ${o.channel}`);await E({ctx:t,conversation:o,message:D,user:i,type:s,client:r,payload:g,ack:async({tags:j})=>{await r.updateMessage({id:D.id,tags:j})}})}async function Qe({req:t,integration:e,ctx:n,client:r}){let{input:o,type:i}=y(t);if(!i)throw new Error("Missing action type");let s=e.actions[i];if(!s)throw new Error(`Action ${i} not found`);let g=await s({ctx:n,input:o,client:r,type:i});return{body:JSON.stringify({output:g})}}var M=class{props;actions;channels;register;unregister;createUser;createConversation;handler;start;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.handler=ie(e),this.start=n=>h(this.handler,n)}};var N={};K(N,{defaults:()=>at});var c=require("zod"),p=c.z.string().min(1),Xe=c.z.object({text:p}),Ye=c.z.object({markdown:p}),et=c.z.object({imageUrl:p}),tt=c.z.object({audioUrl:p}),nt=c.z.object({videoUrl:p}),ot=c.z.object({fileUrl:p,title:p.optional()}),rt=c.z.object({latitude:c.z.number(),longitude:c.z.number(),address:c.z.string().optional(),title:c.z.string().optional()}),se=c.z.object({title:p,subtitle:p.optional(),imageUrl:p.optional(),actions:c.z.array(c.z.object({action:c.z.enum(["postback","url","say"]),label:p,value:p}))}),ae=c.z.object({text:p,options:c.z.array(c.z.object({label:p,value:p}))}),it=c.z.object({items:c.z.array(se)}),at={text:{schema:Xe},markdown:{schema:Ye},image:{schema:et},audio:{schema:tt},video:{schema:nt},file:{schema:ot},location:{schema:rt},carousel:{schema:it},card:{schema:se},dropdown:{schema:ae},choice:{schema:ae}};var st={IntegrationClient:R,BotClient:O};0&&(module.exports={Bot,Integration,IntegrationDefinition,botIdHeader,botUserIdHeader,clients,configurationHeader,integrationIdHeader,messages,operationHeader,serve,typeHeader,webhookIdHeader});
1
+ "use strict";var le=Object.create;var O=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var Z=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})},L=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fe(t))!me.call(e,o)&&o!==n&&O(e,o,{get:()=>t[o],enumerable:!(r=ue(t,o))||r.enumerable});return e};var _=(e,t,n)=>(n=e!=null?le(ye(e)):{},L(t||!e||!e.__esModule?O(n,"default",{value:e,enumerable:!0}):n,e)),he=e=>L(O({},"__esModule",{value:!0}),e);var st={};Z(st,{Bot:()=>H,Integration:()=>M,IntegrationDefinition:()=>k,botIdHeader:()=>g,botUserIdHeader:()=>C,clients:()=>at,configurationHeader:()=>l,integrationIdHeader:()=>I,messages:()=>$,operationHeader:()=>u,serve:()=>h,typeHeader:()=>S,webhookIdHeader:()=>P});module.exports=he(st);var V=_(require("axios"));var g="x-bot-id",C="x-bot-user-id",I="x-integration-id",P="x-webhook-id",l="x-bp-configuration",u="x-bp-operation",S="x-bp-type";var E=class{axios;constructor(t){this.axios=t??V.default.create({timeout:5e3})}register=t=>z("register",t,this.axios);unregister=t=>z("unregister",t,this.axios);eventReceived=t=>z("event_received",t,this.axios)};function be(e){return{[S]:e.type,[g]:e.botId,[u]:e.operation,[l]:Buffer.from(typeof e.configuration=="string"?e.configuration:JSON.stringify(e.configuration),"utf-8").toString("base64")}}async function z(e,{url:t,data:n,...r},o){return(await o.post(t,n,{headers:be({...r,operation:e})})).data}var F=require("node:http");var m=console;async function h(e,t=8072,n=Ie){let r=(0,F.createServer)(async(o,i)=>{try{let s=await xe(o),d=await e(s);i.writeHead(d?.status??200,d?.headers??{}).end(d?.body??"{}")}catch(s){m.error("Error while handling request",{error:s?.message??"Internal error occured"}),i.writeHead(500).end(JSON.stringify({error:s?.message??"Internal error occured"}))}});return r.listen(t,()=>n(t)),r}async function xe(e){let t=await Ce(e),n={};for(let o=0;o<e.rawHeaders.length;o+=2){let i=e.rawHeaders[o].toLowerCase(),s=e.rawHeaders[o+1];n[i]=s}let r=new URL(e.url??"",e.headers.host?`http://${e.headers.host}`:"http://botpress.cloud");return{body:t,path:r.pathname,query:ve(r.search,"?"),headers:n,method:e.method?.toUpperCase()??"GET"}}function ve(e,t){return e.indexOf(t)===0?e.slice(t.length):e}async function Ce(e){return new Promise((t,n)=>{if(e.method!=="POST"&&e.method!=="PUT"&&e.method!=="PATCH")return t(void 0);let r="";e.on("data",o=>r+=o.toString()),e.on("error",o=>n(o)),e.on("end",()=>t(r))})}function Ie(e){m.info(`Listening on port ${e}`)}var q=require("@botpress/client");var W=require("zod"),G=W.z.enum(["event_received","register","unregister","ping"]);var Q=e=>async t=>{let n=Pe(t.headers);n.operation!=="ping"&&m.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let r=new q.Client({botId:n.botId}),o={req:t,botState:e,ctx:n,client:r};switch(n.operation){case"event_received":await Se(o);break;case"register":await De(o);break;case"unregister":await Te(o);break;case"ping":await we(o);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}};function Pe(e){let t=e[g],n=e[l],r=e[S],o=G.parse(e[u]);if(!t)throw new Error("Missing bot headers");if(!r)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!o)throw new Error("Missing operation headers");return{botId:t,operation:o,type:r,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}}async function Se({botState:e,ctx:t,req:n}){m.debug(`Received event ${t.type}`);let r=new q.Client({botId:t.botId}),o=Be(n);switch(t.type){case"message_created":await Promise.all(e.messageHandlers.map(i=>i({client:r,user:o.event.payload.user,conversation:o.event.payload.conversation,message:o.event.payload.message,event:o.event,ctx:t})));break;case"state_expired":await Promise.all(e.stateExpiredHandlers.map(i=>i({client:r,state:o.event.payload.state,ctx:t})));break;default:await Promise.all(e.eventHandlers.map(i=>i({client:r,event:o.event,ctx:t})))}}async function we(e){}async function De(e){}async function Te(e){}function Be(e){if(!e.body)throw new Error("Missing body");return JSON.parse(e.body)}var H=class{_state={registerHandlers:[],unregisterHandlers:[],messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};definition;constructor(t={}){this.definition=t}register=t=>{};unregister=t=>{};message=(t,n)=>{this._state.messageHandlers.push(n)};conversation=(t,n)=>{};user=(t,n)=>{};event=(t,n)=>{this._state.eventHandlers.push(n)};stateExpired=(t,n)=>{this._state.stateExpiredHandlers.push(n)};handler=Q(this._state);start=t=>h(this.handler,t)};var J=require("@botpress/client"),A=_(require("axios"));var Y=require("@botpress/client"),w=require("zod"),X=new Y.RuntimeError(""),ee=w.z.object({code:w.z.literal(X.code),type:w.z.literal(X.type),message:w.z.string()});var R=class{axios;constructor(t){this.axios=t??A.default.create({timeout:5e3})}actionTriggered=t=>b("action_triggered",t,this.axios);messageCreated=t=>b("message_created",t,this.axios);register=t=>b("register",t,this.axios);unregister=t=>b("unregister",t,this.axios);webhookReceived=t=>Oe("webhook_received",t,this.axios);createUser=t=>b("create_user",t,this.axios);createConversation=t=>b("create_conversation",t,this.axios)};function te(e){return{[g]:e.botId,[u]:e.operation,[C]:e.botUserId,[I]:e.integrationId,[P]:e.webhookId,[l]:Buffer.from(typeof e.configuration=="string"?e.configuration:JSON.stringify(e.configuration),"utf-8").toString("base64")}}async function Oe(e,{url:t,data:n,...r},o){return await o.post(t,n,{headers:te({...r,operation:e})}).catch(s=>{if(A.default.isAxiosError(s)&&s.response?.status&&s.response.status<500)return s.response;throw s})}async function b(e,{url:t,data:n,...r},o){try{return await o.post(t,n,{headers:te({...r,operation:e})})}catch(i){let s=new J.RuntimeError("").code;if(A.default.isAxiosError(i)&&i.response?.status===s){let d=ee.safeParse(i.response.data);if(d.success)throw new J.RuntimeError(d.data.message)}throw i}}var ne=require("zod"),oe=ne.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]);var x=require("radash"),a=require("zod");var re=_(require("zod-to-json-schema")),Ee=e=>e?.type==="object";function f(e){let t=(0,re.default)(e.schema,{errorMessages:!0});if(!Ee(t)||!e.ui)return t;for(let[n,r]of Object.entries(e.ui??{})){let o=t.properties?.[n];o&&(r?.title&&(o.title=r.title),r?.examples&&(o.examples=r.examples))}return t}var He=e=>{let t=a.z.record(e);return{min:n=>t.refine(r=>Object.keys(r).length>=n,{message:`At least ${n} item(s) must be defined`})}},v=a.z.object({}).passthrough(),Re=a.z.object({schema:v}),Ae=a.z.object({schema:v}),ke=a.z.object({input:a.z.object({schema:v}),output:a.z.object({schema:v})}),Ue=a.z.object({schema:v}),N=a.z.object({title:a.z.string().optional(),description:a.z.string().optional()}),Me=a.z.object({messages:He(Ue).min(1),message:a.z.object({tags:a.z.record(N)}).partial().optional(),conversation:a.z.object({tags:a.z.record(N),creation:a.z.object({enabled:a.z.boolean(),requiredTags:a.z.array(a.z.string())})}).partial().optional()}),je=a.z.object({type:a.z.union([a.z.literal("integration"),a.z.literal("conversation"),a.z.literal("user")]),schema:v}),_e="0.2.0",ze="0.0.1",qe=a.z.object({name:a.z.string(),version:a.z.enum([ze,_e]),title:a.z.string().optional(),description:a.z.string().optional(),icon:a.z.string().optional(),readme:a.z.string().optional(),configuration:Re.optional(),events:a.z.record(Ae).optional(),actions:a.z.record(ke).optional(),channels:a.z.record(Me).optional(),states:a.z.record(je).optional(),user:a.z.object({tags:a.z.record(N),creation:a.z.object({enabled:a.z.boolean(),requiredTags:a.z.array(a.z.string())})}).partial().optional(),secrets:a.z.array(a.z.string()).optional()});function Je(e){return{...e,configuration:e.configuration?{...e.configuration,schema:f(e.configuration)}:void 0,events:e.events?(0,x.mapValues)(e.events,t=>({...t,schema:f(t)})):void 0,actions:e.actions?(0,x.mapValues)(e.actions,t=>({...t,input:{...t.input,schema:f(t.input)},output:{...t.output,schema:f(t.output)}})):void 0,channels:e.channels?(0,x.mapValues)(e.channels,t=>({...t,messages:(0,x.mapValues)(t.messages,n=>({...n,schema:f(n)}))})):void 0,states:e.states?(0,x.mapValues)(e.states,t=>({...t,schema:f(t)})):void 0,user:e.user}}var k=class{name;version;icon;readme;title;description;configuration;events;actions;channels;states;user;secrets;constructor(t){let n=Je(t),r=qe.parse(n),{name:o,version:i,icon:s,readme:d,title:D,description:T,configuration:B,events:K,actions:j,channels:ce,states:pe,user:de,secrets:ge}=r;this.name=o,this.version=i,this.icon=s,this.readme=d,this.title=D,this.description=T,this.configuration=B,this.events=K,this.actions=j,this.channels=ce,this.states=pe,this.user=de,this.secrets=ge}};var U=require("@botpress/client");var ie=e=>async t=>{let n=Ne(t.headers),r=new U.Client({botId:n.botId,integrationId:n.integrationId}),o={integration:e,ctx:n,req:t,client:r};try{let i;switch(n.operation){case"webhook_received":i=await Ke(o);break;case"register":i=await Ze(o);break;case"unregister":i=await Le(o);break;case"message_created":i=await We(o);break;case"action_triggered":i=await Ge(o);break;case"ping":i=await $e(o);break;case"create_user":i=await Ve(o);break;case"create_conversation":i=await Fe(o);break;default:throw new Error(`Unknown operation ${n.operation}`)}return i?{...i,status:i.status??200}:{status:200}}catch(i){if(i instanceof U.RuntimeError)return{status:i.code,body:JSON.stringify(i.toJSON())};throw i}};function Ne(e){let t=e[g],n=e[C],r=e[I],o=e[P],i=e[l],s=oe.parse(e[u]);if(!t)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!r)throw new Error("Missing integration headers");if(!o)throw new Error("Missing webhook headers");if(!i)throw new Error("Missing configuration headers");if(!s)throw new Error("Missing operation headers");return{botId:t,botUserId:n,integrationId:r,webhookId:o,operation:s,configuration:i?JSON.parse(Buffer.from(i,"base64").toString("utf-8")):{}}}function y(e){if(!e.body)throw new Error("Missing body");return JSON.parse(e.body)}async function $e(e){}async function Ke({client:e,ctx:t,integration:n,req:r}){let{req:o}=y(r);return n.handler({client:e,ctx:t,req:o})}async function Ze({client:e,ctx:t,integration:n,req:r}){if(!n.register)return;let{webhookUrl:o}=y(r);await n.register({client:e,ctx:t,webhookUrl:o})}async function Le({client:e,ctx:t,integration:n,req:r}){if(!n.unregister)return;let{webhookUrl:o}=y(r);await n.unregister({ctx:t,webhookUrl:o,client:e})}async function Ve({client:e,ctx:t,integration:n,req:r}){if(!n.createUser)return;let{tags:o}=y(r);return await n.createUser({ctx:t,client:e,tags:o})}async function Fe({client:e,ctx:t,integration:n,req:r}){if(!n.createConversation)return;let{channel:o,tags:i}=y(r);return await n.createConversation({ctx:t,client:e,channel:o,tags:i})}async function We({ctx:e,integration:t,req:n,client:r}){let{conversation:o,user:i,type:s,payload:d,message:D}=y(n),T=t.channels[o.channel];if(!T)throw new Error(`Channel ${o.channel} not found`);let B=T.messages[s];if(!B)throw new Error(`Message of type ${s} not found in channel ${o.channel}`);await B({ctx:e,conversation:o,message:D,user:i,type:s,client:r,payload:d,ack:async({tags:j})=>{await r.updateMessage({id:D.id,tags:j})}})}async function Ge({req:e,integration:t,ctx:n,client:r}){let{input:o,type:i}=y(e);if(!i)throw new Error("Missing action type");let s=t.actions[i];if(!s)throw new Error(`Action ${i} not found`);let d=await s({ctx:n,input:o,client:r,type:i});return{body:JSON.stringify({output:d})}}var M=class{props;actions;channels;register;unregister;createUser;createConversation;handler;start;constructor(t){this.props=t,this.actions=t.actions,this.channels=t.channels,this.register=t.register,this.unregister=t.unregister,this.createUser=t.createUser,this.createConversation=t.createConversation,this.handler=ie(t),this.start=n=>h(this.handler,n)}};var $={};Z($,{defaults:()=>it});var c=require("zod"),p=c.z.string().min(1),Qe=c.z.object({text:p}),Xe=c.z.object({markdown:p}),Ye=c.z.object({imageUrl:p}),et=c.z.object({audioUrl:p}),tt=c.z.object({videoUrl:p}),nt=c.z.object({fileUrl:p,title:p.optional()}),ot=c.z.object({latitude:c.z.number(),longitude:c.z.number(),address:c.z.string().optional(),title:c.z.string().optional()}),se=c.z.object({title:p,subtitle:p.optional(),imageUrl:p.optional(),actions:c.z.array(c.z.object({action:c.z.enum(["postback","url","say"]),label:p,value:p}))}),ae=c.z.object({text:p,options:c.z.array(c.z.object({label:p,value:p}))}),rt=c.z.object({items:c.z.array(se)}),it={text:{schema:Qe},markdown:{schema:Xe},image:{schema:Ye},audio:{schema:et},video:{schema:tt},file:{schema:nt},location:{schema:ot},carousel:{schema:rt},card:{schema:se},dropdown:{schema:ae},choice:{schema:ae}};var at={IntegrationClient:R,BotClient:E};0&&(module.exports={Bot,Integration,IntegrationDefinition,botIdHeader,botUserIdHeader,clients,configurationHeader,integrationIdHeader,messages,operationHeader,serve,typeHeader,webhookIdHeader});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/bot/client.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/bot/server.ts", "../src/bot/context.ts", "../src/bot/implementation.ts", "../src/integration/client.ts", "../src/integration/error.ts", "../src/integration/context.ts", "../src/integration/definition.ts", "../src/integration/schema.ts", "../src/integration/server.ts", "../src/integration/implementation.ts", "../src/message.ts"],
4
- "sourcesContent": ["import { BotClient } from './bot'\nimport { IntegrationClient } from './integration'\n\nexport * as messages from './message'\nexport const clients = { IntegrationClient, BotClient }\n\nexport * from './const'\nexport * from './serve'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationOperation,\n ActionDefinitions,\n ChannelDefinitions,\n EventDefinitions,\n AckFunction,\n} from './integration'\nexport { Bot, BotContext, BotOperation, IntegrationInstance } from './bot'\n", "import axiosGlobal, { Axios as AxiosInstance } from 'axios'\nimport type { Merge, Except } from 'type-fest'\nimport { botIdHeader, operationHeader, configurationHeader, typeHeader } from '../const'\nimport type { BotContext, BotOperation } from './context'\nimport type { RegisterBotPayload, UnregisterBotPayload, EventReceivedBotPayload } from './implementation'\n\ntype Props<T = any> = Merge<\n Except<BotContext, 'operation'>,\n {\n url: string\n data: T\n }\n>\n\n/**\n * @description Meant to query your bot server directly (e.g. without going through the Botpress API)\n */\nexport class BotClient {\n private axios: AxiosInstance\n\n public constructor(axiosInstance?: AxiosInstance) {\n this.axios = axiosInstance ?? axiosGlobal.create({ timeout: 5000 })\n }\n\n public register = (props: Props<RegisterBotPayload>) => request('register', props, this.axios)\n public unregister = (props: Props<UnregisterBotPayload>) => request('unregister', props, this.axios)\n public eventReceived = (props: Props<EventReceivedBotPayload>) => request('event_received', props, this.axios)\n}\n\nexport function formatBotHeaders(ctx: BotContext) {\n return {\n [typeHeader]: ctx.type,\n [botIdHeader]: ctx.botId,\n [operationHeader]: ctx.operation,\n [configurationHeader]: Buffer.from(\n typeof ctx.configuration === 'string' ? ctx.configuration : JSON.stringify(ctx.configuration),\n 'utf-8'\n ).toString('base64'),\n }\n}\n\nasync function request<O = any>(operation: BotOperation, { url, data, ...ctx }: Props, axios: AxiosInstance) {\n const response = await axios.post<O>(url, data, {\n headers: formatBotHeaders({\n ...ctx,\n operation,\n }),\n })\n\n return response.data\n}\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { Client } from '@botpress/client'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\nimport { log } from '../log'\nimport type { Handler, Request, Response } from '../serve'\nimport { BotContext, botOperationSchema } from './context'\nimport type { EventReceivedBotPayload } from './implementation'\nimport type { BotState } from './state'\n\ntype OperationHandlerProps = {\n botState: BotState\n ctx: BotContext\n client: Client\n req: Request\n}\n\nexport const createBotHandler =\n (botState: BotState): Handler =>\n async (req: Request): Promise<Response> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const client = new Client({ botId: ctx.botId })\n\n const props: OperationHandlerProps = {\n req,\n botState,\n ctx,\n client,\n }\n\n switch (ctx.operation) {\n case 'event_received':\n await onEventReceived(props)\n break\n case 'register':\n await onRegister(props)\n break\n case 'unregister':\n await onUnregister(props)\n break\n case 'ping':\n await onPing(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nfunction extractContext(headers: Record<string, string | undefined>): BotContext {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n\nasync function onEventReceived({ botState, ctx, req }: OperationHandlerProps) {\n log.debug(`Received event ${ctx.type}`)\n\n const client = new Client({ botId: ctx.botId })\n\n const body = parseBody<EventReceivedBotPayload>(req)\n\n switch (ctx.type) {\n case 'message_created':\n await Promise.all(\n botState.messageHandlers.map((handler) =>\n handler({\n client,\n user: body.event.payload.user as any,\n conversation: body.event.payload.conversation as any,\n message: body.event.payload.message as any,\n event: body.event,\n ctx,\n })\n )\n )\n break\n case 'state_expired':\n await Promise.all(\n botState.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n state: body.event.payload.state as any,\n ctx,\n })\n )\n )\n break\n default:\n await Promise.all(\n botState.eventHandlers.map((handler) =>\n handler({\n client,\n event: body.event,\n ctx,\n })\n )\n )\n }\n}\n\n// TODO implement the ping operation once the signature is defined\nasync function onPing(_: OperationHandlerProps) {}\n\nasync function onRegister(_: OperationHandlerProps) {}\n\nasync function onUnregister(_: OperationHandlerProps) {}\n\nfunction parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n\n return JSON.parse(req.body)\n}\n", "import { z } from 'zod'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext<Configuration = any, Type extends string = string> = {\n botId: string\n type: Type\n operation: BotOperation\n configuration: Configuration\n}\n", "import type { Bot as BotType, Event } from '@botpress/client'\nimport type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { createBotHandler } from './server'\nimport type {\n BotState,\n EventHandler,\n MessageHandler,\n RegisterHandler,\n StateExpiredHandler,\n UnregisterHandler,\n} from './state'\n\nexport type RegisterBotPayload = {\n bot: BotType\n}\n\nexport type UnregisterBotPayload = {\n bot: BotType\n}\n\nexport type EventReceivedBotPayload = {\n event: Event\n}\n\nexport type BotDefinitionTags = {\n messages?: string[]\n conversations?: string[]\n users?: string[]\n}\n\nexport type BotDefinitionStateType = 'conversation' | 'user' | 'bot'\nexport type BotDefinitionState = {\n type: BotDefinitionStateType\n schema: Record<string, any>\n expiry?: number\n}\n\nexport type IntegrationInstance = {\n enabled: boolean\n id: string\n configuration: { [key: string]: any }\n}\n\nexport type BotDefinitionRecurringEvent = {\n type: string\n payload: Record<string, any>\n schedule: {\n cron: string\n }\n}\n\nexport type BotDefinitionEvent = {\n schema: Record<string, any>\n}\n\nexport type BotDefinitionConfiguration = {\n schema: Record<string, any>\n}\n\nexport type BotDefinition = {\n tags?: BotDefinitionTags\n states?: Record<string, BotDefinitionState>\n integrations?: IntegrationInstance[]\n configuration?: BotDefinitionConfiguration\n events?: Record<string, BotDefinitionEvent>\n recurringEvents?: Record<string, BotDefinitionRecurringEvent>\n}\n\nexport class Bot {\n private _state: BotState = {\n registerHandlers: [],\n unregisterHandlers: [],\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly tags?: BotDefinitionTags\n public readonly states?: Record<string, BotDefinitionState>\n public readonly integrations?: IntegrationInstance[]\n public readonly configuration?: BotDefinitionConfiguration\n public readonly events?: Record<string, BotDefinitionEvent>\n public readonly recurringEvents?: Record<string, BotDefinitionRecurringEvent>\n\n public constructor(def: BotDefinition = {}) {\n this.tags = def.tags\n this.states = def.states\n this.integrations = def.integrations\n this.configuration = def.configuration\n this.events = def.events\n this.recurringEvents = def.recurringEvents\n }\n\n public register = (_handler: RegisterHandler): void => {}\n public unregister = (_handler: UnregisterHandler): void => {}\n public message = (_type: string, handler: MessageHandler): void => {\n this._state.messageHandlers.push(handler)\n }\n public conversation = (_type: string, _handler: MessageHandler): void => {}\n public user = (_type: string, _handler: MessageHandler): void => {}\n public event = (_type: string, handler: EventHandler): void => {\n this._state.eventHandlers.push(handler)\n }\n public stateExpired = (_type: string, handler: StateExpiredHandler): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public handler = createBotHandler(this._state)\n public start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { Conversation, RuntimeError, Message, User } from '@botpress/client'\nimport axiosGlobal, { Axios as AxiosInstance } from 'axios'\nimport {\n botIdHeader,\n operationHeader,\n integrationIdHeader,\n configurationHeader,\n botUserIdHeader,\n webhookIdHeader,\n} from '../const'\nimport type { IntegrationContext, IntegrationOperation } from './context'\nimport { runtimeErrorSchema } from './error'\nimport type {\n ActionPayload,\n CreateConversationPayload,\n CreateUserPayload,\n MessagePayload,\n RegisterPayload,\n UnregisterPayload,\n WebhookPayload,\n} from './implementation'\n\ntype Props<T = any> = {\n url: string\n data: T\n} & Omit<IntegrationContext, 'operation'>\n\n/**\n * @description Meant to query your integration server directly (e.g. without going through the Botpress API)\n */\nexport class IntegrationClient {\n private axios: AxiosInstance\n\n public constructor(axiosInstance?: AxiosInstance) {\n this.axios = axiosInstance ?? axiosGlobal.create({ timeout: 5000 })\n }\n\n public actionTriggered = (props: Props<ActionPayload<string, any>>) => request('action_triggered', props, this.axios)\n public messageCreated = (props: Props<MessagePayload<any, Message, Conversation, User>>) =>\n request('message_created', props, this.axios)\n public register = (props: Props<RegisterPayload>) => request('register', props, this.axios)\n public unregister = (props: Props<UnregisterPayload>) => request('unregister', props, this.axios)\n public webhookReceived = (props: Props<WebhookPayload>) => webhookRequest('webhook_received', props, this.axios)\n public createUser = (props: Props<CreateUserPayload>) =>\n request<{ user: { id: User['id'] } }>('create_user', props, this.axios)\n public createConversation = (props: Props<CreateConversationPayload>) =>\n request<{ conversation: { id: Conversation['id'] } }>('create_conversation', props, this.axios)\n}\n\nexport function formatIntegrationHeaders(ctx: IntegrationContext) {\n return {\n [botIdHeader]: ctx.botId,\n [operationHeader]: ctx.operation,\n [botUserIdHeader]: ctx.botUserId,\n [integrationIdHeader]: ctx.integrationId,\n [webhookIdHeader]: ctx.webhookId,\n [configurationHeader]: Buffer.from(\n typeof ctx.configuration === 'string' ? ctx.configuration : JSON.stringify(ctx.configuration),\n 'utf-8'\n ).toString('base64'),\n }\n}\n\nasync function webhookRequest(operation: IntegrationOperation, { url, data, ...ctx }: Props, axios: AxiosInstance) {\n const response = await axios\n .post<unknown>(url, data, {\n headers: formatIntegrationHeaders({\n ...ctx,\n operation,\n }),\n })\n .catch((e) => {\n if (axiosGlobal.isAxiosError(e) && e.response?.status && e.response.status < 500) {\n return e.response\n }\n\n throw e\n })\n\n return response\n}\n\nasync function request<O = any>(operation: IntegrationOperation, { url, data, ...ctx }: Props, axios: AxiosInstance) {\n try {\n const response = await axios.post<O>(url, data, {\n headers: formatIntegrationHeaders({\n ...ctx,\n operation,\n }),\n })\n\n return response\n } catch (e) {\n const runtimeErrorCode = new RuntimeError('').code\n if (axiosGlobal.isAxiosError(e) && e.response?.status === runtimeErrorCode) {\n const result = runtimeErrorSchema.safeParse(e.response.data)\n if (result.success) {\n throw new RuntimeError(result.data.message)\n }\n }\n throw e\n }\n}\n", "import { RuntimeError } from '@botpress/client'\nimport { z } from 'zod'\n\n// simply used to build the schema\nconst e = new RuntimeError('')\n\nexport const runtimeErrorSchema = z.object({\n code: z.literal(e.code),\n type: z.literal(e.type),\n message: z.string(),\n})\n", "import { z } from 'zod'\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 type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n", "import { mapValues } from 'radash'\nimport { z } from 'zod'\n\nimport { SchemaDefinition, schemaDefinitionToJsonSchema } from './schema'\n\nconst nonEmptyDict = <V extends z.ZodTypeAny>(v: V) => {\n const r = z.record(v)\n return {\n min: (n: number) =>\n r.refine((obj) => Object.keys(obj).length >= n, { message: `At least ${n} item(s) must be defined` }),\n }\n}\n\nexport const schemaSchema = z.object({}).passthrough()\n\nexport const configurationDefinitionSchema = z.object({\n schema: schemaSchema,\n})\n\nexport const eventDefinitionSchema = z.object({\n schema: schemaSchema,\n})\n\nexport const actionDefinitionSchema = z.object({\n input: z.object({\n schema: schemaSchema,\n }),\n output: z.object({\n schema: schemaSchema,\n }),\n})\n\nexport const messageDefinitionSchema = z.object({\n schema: schemaSchema,\n})\n\nexport const tagsDefinitionSchema = z.object({\n conversations: z.array(z.string()).optional(),\n users: z.array(z.string()).optional(),\n messages: z.array(z.string()).optional(),\n})\n\nexport const channelDefinitionSchema = z.object({\n tags: tagsDefinitionSchema.omit({ users: true }).optional(),\n messages: nonEmptyDict(messageDefinitionSchema).min(1),\n conversation: z\n .object({\n creation: z.object({\n enabled: z.boolean(),\n requiredTags: z.array(z.string()),\n }),\n })\n .optional(),\n})\n\nexport const stateDefinitionSchema = z.object({\n type: z.union([z.literal('integration'), z.literal('conversation'), z.literal('user')]),\n schema: schemaSchema,\n})\n\nconst PUBLIC_VERSION = '0.2.0' as const\nconst PRIVATE_VERSION = '0.0.1' as const\n\nexport const integrationDefinitionSchema = z.object({\n name: z.string(),\n version: z.enum([PRIVATE_VERSION, PUBLIC_VERSION]),\n title: z.string().optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n readme: z.string().optional(),\n tags: tagsDefinitionSchema.pick({ users: true }).optional(),\n configuration: configurationDefinitionSchema.optional(),\n events: z.record(eventDefinitionSchema).optional(),\n actions: z.record(actionDefinitionSchema).optional(),\n channels: z.record(channelDefinitionSchema).optional(),\n states: z.record(stateDefinitionSchema).optional(),\n user: z\n .object({\n creation: z.object({\n enabled: z.boolean(),\n requiredTags: z.array(z.string()),\n }),\n })\n .optional(),\n secrets: z.array(z.string()).optional(),\n})\n\nexport type ConfigurationDefinition = z.infer<typeof configurationDefinitionSchema>\nexport type EventDefinition = z.infer<typeof eventDefinitionSchema>\nexport type TagDefinition = z.infer<typeof tagsDefinitionSchema>\nexport type ChannelDefinition = z.infer<typeof channelDefinitionSchema>\nexport type ActionDefinition = z.infer<typeof actionDefinitionSchema>\nexport type MessageDefinition = z.infer<typeof messageDefinitionSchema>\nexport type StateDefinition = z.infer<typeof stateDefinitionSchema>\n\ntype IntegrationDefinitionInput = z.input<typeof integrationDefinitionSchema>\ntype IntegrationDefinitionOutput = z.infer<typeof integrationDefinitionSchema>\n\ntype AnyZodObject = z.ZodObject<any>\ntype Merge<A extends object, B extends object> = Omit<A, keyof B> & B\ntype Cast<T, U> = T extends U ? T : U\n\ntype BaseConfig = AnyZodObject\ntype BaseEvent = Record<string, AnyZodObject>\ntype BaseAction = Record<string, Record<'input' | 'output', AnyZodObject>>\ntype BaseChannel = Record<string, Record<string, AnyZodObject>>\ntype BaseState = Record<string, AnyZodObject>\n\n// TODO: allow any versions\ntype IntegrationDefinitionVersion =\n | {\n /** Only version 0.2.0 is supported for public integrations yet. This is temporary. */\n version: typeof PUBLIC_VERSION\n }\n | {\n /** Only version 0.0.1 is supported for private integrations yet. This is temporary. */\n version: typeof PRIVATE_VERSION\n }\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig,\n TEvent extends BaseEvent,\n TAction extends BaseAction,\n TChannel extends BaseChannel,\n TState extends BaseState\n> = Omit<\n IntegrationDefinitionOutput,\n 'public' | 'version' | 'configuration' | 'events' | 'actions' | 'channels' | 'states'\n> &\n IntegrationDefinitionVersion & {\n configuration?: Merge<ConfigurationDefinition, SchemaDefinition<TConfig>>\n events?: { [K in keyof TEvent]: Merge<EventDefinition, SchemaDefinition<TEvent[K]>> }\n\n /**\n * TODO:\n * - remove the need to cast\n * - the type inference breaks when using keys \"input\" and \"output\" instead of keyof TAction[K]\n */\n actions?: {\n [K in keyof TAction]: Merge<\n ActionDefinition,\n {\n [L in keyof TAction[K]]: SchemaDefinition<Cast<TAction[K][L], AnyZodObject>>\n }\n >\n }\n\n channels?: {\n [K in keyof TChannel]: Merge<\n ChannelDefinition,\n {\n messages: {\n [L in keyof TChannel[K]]: Merge<MessageDefinition, SchemaDefinition<TChannel[K][L]>>\n }\n }\n >\n }\n\n states?: {\n [K in keyof TState]: Merge<StateDefinition, SchemaDefinition<TState[K]>>\n }\n }\n\nfunction formatIntegrationDefinition(\n definition: IntegrationDefinitionProps<BaseConfig, BaseEvent, BaseAction, BaseChannel, BaseState>\n): IntegrationDefinitionInput {\n return {\n ...definition,\n configuration: definition.configuration\n ? {\n ...definition.configuration,\n schema: schemaDefinitionToJsonSchema(definition.configuration),\n }\n : undefined,\n events: definition.events\n ? mapValues(definition.events, (event) => ({\n ...event,\n schema: schemaDefinitionToJsonSchema(event),\n }))\n : undefined,\n actions: definition.actions\n ? mapValues(definition.actions, (action) => ({\n ...action,\n input: {\n ...action.input,\n schema: schemaDefinitionToJsonSchema(action.input),\n },\n output: {\n ...action.output,\n schema: schemaDefinitionToJsonSchema(action.output),\n },\n }))\n : undefined,\n channels: definition.channels\n ? mapValues(definition.channels, (channel) => ({\n ...channel,\n messages: mapValues(channel.messages, (message) => ({\n ...message,\n schema: schemaDefinitionToJsonSchema(message),\n })),\n }))\n : undefined,\n states: definition.states\n ? mapValues(definition.states, (state) => ({\n ...state,\n schema: schemaDefinitionToJsonSchema(state),\n }))\n : undefined,\n user: definition.user,\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvent extends BaseEvent = BaseEvent,\n TAction extends BaseAction = BaseAction,\n TChannel extends BaseChannel = BaseChannel,\n TState extends BaseState = BaseState\n> {\n public readonly name: IntegrationDefinitionOutput['name']\n public readonly version: IntegrationDefinitionOutput['version']\n public readonly icon: IntegrationDefinitionOutput['icon']\n public readonly readme: IntegrationDefinitionOutput['readme']\n public readonly title: IntegrationDefinitionOutput['title']\n public readonly description: IntegrationDefinitionOutput['description']\n public readonly tags: IntegrationDefinitionOutput['tags']\n public readonly configuration: IntegrationDefinitionOutput['configuration']\n public readonly events: IntegrationDefinitionOutput['events']\n public readonly actions: IntegrationDefinitionOutput['actions']\n public readonly channels: IntegrationDefinitionOutput['channels']\n public readonly states: IntegrationDefinitionOutput['states']\n public readonly user: IntegrationDefinitionOutput['user']\n public readonly secrets: IntegrationDefinitionOutput['secrets']\n public constructor(props: IntegrationDefinitionProps<TConfig, TEvent, TAction, TChannel, TState>) {\n const integrationDefinitionInput = formatIntegrationDefinition(props)\n const parsed = integrationDefinitionSchema.parse(integrationDefinitionInput)\n\n const {\n name,\n version,\n icon,\n readme,\n title,\n description,\n tags,\n configuration,\n events,\n actions,\n channels,\n states,\n user,\n secrets,\n } = parsed\n this.name = name\n this.version = version\n this.icon = icon\n this.readme = readme\n this.title = title\n this.description = description\n this.tags = tags\n this.configuration = configuration\n this.events = events\n this.actions = actions\n this.channels = channels\n this.states = states\n this.user = user\n this.secrets = secrets\n }\n}\n", "import type { z } from 'zod'\nimport zodToJsonSchema from 'zod-to-json-schema'\nimport type { JsonSchema7Type } from 'zod-to-json-schema/src/parseDef'\nimport type { JsonSchema7ObjectType } from 'zod-to-json-schema/src/parsers/object'\n\ntype JsonSchemaPropertyType = JsonSchema7Type & { title?: string; examples?: any[] }\nconst isObjectSchema = (schema: JsonSchema7Type): schema is JsonSchema7ObjectType => {\n return (schema as any)?.type === 'object'\n}\n\nexport type SchemaOptions<T> = {\n title: string\n examples: T[]\n}\n\ntype IsEmptyObject<T> = keyof T extends never ? true : false\n\nexport type UiDefinition<TSchema extends z.ZodObject<any>> = IsEmptyObject<z.infer<TSchema>> extends true\n ? Record<string, never>\n : {\n [K in keyof z.infer<TSchema>]: Partial<SchemaOptions<z.infer<TSchema>[K]>>\n }\n\nexport type SchemaDefinition<TSchema extends z.ZodObject<any>> = {\n schema: TSchema\n ui?: Partial<UiDefinition<TSchema>>\n}\n\nexport function schemaDefinitionToJsonSchema(\n definition: SchemaDefinition<z.ZodObject<any>>\n): ReturnType<typeof zodToJsonSchema> {\n const schema = zodToJsonSchema(definition.schema, { errorMessages: true })\n if (!isObjectSchema(schema) || !definition.ui) {\n return schema\n }\n\n for (const [key, value] of Object.entries(definition.ui ?? {})) {\n const property = schema.properties?.[key] as JsonSchemaPropertyType | undefined\n\n if (!property) {\n continue\n }\n\n if (!!value?.title) {\n property.title = value.title\n }\n\n if (!!value?.examples) {\n property.examples = value.examples\n }\n }\n\n return schema\n}\n", "import { Client, Conversation, Message, User, RuntimeError } from '@botpress/client'\n\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\nimport { Request, Response, serve } from '../serve'\nimport { IntegrationContext, integrationOperationSchema } from './context'\nimport type {\n ActionPayload,\n CreateConversationPayload,\n CreateUserPayload,\n IntegrationImplementationProps as Integration,\n RegisterPayload,\n UnregisterPayload,\n WebhookPayload,\n} from './implementation'\n\ntype OperationHandlerProps = {\n integration: Integration\n ctx: IntegrationContext\n req: Request\n client: Client\n}\n\nexport const serveIntegration = async (integration: Integration, port = 6853) => {\n await serve(integrationHandler(integration), port)\n}\n\nexport const integrationHandler =\n (integration: Integration) =>\n // eslint-disable-next-line complexity\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n const client = new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n\n const props: OperationHandlerProps = {\n integration,\n ctx,\n req,\n client,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook(props)\n break\n case 'register':\n response = await onRegister(props)\n break\n case 'unregister':\n response = await onUnregister(props)\n break\n case 'message_created':\n response = await onMessageCreated(props)\n break\n case 'action_triggered':\n response = await onActionTriggered(props)\n break\n case 'ping':\n response = await onPing(props)\n break\n case 'create_user':\n response = await onCreateUser(props)\n break\n case 'create_conversation':\n response = await onCreateConversation(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (e) {\n if (e instanceof RuntimeError) {\n return { status: e.code, body: JSON.stringify(e.toJSON()) }\n } else {\n throw e\n }\n }\n }\n\nfunction extractContext(headers: Record<string, string | undefined>): IntegrationContext {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n\nfunction parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n\n return JSON.parse(req.body)\n}\n\n// TODO implement the ping operation once the signature is defined\nasync function onPing(_: OperationHandlerProps) {}\n\nasync function onWebhook({ client, ctx, integration, req: incomingRequest }: OperationHandlerProps) {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return integration.handler({ client, ctx, req })\n}\n\nasync function onRegister({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.register) {\n return\n }\n\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n\n await integration.register({ client, ctx, webhookUrl })\n}\n\nasync function onUnregister({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.unregister) {\n return\n }\n\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n\n await integration.unregister({ ctx, webhookUrl, client })\n}\n\nasync function onCreateUser({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.createUser) {\n return\n }\n\n const { tags } = parseBody<CreateUserPayload>(req)\n\n return await integration.createUser({ ctx, client, tags })\n}\n\nasync function onCreateConversation({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.createConversation) {\n return\n }\n\n const { channel, tags } = parseBody<CreateConversationPayload>(req)\n\n return await integration.createConversation({ ctx, client, channel, tags })\n}\n\nexport type MessageCreatedPayload = {\n conversation: Conversation\n user: User\n message: Message\n payload: any\n type: string\n}\n\nasync function onMessageCreated({ ctx, integration, req, client }: OperationHandlerProps) {\n const { conversation, user, type, payload, message } = parseBody<MessageCreatedPayload>(req)\n\n const channelHandler = integration.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n const ack = async ({ tags }: { tags: { [key: string]: string } }) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack })\n}\n\nasync function onActionTriggered({ req, integration, ctx, client }: OperationHandlerProps) {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = integration.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import type { Client, Conversation, Message, User } from '@botpress/client'\nimport type { Server } from 'node:http'\nimport { Request, Response, serve } from '../serve'\nimport type { IntegrationContext } from './context'\nimport { integrationHandler } from './server'\n\ntype IntegrationProps<Configuration> = {\n ctx: IntegrationContext<Configuration>\n client: Client\n}\n\nexport type RegisterPayload = {\n webhookUrl: string\n}\n\nexport type UnregisterPayload = {\n webhookUrl: string\n}\n\nexport type WebhookPayload = {\n req: Request\n}\n\nexport type ActionPayload<T, I> = {\n type: T\n input: I\n}\n\nexport type EventPayload<E> = {\n event: E\n}\n\nexport type CreateUserPayload = {\n tags: Tags\n}\n\nexport type CreateConversationPayload = {\n channel: string\n tags: Tags\n}\n\ntype Tags = { [key: string]: string }\n\nexport type AckFunction = (props: { tags: Tags }) => Promise<void>\n\nexport type MessagePayload<P, M, C, U> = {\n payload: P\n conversation: C\n message: M\n user: U\n type: string\n}\n\nexport type ActionDefinitions = {\n [actionType: string]: {\n input: any\n output: any\n }\n}\n\nexport type ChannelDefinitions = {\n [channelName: string]: MessageDefinitions\n}\n\nexport type EventDefinitions = {\n [eventName: string]: any\n}\n\ntype MessageDefinitions = {\n [messageType: string]: any\n}\n\ntype ActionFunctions<Configuration, A extends ActionDefinitions> = {\n [actionType in keyof A]: (\n props: IntegrationProps<Configuration> & ActionPayload<actionType, A[actionType]['input']>\n ) => Promise<A[actionType]['output']>\n}\n\ntype MessageHandlerProps = {\n ack: AckFunction\n}\n\nexport type ChannelFunctions<Configuration, C extends ChannelDefinitions> = {\n [channelName in keyof C]: {\n messages: {\n [messageType in keyof C[channelName]]: (\n props: IntegrationProps<Configuration> &\n MessagePayload<C[channelName][messageType], Message, Conversation, User> &\n MessageHandlerProps\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationImplementationProps<\n Configuration = any,\n Actions extends ActionDefinitions = any,\n Channels extends ChannelDefinitions = any,\n _Events extends EventDefinitions = any\n> = {\n register: (props: IntegrationProps<Configuration> & RegisterPayload) => Promise<void>\n unregister: (props: IntegrationProps<Configuration> & UnregisterPayload) => Promise<void>\n handler: (props: IntegrationProps<Configuration> & WebhookPayload) => Promise<Response | void>\n createUser?: (props: IntegrationProps<Configuration> & CreateUserPayload) => Promise<Response | void>\n createConversation?: (props: IntegrationProps<Configuration> & CreateConversationPayload) => Promise<Response | void>\n actions: ActionFunctions<Configuration, Actions>\n channels: ChannelFunctions<Configuration, Channels>\n}\n\nexport class IntegrationImplementation<\n Configuration = any,\n Actions extends ActionDefinitions = any,\n Channels extends ChannelDefinitions = any,\n Events extends EventDefinitions = any\n> {\n public readonly props: IntegrationImplementationProps<Configuration, Actions, Channels, Events>\n public readonly actions: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['actions']\n public readonly channels: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['channels']\n public readonly register: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['register']\n public readonly unregister: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['unregister']\n public readonly createUser: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['createUser']\n public readonly createConversation: IntegrationImplementationProps<\n Configuration,\n Actions,\n Channels,\n Events\n >['createConversation']\n public readonly handler: ReturnType<typeof integrationHandler>\n public readonly start: (port?: number) => Promise<Server>\n\n public constructor(props: IntegrationImplementationProps<Configuration, Actions, Channels, Events>) {\n this.props = props\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.handler = integrationHandler(props)\n this.start = (port?: number) => serve(this.handler, port)\n }\n}\n", "import { z } from 'zod'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nexport const defaults = {\n text: { schema: textMessageSchema },\n markdown: { schema: markdownMessageSchema },\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} as const // should use satisfies operator but this works for older versions of TS\n"],
5
- "mappings": "qkBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,SAAAE,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,YAAAC,GAAA,wBAAAC,EAAA,wBAAAC,EAAA,aAAAC,EAAA,oBAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAAf,ICAA,IAAAgB,EAAoD,oBCA7C,IAAMC,EAAc,WACdC,EAAkB,gBAClBC,EAAsB,mBACtBC,EAAkB,eAElBC,EAAsB,qBACtBC,EAAkB,iBAClBC,EAAa,YDUnB,IAAMC,EAAN,KAAgB,CACb,MAED,YAAYC,EAA+B,CAChD,KAAK,MAAQA,GAAiB,EAAAC,QAAY,OAAO,CAAE,QAAS,GAAK,CAAC,CACpE,CAEO,SAAYC,GAAqCC,EAAQ,WAAYD,EAAO,KAAK,KAAK,EACtF,WAAcA,GAAuCC,EAAQ,aAAcD,EAAO,KAAK,KAAK,EAC5F,cAAiBA,GAA0CC,EAAQ,iBAAkBD,EAAO,KAAK,KAAK,CAC/G,EAEO,SAASE,GAAiBC,EAAiB,CAChD,MAAO,CACL,CAACC,CAAU,EAAGD,EAAI,KAClB,CAACE,CAAW,EAAGF,EAAI,MACnB,CAACG,CAAe,EAAGH,EAAI,UACvB,CAACI,CAAmB,EAAG,OAAO,KAC5B,OAAOJ,EAAI,eAAkB,SAAWA,EAAI,cAAgB,KAAK,UAAUA,EAAI,aAAa,EAC5F,OACF,EAAE,SAAS,QAAQ,CACrB,CACF,CAEA,eAAeF,EAAiBO,EAAyB,CAAE,IAAAC,EAAK,KAAAC,EAAM,GAAGP,CAAI,EAAUQ,EAAsB,CAQ3G,OAPiB,MAAMA,EAAM,KAAQF,EAA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AO,EAAE,SAAS,EAC7B,MAAO,IAAE,OAAO,EAAE,SAAS,CAC7B,CAAC,EAEKC,GAAa,IAAE,OAAO,CAC1B,MAAOR,EACP,SAAUA,EAAe,SAAS,EAClC,SAAUA,EAAe,SAAS,EAClC,QAAS,IAAE,MACT,IAAE,OAAO,CACP,OAAQ,IAAE,KAAK,CAAC,WAAY,MAAO,KAAK,CAAC,EACzC,MAAOA,EACP,MAAOA,CACT,CAAC,CACH,CACF,CAAC,EAEKS,GAAe,IAAE,OAAO,CAC5B,KAAMT,EACN,QAAS,IAAE,MACT,IAAE,OAAO,CACP,MAAOA,EACP,MAAOA,CACT,CAAC,CACH,CACF,CAAC,EAEKU,GAAiB,IAAE,OAAO,CAC9B,MAAO,IAAE,MAAMF,EAAU,CAC3B,CAAC,EAEYV,GAAW,CACtB,KAAM,CAAE,OAAQG,EAAkB,EAClC,SAAU,CAAE,OAAQC,EAAsB,EAC1C,MAAO,CAAE,OAAQC,EAAmB,EACpC,MAAO,CAAE,OAAQC,EAAmB,EACpC,MAAO,CAAE,OAAQC,EAAmB,EACpC,KAAM,CAAE,OAAQC,EAAkB,EAClC,SAAU,CAAE,OAAQC,EAAsB,EAC1C,SAAU,CAAE,OAAQG,EAAe,EACnC,KAAM,CAAE,OAAQF,EAAW,EAC3B,SAAU,CAAE,OAAQC,EAAa,EACjC,OAAQ,CAAE,OAAQA,EAAa,CACjC,EfvEO,IAAME,GAAU,CAAE,kBAAAC,EAAmB,UAAAC,CAAU",
6
- "names": ["src_exports", "__export", "Bot", "IntegrationImplementation", "IntegrationDefinition", "botIdHeader", "botUserIdHeader", "clients", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "import_axios", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "BotClient", "axiosInstance", "axiosGlobal", "props", "request", "formatBotHeaders", "ctx", "typeHeader", "botIdHeader", "operationHeader", "configurationHeader", "operation", "url", "data", "axios", "import_node_http", "log", "serve", "handler", "port", "callback", "defaultCallback", "server", "req", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "import_client", "import_zod", "botOperationSchema", "createBotHandler", "botState", "req", "ctx", "extractContext", "log", "client", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "botOperationSchema", "operationHeader", "body", "parseBody", "handler", "_", "Bot", "def", "_handler", "_type", "handler", "createBotHandler", "port", "serve", "import_client", "import_axios", "import_client", "import_zod", "e", "runtimeErrorSchema", "IntegrationClient", "axiosInstance", "axiosGlobal", "props", "request", "webhookRequest", "formatIntegrationHeaders", "ctx", "botIdHeader", "operationHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operation", "url", "data", "axios", "e", "runtimeErrorCode", "result", "runtimeErrorSchema", "import_zod", "integrationOperationSchema", "import_radash", "import_zod", "import_zod_to_json_schema", "isObjectSchema", "schema", "schemaDefinitionToJsonSchema", "definition", "zodToJsonSchema", "key", "value", "property", "nonEmptyDict", "v", "r", "obj", "schemaSchema", "configurationDefinitionSchema", "eventDefinitionSchema", "actionDefinitionSchema", "messageDefinitionSchema", "tagsDefinitionSchema", "channelDefinitionSchema", "stateDefinitionSchema", "PUBLIC_VERSION", "PRIVATE_VERSION", "integrationDefinitionSchema", "formatIntegrationDefinition", "definition", "schemaDefinitionToJsonSchema", "event", "action", "channel", "message", "state", "IntegrationDefinition", "props", "integrationDefinitionInput", "parsed", "name", "version", "icon", "readme", "title", "description", "tags", "configuration", "events", "actions", "channels", "states", "user", "secrets", "import_client", "integrationHandler", "integration", "req", "ctx", "extractContext", "client", "props", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "e", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "integrationOperationSchema", "operationHeader", "parseBody", "_", "incomingRequest", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "message_exports", "__export", "defaults", "import_zod", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "clients", "IntegrationClient", "BotClient"]
4
+ "sourcesContent": ["import { BotClient } from './bot'\nimport { IntegrationClient } from './integration'\n\nexport * as messages from './message'\nexport const clients = { IntegrationClient, BotClient }\n\nexport * from './const'\nexport * from './serve'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationOperation,\n ActionDefinitions,\n ChannelDefinitions,\n EventDefinitions,\n AckFunction,\n} from './integration'\nexport { Bot, BotContext, BotOperation, IntegrationInstance } from './bot'\n", "import axiosGlobal, { Axios as AxiosInstance } from 'axios'\nimport type { Merge, Except } from 'type-fest'\nimport { botIdHeader, operationHeader, configurationHeader, typeHeader } from '../const'\nimport type { BotContext, BotOperation } from './context'\nimport type { RegisterBotPayload, UnregisterBotPayload, EventReceivedBotPayload } from './implementation'\n\ntype Props<T = any> = Merge<\n Except<BotContext, 'operation'>,\n {\n url: string\n data: T\n }\n>\n\n/**\n * @description Meant to query your bot server directly (e.g. without going through the Botpress API)\n */\nexport class BotClient {\n private axios: AxiosInstance\n\n public constructor(axiosInstance?: AxiosInstance) {\n this.axios = axiosInstance ?? axiosGlobal.create({ timeout: 5000 })\n }\n\n public register = (props: Props<RegisterBotPayload>) => request('register', props, this.axios)\n public unregister = (props: Props<UnregisterBotPayload>) => request('unregister', props, this.axios)\n public eventReceived = (props: Props<EventReceivedBotPayload>) => request('event_received', props, this.axios)\n}\n\nexport function formatBotHeaders(ctx: BotContext) {\n return {\n [typeHeader]: ctx.type,\n [botIdHeader]: ctx.botId,\n [operationHeader]: ctx.operation,\n [configurationHeader]: Buffer.from(\n typeof ctx.configuration === 'string' ? ctx.configuration : JSON.stringify(ctx.configuration),\n 'utf-8'\n ).toString('base64'),\n }\n}\n\nasync function request<O = any>(operation: BotOperation, { url, data, ...ctx }: Props, axios: AxiosInstance) {\n const response = await axios.post<O>(url, data, {\n headers: formatBotHeaders({\n ...ctx,\n operation,\n }),\n })\n\n return response.data\n}\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { Client } from '@botpress/client'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\nimport { log } from '../log'\nimport type { Handler, Request, Response } from '../serve'\nimport { BotContext, botOperationSchema } from './context'\nimport type { EventReceivedBotPayload } from './implementation'\nimport type { BotState } from './state'\n\ntype OperationHandlerProps = {\n botState: BotState\n ctx: BotContext\n client: Client\n req: Request\n}\n\nexport const createBotHandler =\n (botState: BotState): Handler =>\n async (req: Request): Promise<Response> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const client = new Client({ botId: ctx.botId })\n\n const props: OperationHandlerProps = {\n req,\n botState,\n ctx,\n client,\n }\n\n switch (ctx.operation) {\n case 'event_received':\n await onEventReceived(props)\n break\n case 'register':\n await onRegister(props)\n break\n case 'unregister':\n await onUnregister(props)\n break\n case 'ping':\n await onPing(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nfunction extractContext(headers: Record<string, string | undefined>): BotContext {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n\nasync function onEventReceived({ botState, ctx, req }: OperationHandlerProps) {\n log.debug(`Received event ${ctx.type}`)\n\n const client = new Client({ botId: ctx.botId })\n\n const body = parseBody<EventReceivedBotPayload>(req)\n\n switch (ctx.type) {\n case 'message_created':\n await Promise.all(\n botState.messageHandlers.map((handler) =>\n handler({\n client,\n user: body.event.payload.user as any,\n conversation: body.event.payload.conversation as any,\n message: body.event.payload.message as any,\n event: body.event,\n ctx,\n })\n )\n )\n break\n case 'state_expired':\n await Promise.all(\n botState.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n state: body.event.payload.state as any,\n ctx,\n })\n )\n )\n break\n default:\n await Promise.all(\n botState.eventHandlers.map((handler) =>\n handler({\n client,\n event: body.event,\n ctx,\n })\n )\n )\n }\n}\n\n// TODO implement the ping operation once the signature is defined\nasync function onPing(_: OperationHandlerProps) {}\n\nasync function onRegister(_: OperationHandlerProps) {}\n\nasync function onUnregister(_: OperationHandlerProps) {}\n\nfunction parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n\n return JSON.parse(req.body)\n}\n", "import { z } from 'zod'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext<Configuration = any, Type extends string = string> = {\n botId: string\n type: Type\n operation: BotOperation\n configuration: Configuration\n}\n", "import type { Bot as BotType, Event } from '@botpress/client'\nimport type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { createBotHandler } from './server'\nimport type {\n BotState,\n EventHandler,\n MessageHandler,\n RegisterHandler,\n StateExpiredHandler,\n UnregisterHandler,\n} from './state'\n\nexport type RegisterBotPayload = {\n bot: BotType\n}\n\nexport type UnregisterBotPayload = {\n bot: BotType\n}\n\nexport type EventReceivedBotPayload = {\n event: Event\n}\n\nexport type BotDefinitionTag = {\n title?: string\n description?: string\n}\n\nexport type BotDefinitionStateType = 'conversation' | 'user' | 'bot'\nexport type BotDefinitionState = {\n type: BotDefinitionStateType\n schema: Record<string, any>\n expiry?: number\n}\n\nexport type IntegrationInstance = {\n enabled: boolean\n id: string\n configuration: { [key: string]: any }\n}\n\nexport type BotDefinitionRecurringEvent = {\n type: string\n payload: Record<string, any>\n schedule: {\n cron: string\n }\n}\n\nexport type BotDefinitionEvent = {\n schema: Record<string, any>\n}\n\nexport type BotDefinitionConfiguration = {\n schema: Record<string, any>\n}\n\nexport type BotDefinitionUser = {\n tags?: Record<string, BotDefinitionTag>\n}\n\nexport type BotDefinitionConversation = {\n tags?: Record<string, BotDefinitionTag>\n}\n\nexport type BotDefinitionMessage = {\n tags?: Record<string, BotDefinitionTag>\n}\n\nexport type BotDefinition = {\n user?: BotDefinitionUser\n conversation?: BotDefinitionConversation\n message?: BotDefinitionMessage\n states?: Record<string, BotDefinitionState>\n integrations?: IntegrationInstance[]\n configuration?: BotDefinitionConfiguration\n events?: Record<string, BotDefinitionEvent>\n recurringEvents?: Record<string, BotDefinitionRecurringEvent>\n}\n\nexport class Bot {\n private _state: BotState = {\n registerHandlers: [],\n unregisterHandlers: [],\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly definition: BotDefinition\n\n public constructor(def: BotDefinition = {}) {\n this.definition = def\n }\n\n public register = (_handler: RegisterHandler): void => {}\n public unregister = (_handler: UnregisterHandler): void => {}\n public message = (_type: string, handler: MessageHandler): void => {\n this._state.messageHandlers.push(handler)\n }\n public conversation = (_type: string, _handler: MessageHandler): void => {}\n public user = (_type: string, _handler: MessageHandler): void => {}\n public event = (_type: string, handler: EventHandler): void => {\n this._state.eventHandlers.push(handler)\n }\n public stateExpired = (_type: string, handler: StateExpiredHandler): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public handler = createBotHandler(this._state)\n public start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { Conversation, RuntimeError, Message, User } from '@botpress/client'\nimport axiosGlobal, { Axios as AxiosInstance } from 'axios'\nimport {\n botIdHeader,\n operationHeader,\n integrationIdHeader,\n configurationHeader,\n botUserIdHeader,\n webhookIdHeader,\n} from '../const'\nimport type { IntegrationContext, IntegrationOperation } from './context'\nimport { runtimeErrorSchema } from './error'\nimport type {\n ActionPayload,\n CreateConversationPayload,\n CreateUserPayload,\n MessagePayload,\n RegisterPayload,\n UnregisterPayload,\n WebhookPayload,\n} from './implementation'\n\ntype Props<T = any> = {\n url: string\n data: T\n} & Omit<IntegrationContext, 'operation'>\n\n/**\n * @description Meant to query your integration server directly (e.g. without going through the Botpress API)\n */\nexport class IntegrationClient {\n private axios: AxiosInstance\n\n public constructor(axiosInstance?: AxiosInstance) {\n this.axios = axiosInstance ?? axiosGlobal.create({ timeout: 5000 })\n }\n\n public actionTriggered = (props: Props<ActionPayload<string, any>>) => request('action_triggered', props, this.axios)\n public messageCreated = (props: Props<MessagePayload<any, Message, Conversation, User>>) =>\n request('message_created', props, this.axios)\n public register = (props: Props<RegisterPayload>) => request('register', props, this.axios)\n public unregister = (props: Props<UnregisterPayload>) => request('unregister', props, this.axios)\n public webhookReceived = (props: Props<WebhookPayload>) => webhookRequest('webhook_received', props, this.axios)\n public createUser = (props: Props<CreateUserPayload>) =>\n request<{ user: { id: User['id'] } }>('create_user', props, this.axios)\n public createConversation = (props: Props<CreateConversationPayload>) =>\n request<{ conversation: { id: Conversation['id'] } }>('create_conversation', props, this.axios)\n}\n\nexport function formatIntegrationHeaders(ctx: IntegrationContext) {\n return {\n [botIdHeader]: ctx.botId,\n [operationHeader]: ctx.operation,\n [botUserIdHeader]: ctx.botUserId,\n [integrationIdHeader]: ctx.integrationId,\n [webhookIdHeader]: ctx.webhookId,\n [configurationHeader]: Buffer.from(\n typeof ctx.configuration === 'string' ? ctx.configuration : JSON.stringify(ctx.configuration),\n 'utf-8'\n ).toString('base64'),\n }\n}\n\nasync function webhookRequest(operation: IntegrationOperation, { url, data, ...ctx }: Props, axios: AxiosInstance) {\n const response = await axios\n .post<unknown>(url, data, {\n headers: formatIntegrationHeaders({\n ...ctx,\n operation,\n }),\n })\n .catch((e) => {\n if (axiosGlobal.isAxiosError(e) && e.response?.status && e.response.status < 500) {\n return e.response\n }\n\n throw e\n })\n\n return response\n}\n\nasync function request<O = any>(operation: IntegrationOperation, { url, data, ...ctx }: Props, axios: AxiosInstance) {\n try {\n const response = await axios.post<O>(url, data, {\n headers: formatIntegrationHeaders({\n ...ctx,\n operation,\n }),\n })\n\n return response\n } catch (e) {\n const runtimeErrorCode = new RuntimeError('').code\n if (axiosGlobal.isAxiosError(e) && e.response?.status === runtimeErrorCode) {\n const result = runtimeErrorSchema.safeParse(e.response.data)\n if (result.success) {\n throw new RuntimeError(result.data.message)\n }\n }\n throw e\n }\n}\n", "import { RuntimeError } from '@botpress/client'\nimport { z } from 'zod'\n\n// simply used to build the schema\nconst e = new RuntimeError('')\n\nexport const runtimeErrorSchema = z.object({\n code: z.literal(e.code),\n type: z.literal(e.type),\n message: z.string(),\n})\n", "import { z } from 'zod'\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 type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n", "import { mapValues } from 'radash'\nimport { z } from 'zod'\n\nimport { SchemaDefinition, schemaDefinitionToJsonSchema } from './schema'\n\nconst nonEmptyDict = <V extends z.ZodTypeAny>(v: V) => {\n const r = z.record(v)\n return {\n min: (n: number) =>\n r.refine((obj) => Object.keys(obj).length >= n, { message: `At least ${n} item(s) must be defined` }),\n }\n}\n\nexport const schemaSchema = z.object({}).passthrough()\n\nexport const configurationDefinitionSchema = z.object({\n schema: schemaSchema,\n})\n\nexport const eventDefinitionSchema = z.object({\n schema: schemaSchema,\n})\n\nexport const actionDefinitionSchema = z.object({\n input: z.object({\n schema: schemaSchema,\n }),\n output: z.object({\n schema: schemaSchema,\n }),\n})\n\nexport const messageDefinitionSchema = z.object({\n schema: schemaSchema,\n})\n\nexport const tagDefinitionSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n})\n\nexport const channelDefinitionSchema = z.object({\n messages: nonEmptyDict(messageDefinitionSchema).min(1),\n message: z\n .object({\n tags: z.record(tagDefinitionSchema),\n })\n .partial()\n .optional(),\n conversation: z\n .object({\n tags: z.record(tagDefinitionSchema),\n creation: z.object({\n enabled: z.boolean(),\n requiredTags: z.array(z.string()),\n }),\n })\n .partial()\n .optional(),\n})\n\nexport const stateDefinitionSchema = z.object({\n type: z.union([z.literal('integration'), z.literal('conversation'), z.literal('user')]),\n schema: schemaSchema,\n})\n\nconst PUBLIC_VERSION = '0.2.0' as const\nconst PRIVATE_VERSION = '0.0.1' as const\n\nexport const integrationDefinitionSchema = z.object({\n name: z.string(),\n version: z.enum([PRIVATE_VERSION, PUBLIC_VERSION]),\n title: z.string().optional(),\n description: z.string().optional(),\n icon: z.string().optional(),\n readme: z.string().optional(),\n configuration: configurationDefinitionSchema.optional(),\n events: z.record(eventDefinitionSchema).optional(),\n actions: z.record(actionDefinitionSchema).optional(),\n channels: z.record(channelDefinitionSchema).optional(),\n states: z.record(stateDefinitionSchema).optional(),\n user: z\n .object({\n tags: z.record(tagDefinitionSchema),\n creation: z.object({\n enabled: z.boolean(),\n requiredTags: z.array(z.string()),\n }),\n })\n .partial()\n .optional(),\n secrets: z.array(z.string()).optional(),\n})\n\nexport type ConfigurationDefinition = z.infer<typeof configurationDefinitionSchema>\nexport type EventDefinition = z.infer<typeof eventDefinitionSchema>\nexport type ChannelDefinition = z.infer<typeof channelDefinitionSchema>\nexport type ActionDefinition = z.infer<typeof actionDefinitionSchema>\nexport type MessageDefinition = z.infer<typeof messageDefinitionSchema>\nexport type StateDefinition = z.infer<typeof stateDefinitionSchema>\n\ntype IntegrationDefinitionInput = z.input<typeof integrationDefinitionSchema>\ntype IntegrationDefinitionOutput = z.infer<typeof integrationDefinitionSchema>\n\ntype AnyZodObject = z.ZodObject<any>\ntype Merge<A extends object, B extends object> = Omit<A, keyof B> & B\ntype Cast<T, U> = T extends U ? T : U\n\ntype BaseConfig = AnyZodObject\ntype BaseEvent = Record<string, AnyZodObject>\ntype BaseAction = Record<string, Record<'input' | 'output', AnyZodObject>>\ntype BaseChannel = Record<string, Record<string, AnyZodObject>>\ntype BaseState = Record<string, AnyZodObject>\n\n// TODO: allow any versions\ntype IntegrationDefinitionVersion =\n | {\n /** Only version 0.2.0 is supported for public integrations yet. This is temporary. */\n version: typeof PUBLIC_VERSION\n }\n | {\n /** Only version 0.0.1 is supported for private integrations yet. This is temporary. */\n version: typeof PRIVATE_VERSION\n }\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig,\n TEvent extends BaseEvent,\n TAction extends BaseAction,\n TChannel extends BaseChannel,\n TState extends BaseState\n> = Omit<\n IntegrationDefinitionOutput,\n 'public' | 'version' | 'configuration' | 'events' | 'actions' | 'channels' | 'states'\n> &\n IntegrationDefinitionVersion & {\n configuration?: Merge<ConfigurationDefinition, SchemaDefinition<TConfig>>\n events?: { [K in keyof TEvent]: Merge<EventDefinition, SchemaDefinition<TEvent[K]>> }\n\n /**\n * TODO:\n * - remove the need to cast\n * - the type inference breaks when using keys \"input\" and \"output\" instead of keyof TAction[K]\n */\n actions?: {\n [K in keyof TAction]: Merge<\n ActionDefinition,\n {\n [L in keyof TAction[K]]: SchemaDefinition<Cast<TAction[K][L], AnyZodObject>>\n }\n >\n }\n\n channels?: {\n [K in keyof TChannel]: Merge<\n ChannelDefinition,\n {\n messages: {\n [L in keyof TChannel[K]]: Merge<MessageDefinition, SchemaDefinition<TChannel[K][L]>>\n }\n }\n >\n }\n\n states?: {\n [K in keyof TState]: Merge<StateDefinition, SchemaDefinition<TState[K]>>\n }\n }\n\nfunction formatIntegrationDefinition(\n definition: IntegrationDefinitionProps<BaseConfig, BaseEvent, BaseAction, BaseChannel, BaseState>\n): IntegrationDefinitionInput {\n return {\n ...definition,\n configuration: definition.configuration\n ? {\n ...definition.configuration,\n schema: schemaDefinitionToJsonSchema(definition.configuration),\n }\n : undefined,\n events: definition.events\n ? mapValues(definition.events, (event) => ({\n ...event,\n schema: schemaDefinitionToJsonSchema(event),\n }))\n : undefined,\n actions: definition.actions\n ? mapValues(definition.actions, (action) => ({\n ...action,\n input: {\n ...action.input,\n schema: schemaDefinitionToJsonSchema(action.input),\n },\n output: {\n ...action.output,\n schema: schemaDefinitionToJsonSchema(action.output),\n },\n }))\n : undefined,\n channels: definition.channels\n ? mapValues(definition.channels, (channel) => ({\n ...channel,\n messages: mapValues(channel.messages, (message) => ({\n ...message,\n schema: schemaDefinitionToJsonSchema(message),\n })),\n }))\n : undefined,\n states: definition.states\n ? mapValues(definition.states, (state) => ({\n ...state,\n schema: schemaDefinitionToJsonSchema(state),\n }))\n : undefined,\n user: definition.user,\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvent extends BaseEvent = BaseEvent,\n TAction extends BaseAction = BaseAction,\n TChannel extends BaseChannel = BaseChannel,\n TState extends BaseState = BaseState\n> {\n public readonly name: IntegrationDefinitionOutput['name']\n public readonly version: IntegrationDefinitionOutput['version']\n public readonly icon: IntegrationDefinitionOutput['icon']\n public readonly readme: IntegrationDefinitionOutput['readme']\n public readonly title: IntegrationDefinitionOutput['title']\n public readonly description: IntegrationDefinitionOutput['description']\n public readonly configuration: IntegrationDefinitionOutput['configuration']\n public readonly events: IntegrationDefinitionOutput['events']\n public readonly actions: IntegrationDefinitionOutput['actions']\n public readonly channels: IntegrationDefinitionOutput['channels']\n public readonly states: IntegrationDefinitionOutput['states']\n public readonly user: IntegrationDefinitionOutput['user']\n public readonly secrets: IntegrationDefinitionOutput['secrets']\n public constructor(props: IntegrationDefinitionProps<TConfig, TEvent, TAction, TChannel, TState>) {\n const integrationDefinitionInput = formatIntegrationDefinition(props)\n const parsed = integrationDefinitionSchema.parse(integrationDefinitionInput)\n\n const {\n name,\n version,\n icon,\n readme,\n title,\n description,\n configuration,\n events,\n actions,\n channels,\n states,\n user,\n secrets,\n } = parsed\n this.name = name\n this.version = version\n this.icon = icon\n this.readme = readme\n this.title = title\n this.description = description\n this.configuration = configuration\n this.events = events\n this.actions = actions\n this.channels = channels\n this.states = states\n this.user = user\n this.secrets = secrets\n }\n}\n", "import type { z } from 'zod'\nimport zodToJsonSchema from 'zod-to-json-schema'\nimport type { JsonSchema7Type } from 'zod-to-json-schema/src/parseDef'\nimport type { JsonSchema7ObjectType } from 'zod-to-json-schema/src/parsers/object'\n\ntype JsonSchemaPropertyType = JsonSchema7Type & { title?: string; examples?: any[] }\nconst isObjectSchema = (schema: JsonSchema7Type): schema is JsonSchema7ObjectType => {\n return (schema as any)?.type === 'object'\n}\n\nexport type SchemaOptions<T> = {\n title: string\n examples: T[]\n}\n\ntype IsEmptyObject<T> = keyof T extends never ? true : false\n\nexport type UiDefinition<TSchema extends z.ZodObject<any>> = IsEmptyObject<z.infer<TSchema>> extends true\n ? Record<string, never>\n : {\n [K in keyof z.infer<TSchema>]: Partial<SchemaOptions<z.infer<TSchema>[K]>>\n }\n\nexport type SchemaDefinition<TSchema extends z.ZodObject<any>> = {\n schema: TSchema\n ui?: Partial<UiDefinition<TSchema>>\n}\n\nexport function schemaDefinitionToJsonSchema(\n definition: SchemaDefinition<z.ZodObject<any>>\n): ReturnType<typeof zodToJsonSchema> {\n const schema = zodToJsonSchema(definition.schema, { errorMessages: true })\n if (!isObjectSchema(schema) || !definition.ui) {\n return schema\n }\n\n for (const [key, value] of Object.entries(definition.ui ?? {})) {\n const property = schema.properties?.[key] as JsonSchemaPropertyType | undefined\n\n if (!property) {\n continue\n }\n\n if (!!value?.title) {\n property.title = value.title\n }\n\n if (!!value?.examples) {\n property.examples = value.examples\n }\n }\n\n return schema\n}\n", "import { Client, Conversation, Message, User, RuntimeError } from '@botpress/client'\n\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\nimport { Request, Response, serve } from '../serve'\nimport { IntegrationContext, integrationOperationSchema } from './context'\nimport type {\n ActionPayload,\n CreateConversationPayload,\n CreateUserPayload,\n IntegrationImplementationProps as Integration,\n RegisterPayload,\n UnregisterPayload,\n WebhookPayload,\n} from './implementation'\n\ntype OperationHandlerProps = {\n integration: Integration\n ctx: IntegrationContext\n req: Request\n client: Client\n}\n\nexport const serveIntegration = async (integration: Integration, port = 6853) => {\n await serve(integrationHandler(integration), port)\n}\n\nexport const integrationHandler =\n (integration: Integration) =>\n // eslint-disable-next-line complexity\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n const client = new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n\n const props: OperationHandlerProps = {\n integration,\n ctx,\n req,\n client,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook(props)\n break\n case 'register':\n response = await onRegister(props)\n break\n case 'unregister':\n response = await onUnregister(props)\n break\n case 'message_created':\n response = await onMessageCreated(props)\n break\n case 'action_triggered':\n response = await onActionTriggered(props)\n break\n case 'ping':\n response = await onPing(props)\n break\n case 'create_user':\n response = await onCreateUser(props)\n break\n case 'create_conversation':\n response = await onCreateConversation(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (e) {\n if (e instanceof RuntimeError) {\n return { status: e.code, body: JSON.stringify(e.toJSON()) }\n } else {\n throw e\n }\n }\n }\n\nfunction extractContext(headers: Record<string, string | undefined>): IntegrationContext {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n\nfunction parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n\n return JSON.parse(req.body)\n}\n\n// TODO implement the ping operation once the signature is defined\nasync function onPing(_: OperationHandlerProps) {}\n\nasync function onWebhook({ client, ctx, integration, req: incomingRequest }: OperationHandlerProps) {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return integration.handler({ client, ctx, req })\n}\n\nasync function onRegister({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.register) {\n return\n }\n\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n\n await integration.register({ client, ctx, webhookUrl })\n}\n\nasync function onUnregister({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.unregister) {\n return\n }\n\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n\n await integration.unregister({ ctx, webhookUrl, client })\n}\n\nasync function onCreateUser({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.createUser) {\n return\n }\n\n const { tags } = parseBody<CreateUserPayload>(req)\n\n return await integration.createUser({ ctx, client, tags })\n}\n\nasync function onCreateConversation({ client, ctx, integration, req }: OperationHandlerProps) {\n if (!integration.createConversation) {\n return\n }\n\n const { channel, tags } = parseBody<CreateConversationPayload>(req)\n\n return await integration.createConversation({ ctx, client, channel, tags })\n}\n\nexport type MessageCreatedPayload = {\n conversation: Conversation\n user: User\n message: Message\n payload: any\n type: string\n}\n\nasync function onMessageCreated({ ctx, integration, req, client }: OperationHandlerProps) {\n const { conversation, user, type, payload, message } = parseBody<MessageCreatedPayload>(req)\n\n const channelHandler = integration.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n const ack = async ({ tags }: { tags: { [key: string]: string } }) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack })\n}\n\nasync function onActionTriggered({ req, integration, ctx, client }: OperationHandlerProps) {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = integration.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import type { Client, Conversation, Message, User } from '@botpress/client'\nimport type { Server } from 'node:http'\nimport { Request, Response, serve } from '../serve'\nimport type { IntegrationContext } from './context'\nimport { integrationHandler } from './server'\n\ntype IntegrationProps<Configuration> = {\n ctx: IntegrationContext<Configuration>\n client: Client\n}\n\nexport type RegisterPayload = {\n webhookUrl: string\n}\n\nexport type UnregisterPayload = {\n webhookUrl: string\n}\n\nexport type WebhookPayload = {\n req: Request\n}\n\nexport type ActionPayload<T, I> = {\n type: T\n input: I\n}\n\nexport type EventPayload<E> = {\n event: E\n}\n\nexport type CreateUserPayload = {\n tags: Tags\n}\n\nexport type CreateConversationPayload = {\n channel: string\n tags: Tags\n}\n\ntype Tags = { [key: string]: string }\n\nexport type AckFunction = (props: { tags: Tags }) => Promise<void>\n\nexport type MessagePayload<P, M, C, U> = {\n payload: P\n conversation: C\n message: M\n user: U\n type: string\n}\n\nexport type ActionDefinitions = {\n [actionType: string]: {\n input: any\n output: any\n }\n}\n\nexport type ChannelDefinitions = {\n [channelName: string]: MessageDefinitions\n}\n\nexport type EventDefinitions = {\n [eventName: string]: any\n}\n\ntype MessageDefinitions = {\n [messageType: string]: any\n}\n\ntype ActionFunctions<Configuration, A extends ActionDefinitions> = {\n [actionType in keyof A]: (\n props: IntegrationProps<Configuration> & ActionPayload<actionType, A[actionType]['input']>\n ) => Promise<A[actionType]['output']>\n}\n\ntype MessageHandlerProps = {\n ack: AckFunction\n}\n\nexport type ChannelFunctions<Configuration, C extends ChannelDefinitions> = {\n [channelName in keyof C]: {\n messages: {\n [messageType in keyof C[channelName]]: (\n props: IntegrationProps<Configuration> &\n MessagePayload<C[channelName][messageType], Message, Conversation, User> &\n MessageHandlerProps\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationImplementationProps<\n Configuration = any,\n Actions extends ActionDefinitions = any,\n Channels extends ChannelDefinitions = any,\n _Events extends EventDefinitions = any\n> = {\n register: (props: IntegrationProps<Configuration> & RegisterPayload) => Promise<void>\n unregister: (props: IntegrationProps<Configuration> & UnregisterPayload) => Promise<void>\n handler: (props: IntegrationProps<Configuration> & WebhookPayload) => Promise<Response | void>\n createUser?: (props: IntegrationProps<Configuration> & CreateUserPayload) => Promise<Response | void>\n createConversation?: (props: IntegrationProps<Configuration> & CreateConversationPayload) => Promise<Response | void>\n actions: ActionFunctions<Configuration, Actions>\n channels: ChannelFunctions<Configuration, Channels>\n}\n\nexport class IntegrationImplementation<\n Configuration = any,\n Actions extends ActionDefinitions = any,\n Channels extends ChannelDefinitions = any,\n Events extends EventDefinitions = any\n> {\n public readonly props: IntegrationImplementationProps<Configuration, Actions, Channels, Events>\n public readonly actions: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['actions']\n public readonly channels: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['channels']\n public readonly register: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['register']\n public readonly unregister: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['unregister']\n public readonly createUser: IntegrationImplementationProps<Configuration, Actions, Channels, Events>['createUser']\n public readonly createConversation: IntegrationImplementationProps<\n Configuration,\n Actions,\n Channels,\n Events\n >['createConversation']\n public readonly handler: ReturnType<typeof integrationHandler>\n public readonly start: (port?: number) => Promise<Server>\n\n public constructor(props: IntegrationImplementationProps<Configuration, Actions, Channels, Events>) {\n this.props = props\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.handler = integrationHandler(props)\n this.start = (port?: number) => serve(this.handler, port)\n }\n}\n", "import { z } from 'zod'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nexport const defaults = {\n text: { schema: textMessageSchema },\n markdown: { schema: markdownMessageSchema },\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} as const // should use satisfies operator but this works for older versions of TS\n"],
5
+ "mappings": "qkBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,SAAAE,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,YAAAC,GAAA,wBAAAC,EAAA,wBAAAC,EAAA,aAAAC,EAAA,oBAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAAf,ICAA,IAAAgB,EAAoD,oBCA7C,IAAMC,EAAc,WACdC,EAAkB,gBAClBC,EAAsB,mBACtBC,EAAkB,eAElBC,EAAsB,qBACtBC,EAAkB,iBAClBC,EAAa,YDUnB,IAAMC,EAAN,KAAgB,CACb,MAED,YAAYC,EAA+B,CAChD,KAAK,MAAQA,GAAiB,EAAAC,QAAY,OAAO,CAAE,QAAS,GAAK,CAAC,CACpE,CAEO,SAAYC,GAAqCC,EAAQ,WAAYD,EAAO,KAAK,KAAK,EACtF,WAAcA,GAAuCC,EAAQ,aAAcD,EAAO,KAAK,KAAK,EAC5F,cAAiBA,GAA0CC,EAAQ,iBAAkBD,EAAO,KAAK,KAAK,CAC/G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CAAC,EAEKM,GAAoB,IAAE,OAAO,CACjC,QAASN,EACT,MAAOA,EAAe,SAAS,CACjC,CAAC,EAEKO,GAAwB,IAAE,OAAO,CACrC,SAAU,IAAE,OAAO,EACnB,UAAW,IAAE,OAAO,EACpB,QAAS,IAAE,OAAO,EAAE,SAAS,EAC7B,MAAO,IAAE,OAAO,EAAE,SAAS,CAC7B,CAAC,EAEKC,GAAa,IAAE,OAAO,CAC1B,MAAOR,EACP,SAAUA,EAAe,SAAS,EAClC,SAAUA,EAAe,SAAS,EAClC,QAAS,IAAE,MACT,IAAE,OAAO,CACP,OAAQ,IAAE,KAAK,CAAC,WAAY,MAAO,KAAK,CAAC,EACzC,MAAOA,EACP,MAAOA,CACT,CAAC,CACH,CACF,CAAC,EAEKS,GAAe,IAAE,OAAO,CAC5B,KAAMT,EACN,QAAS,IAAE,MACT,IAAE,OAAO,CACP,MAAOA,EACP,MAAOA,CACT,CAAC,CACH,CACF,CAAC,EAEKU,GAAiB,IAAE,OAAO,CAC9B,MAAO,IAAE,MAAMF,EAAU,CAC3B,CAAC,EAEYV,GAAW,CACtB,KAAM,CAAE,OAAQG,EAAkB,EAClC,SAAU,CAAE,OAAQC,EAAsB,EAC1C,MAAO,CAAE,OAAQC,EAAmB,EACpC,MAAO,CAAE,OAAQC,EAAmB,EACpC,MAAO,CAAE,OAAQC,EAAmB,EACpC,KAAM,CAAE,OAAQC,EAAkB,EAClC,SAAU,CAAE,OAAQC,EAAsB,EAC1C,SAAU,CAAE,OAAQG,EAAe,EACnC,KAAM,CAAE,OAAQF,EAAW,EAC3B,SAAU,CAAE,OAAQC,EAAa,EACjC,OAAQ,CAAE,OAAQA,EAAa,CACjC,EfvEO,IAAME,GAAU,CAAE,kBAAAC,EAAmB,UAAAC,CAAU",
6
+ "names": ["src_exports", "__export", "Bot", "IntegrationImplementation", "IntegrationDefinition", "botIdHeader", "botUserIdHeader", "clients", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "import_axios", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "BotClient", "axiosInstance", "axiosGlobal", "props", "request", "formatBotHeaders", "ctx", "typeHeader", "botIdHeader", "operationHeader", "configurationHeader", "operation", "url", "data", "axios", "import_node_http", "log", "serve", "handler", "port", "callback", "defaultCallback", "server", "req", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "import_client", "import_zod", "botOperationSchema", "createBotHandler", "botState", "req", "ctx", "extractContext", "log", "client", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "botOperationSchema", "operationHeader", "body", "parseBody", "handler", "_", "Bot", "def", "_handler", "_type", "handler", "createBotHandler", "port", "serve", "import_client", "import_axios", "import_client", "import_zod", "e", "runtimeErrorSchema", "IntegrationClient", "axiosInstance", "axiosGlobal", "props", "request", "webhookRequest", "formatIntegrationHeaders", "ctx", "botIdHeader", "operationHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operation", "url", "data", "axios", "e", "runtimeErrorCode", "result", "runtimeErrorSchema", "import_zod", "integrationOperationSchema", "import_radash", "import_zod", "import_zod_to_json_schema", "isObjectSchema", "schema", "schemaDefinitionToJsonSchema", "definition", "zodToJsonSchema", "key", "value", "property", "nonEmptyDict", "v", "r", "obj", "schemaSchema", "configurationDefinitionSchema", "eventDefinitionSchema", "actionDefinitionSchema", "messageDefinitionSchema", "tagDefinitionSchema", "channelDefinitionSchema", "stateDefinitionSchema", "PUBLIC_VERSION", "PRIVATE_VERSION", "integrationDefinitionSchema", "formatIntegrationDefinition", "definition", "schemaDefinitionToJsonSchema", "event", "action", "channel", "message", "state", "IntegrationDefinition", "props", "integrationDefinitionInput", "parsed", "name", "version", "icon", "readme", "title", "description", "configuration", "events", "actions", "channels", "states", "user", "secrets", "import_client", "integrationHandler", "integration", "req", "ctx", "extractContext", "client", "props", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "e", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "integrationOperationSchema", "operationHeader", "parseBody", "_", "incomingRequest", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "message_exports", "__export", "defaults", "import_zod", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "clients", "IntegrationClient", "BotClient"]
7
7
  }
@@ -80,31 +80,17 @@ export declare const messageDefinitionSchema: z.ZodObject<{
80
80
  [k: string]: unknown;
81
81
  };
82
82
  }>;
83
- export declare const tagsDefinitionSchema: z.ZodObject<{
84
- conversations: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
85
- users: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
86
- messages: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
83
+ export declare const tagDefinitionSchema: z.ZodObject<{
84
+ title: z.ZodOptional<z.ZodString>;
85
+ description: z.ZodOptional<z.ZodString>;
87
86
  }, "strip", z.ZodTypeAny, {
88
- conversations?: string[] | undefined;
89
- users?: string[] | undefined;
90
- messages?: string[] | undefined;
87
+ title?: string | undefined;
88
+ description?: string | undefined;
91
89
  }, {
92
- conversations?: string[] | undefined;
93
- users?: string[] | undefined;
94
- messages?: string[] | undefined;
90
+ title?: string | undefined;
91
+ description?: string | undefined;
95
92
  }>;
96
93
  export declare const channelDefinitionSchema: z.ZodObject<{
97
- tags: z.ZodOptional<z.ZodObject<Omit<{
98
- conversations: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
99
- users: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
100
- messages: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
101
- }, "users">, "strip", z.ZodTypeAny, {
102
- conversations?: string[] | undefined;
103
- messages?: string[] | undefined;
104
- }, {
105
- conversations?: string[] | undefined;
106
- messages?: string[] | undefined;
107
- }>>;
108
94
  messages: z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodObject<{
109
95
  schema: z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>;
110
96
  }, "strip", z.ZodTypeAny, {
@@ -124,8 +110,40 @@ export declare const channelDefinitionSchema: z.ZodObject<{
124
110
  [k: string]: unknown;
125
111
  };
126
112
  }>>;
113
+ message: z.ZodOptional<z.ZodObject<{
114
+ tags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
115
+ title: z.ZodOptional<z.ZodString>;
116
+ description: z.ZodOptional<z.ZodString>;
117
+ }, "strip", z.ZodTypeAny, {
118
+ title?: string | undefined;
119
+ description?: string | undefined;
120
+ }, {
121
+ title?: string | undefined;
122
+ description?: string | undefined;
123
+ }>>>;
124
+ }, "strip", z.ZodTypeAny, {
125
+ tags?: Record<string, {
126
+ title?: string | undefined;
127
+ description?: string | undefined;
128
+ }> | undefined;
129
+ }, {
130
+ tags?: Record<string, {
131
+ title?: string | undefined;
132
+ description?: string | undefined;
133
+ }> | undefined;
134
+ }>>;
127
135
  conversation: z.ZodOptional<z.ZodObject<{
128
- creation: z.ZodObject<{
136
+ tags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
137
+ title: z.ZodOptional<z.ZodString>;
138
+ description: z.ZodOptional<z.ZodString>;
139
+ }, "strip", z.ZodTypeAny, {
140
+ title?: string | undefined;
141
+ description?: string | undefined;
142
+ }, {
143
+ title?: string | undefined;
144
+ description?: string | undefined;
145
+ }>>>;
146
+ creation: z.ZodOptional<z.ZodObject<{
129
147
  enabled: z.ZodBoolean;
130
148
  requiredTags: z.ZodArray<z.ZodString, "many">;
131
149
  }, "strip", z.ZodTypeAny, {
@@ -134,17 +152,25 @@ export declare const channelDefinitionSchema: z.ZodObject<{
134
152
  }, {
135
153
  enabled: boolean;
136
154
  requiredTags: string[];
137
- }>;
155
+ }>>;
138
156
  }, "strip", z.ZodTypeAny, {
139
- creation: {
157
+ tags?: Record<string, {
158
+ title?: string | undefined;
159
+ description?: string | undefined;
160
+ }> | undefined;
161
+ creation?: {
140
162
  enabled: boolean;
141
163
  requiredTags: string[];
142
- };
164
+ } | undefined;
143
165
  }, {
144
- creation: {
166
+ tags?: Record<string, {
167
+ title?: string | undefined;
168
+ description?: string | undefined;
169
+ }> | undefined;
170
+ creation?: {
145
171
  enabled: boolean;
146
172
  requiredTags: string[];
147
- };
173
+ } | undefined;
148
174
  }>>;
149
175
  }, "strip", z.ZodTypeAny, {
150
176
  messages: Record<string, {
@@ -152,15 +178,21 @@ export declare const channelDefinitionSchema: z.ZodObject<{
152
178
  [k: string]: unknown;
153
179
  };
154
180
  }>;
155
- tags?: {
156
- conversations?: string[] | undefined;
157
- messages?: string[] | undefined;
181
+ message?: {
182
+ tags?: Record<string, {
183
+ title?: string | undefined;
184
+ description?: string | undefined;
185
+ }> | undefined;
158
186
  } | undefined;
159
187
  conversation?: {
160
- creation: {
188
+ tags?: Record<string, {
189
+ title?: string | undefined;
190
+ description?: string | undefined;
191
+ }> | undefined;
192
+ creation?: {
161
193
  enabled: boolean;
162
194
  requiredTags: string[];
163
- };
195
+ } | undefined;
164
196
  } | undefined;
165
197
  }, {
166
198
  messages: Record<string, {
@@ -168,15 +200,21 @@ export declare const channelDefinitionSchema: z.ZodObject<{
168
200
  [k: string]: unknown;
169
201
  };
170
202
  }>;
171
- tags?: {
172
- conversations?: string[] | undefined;
173
- messages?: string[] | undefined;
203
+ message?: {
204
+ tags?: Record<string, {
205
+ title?: string | undefined;
206
+ description?: string | undefined;
207
+ }> | undefined;
174
208
  } | undefined;
175
209
  conversation?: {
176
- creation: {
210
+ tags?: Record<string, {
211
+ title?: string | undefined;
212
+ description?: string | undefined;
213
+ }> | undefined;
214
+ creation?: {
177
215
  enabled: boolean;
178
216
  requiredTags: string[];
179
- };
217
+ } | undefined;
180
218
  } | undefined;
181
219
  }>;
182
220
  export declare const stateDefinitionSchema: z.ZodObject<{
@@ -202,15 +240,6 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
202
240
  description: z.ZodOptional<z.ZodString>;
203
241
  icon: z.ZodOptional<z.ZodString>;
204
242
  readme: z.ZodOptional<z.ZodString>;
205
- tags: z.ZodOptional<z.ZodObject<Pick<{
206
- conversations: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
207
- users: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
208
- messages: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
209
- }, "users">, "strip", z.ZodTypeAny, {
210
- users?: string[] | undefined;
211
- }, {
212
- users?: string[] | undefined;
213
- }>>;
214
243
  configuration: z.ZodOptional<z.ZodObject<{
215
244
  schema: z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>;
216
245
  }, "strip", z.ZodTypeAny, {
@@ -280,17 +309,6 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
280
309
  };
281
310
  }>>>;
282
311
  channels: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
283
- tags: z.ZodOptional<z.ZodObject<Omit<{
284
- conversations: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
285
- users: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
286
- messages: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
287
- }, "users">, "strip", z.ZodTypeAny, {
288
- conversations?: string[] | undefined;
289
- messages?: string[] | undefined;
290
- }, {
291
- conversations?: string[] | undefined;
292
- messages?: string[] | undefined;
293
- }>>;
294
312
  messages: z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodObject<{
295
313
  schema: z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>;
296
314
  }, "strip", z.ZodTypeAny, {
@@ -310,8 +328,40 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
310
328
  [k: string]: unknown;
311
329
  };
312
330
  }>>;
331
+ message: z.ZodOptional<z.ZodObject<{
332
+ tags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
333
+ title: z.ZodOptional<z.ZodString>;
334
+ description: z.ZodOptional<z.ZodString>;
335
+ }, "strip", z.ZodTypeAny, {
336
+ title?: string | undefined;
337
+ description?: string | undefined;
338
+ }, {
339
+ title?: string | undefined;
340
+ description?: string | undefined;
341
+ }>>>;
342
+ }, "strip", z.ZodTypeAny, {
343
+ tags?: Record<string, {
344
+ title?: string | undefined;
345
+ description?: string | undefined;
346
+ }> | undefined;
347
+ }, {
348
+ tags?: Record<string, {
349
+ title?: string | undefined;
350
+ description?: string | undefined;
351
+ }> | undefined;
352
+ }>>;
313
353
  conversation: z.ZodOptional<z.ZodObject<{
314
- creation: z.ZodObject<{
354
+ tags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
355
+ title: z.ZodOptional<z.ZodString>;
356
+ description: z.ZodOptional<z.ZodString>;
357
+ }, "strip", z.ZodTypeAny, {
358
+ title?: string | undefined;
359
+ description?: string | undefined;
360
+ }, {
361
+ title?: string | undefined;
362
+ description?: string | undefined;
363
+ }>>>;
364
+ creation: z.ZodOptional<z.ZodObject<{
315
365
  enabled: z.ZodBoolean;
316
366
  requiredTags: z.ZodArray<z.ZodString, "many">;
317
367
  }, "strip", z.ZodTypeAny, {
@@ -320,17 +370,25 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
320
370
  }, {
321
371
  enabled: boolean;
322
372
  requiredTags: string[];
323
- }>;
373
+ }>>;
324
374
  }, "strip", z.ZodTypeAny, {
325
- creation: {
375
+ tags?: Record<string, {
376
+ title?: string | undefined;
377
+ description?: string | undefined;
378
+ }> | undefined;
379
+ creation?: {
326
380
  enabled: boolean;
327
381
  requiredTags: string[];
328
- };
382
+ } | undefined;
329
383
  }, {
330
- creation: {
384
+ tags?: Record<string, {
385
+ title?: string | undefined;
386
+ description?: string | undefined;
387
+ }> | undefined;
388
+ creation?: {
331
389
  enabled: boolean;
332
390
  requiredTags: string[];
333
- };
391
+ } | undefined;
334
392
  }>>;
335
393
  }, "strip", z.ZodTypeAny, {
336
394
  messages: Record<string, {
@@ -338,15 +396,21 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
338
396
  [k: string]: unknown;
339
397
  };
340
398
  }>;
341
- tags?: {
342
- conversations?: string[] | undefined;
343
- messages?: string[] | undefined;
399
+ message?: {
400
+ tags?: Record<string, {
401
+ title?: string | undefined;
402
+ description?: string | undefined;
403
+ }> | undefined;
344
404
  } | undefined;
345
405
  conversation?: {
346
- creation: {
406
+ tags?: Record<string, {
407
+ title?: string | undefined;
408
+ description?: string | undefined;
409
+ }> | undefined;
410
+ creation?: {
347
411
  enabled: boolean;
348
412
  requiredTags: string[];
349
- };
413
+ } | undefined;
350
414
  } | undefined;
351
415
  }, {
352
416
  messages: Record<string, {
@@ -354,15 +418,21 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
354
418
  [k: string]: unknown;
355
419
  };
356
420
  }>;
357
- tags?: {
358
- conversations?: string[] | undefined;
359
- messages?: string[] | undefined;
421
+ message?: {
422
+ tags?: Record<string, {
423
+ title?: string | undefined;
424
+ description?: string | undefined;
425
+ }> | undefined;
360
426
  } | undefined;
361
427
  conversation?: {
362
- creation: {
428
+ tags?: Record<string, {
429
+ title?: string | undefined;
430
+ description?: string | undefined;
431
+ }> | undefined;
432
+ creation?: {
363
433
  enabled: boolean;
364
434
  requiredTags: string[];
365
- };
435
+ } | undefined;
366
436
  } | undefined;
367
437
  }>>>;
368
438
  states: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
@@ -380,7 +450,17 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
380
450
  };
381
451
  }>>>;
382
452
  user: z.ZodOptional<z.ZodObject<{
383
- creation: z.ZodObject<{
453
+ tags: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
454
+ title: z.ZodOptional<z.ZodString>;
455
+ description: z.ZodOptional<z.ZodString>;
456
+ }, "strip", z.ZodTypeAny, {
457
+ title?: string | undefined;
458
+ description?: string | undefined;
459
+ }, {
460
+ title?: string | undefined;
461
+ description?: string | undefined;
462
+ }>>>;
463
+ creation: z.ZodOptional<z.ZodObject<{
384
464
  enabled: z.ZodBoolean;
385
465
  requiredTags: z.ZodArray<z.ZodString, "many">;
386
466
  }, "strip", z.ZodTypeAny, {
@@ -389,17 +469,25 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
389
469
  }, {
390
470
  enabled: boolean;
391
471
  requiredTags: string[];
392
- }>;
472
+ }>>;
393
473
  }, "strip", z.ZodTypeAny, {
394
- creation: {
474
+ tags?: Record<string, {
475
+ title?: string | undefined;
476
+ description?: string | undefined;
477
+ }> | undefined;
478
+ creation?: {
395
479
  enabled: boolean;
396
480
  requiredTags: string[];
397
- };
481
+ } | undefined;
398
482
  }, {
399
- creation: {
483
+ tags?: Record<string, {
484
+ title?: string | undefined;
485
+ description?: string | undefined;
486
+ }> | undefined;
487
+ creation?: {
400
488
  enabled: boolean;
401
489
  requiredTags: string[];
402
- };
490
+ } | undefined;
403
491
  }>>;
404
492
  secrets: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
405
493
  }, "strip", z.ZodTypeAny, {
@@ -409,9 +497,6 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
409
497
  description?: string | undefined;
410
498
  icon?: string | undefined;
411
499
  readme?: string | undefined;
412
- tags?: {
413
- users?: string[] | undefined;
414
- } | undefined;
415
500
  configuration?: {
416
501
  schema: {} & {
417
502
  [k: string]: unknown;
@@ -440,15 +525,21 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
440
525
  [k: string]: unknown;
441
526
  };
442
527
  }>;
443
- tags?: {
444
- conversations?: string[] | undefined;
445
- messages?: string[] | undefined;
528
+ message?: {
529
+ tags?: Record<string, {
530
+ title?: string | undefined;
531
+ description?: string | undefined;
532
+ }> | undefined;
446
533
  } | undefined;
447
534
  conversation?: {
448
- creation: {
535
+ tags?: Record<string, {
536
+ title?: string | undefined;
537
+ description?: string | undefined;
538
+ }> | undefined;
539
+ creation?: {
449
540
  enabled: boolean;
450
541
  requiredTags: string[];
451
- };
542
+ } | undefined;
452
543
  } | undefined;
453
544
  }> | undefined;
454
545
  states?: Record<string, {
@@ -458,10 +549,14 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
458
549
  };
459
550
  }> | undefined;
460
551
  user?: {
461
- creation: {
552
+ tags?: Record<string, {
553
+ title?: string | undefined;
554
+ description?: string | undefined;
555
+ }> | undefined;
556
+ creation?: {
462
557
  enabled: boolean;
463
558
  requiredTags: string[];
464
- };
559
+ } | undefined;
465
560
  } | undefined;
466
561
  secrets?: string[] | undefined;
467
562
  }, {
@@ -471,9 +566,6 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
471
566
  description?: string | undefined;
472
567
  icon?: string | undefined;
473
568
  readme?: string | undefined;
474
- tags?: {
475
- users?: string[] | undefined;
476
- } | undefined;
477
569
  configuration?: {
478
570
  schema: {} & {
479
571
  [k: string]: unknown;
@@ -502,15 +594,21 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
502
594
  [k: string]: unknown;
503
595
  };
504
596
  }>;
505
- tags?: {
506
- conversations?: string[] | undefined;
507
- messages?: string[] | undefined;
597
+ message?: {
598
+ tags?: Record<string, {
599
+ title?: string | undefined;
600
+ description?: string | undefined;
601
+ }> | undefined;
508
602
  } | undefined;
509
603
  conversation?: {
510
- creation: {
604
+ tags?: Record<string, {
605
+ title?: string | undefined;
606
+ description?: string | undefined;
607
+ }> | undefined;
608
+ creation?: {
511
609
  enabled: boolean;
512
610
  requiredTags: string[];
513
- };
611
+ } | undefined;
514
612
  } | undefined;
515
613
  }> | undefined;
516
614
  states?: Record<string, {
@@ -520,16 +618,19 @@ export declare const integrationDefinitionSchema: z.ZodObject<{
520
618
  };
521
619
  }> | undefined;
522
620
  user?: {
523
- creation: {
621
+ tags?: Record<string, {
622
+ title?: string | undefined;
623
+ description?: string | undefined;
624
+ }> | undefined;
625
+ creation?: {
524
626
  enabled: boolean;
525
627
  requiredTags: string[];
526
- };
628
+ } | undefined;
527
629
  } | undefined;
528
630
  secrets?: string[] | undefined;
529
631
  }>;
530
632
  export type ConfigurationDefinition = z.infer<typeof configurationDefinitionSchema>;
531
633
  export type EventDefinition = z.infer<typeof eventDefinitionSchema>;
532
- export type TagDefinition = z.infer<typeof tagsDefinitionSchema>;
533
634
  export type ChannelDefinition = z.infer<typeof channelDefinitionSchema>;
534
635
  export type ActionDefinition = z.infer<typeof actionDefinitionSchema>;
535
636
  export type MessageDefinition = z.infer<typeof messageDefinitionSchema>;
@@ -583,7 +684,6 @@ export declare class IntegrationDefinition<TConfig extends BaseConfig = BaseConf
583
684
  readonly readme: IntegrationDefinitionOutput['readme'];
584
685
  readonly title: IntegrationDefinitionOutput['title'];
585
686
  readonly description: IntegrationDefinitionOutput['description'];
586
- readonly tags: IntegrationDefinitionOutput['tags'];
587
687
  readonly configuration: IntegrationDefinitionOutput['configuration'];
588
688
  readonly events: IntegrationDefinitionOutput['events'];
589
689
  readonly actions: IntegrationDefinitionOutput['actions'];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botpress/sdk",
3
- "version": "0.0.16",
3
+ "version": "0.1.1",
4
4
  "description": "Botpress SDK",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -14,7 +14,7 @@
14
14
  "author": "",
15
15
  "license": "ISC",
16
16
  "dependencies": {
17
- "@botpress/client": "0.0.13",
17
+ "@botpress/client": "0.1.1",
18
18
  "axios": "0.27.2",
19
19
  "radash": "^9.5.0",
20
20
  "zod": "^3.20.6",