@tabsystems/onechat 0.0.0-stage → 0.1.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/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +228 -2
- package/dist-npm/index.cjs +291 -0
- package/dist-npm/index.d.cts +480 -0
- package/dist-npm/index.d.ts +480 -0
- package/dist-npm/index.js +292 -0
- package/dist-npm/protocol-B6LQsEpd.cjs +209 -0
- package/dist-npm/protocol-oujowiFb.js +210 -0
- package/dist-npm/protocol.cjs +25 -0
- package/dist-npm/protocol.d.cts +380 -0
- package/dist-npm/protocol.d.ts +380 -0
- package/dist-npm/protocol.js +25 -0
- package/package.json +92 -3
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { k as errorAnswerSchema, c as WEBHOOK_HEADER, d as WEBHOOK_TOLERANCE_SECONDS, a as API_CHANNEL_PATH, g as handoverRequestSchema, l as handoverAnswerSchema, s as sendMessageRequestSchema, n as sendMessageAnswerSchema, w as webhookEventSchema, u as unknownWebhookEventSchema } from "./protocol-oujowiFb.js";
|
|
2
|
+
import { A, H, M, b, R, U, W, e, f, h, m, i, q, r, j } from "./protocol-oujowiFb.js";
|
|
3
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
4
|
+
const ONECHAT_DEFAULT_BASE_URL = "https://onechat.tabsystems.tech";
|
|
5
|
+
const ONECHAT_DEFAULT_TIMEOUT_MS = 15e3;
|
|
6
|
+
const ONECHAT_DEFAULT_MAX_RETRIES = 2;
|
|
7
|
+
const ONECHAT_RETRY_BASE_DELAY_MS = 500;
|
|
8
|
+
const ONECHAT_RETRY_JITTER_SHARE = 0.5;
|
|
9
|
+
const ONECHAT_MAX_RETRY_DELAY_MS = 1e4;
|
|
10
|
+
const HTTP_STATUS_TOO_MANY_REQUESTS = 429;
|
|
11
|
+
const HTTP_STATUS_SERVER_ERROR_MIN = 500;
|
|
12
|
+
const MS_PER_SECOND = 1e3;
|
|
13
|
+
const AUTHORIZATION_SCHEME = "Bearer";
|
|
14
|
+
const JSON_CONTENT_TYPE = "application/json";
|
|
15
|
+
const RETRY_AFTER_HEADER = "retry-after";
|
|
16
|
+
const RETRY_AFTER_SECONDS_PATTERN = /^\d+$/;
|
|
17
|
+
const UNEXPECTED_ANSWER_MESSAGE = "Unexpected answer from OneChat";
|
|
18
|
+
const TRAILING_SLASHES_PATTERN = /\/+$/;
|
|
19
|
+
const HANDOVER_CALL_OUTCOME = {
|
|
20
|
+
handed: "handed",
|
|
21
|
+
already: "already",
|
|
22
|
+
notified: "notified"
|
|
23
|
+
};
|
|
24
|
+
const WEBHOOK_SIGNATURE_ALGORITHM = "sha256";
|
|
25
|
+
const WEBHOOK_SIGNATURE_ENCODING = "hex";
|
|
26
|
+
const WEBHOOK_SIGNATURE_SEPARATOR = ",";
|
|
27
|
+
const WEBHOOK_SIGNATURE_PATTERN = /^[0-9a-f]{64}$/;
|
|
28
|
+
const WEBHOOK_TIMESTAMP_PATTERN = /^\d+$/;
|
|
29
|
+
const WEBHOOK_VERIFICATION_REASON = {
|
|
30
|
+
missingHeader: "missingHeader",
|
|
31
|
+
invalidTimestamp: "invalidTimestamp",
|
|
32
|
+
timestampOutOfTolerance: "timestampOutOfTolerance",
|
|
33
|
+
invalidSignature: "invalidSignature",
|
|
34
|
+
invalidPayload: "invalidPayload"
|
|
35
|
+
};
|
|
36
|
+
class OneChatApiError extends Error {
|
|
37
|
+
constructor(status, error, body, retryAfterSeconds2 = null) {
|
|
38
|
+
super(`OneChat answered ${status}: ${error}`);
|
|
39
|
+
this.status = status;
|
|
40
|
+
this.error = error;
|
|
41
|
+
this.body = body;
|
|
42
|
+
this.retryAfterSeconds = retryAfterSeconds2;
|
|
43
|
+
}
|
|
44
|
+
status;
|
|
45
|
+
error;
|
|
46
|
+
body;
|
|
47
|
+
retryAfterSeconds;
|
|
48
|
+
name = "OneChatApiError";
|
|
49
|
+
}
|
|
50
|
+
class OneChatConnectionError extends Error {
|
|
51
|
+
name = "OneChatConnectionError";
|
|
52
|
+
constructor(options) {
|
|
53
|
+
super("Could not reach OneChat", options);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
class OneChatTimeoutError extends Error {
|
|
57
|
+
constructor(timeoutMs, options) {
|
|
58
|
+
super(`OneChat did not answer within ${timeoutMs} ms`, options);
|
|
59
|
+
this.timeoutMs = timeoutMs;
|
|
60
|
+
}
|
|
61
|
+
timeoutMs;
|
|
62
|
+
name = "OneChatTimeoutError";
|
|
63
|
+
}
|
|
64
|
+
class OneChatWebhookVerificationError extends Error {
|
|
65
|
+
constructor(reason, message) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.reason = reason;
|
|
68
|
+
}
|
|
69
|
+
reason;
|
|
70
|
+
name = "OneChatWebhookVerificationError";
|
|
71
|
+
}
|
|
72
|
+
const sleep = (ms) => {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
setTimeout(resolve, ms);
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
const backoffMs = (retry) => {
|
|
78
|
+
const ceiling = ONECHAT_RETRY_BASE_DELAY_MS * 2 ** retry;
|
|
79
|
+
const fixed = ceiling * (1 - ONECHAT_RETRY_JITTER_SHARE);
|
|
80
|
+
return fixed + Math.random() * (ceiling - fixed);
|
|
81
|
+
};
|
|
82
|
+
const retryAfterSeconds = (response) => {
|
|
83
|
+
const raw = response.headers.get(RETRY_AFTER_HEADER)?.trim();
|
|
84
|
+
if (!raw) return null;
|
|
85
|
+
if (RETRY_AFTER_SECONDS_PATTERN.test(raw)) return Number(raw);
|
|
86
|
+
const at = Date.parse(raw);
|
|
87
|
+
return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / MS_PER_SECOND));
|
|
88
|
+
};
|
|
89
|
+
const isRetryableStatus = (status) => {
|
|
90
|
+
return status === HTTP_STATUS_TOO_MANY_REQUESTS || status >= HTTP_STATUS_SERVER_ERROR_MIN;
|
|
91
|
+
};
|
|
92
|
+
const parseJson = (text) => {
|
|
93
|
+
try {
|
|
94
|
+
return JSON.parse(text);
|
|
95
|
+
} catch {
|
|
96
|
+
return text;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const toApiError = ({ response, text }) => {
|
|
100
|
+
const body = parseJson(text);
|
|
101
|
+
const answer = errorAnswerSchema.safeParse(body);
|
|
102
|
+
return new OneChatApiError(
|
|
103
|
+
response.status,
|
|
104
|
+
answer.success ? answer.data.error : `HTTP ${response.status}`,
|
|
105
|
+
body,
|
|
106
|
+
retryAfterSeconds(response)
|
|
107
|
+
);
|
|
108
|
+
};
|
|
109
|
+
const retryDelayMs = (error, retry) => {
|
|
110
|
+
if (!(error instanceof OneChatApiError)) return backoffMs(retry);
|
|
111
|
+
if (!isRetryableStatus(error.status)) return null;
|
|
112
|
+
const delayMs = error.retryAfterSeconds === null ? backoffMs(retry) : error.retryAfterSeconds * MS_PER_SECOND;
|
|
113
|
+
return delayMs > ONECHAT_MAX_RETRY_DELAY_MS ? null : delayMs;
|
|
114
|
+
};
|
|
115
|
+
const createOneChatRequest = (options) => {
|
|
116
|
+
const baseUrl = new URL(options.baseUrl ?? ONECHAT_DEFAULT_BASE_URL).href.replace(TRAILING_SLASHES_PATTERN, "");
|
|
117
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
118
|
+
const timeoutMs = options.timeoutMs ?? ONECHAT_DEFAULT_TIMEOUT_MS;
|
|
119
|
+
const maxRetries = options.maxRetries ?? ONECHAT_DEFAULT_MAX_RETRIES;
|
|
120
|
+
const send = async (path, body) => {
|
|
121
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
122
|
+
try {
|
|
123
|
+
const response = await fetchImpl(`${baseUrl}${path}`, {
|
|
124
|
+
method: "POST",
|
|
125
|
+
headers: {
|
|
126
|
+
Authorization: `${AUTHORIZATION_SCHEME} ${options.apiKey}`,
|
|
127
|
+
"Content-Type": JSON_CONTENT_TYPE,
|
|
128
|
+
Accept: JSON_CONTENT_TYPE
|
|
129
|
+
},
|
|
130
|
+
body: JSON.stringify(body),
|
|
131
|
+
signal
|
|
132
|
+
});
|
|
133
|
+
return { response, text: await response.text() };
|
|
134
|
+
} catch (err) {
|
|
135
|
+
if (signal.aborted) throw new OneChatTimeoutError(timeoutMs, { cause: err });
|
|
136
|
+
throw new OneChatConnectionError({ cause: err });
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const attempt = async (path, body, answerSchema) => {
|
|
140
|
+
const answer = await send(path, body);
|
|
141
|
+
if (!answer.response.ok) throw toApiError(answer);
|
|
142
|
+
const json = parseJson(answer.text);
|
|
143
|
+
const parsed = answerSchema.safeParse(json);
|
|
144
|
+
if (parsed.success) return parsed.data;
|
|
145
|
+
throw new OneChatApiError(answer.response.status, UNEXPECTED_ANSWER_MESSAGE, json);
|
|
146
|
+
};
|
|
147
|
+
const post = async (path, body, answerSchema, retry = 0) => {
|
|
148
|
+
try {
|
|
149
|
+
return await attempt(path, body, answerSchema);
|
|
150
|
+
} catch (err) {
|
|
151
|
+
const delayMs = retryDelayMs(err, retry);
|
|
152
|
+
if (retry >= maxRetries || delayMs === null) throw err;
|
|
153
|
+
await sleep(delayMs);
|
|
154
|
+
return post(path, body, answerSchema, retry + 1);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
return { post };
|
|
158
|
+
};
|
|
159
|
+
const computeWebhookSignature = (secret, timestamp, rawBody) => {
|
|
160
|
+
return createHmac(WEBHOOK_SIGNATURE_ALGORITHM, secret).update(`${timestamp}.`).update(rawBody).digest(WEBHOOK_SIGNATURE_ENCODING);
|
|
161
|
+
};
|
|
162
|
+
const matches = (expected, signature) => {
|
|
163
|
+
if (!WEBHOOK_SIGNATURE_PATTERN.test(signature)) return false;
|
|
164
|
+
return timingSafeEqual(expected, Buffer.from(signature, WEBHOOK_SIGNATURE_ENCODING));
|
|
165
|
+
};
|
|
166
|
+
const verifyWebhookSignature = ({
|
|
167
|
+
rawBody,
|
|
168
|
+
signature,
|
|
169
|
+
timestamp,
|
|
170
|
+
secret,
|
|
171
|
+
toleranceSeconds = WEBHOOK_TOLERANCE_SECONDS,
|
|
172
|
+
now = /* @__PURE__ */ new Date()
|
|
173
|
+
}) => {
|
|
174
|
+
if (!signature || !timestamp) {
|
|
175
|
+
throw new OneChatWebhookVerificationError(
|
|
176
|
+
WEBHOOK_VERIFICATION_REASON.missingHeader,
|
|
177
|
+
`Missing ${WEBHOOK_HEADER.signature} or ${WEBHOOK_HEADER.timestamp} header`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
if (!WEBHOOK_TIMESTAMP_PATTERN.test(timestamp)) {
|
|
181
|
+
throw new OneChatWebhookVerificationError(
|
|
182
|
+
WEBHOOK_VERIFICATION_REASON.invalidTimestamp,
|
|
183
|
+
"Webhook timestamp is not Unix seconds"
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
if (Math.abs(now.getTime() / MS_PER_SECOND - Number(timestamp)) > toleranceSeconds) {
|
|
187
|
+
throw new OneChatWebhookVerificationError(
|
|
188
|
+
WEBHOOK_VERIFICATION_REASON.timestampOutOfTolerance,
|
|
189
|
+
`Webhook timestamp is more than ${toleranceSeconds} s from now`
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
const expected = Buffer.from(computeWebhookSignature(secret, timestamp, rawBody), WEBHOOK_SIGNATURE_ENCODING);
|
|
193
|
+
const genuine = signature.split(WEBHOOK_SIGNATURE_SEPARATOR).some((candidate) => {
|
|
194
|
+
return matches(expected, candidate.trim());
|
|
195
|
+
});
|
|
196
|
+
if (!genuine) {
|
|
197
|
+
throw new OneChatWebhookVerificationError(
|
|
198
|
+
WEBHOOK_VERIFICATION_REASON.invalidSignature,
|
|
199
|
+
"Webhook signature does not match"
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
const useOneChat = (options) => {
|
|
204
|
+
const request = createOneChatRequest(options);
|
|
205
|
+
const send = async (message) => {
|
|
206
|
+
const answer = await request.post(
|
|
207
|
+
API_CHANNEL_PATH.messages,
|
|
208
|
+
sendMessageRequestSchema.parse(message),
|
|
209
|
+
sendMessageAnswerSchema
|
|
210
|
+
);
|
|
211
|
+
return { duplicate: answer.duplicate === true };
|
|
212
|
+
};
|
|
213
|
+
const handover = async (input) => {
|
|
214
|
+
const answer = await request.post(
|
|
215
|
+
API_CHANNEL_PATH.handover,
|
|
216
|
+
handoverRequestSchema.parse(input),
|
|
217
|
+
handoverAnswerSchema
|
|
218
|
+
);
|
|
219
|
+
if (answer.already) return { outcome: HANDOVER_CALL_OUTCOME.already };
|
|
220
|
+
if (answer.notified) return { outcome: HANDOVER_CALL_OUTCOME.notified };
|
|
221
|
+
return { outcome: HANDOVER_CALL_OUTCOME.handed };
|
|
222
|
+
};
|
|
223
|
+
return { messages: { send }, conversations: { handover } };
|
|
224
|
+
};
|
|
225
|
+
const readHeader = (headers, name) => {
|
|
226
|
+
const { get } = headers;
|
|
227
|
+
if (typeof get === "function") return get.call(headers, name) ?? void 0;
|
|
228
|
+
const entry = Object.entries(headers).find(([key]) => {
|
|
229
|
+
return key.toLowerCase() === name;
|
|
230
|
+
})?.[1];
|
|
231
|
+
return Array.isArray(entry) ? entry[0] : entry;
|
|
232
|
+
};
|
|
233
|
+
const invalidPayload = (message) => {
|
|
234
|
+
return new OneChatWebhookVerificationError(WEBHOOK_VERIFICATION_REASON.invalidPayload, message);
|
|
235
|
+
};
|
|
236
|
+
const parseBody = (rawBody) => {
|
|
237
|
+
try {
|
|
238
|
+
return JSON.parse(typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody));
|
|
239
|
+
} catch {
|
|
240
|
+
throw invalidPayload("Webhook body is not JSON");
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const constructWebhookEvent = (rawBody, headers, secret, options = {}) => {
|
|
244
|
+
verifyWebhookSignature({
|
|
245
|
+
rawBody,
|
|
246
|
+
signature: readHeader(headers, WEBHOOK_HEADER.signature),
|
|
247
|
+
timestamp: readHeader(headers, WEBHOOK_HEADER.timestamp),
|
|
248
|
+
secret,
|
|
249
|
+
...options
|
|
250
|
+
});
|
|
251
|
+
const body = parseBody(rawBody);
|
|
252
|
+
const known = webhookEventSchema.safeParse(body);
|
|
253
|
+
if (known.success) return known.data;
|
|
254
|
+
const unknown = unknownWebhookEventSchema.safeParse(body);
|
|
255
|
+
if (unknown.success) return unknown.data;
|
|
256
|
+
throw invalidPayload("Webhook body is not a OneChat event");
|
|
257
|
+
};
|
|
258
|
+
export {
|
|
259
|
+
A as API_CHANNEL_LIMIT,
|
|
260
|
+
API_CHANNEL_PATH,
|
|
261
|
+
HANDOVER_CALL_OUTCOME,
|
|
262
|
+
H as HANDOVER_REASON,
|
|
263
|
+
M as MESSAGE_FAILED_REASON,
|
|
264
|
+
b as MESSAGE_FROM,
|
|
265
|
+
ONECHAT_DEFAULT_BASE_URL,
|
|
266
|
+
OneChatApiError,
|
|
267
|
+
OneChatConnectionError,
|
|
268
|
+
OneChatTimeoutError,
|
|
269
|
+
OneChatWebhookVerificationError,
|
|
270
|
+
R as RETURNED_TO_BOT_REASON,
|
|
271
|
+
U as UNKNOWN_WEBHOOK_EVENT,
|
|
272
|
+
W as WEBHOOK_EVENT_TYPE,
|
|
273
|
+
WEBHOOK_HEADER,
|
|
274
|
+
WEBHOOK_TOLERANCE_SECONDS,
|
|
275
|
+
WEBHOOK_VERIFICATION_REASON,
|
|
276
|
+
e as attachmentSchema,
|
|
277
|
+
f as buttonSchema,
|
|
278
|
+
computeWebhookSignature,
|
|
279
|
+
constructWebhookEvent,
|
|
280
|
+
h as handedToStaffEventSchema,
|
|
281
|
+
handoverRequestSchema,
|
|
282
|
+
m as messageCreatedEventSchema,
|
|
283
|
+
i as messageFailedEventSchema,
|
|
284
|
+
q as quickReplySchema,
|
|
285
|
+
r as returnedToBotEventSchema,
|
|
286
|
+
sendMessageRequestSchema,
|
|
287
|
+
unknownWebhookEventSchema,
|
|
288
|
+
useOneChat,
|
|
289
|
+
verifyWebhookSignature,
|
|
290
|
+
webhookEventSchema,
|
|
291
|
+
j as webhookTestEventSchema
|
|
292
|
+
};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const zod = require("zod");
|
|
3
|
+
const API_CHANNEL_PATH = {
|
|
4
|
+
messages: "/api/v1/conversations/messages",
|
|
5
|
+
handover: "/api/v1/conversations/handover"
|
|
6
|
+
};
|
|
7
|
+
const API_CHANNEL_LIMIT = {
|
|
8
|
+
idMaxLength: 128,
|
|
9
|
+
textMaxLength: 2e3,
|
|
10
|
+
payloadMaxLength: 1e3,
|
|
11
|
+
userNameMaxLength: 100,
|
|
12
|
+
duplicateWindowDays: 30
|
|
13
|
+
};
|
|
14
|
+
const WEBHOOK_HEADER = {
|
|
15
|
+
eventId: "x-onechat-event-id",
|
|
16
|
+
timestamp: "x-onechat-timestamp",
|
|
17
|
+
signature: "x-onechat-signature"
|
|
18
|
+
};
|
|
19
|
+
const WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
20
|
+
const UNKNOWN_WEBHOOK_EVENT = { type: "unknown" };
|
|
21
|
+
const WEBHOOK_EVENT_TYPE = {
|
|
22
|
+
messageCreated: "message.created",
|
|
23
|
+
messageFailed: "message.failed",
|
|
24
|
+
handedToStaff: "conversation.handed_to_staff",
|
|
25
|
+
returnedToBot: "conversation.returned_to_bot",
|
|
26
|
+
webhookTest: "webhook.test"
|
|
27
|
+
};
|
|
28
|
+
const MESSAGE_FROM = {
|
|
29
|
+
bot: "bot",
|
|
30
|
+
staff: "staff",
|
|
31
|
+
system: "system"
|
|
32
|
+
};
|
|
33
|
+
const MESSAGE_FAILED_REASON = {
|
|
34
|
+
aiError: "ai_error",
|
|
35
|
+
expired: "expired"
|
|
36
|
+
};
|
|
37
|
+
const HANDOVER_REASON = {
|
|
38
|
+
humanRequest: "human_request",
|
|
39
|
+
tenantRequest: "tenant_request",
|
|
40
|
+
agentDecision: "agent_decision",
|
|
41
|
+
aiError: "ai_error",
|
|
42
|
+
limitReached: "limit_reached",
|
|
43
|
+
noModel: "no_model",
|
|
44
|
+
staff: "staff"
|
|
45
|
+
};
|
|
46
|
+
const RETURNED_TO_BOT_REASON = {
|
|
47
|
+
staff: "staff",
|
|
48
|
+
user: "user",
|
|
49
|
+
timeout: "timeout"
|
|
50
|
+
};
|
|
51
|
+
const idField = zod.z.string().min(1).max(API_CHANNEL_LIMIT.idMaxLength).regex(/^[^\s\p{Cc}]+$/u, "must not contain whitespace or control characters");
|
|
52
|
+
const hasNoNul = (value) => {
|
|
53
|
+
return !value.includes("\0");
|
|
54
|
+
};
|
|
55
|
+
const openEnum = (values) => {
|
|
56
|
+
return zod.z.custom(
|
|
57
|
+
(value) => {
|
|
58
|
+
return typeof value === "string";
|
|
59
|
+
},
|
|
60
|
+
{ message: `Expected a string such as ${Object.values(values).join(", ")}` }
|
|
61
|
+
);
|
|
62
|
+
};
|
|
63
|
+
const readableItems = (item) => {
|
|
64
|
+
return zod.z.array(zod.z.unknown()).transform((items) => {
|
|
65
|
+
return items.flatMap((raw) => {
|
|
66
|
+
const parsed = item.safeParse(raw);
|
|
67
|
+
return parsed.success ? [parsed.data] : [];
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
const sendMessageRequestSchema = zod.z.object({
|
|
72
|
+
messageId: idField,
|
|
73
|
+
userId: idField,
|
|
74
|
+
text: zod.z.string().trim().min(1).max(API_CHANNEL_LIMIT.textMaxLength).refine(hasNoNul, "must not contain NUL"),
|
|
75
|
+
payload: zod.z.string().min(1).max(API_CHANNEL_LIMIT.payloadMaxLength).refine(hasNoNul, "must not contain NUL").optional(),
|
|
76
|
+
userName: zod.z.string().trim().min(1).max(API_CHANNEL_LIMIT.userNameMaxLength).optional()
|
|
77
|
+
});
|
|
78
|
+
const handoverRequestSchema = zod.z.object({
|
|
79
|
+
userId: idField
|
|
80
|
+
});
|
|
81
|
+
const quickReplySchema = zod.z.object({
|
|
82
|
+
title: zod.z.string(),
|
|
83
|
+
payload: zod.z.string()
|
|
84
|
+
});
|
|
85
|
+
const buttonSchema = zod.z.object({
|
|
86
|
+
type: zod.z.enum(["postback", "url"]),
|
|
87
|
+
title: zod.z.string(),
|
|
88
|
+
payload: zod.z.string().optional(),
|
|
89
|
+
url: zod.z.string().optional()
|
|
90
|
+
});
|
|
91
|
+
const attachmentSchema = zod.z.discriminatedUnion("kind", [
|
|
92
|
+
zod.z.object({ kind: zod.z.literal("buttons"), text: zod.z.string(), buttons: readableItems(buttonSchema) }),
|
|
93
|
+
zod.z.object({ kind: zod.z.literal("image"), url: zod.z.string() }),
|
|
94
|
+
zod.z.object({
|
|
95
|
+
kind: zod.z.literal("generic"),
|
|
96
|
+
elements: zod.z.array(
|
|
97
|
+
zod.z.object({
|
|
98
|
+
title: zod.z.string(),
|
|
99
|
+
subtitle: zod.z.string().optional(),
|
|
100
|
+
imageUrl: zod.z.string().optional(),
|
|
101
|
+
defaultUrl: zod.z.string().optional(),
|
|
102
|
+
buttons: readableItems(buttonSchema).optional()
|
|
103
|
+
})
|
|
104
|
+
)
|
|
105
|
+
})
|
|
106
|
+
]);
|
|
107
|
+
const eventBase = {
|
|
108
|
+
id: zod.z.string(),
|
|
109
|
+
createdAt: zod.z.iso.datetime()
|
|
110
|
+
};
|
|
111
|
+
const userEventBase = {
|
|
112
|
+
...eventBase,
|
|
113
|
+
sequence: zod.z.number().int().positive()
|
|
114
|
+
};
|
|
115
|
+
const messageCreatedEventSchema = zod.z.object({
|
|
116
|
+
...userEventBase,
|
|
117
|
+
type: zod.z.literal(WEBHOOK_EVENT_TYPE.messageCreated),
|
|
118
|
+
data: zod.z.object({
|
|
119
|
+
userId: zod.z.string(),
|
|
120
|
+
message: zod.z.object({
|
|
121
|
+
from: openEnum(MESSAGE_FROM),
|
|
122
|
+
text: zod.z.string(),
|
|
123
|
+
quickReplies: zod.z.array(quickReplySchema).optional(),
|
|
124
|
+
attachments: readableItems(attachmentSchema).optional(),
|
|
125
|
+
// The tenant's messageIds this reply answers (several when quick messages were merged).
|
|
126
|
+
inReplyTo: zod.z.array(zod.z.string()).optional()
|
|
127
|
+
})
|
|
128
|
+
})
|
|
129
|
+
});
|
|
130
|
+
const messageFailedEventSchema = zod.z.object({
|
|
131
|
+
...userEventBase,
|
|
132
|
+
type: zod.z.literal(WEBHOOK_EVENT_TYPE.messageFailed),
|
|
133
|
+
data: zod.z.object({
|
|
134
|
+
userId: zod.z.string(),
|
|
135
|
+
inReplyTo: zod.z.array(zod.z.string()),
|
|
136
|
+
reason: openEnum(MESSAGE_FAILED_REASON)
|
|
137
|
+
})
|
|
138
|
+
});
|
|
139
|
+
const handedToStaffEventSchema = zod.z.object({
|
|
140
|
+
...userEventBase,
|
|
141
|
+
type: zod.z.literal(WEBHOOK_EVENT_TYPE.handedToStaff),
|
|
142
|
+
data: zod.z.object({ userId: zod.z.string(), reason: openEnum(HANDOVER_REASON) })
|
|
143
|
+
});
|
|
144
|
+
const returnedToBotEventSchema = zod.z.object({
|
|
145
|
+
...userEventBase,
|
|
146
|
+
type: zod.z.literal(WEBHOOK_EVENT_TYPE.returnedToBot),
|
|
147
|
+
data: zod.z.object({ userId: zod.z.string(), reason: openEnum(RETURNED_TO_BOT_REASON) })
|
|
148
|
+
});
|
|
149
|
+
const webhookTestEventSchema = zod.z.object({
|
|
150
|
+
...eventBase,
|
|
151
|
+
type: zod.z.literal(WEBHOOK_EVENT_TYPE.webhookTest),
|
|
152
|
+
data: zod.z.object({})
|
|
153
|
+
});
|
|
154
|
+
const webhookEventSchema = zod.z.discriminatedUnion("type", [
|
|
155
|
+
messageCreatedEventSchema,
|
|
156
|
+
messageFailedEventSchema,
|
|
157
|
+
handedToStaffEventSchema,
|
|
158
|
+
returnedToBotEventSchema,
|
|
159
|
+
webhookTestEventSchema
|
|
160
|
+
]);
|
|
161
|
+
const KNOWN_EVENT_TYPES = Object.values(WEBHOOK_EVENT_TYPE);
|
|
162
|
+
const unknownWebhookEventSchema = zod.z.looseObject({
|
|
163
|
+
id: zod.z.string(),
|
|
164
|
+
type: zod.z.string().refine((type) => {
|
|
165
|
+
return !KNOWN_EVENT_TYPES.includes(type);
|
|
166
|
+
}),
|
|
167
|
+
createdAt: zod.z.string().optional(),
|
|
168
|
+
data: zod.z.unknown().optional()
|
|
169
|
+
}).transform((event) => {
|
|
170
|
+
return { id: event.id, type: UNKNOWN_WEBHOOK_EVENT.type, originalType: event.type, payload: event };
|
|
171
|
+
});
|
|
172
|
+
const sendMessageAnswerSchema = zod.z.object({
|
|
173
|
+
ok: zod.z.literal(true),
|
|
174
|
+
duplicate: zod.z.boolean().optional()
|
|
175
|
+
});
|
|
176
|
+
const handoverAnswerSchema = zod.z.object({
|
|
177
|
+
ok: zod.z.literal(true),
|
|
178
|
+
already: zod.z.boolean().optional(),
|
|
179
|
+
notified: zod.z.boolean().optional()
|
|
180
|
+
});
|
|
181
|
+
const errorAnswerSchema = zod.z.object({
|
|
182
|
+
ok: zod.z.literal(false),
|
|
183
|
+
error: zod.z.string()
|
|
184
|
+
});
|
|
185
|
+
exports.API_CHANNEL_LIMIT = API_CHANNEL_LIMIT;
|
|
186
|
+
exports.API_CHANNEL_PATH = API_CHANNEL_PATH;
|
|
187
|
+
exports.HANDOVER_REASON = HANDOVER_REASON;
|
|
188
|
+
exports.MESSAGE_FAILED_REASON = MESSAGE_FAILED_REASON;
|
|
189
|
+
exports.MESSAGE_FROM = MESSAGE_FROM;
|
|
190
|
+
exports.RETURNED_TO_BOT_REASON = RETURNED_TO_BOT_REASON;
|
|
191
|
+
exports.UNKNOWN_WEBHOOK_EVENT = UNKNOWN_WEBHOOK_EVENT;
|
|
192
|
+
exports.WEBHOOK_EVENT_TYPE = WEBHOOK_EVENT_TYPE;
|
|
193
|
+
exports.WEBHOOK_HEADER = WEBHOOK_HEADER;
|
|
194
|
+
exports.WEBHOOK_TOLERANCE_SECONDS = WEBHOOK_TOLERANCE_SECONDS;
|
|
195
|
+
exports.attachmentSchema = attachmentSchema;
|
|
196
|
+
exports.buttonSchema = buttonSchema;
|
|
197
|
+
exports.errorAnswerSchema = errorAnswerSchema;
|
|
198
|
+
exports.handedToStaffEventSchema = handedToStaffEventSchema;
|
|
199
|
+
exports.handoverAnswerSchema = handoverAnswerSchema;
|
|
200
|
+
exports.handoverRequestSchema = handoverRequestSchema;
|
|
201
|
+
exports.messageCreatedEventSchema = messageCreatedEventSchema;
|
|
202
|
+
exports.messageFailedEventSchema = messageFailedEventSchema;
|
|
203
|
+
exports.quickReplySchema = quickReplySchema;
|
|
204
|
+
exports.returnedToBotEventSchema = returnedToBotEventSchema;
|
|
205
|
+
exports.sendMessageAnswerSchema = sendMessageAnswerSchema;
|
|
206
|
+
exports.sendMessageRequestSchema = sendMessageRequestSchema;
|
|
207
|
+
exports.unknownWebhookEventSchema = unknownWebhookEventSchema;
|
|
208
|
+
exports.webhookEventSchema = webhookEventSchema;
|
|
209
|
+
exports.webhookTestEventSchema = webhookTestEventSchema;
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const API_CHANNEL_PATH = {
|
|
3
|
+
messages: "/api/v1/conversations/messages",
|
|
4
|
+
handover: "/api/v1/conversations/handover"
|
|
5
|
+
};
|
|
6
|
+
const API_CHANNEL_LIMIT = {
|
|
7
|
+
idMaxLength: 128,
|
|
8
|
+
textMaxLength: 2e3,
|
|
9
|
+
payloadMaxLength: 1e3,
|
|
10
|
+
userNameMaxLength: 100,
|
|
11
|
+
duplicateWindowDays: 30
|
|
12
|
+
};
|
|
13
|
+
const WEBHOOK_HEADER = {
|
|
14
|
+
eventId: "x-onechat-event-id",
|
|
15
|
+
timestamp: "x-onechat-timestamp",
|
|
16
|
+
signature: "x-onechat-signature"
|
|
17
|
+
};
|
|
18
|
+
const WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
19
|
+
const UNKNOWN_WEBHOOK_EVENT = { type: "unknown" };
|
|
20
|
+
const WEBHOOK_EVENT_TYPE = {
|
|
21
|
+
messageCreated: "message.created",
|
|
22
|
+
messageFailed: "message.failed",
|
|
23
|
+
handedToStaff: "conversation.handed_to_staff",
|
|
24
|
+
returnedToBot: "conversation.returned_to_bot",
|
|
25
|
+
webhookTest: "webhook.test"
|
|
26
|
+
};
|
|
27
|
+
const MESSAGE_FROM = {
|
|
28
|
+
bot: "bot",
|
|
29
|
+
staff: "staff",
|
|
30
|
+
system: "system"
|
|
31
|
+
};
|
|
32
|
+
const MESSAGE_FAILED_REASON = {
|
|
33
|
+
aiError: "ai_error",
|
|
34
|
+
expired: "expired"
|
|
35
|
+
};
|
|
36
|
+
const HANDOVER_REASON = {
|
|
37
|
+
humanRequest: "human_request",
|
|
38
|
+
tenantRequest: "tenant_request",
|
|
39
|
+
agentDecision: "agent_decision",
|
|
40
|
+
aiError: "ai_error",
|
|
41
|
+
limitReached: "limit_reached",
|
|
42
|
+
noModel: "no_model",
|
|
43
|
+
staff: "staff"
|
|
44
|
+
};
|
|
45
|
+
const RETURNED_TO_BOT_REASON = {
|
|
46
|
+
staff: "staff",
|
|
47
|
+
user: "user",
|
|
48
|
+
timeout: "timeout"
|
|
49
|
+
};
|
|
50
|
+
const idField = z.string().min(1).max(API_CHANNEL_LIMIT.idMaxLength).regex(/^[^\s\p{Cc}]+$/u, "must not contain whitespace or control characters");
|
|
51
|
+
const hasNoNul = (value) => {
|
|
52
|
+
return !value.includes("\0");
|
|
53
|
+
};
|
|
54
|
+
const openEnum = (values) => {
|
|
55
|
+
return z.custom(
|
|
56
|
+
(value) => {
|
|
57
|
+
return typeof value === "string";
|
|
58
|
+
},
|
|
59
|
+
{ message: `Expected a string such as ${Object.values(values).join(", ")}` }
|
|
60
|
+
);
|
|
61
|
+
};
|
|
62
|
+
const readableItems = (item) => {
|
|
63
|
+
return z.array(z.unknown()).transform((items) => {
|
|
64
|
+
return items.flatMap((raw) => {
|
|
65
|
+
const parsed = item.safeParse(raw);
|
|
66
|
+
return parsed.success ? [parsed.data] : [];
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
const sendMessageRequestSchema = z.object({
|
|
71
|
+
messageId: idField,
|
|
72
|
+
userId: idField,
|
|
73
|
+
text: z.string().trim().min(1).max(API_CHANNEL_LIMIT.textMaxLength).refine(hasNoNul, "must not contain NUL"),
|
|
74
|
+
payload: z.string().min(1).max(API_CHANNEL_LIMIT.payloadMaxLength).refine(hasNoNul, "must not contain NUL").optional(),
|
|
75
|
+
userName: z.string().trim().min(1).max(API_CHANNEL_LIMIT.userNameMaxLength).optional()
|
|
76
|
+
});
|
|
77
|
+
const handoverRequestSchema = z.object({
|
|
78
|
+
userId: idField
|
|
79
|
+
});
|
|
80
|
+
const quickReplySchema = z.object({
|
|
81
|
+
title: z.string(),
|
|
82
|
+
payload: z.string()
|
|
83
|
+
});
|
|
84
|
+
const buttonSchema = z.object({
|
|
85
|
+
type: z.enum(["postback", "url"]),
|
|
86
|
+
title: z.string(),
|
|
87
|
+
payload: z.string().optional(),
|
|
88
|
+
url: z.string().optional()
|
|
89
|
+
});
|
|
90
|
+
const attachmentSchema = z.discriminatedUnion("kind", [
|
|
91
|
+
z.object({ kind: z.literal("buttons"), text: z.string(), buttons: readableItems(buttonSchema) }),
|
|
92
|
+
z.object({ kind: z.literal("image"), url: z.string() }),
|
|
93
|
+
z.object({
|
|
94
|
+
kind: z.literal("generic"),
|
|
95
|
+
elements: z.array(
|
|
96
|
+
z.object({
|
|
97
|
+
title: z.string(),
|
|
98
|
+
subtitle: z.string().optional(),
|
|
99
|
+
imageUrl: z.string().optional(),
|
|
100
|
+
defaultUrl: z.string().optional(),
|
|
101
|
+
buttons: readableItems(buttonSchema).optional()
|
|
102
|
+
})
|
|
103
|
+
)
|
|
104
|
+
})
|
|
105
|
+
]);
|
|
106
|
+
const eventBase = {
|
|
107
|
+
id: z.string(),
|
|
108
|
+
createdAt: z.iso.datetime()
|
|
109
|
+
};
|
|
110
|
+
const userEventBase = {
|
|
111
|
+
...eventBase,
|
|
112
|
+
sequence: z.number().int().positive()
|
|
113
|
+
};
|
|
114
|
+
const messageCreatedEventSchema = z.object({
|
|
115
|
+
...userEventBase,
|
|
116
|
+
type: z.literal(WEBHOOK_EVENT_TYPE.messageCreated),
|
|
117
|
+
data: z.object({
|
|
118
|
+
userId: z.string(),
|
|
119
|
+
message: z.object({
|
|
120
|
+
from: openEnum(MESSAGE_FROM),
|
|
121
|
+
text: z.string(),
|
|
122
|
+
quickReplies: z.array(quickReplySchema).optional(),
|
|
123
|
+
attachments: readableItems(attachmentSchema).optional(),
|
|
124
|
+
// The tenant's messageIds this reply answers (several when quick messages were merged).
|
|
125
|
+
inReplyTo: z.array(z.string()).optional()
|
|
126
|
+
})
|
|
127
|
+
})
|
|
128
|
+
});
|
|
129
|
+
const messageFailedEventSchema = z.object({
|
|
130
|
+
...userEventBase,
|
|
131
|
+
type: z.literal(WEBHOOK_EVENT_TYPE.messageFailed),
|
|
132
|
+
data: z.object({
|
|
133
|
+
userId: z.string(),
|
|
134
|
+
inReplyTo: z.array(z.string()),
|
|
135
|
+
reason: openEnum(MESSAGE_FAILED_REASON)
|
|
136
|
+
})
|
|
137
|
+
});
|
|
138
|
+
const handedToStaffEventSchema = z.object({
|
|
139
|
+
...userEventBase,
|
|
140
|
+
type: z.literal(WEBHOOK_EVENT_TYPE.handedToStaff),
|
|
141
|
+
data: z.object({ userId: z.string(), reason: openEnum(HANDOVER_REASON) })
|
|
142
|
+
});
|
|
143
|
+
const returnedToBotEventSchema = z.object({
|
|
144
|
+
...userEventBase,
|
|
145
|
+
type: z.literal(WEBHOOK_EVENT_TYPE.returnedToBot),
|
|
146
|
+
data: z.object({ userId: z.string(), reason: openEnum(RETURNED_TO_BOT_REASON) })
|
|
147
|
+
});
|
|
148
|
+
const webhookTestEventSchema = z.object({
|
|
149
|
+
...eventBase,
|
|
150
|
+
type: z.literal(WEBHOOK_EVENT_TYPE.webhookTest),
|
|
151
|
+
data: z.object({})
|
|
152
|
+
});
|
|
153
|
+
const webhookEventSchema = z.discriminatedUnion("type", [
|
|
154
|
+
messageCreatedEventSchema,
|
|
155
|
+
messageFailedEventSchema,
|
|
156
|
+
handedToStaffEventSchema,
|
|
157
|
+
returnedToBotEventSchema,
|
|
158
|
+
webhookTestEventSchema
|
|
159
|
+
]);
|
|
160
|
+
const KNOWN_EVENT_TYPES = Object.values(WEBHOOK_EVENT_TYPE);
|
|
161
|
+
const unknownWebhookEventSchema = z.looseObject({
|
|
162
|
+
id: z.string(),
|
|
163
|
+
type: z.string().refine((type) => {
|
|
164
|
+
return !KNOWN_EVENT_TYPES.includes(type);
|
|
165
|
+
}),
|
|
166
|
+
createdAt: z.string().optional(),
|
|
167
|
+
data: z.unknown().optional()
|
|
168
|
+
}).transform((event) => {
|
|
169
|
+
return { id: event.id, type: UNKNOWN_WEBHOOK_EVENT.type, originalType: event.type, payload: event };
|
|
170
|
+
});
|
|
171
|
+
const sendMessageAnswerSchema = z.object({
|
|
172
|
+
ok: z.literal(true),
|
|
173
|
+
duplicate: z.boolean().optional()
|
|
174
|
+
});
|
|
175
|
+
const handoverAnswerSchema = z.object({
|
|
176
|
+
ok: z.literal(true),
|
|
177
|
+
already: z.boolean().optional(),
|
|
178
|
+
notified: z.boolean().optional()
|
|
179
|
+
});
|
|
180
|
+
const errorAnswerSchema = z.object({
|
|
181
|
+
ok: z.literal(false),
|
|
182
|
+
error: z.string()
|
|
183
|
+
});
|
|
184
|
+
export {
|
|
185
|
+
API_CHANNEL_LIMIT as A,
|
|
186
|
+
HANDOVER_REASON as H,
|
|
187
|
+
MESSAGE_FAILED_REASON as M,
|
|
188
|
+
RETURNED_TO_BOT_REASON as R,
|
|
189
|
+
UNKNOWN_WEBHOOK_EVENT as U,
|
|
190
|
+
WEBHOOK_EVENT_TYPE as W,
|
|
191
|
+
API_CHANNEL_PATH as a,
|
|
192
|
+
MESSAGE_FROM as b,
|
|
193
|
+
WEBHOOK_HEADER as c,
|
|
194
|
+
WEBHOOK_TOLERANCE_SECONDS as d,
|
|
195
|
+
attachmentSchema as e,
|
|
196
|
+
buttonSchema as f,
|
|
197
|
+
handoverRequestSchema as g,
|
|
198
|
+
handedToStaffEventSchema as h,
|
|
199
|
+
messageFailedEventSchema as i,
|
|
200
|
+
webhookTestEventSchema as j,
|
|
201
|
+
errorAnswerSchema as k,
|
|
202
|
+
handoverAnswerSchema as l,
|
|
203
|
+
messageCreatedEventSchema as m,
|
|
204
|
+
sendMessageAnswerSchema as n,
|
|
205
|
+
quickReplySchema as q,
|
|
206
|
+
returnedToBotEventSchema as r,
|
|
207
|
+
sendMessageRequestSchema as s,
|
|
208
|
+
unknownWebhookEventSchema as u,
|
|
209
|
+
webhookEventSchema as w
|
|
210
|
+
};
|