@eulab/connect 0.0.0-stage → 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/README.md +28 -2
- package/dist/bot.d.ts +81 -0
- package/dist/bot.js +1 -0
- package/dist/browser.d.ts +233 -0
- package/dist/browser.js +281 -0
- package/dist/functions.d.ts +34 -0
- package/dist/functions.js +8 -0
- package/dist/interactive.d.ts +121 -0
- package/dist/interactive.js +1 -0
- package/dist/realtime.d.ts +44 -0
- package/dist/realtime.js +96 -0
- package/dist/server.d.ts +142 -0
- package/dist/server.js +54 -0
- package/dist/whatsapp.d.ts +150 -0
- package/dist/whatsapp.js +44 -0
- package/package.json +19 -4
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const functionCatalogPath = '/.well-known/eulab-connect.json';
|
|
2
|
+
export function defineFunctions(input) {
|
|
3
|
+
const validKey = (key) => /^[a-z][a-z0-9_.:-]{0,79}$/.test(key);
|
|
4
|
+
if (!validKey(input.appId) || !Number.isSafeInteger(input.version) || input.version < 1 || input.functions.length > 200 || new Set(input.functions.map(f => f.key)).size !== input.functions.length || input.functions.some(f => !validKey(f.key) || !f.name.trim() || f.name.length > 200 || (f.description?.length || 0) > 1000))
|
|
5
|
+
throw new Error('Matrice funzioni non valida');
|
|
6
|
+
return { schemaVersion: 1, appId: input.appId, version: input.version, functions: input.functions.map(f => ({ ...f })) };
|
|
7
|
+
}
|
|
8
|
+
export function functionsResponse(matrix) { return Response.json(defineFunctions(matrix), { headers: { 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' } }); }
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
export type InteractiveAction = {
|
|
2
|
+
type: 'reply';
|
|
3
|
+
id: string;
|
|
4
|
+
label: string;
|
|
5
|
+
} | {
|
|
6
|
+
type: 'url';
|
|
7
|
+
label: string;
|
|
8
|
+
url: string;
|
|
9
|
+
} | {
|
|
10
|
+
type: 'call';
|
|
11
|
+
label: string;
|
|
12
|
+
phoneNumber: string;
|
|
13
|
+
} | {
|
|
14
|
+
type: 'copy';
|
|
15
|
+
label: string;
|
|
16
|
+
code: string;
|
|
17
|
+
};
|
|
18
|
+
/** Portable documents forwarded to OpenWAUnlocked.sendInteractive. */
|
|
19
|
+
export type InteractiveContent = {
|
|
20
|
+
type: 'buttons';
|
|
21
|
+
body: string;
|
|
22
|
+
footer?: string;
|
|
23
|
+
header?: {
|
|
24
|
+
type: 'text';
|
|
25
|
+
text: string;
|
|
26
|
+
};
|
|
27
|
+
actions: InteractiveAction[];
|
|
28
|
+
} | {
|
|
29
|
+
type: 'list';
|
|
30
|
+
body: string;
|
|
31
|
+
footer?: string;
|
|
32
|
+
title?: string;
|
|
33
|
+
buttonLabel: string;
|
|
34
|
+
sections: {
|
|
35
|
+
title?: string;
|
|
36
|
+
rows: {
|
|
37
|
+
id: string;
|
|
38
|
+
title: string;
|
|
39
|
+
description?: string;
|
|
40
|
+
}[];
|
|
41
|
+
}[];
|
|
42
|
+
};
|
|
43
|
+
export interface InteractiveResponse {
|
|
44
|
+
messageId: string;
|
|
45
|
+
chatId: string;
|
|
46
|
+
senderId: string;
|
|
47
|
+
type: 'reply' | 'list';
|
|
48
|
+
id: string;
|
|
49
|
+
label?: string;
|
|
50
|
+
timestamp?: number;
|
|
51
|
+
}
|
|
52
|
+
export interface CallIdentity {
|
|
53
|
+
id: string;
|
|
54
|
+
sessionId: string;
|
|
55
|
+
generation: string;
|
|
56
|
+
}
|
|
57
|
+
export interface CallSnapshot extends CallIdentity {
|
|
58
|
+
peer: string;
|
|
59
|
+
state: string;
|
|
60
|
+
direction: 'incoming' | 'outgoing';
|
|
61
|
+
video: boolean;
|
|
62
|
+
terminal: boolean;
|
|
63
|
+
observedAt: number;
|
|
64
|
+
}
|
|
65
|
+
export interface CallCapabilities {
|
|
66
|
+
control: boolean;
|
|
67
|
+
audio: boolean;
|
|
68
|
+
video: boolean;
|
|
69
|
+
reason?: {
|
|
70
|
+
code: string;
|
|
71
|
+
message: string;
|
|
72
|
+
status: number;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export type CallActionResult = {
|
|
76
|
+
ok: true;
|
|
77
|
+
status: 'requested';
|
|
78
|
+
callId?: string;
|
|
79
|
+
} | {
|
|
80
|
+
ok: false;
|
|
81
|
+
status: 'unavailable' | 'failed' | 'unknown';
|
|
82
|
+
reason: {
|
|
83
|
+
code: string;
|
|
84
|
+
message: string;
|
|
85
|
+
status: number;
|
|
86
|
+
};
|
|
87
|
+
callId?: string;
|
|
88
|
+
};
|
|
89
|
+
export type ProviderCommand = {
|
|
90
|
+
kind: 'contact.refresh';
|
|
91
|
+
chatId: string;
|
|
92
|
+
} | {
|
|
93
|
+
kind: 'call.inspect';
|
|
94
|
+
} | {
|
|
95
|
+
kind: 'call.start';
|
|
96
|
+
to: string;
|
|
97
|
+
} | {
|
|
98
|
+
kind: 'call.accept' | 'call.reject' | 'call.end';
|
|
99
|
+
call: CallIdentity;
|
|
100
|
+
} | {
|
|
101
|
+
kind: 'call.mute';
|
|
102
|
+
call: CallIdentity;
|
|
103
|
+
muted: boolean;
|
|
104
|
+
};
|
|
105
|
+
export interface ProviderOperation<T = unknown> {
|
|
106
|
+
id: string;
|
|
107
|
+
state: 'queued' | 'running' | 'completed' | 'cancelled' | 'uncertain';
|
|
108
|
+
command: ProviderCommand;
|
|
109
|
+
result: T | null;
|
|
110
|
+
error: string | null;
|
|
111
|
+
created_at: string;
|
|
112
|
+
}
|
|
113
|
+
export interface ConversationContact {
|
|
114
|
+
name: string | null;
|
|
115
|
+
pushName: string | null;
|
|
116
|
+
description: string | null;
|
|
117
|
+
avatar: string | null;
|
|
118
|
+
isBusiness: boolean;
|
|
119
|
+
isGroup: boolean;
|
|
120
|
+
updatedAt?: string;
|
|
121
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Request, WhatsAppSession } from './whatsapp.js';
|
|
2
|
+
export interface WhatsAppRealtimeEvent {
|
|
3
|
+
id: string;
|
|
4
|
+
session_id: string;
|
|
5
|
+
kind: string;
|
|
6
|
+
created_at: string;
|
|
7
|
+
payload: Record<string, any>;
|
|
8
|
+
}
|
|
9
|
+
export interface WhatsAppSnapshot {
|
|
10
|
+
sessions: (WhatsAppSession & {
|
|
11
|
+
qr: string | null;
|
|
12
|
+
})[];
|
|
13
|
+
outbox: {
|
|
14
|
+
id: string;
|
|
15
|
+
session_id: string;
|
|
16
|
+
state: string;
|
|
17
|
+
provider_id: string | null;
|
|
18
|
+
error: string | null;
|
|
19
|
+
created_at: string;
|
|
20
|
+
}[];
|
|
21
|
+
bots: {
|
|
22
|
+
archive_id: string;
|
|
23
|
+
revision: number;
|
|
24
|
+
enabled: boolean;
|
|
25
|
+
}[];
|
|
26
|
+
}
|
|
27
|
+
export type WhatsAppRealtimeStatus = 'connecting' | 'connected' | 'reconnecting' | 'closed' | 'unauthorized' | 'error';
|
|
28
|
+
export interface WhatsAppSubscribeOptions {
|
|
29
|
+
onEvent?: (event: WhatsAppRealtimeEvent) => void;
|
|
30
|
+
onSnapshot?: (snapshot: WhatsAppSnapshot) => void;
|
|
31
|
+
onStatus?: (status: WhatsAppRealtimeStatus) => void;
|
|
32
|
+
onError?: (error: Error) => void;
|
|
33
|
+
reconnect?: boolean;
|
|
34
|
+
}
|
|
35
|
+
export interface WhatsAppSubscription {
|
|
36
|
+
close(): void;
|
|
37
|
+
readonly status: WhatsAppRealtimeStatus;
|
|
38
|
+
}
|
|
39
|
+
export interface RealtimeConfig {
|
|
40
|
+
apiUrl: string;
|
|
41
|
+
register?: (close: () => void) => () => void;
|
|
42
|
+
}
|
|
43
|
+
/** Receive only: reconnecting this stream never replays an outbound message. */
|
|
44
|
+
export declare function subscribeWhatsApp(request: Request, root: string, config: RealtimeConfig, options: WhatsAppSubscribeOptions): WhatsAppSubscription;
|
package/dist/realtime.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** Receive only: reconnecting this stream never replays an outbound message. */
|
|
2
|
+
export function subscribeWhatsApp(request, root, config, options) {
|
|
3
|
+
let stopped = false, socket, timer, attempt = 0, status = 'connecting';
|
|
4
|
+
const seen = new Set();
|
|
5
|
+
let unregister;
|
|
6
|
+
function call(fn, value) { try {
|
|
7
|
+
fn?.(value);
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
try {
|
|
11
|
+
options.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
12
|
+
}
|
|
13
|
+
catch { }
|
|
14
|
+
} }
|
|
15
|
+
function setStatus(value) { status = value; call(options.onStatus, value); }
|
|
16
|
+
function finish(value) { if (stopped)
|
|
17
|
+
return; stopped = true; clearTimeout(timer); socket?.close(); unregister?.(); setStatus(value); }
|
|
18
|
+
function retry() {
|
|
19
|
+
if (stopped)
|
|
20
|
+
return;
|
|
21
|
+
if (options.reconnect === false || attempt >= 8) {
|
|
22
|
+
finish('error');
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
setStatus('reconnecting');
|
|
26
|
+
timer = setTimeout(() => void connect(), Math.min(1000 * 2 ** attempt++, 15000));
|
|
27
|
+
}
|
|
28
|
+
async function connect() {
|
|
29
|
+
if (stopped)
|
|
30
|
+
return;
|
|
31
|
+
let opened;
|
|
32
|
+
try {
|
|
33
|
+
const ticket = await request(root + '/events/ticket', 'POST');
|
|
34
|
+
if (stopped)
|
|
35
|
+
return;
|
|
36
|
+
if (ticket.path !== '/v1/whatsapp/events')
|
|
37
|
+
throw new Error('Endpoint realtime non valido');
|
|
38
|
+
const url = new URL(config.apiUrl + ticket.path, typeof location === 'undefined' ? undefined : location.origin);
|
|
39
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
40
|
+
throw new Error('URL API HTTP(S) richiesto');
|
|
41
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
42
|
+
socket = opened = new WebSocket(url);
|
|
43
|
+
let authTimer = setTimeout(() => opened.close(), 10000);
|
|
44
|
+
opened.onopen = () => { if (stopped) {
|
|
45
|
+
opened.close();
|
|
46
|
+
return;
|
|
47
|
+
} opened.send(JSON.stringify({ type: 'authenticate', ticket: ticket.ticket })); };
|
|
48
|
+
opened.onmessage = message => {
|
|
49
|
+
if (stopped || socket !== opened || typeof message.data !== 'string')
|
|
50
|
+
return;
|
|
51
|
+
let frame;
|
|
52
|
+
try {
|
|
53
|
+
frame = JSON.parse(message.data);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (frame.type === 'ready') {
|
|
59
|
+
clearTimeout(authTimer);
|
|
60
|
+
attempt = 0;
|
|
61
|
+
setStatus('connected');
|
|
62
|
+
}
|
|
63
|
+
else if (frame.type === 'snapshot' && Array.isArray(frame.sessions) && Array.isArray(frame.outbox) && Array.isArray(frame.bots))
|
|
64
|
+
call(options.onSnapshot, { sessions: frame.sessions, outbox: frame.outbox, bots: frame.bots });
|
|
65
|
+
else if (frame.type === 'event' && typeof frame.event?.id === 'string' && typeof frame.event?.kind === 'string') {
|
|
66
|
+
if (seen.has(frame.event.id))
|
|
67
|
+
return;
|
|
68
|
+
seen.add(frame.event.id);
|
|
69
|
+
if (seen.size > 5000)
|
|
70
|
+
seen.delete(seen.values().next().value);
|
|
71
|
+
call(options.onEvent, frame.event);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
opened.onerror = () => { call(options.onError, new Error('Connessione realtime non disponibile')); };
|
|
75
|
+
opened.onclose = event => { clearTimeout(authTimer); if (stopped || socket !== opened)
|
|
76
|
+
return; if (event.code === 4003) {
|
|
77
|
+
finish('unauthorized');
|
|
78
|
+
return;
|
|
79
|
+
} retry(); };
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (stopped)
|
|
83
|
+
return;
|
|
84
|
+
call(options.onError, error instanceof Error ? error : new Error(String(error)));
|
|
85
|
+
if ([401, 403].includes(error?.status || 0) || /401|403|Accedi|scaduta|revocata|session_expired/.test(String(error)))
|
|
86
|
+
finish('unauthorized');
|
|
87
|
+
else
|
|
88
|
+
retry();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const handle = { close: () => finish('closed'), get status() { return status; } };
|
|
92
|
+
unregister = config.register?.(handle.close);
|
|
93
|
+
setStatus('connecting');
|
|
94
|
+
void connect();
|
|
95
|
+
return handle;
|
|
96
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
export type { InteractiveAction, InteractiveContent, InteractiveResponse, ProviderCommand, ProviderOperation, ConversationContact, CallIdentity, CallSnapshot, CallCapabilities, CallActionResult } from './interactive.js';
|
|
2
|
+
export type { IVRInput, IVRPrompt, IVRChannel, VoiceIVRSession } from './bot.js';
|
|
3
|
+
export type { WhatsAppRealtimeEvent, WhatsAppSnapshot, WhatsAppRealtimeStatus, WhatsAppSubscribeOptions, WhatsAppSubscription } from './realtime.js';
|
|
4
|
+
export type { WhatsAppBotDefinition, WhatsAppBotNode, WhatsAppBotState, WhatsAppBotTurn, WhatsAppBot } from './bot.js';
|
|
5
|
+
export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
|
|
6
|
+
export type { AppFunction, FunctionMatrix, AccessResult, ConnectUser } from './functions.js';
|
|
7
|
+
import type { AccessResult, ConnectUser } from './functions.js';
|
|
8
|
+
export type { WhatsAppSession, WhatsAppArchive, Conversation, WhatsAppMessage, WhatsAppPayload } from './whatsapp.js';
|
|
9
|
+
export interface LocalUserProfile {
|
|
10
|
+
localUserId: string;
|
|
11
|
+
username: string;
|
|
12
|
+
email: string;
|
|
13
|
+
displayName: string;
|
|
14
|
+
}
|
|
15
|
+
export interface MirroredUser {
|
|
16
|
+
installationId: string;
|
|
17
|
+
customerId: string;
|
|
18
|
+
localUserId: string;
|
|
19
|
+
subject: string;
|
|
20
|
+
username?: string;
|
|
21
|
+
created: boolean;
|
|
22
|
+
status: 'created' | 'already_linked' | 'recovered';
|
|
23
|
+
ssoSetupRequired: boolean | null;
|
|
24
|
+
}
|
|
25
|
+
export declare class ConnectServer {
|
|
26
|
+
private readonly config;
|
|
27
|
+
constructor(config: {
|
|
28
|
+
apiUrl: string;
|
|
29
|
+
installationId: string;
|
|
30
|
+
secret: string;
|
|
31
|
+
domain?: string;
|
|
32
|
+
functionFallbackUrl?: string;
|
|
33
|
+
catalogUrl?: string;
|
|
34
|
+
basePath?: string;
|
|
35
|
+
});
|
|
36
|
+
request<T = any>(path: string, method?: string, body?: unknown, accessToken?: string, extra?: Record<string, string>): Promise<T>;
|
|
37
|
+
functionUrl(feature: string, path?: string): string;
|
|
38
|
+
authorize(accessToken: string, permission: string): Promise<{
|
|
39
|
+
allowed: boolean;
|
|
40
|
+
reason: string;
|
|
41
|
+
}>;
|
|
42
|
+
whatsapp(accessToken: string | (() => Promise<string>)): {
|
|
43
|
+
subscribe: (options: import("./realtime.js").WhatsAppSubscribeOptions) => import("./realtime.js").WhatsAppSubscription;
|
|
44
|
+
bot: {
|
|
45
|
+
get: (archiveId: string) => Promise<import("./bot.js").WhatsAppBot>;
|
|
46
|
+
configure: (archiveId: string, definition: import("./bot.js").WhatsAppBotDefinition, expectedRevision: number) => Promise<import("./bot.js").WhatsAppBot>;
|
|
47
|
+
activate: (archiveId: string, enabled: boolean, expectedRevision: number) => Promise<import("./bot.js").WhatsAppBot>;
|
|
48
|
+
preview: (definition: import("./bot.js").WhatsAppBotDefinition, input: string | import("./bot.js").IVRInput, state?: import("./bot.js").WhatsAppBotState | null, channel?: import("./bot.js").IVRChannel) => Promise<import("./bot.js").WhatsAppBotTurn & {
|
|
49
|
+
sent: false;
|
|
50
|
+
}>;
|
|
51
|
+
};
|
|
52
|
+
ivr: {
|
|
53
|
+
get: (archiveId: string, id: string) => Promise<import("./bot.js").VoiceIVRSession>;
|
|
54
|
+
start: (archiveId: string, callId: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./bot.js").VoiceIVRSession>;
|
|
55
|
+
advance: (archiveId: string, id: string, input: import("./bot.js").IVRInput, expectedTurn: number, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./bot.js").VoiceIVRSession>;
|
|
56
|
+
};
|
|
57
|
+
operations: {
|
|
58
|
+
get: <T = unknown>(id: string) => Promise<import("./interactive.js").ProviderOperation<T>>;
|
|
59
|
+
list: () => Promise<import("./interactive.js").ProviderOperation<unknown>[]>;
|
|
60
|
+
submit: (id: string, command: import("./interactive.js").ProviderCommand, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<unknown>>;
|
|
61
|
+
};
|
|
62
|
+
calls: {
|
|
63
|
+
inspect: (id: string) => Promise<import("./interactive.js").ProviderOperation<{
|
|
64
|
+
capabilities: import("./interactive.js").CallCapabilities;
|
|
65
|
+
active: import("./interactive.js").CallSnapshot | null;
|
|
66
|
+
}>>;
|
|
67
|
+
start: (id: string, to: string, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").CallActionResult>>;
|
|
68
|
+
control: (id: string, action: "accept" | "reject" | "end" | "mute", call: import("./interactive.js").CallIdentity, muted?: boolean, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").CallActionResult>>;
|
|
69
|
+
};
|
|
70
|
+
refreshContact: (id: string, chatId: string) => Promise<import("./interactive.js").ProviderOperation<import("./interactive.js").ConversationContact>>;
|
|
71
|
+
sessions: () => Promise<import("./whatsapp.js").WhatsAppSession[]>;
|
|
72
|
+
connect: () => Promise<{
|
|
73
|
+
id: string;
|
|
74
|
+
state: string;
|
|
75
|
+
}>;
|
|
76
|
+
qr: (id: string) => Promise<{
|
|
77
|
+
state: string;
|
|
78
|
+
qr: string | null;
|
|
79
|
+
}>;
|
|
80
|
+
send: (id: string, payload: import("./whatsapp.js").WhatsAppPayload, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
|
|
81
|
+
id: string;
|
|
82
|
+
state: string;
|
|
83
|
+
}>;
|
|
84
|
+
test: (id: string, payload: import("./whatsapp.js").WhatsAppPayload) => Promise<{
|
|
85
|
+
valid: boolean;
|
|
86
|
+
kind: string;
|
|
87
|
+
to: string;
|
|
88
|
+
connected: boolean;
|
|
89
|
+
sent: false;
|
|
90
|
+
}>;
|
|
91
|
+
outbox: () => Promise<{
|
|
92
|
+
id: string;
|
|
93
|
+
session_id: string;
|
|
94
|
+
state: string;
|
|
95
|
+
provider_id: string | null;
|
|
96
|
+
error: string | null;
|
|
97
|
+
created_at: string;
|
|
98
|
+
}[]>;
|
|
99
|
+
sendText: (id: string, to: string, text: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
|
|
100
|
+
id: string;
|
|
101
|
+
state: string;
|
|
102
|
+
}>;
|
|
103
|
+
reconnect: (id: string) => Promise<any>;
|
|
104
|
+
disconnect: (id: string) => Promise<any>;
|
|
105
|
+
deleteConnection: (id: string) => Promise<{
|
|
106
|
+
removed: boolean;
|
|
107
|
+
state: string;
|
|
108
|
+
}>;
|
|
109
|
+
deleteArchive: (id: string) => Promise<{
|
|
110
|
+
removed: boolean;
|
|
111
|
+
state: string;
|
|
112
|
+
}>;
|
|
113
|
+
archives: () => Promise<import("./whatsapp.js").WhatsAppArchive[]>;
|
|
114
|
+
messages: (id: string, before?: string, chat?: string) => Promise<import("./whatsapp.js").WhatsAppMessage[]>;
|
|
115
|
+
conversations: (id: string) => Promise<import("./whatsapp.js").Conversation[]>;
|
|
116
|
+
media: (archiveId: string, messageId: string) => Promise<{
|
|
117
|
+
data: string | null;
|
|
118
|
+
state: "available" | "queued";
|
|
119
|
+
}>;
|
|
120
|
+
};
|
|
121
|
+
registerFunctions(url?: string): Promise<any>;
|
|
122
|
+
mirrorUser(user: LocalUserProfile): Promise<MirroredUser>;
|
|
123
|
+
permissions(accessToken: string): Promise<AccessResult>;
|
|
124
|
+
notifications(accessToken: string, options?: {
|
|
125
|
+
unread?: boolean;
|
|
126
|
+
before?: string;
|
|
127
|
+
beforeId?: string;
|
|
128
|
+
limit?: number;
|
|
129
|
+
}): Promise<any>;
|
|
130
|
+
markNotification(accessToken: string, id: string, read?: boolean): Promise<any>;
|
|
131
|
+
markAllNotificationsRead(accessToken: string): Promise<any>;
|
|
132
|
+
accountSecurity(accessToken: string): Promise<any>;
|
|
133
|
+
revokeTrustedDevice(accessToken: string, id: string): Promise<any>;
|
|
134
|
+
sessions(accessToken: string): Promise<any>;
|
|
135
|
+
logoutSession(accessToken: string, id: string): Promise<any>;
|
|
136
|
+
logoutAllSessions(accessToken: string): Promise<any>;
|
|
137
|
+
users(accessToken: string): Promise<ConnectUser[]>;
|
|
138
|
+
requireFunction(accessToken: string, functionKey: string): Promise<void>;
|
|
139
|
+
redeemTechnicalTicket(ticket: string): Promise<any>;
|
|
140
|
+
static pair(apiUrl: string, code: string, domain: string): Promise<any>;
|
|
141
|
+
}
|
|
142
|
+
export declare function verifyWebhook(secret: string, rawBody: string, timestamp: string, received: string, now?: number): boolean;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export { defineFunctions, functionsResponse, functionCatalogPath } from './functions.js';
|
|
2
|
+
import { functionCatalogPath } from './functions.js';
|
|
3
|
+
import { whatsappClient } from './whatsapp.js';
|
|
4
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
export class ConnectServer {
|
|
6
|
+
config;
|
|
7
|
+
constructor(config) {
|
|
8
|
+
this.config = config;
|
|
9
|
+
}
|
|
10
|
+
async request(path, method = 'GET', body, accessToken, extra = {}) {
|
|
11
|
+
const response = await fetch(`${this.config.apiUrl}${path}`, { method, headers: { 'Content-Type': 'application/json', 'X-Installation-Id': this.config.installationId, 'X-Installation-Secret': this.config.secret, ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
12
|
+
const result = await response.json();
|
|
13
|
+
if (!response.ok)
|
|
14
|
+
throw new Error(`Connect ${response.status}: ${JSON.stringify(result)}`);
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
functionUrl(feature, path) {
|
|
18
|
+
if (!/^[a-z][a-z0-9_.:-]{0,79}$/.test(feature) || !this.config.domain)
|
|
19
|
+
throw new Error('Dominio o funzione non valido');
|
|
20
|
+
const url = path ? new URL(path, this.config.domain) : new URL(`${(this.config.functionFallbackUrl || this.config.domain + '/eulab/connect/functions').replace(/\/$/, '')}/${encodeURIComponent(feature)}`);
|
|
21
|
+
if (url.origin !== this.config.domain)
|
|
22
|
+
throw new Error('URL funzione esterno al dominio autorizzato');
|
|
23
|
+
return url.href;
|
|
24
|
+
}
|
|
25
|
+
authorize(accessToken, permission) { return this.request('/v1/authorize', 'POST', { installationId: this.config.installationId, permission }, accessToken); }
|
|
26
|
+
whatsapp(accessToken) { return whatsappClient(async (path, method, body, extra) => this.request(path, method, body, typeof accessToken === 'function' ? await accessToken() : accessToken, extra), this.config.installationId, { apiUrl: this.config.apiUrl }); }
|
|
27
|
+
registerFunctions(url) { const source = url || this.config.catalogUrl || (this.config.domain ? this.config.domain + (this.config.basePath || '') + functionCatalogPath : undefined); if (!source)
|
|
28
|
+
throw new Error('URL funzioni o dominio richiesto'); return this.request('/v1/catalog-source', 'POST', { url: source }); }
|
|
29
|
+
mirrorUser(user) { return this.request('/v1/users/mirror', 'POST', user); }
|
|
30
|
+
permissions(accessToken) { return this.request('/v1/access', 'GET', undefined, accessToken); }
|
|
31
|
+
notifications(accessToken, options = {}) { const query = new URLSearchParams(); for (const [key, value] of Object.entries(options))
|
|
32
|
+
if (value !== undefined)
|
|
33
|
+
query.set(key, String(value)); return this.request('/v1/notifications?' + query, 'GET', undefined, accessToken); }
|
|
34
|
+
markNotification(accessToken, id, read = true) { return this.request('/v1/notifications/' + encodeURIComponent(id) + '/read', 'PUT', { read }, accessToken); }
|
|
35
|
+
markAllNotificationsRead(accessToken) { return this.request('/v1/notifications/read-all', 'POST', undefined, accessToken); }
|
|
36
|
+
accountSecurity(accessToken) { return this.request('/v1/security/me', 'GET', undefined, accessToken); }
|
|
37
|
+
revokeTrustedDevice(accessToken, id) { return this.request('/v1/security/devices/' + encodeURIComponent(id), 'DELETE', undefined, accessToken); }
|
|
38
|
+
sessions(accessToken) { return this.request('/v1/sessions', 'GET', undefined, accessToken); }
|
|
39
|
+
logoutSession(accessToken, id) { return this.request(`/v1/sessions/${encodeURIComponent(id)}/logout`, 'POST', undefined, accessToken); }
|
|
40
|
+
logoutAllSessions(accessToken) { return this.request('/v1/sessions/logout-all', 'POST', undefined, accessToken); }
|
|
41
|
+
users(accessToken) { return this.request('/v1/users', 'GET', undefined, accessToken); }
|
|
42
|
+
async requireFunction(accessToken, functionKey) { const result = await this.authorize(accessToken, functionKey); if (!result.allowed)
|
|
43
|
+
throw new Error('Funzione non consentita: ' + result.reason); }
|
|
44
|
+
redeemTechnicalTicket(ticket) { return this.request('/v1/technical/redeem', 'POST', { ticket }); }
|
|
45
|
+
static async pair(apiUrl, code, domain) { const r = await fetch(`${apiUrl}/v1/pairing/redeem`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, domain }) }); if (!r.ok)
|
|
46
|
+
throw new Error('Associazione fallita'); return r.json(); }
|
|
47
|
+
}
|
|
48
|
+
export function verifyWebhook(secret, rawBody, timestamp, received, now = Date.now()) {
|
|
49
|
+
if (!/^\d+$/.test(timestamp) || Math.abs(now / 1000 - Number(timestamp)) > 300 || !/^[a-f0-9]{64}$/.test(received))
|
|
50
|
+
return false;
|
|
51
|
+
const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
|
|
52
|
+
return timingSafeEqual(expected, Buffer.from(received, 'hex'));
|
|
53
|
+
}
|
|
54
|
+
// Persist event IDs in the consumer database before applying side effects; signatures alone do not deduplicate events.
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { InteractiveContent, ProviderCommand, ProviderOperation, ConversationContact, CallIdentity, CallCapabilities, CallSnapshot, CallActionResult } from './interactive.js';
|
|
2
|
+
import type { IVRInput, IVRChannel, VoiceIVRSession } from './bot.js';
|
|
3
|
+
import type { RealtimeConfig, WhatsAppSubscribeOptions } from './realtime.js';
|
|
4
|
+
import type { WhatsAppBotDefinition, WhatsAppBotState, WhatsAppBot, WhatsAppBotTurn } from './bot.js';
|
|
5
|
+
export interface WhatsAppSession {
|
|
6
|
+
id: string;
|
|
7
|
+
created_at: string;
|
|
8
|
+
number: string | null;
|
|
9
|
+
state: string;
|
|
10
|
+
archive_id: string | null;
|
|
11
|
+
runner_id: string;
|
|
12
|
+
runner_online: boolean;
|
|
13
|
+
closed_at: string | null;
|
|
14
|
+
delete_requested: boolean;
|
|
15
|
+
sync_count: number;
|
|
16
|
+
sync_status: string;
|
|
17
|
+
sync_limit: string;
|
|
18
|
+
}
|
|
19
|
+
export interface WhatsAppArchive {
|
|
20
|
+
id: string;
|
|
21
|
+
number: string;
|
|
22
|
+
installation_id: string;
|
|
23
|
+
}
|
|
24
|
+
export interface Conversation {
|
|
25
|
+
chat_id: string;
|
|
26
|
+
messages: number;
|
|
27
|
+
last_message_at: string;
|
|
28
|
+
preview: string;
|
|
29
|
+
kind: string;
|
|
30
|
+
direction: string;
|
|
31
|
+
contact: ConversationContact | null;
|
|
32
|
+
}
|
|
33
|
+
export interface WhatsAppMessage {
|
|
34
|
+
id: string;
|
|
35
|
+
chat_id: string;
|
|
36
|
+
direction: string;
|
|
37
|
+
kind: string;
|
|
38
|
+
occurred_at: string;
|
|
39
|
+
body: {
|
|
40
|
+
text?: string;
|
|
41
|
+
media?: string;
|
|
42
|
+
mediaAvailable?: boolean;
|
|
43
|
+
filename?: string;
|
|
44
|
+
mimetype?: string;
|
|
45
|
+
selectedButtonId?: string;
|
|
46
|
+
interactive?: InteractiveContent;
|
|
47
|
+
senderName?: string;
|
|
48
|
+
quotedText?: string;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export type WhatsAppPayload = {
|
|
52
|
+
kind: 'interactive';
|
|
53
|
+
to: string;
|
|
54
|
+
content: InteractiveContent;
|
|
55
|
+
} | {
|
|
56
|
+
kind: 'text';
|
|
57
|
+
to: string;
|
|
58
|
+
text: string;
|
|
59
|
+
} | {
|
|
60
|
+
kind: 'image' | 'document' | 'audio' | 'video';
|
|
61
|
+
to: string;
|
|
62
|
+
data: string;
|
|
63
|
+
filename: string;
|
|
64
|
+
caption?: string;
|
|
65
|
+
} | {
|
|
66
|
+
kind: 'poll';
|
|
67
|
+
to: string;
|
|
68
|
+
question: string;
|
|
69
|
+
options: string[];
|
|
70
|
+
};
|
|
71
|
+
export type Request = <T = any>(path: string, method?: string, body?: unknown, headers?: Record<string, string>) => Promise<T>;
|
|
72
|
+
export declare function whatsappClient(request: Request, installationId: string, realtime?: RealtimeConfig): {
|
|
73
|
+
subscribe: (options: WhatsAppSubscribeOptions) => import("./realtime.js").WhatsAppSubscription;
|
|
74
|
+
bot: {
|
|
75
|
+
get: (archiveId: string) => Promise<WhatsAppBot>;
|
|
76
|
+
configure: (archiveId: string, definition: WhatsAppBotDefinition, expectedRevision: number) => Promise<WhatsAppBot>;
|
|
77
|
+
activate: (archiveId: string, enabled: boolean, expectedRevision: number) => Promise<WhatsAppBot>;
|
|
78
|
+
preview: (definition: WhatsAppBotDefinition, input: string | IVRInput, state?: WhatsAppBotState | null, channel?: IVRChannel) => Promise<WhatsAppBotTurn & {
|
|
79
|
+
sent: false;
|
|
80
|
+
}>;
|
|
81
|
+
};
|
|
82
|
+
ivr: {
|
|
83
|
+
get: (archiveId: string, id: string) => Promise<VoiceIVRSession>;
|
|
84
|
+
start: (archiveId: string, callId: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<VoiceIVRSession>;
|
|
85
|
+
advance: (archiveId: string, id: string, input: IVRInput, expectedTurn: number, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<VoiceIVRSession>;
|
|
86
|
+
};
|
|
87
|
+
operations: {
|
|
88
|
+
get: <T = unknown>(id: string) => Promise<ProviderOperation<T>>;
|
|
89
|
+
list: () => Promise<ProviderOperation<unknown>[]>;
|
|
90
|
+
submit: (id: string, command: ProviderCommand, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<ProviderOperation<unknown>>;
|
|
91
|
+
};
|
|
92
|
+
calls: {
|
|
93
|
+
inspect: (id: string) => Promise<ProviderOperation<{
|
|
94
|
+
capabilities: CallCapabilities;
|
|
95
|
+
active: CallSnapshot | null;
|
|
96
|
+
}>>;
|
|
97
|
+
start: (id: string, to: string, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<ProviderOperation<CallActionResult>>;
|
|
98
|
+
control: (id: string, action: "accept" | "reject" | "end" | "mute", call: CallIdentity, muted?: boolean, key?: `${string}-${string}-${string}-${string}-${string}`) => Promise<ProviderOperation<CallActionResult>>;
|
|
99
|
+
};
|
|
100
|
+
refreshContact: (id: string, chatId: string) => Promise<ProviderOperation<ConversationContact>>;
|
|
101
|
+
sessions: () => Promise<WhatsAppSession[]>;
|
|
102
|
+
connect: () => Promise<{
|
|
103
|
+
id: string;
|
|
104
|
+
state: string;
|
|
105
|
+
}>;
|
|
106
|
+
qr: (id: string) => Promise<{
|
|
107
|
+
state: string;
|
|
108
|
+
qr: string | null;
|
|
109
|
+
}>;
|
|
110
|
+
send: (id: string, payload: WhatsAppPayload, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
|
|
111
|
+
id: string;
|
|
112
|
+
state: string;
|
|
113
|
+
}>;
|
|
114
|
+
test: (id: string, payload: WhatsAppPayload) => Promise<{
|
|
115
|
+
valid: boolean;
|
|
116
|
+
kind: string;
|
|
117
|
+
to: string;
|
|
118
|
+
connected: boolean;
|
|
119
|
+
sent: false;
|
|
120
|
+
}>;
|
|
121
|
+
outbox: () => Promise<{
|
|
122
|
+
id: string;
|
|
123
|
+
session_id: string;
|
|
124
|
+
state: string;
|
|
125
|
+
provider_id: string | null;
|
|
126
|
+
error: string | null;
|
|
127
|
+
created_at: string;
|
|
128
|
+
}[]>;
|
|
129
|
+
sendText: (id: string, to: string, text: string, idempotencyKey?: `${string}-${string}-${string}-${string}-${string}`) => Promise<{
|
|
130
|
+
id: string;
|
|
131
|
+
state: string;
|
|
132
|
+
}>;
|
|
133
|
+
reconnect: (id: string) => Promise<any>;
|
|
134
|
+
disconnect: (id: string) => Promise<any>;
|
|
135
|
+
deleteConnection: (id: string) => Promise<{
|
|
136
|
+
removed: boolean;
|
|
137
|
+
state: string;
|
|
138
|
+
}>;
|
|
139
|
+
deleteArchive: (id: string) => Promise<{
|
|
140
|
+
removed: boolean;
|
|
141
|
+
state: string;
|
|
142
|
+
}>;
|
|
143
|
+
archives: () => Promise<WhatsAppArchive[]>;
|
|
144
|
+
messages: (id: string, before?: string, chat?: string) => Promise<WhatsAppMessage[]>;
|
|
145
|
+
conversations: (id: string) => Promise<Conversation[]>;
|
|
146
|
+
media: (archiveId: string, messageId: string) => Promise<{
|
|
147
|
+
data: string | null;
|
|
148
|
+
state: "available" | "queued";
|
|
149
|
+
}>;
|
|
150
|
+
};
|
package/dist/whatsapp.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { subscribeWhatsApp } from './realtime.js';
|
|
2
|
+
export function whatsappClient(request, installationId, realtime = { apiUrl: '' }) {
|
|
3
|
+
const root = `/v1/installations/${encodeURIComponent(installationId)}/whatsapp`;
|
|
4
|
+
const session = (id) => root + `/sessions/${encodeURIComponent(id)}`;
|
|
5
|
+
const archive = (id) => root + `/archives/${encodeURIComponent(id)}`;
|
|
6
|
+
return {
|
|
7
|
+
subscribe: (options) => subscribeWhatsApp(request, root, realtime, options),
|
|
8
|
+
bot: {
|
|
9
|
+
get: (archiveId) => request(archive(archiveId) + '/bot'),
|
|
10
|
+
configure: (archiveId, definition, expectedRevision) => request(archive(archiveId) + '/bot', 'PUT', { definition, expectedRevision }),
|
|
11
|
+
activate: (archiveId, enabled, expectedRevision) => request(archive(archiveId) + '/bot/activation', 'PUT', { enabled, expectedRevision }),
|
|
12
|
+
preview: (definition, input, state = null, channel = 'whatsapp') => request(root + '/bot/preview', 'POST', { definition, input, state, channel })
|
|
13
|
+
},
|
|
14
|
+
ivr: {
|
|
15
|
+
get: (archiveId, id) => request(archive(archiveId) + `/bot/voice-sessions/${encodeURIComponent(id)}`),
|
|
16
|
+
start: (archiveId, callId, idempotencyKey = crypto.randomUUID()) => request(archive(archiveId) + '/bot/voice-sessions', 'POST', { callId }, { 'Idempotency-Key': idempotencyKey }),
|
|
17
|
+
advance: (archiveId, id, input, expectedTurn, idempotencyKey = crypto.randomUUID()) => request(archive(archiveId) + `/bot/voice-sessions/${encodeURIComponent(id)}/turns`, 'POST', { input, expectedTurn }, { 'Idempotency-Key': idempotencyKey })
|
|
18
|
+
},
|
|
19
|
+
operations: {
|
|
20
|
+
get: (id) => request(root + `/operations/${encodeURIComponent(id)}`),
|
|
21
|
+
list: () => request(root + '/operations'),
|
|
22
|
+
submit: (id, command, idempotencyKey = crypto.randomUUID()) => request(session(id) + '/operations', 'POST', command, { 'Idempotency-Key': idempotencyKey })
|
|
23
|
+
},
|
|
24
|
+
calls: {
|
|
25
|
+
inspect: (id) => request(session(id) + '/operations', 'POST', { kind: 'call.inspect' }, { 'Idempotency-Key': crypto.randomUUID() }),
|
|
26
|
+
start: (id, to, key = crypto.randomUUID()) => request(session(id) + '/operations', 'POST', { kind: 'call.start', to }, { 'Idempotency-Key': key }),
|
|
27
|
+
control: (id, action, call, muted = false, key = crypto.randomUUID()) => request(session(id) + '/operations', 'POST', { kind: 'call.' + action, call, ...action === 'mute' ? { muted } : {} }, { 'Idempotency-Key': key })
|
|
28
|
+
},
|
|
29
|
+
refreshContact: (id, chatId) => request(session(id) + '/operations', 'POST', { kind: 'contact.refresh', chatId }, { 'Idempotency-Key': crypto.randomUUID() }),
|
|
30
|
+
sessions: () => request(root + '/sessions'), connect: () => request(root + '/sessions', 'POST'),
|
|
31
|
+
qr: (id) => request(session(id) + '/qr'),
|
|
32
|
+
send: (id, payload, idempotencyKey = crypto.randomUUID()) => request(session(id) + '/messages', 'POST', payload, { 'Idempotency-Key': idempotencyKey }),
|
|
33
|
+
test: (id, payload) => request(session(id) + '/messages/test', 'POST', payload),
|
|
34
|
+
outbox: () => request(root + '/outbox'),
|
|
35
|
+
sendText: (id, to, text, idempotencyKey = crypto.randomUUID()) => request(session(id) + '/messages', 'POST', { kind: 'text', to, text }, { 'Idempotency-Key': idempotencyKey }),
|
|
36
|
+
reconnect: (id) => request(session(id) + '/reconnect', 'POST'), disconnect: (id) => request(session(id) + '/disconnect', 'POST'),
|
|
37
|
+
deleteConnection: (id) => request(session(id), 'DELETE'),
|
|
38
|
+
deleteArchive: (id) => request(archive(id), 'DELETE'),
|
|
39
|
+
archives: () => request(root + '/archives'),
|
|
40
|
+
messages: (id, before, chat) => request(archive(id) + `/messages?${new URLSearchParams({ ...before ? { before } : {}, ...chat ? { chat } : {} })}`),
|
|
41
|
+
conversations: (id) => request(archive(id) + '/conversations'),
|
|
42
|
+
media: (archiveId, messageId) => request(archive(archiveId) + `/messages/${encodeURIComponent(messageId)}/media`)
|
|
43
|
+
};
|
|
44
|
+
}
|