@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,548 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { proto } from "zapo-js";
3
+ import { BaseBuilder } from "../core/base-builder.js";
4
+ import { sendConfigured } from "../core/async-send.js";
5
+ import { ValidationError, ItemNotFoundError, InvalidTargetError, } from "../core/errors.js";
6
+ import { parseInline } from "./inline.js";
7
+ import { toTable } from "./table.js";
8
+ import { tokenizeCode } from "./tokenizer.js";
9
+ import { NodeStore } from "./nodes.js";
10
+ import { decodeUnifiedResponse } from "./encode.js";
11
+ import { filterContextInfo, buildContextInfo, } from "./context.js";
12
+ import { layout, wrapBotForwarded, buildRichResponse, buildPlaceholderContent, buildEditContent, } from "./protocol.js";
13
+ import { sendViaZapo, sendPlaceholderThenEdit } from "./transport.js";
14
+ import { sourceSection, imageSection, videoSection, footerActionSection, widgetSection, productSection, postSection, reelsSection, htmlSection, } from "./primitives.js";
15
+ const assertString = (value, name) => {
16
+ if (typeof value !== "string")
17
+ throw new TypeError(`${name} harus string`);
18
+ };
19
+ const asRecord = (value) => value && typeof value === "object" && !Array.isArray(value)
20
+ ? value
21
+ : undefined;
22
+ export class AIRich extends BaseBuilder {
23
+ #nodes = new NodeStore();
24
+ #contextInfo;
25
+ #quote;
26
+ #footer;
27
+ #botJid;
28
+ #lastId;
29
+ #pendingEdits = new Map();
30
+ #responseId = randomUUID();
31
+ constructor(client, { botJid } = {}) {
32
+ super(client);
33
+ if (botJid !== undefined &&
34
+ (typeof botJid !== "string" || !botJid.trim())) {
35
+ throw new TypeError("botJid harus string non-empty");
36
+ }
37
+ this.#botJid = botJid ?? null;
38
+ this.#contextInfo = {};
39
+ this.#quote = null;
40
+ this.#footer = "";
41
+ this.#lastId = null;
42
+ }
43
+ get lastId() {
44
+ return this.#lastId;
45
+ }
46
+ get size() {
47
+ return this.#nodes.size;
48
+ }
49
+ ids() {
50
+ return this.#nodes.ids();
51
+ }
52
+ has(id) {
53
+ return this.#nodes.has(id);
54
+ }
55
+ pendingEdit(jid) {
56
+ return this.#pendingEdits.get(jid) ?? null;
57
+ }
58
+ raw(section, submessage, { id } = {}) {
59
+ if (!section || typeof section !== "object")
60
+ throw new ValidationError("section harus object");
61
+ const node = this.#nodes.makeNode({ id, section, submessage });
62
+ this.#nodes.push(node);
63
+ return this;
64
+ }
65
+ replace(target, section, submessage, { id } = {}) {
66
+ if (!section || typeof section !== "object")
67
+ throw new ValidationError("section harus object");
68
+ const node = this.#resolveTargetNode(target);
69
+ const replacement = this.#nodes.makeNode({ id, section, submessage });
70
+ this.#nodes.replaceAt(this.#nodes.indexOf(node), replacement);
71
+ return this;
72
+ }
73
+ insert(target, section, submessage, { id, after = true } = {}) {
74
+ if (!section || typeof section !== "object")
75
+ throw new ValidationError("section harus object");
76
+ const node = this.#resolveTargetNode(target);
77
+ const index = this.#nodes.indexOf(node);
78
+ const insertion = this.#nodes.makeNode({ id, section, submessage });
79
+ this.#nodes.insertAt(after ? index + 1 : index, insertion);
80
+ return this;
81
+ }
82
+ insertAt(index, section, submessage, { id } = {}) {
83
+ if (!section || typeof section !== "object")
84
+ throw new ValidationError("section harus object");
85
+ const insertion = this.#nodes.makeNode({ id, section, submessage });
86
+ this.#nodes.insertAt(index, insertion);
87
+ return this;
88
+ }
89
+ loadPayload(payload) {
90
+ if (!payload || typeof payload !== "object")
91
+ throw new ValidationError("payload harus object");
92
+ const payloadRecord = payload;
93
+ const message = asRecord(payloadRecord.message) ?? payloadRecord;
94
+ const botForwarded = asRecord(message.botForwardedMessage);
95
+ const botForwardedInner = botForwarded
96
+ ? asRecord(botForwarded.message)
97
+ : undefined;
98
+ const rich = (botForwardedInner
99
+ ? asRecord(botForwardedInner.richResponseMessage)
100
+ : undefined) ??
101
+ (botForwarded ? asRecord(botForwarded.richResponseMessage) : undefined) ??
102
+ asRecord(message.richResponseMessage);
103
+ if (!rich)
104
+ throw new ValidationError("payload tidak mengandung richResponseMessage");
105
+ let sections = [];
106
+ let responseId = null;
107
+ const unifiedResponse = asRecord(rich.unifiedResponse);
108
+ const unifiedData = unifiedResponse ? unifiedResponse.data : undefined;
109
+ if (unifiedData) {
110
+ const unified = asRecord(decodeUnifiedResponse(unifiedData));
111
+ if (unified && Array.isArray(unified.sections))
112
+ sections = structuredClone(unified.sections);
113
+ if (unified &&
114
+ typeof unified.response_id === "string" &&
115
+ unified.response_id)
116
+ responseId = unified.response_id;
117
+ }
118
+ const submessages = Array.isArray(rich.submessages)
119
+ ? structuredClone(rich.submessages)
120
+ : [];
121
+ this.#nodes.clear();
122
+ const count = Math.max(sections.length, submessages.length);
123
+ for (let i = 0; i < count; i++) {
124
+ this.#nodes.push(this.#nodes.makeNode({
125
+ section: (sections[i] ?? null),
126
+ submessage: (submessages[i] ?? null),
127
+ }));
128
+ }
129
+ const loaded = asRecord(rich.contextInfo);
130
+ if (loaded) {
131
+ const clone = structuredClone(loaded);
132
+ const { forwardingScore: _fs, isForwarded: _if, forwardOrigin: _fo, forwardedAiBotMessageInfo, ...rest } = clone;
133
+ this.#contextInfo = rest;
134
+ const botInfo = asRecord(forwardedAiBotMessageInfo);
135
+ if (botInfo && typeof botInfo.botJid === "string" && botInfo.botJid) {
136
+ this.#botJid = botInfo.botJid;
137
+ }
138
+ }
139
+ if (responseId)
140
+ this.#responseId = responseId;
141
+ return this;
142
+ }
143
+ text(text, { id, hyperlink = true, citation = true, latex = true, } = {}) {
144
+ assertString(text, "text");
145
+ const parsed = parseInline(text, { hyperlink, citation, latex });
146
+ return this.raw(layout("Single", {
147
+ text: parsed.text,
148
+ ...(parsed.entities.length && { inline_entities: parsed.entities }),
149
+ __typename: "GenAIMarkdownTextUXPrimitive",
150
+ }), {
151
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
152
+ messageText: text,
153
+ }, { id });
154
+ }
155
+ code(language, code, { id } = {}) {
156
+ assertString(language, "language");
157
+ assertString(code, "code");
158
+ const tokens = tokenizeCode(code, language);
159
+ return this.raw(layout("Single", {
160
+ language,
161
+ code_blocks: tokens.unified_codeBlock,
162
+ __typename: "GenAICodeUXPrimitive",
163
+ }), {
164
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_CODE,
165
+ codeMetadata: { codeLanguage: language, codeBlocks: tokens.codeBlock },
166
+ }, { id });
167
+ }
168
+ table(rows, { id, hyperlink = true, citation = true, latex = true, } = {}) {
169
+ const { unified, legacy } = toTable(rows, { hyperlink, citation, latex });
170
+ return this.raw(layout("Single", { rows: unified, __typename: "GenATableUXPrimitive" }), {
171
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TABLE,
172
+ tableMetadata: { title: "", rows: legacy },
173
+ }, { id });
174
+ }
175
+ metadata(text, { id } = {}) {
176
+ assertString(text, "text");
177
+ return this.raw(layout("Single", { text, __typename: "GenAIMetadataTextPrimitive" }), {
178
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
179
+ messageText: text,
180
+ }, { id });
181
+ }
182
+ tip(text, { id } = {}) {
183
+ assertString(text, "text");
184
+ return this.raw(layout("Single", {
185
+ text: "ⓘ " + text,
186
+ __typename: "GenAIMetadataTextPrimitive",
187
+ }), {
188
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
189
+ messageText: text,
190
+ }, { id });
191
+ }
192
+ suggest(items, { id, scroll = true, layout: layoutName, } = {}) {
193
+ const list = Array.isArray(items) ? items : [items];
194
+ if (!list.length || !list.every((item) => typeof item === "string")) {
195
+ throw new TypeError("suggest harus string atau array string");
196
+ }
197
+ const pills = list.map((prompt_text) => ({
198
+ prompt_text,
199
+ prompt_type: "SUGGESTED_PROMPT",
200
+ __typename: "GenAIFollowUpSuggestionPillPrimitive",
201
+ }));
202
+ const type = layoutName ??
203
+ (pills.length === 1 ? "Single" : scroll ? "HScroll" : "ActionRow");
204
+ const first = pills[0];
205
+ return this.raw(layout(type, type === "Single" && first !== undefined ? first : pills, {
206
+ __typename: "GenAIUnifiedResponseSection",
207
+ }), undefined, { id });
208
+ }
209
+ source(sources, { id, layout: layoutName } = {}) {
210
+ return this.raw(sourceSection(sources, { layout: layoutName }), undefined, {
211
+ id,
212
+ });
213
+ }
214
+ image(url, { id, ...options } = {}) {
215
+ return this.raw(imageSection(url, options), undefined, { id });
216
+ }
217
+ video(url, { id, ...options } = {}) {
218
+ return this.raw(videoSection(url, options), undefined, { id });
219
+ }
220
+ footerAction(data, { id, layout: layoutName } = {}) {
221
+ return this.raw(footerActionSection(data, { layout: layoutName }), undefined, { id });
222
+ }
223
+ widget(data, { id, layout: layoutName } = {}) {
224
+ return this.raw(widgetSection(data, { layout: layoutName }), undefined, {
225
+ id,
226
+ });
227
+ }
228
+ product(data, { id, layout: layoutName } = {}) {
229
+ return this.raw(productSection(data, { layout: layoutName }), undefined, {
230
+ id,
231
+ });
232
+ }
233
+ post(data, { id, layout: layoutName } = {}) {
234
+ return this.raw(postSection(data, { layout: layoutName }), undefined, {
235
+ id,
236
+ });
237
+ }
238
+ reels(items, { id, layout: layoutName } = {}) {
239
+ return this.raw(reelsSection(items, { layout: layoutName }), undefined, {
240
+ id,
241
+ });
242
+ }
243
+ html(html, { id, ...options } = {}) {
244
+ return this.raw(htmlSection(html, options), undefined, { id });
245
+ }
246
+ footer(text) {
247
+ assertString(text, "footer");
248
+ this.#footer = text;
249
+ return this;
250
+ }
251
+ context(info) {
252
+ this.#contextInfo = { ...this.#contextInfo, ...filterContextInfo(info) };
253
+ return this;
254
+ }
255
+ quote(message) {
256
+ const id = message?.key?.id ?? message?.id;
257
+ if (!id)
258
+ throw new ValidationError("quote butuh pesan yang punya key.id");
259
+ this.#quote = {
260
+ stanzaId: id,
261
+ participant: message.key?.participant ?? message.key?.remoteJid,
262
+ quotedType: proto.ContextInfo.QuotedType.EXPLICIT,
263
+ ...(message.message && { quotedMessage: message.message }),
264
+ };
265
+ return this;
266
+ }
267
+ remove(target) {
268
+ if (typeof target === "number") {
269
+ if (!Number.isInteger(target) ||
270
+ target < 0 ||
271
+ target >= this.#nodes.size) {
272
+ throw new ItemNotFoundError(target, this.ids());
273
+ }
274
+ this.#nodes.removeAt(target);
275
+ return this;
276
+ }
277
+ if (typeof target !== "string" || !this.#nodes.has(target)) {
278
+ throw new ItemNotFoundError(target, this.ids());
279
+ }
280
+ this.#nodes.removeNode(this.#nodes.get(target));
281
+ return this;
282
+ }
283
+ clear() {
284
+ this.#nodes.clear();
285
+ this.#footer = "";
286
+ this.#pendingEdits.clear();
287
+ this.#responseId = randomUUID();
288
+ this.#lastId = null;
289
+ return this;
290
+ }
291
+ #resolveTargetNode(target) {
292
+ if (typeof target === "number") {
293
+ if (!Number.isInteger(target) ||
294
+ target < 0 ||
295
+ target >= this.#nodes.size) {
296
+ throw new InvalidTargetError(`index node ${target} di luar rentang (0-${this.#nodes.size - 1})`, { target });
297
+ }
298
+ return this.#nodes.nodes[target];
299
+ }
300
+ if (typeof target !== "string" || !target.trim()) {
301
+ throw new InvalidTargetError("target harus id string atau index number", {
302
+ target,
303
+ });
304
+ }
305
+ return this.#nodes.get(target);
306
+ }
307
+ #sections() {
308
+ if (!this.#nodes.size)
309
+ throw new ValidationError("minimal satu konten sebelum build/send");
310
+ const sections = this.#nodes.nodes
311
+ .filter((node) => node.section !== null)
312
+ .map((node) => node.section);
313
+ const footer = this.#footer;
314
+ if (footer) {
315
+ sections.push(layout("Single", {
316
+ text: footer,
317
+ __typename: "GenAIMetadataTextPrimitive",
318
+ }));
319
+ }
320
+ return sections;
321
+ }
322
+ #submessages(enabled) {
323
+ if (!enabled)
324
+ return [];
325
+ return this.#nodes.nodes
326
+ .map((node) => node.submessage)
327
+ .filter((sub) => Boolean(sub));
328
+ }
329
+ #context(withContext) {
330
+ return withContext
331
+ ? buildContextInfo({
332
+ botJid: this.#botJid,
333
+ quote: this.#quote,
334
+ contextInfo: this.#contextInfo,
335
+ })
336
+ : buildContextInfo({ botJid: this.#botJid });
337
+ }
338
+ #rich({ sections, submessages = [], withContext = false, }) {
339
+ return buildRichResponse({
340
+ responseId: this.#responseId,
341
+ sections,
342
+ submessages,
343
+ contextInfo: this.#context(withContext),
344
+ });
345
+ }
346
+ build({ submessages = true, } = {}) {
347
+ return wrapBotForwarded(this.#rich({
348
+ sections: this.#sections(),
349
+ submessages: this.#submessages(submessages),
350
+ }));
351
+ }
352
+ buildPlaceholder() {
353
+ return buildPlaceholderContent({
354
+ responseId: this.#responseId,
355
+ contextInfo: this.#context(true),
356
+ });
357
+ }
358
+ buildEdit(jid, id, { submessages = true } = {}) {
359
+ if (typeof id !== "string" || !id.trim()) {
360
+ throw new ValidationError("buildEdit butuh ID pesan berupa string yang valid");
361
+ }
362
+ return buildEditContent({ jid, id, rich: this.build({ submessages }) });
363
+ }
364
+ async send(jid, arg) {
365
+ const { client, options } = this._resolve(arg);
366
+ const { twoStep = true, submessages = true, ...sendOptions } = options;
367
+ if (!twoStep) {
368
+ const direct = wrapBotForwarded(this.#rich({
369
+ sections: this.#sections(),
370
+ submessages: this.#submessages(Boolean(submessages)),
371
+ withContext: true,
372
+ }));
373
+ const result = await sendViaZapo(client, jid, direct, sendOptions);
374
+ this.#lastId = result?.id ?? null;
375
+ return result;
376
+ }
377
+ const sent = await sendPlaceholderThenEdit({
378
+ client,
379
+ jid: jid,
380
+ placeholder: this.buildPlaceholder(),
381
+ buildEdit: (messageId) => this.buildEdit(jid, messageId, {
382
+ submessages: Boolean(submessages),
383
+ }),
384
+ options: sendOptions,
385
+ onPlaceholderSent: (target, messageId) => {
386
+ this.#lastId = messageId;
387
+ this.#pendingEdits.set(target, messageId);
388
+ },
389
+ });
390
+ this.#pendingEdits.delete(jid);
391
+ return sent;
392
+ }
393
+ async edit(jid, id = this.#lastId, arg) {
394
+ if (typeof id !== "string" || !id.trim()) {
395
+ throw new ValidationError("edit butuh ID pesan berupa string yang valid");
396
+ }
397
+ const { client, options } = this._resolve(arg);
398
+ const { submessages = false, ...sendOptions } = options;
399
+ const result = await sendViaZapo(client, jid, this.buildEdit(jid, id, { submessages: Boolean(submessages) }), sendOptions);
400
+ this.#pendingEdits.delete(jid);
401
+ return result;
402
+ }
403
+ }
404
+ export function airich(client, first, second, third) {
405
+ if (typeof first === "string") {
406
+ if (second === undefined)
407
+ return new AIRich(client);
408
+ return sendAIRich(client, first, second, third);
409
+ }
410
+ return new AIRich(client, first);
411
+ }
412
+ const isItemArray = (items) => Array.isArray(items);
413
+ const mutableItems = (items) => isItemArray(items) ? [...items] : items;
414
+ const applyAIRichSection = (builder, section) => {
415
+ if (section.type === "text") {
416
+ const { text, hyperlink, citation, latex, id } = section;
417
+ builder.text(text, {
418
+ ...(id !== undefined ? { id } : {}),
419
+ ...(hyperlink !== undefined ? { hyperlink } : {}),
420
+ ...(citation !== undefined ? { citation } : {}),
421
+ ...(latex !== undefined ? { latex } : {}),
422
+ });
423
+ }
424
+ else if (section.type === "code") {
425
+ builder.code(section.language, section.code, {
426
+ ...(section.id !== undefined ? { id: section.id } : {}),
427
+ });
428
+ }
429
+ else if (section.type === "table") {
430
+ const { rows, hyperlink, citation, latex, id } = section;
431
+ builder.table(rows, {
432
+ ...(id !== undefined ? { id } : {}),
433
+ ...(hyperlink !== undefined ? { hyperlink } : {}),
434
+ ...(citation !== undefined ? { citation } : {}),
435
+ ...(latex !== undefined ? { latex } : {}),
436
+ });
437
+ }
438
+ else if (section.type === "metadata") {
439
+ builder.metadata(section.text, {
440
+ ...(section.id !== undefined ? { id: section.id } : {}),
441
+ });
442
+ }
443
+ else if (section.type === "tip") {
444
+ builder.tip(section.text, {
445
+ ...(section.id !== undefined ? { id: section.id } : {}),
446
+ });
447
+ }
448
+ else if (section.type === "suggest") {
449
+ const { items, scroll, layout: layoutName, id } = section;
450
+ builder.suggest(mutableItems(items), {
451
+ ...(id !== undefined ? { id } : {}),
452
+ ...(scroll !== undefined ? { scroll } : {}),
453
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
454
+ });
455
+ }
456
+ else if (section.type === "source") {
457
+ const { sources, layout: layoutName, id } = section;
458
+ builder.source([...sources], {
459
+ ...(id !== undefined ? { id } : {}),
460
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
461
+ });
462
+ }
463
+ else if (section.type === "image") {
464
+ const { url, width, height, status, updateText, id } = section;
465
+ builder.image(url, {
466
+ ...(id !== undefined ? { id } : {}),
467
+ ...(width !== undefined ? { width } : {}),
468
+ ...(height !== undefined ? { height } : {}),
469
+ ...(status !== undefined ? { status } : {}),
470
+ ...(updateText !== undefined ? { update_text: updateText } : {}),
471
+ });
472
+ }
473
+ else if (section.type === "video") {
474
+ const { url, mimeType, fileLength, duration, status, id } = section;
475
+ builder.video(url, {
476
+ ...(id !== undefined ? { id } : {}),
477
+ ...(mimeType !== undefined ? { mime_type: mimeType } : {}),
478
+ ...(fileLength !== undefined ? { file_length: fileLength } : {}),
479
+ ...(duration !== undefined ? { duration } : {}),
480
+ ...(status !== undefined ? { status } : {}),
481
+ });
482
+ }
483
+ else if (section.type === "footerAction") {
484
+ const { items, layout: layoutName, id } = section;
485
+ builder.footerAction(mutableItems(items), {
486
+ ...(id !== undefined ? { id } : {}),
487
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
488
+ });
489
+ }
490
+ else if (section.type === "widget") {
491
+ const { items, layout: layoutName, id } = section;
492
+ builder.widget(mutableItems(items), {
493
+ ...(id !== undefined ? { id } : {}),
494
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
495
+ });
496
+ }
497
+ else if (section.type === "product") {
498
+ const { items, layout: layoutName, id } = section;
499
+ builder.product(mutableItems(items), {
500
+ ...(id !== undefined ? { id } : {}),
501
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
502
+ });
503
+ }
504
+ else if (section.type === "post") {
505
+ const { items, layout: layoutName, id } = section;
506
+ builder.post(mutableItems(items), {
507
+ ...(id !== undefined ? { id } : {}),
508
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
509
+ });
510
+ }
511
+ else if (section.type === "reels") {
512
+ const { items, layout: layoutName, id } = section;
513
+ builder.reels(mutableItems(items), {
514
+ ...(id !== undefined ? { id } : {}),
515
+ ...(layoutName !== undefined ? { layout: layoutName } : {}),
516
+ });
517
+ }
518
+ else if (section.type === "html") {
519
+ const { html, trustedSources, id } = section;
520
+ builder.html(html, {
521
+ ...(id !== undefined ? { id } : {}),
522
+ ...(trustedSources !== undefined
523
+ ? { trusted_sources: [...trustedSources] }
524
+ : {}),
525
+ });
526
+ }
527
+ else {
528
+ builder.raw(section.section, section.submessage, {
529
+ id: section.id,
530
+ });
531
+ }
532
+ };
533
+ export const applyAIRichConfig = (builder, config) => {
534
+ for (const section of config.sections) {
535
+ applyAIRichSection(builder, section);
536
+ }
537
+ if (config.footer !== undefined)
538
+ builder.footer(config.footer);
539
+ if (config.context !== undefined)
540
+ builder.context(config.context);
541
+ if (config.quote !== undefined)
542
+ builder.quote(config.quote);
543
+ };
544
+ export const sendAIRich = async (client, jid, config, options) => {
545
+ const builder = new AIRich(client);
546
+ applyAIRichConfig(builder, config);
547
+ return sendConfigured(builder, jid, options);
548
+ };
@@ -0,0 +1,24 @@
1
+ import { proto } from "zapo-js";
2
+ import type { ContextInfoPayload } from "../payloads.js";
3
+ import type { Proto } from "zapo-js";
4
+ export declare const BUILDER_CONTROLLED_CONTEXT_FIELDS: readonly ["forwardingScore", "isForwarded", "forwardOrigin", "forwardedAiBotMessageInfo", "stanzaId", "participant", "quotedType", "quotedMessage"];
5
+ export declare const ALLOWED_CONTEXT_FIELDS: readonly ["mentionedJid", "groupMentions", "statusAttributions", "expiration", "ephemeralSettingTimestamp", "disappearingMode"];
6
+ export type BuilderControlledContextField = (typeof BUILDER_CONTROLLED_CONTEXT_FIELDS)[number];
7
+ export type AllowedContextField = (typeof ALLOWED_CONTEXT_FIELDS)[number];
8
+ export type AllowedContextInfo = Partial<Record<AllowedContextField, unknown>> & Record<string, unknown>;
9
+ export interface QuoteInfoInput {
10
+ stanzaId: string;
11
+ participant: string | undefined;
12
+ quotedType: proto.ContextInfo.QuotedType;
13
+ quotedMessage?: Proto.IMessage;
14
+ }
15
+ export type QuoteInfo = QuoteInfoInput;
16
+ export declare const forwardInfo: (botJid: string | null) => ContextInfoPayload;
17
+ export declare const quoteInfo: (quote: QuoteInfo | null) => Record<string, unknown>;
18
+ export declare const filterContextInfo: (info: unknown) => AllowedContextInfo;
19
+ export interface BuildContextInfoInput {
20
+ botJid?: string | null | undefined;
21
+ quote?: QuoteInfo | null | undefined;
22
+ contextInfo?: Record<string, unknown> | undefined;
23
+ }
24
+ export declare const buildContextInfo: ({ botJid, quote, contextInfo, }?: BuildContextInfoInput) => Record<string, unknown>;
@@ -0,0 +1,48 @@
1
+ import { proto } from "zapo-js";
2
+ import { ValidationError } from "../core/errors.js";
3
+ export const BUILDER_CONTROLLED_CONTEXT_FIELDS = [
4
+ "forwardingScore",
5
+ "isForwarded",
6
+ "forwardOrigin",
7
+ "forwardedAiBotMessageInfo",
8
+ "stanzaId",
9
+ "participant",
10
+ "quotedType",
11
+ "quotedMessage",
12
+ ];
13
+ export const ALLOWED_CONTEXT_FIELDS = [
14
+ "mentionedJid",
15
+ "groupMentions",
16
+ "statusAttributions",
17
+ "expiration",
18
+ "ephemeralSettingTimestamp",
19
+ "disappearingMode",
20
+ ];
21
+ export const forwardInfo = (botJid) => ({
22
+ forwardingScore: 1,
23
+ isForwarded: true,
24
+ forwardOrigin: proto.ContextInfo.ForwardOrigin.META_AI,
25
+ ...(botJid ? { forwardedAiBotMessageInfo: { botJid } } : {}),
26
+ });
27
+ export const quoteInfo = (quote) => quote ? { ...quote } : {};
28
+ export const filterContextInfo = (info) => {
29
+ if (!info || typeof info !== "object" || Array.isArray(info)) {
30
+ throw new ValidationError("contextInfo harus object");
31
+ }
32
+ const record = info;
33
+ const keys = Object.keys(record);
34
+ const controlled = keys.filter((key) => BUILDER_CONTROLLED_CONTEXT_FIELDS.includes(key));
35
+ if (controlled.length) {
36
+ throw new ValidationError(`field contextInfo dikendalikan builder dan tidak boleh ditimpa lewat context(): ${controlled.join(", ")}`, { fields: controlled });
37
+ }
38
+ const unknown = keys.filter((key) => !ALLOWED_CONTEXT_FIELDS.includes(key));
39
+ if (unknown.length) {
40
+ throw new ValidationError(`field contextInfo tidak di-allowlist (diizinkan: ${ALLOWED_CONTEXT_FIELDS.join(", ")}): ${unknown.join(", ")}`, { fields: unknown, allowed: [...ALLOWED_CONTEXT_FIELDS] });
41
+ }
42
+ return { ...record };
43
+ };
44
+ export const buildContextInfo = ({ botJid = null, quote = null, contextInfo = {}, } = {}) => ({
45
+ ...forwardInfo(botJid),
46
+ ...quoteInfo(quote),
47
+ ...contextInfo,
48
+ });
@@ -0,0 +1,3 @@
1
+ export declare const stringifyEscaped: (payload: unknown) => string;
2
+ export declare const encodeUnifiedResponse: (payload: unknown) => Buffer;
3
+ export declare const decodeUnifiedResponse: (data: string | Uint8Array) => unknown;
@@ -0,0 +1,16 @@
1
+ const ESCAPE_RE = /[\u007f-\uffff]/g;
2
+ export const stringifyEscaped = (payload) => JSON.stringify(payload).replace(ESCAPE_RE, (char) => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0"));
3
+ export const encodeUnifiedResponse = (payload) => Buffer.from(stringifyEscaped(payload), "utf8");
4
+ export const decodeUnifiedResponse = (data) => {
5
+ let json;
6
+ if (typeof data === "string") {
7
+ json = Buffer.from(data, "base64").toString("utf8");
8
+ }
9
+ else if (data instanceof Uint8Array) {
10
+ json = Buffer.from(data).toString("utf8");
11
+ }
12
+ else {
13
+ throw new TypeError("unifiedResponse.data harus base64 string atau Uint8Array");
14
+ }
15
+ return JSON.parse(json);
16
+ };
@@ -0,0 +1,20 @@
1
+ export { AIRich, airich } from "./airich.js";
2
+ export type { AIRichConstructorOptions, AIRichConfig, AIRichSectionConfig, AIRichSendOptions, RawNodeOptions, InsertNodeOptions, QuotableMessage, RichTarget, } from "./airich.js";
3
+ export { parseInline } from "./inline.js";
4
+ export type { InlineEntity, InlineHyperlinkEntity, InlineCitationEntity, InlineLatexEntity, ParsedInline, ParseInlineOptions, } from "./inline.js";
5
+ export { toTable } from "./table.js";
6
+ export type { ToTableResult, UnifiedTableRow } from "./table.js";
7
+ export { tokenizeCode } from "./tokenizer.js";
8
+ export type { TokenizeResult, CodeBlockToken, UnifiedCodeToken, } from "./tokenizer.js";
9
+ export { stringifyEscaped, encodeUnifiedResponse, decodeUnifiedResponse, } from "./encode.js";
10
+ export { layout, ZWSP, buildRichResponse, wrapBotForwarded, buildPlaceholderContent, buildEditContent, } from "./protocol.js";
11
+ export type { UnifiedResponseSection, UnifiedViewModel, UnifiedResponsePayload, RichResponseInput, PlaceholderInput, EditInput, } from "./protocol.js";
12
+ export { forwardInfo, quoteInfo, buildContextInfo, filterContextInfo, ALLOWED_CONTEXT_FIELDS, BUILDER_CONTROLLED_CONTEXT_FIELDS, } from "./context.js";
13
+ export type { QuoteInfo, QuoteInfoInput, AllowedContextInfo, AllowedContextField, BuilderControlledContextField, } from "./context.js";
14
+ export { sendViaZapo, sendPlaceholderThenEdit, sendAttributes, isZapoClient, } from "./transport.js";
15
+ export type { SendPlaceholderThenEditInput } from "./transport.js";
16
+ export { EXPERIMENTAL_PRIMITIVES } from "./primitives.js";
17
+ export { sourceSection, imageSection, videoSection, footerActionSection, widgetSection, productSection, postSection, reelsSection, htmlSection, } from "./primitives.js";
18
+ export type { SourceInput, SourceObjectItem, ImageSectionOptions, VideoSectionOptions, FooterActionItem, WidgetItem, ProductItem, PostItem, ReelsItem, SectionLayoutOptions, HtmlSectionOptions, } from "./primitives.js";
19
+ export { NodeStore } from "./nodes.js";
20
+ export type { RichNode, MakeNodeInput } from "./nodes.js";
@@ -0,0 +1,11 @@
1
+ export { AIRich, airich } from "./airich.js";
2
+ export { parseInline } from "./inline.js";
3
+ export { toTable } from "./table.js";
4
+ export { tokenizeCode } from "./tokenizer.js";
5
+ export { stringifyEscaped, encodeUnifiedResponse, decodeUnifiedResponse, } from "./encode.js";
6
+ export { layout, ZWSP, buildRichResponse, wrapBotForwarded, buildPlaceholderContent, buildEditContent, } from "./protocol.js";
7
+ export { forwardInfo, quoteInfo, buildContextInfo, filterContextInfo, ALLOWED_CONTEXT_FIELDS, BUILDER_CONTROLLED_CONTEXT_FIELDS, } from "./context.js";
8
+ export { sendViaZapo, sendPlaceholderThenEdit, sendAttributes, isZapoClient, } from "./transport.js";
9
+ export { EXPERIMENTAL_PRIMITIVES } from "./primitives.js";
10
+ export { sourceSection, imageSection, videoSection, footerActionSection, widgetSection, productSection, postSection, reelsSection, htmlSection, } from "./primitives.js";
11
+ export { NodeStore } from "./nodes.js";