@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,182 @@
1
+ import { bufferFromBytes } from "./media-source.js";
2
+ import { loadSharp, SHARP_INSTALL_HINT } from "./sharp-loader.js";
3
+ import { MediaError, ValidationError } from "../core/errors.js";
4
+
5
+ export const THUMBNAIL_MAX_DIMENSION = 240;
6
+ export const THUMBNAIL_MAX_BYTES = 100 * 1024;
7
+ export const THUMBNAIL_JPEG_QUALITY = 72;
8
+
9
+ const JPEG_MAGIC: readonly [number, number, number] = [0xff, 0xd8, 0xff];
10
+
11
+ export const isJpegBytes = (bytes: Uint8Array | null | undefined): boolean => {
12
+ if (!bytes || bytes.byteLength < 3) return false;
13
+ return (
14
+ bytes[0] === JPEG_MAGIC[0] &&
15
+ bytes[1] === JPEG_MAGIC[1] &&
16
+ bytes[2] === JPEG_MAGIC[2]
17
+ );
18
+ };
19
+
20
+ export const asThumbnailBytes = (bytes: unknown): Uint8Array => {
21
+ if (!Buffer.isBuffer(bytes) && !(bytes instanceof Uint8Array)) {
22
+ throw new ValidationError(
23
+ `thumbnail butuh Buffer atau Uint8Array, diterima ${typeof bytes}`,
24
+ );
25
+ }
26
+ if (!bytes.byteLength) {
27
+ throw new ValidationError("thumbnail kosong (0 byte)");
28
+ }
29
+ return bytes;
30
+ };
31
+
32
+ export interface ThumbnailLabelOptions {
33
+ label?: string;
34
+ }
35
+
36
+ export const ensureJpegThumbnail = async (
37
+ bytes: unknown,
38
+ { label = "thumbnail" }: ThumbnailLabelOptions = {},
39
+ ): Promise<Buffer> => {
40
+ const input = asThumbnailBytes(bytes);
41
+ if (isJpegBytes(input)) return bufferFromBytes(input);
42
+
43
+ const sharp = await loadSharp();
44
+ if (!sharp) {
45
+ throw new ValidationError(
46
+ `${label} bukan JPEG valid dan ${SHARP_INSTALL_HINT}`,
47
+ { kind: "not_jpeg" },
48
+ );
49
+ }
50
+ try {
51
+ return await sharp(input)
52
+ .jpeg({ quality: THUMBNAIL_JPEG_QUALITY })
53
+ .toBuffer();
54
+ } catch (error) {
55
+ throw new ValidationError(
56
+ `${label} bukan JPEG valid dan gagal dikonversi ke JPEG — berikan JPEG asli atau gambar yang bisa diproses Sharp`,
57
+ { cause: error, kind: "not_jpeg" },
58
+ );
59
+ }
60
+ };
61
+
62
+ export const validateJpegThumbnail = (
63
+ bytes: unknown,
64
+ { label = "thumbnail" }: ThumbnailLabelOptions = {},
65
+ ): Buffer => {
66
+ const input = asThumbnailBytes(bytes);
67
+ if (!isJpegBytes(input)) {
68
+ throw new ValidationError(
69
+ `${label} harus JPEG valid (magic bytes FFD8FF) — diterima ${describeBytes(input)}`,
70
+ { kind: "not_jpeg" },
71
+ );
72
+ }
73
+ return bufferFromBytes(input);
74
+ };
75
+
76
+ export interface GenerateThumbnailOptions extends ThumbnailLabelOptions {
77
+ maxDimension?: number;
78
+ quality?: number;
79
+ }
80
+
81
+ export const generateImageThumbnail = async (
82
+ bytes: unknown,
83
+ {
84
+ label = "thumbnail",
85
+ maxDimension = THUMBNAIL_MAX_DIMENSION,
86
+ quality = THUMBNAIL_JPEG_QUALITY,
87
+ }: GenerateThumbnailOptions = {},
88
+ ): Promise<Buffer> => {
89
+ const input = asThumbnailBytes(bytes);
90
+ const sharp = await loadSharp();
91
+ if (!sharp) {
92
+ throw new MediaError(
93
+ `generasi thumbnail otomatis ${label} gagal — ${SHARP_INSTALL_HINT}`,
94
+ { kind: "thumbnail_failed" },
95
+ );
96
+ }
97
+ try {
98
+ const thumbnail = await sharp(input)
99
+ .resize({
100
+ width: maxDimension,
101
+ height: maxDimension,
102
+ fit: "inside",
103
+ withoutEnlargement: true,
104
+ })
105
+ .jpeg({ quality })
106
+ .toBuffer();
107
+
108
+ if (thumbnail.byteLength > THUMBNAIL_MAX_BYTES) {
109
+ throw new MediaError(
110
+ `thumbnail ${label} terlalu besar setelah kompresi (${thumbnail.byteLength} > ${THUMBNAIL_MAX_BYTES} byte)`,
111
+ { kind: "thumbnail_oversized" },
112
+ );
113
+ }
114
+ return thumbnail;
115
+ } catch (error) {
116
+ if (error instanceof MediaError) throw error;
117
+ throw new MediaError(
118
+ `generasi thumbnail otomatis ${label} gagal — sumber bukan gambar yang bisa diproses Sharp`,
119
+ { cause: error, kind: "thumbnail_failed" },
120
+ );
121
+ }
122
+ };
123
+
124
+ export interface ImageDimensions {
125
+ width: number;
126
+ height: number;
127
+ }
128
+
129
+ export const probeImageDimensions = async (
130
+ bytes: unknown,
131
+ ): Promise<ImageDimensions | undefined> => {
132
+ const input = asThumbnailBytes(bytes);
133
+ const sharp = await loadSharp();
134
+ if (!sharp) return undefined;
135
+ try {
136
+ const metadata = await sharp(input).metadata();
137
+ const width = Number.isFinite(metadata.width) ? metadata.width : undefined;
138
+ const height = Number.isFinite(metadata.height)
139
+ ? metadata.height
140
+ : undefined;
141
+ if (width && height) return { width, height };
142
+ return undefined;
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ };
147
+
148
+ export const generatePngThumbnail = async (
149
+ bytes: unknown,
150
+ {
151
+ label = "thumbnail",
152
+ maxDimension = THUMBNAIL_MAX_DIMENSION,
153
+ }: GenerateThumbnailOptions = {},
154
+ ): Promise<Buffer | undefined> => {
155
+ const input = asThumbnailBytes(bytes);
156
+ const sharp = await loadSharp();
157
+ if (!sharp) return undefined;
158
+ try {
159
+ const thumbnail = await sharp(input)
160
+ .resize({
161
+ width: maxDimension,
162
+ height: maxDimension,
163
+ fit: "inside",
164
+ withoutEnlargement: true,
165
+ })
166
+ .png({ compressionLevel: 9 })
167
+ .toBuffer();
168
+ if (thumbnail.byteLength > THUMBNAIL_MAX_BYTES) return undefined;
169
+ return thumbnail;
170
+ } catch {
171
+ return undefined;
172
+ }
173
+ };
174
+
175
+ const describeBytes = (bytes: Uint8Array): string => {
176
+ if (bytes.byteLength < 3)
177
+ return `bytes terlalu pendek (${bytes.byteLength} byte)`;
178
+ const hex = [...bytes.slice(0, 3)]
179
+ .map((b) => b.toString(16).padStart(2, "0"))
180
+ .join(" ");
181
+ return `bytes dengan magic ${hex}`;
182
+ };
@@ -0,0 +1,237 @@
1
+ import { ValidationError, DuplicateIdError } from "../core/errors.js";
2
+
3
+ export const DISPLAY_TEXT_MAX = 200;
4
+ export const BUTTON_ID_MAX = 256;
5
+ export const SELECT_TITLE_MAX = 100;
6
+ export const COPY_CODE_MAX = 50;
7
+ export const ROW_DESCRIPTION_MAX = 200;
8
+ export const LEGACY_BUTTON_LIMIT = 3;
9
+ export const LIST_SECTION_LIMIT = 10;
10
+ export const LIST_ROWS_PER_SECTION_LIMIT = 100;
11
+
12
+ export interface AssertTextOptions {
13
+ max?: number;
14
+ required?: boolean;
15
+ }
16
+
17
+ export function assertText(
18
+ value: unknown,
19
+ label: string,
20
+ options: { max?: number; required: false },
21
+ ): string | undefined;
22
+ export function assertText(
23
+ value: unknown,
24
+ label: string,
25
+ options?: { max?: number; required?: boolean },
26
+ ): string;
27
+ export function assertText(
28
+ value: unknown,
29
+ label: string,
30
+ { max = DISPLAY_TEXT_MAX, required = true }: AssertTextOptions = {},
31
+ ): string | undefined {
32
+ if (value === undefined || value === null || value === "") {
33
+ if (required)
34
+ throw new ValidationError(`${label} wajib diisi (string non-kosong)`);
35
+ return undefined;
36
+ }
37
+ if (typeof value !== "string")
38
+ throw new ValidationError(
39
+ `${label} harus string, diterima ${typeof value}`,
40
+ );
41
+ if (required && value.trim() === "")
42
+ throw new ValidationError(`${label} wajib diisi (string non-kosong)`);
43
+ if (value.length > max)
44
+ throw new ValidationError(
45
+ `${label} melebihi batas ${max} karakter (${value.length})`,
46
+ );
47
+ return value;
48
+ }
49
+
50
+ export const assertId = (value: unknown, label: string = "id"): string => {
51
+ if (
52
+ value === undefined ||
53
+ value === null ||
54
+ typeof value !== "string" ||
55
+ value === ""
56
+ ) {
57
+ throw new ValidationError(`${label} wajib diisi (string non-kosong)`);
58
+ }
59
+ if (value.length > BUTTON_ID_MAX) {
60
+ throw new ValidationError(
61
+ `${label} melebihi batas ${BUTTON_ID_MAX} karakter (${value.length})`,
62
+ );
63
+ }
64
+ return value;
65
+ };
66
+
67
+ export const assertUniqueId = (ids: Set<string>, id: string): string => {
68
+ if (ids.has(id)) throw new DuplicateIdError(id);
69
+ ids.add(id);
70
+ return id;
71
+ };
72
+
73
+ export const assertUrl = (value: unknown, label: string = "url"): string => {
74
+ if (
75
+ value === undefined ||
76
+ value === null ||
77
+ typeof value !== "string" ||
78
+ value.trim() === ""
79
+ ) {
80
+ throw new ValidationError(`${label} wajib diisi (string URL)`);
81
+ }
82
+ let parsed: URL;
83
+ try {
84
+ parsed = new URL(value);
85
+ } catch {
86
+ throw new ValidationError(`${label} bukan URL valid: "${value}"`);
87
+ }
88
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
89
+ throw new ValidationError(
90
+ `${label} harus http/https, diterima "${parsed.protocol}"`,
91
+ );
92
+ }
93
+ return value;
94
+ };
95
+
96
+ export const assertPhoneNumber = (
97
+ value: unknown,
98
+ label: string = "nomor telepon",
99
+ ): string => {
100
+ if (
101
+ value === undefined ||
102
+ value === null ||
103
+ typeof value !== "string" ||
104
+ value.trim() === ""
105
+ ) {
106
+ throw new ValidationError(`${label} wajib diisi (string nomor)`);
107
+ }
108
+ if (!/^\+?[1-9]\d{6,14}$/.test(value)) {
109
+ throw new ValidationError(
110
+ `${label} tidak valid (format E.164, 7-15 digit): "${value}"`,
111
+ );
112
+ }
113
+ return value;
114
+ };
115
+
116
+ export interface AssertPositiveIntOptions {
117
+ min?: number;
118
+ }
119
+
120
+ export const assertPositiveInt = (
121
+ value: unknown,
122
+ label: string,
123
+ { min = 1 }: AssertPositiveIntOptions = {},
124
+ ): number => {
125
+ if (
126
+ typeof value !== "number" ||
127
+ !Number.isFinite(value) ||
128
+ value < min ||
129
+ !Number.isInteger(value)
130
+ ) {
131
+ throw new ValidationError(
132
+ `${label} harus integer >= ${min}, diterima ${value}`,
133
+ );
134
+ }
135
+ return value;
136
+ };
137
+
138
+ export interface NativeSectionRow {
139
+ id: string;
140
+ title: string;
141
+ description?: string;
142
+ header?: string;
143
+ }
144
+
145
+ export interface NativeSection {
146
+ title?: string;
147
+ rows: NativeSectionRow[];
148
+ }
149
+
150
+ export const validateNativeSections = (
151
+ sections: unknown,
152
+ label: string = "sections",
153
+ ): NativeSection[] => {
154
+ if (!Array.isArray(sections) || sections.length === 0) {
155
+ throw new ValidationError(
156
+ `${label} harus array berisi minimal satu section`,
157
+ );
158
+ }
159
+ if (sections.length > LIST_SECTION_LIMIT) {
160
+ throw new ValidationError(
161
+ `${label} melebihi batas ${LIST_SECTION_LIMIT} section (${sections.length})`,
162
+ );
163
+ }
164
+
165
+ const rowIds = new Set<string>();
166
+ sections.forEach((section: unknown, sectionIndex: number) => {
167
+ if (!section || typeof section !== "object" || Array.isArray(section)) {
168
+ throw new ValidationError(
169
+ `${label}[${sectionIndex}] harus object section`,
170
+ );
171
+ }
172
+ const record = section as Record<string, unknown>;
173
+ assertText(record.title, `${label}[${sectionIndex}].title`, {
174
+ max: SELECT_TITLE_MAX,
175
+ required: false,
176
+ });
177
+ if (!Array.isArray(record.rows) || record.rows.length === 0) {
178
+ throw new ValidationError(
179
+ `${label}[${sectionIndex}].rows harus array berisi minimal satu row`,
180
+ );
181
+ }
182
+ if (record.rows.length > LIST_ROWS_PER_SECTION_LIMIT) {
183
+ throw new ValidationError(
184
+ `${label}[${sectionIndex}].rows melebihi batas ${LIST_ROWS_PER_SECTION_LIMIT} row (${record.rows.length})`,
185
+ );
186
+ }
187
+ record.rows.forEach((row: unknown, rowIndex: number) => {
188
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
189
+ throw new ValidationError(
190
+ `${label}[${sectionIndex}].rows[${rowIndex}] harus object row`,
191
+ );
192
+ }
193
+ const rowRecord = row as Record<string, unknown>;
194
+ const rowId = assertId(
195
+ rowRecord.id,
196
+ `${label}[${sectionIndex}].rows[${rowIndex}].id`,
197
+ );
198
+ assertText(
199
+ rowRecord.title,
200
+ `${label}[${sectionIndex}].rows[${rowIndex}].title`,
201
+ );
202
+ assertText(
203
+ rowRecord.description,
204
+ `${label}[${sectionIndex}].rows[${rowIndex}].description`,
205
+ { max: ROW_DESCRIPTION_MAX, required: false },
206
+ );
207
+ assertText(
208
+ rowRecord.header,
209
+ `${label}[${sectionIndex}].rows[${rowIndex}].header`,
210
+ { required: false },
211
+ );
212
+ if (rowIds.has(rowId)) throw new DuplicateIdError(rowId);
213
+ rowIds.add(rowId);
214
+ });
215
+ });
216
+ return sections as NativeSection[];
217
+ };
218
+
219
+ export const stringifyParams = (
220
+ params: unknown,
221
+ label: string = "buttonParamsJson",
222
+ ): string => {
223
+ let json: string | undefined;
224
+ try {
225
+ json = JSON.stringify(params);
226
+ } catch (error) {
227
+ throw new ValidationError(`${label} gagal diserialisasi ke JSON`, {
228
+ cause: error,
229
+ });
230
+ }
231
+ if (json === undefined) {
232
+ throw new ValidationError(
233
+ `${label} menghasilkan undefined — parameter mengandung nilai yang tidak bisa diserialisasi`,
234
+ );
235
+ }
236
+ return json;
237
+ };
package/src/btn.ts ADDED
@@ -0,0 +1,8 @@
1
+ export {
2
+ Button,
3
+ LegacyButton,
4
+ ListMessage,
5
+ button,
6
+ legacyButton,
7
+ listMessage,
8
+ } from "./btn/builders.js";
@@ -0,0 +1,28 @@
1
+ import type { BaseBuilder } from "./base-builder.js";
2
+ import type { ZapoMessageContent } from "../zapo-client.js";
3
+ import type { MessageSendResult } from "../zapo-client.js";
4
+
5
+ export interface MessageSendOptions {
6
+ quote?: unknown;
7
+ mentions?: readonly string[];
8
+ contextInfo?: Record<string, unknown>;
9
+ forward?: boolean | { score?: number };
10
+ id?: string;
11
+ expirationSeconds?: number;
12
+ additionalAttributes?: Readonly<Record<string, string>>;
13
+ viewOnce?: boolean;
14
+ messageSecret?: Uint8Array;
15
+ ackTimeoutMs?: number;
16
+ maxAttempts?: number;
17
+ retryDelayMs?: number;
18
+ }
19
+
20
+ export const sendConfigured = async <TBuild extends ZapoMessageContent>(
21
+ builder: BaseBuilder<TBuild>,
22
+ jid: string | undefined,
23
+ options: MessageSendOptions | undefined,
24
+ ): Promise<MessageSendResult> =>
25
+ (await builder.send(
26
+ jid,
27
+ (options ?? {}) as Record<string, unknown>,
28
+ )) as MessageSendResult;
@@ -0,0 +1,104 @@
1
+ import { MessageError } from "./errors.js";
2
+ import type {
3
+ ZapoClient,
4
+ ZapoMessageContent,
5
+ ZapoSendOptions,
6
+ } from "../zapo-client.js";
7
+ import type { BuilderMessagePayload } from "../payloads.js";
8
+
9
+ export const isClient = (value: unknown): value is ZapoClient =>
10
+ typeof (value as ZapoClient | null | undefined)?.message?.send === "function";
11
+
12
+ export type SendResolutionArg = ZapoClient | Record<string, unknown>;
13
+
14
+ export class BaseBuilder<
15
+ TBuild extends ZapoMessageContent = BuilderMessagePayload,
16
+ > {
17
+ #client: ZapoClient | undefined;
18
+ #defaultJid: string | undefined;
19
+ #defaultQuote: unknown;
20
+
21
+ constructor(client?: ZapoClient) {
22
+ if (client !== undefined) this.use(client);
23
+ }
24
+
25
+ use(client: ZapoClient): this {
26
+ if (!isClient(client))
27
+ throw new TypeError(
28
+ "client harus WaClient zapo-js (punya client.message.send)",
29
+ );
30
+ this.#client = client;
31
+ return this;
32
+ }
33
+
34
+ get client(): ZapoClient | undefined {
35
+ return this.#client;
36
+ }
37
+
38
+ defaultTo(jid: string | undefined): this {
39
+ if (jid !== undefined && (typeof jid !== "string" || !jid)) {
40
+ throw new TypeError("defaultTo() butuh jid string");
41
+ }
42
+ this.#defaultJid = jid;
43
+ return this;
44
+ }
45
+
46
+ to(jid: string | undefined): this {
47
+ return this.defaultTo(jid);
48
+ }
49
+
50
+ defaultQuote(ref: unknown): this {
51
+ this.#defaultQuote = ref;
52
+ return this;
53
+ }
54
+
55
+ protected _defaultTarget(): string | undefined {
56
+ return this.#defaultJid;
57
+ }
58
+
59
+ build(): TBuild | Promise<TBuild> {
60
+ throw new MessageError(
61
+ `${this.constructor.name}.build() belum diimplementasi`,
62
+ "NOT_IMPLEMENTED",
63
+ );
64
+ }
65
+
66
+ protected _resolve(arg?: SendResolutionArg): {
67
+ client: ZapoClient;
68
+ options: Record<string, unknown>;
69
+ } {
70
+ const resolved: Record<string, unknown> = isClient(arg)
71
+ ? { client: arg as unknown }
72
+ : ((arg ?? {}) as Record<string, unknown>);
73
+ const { client: resolvedClient, ...options } = resolved;
74
+ const client =
75
+ resolvedClient === undefined
76
+ ? this.#client
77
+ : (resolvedClient as ZapoClient);
78
+ if (!client) throw new MessageError("client belum diset", "NO_CLIENT");
79
+ return { client, options };
80
+ }
81
+
82
+ async send(jid?: string, arg?: SendResolutionArg): Promise<unknown> {
83
+ const { client, options } = this._resolve(arg);
84
+
85
+ const target = typeof jid === "string" && jid ? jid : this.#defaultJid;
86
+ if (!target) {
87
+ throw new MessageError(
88
+ "tujuan tidak diketahui. panggil send(jid), .defaultTo(jid), atau buat lewat ctx.button()/ctx.list()",
89
+ "NO_TARGET",
90
+ );
91
+ }
92
+
93
+ const merged: Record<string, unknown> =
94
+ this.#defaultQuote !== undefined && options.quote === undefined
95
+ ? { quote: this.#defaultQuote, ...options }
96
+ : options;
97
+
98
+ const content = await this.build();
99
+ const send = client.message.send.bind(client.message);
100
+ return Object.keys(merged).length
101
+ ? send(target, content as ZapoMessageContent, merged as ZapoSendOptions)
102
+ : send(target, content as ZapoMessageContent);
103
+ }
104
+ }
@@ -0,0 +1,82 @@
1
+ export interface MessageErrorMeta {
2
+ [key: string]: unknown;
3
+ }
4
+
5
+ export class MessageError extends Error {
6
+ code: string;
7
+
8
+ constructor(
9
+ message: string,
10
+ code: string = "MESSAGE_ERROR",
11
+ meta: MessageErrorMeta = {},
12
+ ) {
13
+ super(message);
14
+ this.name = new.target.name;
15
+ this.code = code;
16
+ Object.assign(this, meta);
17
+ }
18
+ }
19
+
20
+ export class ValidationError extends MessageError {
21
+ constructor(message: string, meta: MessageErrorMeta = {}) {
22
+ super(message, "VALIDATION", meta);
23
+ }
24
+ }
25
+
26
+ export class ItemNotFoundError extends MessageError {
27
+ declare readonly id: string | number;
28
+ declare readonly availableIds: string[];
29
+
30
+ constructor(id: string | number, availableIds: string[] = []) {
31
+ const hint = availableIds.length
32
+ ? ` (tersedia: ${availableIds.join(", ")})`
33
+ : " (belum ada item yang punya id)";
34
+ super(`item "${id}" ga ketemu${hint}`, "ITEM_NOT_FOUND", {
35
+ id,
36
+ availableIds,
37
+ });
38
+ }
39
+ }
40
+
41
+ export class DuplicateIdError extends MessageError {
42
+ declare readonly id: string;
43
+
44
+ constructor(id: string) {
45
+ super(`id "${id}" udah dipake`, "DUPLICATE_ID", { id });
46
+ }
47
+ }
48
+
49
+ export class MediaError extends MessageError {
50
+ constructor(message: string, meta: MessageErrorMeta = {}) {
51
+ super(message, "MEDIA", meta);
52
+ if (meta.cause !== undefined) this.cause = meta.cause;
53
+ else if (meta.originalError !== undefined) this.cause = meta.originalError;
54
+ }
55
+ }
56
+
57
+ export class InvalidTargetError extends MessageError {
58
+ constructor(message: string, meta: MessageErrorMeta = {}) {
59
+ super(message, "INVALID_TARGET", meta);
60
+ }
61
+ }
62
+
63
+ export class ProtocolSendError extends MessageError {
64
+ declare readonly stage: string;
65
+ declare readonly placeholderId: string | undefined;
66
+
67
+ constructor(stage: string, meta: MessageErrorMeta = {}) {
68
+ const detail =
69
+ stage === "edit"
70
+ ? `edit AIRich gagal setelah placeholder terkirim (placeholderId: ${meta.placeholderId})`
71
+ : stage === "validate_id"
72
+ ? "transport Zapo tidak mengembalikan ID pesan yang valid; edit dibatalkan"
73
+ : stage === "album_id"
74
+ ? "pengiriman album gagal — id pesan album tidak tersedia dari hasil send"
75
+ : "pengiriman placeholder AIRich gagal";
76
+ super(detail, "PROTOCOL_SEND", { stage, ...meta });
77
+ this.stage = stage;
78
+ if (meta.cause !== undefined) this.cause = meta.cause;
79
+ if (meta.placeholderId !== undefined)
80
+ this.placeholderId = meta.placeholderId as string;
81
+ }
82
+ }