@easbot/gateway-sdk 0.0.0-stage → 0.3.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +123 -0
- package/README.md +122 -2
- package/dist/index.cjs +7 -0
- package/dist/index.d.cts +559 -0
- package/dist/index.d.ts +559 -0
- package/dist/index.mjs +7 -0
- package/package.json +75 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 houjallen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.en.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
[中文](./README.md) | English
|
|
2
|
+
|
|
3
|
+
# @easbot/gateway-sdk
|
|
4
|
+
|
|
5
|
+
EasBot Gateway SDK — REST client for connecting to the EasBot Gateway server (multi-channel messaging routing hub).
|
|
6
|
+
|
|
7
|
+
## Version
|
|
8
|
+
|
|
9
|
+
v0.3.32
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- **Type Safety**: Full TypeScript support with auto-generated types
|
|
13
|
+
- **REST API Coverage**: Mirrors the Gateway server's `/health` `/status` `/channels` `/contacts` `/sessions` `/session` `/prompt` endpoints
|
|
14
|
+
- **Multi-Channel Routing**: Works with Telegram / Discord / Slack / Feishu / WeChat / WebChat and other messaging channels
|
|
15
|
+
- **OpenAPI Generated**: Auto-generated client from `openapi.json`
|
|
16
|
+
- **Directory Routing**: Set `directory` option to inject `x-easbot-directory|` header
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pnpm add @easbot/gateway-sdk
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
### Create a client
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { createEasbotGatewayClient } from '@easbot/gateway-sdk';
|
|
30
|
+
|
|
31
|
+
const client = createEasbotGatewayClient({
|
|
32
|
+
baseUrl: 'http://localhost:8080',
|
|
33
|
+
directory: '/path/to/project', // optional: auto-injected as a header
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// Health check
|
|
37
|
+
const health = await client.healthCheck();
|
|
38
|
+
|
|
39
|
+
// Get Gateway status
|
|
40
|
+
const status = await client.getStatus();
|
|
41
|
+
|
|
42
|
+
// List connected channels
|
|
43
|
+
const { channels } = await client.listChannels();
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Contacts / Sessions / Messages
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
// List contacts for a platform
|
|
50
|
+
const { contacts } = await client.listContacts({
|
|
51
|
+
platform: 'telegram',
|
|
52
|
+
limit: 50,
|
|
53
|
+
offset: 0,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Query / create sessions
|
|
57
|
+
const { sessions } = await client.listSessions({
|
|
58
|
+
platform: 'telegram',
|
|
59
|
+
userId: 'u1',
|
|
60
|
+
chatId: 'c1',
|
|
61
|
+
});
|
|
62
|
+
const session = await client.createSession({
|
|
63
|
+
body: {
|
|
64
|
+
title: 'New chat',
|
|
65
|
+
channel: { platform: 'telegram', channelId: 'tg-1', userId: 'u1', chatId: 'c1' },
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// Send a prompt
|
|
70
|
+
const res = await client.sendMessage({
|
|
71
|
+
id: session.id!,
|
|
72
|
+
body: {
|
|
73
|
+
content: [{ type: 'text', text: 'Hello, EASBot!' }],
|
|
74
|
+
channel: 'telegram',
|
|
75
|
+
userId: 'u1',
|
|
76
|
+
chatId: 'c1',
|
|
77
|
+
messageType: 'input',
|
|
78
|
+
agent: 'default',
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Spin up Gateway + Client in one call
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
import { createEasbotGateway } from '@easbot/gateway-sdk';
|
|
87
|
+
|
|
88
|
+
const { client, server } = await createEasbotGateway({
|
|
89
|
+
hostname: '127.0.0.1',
|
|
90
|
+
port: 8080,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// use client...
|
|
94
|
+
const health = await client.healthCheck();
|
|
95
|
+
|
|
96
|
+
// shutdown the spawned Gateway child process
|
|
97
|
+
server.close();
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Packages
|
|
101
|
+
|
|
102
|
+
- `@easbot/gateway-sdk` — Gateway REST client SDK (this package)
|
|
103
|
+
- `@easbot/sdk` — Main EasBot server SDK (port 4096)
|
|
104
|
+
|
|
105
|
+
## Development
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
# Install dependencies
|
|
109
|
+
pnpm install
|
|
110
|
+
|
|
111
|
+
# Regenerate the client from openapi.json
|
|
112
|
+
pnpm build
|
|
113
|
+
|
|
114
|
+
# Type-check
|
|
115
|
+
pnpm type-check
|
|
116
|
+
|
|
117
|
+
# Lint
|
|
118
|
+
pnpm lint
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
|
|
1
|
+
[English](./README.en.md) | 中文
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# @easbot/gateway-sdk
|
|
4
|
+
|
|
5
|
+
EasBot Gateway 客户端 SDK —— 用于连接 Gateway 服务器的 REST 客户端。
|
|
6
|
+
|
|
7
|
+
## 版本
|
|
8
|
+
|
|
9
|
+
v0.3.32
|
|
10
|
+
## 特性
|
|
11
|
+
|
|
12
|
+
- **类型安全**: 完整的 TypeScript 支持,类型由 OpenAPI 自动生成
|
|
13
|
+
- **REST API 完整覆盖**: 对齐 Gateway 服务器的 `/health` `/status` `/channels` `/contacts` `/sessions` `/session` `/prompt` 接口
|
|
14
|
+
- **多渠道消息路由**: 支持 Telegram / Discord / Slack / 飞书 / 微信 / WebChat 等渠道
|
|
15
|
+
- **OpenAPI 生成**: 从 `openapi.json` 自动生成客户端
|
|
16
|
+
- **目录路由**: 通过 `directory` 选项注入 `x-easbot-directory|` header
|
|
17
|
+
|
|
18
|
+
## 安装
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pnpm add @easbot/gateway-sdk
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## 使用
|
|
25
|
+
|
|
26
|
+
### 创建客户端
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { createEasbotGatewayClient } from '@easbot/gateway-sdk';
|
|
30
|
+
|
|
31
|
+
const client = createEasbotGatewayClient({
|
|
32
|
+
baseUrl: 'http://localhost:8080',
|
|
33
|
+
directory: '/path/to/project', // 可选:自动注入目录 header
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// 健康检查
|
|
37
|
+
const health = await client.healthCheck();
|
|
38
|
+
|
|
39
|
+
// 获取 Gateway 状态
|
|
40
|
+
const status = await client.getStatus();
|
|
41
|
+
|
|
42
|
+
// 列出已连接渠道
|
|
43
|
+
const { channels } = await client.listChannels();
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 联系人 / 会话 / 消息
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
// 列出平台联系人
|
|
50
|
+
const { contacts } = await client.listContacts({
|
|
51
|
+
platform: 'telegram',
|
|
52
|
+
limit: 50,
|
|
53
|
+
offset: 0,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// 查询 / 创建 Session
|
|
57
|
+
const { sessions } = await client.listSessions({
|
|
58
|
+
platform: 'telegram',
|
|
59
|
+
userId: 'u1',
|
|
60
|
+
chatId: 'c1',
|
|
61
|
+
});
|
|
62
|
+
const session = await client.createSession({
|
|
63
|
+
body: {
|
|
64
|
+
title: '新会话',
|
|
65
|
+
channel: { platform: 'telegram', channelId: 'tg-1', userId: 'u1', chatId: 'c1' },
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// 发送 prompt
|
|
70
|
+
const res = await client.sendMessage({
|
|
71
|
+
id: session.id!,
|
|
72
|
+
body: {
|
|
73
|
+
content: [{ type: 'text', text: '你好,EasBot!' }],
|
|
74
|
+
channel: 'telegram',
|
|
75
|
+
userId: 'u1',
|
|
76
|
+
chatId: 'c1',
|
|
77
|
+
messageType: 'input',
|
|
78
|
+
agent: 'default',
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### 一键启动 Gateway + Client
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
import { createEasbotGateway } from '@easbot/gateway-sdk';
|
|
87
|
+
|
|
88
|
+
const { client, server } = await createEasbotGateway({
|
|
89
|
+
hostname: '127.0.0.1',
|
|
90
|
+
port: 8080,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// 使用 client...
|
|
94
|
+
const health = await client.healthCheck();
|
|
95
|
+
|
|
96
|
+
// 程序退出时关闭 Gateway 子进程
|
|
97
|
+
server.close();
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## 包
|
|
101
|
+
|
|
102
|
+
- `@easbot/gateway-sdk` —— Gateway REST 客户端 SDK(当前包)
|
|
103
|
+
- `@easbot/sdk` —— EasBot 主服务 SDK(端口 4096)
|
|
104
|
+
|
|
105
|
+
## 开发
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
# 安装依赖
|
|
109
|
+
pnpm install
|
|
110
|
+
|
|
111
|
+
# 重新生成客户端(从 openapi.json)
|
|
112
|
+
pnpm build
|
|
113
|
+
|
|
114
|
+
# 类型检查
|
|
115
|
+
pnpm type-check
|
|
116
|
+
|
|
117
|
+
# Lint
|
|
118
|
+
pnpm lint
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## 许可证
|
|
122
|
+
|
|
123
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
'use strict';var child_process=require('child_process');var me=Object.defineProperty;var be=(r,t,e)=>t in r?me(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e;var R=(r,t,e)=>be(r,typeof t!="symbol"?t+"":t,e);function ne({onRequest:r,onSseError:t,onSseEvent:e,responseTransformer:n,responseValidator:i,sseDefaultRetryDelay:l,sseMaxRetryAttempts:o,sseMaxRetryDelay:a,sseSleepFn:s,url:c,...p}){let u,g=s??(d=>new Promise(y=>setTimeout(y,d)));return {stream:async function*(){let d=l??3e3,y=0,w=p.signal??new AbortController().signal;for(;!w.aborted;){y++;let C=p.headers instanceof Headers?p.headers:new Headers(p.headers);u!==void 0&&C.set("Last-Event-ID",u);try{let x={redirect:"follow",...p,body:p.serializedBody,headers:C,signal:w},G=new Request(c,x);r&&(G=await r(c,x));let m=await(p.fetch??globalThis.fetch)(G);if(!m.ok)throw new Error(`SSE failed: ${m.status} ${m.statusText}`);if(!m.body)throw new Error("No body in SSE response");let O=m.body.pipeThrough(new TextDecoderStream).getReader(),S="",Y=()=>{try{O.cancel();}catch{}};w.addEventListener("abort",Y);try{for(;;){let{done:fe,value:he}=await O.read();if(fe)break;S+=he,S=S.replace(/\r\n?/g,`
|
|
2
|
+
`);let Z=S.split(`
|
|
3
|
+
|
|
4
|
+
`);S=Z.pop()??"";for(let ge of Z){let we=ge.split(`
|
|
5
|
+
`),P=[],ee;for(let T of we)if(T.startsWith("data:"))P.push(T.replace(/^data:\s*/,""));else if(T.startsWith("event:"))ee=T.replace(/^event:\s*/,"");else if(T.startsWith("id:"))u=T.replace(/^id:\s*/,"");else if(T.startsWith("retry:")){let re=Number.parseInt(T.replace(/^retry:\s*/,""),10);Number.isNaN(re)||(d=re);}let q,te=!1;if(P.length){let T=P.join(`
|
|
6
|
+
`);try{q=JSON.parse(T),te=!0;}catch{q=T;}}te&&(i&&await i(q),n&&(q=await n(q))),e?.({data:q,event:ee,id:u,retry:d}),P.length&&(yield q);}}}finally{w.removeEventListener("abort",Y),O.releaseLock();}break}catch(x){if(t?.(x),o!==void 0&&y>=o)break;let G=Math.min(d*2**(y-1),a??3e4);await g(G);}}}()}}var Se=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},Re=r=>{switch(r){case "form":return ",";case "pipeDelimited":return "|";case "spaceDelimited":return "%20";default:return ","}},xe=r=>{switch(r){case "label":return ".";case "matrix":return ";";case "simple":return ",";default:return "&"}},z=({allowReserved:r,explode:t,name:e,style:n,value:i})=>{if(!t){let a=(r?i:i.map(s=>encodeURIComponent(s))).join(Re(n));switch(n){case "label":return `.${a}`;case "matrix":return `;${e}=${a}`;case "simple":return a;default:return `${e}=${a}`}}let l=Se(n),o=i.map(a=>n==="label"||n==="simple"?r?a:encodeURIComponent(a):v({allowReserved:r,name:e,value:a})).join(l);return n==="label"||n==="matrix"?l+o:o},v=({allowReserved:r,name:t,value:e})=>{if(e==null)return "";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return `${t}=${r?e:encodeURIComponent(e)}`},j=({allowReserved:r,explode:t,name:e,style:n,value:i,valueOnly:l})=>{if(i instanceof Date)return l?i.toISOString():`${e}=${i.toISOString()}`;if(n!=="deepObject"&&!t){let s=[];Object.entries(i).forEach(([p,u])=>{s=[...s,p,r?u:encodeURIComponent(u)];});let c=s.join(",");switch(n){case "form":return `${e}=${c}`;case "label":return `.${c}`;case "matrix":return `;${e}=${c}`;default:return c}}let o=xe(n),a=Object.entries(i).map(([s,c])=>v({allowReserved:r,name:n==="deepObject"?`${e}[${s}]`:s,value:c})).join(o);return n==="label"||n==="matrix"?o+a:a};var Oe=/\{[^{}]+\}/g,Te=({path:r,url:t})=>{let e=t,n=t.match(Oe);if(n)for(let i of n){let l=false,o=i.substring(1,i.length-1),a="simple";o.endsWith("*")&&(l=true,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),a="label"):o.startsWith(";")&&(o=o.substring(1),a="matrix");let s=r[o];if(s==null)continue;if(Array.isArray(s)){e=e.replace(i,z({explode:l,name:o,style:a,value:s}));continue}if(typeof s=="object"){e=e.replace(i,j({explode:l,name:o,style:a,value:s,valueOnly:true}));continue}if(a==="matrix"){e=e.replace(i,`;${v({name:o,value:s})}`);continue}let c=encodeURIComponent(a==="label"?`.${s}`:s);e=e.replace(i,c);}return e},se=({baseUrl:r,path:t,query:e,querySerializer:n,url:i})=>{let l=i.startsWith("/")?i:`/${i}`,o=(r??"")+l;t&&(o=Te({path:t,url:o}));let a=e?n(e):"";return a.startsWith("?")&&(a=a.substring(1)),a&&(o+=`?${a}`),o};function M(r){let t=r.body!==void 0;if(t&&r.bodySerializer)return "serializedBody"in r?r.serializedBody!==void 0&&r.serializedBody!==""?r.serializedBody:null:r.body!==""?r.body:null;if(t)return r.body}var oe=async(r,t)=>{let e=typeof t=="function"?await t(r):t;if(e)return r.scheme==="bearer"?`Bearer ${e}`:r.scheme==="basic"?`Basic ${btoa(e)}`:e};var H={bodySerializer:r=>JSON.stringify(r,(t,e)=>typeof e=="bigint"?e.toString():e)};var ae=({parameters:r={},...t}={})=>n=>{let i=[];if(n&&typeof n=="object")for(let l in n){let o=n[l];if(o==null)continue;let a=r[l]||t;if(Array.isArray(o)){let s=z({allowReserved:a.allowReserved,explode:true,name:l,style:"form",value:o,...a.array});s&&i.push(s);}else if(typeof o=="object"){let s=j({allowReserved:a.allowReserved,explode:true,name:l,style:"deepObject",value:o,...a.object});s&&i.push(s);}else {let s=v({allowReserved:a.allowReserved,name:l,value:o});s&&i.push(s);}}return i.join("&")},ie=r=>{if(!r)return "stream";let t=r.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return "json";if(t==="multipart/form-data")return "formData";if(["application/","audio/","image/","video/"].some(e=>t.startsWith(e)))return "blob";if(t.startsWith("text/"))return "text"}},Ce=(r,t)=>t?!!(r.headers.has(t)||r.query?.[t]||r.headers.get("Cookie")?.includes(`${t}=`)):false;async function le(r){for(let t of r.security??[]){if(Ce(r,t.name))continue;let e=await oe(t,r.auth);if(!e)continue;let n=t.name??"Authorization";switch(t.in){case "query":r.query||(r.query={}),r.query[n]=e;break;case "cookie":r.headers.append("Cookie",`${n}=${e}`);break;default:r.headers.set(n,e);break}}}var F=r=>se({baseUrl:r.baseUrl,path:r.path,query:r.query,querySerializer:typeof r.querySerializer=="function"?r.querySerializer:ae(r.querySerializer),url:r.url}),N=(r,t)=>{let e={...r,...t};return e.baseUrl?.endsWith("/")&&(e.baseUrl=e.baseUrl.substring(0,e.baseUrl.length-1)),e.headers=L(r.headers,t.headers),e},Ee=r=>{let t=[];return r.forEach((e,n)=>{t.push([n,e]);}),t},L=(...r)=>{let t=new Headers;for(let e of r){if(!e)continue;let n=e instanceof Headers?Ee(e):Object.entries(e);for(let[i,l]of n)if(l===null)t.delete(i);else if(Array.isArray(l))for(let o of l)t.append(i,o);else l!==void 0&&t.set(i,typeof l=="object"?JSON.stringify(l):l);}return t},I=class{constructor(){R(this,"fns",[]);}clear(){this.fns=[];}eject(t){let e=this.getInterceptorIndex(t);this.fns[e]&&(this.fns[e]=null);}exists(t){let e=this.getInterceptorIndex(t);return !!this.fns[e]}getInterceptorIndex(t){return typeof t=="number"?this.fns[t]?t:-1:this.fns.indexOf(t)}update(t,e){let n=this.getInterceptorIndex(t);return this.fns[n]?(this.fns[n]=e,t):false}use(t){return this.fns.push(t),this.fns.length-1}},pe=()=>({error:new I,request:new I,response:new I}),ke=ae({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}}),Ge={"Content-Type":"application/json"},A=(r={})=>({...H,headers:Ge,parseAs:"auto",querySerializer:ke,...r});var D=(r={})=>{let t=N(A(),r),e=()=>({...t}),n=p=>(t=N(t,p),e()),i=pe(),l=async p=>{let u={...t,...p,fetch:p.fetch??t.fetch??globalThis.fetch,headers:L(t.headers,p.headers),serializedBody:void 0};u.security&&await le(u),u.requestValidator&&await u.requestValidator(u),u.body!==void 0&&u.bodySerializer&&(u.serializedBody=u.bodySerializer(u.body)),(u.body===void 0||u.serializedBody==="")&&u.headers.delete("Content-Type");let g=u,f=F(g);return {opts:g,url:f}},o=async p=>{let u=p.throwOnError??t.throwOnError,g=p.responseStyle??t.responseStyle,f,h;try{let{opts:d,url:y}=await l(p),w={redirect:"follow",...d,body:M(d)};f=new Request(y,w);for(let m of i.request.fns)m&&(f=await m(f,d));let C=d.fetch;h=await C(f);for(let m of i.response.fns)m&&(h=await m(h,f,d));let x={request:f,response:h};if(h.ok){let m=(d.parseAs==="auto"?ie(h.headers.get("Content-Type")):d.parseAs)??"json";if(h.status===204||h.headers.get("Content-Length")==="0"){let S;switch(m){case "arrayBuffer":case "blob":case "text":S=await h[m]();break;case "formData":S=new FormData;break;case "stream":S=h.body;break;default:S={};break}return d.responseStyle==="data"?S:{data:S,...x}}let O;switch(m){case "arrayBuffer":case "blob":case "formData":case "text":O=await h[m]();break;case "json":{let S=await h.text();O=S?JSON.parse(S):{};break}case "stream":return d.responseStyle==="data"?h.body:{data:h.body,...x}}return m==="json"&&(d.responseValidator&&await d.responseValidator(O),d.responseTransformer&&(O=await d.responseTransformer(O))),d.responseStyle==="data"?O:{data:O,...x}}let G=await h.text(),$;try{$=JSON.parse(G);}catch{}throw $??G}catch(d){let y=d;for(let w of i.error.fns)w&&(y=await w(y,h,f,p));if(y=y||{},u)throw y;return g==="data"?void 0:{error:y,request:f,response:h}}},a=p=>u=>o({...u,method:p}),s=p=>async u=>{let{opts:g,url:f}=await l(u);return ne({...g,body:g.body,method:p,onRequest:async(h,d)=>{let y=new Request(h,d);for(let w of i.request.fns)w&&(y=await w(y,g));return y},serializedBody:M(g),url:f})};return {buildUrl:p=>F({...t,...p}),connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),getConfig:e,head:a("HEAD"),interceptors:i,options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),request:o,setConfig:n,sse:{connect:s("CONNECT"),delete:s("DELETE"),get:s("GET"),head:s("HEAD"),options:s("OPTIONS"),patch:s("PATCH"),post:s("POST"),put:s("PUT"),trace:s("TRACE")},trace:a("TRACE")}};var qe={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},ve=Object.entries(qe);function ue(r,t){t||(t=new Map);for(let e of r)"in"in e?e.key&&t.set(e.key,{in:e.in,map:e.map}):"key"in e?t.set(e.key,{map:e.map}):e.args&&ue(e.args,t);return t}function Ie(r){for(let[t,e]of Object.entries(r))t!=="body"&&e&&typeof e=="object"&&!Array.isArray(e)&&!Object.keys(e).length&&delete r[t];}function E(r,t){let e={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},n=ue(t);function i(o,a,s){let c=e[o];c===void 0&&(c=Object.create(null),e[o]=c),c[a]=s;}let l;for(let[o,a]of r.entries())if(t[o]&&(l=t[o]),!!l)if("in"in l)if(l.key){let s=n.get(l.key),c=s.map||l.key;s.in&&i(s.in,c,a);}else e.body=a;else for(let[s,c]of Object.entries(a??{})){let p=n.get(s);if(p)if(p.in){let u=p.map||s;i(p.in,u,c);}else e[p.map]=c;else {let u=ve.find(([g])=>s.startsWith(g));if(u){let[g,f]=u;i(f,s.slice(g.length),c);}else if("allowExtra"in l&&l.allowExtra){for(let[g,f]of Object.entries(l.allowExtra))if(f){i(g,s,c);break}}}}return Ie(e),e}var ce=D(A({baseUrl:"http://localhost:8080"}));var k=class{constructor(t){R(this,"client");this.client=t?.client??ce;}},_=class{constructor(){R(this,"defaultKey","default");R(this,"instances",new Map);}get(t){let e=this.instances.get(t??this.defaultKey);if(!e)throw new Error('No SDK client found. Create one with "new EasbotGatewayClient()" to fix this error.');return e}set(t,e){this.instances.set(e??this.defaultKey,t);}},V=class extends k{list(t){return (t?.client??this.client).get({url:"/channels",...t})}},J=class extends k{list(t,e){let n=E([t],[{args:[{in:"query",key:"platform"},{in:"query",key:"limit"},{in:"query",key:"offset"}]}]);return (e?.client??this.client).get({url:"/contacts",...e,...n})}get(t,e){let n=E([t],[{args:[{in:"path",key:"uid"}]}]);return (e?.client??this.client).get({url:"/contacts/{uid}",...e,...n})}},W=class extends k{list(t,e){let n=E([t],[{args:[{in:"query",key:"platform"},{in:"query",key:"channelId"},{in:"query",key:"userId"},{in:"query",key:"chatId"},{in:"query",key:"limit"},{in:"query",key:"offset"}]}]);return (e?.client??this.client).get({url:"/sessions",...e,...n})}get(t,e){let n=E([t],[{args:[{in:"path",key:"sessionId"}]}]);return (e?.client??this.client).get({url:"/sessions/{sessionId}",...e,...n})}},K=class extends k{create(t,e){let n=E([t],[{args:[{key:"body",map:"body"}]}]);return (e?.client??this.client).post({url:"/session",...e,...n,headers:{"Content-Type":"application/json",...e?.headers,...n.headers}})}prompt(t,e){let n=E([t],[{args:[{in:"path",key:"sessionId"},{key:"body",map:"body"}]}]);return (e?.client??this.client).post({url:"/session/{sessionId}/prompt",...e,...n,headers:{"Content-Type":"application/json",...e?.headers,...n.headers}})}},Q=class extends k{list(t,e){let n=E([t],[{args:[{in:"query",key:"sessionId"},{in:"query",key:"subscriberId"}]}]);return (e?.client??this.client).get({url:"/subscriptions",...e,...n})}},X=class extends k{constructor(){super(...arguments);R(this,"_channels");R(this,"_contacts");R(this,"_sessions");R(this,"_session");R(this,"_subscriptions");}health(e){return (e?.client??this.client).get({url:"/health",...e})}status(e){return (e?.client??this.client).get({url:"/status",...e})}get channels(){return this._channels??(this._channels=new V({client:this.client}))}get contacts(){return this._contacts??(this._contacts=new J({client:this.client}))}get sessions(){return this._sessions??(this._sessions=new W({client:this.client}))}get session(){return this._session??(this._session=new K({client:this.client}))}get subscriptions(){return this._subscriptions??(this._subscriptions=new Q({client:this.client}))}},B=class B extends k{constructor(e){super(e);R(this,"_gateway");B.__registry.set(this,e?.key);}get gateway(){return this._gateway??(this._gateway=new X({client:this.client}))}};R(B,"__registry",new _);var U=B;function ye(r){if(r?.fetch||(r={...r,fetch:n=>(n.timeout=false,fetch(n))}),r?.directory){let n=/[^\p{ASCII}]/u.test(r.directory)?encodeURIComponent(r.directory):r.directory;r.headers={...r.headers,"x-easbot-directory":n};}let t=D(r);return new U({client:t})}function De(r){if(r.includes("/")||r.includes("\\"))return r;if(process.platform==="win32"){let t=r.toLowerCase();if(!t.endsWith(".cmd")&&!t.endsWith(".exe")&&!t.endsWith(".bat"))return `${r}.cmd`}return r}function Pe(r,t,e){let n=r.config??{};return {...n,server:{...n.server??{},...t!==void 0?{port:t}:{},...e?{hostname:e}:{}}}}var ze=8080,je="127.0.0.1",Le=3e5;async function de(r){let e=Object.assign({hostname:je,port:ze,timeout:Le},r??{}),n=r&&"port"in r?r.port:void 0,i=r&&"hostname"in r?r.hostname:void 0,l=["gateway","start"],o=child_process.spawn(De("easbot"),l,{signal:e.signal,shell:process.platform==="win32",env:{...process.env,EASBOT_CONFIG_CONTENT:JSON.stringify(Pe(e,n,i))}});return {url:await new Promise((s,c)=>{let p=false,u=null,g=null,f=()=>{u&&clearTimeout(u),g&&clearInterval(g);},h=`${e.port===443?"https":"http"}://${e.hostname}:${e.port}/health`,d=()=>{g=setInterval(async()=>{try{let y=new AbortController,w=setTimeout(()=>y.abort(),2e3),C=await fetch(h,{signal:y.signal});clearTimeout(w),C.ok&&(p||(p=!0,f(),s(h)));}catch{}},500);};o.stdout?.on("data",y=>{let w=y.toString();for(let C of w.split(`
|
|
7
|
+
`))if(C.startsWith("easbot gateway listening")){let x=C.match(/on\s+(https?:\/\/[^\s]+)/);if(x&&!p){p=true,f(),s(x[1]);return}}}),o.stderr?.on("data",()=>{}),o.on("exit",y=>{if(p)return;f();let w=`Gateway server exited with code ${y}`;c(new Error(w));}),o.on("error",y=>{p||(f(),c(y));}),u=setTimeout(()=>{p||(f(),c(new Error(`Timeout waiting for gateway server to start after ${e.timeout}ms`)));},e.timeout),e.signal&&e.signal.addEventListener("abort",()=>{p||(f(),c(new Error("Aborted")));}),d();}),close(){o.kill();}}}async function Nt(r){let t=await de({...r});return {client:ye({baseUrl:t.url}),server:t}}exports.EasbotGatewayClient=U;exports.createEasbotGateway=Nt;exports.createEasbotGatewayClient=ye;exports.createEasbotGatewayServer=de;
|