@redonvn/messaging-viber-desktop
v0.10.0
Published
Experimental Viber Desktop client with a verified Qt database bridge and REA research evidence
Keywords
Readme
@redonvn/messaging-viber-desktop
Experimental SDK cho Viber Desktop Windows x64, version 0.9.0-experimental.0.
SDK attach v?o Viber ?ang ch?y b?ng Frida v? ??c qua k?t n?i Qt SQL c?a ?ng d?ng. Viber qu?n l? ??ng nh?p, ??ng b? v? l?u phi?n. C?n Viber Desktop 29.5.0 ??ng SHA-256 trong catalog; ??y ch?a ph?i client network ??c l?p.
API ?? ch?y v?i phi?n th?c t?
connect(),close(): x?c minh executable, attach/detach.getDataSummary(): s? l??ng d? li?u ?ang ??ng b? tr?n Desktop.getConversations({ limit, cursor }): h?i tho?i, ph?n trang ChatID gi?m d?n.getContacts({ limit, cursor }): li?n h?, ph?n trang ContactID t?ng d?n.getFriends(): c?c d?ng Contact c? ABContact=1; ??y l? danh b? Desktop, ch?a ch?ng minh quan h? b?n b? hai chi?u.getConversationMembers(chatId): li?n h? t? ChatRelation.getMessages({ chatId, limit, beforeId, afterId }): event t? b?ng Events. ID/token gi? d?ng chu?i ?? tr?nh m?t ch?nh x?c s? nguy?n 64 bit. Type/direction/status gi? enum g?c ch?a suy di?n.watchMessages({ intervalMs, afterId, batchSize }): ph?t eventmessagekhi database c? EventID m?i; polling m?c ??nh m?t gi?y. Kh?ng theo d?i ch?nh s?a/x?a c?a EventID c?. Kh?ng c? b?o ??m exactly-once; l?u cursor ph?a ?ng d?ng n?u c?n kh?i ph?c.getSocketMetadata(): k?t n?i TCP/UDP thu?c PID. Ch?a gi?i m? frame m?ng.getLoginStatus(),waitForLogin(): quan s?t tr?ng th?i MainWidget/QR, c? timeout v? AbortSignal. MainWidget l? d?u hi?u phi?n Desktop ?? li?n k?t, kh?ng x?c nh?n server ?ang online.
D? li?u gi?i h?n ? nh?ng g? Viber Desktop ?? ??ng b?; kh?ng b?o ??m ??y ?? l?ch s? tr?n server. getMessages() bao g?m c?c lo?i event, kh?ng ch? tin text.
QR login
getLoginQrCode() t?m thu?c t?nh qrCodeUrl trong LoginWizard/LWQrCodeState v? t?o PNG data URL. Nh?nh n?y ?? ???c tri?n khai nh?ng ch?a x?c minh tr?n phi?n ch?a ??ng nh?p. V?i phi?n ?? li?n k?t, h?m tr? l?i ALREADY_LINKED; SDK kh?ng ??ng xu?t ho?c thay ??i t?i kho?n ?? t?o QR m?i. expiresAt l? null v? ch?a x?c ??nh th?i h?n t? giao th?c.
API g?i text/?nh/audio/file ?? ???c b? sung ? phi?n b?n 0.2.0; xem contract g?i b?n d??i. Codec m?ng, heartbeat/reconnect ho?c ??ng nh?p ??c l?p ch?a ???c kh?i ph?c. getCapabilities() c?a ViberDesktopClient tr? tr?ng th?i theo t?ng c? ch?; ViberDesktopResearchSdk l? l?p catalog c? v? b?o capability network ch?a kh?i ph?c.
Ch?y
C?n Node >=22, Windows x64, package Frida native v? Viber ?ang ch?y. Build b?ng npm run build trong package.
const { ViberDesktopClient } = require('@redonvn/messaging-viber-desktop');
const client = new ViberDesktopClient(); // truy?n pid khi c? nhi?u phi?n
try {
await client.connect();
console.log(await client.getLoginStatus());
const chats = await client.getConversations({ limit: 50 });
const friends = await client.getFriends({ limit: 50 });
if (chats.items.length) {
const messages = await client.getMessages({ chatId: chats.items[0].id });
}
client.on('message', ({ message, source }) => { /* x? l? v? l?u cursor */ });
client.on('watchError', error => { /* x? l? l?i polling */ });
const watcher = await client.watchMessages();
// Gi? client m? trong th?i gian ?ng d?ng c?n nh?n event.
await watcher.close();
} finally {
await client.close();
}N?u ? C h?t dung l??ng, ??t TEMP/TMP sang th? m?c c?n ch? tr??c khi kh?i ??ng Node v? Frida t?o file t?m. Kh?ng ??a d? li?u h?i tho?i, token ho?c QR challenge v?o log d?ng chung.
B?ng ch?ng
REA 6.8.0 + Frida ?? ??c schema Qt SQL th?c t? v? c?y QML. Smoke run ng?y 23/11/2026 tr? 22 Contact, 20 ABContact, 1 ChatInfo, 1 Events; ph?t l?i m?t event qua polling v? detach th?nh c?ng. Nh?nh QR tr? ALREADY_LINKED. ??y kh?ng ph?i ki?m th? ??ng nh?p QR m?i ho?c nh?n tin m?i qua m?ng.
Executable SHA-256: 6a8c571ee5947e07e985142619d33e2f1955c363900c3572e46411a21c837815.
resources/endpoint-catalog.json gi? 134 URL/template c? offset; kh?ng x?c nh?n method/schema. resources/native-targets.json gi? c?c tham chi?u byte ?ng vi?n; VA c?n ?i?u ch?nh theo ASLR tr??c khi nghi?n c?u runtime.
Runtime contracts and live validation
Public live-client rows are parsed with strict Zod runtime schemas; public TypeScript DTOs and interfaces are declared independently in src/dto and src/interfaces. Conversation/contact/message pages, members, summary, login probes, QR results, runtime socket snapshots and event payloads are parsed before return/emission. Invalid responses raise INVALID_BRIDGE_RESPONSE with structural issue paths only. Error codes have an exported union and ErrorCodeSchema; event names and listener arguments have a typed EventEmitter map. Unknown native enum codes are retained as safe integers, not assigned guessed semantic names.
Import ConversationSchema, ContactSchema, DesktopMessageSchema, RESPONSE_SCHEMAS or getResponseJsonSchemas() from the package. Generated JSON Schemas are in validation/response-schemas.json. ID maximum validation uses an additional runtime refinement; JSON Schema regex does not express that BigInt refinement. Frida RPC handles are transport objects, so their type assertion is not a claim about payload validity.
Run npm test for synthetic malformed-data, numeric precision and validation checks. Run npm run test:live with Viber running to check all current synced rows, cursor paging, member counts, scoped messages, empty results, event replay and detach. This live check reads data but writes only structural aggregates into validation/live-schema-report.json. It does not generate messages or change login state.
Latest live sample: 22 contacts, 20 address-book entries, 3 conversations and 3 Events. Observed raw direction codes: 0/1; eventType: 0; messageType: 1/9; status: 0/129; flags: 0; duration: 0. Timestamp strings have 13 digits. These observations do not establish enum meanings or timestamp/duration units. No controlled media sample, outgoing send or unlinked QR scan was tested. Endpoint HTTP request/response schemas and independent wire transport remain unrecovered.
Send contracts ? 0.2.0
ViberDesktopClient implements IViberMessageSender. Public API: sendMessage(dto), sendText(chatId,text), sendImage(chatId,filePath), sendAudio(chatId,filePath), sendFile(chatId,filePath), sendVideo(chatId,filePath). DTOs: SendTextDto, SendAttachmentDto, SendMessageDto. Requests and SendReceipt responses have TypeScript DTOs and separate Zod runtime validation; request JSON Schemas are exported by getRequestJsonSchemas().
Live validation in the user-selected conversation confirmed: text EventID 12/type 1, MP3 EventID 13/type 11, PNG EventID 14/type 2, TXT EventID 15/type 11. sendAudio sends an MP3 file attachment, not a recorded voice note. sendVideo is implemented as a fail-closed UNSUPPORTED_MEDIA error after controlled MP4 submission caused native process exits. Video-like extensions and detected MP4/AVI/Matroska containers are blocked before invoking Qt. The verified image route accepts PNG; audio accepts MP3. The local 100 MiB attachment ceiling is an experimental SDK limit, not a recovered Viber server limit.
Before submission the SDK selects the requested chat; existing drafts in another chat block switching. Media preview is only confirmed when its one file URL equals the requested path and active chat still matches. Text sending requires an empty input. Selection and sending use the UI thread, so the user should avoid switching chats during submission. Native errors and timeouts raise SEND_OUTCOME_UNKNOWN and are never automatically retried. Check the conversation before repeating.
SendReceipt.outcome is local-event-observed or submitted-unconfirmed. delivery always remains unknown. A local event is correlated by chat ID, EventID watermark, outbound direction and exact body/payload path; concurrent identical sends may remain ambiguous. A submitted-unconfirmed result may still be waiting for media processing or confirmation. Native return values are retained without assigning undocumented meanings. Upload completion, recipient delivery and read receipts have not been verified.
const receipt = await client.sendText(chatId, 'Hello');
const photo = await client.sendImage(chatId, 'F:/generated/test.png');
const audio = await client.sendAudio(chatId, 'F:/generated/test.mp3');
const file = await client.sendFile(chatId, 'F:/generated/test.txt');
// Inspect outcome and event; delivery is unknown.Controlled text sends had timestamp values close to wall-clock Unix milliseconds. This supports that unit for those outgoing samples only; general timestamp and media duration contracts remain raw until broader validation. MessageType 11 must not be named Audio: both MP3 and TXT produced it. Flags/status 129 retain their raw numeric meaning.
Revoke and reaction ? 0.3.0
ViberDesktopClient now implements IViberMessageActions. All IDs refer to local SQLite EventID, not network message token.
await client.setReaction(chatId, eventId, { kind: 'quick', code: 1 });
await client.setReaction(chatId, eventId, { kind: 'quick', code: 3 });
const reactions = await client.getMessageReactions(chatId, eventId);
await client.removeReaction(chatId, eventId);
await client.revokeMessage(chatId, eventId);ReactionInputSchema supports quick codes 1?6 and raw hex emoji codes, e.g. {kind:'emoji-code',code:'1f44d'}. Quick codes 1 and 3 have been exercised against Viber. Emoji code conversion was inspected, but sending arbitrary emoji codes has not been validated. No guessed emoji names are assigned to quick codes. Code 0 is the internal empty reaction and is handled by removeReaction().
MessageActionReceipt records before/after local state, action, observedAt and outcome: local-state-changed, already-in-state, or submitted-unconfirmed. remoteOutcome remains unknown. Removing an absent own reaction and revoking an already recalled message are no-ops. No automatic retries are performed after ambiguous native errors.
revokeMessage invokes Viber's deleteMessageForAll, not a SQL DELETE. Only an existing outgoing message in the selected chat is eligible. The desktop may enforce additional age/permission restrictions or show confirmation UI. A timed-out observation is submitted-unconfirmed and does not prove a server-side recall. The tested outgoing text became messageType 72 and Body null locally. This code is specific to the tested build and is used to detect the already-recalled case.
Own reaction state is looked up in Reactions using the current default account's contact identity from config.db and Contact.Number. If that identity is ambiguous or missing, mutation is refused. getMessageReactions returns nonempty rows with contactId, raw reaction, messageToken, raw timestamp and raw status. Reactions in group/channel contexts have not been validated.
Live tests in the authorized Kh?m Sk conversation: test text EventID 12 recalled; test image EventID 14 reacted with quick code 1, changed to 3 and removed. A final pass confirmed default-account identity resolution, reaction row readback and idempotent recall. Recipient-side recall/reaction rendering remains unverified. Private before/after data should not be logged without application intent.
Message lookup, search and media reader (0.4.0 experimental)
Added getMessage(chatId,eventId), searchMessages(text,options), getAttachmentState(chatId,eventId), requestDownload(chatId,eventId,target='payload'). IViberMediaReader, AttachmentStateSchema, DownloadRequestSchema and DownloadReceiptSchema are exported. Search is case-sensitive literal substring matching over locally synced Body, with existing cursor paging. Attachment availability means a regular file currently exists at the database path; it does not prove a completed or valid download.
requestDownload uses the observed Chat.requestDownload/requestThumbnail QML methods. The target chat must already be selected in Desktop. A requested receipt acknowledges only native invocation; poll getAttachmentState to inspect local availability. There is no automatic retry, remote completion claim or download-to-destination operation. Native downloads remain unverified with an uncached incoming attachment. Recalled/text messages are rejected before invocation.
Live checks confirmed exact event lookup, cross-chat isolation, Unicode and literal SQL search, attachment response validation and recalled download rejection; see validation/media-reader-live-report.json. No new messages were sent during these checks. Recall readback now also detects messageType transitions for media recalls.
Read state, mute, group management and standalone wire transport remain discovery work. Edit, reply and forward text workflows are described below.
Edit, reply and forward text (0.5.0 experimental)
await client.editMessage({ chatId, eventId, text: 'Updated text' });
await client.replyMessage({ chatId, eventId, text: 'Reply text' });
await client.forwardMessage({ chatId, eventId, targetChatId });IViberMessageWorkflows has strict request DTOs EditMessageDto, ReplyMessageDto, ForwardMessageDto and MessageWorkflowReceipt. Text source messages only are currently supported. Editing requires an own outgoing text message. Source membership is checked against the requested chat. Existing draft, reply, edit or forward popup blocks submission; IDs must fit QML safe integers. Native errors are ambiguous and never retried. If a native step fails, inspect Desktop compose state before another action.
Editing uses Chat.editMessage, verifies EditController.active, sets plain text and accepts. Readback checks the original EventID body: Viber also creates internal edit-control Events, which must not be treated as another independently sent user message. An unchanged edit is a no-op. Native edit eligibility/time limits are enforced by Desktop and are not mapped to SDK enums.
Reply verifies QuoteInfo.eventID and chatID before accept. Correlation checks the resulting Info.quote.token through SQLite text extraction, preserving 64-bit precision. Forward opens MessageActions.forwardMessage, initializes a fresh selector with exactly one target ChatID, checks checkedCount=1 and invokes ForwardPopup.forward(checkedItems()). Readback requires a new outgoing matching body in the target chat and a positive Info.generalFwdInfo.num_forwards. Forward readback cannot prove the exact origin when other identical forwarded texts arrive concurrently.
All receipts report delivery=unknown. local-state-observed describes Desktop database evidence, not recipient delivery. submitted-unconfirmed is not a safe retry signal. Text workflows were exercised against ChatID 3: edit original EventID 16, reply EventID 24, forward EventID 25 to the same test chat. Cross-chat forwarding, media forwarding, rich text and media editing are not live validated. All visible test messages from this investigation were recalled afterwards; internal edit-control events were retained. See validation/message-workflows-live-report.json.
Change snapshots and extended media (0.6.0 experimental)
client.on('messageChange', event => console.log(event.kind, event.after.id));
const watcher = await client.watchMessageChanges({chatId, intervalMs:1000, windowSize:100});
// await watcher.close();
const snapshot = await client.getMessageSnapshots(chatId,100);
// await client.reconnect(); // closes watchers; recreate them afterwardsMessageSnapshotSchema includes runtime-validated reactions. MessageChangeSchema discriminates kind: added, edited, recalled, reaction-changed, status-changed, updated; before/after retain raw codes and IDs as strings. A single SQL snapshot reads messages and associated reactions. Watcher seeds a baseline without emitting old rows, compares the latest window (1..500), and never infers deletion from eviction. Changes outside the window are not monitored. Intermediate states between polls can coalesce; this is not native push, durable replay or exactly-once delivery. A row reentering the window can appear as added. Listener errors can replay changes in the next poll. Internal edit-control Events remain raw added rows. Recall classification uses observed type 72; raw status changes do not establish sent/delivered/read meanings.
Live Notes EventID 40 exercised added, edited, raw status and reaction changes. Recall classification is covered synthetically; no new live recall was performed because test messages must remain visible. JPEG and WebP sends produced type 2 in Notes, EventIDs 42/43. Reply and forwarding now accept observed text/image/file sources (types 1/2/11), with live image/file tests EventIDs 44..47. Only text editing is enabled. Media-forward correlation uses type, body and forward metadata; concurrent identical empty-body attachments remain ambiguous. Cross-chat forwarding remains unverified. No caption, progress or remote delivery claim is added.
reconnect() explicitly detaches and reattaches with binary validation, returning login status. It does not replay mutations, restart Viber or automatically recreate watchers. Full QR login on an unlinked session, video sending, recorded voice notes, transfer completion/progress and chat/group management remain unfinished research. All live mutation tests now target My Notes (ChatID 4 on this installation); test:workflows:live retains the created messages.
Automation and backend contracts (0.7.0 experimental)
The SDK runtime belongs in a Windows worker used by automation-web-staging. redai-v201-be-app-staging receives validated account events through the host webhook gateway/queue. Neither application has been installed, modified or deployed by this SDK preparation. The existing Telegram/Zalo gateway route is not a Viber route; the host must implement its Viber endpoint and authentication explicitly.
// automation-web-staging: singleton runtime registry owned by the NestJS provider.
import { ViberAccountManager } from '@redonvn/messaging-viber-desktop/services';
const manager = new ViberAccountManager();
const account = await manager.attach({
accountId: applicationAccountId, // trusted mapping from the application database
runtimeId: windowsWorkerId,
pid: selectedViberPid,
expectedNativeAccountId: verifiedNativeAccountId,
});
account.on('serviceError', error => logger.error(error));
account.on('event', event => {
// Enqueue synchronously; arrange durable persistence/retry in the host.
// Do not send directly from an async EventEmitter listener without catching failures.
applicationOutbox.enqueue(event);
});
await account.startEvents(chatIds, {intervalMs:1000,windowSize:100});
await account.messages.sendMessage({kind:'text',chatId,text:'Hello'});
const page = await account.messages.getMessages({chatId,limit:50});
// On shutdown: await manager.close();ViberMessagingService wraps message reads, sends, workflows, reactions and downloads. ViberConversationService wraps chat/member/contact reads. ViberAccountService verifies the native default account before operations and event routing. ViberAccountManager reserves application account IDs, native account IDs and PIDs during attach, rejects duplicate registrations, and detaches explicitly. This is a local singleton registry, not distributed locking or tenant authorization. The host must authorize accountId access and hold a worker/runtime lease. Use separate Windows profiles/VMs/workers with an independently running Viber process for independent accounts. One Desktop process cannot be split into multiple independent SDK accounts. Real simultaneous multi-account isolation has not been tested.
AccountBinding has accountId (application routing identity), runtimeId (worker identity), pid (local process), expectedNativeAccountId (verified native identity). Native IDs can contain phone identifiers; do not log bindings publicly. A changed/mismatched identity raises ACCOUNT_IDENTITY_MISMATCH before service dispatch. This verifies an existing session; it does not log in, provision accounts, decrypt credentials or switch profiles. If cleanup after failed attach fails, the manager retains its reservation until explicit detach succeeds. Managers must be singleton per worker to avoid competing process owners.
startEvents subscribes to the explicit chatIds with snapshot polling. Discover new conversations through conversations.getConversations and recreate subscriptions when needed. The event envelope is schemaVersion=1, platform=viber-desktop, UUID eventId, accountId, runtimeId, eventType, observedAt, source, normalized message, before and after. eventId identifies an observation, not a stable remote delivery ID; polling can replay/coalesce events. The host owns deduplication, outbox/retry, persistence, webhook signing and backpressure. No HTTP delivery is performed by the SDK.
// redai-v201-be-app-staging: portable validation, without loading the native client.
import { ViberAccountEventSchema } from '@redonvn/messaging-viber-desktop/contracts';
import type { ViberAccountEvent } from '@redonvn/messaging-viber-desktop/contracts';
const event: ViberAccountEvent = ViberAccountEventSchema.parse(request.body);
// Authenticate the worker, verify its account assignment, then persist/enqueue.The contracts entry imports Zod/schema code only, no Frida or Windows tooling. Frida is optional at installation: automation Windows workers must install optional dependencies; a contracts-only backend can use npm install --omit=optional. Missing Frida prevents native connect. Package supports Node >=22. Install the reviewed .tgz in automation-web-staging when connecting the application; install/use the contracts entry in the backend only if it needs runtime schema validation. SDK files are packaged; local experimental scripts are not entry points.
NormalizedMessage.content is a discriminated union: text, image, video, file, location, contact, recalled, unknown. Native codes observed on the pinned build: 1 text, 2 image, 3 video, 5 location (nonzero raw coordinate fields), 10 contact (Name/PhoneNumber), 11 file, 72 recalled. Code 4 remains unknown; it must not be named sticker without further evidence. MP3 with code 11 remains file. Location coordinate scaling and general duration units remain unverified. Unknown codes and raw direction/status/eventType/flags remain preserved. delivery remains unknown. Normalization never drops unknown messages.
getMessageMetadata selects only file descriptors, contact fields, raw coordinates, quote token and forward count. It does not return Info wholesale, EncParams, credential values or authentication headers. IDs/tokens/sizes stay strings where precision matters. NormalizedMessage.recordKind distinguishes message from edit-control using the observed Info.edit.token; backend consumers must not render edit-control rows as additional visible text messages. The original DesktopMessageSchema stays compatible; use normalizeMessage/getMessageMetadata or account.messages to consume the normalized model. For polling events, metadata is enriched after the snapshot and may reflect a later observation.
Type evidence and tests: validation/integration-services-live-report.json reads incoming samples 50/52/55/57/58/61 through a verified account service. Unit tests cover unknown type preservation, MP3 semantics, 64-bit tokens, account/PID reservations, failed attach cleanup, identity drift blocking sends and account event routing. Public JSON schemas are in validation/integration-schemas.json. Account identity itself was tested against one real process; multi-account concurrency is tested with simulated clients.
API groups and discovery registry (0.7.1)
API groups are runtime, auth, accounts, conversations, contacts, messages, actions, reactions, media, events, diagnostics, groups. The machine-readable callable registry is src/api/catalog.ts, exported as API_CATALOG / getApiCatalog from the root or the portable /catalog entry. Resource resources/api-catalog.json contains the generated group, callable API and discovery backlog inventory.
import { getApiCatalog, API_GROUPS } from '@redonvn/messaging-viber-desktop/catalog';
const media = getApiCatalog({group:'media',scope:'client'});
const pendingValidation = getApiCatalog({validation:'not-live-tested'});Each entry has id (scope.method), group, scope, method, availability (implemented/blocked), validation (live-observed/partial-live/unit-only/not-live-tested), and notes describing evidence limits. Scope separates client APIs from account manager and guarded service facades; testing a client method does not automatically validate its facade. Group groups exposes a capability report; its mutations remain in the discovery backlog. API_DISCOVERY_BACKLOG contains feature candidates, not fake public APIs. resources/endpoint-catalog.json remains a separate unverified HTTP URL inventory.
Services currently organize the account boundary and normalized messaging/conversation access; low-level client methods remain on ViberDesktopClient for compatibility. Since 0.8.0, domain service implementations are split into individual files in src/services/. Add new implementations to the appropriate service/domain, add DTO/runtime schemas and evidence, then register their scope.method/group/availability/validation in the registry. Registry method names are checked against TypeScript public class methods at build time. Run npm run build and npm run catalog:export after editing the registry. Keep native hypotheses out of callable entries until a real public API exists.
One domain service per API group (0.8.0)
Each API group has a canonical service implementation in its own file. src/services.ts remains the public export barrel. ViberAccountService composes account-bound domain services; ViberAccountManager owns their process registrations.
| Group | Account access | Canonical class | File in src/services/ | | --- | --- | --- | --- | | runtime | account.runtime | ViberRuntimeService | runtime.service.ts | | auth | account.auth | ViberAuthService | auth.service.ts | | accounts | account itself | ViberAccountService | account.service.ts | | conversations | account.conversations | ViberConversationService | conversations.service.ts | | contacts | account.contacts | ViberContactService | contacts.service.ts | | messages | account.messages | ViberMessagingService | messages.service.ts | | actions | account.actions | ViberMessageActionsService | actions.service.ts | | reactions | account.reactions | ViberReactionService | reactions.service.ts | | media | account.media | ViberMediaService | media.service.ts | | events | account.events | ViberEventService | events.service.ts | | diagnostics | account.diagnostics | ViberDiagnosticsService | diagnostics.service.ts | | groups | account.groups | ViberGroupService | groups.service.ts |
await account.auth.getLoginStatus();
await account.contacts.getContacts();
await account.actions.replyMessage({chatId,eventId,text:'Reply'});
await account.reactions.setReaction(chatId,eventId,{kind:'quick',code:1});
await account.media.sendImage(chatId,filePath);
account.events.on('event', event => applicationOutbox.enqueue(event));
await account.events.start(chatIds);
const supported = account.groups.getCapabilities(); // group mutations are all falseSubscribe through account.events or through the compatibility account.on('event') surface, not both for the same consumer. The old mixed methods on account.messages and conversations.getContacts, plus startEvents/stopEvents/getLoginStatus on the account facade, delegate to the canonical domain services and are marked deprecated. ViberDesktopClient stays compatible as the low-level bridge. New APIs should be implemented in their domain service and added to API_GROUP_SERVICES / the catalog with accurate evidence status. No additional native capabilities are introduced by this structural refactor.
Runtime reconnect/close stops account event subscriptions first. After reconnect, explicitly restart events; no mutations or subscriptions are automatically replayed. A failed identity check after reconnect closes the attachment. Diagnostics that read public runtime/catalog metadata do not require an authenticated account; message/socket operations still use the account guard. Group service reports capabilities only, with no fake create/add/remove endpoints.
DTO and interface files (0.9.0)
Each of the 12 domains now has src/dto/.dto.ts and src/interfaces/.interface.ts. Common pagination and subscription handles are in dto/common.dto.ts. Re-export barrels support package imports /dto and /interfaces. All domain services implement their named IViber...Service interfaces; public service methods have named Promise<...OutputDto> return declarations. DTO interfaces and types are the public compile-time contract. Zod schemas are separate runtime validators for external JSON and native bridge values; keep both aligned using the domain contract tests.
import { SendMessageRequestSchema, DownloadInputSchema } from '@redonvn/messaging-viber-desktop/dto';
import type { SendMessageDto, SendMessageOutputDto } from '@redonvn/messaging-viber-desktop/dto';
import type { IViberMessagingService } from '@redonvn/messaging-viber-desktop/interfaces';
const dto: SendMessageDto = SendMessageRequestSchema.parse(input);
const receipt: SendMessageOutputDto = await messages.sendMessage(dto);Input/output DTOs are data shapes; existing positional signatures are preserved. For example, MediaFileInputDto has chatId/filePath, while service.sendImage takes (dto.chatId,dto.filePath). StartEventsInputDto has chatIds and watcher options, while events.start takes (chatIds, options). Interface signatures document actual method invocation. Do not pass an aggregate DTO object to a positional method. New schemas are available to host controllers; introducing a DTO file does not by itself add class-validator decorators or a NestJS validation pipe.
MessagePageOutputDto contains NormalizedMessage items. SearchMessagesOutputDto currently contains raw DesktopMessage items. SendMessageOutputDto is the send receipt, not the message itself. getMessage returns a nullable normalized message; metadata is nullable if the row is absent. Raw IDs/tokens stay strings and receipt delivery remains unknown. Local account handles, listener functions, AbortSignal and void returns are explicitly documented as non-JSON types. Unsupported group mutations have no invented input/output contracts.
The generated validation/domain-dto-schemas.json groups serializable request/response schemas by domain. Run npm run build and npm run dto:export to refresh it. Some runtime capabilities accept new string keys; that schema is deliberately extensible. DTO schemas describe data only: file existence, native feature eligibility and account authorization still require the runtime/host checks. Diagnostics schemas are exported for consumers; diagnostics not previously validated by the client are not automatically parsed just because an output DTO now exists.
TypeScript DTO ownership (0.9.x)
The public DTO/interface files are now the source of compile-time types. Domain input/output DTOs are hand-declared TypeScript interfaces or aliases; they no longer use z.infer or z.input. Zod request/response schemas remain a separate runtime validation layer. When changing a field, update the DTO/interface and its runtime schema together. Runtime schemas do not define the public TypeScript type. JSON Schema is generated only from runtime validation schemas. Serializable request fields can be used by automation/backend adapters; local handles, listeners, AbortSignal and void operations are marked localOnly in getDomainDtoJsonSchemas().
