@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 ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release.
6
+
7
+ - `useOneChat({ apiKey, baseUrl?, fetch?, timeoutMs?, maxRetries? })` with `messages.send` and
8
+ `conversations.handover`, retrying network errors, timeouts and 5xx with the same body.
9
+ - `constructWebhookEvent(rawBody, headers, secret, options?)`: signature and timestamp check, typed
10
+ events, and unknown event types returned as `type: 'unknown'`.
11
+ - `OneChatApiError`, `OneChatTimeoutError`, `OneChatConnectionError`,
12
+ `OneChatWebhookVerificationError`.
13
+ - `@tabsystems/onechat/protocol`: the request and webhook constants, zod schemas and types.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tab Systems Mongolia LLC
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.md CHANGED
@@ -1,3 +1,229 @@
1
- # Temporary Holding Version
1
+ # @tabsystems/onechat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js SDK for the [OneChat](https://onechat.tabsystems.tech) **API channel**: connect the chat in
4
+ your own app or website to your OneChat AI agent.
5
+
6
+ Your backend sends each message a user writes to OneChat. The agent's replies, staff replies from
7
+ the OneChat inbox, and handover events come back to your backend as signed webhooks.
8
+
9
+ ```
10
+ user ──> your app ──> your backend ──messages.send()──> OneChat
11
+ ^ │
12
+ └──── webhook (signed) ────────┘
13
+ ```
14
+
15
+ Full API reference: https://onechat.tabsystems.tech/docs/api-channel
16
+
17
+ - Node.js 22 or newer. ESM and CommonJS, with TypeScript types (which use Node's global `fetch` and
18
+ `Headers`, so a TypeScript project needs `@types/node`).
19
+ - Use it on your **server** only: the API key and the signing secret must never reach a browser.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install @tabsystems/onechat
25
+ ```
26
+
27
+ ## Set up
28
+
29
+ 1. In the OneChat admin console, open **Platforms**, add a platform of type **API**, and enter your
30
+ webhook URL (`https://` only).
31
+ 2. On the platform's page press **Generate key**. You get two values, shown only once:
32
+ - the API key `ocp_…`
33
+ - the webhook signing secret `whsec_…`
34
+ 3. Put them in your server's environment variables, for example `ONECHAT_API_KEY` and
35
+ `ONECHAT_WEBHOOK_SECRET`. Never put them in browser code or in git.
36
+
37
+ ## Send a user's message
38
+
39
+ ```ts
40
+ import { useOneChat } from '@tabsystems/onechat'
41
+
42
+ const onechat = useOneChat({ apiKey: process.env.ONECHAT_API_KEY! })
43
+
44
+ await onechat.messages.send({
45
+ messageId: 'm_7f3a', // your own id for this message, unique across the connection
46
+ userId: 'u_1029', // your own id for the user
47
+ text: 'Сайн байна уу',
48
+ userName: 'Bat', // optional, shown to staff in the inbox
49
+ })
50
+ ```
51
+
52
+ The reply does **not** come back in this call: the AI takes a few seconds and staff may answer
53
+ hours later, so every reply arrives at your webhook.
54
+
55
+ `messages.send` resolves `{ duplicate: false }`, or `{ duplicate: true }` when this `messageId` was
56
+ already stored (within 30 days); OneChat then runs nothing again.
57
+
58
+ When the user taps a quick reply or a button from a reply, send its `title` as `text` and its
59
+ `payload` as `payload`:
60
+
61
+ ```ts
62
+ await onechat.messages.send({ messageId, userId, text: quickReply.title, payload: quickReply.payload })
63
+ ```
64
+
65
+ ## Hand a conversation to staff
66
+
67
+ ```ts
68
+ const { outcome } = await onechat.conversations.handover({ userId: 'u_1029' })
69
+ // 'handed' — staff have it now; conversation.handed_to_staff follows by webhook
70
+ // 'already' — staff already had it
71
+ // 'notified' — the agent's handoff mode is "notify": staff were alerted, the bot keeps answering
72
+ ```
73
+
74
+ It throws `OneChatApiError` with status `404` when the user has no open conversation, and `409`
75
+ when the agent's handoff mode is "off".
76
+
77
+ ## Receive webhooks
78
+
79
+ `constructWebhookEvent(rawBody, headers, secret)` checks the signature and the timestamp, then
80
+ returns the typed event. It needs the **raw** request body, exactly as received: a parsed and
81
+ re-serialized body no longer matches the signature.
82
+
83
+ ### Express
84
+
85
+ ```ts
86
+ import express from 'express'
87
+ import { constructWebhookEvent, OneChatWebhookVerificationError } from '@tabsystems/onechat'
88
+
89
+ const app = express()
90
+
91
+ app.post('/onechat/webhook', express.raw({ type: 'application/json' }), (req, res) => {
92
+ let event
93
+
94
+ try {
95
+ event = constructWebhookEvent(req.body, req.headers, process.env.ONECHAT_WEBHOOK_SECRET!)
96
+ } catch (err) {
97
+ if (err instanceof OneChatWebhookVerificationError) return res.sendStatus(400)
98
+
99
+ throw err
100
+ }
101
+
102
+ res.sendStatus(200) // answer within 10 seconds; do the slow work afterwards
103
+
104
+ void handleOneChatEvent(event)
105
+ })
106
+ ```
107
+
108
+ ### Nuxt / H3
109
+
110
+ ```ts
111
+ // server/routes/onechat/webhook.post.ts
112
+ import { constructWebhookEvent, OneChatWebhookVerificationError } from '@tabsystems/onechat'
113
+
114
+ export default defineEventHandler(async (event) => {
115
+ const rawBody = (await readRawBody(event, false)) ?? ''
116
+
117
+ try {
118
+ const onechatEvent = constructWebhookEvent(rawBody, getHeaders(event), process.env.ONECHAT_WEBHOOK_SECRET!)
119
+
120
+ void handleOneChatEvent(onechatEvent)
121
+ } catch (err) {
122
+ if (err instanceof OneChatWebhookVerificationError) throw createError({ statusCode: 400 })
123
+
124
+ throw err
125
+ }
126
+
127
+ return { ok: true }
128
+ })
129
+ ```
130
+
131
+ ### Handling events
132
+
133
+ ```ts
134
+ import type { ReceivedWebhookEvent } from '@tabsystems/onechat'
135
+
136
+ const handleOneChatEvent = async (event: ReceivedWebhookEvent) => {
137
+ if (await alreadyHandled(event.id)) return // see "Delivery" below
138
+
139
+ switch (event.type) {
140
+ case 'message.created':
141
+ // event.data.message.from is 'bot', 'staff' or 'system'
142
+ await showToUser(event.data.userId, event.data.message)
143
+ break
144
+ case 'message.failed':
145
+ // no reply will come for event.data.inReplyTo; event.data.reason is 'ai_error' or 'expired'
146
+ break
147
+ case 'conversation.handed_to_staff':
148
+ // event.data.reason: 'human_request', 'tenant_request', 'agent_decision', 'ai_error',
149
+ // 'limit_reached', 'no_model' or 'staff'
150
+ break
151
+ case 'conversation.returned_to_bot':
152
+ // event.data.reason: 'staff', 'user' or 'timeout'
153
+ break
154
+ case 'webhook.test':
155
+ break
156
+ case 'unknown':
157
+ // an event type added to OneChat after this SDK version: event.originalType, event.payload
158
+ break
159
+ }
160
+ }
161
+ ```
162
+
163
+ Reasons and senders may gain new values later; treat a value you do not know as a generic one.
164
+
165
+ ## Delivery
166
+
167
+ - **At least once.** A webhook that does not get a `2xx` within 10 seconds is sent again, so the
168
+ same event can arrive twice. A repeat has the same `id` (and `x-onechat-event-id` header): keep
169
+ the ids you have handled and drop a repeat.
170
+ - A failed delivery is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, then
171
+ given up. So answering `400` to an event this SDK version cannot read loses nothing while you
172
+ update.
173
+ - **In order per user, within limits.** A user's next event waits while an earlier one is in its
174
+ first three attempts (about 6 minutes). Each event about a user carries that user's `sequence`
175
+ number, so you can spot a gap.
176
+ - A notice is sent before the handover event it goes with. A staff member who takes over by
177
+ replying: their reply arrives first, then `conversation.handed_to_staff`.
178
+
179
+ ## Errors and retries
180
+
181
+ `messages.send` and `conversations.handover` retry a network error, a timeout and a `5xx` with the
182
+ same body, up to `maxRetries` times. Because the body and its `messageId` stay the same, OneChat
183
+ answers a repeat as a duplicate and never runs a message twice. A `429` or `503` is retried only
184
+ when its `Retry-After` is at most 10 seconds; a longer one is thrown at once.
185
+
186
+ After a retry, `duplicate: true` or `outcome: 'already'` may be the call's own earlier attempt,
187
+ whose answer was lost on the way back.
188
+
189
+ | Error | When |
190
+ |---|---|
191
+ | `OneChatApiError` | OneChat answered non-2xx (`status`, OneChat's message as `error`, `body`, `retryAfterSeconds`), or answered 2xx with something that is not a OneChat answer |
192
+ | `OneChatTimeoutError` | No answer within `timeoutMs` on the last attempt |
193
+ | `OneChatConnectionError` | OneChat could not be reached on the last attempt; the network error is its `cause` |
194
+ | `ZodError` | The message or handover request is not valid; nothing was sent |
195
+ | `OneChatWebhookVerificationError` | From `constructWebhookEvent`: `reason` is `missingHeader`, `invalidTimestamp`, `timestampOutOfTolerance`, `invalidSignature` or `invalidPayload`. Answer it `400` |
196
+
197
+ The package ships an ESM and a CommonJS build. If your app loads it both ways (an ESM file and a
198
+ CommonJS dependency both importing it), each build has its own error classes and `instanceof` across
199
+ them is false: compare `error.name` (for example `'OneChatWebhookVerificationError'`) instead.
200
+
201
+ ## Options
202
+
203
+ ```ts
204
+ useOneChat({
205
+ apiKey: process.env.ONECHAT_API_KEY!,
206
+ baseUrl: 'https://stg.onechat.tabsystems.tech', // default https://onechat.tabsystems.tech
207
+ timeoutMs: 15_000, // per attempt
208
+ maxRetries: 2,
209
+ fetch, // your own fetch, e.g. for a proxy
210
+ })
211
+
212
+ constructWebhookEvent(rawBody, headers, secret, { toleranceSeconds: 300 })
213
+ ```
214
+
215
+ ## Rotating the key and the secret
216
+
217
+ - **Regenerate key** in the admin console: the old key keeps working for 24 hours, so you can deploy
218
+ the new one without losing messages. **Revoke old key now** ends it at once.
219
+ - **Regenerate secret**: for 24 hours every webhook is signed with both secrets, so either one
220
+ verifies. Deploy the new one, then **Revoke old secret now** or let it expire.
221
+
222
+ ## Request and webhook shapes only
223
+
224
+ `@tabsystems/onechat/protocol` exports the constants, zod schemas and types without the client and
225
+ without `node:crypto`, for code that only needs the shapes.
226
+
227
+ ## License
228
+
229
+ MIT
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const protocol = require("./protocol-B6LQsEpd.cjs");
4
+ const node_crypto = require("node:crypto");
5
+ const ONECHAT_DEFAULT_BASE_URL = "https://onechat.tabsystems.tech";
6
+ const ONECHAT_DEFAULT_TIMEOUT_MS = 15e3;
7
+ const ONECHAT_DEFAULT_MAX_RETRIES = 2;
8
+ const ONECHAT_RETRY_BASE_DELAY_MS = 500;
9
+ const ONECHAT_RETRY_JITTER_SHARE = 0.5;
10
+ const ONECHAT_MAX_RETRY_DELAY_MS = 1e4;
11
+ const HTTP_STATUS_TOO_MANY_REQUESTS = 429;
12
+ const HTTP_STATUS_SERVER_ERROR_MIN = 500;
13
+ const MS_PER_SECOND = 1e3;
14
+ const AUTHORIZATION_SCHEME = "Bearer";
15
+ const JSON_CONTENT_TYPE = "application/json";
16
+ const RETRY_AFTER_HEADER = "retry-after";
17
+ const RETRY_AFTER_SECONDS_PATTERN = /^\d+$/;
18
+ const UNEXPECTED_ANSWER_MESSAGE = "Unexpected answer from OneChat";
19
+ const TRAILING_SLASHES_PATTERN = /\/+$/;
20
+ const HANDOVER_CALL_OUTCOME = {
21
+ handed: "handed",
22
+ already: "already",
23
+ notified: "notified"
24
+ };
25
+ const WEBHOOK_SIGNATURE_ALGORITHM = "sha256";
26
+ const WEBHOOK_SIGNATURE_ENCODING = "hex";
27
+ const WEBHOOK_SIGNATURE_SEPARATOR = ",";
28
+ const WEBHOOK_SIGNATURE_PATTERN = /^[0-9a-f]{64}$/;
29
+ const WEBHOOK_TIMESTAMP_PATTERN = /^\d+$/;
30
+ const WEBHOOK_VERIFICATION_REASON = {
31
+ missingHeader: "missingHeader",
32
+ invalidTimestamp: "invalidTimestamp",
33
+ timestampOutOfTolerance: "timestampOutOfTolerance",
34
+ invalidSignature: "invalidSignature",
35
+ invalidPayload: "invalidPayload"
36
+ };
37
+ class OneChatApiError extends Error {
38
+ constructor(status, error, body, retryAfterSeconds2 = null) {
39
+ super(`OneChat answered ${status}: ${error}`);
40
+ this.status = status;
41
+ this.error = error;
42
+ this.body = body;
43
+ this.retryAfterSeconds = retryAfterSeconds2;
44
+ }
45
+ status;
46
+ error;
47
+ body;
48
+ retryAfterSeconds;
49
+ name = "OneChatApiError";
50
+ }
51
+ class OneChatConnectionError extends Error {
52
+ name = "OneChatConnectionError";
53
+ constructor(options) {
54
+ super("Could not reach OneChat", options);
55
+ }
56
+ }
57
+ class OneChatTimeoutError extends Error {
58
+ constructor(timeoutMs, options) {
59
+ super(`OneChat did not answer within ${timeoutMs} ms`, options);
60
+ this.timeoutMs = timeoutMs;
61
+ }
62
+ timeoutMs;
63
+ name = "OneChatTimeoutError";
64
+ }
65
+ class OneChatWebhookVerificationError extends Error {
66
+ constructor(reason, message) {
67
+ super(message);
68
+ this.reason = reason;
69
+ }
70
+ reason;
71
+ name = "OneChatWebhookVerificationError";
72
+ }
73
+ const sleep = (ms) => {
74
+ return new Promise((resolve) => {
75
+ setTimeout(resolve, ms);
76
+ });
77
+ };
78
+ const backoffMs = (retry) => {
79
+ const ceiling = ONECHAT_RETRY_BASE_DELAY_MS * 2 ** retry;
80
+ const fixed = ceiling * (1 - ONECHAT_RETRY_JITTER_SHARE);
81
+ return fixed + Math.random() * (ceiling - fixed);
82
+ };
83
+ const retryAfterSeconds = (response) => {
84
+ const raw = response.headers.get(RETRY_AFTER_HEADER)?.trim();
85
+ if (!raw) return null;
86
+ if (RETRY_AFTER_SECONDS_PATTERN.test(raw)) return Number(raw);
87
+ const at = Date.parse(raw);
88
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / MS_PER_SECOND));
89
+ };
90
+ const isRetryableStatus = (status) => {
91
+ return status === HTTP_STATUS_TOO_MANY_REQUESTS || status >= HTTP_STATUS_SERVER_ERROR_MIN;
92
+ };
93
+ const parseJson = (text) => {
94
+ try {
95
+ return JSON.parse(text);
96
+ } catch {
97
+ return text;
98
+ }
99
+ };
100
+ const toApiError = ({ response, text }) => {
101
+ const body = parseJson(text);
102
+ const answer = protocol.errorAnswerSchema.safeParse(body);
103
+ return new OneChatApiError(
104
+ response.status,
105
+ answer.success ? answer.data.error : `HTTP ${response.status}`,
106
+ body,
107
+ retryAfterSeconds(response)
108
+ );
109
+ };
110
+ const retryDelayMs = (error, retry) => {
111
+ if (!(error instanceof OneChatApiError)) return backoffMs(retry);
112
+ if (!isRetryableStatus(error.status)) return null;
113
+ const delayMs = error.retryAfterSeconds === null ? backoffMs(retry) : error.retryAfterSeconds * MS_PER_SECOND;
114
+ return delayMs > ONECHAT_MAX_RETRY_DELAY_MS ? null : delayMs;
115
+ };
116
+ const createOneChatRequest = (options) => {
117
+ const baseUrl = new URL(options.baseUrl ?? ONECHAT_DEFAULT_BASE_URL).href.replace(TRAILING_SLASHES_PATTERN, "");
118
+ const fetchImpl = options.fetch ?? globalThis.fetch;
119
+ const timeoutMs = options.timeoutMs ?? ONECHAT_DEFAULT_TIMEOUT_MS;
120
+ const maxRetries = options.maxRetries ?? ONECHAT_DEFAULT_MAX_RETRIES;
121
+ const send = async (path, body) => {
122
+ const signal = AbortSignal.timeout(timeoutMs);
123
+ try {
124
+ const response = await fetchImpl(`${baseUrl}${path}`, {
125
+ method: "POST",
126
+ headers: {
127
+ Authorization: `${AUTHORIZATION_SCHEME} ${options.apiKey}`,
128
+ "Content-Type": JSON_CONTENT_TYPE,
129
+ Accept: JSON_CONTENT_TYPE
130
+ },
131
+ body: JSON.stringify(body),
132
+ signal
133
+ });
134
+ return { response, text: await response.text() };
135
+ } catch (err) {
136
+ if (signal.aborted) throw new OneChatTimeoutError(timeoutMs, { cause: err });
137
+ throw new OneChatConnectionError({ cause: err });
138
+ }
139
+ };
140
+ const attempt = async (path, body, answerSchema) => {
141
+ const answer = await send(path, body);
142
+ if (!answer.response.ok) throw toApiError(answer);
143
+ const json = parseJson(answer.text);
144
+ const parsed = answerSchema.safeParse(json);
145
+ if (parsed.success) return parsed.data;
146
+ throw new OneChatApiError(answer.response.status, UNEXPECTED_ANSWER_MESSAGE, json);
147
+ };
148
+ const post = async (path, body, answerSchema, retry = 0) => {
149
+ try {
150
+ return await attempt(path, body, answerSchema);
151
+ } catch (err) {
152
+ const delayMs = retryDelayMs(err, retry);
153
+ if (retry >= maxRetries || delayMs === null) throw err;
154
+ await sleep(delayMs);
155
+ return post(path, body, answerSchema, retry + 1);
156
+ }
157
+ };
158
+ return { post };
159
+ };
160
+ const computeWebhookSignature = (secret, timestamp, rawBody) => {
161
+ return node_crypto.createHmac(WEBHOOK_SIGNATURE_ALGORITHM, secret).update(`${timestamp}.`).update(rawBody).digest(WEBHOOK_SIGNATURE_ENCODING);
162
+ };
163
+ const matches = (expected, signature) => {
164
+ if (!WEBHOOK_SIGNATURE_PATTERN.test(signature)) return false;
165
+ return node_crypto.timingSafeEqual(expected, Buffer.from(signature, WEBHOOK_SIGNATURE_ENCODING));
166
+ };
167
+ const verifyWebhookSignature = ({
168
+ rawBody,
169
+ signature,
170
+ timestamp,
171
+ secret,
172
+ toleranceSeconds = protocol.WEBHOOK_TOLERANCE_SECONDS,
173
+ now = /* @__PURE__ */ new Date()
174
+ }) => {
175
+ if (!signature || !timestamp) {
176
+ throw new OneChatWebhookVerificationError(
177
+ WEBHOOK_VERIFICATION_REASON.missingHeader,
178
+ `Missing ${protocol.WEBHOOK_HEADER.signature} or ${protocol.WEBHOOK_HEADER.timestamp} header`
179
+ );
180
+ }
181
+ if (!WEBHOOK_TIMESTAMP_PATTERN.test(timestamp)) {
182
+ throw new OneChatWebhookVerificationError(
183
+ WEBHOOK_VERIFICATION_REASON.invalidTimestamp,
184
+ "Webhook timestamp is not Unix seconds"
185
+ );
186
+ }
187
+ if (Math.abs(now.getTime() / MS_PER_SECOND - Number(timestamp)) > toleranceSeconds) {
188
+ throw new OneChatWebhookVerificationError(
189
+ WEBHOOK_VERIFICATION_REASON.timestampOutOfTolerance,
190
+ `Webhook timestamp is more than ${toleranceSeconds} s from now`
191
+ );
192
+ }
193
+ const expected = Buffer.from(computeWebhookSignature(secret, timestamp, rawBody), WEBHOOK_SIGNATURE_ENCODING);
194
+ const genuine = signature.split(WEBHOOK_SIGNATURE_SEPARATOR).some((candidate) => {
195
+ return matches(expected, candidate.trim());
196
+ });
197
+ if (!genuine) {
198
+ throw new OneChatWebhookVerificationError(
199
+ WEBHOOK_VERIFICATION_REASON.invalidSignature,
200
+ "Webhook signature does not match"
201
+ );
202
+ }
203
+ };
204
+ const useOneChat = (options) => {
205
+ const request = createOneChatRequest(options);
206
+ const send = async (message) => {
207
+ const answer = await request.post(
208
+ protocol.API_CHANNEL_PATH.messages,
209
+ protocol.sendMessageRequestSchema.parse(message),
210
+ protocol.sendMessageAnswerSchema
211
+ );
212
+ return { duplicate: answer.duplicate === true };
213
+ };
214
+ const handover = async (input) => {
215
+ const answer = await request.post(
216
+ protocol.API_CHANNEL_PATH.handover,
217
+ protocol.handoverRequestSchema.parse(input),
218
+ protocol.handoverAnswerSchema
219
+ );
220
+ if (answer.already) return { outcome: HANDOVER_CALL_OUTCOME.already };
221
+ if (answer.notified) return { outcome: HANDOVER_CALL_OUTCOME.notified };
222
+ return { outcome: HANDOVER_CALL_OUTCOME.handed };
223
+ };
224
+ return { messages: { send }, conversations: { handover } };
225
+ };
226
+ const readHeader = (headers, name) => {
227
+ const { get } = headers;
228
+ if (typeof get === "function") return get.call(headers, name) ?? void 0;
229
+ const entry = Object.entries(headers).find(([key]) => {
230
+ return key.toLowerCase() === name;
231
+ })?.[1];
232
+ return Array.isArray(entry) ? entry[0] : entry;
233
+ };
234
+ const invalidPayload = (message) => {
235
+ return new OneChatWebhookVerificationError(WEBHOOK_VERIFICATION_REASON.invalidPayload, message);
236
+ };
237
+ const parseBody = (rawBody) => {
238
+ try {
239
+ return JSON.parse(typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody));
240
+ } catch {
241
+ throw invalidPayload("Webhook body is not JSON");
242
+ }
243
+ };
244
+ const constructWebhookEvent = (rawBody, headers, secret, options = {}) => {
245
+ verifyWebhookSignature({
246
+ rawBody,
247
+ signature: readHeader(headers, protocol.WEBHOOK_HEADER.signature),
248
+ timestamp: readHeader(headers, protocol.WEBHOOK_HEADER.timestamp),
249
+ secret,
250
+ ...options
251
+ });
252
+ const body = parseBody(rawBody);
253
+ const known = protocol.webhookEventSchema.safeParse(body);
254
+ if (known.success) return known.data;
255
+ const unknown = protocol.unknownWebhookEventSchema.safeParse(body);
256
+ if (unknown.success) return unknown.data;
257
+ throw invalidPayload("Webhook body is not a OneChat event");
258
+ };
259
+ exports.API_CHANNEL_LIMIT = protocol.API_CHANNEL_LIMIT;
260
+ exports.API_CHANNEL_PATH = protocol.API_CHANNEL_PATH;
261
+ exports.HANDOVER_REASON = protocol.HANDOVER_REASON;
262
+ exports.MESSAGE_FAILED_REASON = protocol.MESSAGE_FAILED_REASON;
263
+ exports.MESSAGE_FROM = protocol.MESSAGE_FROM;
264
+ exports.RETURNED_TO_BOT_REASON = protocol.RETURNED_TO_BOT_REASON;
265
+ exports.UNKNOWN_WEBHOOK_EVENT = protocol.UNKNOWN_WEBHOOK_EVENT;
266
+ exports.WEBHOOK_EVENT_TYPE = protocol.WEBHOOK_EVENT_TYPE;
267
+ exports.WEBHOOK_HEADER = protocol.WEBHOOK_HEADER;
268
+ exports.WEBHOOK_TOLERANCE_SECONDS = protocol.WEBHOOK_TOLERANCE_SECONDS;
269
+ exports.attachmentSchema = protocol.attachmentSchema;
270
+ exports.buttonSchema = protocol.buttonSchema;
271
+ exports.handedToStaffEventSchema = protocol.handedToStaffEventSchema;
272
+ exports.handoverRequestSchema = protocol.handoverRequestSchema;
273
+ exports.messageCreatedEventSchema = protocol.messageCreatedEventSchema;
274
+ exports.messageFailedEventSchema = protocol.messageFailedEventSchema;
275
+ exports.quickReplySchema = protocol.quickReplySchema;
276
+ exports.returnedToBotEventSchema = protocol.returnedToBotEventSchema;
277
+ exports.sendMessageRequestSchema = protocol.sendMessageRequestSchema;
278
+ exports.unknownWebhookEventSchema = protocol.unknownWebhookEventSchema;
279
+ exports.webhookEventSchema = protocol.webhookEventSchema;
280
+ exports.webhookTestEventSchema = protocol.webhookTestEventSchema;
281
+ exports.HANDOVER_CALL_OUTCOME = HANDOVER_CALL_OUTCOME;
282
+ exports.ONECHAT_DEFAULT_BASE_URL = ONECHAT_DEFAULT_BASE_URL;
283
+ exports.OneChatApiError = OneChatApiError;
284
+ exports.OneChatConnectionError = OneChatConnectionError;
285
+ exports.OneChatTimeoutError = OneChatTimeoutError;
286
+ exports.OneChatWebhookVerificationError = OneChatWebhookVerificationError;
287
+ exports.WEBHOOK_VERIFICATION_REASON = WEBHOOK_VERIFICATION_REASON;
288
+ exports.computeWebhookSignature = computeWebhookSignature;
289
+ exports.constructWebhookEvent = constructWebhookEvent;
290
+ exports.useOneChat = useOneChat;
291
+ exports.verifyWebhookSignature = verifyWebhookSignature;