@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,96 @@
1
+ import { proto } from "zapo-js";
2
+ import { ValidationError } from "../core/errors.js";
3
+ import type { ContextInfoPayload } from "../payloads.js";
4
+ import type { Proto } from "zapo-js";
5
+
6
+ export const BUILDER_CONTROLLED_CONTEXT_FIELDS = [
7
+ "forwardingScore",
8
+ "isForwarded",
9
+ "forwardOrigin",
10
+ "forwardedAiBotMessageInfo",
11
+ "stanzaId",
12
+ "participant",
13
+ "quotedType",
14
+ "quotedMessage",
15
+ ] as const;
16
+
17
+ export const ALLOWED_CONTEXT_FIELDS = [
18
+ "mentionedJid",
19
+ "groupMentions",
20
+ "statusAttributions",
21
+ "expiration",
22
+ "ephemeralSettingTimestamp",
23
+ "disappearingMode",
24
+ ] as const;
25
+
26
+ export type BuilderControlledContextField =
27
+ (typeof BUILDER_CONTROLLED_CONTEXT_FIELDS)[number];
28
+ export type AllowedContextField = (typeof ALLOWED_CONTEXT_FIELDS)[number];
29
+
30
+ export type AllowedContextInfo = Partial<Record<AllowedContextField, unknown>> &
31
+ Record<string, unknown>;
32
+
33
+ export interface QuoteInfoInput {
34
+ stanzaId: string;
35
+ participant: string | undefined;
36
+ quotedType: proto.ContextInfo.QuotedType;
37
+ quotedMessage?: Proto.IMessage;
38
+ }
39
+
40
+ export type QuoteInfo = QuoteInfoInput;
41
+
42
+ export const forwardInfo = (botJid: string | null): ContextInfoPayload => ({
43
+ forwardingScore: 1,
44
+ isForwarded: true,
45
+ forwardOrigin: proto.ContextInfo.ForwardOrigin.META_AI,
46
+ ...(botJid ? { forwardedAiBotMessageInfo: { botJid } } : {}),
47
+ });
48
+
49
+ export const quoteInfo = (quote: QuoteInfo | null): Record<string, unknown> =>
50
+ quote ? { ...quote } : {};
51
+
52
+ export const filterContextInfo = (info: unknown): AllowedContextInfo => {
53
+ if (!info || typeof info !== "object" || Array.isArray(info)) {
54
+ throw new ValidationError("contextInfo harus object");
55
+ }
56
+
57
+ const record = info as Record<string, unknown>;
58
+ const keys = Object.keys(record);
59
+ const controlled = keys.filter((key) =>
60
+ (BUILDER_CONTROLLED_CONTEXT_FIELDS as readonly string[]).includes(key),
61
+ );
62
+ if (controlled.length) {
63
+ throw new ValidationError(
64
+ `field contextInfo dikendalikan builder dan tidak boleh ditimpa lewat context(): ${controlled.join(", ")}`,
65
+ { fields: controlled },
66
+ );
67
+ }
68
+
69
+ const unknown = keys.filter(
70
+ (key) => !(ALLOWED_CONTEXT_FIELDS as readonly string[]).includes(key),
71
+ );
72
+ if (unknown.length) {
73
+ throw new ValidationError(
74
+ `field contextInfo tidak di-allowlist (diizinkan: ${ALLOWED_CONTEXT_FIELDS.join(", ")}): ${unknown.join(", ")}`,
75
+ { fields: unknown, allowed: [...ALLOWED_CONTEXT_FIELDS] },
76
+ );
77
+ }
78
+
79
+ return { ...record };
80
+ };
81
+
82
+ export interface BuildContextInfoInput {
83
+ botJid?: string | null | undefined;
84
+ quote?: QuoteInfo | null | undefined;
85
+ contextInfo?: Record<string, unknown> | undefined;
86
+ }
87
+
88
+ export const buildContextInfo = ({
89
+ botJid = null,
90
+ quote = null,
91
+ contextInfo = {},
92
+ }: BuildContextInfoInput = {}): Record<string, unknown> => ({
93
+ ...forwardInfo(botJid),
94
+ ...quoteInfo(quote),
95
+ ...contextInfo,
96
+ });
@@ -0,0 +1,25 @@
1
+ const ESCAPE_RE = /[\u007f-\uffff]/g;
2
+
3
+ export const stringifyEscaped = (payload: unknown): string =>
4
+ JSON.stringify(payload).replace(
5
+ ESCAPE_RE,
6
+ (char) => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0"),
7
+ );
8
+
9
+ export const encodeUnifiedResponse = (payload: unknown): Buffer =>
10
+ Buffer.from(stringifyEscaped(payload), "utf8");
11
+
12
+ export const decodeUnifiedResponse = (data: string | Uint8Array): unknown => {
13
+ let json: string;
14
+ if (typeof data === "string") {
15
+ json = Buffer.from(data, "base64").toString("utf8");
16
+ } else if (data instanceof Uint8Array) {
17
+ json = Buffer.from(data).toString("utf8");
18
+ } else {
19
+ throw new TypeError(
20
+ "unifiedResponse.data harus base64 string atau Uint8Array",
21
+ );
22
+ }
23
+
24
+ return JSON.parse(json);
25
+ };
@@ -0,0 +1,98 @@
1
+ export { AIRich, airich } from "./airich.js";
2
+ export type {
3
+ AIRichConstructorOptions,
4
+ AIRichConfig,
5
+ AIRichSectionConfig,
6
+ AIRichSendOptions,
7
+ RawNodeOptions,
8
+ InsertNodeOptions,
9
+ QuotableMessage,
10
+ RichTarget,
11
+ } from "./airich.js";
12
+ export { parseInline } from "./inline.js";
13
+ export type {
14
+ InlineEntity,
15
+ InlineHyperlinkEntity,
16
+ InlineCitationEntity,
17
+ InlineLatexEntity,
18
+ ParsedInline,
19
+ ParseInlineOptions,
20
+ } from "./inline.js";
21
+ export { toTable } from "./table.js";
22
+ export type { ToTableResult, UnifiedTableRow } from "./table.js";
23
+ export { tokenizeCode } from "./tokenizer.js";
24
+ export type {
25
+ TokenizeResult,
26
+ CodeBlockToken,
27
+ UnifiedCodeToken,
28
+ } from "./tokenizer.js";
29
+ export {
30
+ stringifyEscaped,
31
+ encodeUnifiedResponse,
32
+ decodeUnifiedResponse,
33
+ } from "./encode.js";
34
+ export {
35
+ layout,
36
+ ZWSP,
37
+ buildRichResponse,
38
+ wrapBotForwarded,
39
+ buildPlaceholderContent,
40
+ buildEditContent,
41
+ } from "./protocol.js";
42
+ export type {
43
+ UnifiedResponseSection,
44
+ UnifiedViewModel,
45
+ UnifiedResponsePayload,
46
+ RichResponseInput,
47
+ PlaceholderInput,
48
+ EditInput,
49
+ } from "./protocol.js";
50
+ export {
51
+ forwardInfo,
52
+ quoteInfo,
53
+ buildContextInfo,
54
+ filterContextInfo,
55
+ ALLOWED_CONTEXT_FIELDS,
56
+ BUILDER_CONTROLLED_CONTEXT_FIELDS,
57
+ } from "./context.js";
58
+ export type {
59
+ QuoteInfo,
60
+ QuoteInfoInput,
61
+ AllowedContextInfo,
62
+ AllowedContextField,
63
+ BuilderControlledContextField,
64
+ } from "./context.js";
65
+ export {
66
+ sendViaZapo,
67
+ sendPlaceholderThenEdit,
68
+ sendAttributes,
69
+ isZapoClient,
70
+ } from "./transport.js";
71
+ export type { SendPlaceholderThenEditInput } from "./transport.js";
72
+ export { EXPERIMENTAL_PRIMITIVES } from "./primitives.js";
73
+ export {
74
+ sourceSection,
75
+ imageSection,
76
+ videoSection,
77
+ footerActionSection,
78
+ widgetSection,
79
+ productSection,
80
+ postSection,
81
+ reelsSection,
82
+ htmlSection,
83
+ } from "./primitives.js";
84
+ export type {
85
+ SourceInput,
86
+ SourceObjectItem,
87
+ ImageSectionOptions,
88
+ VideoSectionOptions,
89
+ FooterActionItem,
90
+ WidgetItem,
91
+ ProductItem,
92
+ PostItem,
93
+ ReelsItem,
94
+ SectionLayoutOptions,
95
+ HtmlSectionOptions,
96
+ } from "./primitives.js";
97
+ export { NodeStore } from "./nodes.js";
98
+ export type { RichNode, MakeNodeInput } from "./nodes.js";
@@ -0,0 +1,272 @@
1
+ export interface InlineHyperlinkEntity {
2
+ key: string;
3
+ metadata: {
4
+ display_name: string;
5
+ is_trusted: boolean;
6
+ url: string;
7
+ __typename: "GenAIInlineLinkItem";
8
+ };
9
+ }
10
+
11
+ export interface InlineCitationEntity {
12
+ key: string;
13
+ metadata: {
14
+ reference_id: number;
15
+ reference_url: string;
16
+ reference_title: string;
17
+ reference_display_name: string;
18
+ sources: [];
19
+ __typename: "GenAISearchCitationItem";
20
+ };
21
+ }
22
+
23
+ export interface InlineLatexEntity {
24
+ key: string;
25
+ metadata: {
26
+ latex_expression: string;
27
+ latex_image: { url: string; width: number; height: number };
28
+ font_height: number;
29
+ padding: number;
30
+ __typename: "GenAILatexItem";
31
+ };
32
+ }
33
+
34
+ export type InlineEntity =
35
+ InlineHyperlinkEntity | InlineCitationEntity | InlineLatexEntity;
36
+
37
+ export interface ParsedInline {
38
+ text: string;
39
+ entities: InlineEntity[];
40
+ }
41
+
42
+ export interface ParseInlineOptions {
43
+ hyperlink?: boolean | undefined;
44
+ citation?: boolean | undefined;
45
+ latex?: boolean | undefined;
46
+ }
47
+
48
+ interface HyperlinkData {
49
+ key: string;
50
+ text: string;
51
+ url: string;
52
+ is_trusted: boolean;
53
+ }
54
+
55
+ interface CitationData {
56
+ key: string;
57
+ reference_id: number;
58
+ url: string;
59
+ }
60
+
61
+ interface LatexData {
62
+ key: string;
63
+ text: string;
64
+ url: string;
65
+ width: string | null;
66
+ height: string | null;
67
+ font_height: string | null;
68
+ padding: string | null;
69
+ }
70
+
71
+ const SCHEME_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;
72
+ const ALLOWED_SCHEMES = new Set(["http", "https", "mailto", "tel", "ftp"]);
73
+
74
+ const isValidUrl = (url: string): boolean => {
75
+ if (!url) return false;
76
+
77
+ const scheme = SCHEME_RE.exec(url);
78
+ if (scheme) return ALLOWED_SCHEMES.has((scheme[1] ?? "").toLowerCase());
79
+
80
+ return !/\s/.test(url) && url.includes(".") && !url.startsWith(".");
81
+ };
82
+
83
+ const scanClose = (
84
+ text: string,
85
+ from: number,
86
+ open: string,
87
+ close: string,
88
+ ): number => {
89
+ let depth = 1;
90
+ let end = from;
91
+
92
+ while (end < text.length && depth) {
93
+ const char = text[end] ?? "";
94
+ if (char === open && (text[end - 1] ?? "") !== "\\") depth++;
95
+ else if (char === close && (text[end - 1] ?? "") !== "\\") {
96
+ depth--;
97
+ if (!depth) return end + 1;
98
+ }
99
+ end++;
100
+ }
101
+
102
+ return -1;
103
+ };
104
+
105
+ const toHyperlinkEntity = ({
106
+ key,
107
+ text,
108
+ url,
109
+ is_trusted,
110
+ }: HyperlinkData): InlineHyperlinkEntity => ({
111
+ key,
112
+ metadata: {
113
+ display_name: text,
114
+ is_trusted,
115
+ url,
116
+ __typename: "GenAIInlineLinkItem",
117
+ },
118
+ });
119
+
120
+ const toCitationEntity = ({
121
+ key,
122
+ reference_id,
123
+ url,
124
+ }: CitationData): InlineCitationEntity => ({
125
+ key,
126
+ metadata: {
127
+ reference_id,
128
+ reference_url: url,
129
+ reference_title: url,
130
+ reference_display_name: url,
131
+ sources: [],
132
+ __typename: "GenAISearchCitationItem",
133
+ },
134
+ });
135
+
136
+ const toLatexEntity = ({
137
+ key,
138
+ text,
139
+ url,
140
+ width,
141
+ height,
142
+ font_height,
143
+ padding,
144
+ }: LatexData): InlineLatexEntity => ({
145
+ key,
146
+ metadata: {
147
+ latex_expression: text,
148
+ latex_image: {
149
+ url,
150
+ width: Number(width) || 100,
151
+ height: Number(height) || 100,
152
+ },
153
+ font_height: Number(font_height) || 83.333333333333,
154
+ padding: Number(padding) || 15,
155
+ __typename: "GenAILatexItem",
156
+ },
157
+ });
158
+
159
+ export const parseInline = (
160
+ text: string,
161
+ { hyperlink = true, citation = true, latex = true }: ParseInlineOptions = {},
162
+ ): ParsedInline => {
163
+ const entities: InlineEntity[] = [];
164
+ const stack: number[] = [];
165
+
166
+ let result = "";
167
+ let last = 0;
168
+ let citationIndex = 1;
169
+ let hyperlinkIndex = 0;
170
+ let latexIndex = 0;
171
+
172
+ for (let i = 0; i < text.length; i++) {
173
+ if ((text[i] ?? "") === "[" && (text[i - 1] ?? "") !== "\\") {
174
+ stack.push(i);
175
+ continue;
176
+ }
177
+
178
+ if (
179
+ (text[i] ?? "") !== "]" ||
180
+ (text[i - 1] ?? "") === "\\" ||
181
+ ((text[i + 1] ?? "") !== "(" && (text[i + 1] ?? "") !== "<")
182
+ )
183
+ continue;
184
+
185
+ const start = stack.pop();
186
+ if (start == null) continue;
187
+
188
+ const open = text[i + 1] ?? "";
189
+ const close = open === "(" ? ")" : ">";
190
+ const isLatex = open === "<";
191
+
192
+ const end = scanClose(text, i + 2, open, close);
193
+ if (end === -1) {
194
+ stack.push(start);
195
+ continue;
196
+ }
197
+
198
+ const raw = text.slice(start + 1, i).trim();
199
+ let url = text.slice(i + 2, end - 1).trim();
200
+
201
+ if (isLatex) {
202
+ if (!latex || !isValidUrl(url)) {
203
+ if (latex) stack.push(start);
204
+ continue;
205
+ }
206
+
207
+ const [
208
+ expr = "",
209
+ width = null,
210
+ height = null,
211
+ font_height = null,
212
+ padding = null,
213
+ ] = raw.split("|");
214
+ const key = `ZAPOK_LATEX_${latexIndex++}`;
215
+ const tag = `{{${key}}}${expr || "image"}{{/${key}}}`;
216
+ const data: LatexData = {
217
+ key,
218
+ text: expr,
219
+ url,
220
+ width,
221
+ height,
222
+ font_height,
223
+ padding,
224
+ };
225
+ result += text.slice(last, start) + tag;
226
+ last = end;
227
+ entities.push(toLatexEntity(data));
228
+ i = end - 1;
229
+ continue;
230
+ }
231
+
232
+ if (raw) {
233
+ if (!hyperlink || !isValidUrl(url)) {
234
+ if (hyperlink) stack.push(start);
235
+ continue;
236
+ }
237
+
238
+ const trusted = !url.startsWith("!");
239
+ if (!trusted) url = url.slice(1);
240
+ if (!isValidUrl(url)) {
241
+ stack.push(start);
242
+ continue;
243
+ }
244
+
245
+ const key = `ZAPOK_HYPERLINK_${hyperlinkIndex++}`;
246
+ const tag = `{{${key}}}${url}{{/${key}}}`;
247
+ const data: HyperlinkData = { key, text: raw, url, is_trusted: trusted };
248
+ result += text.slice(last, start) + tag;
249
+ last = end;
250
+ entities.push(toHyperlinkEntity(data));
251
+ i = end - 1;
252
+ continue;
253
+ }
254
+
255
+ if (!citation || !isValidUrl(url)) {
256
+ if (citation) stack.push(start);
257
+ continue;
258
+ }
259
+
260
+ const key = `ZAPOK_CITATION_${citationIndex - 1}`;
261
+ const tag = `{{${key}}}${url}{{/${key}}}`;
262
+ const data: CitationData = { key, reference_id: citationIndex++, url };
263
+ result += text.slice(last, start) + tag;
264
+ last = end;
265
+ entities.push(toCitationEntity(data));
266
+ i = end - 1;
267
+ }
268
+
269
+ result += text.slice(last);
270
+
271
+ return { text: result, entities };
272
+ };
@@ -0,0 +1,174 @@
1
+ import {
2
+ ValidationError,
3
+ ItemNotFoundError,
4
+ DuplicateIdError,
5
+ InvalidTargetError,
6
+ } from "../core/errors.js";
7
+ import type { SubmessagePayload } from "../payloads.js";
8
+ import type { UnifiedResponseSection } from "./protocol.js";
9
+
10
+ const assertNodeId = (id: unknown): void => {
11
+ if (id === undefined || id === null || id === "") return;
12
+ if (typeof id !== "string")
13
+ throw new ValidationError(
14
+ `id node harus string non-empty, dapat ${typeof id}`,
15
+ );
16
+ if (!id.trim())
17
+ throw new ValidationError("id node tidak boleh string kosong");
18
+ };
19
+
20
+ export interface RichNode {
21
+ id: string | null;
22
+ section: UnifiedResponseSection | null;
23
+ submessage: SubmessagePayload | null;
24
+ }
25
+
26
+ export interface MakeNodeInput {
27
+ id?: string | null | undefined;
28
+ section?: UnifiedResponseSection | null | undefined;
29
+ submessage?: SubmessagePayload | null | undefined;
30
+ }
31
+
32
+ export class NodeStore {
33
+ #nodes: RichNode[];
34
+ #index: Map<string, RichNode>;
35
+
36
+ constructor() {
37
+ this.#nodes = [];
38
+ this.#index = new Map();
39
+ }
40
+
41
+ get nodes(): RichNode[] {
42
+ return this.#nodes;
43
+ }
44
+
45
+ get size(): number {
46
+ return this.#nodes.length;
47
+ }
48
+
49
+ ids(): string[] {
50
+ return this.#nodes
51
+ .filter((node) => node.id)
52
+ .map((node) => node.id as string);
53
+ }
54
+
55
+ has(id: unknown): boolean {
56
+ return typeof id === "string" && this.#index.has(id);
57
+ }
58
+
59
+ get(id: string): RichNode {
60
+ if (typeof id !== "string" || !id.trim()) {
61
+ throw new ValidationError("id node harus string non-empty");
62
+ }
63
+
64
+ const node = this.#index.get(id);
65
+ if (!node) throw new ItemNotFoundError(id, this.ids());
66
+
67
+ return node;
68
+ }
69
+
70
+ indexOf(node: RichNode): number {
71
+ return this.#nodes.indexOf(node);
72
+ }
73
+
74
+ #register(node: RichNode, id: string | null | undefined): void {
75
+ if (id === undefined || id === null || id === "") return;
76
+ assertNodeId(id);
77
+
78
+ if (this.#index.has(id)) throw new DuplicateIdError(id);
79
+
80
+ node.id = id;
81
+ this.#index.set(id, node);
82
+ }
83
+
84
+ #unregister(node: RichNode): void {
85
+ if (node.id && this.#index.get(node.id) === node)
86
+ this.#index.delete(node.id);
87
+ }
88
+
89
+ makeNode({ id, section, submessage }: MakeNodeInput): RichNode {
90
+ assertNodeId(id);
91
+ return {
92
+ id: id ?? null,
93
+ section: section ?? null,
94
+ submessage: submessage ?? null,
95
+ };
96
+ }
97
+
98
+ push(node: RichNode): RichNode {
99
+ this.#register(node, node.id);
100
+ this.#nodes.push(node);
101
+ return node;
102
+ }
103
+
104
+ pushAll(nodes: RichNode[]): void {
105
+ for (const node of nodes) this.push(node);
106
+ }
107
+
108
+ removeAt(index: number): RichNode {
109
+ if (!Number.isInteger(index) || index < 0 || index >= this.#nodes.length) {
110
+ throw new InvalidTargetError(
111
+ `index node ${index} di luar rentang (0-${this.#nodes.length - 1})`,
112
+ { index },
113
+ );
114
+ }
115
+
116
+ const [removed] = this.#nodes.splice(index, 1);
117
+ this.#unregister(removed as RichNode);
118
+ return removed as RichNode;
119
+ }
120
+
121
+ removeNode(node: RichNode): RichNode {
122
+ const index = this.#nodes.indexOf(node);
123
+ if (index === -1)
124
+ throw new InvalidTargetError("node tidak ada di daftar node", {});
125
+ return this.removeAt(index);
126
+ }
127
+
128
+ insertAt(index: number, node: RichNode): RichNode {
129
+ if (!Number.isInteger(index) || index < 0 || index > this.#nodes.length) {
130
+ throw new InvalidTargetError(
131
+ `index sisip ${index} di luar rentang (0-${this.#nodes.length})`,
132
+ { index },
133
+ );
134
+ }
135
+
136
+ this.#register(node, node.id);
137
+ this.#nodes.splice(index, 0, node);
138
+ return node;
139
+ }
140
+
141
+ replaceAt(index: number, node: RichNode): RichNode {
142
+ if (!Number.isInteger(index) || index < 0 || index >= this.#nodes.length) {
143
+ throw new InvalidTargetError(
144
+ `index node ${index} di luar rentang (0-${this.#nodes.length - 1})`,
145
+ { index },
146
+ );
147
+ }
148
+
149
+ const old = this.#nodes[index] as RichNode;
150
+ const newId = node.id;
151
+
152
+ if (newId && newId !== old.id) {
153
+ assertNodeId(newId);
154
+ if (this.#index.has(newId)) throw new DuplicateIdError(newId);
155
+ }
156
+
157
+ this.#unregister(old);
158
+
159
+ if (!newId && old.id) {
160
+ node.id = old.id;
161
+ this.#index.set(node.id, node);
162
+ } else if (node.id) {
163
+ this.#index.set(node.id, node);
164
+ }
165
+
166
+ this.#nodes.splice(index, 1, node);
167
+ return node;
168
+ }
169
+
170
+ clear(): void {
171
+ this.#nodes = [];
172
+ this.#index = new Map();
173
+ }
174
+ }