@kodelyth/zalo 2026.5.39 → 2026.6.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.
@@ -0,0 +1,175 @@
1
+ import { B as registerWebhookTargetWithPluginRoute, I as readJsonWebhookBodyOrReject, K as resolveWebhookTargetWithAuthOrRejectSync, Q as withResolvedWebhookRequestPipeline, V as resolveClientIp, a as WEBHOOK_ANOMALY_COUNTER_DEFAULTS, b as createFixedWindowRateLimiter, l as applyBasicWebhookRequestGuards, o as WEBHOOK_RATE_LIMIT_DEFAULTS, x as createWebhookAnomalyTracker, z as registerWebhookTarget } from "./runtime-api-CxXTp1Q2.js";
2
+ import { safeEqualSecret } from "klaw/plugin-sdk/security-runtime";
3
+ import { createClaimableDedupe } from "klaw/plugin-sdk/persistent-dedupe";
4
+ //#region extensions/zalo/src/monitor.webhook.ts
5
+ const ZALO_WEBHOOK_REPLAY_WINDOW_MS = 5 * 6e4;
6
+ const webhookTargets = /* @__PURE__ */ new Map();
7
+ const webhookRateLimiter = createFixedWindowRateLimiter({
8
+ windowMs: WEBHOOK_RATE_LIMIT_DEFAULTS.windowMs,
9
+ maxRequests: WEBHOOK_RATE_LIMIT_DEFAULTS.maxRequests,
10
+ maxTrackedKeys: WEBHOOK_RATE_LIMIT_DEFAULTS.maxTrackedKeys
11
+ });
12
+ const recentWebhookEvents = createClaimableDedupe({
13
+ ttlMs: ZALO_WEBHOOK_REPLAY_WINDOW_MS,
14
+ memoryMaxSize: 5e3
15
+ });
16
+ const webhookAnomalyTracker = createWebhookAnomalyTracker({
17
+ maxTrackedKeys: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.maxTrackedKeys,
18
+ ttlMs: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.ttlMs,
19
+ logEvery: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.logEvery
20
+ });
21
+ function clearZaloWebhookSecurityStateForTest() {
22
+ webhookRateLimiter.clear();
23
+ recentWebhookEvents.clearMemory();
24
+ webhookAnomalyTracker.clear();
25
+ }
26
+ function getZaloWebhookRateLimitStateSizeForTest() {
27
+ return webhookRateLimiter.size();
28
+ }
29
+ function getZaloWebhookStatusCounterSizeForTest() {
30
+ return webhookAnomalyTracker.size();
31
+ }
32
+ function timingSafeEquals(left, right) {
33
+ return safeEqualSecret(left, right);
34
+ }
35
+ function buildReplayEventCacheKey(target, update) {
36
+ const messageId = update.message?.message_id;
37
+ if (!messageId) return null;
38
+ const chatId = update.message?.chat?.id ?? "";
39
+ const senderId = update.message?.from?.id ?? "";
40
+ return JSON.stringify([
41
+ target.path,
42
+ target.account.accountId,
43
+ update.event_name,
44
+ chatId,
45
+ senderId,
46
+ messageId
47
+ ]);
48
+ }
49
+ var ZaloRetryableWebhookError = class extends Error {
50
+ constructor(message, options) {
51
+ super(message, options);
52
+ this.name = "ZaloRetryableWebhookError";
53
+ }
54
+ };
55
+ async function processZaloReplayGuardedUpdate(params) {
56
+ const replayEventKey = buildReplayEventCacheKey(params.target, params.update);
57
+ if (replayEventKey) {
58
+ if ((await recentWebhookEvents.claim(replayEventKey, { now: params.nowMs })).kind !== "claimed") return "duplicate";
59
+ }
60
+ params.target.statusSink?.({ lastInboundAt: Date.now() });
61
+ try {
62
+ await params.processUpdate({
63
+ update: params.update,
64
+ target: params.target
65
+ });
66
+ if (replayEventKey) await recentWebhookEvents.commit(replayEventKey);
67
+ return "processed";
68
+ } catch (error) {
69
+ if (replayEventKey) if (error instanceof ZaloRetryableWebhookError) recentWebhookEvents.release(replayEventKey, { error });
70
+ else await recentWebhookEvents.commit(replayEventKey);
71
+ throw error;
72
+ }
73
+ }
74
+ function recordWebhookStatus(runtime, path, statusCode) {
75
+ webhookAnomalyTracker.record({
76
+ key: `${path}:${statusCode}`,
77
+ statusCode,
78
+ log: runtime?.log,
79
+ message: (count) => `[zalo] webhook anomaly path=${path} status=${statusCode} count=${String(count)}`
80
+ });
81
+ }
82
+ function headerValue(value) {
83
+ return Array.isArray(value) ? value[0] : value;
84
+ }
85
+ function registerZaloWebhookTarget(target, opts) {
86
+ if (opts?.route) return registerWebhookTargetWithPluginRoute({
87
+ targetsByPath: webhookTargets,
88
+ target,
89
+ route: opts.route,
90
+ onLastPathTargetRemoved: opts.onLastPathTargetRemoved
91
+ }).unregister;
92
+ return registerWebhookTarget(webhookTargets, target, opts).unregister;
93
+ }
94
+ async function handleZaloWebhookRequest(req, res, processUpdate) {
95
+ return await withResolvedWebhookRequestPipeline({
96
+ req,
97
+ res,
98
+ targetsByPath: webhookTargets,
99
+ allowMethods: ["POST"],
100
+ handle: async ({ targets, path }) => {
101
+ const trustedProxies = targets[0]?.config.gateway?.trustedProxies;
102
+ const allowRealIpFallback = targets[0]?.config.gateway?.allowRealIpFallback === true;
103
+ const rateLimitKey = `${path}:${resolveClientIp({
104
+ remoteAddr: req.socket.remoteAddress,
105
+ forwardedFor: headerValue(req.headers["x-forwarded-for"]),
106
+ realIp: headerValue(req.headers["x-real-ip"]),
107
+ trustedProxies,
108
+ allowRealIpFallback
109
+ }) ?? req.socket.remoteAddress ?? "unknown"}`;
110
+ const nowMs = Date.now();
111
+ if (!applyBasicWebhookRequestGuards({
112
+ req,
113
+ res,
114
+ rateLimiter: webhookRateLimiter,
115
+ rateLimitKey,
116
+ nowMs
117
+ })) {
118
+ recordWebhookStatus(targets[0]?.runtime, path, res.statusCode);
119
+ return true;
120
+ }
121
+ const headerToken = String(req.headers["x-bot-api-secret-token"] ?? "");
122
+ const target = resolveWebhookTargetWithAuthOrRejectSync({
123
+ targets,
124
+ res,
125
+ isMatch: (entry) => timingSafeEquals(entry.secret, headerToken)
126
+ });
127
+ if (!target) {
128
+ recordWebhookStatus(targets[0]?.runtime, path, res.statusCode);
129
+ return true;
130
+ }
131
+ if (!applyBasicWebhookRequestGuards({
132
+ req,
133
+ res,
134
+ requireJsonContentType: true
135
+ })) {
136
+ recordWebhookStatus(target.runtime, path, res.statusCode);
137
+ return true;
138
+ }
139
+ const body = await readJsonWebhookBodyOrReject({
140
+ req,
141
+ res,
142
+ maxBytes: 1024 * 1024,
143
+ timeoutMs: 3e4,
144
+ emptyObjectOnEmpty: false,
145
+ invalidJsonMessage: "Bad Request"
146
+ });
147
+ if (!body.ok) {
148
+ recordWebhookStatus(target.runtime, path, res.statusCode);
149
+ return true;
150
+ }
151
+ const raw = body.value;
152
+ const record = raw && typeof raw === "object" ? raw : null;
153
+ const update = record && record.ok === true && record.result ? record.result : record ?? void 0;
154
+ if (!update?.event_name) {
155
+ res.statusCode = 400;
156
+ res.end("Bad Request");
157
+ recordWebhookStatus(target.runtime, path, res.statusCode);
158
+ return true;
159
+ }
160
+ processZaloReplayGuardedUpdate({
161
+ target,
162
+ update,
163
+ processUpdate,
164
+ nowMs
165
+ }).catch((err) => {
166
+ target.runtime.error?.(`[${target.account.accountId}] Zalo webhook failed: ${String(err)}`);
167
+ });
168
+ res.statusCode = 200;
169
+ res.end("ok");
170
+ return true;
171
+ }
172
+ });
173
+ }
174
+ //#endregion
175
+ export { ZaloRetryableWebhookError, clearZaloWebhookSecurityStateForTest, getZaloWebhookRateLimitStateSizeForTest, getZaloWebhookStatusCounterSizeForTest, handleZaloWebhookRequest, processZaloReplayGuardedUpdate, registerZaloWebhookTarget };
@@ -0,0 +1,23 @@
1
+ import { formatAllowFromLowercase as formatAllowFromLowercase$1, isNormalizedSenderAllowed } from "klaw/plugin-sdk/allow-from";
2
+ import { createChannelMessageReplyPipeline } from "klaw/plugin-sdk/channel-message";
3
+ import { PAIRING_APPROVED_MESSAGE, buildTokenChannelStatusSummary as buildTokenChannelStatusSummary$1 } from "klaw/plugin-sdk/channel-status";
4
+ import { deliverTextOrMediaReply as deliverTextOrMediaReply$1, isNumericTargetId as isNumericTargetId$1, sendPayloadWithChunkedTextAndMedia as sendPayloadWithChunkedTextAndMedia$1 } from "klaw/plugin-sdk/reply-payload";
5
+ import { buildBaseAccountStatusSnapshot } from "klaw/plugin-sdk/status-helpers";
6
+ import { chunkTextForOutbound as chunkTextForOutbound$1 } from "klaw/plugin-sdk/text-chunking";
7
+ import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, buildChannelConfigSchema, createDedupeCache, formatPairingApproveHint, jsonResult, normalizeAccountId as normalizeAccountId$1, readStringParam, resolveClientIp } from "klaw/plugin-sdk/core";
8
+ import { buildSecretInputSchema, hasConfiguredSecretInput as hasConfiguredSecretInput$1, normalizeResolvedSecretInputString, normalizeSecretInputString } from "klaw/plugin-sdk/secret-input";
9
+ import { addWildcardAllowFrom as addWildcardAllowFrom$1, applyAccountNameToChannelSection, applySetupAccountConfigPatch, buildSingleChannelSecretPromptState as buildSingleChannelSecretPromptState$1, mergeAllowFromEntries as mergeAllowFromEntries$1, migrateBaseNameToDefaultAccount, promptSingleChannelSecretInput as promptSingleChannelSecretInput$1, runSingleChannelSecretStep as runSingleChannelSecretStep$1, setTopLevelChannelDmPolicyWithAllowFrom } from "klaw/plugin-sdk/setup";
10
+ import { resolveDefaultGroupPolicy as resolveDefaultGroupPolicy$1, resolveOpenProviderRuntimeGroupPolicy as resolveOpenProviderRuntimeGroupPolicy$1, warnMissingProviderGroupPolicyFallbackOnce as warnMissingProviderGroupPolicyFallbackOnce$1 } from "klaw/plugin-sdk/runtime-group-policy";
11
+ import { createChannelPairingController as createChannelPairingController$1 } from "klaw/plugin-sdk/channel-pairing";
12
+ import { logTypingFailure as logTypingFailure$1 } from "klaw/plugin-sdk/channel-feedback";
13
+ import { resolveInboundRouteEnvelopeBuilderWithRuntime as resolveInboundRouteEnvelopeBuilderWithRuntime$1 } from "klaw/plugin-sdk/inbound-envelope";
14
+ import { waitForAbortSignal } from "klaw/plugin-sdk/runtime";
15
+ import { WEBHOOK_ANOMALY_COUNTER_DEFAULTS, WEBHOOK_RATE_LIMIT_DEFAULTS, applyBasicWebhookRequestGuards, createFixedWindowRateLimiter, createWebhookAnomalyTracker, readJsonWebhookBodyOrReject, registerPluginHttpRoute as registerPluginHttpRoute$1, registerWebhookTarget, registerWebhookTargetWithPluginRoute, resolveWebhookPath as resolveWebhookPath$1, resolveWebhookTargetWithAuthOrRejectSync, withResolvedWebhookRequestPipeline } from "klaw/plugin-sdk/webhook-ingress";
16
+ import { createPluginRuntimeStore } from "klaw/plugin-sdk/runtime-store";
17
+ //#region extensions/zalo/src/runtime.ts
18
+ const { setRuntime: setZaloRuntime, getRuntime: getZaloRuntime } = createPluginRuntimeStore({
19
+ pluginId: "zalo",
20
+ errorMessage: "Zalo runtime not initialized"
21
+ });
22
+ //#endregion
23
+ export { mergeAllowFromEntries$1 as A, registerWebhookTargetWithPluginRoute as B, formatAllowFromLowercase$1 as C, isNumericTargetId$1 as D, isNormalizedSenderAllowed as E, promptSingleChannelSecretInput$1 as F, resolveWebhookPath$1 as G, resolveDefaultGroupPolicy$1 as H, readJsonWebhookBodyOrReject as I, sendPayloadWithChunkedTextAndMedia$1 as J, resolveWebhookTargetWithAuthOrRejectSync as K, readStringParam as L, normalizeAccountId$1 as M, normalizeResolvedSecretInputString as N, jsonResult as O, normalizeSecretInputString as P, withResolvedWebhookRequestPipeline as Q, registerPluginHttpRoute$1 as R, deliverTextOrMediaReply$1 as S, hasConfiguredSecretInput$1 as T, resolveInboundRouteEnvelopeBuilderWithRuntime$1 as U, resolveClientIp as V, resolveOpenProviderRuntimeGroupPolicy$1 as W, waitForAbortSignal as X, setTopLevelChannelDmPolicyWithAllowFrom as Y, warnMissingProviderGroupPolicyFallbackOnce$1 as Z, createChannelMessageReplyPipeline as _, WEBHOOK_ANOMALY_COUNTER_DEFAULTS as a, createFixedWindowRateLimiter as b, applyAccountNameToChannelSection as c, buildBaseAccountStatusSnapshot as d, buildChannelConfigSchema as f, chunkTextForOutbound$1 as g, buildTokenChannelStatusSummary$1 as h, PAIRING_APPROVED_MESSAGE as i, migrateBaseNameToDefaultAccount as j, logTypingFailure$1 as k, applyBasicWebhookRequestGuards as l, buildSingleChannelSecretPromptState$1 as m, setZaloRuntime as n, WEBHOOK_RATE_LIMIT_DEFAULTS as o, buildSecretInputSchema as p, runSingleChannelSecretStep$1 as q, DEFAULT_ACCOUNT_ID$1 as r, addWildcardAllowFrom$1 as s, getZaloRuntime as t, applySetupAccountConfigPatch as u, createChannelPairingController$1 as v, formatPairingApproveHint as w, createWebhookAnomalyTracker as x, createDedupeCache as y, registerWebhookTarget as z };
@@ -0,0 +1,2 @@
1
+ import { A as mergeAllowFromEntries, B as registerWebhookTargetWithPluginRoute, C as formatAllowFromLowercase, D as isNumericTargetId, E as isNormalizedSenderAllowed, F as promptSingleChannelSecretInput, G as resolveWebhookPath, H as resolveDefaultGroupPolicy, I as readJsonWebhookBodyOrReject, J as sendPayloadWithChunkedTextAndMedia, K as resolveWebhookTargetWithAuthOrRejectSync, L as readStringParam, M as normalizeAccountId, N as normalizeResolvedSecretInputString, O as jsonResult, P as normalizeSecretInputString, Q as withResolvedWebhookRequestPipeline, R as registerPluginHttpRoute, S as deliverTextOrMediaReply, T as hasConfiguredSecretInput, U as resolveInboundRouteEnvelopeBuilderWithRuntime, V as resolveClientIp, W as resolveOpenProviderRuntimeGroupPolicy, X as waitForAbortSignal, Y as setTopLevelChannelDmPolicyWithAllowFrom, Z as warnMissingProviderGroupPolicyFallbackOnce, _ as createChannelMessageReplyPipeline, a as WEBHOOK_ANOMALY_COUNTER_DEFAULTS, b as createFixedWindowRateLimiter, c as applyAccountNameToChannelSection, d as buildBaseAccountStatusSnapshot, f as buildChannelConfigSchema, g as chunkTextForOutbound, h as buildTokenChannelStatusSummary, i as PAIRING_APPROVED_MESSAGE, j as migrateBaseNameToDefaultAccount, k as logTypingFailure, l as applyBasicWebhookRequestGuards, m as buildSingleChannelSecretPromptState, n as setZaloRuntime, o as WEBHOOK_RATE_LIMIT_DEFAULTS, p as buildSecretInputSchema, q as runSingleChannelSecretStep, r as DEFAULT_ACCOUNT_ID, s as addWildcardAllowFrom, u as applySetupAccountConfigPatch, v as createChannelPairingController, w as formatPairingApproveHint, x as createWebhookAnomalyTracker, y as createDedupeCache, z as registerWebhookTarget } from "./runtime-api-CxXTp1Q2.js";
2
+ export { DEFAULT_ACCOUNT_ID, PAIRING_APPROVED_MESSAGE, WEBHOOK_ANOMALY_COUNTER_DEFAULTS, WEBHOOK_RATE_LIMIT_DEFAULTS, addWildcardAllowFrom, applyAccountNameToChannelSection, applyBasicWebhookRequestGuards, applySetupAccountConfigPatch, buildBaseAccountStatusSnapshot, buildChannelConfigSchema, buildSecretInputSchema, buildSingleChannelSecretPromptState, buildTokenChannelStatusSummary, chunkTextForOutbound, createChannelMessageReplyPipeline, createChannelPairingController, createDedupeCache, createFixedWindowRateLimiter, createWebhookAnomalyTracker, deliverTextOrMediaReply, formatAllowFromLowercase, formatPairingApproveHint, hasConfiguredSecretInput, isNormalizedSenderAllowed, isNumericTargetId, jsonResult, logTypingFailure, mergeAllowFromEntries, migrateBaseNameToDefaultAccount, normalizeAccountId, normalizeResolvedSecretInputString, normalizeSecretInputString, promptSingleChannelSecretInput, readJsonWebhookBodyOrReject, readStringParam, registerPluginHttpRoute, registerWebhookTarget, registerWebhookTargetWithPluginRoute, resolveClientIp, resolveDefaultGroupPolicy, resolveInboundRouteEnvelopeBuilderWithRuntime, resolveOpenProviderRuntimeGroupPolicy, resolveWebhookPath, resolveWebhookTargetWithAuthOrRejectSync, runSingleChannelSecretStep, sendPayloadWithChunkedTextAndMedia, setTopLevelChannelDmPolicyWithAllowFrom, setZaloRuntime, waitForAbortSignal, warnMissingProviderGroupPolicyFallbackOnce, withResolvedWebhookRequestPipeline };
@@ -0,0 +1,87 @@
1
+ import { collectConditionalChannelFieldAssignments, getChannelSurface, hasOwnProperty } from "klaw/plugin-sdk/channel-secret-basic-runtime";
2
+ //#region extensions/zalo/src/secret-contract.ts
3
+ const secretTargetRegistryEntries = [
4
+ {
5
+ id: "channels.zalo.accounts.*.botToken",
6
+ targetType: "channels.zalo.accounts.*.botToken",
7
+ configFile: "klaw.json",
8
+ pathPattern: "channels.zalo.accounts.*.botToken",
9
+ secretShape: "secret_input",
10
+ expectedResolvedValue: "string",
11
+ includeInPlan: true,
12
+ includeInConfigure: true,
13
+ includeInAudit: true
14
+ },
15
+ {
16
+ id: "channels.zalo.accounts.*.webhookSecret",
17
+ targetType: "channels.zalo.accounts.*.webhookSecret",
18
+ configFile: "klaw.json",
19
+ pathPattern: "channels.zalo.accounts.*.webhookSecret",
20
+ secretShape: "secret_input",
21
+ expectedResolvedValue: "string",
22
+ includeInPlan: true,
23
+ includeInConfigure: true,
24
+ includeInAudit: true
25
+ },
26
+ {
27
+ id: "channels.zalo.botToken",
28
+ targetType: "channels.zalo.botToken",
29
+ configFile: "klaw.json",
30
+ pathPattern: "channels.zalo.botToken",
31
+ secretShape: "secret_input",
32
+ expectedResolvedValue: "string",
33
+ includeInPlan: true,
34
+ includeInConfigure: true,
35
+ includeInAudit: true
36
+ },
37
+ {
38
+ id: "channels.zalo.webhookSecret",
39
+ targetType: "channels.zalo.webhookSecret",
40
+ configFile: "klaw.json",
41
+ pathPattern: "channels.zalo.webhookSecret",
42
+ secretShape: "secret_input",
43
+ expectedResolvedValue: "string",
44
+ includeInPlan: true,
45
+ includeInConfigure: true,
46
+ includeInAudit: true
47
+ }
48
+ ];
49
+ function collectRuntimeConfigAssignments(params) {
50
+ const resolved = getChannelSurface(params.config, "zalo");
51
+ if (!resolved) return;
52
+ const { channel: zalo, surface } = resolved;
53
+ collectConditionalChannelFieldAssignments({
54
+ channelKey: "zalo",
55
+ field: "botToken",
56
+ channel: zalo,
57
+ surface,
58
+ defaults: params.defaults,
59
+ context: params.context,
60
+ topLevelActiveWithoutAccounts: true,
61
+ topLevelInheritedAccountActive: ({ account, enabled }) => enabled && !hasOwnProperty(account, "botToken"),
62
+ accountActive: ({ enabled }) => enabled,
63
+ topInactiveReason: "no enabled Zalo surface inherits this top-level botToken.",
64
+ accountInactiveReason: "Zalo account is disabled."
65
+ });
66
+ const baseWebhookUrl = typeof zalo.webhookUrl === "string" ? zalo.webhookUrl.trim() : "";
67
+ const accountWebhookUrl = (account) => hasOwnProperty(account, "webhookUrl") ? typeof account.webhookUrl === "string" ? account.webhookUrl.trim() : "" : baseWebhookUrl;
68
+ collectConditionalChannelFieldAssignments({
69
+ channelKey: "zalo",
70
+ field: "webhookSecret",
71
+ channel: zalo,
72
+ surface,
73
+ defaults: params.defaults,
74
+ context: params.context,
75
+ topLevelActiveWithoutAccounts: baseWebhookUrl.length > 0,
76
+ topLevelInheritedAccountActive: ({ account, enabled }) => enabled && !hasOwnProperty(account, "webhookSecret") && accountWebhookUrl(account).length > 0,
77
+ accountActive: ({ account, enabled }) => enabled && accountWebhookUrl(account).length > 0,
78
+ topInactiveReason: "no enabled Zalo webhook surface inherits this top-level webhookSecret (webhook mode is not active).",
79
+ accountInactiveReason: "Zalo account is disabled or webhook mode is not active for this account."
80
+ });
81
+ }
82
+ const channelSecrets = {
83
+ secretTargetRegistryEntries,
84
+ collectRuntimeConfigAssignments
85
+ };
86
+ //#endregion
87
+ export { collectRuntimeConfigAssignments as n, secretTargetRegistryEntries as r, channelSecrets as t };
@@ -0,0 +1,2 @@
1
+ import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries, t as channelSecrets } from "./secret-contract-CRFukr2n.js";
2
+ export { channelSecrets, collectRuntimeConfigAssignments, secretTargetRegistryEntries };
@@ -0,0 +1,270 @@
1
+ import { d as resolveZaloToken, u as resolveZaloAccount } from "./setup-core-Dr75wK6l.js";
2
+ import { createMessageReceiptFromOutboundResults } from "klaw/plugin-sdk/channel-message";
3
+ import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
4
+ import { resolvePinnedHostnameWithPolicy } from "klaw/plugin-sdk/ssrf-runtime";
5
+ import { makeProxyFetch } from "klaw/plugin-sdk/fetch-runtime";
6
+ //#region extensions/zalo/src/api.ts
7
+ /**
8
+ * Zalo Bot API client
9
+ * @see https://bot.zaloplatforms.com/docs
10
+ */
11
+ const ZALO_API_BASE = "https://bot-api.zaloplatforms.com";
12
+ const ZALO_MEDIA_SSRF_POLICY = {};
13
+ var ZaloApiError = class extends Error {
14
+ constructor(message, errorCode, description) {
15
+ super(message);
16
+ this.errorCode = errorCode;
17
+ this.description = description;
18
+ this.name = "ZaloApiError";
19
+ }
20
+ /** True if this is a long-polling timeout (no updates available) */
21
+ get isPollingTimeout() {
22
+ return this.errorCode === 408;
23
+ }
24
+ };
25
+ /**
26
+ * Call the Zalo Bot API
27
+ */
28
+ async function callZaloApi(method, token, body, options) {
29
+ const url = `${ZALO_API_BASE}/bot${token}/${method}`;
30
+ const controller = new AbortController();
31
+ const timeoutId = options?.timeoutMs ? setTimeout(() => controller.abort(), options.timeoutMs) : void 0;
32
+ const fetcher = options?.fetch ?? fetch;
33
+ try {
34
+ const data = await (await fetcher(url, {
35
+ method: "POST",
36
+ headers: { "Content-Type": "application/json" },
37
+ body: body ? JSON.stringify(body) : void 0,
38
+ signal: controller.signal
39
+ })).json();
40
+ if (!data.ok) throw new ZaloApiError(data.description ?? `Zalo API error: ${method}`, data.error_code, data.description);
41
+ return data;
42
+ } finally {
43
+ if (timeoutId) clearTimeout(timeoutId);
44
+ }
45
+ }
46
+ /**
47
+ * Validate bot token and get bot info
48
+ */
49
+ async function getMe(token, timeoutMs, fetcher) {
50
+ return callZaloApi("getMe", token, void 0, {
51
+ timeoutMs,
52
+ fetch: fetcher
53
+ });
54
+ }
55
+ /**
56
+ * Send a text message
57
+ */
58
+ async function sendMessage(token, params, fetcher) {
59
+ return callZaloApi("sendMessage", token, params, { fetch: fetcher });
60
+ }
61
+ /**
62
+ * Send a photo message
63
+ */
64
+ async function sendPhoto(token, params, fetcher) {
65
+ const photoUrl = params.photo.trim();
66
+ let parsedPhotoUrl;
67
+ try {
68
+ parsedPhotoUrl = new URL(photoUrl);
69
+ } catch {
70
+ throw new Error("Zalo photo URL must be an absolute HTTP or HTTPS URL");
71
+ }
72
+ if (parsedPhotoUrl.protocol !== "http:" && parsedPhotoUrl.protocol !== "https:") throw new Error("Zalo photo URL must use HTTP or HTTPS");
73
+ await resolvePinnedHostnameWithPolicy(parsedPhotoUrl.hostname, { policy: ZALO_MEDIA_SSRF_POLICY });
74
+ return callZaloApi("sendPhoto", token, {
75
+ ...params,
76
+ photo: parsedPhotoUrl.href
77
+ }, { fetch: fetcher });
78
+ }
79
+ /**
80
+ * Send a temporary chat action such as typing.
81
+ */
82
+ async function sendChatAction(token, params, fetcher, timeoutMs) {
83
+ return callZaloApi("sendChatAction", token, params, {
84
+ timeoutMs,
85
+ fetch: fetcher
86
+ });
87
+ }
88
+ /**
89
+ * Get updates using long polling (dev/testing only)
90
+ * Note: Zalo returns a single update per call, not an array like Telegram
91
+ */
92
+ async function getUpdates(token, params, fetcher) {
93
+ const pollTimeoutSec = params?.timeout ?? 30;
94
+ const timeoutMs = (pollTimeoutSec + 5) * 1e3;
95
+ return callZaloApi("getUpdates", token, { timeout: String(pollTimeoutSec) }, {
96
+ timeoutMs,
97
+ fetch: fetcher
98
+ });
99
+ }
100
+ /**
101
+ * Set webhook URL for receiving updates
102
+ */
103
+ async function setWebhook(token, params, fetcher) {
104
+ return callZaloApi("setWebhook", token, params, { fetch: fetcher });
105
+ }
106
+ /**
107
+ * Delete webhook configuration
108
+ */
109
+ async function deleteWebhook(token, fetcher, timeoutMs) {
110
+ return callZaloApi("deleteWebhook", token, void 0, {
111
+ timeoutMs,
112
+ fetch: fetcher
113
+ });
114
+ }
115
+ /**
116
+ * Get current webhook info
117
+ */
118
+ async function getWebhookInfo(token, fetcher) {
119
+ return callZaloApi("getWebhookInfo", token, void 0, { fetch: fetcher });
120
+ }
121
+ //#endregion
122
+ //#region extensions/zalo/src/proxy.ts
123
+ const proxyCache = /* @__PURE__ */ new Map();
124
+ function resolveZaloProxyFetch(proxyUrl) {
125
+ const trimmed = proxyUrl?.trim();
126
+ if (!trimmed) return;
127
+ const cached = proxyCache.get(trimmed);
128
+ if (cached) return cached;
129
+ const fetcher = makeProxyFetch(trimmed);
130
+ proxyCache.set(trimmed, fetcher);
131
+ return fetcher;
132
+ }
133
+ //#endregion
134
+ //#region extensions/zalo/src/send.ts
135
+ function createZaloSendReceipt(params) {
136
+ const messageId = params.messageId?.trim();
137
+ return createMessageReceiptFromOutboundResults({
138
+ results: messageId ? [{
139
+ channel: "zalo",
140
+ messageId,
141
+ chatId: params.chatId
142
+ }] : [],
143
+ kind: params.kind
144
+ });
145
+ }
146
+ function toZaloSendResult(response, params) {
147
+ if (response.ok && response.result) return {
148
+ ok: true,
149
+ messageId: response.result.message_id,
150
+ receipt: createZaloSendReceipt({
151
+ messageId: response.result.message_id,
152
+ chatId: params.chatId,
153
+ kind: params.kind
154
+ })
155
+ };
156
+ return {
157
+ ok: false,
158
+ error: "Failed to send message",
159
+ receipt: createZaloSendReceipt({
160
+ chatId: params.chatId,
161
+ kind: params.kind
162
+ })
163
+ };
164
+ }
165
+ async function runZaloSend(failureMessage, params, send) {
166
+ try {
167
+ const result = toZaloSendResult(await send(), params);
168
+ return result.ok ? result : {
169
+ ok: false,
170
+ error: failureMessage,
171
+ receipt: result.receipt
172
+ };
173
+ } catch (err) {
174
+ return {
175
+ ok: false,
176
+ error: formatErrorMessage(err),
177
+ receipt: createZaloSendReceipt({
178
+ chatId: params.chatId,
179
+ kind: params.kind
180
+ })
181
+ };
182
+ }
183
+ }
184
+ function resolveSendContext(options) {
185
+ if (options.cfg) {
186
+ const account = resolveZaloAccount({
187
+ cfg: options.cfg,
188
+ accountId: options.accountId
189
+ });
190
+ return {
191
+ token: options.token || account.token,
192
+ fetcher: resolveZaloProxyFetch(options.proxy ?? account.config.proxy)
193
+ };
194
+ }
195
+ const token = options.token ?? resolveZaloToken(void 0, options.accountId).token;
196
+ const proxy = options.proxy;
197
+ return {
198
+ token,
199
+ fetcher: resolveZaloProxyFetch(proxy)
200
+ };
201
+ }
202
+ function resolveValidatedSendContext(chatId, options) {
203
+ const { token, fetcher } = resolveSendContext(options);
204
+ if (!token) return {
205
+ ok: false,
206
+ error: "No Zalo bot token configured"
207
+ };
208
+ const trimmedChatId = chatId?.trim();
209
+ if (!trimmedChatId) return {
210
+ ok: false,
211
+ error: "No chat_id provided"
212
+ };
213
+ return {
214
+ ok: true,
215
+ chatId: trimmedChatId,
216
+ token,
217
+ fetcher
218
+ };
219
+ }
220
+ function resolveSendContextOrFailure(chatId, options) {
221
+ const context = resolveValidatedSendContext(chatId, options);
222
+ return context.ok ? { context } : { failure: {
223
+ ok: false,
224
+ error: context.error,
225
+ receipt: createZaloSendReceipt({
226
+ chatId,
227
+ kind: "unknown"
228
+ })
229
+ } };
230
+ }
231
+ async function sendMessageZalo(chatId, text, options = {}) {
232
+ const resolved = resolveSendContextOrFailure(chatId, options);
233
+ if ("failure" in resolved) return resolved.failure;
234
+ const { context } = resolved;
235
+ if (options.mediaUrl) return sendPhotoZalo(context.chatId, options.mediaUrl, {
236
+ ...options,
237
+ token: context.token,
238
+ caption: text || options.caption
239
+ });
240
+ return await runZaloSend("Failed to send message", {
241
+ chatId: context.chatId,
242
+ kind: "text"
243
+ }, () => sendMessage(context.token, {
244
+ chat_id: context.chatId,
245
+ text: text.slice(0, 2e3)
246
+ }, context.fetcher));
247
+ }
248
+ async function sendPhotoZalo(chatId, photoUrl, options = {}) {
249
+ const resolved = resolveSendContextOrFailure(chatId, options);
250
+ if ("failure" in resolved) return resolved.failure;
251
+ const { context } = resolved;
252
+ if (!photoUrl?.trim()) return {
253
+ ok: false,
254
+ error: "No photo URL provided",
255
+ receipt: createZaloSendReceipt({
256
+ chatId: context.chatId,
257
+ kind: "media"
258
+ })
259
+ };
260
+ return await runZaloSend("Failed to send photo", {
261
+ chatId: context.chatId,
262
+ kind: "media"
263
+ }, () => (async () => sendPhoto(context.token, {
264
+ chat_id: context.chatId,
265
+ photo: photoUrl.trim(),
266
+ caption: options.caption?.slice(0, 2e3)
267
+ }, context.fetcher))());
268
+ }
269
+ //#endregion
270
+ export { getMe as a, sendChatAction as c, setWebhook as d, deleteWebhook as i, sendMessage as l, resolveZaloProxyFetch as n, getUpdates as o, ZaloApiError as r, getWebhookInfo as s, sendMessageZalo as t, sendPhoto as u };
@@ -0,0 +1,30 @@
1
+ import { n as zaloDmPolicy, r as zaloSetupAdapter, t as createZaloSetupWizardProxy } from "./setup-core-Dr75wK6l.js";
2
+ import { n as resolveZaloRuntimeGroupPolicy } from "./group-access-DTQVR6Nd.js";
3
+ import { loadBundledEntryExportSync } from "klaw/plugin-sdk/channel-entry-contract";
4
+ //#region extensions/zalo/setup-api.ts
5
+ function createLazyObjectValue(load) {
6
+ return new Proxy({}, {
7
+ get(_target, property, receiver) {
8
+ return Reflect.get(load(), property, receiver);
9
+ },
10
+ has(_target, property) {
11
+ return property in load();
12
+ },
13
+ ownKeys() {
14
+ return Reflect.ownKeys(load());
15
+ },
16
+ getOwnPropertyDescriptor(_target, property) {
17
+ const descriptor = Object.getOwnPropertyDescriptor(load(), property);
18
+ return descriptor ? {
19
+ ...descriptor,
20
+ configurable: true
21
+ } : void 0;
22
+ }
23
+ });
24
+ }
25
+ function loadSetupSurfaceModule() {
26
+ return loadBundledEntryExportSync(import.meta.url, { specifier: "./src/setup-surface.js" });
27
+ }
28
+ const zaloSetupWizard = createLazyObjectValue(() => loadSetupSurfaceModule().zaloSetupWizard);
29
+ //#endregion
30
+ export { createZaloSetupWizardProxy, resolveZaloRuntimeGroupPolicy, zaloDmPolicy, zaloSetupAdapter, zaloSetupWizard };