@kyyinfinite/zapo-message 0.0.0-stage → 1.0.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.
Files changed (191) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/LICENSE +20 -0
  3. package/README.md +1401 -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 +36 -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,342 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import sharp from "sharp";
7
+ import { proto } from "zapo-js";
8
+ import type { WaMediaUploadResult } from "zapo-js";
9
+
10
+ import { legacyButton } from "@kyyinfinite/zapo-message";
11
+ import {
12
+ ValidationError,
13
+ DuplicateIdError,
14
+ MediaError,
15
+ } from "@kyyinfinite/zapo-message";
16
+ import { asClient } from "./helpers.js";
17
+
18
+ const makeJpeg = async ({
19
+ width = 700,
20
+ height = 500,
21
+ }: { width?: number; height?: number } = {}) =>
22
+ sharp({ create: { width, height, channels: 3, background: "#ff9020" } })
23
+ .jpeg({ quality: 85 })
24
+ .toBuffer();
25
+
26
+ const makeUploadClient = ({
27
+ uploadImpl,
28
+ }: {
29
+ uploadImpl?: (
30
+ source: unknown,
31
+ options: Record<string, unknown>,
32
+ ) => Promise<WaMediaUploadResult>;
33
+ } = {}) => {
34
+ const uploads: { source: unknown; options: Record<string, unknown> }[] = [];
35
+ const client = {
36
+ message: {
37
+ async upload(
38
+ source: unknown,
39
+ options: Record<string, unknown>,
40
+ ): Promise<WaMediaUploadResult> {
41
+ uploads.push({ source, options });
42
+ if (uploadImpl) return uploadImpl(source, options);
43
+ const bytes = source instanceof Uint8Array ? source.byteLength : 1024;
44
+ return {
45
+ url: "https://mmg.whatsapp.net/v/t62.7118-24/legacy-fake",
46
+ directPath: "/v/t62.7118-24/legacy-fake",
47
+ mediaKey: new Uint8Array(32).fill(4),
48
+ fileSha256: new Uint8Array(32).fill(5),
49
+ fileEncSha256: new Uint8Array(32).fill(6),
50
+ fileLength: bytes,
51
+ mediaKeyTimestamp: 1730000000,
52
+ };
53
+ },
54
+ async send() {
55
+ return { id: "FAKE", attempts: 1, ack: {} };
56
+ },
57
+ },
58
+ };
59
+ return { client: asClient(client), uploads };
60
+ };
61
+
62
+ const sendOnlyClient = () =>
63
+ asClient({
64
+ message: {
65
+ async send() {
66
+ return { id: "X" };
67
+ },
68
+ },
69
+ });
70
+
71
+ test("legacy: payload dasar — contentText, buttons, headerType EMPTY", async () => {
72
+ const result = await legacyButton(sendOnlyClient())
73
+ .body("Konten")
74
+ .footer("Footer")
75
+ .button("btn1", "Tombol Satu")
76
+ .button("btn2", "Tombol Dua")
77
+ .build();
78
+
79
+ const msg = result.buttonsMessage;
80
+ assert.equal(msg.contentText, "Konten");
81
+ assert.equal(msg.footerText, "Footer");
82
+ assert.equal(msg.headerType, 1);
83
+ assert.equal(msg.buttons.length, 2);
84
+ assert.deepEqual(msg.buttons[0], {
85
+ buttonId: "btn1",
86
+ buttonText: { displayText: "Tombol Satu" },
87
+ type: 1,
88
+ });
89
+ });
90
+
91
+ test("legacy: image attachment — headerType IMAGE dan imageMessage terisi", async () => {
92
+ const jpeg = await makeJpeg();
93
+ const { client, uploads } = makeUploadClient();
94
+ const result = await legacyButton(client)
95
+ .body("Dengan gambar")
96
+ .image(jpeg)
97
+ .button("btn1", "Tombol")
98
+ .build();
99
+
100
+ const msg = result.buttonsMessage;
101
+ assert.equal(msg.headerType, 4);
102
+ assert.ok(msg.imageMessage);
103
+ assert.equal(
104
+ msg.imageMessage?.url,
105
+ "https://mmg.whatsapp.net/v/t62.7118-24/legacy-fake",
106
+ );
107
+ assert.equal(msg.imageMessage?.mimetype, "image/jpeg");
108
+ assert.equal(msg.imageMessage?.fileLength, jpeg.byteLength);
109
+ assert.ok(msg.imageMessage?.jpegThumbnail);
110
+ assert.equal(msg.videoMessage, undefined);
111
+ assert.equal(uploads.length, 1);
112
+ assert.equal(
113
+ (uploads[0] as { options: Record<string, unknown> }).options.type,
114
+ "image",
115
+ );
116
+ });
117
+
118
+ test("legacy: video attachment — headerType VIDEO", async () => {
119
+ const { client } = makeUploadClient();
120
+ const result = await legacyButton(client)
121
+ .video(Buffer.alloc(512, 3), { mimetype: "video/mp4", seconds: 45 })
122
+ .button("btn1", "Tombol")
123
+ .build();
124
+
125
+ const msg = result.buttonsMessage;
126
+ assert.equal(msg.headerType, 5);
127
+ assert.equal(msg.videoMessage?.mimetype, "video/mp4");
128
+ assert.equal(msg.videoMessage?.seconds, 45);
129
+ assert.equal(msg.imageMessage, undefined);
130
+ });
131
+
132
+ test("legacy: document attachment — headerType DOCUMENT, fileName dari options", async () => {
133
+ const { client } = makeUploadClient();
134
+ const result = await legacyButton(client)
135
+ .document(Buffer.from("%PDF-1.4 doc"), {
136
+ mimetype: "application/pdf",
137
+ fileName: "Manual.pdf",
138
+ })
139
+ .button("btn1", "Tombol")
140
+ .build();
141
+
142
+ const msg = result.buttonsMessage;
143
+ assert.equal(msg.headerType, 3);
144
+ assert.equal(msg.documentMessage?.fileName, "Manual.pdf");
145
+ assert.equal(msg.documentMessage?.mimetype, "application/pdf");
146
+ });
147
+
148
+ test("legacy: document dari path — fileName default dari basename", async (t) => {
149
+ const dir = await mkdtemp(join(tmpdir(), "zapo-message-btn-legacy-"));
150
+ t.after(() => rm(dir, { recursive: true, force: true }));
151
+ const file = join(dir, "panduan.pdf");
152
+ await writeFile(file, Buffer.from("%PDF-1.4"));
153
+
154
+ const { client } = makeUploadClient();
155
+ const result = await legacyButton(client)
156
+ .document(file)
157
+ .button("btn1", "Tombol")
158
+ .build();
159
+ assert.equal(result.buttonsMessage.documentMessage?.fileName, "panduan.pdf");
160
+ });
161
+
162
+ test("legacy: document tanpa fileName dan bukan path → error jelas", async () => {
163
+ const { client } = makeUploadClient();
164
+ await assert.rejects(
165
+ async () =>
166
+ legacyButton(client)
167
+ .document(Buffer.from("%PDF"), { mimetype: "application/pdf" })
168
+ .button("b", "B")
169
+ .build(),
170
+ (error: Error) =>
171
+ error instanceof ValidationError && /fileName/.test(error.message),
172
+ );
173
+ });
174
+
175
+ test("legacy: location header + thumb tetap bekerja (kompatibilitas lama)", async () => {
176
+ const thumb = await makeJpeg({ width: 60, height: 60 });
177
+ const result = await legacyButton(sendOnlyClient())
178
+ .location({
179
+ latitude: -6.2,
180
+ longitude: 106.816666,
181
+ name: "HQ",
182
+ address: "Alamat",
183
+ })
184
+ .thumb(thumb)
185
+ .button("test_loc_btn_legacy", "Tombol Lokasi")
186
+ .build();
187
+
188
+ const msg = result.buttonsMessage;
189
+ assert.equal(msg.headerType, 6);
190
+ assert.equal(msg.locationMessage?.degreesLatitude, -6.2);
191
+ assert.equal(msg.locationMessage?.degreesLongitude, 106.816666);
192
+ assert.equal(msg.locationMessage?.name, "HQ");
193
+ assert.deepEqual(
194
+ [...(msg.locationMessage?.jpegThumbnail as Uint8Array)],
195
+ [...thumb],
196
+ );
197
+ });
198
+
199
+ test("legacy: headerThumbnail ditolak dengan pesan jelas (tidak ada field proto-nya)", async () => {
200
+ const jpeg = await makeJpeg({ width: 50, height: 50 });
201
+ assert.throws(
202
+ () => legacyButton(sendOnlyClient()).headerThumbnail(jpeg),
203
+ (error: Error) =>
204
+ error instanceof ValidationError &&
205
+ /tidak mendukung \.headerThumbnail\(\)/.test(error.message),
206
+ );
207
+ });
208
+
209
+ test("legacy: duplikat buttonId → DuplicateIdError", async () => {
210
+ await assert.rejects(
211
+ async () =>
212
+ legacyButton(sendOnlyClient())
213
+ .button("dup", "A")
214
+ .button("dup", "B")
215
+ .build(),
216
+ (error: Error & { id?: string }) =>
217
+ error instanceof DuplicateIdError && error.id === "dup",
218
+ );
219
+ });
220
+
221
+ test("legacy: lebih dari 3 button ditolak", async () => {
222
+ await assert.rejects(
223
+ async () =>
224
+ legacyButton(sendOnlyClient())
225
+ .button("b1", "Satu")
226
+ .button("b2", "Dua")
227
+ .button("b3", "Tiga")
228
+ .button("b4", "Empat")
229
+ .build(),
230
+ (error: Error) =>
231
+ error instanceof ValidationError && /maksimal 3/.test(error.message),
232
+ );
233
+ });
234
+
235
+ test("legacy: tanpa button → ValidationError", async () => {
236
+ await assert.rejects(
237
+ async () => legacyButton(sendOnlyClient()).body("kosong").build(),
238
+ /minimal satu button/,
239
+ );
240
+ });
241
+
242
+ test("legacy: title tanpa media → headerType TEXT + field text", async () => {
243
+ const result = await legacyButton(sendOnlyClient())
244
+ .title("Judul Legacy")
245
+ .button("b1", "Tombol")
246
+ .build();
247
+ assert.equal(result.buttonsMessage.headerType, 2);
248
+ assert.equal(result.buttonsMessage.text, "Judul Legacy");
249
+ });
250
+
251
+ test("legacy: title + image bersama — text tetap terisi, headerType IMAGE", async () => {
252
+ const { client } = makeUploadClient();
253
+ const result = await legacyButton(client)
254
+ .title("Judul")
255
+ .image(await makeJpeg({ width: 100, height: 100 }))
256
+ .button("b1", "Tombol")
257
+ .build();
258
+ assert.equal(result.buttonsMessage.headerType, 4);
259
+ assert.equal(result.buttonsMessage.text, "Judul");
260
+ assert.ok(result.buttonsMessage.imageMessage);
261
+ });
262
+
263
+ test("legacy: media vs location konflik ditolak", async () => {
264
+ const { client } = makeUploadClient();
265
+ await assert.rejects(
266
+ async () =>
267
+ legacyButton(client)
268
+ .location({ latitude: 0, longitude: 0 })
269
+ .image(await makeJpeg({ width: 50, height: 50 }))
270
+ .button("b", "B")
271
+ .build(),
272
+ /satu jenis konten/,
273
+ );
274
+ });
275
+
276
+ test("legacy: legacy_loc_thumb — pola pemanggil plugin lama tetap jalan", async () => {
277
+ const thumb = await makeJpeg({ width: 100, height: 100 });
278
+ const result = await legacyButton(sendOnlyClient())
279
+ .location({ latitude: -6.2, longitude: 106.816666 })
280
+ .thumb(thumb)
281
+ .button("btnv2_1", "Tombol 1")
282
+ .button("btnv2_2", "Tombol 2")
283
+ .build();
284
+
285
+ assert.equal(result.buttonsMessage.headerType, 6);
286
+ assert.equal(result.buttonsMessage.buttons.length, 2);
287
+ assert.deepEqual(
288
+ result.buttonsMessage.buttons.map((b) => b.buttonId),
289
+ ["btnv2_1", "btnv2_2"],
290
+ );
291
+ });
292
+
293
+ test("legacy: upload gagal → MediaError dengan cause asli", async () => {
294
+ const failure = new Error("upload legacy gagal");
295
+ const { client } = makeUploadClient({
296
+ uploadImpl: async () => {
297
+ throw failure;
298
+ },
299
+ });
300
+ await assert.rejects(
301
+ async () =>
302
+ legacyButton(client)
303
+ .image(await makeJpeg({ width: 50, height: 50 }))
304
+ .button("b", "B")
305
+ .build(),
306
+ (error: Error & { cause?: unknown }) =>
307
+ error instanceof MediaError && error.cause === failure,
308
+ );
309
+ });
310
+
311
+ test("legacy: payload round-trip protobuf", async () => {
312
+ const jpeg = await makeJpeg({ width: 300, height: 300 });
313
+ const { client } = makeUploadClient();
314
+ const result = await legacyButton(client)
315
+ .body("Konten Legacy")
316
+ .footer("Footer Legacy")
317
+ .image(jpeg)
318
+ .button("b1", "Satu")
319
+ .button("b2", "Dua")
320
+ .build();
321
+
322
+ const wire = proto.Message.encode(result).finish();
323
+ const decoded = proto.Message.decode(wire);
324
+
325
+ const msg = decoded.buttonsMessage as NonNullable<
326
+ typeof decoded.buttonsMessage
327
+ >;
328
+ assert.equal(msg?.headerType, 4);
329
+ assert.equal(msg?.contentText, "Konten Legacy");
330
+ assert.equal(msg?.footerText, "Footer Legacy");
331
+ assert.equal(msg?.imageMessage?.mimetype, "image/jpeg");
332
+ assert.deepEqual(
333
+ [...(msg?.imageMessage?.mediaKey as Uint8Array)],
334
+ new Array(32).fill(4),
335
+ );
336
+ assert.deepEqual(
337
+ (msg?.buttons ?? []).map((b) => b.buttonId),
338
+ ["b1", "b2"],
339
+ );
340
+ assert.equal((msg?.buttons ?? [])[0]?.buttonText?.displayText, "Satu");
341
+ assert.equal((msg?.buttons ?? [])[0]?.type, 1);
342
+ });
@@ -0,0 +1,295 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { Readable } from "node:stream";
4
+ import sharp from "sharp";
5
+ import { proto } from "zapo-js";
6
+ import type { WaMediaUploadResult } from "zapo-js";
7
+
8
+ import { button, legacyButton } from "@kyyinfinite/zapo-message";
9
+ import { MediaError, ValidationError } from "@kyyinfinite/zapo-message";
10
+ import { asClient, first } from "./helpers.js";
11
+
12
+ const makeJpeg = async ({
13
+ width = 600,
14
+ height = 400,
15
+ }: { width?: number; height?: number } = {}) =>
16
+ sharp({ create: { width, height, channels: 3, background: "#123456" } })
17
+ .jpeg({ quality: 80 })
18
+ .toBuffer();
19
+
20
+ const makeClient = ({
21
+ uploadImpl,
22
+ }: {
23
+ uploadImpl?: (
24
+ source: unknown,
25
+ options: Record<string, unknown>,
26
+ ) => Promise<WaMediaUploadResult>;
27
+ } = {}) => {
28
+ const uploads: { source: unknown; options: Record<string, unknown> }[] = [];
29
+ const sends: { jid?: unknown; content?: unknown; options?: unknown }[] = [];
30
+ return {
31
+ uploads,
32
+ sends,
33
+ client: asClient({
34
+ message: {
35
+ async upload(
36
+ source: unknown,
37
+ options: Record<string, unknown>,
38
+ ): Promise<WaMediaUploadResult> {
39
+ uploads.push({ source, options });
40
+ if (uploadImpl) return uploadImpl(source, options);
41
+ const bytes = source instanceof Uint8Array ? source.byteLength : 0;
42
+ return {
43
+ url: "https://mmg.whatsapp.net/v/t62.7118-24/lifecycle",
44
+ directPath: "/v/t62.7118-24/lifecycle",
45
+ mediaKey: new Uint8Array(32).fill(7),
46
+ fileSha256: new Uint8Array(32).fill(8),
47
+ fileEncSha256: new Uint8Array(32).fill(9),
48
+ fileLength: bytes,
49
+ mediaKeyTimestamp: 1730000000,
50
+ };
51
+ },
52
+ async send(jid: unknown, content: unknown, options: unknown) {
53
+ sends.push({ jid, content, options });
54
+ return { id: "FAKE", attempts: 1, ack: {} };
55
+ },
56
+ },
57
+ }),
58
+ };
59
+ };
60
+
61
+ test("lifecycle: repeated build hanya satu upload", async () => {
62
+ const jpeg = await makeJpeg();
63
+ const { client, uploads } = makeClient();
64
+ const builder = button(client).image(jpeg).quick_reply("QR", "qr1");
65
+
66
+ const first = await builder.build();
67
+ const second = await builder.build();
68
+ const third = await builder.build();
69
+
70
+ assert.equal(uploads.length, 1);
71
+ const firstKey = (
72
+ (first.interactiveMessage.header as Record<string, unknown>)
73
+ .imageMessage as Record<string, unknown>
74
+ ).mediaKey;
75
+ const secondKey = (
76
+ (second.interactiveMessage.header as Record<string, unknown>)
77
+ .imageMessage as Record<string, unknown>
78
+ ).mediaKey;
79
+ assert.deepEqual(
80
+ [...(firstKey as Uint8Array)],
81
+ [...(secondKey as Uint8Array)],
82
+ );
83
+ assert.equal(
84
+ (
85
+ (third.interactiveMessage.header as Record<string, unknown>)
86
+ .imageMessage as Record<string, unknown>
87
+ ).url,
88
+ (
89
+ (first.interactiveMessage.header as Record<string, unknown>)
90
+ .imageMessage as Record<string, unknown>
91
+ ).url,
92
+ );
93
+ });
94
+
95
+ test("lifecycle: build tidak mengubah konfigurasi internal", async () => {
96
+ const { client } = makeClient();
97
+ const builder = button(client)
98
+ .title("Judul")
99
+ .body("Isi")
100
+ .footer("F")
101
+ .quick_reply("QR", "qr1")
102
+ .cta_url("U", "https://example.com")
103
+ .bottom_sheet({ limit: 3 });
104
+
105
+ const snapshot = JSON.stringify({
106
+ buttons: builder._buttons,
107
+ params: builder._params,
108
+ title: builder._title,
109
+ body: builder._body,
110
+ footer: builder._footer,
111
+ });
112
+
113
+ await builder.build();
114
+ await builder.build();
115
+
116
+ const after = JSON.stringify({
117
+ buttons: builder._buttons,
118
+ params: builder._params,
119
+ title: builder._title,
120
+ body: builder._body,
121
+ footer: builder._footer,
122
+ });
123
+ assert.equal(after, snapshot);
124
+ });
125
+
126
+ test("lifecycle: upload gagal → cache dibersihkan, retry bisa sukses", async () => {
127
+ const jpeg = await makeJpeg();
128
+ let attempts = 0;
129
+ const { client } = makeClient({
130
+ uploadImpl: async () => {
131
+ attempts++;
132
+ if (attempts === 1) throw new Error("sementara gagal");
133
+ return {
134
+ url: "https://mmg.whatsapp.net/retry-ok",
135
+ directPath: "/retry-ok",
136
+ mediaKey: new Uint8Array(32).fill(1),
137
+ fileSha256: new Uint8Array(32).fill(1),
138
+ fileEncSha256: new Uint8Array(32).fill(1),
139
+ fileLength: 10,
140
+ mediaKeyTimestamp: 1730000000,
141
+ };
142
+ },
143
+ });
144
+
145
+ const builder = button(client).image(jpeg).quick_reply("QR", "qr1");
146
+ await assert.rejects(
147
+ async () => builder.build(),
148
+ /upload media header.*gagal/,
149
+ );
150
+ const result = await builder.build();
151
+ assert.equal(
152
+ (
153
+ (result.interactiveMessage.header as Record<string, unknown>)
154
+ .imageMessage as Record<string, unknown>
155
+ ).url,
156
+ "https://mmg.whatsapp.net/retry-ok",
157
+ );
158
+ assert.equal(attempts, 2);
159
+ });
160
+
161
+ test("lifecycle: error saat build tidak meninggalkan state rusak", async () => {
162
+ const { client } = makeClient();
163
+ const builder = button(client)
164
+ .image(Buffer.from("bukan gambar"))
165
+ .quick_reply("QR", "qr1")
166
+ .cta_url("U", "https://example.com");
167
+
168
+ await assert.rejects(
169
+ async () => builder.build(),
170
+ (error: Error) =>
171
+ error instanceof MediaError || error instanceof ValidationError,
172
+ );
173
+ assert.equal(builder._buttons.length, 2);
174
+ assert.equal(builder._mediaSlot?.kind, "image");
175
+ assert.equal(builder._mediaSlot?.promise, undefined);
176
+
177
+ const { client: goodClient } = makeClient();
178
+ const healthy = button(goodClient).quick_reply("QR", "qr2");
179
+ const payload = await healthy.build();
180
+ assert.ok(
181
+ (payload.interactiveMessage.nativeFlowMessage.buttons as unknown[])
182
+ .length === 1,
183
+ );
184
+ });
185
+
186
+ test("lifecycle: stream dikonsumsi sekali — retry stream mati memberi error jelas", async () => {
187
+ const jpeg = await makeJpeg({ width: 200, height: 200 });
188
+ const { client } = makeClient({
189
+ uploadImpl: async () => {
190
+ throw new Error("putus koneksi");
191
+ },
192
+ });
193
+ const builder = button(client)
194
+ .image(Readable.from([jpeg]))
195
+ .quick_reply("QR", "qr1");
196
+
197
+ await assert.rejects(async () => builder.build());
198
+ await assert.rejects(
199
+ async () => builder.build(),
200
+ (error: Error) =>
201
+ /sudah dikonsumsi sekali|bukan gambar/.test(error.message),
202
+ );
203
+ });
204
+
205
+ test("lifecycle: tidak ada field internal/undefined bocor ke payload", async () => {
206
+ const jpeg = await makeJpeg();
207
+ const { client } = makeClient();
208
+ const result = await button(client)
209
+ .title("Judul")
210
+ .body("Isi")
211
+ .footer("Footer")
212
+ .image(jpeg, { thumbnail: false })
213
+ .quick_reply("QR", "qr1")
214
+ .build();
215
+
216
+ const wire = proto.Message.encode(result).finish();
217
+ const text = Buffer.from(wire).toString("latin1");
218
+ assert.ok(!text.includes("__id"));
219
+ assert.ok(!text.includes("_internal"));
220
+
221
+ const json = JSON.stringify(result, (_key, value) =>
222
+ value === undefined ? "__UNDEFINED__" : value,
223
+ );
224
+ assert.ok(!json.includes("__UNDEFINED__"));
225
+ });
226
+
227
+ test("lifecycle: send memakai build payload dan meneruskan options", async () => {
228
+ const jpeg = await makeJpeg();
229
+ const { client, sends } = makeClient();
230
+ const quote = { key: { id: "Q9" } };
231
+ await button(client)
232
+ .image(jpeg)
233
+ .quick_reply("QR", "qr1")
234
+ .send("628123456789@s.whatsapp.net", { quote });
235
+
236
+ const firstSend = sends[0] as {
237
+ jid?: unknown;
238
+ content?: unknown;
239
+ options?: unknown;
240
+ };
241
+ assert.equal(sends.length, 1);
242
+ assert.equal(firstSend.jid, "628123456789@s.whatsapp.net");
243
+ assert.ok(
244
+ (
245
+ (firstSend.content as Record<string, unknown>)
246
+ .interactiveMessage as Record<string, unknown>
247
+ ).header,
248
+ );
249
+ assert.deepEqual(firstSend.options, { quote });
250
+ });
251
+
252
+ test("lifecycle: offer expiration stabil dihitung pada build pertama", async () => {
253
+ const { client } = makeClient();
254
+ const builder = button(client)
255
+ .quick_reply("QR", "qr1")
256
+ .limited_time_offer({ copyCode: "LTO", expiresIn: 3600 });
257
+ const first = JSON.parse(
258
+ (await builder.build()).interactiveMessage.nativeFlowMessage
259
+ .messageParamsJson as string,
260
+ ).limited_time_offer;
261
+ const second = JSON.parse(
262
+ (await builder.build()).interactiveMessage.nativeFlowMessage
263
+ .messageParamsJson as string,
264
+ ).limited_time_offer;
265
+ assert.equal(first.expiration_time, second.expiration_time);
266
+ assert.ok(
267
+ Math.abs(first.expiration_time - (Math.floor(Date.now() / 1000) + 3600)) <
268
+ 5,
269
+ );
270
+ });
271
+
272
+ test("lifecycle: LegacyButton repeated build juga satu upload", async () => {
273
+ const jpeg = await makeJpeg();
274
+ const { client, uploads } = makeClient();
275
+ const builder = legacyButton(client).image(jpeg).button("b1", "Satu");
276
+ await builder.build();
277
+ await builder.build();
278
+ assert.equal(uploads.length, 1);
279
+ });
280
+
281
+ test("lifecycle: payload tanpa header tetap valid saat hanya tombol", async () => {
282
+ const { client } = makeClient();
283
+ const result = await button(client)
284
+ .body("Cuma tombol")
285
+ .quick_reply("QR", "qr1")
286
+ .build();
287
+ assert.equal(result.interactiveMessage.header, undefined);
288
+ assert.equal(
289
+ (result.interactiveMessage.body as Record<string, unknown>).text,
290
+ "Cuma tombol",
291
+ );
292
+
293
+ const decoded = proto.Message.decode(proto.Message.encode(result).finish());
294
+ assert.ok(!decoded.interactiveMessage?.header);
295
+ });