@botpress/sdk 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bot/context.d.ts +2 -2
- package/dist/bot/implementation.d.ts +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/integration/context.d.ts +2 -2
- package/dist/message.d.ts +80 -81
- package/dist/schema.d.ts +5 -1
- package/dist/type-utils.d.ts +1 -1
- package/dist/zui.d.ts +290 -0
- package/package.json +8 -7
package/dist/bot/context.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { z } from '
|
|
2
|
-
export declare const botOperationSchema:
|
|
1
|
+
import { z } from '@bpinternal/zui';
|
|
2
|
+
export declare const botOperationSchema: import("@bpinternal/zui").ZodEnum<["event_received", "register", "unregister", "ping", "action_triggered"]>;
|
|
3
3
|
export type BotOperation = z.infer<typeof botOperationSchema>;
|
|
4
4
|
export type BotContext = {
|
|
5
5
|
botId: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * as messages from './message';
|
|
2
2
|
export * from './const';
|
|
3
3
|
export * from './serve';
|
|
4
|
+
export * from './zui';
|
|
4
5
|
export { IntegrationDefinition, IntegrationDefinitionProps, IntegrationImplementation as Integration, IntegrationImplementationProps as IntegrationProps, IntegrationContext, IntegrationSpecificClient, } from './integration';
|
|
5
6
|
export { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var J=Object.create;var v=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var X=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var R=(t,e)=>{for(var n in e)v(t,n,{get:e[n],enumerable:!0})},O=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of V(e))!Y.call(t,s)&&s!==n&&v(t,s,{get:()=>e[s],enumerable:!(r=Q(e,s))||r.enumerable});return t};var D=(t,e,n)=>(n=t!=null?J(X(t)):{},O(e||!t||!t.__esModule?v(n,"default",{value:t,enumerable:!0}):n,t)),ee=t=>O(v({},"__esModule",{value:!0}),t);var Me={};R(Me,{Bot:()=>S,BotSpecificClient:()=>u,Integration:()=>x,IntegrationDefinition:()=>B,IntegrationSpecificClient:()=>T,botIdHeader:()=>h,botUserIdHeader:()=>E,configurationHeader:()=>m,integrationIdHeader:()=>M,messages:()=>P,operationHeader:()=>y,parseBody:()=>p,serve:()=>f,typeHeader:()=>U,webhookIdHeader:()=>w});module.exports=ee(Me);var P={};R(P,{defaults:()=>ce});var a=require("zod"),g=a.z.string().min(1),te=a.z.object({text:g}),ne=a.z.object({markdown:g}),se=a.z.object({imageUrl:g}),oe=a.z.object({audioUrl:g}),re=a.z.object({videoUrl:g}),ae=a.z.object({fileUrl:g,title:g.optional()}),ie=a.z.object({latitude:a.z.number(),longitude:a.z.number(),address:a.z.string().optional(),title:a.z.string().optional()}),G=a.z.object({title:g,subtitle:g.optional(),imageUrl:g.optional(),actions:a.z.array(a.z.object({action:a.z.enum(["postback","url","say"]),label:g,value:g}))}),F=a.z.object({text:g,options:a.z.array(a.z.object({label:g,value:g}))}),ge=a.z.object({items:a.z.array(G)}),ce={text:{schema:te},markdown:{schema:ne},image:{schema:se},audio:{schema:oe},video:{schema:re},file:{schema:ae},location:{schema:ie},carousel:{schema:ge},card:{schema:G},dropdown:{schema:F},choice:{schema:F}};var h="x-bot-id",E="x-bot-user-id",M="x-integration-id",w="x-webhook-id",m="x-bp-configuration",y="x-bp-operation",U="x-bp-type";var _=require("node:http");var d=console;function p(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function f(t,e=8072,n=Te){let r=(0,_.createServer)(async(s,o)=>{try{let i=await pe(s);if(i.path==="/health"){o.writeHead(200).end("ok");return}let c=await t(i);o.writeHead(c?.status??200,c?.headers??{}).end(c?.body??"{}")}catch(i){d.error("Error while handling request",{error:i?.message??"Internal error occured"}),o.writeHead(500).end(JSON.stringify({error:i?.message??"Internal error occured"}))}});return r.listen(e,()=>n(e)),r}async function pe(t){let e=await de(t),n={};for(let s=0;s<t.rawHeaders.length;s+=2){let o=t.rawHeaders[s].toLowerCase(),i=t.rawHeaders[s+1];n[o]=i}let r=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:r.pathname,query:le(r.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function le(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function de(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",s=>r+=s.toString()),t.on("error",s=>n(s)),t.on("end",()=>e(r))})}function Te(t){d.info(`Listening on port ${t}`)}var L=require("zod");var ue=L.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),K=t=>{let e=t[h],n=t[E],r=t[M],s=t[w],o=t[m],i=ue.parse(t[y]);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(!s)throw new Error("Missing webhook headers");if(!o)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:r,webhookId:s,operation:i,configuration:o?JSON.parse(Buffer.from(o,"base64").toString("utf-8")):{}}};var B=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities}name;version;title;description;icon;readme;configuration;events;actions;channels;states;user;secrets;identifier;entities};var C=require("@botpress/client");var T=class{constructor(e){this.client=e}createConversation=e=>this.client.createConversation(e);getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);createEvent=e=>this.client.createEvent(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);createUser=e=>this.client.createUser(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);getOrCreateUser=e=>this.client.getOrCreateUser(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e);setState=e=>this.client.setState(e);getOrSetState=e=>this.client.getOrSetState(e);patchState=e=>this.client.patchState(e);configureIntegration=e=>this.client.configureIntegration(e)};var k=D(require("util")),b=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:k.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return k.default.format(`[For Bot Owner] ${e}`,...n)}},j={forBot:()=>({info:(...t)=>{console.info(b(t))},warn:(...t)=>{console.warn(b(t))},error:(...t)=>{console.error(b(t))},debug:(...t)=>{console.debug(b(t))}})};var q=t=>async e=>{let n=K(e.headers),r=new T(new C.Client({botId:n.botId,integrationId:n.integrationId})),s={ctx:n,req:e,client:r,logger:j,instance:t};try{let o;switch(n.operation){case"webhook_received":o=await he(s);break;case"register":o=await me(s);break;case"unregister":o=await ye(s);break;case"message_created":o=await Be(s);break;case"action_triggered":o=await be(s);break;case"ping":o=await Ie(s);break;case"create_user":o=await fe(s);break;case"create_conversation":o=await ve(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return o?{...o,status:o.status??200}:{status:200}}catch(o){if(o instanceof C.RuntimeError)return{status:o.code,body:JSON.stringify(o.toJSON())};throw o}},Ie=async t=>{},he=async({client:t,ctx:e,req:n,logger:r,instance:s})=>{let{req:o}=p(n);return s.webhook({client:t,ctx:e,req:o,logger:r})},me=async({client:t,ctx:e,req:n,logger:r,instance:s})=>{if(!s.register)return;let{webhookUrl:o}=p(n);await s.register({client:t,ctx:e,webhookUrl:o,logger:r})},ye=async({client:t,ctx:e,req:n,logger:r,instance:s})=>{if(!s.unregister)return;let{webhookUrl:o}=p(n);await s.unregister({ctx:e,webhookUrl:o,client:t,logger:r})},fe=async({client:t,ctx:e,req:n,logger:r,instance:s})=>{if(!s.createUser)return;let{tags:o}=p(n);return await s.createUser({ctx:e,client:t,tags:o,logger:r})},ve=async({client:t,ctx:e,req:n,logger:r,instance:s})=>{if(!s.createConversation)return;let{channel:o,tags:i}=p(n);return await s.createConversation({ctx:e,client:t,channel:o,tags:i,logger:r})},Be=async({ctx:t,req:e,client:n,logger:r,instance:s})=>{let{conversation:o,user:i,type:c,payload:I,message:l}=p(e),A=s.channels[o.channel];if(!A)throw new Error(`Channel ${o.channel} not found`);let H=A.messages[c];if(!H)throw new Error(`Message of type ${c} not found in channel ${o.channel}`);await H({ctx:t,conversation:o,message:l,user:i,type:c,client:n,payload:I,ack:async({tags:W})=>{await n.updateMessage({id:l.id,tags:W})},logger:r})},be=async({req:t,ctx:e,client:n,logger:r,instance:s})=>{let{input:o,type:i}=p(t);if(!i)throw new Error("Missing action type");let c=s.actions[i];if(!c)throw new Error(`Action ${i} not found`);let I=await c({ctx:e,input:o,client:n,type:i,logger:r});return{body:JSON.stringify({output:I})}};var x=class{props;actions;channels;register;unregister;createUser;createConversation;webhook;constructor(e){this.props=e,this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}handler=q(this);start=e=>f(this.handler,e)};var Z=D(require("@botpress/client"));var u=class{constructor(e){this.client=e}getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this.client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this.client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this.client.patchState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));callAction=e=>this.client.callAction(e);createConversation=e=>this.client.createConversation(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);createUser=e=>this.client.createUser(e);getOrCreateUser=e=>this.client.getOrCreateUser(e)};var $=require("zod");var Ce=$.z.enum(["event_received","register","unregister","ping","action_triggered"]),N=t=>{let e=t[h],n=t[m],r=t[U],s=Ce.parse(t[y]);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(!s)throw new Error("Missing operation headers");return{botId:e,operation:s,type:r,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var z=t=>async e=>{let n=N(e.headers);n.operation!=="ping"&&d.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let r=new u(new Z.Client({botId:n.botId})),s={req:e,ctx:n,client:r,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await Ee(s);break;case"register":await Se(s);break;case"unregister":await Pe(s);break;case"ping":await xe(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},xe=async t=>{},Se=async t=>{},Pe=async t=>{},Ee=async({ctx:t,req:e,client:n,instance:r})=>{d.debug(`Received event ${t.type}`);let s=p(e),o=s.event;switch(t.type){case"message_created":let i={user:o.payload.user,conversation:o.payload.conversation,message:o.payload.message,states:o.payload.states,event:o};await Promise.all(r.messageHandlers.map(l=>l({client:n,ctx:t,...i})));break;case"state_expired":let c={state:o.payload.state};await Promise.all(r.stateExpiredHandlers.map(l=>l({client:n,ctx:t,...c})));break;default:let I={event:s.event};await Promise.all(r.eventHandlers.map(l=>l({client:n,ctx:t,...I})))}};var S=class{_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};props;constructor(e){this.props=e}message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=z(this._state);start=e=>f(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,botIdHeader,botUserIdHeader,configurationHeader,integrationIdHeader,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
|
|
1
|
+
"use strict";var ee=Object.create;var S=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var k=(t,e)=>{for(var n in e)S(t,n,{get:e[n],enumerable:!0})},x=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ne(e))!se.call(t,s)&&s!==n&&S(t,s,{get:()=>e[s],enumerable:!(a=te(e,s))||a.enumerable});return t},p=(t,e,n)=>(x(t,e,"default"),n&&x(n,e,"default")),j=(t,e,n)=>(n=t!=null?ee(oe(t)):{},x(e||!t||!t.__esModule?S(n,"default",{value:t,enumerable:!0}):n,t)),re=t=>x(S({},"__esModule",{value:!0}),t);var T={};k(T,{Bot:()=>U,BotSpecificClient:()=>y,Integration:()=>M,IntegrationDefinition:()=>P,IntegrationSpecificClient:()=>I,botIdHeader:()=>b,botUserIdHeader:()=>D,configurationHeader:()=>v,integrationIdHeader:()=>O,messages:()=>A,operationHeader:()=>B,parseBody:()=>u,serve:()=>C,studioComponentDefinitions:()=>_,typeHeader:()=>R,webhookIdHeader:()=>H,z:()=>o.z});module.exports=re(T);var A={};k(A,{defaults:()=>me});var g={};k(g,{default:()=>ae,studioComponentDefinitions:()=>_,z:()=>o.z});var o=require("@bpinternal/zui");p(g,require("@bpinternal/zui"));var d=o.z.object({allowDynamicVariable:o.z.boolean().optional(),horizontal:o.z.boolean().optional()}),_={string:{textInput:{id:"textInput",params:d.extend({multiLine:o.z.boolean().optional(),growVertically:o.z.boolean().optional(),suggestions:o.z.array(o.z.string()).optional()})},dropdown:{id:"dropdown",params:d.extend({filterable:o.z.boolean().optional()})},radiogroup:{id:"radiogroup",params:d.extend({})},datepicker:{id:"datepicker",params:d.extend({dateFormat:o.z.string().optional(),minDate:o.z.string().optional(),maxDate:o.z.string().optional(),defaultTimezone:o.z.string().optional(),disableTimezoneSelection:o.z.boolean().optional(),highlightCurrentDay:o.z.boolean().optional(),showShortcutButtons:o.z.boolean().optional(),showOutsideDaysOfMonth:o.z.boolean().optional(),firstDayOfWeek:o.z.number().optional(),canChangeMonth:o.z.boolean().optional(),showWeekNumbers:o.z.boolean().optional()})},timepicker:{id:"timepicker",params:d.extend({useAMPM:o.z.boolean().optional(),timeFormat:o.z.string().optional(),minTime:o.z.string().optional(),maxTime:o.z.string().optional(),showArrowButtons:o.z.boolean().optional(),precision:o.z.enum(["minute","second","millisecond"]).optional()})},variablepicker:{id:"variablepicker",params:o.z.object({type:o.z.enum(["any","string","number","boolean","object","pattern","date","array","target","time","enum"]),horizontal:o.z.boolean().optional()})},richTextEditor:{id:"richTextEditor",params:o.z.object({allowDynamicVariable:o.z.boolean().optional(),resizable:o.z.boolean().optional()})},JSONInput:{id:"JSONInput",params:d.extend({showPreview:o.z.boolean().optional(),showValidationError:o.z.boolean().optional()})},fileInput:{id:"fileInput",params:d.extend({fileTypes:o.z.array(o.z.enum(["image","audio","video"])).optional(),showUploadedFiles:o.z.boolean().optional()})}},number:{numberInput:{id:"numberInput",params:d.extend({allowNumericCharactersOnly:o.z.boolean().optional(),stepSize:o.z.number().optional()})},slider:{id:"slider",params:o.z.object({horizontal:o.z.boolean().optional(),stepSize:o.z.number().optional()})}},boolean:{switch:{id:"switch",params:d}},array:{optionList:{id:"optionList",params:d},stringList:{id:"stringList",params:d}},object:{collapsible:{id:"collapsible",params:o.z.object({defaultOpen:o.z.boolean().optional()})}}},ae=o.z;var c=o.z.string().min(1),ie=o.z.object({text:c}),ge=o.z.object({markdown:c}),ce=o.z.object({imageUrl:c}),pe=o.z.object({audioUrl:c}),le=o.z.object({videoUrl:c}),de=o.z.object({fileUrl:c,title:c.optional()}),ue=o.z.object({latitude:o.z.number(),longitude:o.z.number(),address:o.z.string().optional(),title:o.z.string().optional()}),q=o.z.object({title:c,subtitle:c.optional(),imageUrl:c.optional(),actions:o.z.array(o.z.object({action:o.z.enum(["postback","url","say"]),label:c,value:c}))}),K=o.z.object({text:c,options:o.z.array(o.z.object({label:c,value:c}))}),Te=o.z.object({items:o.z.array(q)}),me={text:{schema:ie},markdown:{schema:ge},image:{schema:ce},audio:{schema:pe},video:{schema:le},file:{schema:de},location:{schema:ue},carousel:{schema:Te},card:{schema:q},dropdown:{schema:K},choice:{schema:K}};var b="x-bot-id",D="x-bot-user-id",O="x-integration-id",H="x-webhook-id",v="x-bp-configuration",B="x-bp-operation",R="x-bp-type";var z=require("node:http");var h=console;function u(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function C(t,e=8072,n=fe){let a=(0,z.createServer)(async(s,r)=>{try{let i=await he(s);if(i.path==="/health"){r.writeHead(200).end("ok");return}let l=await t(i);r.writeHead(l?.status??200,l?.headers??{}).end(l?.body??"{}")}catch(i){h.error("Error while handling request",{error:i?.message??"Internal error occured"}),r.writeHead(500).end(JSON.stringify({error:i?.message??"Internal error occured"}))}});return a.listen(e,()=>n(e)),a}async function he(t){let e=await ye(t),n={};for(let s=0;s<t.rawHeaders.length;s+=2){let r=t.rawHeaders[s].toLowerCase(),i=t.rawHeaders[s+1];n[r]=i}let a=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:a.pathname,query:Ie(a.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function Ie(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function ye(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let a="";t.on("data",s=>a+=s.toString()),t.on("error",s=>n(s)),t.on("end",()=>e(a))})}function fe(t){h.info(`Listening on port ${t}`)}p(T,g,module.exports);var N=require("@bpinternal/zui");var be=N.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),$=t=>{let e=t[b],n=t[D],a=t[O],s=t[H],r=t[v],i=be.parse(t[B]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!a)throw new Error("Missing integration headers");if(!s)throw new Error("Missing webhook headers");if(!r)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:a,webhookId:s,operation:i,configuration:r?JSON.parse(Buffer.from(r,"base64").toString("utf-8")):{}}};var P=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities}name;version;title;description;icon;readme;configuration;events;actions;channels;states;user;secrets;identifier;entities};var w=require("@botpress/client");var I=class{constructor(e){this.client=e}createConversation=e=>this.client.createConversation(e);getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);createEvent=e=>this.client.createEvent(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);createUser=e=>this.client.createUser(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);getOrCreateUser=e=>this.client.getOrCreateUser(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e);setState=e=>this.client.setState(e);getOrSetState=e=>this.client.getOrSetState(e);patchState=e=>this.client.patchState(e);configureIntegration=e=>this.client.configureIntegration(e)};var F=j(require("util")),E=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:F.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return F.default.format(`[For Bot Owner] ${e}`,...n)}},W={forBot:()=>({info:(...t)=>{console.info(E(t))},warn:(...t)=>{console.warn(E(t))},error:(...t)=>{console.error(E(t))},debug:(...t)=>{console.debug(E(t))}})};var Z=t=>async e=>{let n=$(e.headers),a=new I(new w.Client({botId:n.botId,integrationId:n.integrationId})),s={ctx:n,req:e,client:a,logger:W,instance:t};try{let r;switch(n.operation){case"webhook_received":r=await Be(s);break;case"register":r=await Ce(s);break;case"unregister":r=await xe(s);break;case"message_created":r=await Ee(s);break;case"action_triggered":r=await we(s);break;case"ping":r=await ve(s);break;case"create_user":r=await Se(s);break;case"create_conversation":r=await Pe(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return r?{...r,status:r.status??200}:{status:200}}catch(r){if(r instanceof w.RuntimeError)return{status:r.code,body:JSON.stringify(r.toJSON())};throw r}},ve=async t=>{},Be=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{let{req:r}=u(n);return s.webhook({client:t,ctx:e,req:r,logger:a})},Ce=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.register)return;let{webhookUrl:r}=u(n);await s.register({client:t,ctx:e,webhookUrl:r,logger:a})},xe=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.unregister)return;let{webhookUrl:r}=u(n);await s.unregister({ctx:e,webhookUrl:r,client:t,logger:a})},Se=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createUser)return;let{tags:r}=u(n);return await s.createUser({ctx:e,client:t,tags:r,logger:a})},Pe=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createConversation)return;let{channel:r,tags:i}=u(n);return await s.createConversation({ctx:e,client:t,channel:r,tags:i,logger:a})},Ee=async({ctx:t,req:e,client:n,logger:a,instance:s})=>{let{conversation:r,user:i,type:l,payload:f,message:m}=u(e),G=s.channels[r.channel];if(!G)throw new Error(`Channel ${r.channel} not found`);let L=G.messages[l];if(!L)throw new Error(`Message of type ${l} not found in channel ${r.channel}`);await L({ctx:t,conversation:r,message:m,user:i,type:l,client:n,payload:f,ack:async({tags:Y})=>{await n.updateMessage({id:m.id,tags:Y})},logger:a})},we=async({req:t,ctx:e,client:n,logger:a,instance:s})=>{let{input:r,type:i}=u(t);if(!i)throw new Error("Missing action type");let l=s.actions[i];if(!l)throw new Error(`Action ${i} not found`);let f=await l({ctx:e,input:r,client:n,type:i,logger:a});return{body:JSON.stringify({output:f})}};var M=class{props;actions;channels;register;unregister;createUser;createConversation;webhook;constructor(e){this.props=e,this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}handler=Z(this);start=e=>C(this.handler,e)};var Q=j(require("@botpress/client"));var y=class{constructor(e){this.client=e}getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this.client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this.client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this.client.patchState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));callAction=e=>this.client.callAction(e);createConversation=e=>this.client.createConversation(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);createUser=e=>this.client.createUser(e);getOrCreateUser=e=>this.client.getOrCreateUser(e)};var J=require("@bpinternal/zui");var Me=J.z.enum(["event_received","register","unregister","ping","action_triggered"]),V=t=>{let e=t[b],n=t[v],a=t[R],s=Me.parse(t[B]);if(!e)throw new Error("Missing bot headers");if(!a)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!s)throw new Error("Missing operation headers");return{botId:e,operation:s,type:a,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var X=t=>async e=>{let n=V(e.headers);n.operation!=="ping"&&h.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let a=new y(new Q.Client({botId:n.botId})),s={req:e,ctx:n,client:a,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await De(s);break;case"register":await ke(s);break;case"unregister":await Ae(s);break;case"ping":await Ue(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},Ue=async t=>{},ke=async t=>{},Ae=async t=>{},De=async({ctx:t,req:e,client:n,instance:a})=>{h.debug(`Received event ${t.type}`);let s=u(e),r=s.event;switch(t.type){case"message_created":let i={user:r.payload.user,conversation:r.payload.conversation,message:r.payload.message,states:r.payload.states,event:r};await Promise.all(a.messageHandlers.map(m=>m({client:n,ctx:t,...i})));break;case"state_expired":let l={state:r.payload.state};await Promise.all(a.stateExpiredHandlers.map(m=>m({client:n,ctx:t,...l})));break;default:let f={event:s.event};await Promise.all(a.eventHandlers.map(m=>m({client:n,ctx:t,...f})))}};var U=class{_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};props;constructor(e){this.props=e}message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=X(this._state);start=e=>C(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,botIdHeader,botUserIdHeader,configurationHeader,integrationIdHeader,messages,operationHeader,parseBody,serve,studioComponentDefinitions,typeHeader,webhookIdHeader,z});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../src/message.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/definition.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
|
|
4
|
-
"sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationSpecificClient,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\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", "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 function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { z } from 'zod'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\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\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const 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", "import { SchemaDefinition } from '../schema'\nimport { AnyZodObject } from '../type-utils'\n\ntype BaseConfig = AnyZodObject\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, Record<string, AnyZodObject>>\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEntities = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype ConfigurationDefinition<TConfig extends BaseConfig> = SchemaDefinition<TConfig> & {\n identifier?: {\n required?: boolean\n linkTemplateScript?: string\n }\n}\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent> & {\n title?: string\n description?: string\n}\n\ntype ChannelDefinition<TChannel extends BaseChannels[string]> = {\n title?: string\n description?: string\n messages: {\n [K in keyof TChannel]: SchemaDefinition<TChannel[K]>\n }\n message?: {\n tags?: Record<string, TagDefinition>\n }\n conversation?: Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n }>\n}\n\ntype ActionDefinition<TAction extends BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<AnyZodObject> // cannot infer both input and output types (typescript limitation)\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: 'integration' | 'conversation' | 'user'\n}\n\ntype UserDefinition = Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n}>\n\ntype SecretDefinition = {\n optional?: boolean\n description?: string\n}\n\ntype EntityDefinition<TEntity extends BaseEntities[string]> = SchemaDefinition<TEntity> & {\n title?: string\n description?: string\n}\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n}\n", "import { Client, RuntimeError, type Conversation, type Message, type User } from '@botpress/client'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration['configuration']>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(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\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this.client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this.client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this.client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this.client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this.client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this.client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this.client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this.client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this.client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this.client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this.client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this.client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this.client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this.client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this.client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this.client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this.client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this.client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this.client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this.client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this.client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this.client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this.client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this.client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this.client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this.client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this.client.configureIntegration(x)\n}\n", "/* eslint-disable no-console */\nimport util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\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.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\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 botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this.client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this.client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this.client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this.client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this.client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this.client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this.client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this.client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this.client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) => this.client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this.client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) => this.client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this.client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) => this.client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this.client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this.client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this.client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this.client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this.client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this.client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this.client.callAction(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this.client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this.client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this.client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this.client.getOrCreateUser(x)\n}\n", "import { z } from 'zod'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import type { Server } from 'node:http'\nimport { z } from 'zod'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject, Cast } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<Cast<K, string>>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
|
|
5
|
-
"mappings": "2jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,wBAAAC,EAAA,aAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAAjB,ICAA,IAAAkB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KAAA,IAAAC,EAAkB,eAEZC,EAAiB,IAAE,OAAO,EAAE,IAAI,CAAC,EAEjCC,GAAoB,IAAE,OAAO,CACjC,KAAMD,CACR,CAAC,EAEKE,GAAwB,IAAE,OAAO,CACrC,SAAUF,CACZ,CAAC,EAEKG,GAAqB,IAAE,OAAO,CAClC,SAAUH,CACZ,CAAC,EAEKI,GAAqB,IAAE,OAAO,CAClC,SAAUJ,CACZ,CAAC,EAEKK,GAAqB,IAAE,OAAO,CAClC,SAAUL,CACZ,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,C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,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,EAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
|
|
6
|
-
"names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "
|
|
3
|
+
"sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/definition.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
|
|
4
|
+
"sourcesContent": ["export * as messages from './message'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationSpecificClient,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\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", "import { z, type UIComponentDefinitions, type DefaultComponentDefinitions } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nconst commonInputParams = z.object({\n allowDynamicVariable: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n})\n\nexport const studioComponentDefinitions = {\n string: {\n textInput: {\n id: 'textInput',\n params: commonInputParams.extend({\n multiLine: z.boolean().optional(),\n growVertically: z.boolean().optional(),\n suggestions: z.array(z.string()).optional(),\n }),\n },\n dropdown: {\n id: 'dropdown',\n params: commonInputParams.extend({\n filterable: z.boolean().optional(),\n }),\n },\n radiogroup: {\n id: 'radiogroup',\n params: commonInputParams.extend({}),\n },\n datepicker: {\n id: 'datepicker',\n params: commonInputParams.extend({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n disableTimezoneSelection: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showShortcutButtons: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n timepicker: {\n id: 'timepicker',\n params: commonInputParams.extend({\n useAMPM: z.boolean().optional(),\n timeFormat: z.string().optional(),\n minTime: z.string().optional(),\n maxTime: z.string().optional(),\n showArrowButtons: z.boolean().optional(),\n precision: z.enum(['minute', 'second', 'millisecond']).optional(),\n }),\n },\n variablepicker: {\n id: 'variablepicker',\n params: z.object({\n type: z.enum([\n 'any',\n 'string',\n 'number',\n 'boolean',\n 'object',\n 'pattern',\n 'date',\n 'array',\n 'target',\n 'time',\n 'enum',\n ]),\n horizontal: z.boolean().optional(),\n }),\n },\n richTextEditor: {\n id: 'richTextEditor',\n params: z.object({\n allowDynamicVariable: z.boolean().optional(),\n resizable: z.boolean().optional(),\n }),\n },\n JSONInput: {\n id: 'JSONInput',\n params: commonInputParams.extend({\n showPreview: z.boolean().optional(),\n showValidationError: z.boolean().optional(),\n }),\n },\n fileInput: {\n id: 'fileInput',\n params: commonInputParams.extend({\n fileTypes: z.array(z.enum(['image', 'audio', 'video'])).optional(),\n showUploadedFiles: z.boolean().optional(),\n }),\n },\n },\n number: {\n numberInput: {\n id: 'numberInput',\n params: commonInputParams.extend({\n allowNumericCharactersOnly: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n slider: {\n id: 'slider',\n params: z.object({\n horizontal: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n },\n boolean: {\n switch: {\n id: 'switch',\n params: commonInputParams,\n },\n },\n array: {\n optionList: {\n id: 'optionList',\n params: commonInputParams,\n },\n stringList: {\n id: 'stringList',\n params: commonInputParams,\n },\n },\n object: {\n collapsible: {\n id: 'collapsible',\n params: z.object({\n defaultOpen: z.boolean().optional(),\n }),\n },\n },\n} as const satisfies UIComponentDefinitions\n\nexport type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio'\n ? typeof studioComponentDefinitions\n : Namespace extends 'dashboard'\n ? DefaultComponentDefinitions\n : any\n\nexport default z\nexport { z }\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\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\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const 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", "import { SchemaDefinition } from '../schema'\nimport { AnyZodObject } from '../type-utils'\n\ntype BaseConfig = AnyZodObject\ntype BaseEvents = Record<string, AnyZodObject>\ntype BaseActions = Record<string, AnyZodObject>\ntype BaseChannels = Record<string, Record<string, AnyZodObject>>\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEntities = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype ConfigurationDefinition<TConfig extends BaseConfig> = SchemaDefinition<TConfig> & {\n identifier?: {\n required?: boolean\n linkTemplateScript?: string\n }\n}\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent> & {\n title?: string\n description?: string\n}\n\ntype ChannelDefinition<TChannel extends BaseChannels[string]> = {\n title?: string\n description?: string\n messages: {\n [K in keyof TChannel]: SchemaDefinition<TChannel[K]>\n }\n message?: {\n tags?: Record<string, TagDefinition>\n }\n conversation?: Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n }>\n}\n\ntype ActionDefinition<TAction extends BaseActions[string]> = {\n title?: string\n description?: string\n input: SchemaDefinition<TAction>\n output: SchemaDefinition<AnyZodObject> // cannot infer both input and output types (typescript limitation)\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: 'integration' | 'conversation' | 'user'\n}\n\ntype UserDefinition = Partial<{\n tags: Record<string, TagDefinition>\n /**\n * @deprecated\n */\n creation: {\n enabled: boolean\n requiredTags: string[]\n }\n}>\n\ntype SecretDefinition = {\n optional?: boolean\n description?: string\n}\n\ntype EntityDefinition<TEntity extends BaseEntities[string]> = SchemaDefinition<TEntity> & {\n title?: string\n description?: string\n}\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n}\n", "import { Client, RuntimeError, type Conversation, type Message, type User } from '@botpress/client'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration['configuration']>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(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\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this.client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this.client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this.client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this.client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this.client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this.client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this.client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this.client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this.client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this.client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this.client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this.client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this.client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this.client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this.client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this.client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this.client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this.client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this.client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this.client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this.client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this.client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this.client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this.client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this.client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this.client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this.client.configureIntegration(x)\n}\n", "/* eslint-disable no-console */\nimport util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\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.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\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 botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this.client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this.client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this.client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this.client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this.client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this.client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this.client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this.client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this.client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this.client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) => this.client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this.client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this.client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) => this.client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this.client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) => this.client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this.client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this.client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this.client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this.client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this.client.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this.client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this.client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this.client.callAction(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this.client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this.client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this.client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this.client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport type { Server } from 'node:http'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject, Cast } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<Cast<K, string>>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
|
|
5
|
+
"mappings": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,gBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,wBAAAC,EAAA,aAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,+BAAAC,EAAA,eAAAC,EAAA,oBAAAC,EAAA,2BAAAC,GAAAlB,GCAA,IAAAmB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,GAAA,+BAAAC,EAAA,gBAAAC,EAAiF,2BACjFC,EAAAL,EAAc,4BAEd,IAAMM,EAAoB,IAAE,OAAO,CACjC,qBAAsB,IAAE,QAAQ,EAAE,SAAS,EAC3C,WAAY,IAAE,QAAQ,EAAE,SAAS,CACnC,CAAC,EAEYH,EAA6B,CACxC,OAAQ,CACN,UAAW,CACT,GAAI,YACJ,OAAQG,EAAkB,OAAO,CAC/B,UAAW,IAAE,QAAQ,EAAE,SAAS,EAChC,eAAgB,IAAE,QAAQ,EAAE,SAAS,EACrC,YAAa,IAAE,MAAM,IAAE,OAAO,CAAC,EAAE,SAAS,CAC5C,CAAC,CACH,EACA,SAAU,CACR,GAAI,WACJ,OAAQA,EAAkB,OAAO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EACA,GAAGkB,CACL,CAAC,CACH,CACF,CACJ,CACF,EG1DO,IAAMC,EAAN,KAIL,CACQ,OAAoD,CAC1D,gBAAiB,CAAC,EAClB,cAAe,CAAC,EAChB,qBAAsB,CAAC,CACzB,EAEgB,MAET,YAAYC,EAAkD,CACnE,KAAK,MAAQA,CACf,CAEgB,QAAWC,GAA4E,CACrG,KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,EAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
|
|
6
|
+
"names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "message_exports", "operationHeader", "parseBody", "serve", "studioComponentDefinitions", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "studioComponentDefinitions", "import_zui", "__reExport", "commonInputParams", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "defaults", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "i", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "__reExport", "src_exports", "zui_exports", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "IntegrationDefinition", "props", "import_client", "IntegrationSpecificClient", "client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "client", "IntegrationSpecificClient", "props", "integrationLogger", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "e", "_", "incomingRequest", "logger", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "client", "BotSpecificClient", "client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
|
|
7
7
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { z } from '
|
|
2
|
-
export declare const integrationOperationSchema:
|
|
1
|
+
import { z } from '@bpinternal/zui';
|
|
2
|
+
export declare const integrationOperationSchema: import("@bpinternal/zui").ZodEnum<["webhook_received", "message_created", "action_triggered", "register", "unregister", "ping", "create_user", "create_conversation"]>;
|
|
3
3
|
export type IntegrationOperation = z.infer<typeof integrationOperationSchema>;
|
|
4
4
|
export type IntegrationContext<Configuration = any> = {
|
|
5
5
|
botId: string;
|
package/dist/message.d.ts
CHANGED
|
@@ -1,91 +1,90 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
1
|
export declare const defaults: {
|
|
3
2
|
readonly text: {
|
|
4
|
-
readonly schema:
|
|
5
|
-
text:
|
|
6
|
-
}, "strip",
|
|
3
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
4
|
+
text: import("@bpinternal/zui").ZodString;
|
|
5
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
7
6
|
text: string;
|
|
8
7
|
}, {
|
|
9
8
|
text: string;
|
|
10
9
|
}>;
|
|
11
10
|
};
|
|
12
11
|
readonly markdown: {
|
|
13
|
-
readonly schema:
|
|
14
|
-
markdown:
|
|
15
|
-
}, "strip",
|
|
12
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
13
|
+
markdown: import("@bpinternal/zui").ZodString;
|
|
14
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
16
15
|
markdown: string;
|
|
17
16
|
}, {
|
|
18
17
|
markdown: string;
|
|
19
18
|
}>;
|
|
20
19
|
};
|
|
21
20
|
readonly image: {
|
|
22
|
-
readonly schema:
|
|
23
|
-
imageUrl:
|
|
24
|
-
}, "strip",
|
|
21
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
22
|
+
imageUrl: import("@bpinternal/zui").ZodString;
|
|
23
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
25
24
|
imageUrl: string;
|
|
26
25
|
}, {
|
|
27
26
|
imageUrl: string;
|
|
28
27
|
}>;
|
|
29
28
|
};
|
|
30
29
|
readonly audio: {
|
|
31
|
-
readonly schema:
|
|
32
|
-
audioUrl:
|
|
33
|
-
}, "strip",
|
|
30
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
31
|
+
audioUrl: import("@bpinternal/zui").ZodString;
|
|
32
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
34
33
|
audioUrl: string;
|
|
35
34
|
}, {
|
|
36
35
|
audioUrl: string;
|
|
37
36
|
}>;
|
|
38
37
|
};
|
|
39
38
|
readonly video: {
|
|
40
|
-
readonly schema:
|
|
41
|
-
videoUrl:
|
|
42
|
-
}, "strip",
|
|
39
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
40
|
+
videoUrl: import("@bpinternal/zui").ZodString;
|
|
41
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
43
42
|
videoUrl: string;
|
|
44
43
|
}, {
|
|
45
44
|
videoUrl: string;
|
|
46
45
|
}>;
|
|
47
46
|
};
|
|
48
47
|
readonly file: {
|
|
49
|
-
readonly schema:
|
|
50
|
-
fileUrl:
|
|
51
|
-
title:
|
|
52
|
-
}, "strip",
|
|
53
|
-
title?: string | undefined;
|
|
48
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
49
|
+
fileUrl: import("@bpinternal/zui").ZodString;
|
|
50
|
+
title: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
51
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
54
52
|
fileUrl: string;
|
|
55
|
-
}, {
|
|
56
53
|
title?: string | undefined;
|
|
54
|
+
}, {
|
|
57
55
|
fileUrl: string;
|
|
56
|
+
title?: string | undefined;
|
|
58
57
|
}>;
|
|
59
58
|
};
|
|
60
59
|
readonly location: {
|
|
61
|
-
readonly schema:
|
|
62
|
-
latitude:
|
|
63
|
-
longitude:
|
|
64
|
-
address:
|
|
65
|
-
title:
|
|
66
|
-
}, "strip",
|
|
67
|
-
title?: string | undefined;
|
|
68
|
-
address?: string | undefined;
|
|
60
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
61
|
+
latitude: import("@bpinternal/zui").ZodNumber;
|
|
62
|
+
longitude: import("@bpinternal/zui").ZodNumber;
|
|
63
|
+
address: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
64
|
+
title: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
65
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
69
66
|
latitude: number;
|
|
70
67
|
longitude: number;
|
|
71
|
-
}, {
|
|
72
68
|
title?: string | undefined;
|
|
73
69
|
address?: string | undefined;
|
|
70
|
+
}, {
|
|
74
71
|
latitude: number;
|
|
75
72
|
longitude: number;
|
|
73
|
+
title?: string | undefined;
|
|
74
|
+
address?: string | undefined;
|
|
76
75
|
}>;
|
|
77
76
|
};
|
|
78
77
|
readonly carousel: {
|
|
79
|
-
readonly schema:
|
|
80
|
-
items:
|
|
81
|
-
title:
|
|
82
|
-
subtitle:
|
|
83
|
-
imageUrl:
|
|
84
|
-
actions:
|
|
85
|
-
action:
|
|
86
|
-
label:
|
|
87
|
-
value:
|
|
88
|
-
}, "strip",
|
|
78
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
79
|
+
items: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
80
|
+
title: import("@bpinternal/zui").ZodString;
|
|
81
|
+
subtitle: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
82
|
+
imageUrl: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
83
|
+
actions: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
84
|
+
action: import("@bpinternal/zui").ZodEnum<["postback", "url", "say"]>;
|
|
85
|
+
label: import("@bpinternal/zui").ZodString;
|
|
86
|
+
value: import("@bpinternal/zui").ZodString;
|
|
87
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
89
88
|
value: string;
|
|
90
89
|
action: "postback" | "url" | "say";
|
|
91
90
|
label: string;
|
|
@@ -94,59 +93,59 @@ export declare const defaults: {
|
|
|
94
93
|
action: "postback" | "url" | "say";
|
|
95
94
|
label: string;
|
|
96
95
|
}>, "many">;
|
|
97
|
-
}, "strip",
|
|
98
|
-
imageUrl?: string | undefined;
|
|
99
|
-
subtitle?: string | undefined;
|
|
96
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
100
97
|
title: string;
|
|
101
98
|
actions: {
|
|
102
99
|
value: string;
|
|
103
100
|
action: "postback" | "url" | "say";
|
|
104
101
|
label: string;
|
|
105
102
|
}[];
|
|
106
|
-
}, {
|
|
107
103
|
imageUrl?: string | undefined;
|
|
108
104
|
subtitle?: string | undefined;
|
|
105
|
+
}, {
|
|
109
106
|
title: string;
|
|
110
107
|
actions: {
|
|
111
108
|
value: string;
|
|
112
109
|
action: "postback" | "url" | "say";
|
|
113
110
|
label: string;
|
|
114
111
|
}[];
|
|
115
|
-
}>, "many">;
|
|
116
|
-
}, "strip", z.ZodTypeAny, {
|
|
117
|
-
items: {
|
|
118
112
|
imageUrl?: string | undefined;
|
|
119
113
|
subtitle?: string | undefined;
|
|
114
|
+
}>, "many">;
|
|
115
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
116
|
+
items: {
|
|
120
117
|
title: string;
|
|
121
118
|
actions: {
|
|
122
119
|
value: string;
|
|
123
120
|
action: "postback" | "url" | "say";
|
|
124
121
|
label: string;
|
|
125
122
|
}[];
|
|
123
|
+
imageUrl?: string | undefined;
|
|
124
|
+
subtitle?: string | undefined;
|
|
126
125
|
}[];
|
|
127
126
|
}, {
|
|
128
127
|
items: {
|
|
129
|
-
imageUrl?: string | undefined;
|
|
130
|
-
subtitle?: string | undefined;
|
|
131
128
|
title: string;
|
|
132
129
|
actions: {
|
|
133
130
|
value: string;
|
|
134
131
|
action: "postback" | "url" | "say";
|
|
135
132
|
label: string;
|
|
136
133
|
}[];
|
|
134
|
+
imageUrl?: string | undefined;
|
|
135
|
+
subtitle?: string | undefined;
|
|
137
136
|
}[];
|
|
138
137
|
}>;
|
|
139
138
|
};
|
|
140
139
|
readonly card: {
|
|
141
|
-
readonly schema:
|
|
142
|
-
title:
|
|
143
|
-
subtitle:
|
|
144
|
-
imageUrl:
|
|
145
|
-
actions:
|
|
146
|
-
action:
|
|
147
|
-
label:
|
|
148
|
-
value:
|
|
149
|
-
}, "strip",
|
|
140
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
141
|
+
title: import("@bpinternal/zui").ZodString;
|
|
142
|
+
subtitle: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
143
|
+
imageUrl: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
144
|
+
actions: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
145
|
+
action: import("@bpinternal/zui").ZodEnum<["postback", "url", "say"]>;
|
|
146
|
+
label: import("@bpinternal/zui").ZodString;
|
|
147
|
+
value: import("@bpinternal/zui").ZodString;
|
|
148
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
150
149
|
value: string;
|
|
151
150
|
action: "postback" | "url" | "say";
|
|
152
151
|
label: string;
|
|
@@ -155,78 +154,78 @@ export declare const defaults: {
|
|
|
155
154
|
action: "postback" | "url" | "say";
|
|
156
155
|
label: string;
|
|
157
156
|
}>, "many">;
|
|
158
|
-
}, "strip",
|
|
159
|
-
imageUrl?: string | undefined;
|
|
160
|
-
subtitle?: string | undefined;
|
|
157
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
161
158
|
title: string;
|
|
162
159
|
actions: {
|
|
163
160
|
value: string;
|
|
164
161
|
action: "postback" | "url" | "say";
|
|
165
162
|
label: string;
|
|
166
163
|
}[];
|
|
167
|
-
}, {
|
|
168
164
|
imageUrl?: string | undefined;
|
|
169
165
|
subtitle?: string | undefined;
|
|
166
|
+
}, {
|
|
170
167
|
title: string;
|
|
171
168
|
actions: {
|
|
172
169
|
value: string;
|
|
173
170
|
action: "postback" | "url" | "say";
|
|
174
171
|
label: string;
|
|
175
172
|
}[];
|
|
173
|
+
imageUrl?: string | undefined;
|
|
174
|
+
subtitle?: string | undefined;
|
|
176
175
|
}>;
|
|
177
176
|
};
|
|
178
177
|
readonly dropdown: {
|
|
179
|
-
readonly schema:
|
|
180
|
-
text:
|
|
181
|
-
options:
|
|
182
|
-
label:
|
|
183
|
-
value:
|
|
184
|
-
}, "strip",
|
|
178
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
179
|
+
text: import("@bpinternal/zui").ZodString;
|
|
180
|
+
options: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
181
|
+
label: import("@bpinternal/zui").ZodString;
|
|
182
|
+
value: import("@bpinternal/zui").ZodString;
|
|
183
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
185
184
|
value: string;
|
|
186
185
|
label: string;
|
|
187
186
|
}, {
|
|
188
187
|
value: string;
|
|
189
188
|
label: string;
|
|
190
189
|
}>, "many">;
|
|
191
|
-
}, "strip",
|
|
192
|
-
text: string;
|
|
190
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
193
191
|
options: {
|
|
194
192
|
value: string;
|
|
195
193
|
label: string;
|
|
196
194
|
}[];
|
|
197
|
-
}, {
|
|
198
195
|
text: string;
|
|
196
|
+
}, {
|
|
199
197
|
options: {
|
|
200
198
|
value: string;
|
|
201
199
|
label: string;
|
|
202
200
|
}[];
|
|
201
|
+
text: string;
|
|
203
202
|
}>;
|
|
204
203
|
};
|
|
205
204
|
readonly choice: {
|
|
206
|
-
readonly schema:
|
|
207
|
-
text:
|
|
208
|
-
options:
|
|
209
|
-
label:
|
|
210
|
-
value:
|
|
211
|
-
}, "strip",
|
|
205
|
+
readonly schema: import("@bpinternal/zui").ZodObject<{
|
|
206
|
+
text: import("@bpinternal/zui").ZodString;
|
|
207
|
+
options: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
208
|
+
label: import("@bpinternal/zui").ZodString;
|
|
209
|
+
value: import("@bpinternal/zui").ZodString;
|
|
210
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
212
211
|
value: string;
|
|
213
212
|
label: string;
|
|
214
213
|
}, {
|
|
215
214
|
value: string;
|
|
216
215
|
label: string;
|
|
217
216
|
}>, "many">;
|
|
218
|
-
}, "strip",
|
|
219
|
-
text: string;
|
|
217
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
220
218
|
options: {
|
|
221
219
|
value: string;
|
|
222
220
|
label: string;
|
|
223
221
|
}[];
|
|
224
|
-
}, {
|
|
225
222
|
text: string;
|
|
223
|
+
}, {
|
|
226
224
|
options: {
|
|
227
225
|
value: string;
|
|
228
226
|
label: string;
|
|
229
227
|
}[];
|
|
228
|
+
text: string;
|
|
230
229
|
}>;
|
|
231
230
|
};
|
|
232
231
|
};
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { z } from 'zod';
|
|
2
1
|
import { AnyZodObject } from './type-utils';
|
|
2
|
+
import type z from './zui';
|
|
3
3
|
type SchemaOptions<T> = {
|
|
4
4
|
title: string;
|
|
5
5
|
examples: T[];
|
|
@@ -10,6 +10,10 @@ type UiDefinition<TSchema extends AnyZodObject = AnyZodObject> = IsEmptyObject<z
|
|
|
10
10
|
};
|
|
11
11
|
export type SchemaDefinition<TSchema extends AnyZodObject = AnyZodObject> = {
|
|
12
12
|
schema: TSchema;
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated
|
|
15
|
+
* Use zod.Schema.displayAs() instead
|
|
16
|
+
**/
|
|
13
17
|
ui?: Partial<UiDefinition<TSchema>>;
|
|
14
18
|
};
|
|
15
19
|
export {};
|
package/dist/type-utils.d.ts
CHANGED
package/dist/zui.d.ts
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { z, type DefaultComponentDefinitions } from '@bpinternal/zui';
|
|
2
|
+
export * from '@bpinternal/zui';
|
|
3
|
+
export declare const studioComponentDefinitions: {
|
|
4
|
+
readonly string: {
|
|
5
|
+
readonly textInput: {
|
|
6
|
+
readonly id: "textInput";
|
|
7
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
8
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
9
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
10
|
+
multiLine: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
11
|
+
growVertically: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
12
|
+
suggestions: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodString, "many">>;
|
|
13
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
14
|
+
allowDynamicVariable?: boolean | undefined;
|
|
15
|
+
horizontal?: boolean | undefined;
|
|
16
|
+
multiLine?: boolean | undefined;
|
|
17
|
+
growVertically?: boolean | undefined;
|
|
18
|
+
suggestions?: string[] | undefined;
|
|
19
|
+
}, {
|
|
20
|
+
allowDynamicVariable?: boolean | undefined;
|
|
21
|
+
horizontal?: boolean | undefined;
|
|
22
|
+
multiLine?: boolean | undefined;
|
|
23
|
+
growVertically?: boolean | undefined;
|
|
24
|
+
suggestions?: string[] | undefined;
|
|
25
|
+
}>;
|
|
26
|
+
};
|
|
27
|
+
readonly dropdown: {
|
|
28
|
+
readonly id: "dropdown";
|
|
29
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
30
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
31
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
32
|
+
filterable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
33
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
34
|
+
allowDynamicVariable?: boolean | undefined;
|
|
35
|
+
horizontal?: boolean | undefined;
|
|
36
|
+
filterable?: boolean | undefined;
|
|
37
|
+
}, {
|
|
38
|
+
allowDynamicVariable?: boolean | undefined;
|
|
39
|
+
horizontal?: boolean | undefined;
|
|
40
|
+
filterable?: boolean | undefined;
|
|
41
|
+
}>;
|
|
42
|
+
};
|
|
43
|
+
readonly radiogroup: {
|
|
44
|
+
readonly id: "radiogroup";
|
|
45
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
46
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
47
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
48
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
49
|
+
allowDynamicVariable?: boolean | undefined;
|
|
50
|
+
horizontal?: boolean | undefined;
|
|
51
|
+
}, {
|
|
52
|
+
allowDynamicVariable?: boolean | undefined;
|
|
53
|
+
horizontal?: boolean | undefined;
|
|
54
|
+
}>;
|
|
55
|
+
};
|
|
56
|
+
readonly datepicker: {
|
|
57
|
+
readonly id: "datepicker";
|
|
58
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
59
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
60
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
61
|
+
dateFormat: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
62
|
+
minDate: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
63
|
+
maxDate: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
64
|
+
defaultTimezone: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
65
|
+
disableTimezoneSelection: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
66
|
+
highlightCurrentDay: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
67
|
+
showShortcutButtons: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
68
|
+
showOutsideDaysOfMonth: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
69
|
+
firstDayOfWeek: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodNumber>;
|
|
70
|
+
canChangeMonth: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
71
|
+
showWeekNumbers: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
72
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
73
|
+
allowDynamicVariable?: boolean | undefined;
|
|
74
|
+
horizontal?: boolean | undefined;
|
|
75
|
+
dateFormat?: string | undefined;
|
|
76
|
+
minDate?: string | undefined;
|
|
77
|
+
maxDate?: string | undefined;
|
|
78
|
+
defaultTimezone?: string | undefined;
|
|
79
|
+
disableTimezoneSelection?: boolean | undefined;
|
|
80
|
+
highlightCurrentDay?: boolean | undefined;
|
|
81
|
+
showShortcutButtons?: boolean | undefined;
|
|
82
|
+
showOutsideDaysOfMonth?: boolean | undefined;
|
|
83
|
+
firstDayOfWeek?: number | undefined;
|
|
84
|
+
canChangeMonth?: boolean | undefined;
|
|
85
|
+
showWeekNumbers?: boolean | undefined;
|
|
86
|
+
}, {
|
|
87
|
+
allowDynamicVariable?: boolean | undefined;
|
|
88
|
+
horizontal?: boolean | undefined;
|
|
89
|
+
dateFormat?: string | undefined;
|
|
90
|
+
minDate?: string | undefined;
|
|
91
|
+
maxDate?: string | undefined;
|
|
92
|
+
defaultTimezone?: string | undefined;
|
|
93
|
+
disableTimezoneSelection?: boolean | undefined;
|
|
94
|
+
highlightCurrentDay?: boolean | undefined;
|
|
95
|
+
showShortcutButtons?: boolean | undefined;
|
|
96
|
+
showOutsideDaysOfMonth?: boolean | undefined;
|
|
97
|
+
firstDayOfWeek?: number | undefined;
|
|
98
|
+
canChangeMonth?: boolean | undefined;
|
|
99
|
+
showWeekNumbers?: boolean | undefined;
|
|
100
|
+
}>;
|
|
101
|
+
};
|
|
102
|
+
readonly timepicker: {
|
|
103
|
+
readonly id: "timepicker";
|
|
104
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
105
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
106
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
107
|
+
useAMPM: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
108
|
+
timeFormat: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
109
|
+
minTime: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
110
|
+
maxTime: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
111
|
+
showArrowButtons: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
112
|
+
precision: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodEnum<["minute", "second", "millisecond"]>>;
|
|
113
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
114
|
+
allowDynamicVariable?: boolean | undefined;
|
|
115
|
+
horizontal?: boolean | undefined;
|
|
116
|
+
useAMPM?: boolean | undefined;
|
|
117
|
+
timeFormat?: string | undefined;
|
|
118
|
+
minTime?: string | undefined;
|
|
119
|
+
maxTime?: string | undefined;
|
|
120
|
+
showArrowButtons?: boolean | undefined;
|
|
121
|
+
precision?: "minute" | "second" | "millisecond" | undefined;
|
|
122
|
+
}, {
|
|
123
|
+
allowDynamicVariable?: boolean | undefined;
|
|
124
|
+
horizontal?: boolean | undefined;
|
|
125
|
+
useAMPM?: boolean | undefined;
|
|
126
|
+
timeFormat?: string | undefined;
|
|
127
|
+
minTime?: string | undefined;
|
|
128
|
+
maxTime?: string | undefined;
|
|
129
|
+
showArrowButtons?: boolean | undefined;
|
|
130
|
+
precision?: "minute" | "second" | "millisecond" | undefined;
|
|
131
|
+
}>;
|
|
132
|
+
};
|
|
133
|
+
readonly variablepicker: {
|
|
134
|
+
readonly id: "variablepicker";
|
|
135
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
136
|
+
type: import("@bpinternal/zui").ZodEnum<["any", "string", "number", "boolean", "object", "pattern", "date", "array", "target", "time", "enum"]>;
|
|
137
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
138
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
139
|
+
type: "string" | "number" | "boolean" | "object" | "array" | "any" | "pattern" | "date" | "target" | "time" | "enum";
|
|
140
|
+
horizontal?: boolean | undefined;
|
|
141
|
+
}, {
|
|
142
|
+
type: "string" | "number" | "boolean" | "object" | "array" | "any" | "pattern" | "date" | "target" | "time" | "enum";
|
|
143
|
+
horizontal?: boolean | undefined;
|
|
144
|
+
}>;
|
|
145
|
+
};
|
|
146
|
+
readonly richTextEditor: {
|
|
147
|
+
readonly id: "richTextEditor";
|
|
148
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
149
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
150
|
+
resizable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
151
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
152
|
+
allowDynamicVariable?: boolean | undefined;
|
|
153
|
+
resizable?: boolean | undefined;
|
|
154
|
+
}, {
|
|
155
|
+
allowDynamicVariable?: boolean | undefined;
|
|
156
|
+
resizable?: boolean | undefined;
|
|
157
|
+
}>;
|
|
158
|
+
};
|
|
159
|
+
readonly JSONInput: {
|
|
160
|
+
readonly id: "JSONInput";
|
|
161
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
162
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
163
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
164
|
+
showPreview: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
165
|
+
showValidationError: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
166
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
167
|
+
allowDynamicVariable?: boolean | undefined;
|
|
168
|
+
horizontal?: boolean | undefined;
|
|
169
|
+
showPreview?: boolean | undefined;
|
|
170
|
+
showValidationError?: boolean | undefined;
|
|
171
|
+
}, {
|
|
172
|
+
allowDynamicVariable?: boolean | undefined;
|
|
173
|
+
horizontal?: boolean | undefined;
|
|
174
|
+
showPreview?: boolean | undefined;
|
|
175
|
+
showValidationError?: boolean | undefined;
|
|
176
|
+
}>;
|
|
177
|
+
};
|
|
178
|
+
readonly fileInput: {
|
|
179
|
+
readonly id: "fileInput";
|
|
180
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
181
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
182
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
183
|
+
fileTypes: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodEnum<["image", "audio", "video"]>, "many">>;
|
|
184
|
+
showUploadedFiles: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
185
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
186
|
+
allowDynamicVariable?: boolean | undefined;
|
|
187
|
+
horizontal?: boolean | undefined;
|
|
188
|
+
fileTypes?: ("image" | "audio" | "video")[] | undefined;
|
|
189
|
+
showUploadedFiles?: boolean | undefined;
|
|
190
|
+
}, {
|
|
191
|
+
allowDynamicVariable?: boolean | undefined;
|
|
192
|
+
horizontal?: boolean | undefined;
|
|
193
|
+
fileTypes?: ("image" | "audio" | "video")[] | undefined;
|
|
194
|
+
showUploadedFiles?: boolean | undefined;
|
|
195
|
+
}>;
|
|
196
|
+
};
|
|
197
|
+
};
|
|
198
|
+
readonly number: {
|
|
199
|
+
readonly numberInput: {
|
|
200
|
+
readonly id: "numberInput";
|
|
201
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
202
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
203
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
204
|
+
allowNumericCharactersOnly: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
205
|
+
stepSize: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodNumber>;
|
|
206
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
207
|
+
allowDynamicVariable?: boolean | undefined;
|
|
208
|
+
horizontal?: boolean | undefined;
|
|
209
|
+
allowNumericCharactersOnly?: boolean | undefined;
|
|
210
|
+
stepSize?: number | undefined;
|
|
211
|
+
}, {
|
|
212
|
+
allowDynamicVariable?: boolean | undefined;
|
|
213
|
+
horizontal?: boolean | undefined;
|
|
214
|
+
allowNumericCharactersOnly?: boolean | undefined;
|
|
215
|
+
stepSize?: number | undefined;
|
|
216
|
+
}>;
|
|
217
|
+
};
|
|
218
|
+
readonly slider: {
|
|
219
|
+
readonly id: "slider";
|
|
220
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
221
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
222
|
+
stepSize: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodNumber>;
|
|
223
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
224
|
+
horizontal?: boolean | undefined;
|
|
225
|
+
stepSize?: number | undefined;
|
|
226
|
+
}, {
|
|
227
|
+
horizontal?: boolean | undefined;
|
|
228
|
+
stepSize?: number | undefined;
|
|
229
|
+
}>;
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
readonly boolean: {
|
|
233
|
+
readonly switch: {
|
|
234
|
+
readonly id: "switch";
|
|
235
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
236
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
237
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
238
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
239
|
+
allowDynamicVariable?: boolean | undefined;
|
|
240
|
+
horizontal?: boolean | undefined;
|
|
241
|
+
}, {
|
|
242
|
+
allowDynamicVariable?: boolean | undefined;
|
|
243
|
+
horizontal?: boolean | undefined;
|
|
244
|
+
}>;
|
|
245
|
+
};
|
|
246
|
+
};
|
|
247
|
+
readonly array: {
|
|
248
|
+
readonly optionList: {
|
|
249
|
+
readonly id: "optionList";
|
|
250
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
251
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
252
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
253
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
254
|
+
allowDynamicVariable?: boolean | undefined;
|
|
255
|
+
horizontal?: boolean | undefined;
|
|
256
|
+
}, {
|
|
257
|
+
allowDynamicVariable?: boolean | undefined;
|
|
258
|
+
horizontal?: boolean | undefined;
|
|
259
|
+
}>;
|
|
260
|
+
};
|
|
261
|
+
readonly stringList: {
|
|
262
|
+
readonly id: "stringList";
|
|
263
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
264
|
+
allowDynamicVariable: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
265
|
+
horizontal: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
266
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
267
|
+
allowDynamicVariable?: boolean | undefined;
|
|
268
|
+
horizontal?: boolean | undefined;
|
|
269
|
+
}, {
|
|
270
|
+
allowDynamicVariable?: boolean | undefined;
|
|
271
|
+
horizontal?: boolean | undefined;
|
|
272
|
+
}>;
|
|
273
|
+
};
|
|
274
|
+
};
|
|
275
|
+
readonly object: {
|
|
276
|
+
readonly collapsible: {
|
|
277
|
+
readonly id: "collapsible";
|
|
278
|
+
readonly params: import("@bpinternal/zui").ZodObject<{
|
|
279
|
+
defaultOpen: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
280
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
281
|
+
defaultOpen?: boolean | undefined;
|
|
282
|
+
}, {
|
|
283
|
+
defaultOpen?: boolean | undefined;
|
|
284
|
+
}>;
|
|
285
|
+
};
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
export type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio' ? typeof studioComponentDefinitions : Namespace extends 'dashboard' ? DefaultComponentDefinitions : any;
|
|
289
|
+
export default z;
|
|
290
|
+
export { z };
|
package/package.json
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botpress/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Botpress SDK",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"
|
|
9
|
-
"build:
|
|
10
|
-
"build": "
|
|
11
|
-
"
|
|
8
|
+
"type:check": "tsc --noEmit",
|
|
9
|
+
"build:type": "tsc --emitDeclarationOnly --declaration",
|
|
10
|
+
"build:node": "ts-node -T build.ts",
|
|
11
|
+
"build": "pnpm build:type && pnpm build:node"
|
|
12
12
|
},
|
|
13
13
|
"keywords": [],
|
|
14
14
|
"author": "",
|
|
15
15
|
"license": "MIT",
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@
|
|
18
|
-
"
|
|
17
|
+
"@bpinternal/zui": "0.6.2",
|
|
18
|
+
"@botpress/client": "0.14.0"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
21
|
"@types/node": "^18.11.17",
|
|
22
22
|
"esbuild": "^0.16.10",
|
|
23
23
|
"ts-node": "^10.9.1",
|
|
24
|
+
"tsup": "^8.0.2",
|
|
24
25
|
"type-fest": "^3.4.0",
|
|
25
26
|
"typescript": "^4.9.4"
|
|
26
27
|
}
|