@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,486 @@
1
+ import type { WaMediaUploadResult } from "zapo-js";
2
+ import type { ZapoClient } from "../zapo-client.js";
3
+ import type { MediaSlotResolution } from "../payloads.js";
4
+ import { MediaError, ValidationError } from "../core/errors.js";
5
+ import { createReadStream } from "node:fs";
6
+ import { basename } from "node:path";
7
+ import type { Readable } from "node:stream";
8
+ import { fileTypeFromFile } from "file-type";
9
+ import { getSharedMediaQueue } from "../media-gate.js";
10
+ import {
11
+ normalizeMediaSource,
12
+ sniffBytes,
13
+ readBoundedBytes,
14
+ readPathBounded,
15
+ UPLOAD_TYPE_BY_KIND,
16
+ type MediaKind,
17
+ type MediaSource,
18
+ type NormalizedMediaSource,
19
+ } from "./media-source.js";
20
+ import {
21
+ ensureJpegThumbnail,
22
+ generateImageThumbnail,
23
+ generatePngThumbnail,
24
+ probeImageDimensions,
25
+ } from "./thumbnail.js";
26
+ import { assertPositiveInt, assertText } from "./validators.js";
27
+ import { probeWebp, type WebpInfo } from "../message/webp.js";
28
+
29
+ const DISPLAY_FILENAME_MAX = 100;
30
+
31
+ export interface MediaSlotOptions {
32
+ mimetype?: string;
33
+ thumbnail?: Buffer | Uint8Array | false;
34
+ width?: number;
35
+ height?: number;
36
+ caption?: string;
37
+ seconds?: number;
38
+ fileName?: string;
39
+ title?: string;
40
+ ptt?: boolean;
41
+ waveform?: Uint8Array;
42
+ pngThumbnail?: Uint8Array | false;
43
+ isAnimated?: boolean;
44
+ stickerSentTs?: number;
45
+ }
46
+
47
+ export interface MediaSlot {
48
+ kind: MediaKind;
49
+ source: MediaSource;
50
+ options: MediaSlotOptions;
51
+ label: string;
52
+ normalized?: NormalizedMediaSource | undefined;
53
+ promise?: Promise<MediaSlotResolution> | undefined;
54
+ result?: MediaSlotResolution | undefined;
55
+ }
56
+
57
+ const uploadFailure = (label: string, error: unknown): MediaError => {
58
+ if (error instanceof MediaError) return error;
59
+ return new MediaError(`upload media header ${label} gagal`, {
60
+ cause: error,
61
+ kind: "upload_failed",
62
+ });
63
+ };
64
+
65
+ const KIND_MIME_PREFIX: Partial<Record<MediaKind, string>> = {
66
+ image: "image/",
67
+ video: "video/",
68
+ audio: "audio/",
69
+ };
70
+
71
+ const resolveMimetype = async (
72
+ source: NormalizedMediaSource,
73
+ kind: MediaKind,
74
+ options: MediaSlotOptions,
75
+ label: string,
76
+ bytes: Buffer | undefined,
77
+ ): Promise<string> => {
78
+ const explicit = options.mimetype;
79
+ if (
80
+ explicit !== undefined &&
81
+ (typeof explicit !== "string" || !explicit.trim())
82
+ ) {
83
+ throw new ValidationError(
84
+ `${label}.mimetype harus string mimetype, diterima ${JSON.stringify(explicit)}`,
85
+ );
86
+ }
87
+
88
+ if (kind === "sticker") {
89
+ if (explicit !== undefined && explicit !== "image/webp") {
90
+ throw new ValidationError(
91
+ `${label}.mimetype sticker harus "image/webp", diterima "${explicit}"`,
92
+ );
93
+ }
94
+ if (bytes) {
95
+ const sniffed = (await sniffBytes(bytes))?.mime;
96
+ if (sniffed && sniffed !== "image/webp") {
97
+ throw new ValidationError(
98
+ `isi sumber ${label} terdeteksi "${sniffed}" — sticker harus WebP`,
99
+ );
100
+ }
101
+ if (!sniffed && !isWebpHeader(bytes)) {
102
+ throw new ValidationError(
103
+ `isi sumber ${label} bukan WebP — sticker harus file .webp`,
104
+ );
105
+ }
106
+ }
107
+ return "image/webp";
108
+ }
109
+
110
+ let sniffed: string | undefined;
111
+ if (bytes) sniffed = (await sniffBytes(bytes))?.mime;
112
+ else if (source.kind === "path") {
113
+ try {
114
+ sniffed = (await fileTypeFromFile(source.path))?.mime;
115
+ } catch (error) {
116
+ throw new MediaError(`deteksi tipe file gagal untuk ${label}`, {
117
+ cause: error,
118
+ });
119
+ }
120
+ }
121
+
122
+ if (explicit) {
123
+ const prefix = KIND_MIME_PREFIX[kind];
124
+ if (prefix && !explicit.startsWith(prefix)) {
125
+ throw new ValidationError(
126
+ `${label}.mimetype "${explicit}" tidak cocok untuk header ${kind} (harus ${prefix}*)`,
127
+ );
128
+ }
129
+ if (sniffed && sniffed !== explicit) {
130
+ throw new ValidationError(
131
+ `${label}.mimetype "${explicit}" bertentangan dengan hasil deteksi isi file "${sniffed}"`,
132
+ );
133
+ }
134
+ return explicit;
135
+ }
136
+
137
+ if (sniffed) {
138
+ const prefix = KIND_MIME_PREFIX[kind];
139
+ if (prefix && !sniffed.startsWith(prefix)) {
140
+ throw new ValidationError(
141
+ `isi sumber ${label} terdeteksi "${sniffed}" — bukan ${kind} yang valid`,
142
+ );
143
+ }
144
+ return sniffed;
145
+ }
146
+
147
+ if (kind === "document") return "application/octet-stream";
148
+
149
+ throw new ValidationError(
150
+ `mimetype ${label} tidak diketahui — sumber ${source.kind} tidak bisa dideteksi isinya, berikan options.mimetype`,
151
+ );
152
+ };
153
+
154
+ const resolveThumbnail = async (
155
+ bytes: Buffer | undefined,
156
+ kind: MediaKind,
157
+ options: MediaSlotOptions,
158
+ label: string,
159
+ ): Promise<Buffer | undefined> => {
160
+ if (options.thumbnail === false) return undefined;
161
+ if (options.thumbnail !== undefined && options.thumbnail !== null) {
162
+ return ensureJpegThumbnail(options.thumbnail, {
163
+ label: `${label}.thumbnail`,
164
+ });
165
+ }
166
+ if (kind === "image" && bytes) {
167
+ return generateImageThumbnail(bytes, {
168
+ label: `${label} (thumbnail otomatis)`,
169
+ });
170
+ }
171
+ if (kind === "sticker" && bytes) {
172
+ return generatePngThumbnail(bytes, {
173
+ label: `${label} (thumbnail otomatis)`,
174
+ });
175
+ }
176
+ return undefined;
177
+ };
178
+
179
+ const isWebpHeader = (bytes: Uint8Array): boolean =>
180
+ probeWebp(bytes) !== undefined;
181
+
182
+ const assertDimension = (
183
+ value: number | undefined,
184
+ label: string,
185
+ ): number | undefined => {
186
+ if (value === undefined) return undefined;
187
+ return assertPositiveInt(value, label, { min: 1 });
188
+ };
189
+
190
+ interface MediaProtoInput {
191
+ uploaded: {
192
+ url: string;
193
+ directPath: string;
194
+ mediaKey: Uint8Array;
195
+ fileSha256: Uint8Array;
196
+ fileEncSha256: Uint8Array;
197
+ fileLength: number;
198
+ mediaKeyTimestamp: number;
199
+ streamingSidecar?: Uint8Array;
200
+ };
201
+ mimetype: string;
202
+ kind: MediaKind;
203
+ options: MediaSlotOptions;
204
+ dimensions: { width: number; height: number } | undefined;
205
+ webp: WebpInfo | undefined;
206
+ thumbnail: Buffer | undefined;
207
+ label: string;
208
+ normalized: NormalizedMediaSource;
209
+ }
210
+
211
+ const mediaProtoFields = ({
212
+ uploaded,
213
+ mimetype,
214
+ kind,
215
+ options,
216
+ dimensions,
217
+ webp,
218
+ thumbnail,
219
+ label,
220
+ normalized,
221
+ }: MediaProtoInput): MediaSlotResolution => {
222
+ const base = {
223
+ url: uploaded.url,
224
+ mimetype,
225
+ fileSha256: uploaded.fileSha256,
226
+ fileEncSha256: uploaded.fileEncSha256,
227
+ fileLength: uploaded.fileLength,
228
+ mediaKey: uploaded.mediaKey,
229
+ directPath: uploaded.directPath,
230
+ mediaKeyTimestamp: uploaded.mediaKeyTimestamp,
231
+ };
232
+
233
+ if (kind === "image") {
234
+ const width =
235
+ assertDimension(options.width, `${label}.width`) ?? dimensions?.width;
236
+ const height =
237
+ assertDimension(options.height, `${label}.height`) ?? dimensions?.height;
238
+ const caption =
239
+ options.caption !== undefined
240
+ ? assertText(options.caption, `${label}.caption`, { required: false })
241
+ : undefined;
242
+ return {
243
+ field: "imageMessage",
244
+ message: {
245
+ ...base,
246
+ ...(width !== undefined ? { width } : {}),
247
+ ...(height !== undefined ? { height } : {}),
248
+ ...(thumbnail ? { jpegThumbnail: thumbnail } : {}),
249
+ ...(caption !== undefined ? { caption } : {}),
250
+ },
251
+ };
252
+ }
253
+
254
+ if (kind === "video") {
255
+ const seconds =
256
+ options.seconds === undefined
257
+ ? undefined
258
+ : assertPositiveInt(options.seconds, `${label}.seconds`, { min: 0 });
259
+ const width = assertDimension(options.width, `${label}.width`);
260
+ const height = assertDimension(options.height, `${label}.height`);
261
+ return {
262
+ field: "videoMessage",
263
+ message: {
264
+ ...base,
265
+ ...(seconds !== undefined ? { seconds } : {}),
266
+ ...(width !== undefined ? { width } : {}),
267
+ ...(height !== undefined ? { height } : {}),
268
+ ...(thumbnail ? { jpegThumbnail: thumbnail } : {}),
269
+ ...(uploaded.streamingSidecar
270
+ ? { streamingSidecar: uploaded.streamingSidecar }
271
+ : {}),
272
+ },
273
+ };
274
+ }
275
+
276
+ if (kind === "audio") {
277
+ const seconds =
278
+ options.seconds === undefined
279
+ ? undefined
280
+ : assertPositiveInt(options.seconds, `${label}.seconds`, { min: 0 });
281
+ return {
282
+ field: "audioMessage",
283
+ message: {
284
+ ...base,
285
+ ...(seconds !== undefined ? { seconds } : {}),
286
+ ...(options.ptt === true ? { ptt: true } : {}),
287
+ ...(options.waveform !== undefined
288
+ ? { waveform: options.waveform }
289
+ : {}),
290
+ ...(uploaded.streamingSidecar
291
+ ? { streamingSidecar: uploaded.streamingSidecar }
292
+ : {}),
293
+ },
294
+ };
295
+ }
296
+
297
+ if (kind === "sticker") {
298
+ const probed = webp;
299
+ const width =
300
+ assertDimension(options.width, `${label}.width`) ?? probed?.width;
301
+ const height =
302
+ assertDimension(options.height, `${label}.height`) ?? probed?.height;
303
+ const pngThumbnail =
304
+ options.pngThumbnail === false
305
+ ? undefined
306
+ : options.pngThumbnail !== undefined
307
+ ? options.pngThumbnail
308
+ : thumbnail;
309
+ const animated = options.isAnimated ?? probed?.isAnimated ?? false;
310
+ return {
311
+ field: "stickerMessage",
312
+ message: {
313
+ ...base,
314
+ ...(width !== undefined ? { width } : {}),
315
+ ...(height !== undefined ? { height } : {}),
316
+ ...(pngThumbnail !== undefined ? { pngThumbnail } : {}),
317
+ isAnimated: animated,
318
+ ...(options.stickerSentTs !== undefined
319
+ ? { stickerSentTs: options.stickerSentTs }
320
+ : {}),
321
+ },
322
+ };
323
+ }
324
+
325
+ const title =
326
+ options.title !== undefined
327
+ ? assertText(options.title, `${label}.title`, { required: false })
328
+ : undefined;
329
+ return {
330
+ field: "documentMessage",
331
+ message: {
332
+ ...base,
333
+ fileName: resolveDocumentFileName(options, normalized, label),
334
+ ...(title !== undefined ? { title } : {}),
335
+ ...(thumbnail ? { jpegThumbnail: thumbnail } : {}),
336
+ },
337
+ };
338
+ };
339
+
340
+ const resolveDocumentFileName = (
341
+ options: MediaSlotOptions,
342
+ normalized: NormalizedMediaSource,
343
+ label: string,
344
+ ): string => {
345
+ if (options.fileName !== undefined) {
346
+ return assertText(options.fileName, `${label}.fileName`, {
347
+ max: DISPLAY_FILENAME_MAX,
348
+ });
349
+ }
350
+ if (normalized.kind === "path") return basename(normalized.path);
351
+ throw new ValidationError(
352
+ `${label} document butuh fileName — berikan options.fileName (sumber bukan path tidak bisa menebak nama file)`,
353
+ );
354
+ };
355
+
356
+ export const resolveMediaSlot = async (
357
+ client: ZapoClient,
358
+ slot: MediaSlot,
359
+ ): Promise<MediaSlotResolution> => {
360
+ const { kind, options = {}, label } = slot;
361
+ const uploadType =
362
+ kind === "audio" && options.ptt === true
363
+ ? "ptt"
364
+ : UPLOAD_TYPE_BY_KIND[kind];
365
+ const queue = getSharedMediaQueue();
366
+
367
+ if (!slot.normalized) {
368
+ try {
369
+ slot.normalized = await normalizeMediaSource(slot.source, { label });
370
+ } catch (error) {
371
+ throw new MediaError(`sumber media ${label} tidak bisa dipakai`, {
372
+ cause: error,
373
+ kind: "source_invalid",
374
+ });
375
+ }
376
+ }
377
+ const normalized = slot.normalized;
378
+
379
+ try {
380
+ return await queue.run(
381
+ async ({ maxBytes, noteBytes }) => {
382
+ let bytes: Buffer | undefined;
383
+ if (normalized.kind === "bytes") {
384
+ bytes = normalized.bytes;
385
+ } else if (normalized.kind === "stream" && normalized.streamConsumed) {
386
+ throw new MediaError(
387
+ "stream sumber media sudah dikonsumsi sekali dan tidak bisa dipakai ulang — sumber stream hanya mendukung satu upload",
388
+ { kind: "stream_consumed" },
389
+ );
390
+ } else if (kind === "image" || kind === "sticker") {
391
+ bytes =
392
+ normalized.kind === "path"
393
+ ? await readPathBounded(normalized.path, maxBytes, label)
394
+ : normalized.kind === "stream"
395
+ ? await readBoundedBytes(normalized.stream, maxBytes, label)
396
+ : undefined;
397
+ if (normalized.kind === "stream") normalized.streamConsumed = true;
398
+ }
399
+
400
+ const mimetype = await resolveMimetype(
401
+ normalized,
402
+ kind,
403
+ options,
404
+ label,
405
+ bytes,
406
+ );
407
+
408
+ const thumbnail = await resolveThumbnail(bytes, kind, options, label);
409
+ const dimensions =
410
+ bytes && kind === "image"
411
+ ? await probeImageDimensions(bytes)
412
+ : undefined;
413
+ const webp = bytes && kind === "sticker" ? probeWebp(bytes) : undefined;
414
+
415
+ let input: Buffer | Uint8Array | Readable;
416
+ if (bytes) {
417
+ if (bytes.byteLength > maxBytes) {
418
+ throw new MediaError(
419
+ `media ${label} melebihi batas ukuran (${bytes.byteLength} > ${maxBytes} byte)`,
420
+ { kind: "oversized" },
421
+ );
422
+ }
423
+ input = bytes;
424
+ } else if (normalized.kind === "path") {
425
+ input = createReadStream(normalized.path);
426
+ } else if (normalized.kind === "stream") {
427
+ normalized.streamConsumed = true;
428
+ input = normalized.stream;
429
+ } else {
430
+ throw new MediaError(`media ${label} tidak punya sumber input`, {
431
+ kind: "source_invalid",
432
+ });
433
+ }
434
+
435
+ const upload = client.message.upload;
436
+ if (typeof upload !== "function") {
437
+ throw uploadFailure(
438
+ label,
439
+ new TypeError("client.message.upload is not a function"),
440
+ );
441
+ }
442
+
443
+ let uploaded: WaMediaUploadResult | undefined;
444
+ try {
445
+ uploaded = await upload.call(client.message, input, {
446
+ type: uploadType,
447
+ mimetype,
448
+ });
449
+ } catch (error) {
450
+ throw uploadFailure(label, error);
451
+ }
452
+ if (!uploaded || typeof uploaded !== "object" || !uploaded.url) {
453
+ throw new MediaError(
454
+ `uploader mengembalikan hasil tidak valid untuk ${label} — UploadResult.url wajib ada`,
455
+ { kind: "upload_invalid" },
456
+ );
457
+ }
458
+ const normalizedByteSize =
459
+ normalized.kind === "bytes" || normalized.kind === "path"
460
+ ? normalized.byteSize
461
+ : undefined;
462
+ noteBytes(Number(uploaded.fileLength) || normalizedByteSize || 0);
463
+
464
+ return mediaProtoFields({
465
+ uploaded,
466
+ mimetype,
467
+ kind,
468
+ options,
469
+ dimensions,
470
+ webp,
471
+ thumbnail,
472
+ label,
473
+ normalized,
474
+ });
475
+ },
476
+ { label: `btn-media:${label}` },
477
+ );
478
+ } catch (error) {
479
+ if (error instanceof MediaError || error instanceof ValidationError)
480
+ throw error;
481
+ throw new MediaError(`pemrosesan media header ${label} gagal`, {
482
+ cause: error,
483
+ kind: "media_failed",
484
+ });
485
+ }
486
+ };
@@ -0,0 +1,189 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
+ import type { Readable } from "node:stream";
4
+ import { fileTypeFromBuffer, fileTypeFromFile } from "file-type";
5
+ import { MediaError, ValidationError } from "../core/errors.js";
6
+
7
+ export type MediaSource = Buffer | Uint8Array | string | Readable;
8
+
9
+ export const UPLOAD_TYPE_BY_KIND: Record<
10
+ "image" | "video" | "document" | "audio" | "sticker",
11
+ "image" | "video" | "document" | "audio" | "sticker"
12
+ > = {
13
+ image: "image",
14
+ video: "video",
15
+ document: "document",
16
+ audio: "audio",
17
+ sticker: "sticker",
18
+ };
19
+
20
+ export type MediaKind = "image" | "video" | "document" | "audio" | "sticker";
21
+
22
+ export interface NormalizedBytesSource {
23
+ kind: "bytes";
24
+ bytes: Buffer;
25
+ byteSize: number;
26
+ }
27
+
28
+ export interface NormalizedPathSource {
29
+ kind: "path";
30
+ path: string;
31
+ byteSize: number;
32
+ }
33
+
34
+ export interface NormalizedStreamSource {
35
+ kind: "stream";
36
+ stream: Readable;
37
+ streamConsumed?: boolean;
38
+ }
39
+
40
+ export type NormalizedMediaSource =
41
+ NormalizedBytesSource | NormalizedPathSource | NormalizedStreamSource;
42
+
43
+ export interface NormalizedMediaSourceOptions {
44
+ label?: string;
45
+ }
46
+
47
+ const isReadableStream = (value: unknown): value is Readable =>
48
+ !!value &&
49
+ typeof value === "object" &&
50
+ typeof (value as Readable).pipe === "function" &&
51
+ typeof (value as Readable).read === "function";
52
+
53
+ export const isReadableStreamSource = isReadableStream;
54
+
55
+ export const bufferFromBytes = (bytes: Uint8Array): Buffer => {
56
+ if (Buffer.isBuffer(bytes)) return bytes;
57
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
58
+ };
59
+
60
+ export const sniffBytes = async (
61
+ bytes: Uint8Array,
62
+ ): Promise<{ ext: string; mime: string } | undefined> => {
63
+ try {
64
+ return await fileTypeFromBuffer(bytes);
65
+ } catch (error) {
66
+ throw new MediaError("deteksi tipe file dari bytes gagal", {
67
+ cause: error,
68
+ });
69
+ }
70
+ };
71
+
72
+ export const sniffFile = async (
73
+ path: string,
74
+ ): Promise<{ ext: string; mime: string } | undefined> => {
75
+ try {
76
+ return await fileTypeFromFile(path);
77
+ } catch (error) {
78
+ throw new MediaError(`deteksi tipe file gagal untuk ${path}`, {
79
+ cause: error,
80
+ });
81
+ }
82
+ };
83
+
84
+ export const readBoundedBytes = async (
85
+ stream: Readable,
86
+ maxBytes: number,
87
+ label: string,
88
+ ): Promise<Buffer> => {
89
+ const chunks: Buffer[] = [];
90
+ let total = 0;
91
+ try {
92
+ for await (const chunk of stream) {
93
+ const part = Buffer.isBuffer(chunk)
94
+ ? chunk
95
+ : Buffer.from(chunk as Uint8Array | string);
96
+ total += part.byteLength;
97
+ if (total > maxBytes) {
98
+ stream.destroy?.();
99
+ throw new MediaError(
100
+ `media ${label} melebihi batas ukuran (${total} > ${maxBytes} byte)`,
101
+ { kind: "oversized" },
102
+ );
103
+ }
104
+ chunks.push(part);
105
+ }
106
+ } catch (error) {
107
+ if (error instanceof MediaError) throw error;
108
+ throw new MediaError(`gagal membaca stream ${label}`, { cause: error });
109
+ }
110
+ return Buffer.concat(chunks);
111
+ };
112
+
113
+ export const readPathBounded = async (
114
+ path: string,
115
+ maxBytes: number,
116
+ label: string,
117
+ ): Promise<Buffer> => {
118
+ let info;
119
+ try {
120
+ info = await stat(path);
121
+ } catch (error) {
122
+ throw new ValidationError(
123
+ `file sumber media ${label} tidak ditemukan: ${path}`,
124
+ { cause: error },
125
+ );
126
+ }
127
+ if (!info.isFile())
128
+ throw new ValidationError(`sumber media ${label} bukan file: ${path}`);
129
+ if (info.size > maxBytes) {
130
+ throw new MediaError(
131
+ `media ${label} melebihi batas ukuran (${info.size} > ${maxBytes} byte)`,
132
+ { kind: "oversized" },
133
+ );
134
+ }
135
+ try {
136
+ return await readFile(path);
137
+ } catch (error) {
138
+ throw new MediaError(`gagal membaca file ${label}: ${path}`, {
139
+ cause: error,
140
+ });
141
+ }
142
+ };
143
+
144
+ export const normalizeMediaSource = async (
145
+ source: MediaSource | unknown,
146
+ { label = "media" }: NormalizedMediaSourceOptions = {},
147
+ ): Promise<NormalizedMediaSource> => {
148
+ if (
149
+ source === undefined ||
150
+ source === null ||
151
+ (typeof source === "string" && source.trim() === "")
152
+ ) {
153
+ throw new ValidationError(
154
+ `sumber ${label} kosong — butuh Buffer, Uint8Array, path file, atau Readable stream`,
155
+ );
156
+ }
157
+
158
+ if (Buffer.isBuffer(source)) {
159
+ return { kind: "bytes", bytes: source, byteSize: source.byteLength };
160
+ }
161
+
162
+ if (source instanceof Uint8Array) {
163
+ const bytes = bufferFromBytes(source);
164
+ return { kind: "bytes", bytes, byteSize: bytes.byteLength };
165
+ }
166
+
167
+ if (typeof source === "string") {
168
+ let info;
169
+ try {
170
+ info = await stat(source);
171
+ } catch (error) {
172
+ throw new ValidationError(
173
+ `file sumber ${label} tidak ditemukan: ${source}`,
174
+ { cause: error },
175
+ );
176
+ }
177
+ if (!info.isFile())
178
+ throw new ValidationError(`sumber ${label} bukan file: ${source}`);
179
+ return { kind: "path", path: source, byteSize: info.size };
180
+ }
181
+
182
+ if (isReadableStream(source)) {
183
+ return { kind: "stream", stream: source };
184
+ }
185
+
186
+ throw new ValidationError(
187
+ `sumber ${label} tidak valid: ${typeof source} — didukung Buffer, Uint8Array, path file, atau Readable stream`,
188
+ );
189
+ };
@@ -0,0 +1,23 @@
1
+ export type SharpModule = typeof import("sharp").default;
2
+
3
+ let cached: SharpModule | null | undefined;
4
+
5
+ export const SHARP_INSTALL_HINT =
6
+ "sharp tidak tersedia — instal sharp (peer dependency opsional) untuk pemrosesan gambar otomatis";
7
+
8
+ export const loadSharp = async (): Promise<SharpModule | null> => {
9
+ if (cached !== undefined) return cached;
10
+ try {
11
+ const mod = await import("sharp");
12
+ cached = mod.default ?? null;
13
+ } catch {
14
+ cached = null;
15
+ }
16
+ return cached;
17
+ };
18
+
19
+ export const resetSharpCache = (): void => {
20
+ cached = undefined;
21
+ };
22
+
23
+ export const isSharpCached = (): boolean => cached !== undefined;