zapind 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,1132 @@
1
+ interface Logger {
2
+ debug(message: string, meta?: Record<string, unknown>): void;
3
+ info(message: string, meta?: Record<string, unknown>): void;
4
+ warn(message: string, meta?: Record<string, unknown>): void;
5
+ error(message: string, meta?: Record<string, unknown>): void;
6
+ }
7
+ declare class RedactingLogger implements Logger {
8
+ private readonly sink;
9
+ private readonly debugEnabled;
10
+ constructor(options?: {
11
+ sink?: Logger;
12
+ debug?: boolean;
13
+ });
14
+ private sanitize;
15
+ debug(message: string, meta?: Record<string, unknown>): void;
16
+ info(message: string, meta?: Record<string, unknown>): void;
17
+ warn(message: string, meta?: Record<string, unknown>): void;
18
+ error(message: string, meta?: Record<string, unknown>): void;
19
+ }
20
+ declare const noopLogger: Logger;
21
+ interface RetryOptions {
22
+ readonly maxAttempts: number;
23
+ readonly baseDelayMs: number;
24
+ readonly maxDelayMs: number;
25
+ }
26
+ interface RateLimiterOptions {
27
+ readonly maxRequestsPerSecond: number;
28
+ readonly burst?: number;
29
+ }
30
+ declare class RateLimiter {
31
+ private readonly ratePerMs;
32
+ private readonly capacity;
33
+ private tokens;
34
+ private lastRefillAt;
35
+ private queue;
36
+ constructor(options: RateLimiterOptions);
37
+ private refill;
38
+ acquire(): Promise<void>;
39
+ }
40
+ declare class PolicyExecutor {
41
+ private readonly defaultTimeoutMs;
42
+ private readonly retryOptions;
43
+ private readonly rateLimiter;
44
+ private readonly logger;
45
+ constructor(defaultTimeoutMs: number, retryOptions: RetryOptions, rateLimiter: RateLimiter | null, logger: Logger);
46
+ execute<T>(fn: () => Promise<T>, options: {
47
+ operation: string;
48
+ timeoutMs?: number;
49
+ idempotent?: boolean;
50
+ }): Promise<T>;
51
+ }
52
+
53
+ declare enum ThreadType {
54
+ User = 0,
55
+ Group = 1
56
+ }
57
+ declare enum ClientStatus {
58
+ Idle = "idle",
59
+ Starting = "starting",
60
+ QRPending = "qr_pending",
61
+ Scanned = "scanned",
62
+ Connected = "connected",
63
+ Error = "error"
64
+ }
65
+ declare enum Gender {
66
+ Male = "male",
67
+ Female = "female",
68
+ Unknown = "unknown"
69
+ }
70
+ declare enum GroupType {
71
+ Group = "group",
72
+ Community = "community"
73
+ }
74
+ declare enum CloseReason {
75
+ ManualClosure = 1000,
76
+ AbnormalClosure = 1006,
77
+ DuplicateConnection = 3000,
78
+ KickConnection = 3003
79
+ }
80
+ declare enum TextStyle {
81
+ Bold = "b",
82
+ Italic = "i",
83
+ Underline = "u",
84
+ StrikeThrough = "s",
85
+ Red = "c_db342e",
86
+ Orange = "c_f27806",
87
+ Yellow = "c_f7b503",
88
+ Green = "c_15a85f",
89
+ Small = "f_13",
90
+ Big = "f_18",
91
+ UnorderedList = "lst_1",
92
+ OrderedList = "lst_2",
93
+ Indent = "ind_$"
94
+ }
95
+ declare enum Urgency {
96
+ Default = 0,
97
+ Important = 1,
98
+ Urgent = 2
99
+ }
100
+ declare enum Reaction {
101
+ Heart = "/-heart",
102
+ Like = "/-strong",
103
+ Haha = ":>",
104
+ Wow = ":o",
105
+ Cry = ":-((",
106
+ Angry = ":-h",
107
+ None = ""
108
+ }
109
+
110
+ interface SerializedCookie {
111
+ key?: string;
112
+ name?: string;
113
+ value: string;
114
+ domain?: string;
115
+ path?: string;
116
+ expires?: string | number | null;
117
+ expirationDate?: number;
118
+ httpOnly?: boolean;
119
+ secure?: boolean;
120
+ hostOnly?: boolean;
121
+ sameSite?: string;
122
+ [key: string]: unknown;
123
+ }
124
+ interface SessionCredentials {
125
+ readonly cookie: readonly SerializedCookie[];
126
+ readonly imei: string;
127
+ readonly userAgent: string;
128
+ readonly language?: string;
129
+ }
130
+ interface SessionInfo {
131
+ readonly accountId: string;
132
+ readonly displayName: string;
133
+ readonly avatarUrl: string;
134
+ readonly status: ClientStatus;
135
+ readonly authenticatedAt: Date;
136
+ }
137
+ interface StoredSessionRecord {
138
+ readonly version: 1;
139
+ readonly savedAt: number;
140
+ readonly credentials: SessionCredentials;
141
+ readonly account?: {
142
+ readonly accountId: string;
143
+ readonly displayName: string;
144
+ readonly avatarUrl: string;
145
+ };
146
+ }
147
+ interface QRCodeData {
148
+ readonly imageBase64: string;
149
+ readonly imageDataUrl: string;
150
+ readonly code?: string;
151
+ }
152
+ interface QRScannedData {
153
+ readonly displayName: string;
154
+ readonly avatarUrl: string;
155
+ }
156
+ interface LoginOptions {
157
+ readonly credentials?: SessionCredentials;
158
+ readonly onQRCode?: (qr: QRCodeData) => void | Promise<void>;
159
+ readonly onScanned?: (info: QRScannedData) => void | Promise<void>;
160
+ readonly onExpired?: () => void | Promise<void>;
161
+ readonly onDeclined?: () => void | Promise<void>;
162
+ readonly timeoutMs?: number;
163
+ readonly userAgent?: string;
164
+ readonly language?: string;
165
+ /** If true, skips restoring saved session and starts a fresh QR login. */
166
+ readonly forceQR?: boolean;
167
+ }
168
+ interface LogoutOptions {
169
+ readonly clearSession?: boolean;
170
+ }
171
+
172
+ type MediaInput = string | {
173
+ readonly data: Buffer;
174
+ readonly filename: `${string}.${string}`;
175
+ readonly totalSize?: number;
176
+ readonly width?: number;
177
+ readonly height?: number;
178
+ };
179
+ interface UploadedMedia {
180
+ readonly id: string;
181
+ readonly kind: 'image' | 'video' | 'file';
182
+ readonly url: string;
183
+ readonly hdUrl?: string;
184
+ readonly thumbnailUrl?: string;
185
+ readonly fileName?: string;
186
+ readonly totalSize: number;
187
+ readonly width?: number;
188
+ readonly height?: number;
189
+ readonly checksum?: string;
190
+ }
191
+ interface ImageMetadata {
192
+ readonly width: number;
193
+ readonly height: number;
194
+ readonly size: number;
195
+ }
196
+ type ImageMetadataGetter = (filePath: string) => Promise<ImageMetadata | null>;
197
+ type AttachmentKind = 'image' | 'video' | 'file' | 'audio' | 'link' | 'sticker' | 'other';
198
+ interface Attachment {
199
+ readonly kind: AttachmentKind;
200
+ readonly url?: string;
201
+ readonly thumbnailUrl?: string;
202
+ readonly title?: string;
203
+ readonly description?: string;
204
+ }
205
+ interface Mention {
206
+ readonly userId: string;
207
+ readonly pos: number;
208
+ readonly len: number;
209
+ }
210
+ interface MessageStyle {
211
+ readonly start: number;
212
+ readonly len: number;
213
+ readonly style: TextStyle;
214
+ readonly indentSize?: number;
215
+ }
216
+ interface MessageQuote {
217
+ readonly ownerId: string;
218
+ readonly clientMsgId: string;
219
+ readonly globalMsgId: string;
220
+ readonly text: string;
221
+ readonly timestamp: Date;
222
+ }
223
+ interface SendMessagePayload {
224
+ readonly text?: string;
225
+ readonly attachment?: MediaInput;
226
+ readonly attachments?: readonly MediaInput[];
227
+ readonly replyTo?: Message;
228
+ readonly mentions?: readonly Mention[];
229
+ readonly styles?: readonly MessageStyle[];
230
+ readonly urgency?: Urgency;
231
+ readonly ttlMs?: number;
232
+ readonly link?: {
233
+ readonly url: string;
234
+ readonly title?: string;
235
+ };
236
+ readonly sticker?: {
237
+ readonly id: number;
238
+ readonly cateId: number;
239
+ readonly type: number;
240
+ };
241
+ readonly voice?: {
242
+ readonly voiceUrl: string;
243
+ readonly ttlMs?: number;
244
+ };
245
+ readonly video?: {
246
+ readonly msg?: string;
247
+ readonly videoUrl: string;
248
+ readonly thumbnailUrl: string;
249
+ readonly duration?: number;
250
+ readonly width?: number;
251
+ readonly height?: number;
252
+ readonly ttlMs?: number;
253
+ };
254
+ /** Optional explicit override; normally auto-resolved by Zapind. */
255
+ readonly threadType?: ThreadType;
256
+ }
257
+ type SendMessageContent = string | SendMessagePayload;
258
+ interface SendMessageReceipt {
259
+ readonly messageId: string | null;
260
+ readonly attachmentMessageIds: readonly string[];
261
+ }
262
+ interface MessagePage {
263
+ readonly items: readonly Message[];
264
+ readonly hasMore: boolean;
265
+ readonly nextCursor: string | null;
266
+ }
267
+ interface MessageSenderRef {
268
+ readonly id: string;
269
+ readonly name?: string;
270
+ }
271
+ interface GroupSummary {
272
+ readonly id: string;
273
+ readonly version: string;
274
+ }
275
+ interface GroupSettings {
276
+ readonly blockName: boolean;
277
+ readonly signAdminMsg: boolean;
278
+ readonly addMemberOnly: boolean;
279
+ readonly setTopicOnly: boolean;
280
+ readonly enableMsgHistory: boolean;
281
+ readonly joinApprovalRequired: boolean;
282
+ readonly lockCreatePost: boolean;
283
+ readonly lockCreatePoll: boolean;
284
+ readonly lockSendMsg: boolean;
285
+ readonly lockViewMember: boolean;
286
+ }
287
+ interface GroupMember {
288
+ readonly id: string;
289
+ readonly displayName: string;
290
+ readonly zaloName: string;
291
+ readonly avatarUrl: string;
292
+ readonly globalId?: string;
293
+ readonly accountStatus: number;
294
+ }
295
+ interface OnlineStatus {
296
+ readonly userId: string;
297
+ readonly status: string;
298
+ }
299
+ interface LastOnlineInfo {
300
+ readonly userId: string;
301
+ readonly lastOnlineAt: Date | null;
302
+ readonly showOnlineStatus: boolean;
303
+ }
304
+ interface AccountSettings {
305
+ readonly showOnlineStatus: boolean;
306
+ readonly displaySeenStatus: boolean;
307
+ readonly addFriendViaPhone: boolean;
308
+ readonly addFriendViaContact: boolean;
309
+ readonly addFriendViaGroup: boolean;
310
+ readonly addFriendViaQR: boolean;
311
+ readonly acceptStrangerCall: boolean;
312
+ readonly twoFactorEnabled: boolean;
313
+ }
314
+ interface PinnedConversations {
315
+ readonly conversationIds: readonly string[];
316
+ readonly version: number;
317
+ }
318
+ interface UnreadMark {
319
+ readonly threadId: string;
320
+ readonly threadType: ThreadType;
321
+ readonly clientMsgId: string;
322
+ readonly senderId: string;
323
+ readonly timestamp: Date;
324
+ }
325
+ interface UnreadMarks {
326
+ readonly groups: readonly UnreadMark[];
327
+ readonly users: readonly UnreadMark[];
328
+ }
329
+ /**
330
+ * Internal action bridge injected into contextual domain models.
331
+ */
332
+ interface ModelActions {
333
+ sendMessage(targetId: string, content: SendMessageContent, threadType: ThreadType): Promise<SendMessageReceipt>;
334
+ replyMessage(message: Message, content: SendMessageContent): Promise<SendMessageReceipt>;
335
+ reactMessage(message: Message, reaction: Reaction | string): Promise<void>;
336
+ undoMessage(message: Message): Promise<void>;
337
+ deleteMessage(message: Message, onlyMe?: boolean): Promise<void>;
338
+ markSeen(messages: readonly Message[]): Promise<void>;
339
+ getGroupMessages(groupId: string, count?: number): Promise<MessagePage>;
340
+ sendTyping(threadId: string, threadType: ThreadType): Promise<void>;
341
+ pinConversation(threadId: string, pinned: boolean, threadType: ThreadType): Promise<void>;
342
+ muteConversation(threadId: string, durationSeconds: number, threadType: ThreadType): Promise<void>;
343
+ sendFriendRequest(userId: string, message: string): Promise<void>;
344
+ blockUser(userId: string): Promise<void>;
345
+ unblockUser(userId: string): Promise<void>;
346
+ setFriendAlias(userId: string, alias: string): Promise<void>;
347
+ removeFriend(userId: string): Promise<void>;
348
+ addGroupMembers(groupId: string, userIds: readonly string[]): Promise<void>;
349
+ removeGroupMembers(groupId: string, userIds: readonly string[]): Promise<void>;
350
+ renameGroup(groupId: string, name: string): Promise<void>;
351
+ leaveGroup(groupId: string): Promise<void>;
352
+ }
353
+ interface UserData {
354
+ readonly id: string;
355
+ readonly username?: string;
356
+ readonly displayName: string;
357
+ readonly zaloName: string;
358
+ readonly avatarUrl: string;
359
+ readonly coverUrl?: string;
360
+ readonly gender: Gender;
361
+ readonly birthday?: string;
362
+ readonly statusMessage?: string;
363
+ readonly phoneNumber?: string;
364
+ readonly isFriend: boolean;
365
+ readonly isBlocked: boolean;
366
+ readonly lastActiveAt?: Date;
367
+ }
368
+ /**
369
+ * Contextual User model with direct messaging and relationship actions.
370
+ */
371
+ declare class User implements UserData {
372
+ protected readonly actions: ModelActions;
373
+ readonly threadType = ThreadType.User;
374
+ readonly id: string;
375
+ readonly username?: string;
376
+ readonly displayName: string;
377
+ readonly zaloName: string;
378
+ readonly avatarUrl: string;
379
+ readonly coverUrl?: string;
380
+ readonly gender: Gender;
381
+ readonly birthday?: string;
382
+ readonly statusMessage?: string;
383
+ readonly phoneNumber?: string;
384
+ readonly isFriend: boolean;
385
+ readonly isBlocked: boolean;
386
+ readonly lastActiveAt?: Date;
387
+ constructor(data: UserData, actions: ModelActions);
388
+ /** Send a direct message to this user without passing threadType. */
389
+ send(content: SendMessageContent): Promise<SendMessageReceipt>;
390
+ sendFriendRequest(message?: string): Promise<void>;
391
+ block(): Promise<void>;
392
+ unblock(): Promise<void>;
393
+ }
394
+ interface ProfileData extends UserData {
395
+ readonly globalId?: string;
396
+ readonly isBusiness: boolean;
397
+ readonly createdAt?: Date;
398
+ }
399
+ declare class Profile extends User {
400
+ readonly globalId?: string;
401
+ readonly isBusiness: boolean;
402
+ readonly createdAt?: Date;
403
+ constructor(data: ProfileData, actions: ModelActions);
404
+ }
405
+ interface ContactData extends UserData {
406
+ readonly alias?: string;
407
+ }
408
+ declare class Contact extends User {
409
+ readonly alias?: string;
410
+ constructor(data: ContactData, actions: ModelActions);
411
+ setAlias(alias: string): Promise<void>;
412
+ remove(): Promise<void>;
413
+ }
414
+ interface GroupData {
415
+ readonly id: string;
416
+ readonly name: string;
417
+ readonly description: string;
418
+ readonly type: GroupType;
419
+ readonly creatorId: string;
420
+ readonly avatarUrl: string;
421
+ readonly fullAvatarUrl?: string;
422
+ readonly memberCount: number;
423
+ readonly maxMembers: number;
424
+ readonly memberIds: readonly string[];
425
+ readonly adminIds: readonly string[];
426
+ readonly isE2EE: boolean;
427
+ readonly createdAt?: Date;
428
+ readonly settings?: GroupSettings;
429
+ }
430
+ /**
431
+ * Contextual Group model with direct messaging and group management actions.
432
+ */
433
+ declare class Group implements GroupData {
434
+ private readonly actions;
435
+ readonly threadType = ThreadType.Group;
436
+ readonly id: string;
437
+ readonly name: string;
438
+ readonly description: string;
439
+ readonly type: GroupType;
440
+ readonly creatorId: string;
441
+ readonly avatarUrl: string;
442
+ readonly fullAvatarUrl?: string;
443
+ readonly memberCount: number;
444
+ readonly maxMembers: number;
445
+ readonly memberIds: readonly string[];
446
+ readonly adminIds: readonly string[];
447
+ readonly isE2EE: boolean;
448
+ readonly createdAt?: Date;
449
+ readonly settings?: GroupSettings;
450
+ constructor(data: GroupData, actions: ModelActions);
451
+ /** Send a message to this group without passing threadType. */
452
+ send(content: SendMessageContent): Promise<SendMessageReceipt>;
453
+ getMessages(count?: number): Promise<MessagePage>;
454
+ addMembers(userIds: readonly string[]): Promise<void>;
455
+ removeMembers(userIds: readonly string[]): Promise<void>;
456
+ rename(name: string): Promise<void>;
457
+ leave(): Promise<void>;
458
+ }
459
+ /**
460
+ * Contextual Conversation handle representing either a DM or Group thread.
461
+ */
462
+ declare class Conversation {
463
+ private readonly actions;
464
+ readonly id: string;
465
+ readonly threadType: ThreadType;
466
+ constructor(id: string, threadType: ThreadType, actions: ModelActions);
467
+ get isGroup(): boolean;
468
+ send(content: SendMessageContent): Promise<SendMessageReceipt>;
469
+ getMessages(count?: number): Promise<MessagePage>;
470
+ sendTyping(): Promise<void>;
471
+ pin(pinned?: boolean): Promise<void>;
472
+ mute(durationSeconds: number): Promise<void>;
473
+ }
474
+ interface MessageData {
475
+ readonly id: string;
476
+ readonly clientMsgId: string;
477
+ readonly threadId: string;
478
+ readonly threadType: ThreadType;
479
+ readonly sender: MessageSenderRef;
480
+ readonly recipientId: string;
481
+ readonly isSelf: boolean;
482
+ readonly msgType: string;
483
+ readonly text: string;
484
+ readonly attachments: readonly Attachment[];
485
+ readonly mentions: readonly Mention[];
486
+ readonly replyTo?: MessageQuote;
487
+ readonly timestamp: Date;
488
+ readonly ttlMs: number;
489
+ readonly st: number;
490
+ readonly at: number;
491
+ readonly cmd: number;
492
+ }
493
+ /**
494
+ * Normalized contextual Message model.
495
+ */
496
+ declare class Message implements MessageData {
497
+ private readonly actions;
498
+ readonly id: string;
499
+ readonly clientMsgId: string;
500
+ readonly threadId: string;
501
+ readonly threadType: ThreadType;
502
+ readonly sender: MessageSenderRef;
503
+ readonly recipientId: string;
504
+ readonly isSelf: boolean;
505
+ readonly msgType: string;
506
+ readonly text: string;
507
+ readonly attachments: readonly Attachment[];
508
+ readonly mentions: readonly Mention[];
509
+ readonly replyTo?: MessageQuote;
510
+ readonly timestamp: Date;
511
+ readonly ttlMs: number;
512
+ readonly st: number;
513
+ readonly at: number;
514
+ readonly cmd: number;
515
+ readonly conversation: Conversation;
516
+ constructor(data: MessageData, actions: ModelActions);
517
+ get isGroup(): boolean;
518
+ /** Reply directly to this message (automatically sets quote and threadType). */
519
+ reply(content: SendMessageContent): Promise<SendMessageReceipt>;
520
+ /** React to this message without passing threadId or threadType. */
521
+ react(reaction: Reaction | string): Promise<void>;
522
+ undo(): Promise<void>;
523
+ delete(onlyMe?: boolean): Promise<void>;
524
+ markSeen(): Promise<void>;
525
+ }
526
+ type ThreadTarget = string | User | Contact | Group | Conversation | Message;
527
+
528
+ type ZapindErrorCode = 'ZAPIND_ERROR' | 'AUTHENTICATION_ERROR' | 'SESSION_ERROR' | 'NETWORK_ERROR' | 'RATE_LIMIT_ERROR' | 'VALIDATION_ERROR' | 'PERMISSION_ERROR' | 'NOT_FOUND_ERROR' | 'API_ERROR';
529
+ interface ZapindErrorOptions {
530
+ readonly code?: ZapindErrorCode;
531
+ readonly retryable?: boolean;
532
+ readonly rawCode?: number | null;
533
+ readonly cause?: unknown;
534
+ }
535
+ /**
536
+ * Base error class for all errors thrown by Zapind.
537
+ */
538
+ declare class ZapindError extends Error {
539
+ readonly code: ZapindErrorCode;
540
+ readonly retryable: boolean;
541
+ readonly rawCode: number | null;
542
+ readonly cause?: unknown;
543
+ constructor(message: string, options?: ZapindErrorOptions);
544
+ }
545
+ declare class AuthenticationError extends ZapindError {
546
+ constructor(message?: string, cause?: unknown, rawCode?: number | null);
547
+ }
548
+ declare class SessionError extends ZapindError {
549
+ constructor(message?: string, cause?: unknown, rawCode?: number | null);
550
+ }
551
+ declare class NetworkError extends ZapindError {
552
+ constructor(message?: string, cause?: unknown);
553
+ }
554
+ declare class RateLimitError extends ZapindError {
555
+ readonly retryAfterMs: number | null;
556
+ constructor(message?: string, retryAfterMs?: number | null, cause?: unknown);
557
+ }
558
+ declare class ValidationError extends ZapindError {
559
+ constructor(message: string, cause?: unknown);
560
+ }
561
+ declare class PermissionError extends ZapindError {
562
+ constructor(message?: string, cause?: unknown, rawCode?: number | null);
563
+ }
564
+ declare class NotFoundError extends ZapindError {
565
+ constructor(message?: string, cause?: unknown, rawCode?: number | null);
566
+ }
567
+ declare class APIError extends ZapindError {
568
+ constructor(message: string, rawCode?: number | null, cause?: unknown, retryable?: boolean);
569
+ }
570
+
571
+ interface ConnectionEvent {
572
+ readonly connected: boolean;
573
+ readonly code?: CloseReason | number;
574
+ readonly reason?: string;
575
+ }
576
+ interface ReactionEvent {
577
+ readonly threadId: string;
578
+ readonly threadType: ThreadType;
579
+ readonly senderId: string;
580
+ readonly icon: string;
581
+ readonly targetMessageIds: readonly string[];
582
+ readonly isSelf: boolean;
583
+ readonly timestamp: Date;
584
+ }
585
+ interface TypingEvent {
586
+ readonly threadId: string;
587
+ readonly threadType: ThreadType;
588
+ readonly userId: string;
589
+ readonly isSelf: boolean;
590
+ }
591
+ interface SeenEvent {
592
+ readonly threadId: string;
593
+ readonly threadType: ThreadType;
594
+ readonly messageIds: readonly string[];
595
+ readonly seenBy: readonly string[];
596
+ }
597
+ interface UndoEvent {
598
+ readonly threadId: string;
599
+ readonly threadType: ThreadType;
600
+ readonly senderId: string;
601
+ readonly messageId: string;
602
+ readonly clientMsgId: string;
603
+ readonly isSelf: boolean;
604
+ }
605
+ interface GroupUpdateEvent {
606
+ readonly groupId: string;
607
+ readonly type: string;
608
+ readonly actorId?: string;
609
+ readonly targetIds: readonly string[];
610
+ readonly data: Record<string, unknown>;
611
+ }
612
+ interface UserUpdateEvent {
613
+ readonly userId: string;
614
+ readonly type: string;
615
+ readonly data: Record<string, unknown>;
616
+ }
617
+ interface AuthRequiredEvent {
618
+ readonly reason: 'no_session' | 'session_expired';
619
+ readonly error?: ZapindError;
620
+ }
621
+ interface ZapindEventMap {
622
+ message: Message;
623
+ reaction: ReactionEvent;
624
+ 'group.update': GroupUpdateEvent;
625
+ 'user.update': UserUpdateEvent;
626
+ typing: TypingEvent;
627
+ seen: SeenEvent;
628
+ undo: UndoEvent;
629
+ 'auth.required': AuthRequiredEvent;
630
+ connected: ConnectionEvent;
631
+ disconnected: ConnectionEvent;
632
+ error: ZapindError;
633
+ }
634
+ type ZapindEventName = keyof ZapindEventMap;
635
+ type ZapindEventHandler<K extends ZapindEventName> = (payload: ZapindEventMap[K]) => void | Promise<void>;
636
+ type UnsubscribeFn = () => void;
637
+
638
+ /**
639
+ * Bounded LRU-like TTL cache to avoid redundant network requests and prevent unbounded memory growth.
640
+ */
641
+ declare class TTLCache<K, V> {
642
+ private readonly store;
643
+ private readonly maxEntries;
644
+ private readonly defaultTtlMs;
645
+ constructor(options?: {
646
+ maxEntries?: number;
647
+ defaultTtlMs?: number;
648
+ });
649
+ get(key: K): V | undefined;
650
+ set(key: K, value: V, ttlMs?: number): void;
651
+ has(key: K): boolean;
652
+ delete(key: K): boolean;
653
+ clear(): void;
654
+ get size(): number;
655
+ }
656
+ /**
657
+ * Deduplicates concurrent identical async calls so parallel callers share one network request.
658
+ */
659
+ declare class InFlightDeduplicator {
660
+ private readonly pending;
661
+ run<T>(key: string, fn: () => Promise<T>): Promise<T>;
662
+ clear(): void;
663
+ }
664
+
665
+ interface ThreadTargetLike {
666
+ readonly id: string;
667
+ readonly threadType?: ThreadType;
668
+ }
669
+ /**
670
+ * Automatically resolves ThreadType (User vs Group) without blind guessing:
671
+ * 1. Explicit override if provided
672
+ * 2. Contextual model's own threadType (User / Group / Conversation / Message)
673
+ * 3. Cached set of known Group IDs populated lazily from getAllGroups() & runtime events
674
+ */
675
+ declare class ThreadTypeRegistry {
676
+ private readonly groupIds;
677
+ private readonly userIds;
678
+ private groupsLoadedAt;
679
+ private readonly groupsTtlMs;
680
+ private loadingGroups;
681
+ constructor(groupsTtlMs?: number);
682
+ registerGroup(groupId: string): void;
683
+ registerGroups(ids: Iterable<string>): void;
684
+ registerUser(userId: string): void;
685
+ extractId(target: string | ThreadTargetLike): string;
686
+ resolve(target: string | ThreadTargetLike, explicitType: ThreadType | undefined, fetchAllGroupIds?: () => Promise<string[]>): Promise<{
687
+ threadId: string;
688
+ threadType: ThreadType;
689
+ }>;
690
+ clear(): void;
691
+ }
692
+
693
+ interface RawUserLike {
694
+ userId?: string;
695
+ uid?: string;
696
+ username?: string;
697
+ displayName?: string;
698
+ display_name?: string;
699
+ zaloName?: string;
700
+ zalo_name?: string;
701
+ avatar?: string;
702
+ cover?: string;
703
+ gender?: number;
704
+ sdob?: string;
705
+ status?: string;
706
+ phoneNumber?: string;
707
+ isFr?: number;
708
+ isBlocked?: number | boolean;
709
+ lastActionTime?: number;
710
+ globalId?: string;
711
+ bizPkg?: {
712
+ pkgId?: number;
713
+ } | null;
714
+ createdTs?: number;
715
+ }
716
+ interface RawGroupInfoLike {
717
+ groupId?: string;
718
+ name?: string;
719
+ desc?: string;
720
+ type?: number;
721
+ creatorId?: string;
722
+ avt?: string;
723
+ fullAvt?: string;
724
+ memberIds?: string[];
725
+ adminIds?: string[];
726
+ totalMember?: number;
727
+ maxMember?: number;
728
+ e2ee?: number;
729
+ createdTime?: number;
730
+ setting?: {
731
+ blockName?: number;
732
+ signAdminMsg?: number;
733
+ addMemberOnly?: number;
734
+ setTopicOnly?: number;
735
+ enableMsgHistory?: number;
736
+ joinAppr?: number;
737
+ lockCreatePost?: number;
738
+ lockCreatePoll?: number;
739
+ lockSendMsg?: number;
740
+ lockViewMember?: number;
741
+ };
742
+ }
743
+ interface RawGroupMemberLike {
744
+ id?: string;
745
+ displayName?: string;
746
+ zaloName?: string;
747
+ avatar?: string;
748
+ globalId?: string;
749
+ accountStatus?: number;
750
+ }
751
+ interface RawMessageEnvelope {
752
+ type?: number;
753
+ threadId?: string;
754
+ isSelf?: boolean;
755
+ data?: {
756
+ msgId?: string | number;
757
+ cliMsgId?: string | number;
758
+ msgType?: string;
759
+ uidFrom?: string | number;
760
+ idTo?: string | number;
761
+ dName?: string;
762
+ ts?: string | number;
763
+ content?: unknown;
764
+ ttl?: number;
765
+ st?: number;
766
+ at?: number;
767
+ cmd?: number;
768
+ mentions?: Array<{
769
+ uid?: string;
770
+ pos?: number;
771
+ len?: number;
772
+ }>;
773
+ quote?: {
774
+ ownerId?: string | number;
775
+ cliMsgId?: string | number;
776
+ globalMsgId?: string | number;
777
+ ts?: string | number;
778
+ msg?: string;
779
+ };
780
+ };
781
+ }
782
+ interface RawUploadedMediaLike {
783
+ fileType?: string;
784
+ photoId?: string;
785
+ fileId?: string;
786
+ normalUrl?: string;
787
+ hdUrl?: string;
788
+ thumbUrl?: string;
789
+ fileUrl?: string;
790
+ fileName?: string;
791
+ totalSize?: number;
792
+ width?: number;
793
+ height?: number;
794
+ checksum?: string;
795
+ }
796
+ interface RawOnlineEntry {
797
+ userId?: string;
798
+ status?: string;
799
+ }
800
+ interface RawLastOnlineResponse {
801
+ settings?: {
802
+ show_online_status?: boolean;
803
+ };
804
+ lastOnline?: number;
805
+ }
806
+ interface RawUserSetting {
807
+ show_online_status?: boolean;
808
+ display_seen_status?: number;
809
+ add_friend_via_phone?: number;
810
+ add_friend_via_contact?: number;
811
+ add_friend_via_group?: number;
812
+ add_friend_via_qr?: number;
813
+ accept_stranger_call?: number;
814
+ setting_2FA_status?: number;
815
+ }
816
+
817
+ interface TransportQRCallbacks {
818
+ onQRCode?: (qr: QRCodeData) => void;
819
+ onScanned?: (info: QRScannedData) => void;
820
+ onExpired?: () => void;
821
+ onDeclined?: () => void;
822
+ onCredentials?: (creds: SessionCredentials) => void;
823
+ }
824
+ interface TransportListenerHandlers {
825
+ onMessage: (raw: RawMessageEnvelope) => void;
826
+ onReaction: (evt: ReactionEvent) => void;
827
+ onGroupUpdate: (evt: GroupUpdateEvent) => void;
828
+ onUserUpdate: (evt: UserUpdateEvent) => void;
829
+ onTyping: (evt: TypingEvent) => void;
830
+ onSeen: (evt: SeenEvent) => void;
831
+ onUndo: (evt: UndoEvent) => void;
832
+ onConnected: (evt: ConnectionEvent) => void;
833
+ onDisconnected: (evt: ConnectionEvent) => void;
834
+ onError: (err: unknown) => void;
835
+ }
836
+ interface TransportAdapter {
837
+ loginWithCredentials(credentials: SessionCredentials): Promise<void>;
838
+ loginWithQR(options: {
839
+ userAgent: string;
840
+ language: string;
841
+ signal?: AbortSignal;
842
+ }, callbacks: TransportQRCallbacks): Promise<SessionCredentials>;
843
+ disconnect(): Promise<void>;
844
+ isConnected(): boolean;
845
+ getOwnId(): string;
846
+ getRawApi(): unknown;
847
+ fetchAccountInfo(): Promise<RawUserLike | null>;
848
+ updateProfile(patch: {
849
+ name: string;
850
+ dob: `${number}-${number}-${number}`;
851
+ gender: 0 | 1;
852
+ }): Promise<void>;
853
+ updateBio(bio: string): Promise<void>;
854
+ keepAlive(): Promise<{
855
+ configVersion: number;
856
+ }>;
857
+ getUserInfo(userIds: string | string[]): Promise<Record<string, RawUserLike>>;
858
+ findUserByPhone(phone: string): Promise<RawUserLike | null>;
859
+ findUserByUsername(username: string): Promise<RawUserLike | null>;
860
+ getLastOnline(userId: string): Promise<RawLastOnlineResponse>;
861
+ getAllFriends(count?: number, page?: number): Promise<RawUserLike[]>;
862
+ sendFriendRequest(userId: string, message: string): Promise<void>;
863
+ acceptFriendRequest(userId: string): Promise<void>;
864
+ rejectFriendRequest(userId: string): Promise<void>;
865
+ removeFriend(userId: string): Promise<void>;
866
+ blockUser(userId: string): Promise<void>;
867
+ unblockUser(userId: string): Promise<void>;
868
+ setFriendAlias(userId: string, alias: string): Promise<void>;
869
+ getOnlineFriends(): Promise<RawOnlineEntry[]>;
870
+ getAllGroups(): Promise<Record<string, string>>;
871
+ getGroupInfo(groupIds: string | string[]): Promise<Record<string, RawGroupInfoLike>>;
872
+ getGroupMembersInfo(memberIds: string | string[]): Promise<Record<string, RawGroupMemberLike>>;
873
+ createGroup(options: {
874
+ name?: string;
875
+ members: string[];
876
+ }): Promise<{
877
+ groupId: string;
878
+ }>;
879
+ addGroupMembers(groupId: string, userIds: string[]): Promise<void>;
880
+ removeGroupMembers(groupId: string, userIds: string[]): Promise<void>;
881
+ renameGroup(groupId: string, name: string): Promise<void>;
882
+ leaveGroup(groupId: string): Promise<void>;
883
+ getPinnedConversations(): Promise<PinnedConversations>;
884
+ getUnreadMarks(): Promise<UnreadMarks>;
885
+ setPinnedConversations(ids: string[], pinned: boolean, threadType: ThreadType): Promise<void>;
886
+ setMute(threadId: string, durationSeconds: number, threadType: ThreadType): Promise<void>;
887
+ sendTyping(threadId: string, threadType: ThreadType): Promise<void>;
888
+ sendMessage(threadId: string, payload: SendMessagePayload, threadType: ThreadType): Promise<SendMessageReceipt>;
889
+ getGroupChatHistory(groupId: string, count?: number): Promise<{
890
+ messages: RawMessageEnvelope[];
891
+ hasMore: boolean;
892
+ nextCursor: string | null;
893
+ }>;
894
+ undoMessage(message: Message): Promise<void>;
895
+ deleteMessage(message: Message, onlyMe: boolean): Promise<void>;
896
+ addReaction(message: Message, reaction: Reaction | string): Promise<void>;
897
+ markSeen(messages: readonly Message[], threadType: ThreadType): Promise<void>;
898
+ uploadAttachment(sources: readonly MediaInput[], threadId: string, threadType: ThreadType): Promise<RawUploadedMediaLike[]>;
899
+ getAccountSettings(): Promise<RawUserSetting>;
900
+ updateLanguage(lang: 'VI' | 'EN'): Promise<void>;
901
+ startListening(handlers: TransportListenerHandlers, options?: {
902
+ retryOnClose?: boolean;
903
+ }): void;
904
+ stopListening(): void;
905
+ }
906
+
907
+ interface ServiceDeps {
908
+ transport: TransportAdapter;
909
+ executor: PolicyExecutor;
910
+ registry: ThreadTypeRegistry;
911
+ actions: ModelActions;
912
+ userCache: TTLCache<string, User>;
913
+ groupCache: TTLCache<string, Group>;
914
+ dedup: InFlightDeduplicator;
915
+ }
916
+ declare class AccountService {
917
+ private readonly deps;
918
+ constructor(deps: ServiceDeps);
919
+ getOwnId(): string;
920
+ getMe(): Promise<Profile>;
921
+ updateProfile(patch: {
922
+ name: string;
923
+ dob: `${number}-${number}-${number}`;
924
+ gender: 'male' | 'female';
925
+ }): Promise<void>;
926
+ updateBio(bio: string): Promise<void>;
927
+ keepAlive(): Promise<{
928
+ configVersion: number;
929
+ }>;
930
+ }
931
+ declare class UsersService {
932
+ private readonly deps;
933
+ constructor(deps: ServiceDeps);
934
+ get(userId: string, options?: {
935
+ skipCache?: boolean;
936
+ }): Promise<User | null>;
937
+ getMany(userIds: readonly string[]): Promise<Record<string, User>>;
938
+ findByPhone(phoneNumber: string): Promise<User | null>;
939
+ findByUsername(username: string): Promise<User | null>;
940
+ getLastOnline(userId: string): Promise<LastOnlineInfo>;
941
+ }
942
+ declare class ContactsService {
943
+ private readonly deps;
944
+ constructor(deps: ServiceDeps);
945
+ list(options?: {
946
+ count?: number;
947
+ page?: number;
948
+ }): Promise<Contact[]>;
949
+ sendRequest(userId: string, message?: string): Promise<void>;
950
+ acceptRequest(userId: string): Promise<void>;
951
+ rejectRequest(userId: string): Promise<void>;
952
+ remove(userId: string): Promise<void>;
953
+ block(userId: string): Promise<void>;
954
+ unblock(userId: string): Promise<void>;
955
+ setAlias(userId: string, alias: string): Promise<void>;
956
+ getOnline(): Promise<OnlineStatus[]>;
957
+ }
958
+ declare class GroupsService {
959
+ private readonly deps;
960
+ constructor(deps: ServiceDeps);
961
+ list(): Promise<GroupSummary[]>;
962
+ get(groupId: string, options?: {
963
+ skipCache?: boolean;
964
+ }): Promise<Group>;
965
+ getMany(groupIds: readonly string[]): Promise<Record<string, Group>>;
966
+ create(options: {
967
+ name?: string;
968
+ members: readonly string[];
969
+ }): Promise<Group>;
970
+ getMembers(memberIds: readonly string[]): Promise<GroupMember[]>;
971
+ addMembers(groupId: string, userIds: readonly string[]): Promise<void>;
972
+ removeMembers(groupId: string, userIds: readonly string[]): Promise<void>;
973
+ rename(groupId: string, name: string): Promise<void>;
974
+ leave(groupId: string): Promise<void>;
975
+ }
976
+ declare class ConversationsService {
977
+ private readonly deps;
978
+ constructor(deps: ServiceDeps);
979
+ private fetchGroupIds;
980
+ get(id: string, threadType?: ThreadType): Promise<Conversation>;
981
+ getMessages(conversationId: string, count?: number): Promise<MessagePage>;
982
+ getPinned(): Promise<PinnedConversations>;
983
+ getUnread(): Promise<UnreadMarks>;
984
+ pin(target: ThreadTarget, pinned?: boolean): Promise<void>;
985
+ mute(target: ThreadTarget, durationSeconds: number): Promise<void>;
986
+ sendTyping(target: ThreadTarget): Promise<void>;
987
+ }
988
+ declare class MessagesService {
989
+ private readonly deps;
990
+ constructor(deps: ServiceDeps);
991
+ private fetchGroupIds;
992
+ /**
993
+ * Unified message sender. Automatically resolves threadType from target or Group ID cache.
994
+ */
995
+ send(target: ThreadTarget, content: SendMessageContent, explicitType?: ThreadType): Promise<SendMessageReceipt>;
996
+ reply(message: Message, content: SendMessageContent): Promise<SendMessageReceipt>;
997
+ react(message: Message, reaction: Reaction | string): Promise<void>;
998
+ undo(message: Message): Promise<void>;
999
+ delete(message: Message, onlyMe?: boolean): Promise<void>;
1000
+ markSeen(messages: readonly Message[]): Promise<void>;
1001
+ }
1002
+ declare class MediaService {
1003
+ private readonly deps;
1004
+ private readonly messages;
1005
+ constructor(deps: ServiceDeps, messages: MessagesService);
1006
+ private fetchGroupIds;
1007
+ upload(target: ThreadTarget, sources: MediaInput | readonly MediaInput[], explicitType?: ThreadType): Promise<UploadedMedia[]>;
1008
+ send(target: ThreadTarget, media: MediaInput | readonly MediaInput[], caption?: string): Promise<SendMessageReceipt>;
1009
+ }
1010
+ declare class SettingsService {
1011
+ private readonly deps;
1012
+ constructor(deps: ServiceDeps);
1013
+ get(): Promise<AccountSettings>;
1014
+ updateLanguage(lang: 'VI' | 'EN'): Promise<void>;
1015
+ }
1016
+
1017
+ interface SessionStore {
1018
+ load(): Promise<StoredSessionRecord | null>;
1019
+ save(record: StoredSessionRecord): Promise<void>;
1020
+ clear(): Promise<void>;
1021
+ }
1022
+ declare class MemorySessionStore implements SessionStore {
1023
+ private record;
1024
+ load(): Promise<StoredSessionRecord | null>;
1025
+ save(record: StoredSessionRecord): Promise<void>;
1026
+ clear(): Promise<void>;
1027
+ }
1028
+ declare class FileSessionStore implements SessionStore {
1029
+ readonly filePath: string;
1030
+ constructor(filePath: string);
1031
+ load(): Promise<StoredSessionRecord | null>;
1032
+ save(record: StoredSessionRecord): Promise<void>;
1033
+ clear(): Promise<void>;
1034
+ }
1035
+ declare class EncryptedFileSessionStore implements SessionStore {
1036
+ readonly filePath: string;
1037
+ private readonly secret;
1038
+ constructor(filePath: string, secret: string | Buffer);
1039
+ private deriveKey;
1040
+ load(): Promise<StoredSessionRecord | null>;
1041
+ save(record: StoredSessionRecord): Promise<void>;
1042
+ clear(): Promise<void>;
1043
+ }
1044
+
1045
+ declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0";
1046
+ interface ZapindOptions {
1047
+ /** Path to a session JSON file (e.g. "./session.json") or a custom SessionStore instance. */
1048
+ readonly session?: string | SessionStore;
1049
+ readonly timeoutMs?: number;
1050
+ readonly qrTimeoutMs?: number;
1051
+ readonly retry?: Partial<RetryOptions>;
1052
+ readonly rateLimit?: RateLimiterOptions | false;
1053
+ readonly cacheTtlMs?: number;
1054
+ readonly maxCacheEntries?: number;
1055
+ readonly logger?: Logger;
1056
+ readonly debug?: boolean;
1057
+ readonly selfListen?: boolean;
1058
+ readonly userAgent?: string;
1059
+ readonly language?: string;
1060
+ readonly imageMetadataGetter?: ImageMetadataGetter;
1061
+ /** Optional custom transport (e.g., MockTransport for testing). */
1062
+ readonly transport?: TransportAdapter;
1063
+ }
1064
+ interface EventsNamespace {
1065
+ on: <K extends ZapindEventName>(event: K, handler: ZapindEventHandler<K>) => UnsubscribeFn;
1066
+ once: <K extends ZapindEventName>(event: K, handler: ZapindEventHandler<K>) => UnsubscribeFn;
1067
+ off: <K extends ZapindEventName>(event: K, handler: ZapindEventHandler<K>) => void;
1068
+ start: (options?: {
1069
+ retryOnClose?: boolean;
1070
+ }) => void;
1071
+ stop: () => void;
1072
+ }
1073
+ /**
1074
+ * Zapind — Developer-friendly, contextual, type-safe Zalo SDK.
1075
+ */
1076
+ declare class Zapind {
1077
+ readonly account: AccountService;
1078
+ readonly users: UsersService;
1079
+ readonly contacts: ContactsService;
1080
+ readonly groups: GroupsService;
1081
+ readonly conversations: ConversationsService;
1082
+ readonly messages: MessagesService;
1083
+ readonly media: MediaService;
1084
+ readonly settings: SettingsService;
1085
+ readonly events: EventsNamespace;
1086
+ private readonly transport;
1087
+ private readonly sessionStore;
1088
+ private readonly executor;
1089
+ private readonly logger;
1090
+ private readonly eventBus;
1091
+ private readonly registry;
1092
+ private readonly userCache;
1093
+ private readonly groupCache;
1094
+ private readonly dedup;
1095
+ private readonly selfListen;
1096
+ private readonly defaultUserAgent;
1097
+ private readonly defaultLanguage;
1098
+ private readonly defaultQrTimeoutMs;
1099
+ private readonly modelActions;
1100
+ private status;
1101
+ private sessionInfo;
1102
+ private listening;
1103
+ constructor(options?: ZapindOptions);
1104
+ /**
1105
+ * Low-level escape hatch to access the underlying `zca-js` API directly.
1106
+ * Intended for advanced 10% use cases not wrapped by high-level domain services.
1107
+ */
1108
+ get raw(): unknown;
1109
+ getStatus(): ClientStatus;
1110
+ getSession(): SessionInfo | null;
1111
+ isAuthenticated(): boolean;
1112
+ /**
1113
+ * Smart authentication entry point:
1114
+ * 1. If `options.credentials` is provided -> authenticates with those credentials.
1115
+ * 2. Otherwise tries to restore and validate a saved session from `SessionStore`.
1116
+ * 3. If missing or expired -> emits `auth.required` and performs QR login.
1117
+ */
1118
+ login(options?: LoginOptions): Promise<SessionInfo>;
1119
+ private buildAndPersistSession;
1120
+ private authenticateWithCredentials;
1121
+ private loginWithQR;
1122
+ logout(options?: LogoutOptions): Promise<void>;
1123
+ on<K extends ZapindEventName>(event: K, handler: ZapindEventHandler<K>): UnsubscribeFn;
1124
+ once<K extends ZapindEventName>(event: K, handler: ZapindEventHandler<K>): UnsubscribeFn;
1125
+ off<K extends ZapindEventName>(event: K, handler: ZapindEventHandler<K>): void;
1126
+ startListening(options?: {
1127
+ retryOnClose?: boolean;
1128
+ }): void;
1129
+ stopListening(): void;
1130
+ }
1131
+
1132
+ export { APIError, type AccountSettings, type Attachment, type AttachmentKind, type AuthRequiredEvent, AuthenticationError, ClientStatus, CloseReason, type ConnectionEvent, Contact, Conversation, DEFAULT_USER_AGENT, EncryptedFileSessionStore, type EventsNamespace, FileSessionStore, Gender, Group, type GroupMember, type GroupSettings, type GroupSummary, GroupType, type GroupUpdateEvent, type ImageMetadata, type ImageMetadataGetter, type LastOnlineInfo, type Logger, type LoginOptions, type LogoutOptions, type MediaInput, MemorySessionStore, type Mention, Message, type MessagePage, type MessageQuote, type MessageSenderRef, type MessageStyle, NetworkError, NotFoundError, type OnlineStatus, PermissionError, type PinnedConversations, Profile, type QRCodeData, type QRScannedData, RateLimitError, type RateLimiterOptions, Reaction, type ReactionEvent, RedactingLogger, type RetryOptions, type SeenEvent, type SendMessageContent, type SendMessagePayload, type SendMessageReceipt, type SerializedCookie, type SessionCredentials, SessionError, type SessionInfo, type SessionStore, type StoredSessionRecord, TextStyle, type ThreadTarget, ThreadType, type TransportAdapter, type TypingEvent, type UndoEvent, type UnreadMark, type UnreadMarks, type UnsubscribeFn, type UploadedMedia, Urgency, User, type UserUpdateEvent, ValidationError, Zapind, ZapindError, type ZapindErrorCode, type ZapindErrorOptions, type ZapindEventHandler, type ZapindEventMap, type ZapindEventName, type ZapindOptions, noopLogger };