@gymspace/evolution 1.0.0 → 1.0.2

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 (100) hide show
  1. package/dist/index.d.mts +26 -19
  2. package/dist/index.d.ts +26 -19
  3. package/dist/index.js +173 -62
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +173 -62
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +1 -3
  8. package/src/api/errors.ts +0 -220
  9. package/src/api/routes.ts +0 -76
  10. package/src/api/service.ts +0 -141
  11. package/src/index.ts +0 -89
  12. package/src/modules/chats/index.ts +0 -253
  13. package/src/modules/chats/schemas/archive.ts +0 -15
  14. package/src/modules/chats/schemas/check.ts +0 -20
  15. package/src/modules/chats/schemas/delete-message.ts +0 -16
  16. package/src/modules/chats/schemas/fetch-profile-picture.ts +0 -13
  17. package/src/modules/chats/schemas/find-all.ts +0 -49
  18. package/src/modules/chats/schemas/find-contacts.ts +0 -17
  19. package/src/modules/chats/schemas/find-messages.ts +0 -55
  20. package/src/modules/chats/schemas/find-status-message.ts +0 -11
  21. package/src/modules/chats/schemas/get-base64-from-media-message.ts +0 -20
  22. package/src/modules/chats/schemas/index.ts +0 -33
  23. package/src/modules/chats/schemas/mark-as-read.ts +0 -20
  24. package/src/modules/chats/schemas/mark-as-unread.ts +0 -17
  25. package/src/modules/chats/schemas/presence.ts +0 -41
  26. package/src/modules/chats/schemas/update-message.ts +0 -16
  27. package/src/modules/groups/index.ts +0 -246
  28. package/src/modules/groups/schemas/accept-invite-code.ts +0 -14
  29. package/src/modules/groups/schemas/common.ts +0 -89
  30. package/src/modules/groups/schemas/create.ts +0 -15
  31. package/src/modules/groups/schemas/fetch-invite-code.ts +0 -13
  32. package/src/modules/groups/schemas/find-all.ts +0 -26
  33. package/src/modules/groups/schemas/find-by-invite-code.ts +0 -39
  34. package/src/modules/groups/schemas/find-by-jid.ts +0 -14
  35. package/src/modules/groups/schemas/find-members.ts +0 -16
  36. package/src/modules/groups/schemas/index.ts +0 -24
  37. package/src/modules/groups/schemas/leave.ts +0 -14
  38. package/src/modules/groups/schemas/revoke-invite-code.ts +0 -14
  39. package/src/modules/groups/schemas/send-group-invite.ts +0 -15
  40. package/src/modules/groups/schemas/toggle-ephemeral.ts +0 -15
  41. package/src/modules/groups/schemas/update-description.ts +0 -15
  42. package/src/modules/groups/schemas/update-members.ts +0 -18
  43. package/src/modules/groups/schemas/update-picture.ts +0 -15
  44. package/src/modules/groups/schemas/update-setting.ts +0 -16
  45. package/src/modules/groups/schemas/update-subject.ts +0 -15
  46. package/src/modules/index.ts +0 -7
  47. package/src/modules/instance/index.ts +0 -126
  48. package/src/modules/instance/schemas/connect.ts +0 -14
  49. package/src/modules/instance/schemas/connection-state.ts +0 -16
  50. package/src/modules/instance/schemas/create.ts +0 -99
  51. package/src/modules/instance/schemas/delete.ts +0 -21
  52. package/src/modules/instance/schemas/fetch-all.ts +0 -57
  53. package/src/modules/instance/schemas/index.ts +0 -8
  54. package/src/modules/instance/schemas/logout.ts +0 -22
  55. package/src/modules/instance/schemas/restart.ts +0 -13
  56. package/src/modules/instance/schemas/set-presence.ts +0 -20
  57. package/src/modules/messages/index.ts +0 -246
  58. package/src/modules/messages/schemas/audio.ts +0 -12
  59. package/src/modules/messages/schemas/base.ts +0 -11
  60. package/src/modules/messages/schemas/contact.ts +0 -70
  61. package/src/modules/messages/schemas/document.ts +0 -12
  62. package/src/modules/messages/schemas/image.ts +0 -12
  63. package/src/modules/messages/schemas/index.ts +0 -31
  64. package/src/modules/messages/schemas/list.ts +0 -36
  65. package/src/modules/messages/schemas/location.ts +0 -76
  66. package/src/modules/messages/schemas/media.ts +0 -51
  67. package/src/modules/messages/schemas/poll.ts +0 -87
  68. package/src/modules/messages/schemas/reaction.ts +0 -21
  69. package/src/modules/messages/schemas/status.ts +0 -18
  70. package/src/modules/messages/schemas/sticker.ts +0 -77
  71. package/src/modules/messages/schemas/template.ts +0 -39
  72. package/src/modules/messages/schemas/text.ts +0 -88
  73. package/src/modules/messages/schemas/video.ts +0 -12
  74. package/src/modules/messages/schemas/voice.ts +0 -94
  75. package/src/modules/profile/index.ts +0 -110
  76. package/src/modules/profile/schemas/fetch-business-profile.ts +0 -29
  77. package/src/modules/profile/schemas/fetch-privacy-settings.ts +0 -11
  78. package/src/modules/profile/schemas/fetch-profile.ts +0 -23
  79. package/src/modules/profile/schemas/index.ts +0 -8
  80. package/src/modules/profile/schemas/remove-picture.ts +0 -4
  81. package/src/modules/profile/schemas/update-name.ts +0 -11
  82. package/src/modules/profile/schemas/update-picture.ts +0 -11
  83. package/src/modules/profile/schemas/update-privacy-settings.ts +0 -18
  84. package/src/modules/profile/schemas/update-status.ts +0 -11
  85. package/src/modules/settings/index.ts +0 -28
  86. package/src/modules/settings/schemas/find.ts +0 -11
  87. package/src/modules/settings/schemas/index.ts +0 -2
  88. package/src/modules/settings/schemas/set.ts +0 -18
  89. package/src/modules/webhook/index.ts +0 -28
  90. package/src/modules/webhook/schemas/find.ts +0 -7
  91. package/src/modules/webhook/schemas/index.ts +0 -2
  92. package/src/modules/webhook/schemas/set.ts +0 -16
  93. package/src/schemas/client.ts +0 -23
  94. package/src/schemas/common.ts +0 -44
  95. package/src/types/api.ts +0 -17
  96. package/src/types/events.ts +0 -53
  97. package/src/types/messages.ts +0 -5
  98. package/src/types/tags.ts +0 -14
  99. package/src/types/webhooks.ts +0 -255
  100. package/src/utils/phone-numer-from-jid.ts +0 -9
package/src/api/errors.ts DELETED
@@ -1,220 +0,0 @@
1
- export class EvolutionApiError extends Error {
2
- public readonly statusCode?: number;
3
- public readonly details?: unknown;
4
-
5
- constructor(message: string, cause?: unknown, statusCode?: number) {
6
- const extractedMessage = extractErrorMessage(cause);
7
- const finalMessage = extractedMessage || message || "Unknown error occurred";
8
-
9
- super(finalMessage);
10
-
11
- this.name = EvolutionApiError.name;
12
- this.message = finalMessage;
13
- this.statusCode = statusCode;
14
- this.details = cause;
15
-
16
- // Maintain proper stack trace
17
- if ((Error as any).captureStackTrace) {
18
- (Error as any).captureStackTrace(this, EvolutionApiError);
19
- }
20
- }
21
-
22
- /**
23
- * Returns a user-friendly string representation of the error
24
- */
25
- toString(): string {
26
- let result = `${this.name}: ${this.message}`;
27
-
28
- if (this.statusCode) {
29
- result += ` (${this.statusCode})`;
30
- }
31
-
32
- // Add relevant details without showing [Object ...]
33
- if (this.details && typeof this.details === 'object') {
34
- const details = this.details as Record<string, any>;
35
- const relevantDetails: string[] = [];
36
-
37
- if (details.url) {
38
- relevantDetails.push(`URL: ${details.url}`);
39
- }
40
-
41
- if (details.method) {
42
- relevantDetails.push(`Method: ${details.method}`);
43
- }
44
-
45
- // Show response details if they exist and are meaningful
46
- if (details.response && typeof details.response === 'object') {
47
- const response = details.response as Record<string, any>;
48
- if (response.error && response.error !== this.message) {
49
- relevantDetails.push(`Server Error: ${response.error}`);
50
- }
51
- if (response.message && response.message !== this.message) {
52
- relevantDetails.push(`Server Message: ${response.message}`);
53
- }
54
- }
55
-
56
- if (relevantDetails.length > 0) {
57
- result += `\n ${relevantDetails.join('\n ')}`;
58
- }
59
- }
60
-
61
- return result;
62
- }
63
-
64
- /**
65
- * Returns a JSON representation suitable for logging
66
- */
67
- toJSON(): object {
68
- return {
69
- name: this.name,
70
- message: this.message,
71
- statusCode: this.statusCode,
72
- details: this.details,
73
- stack: this.stack,
74
- };
75
- }
76
- }
77
-
78
- /**
79
- * Extracts error message from various Evolution API error response formats
80
- */
81
- export function extractErrorMessage(response: unknown): string | null {
82
- if (!response) {
83
- return null;
84
- }
85
-
86
- // Handle string responses
87
- if (typeof response === "string") {
88
- return response;
89
- }
90
-
91
- // Handle object responses
92
- if (typeof response === "object" && response !== null) {
93
- const errorObj = response as Record<string, any>;
94
-
95
- // Try different common error message paths, prioritizing Evolution API format
96
- const messagePaths = [
97
- // Evolution API specific nested structure (most common)
98
- errorObj.response?.response?.message?.[0],
99
- errorObj.response?.response?.error,
100
- errorObj.response?.response?.description,
101
-
102
- // Evolution API first level nested
103
- Array.isArray(errorObj.response?.message) ? errorObj.response.message[0] : null,
104
- errorObj.response?.error,
105
- errorObj.response?.description,
106
-
107
- // Direct error message
108
- Array.isArray(errorObj.message) ? errorObj.message[0] : errorObj.message,
109
- errorObj.error,
110
- errorObj.description,
111
- errorObj.detail,
112
-
113
- // Other nested error messages
114
- errorObj.data?.error,
115
- errorObj.data?.message,
116
-
117
- // Array format messages (fallback)
118
- Array.isArray(errorObj.error) ? errorObj.error[0] : null,
119
- Array.isArray(errorObj.errors) ? errorObj.errors[0] : null,
120
- ];
121
-
122
- for (const path of messagePaths) {
123
- if (typeof path === "string" && path.trim()) {
124
- return path.trim();
125
- }
126
- // Handle nested objects in arrays
127
- if (typeof path === "object" && path !== null) {
128
- const nestedMessage = extractErrorMessage(path);
129
- if (nestedMessage) {
130
- return nestedMessage;
131
- }
132
- }
133
- }
134
-
135
- // Handle validation errors (common format)
136
- if (errorObj.validation && Array.isArray(errorObj.validation)) {
137
- const validationErrors = errorObj.validation
138
- .map((v: any) => v.message || v.error || String(v))
139
- .filter(Boolean)
140
- .join(", ");
141
- if (validationErrors) {
142
- return `Validation error: ${validationErrors}`;
143
- }
144
- }
145
-
146
- // Handle specific Evolution API error patterns
147
- if (errorObj.statusCode && errorObj.statusText) {
148
- return `${errorObj.statusCode}: ${errorObj.statusText}`;
149
- }
150
-
151
- // Last resort: try to stringify the object meaningfully
152
- if (Object.keys(errorObj).length > 0) {
153
- try {
154
- return JSON.stringify(errorObj);
155
- } catch {
156
- return "[Complex error object]";
157
- }
158
- }
159
- }
160
-
161
- return null;
162
- }
163
-
164
- /**
165
- * Legacy error message patterns for specific Evolution API errors
166
- * Kept for backward compatibility
167
- */
168
- const SpecificErrorPatterns = [
169
- {
170
- pattern: (obj: any) =>
171
- obj?.message?.some?.((m: any) => m?.exists === false && m?.jid && m?.number),
172
- message: "Provided number is not a valid WhatsApp number"
173
- },
174
- {
175
- pattern: (obj: any) =>
176
- obj?.message?.some?.((m: string) => typeof m === "string" && m.includes("Media upload failed")),
177
- message: "Media upload failed on all hosts"
178
- },
179
- {
180
- pattern: (obj: any) =>
181
- obj?.message?.some?.((m: string) => typeof m === "string" && m.includes("No session")),
182
- message: "No session found, try restarting your instance"
183
- },
184
- {
185
- pattern: (obj: any) =>
186
- obj?.message?.some?.((m: string) => typeof m === "string" && m.includes("AggregateError")),
187
- message: "Connection error occurred"
188
- },
189
- {
190
- pattern: (obj: any) =>
191
- obj?.message?.some?.((m: string) => typeof m === "string" && m.includes("AxiosError")),
192
- message: (obj: any) => obj.message[0] || "Network error occurred"
193
- },
194
- ];
195
-
196
- /**
197
- * Enhanced error message extraction with specific pattern matching
198
- */
199
- function getErrorMessage(response: unknown): string | null {
200
- // First try the general extraction
201
- const generalMessage = extractErrorMessage(response);
202
- if (generalMessage) {
203
- return generalMessage;
204
- }
205
-
206
- // Then try specific patterns
207
- if (typeof response === "object" && response !== null) {
208
- for (const { pattern, message } of SpecificErrorPatterns) {
209
- try {
210
- if (pattern(response)) {
211
- return typeof message === "string" ? message : message(response);
212
- }
213
- } catch {
214
- // Continue to next pattern if this one fails
215
- }
216
- }
217
- }
218
-
219
- return null;
220
- }
package/src/api/routes.ts DELETED
@@ -1,76 +0,0 @@
1
- export const Routes = {
2
- Message: {
3
- SendText: "message/sendText",
4
- SendMedia: "message/sendMedia",
5
- SendVoice: "message/sendWhatsAppAudio",
6
- SendSticker: "message/sendSticker",
7
- SendLocation: "message/sendLocation",
8
- SendContact: "message/sendContact",
9
- SendPoll: "message/sendPoll",
10
- SendReaction: "message/sendReaction",
11
- SendTemplate: "message/sendTemplate",
12
- SendStatus: "message/sendStatus",
13
- SendList: "message/sendList",
14
- },
15
- Chats: {
16
- Check: "chat/whatsappNumbers",
17
- FindAll: "chat/findChats",
18
- SendPresence: "chat/sendPresence",
19
- MarkAsRead: "chat/markMessageAsRead",
20
- MarkAsUnread: "chat/markChatUnread",
21
- Archive: "chat/archive",
22
- DeleteMessage: "chat/deleteMessageForEveryone",
23
- FetchProfilePicture: "chat/fetchProfilePictureUrl",
24
- FindContacts: "chat/findContacts",
25
- FindMessages: "chat/findMessages",
26
- FindStatusMessage: "chat/findStatusMessage",
27
- UpdateMessage: "chat/updateMessage",
28
- GetBase64FromMediaMessage: "chat/getBase64FromMediaMessage",
29
- },
30
- Groups: {
31
- FindAll: "group/fetchAllGroups",
32
- FindByJid: "group/findGroupInfos",
33
- FindByInviteCode: "group/inviteInfo",
34
- Create: "group/create",
35
- UpdatePicture: "group/updateGroupPicture",
36
- UpdateSubject: "group/updateGroupSubject",
37
- UpdateDescription: "group/updateGroupDescription",
38
- FetchInviteCode: "group/fetchInviteCode",
39
- AcceptInviteCode: "group/acceptInviteCode",
40
- RevokeInviteCode: "group/revokeInviteCode",
41
- SendGroupInvite: "group/sendGroupInvite",
42
- FindMembers: "group/findGroupMembers",
43
- UpdateMembers: "group/updateGroupMembers",
44
- UpdateSetting: "group/updateGroupSetting",
45
- ToggleEphemeral: "group/toggleEphemeral",
46
- Leave: "group/leaveGroup",
47
- },
48
- Profile: {
49
- FetchBusinessProfile: "chat/fetchBusinessProfile",
50
- FetchProfile: "chat/fetchProfile",
51
- UpdateName: "chat/updateProfileName",
52
- UpdateStatus: "chat/updateProfileStatus",
53
- UpdatePicture: "chat/updateProfilePicture",
54
- RemovePicture: "chat/removeProfilePicture",
55
- FetchPrivacySettings: "chat/fetchPrivacySettings",
56
- UpdatePrivacySettings: "chat/updatePrivacySettings",
57
- },
58
- Webhook: {
59
- Set: "webhook/set",
60
- Find: "webhook/find",
61
- },
62
- Settings: {
63
- Set: "settings/set",
64
- Find: "settings/find",
65
- },
66
- Instance: {
67
- Create: "instance/create",
68
- FetchAll: "instance/fetchInstances",
69
- Connect: "instance/connect",
70
- Restart: "instance/restart",
71
- ConnectionState: "instance/connectionState",
72
- Logout: "instance/logout",
73
- Delete: "instance/delete",
74
- SetPresence: "instance/setPresence",
75
- },
76
- };
@@ -1,141 +0,0 @@
1
- import type { ClientOptions } from "@/schemas/client";
2
- import type { APIRequestInit } from "@/types/api";
3
-
4
- import { EvolutionApiError, extractErrorMessage } from "./errors";
5
-
6
- export class ApiService {
7
- constructor(private options: ClientOptions) {}
8
-
9
- setInstance(instance: string) {
10
- this.options.instance = instance;
11
- }
12
-
13
- async request<T = unknown>(
14
- path: string,
15
- options: APIRequestInit = {}
16
- ): Promise<T> {
17
- const { isInstanceUrl = true } = options;
18
- let instance = this.options.instance;
19
-
20
- // Priority: options.instance > this.options.instance
21
- if (options.instance) {
22
- instance = options.instance;
23
- delete options.instance;
24
- }
25
-
26
- if (isInstanceUrl && !instance) {
27
- throw new EvolutionApiError("Instance not set", {
28
- message:
29
- "Please set the instance before making a request or pass instance in the method options.",
30
- });
31
- }
32
-
33
- const { init, params } = this.makeInit(options);
34
-
35
- const urlPath = isInstanceUrl ? `/${path}/${instance}/` : `/${path}/`;
36
- const url = new URL(urlPath, this.options.serverUrl);
37
-
38
- // Add query parameters if any
39
- if (params.toString()) {
40
- url.search = params.toString();
41
- }
42
-
43
- let response: Response;
44
- let data: any;
45
-
46
- try {
47
- response = await fetch(url, init);
48
- data = await response.json();
49
- } catch (error) {
50
- // Handle network errors or JSON parsing errors
51
- throw new EvolutionApiError("Network or parsing error", error);
52
- }
53
-
54
- if (!response.ok) {
55
- // Extract meaningful error message from the response
56
- const errorMessage =
57
- extractErrorMessage(data) ||
58
- `Request failed with status ${response.status}: ${response.statusText}`;
59
-
60
- throw new EvolutionApiError(
61
- errorMessage,
62
- {
63
- message: errorMessage,
64
- response: JSON.stringify(data),
65
- url: url.toString(),
66
- params: params.toString(),
67
- body: JSON.stringify(options.body),
68
- } as unknown as Record<string, any>,
69
- response.status
70
- );
71
- }
72
-
73
- return data;
74
- }
75
-
76
- private makeInit(options: APIRequestInit): {
77
- init: RequestInit;
78
- params: URLSearchParams;
79
- } {
80
- const init: RequestInit = {
81
- method: options.method || "GET",
82
- headers: {
83
- "Content-Type": "application/json",
84
- apikey: this.options.token, // Evolution API uses apikey header
85
- ...this.options.headers,
86
- ...options.headers,
87
- },
88
- };
89
-
90
- if (options.body) {
91
- init.body = JSON.stringify(options.body);
92
- }
93
-
94
- const params = new URLSearchParams();
95
- if (options.params) {
96
- // Convert any object to URLSearchParams
97
- Object.entries(options.params).forEach(([key, value]) => {
98
- if (value !== undefined && value !== null) {
99
- params.append(key, String(value));
100
- }
101
- });
102
- }
103
-
104
- return { init, params };
105
- }
106
-
107
- async get<T = unknown>(
108
- path: string,
109
- options: Omit<APIRequestInit, "method"> = {}
110
- ): Promise<T> {
111
- return this.request<T>(path, { ...options, method: "GET" });
112
- }
113
-
114
- async post<T = unknown>(
115
- path: string,
116
- options: Omit<APIRequestInit, "method"> = {}
117
- ): Promise<T> {
118
- return this.request<T>(path, { ...options, method: "POST" });
119
- }
120
-
121
- async put<T = unknown>(
122
- path: string,
123
- options: Omit<APIRequestInit, "method"> = {}
124
- ): Promise<T> {
125
- return this.request<T>(path, { ...options, method: "PUT" });
126
- }
127
-
128
- async patch<T = unknown>(
129
- path: string,
130
- options: Omit<APIRequestInit, "method"> = {}
131
- ): Promise<T> {
132
- return this.request<T>(path, { ...options, method: "PATCH" });
133
- }
134
-
135
- async delete<T = unknown>(
136
- path: string,
137
- options: Omit<APIRequestInit, "method"> = {}
138
- ): Promise<T> {
139
- return this.request<T>(path, { ...options, method: "DELETE" });
140
- }
141
- }
package/src/index.ts DELETED
@@ -1,89 +0,0 @@
1
- export * from "./types/webhooks";
2
-
3
- import { ApiService } from "./api/service";
4
- import {
5
- ChatsModule,
6
- GroupsModule,
7
- InstanceModule,
8
- MessagesModule,
9
- ProfileModule,
10
- SettingsModule,
11
- WebhookModule,
12
- } from "./modules";
13
- import { type ClientOptions } from "./schemas/client";
14
-
15
- export class EvolutionClient {
16
- /**
17
- * API service for directly interacting with the Evolution API (no specific typings)
18
- */
19
- public readonly api: ApiService;
20
-
21
- /**
22
- * Find and manage chats, send presences and check numbers
23
- */
24
- public readonly chats: ChatsModule;
25
- /**
26
- * Find and manage groups
27
- */
28
- public readonly groups: GroupsModule;
29
- /**
30
- * Send messages
31
- */
32
- public readonly messages: MessagesModule;
33
- /**
34
- * Create and manage instances
35
- */
36
- public readonly instances: InstanceModule;
37
- /**
38
- * Manage profile settings
39
- */
40
- public readonly profile: ProfileModule;
41
- /**
42
- * Manage webhooks
43
- */
44
- public readonly webhook: WebhookModule;
45
- /**
46
- * Manage settings
47
- */
48
- public readonly settings: SettingsModule;
49
-
50
- /**
51
- * Evolution Client - API client for interacting with the Evolution API
52
- * @param options - Client options
53
- */
54
- constructor(public options: ClientOptions) {
55
- this.api = new ApiService(options);
56
- this.chats = new ChatsModule(this.api);
57
- this.groups = new GroupsModule(this.api);
58
- this.messages = new MessagesModule(this.api);
59
- this.instances = new InstanceModule(this.api);
60
- this.profile = new ProfileModule(this.api);
61
- this.webhook = new WebhookModule(this.api);
62
- this.settings = new SettingsModule(this.api);
63
- }
64
-
65
- setInstance(instance: string) {
66
- this.options.instance = instance;
67
- this.api.setInstance(instance);
68
- }
69
- }
70
-
71
- export { EvolutionApiError } from "./api/errors";
72
- export { phoneNumberFromJid } from "./utils/phone-numer-from-jid";
73
- export { validatePhoneNumber } from "./schemas/common";
74
-
75
- export type * from "./modules/chats/schemas";
76
- export type * from "./modules/groups/schemas";
77
- export type * from "./modules/messages/schemas";
78
- export type * from "./modules/instance/schemas";
79
- export type * from "./modules/profile/schemas";
80
- export type * from "./modules/webhook/schemas";
81
- export type * from "./modules/settings/schemas";
82
- export type { ClientOptions };
83
-
84
- // API types
85
- export { APIRequestInit, MethodOptions } from "./types/api";
86
- export { MessageUpdateStatus } from "./types/messages";
87
- export { ChatId, GroupJid, Jid, MessageId } from "./types/tags";
88
- export * from "./types/webhooks";
89
- export { WebhookEvent, WebhookEventSetup } from "./types/events";