@arcaelas/whatsapp 6.2.0 → 7.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 (42) hide show
  1. package/README.md +19 -15
  2. package/build/cjs/index.d.ts +9 -5
  3. package/build/cjs/index.js +8 -7
  4. package/build/cjs/lib/bot/decorator.d.ts +2 -9
  5. package/build/cjs/lib/bot/decorator.js +0 -1
  6. package/build/cjs/lib/bot/decorators.d.ts +48 -4
  7. package/build/cjs/lib/bot/decorators.js +2 -2
  8. package/build/cjs/lib/chat/index.d.ts +132 -152
  9. package/build/cjs/lib/chat/index.js +138 -219
  10. package/build/cjs/lib/contact/index.d.ts +114 -80
  11. package/build/cjs/lib/contact/index.js +187 -94
  12. package/build/cjs/lib/message/index.d.ts +400 -321
  13. package/build/cjs/lib/message/index.js +425 -913
  14. package/build/cjs/lib/status/index.d.ts +22 -33
  15. package/build/cjs/lib/status/index.js +52 -93
  16. package/build/cjs/lib/store/index.d.ts +16 -0
  17. package/build/cjs/lib/store/index.js +29 -3
  18. package/build/cjs/lib/whatsapp/index.d.ts +44 -212
  19. package/build/cjs/lib/whatsapp/index.js +473 -1099
  20. package/build/esm/index.d.ts +9 -5
  21. package/build/esm/index.js +6 -4
  22. package/build/esm/lib/bot/decorator.d.ts +2 -9
  23. package/build/esm/lib/bot/decorator.js +1 -1
  24. package/build/esm/lib/bot/decorators.d.ts +48 -4
  25. package/build/esm/lib/bot/decorators.js +2 -2
  26. package/build/esm/lib/chat/index.d.ts +132 -152
  27. package/build/esm/lib/chat/index.js +139 -219
  28. package/build/esm/lib/contact/index.d.ts +114 -80
  29. package/build/esm/lib/contact/index.js +186 -94
  30. package/build/esm/lib/message/index.d.ts +400 -321
  31. package/build/esm/lib/message/index.js +422 -913
  32. package/build/esm/lib/status/index.d.ts +22 -33
  33. package/build/esm/lib/status/index.js +49 -93
  34. package/build/esm/lib/store/index.d.ts +16 -0
  35. package/build/esm/lib/store/index.js +25 -0
  36. package/build/esm/lib/whatsapp/index.d.ts +44 -212
  37. package/build/esm/lib/whatsapp/index.js +476 -1101
  38. package/package.json +1 -1
  39. package/build/cjs/lib/internal.d.ts +0 -40
  40. package/build/cjs/lib/internal.js +0 -38
  41. package/build/esm/lib/internal.d.ts +0 -40
  42. package/build/esm/lib/internal.js +0 -34
@@ -1,14 +1,23 @@
1
1
  /**
2
2
  * @file contact/index.ts
3
- * @description Entidad Contact — una ficha mínima derivada del raw del contacto.
4
- * Contact entity — a minimal card derived from the raw contact document.
3
+ * @description Entidad Contact — ficha derivada del raw del contacto.
4
+ * Contact entity — a card derived from the raw contact document.
5
5
  */
6
- import type { WhatsApp } from '../../lib/whatsapp';
6
+ import { type WASocket } from 'baileys';
7
+ import { Feed } from '../../lib/status';
8
+ import { type Engine } from '../../lib/store';
9
+ import type WhatsApp from '../../lib/whatsapp';
10
+ /** Sesión activa que liga la entidad. / Active session binding the entity. */
11
+ type Init = {
12
+ wa: WhatsApp;
13
+ engine: Engine;
14
+ socket: WASocket;
15
+ };
7
16
  /**
8
- * Clase base del contacto: recibe el raw de baileys y deriva todo con getters.
9
- * Base Contact class: receives the baileys raw and derives everything via getters.
17
+ * Contacto: recibe el raw de baileys y deriva todo con getters.
18
+ * Contact: receives the baileys raw and derives everything via getters.
10
19
  */
11
- export declare class Contact {
20
+ export default class Contact {
12
21
  readonly _raw: {
13
22
  id: string;
14
23
  lid?: string | null;
@@ -20,10 +29,10 @@ export declare class Contact {
20
29
  status?: string | null;
21
30
  };
22
31
  /**
23
- * @internal Documento crudo del contacto en snake_case. `id` llega en formato LID o PN
24
- * según el addressing; `phone_number` es el JID PN cuando baileys lo conoce.
25
- * Raw contact document in snake_case. `id` arrives in LID or PN format depending on
26
- * addressing; `phone_number` is the PN JID when baileys knows it.
32
+ * @internal Documento crudo en snake_case. `id` llega en LID o PN según el addressing;
33
+ * `phone_number` es el JID PN cuando baileys lo conoce.
34
+ * Raw document in snake_case. `id` arrives as LID or PN depending on addressing;
35
+ * `phone_number` is the PN JID when baileys knows it.
27
36
  */
28
37
  constructor(_raw: {
29
38
  id: string;
@@ -37,32 +46,25 @@ export declare class Contact {
37
46
  });
38
47
  /** Nombre: agenda → público → verificado → teléfono. / Name: address book → public → verified → phone. */
39
48
  get name(): string;
40
- /**
41
- * JID legado (`@s.whatsapp.net`): el reportado por baileys o generado desde el id
42
- * cuando ya viene en formato PN; null si no es determinable.
43
- * Legacy JID (`@s.whatsapp.net`): the one baileys reports or generated from the id
44
- * when it is already PN-formatted; null when not determinable.
45
- */
49
+ /** JID legado (`@s.whatsapp.net`), o null si no es determinable. / Legacy JID (`@s.whatsapp.net`), or null when undeterminable. */
46
50
  get jid(): string | null;
47
- /** LID (`@lid`) cuando es definible; null si no. / LID (`@lid`) when definable; null otherwise. */
51
+ /** LID (`@lid`), o null si no es determinable. / LID (`@lid`), or null when undeterminable. */
48
52
  get lid(): string | null;
49
- /**
50
- * Teléfono del contacto, derivado únicamente del JID PN (nunca del LID);
51
- * null cuando no hay JID determinable.
52
- * Contact phone, derived from the PN JID only (never from the LID);
53
- * null when no JID is determinable.
54
- */
53
+ /** Teléfono, derivado del JID PN y nunca del LID. / Phone, derived from the PN JID and never from the LID. */
55
54
  get phone(): string | null;
56
55
  /** URL de la foto de perfil, o null. / Profile picture URL, or null. */
57
56
  get photo(): string | null;
58
57
  }
59
58
  /**
60
- * Factoría de Contact ligada al contexto WhatsApp.
61
- * Context-bound Contact factory.
59
+ * Contacto ligado a la sesión viva: el socket y el engine llegan resueltos, así que sus
60
+ * métodos no vuelven a comprobarlos.
61
+ * Contact bound to the live session: socket and engine arrive resolved, so its methods do not
62
+ * check them again.
62
63
  *
63
- * @param wa - Instancia principal / Main WhatsApp instance
64
+ * @param init - Sesión activa: cliente, motor y socket / Active session: client, engine and socket
65
+ * @returns Clase `Contact` con acceso a la sesión / `Contact` class with session access
64
66
  */
65
- export declare function contact(wa: WhatsApp): {
67
+ export declare function contact(init: Init): {
66
68
  new (_raw: {
67
69
  id: string;
68
70
  lid?: string | null;
@@ -74,12 +76,12 @@ export declare function contact(wa: WhatsApp): {
74
76
  status?: string | null;
75
77
  }): {
76
78
  /**
77
- * Chat 1:1 del contacto: el persistido en el engine, o una instancia mínima.
78
- * The contact's 1:1 chat: the engine-persisted one, or a minimal instance.
79
+ * Chat 1:1 del contacto: el persistido, o una instancia mínima.
80
+ * The contact's 1:1 chat: the persisted one, or a minimal instance.
79
81
  *
80
82
  * @returns Instancia de Chat / Chat instance
81
83
  */
82
- chat(): Promise<InstanceType<typeof wa.Chat>>;
84
+ chat(): Promise<InstanceType<typeof init.wa.Chat>>;
83
85
  readonly _raw: {
84
86
  id: string;
85
87
  lid?: string | null;
@@ -92,42 +94,32 @@ export declare function contact(wa: WhatsApp): {
92
94
  };
93
95
  /** Nombre: agenda → público → verificado → teléfono. / Name: address book → public → verified → phone. */
94
96
  get name(): string;
95
- /**
96
- * JID legado (`@s.whatsapp.net`): el reportado por baileys o generado desde el id
97
- * cuando ya viene en formato PN; null si no es determinable.
98
- * Legacy JID (`@s.whatsapp.net`): the one baileys reports or generated from the id
99
- * when it is already PN-formatted; null when not determinable.
100
- */
97
+ /** JID legado (`@s.whatsapp.net`), o null si no es determinable. / Legacy JID (`@s.whatsapp.net`), or null when undeterminable. */
101
98
  get jid(): string | null;
102
- /** LID (`@lid`) cuando es definible; null si no. / LID (`@lid`) when definable; null otherwise. */
99
+ /** LID (`@lid`), o null si no es determinable. / LID (`@lid`), or null when undeterminable. */
103
100
  get lid(): string | null;
104
- /**
105
- * Teléfono del contacto, derivado únicamente del JID PN (nunca del LID);
106
- * null cuando no hay JID determinable.
107
- * Contact phone, derived from the PN JID only (never from the LID);
108
- * null when no JID is determinable.
109
- */
101
+ /** Teléfono, derivado del JID PN y nunca del LID. / Phone, derived from the PN JID and never from the LID. */
110
102
  get phone(): string | null;
111
103
  /** URL de la foto de perfil, o null. / Profile picture URL, or null. */
112
104
  get photo(): string | null;
113
105
  };
114
106
  /**
115
- * Carga un contacto por teléfono, JID o LID: primero el engine; si no está
116
- * persistido lo descubre por red (`onWhatsApp` + foto + bio) y lo materializa.
117
- * Loads a contact by phone, JID or LID: engine first; when not persisted it
118
- * discovers it over the network (`onWhatsApp` + photo + bio) and materializes it.
107
+ * Contacto por teléfono, JID o LID: primero el engine y, si no está persistido, se
108
+ * descubre por red con su foto y su bio, y se materializa.
109
+ * Contact by phone, JID or LID: the engine first and, when not persisted, it is
110
+ * discovered over the network with its picture and bio, and materialized.
119
111
  *
120
112
  * @param uid - Teléfono, JID o LID / Phone, JID or LID
121
- * @returns Contacto o null si no existe en WhatsApp / Contact or null when not on WhatsApp
113
+ * @returns Contacto, o null si no existe en WhatsApp / Contact, or null when not on WhatsApp
122
114
  */
123
115
  get(uid: string | number): Promise<{
124
116
  /**
125
- * Chat 1:1 del contacto: el persistido en el engine, o una instancia mínima.
126
- * The contact's 1:1 chat: the engine-persisted one, or a minimal instance.
117
+ * Chat 1:1 del contacto: el persistido, o una instancia mínima.
118
+ * The contact's 1:1 chat: the persisted one, or a minimal instance.
127
119
  *
128
120
  * @returns Instancia de Chat / Chat instance
129
121
  */
130
- chat(): Promise<InstanceType<typeof wa.Chat>>;
122
+ chat(): Promise<InstanceType<typeof init.wa.Chat>>;
131
123
  readonly _raw: {
132
124
  id: string;
133
125
  lid?: string | null;
@@ -140,21 +132,11 @@ export declare function contact(wa: WhatsApp): {
140
132
  };
141
133
  /** Nombre: agenda → público → verificado → teléfono. / Name: address book → public → verified → phone. */
142
134
  get name(): string;
143
- /**
144
- * JID legado (`@s.whatsapp.net`): el reportado por baileys o generado desde el id
145
- * cuando ya viene en formato PN; null si no es determinable.
146
- * Legacy JID (`@s.whatsapp.net`): the one baileys reports or generated from the id
147
- * when it is already PN-formatted; null when not determinable.
148
- */
135
+ /** JID legado (`@s.whatsapp.net`), o null si no es determinable. / Legacy JID (`@s.whatsapp.net`), or null when undeterminable. */
149
136
  get jid(): string | null;
150
- /** LID (`@lid`) cuando es definible; null si no. / LID (`@lid`) when definable; null otherwise. */
137
+ /** LID (`@lid`), o null si no es determinable. / LID (`@lid`), or null when undeterminable. */
151
138
  get lid(): string | null;
152
- /**
153
- * Teléfono del contacto, derivado únicamente del JID PN (nunca del LID);
154
- * null cuando no hay JID determinable.
155
- * Contact phone, derived from the PN JID only (never from the LID);
156
- * null when no JID is determinable.
157
- */
139
+ /** Teléfono, derivado del JID PN y nunca del LID. / Phone, derived from the PN JID and never from the LID. */
158
140
  get phone(): string | null;
159
141
  /** URL de la foto de perfil, o null. / Profile picture URL, or null. */
160
142
  get photo(): string | null;
@@ -169,12 +151,12 @@ export declare function contact(wa: WhatsApp): {
169
151
  */
170
152
  list(offset?: number, limit?: number): Promise<{
171
153
  /**
172
- * Chat 1:1 del contacto: el persistido en el engine, o una instancia mínima.
173
- * The contact's 1:1 chat: the engine-persisted one, or a minimal instance.
154
+ * Chat 1:1 del contacto: el persistido, o una instancia mínima.
155
+ * The contact's 1:1 chat: the persisted one, or a minimal instance.
174
156
  *
175
157
  * @returns Instancia de Chat / Chat instance
176
158
  */
177
- chat(): Promise<InstanceType<typeof wa.Chat>>;
159
+ chat(): Promise<InstanceType<typeof init.wa.Chat>>;
178
160
  readonly _raw: {
179
161
  id: string;
180
162
  lid?: string | null;
@@ -187,23 +169,75 @@ export declare function contact(wa: WhatsApp): {
187
169
  };
188
170
  /** Nombre: agenda → público → verificado → teléfono. / Name: address book → public → verified → phone. */
189
171
  get name(): string;
190
- /**
191
- * JID legado (`@s.whatsapp.net`): el reportado por baileys o generado desde el id
192
- * cuando ya viene en formato PN; null si no es determinable.
193
- * Legacy JID (`@s.whatsapp.net`): the one baileys reports or generated from the id
194
- * when it is already PN-formatted; null when not determinable.
195
- */
172
+ /** JID legado (`@s.whatsapp.net`), o null si no es determinable. / Legacy JID (`@s.whatsapp.net`), or null when undeterminable. */
196
173
  get jid(): string | null;
197
- /** LID (`@lid`) cuando es definible; null si no. / LID (`@lid`) when definable; null otherwise. */
174
+ /** LID (`@lid`), o null si no es determinable. / LID (`@lid`), or null when undeterminable. */
198
175
  get lid(): string | null;
199
- /**
200
- * Teléfono del contacto, derivado únicamente del JID PN (nunca del LID);
201
- * null cuando no hay JID determinable.
202
- * Contact phone, derived from the PN JID only (never from the LID);
203
- * null when no JID is determinable.
204
- */
176
+ /** Teléfono, derivado del JID PN y nunca del LID. / Phone, derived from the PN JID and never from the LID. */
205
177
  get phone(): string | null;
206
178
  /** URL de la foto de perfil, o null. / Profile picture URL, or null. */
207
179
  get photo(): string | null;
208
180
  }[]>;
209
181
  };
182
+ /**
183
+ * La cuenta autenticada: un contacto que además edita su propio perfil, controla su presencia
184
+ * y publica estados con audiencia.
185
+ * The authenticated account: a contact that also edits its own profile, controls its presence
186
+ * and publishes statuses with an audience.
187
+ */
188
+ export declare class Account extends Contact {
189
+ readonly _init: Init;
190
+ /** @internal Sesión dueña de la cuenta. / Session owning the account. */
191
+ constructor(_init: Init, raw: Contact['_raw']);
192
+ /**
193
+ * Cambia el nombre público de la cuenta en WhatsApp.
194
+ * Changes the account's public name on WhatsApp.
195
+ *
196
+ * @param name - Nombre nuevo / New name
197
+ */
198
+ rename(name: string): Promise<boolean>;
199
+ /**
200
+ * Actualiza la foto de perfil (Buffer o URL); `null` la elimina.
201
+ * Updates the profile picture (Buffer or URL); `null` removes it.
202
+ *
203
+ * @param content - Imagen nueva, o null / New picture, or null
204
+ * @throws ERR_PROFILE_PICTURE_LIB si falta `sharp` o `jimp` / when `sharp` or `jimp` is missing
205
+ */
206
+ picture(content: Buffer | string | null): Promise<boolean>;
207
+ /**
208
+ * Lee la bio de la cuenta, o la actualiza cuando recibe texto.
209
+ * Reads the account bio, or updates it when given text.
210
+ *
211
+ * @param text - Bio nueva; sin él se lee la actual / New bio; omitted to read the current one
212
+ */
213
+ content(): Promise<string>;
214
+ content(text: string): Promise<boolean>;
215
+ /**
216
+ * Publica la presencia de la cuenta: `true` online, `false` offline. El socket arranca
217
+ * con `markOnlineOnConnect: false`, así que la presencia se controla solo por acá.
218
+ * Publishes the account presence: `true` online, `false` offline. The socket starts with
219
+ * `markOnlineOnConnect: false`, so presence is controlled here only.
220
+ *
221
+ * @param value - true online, false offline / true online, false offline
222
+ */
223
+ online(value: boolean): Promise<boolean>;
224
+ /**
225
+ * Publica un estado en el feed. Con solo `caption` es texto; con `buffer` es imagen o
226
+ * video (el tipo se deduce del binario) y `caption` queda de pie. La audiencia acepta
227
+ * contactos, JIDs, LIDs o teléfonos: WhatsApp no reparte el estado fuera de ella.
228
+ * Publishes a status to the feed. With only `caption` it is text; with `buffer` an image
229
+ * or video (type inferred from the binary) with `caption` as its footer. The audience
230
+ * accepts contacts, JIDs, LIDs or phones: WhatsApp delivers it to nobody outside it.
231
+ *
232
+ * @param input - Contenido y audiencia / Content and audience
233
+ * @returns Publicación creada, o null si el envío no confirmó / Created post, or null when the send did not confirm
234
+ * @throws ERR_FEED_EMPTY sin `buffer` ni `caption` / when neither is given
235
+ * @throws ERR_FEED_MEDIA si el binario no es imagen ni video / when the binary is neither image nor video
236
+ */
237
+ post(input: {
238
+ caption?: string;
239
+ buffer?: Buffer;
240
+ audience: (string | number | Contact)[];
241
+ }): Promise<Feed | null>;
242
+ }
243
+ export {};
@@ -1,139 +1,113 @@
1
1
  "use strict";
2
2
  /**
3
3
  * @file contact/index.ts
4
- * @description Entidad Contact — una ficha mínima derivada del raw del contacto.
5
- * Contact entity — a minimal card derived from the raw contact document.
4
+ * @description Entidad Contact — ficha derivada del raw del contacto.
5
+ * Contact entity — a card derived from the raw contact document.
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.Contact = void 0;
8
+ exports.Account = void 0;
9
9
  exports.contact = contact;
10
10
  const baileys_1 = require("baileys");
11
- const internal_1 = require("../../lib/internal");
11
+ const status_1 = require("../../lib/status");
12
12
  const store_1 = require("../../lib/store");
13
13
  /**
14
- * Clase base del contacto: recibe el raw de baileys y deriva todo con getters.
15
- * Base Contact class: receives the baileys raw and derives everything via getters.
14
+ * Contacto: recibe el raw de baileys y deriva todo con getters.
15
+ * Contact: receives the baileys raw and derives everything via getters.
16
16
  */
17
17
  class Contact {
18
18
  /**
19
- * @internal Documento crudo del contacto en snake_case. `id` llega en formato LID o PN
20
- * según el addressing; `phone_number` es el JID PN cuando baileys lo conoce.
21
- * Raw contact document in snake_case. `id` arrives in LID or PN format depending on
22
- * addressing; `phone_number` is the PN JID when baileys knows it.
19
+ * @internal Documento crudo en snake_case. `id` llega en LID o PN según el addressing;
20
+ * `phone_number` es el JID PN cuando baileys lo conoce.
21
+ * Raw document in snake_case. `id` arrives as LID or PN depending on addressing;
22
+ * `phone_number` is the PN JID when baileys knows it.
23
23
  */
24
24
  constructor(_raw) {
25
25
  this._raw = _raw;
26
26
  }
27
27
  /** Nombre: agenda → público → verificado → teléfono. / Name: address book → public → verified → phone. */
28
28
  get name() {
29
- const { name, notify, verified_name } = this._raw;
30
- return name ?? notify ?? verified_name ?? this.phone ?? this._raw.id.split('@')[0];
29
+ return this._raw.name ?? this._raw.notify ?? this._raw.verified_name ?? this.phone ?? this._raw.id.split('@')[0];
31
30
  }
32
- /**
33
- * JID legado (`@s.whatsapp.net`): el reportado por baileys o generado desde el id
34
- * cuando ya viene en formato PN; null si no es determinable.
35
- * Legacy JID (`@s.whatsapp.net`): the one baileys reports or generated from the id
36
- * when it is already PN-formatted; null when not determinable.
37
- */
31
+ /** JID legado (`@s.whatsapp.net`), o null si no es determinable. / Legacy JID (`@s.whatsapp.net`), or null when undeterminable. */
38
32
  get jid() {
39
- if (this._raw.phone_number)
40
- return (0, baileys_1.jidNormalizedUser)(this._raw.phone_number);
41
- if (this._raw.id.endsWith('@s.whatsapp.net'))
42
- return (0, baileys_1.jidNormalizedUser)(this._raw.id);
43
- return null;
33
+ const pn = this._raw.phone_number ?? (this._raw.id.endsWith('@s.whatsapp.net') ? this._raw.id : null);
34
+ return pn ? (0, baileys_1.jidNormalizedUser)(pn) : null;
44
35
  }
45
- /** LID (`@lid`) cuando es definible; null si no. / LID (`@lid`) when definable; null otherwise. */
36
+ /** LID (`@lid`), o null si no es determinable. / LID (`@lid`), or null when undeterminable. */
46
37
  get lid() {
47
- if (this._raw.lid)
48
- return this._raw.lid;
49
- if (this._raw.id.endsWith('@lid'))
50
- return this._raw.id;
51
- return null;
38
+ return this._raw.lid ?? (this._raw.id.endsWith('@lid') ? this._raw.id : null);
52
39
  }
53
- /**
54
- * Teléfono del contacto, derivado únicamente del JID PN (nunca del LID);
55
- * null cuando no hay JID determinable.
56
- * Contact phone, derived from the PN JID only (never from the LID);
57
- * null when no JID is determinable.
58
- */
40
+ /** Teléfono, derivado del JID PN y nunca del LID. / Phone, derived from the PN JID and never from the LID. */
59
41
  get phone() {
60
42
  return this.jid?.split('@')[0] ?? null;
61
43
  }
62
44
  /** URL de la foto de perfil, o null. / Profile picture URL, or null. */
63
45
  get photo() {
64
- const url = this._raw.img_url;
65
- return url?.startsWith('http') ? url : null;
46
+ return this._raw.img_url?.startsWith('http') ? this._raw.img_url : null;
66
47
  }
67
48
  }
68
- exports.Contact = Contact;
49
+ exports.default = Contact;
69
50
  /**
70
- * Factoría de Contact ligada al contexto WhatsApp.
71
- * Context-bound Contact factory.
51
+ * Contacto ligado a la sesión viva: el socket y el engine llegan resueltos, así que sus
52
+ * métodos no vuelven a comprobarlos.
53
+ * Contact bound to the live session: socket and engine arrive resolved, so its methods do not
54
+ * check them again.
72
55
  *
73
- * @param wa - Instancia principal / Main WhatsApp instance
56
+ * @param init - Sesión activa: cliente, motor y socket / Active session: client, engine and socket
57
+ * @returns Clase `Contact` con acceso a la sesión / `Contact` class with session access
74
58
  */
75
- function contact(wa) {
76
- return class _Contact extends Contact {
59
+ function contact(init) {
60
+ class _Contact extends Contact {
77
61
  /**
78
- * Chat 1:1 del contacto: el persistido en el engine, o una instancia mínima.
79
- * The contact's 1:1 chat: the engine-persisted one, or a minimal instance.
62
+ * Chat 1:1 del contacto: el persistido, o una instancia mínima.
63
+ * The contact's 1:1 chat: the persisted one, or a minimal instance.
80
64
  *
81
65
  * @returns Instancia de Chat / Chat instance
82
66
  */
83
67
  async chat() {
84
68
  const cid = this.jid ?? this.lid ?? this._raw.id;
85
- const cached = (0, store_1.deserialize)(await wa.engine.get(`/chat/${cid}`));
86
- return new wa.Chat(cached ?? { id: cid, name: this.name });
69
+ return new init.wa.Chat((0, store_1.deserialize)(await init.engine.get(`/chat/${cid}`)) ?? { id: cid, name: this.name });
87
70
  }
88
71
  /**
89
- * Carga un contacto por teléfono, JID o LID: primero el engine; si no está
90
- * persistido lo descubre por red (`onWhatsApp` + foto + bio) y lo materializa.
91
- * Loads a contact by phone, JID or LID: engine first; when not persisted it
92
- * discovers it over the network (`onWhatsApp` + photo + bio) and materializes it.
72
+ * Contacto por teléfono, JID o LID: primero el engine y, si no está persistido, se
73
+ * descubre por red con su foto y su bio, y se materializa.
74
+ * Contact by phone, JID or LID: the engine first and, when not persisted, it is
75
+ * discovered over the network with its picture and bio, and materialized.
93
76
  *
94
77
  * @param uid - Teléfono, JID o LID / Phone, JID or LID
95
- * @returns Contacto o null si no existe en WhatsApp / Contact or null when not on WhatsApp
78
+ * @returns Contacto, o null si no existe en WhatsApp / Contact, or null when not on WhatsApp
96
79
  */
97
80
  static async get(uid) {
98
- const digits = String(uid).replace(/\D+/g, '');
99
- const jid = String(uid).includes('@')
100
- ? await (0, internal_1.internals)(wa).resolve_jid(String(uid))
101
- : digits
102
- ? `${digits}@s.whatsapp.net`
103
- : null;
104
- if (jid && !jid.endsWith('@g.us')) {
105
- const cached = (0, store_1.deserialize)(await wa.engine.get(`/contact/${jid}`));
106
- if (cached)
107
- return new _Contact(cached);
108
- const socket = (0, internal_1.internals)(wa).socket;
109
- if (socket) {
110
- const found = (await socket.onWhatsApp(jid.split('@')[0]))?.[0];
111
- if (found?.exists) {
112
- const id = (0, baileys_1.jidNormalizedUser)(found.jid);
113
- const img_url = await socket.profilePictureUrl(id, 'image').catch(() => null);
114
- const status = await socket
115
- .fetchStatus(id)
116
- .then((result) => result?.[0]?.status?.status ?? null)
117
- .catch(() => null);
118
- const raw = {
119
- id,
120
- lid: found.lid ?? null,
121
- phone_number: id,
122
- name: null,
123
- notify: null,
124
- verified_name: null,
125
- img_url: img_url ?? null,
126
- status,
127
- };
128
- await wa.engine.set(`/contact/${id}`, (0, store_1.serialize)(raw));
129
- if (found.lid) {
130
- await wa.engine.set(`/lid/${found.lid}`, (0, store_1.serialize)(id));
131
- }
132
- return new _Contact(raw);
133
- }
134
- }
81
+ const jid = await (0, store_1.jid_of)(init.engine, String(uid), init.socket);
82
+ if (!jid || jid.endsWith('@g.us')) {
83
+ return null;
135
84
  }
136
- return null;
85
+ const cached = (0, store_1.deserialize)(await init.engine.get(`/contact/${jid}`));
86
+ if (cached) {
87
+ return new this(cached);
88
+ }
89
+ const found = (await init.socket.onWhatsApp(jid.split('@')[0]))?.[0];
90
+ if (!found?.exists) {
91
+ return null;
92
+ }
93
+ const id = (0, baileys_1.jidNormalizedUser)(found.jid);
94
+ const doc = {
95
+ id,
96
+ lid: found.lid ?? null,
97
+ phone_number: id,
98
+ name: null,
99
+ notify: null,
100
+ verified_name: null,
101
+ img_url: await init.socket.profilePictureUrl(id, 'image').catch(() => null),
102
+ status: await init.socket.fetchStatus(id)
103
+ .then((result) => result?.[0]?.status?.status ?? null)
104
+ .catch(() => null),
105
+ };
106
+ await init.engine.set(`/contact/${id}`, (0, store_1.serialize)(doc));
107
+ if (found.lid) {
108
+ await init.engine.set(`/lid/${found.lid}`, (0, store_1.serialize)(id));
109
+ }
110
+ return new this(doc);
137
111
  }
138
112
  /**
139
113
  * Pagina los contactos persistidos.
@@ -144,10 +118,129 @@ function contact(wa) {
144
118
  * @returns Página de contactos / Contact page
145
119
  */
146
120
  static async list(offset = 0, limit = 50) {
147
- return (await wa.engine.list('/contact', offset, limit))
121
+ return (await init.engine.list('/contact', offset, limit))
148
122
  .map((raw) => (0, store_1.deserialize)(raw))
149
- .filter((parsed) => parsed !== null)
150
- .map((parsed) => new _Contact(parsed));
123
+ .filter((doc) => doc !== null)
124
+ .map((doc) => new this(doc));
151
125
  }
152
- };
126
+ }
127
+ return _Contact;
128
+ }
129
+ /**
130
+ * La cuenta autenticada: un contacto que además edita su propio perfil, controla su presencia
131
+ * y publica estados con audiencia.
132
+ * The authenticated account: a contact that also edits its own profile, controls its presence
133
+ * and publishes statuses with an audience.
134
+ */
135
+ class Account extends Contact {
136
+ /** @internal Sesión dueña de la cuenta. / Session owning the account. */
137
+ constructor(_init, raw) {
138
+ super(raw);
139
+ this._init = _init;
140
+ }
141
+ /**
142
+ * Cambia el nombre público de la cuenta en WhatsApp.
143
+ * Changes the account's public name on WhatsApp.
144
+ *
145
+ * @param name - Nombre nuevo / New name
146
+ */
147
+ async rename(name) {
148
+ await this._init.socket.updateProfileName(name);
149
+ this._raw.name = name;
150
+ return true;
151
+ }
152
+ /**
153
+ * Actualiza la foto de perfil (Buffer o URL); `null` la elimina.
154
+ * Updates the profile picture (Buffer or URL); `null` removes it.
155
+ *
156
+ * @param content - Imagen nueva, o null / New picture, or null
157
+ * @throws ERR_PROFILE_PICTURE_LIB si falta `sharp` o `jimp` / when `sharp` or `jimp` is missing
158
+ */
159
+ async picture(content) {
160
+ const self = (0, baileys_1.jidNormalizedUser)(this._init.socket.user?.id ?? '');
161
+ if (content === null) {
162
+ await this._init.socket.removeProfilePicture(self);
163
+ }
164
+ else {
165
+ await this._init.socket
166
+ .updateProfilePicture(self, typeof content === 'string' ? { url: content } : content)
167
+ .catch((error) => {
168
+ throw /image processing library/i.test(error.message) ? new Error('ERR_PROFILE_PICTURE_LIB') : error;
169
+ });
170
+ }
171
+ return true;
172
+ }
173
+ async content(text) {
174
+ if (text === undefined) {
175
+ const result = await this._init.socket.fetchStatus((0, baileys_1.jidNormalizedUser)(this._init.socket.user?.id ?? '')).catch(() => null);
176
+ return result?.[0]?.status?.status ?? '';
177
+ }
178
+ await this._init.socket.updateProfileStatus(text);
179
+ return true;
180
+ }
181
+ /**
182
+ * Publica la presencia de la cuenta: `true` online, `false` offline. El socket arranca
183
+ * con `markOnlineOnConnect: false`, así que la presencia se controla solo por acá.
184
+ * Publishes the account presence: `true` online, `false` offline. The socket starts with
185
+ * `markOnlineOnConnect: false`, so presence is controlled here only.
186
+ *
187
+ * @param value - true online, false offline / true online, false offline
188
+ */
189
+ async online(value) {
190
+ await this._init.socket.sendPresenceUpdate(value ? 'available' : 'unavailable');
191
+ return true;
192
+ }
193
+ /**
194
+ * Publica un estado en el feed. Con solo `caption` es texto; con `buffer` es imagen o
195
+ * video (el tipo se deduce del binario) y `caption` queda de pie. La audiencia acepta
196
+ * contactos, JIDs, LIDs o teléfonos: WhatsApp no reparte el estado fuera de ella.
197
+ * Publishes a status to the feed. With only `caption` it is text; with `buffer` an image
198
+ * or video (type inferred from the binary) with `caption` as its footer. The audience
199
+ * accepts contacts, JIDs, LIDs or phones: WhatsApp delivers it to nobody outside it.
200
+ *
201
+ * @param input - Contenido y audiencia / Content and audience
202
+ * @returns Publicación creada, o null si el envío no confirmó / Created post, or null when the send did not confirm
203
+ * @throws ERR_FEED_EMPTY sin `buffer` ni `caption` / when neither is given
204
+ * @throws ERR_FEED_MEDIA si el binario no es imagen ni video / when the binary is neither image nor video
205
+ */
206
+ async post(input) {
207
+ const { wa, engine, socket } = this._init;
208
+ const head = input.buffer?.subarray(0, 12);
209
+ const mime = !head ? null
210
+ : head.subarray(0, 3).toString('hex') === 'ffd8ff' ? 'image/jpeg'
211
+ : head.subarray(0, 8).toString('hex') === '89504e470d0a1a0a' ? 'image/png'
212
+ : head.subarray(0, 4).toString() === 'RIFF' && head.subarray(8, 12).toString() === 'WEBP' ? 'image/webp'
213
+ : head.subarray(4, 8).toString() === 'ftyp' ? 'video/mp4'
214
+ : null;
215
+ if (input.buffer && !mime)
216
+ throw new Error('ERR_FEED_MEDIA');
217
+ if (!input.buffer && !input.caption)
218
+ throw new Error('ERR_FEED_EMPTY');
219
+ const audience = (await Promise.all(input.audience.map((who) => who instanceof Contact ? (who.jid ?? who.lid) : (0, store_1.jid_of)(this._init.engine, String(who), this._init.socket)))).filter((jid) => Boolean(jid));
220
+ const type = mime?.startsWith('video/') ? 'video' : mime ? 'image' : 'text';
221
+ const sent = await socket.sendMessage('status@broadcast', (input.buffer ? { [type]: input.buffer, caption: input.caption } : { text: input.caption }), { statusJidList: audience });
222
+ if (!sent?.key?.id)
223
+ return null;
224
+ const created_at = (Number(sent.messageTimestamp) || Math.floor(Date.now() / 1_000)) * 1_000;
225
+ const doc = {
226
+ id: sent.key.id,
227
+ author_jid: (0, baileys_1.jidNormalizedUser)(socket.user?.id ?? ''),
228
+ type,
229
+ caption: input.caption ?? '',
230
+ mime: mime ?? 'text/plain',
231
+ created_at,
232
+ expires_at: created_at + status_1.TTL_MS,
233
+ viewed: true,
234
+ raw: sent,
235
+ };
236
+ await engine.set(`/status/${doc.id}`, (0, store_1.serialize)(doc), created_at);
237
+ if (input.buffer) {
238
+ await (engine.set_buffer?.(`/status/${doc.id}/content`, input.buffer)
239
+ ?? engine.set(`/status/${doc.id}/content`, (0, store_1.serialize)({ data: input.buffer.toString('base64') })));
240
+ }
241
+ const feed = new status_1.Feed(this._init, doc);
242
+ wa.emit('feed:created', feed, wa);
243
+ return feed;
244
+ }
153
245
  }
246
+ exports.Account = Account;