@kyyinfinite/zapo-message 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/LICENSE +20 -0
  3. package/README.md +532 -2
  4. package/build.config.json +28 -0
  5. package/dist/airich/airich.d.ts +180 -0
  6. package/dist/airich/airich.js +548 -0
  7. package/dist/airich/context.d.ts +24 -0
  8. package/dist/airich/context.js +48 -0
  9. package/dist/airich/encode.d.ts +3 -0
  10. package/dist/airich/encode.js +16 -0
  11. package/dist/airich/index.d.ts +20 -0
  12. package/dist/airich/index.js +11 -0
  13. package/dist/airich/inline.d.ts +45 -0
  14. package/dist/airich/inline.js +152 -0
  15. package/dist/airich/nodes.d.ts +30 -0
  16. package/dist/airich/nodes.js +121 -0
  17. package/dist/airich/primitives.d.ts +144 -0
  18. package/dist/airich/primitives.js +230 -0
  19. package/dist/airich/protocol.d.ts +35 -0
  20. package/dist/airich/protocol.js +65 -0
  21. package/dist/airich/table.d.ts +22 -0
  22. package/dist/airich/table.js +35 -0
  23. package/dist/airich/tokenizer.d.ts +13 -0
  24. package/dist/airich/tokenizer.js +717 -0
  25. package/dist/airich/transport.d.ts +15 -0
  26. package/dist/airich/transport.js +56 -0
  27. package/dist/branding.d.ts +5 -0
  28. package/dist/branding.js +9 -0
  29. package/dist/btn/builders.d.ts +246 -0
  30. package/dist/btn/builders.js +710 -0
  31. package/dist/btn/media-slot.d.ts +28 -0
  32. package/dist/btn/media-slot.js +323 -0
  33. package/dist/btn/media-source.d.ts +38 -0
  34. package/dist/btn/media-source.js +116 -0
  35. package/dist/btn/sharp-loader.d.ts +5 -0
  36. package/dist/btn/sharp-loader.js +18 -0
  37. package/dist/btn/thumbnail.d.ts +21 -0
  38. package/dist/btn/thumbnail.js +124 -0
  39. package/dist/btn/validators.d.ts +40 -0
  40. package/dist/btn/validators.js +135 -0
  41. package/dist/btn.d.ts +1 -0
  42. package/dist/btn.js +1 -0
  43. package/dist/core/async-send.d.ts +20 -0
  44. package/dist/core/async-send.js +1 -0
  45. package/dist/core/base-builder.d.ts +20 -0
  46. package/dist/core/base-builder.js +67 -0
  47. package/dist/core/errors.d.ts +30 -0
  48. package/dist/core/errors.js +61 -0
  49. package/dist/download.d.ts +24 -0
  50. package/dist/download.js +123 -0
  51. package/dist/index.d.ts +38 -0
  52. package/dist/index.js +22 -0
  53. package/dist/integration/augment.d.ts +97 -0
  54. package/dist/integration/augment.js +1 -0
  55. package/dist/integration/auto.d.ts +8 -0
  56. package/dist/integration/auto.js +79 -0
  57. package/dist/integration/index.d.ts +4 -0
  58. package/dist/integration/index.js +2 -0
  59. package/dist/integration/methods.d.ts +25 -0
  60. package/dist/integration/methods.js +24 -0
  61. package/dist/interactive.d.ts +24 -0
  62. package/dist/interactive.js +121 -0
  63. package/dist/media-gate.d.ts +99 -0
  64. package/dist/media-gate.js +322 -0
  65. package/dist/message/album.d.ts +33 -0
  66. package/dist/message/album.js +107 -0
  67. package/dist/message/contact.d.ts +29 -0
  68. package/dist/message/contact.js +123 -0
  69. package/dist/message/forward.d.ts +23 -0
  70. package/dist/message/forward.js +77 -0
  71. package/dist/message/index.d.ts +26 -0
  72. package/dist/message/index.js +13 -0
  73. package/dist/message/link-preview.d.ts +28 -0
  74. package/dist/message/link-preview.js +98 -0
  75. package/dist/message/location.d.ts +24 -0
  76. package/dist/message/location.js +94 -0
  77. package/dist/message/media.d.ts +90 -0
  78. package/dist/message/media.js +123 -0
  79. package/dist/message/poll.d.ts +24 -0
  80. package/dist/message/poll.js +98 -0
  81. package/dist/message/reaction.d.ts +20 -0
  82. package/dist/message/reaction.js +71 -0
  83. package/dist/message/sticker.d.ts +29 -0
  84. package/dist/message/sticker.js +44 -0
  85. package/dist/message/target.d.ts +18 -0
  86. package/dist/message/target.js +24 -0
  87. package/dist/message/text.d.ts +17 -0
  88. package/dist/message/text.js +29 -0
  89. package/dist/message/vcard.d.ts +9 -0
  90. package/dist/message/vcard.js +23 -0
  91. package/dist/message/webp.d.ts +6 -0
  92. package/dist/message/webp.js +57 -0
  93. package/dist/payloads.d.ts +180 -0
  94. package/dist/payloads.js +1 -0
  95. package/dist/serialize.d.ts +41 -0
  96. package/dist/serialize.js +93 -0
  97. package/dist/status.d.ts +3 -0
  98. package/dist/status.js +21 -0
  99. package/dist/zapo-client.d.ts +44 -0
  100. package/dist/zapo-client.js +1 -0
  101. package/examples/airich.ts +59 -0
  102. package/examples/buttons.ts +48 -0
  103. package/examples/client-methods.ts +58 -0
  104. package/examples/hybrid.ts +133 -0
  105. package/examples/serialize.ts +61 -0
  106. package/package.json +271 -4
  107. package/scripts/check-no-comments.mjs +101 -0
  108. package/scripts/compare-golden.mjs +461 -0
  109. package/scripts/lib-config.mjs +9 -0
  110. package/scripts/smoke-auto.mjs +75 -0
  111. package/scripts/test-external-consumer.mjs +316 -0
  112. package/scripts/verify-package.mjs +78 -0
  113. package/src/airich/airich.ts +970 -0
  114. package/src/airich/context.ts +96 -0
  115. package/src/airich/encode.ts +25 -0
  116. package/src/airich/index.ts +98 -0
  117. package/src/airich/inline.ts +272 -0
  118. package/src/airich/nodes.ts +174 -0
  119. package/src/airich/primitives.ts +474 -0
  120. package/src/airich/protocol.ts +133 -0
  121. package/src/airich/table.ts +70 -0
  122. package/src/airich/tokenizer.ts +799 -0
  123. package/src/airich/transport.ts +106 -0
  124. package/src/branding.ts +23 -0
  125. package/src/btn/builders.ts +1073 -0
  126. package/src/btn/media-slot.ts +486 -0
  127. package/src/btn/media-source.ts +189 -0
  128. package/src/btn/sharp-loader.ts +23 -0
  129. package/src/btn/thumbnail.ts +182 -0
  130. package/src/btn/validators.ts +237 -0
  131. package/src/btn.ts +8 -0
  132. package/src/core/async-send.ts +28 -0
  133. package/src/core/base-builder.ts +104 -0
  134. package/src/core/errors.ts +82 -0
  135. package/src/download.ts +212 -0
  136. package/src/index.ts +229 -0
  137. package/src/integration/augment.ts +262 -0
  138. package/src/integration/auto.ts +103 -0
  139. package/src/integration/index.ts +8 -0
  140. package/src/integration/methods.ts +45 -0
  141. package/src/interactive.ts +188 -0
  142. package/src/media-gate.ts +499 -0
  143. package/src/message/album.ts +187 -0
  144. package/src/message/contact.ts +170 -0
  145. package/src/message/forward.ts +123 -0
  146. package/src/message/index.ts +83 -0
  147. package/src/message/link-preview.ts +148 -0
  148. package/src/message/location.ts +150 -0
  149. package/src/message/media.ts +323 -0
  150. package/src/message/poll.ts +158 -0
  151. package/src/message/reaction.ts +133 -0
  152. package/src/message/sticker.ts +100 -0
  153. package/src/message/target.ts +38 -0
  154. package/src/message/text.ts +61 -0
  155. package/src/message/vcard.ts +36 -0
  156. package/src/message/webp.ts +78 -0
  157. package/src/payloads.ts +204 -0
  158. package/src/serialize.ts +180 -0
  159. package/src/status.ts +29 -0
  160. package/src/zapo-client.ts +84 -0
  161. package/test/airich-inline.test.ts +200 -0
  162. package/test/airich-primitives.test.ts +226 -0
  163. package/test/airich-tokenizer.test.ts +145 -0
  164. package/test/airich.golden.test.ts +406 -0
  165. package/test/airich.test.ts +1006 -0
  166. package/test/btn-button.test.ts +416 -0
  167. package/test/btn-header.test.ts +646 -0
  168. package/test/btn-legacy.test.ts +342 -0
  169. package/test/btn-lifecycle.test.ts +295 -0
  170. package/test/btn-list.test.ts +261 -0
  171. package/test/btn-media-source.test.ts +150 -0
  172. package/test/btn-thumbnail.test.ts +160 -0
  173. package/test/builder-compat.test.ts +264 -0
  174. package/test/helpers.ts +27 -0
  175. package/test/hybrid-airich.test.ts +345 -0
  176. package/test/hybrid-client.test.ts +239 -0
  177. package/test/hybrid-errors.test.ts +557 -0
  178. package/test/hybrid-interactive.test.ts +455 -0
  179. package/test/hybrid.golden.test.ts +349 -0
  180. package/test/hybrid.test.ts +479 -0
  181. package/test/integration-auto.test.ts +159 -0
  182. package/test/integration.fakeserver.test.ts +440 -0
  183. package/test/media-gate.test.ts +215 -0
  184. package/test/message-album.test.ts +145 -0
  185. package/test/message-builders.test.ts +401 -0
  186. package/test/message-media.test.ts +303 -0
  187. package/test/message.fakeserver.test.ts +284 -0
  188. package/test/message.golden.test.ts +254 -0
  189. package/test/serializer.test.ts +448 -0
  190. package/tsconfig.json +26 -0
  191. package/tsconfig.test.json +10 -0
@@ -0,0 +1,303 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import sharp from "sharp";
4
+ import type { Readable } from "node:stream";
5
+ import type { WaMediaUploadResult } from "zapo-js";
6
+
7
+ import {
8
+ media,
9
+ sticker,
10
+ probeWebp,
11
+ mediaSlotToMessage,
12
+ } from "@kyyinfinite/zapo-message";
13
+ import { asClient, L } from "./helpers.js";
14
+
15
+ const makeUploadClient = () => {
16
+ const uploads: { source: unknown; options: Record<string, unknown> }[] = [];
17
+ const sends: { jid?: unknown; content?: unknown; options?: unknown }[] = [];
18
+ const uploadResult = (source: unknown): Promise<WaMediaUploadResult> => {
19
+ const bytes =
20
+ source instanceof Uint8Array
21
+ ? source.byteLength
22
+ : new Promise<number>((resolve) => {
23
+ let total = 0;
24
+ const stream = source as Readable;
25
+ stream.on("data", (chunk: Buffer) => {
26
+ total += chunk.length;
27
+ });
28
+ stream.once("end", () => resolve(total));
29
+ stream.once("error", () => resolve(total));
30
+ });
31
+ return Promise.resolve(bytes).then((fileLength) => ({
32
+ url: "https://mmg.whatsapp.net/v/t62.7118-24/fake-upload",
33
+ directPath: "/v/t62.7118-24/fake-upload",
34
+ mediaKey: new Uint8Array(32).fill(1),
35
+ fileSha256: new Uint8Array(32).fill(2),
36
+ fileEncSha256: new Uint8Array(32).fill(3),
37
+ fileLength,
38
+ mediaKeyTimestamp: 1730000000,
39
+ ...(fileLength > 100 ? { streamingSidecar: new Uint8Array([9, 9]) } : {}),
40
+ }));
41
+ };
42
+ return {
43
+ uploads,
44
+ sends,
45
+ client: asClient({
46
+ message: {
47
+ upload: async (source: unknown, options: Record<string, unknown>) => {
48
+ uploads.push({ source, options });
49
+ return uploadResult(source);
50
+ },
51
+ send: async (jid: unknown, content: unknown, options: unknown) => {
52
+ sends.push({ jid, content, options });
53
+ return { id: "MEDIA1", attempts: 1, ack: {} };
54
+ },
55
+ },
56
+ }),
57
+ };
58
+ };
59
+
60
+ const makePng = (width = 120, height = 90): Promise<Buffer> =>
61
+ sharp({ create: { width, height, channels: 3, background: "#3060ff" } })
62
+ .png()
63
+ .toBuffer();
64
+
65
+ const makeWebp = async (width = 512, height = 512): Promise<Buffer> =>
66
+ sharp({
67
+ create: { width, height, channels: 4, background: "#ff9030" },
68
+ })
69
+ .webp({ effort: 0 })
70
+ .toBuffer();
71
+
72
+ const makeAnimatedWebpFixture = (width = 200, height = 100): Buffer => {
73
+ const chunks: Buffer[] = [];
74
+ const push4CC = (fourcc: string, payload: Buffer) => {
75
+ chunks.push(
76
+ Buffer.from(fourcc, "ascii"),
77
+ (() => {
78
+ const size = Buffer.alloc(4);
79
+ size.writeUInt32LE(payload.byteLength);
80
+ return size;
81
+ })(),
82
+ payload,
83
+ ...(payload.byteLength % 2 ? [Buffer.alloc(1)] : []),
84
+ );
85
+ };
86
+ const vp8x = Buffer.alloc(10);
87
+ vp8x.writeUInt8(0x02, 0);
88
+ vp8x.writeUIntLE(width - 1, 4, 3);
89
+ vp8x.writeUIntLE(height - 1, 7, 3);
90
+ push4CC("VP8X", vp8x);
91
+ push4CC("ANIM", Buffer.alloc(6));
92
+ const body = Buffer.concat([Buffer.from("WEBP", "ascii"), ...chunks]);
93
+ const header = Buffer.alloc(8);
94
+ header.write("RIFF", 0, "ascii");
95
+ header.writeUInt32LE(body.byteLength, 4);
96
+ return Buffer.concat([header, body]);
97
+ };
98
+
99
+ test("webp: probe membaca dimensi statis", async () => {
100
+ const bytes = await makeWebp(320, 240);
101
+ const info = probeWebp(new Uint8Array(bytes));
102
+ assert.ok(info, "webp dikenali");
103
+ assert.equal(info?.width, 320);
104
+ assert.equal(info?.height, 240);
105
+ assert.equal(info?.isAnimated, false);
106
+ });
107
+
108
+ test("webp: probe menolak non-webp", () => {
109
+ assert.equal(
110
+ probeWebp(new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])),
111
+ undefined,
112
+ );
113
+ assert.equal(probeWebp(new Uint8Array(0)), undefined);
114
+ });
115
+
116
+ test("webp: probe membaca container animasi (VP8X + ANIM)", () => {
117
+ const fixture = makeAnimatedWebpFixture(200, 100);
118
+ const info = probeWebp(new Uint8Array(fixture));
119
+ assert.ok(info, "container animasi dikenali");
120
+ assert.equal(info?.width, 200);
121
+ assert.equal(info?.height, 100);
122
+ assert.equal(info?.isAnimated, true);
123
+ });
124
+
125
+ test("media: image upload + payload imageMessage", async () => {
126
+ const png = await makePng(300, 200);
127
+ const { client, uploads } = makeUploadClient();
128
+ const payload = await media(client).image(png, { caption: "libur" }).build();
129
+ const image = (payload as { imageMessage: Record<string, unknown> })
130
+ .imageMessage;
131
+ assert.equal(image.url, "https://mmg.whatsapp.net/v/t62.7118-24/fake-upload");
132
+ assert.equal(image.mimetype, "image/png");
133
+ assert.equal(image.width, 300);
134
+ assert.equal(image.height, 200);
135
+ assert.equal(image.caption, "libur");
136
+ assert.ok(image.jpegThumbnail, "thumbnail otomatis dibuat");
137
+ assert.equal(uploads[0]?.options.type, "image");
138
+ });
139
+
140
+ test("media: video dengan seconds + streamingSidecar", async () => {
141
+ const { client, uploads } = makeUploadClient();
142
+ const source = Buffer.alloc(400, 7);
143
+ (source as unknown as { __fake: string }).__fake = "video";
144
+ const payload = await media(client)
145
+ .video(source, {
146
+ mimetype: "video/mp4",
147
+ seconds: 12,
148
+ width: 640,
149
+ height: 360,
150
+ thumbnail: false,
151
+ })
152
+ .build();
153
+ const video = (payload as { videoMessage: Record<string, unknown> })
154
+ .videoMessage;
155
+ assert.equal(video.mimetype, "video/mp4");
156
+ assert.equal(video.seconds, 12);
157
+ assert.equal(video.width, 640);
158
+ assert.equal(video.height, 360);
159
+ assert.ok(video.streamingSidecar, "sidecar besar ikut dari upload");
160
+ assert.equal(uploads[0]?.options.type, "video");
161
+ });
162
+
163
+ test("media: audio + ptt memakai tipe upload ptt", async () => {
164
+ const { client, uploads } = makeUploadClient();
165
+ const payload = await media(client)
166
+ .audio(Buffer.alloc(64, 3), {
167
+ mimetype: "audio/ogg; codecs=opus",
168
+ ptt: true,
169
+ })
170
+ .build();
171
+ const audio = (payload as { audioMessage: Record<string, unknown> })
172
+ .audioMessage;
173
+ assert.equal(audio.mimetype, "audio/ogg; codecs=opus");
174
+ assert.equal(audio.ptt, true);
175
+ assert.equal(uploads[0]?.options.type, "ptt");
176
+ });
177
+
178
+ test("media: audio tanpa ptt memakai tipe upload audio", async () => {
179
+ const { client, uploads } = makeUploadClient();
180
+ await media(client)
181
+ .audio(Buffer.alloc(64, 3), { mimetype: "audio/mpeg", seconds: 3 })
182
+ .build();
183
+ assert.equal(uploads[0]?.options.type, "audio");
184
+ });
185
+
186
+ test("media: document dengan fileName", async () => {
187
+ const { client } = makeUploadClient();
188
+ const payload = await media(client)
189
+ .document(Buffer.alloc(32, 1), {
190
+ mimetype: "application/pdf",
191
+ fileName: "laporan.pdf",
192
+ })
193
+ .build();
194
+ const doc = (payload as { documentMessage: Record<string, unknown> })
195
+ .documentMessage;
196
+ assert.equal(doc.mimetype, "application/pdf");
197
+ assert.equal(doc.fileName, "laporan.pdf");
198
+ });
199
+
200
+ test("media: caption hanya untuk image/video", async () => {
201
+ const { client } = makeUploadClient();
202
+ await assert.rejects(async () => {
203
+ await media(client)
204
+ .document(Buffer.alloc(8, 1), {
205
+ mimetype: "text/plain",
206
+ fileName: "a.txt",
207
+ })
208
+ .caption("nope")
209
+ .build();
210
+ }, /caption hanya didukung/);
211
+ });
212
+
213
+ test("media: dua jenis media ditolak", async () => {
214
+ const { client } = makeUploadClient();
215
+ const png = await makePng(10, 10);
216
+ await assert.rejects(async () => {
217
+ await media(client).image(png).audio(Buffer.alloc(8, 1)).build();
218
+ }, /satu jenis media/);
219
+ });
220
+
221
+ test("media: tanpa sumber ditolak", async () => {
222
+ const { client } = makeUploadClient();
223
+ await assert.rejects(() => media(client).build(), /belum punya sumber/);
224
+ });
225
+
226
+ test("media: caption sebelum media ditolak", () => {
227
+ assert.throws(() => media().caption("x"), /panggil image/);
228
+ });
229
+
230
+ test("media: send mengirim payload protokol", async () => {
231
+ const png = await makePng(20, 20);
232
+ const { client, sends } = makeUploadClient();
233
+ await media(client).image(png).send("6281@s.whatsapp.net");
234
+ const content = L(sends[0]?.content) as Record<string, unknown>;
235
+ assert.ok(content.imageMessage, "content berbentuk imageMessage");
236
+ assert.equal(sends[0]?.jid, "6281@s.whatsapp.net");
237
+ });
238
+
239
+ test("sticker: upload webp + payload stickerMessage", async () => {
240
+ const webp = await makeWebp(512, 512);
241
+ const { client, uploads } = makeUploadClient();
242
+ const payload = await sticker(client).source(webp).build();
243
+ const st = (payload as { stickerMessage: Record<string, unknown> })
244
+ .stickerMessage;
245
+ assert.equal(st.mimetype, "image/webp");
246
+ assert.equal(st.width, 512);
247
+ assert.equal(st.height, 512);
248
+ assert.equal(st.isAnimated, false);
249
+ assert.ok(st.pngThumbnail, "thumbnail png otomatis");
250
+ assert.equal(uploads[0]?.options.type, "sticker");
251
+ });
252
+
253
+ test("sticker: sumber non-webp ditolak", async () => {
254
+ const { client } = makeUploadClient();
255
+ await assert.rejects(
256
+ () => sticker(client).source(Buffer.from("plain text file")).build(),
257
+ /WebP/,
258
+ );
259
+ });
260
+
261
+ test("sticker: webp animasi terdeteksi", async () => {
262
+ const animated = makeAnimatedWebpFixture(200, 100);
263
+ const info = probeWebp(new Uint8Array(animated));
264
+ assert.equal(info?.isAnimated, true);
265
+ const { client, uploads } = makeUploadClient();
266
+ const payload = await sticker(client).source(animated).build();
267
+ const st = (payload as { stickerMessage: Record<string, unknown> })
268
+ .stickerMessage;
269
+ assert.equal(st.isAnimated, true);
270
+ assert.equal(st.width, 200);
271
+ assert.equal(st.height, 100);
272
+ assert.equal(uploads[0]?.options.type, "sticker");
273
+ });
274
+
275
+ test("sticker: isAnimated manual dan pngThumbnail eksplisit", async () => {
276
+ const webp = await makeWebp(300, 300);
277
+ const { client } = makeUploadClient();
278
+ const payload = await sticker(client)
279
+ .source(webp, {
280
+ isAnimated: true,
281
+ pngThumbnail: new Uint8Array([9, 9, 9]),
282
+ stickerSentTs: 1700000000000,
283
+ })
284
+ .build();
285
+ const st = (payload as { stickerMessage: Record<string, unknown> })
286
+ .stickerMessage;
287
+ assert.equal(st.isAnimated, true);
288
+ assert.deepEqual(st.pngThumbnail, new Uint8Array([9, 9, 9]));
289
+ assert.equal(st.stickerSentTs, 1700000000000);
290
+ });
291
+
292
+ test("sticker: tanpa sumber ditolak", async () => {
293
+ const { client } = makeUploadClient();
294
+ await assert.rejects(() => sticker(client).build(), /belum punya sumber/);
295
+ });
296
+
297
+ test("mediaSlotToMessage: pemetaan field", () => {
298
+ const message = mediaSlotToMessage({
299
+ field: "audioMessage",
300
+ message: { mimetype: "audio/mpeg" },
301
+ });
302
+ assert.deepEqual(message, { audioMessage: { mimetype: "audio/mpeg" } });
303
+ });
@@ -0,0 +1,284 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import sharp from "sharp";
4
+ import type { BinaryNode, WaIncomingMessageEvent } from "zapo-js";
5
+
6
+ import { FakeWaServer } from "@zapo-js/fake-server";
7
+ import { createStore, WaClient } from "zapo-js";
8
+ import "@kyyinfinite/zapo-message";
9
+
10
+ const BOT_PN = "5511999999999";
11
+ const BOT_DEVICE_JID = `${BOT_PN}:1@s.whatsapp.net`;
12
+ const OWNER_JID = "5511988888888@s.whatsapp.net";
13
+
14
+ interface DecryptedMessage {
15
+ message: Record<string, unknown>;
16
+ }
17
+
18
+ type StartedFakeServer = Awaited<ReturnType<typeof FakeWaServer.start>>;
19
+
20
+ const asRecord = (value: unknown): Record<string, unknown> =>
21
+ (value ?? {}) as Record<string, unknown>;
22
+
23
+ const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
24
+
25
+ const createPairedClient = async (server: StartedFakeServer) => {
26
+ const store = createStore({});
27
+
28
+ const client = new WaClient({
29
+ store,
30
+ sessionId: "zapo-message-new-kinds",
31
+ chatSocketUrls: [server.url],
32
+ testHooks: { noiseRootCa: server.noiseRootCa },
33
+ proxy: {
34
+ mediaUpload: server.mediaProxyAgent,
35
+ mediaDownload: server.mediaProxyAgent,
36
+ },
37
+ });
38
+
39
+ const pairingMaterial = new Promise<{
40
+ identityPublicKey: Uint8Array;
41
+ advSecretKey: Uint8Array;
42
+ }>((resolve) => {
43
+ void client.once("auth_qr", ({ qr }: { qr: string }) => {
44
+ const [, , identityPubB64, advSecretB64] = qr.split(",");
45
+ resolve({
46
+ identityPublicKey: new Uint8Array(
47
+ Buffer.from(identityPubB64 ?? "", "base64"),
48
+ ),
49
+ advSecretKey: new Uint8Array(Buffer.from(advSecretB64 ?? "", "base64")),
50
+ });
51
+ });
52
+ });
53
+
54
+ await client.connect();
55
+ const pipeline = await server.waitForAuthenticatedPipeline();
56
+ const nextPipelineWaiter = server.waitForNextAuthenticatedPipeline(30_000);
57
+ await server.runPairing(
58
+ pipeline,
59
+ { deviceJid: BOT_DEVICE_JID },
60
+ () => pairingMaterial,
61
+ );
62
+ const registeredPipeline = await nextPipelineWaiter;
63
+
64
+ return { client, registeredPipeline };
65
+ };
66
+
67
+ const waitFor = async <T>(
68
+ deadlineMs: number,
69
+ probe: () => T | null | Promise<T | null>,
70
+ ): Promise<T | null> => {
71
+ const deadline = Date.now() + deadlineMs;
72
+ let found: T | null = null;
73
+ while (Date.now() < deadline && !found) {
74
+ found = await probe();
75
+ if (!found) await new Promise((r) => setTimeout(r, 100));
76
+ }
77
+ return found;
78
+ };
79
+
80
+ const makeWebp = (size = 512): Promise<Buffer> =>
81
+ sharp({
82
+ create: { width: size, height: size, channels: 4, background: "#3080a0" },
83
+ })
84
+ .webp({ effort: 0 })
85
+ .toBuffer();
86
+
87
+ test(
88
+ "integration (fake-server): text, reaction, poll, contact, linkPreview, sticker, album lewat client asli",
89
+ { timeout: 180_000 },
90
+ async () => {
91
+ const server = await FakeWaServer.start();
92
+ let client: WaClient | null = null;
93
+
94
+ try {
95
+ const { client: waClient, registeredPipeline } =
96
+ await createPairedClient(server);
97
+ client = waClient;
98
+
99
+ const peer = await server.createFakePeer(
100
+ { jid: OWNER_JID, displayName: "Owner" },
101
+ registeredPipeline,
102
+ );
103
+ const incoming: WaIncomingMessageEvent[] = [];
104
+ void client.on("message", (event: WaIncomingMessageEvent) => {
105
+ incoming.push(event);
106
+ });
107
+
108
+ const session = server.sessionFor(registeredPipeline);
109
+ const captured: { node: BinaryNode; decrypted?: unknown }[] = [];
110
+ const stopCapture = session.onCapturedStanza((node: BinaryNode) => {
111
+ if (node.tag === "message") captured.push({ node });
112
+ });
113
+ const decryptCaptured = async (): Promise<DecryptedMessage[]> => {
114
+ const received: DecryptedMessage[] = [];
115
+ for (const entry of captured) {
116
+ if (entry.decrypted !== undefined) continue;
117
+ const result = await peer.decryptStanza(entry.node).catch(() => null);
118
+ entry.decrypted = result;
119
+ if (result) received.push(result as unknown as DecryptedMessage);
120
+ }
121
+ return received;
122
+ };
123
+ const findMessage = (
124
+ probe: (message: Record<string, unknown>) => boolean,
125
+ ): Promise<DecryptedMessage | null> =>
126
+ waitFor(15_000, async () => {
127
+ const list = await decryptCaptured();
128
+ return list.find((r) => probe(asRecord(r.message))) ?? null;
129
+ });
130
+
131
+ await peer.sendConversation("ping");
132
+ const peerEvent = await waitFor(15_000, () => {
133
+ const last = incoming[incoming.length - 1];
134
+ return last?.message?.conversation === "ping" ? last : null;
135
+ });
136
+ assert.ok(peerEvent, "pesan ping dari peer diterima client");
137
+
138
+ await client.text().body("halo dari builder").send(OWNER_JID);
139
+ const text = await findMessage(
140
+ (m) => m.conversation === "halo dari builder",
141
+ );
142
+ assert.ok(text, "conversation sampai ke peer");
143
+
144
+ await client.reaction().target(peerEvent).emoji("🔥").send();
145
+ const reaction = await findMessage((m) => {
146
+ const reactionMessage = asRecord(m.reactionMessage);
147
+ return (
148
+ reactionMessage.text === "🔥" &&
149
+ asRecord(reactionMessage.key).id === peerEvent.key.id
150
+ );
151
+ });
152
+ assert.ok(reaction, "reactionMessage menunjuk pesan peer");
153
+
154
+ await client
155
+ .poll()
156
+ .question("Pilih satu")
157
+ .options(["Nasi goreng", "Bakso"])
158
+ .send(OWNER_JID);
159
+ const poll = await findMessage((m) => {
160
+ const pollMessage = asRecord(
161
+ m.pollCreationMessageV3 ?? m.pollCreationMessage,
162
+ );
163
+ return pollMessage.name === "Pilih satu";
164
+ });
165
+ assert.ok(poll, "pollCreationMessage terkirim");
166
+ const pollMessage = asRecord(
167
+ asRecord(poll.message).pollCreationMessageV3 ??
168
+ asRecord(poll.message).pollCreationMessage,
169
+ );
170
+ assert.deepEqual(
171
+ (pollMessage.options as { optionName?: string }[] | undefined)?.map(
172
+ (o) => o?.optionName,
173
+ ),
174
+ ["Nasi goreng", "Bakso"],
175
+ );
176
+
177
+ await client
178
+ .contact()
179
+ .name("Budi Client")
180
+ .phone("+628123456789")
181
+ .send(OWNER_JID);
182
+ const contact = await findMessage((m) => {
183
+ return asRecord(m.contactMessage).displayName === "Budi Client";
184
+ });
185
+ assert.ok(contact, "contactMessage terkirim");
186
+ assert.match(
187
+ String(asRecord(asRecord(contact.message).contactMessage).vcard),
188
+ /BEGIN:VCARD/,
189
+ );
190
+ assert.match(
191
+ String(asRecord(asRecord(contact.message).contactMessage).vcard),
192
+ /TEL;type=CELL;type=VOICE:\+628123456789/,
193
+ );
194
+
195
+ await client
196
+ .linkPreview()
197
+ .body("baca https://example.com/docs ya")
198
+ .title("Dokumentasi")
199
+ .send(OWNER_JID);
200
+ const link = await findMessage((m) => {
201
+ const extended = asRecord(m.extendedTextMessage);
202
+ return (
203
+ extended.matchedText === "https://example.com/docs" &&
204
+ extended.title === "Dokumentasi"
205
+ );
206
+ });
207
+ assert.ok(link, "extendedTextMessage dengan preview terkirim");
208
+ assert.equal(
209
+ asRecord(asRecord(link.message).extendedTextMessage).previewType,
210
+ 5,
211
+ );
212
+
213
+ const webp = await makeWebp();
214
+ await client.sticker().source(webp).send(OWNER_JID);
215
+ const stickerMsg = await findMessage((m) => {
216
+ return asRecord(m.stickerMessage).mimetype === "image/webp";
217
+ });
218
+ assert.ok(stickerMsg, "stickerMessage terkirim");
219
+ const stickerPayload = asRecord(
220
+ asRecord(stickerMsg.message).stickerMessage,
221
+ );
222
+ assert.equal(stickerPayload.width, 512);
223
+ assert.equal(stickerPayload.height, 512);
224
+ assert.equal(stickerPayload.isAnimated, false);
225
+ assert.ok(stickerPayload.url, "url upload ada");
226
+
227
+ const png = await sharp({
228
+ create: { width: 100, height: 80, channels: 3, background: "#ff8020" },
229
+ })
230
+ .png()
231
+ .toBuffer();
232
+ const albumSend = (await client
233
+ .album()
234
+ .image(png)
235
+ .image(png)
236
+ .send(OWNER_JID)) as { id?: string };
237
+ assert.ok(albumSend?.id, "album send mengembalikan id");
238
+ const albumMsg = await findMessage((m) => !!m.albumMessage);
239
+ assert.ok(albumMsg, "albumMessage terkirim");
240
+ assert.deepEqual(
241
+ plain(asRecord(asRecord(albumMsg.message).albumMessage)),
242
+ {
243
+ expectedImageCount: 2,
244
+ expectedVideoCount: 0,
245
+ },
246
+ );
247
+
248
+ const albumChildren = await waitFor(20_000, () => {
249
+ void decryptCaptured();
250
+ const children = captured
251
+ .map((entry) => asRecord(entry.decrypted))
252
+ .filter((msg) => Object.keys(msg).length > 0 && msg.message)
253
+ .map((msg) => asRecord(msg.message))
254
+ .filter((message) => !!message.imageMessage);
255
+ return children.length >= 2 ? children : null;
256
+ });
257
+ assert.ok(albumChildren, "dua anak album terkirim");
258
+ for (const child of albumChildren) {
259
+ const contextInfo = asRecord(asRecord(child.imageMessage).contextInfo);
260
+ assert.equal(contextInfo.stanzaId, albumSend.id);
261
+ }
262
+
263
+ await client.forward().message(peerEvent).send(OWNER_JID);
264
+ const forwarded = await findMessage((m) => {
265
+ const extended = asRecord(m.extendedTextMessage);
266
+ return (
267
+ asRecord(extended.contextInfo).isForwarded === true &&
268
+ extended.text === "ping"
269
+ );
270
+ });
271
+ assert.ok(forwarded, "forward membawa contextInfo.isForwarded");
272
+ assert.equal(
273
+ asRecord(asRecord(forwarded.message).extendedTextMessage).text,
274
+ "ping",
275
+ );
276
+
277
+ stopCapture();
278
+ await client.disconnect();
279
+ } finally {
280
+ await client?.disconnect().catch(() => {});
281
+ await server.stop().catch(() => {});
282
+ }
283
+ },
284
+ );