@arcaelas/whatsapp 4.5.0 → 6.0.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.
Files changed (106) hide show
  1. package/README.md +282 -239
  2. package/build/cjs/decorators.js +0 -1
  3. package/build/cjs/index.d.ts +6 -4
  4. package/build/cjs/index.js +22 -3
  5. package/build/cjs/lib/bot/decorator.d.ts +2 -0
  6. package/build/cjs/lib/bot/decorator.js +6 -1
  7. package/build/cjs/lib/bot/decorators.d.ts +2 -2
  8. package/build/cjs/lib/bot/decorators.js +4 -4
  9. package/build/cjs/lib/bot/index.js +0 -1
  10. package/build/cjs/lib/chat/index.d.ts +381 -204
  11. package/build/cjs/lib/chat/index.js +243 -212
  12. package/build/cjs/lib/contact/index.d.ts +162 -179
  13. package/build/cjs/lib/contact/index.js +96 -191
  14. package/build/cjs/lib/internal.d.ts +40 -0
  15. package/build/cjs/lib/internal.js +38 -0
  16. package/build/cjs/lib/message/index.d.ts +468 -289
  17. package/build/cjs/lib/message/index.js +871 -743
  18. package/build/cjs/lib/status/index.d.ts +60 -70
  19. package/build/cjs/lib/status/index.js +106 -112
  20. package/build/cjs/lib/store/engine/index.d.ts +35 -7
  21. package/build/cjs/lib/store/engine/index.js +6 -4
  22. package/build/cjs/lib/store/engine/lib/file_system/index.d.ts +48 -8
  23. package/build/cjs/lib/store/engine/lib/file_system/index.js +117 -66
  24. package/build/cjs/lib/store/engine/lib/index.d.ts +112 -0
  25. package/build/cjs/lib/store/engine/lib/index.js +212 -0
  26. package/build/cjs/lib/store/engine/lib/redis/index.d.ts +44 -15
  27. package/build/cjs/lib/store/engine/lib/redis/index.js +75 -43
  28. package/build/cjs/lib/store/engine/lib/s3/index.d.ts +44 -1
  29. package/build/cjs/lib/store/engine/lib/s3/index.js +112 -65
  30. package/build/cjs/lib/store/engine/lib/sqlite/index.d.ts +110 -0
  31. package/build/cjs/lib/store/engine/lib/sqlite/index.js +132 -0
  32. package/build/cjs/lib/store/index.d.ts +7 -3
  33. package/build/cjs/lib/store/index.js +14 -5
  34. package/build/cjs/lib/whatsapp/index.d.ts +106 -68
  35. package/build/cjs/lib/whatsapp/index.js +393 -167
  36. package/build/esm/decorators.js +0 -1
  37. package/build/esm/index.d.ts +6 -4
  38. package/build/esm/index.js +5 -3
  39. package/build/esm/lib/bot/decorator.d.ts +2 -0
  40. package/build/esm/lib/bot/decorator.js +6 -1
  41. package/build/esm/lib/bot/decorators.d.ts +2 -2
  42. package/build/esm/lib/bot/decorators.js +4 -4
  43. package/build/esm/lib/bot/index.js +0 -1
  44. package/build/esm/lib/chat/index.d.ts +381 -204
  45. package/build/esm/lib/chat/index.js +243 -212
  46. package/build/esm/lib/contact/index.d.ts +162 -179
  47. package/build/esm/lib/contact/index.js +96 -190
  48. package/build/esm/lib/internal.d.ts +40 -0
  49. package/build/esm/lib/internal.js +34 -0
  50. package/build/esm/lib/message/index.d.ts +468 -289
  51. package/build/esm/lib/message/index.js +866 -738
  52. package/build/esm/lib/status/index.d.ts +60 -70
  53. package/build/esm/lib/status/index.js +105 -111
  54. package/build/esm/lib/store/engine/index.d.ts +35 -7
  55. package/build/esm/lib/store/engine/index.js +4 -3
  56. package/build/esm/lib/store/engine/lib/file_system/index.d.ts +48 -8
  57. package/build/esm/lib/store/engine/lib/file_system/index.js +117 -66
  58. package/build/esm/lib/store/engine/lib/index.d.ts +112 -0
  59. package/build/esm/lib/store/engine/lib/index.js +205 -0
  60. package/build/esm/lib/store/engine/lib/redis/index.d.ts +44 -15
  61. package/build/esm/lib/store/engine/lib/redis/index.js +73 -41
  62. package/build/esm/lib/store/engine/lib/s3/index.d.ts +44 -1
  63. package/build/esm/lib/store/engine/lib/s3/index.js +111 -64
  64. package/build/esm/lib/store/engine/lib/sqlite/index.d.ts +110 -0
  65. package/build/esm/lib/store/engine/lib/sqlite/index.js +128 -0
  66. package/build/esm/lib/store/index.d.ts +7 -3
  67. package/build/esm/lib/store/index.js +13 -5
  68. package/build/esm/lib/whatsapp/index.d.ts +106 -68
  69. package/build/esm/lib/whatsapp/index.js +395 -169
  70. package/package.json +25 -6
  71. package/build/cjs/decorators.js.map +0 -1
  72. package/build/cjs/index.js.map +0 -1
  73. package/build/cjs/lib/bot/decorator.js.map +0 -1
  74. package/build/cjs/lib/bot/decorators.js.map +0 -1
  75. package/build/cjs/lib/bot/index.js.map +0 -1
  76. package/build/cjs/lib/chat/index.js.map +0 -1
  77. package/build/cjs/lib/contact/index.js.map +0 -1
  78. package/build/cjs/lib/message/index.js.map +0 -1
  79. package/build/cjs/lib/status/index.js.map +0 -1
  80. package/build/cjs/lib/store/engine/index.js.map +0 -1
  81. package/build/cjs/lib/store/engine/lib/file_system/index.js.map +0 -1
  82. package/build/cjs/lib/store/engine/lib/redis/index.js.map +0 -1
  83. package/build/cjs/lib/store/engine/lib/s3/index.js.map +0 -1
  84. package/build/cjs/lib/store/index.js.map +0 -1
  85. package/build/cjs/lib/whatsapp/index.js.map +0 -1
  86. package/build/cjs/test.d.ts +0 -1
  87. package/build/cjs/test.js +0 -71
  88. package/build/cjs/test.js.map +0 -1
  89. package/build/esm/decorators.js.map +0 -1
  90. package/build/esm/index.js.map +0 -1
  91. package/build/esm/lib/bot/decorator.js.map +0 -1
  92. package/build/esm/lib/bot/decorators.js.map +0 -1
  93. package/build/esm/lib/bot/index.js.map +0 -1
  94. package/build/esm/lib/chat/index.js.map +0 -1
  95. package/build/esm/lib/contact/index.js.map +0 -1
  96. package/build/esm/lib/message/index.js.map +0 -1
  97. package/build/esm/lib/status/index.js.map +0 -1
  98. package/build/esm/lib/store/engine/index.js.map +0 -1
  99. package/build/esm/lib/store/engine/lib/file_system/index.js.map +0 -1
  100. package/build/esm/lib/store/engine/lib/redis/index.js.map +0 -1
  101. package/build/esm/lib/store/engine/lib/s3/index.js.map +0 -1
  102. package/build/esm/lib/store/index.js.map +0 -1
  103. package/build/esm/lib/whatsapp/index.js.map +0 -1
  104. package/build/esm/test.d.ts +0 -1
  105. package/build/esm/test.js +0 -66
  106. package/build/esm/test.js.map +0 -1
@@ -7,63 +7,56 @@
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.Chat = void 0;
9
9
  exports.chat = chat;
10
+ const internal_1 = require("../../lib/internal");
11
+ const message_1 = require("../../lib/message");
10
12
  const store_1 = require("../../lib/store");
11
13
  /**
12
- * Duración usada cuando `chat.mute(true)` silencia "siempre".
13
- * Duration used when `chat.mute(true)` means "mute forever".
14
- */
15
- const MUTE_FOREVER_MS = 365 * 100 * 24 * 3_600 * 1_000;
16
- /**
17
- * Clase base del chat (forma pública, solo lectura).
18
- * Base Chat class (public shape, read-only).
14
+ * Clase base del chat: recibe el raw y deriva todo con getters.
15
+ * Base Chat class: receives the raw and derives everything via getters.
19
16
  */
20
17
  class Chat {
21
- constructor(raw) {
22
- this._raw = raw;
18
+ /**
19
+ * @internal Documento crudo del chat. `id` es el identificador del engine (JID, LID o
20
+ * `@g.us`); `pinned` y `mute_end_time` son epoch ms.
21
+ * Raw chat document. `id` is the engine identifier (JID, LID or `@g.us`); `pinned` and
22
+ * `mute_end_time` are epoch ms.
23
+ */
24
+ constructor(_raw) {
25
+ this._raw = _raw;
23
26
  }
24
- /** JID del chat. / Chat JID. */
27
+ /** Teléfono del contacto, o el identificador crudo en grupos y LIDs. / Contact phone, or the raw identifier for groups and LIDs. */
25
28
  get id() {
26
- return this._raw.id;
29
+ return this._raw.id.endsWith('@s.whatsapp.net') ? this._raw.id.split('@')[0].split(':')[0] : this._raw.id;
27
30
  }
28
- /** CID (alias). / CID (alias). */
29
- get cid() {
30
- return this._raw.id;
31
+ /** Nombre del grupo o del contacto. / Group or contact name. */
32
+ get name() {
33
+ return this._raw.name ?? this.id;
31
34
  }
32
- /** Tipo: contact o group. / Type: contact or group. */
35
+ /** Tipo de conversación. / Conversation type. */
33
36
  get type() {
34
37
  return this._raw.id.endsWith('@g.us') ? 'group' : 'contact';
35
38
  }
36
- /** Nombre del chat. / Chat name. */
37
- get name() {
38
- return this._raw.name ?? this._raw.display_name ?? this._raw.id.split('@')[0];
39
- }
40
- /** Descripción del grupo. / Group description. */
41
- get content() {
42
- return this._raw.description ?? '';
39
+ /** true si el chat está archivado. / true when the chat is archived. */
40
+ get archived() {
41
+ return this._raw.archived ?? false;
43
42
  }
44
- /** Si está fijado. / Whether it's pinned. */
43
+ /** true si el chat está fijado. / true when the chat is pinned. */
45
44
  get pinned() {
46
45
  return this._raw.pinned != null;
47
46
  }
48
- /** Si está archivado. / Whether it's archived. */
49
- get archived() {
50
- return this._raw.archived ?? false;
47
+ /** Mensajes sin leer del chat. / Chat's unread messages. */
48
+ get count() {
49
+ return this._raw.unread_count ?? 0;
51
50
  }
52
- /** true si el chat está silenciado y el silencio aún no expira. / true if chat is muted and the mute has not expired. */
51
+ /** Fecha ISO UTC hasta la que el chat está silenciado, o null. / ISO UTC date until the chat stays muted, or null. */
53
52
  get muted() {
54
53
  const end = this._raw.mute_end_time;
55
- return end != null && end > Date.now();
56
- }
57
- /** Si está leído. / Whether it's read. */
58
- get read() {
59
- return !this._raw.unread_count && !this._raw.marked_as_unread;
60
- }
61
- /** Si es solo lectura. / Whether it's read-only. */
62
- get readonly() {
63
- return this._raw.read_only ?? false;
54
+ return end != null && end > Date.now() ? new Date(end).toISOString() : null;
64
55
  }
65
56
  }
66
57
  exports.Chat = Chat;
58
+ /** Máximo de chats fijados que acepta WhatsApp; el cuarto se descarta en silencio. / Max pinned chats WhatsApp accepts; the fourth is silently dropped. */
59
+ const MAX_PINNED = 3;
67
60
  /**
68
61
  * Factoría de Chat ligada al contexto WhatsApp.
69
62
  * Context-bound Chat factory.
@@ -72,243 +65,281 @@ exports.Chat = Chat;
72
65
  */
73
66
  function chat(wa) {
74
67
  /**
75
- * Obtiene la key del último mensaje para operaciones de chatModify que la requieren.
76
- * Fetches the last message key required by chatModify operations.
68
+ * Último mensaje del chat en el formato que exige `chatModify`.
69
+ * The chat's last message in the shape `chatModify` requires.
77
70
  */
78
71
  async function last_messages(cid) {
79
72
  const [raw] = await wa.engine.list(`/chat/${cid}/message`, 0, 1);
80
73
  const parsed = (0, store_1.deserialize)(raw ?? null);
81
74
  return parsed
82
- ? [
83
- {
84
- key: { remoteJid: cid, id: parsed.id, fromMe: parsed.me },
85
- messageTimestamp: Math.floor(parsed.created_at / 1000),
86
- },
87
- ]
75
+ ? [{ key: { remoteJid: cid, id: parsed.id, fromMe: parsed.me }, messageTimestamp: Math.floor(parsed.created_at / 1000) }]
88
76
  : [];
89
77
  }
90
- return class _Chat extends Chat {
91
- constructor() {
92
- super(...arguments);
93
- /** @internal Cache TTL (15s) de la promesa de participants del grupo. Evita round-trips a `groupMetadata` y deduplica llamadas concurrentes. */
94
- this._members_cache = null;
95
- }
96
- /**
97
- * Obtiene un chat por CID. Si no está persistido, lo crea a partir del contacto.
98
- * Retrieves a chat by CID. If not persisted, creates it from the contact.
99
- */
100
- static async get(cid) {
101
- let result = null;
102
- const jid = await wa._resolve_jid(cid);
103
- if (jid) {
104
- const cached = (0, store_1.deserialize)(await wa.engine.get(`/chat/${jid}`));
105
- if (cached) {
106
- result = new _Chat(cached);
107
- }
108
- else {
109
- const c = await wa.Contact.get(jid);
110
- if (c) {
111
- const raw = { id: jid, name: c.name };
112
- await wa.engine.set(`/chat/${jid}`, (0, store_1.serialize)(raw));
113
- result = new _Chat(raw);
114
- }
115
- }
78
+ /**
79
+ * Cuenta los chats fijados distintos del indicado, cortando al llegar al máximo.
80
+ * Counts pinned chats other than the given one, stopping once the max is reached.
81
+ */
82
+ async function count_pinned(exclude) {
83
+ let total = 0;
84
+ for (let offset = 0; total < MAX_PINNED; offset += 200) {
85
+ const page = await wa.engine.list('/chat', offset, 200);
86
+ if (page.length === 0) {
87
+ break;
116
88
  }
117
- return result;
118
- }
119
- /** Pagina los chats persistidos por mtime DESC. / Paginates persisted chats by mtime DESC. */
120
- static async list(offset = 0, limit = 50) {
121
- const chats = [];
122
- for (const raw of await wa.engine.list('/chat', offset, limit)) {
89
+ for (const raw of page) {
123
90
  const parsed = (0, store_1.deserialize)(raw);
124
- if (parsed) {
125
- chats.push(new _Chat(parsed));
91
+ if (parsed && parsed.id !== exclude && parsed.pinned != null) {
92
+ total++;
126
93
  }
127
94
  }
128
- return chats;
129
95
  }
130
- /** Fija/desfija un chat por CID. / Pins or unpins a chat by CID. */
131
- static async pin(cid, value) {
132
- const c = await _Chat.get(cid);
133
- return c ? c.pin(value) : false;
134
- }
135
- /** Archiva/desarchiva un chat por CID. / Archives or unarchives a chat by CID. */
136
- static async archive(cid, value) {
137
- const c = await _Chat.get(cid);
138
- return c ? c.archive(value) : false;
96
+ return total;
97
+ }
98
+ /**
99
+ * Participantes del grupo memoizados 15s, para no repetir `groupMetadata` en cada página.
100
+ * Group participants memoized for 15s, avoiding a `groupMetadata` round-trip per page.
101
+ */
102
+ const groups_cache = new Map();
103
+ function group_meta(jid) {
104
+ if (!groups_cache.has(jid)) {
105
+ const socket = (0, internal_1.internals)(wa).socket;
106
+ groups_cache.set(jid, socket ? socket.groupMetadata(jid).catch(() => ({ participants: [] })) : Promise.resolve({ participants: [] }));
107
+ setTimeout(() => groups_cache.delete(jid), 15_000);
139
108
  }
140
- /** Silencia/des-silencia un chat por CID. / Mutes or unmutes a chat by CID. */
141
- static async mute(cid, value) {
142
- const c = await _Chat.get(cid);
143
- return c ? c.mute(value) : false;
109
+ return groups_cache.get(jid);
110
+ }
111
+ /**
112
+ * Contacto desde el engine, o ficha mínima local cuando no está persistido (sin red).
113
+ * Contact from the engine, or a minimal local card when not persisted (no network).
114
+ */
115
+ async function load_contact(id) {
116
+ const cached = (0, store_1.deserialize)(await wa.engine.get(`/contact/${id}`));
117
+ return new wa.Contact(cached ?? { id });
118
+ }
119
+ return class _Chat extends Chat {
120
+ /**
121
+ * Participantes del chat: los integrantes en grupos, el contacto y yo en 1:1.
122
+ * Chat participants: members for groups, the contact and myself for 1:1.
123
+ *
124
+ * @param offset - Desplazamiento / Offset
125
+ * @param limit - Tamaño de página / Page size
126
+ * @returns Página de contactos / Contact page
127
+ */
128
+ async members(offset = 0, limit = 50) {
129
+ const ids = this.type === 'group'
130
+ ? (await group_meta(this._raw.id)).participants.map((participant) => participant.id)
131
+ : [this._raw.id, (0, internal_1.internals)(wa).socket?.user?.id].filter((id) => Boolean(id));
132
+ return Promise.all(ids.slice(offset, offset + limit).map(load_contact));
144
133
  }
145
- /** Vacía mensajes del chat (local). / Clears the chat's messages (local only). */
146
- static async clear(cid) {
147
- const c = await _Chat.get(cid);
148
- return c ? c.clear() : false;
134
+ /**
135
+ * Descripción del chat: el asunto del grupo o, en un 1:1, la bio del contacto.
136
+ * Es asíncrono porque ninguno de los dos vive en el documento del chat.
137
+ * Chat description: the group's subject or, on a 1:1, the contact's bio. It is async
138
+ * because neither of them lives in the chat document.
139
+ *
140
+ * @returns Descripción, o cadena vacía si no hay / Description, or an empty string when absent
141
+ */
142
+ async content() {
143
+ if (this.type === 'group') {
144
+ return (await group_meta(this._raw.id)).desc ?? '';
145
+ }
146
+ return (0, store_1.deserialize)(await wa.engine.get(`/contact/${this._raw.id}`))?.status ?? '';
149
147
  }
150
- /** Elimina el chat y sus mensajes. / Deletes the chat and its messages. */
151
- static async delete(cid) {
152
- const c = await _Chat.get(cid);
153
- return c ? c.delete() : false;
148
+ /**
149
+ * Mensajes del chat paginados desde el más reciente.
150
+ * Chat messages paginated from the most recent one.
151
+ *
152
+ * @param offset - Desplazamiento / Offset
153
+ * @param limit - Tamaño de página / Page size
154
+ * @returns Página de mensajes / Message page
155
+ */
156
+ async messages(offset = 0, limit = 50) {
157
+ return message_1.Message.list(wa, this._raw.id, offset, limit);
154
158
  }
155
- /** Re-hidrata metadata del chat desde el socket. / Re-hydrates chat metadata from the socket. */
156
- async refresh() {
159
+ /**
160
+ * Activa o desactiva el indicador «escribiendo…».
161
+ * Toggles the "typing…" indicator.
162
+ *
163
+ * @param value - true activa, false vuelve a pausa / true enables, false returns to paused
164
+ * @returns true si el socket estaba disponible / true when the socket was available
165
+ */
166
+ async typing(value) {
157
167
  let ok = false;
158
- if (wa._socket) {
159
- if (this.type === 'group') {
160
- try {
161
- const meta = await wa._socket.groupMetadata(this.id);
162
- this._raw.name = meta.subject;
163
- this._raw.description = meta.desc ?? null;
164
- this._raw.participants = meta.participants.map((p) => ({
165
- id: p.id,
166
- admin: p.admin ?? null,
167
- }));
168
- this._raw.created_by = meta.owner ?? null;
169
- this._raw.created_at = meta.creation ?? null;
170
- }
171
- catch {
172
- /* group metadata may fail */
173
- }
174
- }
175
- else {
176
- const c = await wa.Contact.get(this.id);
177
- if (c) {
178
- await c.refresh();
179
- this._raw.name = c.name;
180
- }
181
- }
182
- await wa.engine.set(`/chat/${this.id}`, (0, store_1.serialize)(this._raw));
168
+ const socket = (0, internal_1.internals)(wa).socket;
169
+ if (socket) {
170
+ await socket.sendPresenceUpdate(value ? 'composing' : 'paused', this._raw.id);
183
171
  ok = true;
184
172
  }
185
- return ok ? this : null;
173
+ return ok;
186
174
  }
187
- /** Fija/desfija el chat. / Pins or unpins the chat. */
188
- async pin(value) {
175
+ /**
176
+ * Activa o desactiva el indicador «grabando audio…».
177
+ * Toggles the "recording audio…" indicator.
178
+ *
179
+ * @param value - true activa, false vuelve a pausa / true enables, false returns to paused
180
+ * @returns true si el socket estaba disponible / true when the socket was available
181
+ */
182
+ async recording(value) {
189
183
  let ok = false;
190
- if (wa._socket) {
191
- await wa._socket.chatModify({ pin: value, lastMessages: await last_messages(this.id) }, this.id);
192
- this._raw.pinned = value ? Date.now() : null;
193
- await wa.engine.set(`/chat/${this.id}`, (0, store_1.serialize)(this._raw));
184
+ const socket = (0, internal_1.internals)(wa).socket;
185
+ if (socket) {
186
+ await socket.sendPresenceUpdate(value ? 'recording' : 'paused', this._raw.id);
194
187
  ok = true;
195
188
  }
196
189
  return ok;
197
190
  }
198
- /** Archiva/desarchiva el chat. / Archives or unarchives the chat. */
191
+ /**
192
+ * Archiva o desarchiva el chat en la cuenta de WhatsApp.
193
+ * Archives or unarchives the chat on the WhatsApp account.
194
+ *
195
+ * @param value - true archiva, false desarchiva / true archives, false unarchives
196
+ * @returns true si la acción se envió / true when the action was sent
197
+ */
199
198
  async archive(value) {
200
199
  let ok = false;
201
- if (wa._socket) {
202
- await wa._socket.chatModify({ archive: value, lastMessages: await last_messages(this.id) }, this.id);
200
+ const socket = (0, internal_1.internals)(wa).socket;
201
+ if (socket) {
202
+ await socket.chatModify({ archive: value, lastMessages: await last_messages(this._raw.id) }, this._raw.id);
203
203
  this._raw.archived = value;
204
- await wa.engine.set(`/chat/${this.id}`, (0, store_1.serialize)(this._raw));
204
+ await wa.engine.set(`/chat/${this._raw.id}`, (0, store_1.serialize)(this._raw));
205
205
  ok = true;
206
206
  }
207
207
  return ok;
208
208
  }
209
- /** Silencia/des-silencia el chat. / Mutes or unmutes the chat. */
210
- async mute(value) {
209
+ /**
210
+ * Fija o desfija el chat en la cuenta de WhatsApp. WhatsApp acepta hasta 3 chats
211
+ * fijados y descarta el cuarto sin avisar, así que el límite se verifica antes.
212
+ * Pins or unpins the chat on the WhatsApp account. WhatsApp accepts up to 3 pinned
213
+ * chats and silently drops the fourth, so the limit is checked beforehand.
214
+ *
215
+ * @param value - true fija, false desfija / true pins, false unpins
216
+ * @returns false si el socket está caído o ya hay 3 chats fijados / false when the socket is down or 3 chats are already pinned
217
+ */
218
+ async pin(value) {
211
219
  let ok = false;
212
- if (wa._socket) {
213
- const mute_end = value === true ? Date.now() + MUTE_FOREVER_MS : null;
214
- await wa._socket.chatModify({ mute: mute_end, lastMessages: await last_messages(this.id) }, this.id);
215
- this._raw.mute_end_time = mute_end;
216
- await wa.engine.set(`/chat/${this.id}`, (0, store_1.serialize)(this._raw));
217
- ok = true;
220
+ const socket = (0, internal_1.internals)(wa).socket;
221
+ if (socket) {
222
+ const allowed = value ? (await count_pinned(this._raw.id)) < MAX_PINNED : true;
223
+ if (allowed) {
224
+ await socket.chatModify({ pin: value }, this._raw.id);
225
+ this._raw.pinned = value ? Date.now() : null;
226
+ await wa.engine.set(`/chat/${this._raw.id}`, (0, store_1.serialize)(this._raw));
227
+ ok = true;
228
+ }
218
229
  }
219
230
  return ok;
220
231
  }
221
- /** Toggle "Escribiendo...". / Toggles the "typing..." indicator. */
222
- async typing(on) {
232
+ /**
233
+ * Silencia el chat hasta la fecha indicada. `false` o una fecha pasada lo des-silencian.
234
+ * Mutes the chat until the given date. `false` or a past date unmutes it.
235
+ *
236
+ * @param until - Fecha límite (ISO, epoch ms o Date) o false / Deadline (ISO, epoch ms or Date) or false
237
+ * @returns true si la acción se envió / true when the action was sent
238
+ */
239
+ async mute(until) {
223
240
  let ok = false;
224
- if (wa._socket) {
225
- await wa._socket.sendPresenceUpdate(on ? 'composing' : 'paused', this.id);
241
+ const socket = (0, internal_1.internals)(wa).socket;
242
+ if (socket) {
243
+ const end = until === false ? 0 : new Date(until).getTime();
244
+ const muted = end > Date.now();
245
+ await socket.chatModify({ mute: muted ? end : null }, this._raw.id);
246
+ this._raw.mute_end_time = muted ? end : null;
247
+ await wa.engine.set(`/chat/${this._raw.id}`, (0, store_1.serialize)(this._raw));
226
248
  ok = true;
227
249
  }
228
250
  return ok;
229
251
  }
230
- /** Toggle "Grabando audio...". / Toggles the "recording audio..." indicator. */
231
- async recording(on) {
252
+ /**
253
+ * Marca el chat completo como leído en la cuenta de WhatsApp.
254
+ * Marks the whole chat as read on the WhatsApp account.
255
+ *
256
+ * @returns true si la acción se envió / true when the action was sent
257
+ */
258
+ async seen() {
232
259
  let ok = false;
233
- if (wa._socket) {
234
- await wa._socket.sendPresenceUpdate(on ? 'recording' : 'paused', this.id);
260
+ const socket = (0, internal_1.internals)(wa).socket;
261
+ if (socket) {
262
+ await socket.chatModify({ markRead: true, lastMessages: await last_messages(this._raw.id) }, this._raw.id);
263
+ this._raw.unread_count = 0;
264
+ await wa.engine.set(`/chat/${this._raw.id}`, (0, store_1.serialize)(this._raw));
235
265
  ok = true;
236
266
  }
237
267
  return ok;
238
268
  }
239
- /** Vacía mensajes del chat (engine local). / Clears chat messages (local engine). */
269
+ /**
270
+ * Vacía los mensajes del chat en la cuenta de WhatsApp y en el engine, conservando el chat.
271
+ * Clears the chat messages on the WhatsApp account and in the engine, keeping the chat.
272
+ *
273
+ * @returns true siempre; la limpieza local es idempotente / always true; local cleanup is idempotent
274
+ */
240
275
  async clear() {
241
- await wa.engine.unset(`/chat/${this.id}/message`);
276
+ const socket = (0, internal_1.internals)(wa).socket;
277
+ if (socket) {
278
+ await socket
279
+ .chatModify({ clear: true, lastMessages: await last_messages(this._raw.id) }, this._raw.id)
280
+ .catch(() => null);
281
+ }
282
+ await wa.engine.unset(`/chat/${this._raw.id}/message`);
242
283
  return true;
243
284
  }
244
- /** Elimina el chat y sus mensajes (remoto + local). / Deletes the chat and its messages (remote + local). */
285
+ /**
286
+ * Elimina el chat y sus mensajes en la cuenta de WhatsApp y en el engine; en grupos
287
+ * abandona el grupo.
288
+ * Deletes the chat and its messages on the WhatsApp account and in the engine; for
289
+ * groups it leaves the group.
290
+ *
291
+ * @returns true siempre; la limpieza local es idempotente / always true; local cleanup is idempotent
292
+ */
245
293
  async delete() {
246
- if (wa._socket) {
294
+ const socket = (0, internal_1.internals)(wa).socket;
295
+ if (socket) {
247
296
  if (this.type === 'group') {
248
- try {
249
- await wa._socket.groupLeave(this.id);
250
- }
251
- catch {
252
- /* may fail */
253
- }
297
+ await socket.groupLeave(this._raw.id).catch(() => null);
254
298
  }
255
299
  else {
256
- try {
257
- await wa._socket.chatModify({ delete: true, lastMessages: [] }, this.id);
258
- }
259
- catch {
260
- /* may fail */
261
- }
300
+ await socket
301
+ .chatModify({ delete: true, lastMessages: await last_messages(this._raw.id) }, this._raw.id)
302
+ .catch(() => null);
262
303
  }
263
304
  }
264
- await this.clear();
265
- await wa.engine.unset(`/chat/${this.id}`);
305
+ await wa.engine.unset(`/chat/${this._raw.id}`);
266
306
  return true;
267
307
  }
268
308
  /**
269
- * Participantes del chat paginados (incluyéndome en grupos). Para grupos,
270
- * el `groupMetadata` se memoiza en la instancia con TTL de 15s para evitar
271
- * round-trips repetidos al socket.
272
- * Chat participants paginated (self included in groups). For groups,
273
- * `groupMetadata` is memoized on the instance with a 15s TTL to avoid
274
- * repeated socket round-trips.
309
+ * Carga un chat por teléfono, JID, LID o id de grupo: el persistido en el engine o,
310
+ * si todavía no existe, una instancia mínima lista para usar (no se persiste).
311
+ * Loads a chat by phone, JID, LID or group id: the engine-persisted one or, when it
312
+ * does not exist yet, a minimal ready-to-use instance (not persisted).
313
+ *
314
+ * @param cid - Teléfono, JID, LID o id de grupo / Phone, JID, LID or group id
315
+ * @returns Chat o null si el identificador es irresoluble / Chat or null when the identifier cannot be resolved
275
316
  */
276
- async members(offset = 0, limit = 50) {
277
- const result = [];
278
- if (this.type !== 'group') {
279
- if (offset === 0 && limit > 0) {
280
- const c = await wa.Contact.get(this.id);
281
- if (c) {
282
- result.push(c);
283
- }
284
- }
285
- }
286
- else if (wa._socket) {
287
- try {
288
- const socket = wa._socket;
289
- const participants = await (this._members_cache ??= (async () => {
290
- const meta = await socket.groupMetadata(this.id);
291
- setTimeout(() => { this._members_cache = null; }, 15_000);
292
- return meta.participants;
293
- })());
294
- const slice = participants.slice(offset, offset + limit);
295
- for (const p of slice) {
296
- const existing = await wa.Contact.get(p.id);
297
- if (existing) {
298
- result.push(existing);
299
- }
300
- }
301
- }
302
- catch {
303
- /* may fail */
304
- }
317
+ static async get(cid) {
318
+ const digits = String(cid).replace(/\D+/g, '');
319
+ const jid = String(cid).includes('@')
320
+ ? await (0, internal_1.internals)(wa).resolve_jid(String(cid))
321
+ : digits
322
+ ? `${digits}@s.whatsapp.net`
323
+ : null;
324
+ if (jid) {
325
+ const cached = (0, store_1.deserialize)(await wa.engine.get(`/chat/${jid}`));
326
+ return new _Chat(cached ?? { id: jid });
305
327
  }
306
- return result;
328
+ return null;
307
329
  }
308
- /** Mensajes del chat paginados por mtime DESC. / Chat messages paginated by mtime DESC. */
309
- async messages(offset = 0, limit = 50) {
310
- return wa.Message.list(this.id, offset, limit);
330
+ /**
331
+ * Pagina los chats persistidos, del más reciente al más antiguo.
332
+ * Paginates persisted chats, from the most recent to the oldest.
333
+ *
334
+ * @param offset - Desplazamiento / Offset
335
+ * @param limit - Tamaño de página / Page size
336
+ * @returns Página de chats / Chat page
337
+ */
338
+ static async list(offset = 0, limit = 50) {
339
+ return (await wa.engine.list('/chat', offset, limit))
340
+ .map((raw) => (0, store_1.deserialize)(raw))
341
+ .filter((parsed) => parsed !== null)
342
+ .map((parsed) => new _Chat(parsed));
311
343
  }
312
344
  };
313
345
  }
314
- //# sourceMappingURL=index.js.map