@miguelmorales13/nestkit 0.31.3 → 0.32.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 +236 -0
- package/dist/chunk-2RQINZCR.cjs +17 -0
- package/dist/{chunk-LU3HO7B3.js → chunk-3WISEIHK.js} +4 -15
- package/dist/chunk-HMHUOXGB.cjs +63 -0
- package/dist/chunk-L2QK2HN5.js +17 -0
- package/dist/chunk-PBAPT3L5.js +63 -0
- package/dist/chunk-QVLTEABJ.cjs +248 -0
- package/dist/chunk-XKI3DJVA.js +248 -0
- package/dist/{chunk-33KFVAUZ.cjs → chunk-ZBOQKXGZ.cjs} +7 -18
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/payments/connect/terminal-connections.d.ts +7 -0
- package/dist/payments/index.cjs +36 -7
- package/dist/payments/index.js +31 -2
- package/dist/resilience/index.cjs +48 -262
- package/dist/resilience/index.js +19 -233
- package/dist/security/index.cjs +4 -2
- package/dist/security/index.js +5 -3
- package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
- package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
- package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
- package/dist/telephony/index.cjs +2269 -0
- package/dist/telephony/index.d.ts +20 -0
- package/dist/telephony/index.js +2269 -0
- package/dist/telephony/provider-http.d.ts +35 -0
- package/dist/telephony/relay/access.d.ts +72 -0
- package/dist/telephony/relay/backend.d.ts +81 -0
- package/dist/telephony/relay/index.cjs +483 -0
- package/dist/telephony/relay/index.d.ts +9 -0
- package/dist/telephony/relay/index.js +483 -0
- package/dist/telephony/relay/server.d.ts +89 -0
- package/dist/telephony/relay/session.d.ts +100 -0
- package/dist/telephony/rules/call-limits.d.ts +48 -0
- package/dist/telephony/rules/call-token.d.ts +30 -0
- package/dist/telephony/rules/destination-policy.d.ts +21 -0
- package/dist/telephony/rules/dial-destination.d.ts +21 -0
- package/dist/telephony/rules/event-deduper.d.ts +15 -0
- package/dist/telephony/rules/handoff.d.ts +7 -0
- package/dist/telephony/rules/index.d.ts +20 -0
- package/dist/telephony/rules/opt-out.d.ts +32 -0
- package/dist/telephony/rules/phone.d.ts +9 -0
- package/dist/telephony/rules/provider-gate.d.ts +31 -0
- package/dist/telephony/rules/redact.d.ts +11 -0
- package/dist/telephony/rules/sanitize.d.ts +10 -0
- package/dist/telephony/rules/sliding-window.d.ts +10 -0
- package/dist/telephony/rules/ttl-cache.d.ts +14 -0
- package/dist/telephony/rules/usage-counter.d.ts +16 -0
- package/dist/telephony/telephony.errors.d.ts +46 -0
- package/dist/telephony/telephony.facade.d.ts +71 -0
- package/dist/telephony/telephony.module.d.ts +38 -0
- package/dist/telephony/telephony.options.d.ts +187 -0
- package/dist/telephony/telephony.port.d.ts +421 -0
- package/dist/telephony/telephony.registry.d.ts +24 -0
- package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
- package/dist/telephony/telephony.webhooks.d.ts +53 -0
- package/dist/whatsapp/index.cjs +28 -0
- package/dist/whatsapp/index.js +28 -0
- package/dist/whatsapp/whatsapp-client.d.ts +5 -0
- package/package.json +12 -2
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { DestinationPolicy } from './rules/destination-policy.js';
|
|
2
|
+
import type { OptOutStore } from './rules/opt-out.js';
|
|
3
|
+
import type { EventDeduper } from './rules/event-deduper.js';
|
|
4
|
+
import type { ProviderHttpOptions } from './provider-http.js';
|
|
5
|
+
import type { AnswerInstruction, TelephonyAdapter, TelephonyCapability } from './telephony.port.js';
|
|
6
|
+
/** Token que lleva las {@link TelephonyOptions} con las que se registró el módulo. */
|
|
7
|
+
export declare const TELEPHONY_OPTIONS: unique symbol;
|
|
8
|
+
/** Token del {@link TelephonyWebhooks} (el camino único de todo webhook). */
|
|
9
|
+
export declare const TELEPHONY_WEBHOOKS: unique symbol;
|
|
10
|
+
/** Token del {@link TelephonyHooks} que implementa el consumidor. */
|
|
11
|
+
export declare const TELEPHONY_HOOKS: unique symbol;
|
|
12
|
+
export interface TwilioOptions extends ProviderHttpOptions {
|
|
13
|
+
accountSid: string;
|
|
14
|
+
authToken: string;
|
|
15
|
+
/**
|
|
16
|
+
* *Regulatory Bundle* aprobado (`BUxxxxxxxx`). **Los números de México lo exigen**: lo crea y aprueba una persona en
|
|
17
|
+
* la consola de Twilio; no se automatiza.
|
|
18
|
+
*/
|
|
19
|
+
bundleSid?: string;
|
|
20
|
+
/** Dirección registrada en la cuenta (`ADxxxxxxxx`), también exigida para México. */
|
|
21
|
+
addressSid?: string;
|
|
22
|
+
/** Lada por omisión de los números a comprar (p. ej. `55`). */
|
|
23
|
+
areaCode?: string;
|
|
24
|
+
/** Idioma de la voz y la transcripción (BCP-47). Por omisión `es-MX`. */
|
|
25
|
+
language?: string;
|
|
26
|
+
/** Proveedor de voz y de transcripción de ConversationRelay. Por omisión `Google` en ambos. */
|
|
27
|
+
ttsProvider?: string;
|
|
28
|
+
transcriptionProvider?: string;
|
|
29
|
+
/** Voz concreta del proveedor de TTS (p. ej. `es-MX-Standard-A`). */
|
|
30
|
+
voice?: string;
|
|
31
|
+
/** Modo de interrupción de ConversationRelay. Por omisión `speech`. */
|
|
32
|
+
interruptible?: 'any' | 'speech' | 'dtmf' | 'none';
|
|
33
|
+
/** Número desde el que sale WhatsApp (`whatsapp:+…` también vale) si el envío no trae `from`. */
|
|
34
|
+
whatsappFrom?: string;
|
|
35
|
+
/** Mensaje por omisión cuando un destino de desvío se rechaza. */
|
|
36
|
+
unavailableMessage?: string;
|
|
37
|
+
/** Subcuenta a la que pertenece este adaptador (el `accountSid` ya la identifica; solo informativo). */
|
|
38
|
+
/** Segundos de timbrado de la llamada de prueba del desvío. Por omisión 40. */
|
|
39
|
+
testCallRingSeconds?: number;
|
|
40
|
+
/** Para pruebas. Por omisión `https://api.twilio.com`. */
|
|
41
|
+
baseUrl?: string;
|
|
42
|
+
/** Para pruebas. Por omisión `https://numbers.twilio.com` / `https://pricing.twilio.com`. */
|
|
43
|
+
numbersBaseUrl?: string;
|
|
44
|
+
pricingBaseUrl?: string;
|
|
45
|
+
/** Tope de páginas al sumar uso por número (una consulta nunca recorre toda la historia). Por omisión 20. */
|
|
46
|
+
maxUsagePages?: number;
|
|
47
|
+
/** Permitir un relay que no sea `wss://` (solo desarrollo). Por omisión `false`. */
|
|
48
|
+
allowInsecureRelay?: boolean;
|
|
49
|
+
}
|
|
50
|
+
export interface MetaWhatsAppOptions {
|
|
51
|
+
/** Cliente de `@miguelmorales13/nestkit/whatsapp` (`WhatsAppClient`), ya construido: no se duplica su lógica. */
|
|
52
|
+
client: {
|
|
53
|
+
sendTextMessage(to: string, body: string): Promise<{
|
|
54
|
+
messages: Array<{
|
|
55
|
+
id: string;
|
|
56
|
+
}>;
|
|
57
|
+
}>;
|
|
58
|
+
sendTemplateMessage?(to: string, template: string, language: string, variables?: string[]): Promise<{
|
|
59
|
+
messages: Array<{
|
|
60
|
+
id: string;
|
|
61
|
+
}>;
|
|
62
|
+
}>;
|
|
63
|
+
};
|
|
64
|
+
/** `App Secret` de la app de Meta: firma `X-Hub-Signature-256` del cuerpo. Sin él, ningún webhook es válido. */
|
|
65
|
+
appSecret?: string;
|
|
66
|
+
/** Token de verificación del webhook (el `hub.verify_token` del reto). */
|
|
67
|
+
verifyToken?: string;
|
|
68
|
+
/** Número (E.164) desde el que escribe este `phoneNumberId`; solo para rellenar `from` en `MessageInfo`. */
|
|
69
|
+
displayNumber?: string;
|
|
70
|
+
}
|
|
71
|
+
export interface SimulatedTelephonyOptions {
|
|
72
|
+
/** Secreto con el que el simulador firma y verifica webhooks. Por omisión `simulated-secret`. */
|
|
73
|
+
secret?: string;
|
|
74
|
+
/** Números disponibles. Por omisión se inventan consecutivos `+5255…`. Con `[]` no hay inventario. */
|
|
75
|
+
inventory?: string[];
|
|
76
|
+
/** Hace que `placeTestCall` devuelva `false`. */
|
|
77
|
+
failTestCalls?: boolean;
|
|
78
|
+
/** Capacidades que declara (para probar «no soportado» y los respaldos). Por omisión todas. */
|
|
79
|
+
capabilities?: TelephonyCapability[];
|
|
80
|
+
/** Nombre del proveedor simulado (para tener dos en una prueba de respaldo). */
|
|
81
|
+
name?: string;
|
|
82
|
+
}
|
|
83
|
+
/** Cómo se construye un adaptador a partir de su configuración. */
|
|
84
|
+
export type ProviderFactory = (config: any, context: {
|
|
85
|
+
tenantId?: string;
|
|
86
|
+
}) => TelephonyAdapter;
|
|
87
|
+
export interface TenantTelephonyConfig {
|
|
88
|
+
provider: string;
|
|
89
|
+
/** La configuración (credenciales) de ESE tenant. Nunca se comparte entre tenants. */
|
|
90
|
+
config: unknown;
|
|
91
|
+
fallbacks?: {
|
|
92
|
+
provider: string;
|
|
93
|
+
config: unknown;
|
|
94
|
+
}[];
|
|
95
|
+
}
|
|
96
|
+
/** Una operación saliente que cuesta dinero: el gancho de tope de gasto la recibe antes de ejecutarla. */
|
|
97
|
+
export interface OutboundOperation {
|
|
98
|
+
kind: 'call' | 'sms' | 'whatsapp';
|
|
99
|
+
tenantId?: string;
|
|
100
|
+
from?: string;
|
|
101
|
+
to: string;
|
|
102
|
+
}
|
|
103
|
+
export interface TelephonyPolicy {
|
|
104
|
+
/** Países y prefijos permitidos o bloqueados. Por omisión solo México y sin tarificación especial. */
|
|
105
|
+
destinations?: DestinationPolicy;
|
|
106
|
+
/** Bajas (STOP/BAJA). Por omisión de memoria: en producción pasa uno persistente. */
|
|
107
|
+
optOutStore?: OptOutStore;
|
|
108
|
+
/**
|
|
109
|
+
* Gancho previo a toda llamada/SMS/WhatsApp saliente: lanza (p. ej. `TelephonyLimitExceededException`) para
|
|
110
|
+
* cortar por tope de gasto, de simultáneas o de periodo. La librería no cobra: tú decides.
|
|
111
|
+
*/
|
|
112
|
+
beforeOutbound?: (operation: OutboundOperation) => void | Promise<void>;
|
|
113
|
+
/** Tras un envío exitoso (para contar consumo). */
|
|
114
|
+
afterOutbound?: (operation: OutboundOperation, result: {
|
|
115
|
+
id: string;
|
|
116
|
+
}) => void | Promise<void>;
|
|
117
|
+
/** Largo máximo de un SMS/WhatsApp. Por omisión 1600. */
|
|
118
|
+
maxMessageLength?: number;
|
|
119
|
+
/** Caché de consultas de uso y listados. Por omisión 30 s. */
|
|
120
|
+
readCacheTtlMs?: number;
|
|
121
|
+
}
|
|
122
|
+
export interface TelephonyOptions {
|
|
123
|
+
/** Proveedor principal: `twilio`, `simulated`, `meta-whatsapp` o uno registrado con `factories`. */
|
|
124
|
+
provider?: string;
|
|
125
|
+
/** Respaldos: si el principal no soporta una capacidad (o está caído en una lectura) se usa el siguiente. */
|
|
126
|
+
fallbacks?: string[];
|
|
127
|
+
/** Fuerza una capacidad a un proveedor concreto (p. ej. `{ whatsapp: 'meta-whatsapp' }`). */
|
|
128
|
+
channels?: Partial<Record<TelephonyCapability, string>>;
|
|
129
|
+
twilio?: TwilioOptions;
|
|
130
|
+
simulated?: SimulatedTelephonyOptions;
|
|
131
|
+
metaWhatsApp?: MetaWhatsAppOptions;
|
|
132
|
+
/** Configuración de proveedores propios, por nombre. */
|
|
133
|
+
providers?: Record<string, unknown>;
|
|
134
|
+
/** Fábricas de proveedores propios (`registerProvider`): se suman a las integradas. */
|
|
135
|
+
factories?: Record<string, ProviderFactory>;
|
|
136
|
+
/** Credenciales por tenant: `telephony.forTenant(id)` arma un adaptador con las de ese tenant. */
|
|
137
|
+
tenantProvider?: (tenantId: string) => Promise<TenantTelephonyConfig | null>;
|
|
138
|
+
/** Cuántos tenants se conservan en memoria y por cuánto. Por omisión 500 y 10 min. */
|
|
139
|
+
tenantCache?: {
|
|
140
|
+
max?: number;
|
|
141
|
+
ttlMs?: number;
|
|
142
|
+
};
|
|
143
|
+
policy?: TelephonyPolicy;
|
|
144
|
+
/** Idempotencia de webhooks. Por omisión memoria (15 min). */
|
|
145
|
+
deduper?: EventDeduper;
|
|
146
|
+
webhook?: WebhookOptions;
|
|
147
|
+
/** Dónde escriben los avisos internos (se redactan teléfonos y secretos). Por omisión, ninguno. */
|
|
148
|
+
logger?: (line: string) => void;
|
|
149
|
+
}
|
|
150
|
+
export interface WebhookOptions {
|
|
151
|
+
/** Un evento cuyo `occurredAt` sea más viejo que esto se descarta como repetición. Por omisión 5 min. */
|
|
152
|
+
maxSkewMs?: number;
|
|
153
|
+
/** Cuánto espera a `onEvent` para contestar una llamada entrante antes de usar la respuesta de respaldo. Por omisión 2500. */
|
|
154
|
+
answerBudgetMs?: number;
|
|
155
|
+
/** Qué se contesta si `onEvent` no responde a tiempo, falla o no devuelve instrucción. Por omisión cuelga con el saludo de respaldo. */
|
|
156
|
+
fallbackAnswer?: AnswerInstruction;
|
|
157
|
+
/** Peticiones por ventana por origen (IP o proveedor). Por omisión 600 por minuto; `false` lo apaga. */
|
|
158
|
+
rateLimit?: {
|
|
159
|
+
max: number;
|
|
160
|
+
windowMs: number;
|
|
161
|
+
} | false;
|
|
162
|
+
/** Textos propios (idioma). */
|
|
163
|
+
texts?: Partial<TelephonyTexts>;
|
|
164
|
+
}
|
|
165
|
+
/** Los idiomas y textos por omisión que usa la librería cuando el consumidor no pasa los suyos. */
|
|
166
|
+
export interface TelephonyTexts {
|
|
167
|
+
/** Lo que se dice si un desvío no se puede marcar. */
|
|
168
|
+
unavailable: string;
|
|
169
|
+
/** Lo que se dice si el consumidor no contestó a tiempo la llamada entrante. */
|
|
170
|
+
greetingFallback: string;
|
|
171
|
+
}
|
|
172
|
+
export declare const DEFAULT_TEXTS: TelephonyTexts;
|
|
173
|
+
/**
|
|
174
|
+
* Lo que implementa el consumidor para conectar la librería con su negocio. **Todo es opcional**: se puede empezar
|
|
175
|
+
* solo por números o solo por el validador de firma y agregar hooks después.
|
|
176
|
+
*/
|
|
177
|
+
export interface TelephonyHooks {
|
|
178
|
+
/** Dueño de un número (la línea a la que se llamó o escribió). `null` = no es de nadie: se ignora el evento. */
|
|
179
|
+
resolveTenant?(number: string): Promise<string | null> | string | null;
|
|
180
|
+
/**
|
|
181
|
+
* Cada evento normalizado. Para `llamada.entrante` puede devolver cómo contestar; si no contesta a tiempo
|
|
182
|
+
* (`answerBudgetMs`), se usa `onAnswerTimeout`. Los demás eventos se acusan de inmediato y esto corre aparte.
|
|
183
|
+
*/
|
|
184
|
+
onEvent?(event: import('./telephony.port.js').TelephonyEvent): Promise<AnswerInstruction | void> | AnswerInstruction | void;
|
|
185
|
+
/** Un fallo en `onEvent` (nunca viaja al proveedor ni al cliente): regístralo. */
|
|
186
|
+
onError?(error: unknown, event: import('./telephony.port.js').TelephonyEvent): void;
|
|
187
|
+
}
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Puerto de telefonía **v1**. Un proveedor es un {@link TelephonyAdapter} que declara las capacidades que soporta
|
|
3
|
+
* (`numbers`, `voice`, `sms`, `whatsapp`, `usage`) y siempre trae `webhooks`. Quien consume inyecta {@link Telephony}
|
|
4
|
+
* (la fachada): pedir una capacidad que ningún proveedor soporta lanza `UnsupportedCapabilityException`.
|
|
5
|
+
*
|
|
6
|
+
* Reglas del puerto (para que crezca sin romper a nadie):
|
|
7
|
+
* - Capacidades nuevas (MMS, video, OTP…) son propiedades opcionales nuevas; los métodos nuevos, opcionales.
|
|
8
|
+
* - Los campos nuevos de las respuestas son opcionales; nada de tipos del proveedor se filtra aquí.
|
|
9
|
+
* - Lo específico de un proveedor viaja en `extra` (solo entrada, opt-in, acotado y sin garantías) o `raw` (solo salida).
|
|
10
|
+
* - `TELEPHONY_PORT_VERSION` sube solo ante un cambio incompatible.
|
|
11
|
+
*/
|
|
12
|
+
export declare const TELEPHONY: unique symbol;
|
|
13
|
+
export declare const TELEPHONY_PORT_VERSION = 1;
|
|
14
|
+
export type TelephonyCapability = 'numbers' | 'voice' | 'sms' | 'whatsapp' | 'usage';
|
|
15
|
+
/** Dinero con decimales exactos y su moneda (los proveedores cobran fracciones de centavo por SMS). */
|
|
16
|
+
export interface Money {
|
|
17
|
+
/** Cadena decimal (`'1.15'`, `'0.0079'`): nunca un float. */
|
|
18
|
+
amount: string;
|
|
19
|
+
/** ISO-4217 (`USD`). */
|
|
20
|
+
currency: string;
|
|
21
|
+
}
|
|
22
|
+
export interface Page<T> {
|
|
23
|
+
items: T[];
|
|
24
|
+
/** Pasa esto como `cursor` para la siguiente página; ausente = no hay más. */
|
|
25
|
+
nextCursor?: string;
|
|
26
|
+
}
|
|
27
|
+
export type NumberType = 'local' | 'mobile' | 'toll_free';
|
|
28
|
+
export type NumberStatus = 'active' | 'pending_regulation' | 'released';
|
|
29
|
+
export interface NumberSearch {
|
|
30
|
+
/** País ISO-3166 alfa-2. Por omisión `MX`. */
|
|
31
|
+
country?: string;
|
|
32
|
+
type?: NumberType;
|
|
33
|
+
/** Lada o código de área. */
|
|
34
|
+
areaCode?: string;
|
|
35
|
+
/** Ciudad o localidad, si el proveedor la filtra. */
|
|
36
|
+
city?: string;
|
|
37
|
+
/** Dígitos que debe contener. */
|
|
38
|
+
contains?: string;
|
|
39
|
+
/** Capacidades que necesitas del número. */
|
|
40
|
+
needs?: {
|
|
41
|
+
voice?: boolean;
|
|
42
|
+
sms?: boolean;
|
|
43
|
+
whatsapp?: boolean;
|
|
44
|
+
};
|
|
45
|
+
limit?: number;
|
|
46
|
+
}
|
|
47
|
+
export interface AvailableNumber {
|
|
48
|
+
number: string;
|
|
49
|
+
country: string;
|
|
50
|
+
type: NumberType;
|
|
51
|
+
city?: string;
|
|
52
|
+
region?: string;
|
|
53
|
+
capabilities: {
|
|
54
|
+
voice: boolean;
|
|
55
|
+
sms: boolean;
|
|
56
|
+
mms?: boolean;
|
|
57
|
+
};
|
|
58
|
+
/** El proveedor pide un trámite regulatorio (bundle/dirección) para comprarlo. */
|
|
59
|
+
requiresRegulation: boolean;
|
|
60
|
+
/** Renta mensual, si el proveedor la informa en la búsqueda. */
|
|
61
|
+
monthlyCost?: Money;
|
|
62
|
+
}
|
|
63
|
+
export interface NumberRequirements {
|
|
64
|
+
country: string;
|
|
65
|
+
type: NumberType;
|
|
66
|
+
/** Hace falta un trámite regulatorio aprobado (en México, un *Regulatory Bundle* de Twilio). */
|
|
67
|
+
needsBundle: boolean;
|
|
68
|
+
needsAddress: boolean;
|
|
69
|
+
/** Texto para personas sobre el trámite. */
|
|
70
|
+
notes: string[];
|
|
71
|
+
/** `static` = conocimiento incluido en la librería (puede estar desactualizado); `provider` = lo dijo el proveedor. */
|
|
72
|
+
source: 'static' | 'provider';
|
|
73
|
+
}
|
|
74
|
+
export interface ProvisionNumberInput {
|
|
75
|
+
/** URL pública a la que el proveedor llama cuando entra una llamada. */
|
|
76
|
+
voiceUrl: string;
|
|
77
|
+
smsUrl?: string;
|
|
78
|
+
/** A dónde avisa el proveedor del estado de las llamadas (duración, fin). */
|
|
79
|
+
statusCallbackUrl?: string;
|
|
80
|
+
/** Nombre legible en la consola (`miapp-ab12cd34`). */
|
|
81
|
+
label?: string;
|
|
82
|
+
/** Un número concreto de `search()`; si no, se compra el primero que cumpla `search`. */
|
|
83
|
+
number?: string;
|
|
84
|
+
search?: NumberSearch;
|
|
85
|
+
/** Misma clave = mismo número (un reintento tras un corte no compra dos). */
|
|
86
|
+
idempotencyKey?: string;
|
|
87
|
+
/** Opt-in, acotado, específico del proveedor. */
|
|
88
|
+
extra?: Record<string, string>;
|
|
89
|
+
}
|
|
90
|
+
export interface PhoneNumber {
|
|
91
|
+
id: string;
|
|
92
|
+
number: string;
|
|
93
|
+
provider: string;
|
|
94
|
+
status: NumberStatus;
|
|
95
|
+
country?: string;
|
|
96
|
+
type?: NumberType;
|
|
97
|
+
label?: string;
|
|
98
|
+
capabilities?: {
|
|
99
|
+
voice: boolean;
|
|
100
|
+
sms: boolean;
|
|
101
|
+
};
|
|
102
|
+
voiceUrl?: string;
|
|
103
|
+
smsUrl?: string;
|
|
104
|
+
monthlyCost?: Money;
|
|
105
|
+
createdAt?: string;
|
|
106
|
+
raw?: unknown;
|
|
107
|
+
}
|
|
108
|
+
export interface ConfigureNumberInput {
|
|
109
|
+
voiceUrl?: string;
|
|
110
|
+
voiceFallbackUrl?: string;
|
|
111
|
+
smsUrl?: string;
|
|
112
|
+
statusCallbackUrl?: string;
|
|
113
|
+
label?: string;
|
|
114
|
+
}
|
|
115
|
+
export interface NumbersPort {
|
|
116
|
+
/** Números disponibles para comprar. Vacío = sin inventario. */
|
|
117
|
+
search(query?: NumberSearch): Promise<AvailableNumber[]>;
|
|
118
|
+
/** Qué trámite regulatorio exige este país/tipo. */
|
|
119
|
+
requirements(country?: string, type?: NumberType): Promise<NumberRequirements>;
|
|
120
|
+
/** Renta mensual de un tipo de número (consulta de precios del proveedor). `null` si no la informa. */
|
|
121
|
+
monthlyCost(country?: string, type?: NumberType): Promise<Money | null>;
|
|
122
|
+
/** Busca (o usa `number`), compra y configura. `null` solo si no hay inventario; otra falla lanza. */
|
|
123
|
+
provision(input: ProvisionNumberInput): Promise<PhoneNumber | null>;
|
|
124
|
+
/** Cambia URLs y nombre de un número ya comprado. */
|
|
125
|
+
configure(id: string, input: ConfigureNumberInput): Promise<PhoneNumber>;
|
|
126
|
+
get(id: string): Promise<PhoneNumber>;
|
|
127
|
+
/** Los números de la cuenta, paginados. */
|
|
128
|
+
list(options?: {
|
|
129
|
+
cursor?: string;
|
|
130
|
+
limit?: number;
|
|
131
|
+
}): Promise<Page<PhoneNumber>>;
|
|
132
|
+
/** Libera el número. Idempotente: soltar uno que ya no existe no es error. */
|
|
133
|
+
release(id: string): Promise<void>;
|
|
134
|
+
/** Pasa el número a otra subcuenta del mismo proveedor. */
|
|
135
|
+
transfer?(id: string, toAccountId: string): Promise<PhoneNumber>;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Cómo contestar una llamada. Es **intención**, no el formato del proveedor: cada adaptador la traduce
|
|
139
|
+
* (TwiML en Twilio, XML de Plivo, JSON de otro).
|
|
140
|
+
*/
|
|
141
|
+
export type AnswerInstruction =
|
|
142
|
+
/** Conecta la llamada con un servidor de conversación (STT/TTS lo hace el proveedor). La URL debe ser `wss://`. */
|
|
143
|
+
{
|
|
144
|
+
kind: 'relay';
|
|
145
|
+
url: string;
|
|
146
|
+
greeting: string;
|
|
147
|
+
/** A dónde llama el proveedor cuando termina la sesión (decidir si se desvía a una persona). */
|
|
148
|
+
actionUrl: string;
|
|
149
|
+
/** Parámetros que el proveedor entrega al servidor de voz al conectar (el token de la llamada). */
|
|
150
|
+
parameters?: Record<string, string>;
|
|
151
|
+
/** Idioma/voz de esta llamada; si no, el del adaptador. */
|
|
152
|
+
language?: string;
|
|
153
|
+
}
|
|
154
|
+
/** Desvía a una persona. Un destino no permitido degrada a `hangup` con `fallbackMessage`. */
|
|
155
|
+
| {
|
|
156
|
+
kind: 'dial';
|
|
157
|
+
to: string;
|
|
158
|
+
callerId?: string;
|
|
159
|
+
/** Segundos que suena. Por omisión 25. */
|
|
160
|
+
ringSeconds?: number;
|
|
161
|
+
/** Tope de duración de la llamada desviada. Por omisión 1800. */
|
|
162
|
+
maxSeconds?: number;
|
|
163
|
+
fallbackMessage?: string;
|
|
164
|
+
language?: string;
|
|
165
|
+
}
|
|
166
|
+
/** Rechaza sin contestar ni cobrar. */
|
|
167
|
+
| {
|
|
168
|
+
kind: 'reject';
|
|
169
|
+
}
|
|
170
|
+
/** Cuelga, opcionalmente tras decir un mensaje. */
|
|
171
|
+
| {
|
|
172
|
+
kind: 'hangup';
|
|
173
|
+
message?: string;
|
|
174
|
+
language?: string;
|
|
175
|
+
};
|
|
176
|
+
export interface AnswerResponse {
|
|
177
|
+
body: string;
|
|
178
|
+
/** Se manda tal cual como `Content-Type`. */
|
|
179
|
+
contentType: string;
|
|
180
|
+
}
|
|
181
|
+
export type CallStatus = 'queued' | 'ringing' | 'in_progress' | 'completed' | 'busy' | 'no_answer' | 'failed' | 'canceled';
|
|
182
|
+
export interface CallInfo {
|
|
183
|
+
id: string;
|
|
184
|
+
provider: string;
|
|
185
|
+
direction: 'inbound' | 'outbound';
|
|
186
|
+
from: string;
|
|
187
|
+
to: string;
|
|
188
|
+
status: CallStatus;
|
|
189
|
+
durationSeconds?: number;
|
|
190
|
+
/** Minutos que el proveedor cobra (redondeo al incremento del proveedor). */
|
|
191
|
+
billableMinutes?: number;
|
|
192
|
+
/** Lo que el proveedor cobró por la llamada, si ya lo sabe. */
|
|
193
|
+
cost?: Money;
|
|
194
|
+
startedAt?: string;
|
|
195
|
+
endedAt?: string;
|
|
196
|
+
raw?: unknown;
|
|
197
|
+
}
|
|
198
|
+
export interface PlaceCallInput {
|
|
199
|
+
from: string;
|
|
200
|
+
to: string;
|
|
201
|
+
/** Qué hacer al contestar (se resuelve en línea, sin URL). */
|
|
202
|
+
answer?: AnswerInstruction;
|
|
203
|
+
/** O la URL que el proveedor consulta al contestar. */
|
|
204
|
+
answerUrl?: string;
|
|
205
|
+
statusCallbackUrl?: string;
|
|
206
|
+
/** Segundos que suena antes de rendirse. */
|
|
207
|
+
ringSeconds?: number;
|
|
208
|
+
/** Tope de duración de la llamada. */
|
|
209
|
+
maxSeconds?: number;
|
|
210
|
+
idempotencyKey?: string;
|
|
211
|
+
extra?: Record<string, string>;
|
|
212
|
+
}
|
|
213
|
+
export interface VoicePort {
|
|
214
|
+
/** Traduce la intención de contestación al cuerpo que entiende el proveedor. Puro: no hace red. */
|
|
215
|
+
buildAnswer(instruction: AnswerInstruction): AnswerResponse;
|
|
216
|
+
/** Llamada saliente (a una persona, o a un destino que contesta con `answer`). */
|
|
217
|
+
placeCall(input: PlaceCallInput): Promise<CallInfo>;
|
|
218
|
+
/**
|
|
219
|
+
* Llamada de prueba de «comprobar desvío»: marca desde `from` (un número de la plataforma) hacia `to` (el teléfono del
|
|
220
|
+
* cliente); si el desvío está puesto, vuelve sola con origen = destino y se rechaza sin cobrar. `false` si no se pudo.
|
|
221
|
+
*/
|
|
222
|
+
placeTestCall(from: string, to: string): Promise<boolean>;
|
|
223
|
+
getCall(id: string): Promise<CallInfo>;
|
|
224
|
+
}
|
|
225
|
+
export type MessageChannel = 'sms' | 'whatsapp';
|
|
226
|
+
export type MessageStatus = 'queued' | 'sent' | 'delivered' | 'read' | 'undelivered' | 'failed' | 'received';
|
|
227
|
+
export interface MessageInfo {
|
|
228
|
+
id: string;
|
|
229
|
+
provider: string;
|
|
230
|
+
channel: MessageChannel;
|
|
231
|
+
direction: 'inbound' | 'outbound';
|
|
232
|
+
from: string;
|
|
233
|
+
to: string;
|
|
234
|
+
status: MessageStatus;
|
|
235
|
+
body?: string;
|
|
236
|
+
/** Segmentos facturados (SMS largo = varios). */
|
|
237
|
+
segments?: number;
|
|
238
|
+
cost?: Money;
|
|
239
|
+
/** Código de error estable de la librería si falló; nunca el texto del proveedor. */
|
|
240
|
+
errorReason?: string;
|
|
241
|
+
createdAt?: string;
|
|
242
|
+
raw?: unknown;
|
|
243
|
+
}
|
|
244
|
+
export interface SendSmsInput {
|
|
245
|
+
from: string;
|
|
246
|
+
to: string;
|
|
247
|
+
body: string;
|
|
248
|
+
statusCallbackUrl?: string;
|
|
249
|
+
idempotencyKey?: string;
|
|
250
|
+
/** Quién envía (para la baja y el tope por tenant). */
|
|
251
|
+
tenantId?: string;
|
|
252
|
+
extra?: Record<string, string>;
|
|
253
|
+
}
|
|
254
|
+
export interface SmsPort {
|
|
255
|
+
send(input: SendSmsInput): Promise<MessageInfo>;
|
|
256
|
+
get(id: string): Promise<MessageInfo>;
|
|
257
|
+
}
|
|
258
|
+
export interface SendWhatsAppTextInput {
|
|
259
|
+
from?: string;
|
|
260
|
+
to: string;
|
|
261
|
+
body: string;
|
|
262
|
+
statusCallbackUrl?: string;
|
|
263
|
+
idempotencyKey?: string;
|
|
264
|
+
tenantId?: string;
|
|
265
|
+
}
|
|
266
|
+
export interface SendWhatsAppTemplateInput {
|
|
267
|
+
from?: string;
|
|
268
|
+
to: string;
|
|
269
|
+
/** El id de la plantilla en el proveedor (`ContentSid` en Twilio, nombre en Meta). */
|
|
270
|
+
template: string;
|
|
271
|
+
language?: string;
|
|
272
|
+
/** Variables posicionales (`{{1}}`, `{{2}}`…), ya como texto; se sanitizan. */
|
|
273
|
+
variables?: string[];
|
|
274
|
+
statusCallbackUrl?: string;
|
|
275
|
+
idempotencyKey?: string;
|
|
276
|
+
tenantId?: string;
|
|
277
|
+
}
|
|
278
|
+
export interface WhatsAppPort {
|
|
279
|
+
/** Texto libre: solo dentro de la ventana de 24 h tras un mensaje del cliente (política de WhatsApp). */
|
|
280
|
+
sendText(input: SendWhatsAppTextInput): Promise<MessageInfo>;
|
|
281
|
+
/** Plantilla aprobada: lo único que se puede mandar fuera de la ventana de 24 h. */
|
|
282
|
+
sendTemplate(input: SendWhatsAppTemplateInput): Promise<MessageInfo>;
|
|
283
|
+
get?(id: string): Promise<MessageInfo>;
|
|
284
|
+
}
|
|
285
|
+
export type UsageCategory = 'voice' | 'sms' | 'whatsapp' | 'numbers';
|
|
286
|
+
export interface UsageQuery {
|
|
287
|
+
category: UsageCategory;
|
|
288
|
+
/** Inicio (inclusive) y fin (exclusivo) del periodo, `YYYY-MM-DD`. */
|
|
289
|
+
from: string;
|
|
290
|
+
to: string;
|
|
291
|
+
/** Un número en particular; sin él, toda la cuenta del proveedor. */
|
|
292
|
+
number?: string;
|
|
293
|
+
/** `day` = un registro por día; `total` = uno solo. Por omisión `total`. */
|
|
294
|
+
granularity?: 'day' | 'total';
|
|
295
|
+
}
|
|
296
|
+
export interface UsageRecord {
|
|
297
|
+
category: UsageCategory;
|
|
298
|
+
periodStart: string;
|
|
299
|
+
periodEnd: string;
|
|
300
|
+
/** Cuántas llamadas / mensajes / números. */
|
|
301
|
+
count: number;
|
|
302
|
+
/** Minutos (voz) o mensajes (SMS/WhatsApp) consumidos. */
|
|
303
|
+
units: number;
|
|
304
|
+
unit: 'minutes' | 'messages' | 'numbers';
|
|
305
|
+
/** Lo que el **proveedor** cobró: la base para que cada proyecto ponga su margen. */
|
|
306
|
+
providerCost?: Money;
|
|
307
|
+
}
|
|
308
|
+
export interface UsagePort {
|
|
309
|
+
query(query: UsageQuery): Promise<UsageRecord[]>;
|
|
310
|
+
}
|
|
311
|
+
/** Una petición entrante de un proveedor, tal como la recibe tu controlador. */
|
|
312
|
+
export interface WebhookRequest {
|
|
313
|
+
/** La URL **pública completa** a la que el proveedor llamó (esquema, host, ruta y query). */
|
|
314
|
+
url: string;
|
|
315
|
+
/** Cabeceras (cualquier capitalización). */
|
|
316
|
+
headers: Record<string, string | string[] | undefined>;
|
|
317
|
+
/** El cuerpo crudo, sin tocar. Obligatorio para proveedores que firman el cuerpo (Meta). */
|
|
318
|
+
rawBody?: string;
|
|
319
|
+
/** El formulario ya decodificado, para proveedores que firman parámetros (Twilio). */
|
|
320
|
+
params?: Record<string, string>;
|
|
321
|
+
}
|
|
322
|
+
export interface WebhooksPort {
|
|
323
|
+
/** ¿Lo mandó realmente el proveedor? Tiempo constante; falla cerrado; nunca lanza. */
|
|
324
|
+
verify(request: WebhookRequest): boolean;
|
|
325
|
+
/** Normaliza el cuerpo en eventos. Solo se llama tras `verify`. Un cuerpo puede traer varios. */
|
|
326
|
+
parse(request: WebhookRequest): TelephonyEvent[];
|
|
327
|
+
/** Respuesta de acuse cuando no hay nada que contestar (Twilio espera TwiML vacío). */
|
|
328
|
+
acknowledge(): AnswerResponse;
|
|
329
|
+
/** Reto de verificación de un webhook por GET (Meta `hub.challenge`). `null` = no es un reto válido. Opcional. */
|
|
330
|
+
challenge?(query: Record<string, string | undefined>): string | null;
|
|
331
|
+
}
|
|
332
|
+
/** Los nombres de eventos que cada proyecto escucha. */
|
|
333
|
+
export declare const TELEPHONY_EVENTS: {
|
|
334
|
+
readonly CALL_INCOMING: "llamada.entrante";
|
|
335
|
+
readonly CALL_STATUS: "llamada.estado";
|
|
336
|
+
readonly CALL_ENDED: "llamada.terminada";
|
|
337
|
+
readonly CALL_ACTION: "llamada.accion";
|
|
338
|
+
readonly SMS_RECEIVED: "sms.recibido";
|
|
339
|
+
readonly SMS_STATUS: "sms.estado";
|
|
340
|
+
readonly WHATSAPP_RECEIVED: "whatsapp.recibido";
|
|
341
|
+
readonly WHATSAPP_STATUS: "whatsapp.estado";
|
|
342
|
+
};
|
|
343
|
+
interface EventBase {
|
|
344
|
+
/** Clave de idempotencia: el mismo hecho siempre trae el mismo `id`, aunque el proveedor reintente. */
|
|
345
|
+
id: string;
|
|
346
|
+
provider: string;
|
|
347
|
+
/** Cuándo llegó (ms desde epoch). */
|
|
348
|
+
receivedAt: number;
|
|
349
|
+
/** Cuándo ocurrió según el proveedor, si lo dice (ms desde epoch): sirve para rechazar repeticiones viejas. */
|
|
350
|
+
occurredAt?: number;
|
|
351
|
+
/** Se completa si el consumidor implementó `resolveTenant(to)`. */
|
|
352
|
+
tenantId?: string;
|
|
353
|
+
}
|
|
354
|
+
export type TelephonyEvent = (EventBase & {
|
|
355
|
+
type: typeof TELEPHONY_EVENTS.CALL_INCOMING;
|
|
356
|
+
callId: string;
|
|
357
|
+
from: string;
|
|
358
|
+
to: string;
|
|
359
|
+
}) | (EventBase & {
|
|
360
|
+
type: typeof TELEPHONY_EVENTS.CALL_STATUS;
|
|
361
|
+
callId: string;
|
|
362
|
+
status: CallStatus;
|
|
363
|
+
from: string;
|
|
364
|
+
to: string;
|
|
365
|
+
}) | (EventBase & {
|
|
366
|
+
type: typeof TELEPHONY_EVENTS.CALL_ENDED;
|
|
367
|
+
callId: string;
|
|
368
|
+
status: CallStatus;
|
|
369
|
+
from: string;
|
|
370
|
+
to: string;
|
|
371
|
+
durationSeconds: number;
|
|
372
|
+
billableMinutes: number;
|
|
373
|
+
}) | (EventBase & {
|
|
374
|
+
type: typeof TELEPHONY_EVENTS.CALL_ACTION;
|
|
375
|
+
callId: string;
|
|
376
|
+
/** El relay pidió pasar la llamada a una persona. */
|
|
377
|
+
handoff: boolean;
|
|
378
|
+
/** La sesión de conversación terminó por una falla del proveedor. */
|
|
379
|
+
sessionFailed: boolean;
|
|
380
|
+
}) | (EventBase & {
|
|
381
|
+
type: typeof TELEPHONY_EVENTS.SMS_RECEIVED;
|
|
382
|
+
messageId: string;
|
|
383
|
+
from: string;
|
|
384
|
+
to: string;
|
|
385
|
+
body: string;
|
|
386
|
+
/** Si el texto es una palabra de baja/alta/ayuda; la baja ya quedó registrada. */
|
|
387
|
+
keyword?: 'opt_out' | 'opt_in' | 'help';
|
|
388
|
+
}) | (EventBase & {
|
|
389
|
+
type: typeof TELEPHONY_EVENTS.SMS_STATUS;
|
|
390
|
+
messageId: string;
|
|
391
|
+
status: MessageStatus;
|
|
392
|
+
errorReason?: string;
|
|
393
|
+
}) | (EventBase & {
|
|
394
|
+
type: typeof TELEPHONY_EVENTS.WHATSAPP_RECEIVED;
|
|
395
|
+
messageId: string;
|
|
396
|
+
from: string;
|
|
397
|
+
to: string;
|
|
398
|
+
body: string;
|
|
399
|
+
keyword?: 'opt_out' | 'opt_in' | 'help';
|
|
400
|
+
}) | (EventBase & {
|
|
401
|
+
type: typeof TELEPHONY_EVENTS.WHATSAPP_STATUS;
|
|
402
|
+
messageId: string;
|
|
403
|
+
status: MessageStatus;
|
|
404
|
+
errorReason?: string;
|
|
405
|
+
});
|
|
406
|
+
export type TelephonyEventType = TelephonyEvent['type'];
|
|
407
|
+
/**
|
|
408
|
+
* Lo que implementa un proveedor. Declara solo lo que soporta: omitir una capacidad es la forma de decir «no». Para
|
|
409
|
+
* agregar uno: implementa lo que soporte y pasa `runTelephonyContract` (ver README, «Cómo agregar un proveedor»).
|
|
410
|
+
*/
|
|
411
|
+
export interface TelephonyAdapter {
|
|
412
|
+
readonly provider: string;
|
|
413
|
+
readonly portVersion: typeof TELEPHONY_PORT_VERSION;
|
|
414
|
+
readonly webhooks: WebhooksPort;
|
|
415
|
+
readonly numbers?: NumbersPort;
|
|
416
|
+
readonly voice?: VoicePort;
|
|
417
|
+
readonly sms?: SmsPort;
|
|
418
|
+
readonly whatsapp?: WhatsAppPort;
|
|
419
|
+
readonly usage?: UsagePort;
|
|
420
|
+
}
|
|
421
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ProviderFactory, TelephonyOptions } from './telephony.options.js';
|
|
2
|
+
import type { TelephonyAdapter } from './telephony.port.js';
|
|
3
|
+
/** Los proveedores que trae la librería. Un proveedor propio se suma con `options.factories`. */
|
|
4
|
+
export declare const BUILT_IN_PROVIDERS: Record<string, ProviderFactory>;
|
|
5
|
+
/**
|
|
6
|
+
* Catálogo de proveedores: nombre → fábrica → adaptador. El adaptador del proceso se construye una sola vez; los de
|
|
7
|
+
* tenant los guarda la fachada en su caché acotada. Agregar un proveedor = `registerProvider` (o `options.factories`).
|
|
8
|
+
*/
|
|
9
|
+
export declare class TelephonyRegistry {
|
|
10
|
+
private readonly options;
|
|
11
|
+
private readonly factories;
|
|
12
|
+
private readonly shared;
|
|
13
|
+
constructor(options?: TelephonyOptions);
|
|
14
|
+
registerProvider(name: string, factory: ProviderFactory): void;
|
|
15
|
+
has(name: string): boolean;
|
|
16
|
+
/** La configuración de un proveedor del proceso: la propia de las opciones, o `providers[nombre]`. */
|
|
17
|
+
private configOf;
|
|
18
|
+
/** Adaptador compartido del proceso. Falla en voz alta (al arrancar) si falta su configuración. */
|
|
19
|
+
get(name: string): TelephonyAdapter;
|
|
20
|
+
/** Adaptador con configuración propia (un tenant): no se comparte ni se guarda aquí. */
|
|
21
|
+
build(name: string, config: unknown, context?: {
|
|
22
|
+
tenantId?: string;
|
|
23
|
+
}): TelephonyAdapter;
|
|
24
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Type } from '@nestjs/common';
|
|
2
|
+
export interface CreateTelephonyWebhookControllerOptions {
|
|
3
|
+
/**
|
|
4
|
+
* La URL pública base **exacta** (`https://api.miapp.com`), sin barra final. La firma de Twilio cubre la URL completa
|
|
5
|
+
* a la que llamó el proveedor, así que se arma con esto y NUNCA con la cabecera `Host`/`X-Forwarded-*` (falsificable).
|
|
6
|
+
*/
|
|
7
|
+
publicBaseUrl: string;
|
|
8
|
+
/** Prefijo de ruta. Por omisión `telephony/webhooks`; quedan `POST :provider` y `POST :provider/:tenantId`. */
|
|
9
|
+
path?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Controlador de webhooks listo para montar: recibe a cualquier proveedor en `POST <path>/:provider` (y con tenant en
|
|
13
|
+
* `<path>/:provider/:tenantId`), usa {@link TelephonyWebhooks} y devuelve lo que el proveedor espera.
|
|
14
|
+
*
|
|
15
|
+
* Para proveedores que firman el cuerpo (Meta) crea la app con `NestFactory.create(AppModule, { rawBody: true })`.
|
|
16
|
+
* Los rechazos devuelven cuerpo vacío: nada que ayude a quien prueba firmas.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* @Module({ controllers: [createTelephonyWebhookController({ publicBaseUrl: 'https://api.miapp.com' })] })
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function createTelephonyWebhookController(options: CreateTelephonyWebhookControllerOptions): Type<unknown>;
|